-
Notifications
You must be signed in to change notification settings - Fork 380
/
RsKeywordCompletionContributor.kt
291 lines (244 loc) · 13.2 KB
/
RsKeywordCompletionContributor.kt
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
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.Key
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.PsiElementPattern
import com.intellij.patterns.StandardPatterns.or
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.util.ProcessingContext
import org.rust.lang.core.*
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.core.psi.ext.*
import org.rust.lang.core.resolve.ImplLookup
import org.rust.lang.core.types.TraitRef
import org.rust.lang.core.types.ty.Ty
import org.rust.lang.core.types.ty.TyUnknown
import org.rust.lang.core.types.type
/**
* Completes Rust keywords
*
* TODO: checkout org.jetbrains.kotlin.idea.completion.KeywordCompletion, it has some super cool ideas
*/
class RsKeywordCompletionContributor : CompletionContributor(), DumbAware {
init {
extend(CompletionType.BASIC, declarationPattern(),
RsKeywordCompletionProvider("const", "enum", "extern", "fn", "impl", "mod", "pub", "static", "struct", "trait", "type", "unsafe", "use"))
extend(CompletionType.BASIC, pubDeclarationPattern(),
RsKeywordCompletionProvider("const", "enum", "extern", "fn", "mod", "static", "struct", "trait", "type", "unsafe", "use"))
extend(CompletionType.BASIC, externDeclarationPattern(),
RsKeywordCompletionProvider("crate", "fn"))
extend(CompletionType.BASIC, unsafeDeclarationPattern(),
RsKeywordCompletionProvider("fn", "impl", "trait", "extern"))
extend(CompletionType.BASIC, newCodeStatementPattern(),
RsKeywordCompletionProvider("return", "let"))
extend(CompletionType.BASIC, letPattern(),
RsKeywordCompletionProvider("mut"))
extend(CompletionType.BASIC, loopFlowCommandPatern(),
RsKeywordCompletionProvider("break", "continue"))
extend(CompletionType.BASIC, wherePattern(),
RsKeywordCompletionProvider("where"))
extend(CompletionType.BASIC, constParameterBeginningPattern(),
RsKeywordCompletionProvider("const"))
extend(CompletionType.BASIC, traitOrImplDeclarationPattern(),
RsKeywordCompletionProvider("const", "fn", "type", "unsafe"))
extend(CompletionType.BASIC, unsafeTraitOrImplDeclarationPattern(),
RsKeywordCompletionProvider("fn"))
extend(CompletionType.BASIC, inherentImplDeclarationPattern(),
RsKeywordCompletionProvider("pub"))
extend(CompletionType.BASIC, pubInherentImplDeclarationPattern(),
RsKeywordCompletionProvider("const", "fn", "type", "unsafe"))
extend(CompletionType.BASIC, elsePattern(), object : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val elseBuilder = LookupElementBuilder
.create("else")
.bold()
.withTailText(" {...}")
.withInsertHandler { ctx, _ ->
ctx.document.insertString(ctx.selectionEndOffset, " { }")
EditorModificationUtil.moveCaretRelatively(ctx.editor, 3)
}
val elseIfBuilder = conditionLookupElement("else if")
// `else` is more common than `else if`
result.addElement(elseBuilder.withPriority(KEYWORD_PRIORITY * 1.0001))
result.addElement(elseIfBuilder.withPriority(KEYWORD_PRIORITY))
}
})
extend(CompletionType.BASIC, pathExpressionPattern(), object : CompletionProvider<CompletionParameters>() {
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
for (keyword in CONDITION_KEYWORDS) {
result.addElement(conditionLookupElement(keyword).withPriority(KEYWORD_PRIORITY))
}
}
})
extend(CompletionType.BASIC, postfixAwaitPattern(), object : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet
) {
val awaitTy = context.get(AWAIT_TY) ?: return
val awaitBuilder = LookupElementBuilder
.create("await")
.bold()
.withTypeText(awaitTy.toString())
result.addElement(awaitBuilder.withPriority(KEYWORD_PRIORITY * 1.0001))
}
})
}
private fun conditionLookupElement(lookupString: String): LookupElementBuilder {
return LookupElementBuilder
.create(lookupString)
.bold()
.withTailText(" {...}")
.withInsertHandler { context, _ ->
val isLetExpr = context.file.findElementAt(context.tailOffset - 1)
?.ancestorStrict<RsLetDecl>()
?.let { it.expr?.text == lookupString } == true
val hasSemicolon = context.nextCharIs(';')
var tail = " { }"
if (isLetExpr && !hasSemicolon) tail += ';'
context.document.insertString(context.selectionEndOffset, tail)
EditorModificationUtil.moveCaretRelatively(context.editor, 1)
}
}
private fun declarationPattern(): PsiElementPattern.Capture<PsiElement> =
baseDeclarationPattern().and(statementBeginningPattern())
private fun pubDeclarationPattern(): PsiElementPattern.Capture<PsiElement> =
baseDeclarationPattern().and(statementBeginningPattern("pub"))
private fun externDeclarationPattern(): PsiElementPattern.Capture<PsiElement> =
baseDeclarationPattern().and(statementBeginningPattern("extern"))
private fun unsafeDeclarationPattern(): PsiElementPattern.Capture<PsiElement> =
baseDeclarationPattern().and(statementBeginningPattern("unsafe"))
private fun newCodeStatementPattern(): PsiElementPattern.Capture<PsiElement> =
baseCodeStatementPattern().and(statementBeginningPattern())
private fun letPattern(): PsiElementPattern.Capture<PsiElement> =
baseCodeStatementPattern().and(statementBeginningPattern("let"))
private fun loopFlowCommandPatern(): PsiElementPattern.Capture<PsiElement> =
RsPsiPattern.inAnyLoop.and(newCodeStatementPattern())
private fun baseDeclarationPattern(): PsiElementPattern.Capture<PsiElement> =
psiElement()
.withParent(or(psiElement<RsPath>(), psiElement<RsModItem>(), psiElement<RsFile>()))
private fun baseCodeStatementPattern(): PsiElementPattern.Capture<PsiElement> =
psiElement()
.inside(psiElement<RsFunction>())
.andNot(psiElement().withParent(RsModItem::class.java))
private fun statementBeginningPattern(vararg startWords: String): PsiElementPattern.Capture<PsiElement> =
psiElement(IDENTIFIER).and(RsPsiPattern.onStatementBeginning(*startWords))
private fun elsePattern(): PsiElementPattern.Capture<PsiElement> {
val braceAfterIf = psiElement(RBRACE).withSuperParent(2, psiElement(IF_EXPR))
return psiElement().afterLeafSkipping(RsPsiPattern.whitespace, braceAfterIf)
}
private fun wherePattern(): PsiElementPattern.Capture<PsiElement> {
val typeParameters = psiElement<RsTypeParameterList>()
val function = psiElement<RsFunction>()
.withLastChildSkipping(RsPsiPattern.error, or(psiElement<RsValueParameterList>(), psiElement<RsRetType>()))
.andOr(psiElement().withChild(psiElement<RsTypeParameterList>()),
psiElement().withParent(RsMembers::class.java))
val struct = psiElement<RsStructItem>()
.withChild(typeParameters)
.withLastChildSkipping(RsPsiPattern.error, or(typeParameters, psiElement<RsTupleFields>()))
val enum = psiElement<RsEnumItem>()
.withLastChildSkipping(RsPsiPattern.error, typeParameters)
val typeAlias = psiElement<RsTypeAlias>()
.withLastChildSkipping(RsPsiPattern.error, typeParameters)
.andNot(psiElement().withParent(RsMembers::class.java))
val trait = psiElement<RsTraitItem>()
.withLastChildSkipping(RsPsiPattern.error, or(psiElement(IDENTIFIER), typeParameters))
val impl = psiElement<RsImplItem>()
.withLastChildSkipping(RsPsiPattern.error, psiElement<RsTypeReference>())
return psiElement()
.withPrevSiblingSkipping(RsPsiPattern.whitespace, or(function, struct, enum, typeAlias, trait, impl))
}
private fun pathExpressionPattern(): PsiElementPattern.Capture<PsiElement> {
val parent = psiElement<RsPath>()
.with(object : PatternCondition<RsPath>("RsPath") {
override fun accepts(t: RsPath, context: ProcessingContext?): Boolean {
return t.path == null && t.typeQual == null
}
})
return psiElement(IDENTIFIER)
.withParent(parent)
.withSuperParent<RsPathExpr>(2)
.inside(psiElement<RsFunction>())
}
private fun postfixAwaitPattern(): PsiElementPattern.Capture<PsiElement> {
val parent = psiElement<RsFieldLookup>()
.with(object : PatternCondition<RsFieldLookup>("RsPostfixAwait") {
override fun accepts(t: RsFieldLookup, context: ProcessingContext?): Boolean {
if (context == null || !t.isEdition2018) return false
val receiver = t.receiver.safeGetOriginalOrSelf()
val lookup = ImplLookup.relativeTo(receiver)
val awaitTy = receiver.type.lookupFutureOutputTy(lookup)
if (awaitTy is TyUnknown) return false
context.put(AWAIT_TY, awaitTy)
return true
}
})
return psiElement(IDENTIFIER).withParent(parent)
}
private fun constParameterBeginningPattern(): PsiElementPattern.Capture<PsiElement> {
val parent = psiElement<RsTypeParameter>()
.with(object : PatternCondition<RsTypeParameter>("RsConstParameterBeginning") {
override fun accepts(t: RsTypeParameter, context: ProcessingContext?): Boolean {
val leftSibling = t.leftSiblings.firstOrNull { it !is PsiWhiteSpace }
if (leftSibling != null && leftSibling.elementType != LT && leftSibling.elementType != COMMA) {
return false
}
val rightSibling = t.rightSiblings.firstOrNull { it is RsElement }
if (rightSibling is RsTypeParameter || rightSibling is RsLifetimeParameter) {
return false
}
return true
}
})
return psiElement(IDENTIFIER).withParent(parent)
}
private fun baseTraitOrImplDeclaration(): PsiElementPattern.Capture<PsiElement> {
return psiElement().withParent(or(
psiElement<RsMembers>(),
psiElement().withParent(RsMembers::class.java)
))
}
private fun traitOrImplDeclarationPattern(): PsiElementPattern.Capture<PsiElement> {
return baseTraitOrImplDeclaration().and(statementBeginningPattern())
}
private fun unsafeTraitOrImplDeclarationPattern(): PsiElementPattern.Capture<PsiElement> {
return baseTraitOrImplDeclaration().and(statementBeginningPattern("unsafe"))
}
private fun baseInherentImplDeclarationPattern(): PsiElementPattern.Capture<PsiElement> {
val membersInInherentImpl = psiElement<RsMembers>().withParent(
psiElement<RsImplItem>().with("InherentImpl") { e -> e.traitRef == null }
)
return psiElement().withParent(or(
membersInInherentImpl,
psiElement().withParent(membersInInherentImpl)
))
}
private fun inherentImplDeclarationPattern(): PsiElementPattern.Capture<PsiElement> {
return baseInherentImplDeclarationPattern().and(statementBeginningPattern())
}
private fun pubInherentImplDeclarationPattern(): PsiElementPattern.Capture<PsiElement> {
return baseInherentImplDeclarationPattern().and(statementBeginningPattern("pub"))
}
private fun Ty.lookupFutureOutputTy(lookup: ImplLookup): Ty {
val futureTrait = lookup.items.Future ?: return TyUnknown
val outputType = futureTrait.findAssociatedType("Output") ?: return TyUnknown
val selection = lookup.selectProjectionStrict(TraitRef(this, futureTrait.withSubst()), outputType)
return selection.ok()?.value ?: TyUnknown
}
companion object {
@JvmField
val CONDITION_KEYWORDS: List<String> = listOf("if", "match")
private val AWAIT_TY: Key<Ty> = Key.create("AWAIT_TY")
}
}