Built-in domain language for generating Java code

I am working on a program that performs matrix and vector operation in Java. Multiple function calls and the creation of objects that occur in my current implementation make it sluggish and difficult to understand.

For example, I want to update the position of a mechanical point by integrating speed:

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 highlight the assembly of the new Vector3 link. Obviously, I measured a big performance improvement in the case of real-world applications when building computations 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 specific domain upon request? Cog syntax will be nice. (Cog is a code creation 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]]] } 
+4
source share
1 answer

If you are set up to create code, I would highly recommend the Terence Parr Language Implementation Templates book . It shows how you will create an abstract syntax tree (AST) based on your DSL, and then use rewrite rules to generate the code.

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

The appropriate section for you will be Chapter 15, the Tree Template Wizard.

I agree with some other posters that this can be a little heavy weight for your purposes. Are you sure you cannot implement a more free interface, as @Alessandro Vermeulen showed gist in his comment ? The difference in speed looks pretty slight.

+1
source

All Articles