Bash.Parser.Arithmetic (Bash v0.6.0)

Copy Markdown View Source

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)

  1. , (comma/sequence)
  2. =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |= (assignment)
  3. ? : (ternary)
  4. || (logical OR)
  5. && (logical AND)
  6. | (bitwise OR)
  7. ^ (bitwise XOR)
  8. & (bitwise AND)
  9. ==, != (equality)
  10. <, <=, >, >= (comparison)
  11. <<, >> (bit shift)
  12. +, - (addition/subtraction)
  13. *, /, % (multiplication/division/modulo)
  14. ** (exponentiation)
  15. !, ~, +, - (unary)
  16. ++, -- (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.

Functions

parse(expr)

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"}}

tokenize(input, acc)