Skip to main content

A library for parsing GBNF grammars

Project description

GBNF

Latest GBNF NPM Version License for gbnf Downloads per week on NPM for gbnf Status of tests for gbnf repository Code Coverage for gbnf DeepSource issues for gbnf

A library for parsing .gbnf grammar files in Javascript.

Install

npm install gbnf

Usage

Pass your grammar to GBNF:

import GBNF from 'gbnf';
const state = GBNF(`
root  ::= "yes" | "no"
`)

If the grammar is invalid, GBNF will throw.

GBNF returns a state representing the parsed state:

import GBNF from 'gbnf';
const state = GBNF(`
root  ::= "yes" | "no"
`)
for (const rule of state) {
  console.log(rule); 
  // { type: "CHAR", value: ["y".charCodeAt(0)]}
  // { type: "CHAR", value: ["n".charCodeAt(0)]}
}

state can be iterated over. (You can also call the iterator method directly with state.rules()). state cannot be indexed directly, but can easily be cast to an array with [...state] and indexed that way.

States are immutable. To parse a new token, call state.add():

import GBNF from 'gbnf';
let state = GBNF(`
root  ::= "I like green eggs and ham"
`)
console.log([...state]); // [{ type: "CHAR", value: ["I".charCodeAt(0)]}]
state = state.add("I li");
console.log([...state]); // [{ type: "CHAR", value: ["k".charCodeAt(0)]}]
state = state.add("ke gree");
console.log([...state]); // [{ type: "CHAR", value: ["n".charCodeAt(0)]}]

The possible rules returned include:

  • CHAR - contains an array of either numbers representing code points to match, or an array of two numbers denoting a range within which a code point may appear.
  • CHAR_EXCLUDED - contains an array of numbers representing code points not to match, or an array of two numbers denoting a range within which a code point may not appear.
  • END - denotes a valid end of a string.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

gbnf-0.0.1.tar.gz (3.6 kB view hashes)

Uploaded Source

Built Distribution

gbnf-0.0.1-py3-none-any.whl (3.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page