nodebnf

raw JSON →
1.0.1 verified Fri May 01 auth: no javascript

BNF is a JavaScript library for compiling, parsing, and interpreting BNF and ABNF grammars. Version 1.0.1 uses ECMAScript 6+ and supports inline compilation of grammars, predefined rules (e.g., DIGIT, CRLF, LITERAL), rule events, and multi-language scripts (planned). It runs on Node.js. Unlike other parser generators (e.g., PEG.js, ANTLR), BNF focuses on simplicity and direct embedding of BNF/ABNF syntax without a separate generation step. The library is in early development, with custom rule APIs subject to change.

error TypeError: compiler.AddLanguage is not a function
cause Importing the library incorrectly (e.g., default import or wrong path).
fix
Use import { Compiler } from 'bnf'; and instantiate with new Compiler().
error Error: No language registered
cause Calling ParseScript before AddLanguage.
fix
Ensure AddLanguage is called with a valid grammar before parsing.
error SyntaxError: Unexpected token
cause Invalid BNF/ABNF syntax (e.g., missing angle brackets or incorrect repeat notation).
fix
Validate grammar using BNF syntax: <rule> ::= <expression> | "literal" or ABNF: rule = expression / "literal".
breaking Custom BNF rules API is unstable and will change during minor version updates.
fix Avoid writing custom rules until v2 stabilizes, or pin to a specific minor version.
deprecated The prior version used a custom JavaScript markup for script files; this feature is removed in v1.
fix Migrate to inline compiling with AddLanguage and ParseScript.
gotcha Method names are PascalCase (e.g., AddLanguage, ParseScript) unlike typical JavaScript camelCase.
fix Use exactly the documented casing: AddLanguage, SetRuleEvents, ParseScript.
gotcha The predefined rule SYNTAX must be declared in every grammar; missing it causes parse failure.
fix Always include a rule named SYNTAX as the entry point.
npm install bnf
yarn add bnf
pnpm add bnf

Creates a compiler, adds a calculator grammar, sets rule events, and parses expressions.

import { Compiler } from 'bnf';

const compiler = new Compiler();
compiler.AddLanguage(`
  <SYNTAX> ::= <evaluation> | <evaluation> <CRLF> <SYNTAX>
  <evaluation> ::= <number> <OWSP> <type> <OWSP> <number>
  <number> ::= <DIGITS>
  <type> ::= "+" | "-" | "/" | "*"
`, "testLang");
compiler.SetRuleEvents({
  evaluation(token) {
    console.log("evaluation token found answer:", eval(token.value));
  }
});
compiler.ParseScript(`
5456 / 13
11 + 3
10 * 8
`.trim());