Posts Tagged: dsl


9
Dec 08

Announcing Squill: Not Another ORM

Remember that post about Typesafe DSLs that had a part one and no follow up? Well, meanwhile Juhan Aasaru and yours truly were joined by Michael Hunger of jexp.de and JEQUEL and together we have created the Squill project that came right out of the ideas in the paper we wrote with Rein Raudjärv. The announcement follows, enjoy!

It is with great pleasure that we announce the first release of Squill. Download it now or check out the quickstart guide, the step-by-step tutorial and the Devoxx presentation.

Squill is a slick internal DSL for writing SQL queries in pure Java. It uses the database metadata and generics to catch as many errors as possible during compilation and is almost completely typesafe.

At the same time it is designed to allow everything SQL allows you to do, exactly the way SQL is meant to do it. This means that you’re encouraged to select only the data you need and no hidden queries are generated for you, leaving you in full control of the query performance. Squill supports database-specific extensions, allowing you to both use advanced features and fully tweak your queries.

Squill also has special support for CRUD operations and table relations, adding some sugar over vanilla SQL. A typical Squill query looks like this:
[java] ComplaintTable c = new ComplaintTable();

for (Tuple2 tuple2:
squill
.from(c, c.customer)
.where(
gt(c.customer.isActive, 0),
notNull(c.percentSolved),
notNull(c.refoundSum))
.orderBy(desc(c.customer.id))
.selectList(
c.customer.lastName,
c.percentSolved)) {
System.out.println(
“Customer ” + tuple2.v1 + ” has a complaint solved ” + tuple2.v2 + “%”);
}
[/java]

Squill is a very young project and you can follow (and help) its development by joining the user or developer mailing lists.


19
May 08

Concise EDSL Closures in Java

This trick was pointed to me (without the ThreadLocal part) by Rein Raudjärv, who saw it used in jMock.

The problem with Java “closures” aka anonymous inner classes being a tad too ugly is a well known one, but this semi-solution seems to be quite unused. Although you can apply the same principle for many situations it’ll work best for embedded DSLs.

Let’s start by defining an EDSL intefrace:
[java]
public interface DSL {

DSL doSomething();
DSL doSomethingElse();
DSLPreClosure closure();
}
[/java]

As you can see we separated the actual closure application in a separate interface:
[java]
public interface DSLPreClosure {
DSL apply(DSLClosure closure);
}
[/java]

The reason for that is that we want to use closures without defining a method in the anonymous inner class:
[java]
public class Test {
public static void main(String[] args) {
new DSLImpl()
.doSomething()
.closure().apply(new DSLClosure() {{
dsl
.doSomething()
.doSomethingElse();
}})
.doSomethingElse();
}
}
[/java]

What happens is that we abuse a little used Java feature — initializers. If you put a block in the body of a class definition it will be executed right after the constructor. In our case we construct a new subclass of DSLClosure and immediately add an initializer:
[java]
new DSLClosure() {
//Initializer starts here
{
//Closure body goes here
}
//Initializer ends here
};
[/java]

Of course while this allows to execute a block of code with fewer symbols to write, we still need to somehow pass parameters. Note, that since the initializer executes inside the constructor call, it will be executed before the actual apply() method is called. Therefore we make use of the ThreadLocal class to pass the parameters inside the call:
[java]
public class DSLImpl implements DSLWithClosure {
static final ThreadLocal curDSL =
new ThreadLocal();

public DSL doSomething() {
//Do something…
return this;
}

public DSL doSomethingElse() {
//Do something else…
return this;
}

public DSLWithClosure closure() {
curDSL.set(this);
return this;
}

public DSL apply(DSLClosure closure) {
curDSL.set(null);
return this;
}
}
[/java]

Finally the DSLClosure exposes the ThreadLocal parameter as a protected field:
[java]
public class DSLClosure {
protected DSL dsl =
(DSL) DSLImpl.curDSL.get();
}
[/java]

Of course, for the sake of correctness we should also allow nesting closure calls on the same thread, so we should use a stack inside ThreadLocal, but this is left as an exercise to the reader :)


26
Apr 08

An embedded Java DSL for manipulating hierarchical JavaBeans

Just yesterday I was thinking on how to improve the DSLs I’m working on at the moment and got an idea, which wasn’t too useful in the context of SQL, but could be used for something else.

Imagine we have three JavaBeans (I’m omitting getters/setters for readability):
[java]
class Company {
String name;
Address address;
Collection employees;
}

class Address {
String country;
String zip;
String town;
String street;
}

class Employee {
String firstName;
String lastName;
Address address;
}
[/java]

It’s a straightforward task to build a DSL for manipulating this data. It could look something like that:
[java]
Company c = new CompanyBuilder()
.name(“ZeroTurnaround”)
.address()
.country(“Estonia”)
.finish()
.addEmployee()
.firstName(“Jevgeni”)
.lastName(“Kabanov”)
.address()
.country(“Estonia”)
.finish()
.finish()
.toCompany();
[/java]

The trick is that the AddressBuilder hiding behind the address() call is used in two contexts — as an employee address and as a company address. In a large domain such situations are very common and we would like the corresponding builders to be reused.

What we can do is make every builder keep in mind it’s parent context like this:
[java]
public class EmployeeBuilder
implements Builder {
PARENT parent;

public EmployeeBuilder(Employee e, PARENT parent) {
this.parent = parent;
}

//Field setters …

public AddressBuilder>
addAddress() {
return
new AddressBuilder>(this);
}

public PARENT finish() {
return parent;
}
}

public class AddressBuilder
implements Builder {
PARENT parent;

public AddressBuilder(Address a, PARENT parent) {
this.parent = parent;
}

//Field setters …

public PARENT finish() {
return parent;
}
}
[/java]

This way the generic type becomes nested and holds the whole path to the root of the hierarchy in a typesafe way. Of course we also need to return the actual value independently of the parent, but it’s easy to do by passing a corresponding closure from the parent and calling it in the finish:

[java]

public class AddressBuilder
implements Builder {
//…

interface Closure {
void address(Address address);
}

public PARENT finish() {
addressClosure.address(address);
return parent;
}
}
[/java]

This trick can be reused for any kind of hierarchical composition — JavaBeans, XML and so on. For XML you could generate the DSL from the Schema, which is a relatively painful process. However for JavaBeans you can generate a builder per bean in a very straightforward way from the reflection information. Such a builder could be used for modifying JavaBeans as well as for constructing them.

It would most probably be simplest to output the bytecode directly and generate .class files or JAR for this DSL, which makes it an ideal test case for the typesafe bytecode engineering DSL library I’m working on :) Most likely I’ll implement this language as an example of using typesafe bytecode engineering, so if you’re interested keep an eye on the blog.


26
Mar 08

Typesafe ASM — problems solved?

OK, I think I managed to solve both the primitive and the double slot problem introduced in the previous post. Basically I introduced another parametrized class — InvokeBuilder, which builds method invocations. The example now looks like this:

[java]
ClassWriter cw = new ClassWriter(COMPUTE_MAXS);

new ClassBuilder(cw, V1_4, ACC_PUBLIC, “HelloWorld”, “java/lang/Object”, null)
.beginMethod(ACC_PUBLIC, ““, void.class)
.loadVar0(Self.class)
.invoke().specVoid(Object.class, ““)
.returnVoid()
.endMethod()

.beginStaticMethod(ACC_PUBLIC | ACC_STATIC, “main”, void.class, String[].class)
.getStatic(System.class, “out”, PrintStream.class)
.loadVar0(String[].class)
.push(0)
.arrayLoad(String[].class, Integer.class, String.class)
.invoke().param(String.class).virtVoid(PrintStream.class, “println”)
.returnVoid()
.endMethod();
[/java]

Of course InvokeBuilder contains methods only for building invocation. The only inconvenience is that you have to specify parameters in reverse order to coincide with the way they are laid out on the stack. However it’s easy to add a bit of sugar for the most common cases.

Now all I have to do is overload the param() method for each primitive as well as make a paramTwoCell(), which consumes two stack slots (for long/double). Seems that only tedious work in implementing each and every instruction remains.

P.S. Thanks to Christian Vest Hansen for his input. It definitely helped me get this (last?) piece of the puzzle in place.


24
Mar 08

Typesafe DSLs in Java: Part 1 — Typesafe Bytecode

Domain Specific Languages (DSLs) have been brought to Java under the name of Fluent Interface. However most of them utilize a lot of strings and untyped behavior to make the interface fluent enough. It turns out that using Java 5 and a bag of tricks we can have the compiler to check a lot more. In this post we'll check out how to write Java bytecode using ASM in a typesafe way.

Continue reading →