nearley consists of two components: a compiler and a parser.
The nearley compiler converts grammar definitions from a simple BNF-based syntax to a small JS module. You can then use that module to construct a nearley parser, which parses input strings.
To use the nearley parser, you need to install nearley locally.
$ npm install --save nearley
To use the nearley compiler, you need to additionally install nearley globally.
$ npm install -g nearley
This actually adds several new commands to your
nearley-testlets you quickly test a grammar against some input and see the results. It also lets you explore the internal state of nearley’s Earley table, in case you find that interesting.
nearley-unparseinverts a parser into a generator, allowing you to create random strings that match your grammar.
nearley-railroadgenerates pretty railroad diagrams from your parser. This is mainly helpful for creating documentation, as (for example) on json.org.
These are documented on the tooling page.
Note: If you’re not ready to install nearley yet, you can follow along in your browser using the nearley playground, an online interface for exploring nearley grammars interactively.
nearley in 3 steps
nearley was written with users in mind: getting started with nearley is as simple as:
Step 1: Describe your grammar using the nearley syntax. In
a file called
main -> (statement "\n"):+ statement -> "foo" | "bar"
$ nearleyc grammar.ne -o grammar.js
const nearley = require("nearley"); const grammar = require("./grammar.js"); // Create a Parser object from our grammar. const parser = new nearley.Parser(nearley.Grammar.fromCompiled(grammar)); // Parse something! parser.feed("foo\n"); // parser.results is an array of possible parsings. console.log(parser.results); // [[[[ "foo" ],"\n" ]]]
Now that you have nearley installed, you can learn how to write a grammar!
- Take a look at a nearley tutorial written by @gajus, or a blog post about using nearley-unparse to generate murder mystery plots.
- Read my blog post to learn more about the algorithm.
- Read about Marpa to learn more than you ever thought you wanted to know about parsing.