看這篇產生的疑問:
http://downgra.de/2010/08/05/scala_gotcha_blocks_and_functions/
object A {
def f(g: Int => Int) {
println(">>> f")
println("g(10): " + g(10))
println("g(20): " + g(20))
println("<<< f")
}
def main(args: Array[String]) {
println("=====================")
f(x => { println("##foo##"); x + 1 })
println("=====================")
f({ println("##bar##"); _ + 1 })
println("=====================")
}
}
跑出來像這樣
=====================
>>> f
##foo##
g(10): 11
##foo##
g(20): 21
<<< f
=====================
##bar##
>>> f
g(10): 11
g(20): 21
<<< f
=====================
雖然在 f 中 g 被呼叫了兩次, 但是 "##foo##" 出現了兩次, "##bar##" 只出現了一次, 且出現位置不同.
怎麼知道程式中的某段用的語法名稱是什麼?
方法之一: 用 compiler plugin dump AST
search: scala ast 找到 http://stackoverflow.com/questions/1788627/scala-ast-in-scala 因此知道有 plugin
scala 的 source distribution 有 docs/examples/plugintemplate 可參考
http://stackoverflow.com/questions/14367189/any-info-out-there-on-migrating-a-scala-2-9-compiler-plugin-to-2-10
http://www.scala-lang.org/node/140
方法之二: scala.reflect. ... (search: scala block tree)
http://www.scala-lang.org/api/current/index.html#scala.reflect.api.Printers
方法之三:
scalac -Xprint:all /tmp/a.scala
scalac -Xprint:all -Yshow-trees /tmp/a.scala
scalac -X
scalac -Y
-Yshow:<phases> (Requires -Xshow-class or -Xshow-object) Show after <phases>
-Yshow-symkinds Print abbreviated symbol kinds next to symbol names.
-Yshow-syms Print the AST symbol hierarchy after each phase.
-Yshow-trees (Requires -Xprint:) Print detailed ASTs in formatted form.
-Yshow-trees-compact (Requires -Xprint:) Print detailed ASTs in compact form.
-Yshow-trees-stringified (Requires -Xprint:) Print stringifications along with detailed ASTs.
待看: http://permalink.gmane.org/gmane.comp.lang.scala.user/27523
search: scala.reflect.generic.Trees (來自 compiler dump 的 keyword)