In a Scala Compiler Plugin, I\'m trying to create a new class that implement a pre-existing trait. So far my code looks like this:
def trait2Impl(original: Class
The full source code is here: https://gist.github.com/1794246
The trick is to store the newly created ClassDef
s and use them when creating a new PackageDef
. Note that you need to deal with both Symbols and trees: a package symbol is just a handle. In order to generate code, you need to generate an AST (just like for a class, where the symbol holds the class name and type, but the code is in the ClassDef
trees).
As you noted, package definitions are higher up the tree than classes, so you'd need to recurse first (assuming you'll generate the new class from an existing class). Then, once the subtrees are traversed, you can prepare a new PackageDef (every compilation unit has a package definition, which by default is the empty package) with the new classes.
In the example, assuming the source code is
class Foo {
def foo {
"spring"
}
}
the compiler wraps it into
package {
class Foo {
def foo {
"spring"
}
}
}
and the plugin transforms it into
package {
class Foo {
def foo {
"spring"
}
}
package mypackage {
class MyClass extends AnyRef
}
}