EBNF Grammar to AST Parser

1.9.1 · active · verified Tue Apr 21

The `ebnf` package provides a JavaScript and TypeScript-compatible library for generating Abstract Syntax Tree (AST) parsers from formal grammars defined in either Backus-Naur Form (BNF) or W3C Extended Backus-Naur Form (EBNF). It is currently at version 1.9.1. The library differentiates itself by offering direct AST generation, browser compatibility, and built-in TypeScript type definitions, making it suitable for both Node.js and client-side applications. Releases appear to be driven by bug fixes and minor improvements, without a strict time-based cadence. It's particularly useful for projects requiring custom language parsing or syntax highlighting, such as Domain Specific Languages (DSLs) or code analysis tools.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a simple arithmetic grammar using BNF, create a parser instance, and then use it to generate an Abstract Syntax Tree (AST) for a given expression.

import { Grammars } from 'ebnf';

const mathGrammar = `
<Equation>         ::= <BinaryOperation> | <Term>
<Term>             ::= "(" <RULE_WHITESPACE> <Equation> <RULE_WHITESPACE> ")" | "(" <RULE_WHITESPACE> <Number> <RULE_WHITESPACE> ")" | <RULE_WHITESPACE> <Number> <RULE_WHITESPACE>
<BinaryOperation>  ::= <Term> <RULE_WHITESPACE> <Operator> <RULE_WHITESPACE> <Term>

<Number>           ::= <RULE_NEGATIVE> <RULE_NON_ZERO> <RULE_NUMBER_LIST> | <RULE_NON_ZERO> <RULE_NUMBER_LIST> | <RULE_DIGIT>
<Operator>         ::= "+" | "-" | "*" | "/" | "^"

<RULE_NUMBER_LIST> ::= <RULE_DIGIT> <RULE_NUMBER_LIST> | <RULE_DIGIT>
<RULE_NEGATIVE>    ::= "-"
<RULE_NON_ZERO>    ::= "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
<RULE_DIGIT>       ::= "0" | <RULE_NON_ZERO>
<RULE_WHITESPACE>  ::= <RULE_WS> | ""
<RULE_WS>          ::= " " <RULE_WHITESPACE> | "\n" <RULE_WHITESPACE> | " " | "\n"
`;

// Create a BNF parser instance with the defined grammar
const parser = new Grammars.BNF.Parser(mathGrammar);

// Parse an arithmetic expression and get the Abstract Syntax Tree (AST)
const ast = parser.getAST('(2 + (2 * -123)) * 5332');

console.log(JSON.stringify(ast, null, 2));

/*
Expected AST structure (simplified representation):
{
  "type": "Equation",
  "text": "(2 + (2 * -123)) * 5332",
  "children": [
    // ... detailed AST nodes for operations and numbers
  ]
}
*/

view raw JSON →