# How need help to specify a grammar for arithmetic expressions

I am trying to come up with a grammar for arithmetic expressions with the following order of operations:

1. Parentheses
2. Factorials
3. Exponents
4. Functions / unary plus and minus
5. Juxtaposition (implied multiplication)
6. Multiplication and division
8. 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 = -(2 ^ 2) Exp > Unary
• 2pi^2 = 2 * (pi ^ 2) Exp > Juxtapose
• 2/2pi = 2 / (2 * pi) Juxtapose > Divide
• 2(3) = 2 * 3
• 2 sqrt 2 = 2 * sqrt(2)
• sqrt -2 = sqrt(-2)
• sin 2pi = sin(2 * pi)
• atan pi, pi = (atan(pi), pi)
• atan(pi, pi) = atan(pi, pi)
• The question you ask might even be interesting, however it is difficult to devise a grammar generating the language you want. In my opinion you should show some sentences that exercize the non-standard features you want to include. For instance, I can't image how juxtaposition should work in the presence of other operations. Oct 14 at 11:08
• @Chaos Added some examples. Oct 14 at 11:51
• The language you are asking about is difficult to match using classic tools (lexer & parser). The sentences '2 sqrt 2' and 'sin 2pi' make the problem of recognizing the language very difficult because one would wonder how to distinguish between 'sin(2*pi)' and sin(2)*pi'. The fact you admit '2pi' to be a lexem as well as ' 2 pi' causes ambiguity, because it is unclear whether it represents a sequence of formal parameters to a function o a product that is also the single parameter. While for pi this might not be an issue, it is in general. Oct 14 at 14:37
• I think it is possible to match the language in question, but it would probably become a semantic analysis problem; that is, you read the input, trasform it into an abstract syntax tree and at that point you proceed to decide whether the input is well formed or abort. Oct 14 at 14:46