How to add a new Class in a Scala Compiler Plugin?

前端 未结 1 417
既然无缘
既然无缘 2021-02-11 14:52

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         


        
1条回答
  •  隐瞒了意图╮
    2021-02-11 15:40

    The full source code is here: https://gist.github.com/1794246

    The trick is to store the newly created ClassDefs 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
      }
    }
    

    0 讨论(0)
提交回复
热议问题