Parser generator for JavaScript that produces fast parsers with excellent error reporting
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core functionality for generating JavaScript parsers from PEG grammar specifications with comprehensive configuration options and multiple output formats.
Generates a parser from a specified grammar string with optional configuration.
/**
* Generates a parser from a specified grammar and returns it
* @param grammar - PEG grammar string in parser.pegjs format
* @param options - Optional generation configuration
* @returns Generated parser object or source code string
* @throws {peg.parser.SyntaxError} If grammar contains syntax error
* @throws {peg.GrammarError} If grammar contains semantic error
*/
function generate(grammar, options);Usage Examples:
const peg = require("pegjs");
// Basic parser generation
const parser = peg.generate('start = "hello" "world"');
const result = parser.parse("helloworld"); // Returns: ["hello", "world"]
// Generate source code instead of parser object
const source = peg.generate('start = "hello"', { output: "source" });
console.log(source); // JavaScript parser code as string
// Advanced configuration
const parser = peg.generate(grammar, {
allowedStartRules: ["expression", "statement"],
cache: true,
format: "commonjs",
optimize: "speed",
trace: false
});PEG.js can be used in browser environments with automatic module format detection and global variable support.
Browser Integration:
<!-- Include PEG.js library -->
<script src="path/to/peg.js"></script>
<script>
// PEG.js automatically detects environment:
// - AMD loader available: defines as AMD module
// - No AMD loader: available as global 'peg' variable
// Generate parser in browser
const grammar = `
start = "hello" "world"
`;
const parser = peg.generate(grammar);
const result = parser.parse("hello world");
console.log(result); // ["hello", "world"]
</script>AMD Module Usage:
// When AMD loader (like RequireJS) is detected
define(['peg'], function(peg) {
const parser = peg.generate(grammar);
return parser;
});Browser-Optimized Parser Generation:
// Generate optimized parser for browser delivery
const browserParser = peg.generate(grammar, {
output: "source",
format: "globals", // Creates global variable
exportVar: "MyParser", // Name of global variable
optimize: "size" // Minimize code size
});
// Save browserParser string to .js file for browser inclusion
// Usage: <script src="generated-parser.js"></script>
// MyParser.parse("input");Generated parsers provide a consistent interface for parsing input strings.
/**
* Generated parser interface
*/
interface GeneratedParser {
/**
* Parse input string using the generated grammar
* @param input - String to parse
* @param options - Optional parsing configuration
* @returns Parse result (depends on grammar actions)
* @throws {SyntaxError} If input doesn't match grammar
*/
parse(input, options);
}
/**
* Parse options for generated parsers
*/
interface ParseOptions {
/** Rule name to start parsing from (must be in allowedStartRules) */
startRule?: string;
/** Custom tracer object for debugging */
tracer?: any;
}Usage Examples:
// Basic parsing
const result = parser.parse("some input");
// Parse with specific start rule
const result = parser.parse("expression", { startRule: "expr" });
// Parse with custom tracer for debugging
const tracer = {
trace: function(event) {
console.log("Parse event:", event);
}
};
const result = parser.parse("input", { tracer: tracer });interface OutputOptions {
/**
* Parser output type
* - "parser": Return executable parser object (default)
* - "source": Return parser source code as string
*/
output?: "parser" | "source";
/**
* Generated code format (only when output is "source")
* - "amd": AMD module format
* - "bare": Plain JavaScript (compiler default)
* - "commonjs": CommonJS module format (CLI default)
* - "globals": Global variable assignment
* - "umd": Universal Module Definition
*/
format?: "amd" | "bare" | "commonjs" | "globals" | "umd";
/**
* Global variable name for parser (globals/umd formats only)
*/
exportVar?: string;
}interface BehaviorOptions {
/**
* Rules the parser can start parsing from
* Default: [first rule in grammar]
*/
allowedStartRules?: string[];
/**
* Enable result caching to avoid exponential parsing time
* Trade-off: faster parsing vs higher memory usage
* Default: false
*/
cache?: boolean;
/**
* Enable parser progress tracing for debugging
* Default: false
*/
trace?: boolean;
/**
* Optimization target
* - "speed": Optimize for parsing speed (default)
* - "size": Optimize for generated code size
*/
optimize?: "speed" | "size";
}interface DependencyOptions {
/**
* Module dependencies map for generated parser
* Maps variable names to module IDs
* Valid for: amd, commonjs, umd formats
* Example: { "lodash": "lodash", "utils": "./utils" }
*/
dependencies?: { [variable: string]: string };
/**
* Plugin instances to use during generation
* Plugins can modify compilation passes and options
*/
plugins?: any[];
}Usage Examples:
// Generate CommonJS module with dependencies
const source = peg.generate(grammar, {
output: "source",
format: "commonjs",
dependencies: {
"lodash": "lodash",
"utils": "./my-utils"
}
});
// Generate optimized parser for production
const parser = peg.generate(grammar, {
cache: true,
optimize: "speed",
allowedStartRules: ["program", "expression"]
});
// Generate browser-ready global parser
const source = peg.generate(grammar, {
output: "source",
format: "globals",
exportVar: "MyParser"
});/**
* Thrown when grammar contains semantic errors
*/
class GrammarError extends Error {
name: "GrammarError";
message: string;
location?: LocationRange;
}Common Grammar Errors:
Error Handling Example:
try {
const parser = peg.generate(invalidGrammar);
} catch (error) {
if (error.name === "GrammarError") {
console.error("Grammar error:", error.message);
if (error.location) {
console.error(`At line ${error.location.start.line}`);
}
} else if (error.name === "SyntaxError") {
console.error("Grammar syntax error:", error.message);
}
}Generated parsers throw SyntaxError when input doesn't match the grammar.
/**
* Thrown by generated parsers when input doesn't match grammar
*/
class SyntaxError extends Error {
name: "SyntaxError";
message: string;
expected: any[];
found: string;
location: LocationRange;
}Parser Error Handling Example:
try {
const result = parser.parse("invalid input");
} catch (error) {
if (error.name === "SyntaxError") {
console.error("Parse error:", error.message);
console.error("Expected:", error.expected);
console.error("Found:", error.found);
console.error(`At line ${error.location.start.line}, column ${error.location.start.column}`);
}
}Install with Tessl CLI
npx tessl i tessl/npm-pegjs