Casual Parsing in JavaScript
brandons.me
brandons.me
[0] https://github.com/preludejs/parser/blob/master/rfc4180.ts
The library is open source here, contributions welcome: https://github.com/RoyalIcing/yieldparser
Generator functions have great support in modern browsers (not IE) and Node.js.
For example here’s a simple v4 IP address parser:
import { parse, mustEnd } from 'yieldparser';
function* Digit() {
const [digit]: [string] = yield /^\d+/;
const value = parseInt(digit, 10);
if (value < 0 || value > 255) {
return new Error(`Digit must be between 0 and 255, was ${value}`);
}
return value;
}
function* IPAddress() {
const first = yield Digit;
yield '.';
const second = yield Digit;
yield '.';
const third = yield Digit;
yield '.';
const fourth = yield Digit;
yield mustEnd;
return [first, second, third, fourth];
}
parse('1.2.3.4', IPAddress());
/*
{
success: true,
result: [1, 2, 3, 4],
remaining: '',
}
*/In Python, my go-to library is Tatsu[0], but I guess I should also give a try to ANTLR4[1].
Also, for parser combinators, Elixir have the amazing NimbleParsec[2] library which is amazingly easy to use.
[0] - https://tatsu.readthedocs.io/en/stable/
[1] - https://www.antlr.org
[2] - https://hexdocs.pm/nimble_parsec/NimbleParsec.htmlIt’s not over-promising, either. I went from never having heard of it before to getting complete and correct parse trees of some ancient JSP Expression Language in about 20 minutes. Most of that time was spent typing in the BNF description that I could find only in an image.