PsiSwitchBlock (@NotNull PsiStatement statementToReplace, List<SwitchBranch> newBranches, CommentTracker ct, boolean isExpr) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(statementToReplace.getProject()); if (!(statementToReplace instanceof PsiSwitchStatement)) return null; PsiCodeBlock body = ((PsiSwitchStatement)statementToReplace).getBody(); if (body == null) return null; StringBuilder sb = new StringBuilder(); for (PsiElement e = statementToReplace.getFirstChild(); e != null && e != body; e = e.getNextSibling()) { sb.append(ct.text(e)); } PsiJavaToken lBrace = body.getLBrace(); sb.append(lBrace != null ? ct.textWithComments(lBrace) : "{"); for (SwitchBranch newBranch : newBranches) { sb.append(newBranch.generate(ct)); } PsiJavaToken rBrace = body.getRBrace(); sb.append(rBrace != null ? ct.textWithComments(rBrace) : "}"); PsiSwitchBlock switchBlock; if (isExpr) { switchBlock = (PsiSwitchBlock)factory.createExpressionFromText(sb.toString(), statementToReplace); } else { switchBlock = (PsiSwitchBlock)factory.createStatementFromText(sb.toString(), statementToReplace); } StreamEx.ofTree((PsiElement)switchBlock, block -> Arrays.stream(block.getChildren())) .select(PsiBreakStatement.class) .filter(breakStmt -> ControlFlowUtils.statementCompletesWithStatement(switchBlock, breakStmt) && breakStmt.findExitedStatement() == switchBlock) .forEach(statement -> new CommentTracker().delete(statement)); return switchBlock; }