6

我在回答this question如何将一个无参数构造函数添加到具有宏注解的Scala案例类中?

而是写的:

case class Person(name: String, age: Int) { 
    def this() = this("",1) 
} 

我想我会用宏注释从展开:

@Annotation 
case class Person(name: String, age: Int) 

所以我尝试添加新的构造函数作为一个纯老DefDef使用quasiquotes在宏注释的impl中,如:

val newCtor = q"""def this() = this("", 1)""" 
val newBody = body :+ newCtor 
q"$mods class $name[..$tparams](..$first)(...$rest) extends ..$parents { $self => ..$newBody }" 

但是那个返回ns错误:called constructor's definition must precede calling constructor's definition

有没有办法解决这个问题?我错过了什么?

感谢您抽空看看, -Julian

回答

5

事实证明,一个很自然的意图产生宏注释二级构造暴露了两个不同的问题。

1)第一个问题(https://issues.scala-lang.org/browse/SI-8451)是关于二次构造函数发出错误树形的quasiquotes。在2.11.0-RC4(尚未发布,目前以2.11.0-SNAPSHOT可用)和2.10.x(昨天发布)的天堂2.0.0-M6中得到修复。

2)第二个问题是关于未指派的职位在typechecker期间造成严重破坏。奇怪的是,当typechecking调用构造函数时,typer使用位置来决定这些调用是否合法。这不容易修补,我们必须解决:

  val newCtor = q"""def this() = this(List(Some("")))""" 
-  val newBody = body :+ newCtor 
+ 
+  // It looks like typer sometimes uses positions to decide whether stuff 
+  // (secondary constructors in this case) typechecks or not (?!!): 
+  // https://github.com/xeno-by/scala/blob/c74e1325ff1514b1042c959b0b268b3c6bf8d349/src/compiler/scala/tools/nsc/typechecker/Typers.scala#L2932 
+  // 
+  // In general, positions are important in getting error messages and debug 
+  // information right, but maintaining positions is too hard, so macro writers typically don't care. 
+  // 
+  // This has never been a problem up until now, but here we're forced to work around 
+  // by manually setting an artificial position for the secondary constructor to be greater 
+  // than the position that the default constructor is going to get after macro expansion. 
+  // 
+  // We have a few ideas how to fix positions in a principled way in Palladium, 
+  // but we'll have to see how it goes. 
+  val defaultCtorPos = c.enclosingPosition 
+  val newCtorPos = defaultCtorPos.withEnd(defaultCtorPos.endOrPoint + 1).withStart(defaultCtorPos.startOrPoint + 1).withPoint(defaultCtorPos. point + 1) 
+  val newBody = body :+ atPos(newCtorPos)(newCtor) 
+0

唉,我使用天堂2.0.0-M6为2.10.3。 [Here](https://github.com/julianpeeters/macro-annotation-example/tree/no-args)是一个最小的可运行示例。并且[这里](https://gist.github.com/julianpeeters/9888898)是M4中的错误。 –

+0

哦,我明白了。所以我们在这里有两个错误。一个由M6固定,另一个依然存在。 –

+2

https://github.com/julianpeeters/macro-annotation-example/pull/1 –

相关问题