From 3854a42db888a58f0452bfb23b6e17df5bf8ad39 Mon Sep 17 00:00:00 2001 From: Akshay Nair Date: Thu, 10 Aug 2023 21:27:42 +0530 Subject: feat: multi expression parser done --- src/utils/parser-comb.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src/utils/parser-comb.ts') diff --git a/src/utils/parser-comb.ts b/src/utils/parser-comb.ts index 9cea86f..49f633e 100644 --- a/src/utils/parser-comb.ts +++ b/src/utils/parser-comb.ts @@ -17,12 +17,14 @@ export type ParseResult = Result<{ value: T, input: string }, { error: string export type Parser = (input: string) => ParseResult; export const regex = (re: RegExp): Parser => input => { + if (input.length === 0) return Result.Err({ error: 'fuckedinput', input }) const res = input.match(re) if (!res) return Result.Err({ error: 'fucked', input }); return Result.Ok({ value: res[0], input: input.replace(re, '') }); } export const string = (str: string): Parser => input => { + if (input.length === 0) return Result.Err({ error: 'fuckedinput', input }) if (!input.startsWith(str)) return Result.Err({ error: 'fuckedstring', input }) return Result.Ok({ value: str, input: input.slice(str.length) }); } @@ -61,3 +63,24 @@ export const suffixed = (parser: Parser, parserSuffix: Parser): Parse export const between = (prefix: Parser, parser: Parser, suffix: Parser): Parser => suffixed(prefixed(prefix, parser), suffix) +export const many0 = (parser: Parser): Parser> => originalInput => + match(parser(originalInput), { + Ok: ({ value, input }) => map(many0(parser), ls => [value, ...ls])(input), + Err: ({ input }) => Result.Ok({ value: [], input }), + }) + +export const many1 = (parser: Parser): Parser> => originalInput => + match(parser(originalInput), { + Ok: ({ value, input }) => map(many0(parser), ls => [value, ...ls])(input), + Err: err => Result.Err(err), + }) + +export const sepBy = (parser: Parser, sepP: Parser): Parser> => originalInput => + match(parser(originalInput), { + Ok: ({ value, input }) => map( + many0(prefixed(sepP, parser)), + ls => [value, ...ls] + )(input), + Err: _ => Result.Ok({ value: [], input: originalInput }), + }) + -- cgit v1.3.1