/
SymbolIndexBucket.scala
381 lines (351 loc) Β· 11.6 KB
/
SymbolIndexBucket.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package scala.meta.internal.mtags
import java.io.UncheckedIOException
import java.nio.CharBuffer
import java.util.logging.Level
import java.util.logging.Logger
import scala.util.Properties
import scala.util.control.NonFatal
import scala.meta.Dialect
import scala.meta.internal.io.FileIO
import scala.meta.internal.io.PathIO
import scala.meta.internal.mtags.ScalametaCommonEnrichments._
import scala.meta.internal.semanticdb.Scala._
import scala.meta.internal.{semanticdb => s}
import scala.meta.io.AbsolutePath
final case class SymbolLocation(
path: AbsolutePath,
range: Option[s.Range]
)
/**
* Index split on buckets per dialect in order to have a constant time
* and low memory footprint to infer dialect for SymbolDefinition because
* it's used in WorkspaceSymbolProvider
*
* @param toplevels keys are non-trivial toplevel symbols and values are the file
* the symbols are defined in.
* @param definitions keys are global symbols and the values are the files the symbols
* are defined in. Difference between toplevels and definitions
* is that toplevels contains only symbols generated by ScalaToplevelMtags
* while definitions contains only symbols generated by ScalaMtags.
*/
class SymbolIndexBucket(
toplevels: AtomicTrieMap[String, Set[AbsolutePath]],
definitions: AtomicTrieMap[String, Set[SymbolLocation]],
sourceJars: OpenClassLoader,
toIndexSource: AbsolutePath => AbsolutePath = identity,
mtags: Mtags,
dialect: Dialect
) {
private val logger = Logger.getLogger(classOf[SymbolIndexBucket].getName)
def close(): Unit = sourceJars.close()
def addSourceDirectory(
dir: AbsolutePath
): List[IndexingResult] = {
if (sourceJars.addEntry(dir.toNIO)) {
dir.listRecursive.toList.flatMap {
case source if source.isScala =>
addSourceFile(source, Some(dir), isJava = false)
case _ =>
None
}
} else List.empty
}
def addSourceJar(
jar: AbsolutePath
): List[IndexingResult] = {
if (sourceJars.addEntry(jar.toNIO)) {
FileIO.withJarFileSystem(jar, create = false) { root =>
try {
root.listRecursive.toList.flatMap {
case source if source.isScala =>
addSourceFile(source, None, isJava = false)
case source if source.isJava =>
addSourceFile(source, None, isJava = true)
case _ =>
None
}
} catch {
// this happens in broken jars since file from FileWalker should exists
case _: UncheckedIOException => Nil
}
}
} else
List.empty
}
def addIndexedSourceJar(
jar: AbsolutePath,
symbols: List[(String, AbsolutePath)]
): Unit = {
if (sourceJars.addEntry(jar.toNIO)) {
symbols.foreach { case (sym, path) =>
toplevels.updateWith(sym) {
case Some(acc) => Some(acc + path)
case None => Some(Set(path))
}
}
}
}
def addSourceFile(
source: AbsolutePath,
sourceDirectory: Option[AbsolutePath],
isJava: Boolean
): Option[IndexingResult] = {
val IndexingResult(path, topLevels, overrides) =
indexSource(source, dialect, sourceDirectory, isJava)
topLevels.foreach { symbol =>
toplevels.updateWith(symbol) {
case Some(acc) => Some(acc + source)
case None => Some(Set(source))
}
}
Some(IndexingResult(path, topLevels, overrides))
}
private def indexSource(
source: AbsolutePath,
dialect: Dialect,
sourceDirectory: Option[AbsolutePath],
isJava: Boolean
): IndexingResult = {
val uri = source.toIdeallyRelativeURI(sourceDirectory)
val (doc, overrides) = mtags.indexWithOverrides(source, dialect)
val sourceTopLevels =
doc.occurrences.iterator
.filterNot(_.symbol.isPackage)
.map(_.symbol)
val topLevels =
if (source.isAmmoniteScript) sourceTopLevels.toList
else if (isJava) {
sourceTopLevels.toList.headOption
.filter(sym => !isTrivialToplevelSymbol(uri, sym, "java"))
.toList
} else {
sourceTopLevels
.filter(sym => !isTrivialToplevelSymbol(uri, sym, "scala"))
.toList
}
IndexingResult(source, topLevels, overrides)
}
// Returns true if symbol is com/foo/Bar# and path is /com/foo/Bar.scala
// Such symbols are "trivial" because their definition location can be computed
// on the fly.
private def isTrivialToplevelSymbol(
path: String,
symbol: String,
extension: String = "scala"
): Boolean = {
val pathBuffer =
CharBuffer.wrap(path).subSequence(1, path.length - extension.length - 1)
val symbolBuffer =
CharBuffer.wrap(symbol).subSequence(0, symbol.length - 1)
pathBuffer.equals(symbolBuffer)
}
def addToplevelSymbol(
path: String,
source: AbsolutePath,
toplevel: String
): Unit = {
if (source.isAmmoniteScript || !isTrivialToplevelSymbol(path, toplevel)) {
toplevels.updateWith(toplevel) {
case Some(acc) => Some(acc + source)
case None => Some(Set(source))
}
}
}
def query(symbol: Symbol): List[SymbolDefinition] =
query0(symbol, symbol)
/**
* Returns the file where symbol is defined, if any.
*
* Uses two strategies to recover from missing symbol definitions:
* - try to enter the toplevel symbol definition, then lookup symbol again.
* - if the symbol is synthetic, for examples from a case class of macro annotation,
* fall back to related symbols from the enclosing class, see `DefinitionAlternatives`.
*
* @param querySymbol The original symbol that was queried by the user.
* @param symbol The symbol that
* @return
*/
private def query0(
querySymbol: Symbol,
symbol: Symbol
): List[SymbolDefinition] = {
removeOldEntries(symbol)
if (!definitions.contains(symbol.value)) {
// Fallback 1: enter the toplevel symbol definition
val toplevel = symbol.toplevel
val files = toplevels.get(toplevel.value)
files match {
case Some(files) =>
files.foreach(addMtagsSourceFile(_))
case _ =>
loadFromSourceJars(trivialPaths(toplevel))
.orElse(loadFromSourceJars(modulePaths(toplevel)))
.foreach(_.foreach(addMtagsSourceFile(_)))
}
if (!definitions.contains(symbol.value)) {
// Fallback 2: try with files for companion class
if (toplevel.value.endsWith(".")) {
val toplevelAlternative = s"${toplevel.value.stripSuffix(".")}#"
for {
companionClassFile <- toplevels
.get(toplevelAlternative)
.toSet
.flatten
if (!files.exists(_.contains(companionClassFile)))
} addMtagsSourceFile(companionClassFile)
}
}
}
if (!definitions.contains(symbol.value)) {
// Fallback 3: guess related symbols from the enclosing class.
DefinitionAlternatives(symbol)
.flatMap(alternative => query0(querySymbol, alternative))
} else {
definitions
.get(symbol.value)
.map { paths =>
paths.map { location =>
SymbolDefinition(
querySymbol = querySymbol,
definitionSymbol = symbol,
path = location.path,
dialect = dialect,
range = location.range,
kind = None,
properties = 0
)
}.toList
}
.getOrElse(List.empty)
}
}
/**
* Remove possible old, outdated entries from the toplevels and definitions.
* This action is performed when a symbol is queried, to avoid returning incorrect results.
*/
private def removeOldEntries(symbol: Symbol): Unit = {
val exists =
(toplevels.get(symbol.value).getOrElse(Set.empty) ++ definitions
.get(symbol.value)
.map(_.map(_.path))
.getOrElse(Set.empty)).filter(_.exists)
toplevels.updateWith(symbol.value) {
case None => None
case Some(acc) =>
val updated = acc.filter(exists(_))
if (updated.isEmpty) None
else Some(updated)
}
definitions.updateWith(symbol.value) {
case None => None
case Some(acc) =>
val updated = acc.filter(loc => exists(loc.path))
if (updated.isEmpty) None
else Some(updated)
}
}
private def allSymbols(path: AbsolutePath): s.TextDocument = {
val toIndexSource0 = toIndexSource(path)
mtags.allSymbols(toIndexSource0, dialect)
}
// similar as addSourceFile except indexes all global symbols instead of
// only non-trivial toplevel symbols.
private def addMtagsSourceFile(
file: AbsolutePath,
retry: Boolean = true
): Unit = try {
val docs: s.TextDocuments = PathIO.extension(file.toNIO) match {
case "scala" | "java" | "sc" =>
val document = allSymbols(file)
s.TextDocuments(List(document))
case _ =>
s.TextDocuments(Nil)
}
if (docs.documents.nonEmpty) {
addTextDocuments(file, docs)
}
} catch {
case NonFatal(e) =>
logger.log(Level.WARNING, s"Error indexing $file", e)
if (retry) addMtagsSourceFile(file, retry = false)
}
// Records all global symbol definitions.
private def addTextDocuments(
file: AbsolutePath,
docs: s.TextDocuments
): Unit = {
docs.documents.foreach { document =>
document.occurrences.foreach { occ =>
if (occ.symbol.isGlobal && occ.role.isDefinition) {
definitions.updateWith(occ.symbol) {
case Some(acc) => Some(acc + SymbolLocation(file, occ.range))
case None => Some(Set(SymbolLocation(file, occ.range)))
}
} else {
// do nothing, we only care about global symbol definitions.
}
}
}
}
// Returns the first path that resolves to a file.
private def loadFromSourceJars(
paths: List[String]
): Option[List[AbsolutePath]] = {
paths match {
case Nil => None
case head :: tail =>
sourceJars.resolveAll(head) match {
case Nil => loadFromSourceJars(tail)
case values => Some(values.map(AbsolutePath.apply))
}
}
}
// Returns relative file paths for trivial toplevel symbols, example:
// Input: scala/collection/immutable/List#
// Output: scala/collection/immutable/List.scala
// scala/collection/immutable/List.java
private def trivialPaths(toplevel: Symbol): List[String] = {
val noExtension = toplevel.value.stripSuffix(".").stripSuffix("#")
List(
noExtension + ".scala",
noExtension + ".java"
)
}
private def modulePaths(toplevel: Symbol): List[String] = {
if (Properties.isJavaAtLeast("9")) {
val noExtension = toplevel.value.stripSuffix(".").stripSuffix("#")
val javaSymbol = noExtension.replace("/", ".")
for {
cls <- sourceJars.loadClassSafe(javaSymbol).toList
// note(@tgodzik) Modules are only available in Java 9+, so we need to invoke this reflectively
module <- Option(
cls.getClass().getMethod("getModule").invoke(cls)
).toList
moduleName <- Option(
module.getClass().getMethod("getName").invoke(module)
).toList
file <- List(
s"$moduleName/$noExtension.java",
s"$moduleName/$noExtension.scala"
)
} yield file
} else {
Nil
}
}
}
object SymbolIndexBucket {
def empty(
dialect: Dialect,
mtags: Mtags,
toIndexSource: AbsolutePath => AbsolutePath
): SymbolIndexBucket =
new SymbolIndexBucket(
AtomicTrieMap.empty,
AtomicTrieMap.empty,
new OpenClassLoader,
toIndexSource,
mtags,
dialect
)
}