From 95661492497769723063afa51f69794acda94369 Mon Sep 17 00:00:00 2001 From: Nicolas Stucki Date: Mon, 28 Mar 2022 16:41:00 +0200 Subject: [PATCH] Detect when position is not in known source If the position is outside of the known contents of the source we do not return any source. --- .../quoted/runtime/impl/QuotesImpl.scala | 5 +-- .../tasty-inspector/i14785.scala | 33 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 tests/run-custom-args/tasty-inspector/i14785.scala diff --git a/compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala b/compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala index 8193b5ef4ce6..7641b9f0489b 100644 --- a/compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala +++ b/compiler/src/scala/quoted/runtime/impl/QuotesImpl.scala @@ -2816,8 +2816,9 @@ class QuotesImpl private (using val ctx: Context) extends Quotes, QuoteUnpickler def startColumn: Int = self.startColumn def endColumn: Int = self.endColumn def sourceCode: Option[String] = - // TODO detect when we do not have a source and return None - Some(new String(self.source.content(), self.start, self.end - self.start)) + val contents = self.source.content() + if contents.length < self.end then None + else Some(new String(contents, self.start, self.end - self.start)) end extension end PositionMethods diff --git a/tests/run-custom-args/tasty-inspector/i14785.scala b/tests/run-custom-args/tasty-inspector/i14785.scala new file mode 100644 index 000000000000..eef7571f9420 --- /dev/null +++ b/tests/run-custom-args/tasty-inspector/i14785.scala @@ -0,0 +1,33 @@ + +import scala.quoted.* +import scala.tasty.inspector.* + +@main def Test: Unit = { + val classpath = System.getProperty("java.class.path").split(java.io.File.pathSeparatorChar).toList + val jar = classOf[dotty.tools.dotc.Compiler].getProtectionDomain.getCodeSource.getLocation.getPath + println(classpath) + TastyInspector.inspectAllTastyFiles( + tastyFiles = Nil, + jars = jar :: Nil, + dependenciesClasspath = classpath.filter(_.contains("scala3-compiler_3")) + )(new MyInspector) +} + + +class MyInspector extends Inspector { + def inspect(using Quotes)(tastys: List[Tasty[quotes.type]]): Unit = { + import quotes.reflect.* + val traverser = new TreeTraverser { + override def traverseTree(tree: Tree)(owner: Symbol): Unit = { + tree.pos.sourceCode + super.traverseTree(tree)(owner) + } + } + + tastys.foreach { tasty => + if tasty.path == "dotty/tools/dotc/core/Phases.class" then + val tree = tasty.ast + traverser.traverseTree(tree)(tree.symbol) + } + } +}