PsiElement (@NotNull List<? extends PsiElement> referenceElements) { PsiElement commonParent = null; for (PsiElement referenceElement : referenceElements) { final PsiElement parent = PsiTreeUtil.getParentOfType(referenceElement, PsiCodeBlock.class, PsiForStatement.class, PsiTryStatement.class); if (parent != null && commonParent != null) { if (!commonParent.equals(parent)) { commonParent = PsiTreeUtil.findCommonParent(commonParent, parent); commonParent = PsiTreeUtil.getNonStrictParentOfType(commonParent, PsiCodeBlock.class, PsiForStatement.class, PsiTryStatement.class); } } else { commonParent = parent; } } // don't narrow inside resource variable, only resource expression if (commonParent instanceof PsiTryStatement && !(referenceElements.get(0).getParent() instanceof PsiResourceExpression)) { commonParent = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class, PsiForStatement.class); } // make common parent may only be for-statement if first reference is // the initialization of the for statement or the initialization is // empty. if (commonParent instanceof PsiForStatement forStatement) { final PsiElement referenceElement = referenceElements.get(0); final PsiStatement initialization = forStatement.getInitialization(); if (!(initialization instanceof PsiEmptyStatement)) { if (initialization instanceof PsiExpressionStatement statement) { final PsiExpression expression = statement.getExpression(); if (expression instanceof PsiAssignmentExpression assignmentExpression) { final PsiExpression lExpression = PsiUtil.skipParenthesizedExprDown(assignmentExpression.getLExpression()); if (!lExpression.equals(referenceElement)) { commonParent = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class); } } else { commonParent = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class); } } else { commonParent = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class); } } } // common parent may not be a switch() statement to avoid narrowing // scope to inside switch branch if (commonParent != null) { final PsiElement parent = commonParent.getParent(); if (parent instanceof PsiSwitchBlock) { if (referenceElements.size() > 1) { return PsiTreeUtil.getParentOfType(parent, PsiCodeBlock.class, false); } else if (PsiTreeUtil.getParentOfType(referenceElements.get(0), PsiSwitchLabelStatement.class, true, PsiCodeBlock.class) != null) { // reference is a switch label return PsiTreeUtil.getParentOfType(parent, PsiCodeBlock.class, false); } } } return commonParent; }