PrepopulatedCollectionModel (PsiReferenceExpression expression, String typeName, String collectionClass, CallMatcher addMethod) { PsiLocalVariable variable = tryCast(expression.resolve(), PsiLocalVariable.class); if (variable == null) return null; PsiCodeBlock block = PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class); PsiDeclarationStatement declaration = PsiTreeUtil.getParentOfType(variable, PsiDeclarationStatement.class); if (block == null || declaration == null) return null; PsiElement[] defs = DefUseUtil.getDefs(block, variable, expression); if (defs.length == 1 && defs[0] == variable) { PsiExpression initializer = variable.getInitializer(); if (!ConstructionUtils.isEmptyCollectionInitializer(initializer)) return null; if (!PsiTypesUtil.classNameEquals(initializer.getType(), collectionClass)) return null; Set<PsiElement> refs = ContainerUtil.newHashSet(DefUseUtil.getRefs(block, variable, initializer)); refs.remove(expression); PsiStatement cur = declaration; List<PsiExpression> contents = new ArrayList<>(); List<PsiElement> elementsToRemove = new ArrayList<>(); elementsToRemove.add(initializer); while (true) { cur = tryCast(PsiTreeUtil.skipWhitespacesAndCommentsForward(cur), PsiStatement.class); if (PsiTreeUtil.isAncestor(cur, expression, false)) break; if (!(cur instanceof PsiExpressionStatement)) return null; PsiMethodCallExpression call = tryCast(((PsiExpressionStatement)cur).getExpression(), PsiMethodCallExpression.class); if (!addMethod.test(call)) return null; if (!refs.remove(call.getMethodExpression().getQualifierExpression())) return null; contents.addAll(Arrays.asList(call.getArgumentList().getExpressions())); elementsToRemove.add(cur); } if (!refs.isEmpty()) return null; return new PrepopulatedCollectionModel(contents, elementsToRemove, typeName); } return null; }