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
    }      

The result is:

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

I expected:

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

The last brackets } (and end of line) is missing if I use position from Tree object: text.substring(t.pos.start, t.pos.end)

Any proposal how to extract all text from scala.reflect.api.Trees#Tree object?

Update

Affected scala versions :

  • 2.10.6 - needed for sbt 0.13.x
  • 2.11.8
  • 2.12.7

For scala 2.10.6/2.12.7 result is the same like in above output.

Add project to github

Example project for searching the solution

Andrzej Jozwik
  • 14,331
  • 3
  • 59
  • 68

1 Answers1

0

Just to move the question off the unanswered list, one can refer to the issue booked for it:

https://issues.scala-lang.org/browse/SI-8859

som-snytt
  • 39,429
  • 2
  • 47
  • 129