RFR: 8325440: Confusing error reported for octal literals with wrong digits

Jan Lahoda jlahoda at openjdk.org
Wed Feb 7 21:11:05 UTC 2024


Consider code like:

    int i = 08;


Currently, javac will produce an error like:

/tmp/Octal.java:2: error: ';' expected
    int i = 08;
             ^


Which is fairly confusing. The cause is that this gets lexed as two tokens: `0` and `8`, as `8` is not a valid digit for an octal literal. The current behavior is a consequence of:
https://bugs.openjdk.org/browse/JDK-8267361

Before that fix, the error was:

/tmp/Octal.java:2: error: integer number too large
    int i = 08;
            ^


which was not better.

Please see the original PR:
https://github.com/openjdk/jdk/pull/4111
for more information on the decision there.

It seems to me that it would be better to have an error pinpointing the problem (i.e. wrong digit in what is the octal literal). Which is what this patch is trying to do. It would be possible to do that in the lexer, but that is slightly complex. So, this patch:
- permits non-octal (and non-binary) digits in octal (and binary) literals, while still preserving the fact the literals are octal (binary)
- when the parser tries to convert the textual literal representation to a number, and fails to do that, get a `NumberFormatException`. The handling of this exception is improved to provide better errors.

Note that, for consistency, this patch works not only for octal literals (which is likely the most problematic case in practice), but also for binary literals, although it seems relatively unlikely code would contain literals like `0b123` (unlike `08`, which may be a simple mistake).

The new error is:

/tmp/Octal.java:2: error: illegal digit in an octal literal
    int i = 08;
             ^


(the error message can be re-phrased as needed/desired, of course.)

-------------

Commit messages:
 - Fixing test
 - Adding support for incorrect binary literals.
 - 8325440: Confusing error reported for octal literals with wrong digits

Changes: https://git.openjdk.org/jdk/pull/17760/files
 Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=17760&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8325440
  Stats: 70 lines in 9 files changed: 36 ins; 10 del; 24 mod
  Patch: https://git.openjdk.org/jdk/pull/17760.diff
  Fetch: git fetch https://git.openjdk.org/jdk.git pull/17760/head:pull/17760

PR: https://git.openjdk.org/jdk/pull/17760


More information about the compiler-dev mailing list