0
# Resolution Services
1
2
Core resolution services providing symbol resolution, reference finding, and IDE-like analysis capabilities for Kotlin scripts. These services enable the compiler to understand code context and provide accurate completions and diagnostics.
3
4
## Capabilities
5
6
### ResolutionFacade
7
8
Central interface for Kotlin resolution services, providing access to analysis results and compiler services.
9
10
```kotlin { .api }
11
/**
12
* Central interface for Kotlin resolution services in IDE contexts
13
* Provides access to analysis results, compiler services, and resolution utilities
14
*/
15
interface ResolutionFacade {
16
/** The IntelliJ project context */
17
val project: Project
18
19
/** The module descriptor for the current module */
20
val moduleDescriptor: ModuleDescriptor
21
22
/**
23
* Performs comprehensive analysis with all compiler checks
24
* @param elements - Collection of Kotlin elements to analyze
25
* @param callback - Optional callback for handling diagnostics
26
* @returns AnalysisResult containing binding context and diagnostics
27
*/
28
fun analyzeWithAllCompilerChecks(
29
elements: Collection<KtElement>,
30
callback: DiagnosticSink.DiagnosticsCallback? = null
31
): AnalysisResult
32
33
/**
34
* Gets a frontend service instance for the specified service class
35
* @param serviceClass - Class of the service to retrieve
36
* @returns Service instance
37
*/
38
@FrontendInternals
39
fun <T : Any> getFrontendService(serviceClass: Class<T>): T
40
41
/**
42
* Gets an IDE service instance for the specified service class
43
* @param serviceClass - Class of the service to retrieve
44
* @returns Service instance
45
*/
46
fun <T : Any> getIdeService(serviceClass: Class<T>): T
47
48
/**
49
* Gets a frontend service for a specific PSI element
50
* @param element - PSI element context
51
* @param serviceClass - Class of the service to retrieve
52
* @returns Service instance
53
*/
54
@FrontendInternals
55
fun <T : Any> getFrontendService(element: PsiElement, serviceClass: Class<T>): T
56
57
/**
58
* Attempts to get a frontend service, returning null if unavailable
59
* @param element - PSI element context
60
* @param serviceClass - Class of the service to retrieve
61
* @returns Service instance or null
62
*/
63
@FrontendInternals
64
fun <T : Any> tryGetFrontendService(element: PsiElement, serviceClass: Class<T>): T?
65
66
/**
67
* Gets a frontend service for a specific module descriptor
68
* @param moduleDescriptor - Module descriptor context
69
* @param serviceClass - Class of the service to retrieve
70
* @returns Service instance
71
*/
72
@FrontendInternals
73
fun <T : Any> getFrontendService(moduleDescriptor: ModuleDescriptor, serviceClass: Class<T>): T
74
75
/**
76
* Gets the resolver for the current project
77
* @returns ResolverForProject instance
78
*/
79
fun getResolverForProject(): ResolverForProject<out ModuleInfo>
80
}
81
```
82
83
**Usage Examples:**
84
85
```kotlin
86
// Using ResolutionFacade for analysis
87
val resolutionFacade: ResolutionFacade = // obtained from compiler
88
val elements: Collection<KtElement> = // elements to analyze
89
90
// Perform full analysis
91
val analysisResult = resolutionFacade.analyzeWithAllCompilerChecks(elements) { diagnostics ->
92
// Handle diagnostics during analysis
93
diagnostics.forEach { diagnostic ->
94
println("${diagnostic.severity}: ${diagnostic.factoryName}")
95
}
96
}
97
98
// Access binding context and diagnostics
99
val bindingContext = analysisResult.bindingContext
100
val diagnostics = analysisResult.diagnostics
101
102
// Get language version settings
103
val languageVersionSettings = resolutionFacade.getLanguageVersionSettings()
104
```
105
106
### Extension Functions
107
108
Convenient extension functions for common resolution operations:
109
110
```kotlin { .api }
111
/**
112
* Inline extension for getting frontend services with reified type parameters
113
*/
114
inline fun <reified T : Any> ResolutionFacade.frontendService(): T
115
116
/**
117
* Gets the language version settings for the resolution facade
118
*/
119
fun ResolutionFacade.getLanguageVersionSettings(): LanguageVersionSettings
120
121
/**
122
* Gets the data flow value factory for the resolution facade
123
*/
124
fun ResolutionFacade.getDataFlowValueFactory(): DataFlowValueFactory
125
```
126
127
### ReferenceVariantsHelper
128
129
Helper class for finding reference variants and completion candidates in Kotlin code.
130
131
```kotlin { .api }
132
/**
133
* Helper for finding reference variants and completions in Kotlin code
134
* Provides methods for getting completion candidates based on context
135
*/
136
class ReferenceVariantsHelper(
137
private val bindingContext: BindingContext,
138
private val resolutionFacade: ResolutionFacade,
139
private val moduleDescriptor: ModuleDescriptor,
140
private val visibilityFilter: (DeclarationDescriptor) -> Boolean,
141
private val notProperties: Set<FqNameUnsafe> = emptySet()
142
) {
143
/**
144
* Gets reference variants for a simple name expression
145
* @param expression - The expression to find variants for
146
* @param kindFilter - Filter for descriptor kinds (functions, properties, etc.)
147
* @param nameFilter - Filter for names
148
* @param filterOutJavaGettersAndSetters - Whether to filter Java getters/setters
149
* @param filterOutShadowed - Whether to filter shadowed declarations
150
* @param excludeNonInitializedVariable - Whether to exclude uninitialized variables
151
* @param useReceiverType - Optional receiver type for member completion
152
* @returns Collection of declaration descriptors
153
*/
154
fun getReferenceVariants(
155
expression: KtSimpleNameExpression,
156
kindFilter: DescriptorKindFilter,
157
nameFilter: (Name) -> Boolean,
158
filterOutJavaGettersAndSetters: Boolean = false,
159
filterOutShadowed: Boolean = true,
160
excludeNonInitializedVariable: Boolean = false,
161
useReceiverType: KotlinType? = null
162
): Collection<DeclarationDescriptor>
163
164
/**
165
* Gets reference variants for a context element with call type and receiver
166
* @param contextElement - PSI element providing context
167
* @param callTypeAndReceiver - Call type and receiver information
168
* @param kindFilter - Filter for descriptor kinds
169
* @param nameFilter - Filter for names
170
* @param filterOutJavaGettersAndSetters - Whether to filter Java getters/setters
171
* @param filterOutShadowed - Whether to filter shadowed declarations
172
* @returns Collection of declaration descriptors
173
*/
174
fun getReferenceVariants(
175
contextElement: PsiElement,
176
callTypeAndReceiver: CallTypeAndReceiver<*, *>,
177
kindFilter: DescriptorKindFilter,
178
nameFilter: (Name) -> Boolean,
179
filterOutJavaGettersAndSetters: Boolean = false,
180
filterOutShadowed: Boolean = true
181
): Collection<DeclarationDescriptor>
182
183
/**
184
* Filters out Java getter and setter methods from variants
185
*/
186
fun <TDescriptor : DeclarationDescriptor> filterOutJavaGettersAndSetters(
187
variants: Collection<TDescriptor>
188
): Collection<TDescriptor>
189
190
/**
191
* Excludes non-initialized variables from completion variants
192
*/
193
fun excludeNonInitializedVariable(
194
variants: Collection<DeclarationDescriptor>,
195
contextElement: PsiElement
196
): Collection<DeclarationDescriptor>
197
}
198
```
199
200
**Usage Examples:**
201
202
```kotlin
203
// Create reference variants helper
204
val helper = ReferenceVariantsHelper(
205
bindingContext = bindingContext,
206
resolutionFacade = resolutionFacade,
207
moduleDescriptor = moduleDescriptor,
208
visibilityFilter = { descriptor ->
209
// Custom visibility logic
210
descriptor.visibility.isVisible(
211
receiver = null,
212
what = descriptor,
213
from = currentDescriptor
214
)
215
}
216
)
217
218
// Get completion variants for a simple expression
219
val expression: KtSimpleNameExpression = // PSI element
220
val variants = helper.getReferenceVariants(
221
expression = expression,
222
kindFilter = DescriptorKindFilter.ALL,
223
nameFilter = { name -> name.identifier.startsWith("get") },
224
filterOutShadowed = true,
225
excludeNonInitializedVariable = true
226
)
227
228
// Process variants
229
variants.forEach { descriptor ->
230
when (descriptor) {
231
is FunctionDescriptor -> println("Function: ${descriptor.name}")
232
is PropertyDescriptor -> println("Property: ${descriptor.name}")
233
is ClassDescriptor -> println("Class: ${descriptor.name}")
234
}
235
}
236
```
237
238
### Scope Resolution Extensions
239
240
Extension functions for working with resolution scopes and PSI elements:
241
242
```kotlin { .api }
243
/**
244
* Gets the resolution scope for a PSI element
245
* @param bindingContext - Binding context from analysis
246
* @returns LexicalScope or null if not available
247
*/
248
fun PsiElement.getResolutionScope(bindingContext: BindingContext): LexicalScope?
249
250
/**
251
* Gets the resolution scope for a PSI element with fallback resolution
252
* @param bindingContext - Binding context from analysis
253
* @param resolutionFacade - Resolution facade for fallback resolution
254
* @returns LexicalScope (never null)
255
*/
256
fun PsiElement.getResolutionScope(
257
bindingContext: BindingContext,
258
resolutionFacade: ResolutionFacade
259
): LexicalScope
260
261
/**
262
* Gets the file-level resolution scope
263
* @param file - Kotlin file to get scope for
264
* @returns LexicalScope for the file
265
*/
266
fun ResolutionFacade.getFileResolutionScope(file: KtFile): LexicalScope
267
```
268
269
### Advanced Resolution Functions
270
271
Additional utility functions for complex resolution scenarios:
272
273
```kotlin { .api }
274
/**
275
* Collects synthetic static members and constructors for a resolution scope
276
*/
277
fun ResolutionScope.collectSyntheticStaticMembersAndConstructors(
278
kindFilter: DescriptorKindFilter,
279
nameFilter: (Name) -> Boolean,
280
location: LookupLocation
281
): List<FunctionDescriptor>
282
283
/**
284
* Forces enabling of SAM adapters in synthetic scopes
285
*/
286
fun SyntheticScopes.forceEnableSamAdapters(): SyntheticScopes
287
```
288
289
## Integration with REPL Compiler
290
291
The resolution services are automatically integrated with the REPL compiler:
292
293
```kotlin
294
// Internal usage within KJvmReplCompilerWithIdeServices
295
val analyzeResult = analyzeWithCursor(messageCollector, snippet, configuration, cursor)
296
297
with(analyzeResult.valueOr { return it }) {
298
// Uses resolution facade for completion
299
return getKJvmCompletion(
300
ktScript,
301
bindingContext,
302
resolutionFacade, // ResolutionFacade instance
303
moduleDescriptor,
304
cursorAbs,
305
configuration
306
).asSuccess(messageCollector.diagnostics)
307
}
308
```
309
310
## Error Handling
311
312
Resolution operations may fail in various scenarios:
313
314
- **Missing dependencies**: Required libraries not available in classpath
315
- **Compilation errors**: Syntax or semantic errors preventing resolution
316
- **Context issues**: Invalid PSI element or binding context
317
- **Service unavailability**: Required compiler services not initialized
318
319
Always check for null returns and handle exceptions appropriately when using resolution services directly.