我使用宏注释在类的另一个方法中基于代码内省向类添加方法。我从类定义中提取方法的语法树,但在方法中,不扩展术语和类型的标识符。这些标识符尚未包含有关导入,类中的其他定义和隐式转换的信息。
import geo.model.meta.src.state.IStateCoding
import java.util.{Collection ⇒ JCollection}
import scala.collection.JavaConverters._
@IntrospectionGenerator
class IntrospectionTest(
val a:Int,
val b:String,
map:ConcurrentHashMap[String, JCollection[String]]
){
def inrospectionTarget: IntrospectionTest = {
val map = new ConcurrentHashMap[String, JCollection[String]]()
map.put("some", Seq("bar").asJava)
new IntrospectionTest(a, b, map)
}
}
//Macros definition example
@compileTimeOnly("enable macro paradise to expand macro annotations")
class IntrospectionGenerator extends StaticAnnotation{
def macroTransform(annottees: Any*): Any = macro IntrospectionGenerator.impl
}
object IntrospectionGenerator {
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
annottees.map(_.tree) match{
case (cls @ ClassDef(modifiers, className, typeDefs, template)) :: Nil⇒
val nonInferedContent = template.body.collectFirst{
case DefDef(_, TermName("copyState"), Nil, Nil, _, content) ⇒
content
}.get
val idents = nonInferedContent.collect{
case iden @ Ident(name) ⇒
idents //HOW TO GET SYMBOL FOR THIS IDENTIFIER?
}.flatten
val generatedMethod = q"override def copyStateSource = $someStructure"
val extTemplate = Template(
template.parents,
template.self,
template.body ::: generatedMethod :: Nil
)
c.Expr(ClassDef(modifiers, className, typeDefs, extTemplate))
case _ ⇒
c.abort(c.enclosingPosition, "incorrect use of StateCodingMacro")
}
}
}
1)如何在类的上下文中为方法手动创建上下文(BlackBox),以便此上下文知道类中的所有定义?
2)如何在没有常见typeCheck调用的方法的AST内获得某些标识符(类或方法的完全限定名称)的定义?我想保留原始树结构,但同时要了解此树中术语和类型的标识符是指什么。上述代码中的标识符示例:JCollection,asJava,a,b,map,IntrospectionTest。