ABNF Parser Generator

4.4.0 · active · verified Tue Apr 21

JavaScript APG is a robust ABNF Parser Generator that enables developers to create recursive-descent parsers directly from a superset of ABNF (SABNF). It is currently stable at version 4.4.0, with a release cadence that has seen several updates in the past year, indicating active development and maintenance. Key differentiators include its ability to generate parsers for both standard `apg-js` and the more lightweight `apg-lite` framework, and its focus on fixing issues related to large grammars with mutually-recursive rules, a significant improvement over its predecessors like `apg-js2`. The library is designed to produce efficient parsers and provides options for TypeScript-compatible grammar objects, making it suitable for modern JavaScript and TypeScript environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining a simple ABNF grammar programmatically and using `ApgParser` to parse input strings, logging success or failure.

import { ApgParser } from 'apg-js';

// Define a simple grammar object programmatically. In a real scenario,
// this would often be generated from an ABNF file using the apg-js generator.
// This grammar parses a list of digits separated by commas.
const grammar = {
    _grammar: 'SimpleList',
    callbacks: {
        list: () => {}, // No semantic action needed for this simple example
        element: () => {},
        digit: () => {}
    },
    rules: {
        list: {
            // list = element *("," element)
            op: [
                { type: 1, p: 'element' },
                { type: 2, p: [
                    { type: 7, p: ',' },
                    { type: 1, p: 'element' }
                ]}
            ]
        },
        element: {
            // element = 1*DIGIT
            op: [{ type: 5, min: 1, max: 0, p: 'digit' }]
        },
        digit: {
            // digit = %d48-57 ; '0'-'9'
            op: [{ type: 3, min: 48, max: 57 }]
        }
    },
    udts: {},
    operators: [],
    ast: {
        defined: false,
        nodes: []
    }
};

const parser = new ApgParser(grammar);

const inputString1 = "1,23,456";
const result1 = parser.parse(inputString1);

if (result1.success) {
    console.log(`Successfully parsed "${inputString1}"`);
} else {
    console.error(`Failed to parse "${inputString1}": ${result1.state.toString()}`);
}

const inputString2 = "1,23,A456"; // Invalid input
const result2 = parser.parse(inputString2);

if (result2.success) {
    console.log(`Successfully parsed "${inputString2}"`);
} else {
    console.error(`Failed to parse "${inputString2}": ${result2.state.toString()}`);
}

view raw JSON →