【问题标题】:scala compiler's stackoverflow protectionscala编译器堆栈溢出保护
【发布时间】:2015-02-04 06:21:32
【问题描述】:
在运行时我可以:
def X(R: Any): Any = X(R)
但不能在编译时做类似的事情:
scala> type X[R] = X[R]
<console>:11: error: illegal cyclic reference involving type X
type X[R] = X[R]
^
似乎是无限循环/递归保护,但据我了解Halting problem - 没有通用方法来检测turing-complete 语言的无限递归(因为检测器本身可能不会停止),所以额外的编译器检查将一般不在这里工作。
那么有没有办法在 scalac 上获得无限递归?而且,有没有其他(除了防止这种递归)理由拥有illegal cyclic reference?
【问题讨论】:
标签:
scala
scalac
halting-problem
【解决方案1】:
有一种棘手的方法可以使用递归结合多态性在 scalac 上获取 StackOverflow:
scala> trait Re { type X[R <: Re] }
warning: there were 1 feature warning(s); re-run with -feature for details
defined trait Re
scala> trait ReRe extends Re {type X[R <: Re] = R#X[R]}
defined trait ReRe
scala> type X = ReRe#X[ReRe]
java.lang.StackOverflowError
之所以有效,是因为编译器认为R#X[R] 是在Re 上调用的,但实际上在计算type X 时传递了ReRe。
不知道 illegal cyclic reference 的用途 - 也许它只保护编译器内部的无限循环,而不是无限递归(如果使用非尾递归实现图灵完备性)。