2014-08-28 79 views
5
Welcome to Scala 2.12.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_121). 
Type in expressions for evaluation. Or try :help. 

scala> :paste 
// Entering paste mode (ctrl-D to finish) 

import scala.reflect.runtime._ 
import scala.reflect.runtime.universe._ 
import scala.tools.reflect.ToolBox 

val mirror = universe.runtimeMirror(universe.getClass.getClassLoader) 
val toolbox = mirror.mkToolBox(options = "-Yrangepos") 
val text = 
    """ 
    |libraryDependencies ++= Seq("org.scala-lang" % "scala-compiler" % "2.10.4") map { 
    | (dependency) =>{ 
    |  dependency 
    | } 
    |} 
    """.stripMargin 
val parsed = toolbox.parse(text) 

val parsedTrees = parsed match { 
    case Block(stmt, expr) => 
    stmt :+ expr 
    case t: Tree => 
    Seq(t) 
} 

val statements = parsedTrees.map { (t: Tree) => 
    text.substring(t.pos.start, t.pos.end) 
} 


// Exiting paste mode, now interpreting. 

import scala.reflect.runtime._ 
import scala.reflect.runtime.universe._ 
import scala.tools.reflect.ToolBox 
mirror: reflect.runtime.universe.Mirror = JavaMirror with primordial classloader with boot classpath... 
scala> statements.head 
res0: String = 
libraryDependencies ++= Seq("org.scala-lang" % "scala-compiler" % "2.10.4") map { 
    (dependency) =>{ 
     dependency 
    }  

結果是: Scala的解析器切口最後托架

scala> statements.head 
res1: String = 
libraryDependencies ++= Seq("org.scala-lang" % "scala-compiler" % "2.10.4") map { 
    (dependency) =>{ 
     dependency 
    } 

我預期:

libraryDependencies ++= Seq("org.scala-lang" % "scala-compiler" % "2.10.4") map { 
    (dependency) =>{ 
     dependency 
    } 
} 

最後括號}(和線的端部),如果我使用位置缺少from樹對象:text.substring(t.pos.start, t.pos.end)

任何pro posal如何從scala.reflect.api.Trees#Tree對象中提取所有文本?

更新

受影響的版本階:

  • 2.10.6 - 需要SBT 0.13.x
  • 2.11.8
  • 2.12.1

對於scala 2.10.6/2.12.1的結果與上面的輸出結果相同。

項目添加到GitHub上

Example project for searching the solution

+0

我發現://grokbase.com/t/gg/scala-internals/129smefjxe/reflection-universe-and-range-positions。選項'-Yrangepos'是它的責任。如何更改/設置其他選項? – 2014-08-28 11:01:19

+0

2.11.6仍然受到影響 – 2015-03-13 10:05:16

回答