/
Completions.scala
944 lines (890 loc) Β· 29.4 KB
/
Completions.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
package scala.meta.internal.pc.completions
import java.net.URI
import java.util.logging.Level
import scala.collection.immutable.Nil
import scala.collection.mutable
import scala.reflect.internal.Chars
import scala.util.control.NonFatal
import scala.meta.internal.jdk.CollectionConverters._
import scala.meta.internal.mtags.BuildInfo
import scala.meta.internal.mtags.CoursierComplete
import scala.meta.internal.mtags.MtagsEnrichments._
import scala.meta.internal.pc.IdentifierComparator
import scala.meta.internal.pc.InterpolationSplice
import scala.meta.internal.pc.MemberOrdering
import scala.meta.internal.pc.MetalsGlobal
import scala.meta.internal.semanticdb.Scala._
import org.eclipse.{lsp4j => l}
/**
* Utility methods for completions.
*/
trait Completions { this: MetalsGlobal =>
val clientSupportsSnippets: Boolean =
metalsConfig.isCompletionSnippetsEnabled()
val coursierComplete = new CoursierComplete(BuildInfo.scalaCompilerVersion)
/**
* A member for symbols on the classpath that are not in scope, produced via workspace/symbol.
*/
class WorkspaceMember(sym: Symbol)
extends ScopeMember(sym, NoType, true, EmptyTree) {
def additionalTextEdits: List[l.TextEdit] = Nil
def wrap: String => String = identity
def editRange: Option[l.Range] = None
}
class WorkspaceImplicitMember(sym: Symbol)
extends ScopeMember(sym, sym.tpe, true, EmptyTree)
class WorkspaceInterpolationMember(
sym: Symbol,
override val additionalTextEdits: List[l.TextEdit],
override val wrap: String => String,
override val editRange: Option[l.Range]
) extends WorkspaceMember(sym)
class NamedArgMember(sym: Symbol)
extends ScopeMember(sym, NoType, true, EmptyTree)
class DependecyMember(val dependency: String, val edit: l.TextEdit)
extends ScopeMember(
completionsSymbol(dependency),
NoType,
true,
EmptyTree
) {
val label: String = dependency.stripPrefix(":")
def isVersion: Boolean =
label.takeWhile(_ != '-').forall(c => c.isDigit || c == '.')
}
class TextEditMember(
val filterText: String,
val edit: l.TextEdit,
sym: Symbol,
val label: Option[String] = None,
val detail: Option[String] = None,
val command: Option[String] = None,
val additionalTextEdits: List[l.TextEdit] = Nil,
val commitCharacter: Option[String] = None
) extends ScopeMember(sym, NoType, true, EmptyTree)
val packageSymbols: mutable.Map[String, Option[Symbol]] =
mutable.Map.empty[String, Option[Symbol]]
def packageSymbolFromString(symbol: String): Option[Symbol] =
if (symbol == "_empty_/") Some(rootMirror.EmptyPackage)
else {
packageSymbols.getOrElseUpdate(
symbol, {
val fqn = symbol.stripSuffix("/").replace('/', '.')
try {
Some(rootMirror.staticPackage(fqn))
} catch {
case NonFatal(_) =>
None
}
}
)
}
/**
* Returns a high number for less relevant symbols and low number for relevant numbers.
*
* Relevance is computed based on several factors such as
* - local vs global
* - public vs private
* - synthetic vs non-synthetic
*/
def relevancePenalty(m: Member): Int =
m match {
case tm: TypeMember if tm.accessible =>
computeRelevancePenalty(
tm.sym,
m.implicitlyAdded,
tm.inherited
)
case w: WorkspaceMember =>
MemberOrdering.IsWorkspaceSymbol + w.sym.name.length()
case w: OverrideDefMember =>
var penalty = computeRelevancePenalty(
w.sym,
m.implicitlyAdded,
isInherited = false
) >>> 15
if (!w.sym.isAbstract) penalty |= MemberOrdering.IsNotAbstract
penalty
case sm: ScopeMember if sm.accessible =>
computeRelevancePenalty(
sm.sym,
m.implicitlyAdded,
isInherited = false
)
case _ =>
Int.MaxValue
}
/**
* Computes the relative relevance of a symbol in the completion list
* This is an adaptation of
* https://github.com/scala-ide/scala-ide/blob/a17ace0ee1be1875b8992664069d8ad26162eeee/org.scala-ide.sdt.core/src/org/scalaide/core/completion/ProposalRelevanceCalculator.scala
*/
private def computeRelevancePenalty(
sym: Symbol,
viaImplicitConversion: Boolean,
isInherited: Boolean
): Int = {
import MemberOrdering._
var relevance = 0
// local symbols are more relevant
if (!sym.isLocalToBlock) relevance |= IsNotLocalByBlock
// symbols defined in this file are more relevant
if (!sym.pos.isDefined || sym.hasPackageFlag)
relevance |= IsNotDefinedInFile
// fields are more relevant than non fields
if (!sym.hasGetter) relevance |= IsNotGetter
// non-inherited members are more relevant
if (isInherited) relevance |= IsInherited
// symbols whose owner is a base class are less relevant
val isInheritedBaseMethod = sym.owner match {
case definitions.AnyClass | definitions.AnyRefClass |
definitions.ObjectClass =>
true
case _ =>
false
}
if (isInheritedBaseMethod)
relevance |= IsInheritedBaseMethod
// symbols not provided via an implicit are more relevant
if (viaImplicitConversion) relevance |= IsImplicitConversion
if (sym.hasPackageFlag) relevance |= IsPackage
// accessors of case class members are more relevant
if (!sym.isCaseAccessor) relevance |= IsNotCaseAccessor
// public symbols are more relevant
if (!sym.isPublic) relevance |= IsNotCaseAccessor
// synthetic symbols are less relevant (e.g. `copy` on case classes)
if (sym.isSynthetic) relevance |= IsSynthetic
if (sym.isDeprecated) relevance |= IsDeprecated
if (isEvilMethod(sym.name)) relevance |= IsEvilMethod
relevance
}
lazy val isEvilMethod: Set[Name] = Set[Name](
termNames.notifyAll_,
termNames.notify_,
termNames.wait_,
termNames.clone_,
termNames.finalize_
)
def memberOrdering(
query: String,
history: ShortenedNames,
completion: CompletionPosition
): Ordering[Member] =
new Ordering[Member] {
val queryLower = query.toLowerCase()
val fuzzyCache = mutable.Map.empty[Symbol, Int]
def compareLocalSymbols(o1: Member, o2: Member): Int = {
if (
o1.sym.isLocallyDefinedSymbol &&
o2.sym.isLocallyDefinedSymbol &&
!o1.isInstanceOf[NamedArgMember] &&
!o2.isInstanceOf[NamedArgMember]
) {
if (o1.sym.pos.isAfter(o2.sym.pos)) -1
else 1
} else {
0
}
}
def fuzzyScore(o: Member): Int = {
fuzzyCache.getOrElseUpdate(
o.sym, {
val name = o.sym.name.toString().toLowerCase()
if (name.startsWith(queryLower)) 0
else if (name.toLowerCase().contains(queryLower)) 1
else 2
}
)
}
override def compare(o1: Member, o2: Member): Int = {
val byCompletion = completion.compare(o1, o2)
if (byCompletion != 0) byCompletion
else {
val byLocalSymbol = compareLocalSymbols(o1, o2)
if (byLocalSymbol != 0) byLocalSymbol
else {
val byRelevance = Integer.compare(
relevancePenalty(o1),
relevancePenalty(o2)
)
if (byRelevance != 0) byRelevance
else {
val byFuzzy =
java.lang.Integer.compare(fuzzyScore(o1), fuzzyScore(o2))
if (byFuzzy != 0) byFuzzy
else {
val byIdentifier =
IdentifierComparator.compare(
o1.sym.name.decode,
o2.sym.name.decode
)
if (byIdentifier != 0) byIdentifier
else {
val byOwner =
o1.sym.owner.fullName.compareTo(o2.sym.owner.fullName)
if (byOwner != 0) byOwner
else {
val byParamCount = Integer.compare(
o1.sym.paramss.iterator.flatten.size,
o2.sym.paramss.iterator.flatten.size
)
if (byParamCount != 0) byParamCount
else {
detailString(o1, history)
.compareTo(detailString(o2, history))
}
}
}
}
}
}
}
}
}
def infoString(sym: Symbol, info: Type, history: ShortenedNames): String =
sym match {
case m: MethodSymbol =>
new SignaturePrinter(m, history, info, includeDocs = false)
.defaultMethodSignature()
case _ =>
def fullName(s: Symbol): String =
" " + s.owner.fullNameSyntax
dealiasedValForwarder(sym) match {
case dealiased :: _ =>
fullName(dealiased)
case _ =>
if (
sym.isModuleOrModuleClass || sym.hasPackageFlag || sym.isClass
) {
fullName(sym)
} else {
val short = shortType(info, history)
if (short == NoType) ""
else sym.infoString(short).trim.replace(" <: <?>", "")
}
}
}
def completionsSymbol(name: String): Symbol = {
definitions.ScalaPackage
.newErrorSymbol(TermName(name))
.setInfo(NoType)
}
def detailString(r: Member, history: ShortenedNames): String = {
if (!r.sym.hasPackageFlag) {
// Compute type parameters based on the qualifier.
// Example: Map[Int, String].applyOrE@@
// Before: getOrElse[V1 >: V] (key: K, default: => V1): V1
// After: getOrElse[V1 >: String](key: Int, default: => V1): V1
infoString(r.sym, r.prefix.memberType(r.sym), history)
} else if (r.sym.hasRawInfo) {
infoString(r.sym, r.sym.rawInfo, history)
} else {
"<_>"
}
}
def dealiasedType(sym: Symbol): List[Symbol] = {
if (sym.isAliasType) sym.dealiased :: Nil
else Nil
}
def dealiasedValForwarder(sym: Symbol): List[Symbol] = {
if (sym.isValue && sym.hasRawInfo && !semanticdbSymbol(sym).isLocal) {
sym.rawInfo match {
case SingleType(_, dealias) if dealias.isModule =>
dealias :: dealias.companion :: Nil
case _ =>
Nil
}
} else {
Nil
}
}
/**
* Detects type member select from qualifiers that extend `scala.Dynamic`.
*
* By default, type member completions on classes that extend `scala.Dynamic`
* return no results due to how `Dynamic` desugars trees. This traverser
* detects such cases and run a custom type member completion.
*
* @param pos the position of the completion.
*/
class DynamicFallbackCompletions(pos: Position) extends Traverser {
var result: CompletionResult = CompletionResult.NoResults
def print(): CompletionResult = {
traverse(typedTreeAt(pos))
result
}
override def traverse(tree: Tree): Unit = {
tree match {
case tree @ Apply(
Select(qual, TermName("selectDynamic")),
List(lit @ Literal(Constant(name: String)))
) if lit.pos.isTransparent && lit.pos.end >= tree.pos.end =>
val typeMembers = metalsTypeMembers(tree.fun.pos).collect {
case t: TypeMember => t
}
if (typeMembers.nonEmpty) {
val termName = name.stripSuffix(CURSOR)
result = CompletionResult.TypeMembers(
pos.point - termName.length,
qual,
tree,
typeMembers,
TermName(termName)
)
}
tree.setPos(tree.pos.withEnd(lit.pos.end))
case _ =>
if (tree.pos.includes(pos)) {
super.traverse(tree)
}
}
}
}
// NOTE(olafur): This variable keeps the list of all parent tree nodes
// from the last visited tree node called from `typedTreeAt(pos)`
// or `locateTree(pos)`. It's dirty to store this as a global mutable
// variable but it avoids repeating traversals from the compiler
// implementation of `completionsAt(pos)`.
var lastVisitedParentTrees: List[Tree] = Nil
def findLastVisitedParentTree(pos: Position): Option[Tree] = {
if (lastVisitedParentTrees.isEmpty) {
locateTree(pos)
}
lastVisitedParentTrees.headOption
}
abstract class CompletionPosition {
def isType: Boolean = false
def isNew: Boolean = false
/**
* Returns false if this member should be excluded from completion items.
*/
def isCandidate(member: Member): Boolean = true
/**
* Returns ordering between two candidate completions.
*
* - negative number if o1 member should be sorted before o2
* - positive number if o2 member should be sorted before o1
* - zero 0 if o1 and o2 are equal
*/
def compare(o1: Member, o2: Member): Int = {
-java.lang.Boolean.compare(
isPrioritizedCached(o1),
isPrioritizedCached(o2)
)
}
// Default implementation for `compare` delegates to the `isPrioritized` method
// which groups prioritized members with first and non-prioritized second.
final lazy val cache: mutable.Map[Symbol, Boolean] =
mutable.Map.empty[Symbol, Boolean]
final def isPrioritizedCached(m: Member): Boolean =
cache.getOrElseUpdate(m.sym, isPrioritized(m))
/**
* Returns true if this member should be sorted at the top of completion items.
*/
def isPrioritized(m: Member): Boolean = true
/**
* Returns candidate completion items.
*/
def contribute: List[Member] = Nil
}
def completionPosition(
pos: Position,
source: URI,
text: String,
editRange: l.Range,
completions: CompletionResult,
latestEnclosing: List[Tree]
): CompletionPosition = {
// the implementation of completionPositionUnsafe does a lot of `typedTreeAt(pos).tpe`
// which often causes null pointer exceptions, it's easier to catch the error here than
// enforce discipline in the code.
try
completionPositionUnsafe(
pos,
source,
text,
editRange,
completions,
latestEnclosing
)
catch {
case NonFatal(e) =>
logger.log(Level.SEVERE, e.getMessage(), e)
NoneCompletion
}
}
def completionPositionUnsafe(
pos: Position,
source: URI,
text: String,
editRange: l.Range,
completions: CompletionResult,
latestEnclosingArg: List[Tree]
): CompletionPosition = {
val ScalaCliExtractor = new ScalaCliExtractor(pos)
def fromIdentApply(
ident: Ident,
apply: Apply
): CompletionPosition = {
if (hasLeadingBrace(ident, text)) {
if (isCasePrefix(ident.name)) {
val moveToNewLine = ident.pos.line == apply.pos.line
val addNewLineAfter = apply.pos.focusEnd.line == ident.pos.line
CaseKeywordCompletion(
EmptyTree,
editRange,
pos,
text,
source,
apply,
includeExhaustive =
Some(NewLineOptions(moveToNewLine, addNewLineAfter))
)
} else {
NoneCompletion
}
} else {
if (!isInfix(apply.fun, text)) {
ArgCompletion(ident, apply, pos, text, completions)
} else NoneCompletion
}
}
latestEnclosingArg match {
case MillIvyExtractor(dep) =>
MillIvyCompletion(coursierComplete, pos, text, dep)
case SbtLibExtractor(pos, dep) if pos.source.path.isSbt =>
SbtLibCompletion(coursierComplete, pos, dep)
case ScalaCliExtractor(dep) =>
ScalaCliCompletion(coursierComplete, pos, text, dep)
case _ if isMultilineCommentStart(pos, text) =>
MultilineCommentCompletion(editRange, pos, text)
case _ if isScaladocCompletion(pos, text) =>
val associatedDef = onUnitOf(pos.source) { unit =>
new AssociatedMemberDefFinder(pos).findAssociatedDef(unit.body)
}
associatedDef
.map(definition =>
ScaladocCompletion(editRange, Some(definition), pos, text)
)
.getOrElse(ScaladocCompletion(editRange, None, pos, text))
case (ident: Ident) :: (a: Apply) :: _ =>
fromIdentApply(ident, a)
case (ident: Ident) :: (_: Select) :: (_: Assign) :: (a: Apply) :: _ =>
fromIdentApply(ident, a)
case (lit @ Literal(Constant(_: String))) :: head :: _ =>
InterpolationSplice(pos.point, pos.source.content, text) match {
case Some(i) =>
InterpolatorScopeCompletion(lit, pos, i, text)
case _ =>
isPossibleInterpolatorMember(lit, head, text, pos)
.getOrElse(NoneCompletion)
}
case CaseExtractors.CaseExtractor(selector, parent) =>
CaseKeywordCompletion(
selector,
editRange,
pos,
text,
source,
parent
)
case CaseExtractors.CasePatternExtractor(selector, parent, name) =>
CaseKeywordCompletion(
selector,
editRange,
pos,
text,
source,
parent,
patternOnly = Some(name.stripSuffix("_CURSOR_"))
)
case CaseExtractors.TypedCasePatternExtractor(selector, parent, name) =>
CaseKeywordCompletion(
selector,
editRange,
pos,
text,
source,
parent,
patternOnly = Some(name.stripSuffix("_CURSOR_")),
hasBind = true
)
case (c: DefTree) :: (p: PackageDef) :: _
if c.namePosition.includes(pos) =>
FilenameCompletion(c, p, pos, editRange)
case OverrideExtractor(name, template, start, isCandidate) =>
OverrideCompletion(
name,
template,
pos,
text,
start,
isCandidate
)
case (imp @ Import(select, selector)) :: _
if isAmmoniteFileCompletionPosition(imp, pos) =>
AmmoniteFileCompletion(select, selector, pos, editRange)
case (imp @ Import(select, selector)) :: _
if isAmmoniteIvyCompletionPosition(
imp,
pos
) || isWorksheetIvyCompletionPosition(imp, pos) =>
AmmoniteIvyCompletion(
coursierComplete,
select,
selector,
pos,
editRange,
text
)
case _ =>
inferCompletionPosition(
pos,
source,
text,
latestEnclosingArg,
completions,
editRange
)
}
}
private def isAmmoniteCompletionPosition(
magicImport: String,
tree: Tree,
pos: Position
): Boolean = {
tree match {
case Import(select, _) =>
pos.source.file.name.isAmmoniteGeneratedFile && select
.toString()
.startsWith(magicImport)
case _ => false
}
}
def isAmmoniteFileCompletionPosition(tree: Tree, pos: Position): Boolean =
isAmmoniteCompletionPosition("$file", tree, pos)
def isAmmoniteIvyCompletionPosition(tree: Tree, pos: Position): Boolean =
isAmmoniteCompletionPosition("$ivy", tree, pos)
def isWorksheetIvyCompletionPosition(tree: Tree, pos: Position): Boolean =
tree match {
case Import(select, _) =>
pos.source.file.name.isWorksheet &&
(select.toString().startsWith("<$ivy: error>") ||
select.toString().startsWith("<$dep: error>"))
case _ => false
}
private def inferCompletionPosition(
pos: Position,
source: URI,
text: String,
enclosing: List[Tree],
completions: CompletionResult,
editRange: l.Range
): CompletionPosition = {
object ExhaustiveMatch {
def unapply(sel: Select): Option[CompletionPosition] = {
if (!isMatchPrefix(sel.name)) None
else if (
sel.pos.point < 1 ||
text.charAt(sel.pos.point - 1) != ' '
) None
else {
completions match {
case t: CompletionResult.TypeMembers =>
t.results.collectFirst {
case result if result.prefix.isDefined =>
MatchKeywordCompletion(
result.prefix,
editRange,
pos,
source,
text
)
}
case _ =>
None
}
}
}
}
enclosing match {
case ExhaustiveMatch(pos) :: _ =>
pos
case (_: Ident | _: Select) :: tail =>
tail match {
case (v: ValOrDefDef) :: _ =>
if (v.tpt.pos.includes(pos)) {
TypeCompletion
} else {
NoneCompletion
}
case _ =>
inferCompletionPosition(
pos,
source,
text,
tail,
completions,
editRange
)
}
case AppliedTypeTree(_, args) :: _ =>
if (args.exists(_.pos.includes(pos))) {
TypeCompletion
} else {
NoneCompletion
}
case New(_) :: _ =>
NewCompletion
case head :: tail if !head.pos.includes(pos) =>
inferCompletionPosition(pos, source, text, tail, completions, editRange)
case _ =>
NoneCompletion
}
}
class MetalsLocator(pos: Position, acceptTransparent: Boolean = false)
extends Traverser {
def locateIn(root: Tree): Tree = {
lastVisitedParentTrees = Nil
traverse(root)
lastVisitedParentTrees match {
case head :: _ => head
case _ => EmptyTree
}
}
private def addToPath(path: List[Tree], t: Tree): List[Tree] = {
def goesAfter(prev: Tree): Boolean =
// in most cases prev tree should include next one
// however it doesn't work for some synthetic trees
// in this case check if both tree have different position ranges
prev.pos.includes(t.pos) || !t.pos.includes(prev.pos)
path match {
case Nil => List(t)
case head :: tl if goesAfter(head) => t :: head :: tl
case head :: tl => head :: addToPath(tl, t)
}
}
protected def isEligible(t: Tree): Boolean = {
!t.pos.isTransparent || acceptTransparent || {
t match {
// new User(age = 42, name = "") becomes transparent, which doesn't happen with normal methods
case Apply(Select(_: New, _), _) => true
// for named args apply becomes transparent but fun doesn't
case Apply(fun, args) =>
!fun.pos.isTransparent && args.forall(_.pos.isOffset)
// for synthetic val definition select on it becomes transparent
case sel @ Select(qual: Ident, _) =>
val qualifierIsSyntheticVal =
Option(qual.symbol).exists(sym => sym.isValue && sym.isSynthetic)
qualifierIsSyntheticVal &&
!sel.namePosition.isTransparent && sel.namePosition.encloses(pos)
case _ => false
}
}
}
override def traverse(t: Tree): Unit = {
t match {
case tt: TypeTree
if tt.original != null && (tt.pos includes tt.original.pos) =>
traverse(tt.original)
case _ =>
if (t.pos.includes(pos)) {
if (isEligible(t)) {
lastVisitedParentTrees = addToPath(lastVisitedParentTrees, t)
}
super.traverse(t)
} else {
t match {
// workaround for Scala 2.13,
// where position is not set properly for synthetic val definition
// we are interested only in its children, which have correct positions set
case v: ValDef if v.pos.isOffset && v.symbol.isSynthetic =>
super.traverse(v)
case mdef: MemberDef =>
val annTrees = mdef.mods.annotations match {
case Nil if mdef.symbol != null =>
// After typechecking, annotations are moved from the modifiers
// to the annotation on the symbol of the annotatee.
mdef.symbol.annotations.map(_.original)
case anns => anns
}
traverseTrees(annTrees)
case _ =>
}
}
}
}
}
lazy val isNotOverridableName: Set[Name] =
Iterator(
definitions.syntheticCoreMethods.iterator.map(_.name),
Iterator(
termNames.notify_,
termNames.notifyAll_,
termNames.wait_,
termNames.MIXIN_CONSTRUCTOR,
termNames.CONSTRUCTOR
)
).flatten.toSet -- Set[Name](
termNames.hashCode_,
termNames.toString_,
termNames.equals_
)
lazy val isUninterestingSymbolOwner: Set[Symbol] = Set[Symbol](
// The extension methods in these classes are noisy because they appear on every completion.
definitions.getMemberClass(
definitions.PredefModule,
TypeName("ArrowAssoc")
),
definitions.getMemberClass(
definitions.PredefModule,
TypeName("Ensuring")
)
)
lazy val isUninterestingSymbol: Set[Symbol] = Set[Symbol](
definitions.Any_==,
definitions.Any_!=,
definitions.Any_##,
definitions.Object_==,
definitions.Object_!=,
definitions.Object_##,
definitions.Object_eq,
definitions.Object_ne,
definitions.RepeatedParamClass,
definitions.ByNameParamClass,
definitions.JavaRepeatedParamClass,
definitions.Object_notify,
definitions.Object_notifyAll,
definitions.Object_notify,
definitions.getMemberMethod(definitions.ObjectClass, termNames.wait_),
// NOTE(olafur) IntelliJ does not complete the root package and without this filter
// then `_root_` would appear as a completion result in the code `foobar(_<COMPLETE>)`
rootMirror.RootPackage,
// NOTE(gabro) valueOf was added as a Predef member in 2.13. We filter it out since is a niche
// use case and it would appear upon typing 'val'
definitions.getMemberIfDefined(
definitions.PredefModule,
TermName("valueOf")
)
).flatMap(_.alternatives)
lazy val renameConfig: collection.Map[Symbol, Name] =
metalsConfig
.symbolPrefixes()
.asScala
.map { case (sym, name) =>
val nme =
if (name.endsWith("#")) TypeName(name.stripSuffix("#"))
else if (name.endsWith(".")) TermName(name.stripSuffix("."))
else TermName(name)
inverseSemanticdbSymbol(sym) -> nme
}
.filterKeys(_ != NoSymbol)
.toMap
// Infers the indentation at the completion position by counting the number of leading
// spaces in the line.
// For example:
// class Main {
// def foo<COMPLETE> // inferred indent is 2 spaces.
// }
def inferIndent(lineStart: Int, text: String): (Int, Boolean) = {
var i = 0
var tabIndented = false
while (
lineStart + i < text.length && {
val char = text.charAt(lineStart + i)
if (char == '\t') {
tabIndented = true
true
} else
char == ' '
}
) {
i += 1
}
(i, tabIndented)
}
// Returns the symbols that have been renamed in this scope.
// For example:
// import java.lang.{Boolean => JBoolean}
// class Main {
// // renamedSymbols: Map(j.l.Boolean => JBoolean)
// }
def renamedSymbols(context: Context): collection.Map[Symbol, Name] = {
val result = mutable.Map.empty[Symbol, Name]
context.imports.foreach { imp =>
lazy val pre = imp.qual.tpe
imp.tree.selectors.foreach { sel =>
if (sel.rename != null) {
val member = pre.member(sel.name)
if (member != NoSymbol)
result(member) = sel.rename
member.companion match {
case NoSymbol =>
case companion =>
if (companion != NoSymbol)
result(companion) = sel.rename
}
}
}
}
result
}
def inferStart(
pos: Position,
text: String,
charPred: Char => Boolean
): Int = {
def fallback: Int = {
var i = pos.point - 1
while (i >= 0 && charPred(text.charAt(i))) {
i -= 1
}
i + 1
}
def loop(enclosing: List[Tree]): Int =
enclosing match {
case Nil => fallback
case head :: tl =>
if (!treePos(head).includes(pos)) loop(tl)
else {
head match {
case i: Ident =>
treePos(i).point
case Select(qual, _) if !treePos(qual).includes(pos) =>
treePos(head).point
case _ => fallback
}
}
}
loop(lastVisitedParentTrees)
}
/** Can character form part of an alphanumeric Scala identifier? */
private def isIdentifierPart(c: Char) =
(c == '$') || Character.isUnicodeIdentifierPart(c)
/**
* Returns the start offset of the identifier starting as the given offset position.
*/
def inferIdentStart(pos: Position, text: String): Int =
inferStart(pos, text, isIdentifierPart)
/**
* Returns the end offset of the identifier starting as the given offset position.
*/
def inferIdentEnd(pos: Position, text: String): Int = {
var i = pos.point
while (i < text.length && Chars.isIdentifierPart(text.charAt(i))) {
i += 1
}
i
}
def isSnippetEnabled(pos: Position, text: String): Boolean = {
pos.point < text.length() && {
text.charAt(pos.point) match {
case ')' | ']' | '}' | ',' | '\n' => true
case _ =>
!text.startsWith(" _", pos.point) && {
text.startsWith("\r\n", pos.point)
}
}
}
}
}