3

I have defined a grammar through which I produce a series of abstract syntax trees of sorts. For example

x = 7
println + * x 2 5

becomes

    (assign)
    /      \
   x        7

    (println)
        |
       (+)
      /   \
    (*)    5
   /   \
  x     2

These trees are made from various Node classes representing values and operations. Now, these trees are easy to interpret but my goal is to generate Java bytecode representing these processes. My question is, what would be the best way to approach that? Should I just literally write various bytecode instructions to a .class file, or is there some library or interface that can help with this sort of thing?

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • http://www.antlr.org/ ? Also related http://stackoverflow.com/questions/3380498/create-a-jvm-programming-language – Benjamin Gruenbaum Jun 22 '13 at 15:59
  • @BenjaminGruenbaum As far as I know ANTLR helps with the parsing process, but I already have that taken care of. I just want to write the Java bytecode dynamically. – arshajii Jun 22 '13 at 16:00
  • 1
    possible duplicate of [Java Bytecode Manipulation Library Suggestions](http://stackoverflow.com/questions/2532215/java-bytecode-manipulation-library-suggestions) – Joni Jun 22 '13 at 16:02

2 Answers2

3

The answer is yes. ASM and BCEL are two Java libraries designed to assist with runtime generation of classfiles.

Antimony
  • 37,781
  • 10
  • 100
  • 107
3

I have written a framework that lets you compose code with declarative expression trees and then compile them to bytecode. Though I had developed it to ease runtime code generation, it could just as easily be leveraged as a sort of compiler back end, e.g., by translating your syntax tree into one of my expression trees.

At the very least, you could probably glean some useful bits from my compiler and maybe use my low-level code generation framework.

My repository is here. The expression tree library is procyon-expressions.

Mike Strobel
  • 25,075
  • 57
  • 69
  • Do you use another library such as ASM within your framework? – arshajii Jun 23 '13 at 15:16
  • No, I have my own TypeBuilder and CodeGenerator. I have no third party dependencies for this particular framework. I find ASM extremely cumbersome to use. – Mike Strobel Jun 23 '13 at 15:20