chharvey / counterpoint

A robust programming language.
GNU Affero General Public License v3.0
2 stars 0 forks source link

Parse Integer Operations #2

Closed chharvey closed 4 years ago

chharvey commented 4 years ago

Use an LR syntactic grammar to parse the token stream given by the lexer. The goal symbol is either a single expression or nothing. Support the operations of addition, subtraction, multiplication, division, and exponentiation.

Goal ::= #x02 Expression? #x03

Expression ::= ExpressionAdditive

ExpressionAdditive       ::= (ExpressionAdditive       ("+" | "-"))? ExpressionMultiplicative
ExpressionMultiplicative ::= (ExpressionMultiplicative ("*" | "/"))? ExpressionExponential
ExpressionExponential    ::=  ExpressionUnarySymbol   ( "^"          ExpressionExponential)?

ExpressionUnarySymbol ::= ExpressionUnit | ("+" | "-") ExpressionUnarySymbol

ExpressionUnit ::= NUMBER | "(" Expression ")"

The terminal NUMBER in the syntactic grammar above refers to the nonterminal IntegerLiteral in the lexical grammar.

Implicit grouping (sometimes incorrectly called “associativity”) is left-to-right for all operations except for exponentiation, which is right-to-left.

"1 + 2 + 3" is implied as "(1 + 2) + 3"
"1 - 2 - 3" is implied as "(1 - 2) - 3"
"1 * 2 * 3" is implied as "(1 * 2) * 3"
"1 / 2 / 3" is implied as "(1 / 2) / 3"
"1 ^ 2 ^ 3" is implied as "1 ^ (2 ^ 3)"

Operator precedence, not including grouping symbols, is strongest for exponentiation, medium for multiplication/division, and weakest for addition/subtraction.

"1 + 2 - 3" is implied as "(1 + 2) - 3"
"1 - 2 + 3" is implied as "(1 - 2) + 3"
"1 * 2 / 3" is implied as "(1 * 2) / 3"
"1 / 2 * 3" is implied as "(1 / 2) * 3"
"1 + 2 * 3" is implied as "1 + (2 * 3)"
"1 - 2 * 3" is implied as "1 - (2 * 3)"
"1 + 2 / 3" is implied as "1 + (2 / 3)"
"1 - 2 / 3" is implied as "1 - (2 / 3)"
"1 + 2 ^ 3" is implied as "1 + (2 ^ 3)"
"1 - 2 ^ 3" is implied as "1 - (2 ^ 3)"
"1 * 2 ^ 3" is implied as "1 * (2 ^ 3)"
"1 / 2 ^ 3" is implied as "1 / (2 ^ 3)"