PsiElement (@NotNull final PsiElement elementToResolve) { PsiElement currentElement = elementToResolve; final Set<PsiElement> checkedElements = new HashSet<>(); // To prevent PY-20553 while (true) { final PsiReference reference = currentElement.getReference(); if (reference == null) { break; } final PsiElement resolve = reference.resolve(); if (resolve == null || checkedElements.contains(resolve) || resolve.equals(currentElement) || !inSameFile(resolve, currentElement)) { break; } currentElement = resolve; checkedElements.add(resolve); } return currentElement; }