import { flow, pipe } from 'fp-ts/function' import { Either, left, right, map, chain, orElse } from 'fp-ts/Either' export type char = string export type ParserResult = [T, string] export type ParserError = [string, string] export type Parser = (input: string) => Either> export const constP = (v: T): Parser => (inp: string) => right([v, inp]) 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 prefixed = (a: Parser, b: Parser): Parser => flow( a, chain(([_, inp]) => b(inp)) ) export const suffixed = (a: Parser, b: Parser): Parser => flow( a, chain(([out, inp]) => pipe( inp, b, chain(([_, inp2]) => right([out, inp2])) ) ) ) export const delimited = ( p: Parser, a: Parser, s: Parser ): Parser => suffixed(prefixed(p, a), s) export const satifyChar = (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 = satifyChar((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 matchChar = (ch: char): Parser => satifyChar((c) => c === ch) export const space = matchChar(' ') export const newline = matchChar('\n') export const tab = matchChar('\t') export const whitespace = or([space, newline, tab]) export const whitespaces0 = many0(whitespace) export const matchString = (s: string): Parser => s === '' ? constP('') : flow( matchChar(s.charAt(0)), chain(([c, inp]) => pipe( inp, matchString(s.slice(1)), map(([s, inp]) => [c + s, inp]) ) ) ) export const symbol = (s: string): Parser => delimited(whitespaces0, matchString(s), whitespaces0) export const mapTo = (p: Parser, f: (p: I) => R): Parser => flow( p, map(([v, inp]) => [f(v), inp]) )