I'm investigating the possibility to make the following kind of imports compile in Scala:
def helpers[T] = new { def foo: T = ??? }
import helpers[Int]._
This arose as an idea to pin down some types that Scala could not infer on its own. A manually expanded version works:
val m = helpers[Int]
import m._
(foo: Int)
However, my naive attempt at a macro failed:
import scala.reflect.macros.blackbox.Context
object Open {
def open[T](m: Any)(t: T): T = macro open_impl[T]
def open_impl[T](c: Context)(m: c.Tree)(t: c.Tree): c.Tree = {
import c.universe._
val freshName = TermName(c.freshName("import$"))
q"{ val $freshName = $m; import $freshName._; $t }"
}
}
The syntax I had in mind was the let open M in
-syntax from OCaml.
Problem being that the binding of variables seems to happen before the
macro expansion:
import Open._
object Foo { val x = 7 }
open(Foo) { println(x) }
fails in the REPL with:
<console>:16: error: not found: value x
open(Foo) { println(x) }
Any ideas how to work around this? Is it at all possible with macros? Or perhaps with a compiler plugin?