Parser for bash arithmetic expressions.
Parses expressions like "x + 1", "a++ * b--", "x = y ? 1 : 0"
into an AST that can be evaluated by Bash.AST.Arithmetic.
Operator Precedence (lowest to highest)
,(comma/sequence)=,+=,-=,*=,/=,%=,<<=,>>=,&=,^=,|=(assignment)? :(ternary)||(logical OR)&&(logical AND)|(bitwise OR)^(bitwise XOR)&(bitwise AND)==,!=(equality)<,<=,>,>=(comparison)<<,>>(bit shift)+,-(addition/subtraction)*,/,%(multiplication/division/modulo)**(exponentiation)!,~,+,-(unary)++,--(pre/post increment/decrement)
AST Node Types
{:number, n}- integer literal{:var, name}- variable reference{:binop, op, left, right}- binary operation{:unop, op, expr}- unary operation{:assign, op, var_node, expr}- assignment{:ternary, cond, true_expr, false_expr}- ternary operator{:pre_inc, name}/{:pre_dec, name}- pre-increment/decrement{:post_inc, var_node}/{:post_dec, var_node}- post-increment/decrement
Summary
Functions
Parse an arithmetic expression string into an AST.
Returns {:ok, ast} or {:error, reason}.
Examples
iex> Arithmetic.parse("1 + 2")
{:ok, {:binop, "+", {:number, 1}, {:number, 2}}}
iex> Arithmetic.parse("x = 5")
{:ok, {:assign, "=", {:var, "x"}, {:number, 5}}}
iex> Arithmetic.parse("++x")
{:ok, {:pre_inc, "x"}}