Skip to content

Commit 0c09917

Browse files
committed
Add sourceCode to TASTy reflect Position
Partial fix for scala#5782: * get the ~raw code of arguments of the root context (in `def foo(s: Seq[Int])(implicit foo: Foo)`, with the implicit materialization of `Foo` backed by a macro - how can the macro get a String `"(1 to 10).sum"` in `f((1 to 10).sum)`?). Prevents to have `sourcecode.Text` work fine.
1 parent 732f7e2 commit 0c09917

File tree

5 files changed

+35
-0
lines changed

5 files changed

+35
-0
lines changed

compiler/src/dotty/tools/dotc/tastyreflect/PositionOpsImpl.scala

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,7 @@ trait PositionOpsImpl extends scala.tasty.reflect.PositionOps with CoreImpl {
1515

1616
def startColumn: Int = pos.startColumn
1717
def endColumn: Int = pos.endColumn
18+
19+
def sourceCode: String = new String(pos.source.content(), pos.start, pos.end - pos.start)
1820
}
1921
}

library/src/scala/tasty/reflect/PositionOps.scala

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ trait PositionOps extends Core {
2626
/** The end column in the source file */
2727
def endColumn: Int
2828

29+
/** Source code within the position */
30+
def sourceCode: String
31+
2932
}
3033
implicit def PositionDeco(pos: Position): PositionAPI
3134

tests/run/tasty-original-source.check

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
(foo("abc"),abc)
2+
(foo( "def" ),def)
3+
(foo("ghi" /* comment */),ghi)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import scala.quoted._
2+
import scala.tasty._
3+
4+
object Macros {
5+
6+
implicit inline def withSource(arg: Any): (String, Any) = ~impl('(arg))
7+
8+
private def impl(arg: Expr[Any])(implicit reflect: Reflection): Expr[(String, Any)] = {
9+
import reflect._
10+
val source = arg.unseal.underlyingArgument.pos.sourceCode.toString.toExpr
11+
'(Tuple2(~source, ~arg))
12+
}
13+
14+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
2+
import Macros._
3+
4+
object Test {
5+
def main(args: Array[String]): Unit = {
6+
println(withSource(foo("abc")))
7+
println(withSource( foo( "def" )))
8+
println(withSource(foo("ghi" /* comment */)))
9+
}
10+
11+
def foo(x: Any): Any = x
12+
13+
}

0 commit comments

Comments
 (0)