From b3fc08cae05f997e71d846109d400e630b8a4c35 Mon Sep 17 00:00:00 2001 From: Akshay Nair Date: Fri, 7 Jan 2022 17:51:12 +0530 Subject: feat: adds quantifier suffix parsing + recoverInput for combinators --- src/parser.ts | 44 +++++++++++++++++++++++++++++++++++--------- 1 file changed, 35 insertions(+), 9 deletions(-) (limited to 'src/parser.ts') diff --git a/src/parser.ts b/src/parser.ts index baa3e76..a7d6528 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -1,14 +1,24 @@ -import { flow, pipe } from 'fp-ts/function' -import { Either, left, right, map, chain, orElse, fold } from 'fp-ts/Either' +import { constant, flow, pipe } from 'fp-ts/function' +import { + Either, + left, + right, + map, + chain, + orElse, + fold, + orElseW, +} from 'fp-ts/Either' import { none, some, Option } from 'fp-ts/Option' -import { mapFst, snd } from 'fp-ts/Tuple' +import { mapFst, mapSnd, snd } from 'fp-ts/Tuple' import { eq } from './utils' export type char = string -export type ParserResult = [T, string] +export type ParserState = [T, string] export type ParserError = [string, string] -export type Parser = (input: string) => Either> +export type ParserResult = Either> +export type Parser = (input: string) => ParserResult export const constP = (v: T): Parser => @@ -39,13 +49,29 @@ export const many1 = (parser: Parser): Parser> => ) ) +const recoverInput = + (p: Parser): Parser => + (input: string) => + pipe( + input, + p, + orElseW( + flow( + mapSnd((_) => input), + left + ) + ) + ) + export const prefixed = (a: Parser, b: Parser): Parser => - flow(a, chain(flow(snd, b))) + recoverInput(flow(a, chain(flow(snd, b)))) export const suffixed = (a: Parser, b: Parser): Parser => - flow( - a, - chain(([out, inp]) => pipe(inp, b, map(mapFst((_) => out)))) + recoverInput( + flow( + a, + chain(([out, inp]) => pipe(inp, b, map(mapFst((_) => out)))) + ) ) export const delimited = ( -- cgit v1.3.1