Search code examples
javacc

JavaCC - choice based on return type?


I have an ifElse Statement which can be of the following two types

a) ifElse(condition, expression_bool_result, expression_bool_result)

whereas expression_bool_result may either be TRUE/FALSE, the result of and(), or(), ==, !=.... or further ifElse

b) ifElse(condition, expression_arith_result, expression_arith_result)

whereas expression_arith_result may either be any number, the result of calculations of further functions returning a number... (or further ifElse)

Since I am new to javacc, I would like to ask you how a production could look like which allows the parser for a clear decision.

Currently I get the warning

Warning: Choice conflict involving two expansions at
line 824, column 5 and line 825, column 5 respectively.
A common prefix is: "ifElse" "("
Consider using a lookahead of 3 or more for earlier expansion.

which - as far as I can tell - implies that my grammer (regarding ifelse) is ambiguous.

If there is no way to write it unambiguously, how could the suggested lookahead look like?

Thanks for your feedback in advance!


Solution

  • No fixed amount of lookahead could possibly resolve this ambiguity in all cases. You could have an arbitrarily long stream of tokens that form a valid expression_arith_result - but is then followed by a comparison operator and another arithmetic value, thus turning it into an expression_bool_result.

    The solution would be to have a single ifElse statement, that takes two arbitrary expressions. The required agreement in type between the two expressions would be a matter of semantics, not grammar.