diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1acc75a6..7197a3b6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,15 +22,14 @@ jobs: with: persist-credentials: false - # setup-java's problem matcher turns javac's warnings, Error Prone's among them, into annotations on - # the diff. This is the one job that keeps it: every other job compiles the same sources, and with - # the matcher on there too each warning showed once per job. GitHub keeps only the first ten + # The 17 line builds and tests on JDK 17 alone; 21.x is the line for JDK 21 and later. setup-java's + # problem matcher turns javac's warnings into annotations on the diff. GitHub keeps only the first ten # warnings of a step, so the annotations are the first ten warnings the parallel build prints. - - name: Install JDK 21 + - name: Install JDK 17 uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: temurin - java-version: '21' + java-version: '17' problem-matcher: true # Gradle's downloads come from the Actions cache rather than the network: the wrapper's distribution @@ -68,292 +67,3 @@ jobs: report_paths: '**/build/test-results/test/*.xml' annotate_only: true job_summary: true - - # The tests of `build` on the newer JDKs, in parallel with everything else: nothing waits for these - # jobs and nothing they build is kept. The code is still compiled for Java 21 by JDK 21, as in the - # release; -PjavaRuntime moves only the test JVMs, and with them the javac whose internals the - # formatter parses with. The IntelliJ plugin's tests stay on the runtime of the IDE they start. - # JDK 21 itself is `build`, the check the default branch requires. - jdk: - name: build (JDK ${{ matrix.jdk }}) - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - # `gradle` is what the Gradle plugins' tests build their projects with: the oldest release that runs on - # the leg's JDK (https://docs.gradle.org/current/userguide/compatibility.html#java_runtime), or 9.3.1, - # the oldest the plugins support, where that is older. Each leg thus tests the far end of what it can. - # 28-ea has none that runs on it yet. - include: - - jdk: 25 - gradle: 9.3.1 - gradle_args: '' - gradle_args_reason: '' - - jdk: 26 - gradle: 9.4.0 - gradle_args: '' - gradle_args_reason: '' - - jdk: 27 - gradle: 9.8.0 - gradle_args: '' - gradle_args_reason: '' - # Value classes (JEP 401) are a preview feature of JDK 28, so until it is released the `value` modifier - # tests (#131) run on its early-access builds and are skipped everywhere else. The version is spelled - # as setup-java spells it; Gradle gets the number alone. - - jdk: 28-ea - gradle: '' - gradle_args: -x :gradle-open-java-format:test - gradle_args_reason: >- - No Gradle release runs on Java 28 yet: 9.8.2, the newest, fails to compile a build script there with - "Unsupported class file major version 72". The Gradle plugins' tests build their projects with Gradle - on the test JVM, so they are left out until a release runs on it. - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - # No problem matcher in this job: `build` annotates the warnings. - - name: Install JDK ${{ matrix.jdk }} for the tests - id: test-jdk - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 - with: - distribution: temurin - java-version: ${{ matrix.jdk }} - problem-matcher: false - - # Installed last, so that it is the JAVA_HOME Gradle runs and compiles on. - - name: Install JDK 21 - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 - with: - distribution: temurin - java-version: '21' - problem-matcher: false - - # The same cache as in `build`. - - name: Cache Gradle's downloads - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - with: - gradle-home-cache-includes: | - caches - notifications - test-kit/caches/modules-2 - gradle-home-cache-excludes: | - caches/build-cache-1 - caches/modules-2/files-2.1/com.jetbrains.intellij.idea - caches/*/transforms - - - name: Explain the extra Gradle arguments - if: ${{ matrix.gradle_args != '' }} - env: - GRADLE_ARGS: ${{ matrix.gradle_args }} - REASON: ${{ matrix.gradle_args_reason }} - run: echo "::notice title=JDK ${{ matrix.jdk }} runs with $GRADLE_ARGS::$REASON" - - # Gradle does not look into the runner's tool cache, so it is told where the test JDK is. The path is - # a step's output, so it reaches the shell as a variable rather than being pasted into the script. - # -PjavaRuntime takes a number, so an early-access leg loses its -ea suffix here. - - name: Build - env: - TEST_JDK: ${{ steps.test-jdk.outputs.path }} - JDK: ${{ matrix.jdk }} - TESTKIT_GRADLE: ${{ matrix.gradle }} - run: >- - ./gradlew test -PjavaRuntime="${JDK%-ea}" -PtestkitGradleVersion="$TESTKIT_GRADLE" ${{ matrix.gradle_args }} - -Porg.gradle.java.installations.paths="$TEST_JDK" -PtestkitDir="$GRADLE_USER_HOME/test-kit" - - - name: Publish Test Report - uses: mikepenz/action-junit-report@a16be3a69023e9bd7e748ede768b3282ea7b30ce # v6.7.1 - if: ${{ !cancelled() }} - with: - report_paths: '**/build/test-results/test/*.xml' - annotate_only: true - job_summary: true - - # One explicit job per target, so every binary we ship is traceable to a named run. - native: - name: native (${{ matrix.runner }}) - needs: build - runs-on: ${{ matrix.runner }} - timeout-minutes: 90 - # bash on Windows too, so that every step reads the same on every runner. - defaults: - run: - shell: bash - strategy: - fail-fast: false - matrix: - # Linux on the previous Ubuntu LTS, not the newest: a binary built against a newer glibc may need that - # glibc to start, and the older one keeps the binaries running on older systems. GitHub retires an - # image once two newer ones are out. release.yml builds on the same images. Elsewhere the newest - # images; Intel macOS has no free -latest label, so its image is named. - runner: - - ubuntu-24.04 - - ubuntu-24.04-arm - # macOS on Apple silicon is built for a release only, in release.yml. - # - macos-latest - - macos-26-intel - - windows-latest - - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - # The jars compile with a Java 21 toolchain, which gradle.properties looks up in JDK21_HOME. On - # Linux and macOS Gradle also finds the runner's own JDK 21 by its location, on Windows it does not. - # Installed before GraalVM, so that Gradle itself still runs on GraalVM. No problem matcher: `build` - # annotates the warnings. - - name: Install JDK 21 for the jars - id: jdk21 - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 - with: - distribution: temurin - java-version: '21' - problem-matcher: false - - - name: Install GraalVM 25 for the image - uses: graalvm/setup-graalvm@60e76998d25690099182b796e99b8804da582d90 # v1.6.10 - with: - java-version: '25' - distribution: 'graalvm-community' - github-token: ${{ secrets.GITHUB_TOKEN }} - - # The same cache as in `build`. - - name: Cache Gradle's downloads - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - with: - gradle-home-cache-includes: | - caches - notifications - test-kit/caches/modules-2 - gradle-home-cache-excludes: | - caches/build-cache-1 - caches/modules-2/files-2.1/com.jetbrains.intellij.idea - caches/*/transforms - - - name: Compile the native image - run: ./gradlew -PnativeImage=true :open-java-format-native:nativeCompile - env: - JDK21_HOME: ${{ steps.jdk21.outputs.path }} - - # The binary itself on a file that needs formatting, a formatted one, one that does not parse and - # one in Java 25 syntax. - - name: Smoke-test the binary - run: | - binary="$PWD/$(ls open-java-format-native/build/native/nativeCompile/open-java-format-* | grep -v '\.txt$')" - mkdir smoke-test && cd smoke-test - "$binary" --version - printf 'class A{int x;}\n' > A.java - "$binary" --replace A.java - printf 'class A {\n int x;\n}\n' | diff - A.java - "$binary" --dry-run --set-exit-if-changed A.java - printf 'class B {\n' > B.java - set +e; "$binary" B.java; status=$?; set -e - test "$status" -eq 2 - # Java 25 syntax: a compact source file with a module import and an unnamed pattern. - printf 'import module java.base;\nrecord Box(int a,int b){}\nvoid main(){Object o=new Box(1,2);if(o instanceof Box(_,_)){IO.println(List.of(1));}}\n' > C.java - "$binary" --replace C.java - printf 'import module java.base;\n\nrecord Box(int a, int b) {}\n\nvoid main() {\n Object o = new Box(1, 2);\n if (o instanceof Box(_, _)) {\n IO.println(List.of(1));\n }\n}\n' | diff - C.java - - # Packaged as release.yml packages it for the GitHub release and the apt repository, under the version - # the binary prints. - - name: Find the binary and its version - id: binary - if: runner.os == 'Linux' - run: | - binary="$(ls open-java-format-native/build/native/nativeCompile/open-java-format-* | grep -v '\.txt$')" - echo "path=$binary" >> "$GITHUB_OUTPUT" - echo "version=$("$binary" --version 2>&1 | sed -n 's/^open-java-format: Version //p')" >> "$GITHUB_OUTPUT" - - - name: Package and install the binary as a .deb - if: runner.os == 'Linux' - uses: $/.github/actions/deb-package - with: - binary: ${{ steps.binary.outputs.path }} - version: ${{ steps.binary.outputs.version }} - out-dir: ${{ runner.temp }}/deb-package - - - name: Test the plugins against the image - run: >- - ./gradlew -PnativeImage=true -PtestkitDir="$GRADLE_USER_HOME/test-kit" - :open-java-format-jdk-bootstrap:test :gradle-open-java-format:test - env: - JDK21_HOME: ${{ steps.jdk21.outputs.path }} - - - name: Publish Test Report - uses: mikepenz/action-junit-report@a16be3a69023e9bd7e748ede768b3282ea7b30ce # v6.7.1 - if: ${{ !cancelled() }} - with: - report_paths: '**/build/test-results/test/*.xml' - annotate_only: true - job_summary: true - - # The WebAssembly module, built and tested as the release's `wasm` job does, so that a change that breaks it shows - # in its pull request rather than in a release. The module itself is not kept. - wasm: - name: wasm - needs: build - runs-on: ubuntu-latest - timeout-minutes: 60 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - # The jars compile with Java 21 through JDK21_HOME, as in `native`. Installed before GraalVM, so that Gradle - # still runs on GraalVM. No problem matcher: `build` annotates the warnings. - - name: Install JDK 21 for the jars - id: jdk21 - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 - with: - distribution: temurin - java-version: '21' - problem-matcher: false - - # The same release as in release.yml: Web Image is experimental, and its options and output change between - # releases. - - name: Install Oracle GraalVM 25 for the module - uses: graalvm/setup-graalvm@60e76998d25690099182b796e99b8804da582d90 # v1.6.10 - with: - java-version: '25.0.4' - distribution: 'graalvm' - github-token: ${{ secrets.GITHUB_TOKEN }} - - # Web Image runs wasm-opt from the PATH, and needs Binaryen 119 or later; Ubuntu's package is older. - - name: Install Binaryen - env: - BINARYEN_VERSION: version_133 - BINARYEN_SHA256: 2dc9c7813f5375db93d96ead4b78222fcc3e2677bbb832297af4797782a37489 - run: | - archive="binaryen-${BINARYEN_VERSION}-x86_64-linux.tar.gz" - curl --fail --silent --show-error --location --output "${RUNNER_TEMP}/${archive}" \ - "https://github.com/WebAssembly/binaryen/releases/download/${BINARYEN_VERSION}/${archive}" - echo "${BINARYEN_SHA256} ${RUNNER_TEMP}/${archive}" | sha256sum --check - tar -xzf "${RUNNER_TEMP}/${archive}" -C "${RUNNER_TEMP}" - echo "${RUNNER_TEMP}/binaryen-${BINARYEN_VERSION}/bin" >> "$GITHUB_PATH" - - # Node 24 has the WebAssembly GC and exception handling the module needs. - - name: Install Node.js 24 for the tests - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 - with: - node-version: '24' - package-manager-cache: false - - # The same cache as in `build`. - - name: Cache Gradle's downloads - uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 - with: - gradle-home-cache-includes: | - caches - notifications - test-kit/caches/modules-2 - gradle-home-cache-excludes: | - caches/build-cache-1 - caches/modules-2/files-2.1/com.jetbrains.intellij.idea - caches/*/transforms - - # wasmTest: the smoke test, then every Java 21 and Java 25 test case's input against the runnable jar. - - name: Build and test the module - run: ./gradlew -Pwasm=true :open-java-format-wasm:wasmTest - env: - JDK21_HOME: ${{ steps.jdk21.outputs.path }} diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 286e3ef4..ab12fdf3 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -31,11 +31,11 @@ jobs: persist-credentials: false # No problem matcher: the javac warnings are annotated by CI's `build` job. - - name: Set up JDK 21 + - name: Set up JDK 17 uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: temurin - java-version: '21' + java-version: '17' problem-matcher: false - name: Initialize CodeQL diff --git a/.github/workflows/dependency-submission.yml b/.github/workflows/dependency-submission.yml index 3e797285..ee3fbee6 100644 --- a/.github/workflows/dependency-submission.yml +++ b/.github/workflows/dependency-submission.yml @@ -19,7 +19,7 @@ jobs: uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 with: distribution: temurin - java-version: '21' + java-version: '17' - name: Submit Dependency Snapshot uses: gradle/actions/dependency-submission@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 diff --git a/build.gradle b/build.gradle index 602c9fd8..00306dbe 100644 --- a/build.gradle +++ b/build.gradle @@ -6,8 +6,10 @@ buildscript { dependencies { classpath 'com.gradle.publish:plugin-publish-plugin:2.2.1' - // The released open-java-format formats this repository, not the one being built here. - classpath 'dev.openjavaformat:gradle-open-java-format:21.0.2' + // The released open-java-format formats this repository, not the one being built here. The 21 line's + // plugin does not load on Gradle with JDK 17, so the 17 line applies none until 17.1.0 is out; until then, + // changes made on the branch are formatted with the 21 line's -all.jar. + // classpath 'dev.openjavaformat:gradle-open-java-format:21.0.2' classpath 'me.champeau.jmh:jmh-gradle-plugin:0.7.4' } } @@ -47,7 +49,7 @@ def javacInternalExports = [ ] allprojects { - apply plugin: 'dev.openjavaformat.java-format' + // apply plugin: 'dev.openjavaformat.java-format' // The fork's Maven group (README, "Coordinates"). The Java packages stay com.palantir.javaformat. group = 'dev.openjavaformat' @@ -84,7 +86,6 @@ allprojects { subprojects { apply plugin: 'java-library' apply plugin: 'open-java-format.java-conventions' - apply plugin: 'open-java-format.error-prone-conventions' // Bans Guava's immutable collections, but not in the SPI: FormatterService.getFormatReplacements keeps // returning ImmutableList, so that code compiled against an older SPI still links. diff --git a/buildSrc/build.gradle b/buildSrc/build.gradle index a565b5a7..664b2912 100644 --- a/buildSrc/build.gradle +++ b/buildSrc/build.gradle @@ -11,8 +11,6 @@ repositories { } dependencies { - implementation 'net.ltgt.gradle:gradle-errorprone-plugin:5.2.0' - implementation 'net.ltgt.gradle:gradle-nullaway-plugin:3.3.0' implementation 'de.thetaphi:forbiddenapis:3.11' implementation 'org.jreleaser:org.jreleaser.gradle.plugin:1.26.0' } diff --git a/buildSrc/src/main/groovy/open-java-format.error-prone-conventions.gradle b/buildSrc/src/main/groovy/open-java-format.error-prone-conventions.gradle deleted file mode 100644 index bed65bfb..00000000 --- a/buildSrc/src/main/groovy/open-java-format.error-prone-conventions.gradle +++ /dev/null @@ -1,55 +0,0 @@ -// Error Prone with NullAway and Picnic's error-prone-support checks, on the plain net.ltgt plugins. -plugins { - id 'net.ltgt.errorprone' - id 'net.ltgt.nullaway' -} - -dependencies { - errorprone libs.errorprone.core - errorprone libs.nullaway - errorprone libs.errorProneSupport.contrib -} - -nullaway { - severity = net.ltgt.gradle.errorprone.CheckSeverity.ERROR - annotatedPackages.add('com.palantir') - jspecifyMode = true -} - -tasks.withType(JavaCompile).configureEach { - // JSpecify mode reads @Nullable on types from class files, which javac 21 does only with this flag. - options.compilerArgs.add('-XDaddTypeAnnotationsToSymbol=true') - options.errorprone { - // Annotation processor output (Immutables) is not ours to fix. - excludedPaths = '.*/build/generated/.*' - nullaway { - handleTestAssertionLibraries = true - } - error('AlmostJavadoc') - error('CanonicalAnnotationSyntax') - error('CollectorMutability') - error('DefaultCharset') - error('DirectReturn') - error('EffectivelyPrivate') - error('FormatStringConcatenation') - error('JUnitClassModifiers') - error('JUnitMethodDeclaration') - error('RedundantStringConversion') - error('RefactorSwitch') - error('SameNameButDifferent') - error('StringConcatToTextBlock') - error('UnrecognisedJavadocTag') - error('UnusedVariable') - disable('IsInstanceLambdaUsage') - disable('LexicographicalAnnotationAttributeListing') - disable('LexicographicalAnnotationListing') - disable('StringJoining') - } -} - -// Gradle injects services through abstract @Inject getters, which is what this check forbids. -pluginManager.withPlugin('java-gradle-plugin') { - tasks.withType(JavaCompile).configureEach { - options.errorprone.disable('JavaxInjectOnAbstractMethod') - } -} diff --git a/buildSrc/src/main/groovy/open-java-format.java-conventions.gradle b/buildSrc/src/main/groovy/open-java-format.java-conventions.gradle index b5a33773..74f9320e 100644 --- a/buildSrc/src/main/groovy/open-java-format.java-conventions.gradle +++ b/buildSrc/src/main/groovy/open-java-format.java-conventions.gradle @@ -1,16 +1,15 @@ // Java compilation and tests for every module: what palantir/gradle-baseline used to set, in plain Gradle. plugins { id 'java' - id 'checkstyle' } -// The JDK the tests run on, and with it the javac whose internals the formatter parses with. The code is -// compiled for 21 whatever this says. CI's `jdk` jobs pass -PjavaRuntime=25 and so on. -ext.javaRuntime = providers.gradleProperty('javaRuntime').getOrElse('21') +// The JDK the tests run on, and with it the javac whose internals the formatter parses with. The 17 line builds and +// tests on JDK 17 only; 21.x is the line for JDK 21 and later. +ext.javaRuntime = providers.gradleProperty('javaRuntime').getOrElse('17') java { toolchain { - languageVersion = JavaLanguageVersion.of(21) + languageVersion = JavaLanguageVersion.of(17) } } @@ -28,11 +27,6 @@ tasks.withType(Javadoc).configureEach { options.tags('apiNote', 'implSpec', 'implNote') } -// The configuration is Gradle's default, config/checkstyle in the root project. -checkstyle { - toolVersion = libs.versions.checkstyle.get() -} - tasks.withType(AbstractArchiveTask).configureEach { duplicatesStrategy = DuplicatesStrategy.WARN } diff --git a/gradle-open-java-format/build.gradle b/gradle-open-java-format/build.gradle index 45453015..f36b2bb8 100644 --- a/gradle-open-java-format/build.gradle +++ b/gradle-open-java-format/build.gradle @@ -99,11 +99,12 @@ configurations { dependencies { impl project(':open-java-format') - formatterNativeImage(project(':open-java-format-native')) { - attributes { - attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements, 'nativeImage')) - } - } + // The 17 line builds no native image: open-java-format-native is not in settings.gradle. + // formatterNativeImage(project(':open-java-format-native')) { + // attributes { + // attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements, 'nativeImage')) + // } + // } } tasks.register("copyNativeImage", Copy.class) { diff --git a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java index 1a1114ff..9245d9a0 100644 --- a/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java +++ b/gradle-open-java-format/src/main/java/com/palantir/javaformat/gradle/XmlUtils.java @@ -135,32 +135,33 @@ private static void print(Node node, String indent, StringBuilder out) { } private static void printInline(Node node, StringBuilder out) { - switch (node) { - case Element element -> { - printStartTag(element, out); - var children = children(element); - if (children.isEmpty()) { - out.append(" />"); - } else { - out.append('>'); - for (var child : children) { - printInline(child, out); - } - out.append("'); + if (node instanceof Element element) { + printStartTag(element, out); + var children = children(element); + if (children.isEmpty()) { + out.append(" />"); + } else { + out.append('>'); + for (var child : children) { + printInline(child, out); } + out.append("'); } - case CDATASection cdata -> - out.append(""); - case Text text -> out.append(escape(text.getData(), false)); - case Comment comment -> out.append(""); - case ProcessingInstruction instruction -> { - out.append(""); + } else if (node instanceof CDATASection cdata) { + // Before Text, which a CDATASection also is. + out.append(""); + } else if (node instanceof Text text) { + out.append(escape(text.getData(), false)); + } else if (node instanceof Comment comment) { + out.append(""); + } else if (node instanceof ProcessingInstruction instruction) { + out.append(" throw new IllegalArgumentException("Unexpected XML node: " + node); + out.append("?>"); + } else { + throw new IllegalArgumentException("Unexpected XML node: " + node); } } diff --git a/gradle.properties b/gradle.properties index be6acf4b..55c397f8 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,19 +7,16 @@ org.gradle.jvmargs=--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAME --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED \ --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED -# Read by the released dev.openjavaformat.java-format plugin that formats this repository (applied -# in build.gradle): formatDiff runs its native image instead of the formatter inside the Gradle JVM. -openjavaformat.native.formatter=true +# Read by the released dev.openjavaformat.java-format plugin that formats this repository, which the 17 line does +# not apply until 17.1.0 is out (build.gradle); the 17 line publishes no native image of its own. +# openjavaformat.native.formatter=true -# Where Gradle looks for JDKs. Auto-detection only reads JAVA_HOME, and CI overwrites that with -# the JDK 21 used for the jars — so without this line GraalVM stays invisible and nativeCompile -# fails with "Cannot find a Java installation ... vendor=GraalVM Community". Locally these are -# unset and mise's installs are found through Gradle's asdf provider instead. +# Where Gradle looks for JDKs: the 17 line needs JDK 17 alone. Locally JDK17_HOME is unset and mise's install is +# found through Gradle's asdf provider instead. # -# Auto-provisioning stays off deliberately: it cannot produce a working GraalVM anyway, because -# unpacking a downloaded JDK does not preserve the symlink GraalVM ships at bin/native-image. +# Auto-provisioning stays off deliberately, as on the 21 line: the JDK is the one mise or CI installs. org.gradle.java.installations.auto-download=false -org.gradle.java.installations.fromEnv=JDK21_HOME,GRAALVM_HOME +org.gradle.java.installations.fromEnv=JDK17_HOME # Configuration cache off for now: parts of this build are not cache-safe yet — the GraalVM plugin # cannot serialise its NativeConfigurations bean (see README, phase 1) — and chasing a stale entry diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 0e9f3db8..1aeab868 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -2,10 +2,6 @@ # (versions.props + versions.lock): a version catalog is plain Gradle, and Dependabot # updates it, which it could not do for versions.props. -[versions] -# Checkstyle, run by open-java-format.java-conventions with the configuration in config/checkstyle. -checkstyle = "14.3.0" - [libraries] # Eclipse bundles the plugin compiles against. compileOnly: at runtime the host IDE # provides them, and META-INF/MANIFEST.MF imports the packages without version ranges. @@ -21,11 +17,6 @@ assertj = { module = "org.assertj:assertj-core", version = "3.27.7" } autoService = { module = "com.google.auto.service:auto-service", version = "1.1.1" } caffeine = { module = "com.github.ben-manes.caffeine:caffeine", version = "3.3.1" } compileTesting = { module = "com.google.testing.compile:compile-testing", version = "0.24.0" } -# Error Prone, the checks it runs: open-java-format.error-prone-conventions. error-prone-contrib is -# Picnic's error-prone-support, built against one Error Prone release; keep the two in step. -errorprone-core = { module = "com.google.errorprone:error_prone_core", version = "2.52.0" } -errorProneSupport-contrib = { module = "tech.picnic.error-prone-support:error-prone-contrib", version = "0.30.0" } -nullaway = { module = "com.uber.nullaway:nullaway", version = "0.14.3" } functionaljava = { module = "org.functionaljava:functionaljava", version = "5.0" } guava = { module = "com.google.guava:guava", version = "33.8.0-jre" } guava-testlib = { module = "com.google.guava:guava-testlib", version = "33.8.0-jre" } diff --git a/mise.toml b/mise.toml index 3acdd0cf..2b284448 100644 --- a/mise.toml +++ b/mise.toml @@ -1,7 +1,7 @@ # Development tooling for open-java-format. # [tools] -java = "temurin-21" +java = "temurin-17" act = "latest" [tasks."ci:list"] @@ -13,12 +13,8 @@ description = "Dry-run every CI job: resolves images, actions and steps, execute run = "act push --dryrun" [tasks."ci:build"] -description = "Run the linux jar+native build job locally in Docker (slow: downloads JDKs, runs all tests)" -run = "act push --job build --env JAVA_HOME=/opt/hostedtoolcache/Java_Temurin-Hotspot_jdk/21.0.12-101.0.LTS/arm64" - -[tasks."ci:native"] -description = "Run the linux-aarch64 native job locally in Docker" -run = "act push --job native --matrix runner:ubuntu-26.04-arm" +description = "Run the build job locally in Docker (slow: downloads the JDK, runs all tests)" +run = "act push --job build" # ---- GitHub Actions secrets ---- # Read from 1Password at apply time; nothing secret is stored in the repo. Requires gh diff --git a/open-java-format-jdk-bootstrap/build.gradle b/open-java-format-jdk-bootstrap/build.gradle index fc516204..4aee660b 100644 --- a/open-java-format-jdk-bootstrap/build.gradle +++ b/open-java-format-jdk-bootstrap/build.gradle @@ -16,11 +16,12 @@ dependencies { testImplementation libs.assertj testImplementation libs.jackson.databind - formatterNativeImage(project(':open-java-format-native')) { - attributes { - attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements, 'nativeImage')) - } - } + // The 17 line builds no native image: open-java-format-native is not in settings.gradle. + // formatterNativeImage(project(':open-java-format-native')) { + // attributes { + // attribute(LibraryElements.LIBRARY_ELEMENTS_ATTRIBUTE, project.objects.named(LibraryElements, 'nativeImage')) + // } + // } } tasks.named('test', Test.class) { diff --git a/open-java-format/src/main/java/com/palantir/javaformat/BreakBehaviour.java b/open-java-format/src/main/java/com/palantir/javaformat/BreakBehaviour.java index fa2c1b15..cdaf2865 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/BreakBehaviour.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/BreakBehaviour.java @@ -104,17 +104,18 @@ final class Json extends JsonSerializer { public void serialize(BreakBehaviour value, JsonGenerator gen, SerializerProvider serializers) throws IOException { gen.writeStartObject(); - switch (value) { - case BreakThisLevel() -> gen.writeObjectField("type", "breakThisLevel"); - case PreferBreakingLastInnerLevel(boolean keepIndentWhenInlined) -> { - gen.writeObjectField("type", "preferBreakingLastInnerLevel"); - gen.writeObjectField("keepIndentWhenInlined", keepIndentWhenInlined); - } - case InlineSuffix() -> gen.writeObjectField("type", "inlineSuffix"); - case BreakOnlyIfInnerLevelsThenFitOnOneLine(boolean keepIndentWhenInlined) -> { - gen.writeObjectField("type", "breakOnlyIfInnerLevelsThenFitOnOneLine"); - gen.writeObjectField("keepIndentWhenInlined", keepIndentWhenInlined); - } + if (value instanceof BreakThisLevel) { + gen.writeObjectField("type", "breakThisLevel"); + } else if (value instanceof PreferBreakingLastInnerLevel prefer) { + gen.writeObjectField("type", "preferBreakingLastInnerLevel"); + gen.writeObjectField("keepIndentWhenInlined", prefer.keepIndentWhenInlined()); + } else if (value instanceof InlineSuffix) { + gen.writeObjectField("type", "inlineSuffix"); + } else if (value instanceof BreakOnlyIfInnerLevelsThenFitOnOneLine breakOnly) { + gen.writeObjectField("type", "breakOnlyIfInnerLevelsThenFitOnOneLine"); + gen.writeObjectField("keepIndentWhenInlined", breakOnly.keepIndentWhenInlined()); + } else { + throw new IllegalStateException("Unknown break behaviour: " + value); } gen.writeEndObject(); } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java index 64f87cab..9b968753 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/doc/Level.java @@ -222,13 +222,17 @@ public BreakImpl(CommentsHelper commentsHelper, int maxWidth, State state, Obs.L } State apply(BreakBehaviour breakBehaviour) { - return switch (breakBehaviour) { - case BreakThisLevel() -> breakThisLevel(); - case PreferBreakingLastInnerLevel unused -> preferBreakingLastInnerLevel(); - case InlineSuffix() -> inlineSuffix(); - case BreakOnlyIfInnerLevelsThenFitOnOneLine(boolean keepIndentWhenInlined) -> - breakOnlyIfInnerLevelsThenFitOnOneLine(keepIndentWhenInlined); - }; + if (breakBehaviour instanceof BreakThisLevel) { + return breakThisLevel(); + } else if (breakBehaviour instanceof PreferBreakingLastInnerLevel) { + return preferBreakingLastInnerLevel(); + } else if (breakBehaviour instanceof InlineSuffix) { + return inlineSuffix(); + } else if (breakBehaviour instanceof BreakOnlyIfInnerLevelsThenFitOnOneLine breakOnly) { + return breakOnlyIfInnerLevelsThenFitOnOneLine(breakOnly.keepIndentWhenInlined()); + } else { + throw new IllegalStateException("Unknown break behaviour: " + breakBehaviour); + } } private Exploration breakNormally(State state) { @@ -561,78 +565,78 @@ private static Optional tryBreakInnerLevel_checkInner( boolean isSimpleInlining, State state) { // Try to fit the entire inner prefix if it's that kind of level. - return switch (innerLevel.getBreakBehaviour()) { - case PreferBreakingLastInnerLevel(boolean keepIndentWhenInlined) -> { - State state1 = - keepIndentWhenInlined ? state.withIndentIncrementedBy(innerLevel.getPlusIndent()) : state; - - yield explorationNode - .newChildNode(innerLevel, state1) - .maybeExplore( - "recurse into inner tryBreakLastLevel", - state1, - exp -> innerLevel.tryBreakLastLevel( - commentsHelper, maxWidth, state1, exp, isSimpleInlining)) - .map(Exploration::markAccepted); - } - case InlineSuffix() -> - explorationNode - .newChildNode(innerLevel, state) - .maybeExplore( - "recurse into inner tryInlineSuffix", - state, - exp -> innerLevel.tryInlineSuffix( - commentsHelper, maxWidth, state, exp, isSimpleInlining)) - .map(Exploration::markAccepted); - case BreakOnlyIfInnerLevelsThenFitOnOneLine(boolean keepIndentWhenInlined) -> { - // This case currently only matches lambda _expressions_ (without curlies) - State state1 = - keepIndentWhenInlined ? state.withIndentIncrementedBy(innerLevel.getPlusIndent()) : state; - - String humanDescription = "end tryBreakLastLevel chain -> breakOnlyIfInnerLevelsThenFitOnOneLine"; - LevelNode levelNode = explorationNode.newChildNode(innerLevel, state1); - yield levelNode - .maybeExplore(humanDescription, state1, exp -> { - // Not all levels would look good if inlined in this position, so we accept - // levels that are meant to look good even if partially inlined, e.g. method - // chains, which will catch things like builders, but not other kinds of levels like - // constant expressions. - // See the palantir-expression-lambdas cases in test-cases-java17/testdata for an example of - // what this is trying to avoid. - - // For this, need to actually check the last inner level of `lastLevel` (2 levels down). - if (innerLevel.docs.isEmpty() || !(getLast(innerLevel.docs) instanceof Level)) { + var breakBehaviour = innerLevel.getBreakBehaviour(); + if (breakBehaviour instanceof PreferBreakingLastInnerLevel prefer) { + boolean keepIndentWhenInlined = prefer.keepIndentWhenInlined(); + State state1 = keepIndentWhenInlined ? state.withIndentIncrementedBy(innerLevel.getPlusIndent()) : state; + + return explorationNode + .newChildNode(innerLevel, state1) + .maybeExplore( + "recurse into inner tryBreakLastLevel", + state1, + exp -> innerLevel.tryBreakLastLevel( + commentsHelper, maxWidth, state1, exp, isSimpleInlining)) + .map(Exploration::markAccepted); + } else if (breakBehaviour instanceof InlineSuffix) { + return explorationNode + .newChildNode(innerLevel, state) + .maybeExplore( + "recurse into inner tryInlineSuffix", + state, + exp -> innerLevel.tryInlineSuffix(commentsHelper, maxWidth, state, exp, isSimpleInlining)) + .map(Exploration::markAccepted); + } else if (breakBehaviour instanceof BreakOnlyIfInnerLevelsThenFitOnOneLine breakOnly) { + boolean keepIndentWhenInlined = breakOnly.keepIndentWhenInlined(); + // This case currently only matches lambda _expressions_ (without curlies) + State state1 = keepIndentWhenInlined ? state.withIndentIncrementedBy(innerLevel.getPlusIndent()) : state; + + String humanDescription = "end tryBreakLastLevel chain -> breakOnlyIfInnerLevelsThenFitOnOneLine"; + LevelNode levelNode = explorationNode.newChildNode(innerLevel, state1); + return levelNode + .maybeExplore(humanDescription, state1, exp -> { + // Not all levels would look good if inlined in this position, so we accept + // levels that are meant to look good even if partially inlined, e.g. method + // chains, which will catch things like builders, but not other kinds of levels like + // constant expressions. + // See the palantir-expression-lambdas cases in test-cases-java17/testdata for an example of + // what this is trying to avoid. + + // For this, need to actually check the last inner level of `lastLevel` (2 levels down). + if (innerLevel.docs.isEmpty() || !(getLast(innerLevel.docs) instanceof Level)) { + return Optional.empty(); + } + Level lastLevel2 = ((Level) getLast(innerLevel.docs)); + switch (lastLevel2.getBreakabilityIfLastLevel()) { + case ABORT, CHECK_INNER -> { return Optional.empty(); } - Level lastLevel2 = ((Level) getLast(innerLevel.docs)); - switch (lastLevel2.getBreakabilityIfLastLevel()) { - case ABORT, CHECK_INNER -> { - return Optional.empty(); - } - case ACCEPT_INLINE_CHAIN -> { - Exploration broken = - innerLevel.breakNormally(state, levelNode, commentsHelper, maxWidth); - return innerLevel.handle_breakOnlyIfInnerLevelsThenFitOnOneLine( - commentsHelper, - maxWidth, - state1, - broken.state(), - keepIndentWhenInlined, - explorationNode); - } - case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER -> { - // specific to lambda body expressions - falls back to `breakNormally` in - // `preferBreakingLastInnerLevel` - return Optional.empty(); - } - default -> throw new RuntimeException("Unknown breakabilityIfLastLevel: " + lastLevel2); + case ACCEPT_INLINE_CHAIN -> { + Exploration broken = + innerLevel.breakNormally(state, levelNode, commentsHelper, maxWidth); + return innerLevel.handle_breakOnlyIfInnerLevelsThenFitOnOneLine( + commentsHelper, + maxWidth, + state1, + broken.state(), + keepIndentWhenInlined, + explorationNode); } - }) - .map(Exploration::markAccepted); - } + case ACCEPT_INLINE_CHAIN_IF_SIMPLE_OTHERWISE_CHECK_INNER -> { + // specific to lambda body expressions - falls back to `breakNormally` in + // `preferBreakingLastInnerLevel` + return Optional.empty(); + } + default -> throw new RuntimeException("Unknown breakabilityIfLastLevel: " + lastLevel2); + } + }) + .map(Exploration::markAccepted); + } else if (breakBehaviour instanceof BreakThisLevel) { // We don't know how to fit the inner level on the same line, so bail out. - case BreakThisLevel() -> Optional.empty(); - }; + return Optional.empty(); + } else { + throw new IllegalStateException("Unknown break behaviour: " + breakBehaviour); + } } /** diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/ExtraneousSemicolons.java b/open-java-format/src/main/java/com/palantir/javaformat/java/ExtraneousSemicolons.java new file mode 100644 index 00000000..2b746792 --- /dev/null +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/ExtraneousSemicolons.java @@ -0,0 +1,130 @@ +/* + * 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.palantir.javaformat.java; + +import com.google.common.collect.Iterables; +import com.sun.tools.javac.code.Flags; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.Tag; +import com.sun.tools.javac.tree.TreeInfo; +import com.sun.tools.javac.util.DiagnosticSource; +import java.util.ArrayList; +import java.util.List; +import javax.lang.model.SourceVersion; +import javax.tools.Diagnostic; +import javax.tools.JavaFileObject; + +/** + * The semicolons before the first type declaration that javac 21 rejects and javac 17 takes. JLS 7.3 allows none after + * the package and the import declarations. From Java 21, {@code JavacParser.parseCompilationUnit} reports a run of + * them, at its first, when an import comes after it, or a declaration that starts with an identifier once its + * modifiers are read, as a record or a module does. javac 17 takes them all, as {@code JCSkip}s, so the 17 line looks + * for those runs in its tree and reports them as javac 21 does: a file that 21.x rejects fails on 17.x with the same + * error at the same place. + */ +final class ExtraneousSemicolons { + + private static final String JAVAC_21_CODE = "compiler.err.extraneous.semicolon"; + private static final String MESSAGE = "extraneous semicolon"; + + /** + * Throws if {@code unit} has a run of semicolons that javac 21 rejects: with every such run and every one of + * {@code javacErrors}, in the order javac 21 reports them while it parses. Does nothing where javac reports them + * itself, from JDK 21 on. + */ + static void check( + Iterable> javacErrors, + JCCompilationUnit unit, + String sourceText, + DiagnosticSource source) + throws FormatterException { + if (Iterables.any(javacErrors, error -> JAVAC_21_CODE.equals(error.getCode()))) { + return; + } + var runs = runsJavac21Rejects(unit, sourceText); + if (runs.isEmpty()) { + return; + } + var errors = new ArrayList(); + var next = 0; + for (var error : javacErrors) { + while (next < runs.size() && runs.get(next) < error.getPosition()) { + errors.add(diagnostic(source, runs.get(next++))); + } + errors.add(FormatterExceptions.toFormatterDiagnostic(error)); + } + while (next < runs.size()) { + errors.add(diagnostic(source, runs.get(next++))); + } + throw new FormatterException(errors); + } + + /** The position of the first semicolon of every run that javac 21 rejects. */ + private static List runsJavac21Rejects(JCCompilationUnit unit, String sourceText) { + var runs = new ArrayList(); + // The position of the first semicolon of the run so far, or -1. + var run = -1; + for (JCTree def : unit.defs) { + if (def.hasTag(Tag.PACKAGEDEF)) { + continue; + } + if (def.hasTag(Tag.SKIP)) { + if (run < 0) { + run = def.pos; + } + continue; + } + var isImport = def.hasTag(Tag.IMPORT); + if (run >= 0 && (isImport || startsWithAnIdentifier(def, sourceText))) { + runs.add(run); + } + run = -1; + if (!isImport) { + // javac 21 takes semicolons after the first type declaration as it always did. + break; + } + } + return runs; + } + + /** + * Whether javac 21 reads an identifier once the modifiers of {@code def} are read: a record, or what javac 17 does + * not parse after a semicolon, as a module, which javac 17 reports on its own too. + */ + private static boolean startsWithAnIdentifier(JCTree def, String sourceText) { + if (def instanceof JCClassDecl classDecl) { + return (classDecl.mods.flags & Flags.RECORD) != 0; + } + // What javac 17 cannot parse is an erroneous tree with no start of its own, at the token it stopped at. + var start = TreeInfo.getStartPos(def) >= 0 ? TreeInfo.getStartPos(def) : def.pos; + var end = start; + while (end < sourceText.length() && Character.isJavaIdentifierPart(sourceText.charAt(end))) { + end++; + } + return end > start + && Character.isJavaIdentifierStart(sourceText.charAt(start)) + && !SourceVersion.isKeyword(sourceText.substring(start, end)); + } + + /** The error at {@code position}, with javac's line and column: a tab moves the column to the next multiple of 8. */ + private static FormatterDiagnostic diagnostic(DiagnosticSource source, int position) { + return FormatterDiagnostic.create( + source.getLineNumber(position), source.getColumnNumber(position, true), MESSAGE); + } + + private ExtraneousSemicolons() {} +} diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java b/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java index 6e314ffa..14350bb7 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/Formatter.java @@ -240,6 +240,8 @@ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOExcept Iterable> errorDiagnostics = Iterables.filter(diagnostics.getDiagnostics(), Formatter::errorDiagnostic); + ExtraneousSemicolons.check( + errorDiagnostics, unit, sourceText, Log.instance(context).currentSource()); if (!Iterables.isEmpty(errorDiagnostics)) { throw FormatterExceptions.fromJavacDiagnostics(errorDiagnostics); } @@ -252,30 +254,14 @@ static int getRuntimeVersion() { } /** - * The visitor that lays out the code on JDK {@code javaVersion}: {@link JavaInputAstVisitor} up to JDK 20, and from - * JDK 21 the visitor for its syntax. That one is loaded by name, so that its class, built on the syntax trees of - * JDK 21, is only loaded where the JDK has them. + * The visitor that lays out the code on JDK {@code javaVersion}: {@link JavaInputAstVisitor} on every JDK. The 17 + * line has no visitor for the syntax of JDK 21, which javac 17 cannot compile; that syntax needs 21.x. */ @VisibleForTesting static JavaInputAstVisitor visitorFor(int javaVersion, OpsBuilder builder, JavaFormatterOptions options) { - if (javaVersion >= 21) { - return createVisitor("com.palantir.javaformat.java.java21.Java21InputAstVisitor", builder, options); - } return new JavaInputAstVisitor(builder, options.indentationMultiplier()); } - private static JavaInputAstVisitor createVisitor( - final String className, final OpsBuilder builder, final JavaFormatterOptions options) { - try { - return Class.forName(className) - .asSubclass(JavaInputAstVisitor.class) - .getConstructor(OpsBuilder.class, int.class) - .newInstance(builder, options.indentationMultiplier()); - } catch (ReflectiveOperationException e) { - throw new LinkageError(e.getMessage()); - } - } - static boolean errorDiagnostic(Diagnostic input) { if (input.getKind() != Diagnostic.Kind.ERROR) { return false; diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/FormatterExceptions.java b/open-java-format/src/main/java/com/palantir/javaformat/java/FormatterExceptions.java index 5da8d6ae..903bdcf6 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/FormatterExceptions.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/FormatterExceptions.java @@ -28,7 +28,7 @@ static FormatterException fromJavacDiagnostics(Iterable input) { + static FormatterDiagnostic toFormatterDiagnostic(Diagnostic input) { return FormatterDiagnostic.create( (int) input.getLineNumber(), (int) input.getColumnNumber(), input.getMessage(ENGLISH)); } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/Main.java b/open-java-format/src/main/java/com/palantir/javaformat/java/Main.java index ea21f1e2..a8e6b79b 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/Main.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/Main.java @@ -134,10 +134,13 @@ int format(String... args) throws UsageException { private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions options) { int numThreads = Math.min(MAX_THREADS, parameters.files().size()); - // Closing the pool ends its threads, so that a tool that runs Main in-process does not keep them. The close - // waits for the submitted tasks, which formatFiles has already waited for. - try (ExecutorService executorService = Executors.newFixedThreadPool(numThreads)) { + // Shutting the pool down ends its threads, so that a tool that runs Main in-process does not keep them. + // formatFiles has already waited for the submitted tasks. Java 17 has no ExecutorService.close. + var executorService = Executors.newFixedThreadPool(numThreads); + try { return formatFiles(parameters, options, executorService); + } finally { + executorService.shutdown(); } } diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/RemoveUnusedImports.java b/open-java-format/src/main/java/com/palantir/javaformat/java/RemoveUnusedImports.java index d3594d4b..51edc613 100644 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/RemoveUnusedImports.java +++ b/open-java-format/src/main/java/com/palantir/javaformat/java/RemoveUnusedImports.java @@ -26,6 +26,7 @@ import com.google.common.collect.TreeRangeSet; import com.palantir.javaformat.Newlines; import com.sun.source.doctree.DocCommentTree; +import com.sun.source.doctree.ErroneousTree; import com.sun.source.doctree.ReferenceTree; import com.sun.source.tree.CaseTree; import com.sun.source.tree.IdentifierTree; @@ -48,6 +49,8 @@ import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.jspecify.annotations.Nullable; /** @@ -56,6 +59,10 @@ */ public class RemoveUnusedImports { + /** {@code {@link}}, {@code {@linkplain}} or {@code @see} and a reference to an anchor, with its first name. */ + private static final Pattern ANCHOR_REFERENCE = Pattern.compile("(?:\\{@link(?:plain)?|@see)\\s+" + + "(\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*)[\\p{javaJavaIdentifierPart}.]*##"); + // Visits an AST, recording all simple names that could refer to imported // types and also any javadoc references that could refer to imported // types (`@link`, `@see`, `@throws`, etc.) @@ -137,6 +144,18 @@ public Void visitIdentifier(com.sun.source.doctree.IdentifierTree node, Void aVo return null; } + // A reference to an anchor of a type, {@link Set##anchor}, which javadoc reads from JDK 20 on, is a + // reference whose qualifier is Set to javac 21, and the tag an erroneous tree to javac 17. Record the + // first name of the qualifier, as visitReference does on JDK 21. + @Override + public Void visitErroneous(ErroneousTree node, Void unused) { + Matcher anchorReference = ANCHOR_REFERENCE.matcher(node.getBody()); + if (anchorReference.lookingAt()) { + usedInJavadoc.put(anchorReference.group(1), null); + } + return null; + } + @Override public Void visitReference(ReferenceTree referenceTree, Void unused) { DCReference reference = (DCReference) referenceTree; diff --git a/open-java-format/src/main/java/com/palantir/javaformat/java/java21/Java21InputAstVisitor.java b/open-java-format/src/main/java/com/palantir/javaformat/java/java21/Java21InputAstVisitor.java deleted file mode 100644 index a0b2ebac..00000000 --- a/open-java-format/src/main/java/com/palantir/javaformat/java/java21/Java21InputAstVisitor.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * (c) Copyright 2025 Palantir Technologies Inc. All rights reserved. - * - * 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.palantir.javaformat.java.java21; - -import com.palantir.javaformat.OpsBuilder; -import com.palantir.javaformat.java.JavaInputAstVisitor; -import com.sun.source.tree.CaseTree; -import com.sun.source.tree.ConstantCaseLabelTree; -import com.sun.source.tree.DeconstructionPatternTree; -import com.sun.source.tree.DefaultCaseLabelTree; -import com.sun.source.tree.ExpressionTree; -import com.sun.source.tree.PatternCaseLabelTree; -import com.sun.source.tree.PatternTree; -import com.sun.source.tree.Tree; -import javax.lang.model.element.Name; -import org.jspecify.annotations.Nullable; - -/** - * Extends {@link JavaInputAstVisitor}, which lays out the code on JDK 17 to 20, with support for AST nodes that were - * added or modified in Java 21. - */ -public class Java21InputAstVisitor extends JavaInputAstVisitor { - // AnyPatternTree (the unnamed pattern `_`, JEP 456) is still a preview API on JDK 21, which this - // module compiles with, so match it by Tree.Kind name instead of by type. - private static final String ANY_PATTERN_KIND_NAME = "ANY_PATTERN"; - - public Java21InputAstVisitor(OpsBuilder builder, int indentMultiplier) { - super(builder, indentMultiplier); - } - - @Override - public Void scan(@Nullable Tree tree, Void unused) { - if (tree != null && tree.getKind().name().equals(ANY_PATTERN_KIND_NAME)) { - // No sync(tree): javac records the start position one past the `_`, which makes sync() - // think a token was skipped and throw. This branch emits one leaf token and never recurses. - token("_"); - return null; - } - return super.scan(tree, null); - } - - @Override - protected ExpressionTree getGuard(final CaseTree node) { - return node.getGuard(); - } - - @Override - public Void visitDefaultCaseLabel(DefaultCaseLabelTree node, Void unused) { - token("default"); - return null; - } - - @Override - public Void visitPatternCaseLabel(PatternCaseLabelTree node, Void unused) { - scan(node.getPattern(), null); - return null; - } - - @Override - public Void visitConstantCaseLabel(ConstantCaseLabelTree node, Void aVoid) { - scan(node.getConstantExpression(), null); - return null; - } - - @Override - public Void visitDeconstructionPattern(DeconstructionPatternTree node, Void unused) { - scan(node.getDeconstructor(), null); - builder.open(plusFour); - token("("); - builder.breakOp(); - boolean first = true; - for (PatternTree pattern : node.getNestedPatterns()) { - if (!first) { - token(","); - builder.breakOp(" "); - } - first = false; - scan(pattern, null); - } - builder.close(); - token(")"); - return null; - } - - @Override - protected void variableName(Name name) { - if (name.isEmpty()) { - token("_"); - } else { - visit(name); - } - } -} diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/CaseFile.java b/open-java-format/src/test/java/com/palantir/javaformat/java/CaseFile.java index a5f6775b..49d7937b 100644 --- a/open-java-format/src/test/java/com/palantir/javaformat/java/CaseFile.java +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/CaseFile.java @@ -49,18 +49,18 @@ static CaseFile parse(String path, String text) { path + ": a case has two lines of six or more dashes, found " + separators.size()); } - for (var line : text.substring(0, separators.getFirst().start()).lines().toList()) { + for (var line : text.substring(0, separators.get(0).start()).lines().toList()) { if (!line.isBlank() && !line.startsWith("#")) { throw new IllegalArgumentException(path + ": there are no settings yet, the header takes blank lines and # comments only: " + line); } } - var afterStart = separators.getLast().end(); + var afterStart = separators.get(1).end(); var afterLine = (int) text.substring(0, afterStart).lines().count() + 1; return new CaseFile( - text.substring(separators.getFirst().end(), separators.getLast().start()), + text.substring(separators.get(0).end(), separators.get(1).start()), text.substring(afterStart), afterLine); } diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/ExtraneousSemicolonsTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/ExtraneousSemicolonsTest.java new file mode 100644 index 00000000..a9851e6c --- /dev/null +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/ExtraneousSemicolonsTest.java @@ -0,0 +1,154 @@ +/* + * 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.palantir.javaformat.java; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.InstanceOfAssertFactories.list; + +import com.palantir.javaformat.java.JavaFormatterOptions.Style; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Semicolons before the first type declaration, which JLS 7.3 does not allow after the package and import + * declarations. From Java 21 javac rejects a run of them that an import or a declaration starting with an identifier + * comes after, and javac 17 takes them all. The 17 line rejects the same files as 21.1.2 does on JDK 21, with the same + * errors at the same places, and formats the rest as it does: every expectation here is what 21.1.2 answers. + */ +final class ExtraneousSemicolonsTest { + + private static final Formatter FORMATTER = Formatter.createFormatter( + JavaFormatterOptions.builder().style(Style.OJF).build()); + + static Stream rejected() { + return Stream.of( + Arguments.of("between imports", "import b.B;\n;\nimport a.A;\n\nclass T {}\n", "2:1", "2:1"), + Arguments.of("after the package", "package p;\n;\nimport a.A;\n\nclass T {}\n", "2:1", "2:1"), + Arguments.of("first in the file", ";\nimport a.A;\n\nclass T {}\n", "1:1", "1:1"), + Arguments.of("a run, at its first", "import a.A;\n;;\n;\nimport b.B;\n\nclass T {}\n", "2:1", "2:1"), + Arguments.of("after a tab", "import a.A;\n\t;\nimport b.B;\n\nclass T {}\n", "2:9", "2:9"), + Arguments.of("on the line of an import", "import a.A; ;\nimport b.B;\n\nclass T {}\n", "1:13", "1:13"), + Arguments.of( + "between lines of Windows", + "import b.B;\r\n;\r\nimport a.A;\r\n\r\nclass T {}\r\n", + "2:1", + "2:1"), + Arguments.of("before a record", "import a.A;\n;\n\nrecord R(A a) {}\n", "2:1", "3:1"), + Arguments.of( + "before an annotated record", + "import a.A;\n;\n\n@Deprecated\nrecord R(A a) {}\n", + "2:1", + "3:1"), + Arguments.of("before a public record", "import a.A;\n;\n\npublic record R(A a) {}\n", "2:1", "3:1"), + Arguments.of("before a module", "import a.A;\n;\nmodule m {}\n", "2:1", "3:1")); + } + + /** + * Fixing the imports first sets a blank line after them, before a record or a module, so that the semicolon is a + * line further down there, on 21.1.2 as here. + */ + @ParameterizedTest(name = "{0}") + @MethodSource("rejected") + void rejectsTheSemicolonsThatJavac21Rejects( + String description, String source, String position, String positionAfterFixingImports) { + assertThatThrownBy(() -> FORMATTER.formatSource(source)) + .isInstanceOf(FormatterException.class) + .hasMessage(position + ": error: extraneous semicolon"); + assertThatThrownBy(() -> FORMATTER.formatSourceAndFixImports(source)) + .isInstanceOf(FormatterException.class) + .hasMessage(positionAfterFixingImports + ": error: extraneous semicolon"); + } + + @Test + void reportsEveryRun() { + String source = "import a.A;\n;\nimport b.B;\n;\nimport c.C;\n\nclass T {}\n"; + + assertThatThrownBy(() -> FORMATTER.formatSource(source)) + .isInstanceOf(FormatterException.class) + .extracting(e -> ((FormatterException) e).diagnostics(), list(FormatterDiagnostic.class)) + .extracting(FormatterDiagnostic::toString) + .containsExactly("2:1: error: extraneous semicolon", "4:1: error: extraneous semicolon"); + } + + @Test + void reportsTheRunAmongTheOtherErrorsInTheOrderOfTheFile() { + String source = "import a.A;\n;\nimport b.B;\n\nclass T {\n int x = ;\n}\n"; + + assertThatThrownBy(() -> FORMATTER.formatSource(source)) + .isInstanceOf(FormatterException.class) + .hasMessage("2:1: error: extraneous semicolon") + .extracting(e -> ((FormatterException) e).diagnostics(), list(FormatterDiagnostic.class)) + .extracting(FormatterDiagnostic::toString) + .containsExactly("2:1: error: extraneous semicolon", "6:13: error: illegal start of expression"); + } + + static Stream accepted() { + return Stream.of( + Arguments.of( + "before a class", + "import a.A;\n;\n\nclass T {\n A a;\n}\n", + "import a.A;\n;\n\nclass T {\n A a;\n}\n"), + Arguments.of( + "before a public final class", + "import a.A;\n;\n\npublic final class T {\n A a;\n}\n", + "import a.A;\n;\n\npublic final class T {\n A a;\n}\n"), + Arguments.of( + "before a sealed interface", + "import a.A;\n" + + ";\n\n" + + "sealed interface I permits J {}\n\n" + + "final class J implements I {\n" + + " A a;\n" + + "}\n", + "import a.A;\n" + + ";\n\n" + + "sealed interface I permits J {}\n\n" + + "final class J implements I {\n" + + " A a;\n" + + "}\n"), + Arguments.of( + "before an enum", + "import a.A;\n;\n\nenum E {\n X;\n A a;\n}\n", + "import a.A;\n;\n\nenum E {\n X;\n A a;\n}\n"), + Arguments.of( + "before an interface", + "import a.A;\n;\n\ninterface I {\n A a();\n}\n", + "import a.A;\n;\n\ninterface I {\n A a();\n}\n"), + Arguments.of( + "before an annotation type", + "import a.A;\n;\n\n@interface N {\n Class a();\n}\n", + "import a.A;\n;\n\n@interface N {\n Class a();\n}\n"), + Arguments.of("at the end of the file", "import a.A;\n;\n", ";\n"), + Arguments.of( + "after the first type declaration", + "import a.A;\n\nclass T {\n A a;\n}\n;\n", + "import a.A;\n\nclass T {\n A a;\n}\n;\n"), + Arguments.of( + "before a record after the first type declaration", + "import a.A;\n\nclass T {\n A a;\n}\n;\nrecord R() {}\n", + "import a.A;\n\nclass T {\n A a;\n}\n;\n\nrecord R() {}\n")); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("accepted") + void formatsTheSemicolonsThatJavac21Takes(String description, String source, String formatted) + throws FormatterException { + assertThat(FORMATTER.formatSourceAndFixImports(source)).isEqualTo(formatted); + } +} diff --git a/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterVisitorTest.java b/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterVisitorTest.java index 74557f94..209825a6 100644 --- a/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterVisitorTest.java +++ b/open-java-format/src/test/java/com/palantir/javaformat/java/FormatterVisitorTest.java @@ -20,7 +20,6 @@ import com.palantir.javaformat.OpsBuilder; import com.palantir.javaformat.java.JavaFormatterOptions.Style; -import com.palantir.javaformat.java.java21.Java21InputAstVisitor; import java.io.ByteArrayInputStream; import java.io.PrintWriter; import java.io.StringWriter; @@ -28,23 +27,17 @@ import org.junit.jupiter.api.condition.EnabledForJreRange; import org.junit.jupiter.api.condition.JRE; -/** Which visitor lays out the code on which JDK: one for JDK 17 to 20, and {@link Java21InputAstVisitor} from 21. */ +/** Which visitor lays out the code on which JDK: on the 17 line, the one for JDK 17 on every JDK. */ final class FormatterVisitorTest { private static final JavaFormatterOptions OPTIONS = JavaFormatterOptions.builder().style(Style.OJF).build(); @Test - void jdk21AndLaterGetTheVisitorForJdk21() throws FormatterException { - assertThat(visitorFor(21)).isExactlyInstanceOf(Java21InputAstVisitor.class); - assertThat(visitorFor(25)).isExactlyInstanceOf(Java21InputAstVisitor.class); - } - - @Test - void jdk17To20GetOneVisitorThatIsNotTheOneForJdk21() throws FormatterException { - var visitor = visitorFor(17); - - assertThat(visitor).isNotInstanceOf(Java21InputAstVisitor.class); - assertThat(visitorFor(20)).isExactlyInstanceOf(visitor.getClass()); + void everyJdkGetsTheVisitorForJdk17() throws FormatterException { + assertThat(visitorFor(17)).isExactlyInstanceOf(JavaInputAstVisitor.class); + assertThat(visitorFor(20)).isExactlyInstanceOf(JavaInputAstVisitor.class); + assertThat(visitorFor(21)).isExactlyInstanceOf(JavaInputAstVisitor.class); + assertThat(visitorFor(25)).isExactlyInstanceOf(JavaInputAstVisitor.class); } /** diff --git a/open-java-format/src/test/resources/test-cases-java17/imports/javadocReferenceToAnAnchorKeepsItsImport.case b/open-java-format/src/test/resources/test-cases-java17/imports/javadocReferenceToAnAnchorKeepsItsImport.case new file mode 100644 index 00000000..ec13013e --- /dev/null +++ b/open-java-format/src/test/resources/test-cases-java17/imports/javadocReferenceToAnAnchorKeepsItsImport.case @@ -0,0 +1,25 @@ +# A Javadoc reference to an anchor of a type keeps the import of the type, in {@link}, {@linkplain} and @see alike. +# javadoc reads such a reference from JDK 20 on; javac 17 does not parse it, and the 17 line still keeps the import. +---------- +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.Unused; + +/** + * See {@link Set##unmodifiable Set.of} and {@linkplain List##lists lists}. + * + * @see Map##views + */ +public class Test {} +---------- +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * See {@link Set##unmodifiable Set.of} and {@linkplain List##lists lists}. + * + * @see Map##views + */ +public class Test {} diff --git a/settings.gradle b/settings.gradle index 21bf7b1e..316812a3 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,19 +1,21 @@ rootProject.name = 'open-java-format-parent' include ':gradle-open-java-format' -include ':open-java-format-eclipse-plugin' -include ':open-java-format-idea-plugin' +// The 17 line builds what a build on JDK 17 loads. The IDE plugins, the native image, the WebAssembly module and the +// benchmarks come with the 21 line; they stay in the tree, so that a backport that touches them applies as it is. +// include ':open-java-format-eclipse-plugin' +// include ':open-java-format-idea-plugin' include ':open-java-format-spi' include ':open-java-format' include ':open-java-format-jdk-bootstrap' -include ':open-java-format-benchmarks' -include ':open-java-format-native' +// include ':open-java-format-benchmarks' +// include ':open-java-format-native' // The WebAssembly module compiles against Oracle GraalVM, which nobody who only wants the jars has, so it is part of // the build only with -Pwasm=true. CI's and the release's `wasm` jobs build it that way; nothing else does. -if (Boolean.parseBoolean(providers.gradleProperty('wasm').getOrElse('false'))) { - include ':open-java-format-wasm' -} +// if (Boolean.parseBoolean(providers.gradleProperty('wasm').getOrElse('false'))) { +// include ':open-java-format-wasm' +// } boolean isCiServer = System.getenv().containsKey('CI') buildCache {