From 81aaab96cdde86e52863827b6bb09f5583707d89 Mon Sep 17 00:00:00 2001 From: Anthony Vanelverdinghe Date: Tue, 17 Dec 2019 17:07:16 -0800 Subject: [PATCH 01/46] Update outdated Javadoc links Fixes #409 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=286092096 --- core/pom.xml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index e85174f22..32bfca798 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -87,8 +87,8 @@ UTF-8 UTF-8 - https://google.github.io/guava/releases/${guava.version}/api/docs/ - https://javadoc.io/page/com.google.code.findbugs/jsr305/${jsr305.version}/ + https://guava.dev/releases/${guava.version}/api/docs/ + https://javadoc.io/static/com.google.code.findbugs/jsr305/${jsr305.version}/ https://docs.oracle.com/javase/8/docs/api/ From ed40e472878b9daa215787e6d27164bf2ec6f8ea Mon Sep 17 00:00:00 2001 From: cushon Date: Thu, 19 Dec 2019 14:46:50 -0800 Subject: [PATCH 02/46] Fix a crash on c-style arrays in parameters Fixes https://github.com/google/google-java-format/issues/374 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=286467734 --- .../googlejavaformat/java/JavaInputAstVisitor.java | 6 ++++-- .../com/google/googlejavaformat/java/testdata/I374.input | 9 +++++++++ .../google/googlejavaformat/java/testdata/I374.output | 9 +++++++++ 3 files changed, 22 insertions(+), 2 deletions(-) create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.output diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index c0f645654..b3f6e5ade 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -2542,18 +2542,20 @@ private void visitToDeclare( String equals, Optional trailing) { sync(node); + TypeWithDims extractedDims = DimensionHelpers.extractDims(node.getType(), SortedDims.YES); + Optional typeWithDims = Optional.of(extractedDims); declareOne( kind, annotationsDirection, Optional.of(node.getModifiers()), - node.getType(), + extractedDims.node, node.getName(), "", equals, initializer, trailing, /* receiverExpression= */ Optional.empty(), - /* typeWithDims= */ Optional.empty()); + typeWithDims); } /** Does not omit the leading '<', which should be associated with the type name. */ diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.input new file mode 100644 index 000000000..2364f0c16 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.input @@ -0,0 +1,9 @@ +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) +@interface MyTypeAnno {} + +public class GjfFailure { + void m(int a @MyTypeAnno []) {} +} \ No newline at end of file diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.output new file mode 100644 index 000000000..a36919e4d --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I374.output @@ -0,0 +1,9 @@ +import java.lang.annotation.ElementType; +import java.lang.annotation.Target; + +@Target({ElementType.TYPE_USE, ElementType.TYPE_PARAMETER}) +@interface MyTypeAnno {} + +public class GjfFailure { + void m(int a @MyTypeAnno []) {} +} From 45e4afbf9158a8ab40bff8179e2135972a2cde2e Mon Sep 17 00:00:00 2001 From: Ben McCann <322311+benmccann@users.noreply.github.com> Date: Thu, 19 Dec 2019 17:15:38 -0800 Subject: [PATCH 03/46] Add SBT plugin to readme Fixes #391 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=286493206 --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 72d881944..c5fdee230 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,8 @@ Implementation`. * [Cosium/maven-git-code-format](https://github.com/Cosium/maven-git-code-format): A maven plugin that automatically deploys google-java-format as a pre-commit git hook. +* SBT plugins + * [sbt/sbt-java-formatter](https://github.com/sbt/sbt-java-formatter) * [maltzj/google-style-precommit-hook](https://github.com/maltzj/google-style-precommit-hook): A pre-commit (pre-commit.com) hook that will automatically run GJF whenever you commit code to your repository From 8a215cdd190fc8b0b87bef229542336aecde24e5 Mon Sep 17 00:00:00 2001 From: cushon Date: Fri, 20 Dec 2019 15:33:32 -0800 Subject: [PATCH 04/46] annotation/parameterless annotation Parameterless annotations aren't necessarily marker annotations. All we can tell about a use of an annotation is that it's parameterless, and that's how 4.8.5 is specified. Related: #360 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=286650854 --- .../googlejavaformat/java/JavaInputAstVisitor.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index b3f6e5ade..6a600e734 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -3546,26 +3546,27 @@ private boolean hasTrailingToken(Input input, List nodes, String /** * Can a local with a set of modifiers be declared with horizontal annotations? This is currently - * true if there is at most one marker annotation, and no others. + * true if there is at most one parameterless annotation, and no others. * * @param modifiers the list of {@link ModifiersTree}s * @return whether the local can be declared with horizontal annotations */ private Direction canLocalHaveHorizontalAnnotations(ModifiersTree modifiers) { - int markerAnnotations = 0; + int parameterlessAnnotations = 0; for (AnnotationTree annotation : modifiers.getAnnotations()) { if (annotation.getArguments().isEmpty()) { - markerAnnotations++; + parameterlessAnnotations++; } } - return markerAnnotations <= 1 && markerAnnotations == modifiers.getAnnotations().size() + return parameterlessAnnotations <= 1 + && parameterlessAnnotations == modifiers.getAnnotations().size() ? Direction.HORIZONTAL : Direction.VERTICAL; } /** * Should a field with a set of modifiers be declared with horizontal annotations? This is - * currently true if all annotations are marker annotations. + * currently true if all annotations are parameterless annotations. */ private Direction fieldAnnotationDirection(ModifiersTree modifiers) { for (AnnotationTree annotation : modifiers.getAnnotations()) { From 1288c856efb4f3d03c65b40d13f25c32b30dc0ec Mon Sep 17 00:00:00 2001 From: Carmi Grushko Date: Fri, 3 Jan 2020 10:53:49 -0800 Subject: [PATCH 05/46] Tell maven-javadoc-plugin to target JDK 8 This unbreaks `mvn install` on AdoptOpenJDK 11. Presumably it unbreaks on all JDKs >= 11. Fixes #429 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=288016119 --- core/pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/core/pom.xml b/core/pom.xml index 32bfca798..3900bb6b1 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -83,6 +83,7 @@ maven-javadoc-plugin + 8 UTF-8 UTF-8 UTF-8 From 05f57ec9610a6371c38106b5e356476f2223504f Mon Sep 17 00:00:00 2001 From: "Eckert, Alexander" Date: Mon, 6 Jan 2020 13:30:33 -0800 Subject: [PATCH 06/46] Remove trailing tabs from comments to make behavior idempotent. Fixes #422, fixes #423 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=288364171 --- .../googlejavaformat/java/JavaOutput.java | 22 +++++++++++-------- .../googlejavaformat/java/FormatterTest.java | 20 +++++++++++++++++ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java index 3c2248079..c059318e8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java @@ -18,6 +18,7 @@ import com.google.common.base.CharMatcher; import com.google.common.base.MoreObjects; +import com.google.common.base.Strings; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.ImmutableList; import com.google.common.collect.Range; @@ -55,9 +56,9 @@ public final class JavaOutput extends Output { private final int kN; // The number of tokens or comments in the input, excluding the EOF. private int iLine = 0; // Closest corresponding line number on input. private int lastK = -1; // Last {@link Tok} index output. - private int spacesPending = 0; private int newlinesPending = 0; private StringBuilder lineBuilder = new StringBuilder(); + private StringBuilder spacesPending = new StringBuilder(); /** * {@code JavaOutput} constructor. @@ -121,7 +122,7 @@ public void append(String text, Range range) { if (newlinesPending == 0) { ++newlinesPending; } - spacesPending = 0; + spacesPending = new StringBuilder(); } else { boolean rangesSet = false; int textN = text.length(); @@ -129,7 +130,10 @@ public void append(String text, Range range) { char c = text.charAt(i); switch (c) { case ' ': - ++spacesPending; + spacesPending.append(' '); + break; + case '\t': + spacesPending.append('\t'); break; case '\r': if (i + 1 < text.length() && text.charAt(i + 1) == '\n') { @@ -137,7 +141,7 @@ public void append(String text, Range range) { } // falls through case '\n': - spacesPending = 0; + spacesPending = new StringBuilder(); ++newlinesPending; break; default: @@ -150,9 +154,9 @@ public void append(String text, Range range) { rangesSet = false; --newlinesPending; } - while (spacesPending > 0) { - lineBuilder.append(' '); - --spacesPending; + if (spacesPending.length() > 0) { + lineBuilder.append(spacesPending); + spacesPending = new StringBuilder(); } lineBuilder.append(c); if (!range.isEmpty()) { @@ -174,7 +178,7 @@ public void append(String text, Range range) { @Override public void indent(int indent) { - spacesPending = indent; + spacesPending.append(Strings.repeat(" ", indent)); } /** Flush any incomplete last line, then add the EOF token into our data structures. */ @@ -387,7 +391,7 @@ public String toString() { return MoreObjects.toStringHelper(this) .add("iLine", iLine) .add("lastK", lastK) - .add("spacesPending", spacesPending) + .add("spacesPending", spacesPending.toString().replace("\t", "\\t")) .add("newlinesPending", newlinesPending) .add("blankLines", blankLines) .add("super", super.toString()) diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java index 952727808..3f6e974d1 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java @@ -472,4 +472,24 @@ public void dontWrapMoeLineComments() throws Exception { + " chance to interrupt;\n" + "}\n"); } + + @Test + public void removeTrailingTabsInComments() throws Exception { + assertThat( + new Formatter() + .formatSource( + "class Foo {\n" + + " void f() {\n" + + " int x = 0; // comment\t\t\t\n" + + " return;\n" + + " }\n" + + "}\n")) + .isEqualTo( + "class Foo {\n" + + " void f() {\n" + + " int x = 0; // comment\n" + + " return;\n" + + " }\n" + + "}\n"); + } } From eb76f92acdc2b02bacab29f412551c7c40ccb0e8 Mon Sep 17 00:00:00 2001 From: cushon Date: Fri, 13 Mar 2020 14:03:22 -0700 Subject: [PATCH 07/46] Migrate from JSR-305 to the Checker Framework annotations this is tangentially related to Java 11 preparedness. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=300822964 --- core/pom.xml | 5 ++--- .../google/googlejavaformat/java/JavaInputAstVisitor.java | 2 +- .../googlejavaformat/java/filer/FormattingFiler.java | 2 +- .../java/filer/FormattingJavaFileObject.java | 2 +- .../intellij/CodeStyleManagerDecorator.java | 2 +- .../intellij/GoogleJavaFormatConfigurable.java | 2 +- .../intellij/GoogleJavaFormatSettings.java | 2 +- pom.xml | 8 ++++---- 8 files changed, 12 insertions(+), 13 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 3900bb6b1..92de6d1a5 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -46,8 +46,8 @@ - com.google.code.findbugs - jsr305 + org.checkerframework + checker-qual true @@ -89,7 +89,6 @@ UTF-8 https://guava.dev/releases/${guava.version}/api/docs/ - https://javadoc.io/static/com.google.code.findbugs/jsr305/${jsr305.version}/ https://docs.oracle.com/javase/8/docs/api/ diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 6a600e734..23cae5f0c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -81,7 +81,7 @@ import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Stream; -import javax.annotation.Nullable; +import org.checkerframework.checker.nullness.qual.Nullable; import org.openjdk.javax.lang.model.element.Name; import org.openjdk.source.tree.AnnotatedTypeTree; import org.openjdk.source.tree.AnnotationTree; diff --git a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java index 7c7894754..d38d84eca 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java +++ b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingFiler.java @@ -18,13 +18,13 @@ import com.google.googlejavaformat.java.Formatter; import java.io.IOException; -import javax.annotation.Nullable; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.lang.model.element.Element; import javax.tools.FileObject; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; +import org.checkerframework.checker.nullness.qual.Nullable; /** * A decorating {@link Filer} implementation which formats Java source files with a {@link diff --git a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java index 83728a0b4..c8ae80769 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java +++ b/core/src/main/java/com/google/googlejavaformat/java/filer/FormattingJavaFileObject.java @@ -22,11 +22,11 @@ import com.google.googlejavaformat.java.FormatterException; import java.io.IOException; import java.io.Writer; -import javax.annotation.Nullable; import javax.annotation.processing.Messager; import javax.tools.Diagnostic; import javax.tools.ForwardingJavaFileObject; import javax.tools.JavaFileObject; +import org.checkerframework.checker.nullness.qual.Nullable; /** A {@link JavaFileObject} decorator which {@linkplain Formatter formats} source code. */ final class FormattingJavaFileObject extends ForwardingJavaFileObject { diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java b/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java index 4602802c3..ee28e1bc8 100644 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java +++ b/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java @@ -33,7 +33,7 @@ import com.intellij.util.IncorrectOperationException; import com.intellij.util.ThrowableRunnable; import java.util.Collection; -import javax.annotation.Nullable; +import org.checkerframework.checker.nullness.qual.Nullable; /** * Decorates the {@link CodeStyleManager} abstract class by delegating to a concrete implementation diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java index 79859581a..2f34b7471 100644 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java +++ b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatConfigurable.java @@ -26,12 +26,12 @@ import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.uiDesigner.core.Spacer; import java.awt.Insets; -import javax.annotation.Nullable; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; +import org.checkerframework.checker.nullness.qual.Nullable; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java index 15449d701..f6d9b5ff1 100644 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java +++ b/idea_plugin/src/com/google/googlejavaformat/intellij/GoogleJavaFormatSettings.java @@ -22,7 +22,7 @@ import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import com.intellij.openapi.project.Project; -import javax.annotation.Nullable; +import org.checkerframework.checker.nullness.qual.Nullable; @State( name = "GoogleJavaFormatSettings", diff --git a/pom.xml b/pom.xml index 71c3245c4..edb5bbb86 100644 --- a/pom.xml +++ b/pom.xml @@ -98,7 +98,7 @@ 28.1-jre 9+181-r4173-1 1.0 - 3.0.2 + 2.0.0 @@ -117,9 +117,9 @@ - com.google.code.findbugs - jsr305 - ${jsr305.version} + org.checkerframework + checker-qual + ${checker.version} com.google.errorprone From cdf7665ef22253427f9312e04001ddb1349736f9 Mon Sep 17 00:00:00 2001 From: cushon Date: Mon, 16 Mar 2020 17:37:44 -0700 Subject: [PATCH 08/46] Add Java 11 regression tests ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=301273002 --- .../google/googlejavaformat/java/testdata/java11.input | 9 +++++++++ .../google/googlejavaformat/java/testdata/java11.output | 9 +++++++++ 2 files changed, 18 insertions(+) create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.output diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.input new file mode 100644 index 000000000..97bd4ac20 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.input @@ -0,0 +1,9 @@ +class Java11 { + interface I { + private default void f() {} + } + + public static void main(String[] args) { + var x = 42; + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.output new file mode 100644 index 000000000..97bd4ac20 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java11.output @@ -0,0 +1,9 @@ +class Java11 { + interface I { + private default void f() {} + } + + public static void main(String[] args) { + var x = 42; + } +} From 3c191c1326b77aabbf2a48c3edc19b628f4327d6 Mon Sep 17 00:00:00 2001 From: cushon Date: Wed, 18 Mar 2020 12:40:25 -0700 Subject: [PATCH 09/46] Use the built-in JDK 11 javac instead of relying on the shaded/vendored version. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=301645476 --- core/pom.xml | 28 +++- .../java/DimensionHelpers.java | 10 +- .../googlejavaformat/java/Formatter.java | 28 ++-- .../java/FormatterException.java | 4 +- .../googlejavaformat/java/ImportOrderer.java | 2 +- .../googlejavaformat/java/JavaInput.java | 24 +-- .../java/JavaInputAstVisitor.java | 158 +++++++++--------- .../googlejavaformat/java/JavacTokens.java | 18 +- .../java/ModifierOrderer.java | 4 +- .../java/RemoveUnusedImports.java | 62 +++---- .../googlejavaformat/java/StringWrapper.java | 42 ++--- .../google/googlejavaformat/java/Trees.java | 26 +-- pom.xml | 40 +---- 13 files changed, 219 insertions(+), 227 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 92de6d1a5..6ec553fb0 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -39,10 +39,6 @@ com.google.guava guava - - com.google.errorprone - javac-shaded - @@ -83,14 +79,26 @@ maven-javadoc-plugin - 8 + 11 UTF-8 UTF-8 UTF-8 + + https://docs.oracle.com/en/java/javase/11/docs/api + + --add-exports=jdk.compiler/com.sun.tools.javac.file=com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.main=com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.parser=com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.tree=com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.util=com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.code=com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.api=com.google.googlejavaformat + @@ -238,6 +246,14 @@ + + org.apache.maven.plugins + maven-compiler-plugin + + 11 + 11 + + diff --git a/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java b/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java index a18db691e..4bd19bee3 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java +++ b/core/src/main/java/com/google/googlejavaformat/java/DimensionHelpers.java @@ -15,16 +15,16 @@ package com.google.googlejavaformat.java; import com.google.common.collect.ImmutableList; +import com.sun.source.tree.AnnotatedTypeTree; +import com.sun.source.tree.AnnotationTree; +import com.sun.source.tree.ArrayTypeTree; +import com.sun.source.tree.Tree; +import com.sun.tools.javac.tree.JCTree; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.List; -import org.openjdk.source.tree.AnnotatedTypeTree; -import org.openjdk.source.tree.AnnotationTree; -import org.openjdk.source.tree.ArrayTypeTree; -import org.openjdk.source.tree.Tree; -import org.openjdk.tools.javac.tree.JCTree; /** * Utilities for working with array dimensions. diff --git a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java index e53f79fcf..59a1a5e29 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java @@ -31,26 +31,26 @@ import com.google.googlejavaformat.Newlines; import com.google.googlejavaformat.Op; import com.google.googlejavaformat.OpsBuilder; +import com.sun.tools.javac.file.JavacFileManager; +import com.sun.tools.javac.main.Option; +import com.sun.tools.javac.parser.JavacParser; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Log; +import com.sun.tools.javac.util.Options; import java.io.IOError; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import org.openjdk.javax.tools.Diagnostic; -import org.openjdk.javax.tools.DiagnosticCollector; -import org.openjdk.javax.tools.DiagnosticListener; -import org.openjdk.javax.tools.JavaFileObject; -import org.openjdk.javax.tools.SimpleJavaFileObject; -import org.openjdk.javax.tools.StandardLocation; -import org.openjdk.tools.javac.file.JavacFileManager; -import org.openjdk.tools.javac.main.Option; -import org.openjdk.tools.javac.parser.JavacParser; -import org.openjdk.tools.javac.parser.ParserFactory; -import org.openjdk.tools.javac.tree.JCTree.JCCompilationUnit; -import org.openjdk.tools.javac.util.Context; -import org.openjdk.tools.javac.util.Log; -import org.openjdk.tools.javac.util.Options; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.DiagnosticListener; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardLocation; /** * This is google-java-format, a new Java formatter that follows the Google Java Style Guide quite diff --git a/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java b/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java index 972b8ce06..3ccb44a46 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java @@ -20,8 +20,8 @@ import com.google.common.collect.Iterables; import com.google.googlejavaformat.FormatterDiagnostic; import java.util.List; -import org.openjdk.javax.tools.Diagnostic; -import org.openjdk.javax.tools.JavaFileObject; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; /** Checked exception class for formatter errors. */ public final class FormatterException extends Exception { diff --git a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java index a364c15e8..a82715e0a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java @@ -25,13 +25,13 @@ import com.google.googlejavaformat.Newlines; import com.google.googlejavaformat.java.JavaFormatterOptions.Style; import com.google.googlejavaformat.java.JavaInput.Tok; +import com.sun.tools.javac.parser.Tokens.TokenKind; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.function.BiFunction; import java.util.stream.Stream; -import org.openjdk.tools.javac.parser.Tokens.TokenKind; /** Orders imports in Java source code. */ public class ImportOrderer { diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java index 4781d5aed..e5e4f4580 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java @@ -33,24 +33,24 @@ import com.google.googlejavaformat.Input; import com.google.googlejavaformat.Newlines; import com.google.googlejavaformat.java.JavacTokens.RawTok; +import com.sun.tools.javac.file.JavacFileManager; +import com.sun.tools.javac.parser.Tokens.TokenKind; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Log; +import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; -import org.openjdk.javax.tools.Diagnostic; -import org.openjdk.javax.tools.DiagnosticCollector; -import org.openjdk.javax.tools.DiagnosticListener; -import org.openjdk.javax.tools.JavaFileObject; -import org.openjdk.javax.tools.JavaFileObject.Kind; -import org.openjdk.javax.tools.SimpleJavaFileObject; -import org.openjdk.tools.javac.file.JavacFileManager; -import org.openjdk.tools.javac.parser.Tokens.TokenKind; -import org.openjdk.tools.javac.tree.JCTree.JCCompilationUnit; -import org.openjdk.tools.javac.util.Context; -import org.openjdk.tools.javac.util.Log; -import org.openjdk.tools.javac.util.Log.DeferredDiagnosticHandler; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.DiagnosticListener; +import javax.tools.JavaFileObject; +import javax.tools.JavaFileObject.Kind; +import javax.tools.SimpleJavaFileObject; /** {@code JavaInput} extends {@link Input} to represent a Java input document. */ public final class JavaInput extends Input { diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 23cae5f0c..06543598a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -29,19 +29,19 @@ import static com.google.googlejavaformat.java.Trees.operatorName; import static com.google.googlejavaformat.java.Trees.precedence; import static com.google.googlejavaformat.java.Trees.skipParen; +import static com.sun.source.tree.Tree.Kind.ANNOTATION; +import static com.sun.source.tree.Tree.Kind.ARRAY_ACCESS; +import static com.sun.source.tree.Tree.Kind.ASSIGNMENT; +import static com.sun.source.tree.Tree.Kind.BLOCK; +import static com.sun.source.tree.Tree.Kind.EXTENDS_WILDCARD; +import static com.sun.source.tree.Tree.Kind.IF; +import static com.sun.source.tree.Tree.Kind.METHOD_INVOCATION; +import static com.sun.source.tree.Tree.Kind.NEW_ARRAY; +import static com.sun.source.tree.Tree.Kind.NEW_CLASS; +import static com.sun.source.tree.Tree.Kind.STRING_LITERAL; +import static com.sun.source.tree.Tree.Kind.UNION_TYPE; +import static com.sun.source.tree.Tree.Kind.VARIABLE; import static java.util.stream.Collectors.toList; -import static org.openjdk.source.tree.Tree.Kind.ANNOTATION; -import static org.openjdk.source.tree.Tree.Kind.ARRAY_ACCESS; -import static org.openjdk.source.tree.Tree.Kind.ASSIGNMENT; -import static org.openjdk.source.tree.Tree.Kind.BLOCK; -import static org.openjdk.source.tree.Tree.Kind.EXTENDS_WILDCARD; -import static org.openjdk.source.tree.Tree.Kind.IF; -import static org.openjdk.source.tree.Tree.Kind.METHOD_INVOCATION; -import static org.openjdk.source.tree.Tree.Kind.NEW_ARRAY; -import static org.openjdk.source.tree.Tree.Kind.NEW_CLASS; -import static org.openjdk.source.tree.Tree.Kind.STRING_LITERAL; -import static org.openjdk.source.tree.Tree.Kind.UNION_TYPE; -import static org.openjdk.source.tree.Tree.Kind.VARIABLE; import com.google.common.base.MoreObjects; import com.google.common.base.Predicate; @@ -69,6 +69,72 @@ import com.google.googlejavaformat.Output.BreakTag; import com.google.googlejavaformat.java.DimensionHelpers.SortedDims; import com.google.googlejavaformat.java.DimensionHelpers.TypeWithDims; +import com.sun.source.tree.AnnotatedTypeTree; +import com.sun.source.tree.AnnotationTree; +import com.sun.source.tree.ArrayAccessTree; +import com.sun.source.tree.ArrayTypeTree; +import com.sun.source.tree.AssertTree; +import com.sun.source.tree.AssignmentTree; +import com.sun.source.tree.BinaryTree; +import com.sun.source.tree.BlockTree; +import com.sun.source.tree.BreakTree; +import com.sun.source.tree.CaseTree; +import com.sun.source.tree.CatchTree; +import com.sun.source.tree.ClassTree; +import com.sun.source.tree.CompilationUnitTree; +import com.sun.source.tree.CompoundAssignmentTree; +import com.sun.source.tree.ConditionalExpressionTree; +import com.sun.source.tree.ContinueTree; +import com.sun.source.tree.DirectiveTree; +import com.sun.source.tree.DoWhileLoopTree; +import com.sun.source.tree.EmptyStatementTree; +import com.sun.source.tree.EnhancedForLoopTree; +import com.sun.source.tree.ExportsTree; +import com.sun.source.tree.ExpressionStatementTree; +import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.ForLoopTree; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.IfTree; +import com.sun.source.tree.ImportTree; +import com.sun.source.tree.InstanceOfTree; +import com.sun.source.tree.IntersectionTypeTree; +import com.sun.source.tree.LabeledStatementTree; +import com.sun.source.tree.LambdaExpressionTree; +import com.sun.source.tree.LiteralTree; +import com.sun.source.tree.MemberReferenceTree; +import com.sun.source.tree.MemberSelectTree; +import com.sun.source.tree.MethodInvocationTree; +import com.sun.source.tree.MethodTree; +import com.sun.source.tree.ModifiersTree; +import com.sun.source.tree.ModuleTree; +import com.sun.source.tree.NewArrayTree; +import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.OpensTree; +import com.sun.source.tree.ParameterizedTypeTree; +import com.sun.source.tree.ParenthesizedTree; +import com.sun.source.tree.PrimitiveTypeTree; +import com.sun.source.tree.ProvidesTree; +import com.sun.source.tree.RequiresTree; +import com.sun.source.tree.ReturnTree; +import com.sun.source.tree.StatementTree; +import com.sun.source.tree.SwitchTree; +import com.sun.source.tree.SynchronizedTree; +import com.sun.source.tree.ThrowTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.TryTree; +import com.sun.source.tree.TypeCastTree; +import com.sun.source.tree.TypeParameterTree; +import com.sun.source.tree.UnaryTree; +import com.sun.source.tree.UnionTypeTree; +import com.sun.source.tree.UsesTree; +import com.sun.source.tree.VariableTree; +import com.sun.source.tree.WhileLoopTree; +import com.sun.source.tree.WildcardTree; +import com.sun.source.util.TreePath; +import com.sun.source.util.TreePathScanner; +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.TreeScanner; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; @@ -81,74 +147,8 @@ import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Stream; +import javax.lang.model.element.Name; import org.checkerframework.checker.nullness.qual.Nullable; -import org.openjdk.javax.lang.model.element.Name; -import org.openjdk.source.tree.AnnotatedTypeTree; -import org.openjdk.source.tree.AnnotationTree; -import org.openjdk.source.tree.ArrayAccessTree; -import org.openjdk.source.tree.ArrayTypeTree; -import org.openjdk.source.tree.AssertTree; -import org.openjdk.source.tree.AssignmentTree; -import org.openjdk.source.tree.BinaryTree; -import org.openjdk.source.tree.BlockTree; -import org.openjdk.source.tree.BreakTree; -import org.openjdk.source.tree.CaseTree; -import org.openjdk.source.tree.CatchTree; -import org.openjdk.source.tree.ClassTree; -import org.openjdk.source.tree.CompilationUnitTree; -import org.openjdk.source.tree.CompoundAssignmentTree; -import org.openjdk.source.tree.ConditionalExpressionTree; -import org.openjdk.source.tree.ContinueTree; -import org.openjdk.source.tree.DirectiveTree; -import org.openjdk.source.tree.DoWhileLoopTree; -import org.openjdk.source.tree.EmptyStatementTree; -import org.openjdk.source.tree.EnhancedForLoopTree; -import org.openjdk.source.tree.ExportsTree; -import org.openjdk.source.tree.ExpressionStatementTree; -import org.openjdk.source.tree.ExpressionTree; -import org.openjdk.source.tree.ForLoopTree; -import org.openjdk.source.tree.IdentifierTree; -import org.openjdk.source.tree.IfTree; -import org.openjdk.source.tree.ImportTree; -import org.openjdk.source.tree.InstanceOfTree; -import org.openjdk.source.tree.IntersectionTypeTree; -import org.openjdk.source.tree.LabeledStatementTree; -import org.openjdk.source.tree.LambdaExpressionTree; -import org.openjdk.source.tree.LiteralTree; -import org.openjdk.source.tree.MemberReferenceTree; -import org.openjdk.source.tree.MemberSelectTree; -import org.openjdk.source.tree.MethodInvocationTree; -import org.openjdk.source.tree.MethodTree; -import org.openjdk.source.tree.ModifiersTree; -import org.openjdk.source.tree.ModuleTree; -import org.openjdk.source.tree.NewArrayTree; -import org.openjdk.source.tree.NewClassTree; -import org.openjdk.source.tree.OpensTree; -import org.openjdk.source.tree.ParameterizedTypeTree; -import org.openjdk.source.tree.ParenthesizedTree; -import org.openjdk.source.tree.PrimitiveTypeTree; -import org.openjdk.source.tree.ProvidesTree; -import org.openjdk.source.tree.RequiresTree; -import org.openjdk.source.tree.ReturnTree; -import org.openjdk.source.tree.StatementTree; -import org.openjdk.source.tree.SwitchTree; -import org.openjdk.source.tree.SynchronizedTree; -import org.openjdk.source.tree.ThrowTree; -import org.openjdk.source.tree.Tree; -import org.openjdk.source.tree.TryTree; -import org.openjdk.source.tree.TypeCastTree; -import org.openjdk.source.tree.TypeParameterTree; -import org.openjdk.source.tree.UnaryTree; -import org.openjdk.source.tree.UnionTypeTree; -import org.openjdk.source.tree.UsesTree; -import org.openjdk.source.tree.VariableTree; -import org.openjdk.source.tree.WhileLoopTree; -import org.openjdk.source.tree.WildcardTree; -import org.openjdk.source.util.TreePath; -import org.openjdk.source.util.TreePathScanner; -import org.openjdk.tools.javac.code.Flags; -import org.openjdk.tools.javac.tree.JCTree; -import org.openjdk.tools.javac.tree.TreeScanner; /** * An AST visitor that builds a stream of {@link Op}s to format from the given {@link diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java b/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java index 72f8bce3a..a8c9efd2c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java @@ -18,16 +18,16 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; +import com.sun.tools.javac.parser.JavaTokenizer; +import com.sun.tools.javac.parser.Scanner; +import com.sun.tools.javac.parser.ScannerFactory; +import com.sun.tools.javac.parser.Tokens.Comment; +import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; +import com.sun.tools.javac.parser.Tokens.Token; +import com.sun.tools.javac.parser.Tokens.TokenKind; +import com.sun.tools.javac.parser.UnicodeReader; +import com.sun.tools.javac.util.Context; import java.util.Set; -import org.openjdk.tools.javac.parser.JavaTokenizer; -import org.openjdk.tools.javac.parser.Scanner; -import org.openjdk.tools.javac.parser.ScannerFactory; -import org.openjdk.tools.javac.parser.Tokens.Comment; -import org.openjdk.tools.javac.parser.Tokens.Comment.CommentStyle; -import org.openjdk.tools.javac.parser.Tokens.Token; -import org.openjdk.tools.javac.parser.Tokens.TokenKind; -import org.openjdk.tools.javac.parser.UnicodeReader; -import org.openjdk.tools.javac.util.Context; /** A wrapper around javac's lexer. */ class JavacTokens { diff --git a/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java index 239973226..f7f610be7 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java @@ -23,6 +23,7 @@ import com.google.common.collect.TreeRangeMap; import com.google.googlejavaformat.Input.Tok; import com.google.googlejavaformat.Input.Token; +import com.sun.tools.javac.parser.Tokens.TokenKind; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -30,8 +31,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.openjdk.javax.lang.model.element.Modifier; -import org.openjdk.tools.javac.parser.Tokens.TokenKind; +import javax.lang.model.element.Modifier; /** Fixes sequences of modifiers to be in JLS order. */ final class ModifierOrderer { diff --git a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java index bd2fa8171..8bc2f0541 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java +++ b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java @@ -29,42 +29,42 @@ import com.google.common.collect.TreeRangeMap; import com.google.common.collect.TreeRangeSet; import com.google.googlejavaformat.Newlines; +import com.sun.source.doctree.DocCommentTree; +import com.sun.source.doctree.ReferenceTree; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.ImportTree; +import com.sun.source.tree.Tree; +import com.sun.source.util.DocTreePath; +import com.sun.source.util.DocTreePathScanner; +import com.sun.source.util.TreePathScanner; +import com.sun.source.util.TreeScanner; +import com.sun.tools.javac.api.JavacTrees; +import com.sun.tools.javac.file.JavacFileManager; +import com.sun.tools.javac.main.Option; +import com.sun.tools.javac.parser.JavacParser; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.tree.DCTree; +import com.sun.tools.javac.tree.DCTree.DCReference; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCFieldAccess; +import com.sun.tools.javac.tree.JCTree.JCIdent; +import com.sun.tools.javac.tree.JCTree.JCImport; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Log; +import com.sun.tools.javac.util.Options; import java.io.IOError; import java.io.IOException; import java.net.URI; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; -import org.openjdk.javax.tools.Diagnostic; -import org.openjdk.javax.tools.DiagnosticCollector; -import org.openjdk.javax.tools.DiagnosticListener; -import org.openjdk.javax.tools.JavaFileObject; -import org.openjdk.javax.tools.SimpleJavaFileObject; -import org.openjdk.javax.tools.StandardLocation; -import org.openjdk.source.doctree.DocCommentTree; -import org.openjdk.source.doctree.ReferenceTree; -import org.openjdk.source.tree.IdentifierTree; -import org.openjdk.source.tree.ImportTree; -import org.openjdk.source.tree.Tree; -import org.openjdk.source.util.DocTreePath; -import org.openjdk.source.util.DocTreePathScanner; -import org.openjdk.source.util.TreePathScanner; -import org.openjdk.source.util.TreeScanner; -import org.openjdk.tools.javac.api.JavacTrees; -import org.openjdk.tools.javac.file.JavacFileManager; -import org.openjdk.tools.javac.main.Option; -import org.openjdk.tools.javac.parser.JavacParser; -import org.openjdk.tools.javac.parser.ParserFactory; -import org.openjdk.tools.javac.tree.DCTree; -import org.openjdk.tools.javac.tree.DCTree.DCReference; -import org.openjdk.tools.javac.tree.JCTree; -import org.openjdk.tools.javac.tree.JCTree.JCCompilationUnit; -import org.openjdk.tools.javac.tree.JCTree.JCFieldAccess; -import org.openjdk.tools.javac.tree.JCTree.JCIdent; -import org.openjdk.tools.javac.tree.JCTree.JCImport; -import org.openjdk.tools.javac.util.Context; -import org.openjdk.tools.javac.util.Log; -import org.openjdk.tools.javac.util.Options; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.DiagnosticListener; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardLocation; /** * Removes unused imports from a source file. Imports that are only used in javadoc are also @@ -138,7 +138,7 @@ private void scanJavadoc() { // scan javadoc comments, checking for references to imported types class DocTreeScanner extends DocTreePathScanner { @Override - public Void visitIdentifier(org.openjdk.source.doctree.IdentifierTree node, Void aVoid) { + public Void visitIdentifier(com.sun.source.doctree.IdentifierTree node, Void aVoid) { return null; } diff --git a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java index 6dfca5335..6bb63db3a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java @@ -26,6 +26,21 @@ import com.google.common.collect.Range; import com.google.common.collect.TreeRangeMap; import com.google.googlejavaformat.Newlines; +import com.sun.source.tree.BinaryTree; +import com.sun.source.tree.LiteralTree; +import com.sun.source.tree.MemberSelectTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.Tree.Kind; +import com.sun.source.util.TreePath; +import com.sun.source.util.TreePathScanner; +import com.sun.tools.javac.file.JavacFileManager; +import com.sun.tools.javac.parser.JavacParser; +import com.sun.tools.javac.parser.ParserFactory; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.Log; +import com.sun.tools.javac.util.Options; +import com.sun.tools.javac.util.Position; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; @@ -37,27 +52,12 @@ import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import java.util.stream.Stream; -import org.openjdk.javax.tools.Diagnostic; -import org.openjdk.javax.tools.DiagnosticCollector; -import org.openjdk.javax.tools.DiagnosticListener; -import org.openjdk.javax.tools.JavaFileObject; -import org.openjdk.javax.tools.SimpleJavaFileObject; -import org.openjdk.javax.tools.StandardLocation; -import org.openjdk.source.tree.BinaryTree; -import org.openjdk.source.tree.LiteralTree; -import org.openjdk.source.tree.MemberSelectTree; -import org.openjdk.source.tree.Tree; -import org.openjdk.source.tree.Tree.Kind; -import org.openjdk.source.util.TreePath; -import org.openjdk.source.util.TreePathScanner; -import org.openjdk.tools.javac.file.JavacFileManager; -import org.openjdk.tools.javac.parser.JavacParser; -import org.openjdk.tools.javac.parser.ParserFactory; -import org.openjdk.tools.javac.tree.JCTree; -import org.openjdk.tools.javac.util.Context; -import org.openjdk.tools.javac.util.Log; -import org.openjdk.tools.javac.util.Options; -import org.openjdk.tools.javac.util.Position; +import javax.tools.Diagnostic; +import javax.tools.DiagnosticCollector; +import javax.tools.DiagnosticListener; +import javax.tools.JavaFileObject; +import javax.tools.SimpleJavaFileObject; +import javax.tools.StandardLocation; /** Wraps string literals that exceed the column limit. */ public final class StringWrapper { diff --git a/core/src/main/java/com/google/googlejavaformat/java/Trees.java b/core/src/main/java/com/google/googlejavaformat/java/Trees.java index 69b954c4f..397dacae6 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Trees.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Trees.java @@ -14,21 +14,21 @@ package com.google.googlejavaformat.java; +import com.sun.source.tree.ClassTree; +import com.sun.source.tree.CompoundAssignmentTree; +import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.MemberSelectTree; +import com.sun.source.tree.MethodInvocationTree; +import com.sun.source.tree.ParenthesizedTree; +import com.sun.source.tree.Tree; +import com.sun.source.util.TreePath; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.Pretty; +import com.sun.tools.javac.tree.TreeInfo; import java.io.IOError; import java.io.IOException; -import org.openjdk.javax.lang.model.element.Name; -import org.openjdk.source.tree.ClassTree; -import org.openjdk.source.tree.CompoundAssignmentTree; -import org.openjdk.source.tree.ExpressionTree; -import org.openjdk.source.tree.IdentifierTree; -import org.openjdk.source.tree.MemberSelectTree; -import org.openjdk.source.tree.MethodInvocationTree; -import org.openjdk.source.tree.ParenthesizedTree; -import org.openjdk.source.tree.Tree; -import org.openjdk.source.util.TreePath; -import org.openjdk.tools.javac.tree.JCTree; -import org.openjdk.tools.javac.tree.Pretty; -import org.openjdk.tools.javac.tree.TreeInfo; +import javax.lang.model.element.Name; /** Utilities for working with {@link Tree}s. */ class Trees { diff --git a/pom.xml b/pom.xml index edb5bbb86..a0952ec9d 100644 --- a/pom.xml +++ b/pom.xml @@ -96,7 +96,6 @@ UTF-8 1.8 28.1-jre - 9+181-r4173-1 1.0 2.0.0 @@ -109,11 +108,6 @@ guava ${guava.version} - - com.google.errorprone - javac-shaded - ${javac.version} - @@ -166,7 +160,7 @@ maven-javadoc-plugin - 3.0.0 + 3.1.1 maven-gpg-plugin @@ -189,6 +183,13 @@ -XDcompilePolicy=simple -Xplugin:ErrorProne + --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED + --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED @@ -248,29 +249,4 @@ - - - - - jdk8 - - 1.8 - - - - - org.apache.maven.plugins - maven-compiler-plugin - - true - - -J-Xbootclasspath/p:${settings.localRepository}/com/google/errorprone/javac/${javac.version}/javac-${javac.version}.jar - - - - - - - - From 20e38aa2442c9e1557320f45926e17c621eeadf1 Mon Sep 17 00:00:00 2001 From: cushon Date: Thu, 19 Mar 2020 09:34:26 -0700 Subject: [PATCH 10/46] Increase minimum required JDK version to 11 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=301832060 --- .travis.yml | 3 --- appveyor.yml | 1 + 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 829f0fe06..048e3ed19 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,9 +8,6 @@ notifications: on_failure: always jdk: - - openjdk8 - - openjdk9 - - openjdk10 - openjdk11 - openjdk-ea diff --git a/appveyor.yml b/appveyor.yml index a4c7ee9cb..3522155d1 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -9,6 +9,7 @@ install: ) [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") } + - cmd: SET JAVA_HOME=C:\Program Files\Java\jdk11 - cmd: SET PATH=C:\maven\apache-maven-3.3.9\bin;%JAVA_HOME%\bin;%PATH% - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g From d6d0b4d45096b0387b427ccf1e35ddbc9571fd0e Mon Sep 17 00:00:00 2001 From: cushon Date: Fri, 20 Mar 2020 14:59:46 -0700 Subject: [PATCH 11/46] Use the default / latest supported language level Previously the shaded javac was defaulting to Java 8, which we needed to override to support Java 9. Now that we're using stock JDK 11 this is unnecessary. Also explicitly support `var`, instead of relying on it getting parsed as an actual type name. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=302105420 --- .../java/com/google/googlejavaformat/java/Formatter.java | 5 ----- .../google/googlejavaformat/java/JavaInputAstVisitor.java | 8 ++++++-- .../google/googlejavaformat/java/RemoveUnusedImports.java | 3 --- 3 files changed, 6 insertions(+), 10 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java index 59a1a5e29..4348506b8 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java @@ -32,7 +32,6 @@ import com.google.googlejavaformat.Op; import com.google.googlejavaformat.OpsBuilder; import com.sun.tools.javac.file.JavacFileManager; -import com.sun.tools.javac.main.Option; import com.sun.tools.javac.parser.JavacParser; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; @@ -116,10 +115,6 @@ static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatt DiagnosticCollector diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); - // TODO(cushon): this should default to the latest supported source level, remove this after - // backing out - // https://github.com/google/error-prone-javac/commit/c97f34ddd2308302587ce2de6d0c984836ea5b9f - Options.instance(context).put(Option.SOURCE, "9"); JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 06543598a..8edd68049 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -3251,7 +3251,9 @@ int declareOne( visitAndBreakModifiers( modifiers.get(), annotationsDirection, Optional.of(verticalAnnotationBreak)); } - builder.open(type != null ? plusFour : ZERO); + boolean isVar = builder.peekToken().get().equals("var"); + boolean hasType = type != null || isVar; + builder.open(hasType ? plusFour : ZERO); { builder.open(ZERO); { @@ -3264,13 +3266,15 @@ int declareOne( maybeAddDims(dims); builder.close(); baseDims = totalDims - dims.size(); + } else if (isVar) { + token("var"); } else { scan(type, null); } } builder.close(); - if (type != null) { + if (hasType) { builder.breakOp(Doc.FillMode.INDEPENDENT, " ", ZERO, Optional.of(typeBreak)); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java index 8bc2f0541..9d0bb27d2 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java +++ b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java @@ -40,7 +40,6 @@ import com.sun.source.util.TreeScanner; import com.sun.tools.javac.api.JavacTrees; import com.sun.tools.javac.file.JavacFileManager; -import com.sun.tools.javac.main.Option; import com.sun.tools.javac.parser.JavacParser; import com.sun.tools.javac.parser.ParserFactory; import com.sun.tools.javac.tree.DCTree; @@ -186,8 +185,6 @@ public Void visitIdentifier(IdentifierTree node, Void aVoid) { public static String removeUnusedImports(final String contents) throws FormatterException { Context context = new Context(); - // TODO(cushon): this should default to the latest supported source level, same as in Formatter - Options.instance(context).put(Option.SOURCE, "9"); JCCompilationUnit unit = parse(context, contents); if (unit == null) { // error handling is done during formatting From b810032a87f5db936481d7c3b36d8d6fee058d43 Mon Sep 17 00:00:00 2001 From: Andrew Reid Date: Thu, 26 Mar 2020 10:05:58 -0700 Subject: [PATCH 12/46] Preserve tabular arguments for mixed sign numeric lists. Treats unary minus literals (eg -4.0) as their underlying type when checking if all elements in a tabular list are of the same Tree.Kind. Fixes #400, #406 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=303137504 --- .../java/JavaInputAstVisitor.java | 8 +++++++- .../testdata/TabularMixedSignInitializer.input | 17 +++++++++++++++++ .../testdata/TabularMixedSignInitializer.output | 17 +++++++++++++++++ 3 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.output diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 8edd68049..6ece007c7 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -3192,7 +3192,13 @@ private static boolean expressionsAreParallel( if (column >= row.size()) { continue; } - nodeTypes.add(row.get(column).getKind()); + // Treat UnaryTree expressions as their underlying type for the comparison (so, for example + // -ve and +ve numeric literals are considered the same). + if (row.get(column) instanceof UnaryTree) { + nodeTypes.add(((UnaryTree) row.get(column)).getExpression().getKind()); + } else { + nodeTypes.add(row.get(column).getKind()); + } } for (Multiset.Entry nodeType : nodeTypes.entrySet()) { if (nodeType.getCount() >= atLeastM) { diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.input new file mode 100644 index 000000000..2715158b1 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.input @@ -0,0 +1,17 @@ +public class T { + private static final double[] f = { + 95.0, 75.0, -95.0, 75.0, + -95.0, 75.0, +95.0, 75.0 + }; + + private static final int[] g = { + x++, y, ++z, + x, y, ~z, + --x, ++y, z-- + }; + + private static final bool[] h = { + a, b, c, d, + !e, a, b, c + }; +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.output new file mode 100644 index 000000000..2715158b1 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/TabularMixedSignInitializer.output @@ -0,0 +1,17 @@ +public class T { + private static final double[] f = { + 95.0, 75.0, -95.0, 75.0, + -95.0, 75.0, +95.0, 75.0 + }; + + private static final int[] g = { + x++, y, ++z, + x, y, ~z, + --x, ++y, z-- + }; + + private static final bool[] h = { + a, b, c, d, + !e, a, b, c + }; +} From 4ddb9148c103b9c65768e519884b0c8ad5caaf39 Mon Sep 17 00:00:00 2001 From: cushon Date: Fri, 27 Mar 2020 11:14:18 -0700 Subject: [PATCH 13/46] Add initial support for Java 14 language features ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=303367644 --- .travis.yml | 1 + core/pom.xml | 28 +++ .../googlejavaformat/java/Formatter.java | 37 ++- .../googlejavaformat/java/JavaInput.java | 2 + .../java/JavaInputAstVisitor.java | 78 ++++--- .../java/RemoveUnusedImports.java | 1 + .../googlejavaformat/java/StringWrapper.java | 1 + .../java/java14/Java14InputAstVisitor.java | 219 ++++++++++++++++++ .../googlejavaformat/java/DiagnosticTest.java | 3 +- .../java/FormatterIntegrationTest.java | 24 ++ .../googlejavaformat/java/MainTest.java | 4 +- .../java/testdata/java14.input | 38 +++ .../java/testdata/java14.output | 39 ++++ 13 files changed, 439 insertions(+), 36 deletions(-) create mode 100644 core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output diff --git a/.travis.yml b/.travis.yml index 048e3ed19..b8a7c33af 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,7 @@ notifications: jdk: - openjdk11 + - openjdk14 - openjdk-ea matrix: diff --git a/core/pom.xml b/core/pom.xml index 6ec553fb0..c6f1e664b 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -256,4 +256,32 @@ + + + + jdk11 + + (,14) + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + **/Java14InputAstVisitor.java + + + + + maven-javadoc-plugin + + com.google.googlejavaformat.java.java14 + + + + + + diff --git a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java index 4348506b8..3e973958d 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Formatter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Formatter.java @@ -14,6 +14,8 @@ package com.google.googlejavaformat.java; +import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_VERSION; +import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.ImmutableList; @@ -40,6 +42,7 @@ import com.sun.tools.javac.util.Options; import java.io.IOError; import java.io.IOException; +import java.lang.reflect.Method; import java.net.URI; import java.util.ArrayList; import java.util.Collection; @@ -115,6 +118,7 @@ static void format(final JavaInput javaInput, JavaOutput javaOutput, JavaFormatt DiagnosticCollector diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); Options.instance(context).put("allowStringFolding", "false"); + Options.instance(context).put("--enable-preview", "true"); JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); try { @@ -149,7 +153,21 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOExcept } OpsBuilder builder = new OpsBuilder(javaInput, javaOutput); // Output the compilation unit. - new JavaInputAstVisitor(builder, options.indentationMultiplier()).scan(unit, null); + JavaInputAstVisitor visitor; + if (getMajor() >= 14) { + try { + visitor = + Class.forName("com.google.googlejavaformat.java.java14.Java14InputAstVisitor") + .asSubclass(JavaInputAstVisitor.class) + .getConstructor(OpsBuilder.class, int.class) + .newInstance(builder, options.indentationMultiplier()); + } catch (ReflectiveOperationException e) { + throw new LinkageError(e.getMessage(), e); + } + } else { + visitor = new JavaInputAstVisitor(builder, options.indentationMultiplier()); + } + visitor.scan(unit, null); builder.sync(javaInput.getText().length()); builder.drain(); Doc doc = new DocBuilder().withOps(builder.build()).build(); @@ -158,6 +176,23 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOExcept javaOutput.flush(); } + // Runtime.Version was added in JDK 9, so use reflection to access it to preserve source + // compatibility with Java 8. + private static int getMajor() { + try { + Method versionMethod = Runtime.class.getMethod("version"); + Object version = versionMethod.invoke(null); + return (int) version.getClass().getMethod("major").invoke(version); + } catch (Exception e) { + // continue below + } + int version = (int) Double.parseDouble(JAVA_CLASS_VERSION.value()); + if (49 <= version && version <= 52) { + return version - (49 - 5); + } + throw new IllegalStateException("Unknown Java version: " + JAVA_SPECIFICATION_VERSION.value()); + } + static boolean errorDiagnostic(Diagnostic input) { if (input.getKind() != Diagnostic.Kind.ERROR) { return false; diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java index e5e4f4580..17ae0fac0 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java @@ -39,6 +39,7 @@ import com.sun.tools.javac.util.Context; import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler; +import com.sun.tools.javac.util.Options; import java.io.IOException; import java.net.URI; import java.util.ArrayList; @@ -347,6 +348,7 @@ static ImmutableList buildToks(String text, ImmutableSet stopTok throws FormatterException { stopTokens = ImmutableSet.builder().addAll(stopTokens).add(TokenKind.EOF).build(); Context context = new Context(); + Options.instance(context).put("--enable-preview", "true"); new JavacFileManager(context, true, UTF_8); DiagnosticCollector diagnosticCollector = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnosticCollector); diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 6ece007c7..11b9e3a0c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -134,6 +134,7 @@ import com.sun.source.util.TreePathScanner; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; import com.sun.tools.javac.tree.TreeScanner; import java.util.ArrayDeque; import java.util.ArrayList; @@ -154,10 +155,10 @@ * An AST visitor that builds a stream of {@link Op}s to format from the given {@link * CompilationUnitTree}. */ -public final class JavaInputAstVisitor extends TreePathScanner { +public class JavaInputAstVisitor extends TreePathScanner { /** Direction for Annotations (usually VERTICAL). */ - enum Direction { + protected enum Direction { VERTICAL, HORIZONTAL; @@ -211,7 +212,7 @@ static AllowTrailingBlankLine valueOf(boolean b) { } /** Whether to include braces. */ - enum BracesOrNot { + protected enum BracesOrNot { YES, NO; @@ -259,7 +260,7 @@ boolean isYes() { } /** Whether these declarations are the first in the block. */ - enum FirstDeclarationsOrNot { + protected enum FirstDeclarationsOrNot { YES, NO; @@ -268,14 +269,14 @@ boolean isYes() { } } - private final OpsBuilder builder; + protected final OpsBuilder builder; - private static final Indent.Const ZERO = Indent.Const.ZERO; - private final int indentMultiplier; - private final Indent.Const minusTwo; - private final Indent.Const minusFour; - private final Indent.Const plusTwo; - private final Indent.Const plusFour; + protected static final Indent.Const ZERO = Indent.Const.ZERO; + protected final int indentMultiplier; + protected final Indent.Const minusTwo; + protected final Indent.Const minusFour; + protected final Indent.Const plusTwo; + protected final Indent.Const plusFour; private static final ImmutableList breakList(Optional breakTag) { return ImmutableList.of(Doc.Break.make(Doc.FillMode.UNIFIED, " ", ZERO, breakTag)); @@ -382,7 +383,7 @@ public Void visitCompilationUnit(CompilationUnitTree node, Void unused) { } /** Skips over extra semi-colons at the top-level, or in a class member declaration lists. */ - private void dropEmptyDeclarations() { + protected void dropEmptyDeclarations() { if (builder.peekToken().equals(Optional.of(";"))) { while (builder.peekToken().equals(Optional.of(";"))) { builder.forcedBreak(); @@ -1331,12 +1332,19 @@ public Void visitAnnotatedType(AnnotatedTypeTree node, Void unused) { return null; } + // TODO(cushon): Use Flags.COMPACT_RECORD_CONSTRUCTOR once if/when we drop support for Java 11 + protected static final long COMPACT_RECORD_CONSTRUCTOR = 1L << 51; + @Override public Void visitMethod(MethodTree node, Void unused) { sync(node); List annotations = node.getModifiers().getAnnotations(); List returnTypeAnnotations = ImmutableList.of(); + boolean isRecordConstructor = + (((JCMethodDecl) node).mods.flags & COMPACT_RECORD_CONSTRUCTOR) + == COMPACT_RECORD_CONSTRUCTOR; + if (!node.getTypeParameters().isEmpty() && !annotations.isEmpty()) { int typeParameterStart = getStartPosition(node.getTypeParameters().get(0)); for (int i = 0; i < annotations.size(); i++) { @@ -1406,7 +1414,9 @@ public Void visitMethod(MethodTree node, Void unused) { name = builder.peekToken().get(); } token(name); - token("("); + if (!isRecordConstructor) { + token("("); + } // end of name and type scope builder.close(); } @@ -1416,12 +1426,14 @@ public Void visitMethod(MethodTree node, Void unused) { builder.open(Indent.If.make(breakBeforeType, plusFour, ZERO)); builder.open(ZERO); { - if (!node.getParameters().isEmpty() || node.getReceiverParameter() != null) { - // Break before args. - builder.breakToFill(""); - visitFormals(Optional.ofNullable(node.getReceiverParameter()), node.getParameters()); + if (!isRecordConstructor) { + if (!node.getParameters().isEmpty() || node.getReceiverParameter() != null) { + // Break before args. + builder.breakToFill(""); + visitFormals(Optional.ofNullable(node.getReceiverParameter()), node.getParameters()); + } + token(")"); } - token(")"); if (dims != null) { maybeAddDims(dims); } @@ -1795,17 +1807,22 @@ public Void visitCase(CaseTree node, Void unused) { @Override public Void visitSwitch(SwitchTree node, Void unused) { sync(node); + visitSwitch(node.getExpression(), node.getCases()); + return null; + } + + protected void visitSwitch(ExpressionTree expression, List cases) { token("switch"); builder.space(); token("("); - scan(skipParen(node.getExpression()), null); + scan(skipParen(expression), null); token(")"); builder.space(); tokenBreakTrailingComment("{", plusTwo); builder.blankLineWanted(BlankLineWanted.NO); builder.open(plusTwo); boolean first = true; - for (CaseTree caseTree : node.getCases()) { + for (CaseTree caseTree : cases) { if (!first) { builder.blankLineWanted(BlankLineWanted.PRESERVE); } @@ -1816,7 +1833,6 @@ public Void visitSwitch(SwitchTree node, Void unused) { builder.forcedBreak(); builder.blankLineWanted(BlankLineWanted.NO); token("}", plusFour); - return null; } @Override @@ -2126,7 +2142,7 @@ private void visitStatement( } } - private void visitStatements(List statements) { + protected void visitStatements(List statements) { boolean first = true; PeekingIterator it = Iterators.peekingIterator(statements.iterator()); dropEmptyDeclarations(); @@ -2164,7 +2180,7 @@ public Void visitModifiers(ModifiersTree node, Void unused) { } /** Output combined modifiers and annotations and returns the trailing break. */ - private List visitModifiers( + protected List visitModifiers( ModifiersTree modifiersTree, Direction annotationsDirection, Optional declarationAnnotationBreak) { @@ -2172,7 +2188,7 @@ private List visitModifiers( modifiersTree.getAnnotations(), annotationsDirection, declarationAnnotationBreak); } - private List visitModifiers( + protected List visitModifiers( List annotationTrees, Direction annotationsDirection, Optional declarationAnnotationBreak) { @@ -2339,7 +2355,7 @@ private static void walkInfix( } } - private void visitFormals( + protected void visitFormals( Optional receiver, List parameters) { if (!receiver.isPresent() && parameters.isEmpty()) { return; @@ -2559,7 +2575,7 @@ private void visitToDeclare( } /** Does not omit the leading '<', which should be associated with the type name. */ - private void typeParametersRest( + protected void typeParametersRest( List typeParameters, Indent plusIndent) { builder.open(plusIndent); builder.breakOp(); @@ -3446,7 +3462,7 @@ private void declareMany(List fragments, Direction annotationDirec } /** Add a list of declarations. */ - void addBodyDeclarations( + protected void addBodyDeclarations( List bodyDeclarations, BracesOrNot braces, FirstDeclarationsOrNot first0) { if (bodyDeclarations.isEmpty()) { if (braces.isYes()) { @@ -3592,7 +3608,7 @@ private Direction fieldAnnotationDirection(ModifiersTree modifiers) { * * @param token the {@link String} to wrap in a {@link Doc.Token} */ - final void token(String token) { + protected final void token(String token) { builder.token( token, Doc.Token.RealOrImaginary.REAL, @@ -3606,7 +3622,7 @@ final void token(String token) { * @param token the {@link String} to wrap in a {@link Doc.Token} * @param plusIndentCommentsBefore extra indent for comments before this token */ - final void token(String token, Indent plusIndentCommentsBefore) { + protected final void token(String token, Indent plusIndentCommentsBefore) { builder.token( token, Doc.Token.RealOrImaginary.REAL, @@ -3620,7 +3636,7 @@ final void tokenBreakTrailingComment(String token, Indent breakAndIndentTrailing token, Doc.Token.RealOrImaginary.REAL, ZERO, Optional.of(breakAndIndentTrailingComment)); } - private void markForPartialFormat() { + protected void markForPartialFormat() { if (!inExpression()) { builder.markForPartialFormat(); } @@ -3632,7 +3648,7 @@ private void markForPartialFormat() { * * @param node the ASTNode holding the input position */ - final void sync(Tree node) { + protected final void sync(Tree node) { builder.sync(((JCTree) node).getStartPosition()); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java index 9d0bb27d2..d93948082 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java +++ b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java @@ -200,6 +200,7 @@ private static JCCompilationUnit parse(Context context, String javaInput) throws FormatterException { DiagnosticCollector diagnostics = new DiagnosticCollector<>(); context.put(DiagnosticListener.class, diagnostics); + Options.instance(context).put("--enable-preview", "true"); Options.instance(context).put("allowStringFolding", "false"); JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); diff --git a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java index 6bb63db3a..e41bb6663 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java @@ -372,6 +372,7 @@ private static JCTree.JCCompilationUnit parse(String source, boolean allowString DiagnosticCollector diagnostics = new DiagnosticCollector<>(); Context context = new Context(); context.put(DiagnosticListener.class, diagnostics); + Options.instance(context).put("--enable-preview", "true"); Options.instance(context).put("allowStringFolding", Boolean.toString(allowStringFolding)); JCTree.JCCompilationUnit unit; JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8); diff --git a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java new file mode 100644 index 000000000..f3dee6b67 --- /dev/null +++ b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java @@ -0,0 +1,219 @@ +/* + * Copyright 2020 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License + * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the License for the specific language governing permissions and limitations under + * the License. + */ + +package com.google.googlejavaformat.java.java14; + +import static com.google.common.collect.ImmutableList.toImmutableList; +import static com.google.common.collect.MoreCollectors.onlyElement; + +import com.google.common.base.Verify; +import com.google.googlejavaformat.Op; +import com.google.googlejavaformat.OpsBuilder; +import com.google.googlejavaformat.java.JavaInputAstVisitor; +import com.sun.source.tree.BindingPatternTree; +import com.sun.source.tree.CaseTree; +import com.sun.source.tree.ClassTree; +import com.sun.source.tree.ExpressionTree; +import com.sun.source.tree.InstanceOfTree; +import com.sun.source.tree.MethodTree; +import com.sun.source.tree.SwitchExpressionTree; +import com.sun.source.tree.Tree; +import com.sun.source.tree.YieldTree; +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.TreeInfo; +import java.util.List; +import java.util.Optional; + +/** + * Extends {@link JavaInputAstVisitor} with support for AST nodes that were added or modified for + * Java 14. + */ +public class Java14InputAstVisitor extends JavaInputAstVisitor { + + public Java14InputAstVisitor(OpsBuilder builder, int indentMultiplier) { + super(builder, indentMultiplier); + } + + @Override + public Void visitBindingPattern(BindingPatternTree node, Void unused) { + sync(node); + scan(node.getType(), null); + builder.breakOp(" "); + visit(node.getBinding()); + return null; + } + + @Override + public Void visitYield(YieldTree node, Void aVoid) { + sync(node); + return super.visitYield(node, aVoid); + } + + @Override + public Void visitSwitchExpression(SwitchExpressionTree node, Void aVoid) { + sync(node); + visitSwitch(node.getExpression(), node.getCases()); + return null; + } + + @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 AssertionError(tree.getKind()); + } + return null; + } + + public void visitRecordDeclaration(ClassTree node) { + sync(node); + List breaks = + visitModifiers( + node.getModifiers(), + Direction.VERTICAL, + /* declarationAnnotationBreak= */ Optional.empty()); + Verify.verify(node.getExtendsClause() == null); + boolean hasSuperInterfaceTypes = !node.getImplementsClause().isEmpty(); + builder.addAll(breaks); + token("record"); + builder.space(); + visit(node.getSimpleName()); + if (!node.getTypeParameters().isEmpty()) { + token("<"); + } + builder.open(plusFour); + { + if (!node.getTypeParameters().isEmpty()) { + typeParametersRest(node.getTypeParameters(), hasSuperInterfaceTypes ? plusFour : ZERO); + } + MethodTree constructor = + node.getMembers().stream() + .filter(JCMethodDecl.class::isInstance) + .map(JCMethodDecl.class::cast) + .filter( + m -> (m.mods.flags & COMPACT_RECORD_CONSTRUCTOR) == COMPACT_RECORD_CONSTRUCTOR) + .collect(onlyElement()); + token("("); + if (!constructor.getParameters().isEmpty() || constructor.getReceiverParameter() != null) { + // Break before args. + builder.breakToFill(""); + } + visitFormals( + Optional.ofNullable(constructor.getReceiverParameter()), constructor.getParameters()); + token(")"); + if (hasSuperInterfaceTypes) { + builder.breakToFill(" "); + builder.open(node.getImplementsClause().size() > 1 ? plusFour : ZERO); + token("implements"); + builder.space(); + boolean first = true; + for (Tree superInterfaceType : node.getImplementsClause()) { + if (!first) { + token(","); + builder.breakOp(" "); + } + scan(superInterfaceType, null); + first = false; + } + builder.close(); + } + } + builder.close(); + if (node.getMembers() == null) { + token(";"); + } else { + List members = + node.getMembers().stream() + .filter(t -> (TreeInfo.flags((JCTree) t) & Flags.GENERATED_MEMBER) == 0) + .collect(toImmutableList()); + addBodyDeclarations(members, BracesOrNot.YES, FirstDeclarationsOrNot.YES); + } + dropEmptyDeclarations(); + } + + @Override + public Void visitInstanceOf(InstanceOfTree node, Void unused) { + sync(node); + builder.open(plusFour); + scan(node.getExpression(), null); + builder.breakOp(" "); + builder.open(ZERO); + token("instanceof"); + builder.breakOp(" "); + if (node.getPattern() != null) { + scan(node.getPattern(), null); + } else { + scan(node.getType(), null); + } + builder.close(); + builder.close(); + return null; + } + + @Override + public Void visitCase(CaseTree node, Void unused) { + sync(node); + markForPartialFormat(); + builder.forcedBreak(); + if (node.getExpressions().isEmpty()) { + token("default", plusTwo); + } else { + token("case", plusTwo); + builder.space(); + boolean first = true; + for (ExpressionTree expression : node.getExpressions()) { + if (!first) { + token(","); + builder.space(); + } + scan(expression, null); + first = false; + } + } + switch (node.getCaseKind()) { + case STATEMENT: + token(":"); + builder.open(plusTwo); + visitStatements(node.getStatements()); + builder.close(); + break; + case RULE: + builder.space(); + token("-"); + token(">"); + builder.space(); + scan(node.getBody(), null); + token(";"); + break; + default: + throw new AssertionError(node.getCaseKind()); + } + return null; + } +} diff --git a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java index 58ea959fd..0b81ba6b4 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java @@ -143,8 +143,7 @@ public void oneFileParseErrorReplace() throws Exception { int result = main.format("-i", pathOne.toString(), pathTwo.toString()); assertThat(stdout.toString()).isEmpty(); - assertThat(stderr.toString()) - .contains("One.java:1:14: error: class, interface, or enum expected"); + assertThat(stderr.toString()).contains("One.java:1:14: error: class, interface"); assertThat(result).isEqualTo(1); // don't edit files with parse errors assertThat(Files.readAllLines(pathOne, UTF_8)).containsExactly("class One {}}"); diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java index bb722f2ea..289ea1baf 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java @@ -14,6 +14,8 @@ package com.google.googlejavaformat.java; +import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_VERSION; +import static com.google.common.base.StandardSystemProperty.JAVA_SPECIFICATION_VERSION; import static com.google.common.io.Files.getFileExtension; import static com.google.common.io.Files.getNameWithoutExtension; import static java.nio.charset.StandardCharsets.UTF_8; @@ -21,6 +23,7 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import com.google.common.collect.ImmutableSet; import com.google.common.io.CharStreams; import com.google.common.reflect.ClassPath; import com.google.common.reflect.ClassPath.ResourceInfo; @@ -28,6 +31,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.lang.reflect.Method; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; @@ -43,6 +47,8 @@ @RunWith(Parameterized.class) public class FormatterIntegrationTest { + private static final ImmutableSet JAVA14_TESTS = ImmutableSet.of("java14"); + @Parameters(name = "{index}: {0}") public static Iterable data() throws IOException { Path testDataPath = Paths.get("com/google/googlejavaformat/java/testdata"); @@ -80,11 +86,29 @@ public static Iterable data() throws IOException { String input = inputs.get(fileName); assertTrue("unmatched input", outputs.containsKey(fileName)); String expectedOutput = outputs.get(fileName); + if (JAVA14_TESTS.contains(fileName) && getMajor() < 14) { + continue; + } testInputs.add(new Object[] {fileName, input, expectedOutput}); } return testInputs; } + private static int getMajor() { + try { + Method versionMethod = Runtime.class.getMethod("version"); + Object version = versionMethod.invoke(null); + return (int) version.getClass().getMethod("major").invoke(version); + } catch (Exception e) { + // continue below + } + int version = (int) Double.parseDouble(JAVA_CLASS_VERSION.value()); + if (49 <= version && version <= 52) { + return version - (49 - 5); + } + throw new IllegalStateException("Unknown Java version: " + JAVA_SPECIFICATION_VERSION.value()); + } + private final String name; private final String input; private final String expected; diff --git a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java index 0d559440d..613d3912c 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java @@ -294,7 +294,7 @@ public void importRemoveErrorParseError() throws Exception { new PrintWriter(err, true), new ByteArrayInputStream(joiner.join(input).getBytes(UTF_8))); assertThat(main.format("-")).isEqualTo(1); - assertThat(err.toString()).contains(":4:3: error: class, interface, or enum expected"); + assertThat(err.toString()).contains(":4:3: error: class, interface"); } finally { Locale.setDefault(backupLocale); @@ -491,7 +491,7 @@ public void assumeFilename_error() throws Exception { new PrintWriter(err, true), new ByteArrayInputStream(joiner.join(input).getBytes(UTF_8))); assertThat(main.format("--assume-filename=Foo.java", "-")).isEqualTo(1); - assertThat(err.toString()).contains("Foo.java:1:15: error: class, interface, or enum expected"); + assertThat(err.toString()).contains("Foo.java:1:15: error: class, interface"); } @Test diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input new file mode 100644 index 000000000..ce9c1257c --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input @@ -0,0 +1,38 @@ +class Java14 { + void f() { + if (obj instanceof String s) { + } else { + } + } + + record Range(T lo, T hi) implements Comparable> { + + public Range {} + + Range(T lo) { + this(lo, lo); + } + + @Override + public int compareTo(Range other) { + throw new UnsupportedOperationException(); + } + } + + void g() { + var block = """ + hello + text + blocks + """.indent(6); + } + + void h() { + int numLetters = switch (day) { + case MONDAY, FRIDAY, SUNDAY -> 6; + case TUESDAY -> 7; + case THURSDAY, SATURDAY -> 8; + case WEDNESDAY -> 9; + }; + } +} \ No newline at end of file diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output new file mode 100644 index 000000000..bddf08da7 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output @@ -0,0 +1,39 @@ +class Java14 { + void f() { + if (obj instanceof String s) { + } else { + } + } + + record Range(T lo, T hi) implements Comparable> { + + public Range {} + + Range(T lo) { + this(lo, lo); + } + + @Override + public int compareTo(Range other) { + throw new UnsupportedOperationException(); + } + } + + void g() { + var block = """ + hello + text + blocks + """.indent(6); + } + + void h() { + int numLetters = + switch (day) { + case MONDAY, FRIDAY, SUNDAY -> 6; + case TUESDAY -> 7; + case THURSDAY, SATURDAY -> 8; + case WEDNESDAY -> 9; + }; + } +} From 16b56a33b0019f83c22f5a8969410ded7ca1d2b0 Mon Sep 17 00:00:00 2001 From: cushon Date: Tue, 21 Apr 2020 15:32:49 -0700 Subject: [PATCH 14/46] Make re-parsing of var more robust to support uses of `var` as an identifier, with and without a type, e.g. in `var -> { ... }` and `int var x = 42`; and uses of `var ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=307693554 --- .../google/googlejavaformat/java/JavaInputAstVisitor.java | 4 +++- .../googlejavaformat/java/testdata/B154342628.input | 8 ++++++++ .../googlejavaformat/java/testdata/B154342628.output | 8 ++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.output diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 11b9e3a0c..7370b668c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -3273,7 +3273,9 @@ int declareOne( visitAndBreakModifiers( modifiers.get(), annotationsDirection, Optional.of(verticalAnnotationBreak)); } - boolean isVar = builder.peekToken().get().equals("var"); + boolean isVar = + builder.peekToken().get().equals("var") + && (!name.contentEquals("var") || builder.peekToken(1).get().equals("var")); boolean hasType = type != null || isVar; builder.open(hasType ? plusFour : ZERO); { diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.input new file mode 100644 index 000000000..dbde8f724 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.input @@ -0,0 +1,8 @@ +class B154342628 { + void f() { + var var = 42; + return writtenVariables.stream() + .filter(var -> deletedVariableIds.contains(var.getId())) + .collect(toImmutableList()); + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.output new file mode 100644 index 000000000..dbde8f724 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B154342628.output @@ -0,0 +1,8 @@ +class B154342628 { + void f() { + var var = 42; + return writtenVariables.stream() + .filter(var -> deletedVariableIds.contains(var.getId())) + .collect(toImmutableList()); + } +} From 7ba82f7ccfff06136fe6bb41d7c718a7d2ffcaa9 Mon Sep 17 00:00:00 2001 From: plumpy Date: Mon, 27 Apr 2020 10:24:00 -0700 Subject: [PATCH 15/46] Update the open-source google-java-format plugin for 2020.1. I couldn't find any good way to make this backwards compatible. Oh well. FYI, It looks like in 2020.1, we can probably actually use the ExternalFormatProcessor extension point instead of doing all this hacky nonsense... they added a #format(PsiFile, TextRange) method you can override. But I'll leave that for later because 2020.1 is out now and people are mad. ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=308647308 --- idea_plugin/build.gradle | 8 ++-- idea_plugin/resources/META-INF/plugin.xml | 23 +++++----- .../intellij/GoogleJavaFormatInstaller.java | 43 ++++++------------- ...lConfigurationProjectManagerListener.java} | 20 ++++----- 4 files changed, 34 insertions(+), 60 deletions(-) rename idea_plugin/src/com/google/googlejavaformat/intellij/{InitialConfigurationComponent.java => InitialConfigurationProjectManagerListener.java} (77%) diff --git a/idea_plugin/build.gradle b/idea_plugin/build.gradle index 23691f62a..7b2f389d9 100644 --- a/idea_plugin/build.gradle +++ b/idea_plugin/build.gradle @@ -15,7 +15,7 @@ */ plugins { - id "org.jetbrains.intellij" version "0.4.11" + id "org.jetbrains.intellij" version "0.4.18" } repositories { @@ -31,14 +31,14 @@ apply plugin: 'java' intellij { pluginName = "google-java-format" - version = "193.4932.9-EAP-SNAPSHOT" + version = "2020.1" } patchPluginXml { pluginDescription = "Formats source code using the google-java-format tool. This version of " + "the plugin uses version ${googleJavaFormatVersion} of the tool." - version = "${googleJavaFormatVersion}.0.3" - sinceBuild = '173' + version = "${googleJavaFormatVersion}.0.5" + sinceBuild = '201' untilBuild = '' } diff --git a/idea_plugin/resources/META-INF/plugin.xml b/idea_plugin/resources/META-INF/plugin.xml index 8b4bb1f70..d633b4045 100644 --- a/idea_plugin/resources/META-INF/plugin.xml +++ b/idea_plugin/resources/META-INF/plugin.xml @@ -12,6 +12,10 @@ +
1.7.0.5
+
Added a version for 2020.1+ IDEs.
+
1.7.0.4
+
Marked the plugin as being incompatible with 2020.1+ IDEs.
1.7.0.3
Fixed the plugin on 2019.3 IDEs.
1.7.0.2
@@ -23,19 +27,12 @@ ]]>
- - - - com.google.googlejavaformat.intellij.GoogleJavaFormatInstaller - - - - - - com.google.googlejavaformat.intellij.InitialConfigurationComponent - - - + + + + = 193; + ComponentManagerImpl platformComponentManager = (ComponentManagerImpl) project; + IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(PluginId.getId("google-java-format")); + checkState(plugin != null, "Couldn't locate our own PluginDescriptor."); + platformComponentManager.registerServiceInstance(CodeStyleManager.class, newManager, plugin); } } diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationComponent.java b/idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationProjectManagerListener.java similarity index 77% rename from idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationComponent.java rename to idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationProjectManagerListener.java index 39bde1b29..da02310c7 100644 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationComponent.java +++ b/idea_plugin/src/com/google/googlejavaformat/intellij/InitialConfigurationProjectManagerListener.java @@ -20,32 +20,28 @@ import com.intellij.notification.NotificationDisplayType; import com.intellij.notification.NotificationGroup; import com.intellij.notification.NotificationType; -import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.project.Project; +import com.intellij.openapi.project.ProjectManagerListener; +import org.jetbrains.annotations.NotNull; -final class InitialConfigurationComponent implements ProjectComponent { +final class InitialConfigurationProjectManagerListener implements ProjectManagerListener { private static final String NOTIFICATION_TITLE = "Enable google-java-format"; private static final NotificationGroup NOTIFICATION_GROUP = new NotificationGroup(NOTIFICATION_TITLE, NotificationDisplayType.STICKY_BALLOON, true); - private final Project project; - private final GoogleJavaFormatSettings settings; + @Override + public void projectOpened(@NotNull Project project) { - public InitialConfigurationComponent(Project project, GoogleJavaFormatSettings settings) { - this.project = project; - this.settings = settings; - } + GoogleJavaFormatSettings settings = GoogleJavaFormatSettings.getInstance(project); - @Override - public void projectOpened() { if (settings.isUninitialized()) { settings.setEnabled(false); - displayNewUserNotification(); + displayNewUserNotification(project, settings); } } - private void displayNewUserNotification() { + private void displayNewUserNotification(Project project, GoogleJavaFormatSettings settings) { Notification notification = new Notification( NOTIFICATION_GROUP.getDisplayId(), From ca529a291f766936da8ff70aaa706f4ccf2442b2 Mon Sep 17 00:00:00 2001 From: cushon Date: Mon, 27 Apr 2020 11:13:08 -0700 Subject: [PATCH 16/46] Fix formatting of records without an explicit constructor Fixes https://github.com/google/google-java-format/issues/460 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=308658958 --- .../java/JavaInputAstVisitor.java | 5 ++- .../java/java14/Java14InputAstVisitor.java | 38 +++++++++++++------ .../java/testdata/java14.input | 10 ++++- .../java/testdata/java14.output | 8 ++++ 4 files changed, 47 insertions(+), 14 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 7370b668c..ee211b500 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -1332,9 +1332,12 @@ public Void visitAnnotatedType(AnnotatedTypeTree node, Void unused) { return null; } - // TODO(cushon): Use Flags.COMPACT_RECORD_CONSTRUCTOR once if/when we drop support for Java 11 + // TODO(cushon): Use Flags if/when we drop support for Java 11 + protected static final long COMPACT_RECORD_CONSTRUCTOR = 1L << 51; + protected static final long RECORD = 1L << 61; + @Override public Void visitMethod(MethodTree node, Void unused) { sync(node); diff --git a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java index f3dee6b67..28a110395 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java @@ -15,9 +15,10 @@ package com.google.googlejavaformat.java.java14; import static com.google.common.collect.ImmutableList.toImmutableList; -import static com.google.common.collect.MoreCollectors.onlyElement; +import static com.google.common.collect.MoreCollectors.toOptional; import com.google.common.base.Verify; +import com.google.common.collect.ImmutableList; import com.google.googlejavaformat.Op; import com.google.googlejavaformat.OpsBuilder; import com.google.googlejavaformat.java.JavaInputAstVisitor; @@ -26,13 +27,13 @@ import com.sun.source.tree.ClassTree; import com.sun.source.tree.ExpressionTree; import com.sun.source.tree.InstanceOfTree; -import com.sun.source.tree.MethodTree; import com.sun.source.tree.SwitchExpressionTree; import com.sun.source.tree.Tree; import com.sun.source.tree.YieldTree; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.tree.TreeInfo; import java.util.List; import java.util.Optional; @@ -112,20 +113,17 @@ public void visitRecordDeclaration(ClassTree node) { if (!node.getTypeParameters().isEmpty()) { typeParametersRest(node.getTypeParameters(), hasSuperInterfaceTypes ? plusFour : ZERO); } - MethodTree constructor = - node.getMembers().stream() - .filter(JCMethodDecl.class::isInstance) - .map(JCMethodDecl.class::cast) - .filter( - m -> (m.mods.flags & COMPACT_RECORD_CONSTRUCTOR) == COMPACT_RECORD_CONSTRUCTOR) - .collect(onlyElement()); + ImmutableList parameters = + compactRecordConstructor(node) + .map(m -> ImmutableList.copyOf(m.getParameters())) + .orElseGet(() -> recordVariables(node)); token("("); - if (!constructor.getParameters().isEmpty() || constructor.getReceiverParameter() != null) { + if (!parameters.isEmpty()) { // Break before args. builder.breakToFill(""); } - visitFormals( - Optional.ofNullable(constructor.getReceiverParameter()), constructor.getParameters()); + // record headers can't declare receiver parameters + visitFormals(/* receiver= */ Optional.empty(), parameters); token(")"); if (hasSuperInterfaceTypes) { builder.breakToFill(" "); @@ -157,6 +155,22 @@ public void visitRecordDeclaration(ClassTree node) { dropEmptyDeclarations(); } + private static Optional compactRecordConstructor(ClassTree node) { + return node.getMembers().stream() + .filter(JCMethodDecl.class::isInstance) + .map(JCMethodDecl.class::cast) + .filter(m -> (m.mods.flags & COMPACT_RECORD_CONSTRUCTOR) == COMPACT_RECORD_CONSTRUCTOR) + .collect(toOptional()); + } + + private static ImmutableList recordVariables(ClassTree node) { + return node.getMembers().stream() + .filter(JCVariableDecl.class::isInstance) + .map(JCVariableDecl.class::cast) + .filter(m -> (m.mods.flags & RECORD) == RECORD) + .collect(toImmutableList()); + } + @Override public Void visitInstanceOf(InstanceOfTree node, Void unused) { sync(node); diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input index ce9c1257c..ecbea285b 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input @@ -19,6 +19,14 @@ class Java14 { } } + record Foo(int id) {} + + record Rcv(int id) { + public Rcv(Rcv this, int id) { + this.id = id; + } + } + void g() { var block = """ hello @@ -35,4 +43,4 @@ class Java14 { case WEDNESDAY -> 9; }; } -} \ No newline at end of file +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output index bddf08da7..c8c435bbd 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output @@ -19,6 +19,14 @@ class Java14 { } } + record Foo(int id) {} + + record Rcv(int id) { + public Rcv(Rcv this, int id) { + this.id = id; + } + } + void g() { var block = """ hello From e19b76376e54e3ce2822b74f8f4b9393259dc962 Mon Sep 17 00:00:00 2001 From: cushon Date: Tue, 28 Apr 2020 13:56:11 -0700 Subject: [PATCH 17/46] Support `var` in enhanced for loops Fixes https://github.com/google/google-java-format/issues/463 ------------- Created by MOE: https://github.com/google/moe MOE_MIGRATED_REVID=308891540 --- .../googlejavaformat/java/JavaInputAstVisitor.java | 14 +++++++++++--- .../googlejavaformat/java/testdata/java14.input | 4 ++++ .../googlejavaformat/java/testdata/java14.output | 4 ++++ 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index ee211b500..4ff563ec2 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -2561,13 +2561,21 @@ private void visitToDeclare( String equals, Optional trailing) { sync(node); - TypeWithDims extractedDims = DimensionHelpers.extractDims(node.getType(), SortedDims.YES); - Optional typeWithDims = Optional.of(extractedDims); + Optional typeWithDims; + Tree type; + if (node.getType() != null) { + TypeWithDims extractedDims = DimensionHelpers.extractDims(node.getType(), SortedDims.YES); + typeWithDims = Optional.of(extractedDims); + type = extractedDims.node; + } else { + typeWithDims = Optional.empty(); + type = null; + } declareOne( kind, annotationsDirection, Optional.of(node.getModifiers()), - extractedDims.node, + type, node.getName(), "", equals, diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input index ecbea285b..10d45221b 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input @@ -43,4 +43,8 @@ class Java14 { case WEDNESDAY -> 9; }; } + + { + for (var arg : List.of()) {} + } } diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output index c8c435bbd..9779198b1 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output @@ -44,4 +44,8 @@ class Java14 { case WEDNESDAY -> 9; }; } + + { + for (var arg : List.of()) {} + } } From b53d614c06a583d8c47b03b73ba7892d8403eca1 Mon Sep 17 00:00:00 2001 From: google-java-format Team Date: Thu, 30 Apr 2020 17:15:04 -0700 Subject: [PATCH 18/46] Minor Javadoc improvement. PiperOrigin-RevId: 309329483 --- .../main/java/com/google/googlejavaformat/java/JavaInput.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java index 17ae0fac0..999c8fb7f 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java @@ -562,7 +562,7 @@ private static boolean isParamComment(Tok tok) { * @param offset the {@code 0}-based offset in characters * @param length the length in characters * @return the {@code 0}-based {@link Range} of tokens - * @throws FormatterException + * @throws FormatterException if offset + length is outside the file */ Range characterRangeToTokenRange(int offset, int length) throws FormatterException { int requiredLength = offset + length; From d1c2aef1869b5d485a7fed9ad8a8b57f814dae19 Mon Sep 17 00:00:00 2001 From: Christian Stein Date: Thu, 30 Apr 2020 23:02:14 -0700 Subject: [PATCH 19/46] Fix javadoc syntax Fix javadoc syntax by wrap `<` into an inline code block. ``` [WARNING] ...\google-java-format\core\src\main\java\com\google\googlejavaformat\java\JavaInputAstVisitor.java:2577: warning - invalid usage of tag < ``` Fixes #454 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/454 from sormuras:patch-1 f5583c7cfea178a6475cd39510e366cc6694bb78 PiperOrigin-RevId: 309364827 --- .../com/google/googlejavaformat/java/JavaInputAstVisitor.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 4ff563ec2..6ce0f6680 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -2585,7 +2585,7 @@ private void visitToDeclare( typeWithDims); } - /** Does not omit the leading '<', which should be associated with the type name. */ + /** Does not omit the leading {@code "<"}, which should be associated with the type name. */ protected void typeParametersRest( List typeParameters, Indent plusIndent) { builder.open(plusIndent); From c525db0972cc25e71d33d314c61058580cbd89ee Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Fri, 1 May 2020 12:46:24 -0700 Subject: [PATCH 20/46] Pre-release javadoc fixes PiperOrigin-RevId: 309456095 --- core/pom.xml | 17 +++++++---------- pom.xml | 3 ++- 2 files changed, 9 insertions(+), 11 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index c6f1e664b..88b3cf910 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -84,20 +84,17 @@ UTF-8 UTF-8 - https://docs.oracle.com/en/java/javase/11/docs/api - --add-exports=jdk.compiler/com.sun.tools.javac.file=com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.main=com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.parser=com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.tree=com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.util=com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.code=com.google.googlejavaformat - --add-exports=jdk.compiler/com.sun.tools.javac.api=com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED,com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED,com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED,com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED,com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED,com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED,com.google.googlejavaformat + --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED,com.google.googlejavaformat diff --git a/pom.xml b/pom.xml index a0952ec9d..2ece22d5e 100644 --- a/pom.xml +++ b/pom.xml @@ -160,7 +160,7 @@ maven-javadoc-plugin - 3.1.1 + 3.2.0 maven-gpg-plugin @@ -226,6 +226,7 @@ org.apache.maven.plugins maven-javadoc-plugin + 3.2.0 none From 0354f029adc8b5828ef06becb94904b2f0985974 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Fri, 1 May 2020 13:49:49 -0700 Subject: [PATCH 21/46] Increment versions for 1.8 release PiperOrigin-RevId: 309467646 --- README.md | 6 +++--- core/pom.xml | 2 +- pom.xml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index c5fdee230..07325b77d 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ and run it with: ``` -java -jar /path/to/google-java-format-1.7-all-deps.jar [files...] +java -jar /path/to/google-java-format-1.8-all-deps.jar [files...] ``` The formatter can act on whole files, on limited lines (`--lines`), on specific @@ -94,7 +94,7 @@ configuration. com.google.googlejavaformat google-java-format - 1.7 + 1.8 ``` @@ -102,7 +102,7 @@ configuration. ```groovy dependencies { - compile 'com.google.googlejavaformat:google-java-format:1.7' + compile 'com.google.googlejavaformat:google-java-format:1.8' } ``` diff --git a/core/pom.xml b/core/pom.xml index 88b3cf910..8e394756c 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.google.googlejavaformat google-java-format-parent - 1.8-SNAPSHOT + 1.9-SNAPSHOT google-java-format diff --git a/pom.xml b/pom.xml index 2ece22d5e..f0776d3d7 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ com.google.googlejavaformat google-java-format-parent pom - 1.8-SNAPSHOT + 1.9-SNAPSHOT core From f5a9280558d46f2a1bf269eeefa0f53d7ba3ebfe Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Mon, 11 May 2020 13:00:03 -0700 Subject: [PATCH 22/46] Fix a crash in expression switches `throws` statements are allows to occur in non-block expression switch cases, which was causing the trailing `;` to be printed twice. Fixes https://github.com/google/google-java-format/issues/477 PiperOrigin-RevId: 310974906 --- .../java/java14/Java14InputAstVisitor.java | 2 +- .../java/FormatterIntegrationTest.java | 2 +- .../googlejavaformat/java/testdata/I477.input | 17 +++++++++++++++++ .../googlejavaformat/java/testdata/I477.output | 17 +++++++++++++++++ 4 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.output diff --git a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java index 28a110395..6585c6f6e 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java @@ -223,7 +223,7 @@ public Void visitCase(CaseTree node, Void unused) { token(">"); builder.space(); scan(node.getBody(), null); - token(";"); + builder.guessToken(";"); break; default: throw new AssertionError(node.getCaseKind()); diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java index 289ea1baf..0e0ab9f49 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java @@ -47,7 +47,7 @@ @RunWith(Parameterized.class) public class FormatterIntegrationTest { - private static final ImmutableSet JAVA14_TESTS = ImmutableSet.of("java14"); + private static final ImmutableSet JAVA14_TESTS = ImmutableSet.of("java14", "I477"); @Parameters(name = "{index}: {0}") public static Iterable data() throws IOException { diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.input new file mode 100644 index 000000000..ecd8658b3 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.input @@ -0,0 +1,17 @@ +class I477 { + public static String foo(int in) { + return switch (in) { + case 1 -> "A"; + case 2 -> "B"; + default -> throw new IllegalStateException("Unknown input " + in); + }; + } + + public static String foo(int in) { + return switch (in) { + case 1 -> "A"; + case 2 -> "B"; + default -> "C"; + }; + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.output new file mode 100644 index 000000000..ecd8658b3 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/I477.output @@ -0,0 +1,17 @@ +class I477 { + public static String foo(int in) { + return switch (in) { + case 1 -> "A"; + case 2 -> "B"; + default -> throw new IllegalStateException("Unknown input " + in); + }; + } + + public static String foo(int in) { + return switch (in) { + case 1 -> "A"; + case 2 -> "B"; + default -> "C"; + }; + } +} From 98c8525593e206225d92c76dd3f05513be18d699 Mon Sep 17 00:00:00 2001 From: cpovirk Date: Wed, 13 May 2020 09:34:40 -0700 Subject: [PATCH 23/46] Split up the string "M" + "OE:(begin|end)_intracomment_stripping," as the full string will trigger stripping under Copybara. Also, avoid reference to an internal link shortener, as we are making references to it an error. Looking to the future: When we migrate to use proper Copybara stripping directives, we could consider removing support for the old directives. Then the problem would mostly go away. However, we might end up having the same problem with Copybara directives when google-java-format's strings and method names start mentioning *them*. PiperOrigin-RevId: 311344956 --- .../java/javadoc/JavadocLexer.java | 4 +- .../java/JavadocFormattingTest.java | 50 +++++++++---------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java index 108d4a7bf..cc707ae7e 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocLexer.java @@ -507,9 +507,9 @@ private static boolean hasMultipleNewlines(String s) { // Match "@param " specially in case the is a

or other HTML tag we treat specially. private static final Pattern FOOTER_TAG_PATTERN = compile("^@(param\\s+<\\w+>|[a-z]\\w*)"); private static final Pattern MOE_BEGIN_STRIP_COMMENT_PATTERN = - compile("^"); + compile("^"); private static final Pattern MOE_END_STRIP_COMMENT_PATTERN = - compile("^"); + compile("^"); private static final Pattern HTML_COMMENT_PATTERN = fullCommentPattern(); private static final Pattern PRE_OPEN_PATTERN = openTagPattern("pre"); private static final Pattern PRE_CLOSE_PATTERN = closeTagPattern("pre"); diff --git a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java index 411699765..f5103d9b5 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/JavadocFormattingTest.java @@ -115,48 +115,48 @@ public void moeComments() { String[] input = { "/**", " * Deatomizes the given user.", - " * ", - " * See go/deatomizer-v5 for the design doc.", - " * ", + " * ", + " * See deatomizer-v5 for the design doc.", + " * ", " * To reatomize, call {@link reatomize}.", " *", - " * ", + " * ", " *

This method is used in the Google teleporter.", " *", " *

Yes, we have a teleporter.", - " * ", + " * ", " *", " * @param user the person to teleport.", - " * ", - " * Users must sign go/deatomize-waiver ahead of time.", - " * ", - " * ", + " * ", + " * Users must sign deatomize-waiver ahead of time.", + " * ", + " * ", " * @deprecated Sometimes turns the user into a goat.", - " * ", + " * ", " */", "class Test {}", }; String[] expected = { "/**", " * Deatomizes the given user.", - " * ", - " * See go/deatomizer-v5 for the design doc.", - " * ", + " * ", + " * See deatomizer-v5 for the design doc.", + " * ", " * To reatomize, call {@link reatomize}.", " *", - " * ", + " * ", " *

This method is used in the Google teleporter.", " *", " *

Yes, we have a teleporter.", - " * ", + " * ", " *", " * @param user the person to teleport.", - " * ", - " * Users must sign go/deatomize-waiver ahead of time.", - " * ", - " * ", + " * ", + " * Users must sign deatomize-waiver ahead of time.", + " * ", + " * ", " * @deprecated Sometimes turns the user into a goat.", - " * ", + " * ", " */", "class Test {}", }; @@ -169,7 +169,7 @@ public void moeCommentBeginOnlyInMiddleOfDoc() { String[] input = { "/**", // " * Foo.", - " * ", + " * ", " * Bar.", " */", "class Test {}", @@ -177,7 +177,7 @@ public void moeCommentBeginOnlyInMiddleOfDoc() { String[] expected = { "/**", // " * Foo.", - " * ", + " * ", " * Bar.", " */", "class Test {}", @@ -192,7 +192,7 @@ public void moeCommentBeginOnlyAtEndOfDoc() { String[] input = { "/**", // " * Foo.", - " * ", + " * ", " */", "class Test {}", }; @@ -209,14 +209,14 @@ public void moeCommentEndOnly() { String[] input = { "/**", // " * Foo.", - " * ", + " * ", " */", "class Test {}", }; String[] expected = { "/**", // " * Foo.", - " * ", + " * ", " */", "class Test {}", }; From 2ddcfd392cc5e45eaa5fb30c723b7e024f5caabb Mon Sep 17 00:00:00 2001 From: Avi Mimoun <36456709+av1m@users.noreply.github.com> Date: Tue, 26 May 2020 19:24:57 -0700 Subject: [PATCH 24/46] Addition of a third party: Github Actions - Add the possibility of formatting your code from Github directly (taking all the events of Github Actions) - Addition of the word "old" for the eclipse plugin, since it is 1.6 release Fixes #487 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/487 from av1m:master 351b737be5580c2f3320605668c218882624a3fc PiperOrigin-RevId: 313312689 --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 07325b77d..c12ca348e 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ and import it into File→Settings→Editor→Code Style. ### Eclipse -A +Version 1.6 of the [google-java-format Eclipse plugin](https://github.com/google/google-java-format/releases/download/google-java-format-1.6/google-java-format-eclipse-plugin_1.6.0.jar) can be downloaded from the releases page. Drop it into the Eclipse [drop-ins folder](http://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.isv%2Freference%2Fmisc%2Fp2_dropins_format.html) @@ -81,6 +81,9 @@ Implementation`. * [maltzj/google-style-precommit-hook](https://github.com/maltzj/google-style-precommit-hook): A pre-commit (pre-commit.com) hook that will automatically run GJF whenever you commit code to your repository +* [Github Actions](https://github.com/features/actions) + * [googlejavaformat-action](https://github.com/axel-op/googlejavaformat-action): + Automatically format your Java files when you push on github ### as a library From 22d8c55fb4699cf08e4c9728dc6ccc9360becd5a Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Wed, 3 Jun 2020 11:14:53 -0700 Subject: [PATCH 25/46] Java 14 integration tests PiperOrigin-RevId: 314566781 --- .../java/FormatterIntegrationTest.java | 3 +- .../java/testdata/ExpressionSwitch.input | 9 ++++ .../java/testdata/ExpressionSwitch.output | 9 ++++ .../googlejavaformat/java/testdata/RSLs.input | 6 +++ .../java/testdata/RSLs.output | 6 +++ .../java/testdata/Records.input | 29 +++++++++++ .../java/testdata/Records.output | 29 +++++++++++ .../googlejavaformat/java/testdata/Var.input | 5 ++ .../googlejavaformat/java/testdata/Var.output | 5 ++ .../java/testdata/java14.input | 50 ------------------ .../java/testdata/java14.output | 51 ------------------- 11 files changed, 100 insertions(+), 102 deletions(-) create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.output create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.output create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.input create mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.output delete mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input delete mode 100644 core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java index 0e0ab9f49..44ba63925 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterIntegrationTest.java @@ -47,7 +47,8 @@ @RunWith(Parameterized.class) public class FormatterIntegrationTest { - private static final ImmutableSet JAVA14_TESTS = ImmutableSet.of("java14", "I477"); + private static final ImmutableSet JAVA14_TESTS = + ImmutableSet.of("I477", "Records", "RSLs", "Var", "ExpressionSwitch"); @Parameters(name = "{index}: {0}") public static Iterable data() throws IOException { diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input new file mode 100644 index 000000000..381d5d17d --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input @@ -0,0 +1,9 @@ +class ExpressionSwitch { + boolean odd(int x) { + return switch (x) { + case 0 -> true; + case 1 -> false; + default -> odd(x - 1); + }; + } +} \ No newline at end of file diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output new file mode 100644 index 000000000..38eca1b2d --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output @@ -0,0 +1,9 @@ +class ExpressionSwitch { + boolean odd(int x) { + return switch (x) { + case 0 -> true; + case 1 -> false; + default -> odd(x - 1); + }; + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.input new file mode 100644 index 000000000..9c18f0def --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.input @@ -0,0 +1,6 @@ +class RSLs { + String s = """ + lorem + ipsum + """; +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.output new file mode 100644 index 000000000..9c18f0def --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/RSLs.output @@ -0,0 +1,6 @@ +class RSLs { + String s = """ + lorem + ipsum + """; +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.input new file mode 100644 index 000000000..03a3c06b0 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.input @@ -0,0 +1,29 @@ +class Records { + record R1() {} + + private record R2() {} + + @Deprecated + private record R3() {} + + record R4() {} + + record R5(int x) {} + + record R6(@Deprecated int x) {} + + record R7(@Deprecated int x, int... y) {} + + record R8() implements Comparable> { + @Override + public int compareTo(R8 other) { + return 0; + } + } + + record R9(int x) { + R9(int x) { + this.x = x; + } + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.output new file mode 100644 index 000000000..03a3c06b0 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Records.output @@ -0,0 +1,29 @@ +class Records { + record R1() {} + + private record R2() {} + + @Deprecated + private record R3() {} + + record R4() {} + + record R5(int x) {} + + record R6(@Deprecated int x) {} + + record R7(@Deprecated int x, int... y) {} + + record R8() implements Comparable> { + @Override + public int compareTo(R8 other) { + return 0; + } + } + + record R9(int x) { + R9(int x) { + this.x = x; + } + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.input new file mode 100644 index 000000000..2633632d6 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.input @@ -0,0 +1,5 @@ +class Var { + void f() { + for (var x : ImmutableList.of(42)) {} + } +} \ No newline at end of file diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.output new file mode 100644 index 000000000..95d436ab5 --- /dev/null +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/Var.output @@ -0,0 +1,5 @@ +class Var { + void f() { + for (var x : ImmutableList.of(42)) {} + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input deleted file mode 100644 index 10d45221b..000000000 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.input +++ /dev/null @@ -1,50 +0,0 @@ -class Java14 { - void f() { - if (obj instanceof String s) { - } else { - } - } - - record Range(T lo, T hi) implements Comparable> { - - public Range {} - - Range(T lo) { - this(lo, lo); - } - - @Override - public int compareTo(Range other) { - throw new UnsupportedOperationException(); - } - } - - record Foo(int id) {} - - record Rcv(int id) { - public Rcv(Rcv this, int id) { - this.id = id; - } - } - - void g() { - var block = """ - hello - text - blocks - """.indent(6); - } - - void h() { - int numLetters = switch (day) { - case MONDAY, FRIDAY, SUNDAY -> 6; - case TUESDAY -> 7; - case THURSDAY, SATURDAY -> 8; - case WEDNESDAY -> 9; - }; - } - - { - for (var arg : List.of()) {} - } -} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output deleted file mode 100644 index 9779198b1..000000000 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/java14.output +++ /dev/null @@ -1,51 +0,0 @@ -class Java14 { - void f() { - if (obj instanceof String s) { - } else { - } - } - - record Range(T lo, T hi) implements Comparable> { - - public Range {} - - Range(T lo) { - this(lo, lo); - } - - @Override - public int compareTo(Range other) { - throw new UnsupportedOperationException(); - } - } - - record Foo(int id) {} - - record Rcv(int id) { - public Rcv(Rcv this, int id) { - this.id = id; - } - } - - void g() { - var block = """ - hello - text - blocks - """.indent(6); - } - - void h() { - int numLetters = - switch (day) { - case MONDAY, FRIDAY, SUNDAY -> 6; - case TUESDAY -> 7; - case THURSDAY, SATURDAY -> 8; - case WEDNESDAY -> 9; - }; - } - - { - for (var arg : List.of()) {} - } -} From 5202af98006d744aafc2ba7cba2fa19a14e9b7b1 Mon Sep 17 00:00:00 2001 From: Tim Koopman Date: Wed, 3 Jun 2020 17:07:38 -0700 Subject: [PATCH 26/46] Add support for yield statement Implement visitYield. Fixes #489 from ntkoopman:yield b46d1f0f2526044676e7ed5cca07a6f745772c0d COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/489 PiperOrigin-RevId: 314633394 --- .../java/java14/Java14InputAstVisitor.java | 6 ++++- .../java/testdata/ExpressionSwitch.input | 21 +++++++++++++++- .../java/testdata/ExpressionSwitch.output | 25 +++++++++++++++++++ 3 files changed, 50 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java index 6585c6f6e..78cfd66b1 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java @@ -60,7 +60,11 @@ public Void visitBindingPattern(BindingPatternTree node, Void unused) { @Override public Void visitYield(YieldTree node, Void aVoid) { sync(node); - return super.visitYield(node, aVoid); + token("yield"); + builder.space(); + scan(node.getValue(), null); + token(";"); + return null; } @Override diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input index 381d5d17d..1e4db164d 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.input @@ -6,4 +6,23 @@ class ExpressionSwitch { default -> odd(x - 1); }; } -} \ No newline at end of file + + { + int f = switch (i) { + case 0 -> 0; + default -> { + yield n / i; + } + }; + + int g = switch (i) { + case 0: yield 0; + default: yield n/i; + }; + + switch (i) { + case 0 -> { System.out.println("0"); } + default -> System.out.println("default"); + } + } +} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output index 38eca1b2d..6458aa09d 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/ExpressionSwitch.output @@ -6,4 +6,29 @@ class ExpressionSwitch { default -> odd(x - 1); }; } + + { + int f = + switch (i) { + case 0 -> 0; + default -> { + yield n / i; + } + }; + + int g = + switch (i) { + case 0: + yield 0; + default: + yield n / i; + }; + + switch (i) { + case 0 -> { + System.out.println("0"); + } + default -> System.out.println("default"); + } + } } From 1e4f14f65703e9771dcdc8db90a7d27597559164 Mon Sep 17 00:00:00 2001 From: "taesu82.lee" <66580975+taesu82@users.noreply.github.com> Date: Tue, 9 Jun 2020 14:28:27 -0700 Subject: [PATCH 27/46] Support --skip-removing-unused-imports in google-java-format-diff.py Fixes #495 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/495 from taesu82:patch-1 91e32d443cf8159a72f05a38146dd9b5d4bf550c PiperOrigin-RevId: 315560436 --- scripts/google-java-format-diff.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/scripts/google-java-format-diff.py b/scripts/google-java-format-diff.py index 4c6724b90..1abd037d3 100755 --- a/scripts/google-java-format-diff.py +++ b/scripts/google-java-format-diff.py @@ -57,6 +57,8 @@ def main(): help='use AOSP style instead of Google Style (4-space indentation)') parser.add_argument('--skip-sorting-imports', action='store_true', help='do not fix the import order') + parser.add_argument('--skip-removing-unused-imports', action='store_true', + help='do not remove ununsed imports') parser.add_argument('-b', '--binary', help='path to google-java-format binary') parser.add_argument('--google-java-format-jar', metavar='ABSOLUTE_PATH', default=None, help='use a custom google-java-format jar') @@ -112,6 +114,8 @@ def main(): command.append('--aosp') if args.skip_sorting_imports: command.append('--skip-sorting-imports') + if args.skip_removing_unused_imports: + command.append('--skip-removing-unused-imports') command.extend(lines) command.append(filename) p = subprocess.Popen(command, stdout=subprocess.PIPE, From c2c8a517c92fbf3553e53524057cd2ad8ae62962 Mon Sep 17 00:00:00 2001 From: google-java-format Team Date: Fri, 26 Jun 2020 10:20:09 -0700 Subject: [PATCH 28/46] Update the IDEA plugin to use google-java-format 1.8. PiperOrigin-RevId: 318495968 --- idea_plugin/build.gradle | 6 +++--- idea_plugin/resources/META-INF/plugin.xml | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/idea_plugin/build.gradle b/idea_plugin/build.gradle index 7b2f389d9..f7b54f18b 100644 --- a/idea_plugin/build.gradle +++ b/idea_plugin/build.gradle @@ -15,7 +15,7 @@ */ plugins { - id "org.jetbrains.intellij" version "0.4.18" + id "org.jetbrains.intellij" version "0.4.21" } repositories { @@ -23,7 +23,7 @@ repositories { } ext { - googleJavaFormatVersion = '1.7' + googleJavaFormatVersion = '1.8' } apply plugin: 'org.jetbrains.intellij' @@ -37,7 +37,7 @@ intellij { patchPluginXml { pluginDescription = "Formats source code using the google-java-format tool. This version of " + "the plugin uses version ${googleJavaFormatVersion} of the tool." - version = "${googleJavaFormatVersion}.0.5" + version = "${googleJavaFormatVersion}.0.0" sinceBuild = '201' untilBuild = '' } diff --git a/idea_plugin/resources/META-INF/plugin.xml b/idea_plugin/resources/META-INF/plugin.xml index d633b4045..cb7d716c7 100644 --- a/idea_plugin/resources/META-INF/plugin.xml +++ b/idea_plugin/resources/META-INF/plugin.xml @@ -12,6 +12,8 @@ +

1.8.0.0
+
Updated to use google-java-format 1.8.
1.7.0.5
Added a version for 2020.1+ IDEs.
1.7.0.4
From 02a072f296802e4ca771ce4b6ad97b62af665573 Mon Sep 17 00:00:00 2001 From: Eddie Aftandilian Date: Fri, 10 Jul 2020 23:21:35 -0700 Subject: [PATCH 29/46] Add missing license headers. PiperOrigin-RevId: 320733285 --- eclipse_plugin/plugin.xml | 16 ++++++++++++++++ idea_plugin/resources/META-INF/plugin.xml | 16 ++++++++++++++++ scripts/mvn-deploy.sh | 15 +++++++++++++++ util/publish-snapshot-on-commit.sh | 14 ++++++++++++++ util/settings.xml | 16 ++++++++++++++++ 5 files changed, 77 insertions(+) diff --git a/eclipse_plugin/plugin.xml b/eclipse_plugin/plugin.xml index 5d0bbf92b..b832a1e21 100644 --- a/eclipse_plugin/plugin.xml +++ b/eclipse_plugin/plugin.xml @@ -1,3 +1,19 @@ + + diff --git a/idea_plugin/resources/META-INF/plugin.xml b/idea_plugin/resources/META-INF/plugin.xml index cb7d716c7..938a02f53 100644 --- a/idea_plugin/resources/META-INF/plugin.xml +++ b/idea_plugin/resources/META-INF/plugin.xml @@ -1,3 +1,19 @@ + + google-java-format google-java-format diff --git a/scripts/mvn-deploy.sh b/scripts/mvn-deploy.sh index f6db09338..0133e3612 100755 --- a/scripts/mvn-deploy.sh +++ b/scripts/mvn-deploy.sh @@ -1,4 +1,19 @@ #!/bin/bash + +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + if [ $# -lt 1 ]; then echo "usage $0 [ ...]" exit 1; diff --git a/util/publish-snapshot-on-commit.sh b/util/publish-snapshot-on-commit.sh index 6da8da446..c14368da1 100755 --- a/util/publish-snapshot-on-commit.sh +++ b/util/publish-snapshot-on-commit.sh @@ -1,3 +1,17 @@ +# Copyright 2020 Google Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + # https://github.com/google/dagger/blob/master/util/publish-snapshot-on-commit.sh if [ "$TRAVIS_REPO_SLUG" == "google/google-java-format" ] && \ diff --git a/util/settings.xml b/util/settings.xml index 91f444b22..aea3d4ef7 100644 --- a/util/settings.xml +++ b/util/settings.xml @@ -1,3 +1,19 @@ + + From 1715884a46b0953b0491039b668fdc23bb2e7788 Mon Sep 17 00:00:00 2001 From: Eddie Aftandilian Date: Fri, 10 Jul 2020 23:38:23 -0700 Subject: [PATCH 30/46] Disable Appveyor builds on branches. Our account for Appveyor allows only 1 concurrent build. Our current Appveyor config builds every commit to a PR twice -- once as the PR and once as the branch. This CL updates our Appveyor config to disable builds on branches, so we get only one build per PR commit. PiperOrigin-RevId: 320734870 --- appveyor.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/appveyor.yml b/appveyor.yml index 3522155d1..ac535c9a6 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,4 +1,10 @@ +# Don't build branches that are not PRs, to avoid double builds. +branches: + only: + - master + os: Visual Studio 2015 + install: - ps: | Add-Type -AssemblyName System.IO.Compression.FileSystem From 45fb41a7bac3dfe0726601ceb87d1c17bbf494ec Mon Sep 17 00:00:00 2001 From: google-java-format Team Date: Mon, 13 Jul 2020 06:41:23 -0700 Subject: [PATCH 31/46] Fix the google-java-format IDEA plugin for 2020.2 IDEs. PiperOrigin-RevId: 320945302 --- idea_plugin/build.gradle | 4 ++-- idea_plugin/resources/META-INF/plugin.xml | 2 ++ .../googlejavaformat/intellij/CodeStyleManagerDecorator.java | 5 +++++ 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/idea_plugin/build.gradle b/idea_plugin/build.gradle index f7b54f18b..d74957d66 100644 --- a/idea_plugin/build.gradle +++ b/idea_plugin/build.gradle @@ -31,13 +31,13 @@ apply plugin: 'java' intellij { pluginName = "google-java-format" - version = "2020.1" + version = "202.6250.13-EAP-SNAPSHOT" } patchPluginXml { pluginDescription = "Formats source code using the google-java-format tool. This version of " + "the plugin uses version ${googleJavaFormatVersion} of the tool." - version = "${googleJavaFormatVersion}.0.0" + version = "${googleJavaFormatVersion}.0.1" sinceBuild = '201' untilBuild = '' } diff --git a/idea_plugin/resources/META-INF/plugin.xml b/idea_plugin/resources/META-INF/plugin.xml index 938a02f53..5b313cf62 100644 --- a/idea_plugin/resources/META-INF/plugin.xml +++ b/idea_plugin/resources/META-INF/plugin.xml @@ -28,6 +28,8 @@ +
1.8.0.1
+
Fixed support for 2020.2 IDEs.
1.8.0.0
Updated to use google-java-format 1.8.
1.7.0.5
diff --git a/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java b/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java index ee28e1bc8..c70ba1751 100644 --- a/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java +++ b/idea_plugin/src/com/google/googlejavaformat/intellij/CodeStyleManagerDecorator.java @@ -231,4 +231,9 @@ public int adjustLineIndent(final Document document, final int offset, Formattin } return offset; } + + @Override + public void scheduleReformatWhenSettingsComputed(PsiFile file) { + delegate.scheduleReformatWhenSettingsComputed(file); + } } From 062e5d2e150abee4de6640b25db963e5de4d4f13 Mon Sep 17 00:00:00 2001 From: Ned Twigg Date: Thu, 23 Jul 2020 11:48:48 -0700 Subject: [PATCH 32/46] Update links to Spotless' new documentation layout Also included the Spotless maven plugin (2+ years old, but not well marketed) Fixes #509 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/509 from nedtwigg:patch-2 546c758cc5be91141118cc1b9c560b082ea191cd PiperOrigin-RevId: 322832707 --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c12ca348e..9ce399838 100644 --- a/README.md +++ b/README.md @@ -68,9 +68,10 @@ Implementation`. ### Third-party integrations * Gradle plugins - * [Spotless](https://github.com/diffplug/spotless/tree/master/plugin-gradle#applying-to-java-source-google-java-format): + * [spotless](https://github.com/diffplug/spotless/tree/main/plugin-gradle#google-java-format) * [sherter/google-java-format-gradle-plugin](https://github.com/sherter/google-java-format-gradle-plugin) * Apache Maven plugins + * [spotless](https://github.com/diffplug/spotless/tree/main/plugin-maven#google-java-format) * [coveo/fmt-maven-plugin](https://github.com/coveo/fmt-maven-plugin) * [talios/googleformatter-maven-plugin](https://github.com/talios/googleformatter-maven-plugin) * [Cosium/maven-git-code-format](https://github.com/Cosium/maven-git-code-format): From 1c45fa55b1a483314f8cb52bd0a0b21838c2bc32 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Mon, 24 Aug 2020 10:04:28 -0700 Subject: [PATCH 33/46] Bump versions to 1.9 PiperOrigin-RevId: 328160170 --- core/pom.xml | 2 +- pom.xml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/core/pom.xml b/core/pom.xml index 8e394756c..e5eab9cc0 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.google.googlejavaformat google-java-format-parent - 1.9-SNAPSHOT + 1.9 google-java-format diff --git a/pom.xml b/pom.xml index f0776d3d7..35bba263b 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ com.google.googlejavaformat google-java-format-parent pom - 1.9-SNAPSHOT + 1.9 core From 1614b6a348a82dcb78bbe9f68c2eb4ede9330c32 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Mon, 24 Aug 2020 14:52:24 -0700 Subject: [PATCH 34/46] Increment versions after 1.10 release PiperOrigin-RevId: 328214914 --- README.md | 6 +++--- core/pom.xml | 2 +- pom.xml | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 9ce399838..6f7d5c654 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ and run it with: ``` -java -jar /path/to/google-java-format-1.8-all-deps.jar [files...] +java -jar /path/to/google-java-format-1.9-all-deps.jar [files...] ``` The formatter can act on whole files, on limited lines (`--lines`), on specific @@ -98,7 +98,7 @@ configuration. com.google.googlejavaformat google-java-format - 1.8 + 1.9 ``` @@ -106,7 +106,7 @@ configuration. ```groovy dependencies { - compile 'com.google.googlejavaformat:google-java-format:1.8' + compile 'com.google.googlejavaformat:google-java-format:1.9' } ``` diff --git a/core/pom.xml b/core/pom.xml index e5eab9cc0..e2d015316 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -22,7 +22,7 @@ com.google.googlejavaformat google-java-format-parent - 1.9 + 1.10-SNAPSHOT google-java-format diff --git a/pom.xml b/pom.xml index 35bba263b..a8cb645fb 100644 --- a/pom.xml +++ b/pom.xml @@ -28,7 +28,7 @@ com.google.googlejavaformat google-java-format-parent pom - 1.9 + 1.10-SNAPSHOT core From 6bde01e0880586518efad4cc5fd5a00916f41bb5 Mon Sep 17 00:00:00 2001 From: Michael Ernst Date: Tue, 15 Sep 2020 12:38:43 -0700 Subject: [PATCH 35/46] Bump checker-qual from 2.0.0 to 3.6.1 Fixes #519 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/519 from mernst:checker-qual-361 ca54cb9c65d4b1aeffdef3ddbd81f9948ed40bb8 PiperOrigin-RevId: 331830590 --- .../com/google/googlejavaformat/java/JavaInputAstVisitor.java | 4 ++-- .../java/com/google/googlejavaformat/java/JavaOutput.java | 2 +- .../com/google/googlejavaformat/java/testdata/A.input | 4 ++-- .../com/google/googlejavaformat/java/testdata/A.output | 4 ++-- .../com/google/googlejavaformat/java/testdata/B20844369.input | 2 +- .../google/googlejavaformat/java/testdata/B20844369.output | 2 +- .../com/google/googlejavaformat/java/testdata/C.input | 2 +- .../com/google/googlejavaformat/java/testdata/C.output | 2 +- .../com/google/googlejavaformat/java/testdata/D.input | 2 +- .../com/google/googlejavaformat/java/testdata/D.output | 2 +- .../com/google/googlejavaformat/java/testdata/E.input | 2 +- .../com/google/googlejavaformat/java/testdata/E.output | 2 +- .../com/google/googlejavaformat/java/testdata/L.input | 2 +- .../com/google/googlejavaformat/java/testdata/L.output | 2 +- .../com/google/googlejavaformat/java/testdata/S.input | 2 +- .../com/google/googlejavaformat/java/testdata/S.output | 2 +- .../com/google/googlejavaformat/java/testdata/T.input | 2 +- .../com/google/googlejavaformat/java/testdata/T.output | 2 +- pom.xml | 2 +- 19 files changed, 22 insertions(+), 22 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 6ce0f6680..672d8b74b 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -2366,7 +2366,7 @@ protected void visitFormals( builder.open(ZERO); boolean first = true; if (receiver.isPresent()) { - // TODO(jdd): Use builders. + // TODO(user): Use builders. declareOne( DeclarationKind.PARAMETER, Direction.HORIZONTAL, @@ -2906,7 +2906,7 @@ private void dotExpressionUpToArgs(ExpressionTree expression, Optional if (!methodInvocation.getTypeArguments().isEmpty()) { builder.open(plusFour); addTypeArguments(methodInvocation.getTypeArguments(), ZERO); - // TODO(jdd): Should indent the name -4. + // TODO(user): Should indent the name -4. builder.breakOp(Doc.FillMode.UNIFIED, "", ZERO, tyargTag); builder.close(); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java index c059318e8..9564a225a 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java @@ -89,7 +89,7 @@ public void markForPartialFormat(Token start, Token end) { partialFormatRanges.add(Range.closed(lo, hi)); } - // TODO(jdd): Add invariant. + // TODO(user): Add invariant. @Override public void append(String text, Range range) { if (!range.isEmpty()) { diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.input index 81d13aa1d..c6586300e 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.input @@ -17,13 +17,13 @@ class A { @X(x = 1) private @interface Y {} - // TODO(jdd): Add annotation declaration with empty body. + // TODO(user): Add annotation declaration with empty body. @X(x = 1) @Y protected @interface Z {} - // TODO(jdd): Include type annotations once we can include a higher language level. + // TODO(user): Include type annotations once we can include a higher language level. int[] array1 = new int[5]; int[] array2 = diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.output index 3eff456df..5d5d88f01 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/A.output @@ -17,13 +17,13 @@ class A { @X(x = 1) private @interface Y {} - // TODO(jdd): Add annotation declaration with empty body. + // TODO(user): Add annotation declaration with empty body. @X(x = 1) @Y protected @interface Z {} - // TODO(jdd): Include type annotations once we can include a higher language level. + // TODO(user): Include type annotations once we can include a higher language level. int[] array1 = new int[5]; int[] array2 = diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.input index 86e46d50e..7317f17b9 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.input @@ -1,6 +1,6 @@ public class B20844369 { private static final String ID_PATTERN = - // TODO(daw): add min/max lengths for the numbers here, e.g. android ID + // TODO(user): add min/max lengths for the numbers here, e.g. android ID "(?:(?\\d+)\\+)?" // optional Android ID + "(?\\d+)" // type + ":" diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.output index 982dc2b5d..62f9721b6 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/B20844369.output @@ -1,6 +1,6 @@ public class B20844369 { private static final String ID_PATTERN = - // TODO(daw): add min/max lengths for the numbers here, e.g. android ID + // TODO(user): add min/max lengths for the numbers here, e.g. android ID "(?:(?\\d+)\\+)?" // optional Android ID + "(?\\d+)" // type + ":" diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.input index 7baed6cfe..31bf3b8f4 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.input @@ -6,7 +6,7 @@ package com.google.googlejavaformat.java.test; * CreationReferences. */ class C { - // TODO(jdd): Test higher-language-level constructs. + // TODO(user): Test higher-language-level constructs. C() { this( diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.output index fcf773ec0..c62c7ae29 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/C.output @@ -6,7 +6,7 @@ package com.google.googlejavaformat.java.test; * CreationReferences. */ class C { - // TODO(jdd): Test higher-language-level constructs. + // TODO(user): Test higher-language-level constructs. C() { this( diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.input index daca973b6..d69ed1e14 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.input @@ -2,7 +2,7 @@ package com.google.googlejavaformat.java.test; /** Tests for Dimensions and DoStatements. */ class D { - // TODO(jdd): Test higher-language-level features. + // TODO(user): Test higher-language-level features. int[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] [][][][] diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.output index daca973b6..d69ed1e14 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/D.output @@ -2,7 +2,7 @@ package com.google.googlejavaformat.java.test; /** Tests for Dimensions and DoStatements. */ class D { - // TODO(jdd): Test higher-language-level features. + // TODO(user): Test higher-language-level features. int[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][] [][][][] diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.input index 0e98139a6..479466ace 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.input @@ -9,7 +9,7 @@ import com.google.common.collect.Lists; */ @MarkerAnnotation class E { - // TODO(jdd): Test higher language-level features. + // TODO(user): Test higher language-level features. enum Enum1 { A, B, C, D; diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.output index 4dd603a39..fb4f2fae5 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/E.output @@ -9,7 +9,7 @@ import com.google.common.collect.Lists; */ @MarkerAnnotation class E { - // TODO(jdd): Test higher language-level features. + // TODO(user): Test higher language-level features. enum Enum1 { A, diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.input index f0b3e6681..eda543d0c 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.input @@ -2,7 +2,7 @@ package com.google.googlejavaformat.java.test; /** Tests for LabeledStatements and LambdaExpressions. */ class L { - // TODO(jdd): Include high language-level tests. + // TODO(user): Include high language-level tests. void f() { LABEL: diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.output index f0b3e6681..eda543d0c 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/L.output @@ -2,7 +2,7 @@ package com.google.googlejavaformat.java.test; /** Tests for LabeledStatements and LambdaExpressions. */ class L { - // TODO(jdd): Include high language-level tests. + // TODO(user): Include high language-level tests. void f() { LABEL: diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.input index a1e07d1c8..15fc1b2c0 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.input @@ -7,7 +7,7 @@ package com.google.googlejavaformat.java.test; * SynchronizedStatements. */ class S { - // TODO(jdd): Add tests for higher language levels. + // TODO(user): Add tests for higher language levels. int x = 0; diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.output index a1e07d1c8..15fc1b2c0 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/S.output @@ -7,7 +7,7 @@ package com.google.googlejavaformat.java.test; * SynchronizedStatements. */ class S { - // TODO(jdd): Add tests for higher language levels. + // TODO(user): Add tests for higher language levels. int x = 0; diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.input b/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.input index c8cd29316..fc9bc0978 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.input +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.input @@ -5,7 +5,7 @@ package com.google.googlejavaformat.java.test; * TypeDeclarations, TypeLiterals, TypeMethodReferences, TypeParameters, and Types. */ class T { - // TODO(jdd): Add tests for higher language levels. + // TODO(user): Add tests for higher language levels. T f(int x) throws Exception { class TT {} diff --git a/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.output b/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.output index c8cd29316..fc9bc0978 100644 --- a/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.output +++ b/core/src/test/resources/com/google/googlejavaformat/java/testdata/T.output @@ -5,7 +5,7 @@ package com.google.googlejavaformat.java.test; * TypeDeclarations, TypeLiterals, TypeMethodReferences, TypeParameters, and Types. */ class T { - // TODO(jdd): Add tests for higher language levels. + // TODO(user): Add tests for higher language levels. T f(int x) throws Exception { class TT {} diff --git a/pom.xml b/pom.xml index a8cb645fb..0b2000415 100644 --- a/pom.xml +++ b/pom.xml @@ -97,7 +97,7 @@ 1.8 28.1-jre 1.0 - 2.0.0 + 3.6.1 From f77e9270b187c4a013e4826dff6bba1c33363347 Mon Sep 17 00:00:00 2001 From: Michael Plump Date: Thu, 17 Sep 2020 15:01:02 -0700 Subject: [PATCH 36/46] Update the IntelliJ plugin to google-java-format 1.9. PiperOrigin-RevId: 332323928 --- idea_plugin/build.gradle | 8 ++++---- idea_plugin/resources/META-INF/plugin.xml | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/idea_plugin/build.gradle b/idea_plugin/build.gradle index d74957d66..6ec1c210d 100644 --- a/idea_plugin/build.gradle +++ b/idea_plugin/build.gradle @@ -15,7 +15,7 @@ */ plugins { - id "org.jetbrains.intellij" version "0.4.21" + id "org.jetbrains.intellij" version "0.4.22" } repositories { @@ -23,7 +23,7 @@ repositories { } ext { - googleJavaFormatVersion = '1.8' + googleJavaFormatVersion = '1.9' } apply plugin: 'org.jetbrains.intellij' @@ -31,13 +31,13 @@ apply plugin: 'java' intellij { pluginName = "google-java-format" - version = "202.6250.13-EAP-SNAPSHOT" + version = "2020.2.2" } patchPluginXml { pluginDescription = "Formats source code using the google-java-format tool. This version of " + "the plugin uses version ${googleJavaFormatVersion} of the tool." - version = "${googleJavaFormatVersion}.0.1" + version = "${googleJavaFormatVersion}.0.0" sinceBuild = '201' untilBuild = '' } diff --git a/idea_plugin/resources/META-INF/plugin.xml b/idea_plugin/resources/META-INF/plugin.xml index 5b313cf62..5996dba68 100644 --- a/idea_plugin/resources/META-INF/plugin.xml +++ b/idea_plugin/resources/META-INF/plugin.xml @@ -28,6 +28,8 @@ +
1.9.0.0
+
Updated to use google-java-format 1.9.
1.8.0.1
Fixed support for 2020.2 IDEs.
1.8.0.0
From ea4828aaa4498949f179b9bf87fd5a4b8afe31dd Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Tue, 13 Oct 2020 15:20:33 -0700 Subject: [PATCH 37/46] Upgrade junit dependency to 4.13.1 PiperOrigin-RevId: 336966883 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 0b2000415..82b0a3ba2 100644 --- a/pom.xml +++ b/pom.xml @@ -125,7 +125,7 @@ junit junit - 4.12 + 4.13.1 test From b769e812a052d7cff4a2d86eff4981a5d358ee2d Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Wed, 14 Oct 2020 16:03:01 -0700 Subject: [PATCH 38/46] Tolerate extra semi-colons in import lists even if they're own their own line (which g-j-f does if it runs with import cleanup disabled). PiperOrigin-RevId: 337192414 --- .../googlejavaformat/java/ImportOrderer.java | 4 ++++ .../java/ImportOrdererTest.java | 21 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java index a82715e0a..dcbaea172 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ImportOrderer.java @@ -346,6 +346,10 @@ private ImportsAndIndex scanImports(int i) throws FormatterException { i++; } } + while (tokenAt(i).equals(";")) { + // Extra semicolons are not allowed by the JLS but are accepted by javac. + i++; + } imports.add(new Import(importedName, trailing.toString(), isStatic)); // Remember the position just after the import we just saw, before skipping blank lines. // If the next thing after the blank lines is not another import then we don't want to diff --git a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java index 5a6b1f906..1a03c743d 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java @@ -800,6 +800,27 @@ public static Collection parameters() { "public class Blim {}", }, }, + { + { + "package p;", + "", + "import java.lang.Bar;", + "import java.lang.Baz;", + ";", + "import java.lang.Foo;", + "", + "interface Test {}", + }, + { + "package p;", + "", + "import java.lang.Bar;", + "import java.lang.Baz;", + "import java.lang.Foo;", + "", + "interface Test {}", + } + } }; ImmutableList.Builder builder = ImmutableList.builder(); Arrays.stream(inputsOutputs).forEach(input -> builder.add(createRow(input))); From 93d649d0fbc07fc604f7b47b3098cf6e1df521de Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Fri, 16 Oct 2020 08:38:42 -0700 Subject: [PATCH 39/46] Move import ordering tests out of the AOSP section follow-up to https://github.com/google/google-java-format/commit/b769e812a052d7cff4a2d86eff4981a5d358ee2d PiperOrigin-RevId: 337511552 --- .../java/ImportOrdererTest.java | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java index 1a03c743d..f40fa3821 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/ImportOrdererTest.java @@ -527,6 +527,27 @@ public static Collection parameters() { "class Test {}", } }, + { + { + "package p;", + "", + "import java.lang.Bar;", + "import java.lang.Baz;", + ";", + "import java.lang.Foo;", + "", + "interface Test {}", + }, + { + "package p;", + "", + "import java.lang.Bar;", + "import java.lang.Baz;", + "import java.lang.Foo;", + "", + "interface Test {}", + } + } }; ImmutableList.Builder builder = ImmutableList.builder(); @@ -799,27 +820,6 @@ public static Collection parameters() { "", "public class Blim {}", }, - }, - { - { - "package p;", - "", - "import java.lang.Bar;", - "import java.lang.Baz;", - ";", - "import java.lang.Foo;", - "", - "interface Test {}", - }, - { - "package p;", - "", - "import java.lang.Bar;", - "import java.lang.Baz;", - "import java.lang.Foo;", - "", - "interface Test {}", - } } }; ImmutableList.Builder builder = ImmutableList.builder(); From 3ce093515ad0bc1458e8965fdf71f78482f87968 Mon Sep 17 00:00:00 2001 From: google-java-format Team Date: Fri, 20 Nov 2020 12:53:43 -0800 Subject: [PATCH 40/46] Remove typo period in flags documentation. I *think* they are typoes? Apologies if this is intended. PiperOrigin-RevId: 343547804 --- .../java/com/google/googlejavaformat/java/UsageException.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java index 82c0843dc..a10f2d076 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/UsageException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/UsageException.java @@ -46,9 +46,9 @@ final class UsageException extends Exception { " Do not fix the import order. Unused imports will still be removed.", " --skip-removing-unused-imports", " Do not remove unused imports. Imports will still be sorted.", - " . --skip-reflowing-long-strings", + " --skip-reflowing-long-strings", " Do not reflow string literals that exceed the column limit.", - " . --skip-javadoc-formatting", + " --skip-javadoc-formatting", " Do not reformat javadoc.", " --dry-run, -n", " Prints the paths of the files whose contents would change if the formatter were run" From c1dd08d349b098f4bceb5b71aa1d6c2251de4f6d Mon Sep 17 00:00:00 2001 From: Christian Stein Date: Wed, 25 Nov 2020 10:47:19 -0800 Subject: [PATCH 41/46] Introduce GitHub Actions based CI workflow This PR introduces a CI workflow using GitHub Actions and removes the Travis CI configuration file. Find new workflow runs for this PR here: https://github.com/sormuras/google-java-format/actions #### TODO - [x] Email [Notifications](https://docs.github.com/en/free-pro-team@latest/github/managing-subscriptions-and-notifications-on-github/configuring-notifications) -- register `google-java-format-dev+ci@google.com` as a watcher or let each interested use register themself? - [ ] Test publish snapshot job on `google:master` -- after storing credential [secrets](https://github.com/google/google-java-format/settings/secrets/actions). - [ ] Remove AppVeyor [integration](https://github.com/google/google-java-format/settings/installations) and delete `appveyor.yml` configuration file. Closes #543 Fixes #544 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/544 from sormuras:github-action a689f6234aed2e32bd7aca093b92e391ac6c8170 PiperOrigin-RevId: 344280060 --- .github/workflows/ci.yml | 58 ++++++++++++++++++++++++++++++++++++++++ .travis.yml | 42 ----------------------------- 2 files changed, 58 insertions(+), 42 deletions(-) create mode 100644 .github/workflows/ci.yml delete mode 100644 .travis.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..c3e53dd5e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,58 @@ +name: CI + +on: [ push, pull_request ] + +jobs: + test: + name: "JDK ${{ matrix.java }} on ${{ matrix.os }}" + strategy: + fail-fast: false + matrix: + os: [ ubuntu-latest, macos-latest, windows-latest ] + java: [ 15, 11 ] + runs-on: ${{ matrix.os }} + steps: + - name: 'Check out repository' + uses: actions/checkout@v2 + - name: 'Cache local Maven repository' + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + - name: 'Set up JDK ${{ matrix.java }}' + uses: actions/setup-java@v1 + with: + java-version: ${{ matrix.java }} + - name: 'Install' + shell: bash + run: mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V + - name: 'Test' + shell: bash + run: mvn test -B + + publish_snapshot: + name: 'Publish snapshot' + needs: test + if: github.event_name == 'push' && github.repository == 'google/google-java-format' && github.ref == 'refs/heads/master' + runs-on: ubuntu-latest + steps: + - name: 'Check out repository' + uses: actions/checkout@v2 + - name: 'Cache local Maven repository' + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + - name: 'Set up JDK 15' + uses: actions/setup-java@v1 + with: + java-version: 15 + server-id: sonatype-nexus-snapshots + server-username: CI_DEPLOY_USERNAME + server-password: CI_DEPLOY_PASSWORD + - name: 'Publish' + run: mvn source:jar deploy -B -DskipTests=true -Dinvoker.skip=true -Dmaven.javadoc.skip=true diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index b8a7c33af..000000000 --- a/.travis.yml +++ /dev/null @@ -1,42 +0,0 @@ -language: java - -notifications: - email: - recipients: - - google-java-format-dev+ci@google.com - on_success: change - on_failure: always - -jdk: - - openjdk11 - - openjdk14 - - openjdk-ea - -matrix: - allow_failures: - - jdk: openjdk-ea - -# see https://github.com/travis-ci/travis-ci/issues/8408 -before_install: -- unset _JAVA_OPTIONS - -install: echo "The default Travis install script is being skipped!" - -# use travis-ci docker based infrastructure -sudo: false - -cache: - directories: - - $HOME/.m2 - -script: -- mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V -- mvn test -B - -env: - global: - - secure: KkUX74NDDk95WR60zwN6x6pz49KAfR0zUu1thxl8Kke0+WVoIv1EBo7/e4ZXTdBKxlzQCX9Aa0OlIyUlhGJeuNIGtX16lcNyZNmKSacfrT68MpZqi+nAiYp8tnOyW/zuI+shSKHkGQOFq6c9KTtR9vG8kjr1Q9dNl/H5QjGaG1ZMiU/mGH9ompf+0nQTMDLKaEWV+SpKGjK5U1Zs2p08I9KKePbZoi9L2oAw5cH9wW8Q3pQJds6Rkwy9aecxRd4xmTza7Lb04dmByjqY8gsIjrTN0onOndBmLKTHiH5NVLKf0ilEVGiMQ1x4eCQolcRpGzxdTTKI0ahiWS59UABVoy1sXYqkIbZjpmMuGhHvbRir7YEXaG8LRUAxdWd9drJfvKQeBphQlIJKwajHSiMAdc9zisQg1UW75HSGKoPDHpzq+P7YBil2PUjk+5yUy5OytX6IebFT4KdeCO2ayu338yqb2t8q98elMoD5jwFVD0tpkLQ6xsYodClSGfMCVfP2zTkB7c4sHZV7tJS68CiNt7sCwz9CTNApFiSWMBxLKkKQ7VSBTy9bAn+phvW0u/maGsrRnehmsV3PVPtEsMlrqeMGwaPqIwx1l6otVQCnGRt3e8z3HoxY6AaBPaX0Z8lH2y+BxYhWTYzGhRxyyV666u/9yekTXmH53c7at7mau6Q= - - secure: VWnZcPA4esdaMJgh0Mui7K5O++AGZY3AYswufd0UUbAmnK60O6cDBOSelnr7hImDgZ09L2RWMXIVCt4b+UFXoIhqrvZKVitUXPldS6uNJeGT9p6quFf36o8Wf0ppKWnPd66AY6ECnE75Ujn1Maw899kb3zY2SvIvzA7HlXqtmowHCVGoJ4ou6LQxJpVEJ4hjvS2gQMF9W31uOzRzMI1JhdZioYmqe6eq9sGmRZZiYON7jBqX8f4XW0tTZoK+dVRNwYQcwyqcvQpxeI15VWDq5cqjBw3ps5XSEYTNIFUXREnEEi+vLdCuw/YRZp1ij7LiQKp6bcb2KROXaWii4VpUNWxIAflm4Nvn/8pa/3CUwqIbxTSAL+Qkb2iEzuYuNPGLr72mQgGEnlSpaqzUx0miwjJ41x3Q8mf72ihIME7YQGMDJL7TA7/GjXFeSxroPk65tbssAGmbjwGGJX67NHUzeQPW2QPA2cohCHyopKB9GqhKgKwKjenkCUaBGCaZReZz9XkSkHTXlxxSakMTmgJnA9To9d2lPOy0nppUvrd/0uAbPuxxCZqXElRvOvHKzpV1ZpKpqSxvjh63mCQRTi2rFiPn8uFaajai9mHaPoGmNwQwIUbAviNqifuIEPpc6cOuyV0MWJwdFLo1SKamJya/MwQz+IwXuY2TX7Fmv9HovdM= - -after_success: -- util/publish-snapshot-on-commit.sh From fcf767116e3f478a17dd28c22a25e509b2cabbab Mon Sep 17 00:00:00 2001 From: Christian Stein Date: Mon, 30 Nov 2020 08:38:04 -0800 Subject: [PATCH 42/46] Check build with JDK 16-ea Addresses https://github.com/google/google-java-format/issues/538#issuecomment-733522202 Fixes #548 COPYBARA_INTEGRATE_REVIEW=https://github.com/google/google-java-format/pull/548 from sormuras:jdk-ea 0ee3f7c62c75a4f05b54ed088e3fefa8d40c650c PiperOrigin-RevId: 344818484 --- .github/workflows/ci.yml | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3e53dd5e..468d9e99f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,6 +32,31 @@ jobs: shell: bash run: mvn test -B + early_access: + name: 'JDK Early-Access' + continue-on-error: true + runs-on: ubuntu-latest + steps: + - name: 'Check out repository' + uses: actions/checkout@v2 + - name: 'Cache local Maven repository' + uses: actions/cache@v2 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + - name: 'Set up JDK ${{ matrix.java }}' + uses: actions/setup-java@v1 + with: + java-version: 16-ea + - name: 'Install' + shell: bash + run: mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V + - name: 'Test' + shell: bash + run: mvn test -B + publish_snapshot: name: 'Publish snapshot' needs: test From d25a84487dd5b32ebba5112a7d51081162b6ab26 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Mon, 30 Nov 2020 15:41:51 -0800 Subject: [PATCH 43/46] Fix GitHub Actions-based snapshot deployment Fixes https://github.com/google/google-java-format/issues/547 PiperOrigin-RevId: 344903246 --- .github/workflows/ci.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 468d9e99f..a14629ff8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -80,4 +80,7 @@ jobs: server-username: CI_DEPLOY_USERNAME server-password: CI_DEPLOY_PASSWORD - name: 'Publish' + env: + CI_DEPLOY_USERNAME: ${{ secrets.CI_DEPLOY_USERNAME }} + CI_DEPLOY_PASSWORD: ${{ secrets.CI_DEPLOY_PASSWORD }} run: mvn source:jar deploy -B -DskipTests=true -Dinvoker.skip=true -Dmaven.javadoc.skip=true From cc58ed36614b10e97e74d69daeb02c093a03885e Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Wed, 2 Dec 2020 13:29:13 -0800 Subject: [PATCH 44/46] Delete google-java-format appveyor and travis configs PiperOrigin-RevId: 345300707 --- .github/workflows/ci.yml | 14 ++++++++++++++ appveyor.yml | 39 --------------------------------------- 2 files changed, 14 insertions(+), 39 deletions(-) delete mode 100644 appveyor.yml diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a14629ff8..2b3134c10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,3 +1,17 @@ +# Copyright 2020 The Error Prone Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + name: CI on: [ push, pull_request ] diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index ac535c9a6..000000000 --- a/appveyor.yml +++ /dev/null @@ -1,39 +0,0 @@ -# Don't build branches that are not PRs, to avoid double builds. -branches: - only: - - master - -os: Visual Studio 2015 - -install: - - ps: | - Add-Type -AssemblyName System.IO.Compression.FileSystem - if (!(Test-Path -Path "C:\maven" )) { - (new-object System.Net.WebClient).DownloadFile( - 'http://www.us.apache.org/dist/maven/maven-3/3.3.9/binaries/apache-maven-3.3.9-bin.zip', - 'C:\maven-bin.zip' - ) - [System.IO.Compression.ZipFile]::ExtractToDirectory("C:\maven-bin.zip", "C:\maven") - } - - cmd: SET JAVA_HOME=C:\Program Files\Java\jdk11 - - cmd: SET PATH=C:\maven\apache-maven-3.3.9\bin;%JAVA_HOME%\bin;%PATH% - - cmd: SET MAVEN_OPTS=-XX:MaxPermSize=2g -Xmx4g - - cmd: SET JAVA_OPTS=-XX:MaxPermSize=2g -Xmx4g - -build_script: - - mvn install -DskipTests=true -Dmaven.javadoc.skip=true -B -V - -test_script: - - mvn test -B - -cache: - - C:\maven\ - - C:\Users\appveyor\.m2 - -notifications: - - provider: Email - to: - - google-java-format-dev+ci@google.com - on_build_success: false - on_build_failure: true - on_build_status_changed: true From 8ba2b05955fb7d3b40bf15bcc942e9cddddf617d Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Fri, 4 Dec 2020 11:23:28 -0800 Subject: [PATCH 45/46] Miscellaneous cleanups Startblock: cl-status copybara contains unknown commit in live PiperOrigin-RevId: 345718768 --- .../java/com/google/googlejavaformat/Doc.java | 3 +- .../google/googlejavaformat/OpsBuilder.java | 9 +++-- .../java/CommandLineOptionsParser.java | 2 +- .../java/FormatterException.java | 5 +-- .../java/JavaInputAstVisitor.java | 4 +-- .../googlejavaformat/java/JavaOutput.java | 8 ++--- .../google/googlejavaformat/java/Main.java | 7 ++-- .../java/ModifierOrderer.java | 2 +- .../java/RemoveUnusedImports.java | 3 +- .../googlejavaformat/java/StringWrapper.java | 2 +- .../java/javadoc/JavadocWriter.java | 5 ++- .../java/CommandLineOptionsParserTest.java | 6 ++-- .../googlejavaformat/java/DiagnosticTest.java | 9 +++-- .../googlejavaformat/java/FormatterTest.java | 16 ++++----- .../googlejavaformat/java/MainTest.java | 20 ++++++----- .../java/PartialFormattingTest.java | 33 +++++++++---------- .../java/RemoveUnusedImportsTest.java | 2 +- .../java/StringWrapperIntegrationTest.java | 4 +-- .../java/filer/FormattingFilerTest.java | 8 ++--- pom.xml | 2 +- 20 files changed, 77 insertions(+), 73 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/Doc.java b/core/src/main/java/com/google/googlejavaformat/Doc.java index e663c9603..35acca367 100644 --- a/core/src/main/java/com/google/googlejavaformat/Doc.java +++ b/core/src/main/java/com/google/googlejavaformat/Doc.java @@ -15,6 +15,7 @@ package com.google.googlejavaformat; import static com.google.common.collect.Iterables.getLast; +import static java.lang.Math.max; import com.google.common.base.MoreObjects; import com.google.common.collect.DiscreteDomain; @@ -653,7 +654,7 @@ public State computeBreaks(State state, int lastIndent, boolean broken) { if (broken) { this.broken = true; - this.newIndent = Math.max(lastIndent + plusIndent.eval(), 0); + this.newIndent = max(lastIndent + plusIndent.eval(), 0); return state.withColumn(newIndent); } else { this.broken = false; diff --git a/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java b/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java index e8e100f3f..36e038adf 100644 --- a/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java +++ b/core/src/main/java/com/google/googlejavaformat/OpsBuilder.java @@ -14,6 +14,9 @@ package com.google.googlejavaformat; +import static java.lang.Math.max; +import static java.lang.Math.min; + import com.google.common.base.MoreObjects; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; @@ -39,14 +42,14 @@ public int actualSize(int position, int length) { int start = startToken.getTok().getPosition(); for (Tok tok : startToken.getToksBefore()) { if (tok.isComment()) { - start = Math.min(start, tok.getPosition()); + start = min(start, tok.getPosition()); } } Token endToken = input.getPositionTokenMap().get(position + length - 1); int end = endToken.getTok().getPosition() + endToken.getTok().length(); for (Tok tok : endToken.getToksAfter()) { if (tok.isComment()) { - end = Math.max(end, tok.getPosition() + tok.length()); + end = max(end, tok.getPosition() + tok.length()); } } return end - start; @@ -62,7 +65,7 @@ public Integer actualStartColumn(int position) { return start; } if (tok.isComment()) { - start = Math.min(start, tok.getPosition()); + start = min(start, tok.getPosition()); } } return start; diff --git a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java index 202382640..f7c3dec95 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java +++ b/core/src/main/java/com/google/googlejavaformat/java/CommandLineOptionsParser.java @@ -54,7 +54,7 @@ static CommandLineOptions parse(Iterable options) { int idx = option.indexOf('='); if (idx >= 0) { flag = option.substring(0, idx); - value = option.substring(idx + 1, option.length()); + value = option.substring(idx + 1); } else { flag = option; value = null; diff --git a/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java b/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java index 3ccb44a46..808916c2c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java @@ -26,7 +26,7 @@ /** Checked exception class for formatter errors. */ public final class FormatterException extends Exception { - private ImmutableList diagnostics; + private final ImmutableList diagnostics; public FormatterException(String message) { this(FormatterDiagnostic.create(message)); @@ -47,7 +47,8 @@ public List diagnostics() { public static FormatterException fromJavacDiagnostics( Iterable> diagnostics) { - return new FormatterException(Iterables.transform(diagnostics, d -> toFormatterDiagnostic(d))); + return new FormatterException( + Iterables.transform(diagnostics, FormatterException::toFormatterDiagnostic)); } private static FormatterDiagnostic toFormatterDiagnostic(Diagnostic input) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java index 672d8b74b..f84e228f1 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInputAstVisitor.java @@ -139,7 +139,6 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Deque; import java.util.LinkedHashSet; import java.util.List; @@ -3270,8 +3269,7 @@ int declareOne( } Deque> dims = - new ArrayDeque<>( - typeWithDims.isPresent() ? typeWithDims.get().dims : Collections.emptyList()); + new ArrayDeque<>(typeWithDims.isPresent() ? typeWithDims.get().dims : ImmutableList.of()); int baseDims = 0; builder.open( diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java index 9564a225a..c43a91ad1 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaOutput.java @@ -14,6 +14,7 @@ package com.google.googlejavaformat.java; +import static java.lang.Math.min; import static java.util.Comparator.comparing; import com.google.common.base.CharMatcher; @@ -261,8 +262,7 @@ public ImmutableList getFormatReplacements(RangeSet iRange } } - int replaceTo = - Math.min(endTok.getPosition() + endTok.length(), javaInput.getText().length()); + int replaceTo = min(endTok.getPosition() + endTok.length(), javaInput.getText().length()); // If the formatted ranged ended in the trailing trivia of the last token before EOF, // format all the way up to EOF to deal with trailing whitespace correctly. if (endTok.getIndex() == javaInput.getkN() - 1) { @@ -304,7 +304,7 @@ public ImmutableList getFormatReplacements(RangeSet iRange } else { if (newline == -1) { // If there wasn't a trailing newline in the input, indent the next line. - replacement.append(after.substring(0, idx)); + replacement.append(after, 0, idx); } break; } @@ -352,7 +352,7 @@ public static String applyReplacements(String input, List replaceme public static int startPosition(Token token) { int min = token.getTok().getPosition(); for (Input.Tok tok : token.getToksBefore()) { - min = Math.min(min, tok.getPosition()); + min = min(min, tok.getPosition()); } return min; } diff --git a/core/src/main/java/com/google/googlejavaformat/java/Main.java b/core/src/main/java/com/google/googlejavaformat/java/Main.java index 9231bdae4..451bc697c 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -14,6 +14,7 @@ package com.google.googlejavaformat.java; +import static java.lang.Math.min; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.io.ByteStreams; @@ -109,7 +110,7 @@ public int format(String... args) throws UsageException { } private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions options) { - int numThreads = Math.min(MAX_THREADS, parameters.files().size()); + int numThreads = min(MAX_THREADS, parameters.files().size()); ExecutorService executorService = Executors.newFixedThreadPool(numThreads); Map inputs = new LinkedHashMap<>(); @@ -146,7 +147,7 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti } catch (ExecutionException e) { if (e.getCause() instanceof FormatterException) { for (FormatterDiagnostic diagnostic : ((FormatterException) e.getCause()).diagnostics()) { - errWriter.println(path + ":" + diagnostic.toString()); + errWriter.println(path + ":" + diagnostic); } } else { errWriter.println(path + ": error: " + e.getCause().getMessage()); @@ -205,7 +206,7 @@ private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions opti } } catch (FormatterException e) { for (FormatterDiagnostic diagnostic : e.diagnostics()) { - errWriter.println(stdinFilename + ":" + diagnostic.toString()); + errWriter.println(stdinFilename + ":" + diagnostic); } ok = false; // TODO(cpovirk): Catch other types of exception (as we do in the formatFiles case). diff --git a/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java b/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java index f7f610be7..42eaf45f3 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java +++ b/core/src/main/java/com/google/googlejavaformat/java/ModifierOrderer.java @@ -130,7 +130,7 @@ static JavaInput reorderModifiers(JavaInput javaInput, Collection if (i > 0) { addTrivia(replacement, modifierTokens.get(i).getToksBefore()); } - replacement.append(mods.get(i).toString()); + replacement.append(mods.get(i)); if (i < (modifierTokens.size() - 1)) { addTrivia(replacement, modifierTokens.get(i).getToksAfter()); } diff --git a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java index d93948082..b2b484adc 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java +++ b/core/src/main/java/com/google/googlejavaformat/java/RemoveUnusedImports.java @@ -16,6 +16,7 @@ package com.google.googlejavaformat.java; +import static java.lang.Math.max; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.CharMatcher; @@ -247,7 +248,7 @@ private static RangeMap buildReplacements( } // delete the import int endPosition = importTree.getEndPosition(unit.endPositions); - endPosition = Math.max(CharMatcher.isNot(' ').indexIn(contents, endPosition), endPosition); + endPosition = max(CharMatcher.isNot(' ').indexIn(contents, endPosition), endPosition); String sep = Newlines.guessLineSeparator(contents); if (endPosition + sep.length() < contents.length() && contents.subSequence(endPosition, endPosition + sep.length()).toString().equals(sep)) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java index e41bb6663..063843622 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java @@ -259,7 +259,7 @@ private static String reflow( while (!input.isEmpty()) { int length = 0; List line = new ArrayList<>(); - if (input.stream().mapToInt(x -> x.length()).sum() <= width) { + if (input.stream().mapToInt(String::length).sum() <= width) { width -= trailing; } while (!input.isEmpty() && (length <= 4 || (length + input.peekFirst().length()) < width)) { diff --git a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java index c2431c456..9c5838aeb 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java +++ b/core/src/main/java/com/google/googlejavaformat/java/javadoc/JavadocWriter.java @@ -15,6 +15,7 @@ package com.google.googlejavaformat.java.javadoc; import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.collect.Comparators.max; import static com.google.common.collect.Sets.immutableEnumSet; import static com.google.googlejavaformat.java.javadoc.JavadocWriter.AutoIndent.AUTO_INDENT; import static com.google.googlejavaformat.java.javadoc.JavadocWriter.AutoIndent.NO_AUTO_INDENT; @@ -28,7 +29,6 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Ordering; import com.google.googlejavaformat.java.javadoc.Token.Type; /** @@ -270,8 +270,7 @@ private void requestNewline() { } private void requestWhitespace(RequestedWhitespace requestedWhitespace) { - this.requestedWhitespace = - Ordering.natural().max(requestedWhitespace, this.requestedWhitespace); + this.requestedWhitespace = max(requestedWhitespace, this.requestedWhitespace); } /** diff --git a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java index 8d71f4dd6..1a4ed09b4 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/CommandLineOptionsParserTest.java @@ -19,12 +19,12 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.fail; +import com.google.common.collect.ImmutableList; import com.google.common.collect.Range; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; -import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; @@ -39,7 +39,7 @@ public class CommandLineOptionsParserTest { @Test public void defaults() { - CommandLineOptions options = CommandLineOptionsParser.parse(Collections.emptyList()); + CommandLineOptions options = CommandLineOptionsParser.parse(ImmutableList.of()); assertThat(options.files()).isEmpty(); assertThat(options.stdin()).isFalse(); assertThat(options.aosp()).isFalse(); @@ -159,7 +159,7 @@ public void illegalLines() { CommandLineOptionsParser.parse(Arrays.asList("-lines=1:1", "-lines=1:1")); fail(); } catch (IllegalArgumentException e) { - assertThat(e.getMessage()).contains("overlap"); + assertThat(e).hasMessageThat().contains("overlap"); } } diff --git a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java index 0b81ba6b4..6e48dfc5e 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java @@ -23,7 +23,6 @@ import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Locale; @@ -156,7 +155,7 @@ public void parseError2() throws FormatterException, IOException, UsageException Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("A.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -173,7 +172,7 @@ public void parseError2() throws FormatterException, IOException, UsageException public void parseErrorStdin() throws FormatterException, IOException, UsageException { String input = "class Foo { void f() {\n g() } }"; - InputStream inStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + InputStream inStream = new ByteArrayInputStream(input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), inStream); @@ -190,7 +189,7 @@ public void lexError2() throws FormatterException, IOException, UsageException { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("A.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -206,7 +205,7 @@ public void lexError2() throws FormatterException, IOException, UsageException { @Test public void lexErrorStdin() throws FormatterException, IOException, UsageException { String input = "class Foo { void f() {\n g('foo'); } }"; - InputStream inStream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + InputStream inStream = new ByteArrayInputStream(input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); Main main = new Main(new PrintWriter(out, true), new PrintWriter(err, true), inStream); diff --git a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java index 3f6e974d1..9859245c7 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java @@ -16,6 +16,7 @@ import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; +import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.fail; import com.google.common.base.Joiner; @@ -27,7 +28,6 @@ import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import org.junit.Rule; @@ -63,7 +63,7 @@ public void testFormatAosp() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("A.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -94,7 +94,7 @@ public void testFormatStdinStdoutWithDashFlag() throws Exception { String input = "class Foo{\n" + "void f\n" + "() {\n" + "}\n" + "}\n"; String expectedOutput = "class Foo {\n" + " void f() {}\n" + "}\n"; - InputStream in = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)); + InputStream in = new ByteArrayInputStream(input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -115,7 +115,7 @@ public void testFormatLengthUpToEOF() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -132,7 +132,7 @@ public void testFormatLengthOutOfRange() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -302,7 +302,7 @@ private void importOrdering(String sortArg, String outputResourceName) String inputResourceName = "com/google/googlejavaformat/java/testimports/A.input"; String input = getResource(inputResourceName); String expectedOutput = getResource(outputResourceName); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -315,14 +315,14 @@ private void importOrdering(String sortArg, String outputResourceName) assertThat(err.toString()).isEmpty(); assertThat(out.toString()).isEmpty(); - String output = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); + String output = new String(Files.readAllBytes(path), UTF_8); assertThat(output).isEqualTo(expectedOutput); } private String getResource(String resourceName) throws IOException { try (InputStream stream = getClass().getClassLoader().getResourceAsStream(resourceName)) { assertWithMessage("Missing resource: " + resourceName).that(stream).isNotNull(); - return CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); + return CharStreams.toString(new InputStreamReader(stream, UTF_8)); } } diff --git a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java index 613d3912c..fa23486fd 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/MainTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/MainTest.java @@ -14,6 +14,8 @@ package com.google.googlejavaformat.java; +import static com.google.common.base.StandardSystemProperty.JAVA_CLASS_PATH; +import static com.google.common.base.StandardSystemProperty.JAVA_HOME; import static com.google.common.truth.Truth.assertThat; import static com.google.common.truth.Truth.assertWithMessage; import static java.nio.charset.StandardCharsets.UTF_8; @@ -108,9 +110,9 @@ public void testMain() throws Exception { Process process = new ProcessBuilder( ImmutableList.of( - Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(), + Paths.get(JAVA_HOME.value()).resolve("bin/java").toString(), "-cp", - System.getProperty("java.class.path"), + JAVA_CLASS_PATH.value(), Main.class.getName())) .redirectError(Redirect.PIPE) .redirectOutput(Redirect.PIPE) @@ -388,9 +390,9 @@ public void dryRunFiles() throws Exception { assertThat(out.toString()) .isEqualTo( - b.toAbsolutePath().toString() + b.toAbsolutePath() + System.lineSeparator() - + c.toAbsolutePath().toString() + + c.toAbsolutePath() + System.lineSeparator()); assertThat(err.toString()).isEmpty(); } @@ -434,9 +436,9 @@ public void exitIfChangedStdin() throws Exception { Process process = new ProcessBuilder( ImmutableList.of( - Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(), + Paths.get(JAVA_HOME.value()).resolve("bin/java").toString(), "-cp", - System.getProperty("java.class.path"), + JAVA_CLASS_PATH.value(), Main.class.getName(), "-n", "--set-exit-if-changed", @@ -460,9 +462,9 @@ public void exitIfChangedFiles() throws Exception { Process process = new ProcessBuilder( ImmutableList.of( - Paths.get(System.getProperty("java.home")).resolve("bin/java").toString(), + Paths.get(JAVA_HOME.value()).resolve("bin/java").toString(), "-cp", - System.getProperty("java.class.path"), + JAVA_CLASS_PATH.value(), Main.class.getName(), "-n", "--set-exit-if-changed", @@ -474,7 +476,7 @@ public void exitIfChangedFiles() throws Exception { String err = new String(ByteStreams.toByteArray(process.getErrorStream()), UTF_8); String out = new String(ByteStreams.toByteArray(process.getInputStream()), UTF_8); assertThat(err).isEmpty(); - assertThat(out).isEqualTo(path.toAbsolutePath().toString() + System.lineSeparator()); + assertThat(out).isEqualTo(path.toAbsolutePath() + System.lineSeparator()); assertThat(process.exitValue()).isEqualTo(1); } diff --git a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java index 57d55d707..b1142b3b2 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/PartialFormattingTest.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; -import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -397,7 +396,7 @@ public void testLength() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -429,7 +428,7 @@ public void testLengthRange() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -475,7 +474,7 @@ public void statementAndComments() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -521,7 +520,7 @@ public void statementAndComments2() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -567,7 +566,7 @@ public void statementAndComments3() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -714,7 +713,7 @@ public void noTokensOnLine() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("FormatterException.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -957,7 +956,7 @@ public void lineWithTrailingComment() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1081,7 +1080,7 @@ public void outOfRangeStartLine() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1108,7 +1107,7 @@ public void outOfRangeEndLine() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1133,7 +1132,7 @@ public void testOutOfRangeLines() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1156,7 +1155,7 @@ public void testEmptyFirstLine() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1177,7 +1176,7 @@ public void testEmptyLastLine() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1429,7 +1428,7 @@ public void partialEnum() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, lines(input).getBytes(StandardCharsets.UTF_8)); + Files.write(path, lines(input).getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1459,7 +1458,7 @@ public void partialModifierOrder() throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, lines(input).getBytes(StandardCharsets.UTF_8)); + Files.write(path, lines(input).getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1505,7 +1504,7 @@ public void endOfLine() throws Exception { private String formatMain(String input, String... args) throws Exception { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Test.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); @@ -1655,7 +1654,7 @@ public void b21668189() throws Exception { private String runFormatter(String input, String[] args) throws IOException, UsageException { Path tmpdir = testFolder.newFolder().toPath(); Path path = tmpdir.resolve("Foo.java"); - Files.write(path, input.getBytes(StandardCharsets.UTF_8)); + Files.write(path, input.getBytes(UTF_8)); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); diff --git a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java index 1965febef..675bc8884 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/RemoveUnusedImportsTest.java @@ -258,7 +258,7 @@ public static Collection parameters() { }; ImmutableList.Builder builder = ImmutableList.builder(); for (String[][] inputAndOutput : inputsOutputs) { - assertThat(inputAndOutput.length).isEqualTo(2); + assertThat(inputAndOutput).hasLength(2); String[] input = inputAndOutput[0]; String[] output = inputAndOutput[1]; String[] parameters = { diff --git a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java index 89c94ea30..53fb54d91 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/StringWrapperIntegrationTest.java @@ -395,8 +395,8 @@ public void test() throws Exception { @Test public void testCR() throws Exception { - assertThat(StringWrapper.wrap(40, formatter.formatSource(input.replace("\n", "\r")), formatter)) - .isEqualTo(output.replace("\n", "\r")); + assertThat(StringWrapper.wrap(40, formatter.formatSource(input.replace('\n', '\r')), formatter)) + .isEqualTo(output.replace('\n', '\r')); } @Test diff --git a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java b/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java index 4fef2076b..38cac3550 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/filer/FormattingFilerTest.java @@ -52,7 +52,7 @@ public void invalidSyntaxDoesNotThrowError() throws IOException { new Messager() { @Override public void printMessage(javax.tools.Diagnostic.Kind kind, CharSequence msg) { - logMessages.add(kind.toString() + ";" + msg); + logMessages.add(kind + ";" + msg); } @Override @@ -73,9 +73,9 @@ public void printMessage( String file = Joiner.on('\n').join("package foo;", "public class Bar {"); FormattingFiler formattingFiler = new FormattingFiler(new FakeFiler(), messager); - Writer writer = formattingFiler.createSourceFile("foo.Bar").openWriter(); - writer.write(file); - writer.close(); + try (Writer writer = formattingFiler.createSourceFile("foo.Bar").openWriter()) { + writer.write(file); + } assertThat(logMessages).containsExactly("NOTE;Error formatting foo.Bar"); } diff --git a/pom.xml b/pom.xml index 82b0a3ba2..87049dec4 100644 --- a/pom.xml +++ b/pom.xml @@ -95,7 +95,7 @@ UTF-8 1.8 - 28.1-jre + 30.0-jre 1.0 3.6.1 From 0a2f8647929e361304db5d1360896152e76a7e21 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Sun, 13 Dec 2020 22:13:09 -0800 Subject: [PATCH 46/46] Prepare google-java-format for JDK 16 ea * Work around change to tokenization in JDK-8254073 * Access refactored expression pattern getters reflectively * Relax a check on a diagnostic whose position changed PiperOrigin-RevId: 347318664 --- .../googlejavaformat/java/JavacTokens.java | 20 ++++++++++++++- .../java/java14/Java14InputAstVisitor.java | 25 ++++++++++++++++--- .../googlejavaformat/java/DiagnosticTest.java | 3 +-- 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java b/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java index a8c9efd2c..ba7e3b774 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java @@ -128,10 +128,28 @@ static class CommentSavingTokenizer extends JavaTokenizer { @Override protected Comment processComment(int pos, int endPos, CommentStyle style) { - char[] buf = reader.getRawCharacters(pos, endPos); + char[] buf = getRawCharactersReflectively(pos, endPos); return new CommentWithTextAndPosition( pos, endPos, new AccessibleReader(fac, buf, buf.length), style); } + + private char[] getRawCharactersReflectively(int beginIndex, int endIndex) { + Object instance; + try { + instance = JavaTokenizer.class.getDeclaredField("reader").get(this); + } catch (ReflectiveOperationException e) { + instance = this; + } + try { + return (char[]) + instance + .getClass() + .getMethod("getRawCharacters", int.class, int.class) + .invoke(instance, beginIndex, endIndex); + } catch (ReflectiveOperationException e) { + throw new LinkageError(e.getMessage(), e); + } + } } /** A {@link Comment} that saves its text and start position. */ diff --git a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java index 78cfd66b1..2a90b939d 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java +++ b/core/src/main/java/com/google/googlejavaformat/java/java14/Java14InputAstVisitor.java @@ -29,6 +29,7 @@ import com.sun.source.tree.InstanceOfTree; import com.sun.source.tree.SwitchExpressionTree; import com.sun.source.tree.Tree; +import com.sun.source.tree.VariableTree; import com.sun.source.tree.YieldTree; import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.tree.JCTree; @@ -37,6 +38,7 @@ import com.sun.tools.javac.tree.TreeInfo; import java.util.List; import java.util.Optional; +import javax.lang.model.element.Name; /** * Extends {@link JavaInputAstVisitor} with support for AST nodes that were added or modified for @@ -51,12 +53,29 @@ public Java14InputAstVisitor(OpsBuilder builder, int indentMultiplier) { @Override public Void visitBindingPattern(BindingPatternTree node, Void unused) { sync(node); - scan(node.getType(), null); - builder.breakOp(" "); - visit(node.getBinding()); + try { + VariableTree variableTree = + (VariableTree) BindingPatternTree.class.getMethod("getVariable").invoke(node); + visitBindingPattern(variableTree.getType(), variableTree.getName()); + } catch (ReflectiveOperationException e1) { + try { + Tree type = (Tree) BindingPatternTree.class.getMethod("getType").invoke(node); + Name name = (Name) BindingPatternTree.class.getMethod("getName").invoke(node); + visitBindingPattern(type, name); + } catch (ReflectiveOperationException e2) { + e2.addSuppressed(e1); + throw new LinkageError(e2.getMessage(), e2); + } + } return null; } + private void visitBindingPattern(Tree type, Name name) { + scan(type, null); + builder.breakOp(" "); + visit(name); + } + @Override public Void visitYield(YieldTree node, Void aVoid) { sync(node); diff --git a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java index 6e48dfc5e..fc966fac3 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java @@ -97,8 +97,7 @@ public void lexError() throws Exception { int result = main.format(path.toString()); assertThat(stdout.toString()).isEmpty(); - assertThat(stderr.toString()) - .contains("InvalidSyntax.java:1:35: error: illegal unicode escape"); + assertThat(stderr.toString()).contains("error: illegal unicode escape"); assertThat(result).isEqualTo(1); }