PsiElement (PsiElement declaration, PsiExpression initializer, @NotNull PsiElement anchor) { if (anchor instanceof PsiDeclarationStatement) { final PsiElement[] declaredElements = ((PsiDeclarationStatement)anchor).getDeclaredElements(); if (declaredElements.length > 1) { final int[] usedFirstVar = new int[]{-1}; initializer.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitReferenceExpression(@NotNull PsiReferenceExpression expression) { final int i = ArrayUtilRt.find(declaredElements, expression.resolve()); if (i > -1) { usedFirstVar[0] = Math.max(i, usedFirstVar[0]); } super.visitReferenceExpression(expression); } }); if (usedFirstVar[0] > -1) { final PsiVariable psiVariable = (PsiVariable)declaredElements[usedFirstVar[0]]; psiVariable.normalizeDeclaration(); final PsiDeclarationStatement parDeclarationStatement = PsiTreeUtil.getParentOfType(psiVariable, PsiDeclarationStatement.class); return anchor.getParent().addAfter(declaration, parDeclarationStatement); } } } if (anchor instanceof PsiInstanceOfExpression && declaration instanceof PsiInstanceOfExpression) { PsiInstanceOfExpression newInstanceOf = (PsiInstanceOfExpression)anchor.replace(declaration); return ((PsiTypeTestPattern)Objects.requireNonNull(newInstanceOf.getPattern())).getPatternVariable(); } if (anchor instanceof PsiResourceListElement) { PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)declaration; PsiLocalVariable localVariable = (PsiLocalVariable)declarationStatement.getDeclaredElements()[0]; PsiResourceVariable resourceVariable = JavaPsiFacade.getElementFactory(anchor.getProject()) .createResourceVariable(localVariable.getName(), localVariable.getType(), initializer, anchor); return anchor.replace(resourceVariable); } PsiElement parent = anchor.getParent(); if (parent == null) { throw new IllegalStateException("Unexpectedly anchor has no parent. Anchor class: " + anchor.getClass()); } tryFixSurroundContext(anchor); return parent.addBefore(declaration, anchor); }