forked from scala/scala3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSemanticdbTextDocumentProvider.scala
63 lines (56 loc) · 1.9 KB
/
SemanticdbTextDocumentProvider.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package dotty.tools.pc
import java.io.ByteArrayOutputStream
import java.net.URI
import java.nio.file.Path
import java.nio.file.Paths
import scala.meta.internal.mtags.MD5
import scala.util.Properties
import dotty.tools.dotc.interactive.InteractiveDriver
import dotty.tools.dotc.semanticdb.ExtractSemanticDB
import dotty.tools.dotc.semanticdb.Language
import dotty.tools.dotc.semanticdb.Schema
import dotty.tools.dotc.semanticdb.TextDocument
import dotty.tools.dotc.semanticdb.internal.SemanticdbOutputStream
import dotty.tools.dotc.util.SourceFile
class SemanticdbTextDocumentProvider(
driver: InteractiveDriver,
workspace: Option[Path]
) extends WorksheetSemanticdbProvider:
def textDocument(
uri: URI,
sourceCode: String
): Array[Byte] =
val filePath = Paths.get(uri)
val validCode = removeMagicImports(sourceCode, filePath)
driver.run(
uri,
SourceFile.virtual(filePath.toString, validCode)
)
val tree = driver.currentCtx.run.units.head.tpdTree
val extractor = ExtractSemanticDB.Extractor()
extractor.traverse(tree)(using driver.currentCtx)
val path = workspace
.flatMap { workspacePath =>
scala.util.Try(workspacePath.relativize(filePath)).toOption
}
.map { relativeUri =>
if Properties.isWin then relativeUri.toString().replace("\\", "/")
else relativeUri.toString()
}
.getOrElse(filePath.toString)
val document = TextDocument(
schema = Schema.SEMANTICDB4,
language = Language.SCALA,
uri = path,
text = sourceCode,
md5 = MD5.compute(sourceCode),
symbols = extractor.symbolInfos.toList,
occurrences = extractor.occurrences.toList
)
val byteStream = new ByteArrayOutputStream()
val out = SemanticdbOutputStream.newInstance(byteStream)
document.writeTo(out)
out.flush()
byteStream.toByteArray
end textDocument
end SemanticdbTextDocumentProvider