/
OverrideCompletions.scala
596 lines (550 loc) Β· 18.8 KB
/
OverrideCompletions.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
package scala.meta.internal.pc
package completions
import java.util as ju
import scala.collection.JavaConverters.*
import scala.meta.internal.metals.ReportContext
import scala.meta.internal.mtags.MtagsEnrichments.*
import scala.meta.internal.pc.AutoImports.AutoImport
import scala.meta.internal.pc.AutoImports.AutoImportsGenerator
import scala.meta.internal.pc.printer.MetalsPrinter
import scala.meta.pc.OffsetParams
import scala.meta.pc.PresentationCompilerConfig
import scala.meta.pc.PresentationCompilerConfig.OverrideDefFormat
import scala.meta.pc.SymbolSearch
import dotty.tools.dotc.ast.tpd.*
import dotty.tools.dotc.ast.tpd.Tree
import dotty.tools.dotc.core.Contexts.Context
import dotty.tools.dotc.core.Flags
import dotty.tools.dotc.core.Flags.*
import dotty.tools.dotc.core.NameKinds.DefaultGetterName
import dotty.tools.dotc.core.Names.Name
import dotty.tools.dotc.core.StdNames
import dotty.tools.dotc.core.SymDenotations.SymDenotation
import dotty.tools.dotc.core.Symbols.Symbol
import dotty.tools.dotc.core.Types.Type
import dotty.tools.dotc.interactive.Interactive
import dotty.tools.dotc.interactive.InteractiveDriver
import dotty.tools.dotc.util.SourceFile
import dotty.tools.dotc.util.SourcePosition
import org.eclipse.lsp4j as l
object OverrideCompletions:
private type TargetDef = TypeDef | DefDef
private def defaultIndent(tabIndent: Boolean) =
if tabIndent then 1 else 2
/**
* @param td A surrounded type definition being complete
* @param filterName A prefix string for filtering, if None no filter
* @param start The starting point of the completion. For example, starting point is `*`
* `*override def f|` (where `|` represents the cursor position).
*/
def contribute(
td: TypeDef,
completing: Option[Symbol],
start: Int,
indexedContext: IndexedContext,
search: SymbolSearch,
config: PresentationCompilerConfig,
autoImportsGen: AutoImportsGenerator,
fallbackName: Option[String],
)(using ReportContext): List[CompletionValue] =
import indexedContext.ctx
val clazz = td.symbol.asClass
val syntheticCoreMethods: Set[Name] =
indexedContext.ctx.definitions.syntheticCoreMethods.map(_.name).toSet
val isDecl = td.typeOpt.decls.toList.toSet
/** Is the given symbol that we're trying to complete? */
def isSelf(sym: Symbol) = completing.fold(false)(self => self == sym)
def isOverrideable(sym: Symbol)(using Context): Boolean =
val overridingSymbol = sym.overridingSymbol(clazz)
!sym.is(Synthetic) &&
!sym.is(Artifact) &&
// not overridden in in this class, except overridden by the symbol that we're completing
(!isDecl(overridingSymbol) || isSelf(overridingSymbol)) &&
!(sym.is(Mutable) && !sym.is(
Deferred
)) && // concrete var can't be override
(!syntheticCoreMethods(sym.name) || allowedList(sym.name)) &&
!sym.is(Final) &&
!sym.isConstructor &&
!sym.isSetter &&
// exclude symbols desugared by default args
!sym.name.is(DefaultGetterName)
end isOverrideable
// Given the base class `trait Foo { def foo: Int; val bar: Int; var baz: Int }`
// and typing `def @@` in the subclass of `Foo`,
// suggest `def foo` and exclude `val bar`, and `var baz` from suggestion
// because they are not method definitions (not starting from `def`).
val flags = completing.map(_.flags & interestingFlags).getOrElse(EmptyFlags)
val name =
completing
.fold(fallbackName)(sym => Some(sym.name.show))
.map(_.replace(Cursor.value, ""))
.filter(!_.isEmpty())
// not using `td.tpe.abstractTermMembers` because those members includes
// the abstract members in `td.tpe`. For example, when we type `def foo@@`,
// `td.tpe.abstractTermMembers` contains `method foo: <error>` and it overrides the parent `foo` method.
val overridables = td.tpe.parents
.flatMap { parent =>
parent.membersBasedOnFlags(
flags,
Flags.Private,
)
}
.distinct
.collect {
case denot
if name
.fold(true)(name => denot.name.startsWith(name)) &&
!denot.symbol.isType =>
denot.symbol
}
.filter(isOverrideable)
overridables
.map(sym =>
toCompletionValue(
sym.denot,
start,
td,
indexedContext,
search,
shouldMoveCursor = true,
config,
autoImportsGen,
indexedContext.ctx.compilationUnit.source.content
.startsWith("o", start),
)
)
.toList
end contribute
def implementAllAt(
params: OffsetParams,
driver: InteractiveDriver,
search: SymbolSearch,
config: PresentationCompilerConfig,
)(using ReportContext): ju.List[l.TextEdit] =
object FindTypeDef:
def unapply(path: List[Tree])(using Context): Option[TypeDef] = path match
// class <<Foo>> extends ... {}
case (td: TypeDef) :: _ => Some(td)
// new Iterable[Int] {}
case (_: Ident) :: _ :: (_: Template) :: (td: TypeDef) :: _ =>
Some(td)
// given Foo with {}
case (_: Ident) :: (_: Template) :: (td: TypeDef) :: _ =>
Some(td)
// <<new>> Foo {}
case (_: Template) :: (td: TypeDef) :: _ =>
Some(td)
// abstract class Mutable { ... }
// new <<Mutable>> { }
case (_: Ident) :: (_: New) :: (_: Select) :: (_: Apply) :: (_: Template) :: (td: TypeDef) :: _ =>
Some(td)
// trait Base[T]:
// extension (x: T)
// ...
// class <<Concrete>>[T] extends Base[Int]
case (dd: DefDef) :: (_: Template) :: (td: TypeDef) :: _
if dd.symbol.isConstructor =>
Some(td)
// case class <<Foo>>(a: Int) extends ...
// if there is no companion object Foo, td would be Foo$
// we have to look for defininion of Foo class
case (dd: DefDef) :: (t: Template) :: (td: TypeDef) :: parent :: _
if dd.symbol.decodedName == "apply" =>
fallbackFromParent(
parent: Tree,
dd.symbol.owner.decodedName,
)
case _ => None
end FindTypeDef
val uri = params.uri
driver.run(
uri,
SourceFile.virtual(uri.toASCIIString, params.text),
)
val unit = driver.currentCtx.run.units.head
val pos = driver.sourcePosition(params)
val newctx = driver.currentCtx.fresh.setCompilationUnit(unit)
val tpdTree = newctx.compilationUnit.tpdTree
val path =
Interactive.pathTo(tpdTree, pos.span)(using newctx) match
case path @ TypeDef(_, template) :: _ =>
template :: path
case path => path
val indexedContext = IndexedContext(
Interactive.contextOfPath(path)(using newctx)
)
import indexedContext.ctx
lazy val autoImportsGen = AutoImports.generator(
pos,
params.text,
unit.tpdTree,
indexedContext,
config,
)
lazy val implementAll = implementAllFor(
indexedContext,
params.text,
search,
autoImportsGen,
config,
)
path match
// given <<Foo>>
case (_: Ident) :: (dd: DefDef) :: _ =>
implementAll(dd).asJava
case FindTypeDef(td) =>
implementAll(td).asJava
case _ =>
new ju.ArrayList[l.TextEdit]()
end implementAllAt
private def implementAllFor(
indexedContext: IndexedContext,
text: String,
search: SymbolSearch,
autoImports: AutoImportsGenerator,
config: PresentationCompilerConfig,
)(
defn: TargetDef
)(using Context, ReportContext): List[l.TextEdit] =
def calcIndent(
defn: TargetDef,
decls: List[Symbol],
source: SourceFile,
text: String,
shouldCompleteBraces: Boolean,
)(using Context): (String, String, String) =
// For `FooImpl` in the below, the necessaryIndent will be 2
// because there're 2 spaces before `class FooImpl`.
// ```scala
// |object X:
// | class FooImpl extends Foo {
// | }
// ```
val (necessaryIndent, tabIndented) = CompletionPos.inferIndent(
source.lineToOffset(defn.sourcePos.line),
text,
)
// infer indent for implementations
// If there's declaration in the class/object, follow its indent.
// For example, numIndent will be 8, because there're 8 spaces before
// `override def foo: Int`
// ```scala
// |object X:
// | class FooImpl extends Foo {
// | override def foo: Int = 1
// | }
// ```
val (numIndent, shouldTabIndent) =
decls.headOption
.map { decl =>
CompletionPos.inferIndent(
source.lineToOffset(decl.sourcePos.line),
text,
)
}
.getOrElse({
val default = defaultIndent(tabIndented)
(necessaryIndent + default, tabIndented)
})
val indentChar = if shouldTabIndent then "\t" else " "
val indent = indentChar * numIndent
val lastIndent =
if (defn.sourcePos.startLine == defn.sourcePos.endLine) ||
shouldCompleteBraces
then "\n" + indentChar * necessaryIndent
else ""
(indent, indent, lastIndent)
end calcIndent
val abstractMembers = defn.tpe.abstractTermMembers.map(_.symbol)
val caseClassOwners = Set("Product", "Equals")
val overridables =
if defn.symbol.is(Flags.CaseClass) then
abstractMembers.filter(sym =>
sym.sourcePos.exists || !caseClassOwners(sym.owner.decodedName)
)
else abstractMembers
val completionValues = overridables
.map(sym =>
toCompletionValue(
sym.denot,
0, // we don't care the position of each completion value from ImplementAll
defn,
indexedContext,
search,
shouldMoveCursor = false,
config,
autoImports,
shouldAddOverrideKwd = true,
)
)
.toList
val (edits, imports) = toEdits(completionValues)
if edits.isEmpty then Nil
else
// A list of declarations in the class/object to implement
val decls = defn.tpe.decls.toList
.filter(sym =>
!sym.isPrimaryConstructor &&
!sym.isTypeParam &&
!sym.is(ParamAccessor) && // `num` of `class Foo(num: int)`
sym.span.exists &&
!(sym.span.isZeroExtent && defn.symbol.is(Flags.CaseClass)) &&
defn.sourcePos.contains(sym.sourcePos)
)
.sortBy(_.sourcePos.start)
val source = indexedContext.ctx.source
val shouldCompleteBraces =
decls.isEmpty && hasBracesOrColon(text, defn).isEmpty
val (startIndent, indent, lastIndent) =
calcIndent(defn, decls, source, text, shouldCompleteBraces)
// If there're declarations in the class/object to implement e.g.
// ```scala
// class FooImpl extends Foo:
// override def foo(...) = ...
// ```
// The edit position will be the beginning line of `override def foo`
// Otherwise, infer the position by `inferEditPosiiton`
val posFromDecls =
decls.headOption.map(decl =>
val pos = source.lineToOffset(decl.sourcePos.line)
val span = decl.sourcePos.span.withStart(pos).withEnd(pos)
defn.sourcePos.withSpan(span)
)
val editPos = posFromDecls.getOrElse(inferEditPosition(text, defn))
lazy val shouldCompleteWith = defn match
case dd: DefDef =>
dd.symbol.is(Given)
case _ => false
val (start, last) =
val (startNL, lastNL) =
if posFromDecls.nonEmpty then ("\n", "\n\n") else ("\n\n", "\n")
if shouldCompleteWith then
(s" with$startNL$indent", s"$lastNL$lastIndent")
else if shouldCompleteBraces then
(s" {$startNL$indent", s"$lastNL$lastIndent}")
else (s"$startNL$indent", s"$lastNL$lastIndent")
val newEdit =
edits.mkString(start, s"\n\n$indent", last)
val implementAll = new l.TextEdit(
editPos.toLsp,
newEdit,
)
implementAll +: imports.toList
end if
end implementAllFor
private def toEdits(
completions: List[CompletionValue.Override]
): (List[String], Set[l.TextEdit]) =
completions.foldLeft(
(List.empty[String], Set.empty[l.TextEdit])
) { (editsAndImports, completion) =>
val edit =
completion.value
val edits = editsAndImports._1 :+ edit
val imports = completion.additionalEdits.toSet ++ editsAndImports._2
(edits, imports)
}
end toEdits
private lazy val allowedList: Set[Name] =
Set[Name](
StdNames.nme.hashCode_,
StdNames.nme.toString_,
StdNames.nme.equals_,
)
private def toCompletionValue(
sym: SymDenotation,
start: Int,
defn: TargetDef,
indexedContext: IndexedContext,
search: SymbolSearch,
shouldMoveCursor: Boolean,
config: PresentationCompilerConfig,
autoImportsGen: AutoImportsGenerator,
shouldAddOverrideKwd: Boolean,
)(using Context, ReportContext): CompletionValue.Override =
val renames = AutoImport.renameConfigMap(config)
val printer = MetalsPrinter.standard(
indexedContext,
search,
includeDefaultParam = MetalsPrinter.IncludeDefaultParam.Never,
renames,
)
val overrideKeyword: String =
// if the overriding method is not an abstract member, add `override` keyword
if !sym.isOneOf(Deferred) || shouldAddOverrideKwd
then "override"
else ""
val overrideDefLabel: String = config.overrideDefFormat() match
case OverrideDefFormat.Unicode =>
if sym.is(Deferred) then "πΌ "
else "β« "
case _ => ""
val signature =
// `iterator` method in `new Iterable[Int] { def iterato@@ }`
// should be completed as `def iterator: Iterator[Int]` instead of `Iterator[A]`.
val seenFrom =
val memInfo = defn.tpe.memberInfo(sym.symbol)
if memInfo.isErroneous || memInfo.finalResultType.isAny then
sym.info.widenTermRefExpr
else memInfo
if sym.is(Method) then
printer.defaultMethodSignature(
sym.symbol,
seenFrom,
additionalMods =
if overrideKeyword.nonEmpty then List(overrideKeyword) else Nil,
)
else
printer.defaultValueSignature(
sym.symbol,
seenFrom,
additionalMods =
if overrideKeyword.nonEmpty then List(overrideKeyword) else Nil,
)
end if
end signature
val label = s"$overrideDefLabel$signature"
val stub =
if config.isCompletionSnippetsEnabled && shouldMoveCursor then "${0:???}"
else "???"
val value = s"$signature = $stub"
val additionalEdits =
printer.shortenedNames
.sortBy(nme => nme.name)
.flatMap(name => autoImportsGen.forShortName(name))
.flatten
CompletionValue.Override(
label,
value,
sym.symbol,
additionalEdits,
Some(signature),
Some(autoImportsGen.pos.withStart(start).toLsp),
)
end toCompletionValue
private val interestingFlags = Flags.Method | Flags.Mutable
/**
* Infer the editPosition for "implement all" code action for the given TypeDef.
*
* If there're braces like `class FooImpl extends Foo {}`,
* editPosition will be inside the braces.
* Otherwise, e.g. `class FooImpl extends Foo`, editPosition will be
* after the `extends Foo`.
*
* @param text the whole text of the source file
* @param td the class/object to impement all
*/
private def inferEditPosition(text: String, defn: TargetDef)(using
Context
): SourcePosition =
val span = hasBracesOrColon(text, defn)
.map { offset =>
defn.sourcePos.span.withStart(offset + 1).withEnd(offset + 1)
}
.getOrElse({
defn.sourcePos.span.withStart(defn.span.end)
})
defn.sourcePos.withSpan(span)
end inferEditPosition
private def hasBracesOrColon(text: String, defn: TargetDef)(using
Context
): Option[Int] =
def hasSelfTypeAnnot = defn match
case td: TypeDef =>
td.rhs match
case t: Template =>
t.self.span.isSourceDerived
case _ => false
case _ => false
val start = defn.span.start
val braceOffset =
if hasSelfTypeAnnot then text.indexOf("=>", start) + 1
else text.indexOf("{", start)
if braceOffset > 0 && braceOffset < defn.span.end then Some(braceOffset)
else hasColon(text, defn)
end hasBracesOrColon
private def hasColon(text: String, defn: TargetDef)(using
Context
): Option[Int] =
defn match
case td: TypeDef if text.charAt(td.rhs.span.end) == ':' =>
Some(td.rhs.span.end)
case _ => None
private def fallbackFromParent(parent: Tree, name: String)(using Context) =
val stats = parent match
case t: Template => Some(t.body)
case pkg: PackageDef => Some(pkg.stats)
case b: Block => Some(b.stats)
case _ => None
stats.flatMap(_.collectFirst {
case td: TypeDef if td.symbol.decodedName == name => td
})
object OverrideExtractor:
def unapply(path: List[Tree])(using Context) =
path match
// class FooImpl extends Foo:
// def x|
case (dd: (DefDef | ValDef)) :: (t: Template) :: (td: TypeDef) :: _
if t.parents.nonEmpty =>
val completing =
if dd.symbol.name == StdNames.nme.ERROR then None
else Some(dd.symbol)
Some(
(
td,
completing,
dd.sourcePos.start,
true,
None,
)
)
// class FooImpl extends Foo:
// ov|
case (ident: Ident) :: (t: Template) :: (td: TypeDef) :: _
if t.parents.nonEmpty && "override".startsWith(
ident.name.show.replace(Cursor.value, "")
) =>
Some(
(
td,
None,
ident.sourcePos.start,
false,
None,
)
)
// class Main extends Val:
// def@@
case (id: Ident) :: (t: Template) :: (td: TypeDef) :: _
if t.parents.nonEmpty && "def".startsWith(
id.name.decoded.replace(
Cursor.value,
"",
)
) =>
Some(
(
td,
None,
id.sourcePos.start,
true,
None,
)
)
// class Main extends Val:
// he@@
case (id: Ident) :: (t: Template) :: (td: TypeDef) :: _
if t.parents.nonEmpty =>
Some(
(
td,
None,
id.sourcePos.start,
false,
Some(id.name.show),
)
)
case _ => None
end OverrideExtractor
end OverrideCompletions