PsiLoopStatement (@NotNull PsiExpression expression, @NotNull PsiVariable variable) { PsiElement stopAt = null; PsiCodeBlock block = StringConcatenationInLoopsVisitor.getSurroundingBlock(expression); if (block != null) { PsiElement ref; if (expression instanceof PsiAssignmentExpression) { ref = expression; } else { PsiReference reference = ReferencesSearch.search(variable, new LocalSearchScope(expression)).findFirst(); ref = reference != null ? reference.getElement() : null; } if (ref != null) { PsiElement[] elements = StreamEx.of(DefUseUtil.getDefs(block, variable, expression)).prepend(expression).toArray(PsiElement[]::new); stopAt = PsiTreeUtil.findCommonParent(elements); } } PsiElement parent = expression.getParent(); PsiLoopStatement commonLoop = null; while (parent != null && parent != stopAt && !(parent instanceof PsiMethod) && !(parent instanceof PsiClass) && !(parent instanceof PsiLambdaExpression)) { if (parent instanceof PsiLoopStatement) { commonLoop = (PsiLoopStatement)parent; } parent = parent.getParent(); } return commonLoop; }