Generating import statements with scala macros

341 views Asked by At

I have the following code:

@mymacro @imports
val _1 = { import scala.collection.mutable.ListBuffer }

@mymacro
val _2 = { val yy: ListBuffer[Int] = ListBuffer.empty }

@mymacro is a scala macro that checks if it has been annotated with the @importsannotation. Part of the implementatation is as follows:

case (cc@q"${mods: Modifiers} val $tname: ${tpt: Tree} = ${expr: Tree}") :: Nil =>
      if (tname.toString().startsWith("_"))
        if (checkImports(mods, expr)) {
          q"import scala.collection.mutable.ListBuffer"
        }
        else
          q"{$expr}"

Currently the macro is able to transform the whole val _1 = ... statement to import scala.collection.mutable.ListBuffer (without the {} brackets!) But when the compilation continues, I keep getting the not found: type ListBuffer compilation error. Now I wonder if it is possible to fix this error somehow without having to define the import statement at the top of the file.

I am using the Scala 2.10 macro paradise plugin

0

There are 0 answers