EXC_BAD_ACCESS
EXC_BAD_ACCESS

Reputation: 31

Dynamic operator precedence and associativity in ANTLR4?

i've been working on an antlr4 grammar for Z Notation (ISO UTF version), and the specification calls for a lex phase, and then a "2 phased" parse. you first lex it into a bunch of NAME (or DECORWORD) tokens, and then you parse the resulting tokens against the operatorTemplate rules in the spec's parser grammar, replace appropriate tokens, and then finally parse your new modified token stream to get the AST.

i have the above working, but i can't figure out how to set the precedence and associativity of the parser rules dynamically, so the parse trees are wrong.

the operator syntax looks like (numbers are precedence):

-generic 5 rightassoc (_ → _)
-function 65 rightassoc (_ ◁ _)

i don't see any api to set the associativity on a rule, so i tried with semantic predicates, something like:

expression:
: {ZSupport.isLeftAssociative()}? expression I expression
| <assoc=right> expression i expression
;

or

expression:
: {ZSupport.isLeftAssociative()}? expression i expression
| <assoc=right> {ZSupport.isRightAssociative()}? expression I expression
;

but then i get "The following sets of rules are mutually left-recursive [expression]"

can this be done?

Upvotes: 2

Views: 528

Answers (1)

EXC_BAD_ACCESS
EXC_BAD_ACCESS

Reputation: 31

I was able to accomplish this by moving the semantic predicate:

expression:
: expression {ZSupport.isLeftAssociative()}? I expression
| <assoc=right> expression I expression
;

I was under the impression that this wasn't going to work based on this discussion: https://stackoverflow.com/a/23677069/7711235

...but it does seem to work correctly in all my test cases...

Upvotes: 1

Related Questions