PsiExpression (PsiExpression expression) { final PsiExpression[] result = {(PsiExpression)expression.copy()}; final ExpressionVisitor expressionVisitor = new ExpressionVisitor(expression.getManager(), true); final IncorrectOperationException[] exception = {null}; result[0].accept(new JavaRecursiveElementVisitor() { @Override public void visitElement(@NotNull PsiElement element) { // read in all children in advance since due to element replacement involving its siblings invalidation PsiElement[] children = element.getChildren(); for (PsiElement child : children) { child.accept(this); } } @Override public void visitExpression(@NotNull PsiExpression expression) { super.visitExpression(expression); expressionVisitor.clear(); expression.accept(expressionVisitor); if (expressionVisitor.resultExpression != null) { LOG.assertTrue(expressionVisitor.resultExpression.isValid()); try { if (expression != result[0]) { expression.replace(expressionVisitor.resultExpression); } else { result[0] = expressionVisitor.resultExpression; } } catch (IncorrectOperationException e) { exception[0] = e; } } } }); if (exception[0] != null) { throw exception[0]; } return result[0]; }