Sha256: 95f1f92d1dc337912d33392567a6071d3f6ca7ab666cee5a44d61bf45e12a73a

Contents?: true

Size: 1.52 KB

Versions: 3

Compression:

Stored size: 1.52 KB

Contents

# A grammar for mathematical formulas that apply basic mathematical operations
# to all numbers, respecting operator precedence and grouping of expressions
# while ignoring whitespace. This grammar should provide the same interpretation
# as Ruby for all mathematical expressions.
grammar Calc

  ## Hierarchical syntax

  rule term
    additive | factor
  end

  rule additive
    (factor operator:('+' | '-') space* term) {
      factor.value.send(operator.to_s, term.value)
    }
  end

  rule factor
    multiplicative | prefix
  end

  rule multiplicative
    (prefix operator:('*' | '/' | '%') space* factor) {
      prefix.value.send(operator.to_s, factor.value)
    }
  end

  rule prefix
    prefixed | exponent
  end

  rule prefixed
    (operator:('-' | '+' | '~') space* prefix) {
      s = operator.to_s
      s += '@' unless s == '~' # Unary + and - require an @.
      prefix.value.send(s)
    }
  end

  rule exponent
    exponential | primary
  end

  rule exponential
    (primary operator:'**' space* prefix) {
      primary.value.send(operator.to_s, prefix.value)
    }
  end

  rule primary
    group | number
  end

  rule group
    (lparen term rparen) {
      term.value
    }
  end

  ## Lexical syntax

  rule number
    float | integer
  end

  rule float
    (digits '.' digits space*) { to_f }
  end

  rule integer
    (digits space*) { to_i }
  end

  rule digits
    [0-9]+ ('_' [0-9]+)* # Numbers may contain underscores.
  end

  rule lparen '(' space* end
  rule rparen ')' space* end
  rule space  [ \t\n\r]  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
citrus-2.3.7 examples/calc.citrus
citrus-2.3.6 examples/calc.citrus
citrus-2.3.5 examples/calc.citrus