简体   繁体   中英

ANTLR syntactic pred

I have the following ANTLR grammar which is given as an example by Terrence Parr.

grammar b;
backtrack
   :    (cast ';')=> cast ';'
   |   (e ';')=>    e ';'
   |                e '.'
   ;

cast:   '(' ID ')' ;

e   :   '(' e ')'
    |   ID
;

ID  :   'a'..'z'+ ;

However, when I try to interpret (a) with the backtrack rule, I get a MisMatchedToken exception. I ask this question because I have a much bigger grammar which I use for a compiler. I have the exact problem there. If I remove one of the rules everything works fine (except for the input parse by the rule removed, of course) but when I add the syntactic predicates I get an error when I parse, even though the grammar compiles(exactly like with the b grammar).

Any suggestions or ideas why this might be? Thank you.

The interpreter in ANTLRWorks is notoriously buggy, and doesn't handle any kind of predicate at all. So don't use it.

Note that you said you parsed "a()" , but that will not be parsed properly. The parser will complain it is missing a "." . I presume you meant you's parsing "a();"

If you run the following demo:

grammar b;

@parser::members {
  public static void main(String[] args) throws Exception {
    bLexer lexer = new bLexer(new ANTLRStringStream("(a);"));
    bParser parser = new bParser(new CommonTokenStream(lexer));
    parser.backtrack();
  }
}

backtrack
 : (cast ';')=> cast ';' {System.out.println("cast");}
 | (e ';')=>    e ';'    {System.out.println("e");}
 |              e '.'
 ;

cast
 : '(' ID ')' 
 ;

e
 : '(' e ')'
 | ID
 ;

ID : 'a'..'z'+ ;

by executing:

java -cp antlr-3.3.jar org.antlr.Tool b.g 
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar bParser

(on Windows, the last command should look like: java -cp .;antlr-3.3.jar bParser )

you'll see that cast is being printed to the console without any kind of error or warning from ANTLR.

If you're getting this error in ANTLRWorks I would try loading the grammar in a sample program and see if you get the same error. ANTLRWorks can sometimes give errors on valid input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM