ExpressionOccurrenceManager (PsiExpression expr, PsiElement tempContainer) { Set<PsiVariable> vars = new HashSet<>(); SyntaxTraverser.psiTraverser().withRoot(expr) .filter(element -> element instanceof PsiReferenceExpression) .forEach(element -> { final PsiElement resolve = ((PsiReferenceExpression)element).resolve(); if (resolve instanceof PsiVariable) { vars.add((PsiVariable)resolve); } }); PsiElement containerParent = tempContainer; PsiElement lastScope = tempContainer; while (true) { if (containerParent instanceof PsiFile) break; if (containerParent instanceof PsiMethod) { PsiClass containingClass = ((PsiMethod)containerParent).getContainingClass(); if (containingClass == null || !PsiUtil.isLocalOrAnonymousClass(containingClass)) break; if (ContainerUtil.exists(vars, variable -> PsiTreeUtil.isAncestor(containingClass, variable, true))) { break; } } if (containerParent instanceof PsiLambdaExpression) { PsiParameter[] parameters = ((PsiLambdaExpression)containerParent).getParameterList().getParameters(); if (ContainerUtil.exists(parameters, vars::contains)) { break; } } if (containerParent instanceof PsiForStatement forStatement && ContainerUtil.exists(vars, variable -> PsiTreeUtil.isAncestor(forStatement.getInitialization(), variable, true))) { break; } containerParent = containerParent.getParent(); if (containerParent instanceof PsiCodeBlock) { lastScope = containerParent; } } return new ExpressionOccurrenceManager(expr, lastScope, NotInSuperCallOccurrenceFilter.INSTANCE); }