Permalink
98 lines (80 sloc) 2.65 KB

Ohm Documentation

Examples

Here are some quick samples of what it's like to work with Ohm. For more in-depth examples, see the examples directory.

Matching Strings

Instantiate a grammar from a string using ohm.grammar(), and check inputs using the grammar's match() method:

var ohm = require('ohm-js');
var g = ohm.grammar(
    'Laugh {' +
    '  laugh = lol | "lmao"' +
    '  lol = "l" "o"+ "l"' +
    '}');
assert(g.match('lol').succeeded());
assert(!g.match('lmao').failed());
assert(g.match('loooooool').succeeded());

Implementing Semantics

You can use operations and attributes to analyze and extract values from parsed data. For example, take the following grammar in arithmetic.ohm:

Arithmetic {
  Exp
    = AddExp

  AddExp
    = AddExp "+" PriExp  -- plus
    | AddExp "-" PriExp  -- minus
    | PriExp

  PriExp
    = "(" Exp ")"  -- paren
    | number

  number
    = digit+
}

We can create an operation named 'eval' to evaluate arithmetic expressions that match the grammar:

// Instantiate the grammar.
var fs = require('fs');
var g = ohm.grammar(fs.readFileSync('arithmetic.ohm'));

// Create an operation that evaluates the expression. An operation always belongs to a Semantics,
// which is a family of related operations and attributes for a particular grammar.
var semantics = g.createSemantics().addOperation('eval', {
  Exp: function(e) {
    return e.eval();
  },
  AddExp: function(e) {
    return e.eval();
  },
  AddExp_plus: function(left, op, right) {
    return left.eval() + right.eval();
  },
  AddExp_minus: function(left, op, right) {
    return left.eval() - right.eval();
  },
  PriExp: function(e) {
    return e.eval();
  },
  PriExp_paren: function(open, exp, close) {
    return exp.eval();
  },
  number: function(chars) {
    return parseInt(this.sourceString, 10);
  },
});
var match = g.match('1 + (2 - 3) + 4');
assert.equal(semantics(match).eval(), 4);

You can learn more about semantics in the API reference.