Peggy/PEG.js Utility Library

2.0.2 · active · verified Sun Apr 19

pegjs-util is a utility library for the Peggy parser generator (formerly PEG.js), currently at stable version 2.0.2. It enhances Peggy's core `parse` function by injecting convenient utilities directly into grammar actions. The library provides three main features: Parser Tree Token Unrolling, which simplifies common patterns of extracting tokens from repeated grammar rule matches; Abstract Syntax Tree (AST) Node Generation, which assists in building structured ASTs directly within grammar rules; and improved, "cooked" Error Reporting, offering more user-friendly diagnostics than Peggy's default output. Releases appear to follow the development of Peggy itself, with the latest versions published as needed. It differentiates itself by streamlining common parser generator tasks, reducing boilerplate in `.peggy` grammar files, and providing a more robust parsing and error reporting experience.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use `pegjs-util` to parse a simple language, generate an Abstract Syntax Tree (AST) with `asty`, and benefit from enhanced error reporting. It shows the integration of `unroll` and `ast` helpers within a Peggy grammar, enabled by `PEGUtil.parse`.

const fs = require("fs");
const ASTY = require("asty"); // Companion library, install separately if needed
const PEG = require("peggy");
const PEGUtil = require("pegjs-util");

const pegjsGrammar = `
{
    var unroll = options.util.makeUnroll(location, options);
    var ast    = options.util.makeAST(location, options);
}

start
    = _ seq:id_seq _ {
          return ast("Sample").add(seq);
      }

id_seq
    = id:id ids:(_ "," _ id)* {
          return ast("IdentifierSequence").add(unroll(id, ids, 3));
      }

id
    = id:$([a-zA-Z_][a-zA-Z0-9_]*) {
          return ast("Identifier").set("name", id);
      }

_ "blank"
    = (co / ws)*

co "comment"
    = "//" (![\r\n] .)*
    / "/*" (!"*/" .)* "*/"

ws "whitespaces"
    = [ \t\r\n]+
`;

const asty = new ASTY();
const parser = PEG.generate(pegjsGrammar);

// Simulate input for parsing
const sampleInputOk = "/*  some ok input  */\nfoo, bar, quux";
const sampleInputBad = "/*  some bad input  */\nfoo, bar, quux baz";

function parseInput(inputString, fileName) {
  console.log(`\n--- Parsing ${fileName || 'input'} ---`);
  const result = PEGUtil.parse(parser, inputString, {
    startRule: "start",
    makeAST: function (line, column, offset, args) {
      // This callback is what the 'ast' helper in the grammar calls
      return asty.create.apply(asty, args).pos(line, column, offset);
    }
  });

  if (result.error !== null) {
    console.error("ERROR: Parsing Failure:\n" +
      PEGUtil.errorMessage(result.error, true).replace(/^/mg, "ERROR: "));
  } else {
    console.log(result.ast.dump().replace(/\n$/, ""));
  }
}

// To run this code, ensure you have installed:
// npm install peggy asty pegjs-util

parseInput(sampleInputOk, "sample-input-ok.txt");
parseInput(sampleInputBad, "sample-input-bad.txt");

view raw JSON →