如何在quasiquote中拼接各种类型的符号?

时间:2014-01-03 16:17:58

标签: scala scala-macros scala-quasiquotes

我正在开发一个宏,在其实现中我得到了weakTypeOf T,其中T是宏函数的类型参数。我想将信息从这个具体类型的方法定义拼接到一个新的类声明树。我无法获得类型参数的AST(为了模式匹配),所以我必须使用基于符号的API。我的问题是如何在比缩进和成员选择更多的位置拼接符号?

例如,要获取我所做的符号列表:

val methodDefs = tpe.declarations
.filter(decl => decl.isMethod && decl.isPublic && !decl.asMethod.isConstructor && !decl.isSynthetic)
.map(symb => symb.asMethod)

然后将信息拼接到q插值器我想这样做:

val newdefs : List[Tree] = methodDefs.map(methodDef => { q"def ${methodDef.name}[..${methodDef.typeParams}](...${methodDef.paramss}): ${methodDef.returnType} = ???"})

根据符号如何拼接(described here (PDF)),我无法直接进行这种拼接。实现这一目标的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

我认为这样的事情就足够了:

val newdefs = tpe
    .declarations
    .collect {
        case m: MethodSymbol if !m.isConstructor && m.typeParams.length > 0 => 
            val typeParams =  m.typeParams.map(TypeDef(_))
            val paramss = m.paramss.map(_.map(ValDef(_)))
            val returns = TypeTree(m.returnType)
            q"def ${m.name}[..${typeParams}](...${paramss}): ${returns} = ???"
    }.toList