/groovy-bytecode-ast

A Groovy AST transformation which allows writing the body of a method as bytecode instructions.

Primary LanguageGroovyApache License 2.0Apache-2.0

@Bytecode AST transformation

Build Status

This project adds a @Bytecode AST transformation to Groovy, which will let you write bytecode directly as a method body!

This is for educational purposes only. I would never use this in real production code.

Usage

Build script

If you use Gradle:

build.gradle
repositories {
   maven { url 'http://oss.jfrog.org/oss-release-local' }
}
dependencies {
    compile 'me.champeau.groovy:bytecode-xform:0.2.0'
}

Note that you might have to use a weird classloading trick like the one here if you face a classloader constraint violation.

But if you really insist on using Maven:

pom.xml
    <dependencies>
        <dependency>
            <groupId>me.champeau.groovy</groupId>
            <artifactId>bytecode-xform</artifactId>
            <version>0.2.0</version>
        </dependency>
    </dependencies>
    <repositories>
        <repository>
            <id>jfrog</id>
            <url>http://oss.jfrog.org/oss-release-local</url>
            <releases>
                <enabled>true</enabled>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

Code

Then you can start using it in your Groovy code like in this example:

@groovyx.ast.bytecode.Bytecode
int fib(int n) {
    l0:
    iload 1
    iconst_2
    if_icmpge l1
    iload 1
    _goto l2
    l1:
    aload 0
    iload 1
    iconst_2
    isub
    invokevirtual '.fib','(I)I'
    aload 0
    iload 1
    iconst_1
    isub
    invokevirtual '.fib', '(I)I'
    iadd
    l2:
    ireturn
}

A detailed explanation of the concept and why it was done can be found on some blog posts I wrote: