diff --git a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java index 9c8cc5b5b..4aaba36d5 100644 --- a/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java +++ b/open-java-format-idea-plugin/src/test/java/com/palantir/javaformat/intellij/PalantirJavaFormatConfigurableTest.java @@ -108,7 +108,7 @@ private static Optional findCheckBox(Component root) { if (root instanceof Container container) { return Arrays.stream(container.getComponents()) .map(PalantirJavaFormatConfigurableTest::findCheckBox) - .flatMap(Optional::stream) + .mapMulti(Optional::ifPresent) .findFirst(); } return Optional.empty(); diff --git a/open-java-format-spi/src/main/java/com/palantir/javaformat/java/Replacement.java b/open-java-format-spi/src/main/java/com/palantir/javaformat/java/Replacement.java index e3ae489f5..1140a441f 100644 --- a/open-java-format-spi/src/main/java/com/palantir/javaformat/java/Replacement.java +++ b/open-java-format-spi/src/main/java/com/palantir/javaformat/java/Replacement.java @@ -57,8 +57,7 @@ public boolean equals(Object o) { if (o == this) { return true; } - if (o instanceof Replacement) { - Replacement that = (Replacement) o; + if (o instanceof Replacement that) { return replaceRange.equals(that.getReplaceRange()) && replacementString.equals(that.getReplacementString()); } return false; diff --git a/open-java-format/src/main/java/com/palantir/javaformat/Newlines.java b/open-java-format/src/main/java/com/palantir/javaformat/Newlines.java index e87119af4..73b03ce73 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/Newlines.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/Newlines.java @@ -71,15 +71,16 @@ public static String guessLineSeparator(String text) { for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); switch (c) { - case '\r': + case '\r' -> { if (i + 1 < text.length() && text.charAt(i + 1) == '\n') { return "\r\n"; } return "\r"; - case '\n': + } + case '\n' -> { return "\n"; - default: - break; + } + default -> {} } } return "\n"; diff --git a/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java b/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java index 322242c8a..f61321788 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/OpsBuilder.java @@ -149,10 +149,10 @@ public Optional wanted(State state) { @Override public BlankLineWanted merge(BlankLineWanted other) { - if (!(other instanceof ConditionalBlankLine)) { + if (!(other instanceof ConditionalBlankLine conditionalBlankLine)) { return other; } - return new ConditionalBlankLine(Iterables.concat(this.tags, ((ConditionalBlankLine) other).tags)); + return new ConditionalBlankLine(Iterables.concat(this.tags, conditionalBlankLine.tags)); } } } @@ -522,13 +522,12 @@ public OpsOutput build() { int opsN = ops.size(); for (int i = 0; i < opsN; i++) { Op op = ops.get(i); - if (op instanceof Token) { + if (op instanceof Token tokenOp) { /* * Token ops can have associated non-tokens, including comments, which we need to insert. * They can also cause line breaks, so we insert them before or after the current level, * when possible. */ - Token tokenOp = (Token) op; Input.Token token = tokenOp.getToken(); int j = i; // Where to insert toksBefore before. while (0 < j && ops.get(j - 1) instanceof OpenOp) { @@ -654,9 +653,9 @@ public OpsOutput build() { Op op = ops.get(i); if (afterForcedBreak && (op instanceof NonBreakingSpace - || (op instanceof Break - && ((Break) op).evalPlusIndent(State.startingState()) == 0 - && " ".equals(((Doc) op).getFlat())))) { + || (op instanceof Break b + && b.evalPlusIndent(State.startingState()) == 0 + && " ".equals(b.getFlat())))) { continue; } newOps.add(op); @@ -681,7 +680,7 @@ private static boolean isNonNlsComment(Input.Tok tokAfter) { } private static boolean isForcedBreak(Op op) { - return op instanceof Break && ((Break) op).isForced(); + return op instanceof Break b && b.isForced(); } private static List makeComment(Input.Tok comment) { diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/DocVisitor.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/DocVisitor.java index 3d2d6ade7..89b82d92d 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/DocVisitor.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/DocVisitor.java @@ -18,16 +18,16 @@ public interface DocVisitor { default T visit(Doc doc) { - if (doc instanceof Level) { - return visitLevel((Level) doc); - } else if (doc instanceof Break) { - return visitBreak((Break) doc); - } else if (doc instanceof Token) { - return visitToken((Token) doc); - } else if (doc instanceof Comment) { - return visitComment((Comment) doc); - } else if (doc instanceof NonBreakingSpace) { - return visitSpace((NonBreakingSpace) doc); + if (doc instanceof Level level) { + return visitLevel(level); + } else if (doc instanceof Break b) { + return visitBreak(b); + } else if (doc instanceof Token token) { + return visitToken(token); + } else if (doc instanceof Comment comment) { + return visitComment(comment); + } else if (doc instanceof NonBreakingSpace space) { + return visitSpace(space); } throw new RuntimeException(); } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java index 4c3b27e0d..90f9df610 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java @@ -148,12 +148,11 @@ private Optional tryToFitOnOneLine(int maxWidth, State state, Iterable< int column = state.column(); int columnBeforeLastBreak = 0; // Not activated by default for (Doc doc : docs) { - if (doc instanceof Break && ((Break) doc).hasColumnLimit()) { + if (doc instanceof Break b && b.hasColumnLimit()) { columnBeforeLastBreak = column; - } else if (doc instanceof Level) { + } else if (doc instanceof Level innerLevel) { // Levels might have nested levels that have a 'columnLimitBeforeLastBreak' set, so recurse. State newState = state.withColumn(column); - Level innerLevel = (Level) doc; Optional newWidth = innerLevel.tryToFitOnOneLine(maxWidth, newState, innerLevel.getDocs()); if (!newWidth.isPresent()) { return Optional.empty(); @@ -571,10 +570,10 @@ private static Optional tryBreakInnerLevel_checkInner( } Level lastLevel2 = ((Level) getLast(innerLevel.docs)); switch (lastLevel2.getBreakabilityIfLastLevel()) { - case ABORT: - case CHECK_INNER: + case ABORT, CHECK_INNER -> { return Optional.empty(); - case ACCEPT_INLINE_CHAIN: + } + case ACCEPT_INLINE_CHAIN -> { Exploration broken = innerLevel.breakNormally(state, levelNode, commentsHelper, maxWidth); return innerLevel.handle_breakOnlyIfInnerLevelsThenFitOnOneLine( @@ -584,11 +583,13 @@ private static Optional tryBreakInnerLevel_checkInner( broken.state(), keepIndentWhenInlined, explorationNode); - case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER: + } + case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER -> { // specific to lambda body expressions - falls back to `breakNormally` in // `preferBreakingLastInnerLevel` return Optional.empty(); - default: + } + default -> throw new RuntimeException("Unknown breakabilityIfLastLevel: " + lastLevel2); } }) @@ -633,10 +634,10 @@ private static SplitsBreaks splitByBreaks(List docs) { ImmutableSplitsBreaks.Builder builder = ImmutableSplitsBreaks.builder(); ImmutableList.Builder currentSplit = ImmutableList.builder(); for (Doc doc : docs) { - if (doc instanceof Break) { + if (doc instanceof Break b) { builder.addSplits(currentSplit.build()); currentSplit = ImmutableList.builder(); - builder.addBreaks((Break) doc); + builder.addBreaks(b); } else { currentSplit.add(doc); } @@ -790,8 +791,7 @@ private int getMaxDepth() { private int computeMaxDepth(Iterable docs) { int maxChildDepth = 0; for (Doc doc : docs) { - if (doc instanceof Level) { - Level childLevel = (Level) doc; + if (doc instanceof Level childLevel) { maxChildDepth = Math.max(maxChildDepth, childLevel.getMaxDepth()); } } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/CommandLineOptionsParser.java b/open-java-format/src/main/java/com/palantir/javaformat/java/CommandLineOptionsParser.java index 6e4dac004..7a1dd0a36 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/CommandLineOptionsParser.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/CommandLineOptionsParser.java @@ -79,83 +79,30 @@ static CommandLineOptions parse(Iterable options) { } // NOTE: update usage information in UsageException when new flags are added switch (flag) { - case "-i": - case "-r": - case "-replace": - case "--replace": - optionsBuilder.inPlace(true); - break; - case "--lines": - case "-lines": - case "--line": - case "-line": + case "-i", "-r", "-replace", "--replace" -> optionsBuilder.inPlace(true); + case "--lines", "-lines", "--line", "-line" -> parseRangeSet(optionsBuilder.linesBuilder(), getValue(flag, it, value)); - break; - case "--character-ranges": - case "-character-ranges": - case "--character-range": - case "-character-range": + case "--character-ranges", "-character-ranges", "--character-range", "-character-range" -> parseCharacterRanges(optionsBuilder.characterRangesBuilder(), getValue(flag, it, value)); - break; - case "--offset": - case "-offset": - optionsBuilder.addOffset(parseInteger(it, flag, value)); - break; - case "--length": - case "-length": - optionsBuilder.addLength(parseInteger(it, flag, value)); - break; - case "--aosp": - case "-aosp": - case "-a": - case "--ojf": - case "-ojf": + case "--offset", "-offset" -> optionsBuilder.addOffset(parseInteger(it, flag, value)); + case "--length", "-length" -> optionsBuilder.addLength(parseInteger(it, flag, value)); + case "--aosp", "-aosp", "-a", "--ojf", "-ojf" -> // There is one style. The old style flags are accepted so that a script keeps working, and // Main warns about each of them. optionsBuilder.addUnsupportedFlag(flag); - break; - case "--version": - case "-version": - case "-v": - optionsBuilder.version(true); - break; - case "--help": - case "-help": - case "-h": - optionsBuilder.help(true); - break; - case "--fix-imports-only": - optionsBuilder.fixImportsOnly(true); - break; - case "--skip-sorting-imports": - optionsBuilder.sortImports(false); - break; - case "--skip-removing-unused-imports": - optionsBuilder.removeUnusedImports(false); - break; - case "--skip-reflowing-long-strings": - optionsBuilder.reflowLongStrings(false); - break; - case "-": - optionsBuilder.stdin(true); - break; - case "-n": - case "--dry-run": - optionsBuilder.dryRun(true); - break; - case "--set-exit-if-changed": - optionsBuilder.setExitIfChanged(true); - break; - case "-assume-filename": - case "--assume-filename": + case "--version", "-version", "-v" -> optionsBuilder.version(true); + case "--help", "-help", "-h" -> optionsBuilder.help(true); + case "--fix-imports-only" -> optionsBuilder.fixImportsOnly(true); + case "--skip-sorting-imports" -> optionsBuilder.sortImports(false); + case "--skip-removing-unused-imports" -> optionsBuilder.removeUnusedImports(false); + case "--skip-reflowing-long-strings" -> optionsBuilder.reflowLongStrings(false); + case "-" -> optionsBuilder.stdin(true); + case "-n", "--dry-run" -> optionsBuilder.dryRun(true); + case "--set-exit-if-changed" -> optionsBuilder.setExitIfChanged(true); + case "-assume-filename", "--assume-filename" -> optionsBuilder.assumeFilename(getValue(flag, it, value)); - break; - case "-output-replacements": - case "--output-replacements": - optionsBuilder.outputReplacements(true); - break; - default: - throw new IllegalArgumentException("unexpected flag: " + flag); + case "-output-replacements", "--output-replacements" -> optionsBuilder.outputReplacements(true); + default -> throw new IllegalArgumentException("unexpected flag: " + flag); } } return optionsBuilder.build(); @@ -196,15 +143,16 @@ private static void parseCharacterRanges(ImmutableRangeSet.Builder resu private static Range parseCharacterRange(String range) { List args = COLON_SPLITTER.splitToList(range); switch (args.size()) { - case 1: + case 1 -> { int lowerUpperRange = Integer.parseInt(args.get(0)); return Range.closed(lowerUpperRange, lowerUpperRange); - case 2: + } + case 2 -> { int lower = Integer.parseInt(args.get(0)); int higher = Integer.parseInt(args.get(1)); return Range.closed(lower, higher); - default: - throw new IllegalArgumentException(range); + } + default -> throw new IllegalArgumentException(range); } } @@ -226,15 +174,16 @@ private static void parseRangeSet(RangeSet result, String ranges) { private static Range parseRange(String arg) { List args = COLON_SPLITTER.splitToList(arg); switch (args.size()) { - case 1: + case 1 -> { int line = Integer.parseInt(args.get(0)) - 1; return Range.closedOpen(line, line + 1); - case 2: + } + case 2 -> { int line0 = Integer.parseInt(args.get(0)) - 1; int line1 = Integer.parseInt(args.get(1)) - 1; return Range.closedOpen(line0, line1 + 1); - default: - throw new IllegalArgumentException(arg); + } + default -> throw new IllegalArgumentException(arg); } } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/DebugRenderer.java b/open-java-format/src/main/java/com/palantir/javaformat/java/DebugRenderer.java index 0b02212df..01cebd7f3 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/DebugRenderer.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/DebugRenderer.java @@ -61,8 +61,15 @@ static void render( String formatterDecisionsJson) { String javascript = String.format( - "window.palantirJavaFormat = {\njavaInput: %s,\nops: %s,\ndoc: %s,\njavaOutput: %s,\n" - + "formatterDecisions: %s\n};\n", + """ + window.palantirJavaFormat = { + javaInput: %s, + ops: %s, + doc: %s, + javaOutput: %s, + formatterDecisions: %s + }; + """, jsonEscapedString(javaInput.getText()), opsJson(opsOutput), new JsonDocVisitor(finalState).visit(doc), @@ -90,8 +97,7 @@ private static String opsJson(OpsOutput opsOutput) { ImmutableList ops = opsOutput.ops(); for (Op op : ops) { - if (op instanceof Token) { - Token token = (Token) op; + if (op instanceof Token token) { Input.Token inputToken = token.getToken(); ObjectNode json = arrayNode.addObject(); @@ -109,9 +115,7 @@ private static String opsJson(OpsOutput opsOutput) { .collect(Collectors.joining())); json.put("hue", computeHue(token)); } - if (op instanceof Break) { - Break breakOp = (Break) op; - + if (op instanceof Break breakOp) { ObjectNode json = arrayNode.addObject(); json.put("type", "break"); json.put("fillMode", breakOp.fillMode().toString()); diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/DimensionHelpers.java b/open-java-format/src/main/java/com/palantir/javaformat/java/DimensionHelpers.java index 6459b8f08..965be309f 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/DimensionHelpers.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/DimensionHelpers.java @@ -103,9 +103,10 @@ private static Iterable> reorderBySourcePosition(Deque> dims, Tree node) { switch (node.getKind()) { - case ARRAY_TYPE: + case ARRAY_TYPE -> { return extractDims(dims, ((ArrayTypeTree) node).getType()); - case ANNOTATED_TYPE: + } + case ANNOTATED_TYPE -> { AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node; if (!(annotatedTypeTree.getUnderlyingType() instanceof ArrayTypeTree)) { return node; @@ -113,8 +114,10 @@ private static Tree extractDims(Deque> dims, Tree node) { node = extractDims(dims, annotatedTypeTree.getUnderlyingType()); dims.addFirst(ImmutableList.copyOf(annotatedTypeTree.getAnnotations())); return node; - default: + } + default -> { return node; + } } } } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java b/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java index b6b78bfda..00952cd69 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java @@ -220,12 +220,12 @@ static boolean errorDiagnostic(Diagnostic input) { return false; } switch (input.getCode()) { - case "compiler.err.invalid.meth.decl.ret.type.req": + case "compiler.err.invalid.meth.decl.ret.type.req" -> { // accept constructor-like method declarations that don't match the name of their // enclosing class return false; - default: - break; + } + default -> {} } return true; } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/ImportOrderer.java b/open-java-format/src/main/java/com/palantir/javaformat/java/ImportOrderer.java index 873b56a01..3478db685 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/ImportOrderer.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/ImportOrderer.java @@ -257,13 +257,10 @@ boolean isAndroid() { /** True if this is a Java import per AOSP style. */ boolean isJava() { - switch (topLevel()) { - case "java": - case "javax": - return true; - default: - return false; - } + return switch (topLevel()) { + case "java", "javax" -> true; + default -> false; + }; } /** diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInput.java b/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInput.java index 87fbf5285..aba9e6a82 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInput.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInput.java @@ -543,20 +543,18 @@ private static ImmutableList buildTokens(List toks) { // TODO(cushon): find a better strategy. if (toks.get(k).isSlashStarComment()) { switch (tok.getText()) { - case "(": - case "<": - case ".": + case "(", "<", "." -> { break OUTER; - default: - break; + } + default -> {} } } if (toks.get(k).isJavadocComment()) { switch (tok.getText()) { - case ";": + case ";" -> { break OUTER; - default: - break; + } + default -> {} } } if (isParamComment(toks.get(k))) { diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInputAstVisitor.java b/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInputAstVisitor.java index 5f51b33ee..c49d89268 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInputAstVisitor.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/JavaInputAstVisitor.java @@ -413,18 +413,10 @@ protected void dropEmptyDeclarations() { @Override public Void visitClass(ClassTree tree, Void unused) { switch (tree.getKind()) { - case ANNOTATION_TYPE: - visitAnnotationType(tree); - break; - case CLASS: - case INTERFACE: - visitClassDeclaration(tree); - break; - case ENUM: - visitEnumDeclaration(tree); - break; - default: - throw new IllegalArgumentException(tree.getKind().name()); + case ANNOTATION_TYPE -> visitAnnotationType(tree); + case CLASS, INTERFACE -> visitClassDeclaration(tree); + case ENUM -> visitEnumDeclaration(tree); + default -> throw new IllegalArgumentException(tree.getKind().name()); } return null; } @@ -866,8 +858,7 @@ public boolean visitEnumDeclaration(ClassTree node) { ArrayList enumConstants = new ArrayList<>(); ArrayList members = new ArrayList<>(); for (Tree member : node.getMembers()) { - if (member instanceof JCTree.JCVariableDecl) { - JCTree.JCVariableDecl variableDecl = (JCTree.JCVariableDecl) member; + if (member instanceof JCTree.JCVariableDecl variableDecl) { if ((variableDecl.mods.flags & Flags.ENUM) == Flags.ENUM) { enumConstants.add(variableDecl); continue; @@ -950,14 +941,9 @@ public Void visitMemberReference(MemberReferenceTree node, Void unused) { builder.op("::"); addTypeArguments(node.getTypeArguments(), plusFour); switch (node.getMode()) { - case INVOKE: - visit(node.getName()); - break; - case NEW: - token("new"); - break; - default: - throw new IllegalArgumentException(node.getMode().name()); + case INVOKE -> visit(node.getName()); + case NEW -> token("new"); + default -> throw new IllegalArgumentException(node.getMode().name()); } builder.close(); builder.close(); @@ -1332,8 +1318,8 @@ public Void visitAnnotation(AnnotationTree node, Void unused) { builder.breakOp(" "); } } - if (argument instanceof AssignmentTree) { - visitAnnotationArgument((AssignmentTree) argument); + if (argument instanceof AssignmentTree assignmentTree) { + visitAnnotationArgument(assignmentTree); } else { scan(argument, null); } @@ -1353,11 +1339,11 @@ public Void visitAnnotation(AnnotationTree node, Void unused) { } private static boolean isArrayValue(ExpressionTree argument) { - if (!(argument instanceof AssignmentTree)) { + if (!(argument instanceof AssignmentTree assignmentTree)) { return false; } - ExpressionTree expression = ((AssignmentTree) argument).getExpression(); - return expression instanceof NewArrayTree && ((NewArrayTree) expression).getType() == null; + ExpressionTree expression = assignmentTree.getExpression(); + return expression instanceof NewArrayTree newArrayTree && newArrayTree.getType() == null; } public void visitAnnotationArgument(AssignmentTree node) { @@ -1383,8 +1369,7 @@ public void visitAnnotationArgument(AssignmentTree node) { public Void visitAnnotatedType(AnnotatedTypeTree node, Void unused) { sync(node); ExpressionTree base = node.getUnderlyingType(); - if (base instanceof MemberSelectTree) { - MemberSelectTree selectTree = (MemberSelectTree) base; + if (base instanceof MemberSelectTree selectTree) { scan(selectTree.getExpression(), null); token("."); visitAnnotations(node.getAnnotations(), BreakOrNot.NO, BreakOrNot.NO); @@ -1411,8 +1396,8 @@ public Void visitAnnotatedType(AnnotatedTypeTree node, Void unused) { /** Is {@code type} the implicit wrapper class javac synthesizes for a compact source file? */ private static boolean isCompactSourceFile(Tree type) { - return type instanceof JCTree.JCClassDecl - && (((JCTree.JCClassDecl) type).mods.flags & IMPLICIT_CLASS) == IMPLICIT_CLASS; + return type instanceof JCTree.JCClassDecl classDecl + && (classDecl.mods.flags & IMPLICIT_CLASS) == IMPLICIT_CLASS; } @SuppressWarnings("for-rollout:NullAway") @@ -1646,10 +1631,10 @@ private boolean handleLogStatement(MethodInvocationTree node) { private static List handleStream(List parts) { return indexes(parts.stream(), p -> { - if (!(p instanceof MethodInvocationTree)) { + if (!(p instanceof MethodInvocationTree methodInvocation)) { return false; } - Name name = getMethodName((MethodInvocationTree) p); + Name name = getMethodName(methodInvocation); return Stream.of("stream", "parallelStream", "toBuilder").anyMatch(name::contentEquals); }) .collect(toList()); @@ -1766,11 +1751,10 @@ private void splitToken(String operatorName) { private boolean ambiguousUnaryOperator(UnaryTree node, String operatorName) { switch (node.getKind()) { - case UNARY_MINUS: - case UNARY_PLUS: - break; - default: + case UNARY_MINUS, UNARY_PLUS -> {} + default -> { return false; + } } JCTree.Tag tag = unaryTag(node.getExpression()); if (tag == null) { @@ -1800,35 +1784,16 @@ && isUnaryMinusLiteral(getSourceForNode(expression, getCurrentPath()))) { public Void visitPrimitiveType(PrimitiveTypeTree node, Void unused) { sync(node); switch (node.getPrimitiveTypeKind()) { - case BOOLEAN: - token("boolean"); - break; - case BYTE: - token("byte"); - break; - case SHORT: - token("short"); - break; - case INT: - token("int"); - break; - case LONG: - token("long"); - break; - case CHAR: - token("char"); - break; - case FLOAT: - token("float"); - break; - case DOUBLE: - token("double"); - break; - case VOID: - token("void"); - break; - default: - throw new RuntimeException(node.getPrimitiveTypeKind().name()); + case BOOLEAN -> token("boolean"); + case BYTE -> token("byte"); + case SHORT -> token("short"); + case INT -> token("int"); + case LONG -> token("long"); + case CHAR -> token("char"); + case FLOAT -> token("float"); + case DOUBLE -> token("double"); + case VOID -> token("void"); + default -> throw new RuntimeException(node.getPrimitiveTypeKind().name()); } return null; } @@ -1976,8 +1941,7 @@ public Void visitTry(TryTree node, Void unused) { if (!first) { builder.forcedBreak(); } - if (resource instanceof VariableTree) { - VariableTree variableTree = (VariableTree) resource; + if (resource instanceof VariableTree variableTree) { declareOne( DeclarationKind.PARAMETER, inlineAnnotationDirection(variableTree.getModifiers()), @@ -2213,15 +2177,16 @@ private void visitStatement( AllowTrailingBlankLine allowTrailingBlank) { sync(node); switch (node.getKind()) { - case BLOCK: + case BLOCK -> { builder.space(); visitBlock((BlockTree) node, collapseEmptyOrNot, allowLeadingBlank, allowTrailingBlank); - break; - default: + } + default -> { builder.open(plusTwo); builder.breakOp(" "); scan(node, null); builder.close(); + } } } @@ -2352,26 +2317,24 @@ private List visitModifiers( } boolean nextIsModifier() { - switch (builder.peekToken().get()) { - case "public": - case "protected": - case "private": - case "abstract": - case "static": - case "final": - case "transient": - case "volatile": - case "synchronized": - case "native": - case "strictfp": - case "default": - case "sealed": - case "non": - case "-": - return true; - default: - return false; - } + return switch (builder.peekToken().get()) { + case "public", + "protected", + "private", + "abstract", + "static", + "final", + "transient", + "volatile", + "synchronized", + "native", + "strictfp", + "default", + "sealed", + "non", + "-" -> true; + default -> false; + }; } @Override @@ -2446,8 +2409,7 @@ private void visitUnionType(VariableTree declaration) { /** Accumulate the operands and operators. */ private static void walkInfix( int precedence, ExpressionTree expression, List operands, List operators) { - if (expression instanceof BinaryTree) { - BinaryTree binaryTree = (BinaryTree) expression; + if (expression instanceof BinaryTree binaryTree) { if (precedence(binaryTree) == precedence) { walkInfix(precedence, binaryTree.getLeftOperand(), operands, operators); operators.add(operatorName(expression)); @@ -2756,21 +2718,19 @@ void visitDot(ExpressionTree node0) { node = getArrayBase(node); } switch (node.getKind()) { - case MEMBER_SELECT: - node = ((MemberSelectTree) node).getExpression(); - break; - case METHOD_INVOCATION: - node = getMethodReceiver((MethodInvocationTree) node); - break; - case IDENTIFIER: + case MEMBER_SELECT -> node = ((MemberSelectTree) node).getExpression(); + case METHOD_INVOCATION -> node = getMethodReceiver((MethodInvocationTree) node); + case IDENTIFIER -> { node = null; break LOOP; - default: + } + default -> { // If the dot chain starts with a primary expression // (e.g. a class instance creation, or a conditional expression) // then remove it from the list and deal with it first. node = stack.removeFirst(); break LOOP; + } } } while (node != null); List items = new ArrayList<>(stack); @@ -2868,12 +2828,8 @@ void visitDot(ExpressionTree node0) { if (prefixes.isEmpty() && items.get(0) instanceof IdentifierTree) { switch (((IdentifierTree) items.get(0)).getName().toString()) { - case "this": - case "super": - prefixes.add(1); - break; - default: - break; + case "this", "super" -> prefixes.add(1); + default -> {} } } @@ -2958,10 +2914,9 @@ private boolean fillFirstArgument(ExpressionTree e, List items, return false; } // don't special-case calls nested inside expressions - if (!(e instanceof MethodInvocationTree)) { + if (!(e instanceof MethodInvocationTree methodInvocation)) { return false; } - MethodInvocationTree methodInvocation = (MethodInvocationTree) e; Name name = getMethodName(methodInvocation); if (!(methodInvocation.getMethodSelect() instanceof IdentifierTree) || name.length() > 4 @@ -3076,19 +3031,19 @@ private List simpleNames(Deque stack) { boolean isArray = expression instanceof ArrayAccessTree; expression = getArrayBase(expression); switch (expression.getKind()) { - case MEMBER_SELECT: + case MEMBER_SELECT -> simpleNames.add( ((MemberSelectTree) expression).getIdentifier().toString()); - break; - case IDENTIFIER: + case IDENTIFIER -> simpleNames.add(((IdentifierTree) expression).getName().toString()); - break; - case METHOD_INVOCATION: + case METHOD_INVOCATION -> { simpleNames.add( getMethodName((MethodInvocationTree) expression).toString()); break OUTER; - default: + } + default -> { break OUTER; + } } if (isArray) { break OUTER; @@ -3100,11 +3055,11 @@ private List simpleNames(Deque stack) { private void dotExpressionUpToArgs(ExpressionTree expression, Optional tyargTag) { expression = getArrayBase(expression); switch (expression.getKind()) { - case MEMBER_SELECT: + case MEMBER_SELECT -> { MemberSelectTree fieldAccess = (MemberSelectTree) expression; visit(fieldAccess.getIdentifier()); - break; - case METHOD_INVOCATION: + } + case METHOD_INVOCATION -> { MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; if (!methodInvocation.getTypeArguments().isEmpty()) { builder.open(plusFour); @@ -3114,13 +3069,9 @@ private void dotExpressionUpToArgs(ExpressionTree expression, Optional builder.close(); } visit(getMethodName(methodInvocation)); - break; - case IDENTIFIER: - visit(((IdentifierTree) expression).getName()); - break; - default: - scan(expression, null); - break; + } + case IDENTIFIER -> visit(((IdentifierTree) expression).getName()); + default -> scan(expression, null); } } @@ -3135,14 +3086,14 @@ private ExpressionTree getArrayBase(ExpressionTree node) { @SuppressWarnings("for-rollout:NullAway") private ExpressionTree getMethodReceiver(MethodInvocationTree methodInvocation) { ExpressionTree select = methodInvocation.getMethodSelect(); - return select instanceof MemberSelectTree ? ((MemberSelectTree) select).getExpression() : null; + return select instanceof MemberSelectTree memberSelectTree ? memberSelectTree.getExpression() : null; } private void dotExpressionArgsAndParen(ExpressionTree expression, Indent tyargIndent, Indent indent) { Deque indices = getArrayIndices(expression); expression = getArrayBase(expression); switch (expression.getKind()) { - case METHOD_INVOCATION: + case METHOD_INVOCATION -> { // Note: we don't BREAK_HERE because we want to make sure that the last argument is actually // breakable in a way we prefer. builder.open(OpenOp.builder() @@ -3154,9 +3105,8 @@ private void dotExpressionArgsAndParen(ExpressionTree expression, Indent tyargIn MethodInvocationTree methodInvocation = (MethodInvocationTree) expression; addArguments(methodInvocation.getArguments(), indent); builder.close(); - break; - default: - break; + } + default -> {} } formatArrayIndices(indices); } @@ -3340,14 +3290,9 @@ public void scan(JCTree tree) { return; } switch (tree.getKind()) { - case STRING_LITERAL: - stringConcat[0] = true; - break; - case PLUS: - super.scan(tree); - break; - default: - break; + case STRING_LITERAL -> stringConcat[0] = true; + case PLUS -> super.scan(tree); + default -> {} } } }.scan((JCTree) first); @@ -3364,14 +3309,9 @@ public void scan(JCTree tree) { return; } switch (tree.getKind()) { - case STRING_LITERAL: - break; - case PLUS: - super.scan(tree); - break; - default: - stringLiteral[0] = false; - break; + case STRING_LITERAL -> {} + case PLUS -> super.scan(tree); + default -> stringLiteral[0] = false; } if (tree.getKind() == STRING_LITERAL) { Object value = ((LiteralTree) tree).getValue(); @@ -3453,11 +3393,10 @@ private int argumentsAreTabular(List arguments) { static int rowLength(List row) { int size = 0; for (ExpressionTree tree : row) { - if (!(tree instanceof NewArrayTree)) { + if (!(tree instanceof NewArrayTree array)) { size++; continue; } - NewArrayTree array = (NewArrayTree) tree; if (array.getInitializers() == null) { size++; continue; @@ -3656,7 +3595,7 @@ int declareOne( if (initializer.isPresent()) { builder.space(); token(equals); - if (initializer.get() instanceof NewArrayTree && ((NewArrayTree) initializer.get()).getType() == null) { + if (initializer.get() instanceof NewArrayTree newArrayTree && newArrayTree.getType() == null) { builder.open(minusFour); builder.space(); initializer.get().accept(this, null); @@ -3712,7 +3651,7 @@ private void maybeAddDims(Deque dimExpressions, Deque { if (annotations.isEmpty()) { return; } @@ -3723,8 +3662,8 @@ private void maybeAddDims(Deque dimExpressions, Deque { if (lastWasAnnotation) { builder.breakToFill(" "); } else { @@ -3736,8 +3675,8 @@ private void maybeAddDims(Deque dimExpressions, Deque { if (!builder.peekToken().get().equals(".") || !builder.peekToken(1).get().equals(".")) { return; @@ -3749,9 +3688,10 @@ private void maybeAddDims(Deque dimExpressions, Deque { return; + } } } } @@ -3919,9 +3859,9 @@ private void classDeclarationTypeList(String token, List types) */ private List variableFragments(PeekingIterator it, Tree first) { List fragments = new ArrayList<>(); - if (first instanceof VariableTree) { + if (first instanceof VariableTree variableTree) { int start = getStartPosition(first); - fragments.add((VariableTree) first); + fragments.add(variableTree); while (it.hasNext() && it.peek() instanceof VariableTree && getStartPosition(it.peek()) == start) { fragments.add((VariableTree) it.next()); } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/ModifierOrderer.java b/open-java-format/src/main/java/com/palantir/javaformat/java/ModifierOrderer.java index e59bf115c..996ff849e 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/ModifierOrderer.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/ModifierOrderer.java @@ -213,39 +213,49 @@ private static Modifier asModifier(Token token) { TokenKind kind = ((JavaInput.Tok) token.getTok()).kind(); if (kind != null) { switch (kind) { - case PUBLIC: + case PUBLIC -> { return Modifier.PUBLIC; - case PROTECTED: + } + case PROTECTED -> { return Modifier.PROTECTED; - case PRIVATE: + } + case PRIVATE -> { return Modifier.PRIVATE; - case ABSTRACT: + } + case ABSTRACT -> { return Modifier.ABSTRACT; - case STATIC: + } + case STATIC -> { return Modifier.STATIC; - case DEFAULT: + } + case DEFAULT -> { return Modifier.DEFAULT; - case FINAL: + } + case FINAL -> { return Modifier.FINAL; - case TRANSIENT: + } + case TRANSIENT -> { return Modifier.TRANSIENT; - case VOLATILE: + } + case VOLATILE -> { return Modifier.VOLATILE; - case SYNCHRONIZED: + } + case SYNCHRONIZED -> { return Modifier.SYNCHRONIZED; - case NATIVE: + } + case NATIVE -> { return Modifier.NATIVE; - case STRICTFP: + } + case STRICTFP -> { return Modifier.STRICTFP; - default: // fall out + } + default -> {} } } - switch (token.getTok().getText()) { - case "sealed": - return Modifier.valueOf("SEALED"); - default: - return null; - } + return switch (token.getTok().getText()) { + case "sealed" -> Modifier.valueOf("SEALED"); + default -> null; + }; } /** Applies replacements to the given string. */ diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java b/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java index 80337879f..28c954f19 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/StringWrapper.java @@ -194,8 +194,8 @@ public Void visitLiteral(LiteralTree literalTree, Void aVoid) { return null; } Tree parent = getCurrentPath().getParentPath().getLeaf(); - if (parent instanceof MemberSelectTree - && ((MemberSelectTree) parent).getExpression().equals(literalTree)) { + if (parent instanceof MemberSelectTree memberSelectTree + && memberSelectTree.getExpression().equals(literalTree)) { return null; } int endPosition = getEndPosition(unit, literalTree); diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/Trees.java b/open-java-format/src/main/java/com/palantir/javaformat/java/Trees.java index 501561fc6..d7fd65e2b 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/Trees.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/Trees.java @@ -136,8 +136,8 @@ static String getSourceForNode(Tree node, TreePath path) { /** Returns the simple name of a (possibly qualified) method invocation expression. */ static Name getMethodName(MethodInvocationTree methodInvocation) { ExpressionTree select = methodInvocation.getMethodSelect(); - return select instanceof MemberSelectTree - ? ((MemberSelectTree) select).getIdentifier() + return select instanceof MemberSelectTree memberSelectTree + ? memberSelectTree.getIdentifier() : ((IdentifierTree) select).getName(); } @@ -145,7 +145,7 @@ static Name getMethodName(MethodInvocationTree methodInvocation) { @SuppressWarnings("for-rollout:NullAway") static ExpressionTree getMethodReceiver(MethodInvocationTree methodInvocation) { ExpressionTree select = methodInvocation.getMethodSelect(); - return select instanceof MemberSelectTree ? ((MemberSelectTree) select).getExpression() : null; + return select instanceof MemberSelectTree memberSelectTree ? memberSelectTree.getExpression() : null; } /** Returns the string name of an operator, including assignment and compound assignment. */ @@ -171,13 +171,10 @@ static int precedence(ExpressionTree expression) { static ClassTree getEnclosingTypeDeclaration(TreePath path) { for (; path != null; path = path.getParentPath()) { switch (path.getLeaf().getKind()) { - case CLASS: - case ENUM: - case INTERFACE: - case ANNOTATED_TYPE: + case CLASS, ENUM, INTERFACE, ANNOTATED_TYPE -> { return (ClassTree) path.getLeaf(); - default: - break; + } + default -> {} } } throw new IllegalStateException(); diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/TypeNameClassifier.java b/open-java-format/src/main/java/com/palantir/javaformat/java/TypeNameClassifier.java index ccdd5e4b6..8780f73ca 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/TypeNameClassifier.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/TypeNameClassifier.java @@ -30,20 +30,17 @@ private enum TyParseState { START(false) { @Override public TyParseState next(JavaCaseFormat n) { - switch (n) { - case UPPERCASE: + return switch (n) { + case UPPERCASE -> // if we see an UpperCamel later, assume this was a class // e.g. com.google.FOO.Bar - return TyParseState.AMBIGUOUS; - case LOWER_CAMEL: - return TyParseState.REJECT; - case LOWERCASE: + TyParseState.AMBIGUOUS; + case LOWER_CAMEL -> TyParseState.REJECT; + case LOWERCASE -> // could be a package - return TyParseState.START; - case UPPER_CAMEL: - return TyParseState.TYPE; - } - throw new IllegalStateException(); + TyParseState.START; + case UPPER_CAMEL -> TyParseState.TYPE; + }; } }, @@ -51,15 +48,10 @@ public TyParseState next(JavaCaseFormat n) { TYPE(true) { @Override public TyParseState next(JavaCaseFormat n) { - switch (n) { - case UPPERCASE: - case LOWER_CAMEL: - case LOWERCASE: - return TyParseState.FIRST_STATIC_MEMBER; - case UPPER_CAMEL: - return TyParseState.TYPE; - } - throw new IllegalStateException(); + return switch (n) { + case UPPERCASE, LOWER_CAMEL, LOWERCASE -> TyParseState.FIRST_STATIC_MEMBER; + case UPPER_CAMEL -> TyParseState.TYPE; + }; } }, @@ -83,16 +75,11 @@ public TyParseState next(JavaCaseFormat n) { AMBIGUOUS(false) { @Override public TyParseState next(JavaCaseFormat n) { - switch (n) { - case UPPERCASE: - return AMBIGUOUS; - case LOWER_CAMEL: - case LOWERCASE: - return TyParseState.REJECT; - case UPPER_CAMEL: - return TyParseState.TYPE; - } - throw new IllegalStateException(); + return switch (n) { + case UPPERCASE -> AMBIGUOUS; + case LOWER_CAMEL, LOWERCASE -> TyParseState.REJECT; + case UPPER_CAMEL -> TyParseState.TYPE; + }; } }; diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/java14/Java14InputAstVisitor.java b/open-java-format/src/main/java/com/palantir/javaformat/java/java14/Java14InputAstVisitor.java index 5a8f9938e..746a8e2be 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/java14/Java14InputAstVisitor.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/java14/Java14InputAstVisitor.java @@ -160,21 +160,11 @@ public Void visitSwitchExpression(SwitchExpressionTree node, Void unused) { @Override public Void visitClass(ClassTree tree, Void unused) { switch (tree.getKind()) { - case ANNOTATION_TYPE: - visitAnnotationType(tree); - break; - case CLASS: - case INTERFACE: - visitClassDeclaration(tree); - break; - case ENUM: - visitEnumDeclaration(tree); - break; - case RECORD: - visitRecordDeclaration(tree); - break; - default: - throw new IllegalArgumentException(tree.getKind().name()); + case ANNOTATION_TYPE -> visitAnnotationType(tree); + case CLASS, INTERFACE -> visitClassDeclaration(tree); + case ENUM -> visitEnumDeclaration(tree); + case RECORD -> visitRecordDeclaration(tree); + default -> throw new IllegalArgumentException(tree.getKind().name()); } return null; } @@ -305,7 +295,7 @@ public Void visitCase(CaseTree node, Void unused) { } switch (node.getCaseKind()) { - case STATEMENT: + case STATEMENT -> { token(":"); boolean isBlock = node.getStatements().size() == 1 && node.getStatements().get(0) instanceof BlockTree; @@ -315,8 +305,8 @@ public Void visitCase(CaseTree node, Void unused) { } visitStatements(node.getStatements(), isBlock); builder.close(); - break; - case RULE: + } + case RULE -> { builder.open(plusTwo); builder.space(); token("-"); @@ -336,9 +326,8 @@ public Void visitCase(CaseTree node, Void unused) { builder.close(); } builder.guessToken(";"); - break; - default: - throw new IllegalArgumentException(node.getCaseKind().name()); + } + default -> throw new IllegalArgumentException(node.getCaseKind().name()); } return null; } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/javadoc/JavadocFormatter.java b/open-java-format/src/main/java/com/palantir/javaformat/java/javadoc/JavadocFormatter.java index 44eff1642..1bc7530ba 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/javadoc/JavadocFormatter.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/javadoc/JavadocFormatter.java @@ -60,90 +60,36 @@ private String render(List input, int blockIndent) { JavadocWriter output = new JavadocWriter(blockIndent, maxLineLength); for (Token token : input) { switch (token.getType()) { - case BEGIN_JAVADOC: - output.writeBeginJavadoc(); - break; - case END_JAVADOC: + case BEGIN_JAVADOC -> output.writeBeginJavadoc(); + case END_JAVADOC -> { output.writeEndJavadoc(); return output.toString(); - case FOOTER_JAVADOC_TAG_START: - output.writeFooterJavadocTagStart(token); - break; - case SNIPPET_BEGIN: - output.writeSnippetBegin(token); - break; - case SNIPPET_END: - output.writeSnippetEnd(token); - break; - case LIST_OPEN_TAG: - output.writeListOpen(token); - break; - case LIST_CLOSE_TAG: - output.writeListClose(token); - break; - case LIST_ITEM_OPEN_TAG: - output.writeListItemOpen(token); - break; - case HEADER_OPEN_TAG: - output.writeHeaderOpen(token); - break; - case HEADER_CLOSE_TAG: - output.writeHeaderClose(token); - break; - case PARAGRAPH_OPEN_TAG: - output.writeParagraphOpen(standardizePToken(token)); - break; - case BLOCKQUOTE_OPEN_TAG: - case BLOCKQUOTE_CLOSE_TAG: - output.writeBlockquoteOpenOrClose(token); - break; - case PRE_OPEN_TAG: - output.writePreOpen(token); - break; - case PRE_CLOSE_TAG: - output.writePreClose(token); - break; - case CODE_OPEN_TAG: - output.writeCodeOpen(token); - break; - case CODE_CLOSE_TAG: - output.writeCodeClose(token); - break; - case TABLE_OPEN_TAG: - output.writeTableOpen(token); - break; - case TABLE_CLOSE_TAG: - output.writeTableClose(token); - break; - case MOE_BEGIN_STRIP_COMMENT: - output.requestMoeBeginStripComment(token); - break; - case MOE_END_STRIP_COMMENT: - output.writeMoeEndStripComment(token); - break; - case HTML_COMMENT: - output.writeHtmlComment(token); - break; - case BR_TAG: - output.writeBr(standardizeBrToken(token)); - break; - case WHITESPACE: - output.requestWhitespace(); - break; - case FORCED_NEWLINE: - output.writeLineBreakNoAutoIndent(); - break; - case LITERAL: - case INLINE_TAG_OPEN: - case INLINE_TAG_CLOSE: - output.writeLiteral(token); - break; - case PARAGRAPH_CLOSE_TAG: - case LIST_ITEM_CLOSE_TAG: - case OPTIONAL_LINE_BREAK: - break; - default: - throw new IllegalArgumentException(token.getType().name()); + } + case FOOTER_JAVADOC_TAG_START -> output.writeFooterJavadocTagStart(token); + case SNIPPET_BEGIN -> output.writeSnippetBegin(token); + case SNIPPET_END -> output.writeSnippetEnd(token); + case LIST_OPEN_TAG -> output.writeListOpen(token); + case LIST_CLOSE_TAG -> output.writeListClose(token); + case LIST_ITEM_OPEN_TAG -> output.writeListItemOpen(token); + case HEADER_OPEN_TAG -> output.writeHeaderOpen(token); + case HEADER_CLOSE_TAG -> output.writeHeaderClose(token); + case PARAGRAPH_OPEN_TAG -> output.writeParagraphOpen(standardizePToken(token)); + case BLOCKQUOTE_OPEN_TAG, BLOCKQUOTE_CLOSE_TAG -> output.writeBlockquoteOpenOrClose(token); + case PRE_OPEN_TAG -> output.writePreOpen(token); + case PRE_CLOSE_TAG -> output.writePreClose(token); + case CODE_OPEN_TAG -> output.writeCodeOpen(token); + case CODE_CLOSE_TAG -> output.writeCodeClose(token); + case TABLE_OPEN_TAG -> output.writeTableOpen(token); + case TABLE_CLOSE_TAG -> output.writeTableClose(token); + case MOE_BEGIN_STRIP_COMMENT -> output.requestMoeBeginStripComment(token); + case MOE_END_STRIP_COMMENT -> output.writeMoeEndStripComment(token); + case HTML_COMMENT -> output.writeHtmlComment(token); + case BR_TAG -> output.writeBr(standardizeBrToken(token)); + case WHITESPACE -> output.requestWhitespace(); + case FORCED_NEWLINE -> output.writeLineBreakNoAutoIndent(); + case LITERAL, INLINE_TAG_OPEN, INLINE_TAG_CLOSE -> output.writeLiteral(token); + case PARAGRAPH_CLOSE_TAG, LIST_ITEM_CLOSE_TAG, OPTIONAL_LINE_BREAK -> {} + default -> throw new IllegalArgumentException(token.getType().name()); } } throw new IllegalStateException(); diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/ModuleImportTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/ModuleImportTest.java index 269c98b07..9284f84a7 100644 --- a/open-java-format/src/test/java/com/palantir/javaformat/java/ModuleImportTest.java +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/ModuleImportTest.java @@ -49,17 +49,31 @@ private static void assertFormats(String input, String expected) throws Formatte @Test public void formatsAndFixesImports() throws FormatterException { - String input = "import module java.base;\n" + "class Example {}\n"; - String expected = "import module java.base;\n" + "\n" + "class Example {}\n"; + String input = """ + import module java.base; + class Example {} + """; + String expected = """ + import module java.base; + + class Example {} + """; assertFormats(input, expected); } @Test public void fixesImportsOnlyFromTheCommandLine() throws Exception { // The flag combination from the #1506 report, which failed with `Expected ; after import`. - String input = "import module java.base;\n" + "class Example {}\n"; + String input = """ + import module java.base; + class Example {} + """; // Reordering puts a blank line after the import block; nothing else changes. - String expected = "import module java.base;\n" + "\n" + "class Example {}\n"; + String expected = """ + import module java.base; + + class Example {} + """; StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main( @@ -74,50 +88,88 @@ public void fixesImportsOnlyFromTheCommandLine() throws Exception { @Test public void keepsACommentBetweenModuleAndTheModuleName() throws FormatterException { - String input = "import module /* comment */ java.base;\n" + "class Example {}\n"; - String expected = "import module /* comment */ java.base;\n" + "\n" + "class Example {}\n"; + String input = """ + import module /* comment */ java.base; + class Example {} + """; + String expected = """ + import module /* comment */ java.base; + + class Example {} + """; assertFormats(input, expected); } @Test public void keepsACommentBetweenThePartsOfTheModuleName() throws FormatterException { - String input = "import module java./* comment */base;\n" + "class Example {}\n"; + String input = """ + import module java./* comment */base; + class Example {} + """; // Reordering normalizes the whitespace around the comment and leaves it between the parts. - String reordered = "import module java./* comment */ base;\n" + "\n" + "class Example {}\n"; + String reordered = """ + import module java./* comment */ base; + + class Example {} + """; assertThat(Formatter.create().fixImports(input)).isEqualTo(reordered); assertThat(Formatter.create().fixImports(reordered)).isEqualTo(reordered); // Formatting then breaks the line after the dot, which is where the formatter puts a comment // in a qualified name; that output is stable too. - String formatted = "import module java.\n" + "/* comment */ base;\n" + "\n" + "class Example {}\n"; + String formatted = """ + import module java. + /* comment */ base; + + class Example {} + """; assertThat(Formatter.create().formatSourceAndFixImports(input)).isEqualTo(formatted); assertThat(Formatter.create().formatSourceAndFixImports(formatted)).isEqualTo(formatted); } @Test public void normalizesWhitespaceInsideTheModuleName() throws FormatterException { - String input = "import module java . base;\n" + "class Example {}\n"; - String expected = "import module java.base;\n" + "\n" + "class Example {}\n"; + String input = """ + import module java . base; + class Example {} + """; + String expected = """ + import module java.base; + + class Example {} + """; assertFormats(input, expected); } @Test public void keepsBothCopiesOfADuplicateThatCarriesAComment() throws FormatterException { // Identical declarations collapse; ones that differ are both kept, so no comment is dropped. - String input = "import module /* explanation A */ java.base;\n" - + "import module /* explanation B */ java.base;\n" - + "class Example {}\n"; - String expected = "import module /* explanation A */ java.base;\n" - + "import module /* explanation B */ java.base;\n" - + "\n" - + "class Example {}\n"; + String input = """ + import module /* explanation A */ java.base; + import module /* explanation B */ java.base; + class Example {} + """; + String expected = """ + import module /* explanation A */ java.base; + import module /* explanation B */ java.base; + + class Example {} + """; assertFormats(input, expected); } @Test public void acceptsALineBreakAfterModule() throws FormatterException { - String input = "import module\n" + " java.base;\n" + "class Example {}\n"; - String expected = "import module java.base;\n" + "\n" + "class Example {}\n"; + String input = """ + import module + java.base; + class Example {} + """; + String expected = """ + import module java.base; + + class Example {} + """; assertFormats(input, expected); } }