Skip to: Site menu | Main content

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

From source code to bytecode Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Here are some tips on how to debug what is happening on the transition from groovy source code into the generated bytecode.

artifact

transformation artifact

source ( Hello.groovy) - GroovyLexer -> antlr tokens

antlr tokens - GroovyRecognizer -> antlr ast

antlr ast - AntlrParserPlugin -> groovy ast

groovy ast - AsmClassGenerator-> bytecode ( Hello.class)



Note1 groovy.g is used to generate GroovyLexer and GroovyRecognizer

Note2 GroovyRecognizer is sometimes easier to understand in its syntax diagram form

Note3 AntlrParserPlugin source available.

Example

For these examples let's assume the file Hello.groovy contains

class Hello {
    
static void main(args) {
        println 
"hello world"
    }
}
    

GroovyLexer (viewing Antlr Tokens)

To view the antlr tokens that the source code has been broken into you need to do the following in groovy-core subdirectory

java -cp 
  target/install/embeddable/groovy-all-1.0-jsr-01-SNAPSHOT.jar
  :target/install/lib/antlr-2.7.5.jar 
  org.codehaus.groovy.antlr.LexerFrame
    

GroovyRecognizer (viewing Antlr AST)

To view the antlr AST that the recognized tokens have built

java -cp 
  target/install/embeddable/groovy-all-1.0-jsr-01-SNAPSHOT.jar
  :target/install/lib/antlr-2.7.5.jar
  org.codehaus.groovy.antlr.Main 
  -showtree Hello.groovy
    

AntlrParserPlugin (viewing Groovy AST)

To view the Groovy AST that is one step closer to the generated bytecode you can generate Hello.groovy.xml using these unix commands.

This can be generated using both classic and jsr parsers, by changing the groovy.jsr system property. By doing this we can diff the generated Groovy AST artifacts for debugging and migration purposes.

jsr parser
$ export JAVA_OPTS=
"-Dgroovy.ast=xml -Dgroovy.jsr=
true"
$ groovyc Hello.groovy
Written AST to Hello.groovy.xml
    
classic parser
$ export JAVA_OPTS=
"-Dgroovy.ast=xml -Dgroovy.jsr=
false"
$ groovyc Hello.groovy
Written AST to Hello.groovy.xml
    

Viewing Bytecode

One interesting bytecode viewer is jclasslib which renders Hello.class in this manner...

Decompiling bytecode back to Java

If, however, you are bamboozled by bytecode... The easiest to grok mechanism for reading the compiled code is to use a tool like JAD to decompile the Hello.class into a readable Hello.java