-
Notifications
You must be signed in to change notification settings - Fork 380
/
RsPsiPattern.kt
281 lines (223 loc) · 9.86 KB
/
RsPsiPattern.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
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core
import com.intellij.patterns.*
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.patterns.StandardPatterns.or
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiErrorElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.tree.TokenSet
import com.intellij.util.ProcessingContext
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.RsElementTypes.*
import org.rust.lang.core.psi.ext.*
/**
* Rust PSI tree patterns.
*/
object RsPsiPattern {
private val STATEMENT_BOUNDARIES = TokenSet.create(SEMICOLON, LBRACE, RBRACE)
/**
* Source of attributes: [https://doc.rust-lang.org/1.41.1/reference/attributes.html#built-in-attributes-index]
*/
val STD_ATTRIBUTES: Set<String> = setOf(
"cfg",
"cfg_attr",
"test",
"ignore",
"should_panic",
"derive",
"macro_export",
"macro_use",
"proc_macro",
"proc_macro_derive",
"proc_macro_attribute",
"allow",
"warn",
"deny",
"forbid",
"deprecated",
"must_use",
"link",
"link_name",
"no_link",
"repr",
"crate_type",
"no_main",
"export_name",
"link_section",
"no_mangle",
"used",
"crate_name",
"inline",
"cold",
"no_builtins",
"target_feature",
"doc",
"no_std",
"no_implicit_prelude",
"path",
"recursion_limit",
"type_length_limit",
"panic_handler",
"global_allocator",
"windows_subsystem",
"non_exhaustive",
// unstable attr
"start"
)
private val LINT_ATTRIBUTES: Set<String> = setOf(
"allow",
"warn",
"deny",
"forbid"
)
const val META_ITEM_IDENTIFIER_DEPTH = 4
val onStatementBeginning: PsiElementPattern.Capture<PsiElement> = psiElement().with(OnStatementBeginning())
fun onStatementBeginning(vararg startWords: String): PsiElementPattern.Capture<PsiElement> =
psiElement().with(OnStatementBeginning(*startWords))
val onStruct: PsiElementPattern.Capture<PsiElement> = onItem<RsStructItem>()
val onEnum: PsiElementPattern.Capture<PsiElement> = onItem<RsEnumItem>()
val onFn: PsiElementPattern.Capture<PsiElement> = onItem<RsFunction>()
val onMod: PsiElementPattern.Capture<PsiElement> = onItem<RsModItem>() or onItem<RsModDeclItem>()
val onStatic: PsiElementPattern.Capture<PsiElement> = onItem(psiElement<RsConstant>()
.with("onStaticCondition") { e -> e.kind == RsConstantKind.STATIC })
val onStaticMut: PsiElementPattern.Capture<PsiElement> = onItem(psiElement<RsConstant>()
.with("onStaticMutCondition") { e -> e.kind == RsConstantKind.MUT_STATIC })
val onMacro: PsiElementPattern.Capture<PsiElement> = onItem<RsMacro>()
val onTupleStruct: PsiElementPattern.Capture<PsiElement> = onItem(psiElement<RsStructItem>()
.withChild(psiElement<RsTupleFields>()))
val onCrate: PsiElementPattern.Capture<PsiElement> = onItem<RsFile>()
.with("onCrateCondition") { e ->
val file = e.containingFile.originalFile as RsFile
file.isCrateRoot
}
val onExternBlock: PsiElementPattern.Capture<PsiElement> = onItem<RsForeignModItem>()
val onExternBlockDecl: PsiElementPattern.Capture<PsiElement> =
onItem<RsFunction>() or //FIXME: check if this is indeed a foreign function
onItem<RsConstant>() or
onItem<RsForeignModItem>()
val onAnyItem: PsiElementPattern.Capture<PsiElement> = onItem<RsDocAndAttributeOwner>()
val onExternCrate: PsiElementPattern.Capture<PsiElement> = onItem<RsExternCrateItem>()
val onTrait: PsiElementPattern.Capture<PsiElement> = onItem<RsTraitItem>()
val onDropFn: PsiElementPattern.Capture<PsiElement>
get() {
val dropTraitRef = psiElement<RsTraitRef>().withText("Drop")
val implBlock = psiElement<RsImplItem>().withChild(dropTraitRef)
return psiElement().withSuperParent(6, implBlock)
}
val onTestFn: PsiElementPattern.Capture<PsiElement> = onItem(psiElement<RsFunction>()
.withChild(psiElement<RsOuterAttr>().withText("#[test]")))
val inAnyLoop: PsiElementPattern.Capture<PsiElement> =
psiElement().inside(
true,
psiElement<RsBlock>().withParent(
or(
psiElement<RsForExpr>(),
psiElement<RsLoopExpr>(),
psiElement<RsWhileExpr>()
)
),
psiElement<RsLambdaExpr>()
)
val derivedTraitMetaItem: PsiElementPattern.Capture<RsMetaItem> =
psiElement<RsMetaItem>().withSuperParent(
2,
psiElement()
.withSuperParent<RsStructOrEnumItemElement>(2)
.with("deriveCondition") { e -> e is RsMetaItem && e.name == "derive" }
)
/**
* Supposed to capture outer attributes names, like `attribute` in `#[attribute(par1, par2)]`.
*/
val nonStdOuterAttributeMetaItem: PsiElementPattern.Capture<RsMetaItem> =
psiElement<RsMetaItem>()
.withSuperParent(2, RsOuterAttributeOwner::class.java)
.with("nonStdAttributeCondition") { e -> e.name !in STD_ATTRIBUTES }
val lintAttributeMetaItem: PsiElementPattern.Capture<RsMetaItem> =
psiElement<RsMetaItem>()
.withParent(RsAttr::class.java)
.with("lintAttributeCondition") { e -> e.name in LINT_ATTRIBUTES }
val includeMacroLiteral: PsiElementPattern.Capture<RsLitExpr> = psiElement<RsLitExpr>()
.withParent(psiElement<RsIncludeMacroArgument>())
val pathAttrLiteral: PsiElementPattern.Capture<RsLitExpr> = psiElement<RsLitExpr>()
.withParent(psiElement<RsMetaItem>()
.withSuperParent(2, or(psiElement<RsModDeclItem>(), psiElement<RsModItem>()))
.with("pathAttrCondition") { metaItem -> metaItem.name == "path" }
)
val whitespace: PsiElementPattern.Capture<PsiElement> = psiElement().whitespace()
val error: PsiElementPattern.Capture<PsiErrorElement> = psiElement<PsiErrorElement>()
val simplePathPattern: ElementPattern<PsiElement>
get() {
val simplePath = psiElement<RsPath>()
.with(object : PatternCondition<RsPath>("SimplePath") {
override fun accepts(path: RsPath, context: ProcessingContext?): Boolean =
path.kind == PathKind.IDENTIFIER &&
path.path == null &&
path.typeQual == null &&
!path.hasColonColon &&
path.ancestorStrict<RsUseSpeck>() == null
})
return psiElement().withParent(simplePath)
}
private inline fun <reified I : RsDocAndAttributeOwner> onItem(): PsiElementPattern.Capture<PsiElement> {
return psiElement().withSuperParent<I>(META_ITEM_IDENTIFIER_DEPTH)
}
private fun onItem(pattern: ElementPattern<out RsDocAndAttributeOwner>): PsiElementPattern.Capture<PsiElement> {
return psiElement().withSuperParent(META_ITEM_IDENTIFIER_DEPTH, pattern)
}
private class OnStatementBeginning(vararg startWords: String) : PatternCondition<PsiElement>("on statement beginning") {
val myStartWords = startWords
override fun accepts(t: PsiElement, context: ProcessingContext?): Boolean {
val prev = t.prevVisibleOrNewLine
return if (myStartWords.isEmpty())
prev == null || prev is PsiWhiteSpace || prev.node.elementType in STATEMENT_BOUNDARIES
else
prev != null && prev.node.text in myStartWords
}
}
}
inline fun <reified I : PsiElement> psiElement(): PsiElementPattern.Capture<I> {
return psiElement(I::class.java)
}
inline fun <reified I : PsiElement> psiElement(contextName: String): PsiElementPattern.Capture<I> {
return psiElement(I::class.java).with("putIntoContext") { e, context ->
context?.put(contextName, e)
true
}
}
inline fun <reified I : PsiElement> PsiElementPattern.Capture<PsiElement>.withSuperParent(level: Int): PsiElementPattern.Capture<PsiElement> {
return this.withSuperParent(level, I::class.java)
}
inline infix fun <reified I : PsiElement> ElementPattern<out I>.or(pattern: ElementPattern<out I>): PsiElementPattern.Capture<PsiElement> {
return psiElement().andOr(this, pattern)
}
private val PsiElement.prevVisibleOrNewLine: PsiElement?
get() = leftLeaves
.filterNot { it is PsiComment || it is PsiErrorElement }
.filter { it !is PsiWhiteSpace || it.textContains('\n') }
.firstOrNull()
/**
* Similar with [TreeElementPattern.afterSiblingSkipping]
* but it uses [PsiElement.getPrevSibling] to get previous sibling elements
* instead of [PsiElement.getChildren].
*/
fun <T : PsiElement, Self : PsiElementPattern<T, Self>> PsiElementPattern<T, Self>.withPrevSiblingSkipping(
skip: ElementPattern<out T>,
pattern: ElementPattern<out T>
): Self = with("withPrevSiblingSkipping") { e ->
val sibling = e.leftSiblings.dropWhile { skip.accepts(it) }
.firstOrNull() ?: return@with false
pattern.accepts(sibling)
}
fun <T, Self : ObjectPattern<T, Self>> ObjectPattern<T, Self>.with(name: String, cond: (T) -> Boolean): Self =
with(object : PatternCondition<T>(name) {
override fun accepts(t: T, context: ProcessingContext?): Boolean = cond(t)
})
fun <T, Self : ObjectPattern<T, Self>> ObjectPattern<T, Self>.with(name: String, cond: (T, ProcessingContext?) -> Boolean): Self =
with(object : PatternCondition<T>(name) {
override fun accepts(t: T, context: ProcessingContext?): Boolean = cond(t, context)
})