Registry / data / pegjs
library0.10.0jsnpmunverified

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.

npm install pegjs
INSTALL
IMPORT
SIG · PEGJS
P
pegjs
datajavascriptv0.10.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pegjs
const pegjs = require('pegjs');
import pegjs from 'pegjs';
PEG.js v0.10.0 is a CommonJS module. Direct `import` syntax is not supported without a transpiler like Babel or a bundler configured for CJS interop. For modern ES module usage, consider `peggy`.
generate
const parser = pegjs.generate(grammarString, options);
const parser = pegjs.buildParser(grammarString, options);
The `pegjs.buildParser` function was renamed to `pegjs.generate` in v0.10.0. Using `buildParser` will result in an error in this version.
parser.parse
const result = myParser.parse('input string');
The generated parser (e.g., `myParser`) is a function with a `.parse()` method. This method takes the input string and returns the parsed result or throws a `SyntaxError`.

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); }
pegjs --version
Debug
Known issues
breakingIn v0.10.0, the primary API function `pegjs.buildParser` was renamed to `pegjs.generate`. Code using the old function name will break. Additionally, the global variable name for browser use changed from `PEG` to `peg`.
fix
Update calls from `pegjs.buildParser` to `pegjs.generate`. For browser environments, use `peg` instead of `PEG` if relying on global exports.
affects: >=0.10.0
breakingIn v0.8.0, all internal identifiers in generated parser code were prefixed with `peg$` to discourage their direct use and avoid conflicts. Code that directly accessed non-prefixed internal variables within generated parsers will likely break.
fix
Avoid direct manipulation of internal parser state or variables within generated code. If absolutely necessary, adapt to the `peg$` prefix, but this is discouraged.
affects: >=0.8.0
gotchaThe default output module format for generated parsers changed in v0.10.0. While CommonJS remains the default, explicitly specifying the `format` option (e.g., `format: 'commonjs'`, `format: 'umd'`, `format: 'globals'`) is now clearer and recommended, especially if distributing the generated parser.
fix
Always specify the `format` option in `pegjs.generate` (e.g., `{ format: 'commonjs' }`) or via the `--format` CLI option to ensure the desired output module system.
affects: >=0.10.0
gotchaPEG.js v0.10.0 was released in August 2016 and is no longer actively maintained. For ongoing development, modern JavaScript features, and TypeScript support, consider migrating to its direct successor, Peggy.js (`npm install peggy`), which is API compatible and actively maintained.
fix
Evaluate migrating to Peggy.js (`npm install peggy`) for an actively maintained and compatible parser generator.
affects: >=0.10.0
deprecatedTracing support, introduced in v0.9.0, was marked as experimental. Its API and behavior were subject to change, and users should not rely on its stability across minor versions.
fix
If using tracing features, be prepared for potential API changes. For v0.10.0, consult the specific documentation for its tracing implementation, if available.
affects: >=0.9.0 <0.10.0
Errors
Common errors & fixes
TypeError: pegjs.buildParser is not a function
Attempting to call the deprecated `buildParser` method instead of `generate`.
fix
Change `pegjs.buildParser(...)` to `pegjs.generate(...)`.
Error: Infinite loop detected in grammar.
The grammar contains a construct that could lead to infinite recursion during parsing, a check introduced in v0.9.0.
fix
Review grammar rules for left recursion or other patterns that could cause infinite loops. Restructure rules to ensure progress is made with each match.
ReferenceError: PEG is not defined
In a browser environment, the global API name changed from `PEG` to `peg` in v0.10.0, or the UMD/global output format was not correctly integrated.
fix
Use `peg` instead of `PEG` for the global variable. Ensure the generated parser script is included correctly and the format option (e.g., `globals`) is set appropriately during generation.
SyntaxError: Expected [rule description] but [found token] found.
The input string does not conform to the defined grammar rules at the specified location.
fix
Debug the input string and grammar. Use the error's `location` property (offset, line, column) to pinpoint the exact mismatch. Consider adding more robust error handling or `error()` calls within grammar actions.
Upgrade
Version history
0.10.0latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
4 hits · last 30 days
node
4
Resources
pegjs — npm install pegjs · libregistry