Question

Consider this portion of my vbscript grammar

EXPR.Rule = BINARY_EXPR 
        | COMPARE_EXPR
        | AND_EXPR
        | OR_EXPR;

BINARY_EXPR.Rule = EXPR + BINARY_OP + EXPR + ReduceHere();
COMPARE_EXPR.Rule = EXPR + COMPARE_OP + EXPR + ReduceHere();
AND_EXPR.Rule = EXPR + "and" + EXPR;
OR_EXPR.Rule = EXPR + "or" + EXPR;

COMPARE_OP.Rule = ToTerm("=") | "<=" | ">=" | "<" | ">" | "<>";
BINARY_OP.Rule = ToTerm("+") | "&" | "^" | "-" | "*" | "/" | "\\";// | "=" | "<=" | ">=" | "<" | ">" | "<>" | "mod" | "and" | "or";

RegisterOperators(60, "^");
RegisterOperators(50, "*", "/", "\\", "mod");
RegisterOperators(40, "+", "-", "&");
RegisterOperators(30, "=", "<=", ">=", "<", ">", "<>");
RegisterOperators(20, "and", "or");

and this vbscript program:

if 2=1+1 then x = 5

It's parsing this as if (2=1)+1 then x = 5 instead of if 2=(1+1) then x = 5. I have BINARY_EXPR specified before COMPARE_EXPR and "+" has a higher operator precedence so I can't figure out how to tell it that it should be looking for the addition operation first. How else can I express this so Irony will parse it the way I'm intending?

Was it helpful?

Solution

I've never worked with Irony, but if it doesn't provide that functionality (or if you can't figure out how it works), you can always try to stratify your EXPR nonterminal.

Let's take only addition, subtraction, multiplication, parentheses, and comparison for example:

EXPR0.Rule = EXPR1
           | EXPR1 + "=" + EXPR1
           ;
EXPR1.Rule = EXPR2
           | EXPR1 + "+" + EXPR1
           | EXPR1 + "-" + EXPR2
           ;
EXPR2.Rule = EXPR3
           | EXPR2 + "*" + EXPR2
           ;
EXPR3.Rule = "(" + EXPR0 + ")"
           | USEVARIABLE
           | LITERAL
           ;

All operators with the same precedence live in their own stratum. They can't have operators of a lower precedence on their left- or right-hand side without running all the way through to EXPR3, which provides a loop back to EXPR0.

Note that "-" takes an EXPR2 on its right-hand side. This is because it's a right-associative operator, while "+" is an associative operator. While 1 - 2 - 3 must always be interpreted as (1 - 2) - 3, 1 + 2 + 3 can be interpreted as both (1 + 2) + 3 and 1 + (2 + 3). I'm not familiar enough with VB to say anything about the associativity of "=", so I've made it non-associative.

Again, I'm not familiar with the framework you're using, so the syntax might not be correct ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top