Reputation: 13
If i have a grammar like this:
g: String -> String ;
String: [A-Z]+ ;
is there a way to write a rule in the grammar to check if the first String is different from the second String ?
For example, i want to parser a string like this A -> B
!
BUT not like this A -> A
.
In the case the tokens are equal i want a parser to be able to throw an error.
Is it something i can do with the grammar ? Or it is something i am able to verify only with a listener ? (when i am walking in the parse tree). Thanks!
Upvotes: 1
Views: 66
Reputation: 53337
You can use a predicate to achieve that, like:
g: s1 = String '->' s2 = String { s1.getText() != s2.getText() }?;
However, I discourage you doing it that way. You are doing semantic processing in the syntactic phase, which leads to useless error messages and makes later processing of the recognized values more difficult.
Instead parse A -> A
as syntactically correct input and in a second step examine the generated parse tree and do semantic checks, like the validation of different identifiers. If that fails you can print a nice error message like "Identifiers must be different" instead of having to process the parser's message (which will be something like "No viable alt at position...").
Upvotes: 1