Sha256: 94c019971db5d1223a236f84250137ae1be4a8b596800f2f260ff87a1590d295

Contents?: true

Size: 1.5 KB

Versions: 4

Compression:

Stored size: 1.5 KB

Contents

# A grammar for mathematical formulas that apply the basic four operations to
# non-negative numbers (integers and floats), respecting operator precedence and
# ignoring whitespace.
grammar Calc
  rule term
    additive | factor
  end

  rule additive
    (factor operator:(plus | minus) term) {
      def value
        operator.apply(factor, term)
      end
    }
  end

  rule factor
    multiplicative | primary
  end

  rule multiplicative
    (primary operator:(star | slash) factor) {
      def value
        operator.apply(primary, factor)
      end
    }
  end

  rule primary
    term_paren | number
  end

  rule term_paren
    (lparen term rparen) {
      def value
        term.value
      end
    }
  end

  rule number
    float | integer
  end

  rule float
    ([0-9]+ '.' [0-9]+ space) {
      def value
        text.strip.to_f
      end
    }
  end

  rule integer
    ([0-9]+ space) {
      def value
        text.strip.to_i
      end
    }
  end

  rule plus
    ('+' space) {
      def apply(factor, term)
        factor.value + term.value
      end
    }
  end

  rule minus
    ('-' space) {
      def apply(factor, term)
        factor.value - term.value
      end
    }
  end

  rule star
    ('*' space) {
      def apply(primary, factor)
        primary.value * factor.value
      end
    }
  end

  rule slash
    ('/' space) {
      def apply(primary, factor)
        primary.value / factor.value
      end
    }
  end

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

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
citrus-1.6.0 examples/calc.citrus
citrus-1.5.2 examples/calc.citrus
citrus-1.5.1 examples/calc.citrus
citrus-1.5.0 examples/calc.citrus