Uncommonly used Java syntax (JavaParser)?

algorithm, java, syntax, syntax-error

Solution

This is indeed valid code, without seeing everything, I can see some odditities:

- 'Incorrect' variable and method naming, using PascalCase sometimes.

- Instance variable `token`

- Static variable `IDENTIFIER`

Then:

label_23: while (true) {
    if (jj_2_17(2)) {
        ;
    } else {
        break label_23;
    }
    jj_consume_token(DOT);
    jj_consume_token(IDENTIFIER);
    ret = new QualifiedNameExpr(ret.getBeginLine(), ret.getBeginColumn(), token.endLine, token.endColumn, ret, token.image);
}

This is an infinite loop that keeps running as long as `jj_2_17(2)` returns `true`, but appears to do nothing upon that result. It breaks out of `label_23` when the expression was `false`. To confuse future readers even more, it then actually does things only if the expression is `true` (as it breaks on `false`), namely the last three lines.

For futher information, the `label_23` is simply a label that may only be used on `while` and `for` loops. You can then break out of that loop when using `break labelName;`.

Example that breaks out of an outer loop from within an inner loop:

outerLoop: for (int i = 0; i < max; i++) {
    innerLoop: for (int j = 0; j < max2 - i; j++) {
        if (something) {
            break outerLoop;
        }
        //...
    }
}

You can actually also use `continue` in combination with labels.

Then we see a scoped block without guard that always returns `ret`:

{
    if (true) {
        return ret;
    }
}

So it's all valid. I think we can also conclude with high chance that this code has been machine-generatd.

Problem

I'm exploring a Java grammar parser and I came across this strange piece of code that I wouldn't normally use in ordinary code. Taken from https://code.google.com/p/javaparser/source/browse/branches/mavenized/JavaParser/src/main/java/japa/parser/ASTParser.java#1998 It has many functions that contains code such as ``` final public NameExpr Name() throws ParseException { NameExpr ret; jj_consume_token(IDENTIFIER); ret = new NameExpr(token.beginLine, token.beginColumn, token.endLine, token.endColumn, token.image); label_23: while (true) { if (jj_2_17(2)) { ; } else { break label_23; } jj_consume_token(DOT); jj_consume_token(IDENTIFIER); ret = new QualifiedNameExpr(ret.getBeginLine(), ret.getBeginColumn(), token.endLine, token.endColumn, ret, token.image); } { if (true) { return ret; } } throw new Error("Missing return statement in function"); } ``` At a glance it appears strange but no doubt it's valid as I can compile it. But can someone explain how it works? I have tried to input invalid Java syntax and it does it's job! I'm baffled. How does the few lines throw exception after the return?

Original source