/
InterpolatorCompletions.scala
316 lines (296 loc) Β· 10 KB
/
InterpolatorCompletions.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
package scala.meta.internal.pc.completions
import scala.collection.mutable.ListBuffer
import scala.meta.internal.metals.ReportContext
import scala.meta.internal.mtags.MtagsEnrichments.*
import scala.meta.internal.pc.CompilerSearchVisitor
import scala.meta.internal.pc.CompletionFuzzy
import scala.meta.internal.pc.IndexedContext
import scala.meta.internal.pc.InterpolationSplice
import scala.meta.pc.PresentationCompilerConfig
import scala.meta.pc.SymbolSearch
import dotty.tools.dotc.ast.tpd.*
import dotty.tools.dotc.core.Contexts.Context
import dotty.tools.dotc.core.Flags
import dotty.tools.dotc.core.Flags.*
import dotty.tools.dotc.core.Symbols.Symbol
import dotty.tools.dotc.core.Types.Type
import dotty.tools.dotc.util.SourcePosition
import org.eclipse.lsp4j as l
object InterpolatorCompletions:
def contribute(
text: String,
pos: SourcePosition,
completionPos: CompletionPos,
indexedContext: IndexedContext,
lit: Literal,
path: List[Tree],
completions: Completions,
snippetsEnabled: Boolean,
search: SymbolSearch,
config: PresentationCompilerConfig,
buildTargetIdentifier: String,
)(using Context, ReportContext) =
InterpolationSplice(pos.span.point, text.toCharArray(), text) match
case Some(interpolator) =>
InterpolatorCompletions.contributeScope(
text,
lit,
pos,
interpolator,
indexedContext,
completions,
snippetsEnabled,
hasStringInterpolator =
path.drop(1).headOption.exists(_.isInstanceOf[SeqLiteral]),
search,
buildTargetIdentifier,
)
case None =>
InterpolatorCompletions.contributeMember(
lit,
path,
text,
pos,
completionPos,
completions,
snippetsEnabled,
search,
buildTargetIdentifier,
)
end match
end contribute
/**
* Find the identifier that corresponds to the previous interpolation splice.
* For string `s" $Main.metho@@ "` we want to get `Main` identifier.
* The difference with Scala 2 is that we search for it through the path using
* the created partial function.
*/
private def interpolatorMemberArg(
lit: Literal,
parent: Tree,
): PartialFunction[Tree, Option[Ident | Select]] =
case tree @ Apply(
_,
List(Typed(expr: SeqLiteral, _)),
) if expr.elems.exists {
case _: Ident => true
case _: Select => true
case _ => false
} =>
parent match
case SeqLiteral(elems, _) if elems.size > 0 =>
expr.elems.zip(elems.tail).collectFirst {
case (i: (Ident | Select), literal) if literal == lit =>
i
}
case _ => None
end interpolatorMemberArg
/**
* A completion to select type members inside string interpolators.
*
* Example: {{{
* // before
* s"Hello $name.len@@!"
* // after
* s"Hello ${name.length()$0}"
* }}}
*/
private def contributeMember(
lit: Literal,
path: List[Tree],
text: String,
cursor: SourcePosition,
completionPos: CompletionPos,
completions: Completions,
areSnippetsSupported: Boolean,
search: SymbolSearch,
buildTargetIdentifier: String,
)(using Context, ReportContext): List[CompletionValue] =
def newText(
name: String,
suffix: Option[String],
identOrSelect: Ident | Select,
): String =
val snippetCursor = suffixEnding(suffix, areSnippetsSupported)
new StringBuilder()
.append('{')
.append(
text.substring(identOrSelect.span.start, identOrSelect.span.end)
)
.append('.')
.append(name.backticked)
.append(snippetCursor)
.append('}')
.toString
end newText
def extensionMethods(qualType: Type) =
val buffer = ListBuffer.empty[Symbol]
val visitor = new CompilerSearchVisitor(sym =>
if sym.is(ExtensionMethod) &&
qualType.widenDealias <:< sym.extensionParam.info.widenDealias
then
buffer.append(sym)
true
else false,
)
search.searchMethods(completionPos.query, buildTargetIdentifier, visitor)
buffer.toList
end extensionMethods
def completionValues(
syms: Seq[Symbol],
isExtension: Boolean,
identOrSelect: Ident | Select,
): Seq[CompletionValue] =
syms.collect {
case sym
if CompletionFuzzy.matches(
completionPos.query,
sym.name.toString(),
) =>
val label = sym.name.decoded
completions.completionsWithSuffix(
sym,
label,
(name, s, suffix) =>
CompletionValue.Interpolator(
s,
label,
Some(newText(name, suffix.toEditOpt, identOrSelect)),
Nil,
Some(cursor.withStart(identOrSelect.span.start).toLsp),
// Needed for VS Code which will not show the completion otherwise
Some(identOrSelect.name.toString() + "." + label),
s,
isExtension = isExtension,
),
)
}.flatten
val qualType = for
parent <- path.drop(1).headOption.toList
if lit.span.exists && text.charAt(lit.span.point - 1) != '}'
identOrSelect <- path
.collectFirst(interpolatorMemberArg(lit, parent))
.flatten
yield identOrSelect
qualType.flatMap(identOrSelect =>
val tp = identOrSelect.symbol.info
val members = tp.allMembers.map(_.symbol)
val extensionSyms = extensionMethods(tp)
completionValues(members, isExtension = false, identOrSelect) ++
completionValues(extensionSyms, isExtension = true, identOrSelect)
)
end contributeMember
private def suffixEnding(
suffix: Option[String],
areSnippetsSupported: Boolean,
): String =
suffix match
case Some(suffix) if areSnippetsSupported && suffix == "()" =>
suffix + "$0"
case Some(suffix) => suffix
case None if areSnippetsSupported => "$0"
case _ => ""
/**
* contributeScope provides completions to convert a string literal into splice,
* example `"Hello $na@@"`.
*
* When converting a string literal into an interpolator we need to ensure a few cases:
*
* - escape existing `$` characters into `$$`, which are printed as `\$\$` in order to
* escape the TextMate snippet syntax.
* - wrap completed name in curly braces `s"Hello ${name}_` when the trailing character
* can be treated as an identifier part.
* - insert the leading `s` interpolator.
* - place the cursor at the end of the completed name using TextMate `$0` snippet syntax.
*/
private def contributeScope(
text: String,
lit: Literal,
position: SourcePosition,
interpolator: InterpolationSplice,
indexedContext: IndexedContext,
completions: Completions,
areSnippetsSupported: Boolean,
hasStringInterpolator: Boolean,
search: SymbolSearch,
buildTargetIdentifier: String,
)(using ctx: Context, reportsContext: ReportContext): List[CompletionValue] =
val litStartPos = lit.span.start
val litEndPos = lit.span.end - Cursor.value.length()
val span = position.span
val nameStart =
span.withStart(span.start - interpolator.name.size)
val nameRange = position.withSpan(nameStart).toLsp
val hasClosingBrace: Boolean = text.charAt(span.point) == '}'
val hasOpeningBrace: Boolean = text.charAt(
span.start - interpolator.name.size - 1
) == '{'
def additionalEdits(): List[l.TextEdit] =
val interpolatorEdit =
if !hasStringInterpolator then
val range = lit.sourcePos.withEnd(litStartPos).toLsp
List(new l.TextEdit(range, "s"))
else Nil
val dollarEdits = for
i <- litStartPos to litEndPos
if !hasStringInterpolator &&
text.charAt(i) == '$' && i != interpolator.dollar
yield new l.TextEdit(lit.sourcePos.focusAt(i).toLsp, "$")
interpolatorEdit ++ dollarEdits
end additionalEdits
def newText(symbolName: String, suffix: Option[String]): String =
val out = new StringBuilder()
val identifier = symbolName.backticked
val symbolNeedsBraces =
interpolator.needsBraces ||
identifier.startsWith("`") ||
suffix.isDefined
if symbolNeedsBraces && !hasOpeningBrace then out.append('{')
out.append(identifier)
out.append(suffixEnding(suffix, areSnippetsSupported))
if symbolNeedsBraces && !hasClosingBrace then out.append('}')
out.toString
end newText
val workspaceSymbols = ListBuffer.empty[Symbol]
val visitor = new CompilerSearchVisitor(sym =>
indexedContext.lookupSym(sym) match
case IndexedContext.Result.InScope => false
case _ =>
if sym.is(Flags.Module) then workspaceSymbols += sym
true,
)
if interpolator.name.nonEmpty then
search.search(interpolator.name, buildTargetIdentifier, visitor)
def collectCompletions(
isWorkspace: Boolean
): PartialFunction[Symbol, List[CompletionValue]] =
case sym
if CompletionFuzzy.matches(
interpolator.name,
sym.name.decoded,
) && !sym.isType =>
val label = sym.name.decoded
completions.completionsWithSuffix(
sym,
label,
(name, s, suffix) =>
CompletionValue.Interpolator(
s,
label,
Some(newText(name, suffix.toEditOpt)),
additionalEdits(),
Some(nameRange),
None,
sym,
isWorkspace,
),
)
end collectCompletions
val fromWorkspace =
workspaceSymbols.toList.collect(collectCompletions(isWorkspace = true))
val fromLocal = indexedContext.scopeSymbols.collect(
collectCompletions(isWorkspace = false)
)
(fromLocal ++ fromWorkspace).flatten
end contributeScope
end InterpolatorCompletions