I have been using matlab grammar from this source. I came across an error to the following input
a = 2^2*3
b = 3*2^2
Result in both cases should be 12, but it is not, because the exponential operator in Matlab grammar using ANTLR4 does not work correctly which shows following tree
Problem might be in the multiplicative expression, but I do not have best solution for the issue in my mind. To be honest I do not have any solution for this. Can anybody please tell me how to fix this?
multiplicative_expression
: unary_expression
| multiplicative_expression '*' unary_expression
| multiplicative_expression '/' unary_expression
| multiplicative_expression '\\' unary_expression
| multiplicative_expression '^' unary_expression
| multiplicative_expression ARRAYMUL unary_expression
| multiplicative_expression ARRAYDIV unary_expression
| multiplicative_expression ARRAYRDIV unary_expression
| multiplicative_expression ARRAYPOW unary_expression
;
I think you need to replace the section multiplicative_expression
with the following:
multiplicative_expression
: pow_expression
| multiplicative_expression '*' pow_expression
| multiplicative_expression '/' pow_expression
| multiplicative_expression '\\' pow_expression
| multiplicative_expression ARRAYMUL pow_expression
| multiplicative_expression ARRAYDIV pow_expression
| multiplicative_expression ARRAYRDIV pow_expression
;
and then include an additional section pow_expression
:
pow_expression
: unary_expression
| pow_expression '^' unary_expression
| pow_expression ARRAYPOW unary_expression
;
That should give the exponentiation operators a higher precedence than the multiplicative operators.
However, if you're trying to actually implement MATLAB's actual grammar, you should realize that this grammar on GitHub is not a very good reflection of it. MATLAB has further exponentiation operators (.^-
, .^+
, .^~
, ^-
, ^+
, ^~
) for example, and there are entire categories of syntax, e.g. all the object-oriented functionality, that are not covered at all.