inline domain specific language to generate Java code

726 Views Asked by At

I work on a program that performs matrix and vector operation in Java. The multiple function call and object creation that occurs in my current implementation makes it sluggish and difficult to understand.

For instance I want to update the position of a mechanical point, by speed integration:

void update(Vector3 position, Vector3 speed, float dt){
   Vector3 displacement = new Vector3(speed);
   displacement.assignMul(dt);
   position.assignAdd(displacement);
}

Here the API is not natural, and in addition I need to allocate an build a new Vector3 reference. Obviously i measured a great performance improvement on real uses case when inlining the computation this way:

void update(Vector3 position, Vector3 speed, float dt){
   position.x += speed.x * dt;
   position.y += speed.y * dt;
   position.z += speed.z * dt;
}

Is there any tool that could generate this code from a domain specific language on demand? A Cog like syntax would be nice. (Cog is a code generation tool from Ned Batchelder)

void update(Vector3 position, Vector3 speed, float dt){
   // [[[DSL position += speed * dt ]]] 
   position.x += speed.x * dt;//Generated Code
   position.y += speed.y * dt;//Generated Code
   position.z += speed.z * dt;//Generated Code
   // [[[END]]]
}
1

There are 1 best solutions below

1
On

If you're heart set on code generation, I would highly recommend the book Language Implementation Patterns by Terence Parr. He shows how you would create an abstract syntax tree (AST) based of your DSL and then use rewrite rules to generate code.

Furthermore, he uses a vector DSL as one of his examples, including showing how you can distribute constant multiplications in the syntax tree. e.g.Simplification of a vector DSL.  Page 141 of Language Implementation Patterns by Terence Parr

The relevant section to you would be Chapter 15, Tree Pattern Matcher.

I agree with some of the other posters that this might be a little heavy weight for your purposes. Are you sure you can't implement a more fluent interface as @Alessandro Vermeulen showed in his gist comment? The speed differences look pretty negligible.