Skip to content

Instantly share code, notes, and snippets.

Created January 4, 2013 07:35
Show Gist options
  • Save anonymous/4450690 to your computer and use it in GitHub Desktop.
Save anonymous/4450690 to your computer and use it in GitHub Desktop.
import scala.reflect.macros.Context
import language.experimental.macros
case class EnclosingApplication(tree: scala.reflect.runtime.universe.Tree)
object Macros {
def impl(c: Context): c.Expr[EnclosingApplication] = {
import c.universe._
import treeBuild._
val hackedc = c.asInstanceOf[scala.reflect.macros.runtime.Context]
type HackedTree = hackedc.universe.analyzer.global.Tree
type HackedType = hackedc.universe.analyzer.global.Type
val fun = hackedc.callsiteTyper.context.enclosingContextChain.head.tree.asInstanceOf[Apply]
// 0x8301 = EXPRMODE | FUNmode | POLYmode | BYVALmode
val fun1 = hackedc.callsiteTyper.typed(fun.asInstanceOf[HackedTree], 0x8031, WildcardType.asInstanceOf[HackedType]).asInstanceOf[Tree]
val reified = Select(c.reifyTree(mkRuntimeUniverseRef, EmptyTree, fun1), newTermName("tree"))
val result = Apply(Ident(newTermName("EnclosingApplication")), List(reified))
c.Expr[EnclosingApplication](result)
}
implicit def materializeEnclosingApplication: EnclosingApplication = macro impl
}
====
import scala.reflect.runtime.universe._
import Macros._
object Test extends App {
def foo(x: Int)(y: Int)(implicit ea: EnclosingApplication) = println(showRaw(ea.tree, printIds = true, printTypes = true))
foo(2)(3)
def bar(x: Int)(implicit ea: EnclosingApplication) = println(showRaw(ea.tree, printIds = true, printTypes = true))
bar(2)
}
====
10:32 ~/Projects/Kepler_snippet00/sandbox (topic/snippet00)$ scalac Macros.scala && scalac Test.scala && scala Test
Apply(Apply(Select(This(TypeName("Test")), TermName("foo")), List(Literal(Constant(2)))), List(Literal(Constant(3))))
Apply(Select(This(TypeName("Test")), TermName("bar")), List(Literal(Constant(2))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment