Skip to content

Commit a274a26

Browse files
committed
Refactor relativePath logic
1 parent e06e7b7 commit a274a26

File tree

2 files changed

+16
-15
lines changed

2 files changed

+16
-15
lines changed

compiler/src/dotty/tools/dotc/transform/PostTyper.scala

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -335,21 +335,7 @@ class PostTyper extends MacroTransform with IdentityDenotTransformer { thisPhase
335335
&& ctx.compilationUnit.source.exists
336336
&& sym != defn.SourceFileAnnot
337337
then
338-
def sourcerootPath =
339-
java.nio.file.Paths.get(ctx.settings.sourceroot.value)
340-
.toAbsolutePath
341-
.normalize
342-
val file = ctx.compilationUnit.source.file
343-
val jpath = file.jpath
344-
val relativePath =
345-
if jpath eq null then file.path // repl and other custom tests use abstract files with no path
346-
else if jpath.isAbsolute then
347-
val cunitPath = jpath.normalize
348-
// On Windows we can only relativize paths if root component matches
349-
// (see implementation of sun.nio.fs.WindowsPath#relativize)
350-
try sourcerootPath.relativize(cunitPath).toString
351-
catch case _: IllegalArgumentException => cunitPath.toString
352-
else jpath.normalize.toString
338+
val relativePath = util.SourceFile.relativePath(ctx.compilationUnit.source)
353339
sym.addAnnotation(Annotation.makeSourceFile(relativePath))
354340
else (tree.rhs, sym.info) match
355341
case (rhs: LambdaTypeTree, bounds: TypeBounds) =>

compiler/src/dotty/tools/dotc/util/SourceFile.scala

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,21 @@ object SourceFile {
191191
val src = new SourceFile(new VirtualFile(name, content.getBytes(StandardCharsets.UTF_8)), scala.io.Codec.UTF8)
192192
src._maybeInComplete = maybeIncomplete
193193
src
194+
195+
def relativePath(source: SourceFile)(using Context): String = {
196+
def sourcerootPath =
197+
java.nio.file.Paths.get(ctx.settings.sourceroot.value)
198+
.toAbsolutePath
199+
.normalize
200+
val file = source.file
201+
val jpath = file.jpath
202+
if jpath eq null then
203+
file.path // repl and other custom tests use abstract files with no path
204+
else if jpath.isAbsolute then
205+
sourcerootPath.relativize(jpath.normalize).toString
206+
else
207+
jpath.normalize.toString
208+
}
194209
}
195210

196211
@sharable object NoSource extends SourceFile(NoAbstractFile, Array[Char]()) {

0 commit comments

Comments
 (0)