2015-11-30 89 views
0

我正在使用macros annotation生成代碼。我想根據其他字符串參數改變它的行爲。所以對於相同的代碼它會產生不同的結果。我密切關注僅包含最簡單用法的宏註釋指南。如何使用宏擴展將參數傳遞給註釋

@myMacros 
class MyClass { 
} 

這就是我現在如何使用宏。我想什麼來實現:

@myMacros(name : String) 
class MyClass { 
} 

回答

1

可以使用macroApplication

class AnnotationPassVal(val name: String) extends StaticAnnotation { 
    def macroTransform(annottees: Any*): Any = macro AnnotationPassValImpl.apply 
} 

class AnnotationPassValImpl(val c: Context) { 

    import c.universe._ 

    def showInfo(s: String) = 
    c.info(c.enclosingPosition, s.split("\n").mkString("\n |---macro info---\n |", "\n |", ""), true) 

    def apply(annottees: c.Expr[Any]*) = { 
    val a = c.macroApplication 

    //look macroApplication is what 
    showInfo(show(a)) 


    val AnnotationName: Tree = a match { 
     case q"new AnnotationPassVal(name = $name).macroTransform(..$a)" => 
     name: Tree 
    } 

    showInfo(show(AnnotationName)) 
    q"""{..$annottees}""" 
    } 
} 

測試

@AnnotationPassVal(name = "hello") 
class AnnotationPassValTest //when show info "hello" 
+0

,建議您使用標籤'斯卡拉-macros',會更容易找到問題 –