PsiStatement () { PsiElement parent = myReturnStatement.getParent(); while (parent instanceof PsiCodeBlock) { PsiElement grandParent = parent.getParent(); if (!(grandParent instanceof PsiSwitchStatement)) { PsiStatement[] statements = ((PsiCodeBlock)parent).getStatements(); boolean afterReturn = false; for (PsiStatement statement : statements) { if (statement == myReturnStatement) { afterReturn = true; } else if (afterReturn) { // Unreachable statements after return (compilation error): remove them new CommentTracker().deleteAndRestoreComments(statement); } } } if (grandParent instanceof PsiBlockStatement) { parent = grandParent.getParent(); continue; } if (grandParent instanceof PsiCatchSection) { parent = grandParent.getParent(); break; } if (grandParent instanceof PsiStatement) { parent = grandParent; } else if (parent == myBlock) { // May happen for incorrect code return null; } else { throw new RuntimeExceptionWithAttachments("Unexpected structure: " + grandParent.getClass(), new Attachment("body.txt", myBlock.getText()), new Attachment("context.txt", grandParent.getText())); } break; } if (!(parent instanceof PsiStatement currentContext)) { throw new RuntimeExceptionWithAttachments("Unexpected structure: " + parent.getClass(), new Attachment("body.txt", myBlock.getText()), new Attachment("context.txt", parent.getText())); } PsiStatement loopOrSwitch = PsiTreeUtil.getNonStrictParentOfType(currentContext, PsiLoopStatement.class, PsiSwitchStatement.class); if (loopOrSwitch != null && PsiTreeUtil.isAncestor(myBlock, loopOrSwitch, true)) { myReplacements.add("break;"); return loopOrSwitch; } while (true) { if (currentContext instanceof PsiIfStatement ifStatement) { boolean inThen = PsiTreeUtil.isAncestor(ifStatement.getThenBranch(), myReturnStatement, false); PsiElement ifParent = currentContext.getParent(); if (ifParent instanceof PsiCodeBlock) { PsiCodeBlock resultBlock = swallowTail(currentContext, ifStatement, inThen, (PsiCodeBlock)ifParent); if (resultBlock != null && !ControlFlowUtils.codeBlockMayCompleteNormally(resultBlock) && ifParent.getParent() instanceof PsiBlockStatement && ifParent.getParent().getParent() instanceof PsiIfStatement) { currentContext = (PsiStatement)ifParent.getParent().getParent(); continue; } } } return currentContext; } }