PaulMcClernan / BNFToLPEG

LPEG parser from BNF grammar

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Hypervariety BNFToLPEG

What is it?

BNFToLPEG is a compact JavaScript library that will read and use a left-recursive parsing expression grammar. It's written to educate, and comes with a working editable demo.

A grammar defines a set of named rules and how they are combined. Given a grammar, you could parse text and diagram it automatically, link the result to other functions, or even convert the result into a similar grammar. BNF (Backus–Naur form) is a good choice for simple grammars because it is easy to read the declarations (rules, written out).

Simple example

In this simple example, we denote rules like this: <Rule>, by enclosing their names in angle brackets. Everything after the name and the equals sign is considered the text of the rule itself except for the special [] (optional) and | (choices). Text parsing with a grammar begins with a start rule, in this case <Sentence>.
<Sentence> = <Verb> the <Noun>.
<Sentence> = <Person>, [would you] [please] <Verb> the <Noun>?

<Verb> = look at | walk to | throw | eat | learn about
<Noun> = ball | dog | guitar | turkey sandwich
<Person> = you | Dad | Mr. President | Dog

Given this example, sort of a diagram of a very small part of the English language, we can examine a sentence to see if it fits the grammar. These sentences will fit:

Look at the ball.
Eat the turkey sandwich.
Dad, please walk to the guitar?
Mr. President, would you please learn about the turkey sandwich?
Eat the guitar.

These sentences will not fit, because they use text that is not in the grammar, or they do not fit any of the declarations:

Eat the chocolate.
Mr. President, dog guitar.
Dad, would you throw the you?
Eat the dad.

Full Documentation

Available at hypervariety.com/BNFToLPEG/

How to use BNFToLPEG

The BNFToLPEG library has almost no options. First, download or link the JavaScript at BNFToLPEG.js

BNFToLPEGParser(grammar).parse(input).output will construct a parser, parse input, and produce output. Using the success parameter instead of output will access a object containing { index, endIndex, subrules[], rule, version }, or null if the input didn't fit the grammar. See the text of the script for documentation.

Feel free to use the code in personal projects (noncommercial). Feel free to use the techniques in this document wherever you can.

BNFToLPEG : (c) 2023 Hypervariety Custom Programming

About

LPEG parser from BNF grammar


Languages

Language:HTML 52.5%Language:JavaScript 47.5%