nearley-there
Nearley.js is a fantastic parser toolkit for Javascript. However I've found it's programmatic interface a bit lacking. nearley-there
fills in the gaps and make it easy to programmtically test and compile Nearley grammars into functional code.
Note: nearley-there
is a development tool and you should compile your grammars and not use this lib for production.
install
npm install nearley
npm install --save-dev nearley-there
The compiled grammars produced by nearley-there
require nearley
to run, but nearley-there
shouldn't be used in production.
usage
const N = ;const fs = ; const colorGrammar = fs; //N.parse takes a grammar string and targetconst color = N; //If can also take file paths to grammarsconst four = N; //N.compile returns a compiled module for your grammar, ready-to-useconst compiled = N;fs; //If you provide a filepath, it'll write the compiled grammar thereN;
api
.compile(grammar|path, [filepath])
Takes a grammar or a path to a grammar, compiles it, and returns the compiled parser as a string. If a filepath
is provided it will write the result to a new file there.
const compiled = N;fs; N;const ColorParser = ;const color = ;
.parse(grammar|path, target)
Takes a grammar or a path to a grammar, compiles it, then parses the target
through the compiled grammar and returns the result. This function will not throw errors if the target does not match the grammar, it will instead just return the parsing errors. It will throw errors if the grammar is invalid.
Warning: Uses eval()
. Don't use this other than for testing.
const color = N; const four = N;
.unparse(grammar|path, [depth=5])
Nearley also has the ability to do unparsing, where it can take a grammar and produce random strings that conform to that grammar.
.unparse()
takes a grammar or a path to a grammar, compiles it, the runs an unparser on it executing to the depth. This function may throw an error if the depth provided is too shallow ofr it to generate any results.
const randomColor = N; //randomColor -> '#3471a3';
.generator(grammar|path, [filepath])
Takes a grammar or a path to a grammar, compiles it, integrates in the unparser and returns the generator as a string. If a filepath
is provided it will write the result to a new file there.
N; const RandColor = ;const randomColor = ; //randomColor -> '#3471a3';
compiled parsers
Compiled parsers are ready-to-use js files that can be required and used as a parsing function. This is what is used to produce a compiled parser.
const Nearley = ; /** Generated by Nearley.js **/NEARLEY COMPILED GRAMMAR/** End **/ const CompiledGrammar = grammarParserRulesgrammarParserStartgrammar; module{ return CompiledGrammar results0;};
usage
//On buildconst N = ;N; //After buildconst Calculator = ; // -> 5