PsiStatement (@NotNull Project project, @NotNull PsiElementFactory factory) { boolean then = PsiTreeUtil.isAncestor(myConditional.getThenExpression(), myExpression, false); SurroundResult upstreamResult = myUpstream.surround(); PsiConditionalExpression ternary = Objects.requireNonNull( (PsiConditionalExpression)PsiUtil.skipParenthesizedExprDown(upstreamResult.getExpression())); PsiElement parent = PsiUtil.skipParenthesizedExprUp(ternary.getParent()); PsiStatement statement = upstreamResult.getAnchor(); if (parent instanceof PsiLocalVariable variable) { variable.normalizeDeclaration(); PsiDeclarationStatement declaration = (PsiDeclarationStatement)variable.getParent(); PsiAssignmentExpression assignment = ExpressionUtils.splitDeclaration(declaration, project); if (assignment != null) { ternary = (PsiConditionalExpression)Objects.requireNonNull(PsiUtil.skipParenthesizedExprDown(assignment.getRExpression())); statement = (PsiStatement)assignment.getParent(); } } CommentTracker ct = new CommentTracker(); PsiIfStatement ifStatement = (PsiIfStatement)factory.createStatementFromText("if(" + ct.text(ternary.getCondition()) + ") {} else {}", statement); Object mark = new Object(); PsiTreeUtil.mark(ternary, mark); for (PsiElement child : statement.getChildren()) { if (child instanceof PsiComment) { ct.delete(child); } } PsiStatement thenStatement = (PsiStatement)statement.copy(); PsiConditionalExpression thenTernary = Objects.requireNonNull((PsiConditionalExpression)PsiTreeUtil.releaseMark(thenStatement, mark)); PsiExpression thenBranch = ternary.getThenExpression(); if (thenBranch != null) { thenTernary.replace(ct.markUnchanged(thenBranch)); } PsiStatement elseStatement = (PsiStatement)statement.copy(); PsiConditionalExpression elseTernary = Objects.requireNonNull((PsiConditionalExpression)PsiTreeUtil.releaseMark(elseStatement, mark)); PsiExpression elseBranch = ternary.getElseExpression(); if (elseBranch != null) { elseTernary.replace(ct.markUnchanged(elseBranch)); } ifStatement = (PsiIfStatement)ct.replaceAndRestoreComments(statement, ifStatement); thenStatement = (PsiStatement)((PsiBlockStatement)Objects.requireNonNull(ifStatement.getThenBranch())).getCodeBlock().add(thenStatement); elseStatement = (PsiStatement)((PsiBlockStatement)Objects.requireNonNull(ifStatement.getElseBranch())).getCodeBlock().add(elseStatement); return then ? thenStatement : elseStatement; }