This is an arithmetic expression for my language: ADD 100 MUL 5 DIV 10 SUB 7 MOD 10 4
Where ADD
= addition, SUB
= subtraction, MUL
= multiplication, DIV
= division, MOD
= modulo.
The expression above can also be rewitten into the standard 100 + (5 * (10 / (7 - (10 % 4))))
, parenthesis included to mark the order of operations.
This is quite different than the standard because evaluation starts with the right most operation, that is MOD 10 4
, then the result of that is then used to evaluate the next operation, that is SUB 7 2
, where 2
is the result of the modulo operation. Parenthesis is not required for this grammar.
I have gotten hold the grammar for the standard notation from https://ruslanspivak.com/lsbasi-part6/ , here it is:
<expr> := <term> ((ADD|SUB) <term>)*
<term> := <factor> ((MUL|DIV|MOD) <factor>)*
<factor> := integer
In my language, I am clueless in writing the grammar for arithmetic operations. Are modifications needed for the grammar above? Or do I need to write a completely new grammar?
I managed to solve this by analyzing the execution of each production in my code. To my surprise, I forgot to include an <expr>
production in <factor>
. Changing my code a bit my moving certain conditions and I was able to parse the sample expression above. This is the grammar for the arithmetic expression in my language:
<expr> := ((ADD|SUB) <term> <term>)* | <term>
<term> := ((MUL|DIV|MOD) <factor> <factor>)* | <factor>
<factor> := INTEGER | <expr>
The <expr>
production in <factor>
makes it possible to have multiple operations because it goes back to the start to parse the next operation.
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.