diff options
| author | Akshay Nair <phenax5@gmail.com> | 2022-01-06 21:08:12 +0530 |
|---|---|---|
| committer | Akshay Nair <phenax5@gmail.com> | 2022-01-06 21:08:12 +0530 |
| commit | f129d1d6e8f03e586952d8c792c8e085ae7bca85 (patch) | |
| tree | d9957ad3c42f886748cb6007451cba8b5f566d49 /src | |
| parent | 6ee30757cf9946074e2b5bb29a59b299fc48d0d8 (diff) | |
| download | elxr-f129d1d6e8f03e586952d8c792c8e085ae7bca85.tar.gz elxr-f129d1d6e8f03e586952d8c792c8e085ae7bca85.zip | |
feat: basic parser
Diffstat (limited to '')
| -rw-r--r-- | src/index.d.ts | 7 | ||||
| -rw-r--r-- | src/index.ts | 56 |
2 files changed, 62 insertions, 1 deletions
diff --git a/src/index.d.ts b/src/index.d.ts new file mode 100644 index 0000000..fdaab41 --- /dev/null +++ b/src/index.d.ts @@ -0,0 +1,7 @@ +import { Either } from 'fp-ts/Either'; +declare type ParserResult<T> = [T, string]; +declare type ParserError = [string, string]; +declare type Parser<T> = (input: string) => Either<ParserError, ParserResult<T>>; +export declare const p_digit: Parser<string>; +export declare const many0: <T>(p: Parser<T>) => Parser<T[]>; +export {}; 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> = [T, string] +type ParserError = [string, string] +type Parser<T> = (input: string) => Either<ParserError, ParserResult<T>> + +export const many0 = <T>(parser: Parser<T>): Parser<Array<T>> => flow( + parser, + chain(([a, nextInput]) => + pipe( + nextInput, + many0(parser), + map(([ls, inp]): ParserResult<T[]> => [[a, ...ls], inp]), + ) + ), + orElse(([_, inp]) => right([[] as T[], inp])) +) + +export const many1 = <T>(parser: Parser<T>): Parser<Array<T>> => 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<char> => (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<number> = flow( + many1(digit), + map(([ds, input]) => [parseInt(ds.join(''), 10), input]) +) + +export const or = <T>(parsers: Parser<T>[]): Parser<T> => { + const ppp = ([p, ...ps]: Parser<T>[]) => 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]) + |
