UNPKG

@thi.ng/parse

Version:

Purely functional parser combinators & AST generation for generic inputs

47 lines (46 loc) 1.13 kB
const string = (str, id = "string") => (ctx) => { if (ctx.done) return false; const scope = ctx.start(id); const state = scope.state; const reader = ctx.reader; for (let i = 0, n = str.length; i < n; i++) { if (state.done) return false; if (reader.read(state) !== str[i]) { return ctx.discard(); } reader.next(state); } scope.result = str; return ctx.end(); }; const stringD = (str) => (ctx) => { if (ctx.done) return false; const state = ctx.state.copy(); const reader = ctx.reader; for (let i = 0, n = str.length; i < n; i++) { if (state.done) return false; if (reader.read(state) !== str[i]) { return false; } reader.next(state); } ctx.state = state; return true; }; const stringOf = (pred, id = "string", reduce = (x) => x.join("")) => (ctx) => { const state = ctx.state.copy(); const reader = ctx.reader; let acc = []; while (!state.done) { const r = reader.read(state); if (!pred(r)) break; acc.push(r); reader.next(state); } return ctx.addChild(id, reduce(acc), state); }; export { string, stringD, stringOf };