|
| 1 | +/* |
| 2 | + * Copyright 2025 the original author or authors. |
| 3 | + * <p> |
| 4 | + * Licensed under the Moderne Source Available License (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * <p> |
| 8 | + * https://docs.moderne.io/licensing/moderne-source-available-license |
| 9 | + * <p> |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.openrewrite.java.migrate.lang; |
| 17 | + |
| 18 | +import lombok.EqualsAndHashCode; |
| 19 | +import lombok.Value; |
| 20 | +import org.openrewrite.*; |
| 21 | +import org.openrewrite.internal.ListUtils; |
| 22 | +import org.openrewrite.java.JavaIsoVisitor; |
| 23 | +import org.openrewrite.java.tree.Expression; |
| 24 | +import org.openrewrite.java.tree.J; |
| 25 | +import org.openrewrite.java.tree.Space; |
| 26 | +import org.openrewrite.java.tree.Statement; |
| 27 | +import org.openrewrite.staticanalysis.kotlin.KotlinFileChecker; |
| 28 | + |
| 29 | +import java.util.ArrayList; |
| 30 | +import java.util.HashSet; |
| 31 | +import java.util.List; |
| 32 | +import java.util.Set; |
| 33 | + |
| 34 | +import static java.util.Collections.singletonList; |
| 35 | +import static java.util.stream.Collectors.toSet; |
| 36 | +import static org.openrewrite.java.tree.J.Block.createEmptyBlock; |
| 37 | + |
| 38 | +@Value |
| 39 | +@EqualsAndHashCode(callSuper = false) |
| 40 | +public class RefineSwitchCases extends Recipe { |
| 41 | + @Override |
| 42 | + public String getDisplayName() { |
| 43 | + return "Use switch cases refinement when possible"; |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public String getDescription() { |
| 48 | + return "Use guarded switch case labels and guards if all the statements in the switch block do if/else if/else on the guarded label."; |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public TreeVisitor<?, ExecutionContext> getVisitor() { |
| 53 | + return Preconditions.check(Preconditions.not(new KotlinFileChecker<>()), new JavaIsoVisitor<ExecutionContext>() { |
| 54 | + @Override |
| 55 | + public J.Switch visitSwitch(J.Switch sw, ExecutionContext ctx) { |
| 56 | + J.Switch switch_ = super.visitSwitch(sw, ctx); |
| 57 | + J.Switch mappedSwitch = switch_.withCases(switch_.getCases() |
| 58 | + .withStatements(ListUtils.flatMap(switch_.getCases().getStatements(), statement -> { |
| 59 | + if (statement instanceof J.Case) { |
| 60 | + J.Case case_ = (J.Case) statement; |
| 61 | + if (!(case_.getBody() instanceof J.Block) || case_.getGuard() != null) { |
| 62 | + return statement; |
| 63 | + } |
| 64 | + List<Statement> caseStatements = ((J.Block) case_.getBody()).getStatements(); |
| 65 | + if (caseStatements.size() == 1 && caseStatements.get(0) instanceof J.If) { |
| 66 | + J.If if_ = (J.If) caseStatements.get(0); |
| 67 | + if (extractLabelVariables(case_) |
| 68 | + .containsAll(extractConditionVariables(if_.getIfCondition().getTree()))) { |
| 69 | + // Replace case with multiple cases |
| 70 | + return createGuardedCases(case_, if_); |
| 71 | + } |
| 72 | + } |
| 73 | + } |
| 74 | + return statement; |
| 75 | + }))); |
| 76 | + return new JavaIsoVisitor<ExecutionContext>() { |
| 77 | + @Override |
| 78 | + public J.Case visitCase(J.Case case_, ExecutionContext ctx) { |
| 79 | + // Remove any trailing new line in empty case body |
| 80 | + if (case_.getBody() instanceof J.Block) { |
| 81 | + J.Block body = (J.Block) case_.getBody(); |
| 82 | + if (body.getStatements().isEmpty() && !body.getEnd().isEmpty()) { |
| 83 | + return case_.withBody(body.withEnd(Space.EMPTY)); |
| 84 | + } |
| 85 | + } |
| 86 | + return case_; |
| 87 | + } |
| 88 | + }.visitSwitch(maybeAutoFormat(switch_, mappedSwitch, ctx), ctx); |
| 89 | + } |
| 90 | + |
| 91 | + private Set<String> extractLabelVariables(J.Case case_) { |
| 92 | + return case_.getCaseLabels().stream() |
| 93 | + .filter(J.VariableDeclarations.class::isInstance) |
| 94 | + .map(J.VariableDeclarations.class::cast) |
| 95 | + .map(J.VariableDeclarations::getVariables) |
| 96 | + .flatMap(List::stream) |
| 97 | + .map(J.VariableDeclarations.NamedVariable::getName) |
| 98 | + .map(J.Identifier::getSimpleName) |
| 99 | + .collect(toSet()); |
| 100 | + } |
| 101 | + |
| 102 | + private Set<String> extractConditionVariables(Expression expression) { |
| 103 | + return new JavaIsoVisitor<Set<String>>() { |
| 104 | + @Override |
| 105 | + public J.Identifier visitIdentifier(J.Identifier identifier, Set<String> identifiers) { |
| 106 | + identifiers.add(identifier.getSimpleName()); |
| 107 | + return super.visitIdentifier(identifier, identifiers); |
| 108 | + } |
| 109 | + |
| 110 | + @Override |
| 111 | + public J.MethodInvocation visitMethodInvocation(J.MethodInvocation method, Set<String> identifiers) { |
| 112 | + // Do not pull out method name as identifier, just any select and arguments |
| 113 | + super.visit(method.getSelect(), identifiers); |
| 114 | + method.getArguments().forEach(arg -> super.visit(arg, identifiers)); |
| 115 | + return method; |
| 116 | + } |
| 117 | + }.reduce(expression, new HashSet<>()); |
| 118 | + } |
| 119 | + |
| 120 | + private List<J.Case> createGuardedCases(J.Case case_, J.If if_) { |
| 121 | + if (case_.getBody() == null) { |
| 122 | + return singletonList(case_); |
| 123 | + } |
| 124 | + List<J.Case> cases = new ArrayList<>(); |
| 125 | + Statement caseBody = if_.getThenPart(); |
| 126 | + if (caseBody instanceof J.Block && ((J.Block) caseBody).getStatements().size() == 1) { |
| 127 | + caseBody = ((J.Block) caseBody).getStatements().get(0); |
| 128 | + } |
| 129 | + cases.add(case_.withId(Tree.randomId()).withGuard(if_.getIfCondition().getTree().withPrefix(Space.SINGLE_SPACE)).withBody(caseBody)); |
| 130 | + if (if_.getElsePart() == null) { |
| 131 | + if (case_.getBody() instanceof J.Block) { |
| 132 | + cases.add(case_.withBody(createEmptyBlock().withPrefix(Space.SINGLE_SPACE))); |
| 133 | + } |
| 134 | + } else if (if_.getElsePart().getBody() instanceof J.If) { |
| 135 | + cases.addAll(createGuardedCases(case_, (J.If) if_.getElsePart().getBody())); |
| 136 | + } else { |
| 137 | + cases.add(case_.withBody(if_.getElsePart().getBody())); |
| 138 | + } |
| 139 | + |
| 140 | + return cases; |
| 141 | + } |
| 142 | + }); |
| 143 | + } |
| 144 | +} |
0 commit comments