0

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

michael
  • 1
  • 1
  • In macros you generally have fully defined types. `val bufferTpe = tq"_root_.scala.collection.mutable.ListBuffer"` and you use these all the time. – flavian May 20 '17 at 18:34
  • @flavian The `ListBuffer`is just an example. It should be possible to define multiple import statements inside the `_1` expression and use these inside the `_2`expression – michael May 20 '17 at 18:46
  • Nope, the standard practice is to use non literal values just like I've shown you above. In a macro you always need to refer to a type by its FQDN starting with `_root_` to make sure no overrides can happen at the callsite of a macro when a user actually needs you macro. – flavian May 20 '17 at 21:46

0 Answers0