@@ -290,17 +290,36 @@ fun determineFileContext(file: PsiFile): Set<Directive>? {
290290 .filterIsInstance<DirectiveStmt >()
291291
292292 // Try to find a directive with a valid context
293- var context = mutableSetOf <Directive >()
293+ var context: MutableSet <Directive >? = null
294294 for (directive in directives) {
295295 val matchingDirectives = Directive .all.filter { it.name == directive.name }
296296 if (matchingDirectives.isEmpty()) {
297297 continue
298298 }
299- val matchingDirectivesContext = matchingDirectives.map { it.context }.flatten().toSet()
300- if (context.isEmpty()) {
299+ val matchingDirectivesContext = matchingDirectives
300+ .flatMap { matchedDirective ->
301+ matchedDirective.context.flatMap { ctx ->
302+ when (ctx) {
303+ any -> emptyList()
304+ self -> listOf (matchedDirective)
305+ else -> listOf (ctx)
306+ }
307+ }
308+ }
309+ .toSet()
310+
311+ // Directives that only allow wildcard contexts (e.g. include) don't help narrow scope
312+ if (matchingDirectivesContext.isEmpty()) {
313+ continue
314+ }
315+
316+ if (context == null ) {
317+ // The one and only include directive exposes the wildcard context any and no other directives do,
318+ // so the first match still captures all directive-specific contexts
301319 context = matchingDirectivesContext.toMutableSet()
302320 continue
303321 }
322+
304323 val newContext = context.intersect(matchingDirectivesContext)
305324 if (newContext.isEmpty()) {
306325 return context
@@ -311,5 +330,5 @@ fun determineFileContext(file: PsiFile): Set<Directive>? {
311330
312331 // If no directives with context found, return null
313332 // any context is allowed
314- return null
333+ return context
315334}
0 commit comments