Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8340568

Incorrect escaping of single quotes when pretty-printing character literals

XMLWordPrintable

    • Icon: Enhancement Enhancement
    • Resolution: Fixed
    • Icon: P4 P4
    • 24
    • None
    • tools
    • b17

      JDK-8325078 (Better escaping of single and double quotes in javac annotation toString() results) changed some logic for quoting strings that is also used by Pretty when pretty-printing AST nodes. The new logic distinguishes between char and string contexts, to escape " but not ' in string contexts, and vice versa for char contexts.

      The modified Convert.quote function is used by Pretty here [1], and the new behaviour means that when pretty-printing char literals the wrong quoting happens.

      I don't know if this results in any user-visible issues, I think pretty-printing is mainly used for debugging. But it would still be nice to clear this up so the pretty printed output was valid Java source.

      Demo:

      import com.sun.tools.javac.file.JavacFileManager;
      import com.sun.tools.javac.tree.TreeMaker;
      import com.sun.tools.javac.util.Context;

      import java.nio.charset.StandardCharsets;
      import java.util.List;

      public class T {
        public static void main(String[] args) {
          var context = new Context();
          new JavacFileManager(context, true, StandardCharsets.UTF_8);
          var make = TreeMaker.instance(context);
          for (var l : List .of('\'', '\"', "\"", "\'")) {
            System.err.printf("%s -> %s\n", l, make.Literal(l));
          }
        }
      }

      /google/data/ro/projects/java-platform/linux-amd64/jdk-22-latest/bin/java --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED T
      ' -> '\''
      " -> '\"'
      " -> "\""
      ' -> "\'"

      ' -> '''
      " -> '\"'
      " -> "\""
      ' -> "'"

      The case of a character literal for a single quote shows the pretty printed output is ''', which is incorrect.

      [1] https://github.com/openjdk/jdk/blob/2461263aac35b25e2a48b6fc84da49e4b553dbc3/src/jdk.compiler/share/classes/com/sun/tools/javac/tree/Pretty.java#L1470

            cushon Liam Miller-Cushon
            cushon Liam Miller-Cushon
            Votes:
            0 Vote for this issue
            Watchers:
            3 Start watching this issue

              Created:
              Updated:
              Resolved: