{"id":16875,"library":"pegjs","title":"PEG.js Parser Generator","description":"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.","status":"maintenance","version":"0.10.0","language":"javascript","source_language":"en","source_url":"https://github.com/pegjs/pegjs","tags":["javascript","parser generator","PEG"],"install":[{"cmd":"npm install pegjs","lang":"bash","label":"npm"},{"cmd":"yarn add pegjs","lang":"bash","label":"yarn"},{"cmd":"pnpm add pegjs","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"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`.","wrong":"import pegjs from 'pegjs';","symbol":"pegjs","correct":"const pegjs = require('pegjs');"},{"note":"The `pegjs.buildParser` function was renamed to `pegjs.generate` in v0.10.0. Using `buildParser` will result in an error in this version.","wrong":"const parser = pegjs.buildParser(grammarString, options);","symbol":"generate","correct":"const parser = pegjs.generate(grammarString, options);"},{"note":"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`.","symbol":"parser.parse","correct":"const result = myParser.parse('input string');"}],"quickstart":{"code":"const pegjs = require('pegjs');\n\n// Define a simple grammar for arithmetic expressions\nconst grammar = `\n  start = expression\n\n  expression = term (('+' / '-') term)* {\n    return arguments[0].reduce((acc, current) => {\n      const [op, val] = current;\n      return op === '+' ? acc + val : acc - val;\n    });\n  }\n\n  term = factor (('*' / '/') factor)* {\n    return arguments[0].reduce((acc, current) => {\n      const [op, val] = current;\n      return op === '*' ? acc * val : acc / val;\n    });\n  }\n\n  factor = number / '(' expression ')'\n\n  number = [0-9]+ {\n    return parseInt(text(), 10);\n  }\n\n  whitespace = [ \\t\\n\\r]*\n`;\n\n// Generate the parser\ntry {\n  const parser = pegjs.generate(grammar, { \n    output: 'parser', \n    format: 'commonjs', \n    optimize: 'speed' \n  });\n\n  // Use the generated parser\n  const input1 = \"10 + 5 * (2 - 1)\";\n  const result1 = parser.parse(input1);\n  console.log(`Input: \"${input1}\", Result: ${result1}`); // Expected: 15\n\n  const input2 = \"(100 / 2) - 15\";\n  const result2 = parser.parse(input2);\n  console.log(`Input: \"${input2}\", Result: ${result2}`); // Expected: 35\n\n  // Example of a parsing error\n  const invalidInput = \"10 + * 5\";\n  try {\n    parser.parse(invalidInput);\n  } catch (e) {\n    console.error(`Error parsing \"${invalidInput}\": ${e.message}`);\n  }\n\n} catch (e) {\n  console.error(\"Error generating parser: \", e.message);\n}","lang":"javascript","description":"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."},"warnings":[{"fix":"Update calls from `pegjs.buildParser` to `pegjs.generate`. For browser environments, use `peg` instead of `PEG` if relying on global exports.","message":"In 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`.","severity":"breaking","affected_versions":">=0.10.0"},{"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.","message":"In 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.","severity":"breaking","affected_versions":">=0.8.0"},{"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.","message":"The 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.","severity":"gotcha","affected_versions":">=0.10.0"},{"fix":"Evaluate migrating to Peggy.js (`npm install peggy`) for an actively maintained and compatible parser generator.","message":"PEG.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.","severity":"gotcha","affected_versions":">=0.10.0"},{"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.","message":"Tracing 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.","severity":"deprecated","affected_versions":">=0.9.0 <0.10.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change `pegjs.buildParser(...)` to `pegjs.generate(...)`.","cause":"Attempting to call the deprecated `buildParser` method instead of `generate`.","error":"TypeError: pegjs.buildParser is not a function"},{"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.","cause":"The grammar contains a construct that could lead to infinite recursion during parsing, a check introduced in v0.9.0.","error":"Error: Infinite loop detected in grammar."},{"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.","cause":"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.","error":"ReferenceError: PEG is not defined"},{"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.","cause":"The input string does not conform to the defined grammar rules at the specified location.","error":"SyntaxError: Expected [rule description] but [found token] found."}],"ecosystem":"npm","meta_description":null}