PEG.js Parser Generator

0.10.0 · maintenance · verified Wed Apr 22

PEG.js is a parser generator for JavaScript that produces fast parsers based on the Parsing Expression Grammar (PEG) formalism. It enables developers to define grammars for custom languages or complex data formats and generate a JavaScript parser function from them. The current stable version, 0.10.0, was released in August 2016. While the project's direct development on PEG.js itself has largely ceased, its successor, Peggy.js (npm: `peggy`), maintains API compatibility and active development. Key differentiators of PEG.js include its simple, expressive grammar syntax, excellent error reporting, and the ability to integrate both lexical and syntactical analysis into a single grammar. It can be used programmatically via a JavaScript API or through a command-line interface, generating parsers in multiple module formats like CommonJS (default), AMD, UMD, or global variables.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `pegjs` to define a simple arithmetic grammar, generate a parser at runtime, and then use that parser to evaluate expressions and catch parsing errors.

const pegjs = require('pegjs');

// Define a simple grammar for arithmetic expressions
const grammar = `
  start = expression

  expression = term (('+' / '-') term)* {
    return arguments[0].reduce((acc, current) => {
      const [op, val] = current;
      return op === '+' ? acc + val : acc - val;
    });
  }

  term = factor (('*' / '/') factor)* {
    return arguments[0].reduce((acc, current) => {
      const [op, val] = current;
      return op === '*' ? acc * val : acc / val;
    });
  }

  factor = number / '(' expression ')'

  number = [0-9]+ {
    return parseInt(text(), 10);
  }

  whitespace = [ \t\n\r]*
`;

// Generate the parser
try {
  const parser = pegjs.generate(grammar, { 
    output: 'parser', 
    format: 'commonjs', 
    optimize: 'speed' 
  });

  // Use the generated parser
  const input1 = "10 + 5 * (2 - 1)";
  const result1 = parser.parse(input1);
  console.log(`Input: "${input1}", Result: ${result1}`); // Expected: 15

  const input2 = "(100 / 2) - 15";
  const result2 = parser.parse(input2);
  console.log(`Input: "${input2}", Result: ${result2}`); // Expected: 35

  // Example of a parsing error
  const invalidInput = "10 + * 5";
  try {
    parser.parse(invalidInput);
  } catch (e) {
    console.error(`Error parsing "${invalidInput}": ${e.message}`);
  }

} catch (e) {
  console.error("Error generating parser: ", e.message);
}

view raw JSON →