abstract syntax tree - Groovy - Add Class to script via AST transformations -
i'm creating groovy dsl
looks this:
types { "http://some.namespace.here" b "..." } testmethod(a a, b b) { ... }
the user defines several types , methods on these types. need create a
, b
classnode
s in ast groovy can find them.
to so, created following ast transformation:
@groovyasttransformation(phase = compilephase.semantic_analysis) class generateclassestransformer implements asttransformation { @override public void visit(astnode[] nodes, sourceunit source) { classnode = createclass("a") classnode b = createclass("b") modulenode module = sourceunit.getast() module.addclass(a) module.addclass(b) module.getclasses().each { println "class: " + } } private classnode createclass(string classname) { new astbuilder().buildfromspec { classnode(classname, classnode.acc_public) { classnode object interfaces { classnode groovyobject } mixins { } } }.first() } }
i add ast transformation groovy shell:
compilerconfiguration cc = new compilerconfiguration(); cc.setscriptbaseclass("groovy.util.delegatingscript"); cc.addcompilationcustomizers(new asttransformationcustomizer(new generateclassestransformer())); groovyshell sh = new groovyshell(loader, binding, cc); // ...
when run code , not reference a
, b
, works out fine. however, use a
, b
, groovy cannot find classes (although on ast). instead, get:
org.codehaus.groovy.control.multiplecompilationerrorsexception: startup failed: c:\...\test.groovy: 23: unable resolve class @ line 23, column 6. a = null ^
any appreciated!
update: classloader
i'm using custom urlclassloader
, since i'm adding couple of jar
s classpath:
url[] urls = this.getextrajarurls(); // read jars directory relative dsl script classloader base = launcher.class.getclassloader(); loader = new urlclassloader(urls, base);
Comments
Post a Comment