问题
I try to parse:
return 3 + 4;
My parse code (see below) parses it as the second rule (statement statements program) instead of the first rule. If I comment out the second rule, then the parser interprets it as the third rule (functions statement program).
My "fix" that has worked so far is to make:
master : program EOF ;
Why does that fix my issue?
Relevant Parse Code:
program
: statement {
System.out.println("STATEMENT PROGRAM");
}
| statement statements program {
System.out.println("MULTI STATEMENT PROGRAM");
}
| functions statement program {
System.out.println("FUNCTION PROGRAM");
};
statement :
RETURN expr SEMICOLON {
System.out.println("STATEMENT");
};
Note: 'statements' and 'functions' can be nullable
Also, assume expr is correct :) (it cannot be nullable)
Some clarification:
statements : statement* ;
When I run parser.program(), I expect that return 3 + 4; should parse properly (and then the EOF comes after which is not caught by any parse rules); however, return 'return 3 + 4;' is not treated as a statement but a statement statements program.
Commenting out that rule, my parser still does not parse return 3 + 4; as a statement but as a functions statement program.
I would think that the return statement is parsed as
statement='return 3 + 4;' EOF
and not
statement='return 3 + 4;' statements='' program=?
and also not
functions='' statement='return 3 + 4;' program=?
My question is, why is ANTLR trying to parse it as the second and third rules?
来源:https://stackoverflow.com/questions/18952397/antlr-parsing-matches-wrong-thing-but-fix-is-eof