I am trying to come up with a grammar for arithmetic expressions with the following order of operations:
- Functions / unary plus and minus
- Juxtaposition (implied multiplication)
- Multiplication and division
- Addition and subtraction
- Comma separated expressions
Functions should not require parenthesis, i.e. both
sqrt 2 and
sqrt(2) are valid. Valid juxtapositions should be
<number> (<parenthesis> | <constant> | <function_expression>).
I can find plenty of examples of people who have created grammar for simple arithmetic that only includes binary operators and parenthesis. This is trivial, but when I try to expand it to included the previously stated items, it never works. I am not sure if the grammar I want is even specifiable in a non-ambiguous way, or if I am simply failing.
<expression> ::= <add> ("," <add>)* <add> ::= <multiply> (("+" | "-") <multiply>)* <multiply> ::= <juxtapose> (("*" | "/") <juxtapose>)* ... no idea how to handle unary ops, functions, and juxtaposition as they seem to interact with each other ... <exponent> ::= <factorial> ("^" <exponent>)* <factorial> ::= <primary> ("!" | "!!")* <primary> ::= <number> | <constant> | <parenthesis> <parenthesis> ::= "(" <expression> ")"
Also, if you are unfamiliar with it, I found this useful site https://bnfplayground.pauliankline.com/
Edit: Here are some examples sentences:
-(2 ^ 2)Exp > Unary
2 * (pi ^ 2)Exp > Juxtapose
2 / (2 * pi)Juxtapose > Divide
2 * 3
2 sqrt 2=
2 * sqrt(2)
sin(2 * pi)
atan pi, pi=