diff --git a/uast/uast-common/src/org/jetbrains/uast/UastContext.kt b/uast/uast-common/src/org/jetbrains/uast/UastContext.kt index 5d6a54eda809..6b304ecf7221 100644 --- a/uast/uast-common/src/org/jetbrains/uast/UastContext.kt +++ b/uast/uast-common/src/org/jetbrains/uast/UastContext.kt @@ -130,15 +130,13 @@ fun PsiFile.findUElementAt(offset: Int, cls: Class): T? { * Finds an UAST element of the given type among the parents of the given PSI element. */ @JvmOverloads -fun PsiElement?.getUastParentOfType(cls: Class, strict: Boolean = false): T? { - val uElement = this.toUElement() ?: return null - val sequence = if (strict) - (uElement.uastParent?.withContainingElements ?: emptySequence()) - else - uElement.withContainingElements +fun PsiElement?.getUastParentOfType(cls: Class, strict: Boolean = false): T? = this?.run { + val startingElement = if (strict) this.parent else this + val parentSequence = generateSequence(startingElement, PsiElement::getParent) + val firstUElement = parentSequence.mapNotNull { it.toUElement() }.firstOrNull() ?: return null @Suppress("UNCHECKED_CAST") - return sequence.firstOrNull { cls.isInstance(it) } as T? + return firstUElement.withContainingElements.firstOrNull { cls.isInstance(it) } as T? } inline fun PsiElement?.getUastParentOfType(strict: Boolean = false): T? = getUastParentOfType(T::class.java, strict)