From f129d1d6e8f03e586952d8c792c8e085ae7bca85 Mon Sep 17 00:00:00 2001 From: Akshay Nair Date: Thu, 6 Jan 2022 21:08:12 +0530 Subject: feat: basic parser --- src/index.ts | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 55 insertions(+), 1 deletion(-) (limited to 'src/index.ts') diff --git a/src/index.ts b/src/index.ts index 71455c6..a9b3409 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1 +1,55 @@ -export const x: number = 200 +import { flow, identity, pipe } from 'fp-ts/function' +import { Either, left, right, map, chain, mapLeft, fold, orElse } from 'fp-ts/Either' + +type char = string + +type ParserResult = [T, string] +type ParserError = [string, string] +type Parser = (input: string) => Either> + +export const many0 = (parser: Parser): Parser> => flow( + parser, + chain(([a, nextInput]) => + pipe( + nextInput, + many0(parser), + map(([ls, inp]): ParserResult => [[a, ...ls], inp]), + ) + ), + orElse(([_, inp]) => right([[] as T[], inp])) +) + +export const many1 = (parser: Parser): Parser> => flow( + many0(parser), + chain(([res, inp]) => + res.length > 0 ? right([res, inp]) : left([`many1 failed to parse at ${inp}`, inp])) +) + +export const satify_char = (f: (c: char) => boolean): Parser => (input: string) => { + const c = input.charAt(0) + if (f(c)) return right([c, input.slice(1)]) + return left([`Expected to satisfy ${f}, got "${c}"`, input]) +}; + +export const digit = satify_char(c => /^[0-9]$/g.test(c)) + +export const integer: Parser = flow( + many1(digit), + map(([ds, input]) => [parseInt(ds.join(''), 10), input]) +) + +export const or = (parsers: Parser[]): Parser => { + const ppp = ([p, ...ps]: Parser[]) => flow( + p, + orElse(([_, inp]) => or(ps)(inp)) + ) + + return parsers.length > 0 ? ppp(parsers) : (inp: string) => left(['unable to match', inp]) +} + +export const space = satify_char(c => c === ' ') +export const newline = satify_char(c => c === '\n') +export const tab = satify_char(c => c === '\t') + +export const whitespace = or([space, newline, tab]) + -- cgit v1.3.1