From 950faa740b86af5f264717898f24ae8fb65c036d Mon Sep 17 00:00:00 2001 From: Akshay Nair Date: Fri, 14 Jan 2022 21:15:29 +0530 Subject: feat: implements string literal parser --- src/parser/utils.ts | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) (limited to 'src/parser/utils.ts') diff --git a/src/parser/utils.ts b/src/parser/utils.ts index 4e2c9d6..564d97c 100644 --- a/src/parser/utils.ts +++ b/src/parser/utils.ts @@ -29,18 +29,20 @@ export const sepBy1 = (sep: Parser, parser: Parser): Parser => ), ) -export const not = (parser: Parser): Parser => (input: string) => +export const not = (parser: Parser): Parser => (input: string) => pipe( input, parser, Either.fold( - ([_left, inp]) => Either.right([null, inp]), + ([_left, inp]) => Either.right([null as never, inp]), ([_right, inp]) => Either.left(['`not` parser failed. Match found', inp]) ), ) -export const manyTill = (parser: Parser, end: Parser): Parser => - mapTo(pair(many0(suffixed(parser, not(end))), parser), ([xs, l]) => xs.concat([l])) +export const manyTill = (parser: Parser, end: Parser): Parser => { + const p = pair(many0(suffixed(parser, not(end))), suffixed(parser, end)) + return mapTo(p, ([xs, l]) => xs.concat([l])) +} export const many0 = (parser: Parser): Parser> => flow( @@ -94,15 +96,16 @@ export const delimited = ( s: Parser, ): Parser => suffixed(prefixed(p, a), s) -export const satifyChar = +export const satisfyChar = (f: (c: char) => boolean): Parser => (input: string) => { + if (input.length === 0) return Either.left(['Unexpected end of input', input]) const c = input.charAt(0) if (f(c)) return Either.right([c, input.slice(1)]) return Either.left([`Expected to satisfy ${f}, got "${c}"`, input]) } -export const digit = satifyChar(c => /^[0-9]$/g.test(c)) +export const digit = satisfyChar(c => /^[0-9]$/g.test(c)) export const digits: Parser = flow( many1(digit), @@ -121,7 +124,7 @@ export const or = (parsers: Parser[]): Parser => { : (inp: string) => Either.left(['unable to match', inp]) } -export const matchChar = (ch: char): Parser => satifyChar(eq(ch)) +export const matchChar = (ch: char): Parser => satisfyChar(eq(ch)) export const matchString = (s: string): Parser => -- cgit v1.3.1