Peggy Parser Generator

5.1.0 · active · verified Sun Apr 19

Peggy is a robust, open-source parser generator for JavaScript that serves as the successor to the popular PEG.js project. It enables developers to define grammars using a simple and expressive syntax based on parsing expression grammar (PEG) formalism, which is more powerful than traditional LL(k) and LR(k) parsers. Peggy integrates both lexical and syntactical analysis and produces fast parsers with excellent error reporting capabilities. The current stable version is 5.1.0, with regular patch and minor releases, and major versions released less frequently. Key differentiators include its superior error reporting, integration of lexical and syntactical analysis, and being usable across various environments: browsers (via an online tool), command line, and as a JavaScript API. It also provides source map support and ships with TypeScript definitions, making it well-suited for modern JavaScript and TypeScript development workflows. It requires Node.js version 20 or higher.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple arithmetic grammar, generate a parser using `peggy.generate`, and then use the generated parser to process an input string. It also illustrates how to catch and handle `SyntaxError` instances thrown by the parser.

import { generate } from 'peggy';

const grammar = `
  start = expression
  expression = term (('+' / '-') term)*
  term = factor (('*' / '/') factor)*
  factor = number / '(' expression ')'
  number 'number' = [0-9]+ { return parseInt(text()); }
`;

try {
  const parser = generate(grammar, { output: 'parser', format: 'es' });

  const result = parser.parse('1 + 2 * (3 - 4)');
  console.log('Parse successful:', result);

  // Example of a syntax error
  parser.parse('1 +');
} catch (e: any) {
  if (e.name === 'SyntaxError') {
    console.error(`Syntax Error at line ${e.location.start.line}, column ${e.location.start.column}: ${e.message}`);
  } else {
    console.error('An unexpected error occurred:', e);
  }
}

view raw JSON →