Domanda

How does the Java parser handle ambiguous unary operators?

For example, assuming you had int x declared somewhere, +--x is perfectly valid code. ---x is theoretically valid as well, but the compiler throws an error. Likewise, +~~~~~~+--x is accepted, but ~~~~~~++--x is not even though they could both be parsed into valid expressions.

As far as I can tell, the grammar is ambiguous, so it must be handled during tokenization, but I can't find anything that explains it.

È stato utile?

Soluzione

As Stephen P has implied, unary operators are grouped right to left in Java, which means those expressions are ambiguous as different operators could group to the right. See Section 15.15 of the Java 7 spec for the rules on unary operators.

EDIT

To some extent I think you've answered your own question. It seems that expressions that are ambiguous, such as ---x, cause compile errors, as the compiler doesn't know what you want it to do. In these cases it is the programmer that needs to resolve the ambiguity by making the expression more specific - e.g. by adding parentheses to remove the ambiguity.

Altri suggerimenti

---x is ambiguous because it could mean -(--x) or --(-x) or -(-(-x)) while +--x is unambiguous because there is no +-(-x) possible.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top