PsiElement (@NotNull PsiElement anchor) { while (true) { PsiElement prevSibling = PsiTreeUtil.skipWhitespacesAndCommentsBackward(anchor); PsiElement prevStatement = null; if (prevSibling instanceof PsiErrorElement) { prevStatement = PsiTreeUtil.getPrevSiblingOfType(prevSibling, PsiStatement.class); } else if (prevSibling instanceof PsiStatement) { PsiElement lastChild = prevSibling; while (lastChild != null && !(lastChild instanceof PsiErrorElement)) { lastChild = lastChild.getLastChild(); } if (lastChild != null) { prevStatement = prevSibling; } } if (prevStatement == null) break; // Let's try to find more valid context to be able to reparse anchor = prevStatement; } return anchor; }