Ohm Arithmetic Expression Evaluation
Simple example of using Ohm/JS to evaluate simple arithmetic expressions
HTML
<script src="http://www.cdglabs.org/ohm/dist/ohm.js"></script>
<script type="text/ohm-js">
// Based on http://jsfiddle.net/pdubroy/15k63qae/
Arithmetic {
Exp = Exp "+" Term -- plus
| Exp "-" Term -- minus
| Term
Term = Term "*" Factor -- times
| Term "/" Factor -- divide
| Factor
Factor = Primary
| "-" Primary -- negate
Primary = "(" Exp ")" -- paren
| number
number = digit+ ("." digit+)?
}
</script>
<pre id="result"></pre>
JavaScript
let g = ohm.grammarFromScriptElement();
let semantics = g.semantics().addOperation('eval', {
Exp_plus: (x, op, y) => x.eval() + y.eval(),
Exp_minus: (x, op, y) => x.eval() - y.eval(),
Term_times: (x, op, y) => x.eval() * y.eval(),
Term_divide: (x, op, y) => x.eval() / y.eval(),
Factor_negate: (op, x) => -x.eval(),
Primary_paren: (_left, exp, _right) => exp.eval(),
number(_, __, ___) {return parseFloat(this.interval.contents)},
});
let m = g.match('2+3*4');
let result = m.succeeded() ? semantics(m).eval() : m.message;
document.getElementById('result').textContent = result;