简体   繁体   中英

antlr add syntactic predicate

For the following rule :

 switchBlockLabels

:   ^(SWITCH_BLOCK_LABEL_LIST switchCaseLabel* switchDefaultLabel? switchCaseLabel*)
;

I got an error:"rule switchBlockLabels has non-LL descision due to recursive rule invocations reachable from alts 1,2".And I tried to add syntactic predicate to solve this problem.I read the book "The Definitive ANTLR Reference".And Now I am confused that since there is no alternatives in rule switchBlockLabels,then no decision need to be made on which one to choose. Is anyone can help me?

Whenever the tree parser stumbles upon, say, 2 switchCaseLabel s (and no switchDefaultLabel in the middle), it does not know to which these switchCaseLabel s belong. There are 3 possibilities the parser can choose from:

  • 2 switchCaseLabel s are matched by the 1 st switchCaseLabel* ;
  • 2 switchCaseLabel s are matched by the 2 nd switchCaseLabel* ;
  • 1 switchCaseLabel is matched by the 1 st switchCaseLabel* , and one by the 2 nd switchCaseLabel* .

and since the parser does not like to choose for you, it emits an error.

You need to do something like this instead:

switchBlockLabels
 : ^(SWITCH_BLOCK_LABEL_LIST switchCaseLabel* (switchDefaultLabel switchCaseLabel*)?)
 ;

That way, when there are only switchCaseLabel s, and no switchDefaultLabel , these switchCaseLabel s would be always matched by the first switchCaseLabel* : there is no ambiguity anymore.

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