https://github.com/codebox/top-down-parser
A simple top-down parser written in JavaScript
https://github.com/codebox/top-down-parser
es6 javascript parser
Last synced: 7 months ago
JSON representation
A simple top-down parser written in JavaScript
- Host: GitHub
- URL: https://github.com/codebox/top-down-parser
- Owner: codebox
- License: mit
- Created: 2018-12-08T13:40:58.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2018-12-27T13:21:31.000Z (about 7 years ago)
- Last Synced: 2025-05-25T04:21:34.323Z (8 months ago)
- Topics: es6, javascript, parser
- Language: JavaScript
- Homepage: https://codebox.net/pages/top-down-parser-in-javascript
- Size: 61.5 KB
- Stars: 4
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Top-Down Parser
A simple top-down parser written in JavaScript. Every so often I need to write a parser, and keep forgetting how the recursion works.
This is a simple- and general-as-possible implementation that I can refer back to in the future.
To use the parser, call the `buildParser()` function with a single string argument containing the grammar.
Each production rule in the grammar should be on a separate line, and the symbol should be followed by the character sequence `->`,
and then by the substitutions. The symbol `|` is used as a delimiter on the RHS of a rule if there are multiple valid substitutions.
By default the start symbol is the text `START` and `ε` is used to represent an empty string,
alternate values can be supplied when calling `buildParser()`.
I have used several ES6 language features in the code, so this won't work in older browsers.
## Example
const parser = buildParser(`
START -> EXPR
EXPR -> NUM | NUM OP EXPR
NUM -> 0 | 1 | 2 | 3 | 4
OP -> + | - | * | /
`);
parser.parse('1 + 2')
Will return:
{
'remainder : '',
'tree' : {
'START' : [
{'EXPR' : [
{'NUM' : ['1']},
{'OP' : ['+']},
{'EXPR' : [
{'NUM' : ['2']},
]}
]}
]
}
}