From 805b08bcc18afbd8fb8aa6454735615291a98258 Mon Sep 17 00:00:00 2001 From: Liam Miller-Cushon Date: Tue, 17 Nov 2026 04:28:25 -0800 Subject: [PATCH] Reject Unicode escapes outside literal and comment contents, and ignorable characters in identifiers and keywords. Java translates Unicode escapes before lexing, but the formatter works on the original source text. Escapes such as `\u000D` can terminate a `//` comment early and leave the escape in the gap between tokens, and escapes in comment or literal delimiters, or in text block line terminators, make the source text disagree with javac's tokens. This could produce invalid output, crash, or change the value of a text block when it was re-indented. Similarly, javac discards `Character.isIdentifierIgnorable` characters (such as U+200B) in identifiers and keywords, so their names diverge from the source text. Reject these inputs with a diagnostic that reports the line and column of the offending escape or character. Unicode escapes in the contents of comments, string literals, character literals, and text blocks are still allowed. Fixes https://github.com/google/google-java-format/issues/372 Fixes https://github.com/google/google-java-format/issues/836 PiperOrigin-RevId: 1023620804 --- .../googlejavaformat/java/JavaInput.java | 165 +++++++++++---- .../googlejavaformat/java/JavacTokens.java | 19 +- .../googlejavaformat/java/DiagnosticTest.java | 191 ++++++++++++++++++ .../googlejavaformat/java/FormatterTest.java | 20 ++ 4 files changed, 348 insertions(+), 47 deletions(-) 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 1cafb8e37..edfb2ab10 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavaInput.java @@ -16,6 +16,7 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.getLast; +import static java.lang.Math.max; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.base.CharMatcher; @@ -31,6 +32,7 @@ import com.google.common.collect.Range; import com.google.common.collect.RangeSet; import com.google.common.collect.TreeRangeSet; +import com.google.googlejavaformat.FormatterDiagnostic; import com.google.googlejavaformat.Input; import com.google.googlejavaformat.Newlines; import com.google.googlejavaformat.java.JavacTokens.RawTok; @@ -42,6 +44,7 @@ import com.sun.tools.javac.util.Log; import com.sun.tools.javac.util.Log.DeferredDiagnosticHandler; import com.sun.tools.javac.util.Options; +import com.sun.tools.javac.util.Position; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.URI; @@ -370,21 +373,20 @@ public String getCharContent(boolean ignoreEncodingErrors) { break; } int charI0 = t.pos(); - // Get string, possibly with Unicode escapes. - String originalTokText = text.substring(charI0, t.endPos()); - String tokText = - t.kind() == TokenKind.STRINGLITERAL - ? t.stringVal() // Unicode escapes removed. - : originalTokText; + String tokText = text.substring(charI0, t.endPos()); // The token's source text. char tokText0 = tokText.charAt(0); // The token's first character. final boolean isToken; // Is this tok a token? final boolean isNumbered; // Is this tok numbered? (tokens and comments) String extraNewline = null; // Extra newline at end? List strings = new ArrayList<>(); if (Character.isWhitespace(tokText0)) { + int escape = tokText.indexOf('\\'); + if (escape != -1) { + throw error(text, charI0 + escape, "Unicode escapes not allowed in whitespace"); + } isToken = false; isNumbered = false; - Iterator it = Newlines.lineIterator(originalTokText); + Iterator it = Newlines.lineIterator(tokText); while (it.hasNext()) { String line = it.next(); String newline = Newlines.getLineEnding(line); @@ -398,22 +400,41 @@ public String getCharContent(boolean ignoreEncodingErrors) { strings.add(line); } } - } else if (tokText.startsWith("'") || tokText.startsWith("\"")) { + } else if (t.kind() == TokenKind.CHARLITERAL || t.kind() == TokenKind.STRINGLITERAL) { + checkLiteral(text, charI0, t.kind(), tokText); isToken = true; isNumbered = true; - strings.add(originalTokText); - } else if (tokText.startsWith("//") || tokText.startsWith("/*")) { + strings.add(tokText); + } else if (tokText.startsWith("//") || (tokText.startsWith("/*") && tokText.endsWith("*/"))) { // For compatibility with an earlier lexer, the newline after a // comment is its own tok. - if (tokText.startsWith("//") - && (originalTokText.endsWith("\n") || originalTokText.endsWith("\r"))) { - extraNewline = Newlines.getLineEnding(originalTokText); + if (tokText.startsWith("//") && (tokText.endsWith("\n") || tokText.endsWith("\r"))) { + extraNewline = Newlines.getLineEnding(tokText); tokText = tokText.substring(0, tokText.length() - extraNewline.length()); - originalTokText = - originalTokText.substring(0, originalTokText.length() - extraNewline.length()); } isToken = false; isNumbered = true; - strings.add(originalTokText); + strings.add(tokText); + } else if (t.kind() == null) { + // A non-token that is neither whitespace nor a comment, because a Unicode escape in a + // comment delimiter or line terminator changed how javac lexed it. A block comment is only + // misidentified if its closing delimiter is escaped. + int escape = tokText.startsWith("/*") ? tokText.lastIndexOf('\\') : tokText.indexOf('\\'); + throw error( + text, + charI0 + max(escape, 0), + "Unicode escapes not allowed in whitespace or comment delimiters"); + } else if (tokText.indexOf('\\') != -1) { + throw error( + text, + charI0 + tokText.indexOf('\\'), + "Unicode escapes not allowed in identifiers, keywords, operators, or numeric literals"); + } else if (indexOfIgnorable(tokText) != -1) { + // javac discards ignorable characters in identifiers and keywords, e.g. `in`, U+200B, `t` + // is lexed as the keyword `int`. + throw error( + text, + charI0 + indexOfIgnorable(tokText), + "Ignorable characters not allowed in identifiers or keywords"); } else if (Character.isJavaIdentifierStart(tokText0) || Character.isDigit(tokText0) || (tokText0 == '.' && tokText.length() > 1 && Character.isDigit(tokText.charAt(1)))) { @@ -423,8 +444,7 @@ public String getCharContent(boolean ignoreEncodingErrors) { strings.add(tokText); } else { // Other tokens ("+" or "++" or ">>" are broken into one-character toks, because ">>" - // cannot be lexed without syntactic knowledge. This implementation fails if the token - // contains Unicode escapes. + // cannot be lexed without syntactic knowledge. isToken = true; isNumbered = true; for (char c : tokText.toCharArray()) { @@ -433,26 +453,14 @@ public String getCharContent(boolean ignoreEncodingErrors) { } if (strings.size() == 1) { toks.add( - new Tok( - isNumbered ? kN++ : -1, - originalTokText, - tokText, - charI, - columnI, - isToken, - t.kind())); - charI += originalTokText.length(); - columnI = updateColumn(columnI, originalTokText); - + new Tok(isNumbered ? kN++ : -1, tokText, tokText, charI, columnI, isToken, t.kind())); + charI += tokText.length(); + columnI = updateColumn(columnI, tokText); } else { - if (strings.size() != 1 && !tokText.equals(originalTokText)) { - throw new FormatterException( - "Unicode escapes not allowed in whitespace or multi-character operators"); - } for (String str : strings) { toks.add(new Tok(isNumbered ? kN++ : -1, str, str, charI, columnI, isToken, null)); charI += str.length(); - columnI = updateColumn(columnI, originalTokText); + columnI = updateColumn(columnI, tokText); } } if (extraNewline != null) { @@ -465,6 +473,95 @@ public String getCharContent(boolean ignoreEncodingErrors) { return ImmutableList.copyOf(toks); } + /// Rejects literals whose delimiters, or text block line terminators, are Unicode escapes. The + /// formatter operates on the source text of literals, which needs to agree with javac's lexing. + private static void checkLiteral(String text, int pos, TokenKind kind, String tokText) + throws FormatterException { + int lineTerminator = indexOfUnicodeLineTerminatorEscape(tokText); + String delimiter; + String description; + if (kind == TokenKind.CHARLITERAL) { + delimiter = "'"; + description = "character literal"; + } else if (Newlines.firstBreak(tokText) != -1 || lineTerminator != -1) { + // A Unicode line terminator will be rejected below. Here we identify it is in a text block. + delimiter = "\"\"\""; + description = "text block"; + } else { + delimiter = "\""; + description = "string literal"; + } + if (!tokText.startsWith(delimiter)) { + throw error( + text, + pos + tokText.indexOf('\\'), + "Unicode escapes not allowed in " + description + " delimiters"); + } + if (!tokText.endsWith(delimiter)) { + throw error( + text, + pos + tokText.lastIndexOf('\\'), + "Unicode escapes not allowed in " + description + " delimiters"); + } + if (lineTerminator != -1) { + throw error( + text, + pos + lineTerminator, + "Unicode escapes not allowed in " + description + " line terminators"); + } + } + + /// Returns the index of the first Unicode escape for a line terminator (LF U+000A or CR U+000D) + /// in `s`, or `-1`. + private static int indexOfUnicodeLineTerminatorEscape(String s) { + int start = s.indexOf('\\'); + while (start != -1) { + int end = start; + while (end < s.length() && s.charAt(end) == '\\') { + end++; + } + // A backslash is only eligible to begin a Unicode escape if it is preceded by an even number + // of contiguous backslashes (JLS 3.3), and only the last backslash in a run can be followed + // by a `u`. + int last = end - 1; + if ((last - start) % 2 == 0 && isUnicodeLineTerminatorEscape(s, last)) { + return last; + } + start = s.indexOf('\\', end); + } + return -1; + } + + /// Returns true if the backslash at `backslash` begins a Unicode escape for a line terminator. + private static boolean isUnicodeLineTerminatorEscape(String s, int backslash) { + int i = backslash + 1; + while (i < s.length() && s.charAt(i) == 'u') { + i++; + } + return i > backslash + 1 + && (s.regionMatches(/* ignoreCase= */ true, i, "000a", 0, 4) + || s.regionMatches(/* ignoreCase= */ true, i, "000d", 0, 4)); + } + + /// Returns the index of the first identifier-ignorable character in `s`, or `-1`. + private static int indexOfIgnorable(String s) { + for (int i = 0; i < s.length(); ) { + int codePoint = s.codePointAt(i); + if (Character.isIdentifierIgnorable(codePoint)) { + return i; + } + i += Character.charCount(codePoint); + } + return -1; + } + + private static FormatterException error(String text, int inputPosition, String message) { + Position.LineMap lineMap = Position.makeLineMap(text.toCharArray(), text.length(), false); + return new FormatterException( + new FormatterDiagnostic( + lineMap.getLineNumber(inputPosition), lineMap.getColumnNumber(inputPosition), message)); + } + private static final Constructor DEFERRED_DIAGNOSTIC_HANDLER_CONSTRUCTOR = getDeferredDiagnosticHandlerConstructor(); 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 b1dd1de3a..b06df2e34 100644 --- a/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java +++ b/core/src/main/java/com/google/googlejavaformat/java/JavacTokens.java @@ -39,11 +39,10 @@ final class JavacTokens { /// An unprocessed input token, including whitespace and comments. /// - /// @param stringVal the escaped string value of a literal, or `null` for other tokens. /// @param kind the token kind, or `null` for whitespace and comments. /// @param pos the start position. /// @param endPos the end position. - record RawTok(String stringVal, TokenKind kind, int pos, int endPos) {} + record RawTok(TokenKind kind, int pos, int endPos) {} /// Lex the input and return a list of [RawTok]s. static ImmutableList getTokens( @@ -64,10 +63,9 @@ static ImmutableList getTokens( if (t.comments != null) { for (CommentWithTextAndPosition c : getComments(t, tokenizer.comments())) { if (last < c.getSourcePos(0)) { - tokens.add(new RawTok(null, null, last, c.getSourcePos(0))); + tokens.add(new RawTok(null, last, c.getSourcePos(0))); } - tokens.add( - new RawTok(null, null, c.getSourcePos(0), c.getSourcePos(0) + c.text().length())); + tokens.add(new RawTok(null, c.getSourcePos(0), c.getSourcePos(0) + c.text().length())); last = c.getSourcePos(0) + c.text().length(); } } @@ -78,18 +76,13 @@ static ImmutableList getTokens( break; } if (last < t.pos) { - tokens.add(new RawTok(null, null, last, t.pos)); + tokens.add(new RawTok(null, last, t.pos)); } - tokens.add( - new RawTok( - t.kind == TokenKind.STRINGLITERAL ? "\"" + t.stringVal() + "\"" : null, - t.kind, - t.pos, - t.endPos)); + tokens.add(new RawTok(t.kind, t.pos, t.endPos)); last = t.endPos; } while (scanner.token().kind != TokenKind.EOF); if (last < end) { - tokens.add(new RawTok(null, null, last, end)); + tokens.add(new RawTok(null, last, end)); } return tokens.build(); } 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 ccc4f0552..7ab007272 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/DiagnosticTest.java @@ -247,4 +247,195 @@ class Foo { void f() { assertThat(exitCode).isEqualTo(1); assertThat(err.toString()).contains(":2:4: error: unclosed character literal"); } + + @Test + public void unicodeEscapes() throws Exception { + assertStdinError( + """ + class Foo { + // \\u000D + } + """, + ":2:6: error: Unicode escapes not allowed in whitespace or comment delimiters"); + assertStdinError( + """ + class Foo {\\u0020} + """, + ":1:12: error: Unicode escapes not allowed in whitespace or comment delimiters"); + assertStdinError( + """ + class Foo { \\u0020 } + """, + ":1:13: error: Unicode escapes not allowed in whitespace"); + assertStdinError( + """ + class Foo { + \\u002f\\u002f comment + } + """, + ":2:3: error: Unicode escapes not allowed in whitespace or comment delimiters"); + assertStdinError( + """ + class Foo { + /* \\u221e *\\u002f + } + """, + ":2:14: error: Unicode escapes not allowed in whitespace or comment delimiters"); + assertStdinError( + """ + class Foo { + int x = 1 \\u002b 2; + } + """, + ":2:13: error: Unicode escapes not allowed in identifiers, keywords, operators, or" + + " numeric literals"); + assertStdinError( + """ + class Foo { + int x = 1\\u0030; + } + """, + ":2:12: error: Unicode escapes not allowed in identifiers, keywords, operators, or" + + " numeric literals"); + assertStdinError( + """ + class Foo { + void f() { + getAndIncrement\\u200b("foo"); + } + } + """, + ":3:20: error: Unicode escapes not allowed in identifiers, keywords, operators, or" + + " numeric literals"); + assertStdinError( + """ + class Foo { + void f() { + f\\u006fo("bar"); + } + } + """, + ":3:6: error: Unicode escapes not allowed in identifiers, keywords, operators, or" + + " numeric literals"); + assertStdinError( + """ + class Foo { + \\u0069nt x = 1; + } + """, + ":2:3: error: Unicode escapes not allowed in identifiers, keywords, operators, or" + + " numeric literals"); + assertStdinError( + """ + class Foo { + String s = \\u0022hello\\u0022; + } + """, + ":2:14: error: Unicode escapes not allowed in string literal delimiters"); + assertStdinError( + """ + class Foo { + String s = "hello\\u0022; + } + """, + ":2:20: error: Unicode escapes not allowed in string literal delimiters"); + assertStdinError( + """ + class Foo { + char c = 'a\\u0027; + } + """, + ":2:14: error: Unicode escapes not allowed in character literal delimiters"); + assertStdinError( + """ + class Foo { + String s = \\u0022"" + hello + \"""; + } + """, + ":2:14: error: Unicode escapes not allowed in text block delimiters"); + assertStdinError( + """ + class Foo { + String s = \""" + hello + ""\\u0022; + } + """, + ":4:3: error: Unicode escapes not allowed in text block delimiters"); + assertStdinError( + """ + class Foo { + String s = \"""\\u000ahello\"""; + } + """, + ":2:17: error: Unicode escapes not allowed in text block line terminators"); + assertStdinError( + """ + class Foo { + String s = \""" + hello\\u000Aworld + \"""; + } + """, + ":3:8: error: Unicode escapes not allowed in text block line terminators"); + assertStdinError( + """ + class Foo { + String s = \""" + hello\\uuu000dworld + \"""; + } + """, + ":3:8: error: Unicode escapes not allowed in text block line terminators"); + assertStdinError( + """ + class Foo { + String s = \""" + hello\\\\\\u000aworld + \"""; + } + """, + ":3:10: error: Unicode escapes not allowed in text block line terminators"); + assertStdinError( + """ + class Foo { + String s = \""" + hello\\u005c\\u000aworld + \"""; + } + """, + ":3:14: error: Unicode escapes not allowed in text block line terminators"); + } + + @Test + public void ignorableCharacters() throws Exception { + assertStdinError( + """ + class Foo { + void f() { + getAndIncrement\u200b("foo"); + } + } + """, + ":3:20: error: Ignorable characters not allowed in identifiers or keywords"); + assertStdinError( + """ + class Foo { + in\u200bt x = 1; + } + """, + ":2:5: error: Ignorable characters not allowed in identifiers or keywords"); + } + + private static void assertStdinError(String input, String expected) throws Exception { + 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); + int exitCode = main.format("-"); + assertThat(exitCode).isEqualTo(1); + assertThat(err.toString()).startsWith(expected + System.lineSeparator()); + } } 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 db399aecd..a63e4ad53 100644 --- a/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java +++ b/core/src/test/java/com/google/googlejavaformat/java/FormatterTest.java @@ -779,6 +779,26 @@ public class T { assertThat(actual).isEqualTo(expected); } + @Test + public void unicodeEscapesInLiteralAndCommentContents() throws Exception { + // Unicode escapes in the contents of comments and literals are preserved. The input contains + // Unicode escapes, so they need to be escaped in the string literal in this test. + String input = + """ + class T { + // \\u221e + /* \\u221e */ + String s = "\\u0041\\u005c\\u005c"; + char c = '\\u0041'; + String t = + \""" + \\\\u000a \\u0041 + \"""; + } + """; + assertThat(new Formatter().formatSource(input)).isEqualTo(input); + } + @Test public void textBlockSpaceTabMix() throws Exception { String input =