2
votes

I use ANTLR in the Eclipse environment. I want to pass an attribute (n.text) to another rule (description) and also use a semantic predicate in the latter rule to validate the input in relation to n.text. Here is my code:

useCaseSpecification 
    :   n=useCase '='
        description[$n.text]
    ;

useCase
    : ucID=('UC' INTEGER)? ucName
    ;

ucName
    :   caren io
    ;

caren
    :   'create' | 'creates' | alter | read | 'erase' | 'erases' | notify
    ;

/* ..more code */

description[String str]
    :   'Description' ':' primaryActor (useCase {str==$useCase.text}?) /* more grammar */
    ;

I tried many alternatives for the semantic predicate expression, such as {str.equals($useCase.text)}, but nothing. It seems that the parser does not make the validation.

When I run the interpreter with an example, it allows every input of useCase type. For example, if the input is:

create a Prescription = 
Description: a doctor create a Prescription /* ... */

that should be correct.

If the input, is:

create a Prescription = 
Description: a doctor create a Rrrrescription /* ... */

that should be wrong.

2

2 Answers

3
votes

Do not rely on the interpreter (either ANTLRWorks' interpreter, or the one of Eclipse's plugin). The interpreter does not take any predicates into account.

Also, not sure what target you're using, but realize that {str==$useCase.text}? is wrong in case you're using Java (== compares the identity of objects, use equals(...) instead).

For example, parsing two the same letters can be done as follows:

grammar T;

parse
 : Letter same[$Letter.text] EOF
 ;

same [String s]
 : Letter {$Letter.text.equals(s)}?
 ;

Letter : 'a'..'z' | 'A'..'Z';

Parsing "AB" will result in an exception:

enter image description here

while parsing "AA" does not:

enter image description here

The trees above are generated using ANTLRWorks' debugger, which works like a charm. Note that the debugger ignores the language=XYZ option: it will debug your grammar with Java as the target language. So any embedded code other that Java will cause problems!

Be aware that cramming too much of these semantic checks in your grammar will result in a hard to maintain jumble of mixed grammar rules and code. These kind of checks are usually performed after the parser created a (abstract) parse tree: that means liberally matching useCases and then validating them when iterating over the tree created by the parser.

0
votes

Since you are using Eclipse, I probably should have posted this as an answer instead of a comment. Look at How To Configure ANTLR IDE and then Debug/Test with ANTLR IDE. Appreciate the upvote if you already found these helpful.