如何解决两种与路径相关的类型的等价性,我知道这些类型是相同的,但编译器没有?
使用Scala 2.10.0 M7我试图将AST从一个宇宙转换为另一个宇宙。
case class MacroBridge(context: Context) {
def toMacroTree(tree: treehugger.forest.Tree): context.universe.Tree = ???
def fromMacroTree(tree: context.universe.Tree): treehugger.forest.Tree = ???
}
在宏实现中,我可以将其用作:
val bridge = treehugger.MacroBridge(c)
def fromMacroTree(tree: c.universe.Tree): Tree = bridge.fromMacroTree(tree)
但是,这会导致编译器错误:
[error] /scalamacros-getting-started/library/Macros.scala:21: type mismatch;
[error] found : c.universe.Tree
[error] required: bridge.context.universe.Tree
[error] possible cause: missing arguments for method or constructor
[error] def fromMacroTree(tree: c.universe.Tree): Tree = bridge.fromMacroTree(tree)
在上面的代码中,c
显然与bridge.context
的值相同,但也许是因为它是值类型检查器无法检查它。放置广义类型约束没有帮助:
def fromMacroTree[A](tree: A)(implicit ev: A =:= context.universe.Tree): Tree =
在宏中,这仍然导致错误:
[error] /scalamacros-getting-started/library/Macros.scala:21: Cannot prove that c.universe.Tree =:= bridge.context.universe.Tree.
[error] def fromMacroTree(tree: c.universe.Tree): Tree = bridge.fromMacroTree(tree)
我需要访问context.universe
,因此我可以访问其他依赖类型,例如TermName
。除了演员之外还有更好的解决方法吗?:
def fromMacroTree(tree: c.universe.Tree): Tree =
bridge.fromMacroTree(tree.asInstanceOf[bridge.context.universe.Tree])
答案 0 :(得分:9)
我可以通过以下方式开展工作:
case class MacroBridge[C <: Context](context: C) {
def fromMacroTree(tree: context.universe.Tree): context.universe.Tree = ???
}
trait MB {
def meth(c: Context) {
val bridge = MacroBridge[c.type](c)
def fromMacroTree(tree: c.universe.Tree): c.universe.Tree =
bridge.fromMacroTree(tree)
}
}
我前段时间差不多same problem。