Skip to content

KtStubbedPsiUtil

Static helpers for navigating the Kotlin PSI in a way that also works over stubs.

The platform's PsiTreeUtil operates on the AST tree, which forces a stub-backed element to be parsed. The methods here (such as getContainingDeclaration and getPsiOrStubParent) instead walk the stub hierarchy when one is available, avoiding unnecessary parsing.

Companion functions

getContainingDeclaration

@Nullable
open fun getContainingDeclaration(@NotNull element: PsiElement): KtDeclaration

Returns the nearest enclosing KtDeclaration of the given element (excluding the element itself), or null if there is none.

@Nullable
open fun <T : KtDeclaration?> getContainingDeclaration(@NotNull element: PsiElement, @NotNull declarationClass: Class<T>): T

Returns the nearest enclosing KtDeclaration of the given element that is an instance of declarationClass (excluding the element itself), or null if there is none.

getPsiOrStubParent

@Nullable
open fun <T : KtElement?> getPsiOrStubParent(
    @NotNull element: PsiElement, 
    @NotNull declarationClass: Class<T>, 
    strict: Boolean
): T

Returns the nearest parent of the given element assignable to declarationClass, or null if there is none. When strict is false, the element itself is also considered a candidate.

When the element is backed by a stub, its stub hierarchy is walked instead of the AST, avoiding parsing; otherwise this falls back to getParentOfType.

getStubOrPsiChild

@Nullable
open fun <T : KtElement?> getStubOrPsiChild(
    @NotNull element: KtElementImplStub<*>, 
    @NotNull types: TokenSet, 
    @NotNull factory: ArrayFactory<T>
): T

Returns the first child of the given element whose type is in types, or null if there is none. Stub children are used when the element is backed by a stub, avoiding parsing; otherwise its PSI children are traversed. The factory produces the typed array used to collect the matching children.