diff options
| author | Akshay Nair <phenax5@gmail.com> | 2022-01-14 21:15:19 +0530 |
|---|---|---|
| committer | Akshay Nair <phenax5@gmail.com> | 2022-01-14 21:15:19 +0530 |
| commit | 3b0e7428441f85de5e76a59abbb09931bcf2387b (patch) | |
| tree | 093b71f4ec86c77ca9741526499e119cad38387f | |
| parent | 920038de1945298e5a693cc11fd97a73e48b9bc8 (diff) | |
| download | elxr-3b0e7428441f85de5e76a59abbb09931bcf2387b.tar.gz elxr-3b0e7428441f85de5e76a59abbb09931bcf2387b.zip | |
feat: implements manyTill parser combinator
| -rw-r--r-- | src/parser/utils.ts | 15 | ||||
| -rw-r--r-- | tests/parser.spec.ts | 9 |
2 files changed, 23 insertions, 1 deletions
diff --git a/src/parser/utils.ts b/src/parser/utils.ts index 4b68aff..4e2c9d6 100644 --- a/src/parser/utils.ts +++ b/src/parser/utils.ts @@ -3,7 +3,7 @@ import * as Either from 'fp-ts/Either' import * as Option from 'fp-ts/Option' import { fst, mapFst, mapSnd, snd } from 'fp-ts/Tuple' import { eq } from '../utils' -import { prepend } from 'fp-ts/Array' +import { flatten, prepend } from 'fp-ts/Array' export type char = string @@ -29,6 +29,19 @@ export const sepBy1 = <T>(sep: Parser<any>, parser: Parser<T>): Parser<T[]> => ), ) +export const not = (parser: Parser<any>): Parser<null> => (input: string) => + pipe( + input, + parser, + Either.fold( + ([_left, inp]) => Either.right([null, inp]), + ([_right, inp]) => Either.left(['`not` parser failed. Match found', inp]) + ), + ) + +export const manyTill = <T>(parser: Parser<T>, end: Parser<any>): Parser<T[]> => + mapTo(pair(many0(suffixed(parser, not(end))), parser), ([xs, l]) => xs.concat([l])) + export const many0 = <T>(parser: Parser<T>): Parser<Array<T>> => flow( parser, diff --git a/tests/parser.spec.ts b/tests/parser.spec.ts index 0abb1a0..0506be0 100644 --- a/tests/parser.spec.ts +++ b/tests/parser.spec.ts @@ -4,10 +4,17 @@ import { whitespace, whitespaces0, delimited, + not, + symbol, + satifyChar, + matchChar, + manyTill, + pair, } from '../src/parser/utils' import { parser } from '../src/parser' import { none, some } from 'fp-ts/Option' import { Expr, Literal } from '../src/types' +import {jlog} from '../src/utils' const wrap = (e: Expr) => right([[none, e, none], '']) const grouped = (l: Expr[]) => wrap(Expr.Group({ exprs: l })) @@ -16,6 +23,8 @@ const groupedAlt = (l: Expr[]) => wrap(Expr.Or({ exprs: l })) describe('Parser', () => { it('should do shit', () => { // jlog(parser(/ -2.05|\n2|true|\s|\T /.source)) + //const p = pair(symbol('a'), symbol('b')) + //jlog(manyTill(p, matchChar('!'))('ab ab ab ab! nice nice')) }) it('should do shit', () => { |
