nearley Parser Toolkit

2.20.1 · active · verified Tue Apr 21

nearley is a comprehensive parsing toolkit for JavaScript that enables developers to define and parse custom languages. It utilizes the Earley parsing algorithm, making it capable of handling any context-free grammar, including notoriously difficult cases like left recursion, which often trip up other parser generators like PEG.js or Jison. The current stable version is 2.20.1, with releases synchronized to Zenodo for academic citation. Key differentiators include its streaming capabilities, graceful error handling, support for ambiguous grammars by providing all possible parsings, and compatibility with various lexers (e.g., moo). It also provides a robust toolchain for testing, railroad diagrams, and fuzzers, and works seamlessly in both Node.js and browser environments.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart defines a simple arithmetic grammar, compiles it dynamically (for demonstration), and then uses the nearley Parser to parse an input string and print the result. It also demonstrates error handling for invalid input.

const nearley = require('nearley');
const fs = require('fs');
const path = require('path');

// 1. Define your grammar in a .ne file or directly as a JS object
// For this example, let's create a simple grammar dynamically
const grammarSource = `
@{% function id(x) {return x[0];} %}
start -> expression:id
expression -> number:id (operation number):id* {% function(data) {
  let result = data[0];
  for (let i = 0; i < data[1].length; i++) {
    const op = data[1][i][0];
    const num = data[1][i][1];
    if (op === '+') result += num;
    if (op === '-') result -= num;
  }
  return result;
} %}
number -> [0-9]:+ {% function(data) { return parseInt(data.join('')); } %}
operation -> '+' | '-'
`;

// In a real scenario, you'd compile this via CLI:
// npx nearleyc mygrammar.ne -o mygrammar.js
// Then load it: const grammar = require('./mygrammar.js');

// For a quickstart, we'll compile it in-memory (requires nearley compiler)
const compile = require('nearley/lib/compile');
const generate = require('nearley/lib/generate');
const nearleyGrammar = require('nearley/lib/nearley-language-grammar');

const compiledGrammar = compile(nearley.Grammar.fromCompiled(nearleyGrammar), grammarSource);
const grammar = nearley.Grammar.fromCompiled(eval(generate(compiledGrammar, {}))); // Eval is risky, avoid in production

// 2. Create a Parser instance
const parser = new nearley.Parser(grammar);

// 3. Feed input to the parser
try {
  parser.feed('10+20-5');
  console.log('Parsed results:', parser.results); // Should output [25]
  parser.feed('3*4'); // This will fail as '*' is not in grammar
} catch (error) {
  console.error('Parsing error:', error.message);
}

// Example of parsing another valid input
const parser2 = new nearley.Parser(grammar);
parser2.feed('1+2+3-1');
console.log('Another result:', parser2.results); // Should output [5]

view raw JSON →