From 722d074791787034c35d15adc785bf4d0f6ace21 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Thu, 29 Oct 2026 06:22:04 -0700 Subject: [PATCH] Report string wrapping failures without crashing or hanging the CLI. When reflowing long strings produced code that didn't parse, `StringWrapper` propagated javac's diagnostics, whose line numbers refer to the reflowed output. `Main` then printed them against the original input, and `FormatterException.formatDiagnostics` threw `IndexOutOfBoundsException` if the error was past the input's last line. Because `Main.formatFiles` only shut down its thread pool at the end, that exception also left non-daemon worker threads running, so the CLI hung instead of exiting. `StringWrapper` now reports an output that doesn't parse as an internal error, like the existing check for AST changes, `formatDiagnostics` skips the source context for out-of-range positions, and `Main` shuts down its thread pool even if formatting throws. This is the crash reported in https://github.com/google/google-java-format/issues/1439. PiperOrigin-RevId: 1009639357 --- .../java/FormatterException.java | 2 +- .../google/googlejavaformat/java/Main.java | 23 ++++++++-- .../googlejavaformat/java/StringWrapper.java | 32 +++++++++---- .../googlejavaformat/java/DiagnosticTest.java | 46 +++++++++++++++++++ 4 files changed, 88 insertions(+), 15 deletions(-) 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 b83d51eb1..c0598a2f4 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java +++ b/core/src/main/java/com/google/googlejavaformat/java/FormatterException.java @@ -68,7 +68,7 @@ public String formatDiagnostics(String path, String input) { sb.append(path).append(":").append(diagnostic).append(System.lineSeparator()); int line = diagnostic.line(); int column = diagnostic.column(); - if (line != -1 && column != -1) { + if (line > 0 && column > 0 && line <= lines.size()) { sb.append(CharMatcher.breakingWhitespace().trimTrailingFrom(lines.get(line - 1))) .append(System.lineSeparator()); sb.append(" ".repeat(column - 1)).append('^').append(System.lineSeparator()); 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 72f44d164..31ffcbaac 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/Main.java +++ b/core/src/main/java/com/google/googlejavaformat/java/Main.java @@ -125,7 +125,24 @@ public int format(String... args) throws UsageException { private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions options) { int numThreads = min(MAX_THREADS, parameters.files().size()); ExecutorService executorService = Executors.newFixedThreadPool(numThreads); + boolean allOk; + try { + allOk = formatFiles(parameters, options, executorService); + } finally { + // Shut down the executor even if formatting throws, otherwise its non-daemon threads keep the + // JVM alive. + if (!MoreExecutors.shutdownAndAwaitTermination(executorService, Duration.ofSeconds(5))) { + errWriter.println("Failed to shut down ExecutorService"); + allOk = false; + } + } + return allOk ? 0 : 1; + } + private boolean formatFiles( + CommandLineOptions parameters, + JavaFormatterOptions options, + ExecutorService executorService) { ExecutorCompletionService cs = new ExecutorCompletionService<>(executorService); boolean allOk = true; @@ -195,11 +212,7 @@ private int formatFiles(CommandLineOptions parameters, JavaFormatterOptions opti outWriter.write(formatted); } } - if (!MoreExecutors.shutdownAndAwaitTermination(executorService, Duration.ofSeconds(5))) { - errWriter.println("Failed to shut down ExecutorService"); - allOk = false; - } - return allOk ? 0 : 1; + return allOk; } private int formatStdin(CommandLineOptions parameters, JavaFormatterOptions options) { 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 c199b8673..787c98361 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java +++ b/core/src/main/java/com/google/googlejavaformat/java/StringWrapper.java @@ -80,22 +80,36 @@ static String wrap(final int columnLimit, String input, Formatter formatter) // We really don't want bugs in this pass to change the behaviour of programs we're // formatting, so check that the pretty-printed AST is the same before and after reformatting. String expected = parse(input, /* allowStringFolding= */ true).toString(); - String actual = parse(result, /* allowStringFolding= */ true).toString(); + String actual; + try { + actual = parse(result, /* allowStringFolding= */ true).toString(); + } catch (FormatterException e) { + // Diagnostics for the reflowed output don't correspond to positions in the original input, + // and the error is a bug in this pass rather than in the input, so report it as such. + throw somethingHasGoneTerriblyWrong( + "it would produce code that does not parse (" + e.getMessage() + ")", result, input); + } if (!expected.equals(actual)) { - throw new FormatterException( - String.format( - "Something has gone terribly wrong. We planned to make the below formatting change," - + " but have aborted because it would unexpectedly change the AST.\n" - + "Please file a bug: " - + "https://github.com/google/google-java-format/issues/new" - + "\n\n=== Actual: ===\n%s\n=== Expected: ===\n%s\n", - actual, expected)); + throw somethingHasGoneTerriblyWrong( + "it would unexpectedly change the AST", actual, expected); } } return result; } + private static FormatterException somethingHasGoneTerriblyWrong( + String reason, String actual, String expected) { + return new FormatterException( + String.format( + "Something has gone terribly wrong. We planned to make the below formatting change," + + " but have aborted because %s.\n" + + "Please file a bug: " + + "https://github.com/google/google-java-format/issues/new" + + "\n\n=== Actual: ===\n%s\n=== Expected: ===\n%s\n", + reason, actual, expected)); + } + private static TreeRangeMap getReflowReplacements( int columnLimit, final String input, JavaFormatterOptions options) throws FormatterException { return new Reflower(columnLimit, input, options).getReflowReplacements(); 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 d8009a87c..ab3599fed 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java @@ -17,6 +17,7 @@ import static com.google.common.truth.Truth.assertThat; import static java.nio.charset.StandardCharsets.UTF_8; +import com.google.googlejavaformat.FormatterDiagnostic; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -100,6 +101,51 @@ public void lexError() throws Exception { assertThat(result).isEqualTo(1); } + @Test + public void formatDiagnostics_positionOutOfRange() { + String input = "class T {}\n"; + assertThat( + new FormatterException(new FormatterDiagnostic(5, 3, "oops")) + .formatDiagnostics("T.java", input)) + .isEqualTo("T.java:5:3: error: oops" + System.lineSeparator()); + assertThat( + new FormatterException(new FormatterDiagnostic(0, 3, "oops")) + .formatDiagnostics("T.java", input)) + .isEqualTo("T.java:0:3: error: oops" + System.lineSeparator()); + assertThat( + new FormatterException(new FormatterDiagnostic(1, 0, "oops")) + .formatDiagnostics("T.java", input)) + .isEqualTo("T.java:1:0: error: oops" + System.lineSeparator()); + } + + @Test + public void stringWrappingProducesInvalidCode() throws Exception { + // Reflowing this string splits the escaped backslash in `\\t`, which produces an unterminated + // string literal several lines past the end of the original input. + String input = + """ + class T { + String s = "%s%s\\\\tend"; + } + """ + .formatted("word ".repeat(100), "x".repeat(95)); + + StringWriter stdout = new StringWriter(); + StringWriter stderr = new StringWriter(); + Main main = new Main(new PrintWriter(stdout, true), new PrintWriter(stderr, true), System.in); + + Path tmpdir = testFolder.newFolder().toPath(); + Path path = tmpdir.resolve("T.java"); + Files.writeString(path, input); + + int result = main.format(path.toString()); + assertThat(stdout.toString()).isEmpty(); + assertThat(stderr.toString()) + .contains( + "it would produce code that does not parse (9:13: error: unclosed string literal)"); + assertThat(result).isEqualTo(1); + } + @Test public void oneFileParseError() throws Exception { String one = "class One {\n";