I am writing an interpreter in Java for a domain-specific language with some scripting capabilities. I have already implemented a parser and now need to do a back end. To this end I am considering either to write my own interpreter (either working with abstract syntax trees or with some custom bytecodes) or target JVM (emit and execute Java bytecode at runtime).
Could someone with more experience in this area say how feasible is the approach of targeting JVM and what libraries would you recommend to use for emitting Java bytecode?
Here is a working “hello world” made with ObjectWeb ASM (a library which I recommend):
To generate the code, I found very useful Bytecode Outline for Eclipse plug-in. Although you could use the ASMifier (included with ASM) like this:
At runtime, if you need to obtain the
Classobject for the created class, you can load your class by extending a class loader and publishing (through another method, for instance) thedefineClassmethod and providing the class as a byte array, as listed in the example.You can also handle the created class with an interface, like in this example:
Have fun.
PS: I can add comments to the code if not clear enough. I didn’t because the answer is already too long. Nevertheless, my suggestion for you is to try debugging it.