nearley is a comprehensive parsing toolkit for JavaScript that enables developers to define and parse custom languages. It utilizes the Earley parsing algorithm, making it capable of handling any context-free grammar, including notoriously difficult cases like left recursion, which often trip up other parser generators like PEG.js or Jison. The current stable version is 2.20.1, with releases synchronized to Zenodo for academic citation. Key differentiators include its streaming capabilities, graceful error handling, support for ambiguous grammars by providing all possible parsings, and compatibility with various lexers (e.g., moo). It also provides a robust toolchain for testing, railroad diagrams, and fuzzers, and works seamlessly in both Node.js and browser environments.
npm install nearleyVerified import paths — ran on the pinned version, not inferred.
This quickstart defines a simple arithmetic grammar, compiles it dynamically (for demonstration), and then uses the nearley Parser to parse an input string and print the result. It also demonstrates error handling for invalid input.
Thoroughly test your lexer rules, often by integrating a separate lexer like 'moo' and inspecting its output. Use nearley's built-in `nearley-test` tool.
If ambiguity is not desired, refine your grammar rules to be more specific or introduce precedence rules. The `nearley-test` tool can help visualize parse trees and identify ambiguities.
Run `npx nearleyc mygrammar.ne -o mygrammar.js` as part of your build process or development workflow. Then `require` or `import` the generated `.js` file.
Unset or appropriately manage `process.env.DEBUG` for production builds. Use `DEBUG=nearley:*` for more specific debugging control.
Review your input string and the corresponding grammar rules. Ensure your lexer is producing the expected tokens and that your grammar handles all possible sequences of these tokens. Use `nearley-test` for debugging.
Carefully review your `.ne` file for syntax errors. The `nearleyc` compiler will often provide a more specific line number for the error.
Ensure `nearley.Grammar.fromCompiled(myGrammar)` is correctly called with the output from your `.ne` file's compilation, and that `myGrammar` is indeed the object exported by the compiled grammar file.