Skip to content

Commit 8501978

Browse files
committed
Refactor relativePath logic
1 parent f7ea0d0 commit 8501978

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
@@ -209,6 +209,21 @@ object SourceFile {
209209
val src = new SourceFile(new VirtualFile(name, content.getBytes(StandardCharsets.UTF_8)), scala.io.Codec.UTF8)
210210
src._maybeInComplete = maybeIncomplete
211211
src
212+
213+
def relativePath(source: SourceFile)(using Context): String = {
214+
def sourcerootPath =
215+
java.nio.file.Paths.get(ctx.settings.sourceroot.value)
216+
.toAbsolutePath
217+
.normalize
218+
val file = source.file
219+
val jpath = file.jpath
220+
if jpath eq null then
221+
file.path // repl and other custom tests use abstract files with no path
222+
else if jpath.isAbsolute then
223+
sourcerootPath.relativize(jpath.normalize).toString
224+
else
225+
jpath.normalize.toString
226+
}
212227
}
213228

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

0 commit comments

Comments
 (0)