String () { myReturns.forEach((statement, node) -> statement.putCopyableUserData(NODE_KEY, node)); PsiSwitchExpression copy = (PsiSwitchExpression)myAnchor.copy(); Map<PsiStatement, PsiStatement[]> replacementMap = new HashMap<>(); PsiElementFactory factory = JavaPsiFacade.getElementFactory(myAnchor.getProject()); PsiCodeBlock body = Objects.requireNonNull(copy.getBody()); body.accept(new JavaRecursiveElementWalkingVisitor() { @Override public void visitExpressionStatement(@NotNull PsiExpressionStatement statement) { if (statement.getParent() instanceof PsiSwitchLabeledRuleStatement && ((PsiSwitchLabeledRuleStatement)statement.getParent()).getEnclosingSwitchBlock() == copy) { process(statement); } } @Override public void visitYieldStatement(@NotNull PsiYieldStatement statement) { if (statement.getExpression() != null && statement.findEnclosingExpression() == copy) { process(statement); } } @Override public void visitExpression(@NotNull PsiExpression expression) { // Do not go into any expressions } private void process(PsiStatement statement) { Node data = statement.getCopyableUserData(NODE_KEY); if (data == null) { replacementMap.put(statement, PsiStatement.EMPTY_ARRAY); } else { replacementMap.put(statement, factory.createCodeBlockFromText("{" + data + "}", statement).getStatements()); } } }); replacementMap.forEach((statement, replacements) -> { boolean keep = statement instanceof PsiYieldStatement && shouldKeepBreak(statement); if (!keep && replacements.length == 1) { statement.replace(replacements[0]); } else { if (!keep || replacements.length > 0) { if (!(statement.getParent() instanceof PsiCodeBlock)) { statement = BlockUtils.expandSingleStatementToBlockStatement(statement); } PsiElement parent = statement.getParent(); for (PsiStatement replacement : replacements) { parent.addBefore(replacement, statement); } } if (!keep) { statement.delete(); } else { statement.replace(factory.createStatementFromText("break;", null)); } } }); return copy.getText(); }