-
Notifications
You must be signed in to change notification settings - Fork 0
/
combinator.ts
176 lines (160 loc) · 5.21 KB
/
combinator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import { MAX_INT32, clamp } from "emnorst";
import { type Parsed, Parser, type SourceOf } from "./parser";
import { type ParseState, updateState } from "./state";
/**
* Defers variable references until the parser runs.
*/
export const lazy = <T, S>(getParser: () => Parser<T, S>): Parser<T, S> => {
const lazyParser: Parser<T, S> = new Parser((state, context) => {
// @ts-expect-error readonly
return (lazyParser.run = getParser().run)(state, context);
});
return lazyParser;
};
/**
* Succeeds if the given parser fails, without consuming input.
*/
export const notFollowedBy = <S>(parser: Parser<unknown, S>): Parser<unknown, S> =>
new Parser((state, context) => {
const newState = parser.run(state, context);
if (newState == null) {
return state;
}
context.addError(state.i);
return null;
});
/**
* Applies the given parser without consuming input.
*/
export const lookAhead = <T, S = unknown>(parser: Parser<T, S>): Parser<T, S> =>
new Parser((state, context) => {
const newState = parser.run(state, context);
return newState && updateState(state, newState.v);
});
type Seq<out T extends readonly Parser[]> = {
[K in keyof T]: Parsed<T[K]>;
};
/**
* @example
* ```ts
* const parser = seq([el("a"), anyEl()]);
* parseA(parser, "ab"); // => ["a", "b"]
* parseA(parser, "a1"); // => ["a", "1"]
* parseA(parser, "a"); // parse error
* ```
*/
export const seq: {
<T extends readonly Parser[] | []>(
parsers: T,
options?: { allowPartial?: false },
): Parser<Seq<T>, SourceOf<T[number]>>;
<T extends readonly Parser[] | []>(
parsers: T,
options: { allowPartial: boolean },
): Parser<Partial<Seq<T>>, SourceOf<T[number]>>;
} = (parsers, options) =>
new Parser((state, context) => {
const values: unknown[] = [];
for (const parser of parsers) {
const newState = parser.run(state, context as never);
if (newState == null) {
if (options?.allowPartial) break;
return null;
}
values.push((state = newState).v);
}
return updateState(state, values);
});
type Choice<T extends readonly Parser[]> = Parser<Parsed<T[number]>, SourceOf<T[number]>>;
/**
* @example
* ```ts
* const parser = choice([el("a"), el("b")]);
* parseA(parser, "a"); // => "a"
* parseA(parser, "b"); // => "b"
* parseA(parser, "c"); // parse error
* ```
*/
export const choice = <T extends readonly Parser[] | []>(parsers: T): Choice<T> =>
new Parser((state, context) => {
for (const parser of parsers) {
const newState = parser.run(state, context as never);
if (newState != null) {
return newState as ParseState<Parsed<T[number]>>;
}
}
return null;
});
/**
* @example
* ```ts
* const parser = many(anyEl());
* parseA(parser, "ab"); // => ["a", "b"]
* ```
* @example
* ```ts
* const parser = many(anyEl(), { min: 1 });
* parseA(parser, ""); // parse error
* parseA(parser, "a"); // => ["a"]
* ```
*/
export const many = <T, S>(
parser: Parser<T, S>,
options?: { min?: number; max?: number },
): Parser<T[], S> => {
const min = clamp(options?.min || 0, 0, MAX_INT32) | 0;
const max = clamp(options?.max || MAX_INT32, min, MAX_INT32) | 0;
return new Parser((state, context) => {
const result: T[] = [];
while (result.length < max) {
const newState = parser.run(state, context);
if (newState == null || !(state.i < newState.i)) break;
result.push((state = newState).v);
}
return result.length < min ? null : updateState(state, result);
});
};
/**
* To require the trailing {@link separator}, use {@link many} with `parser.skip(separator)`.
*
* @example
* ```ts
* const parser = sepBy(anyEl(), el(","), { min: 1 });
* parseA(parser, ""); // parse error
* parseA(parser, "a"); // => ["a"]
* parseA(parser, "a,b"); // => ["a", "b"]
* ```
* @example
* ```ts
* const parser = sepBy(anyEl(), el(","), { trailing: "allow" });
* parseA(parser, ""); // => []
* parseA(parser, "a"); // => ["a"]
* parseA(parser, "a,b,"); // => ["a", "b"]
* ```
*/
export const sepBy = <T, S>(
parser: Parser<T, S>,
separator: Parser<unknown, S>,
options?: { min?: number; max?: number; trailing?: "none" | "allow" },
): Parser<T[], S> => {
const min = clamp(options?.min || 0, 0, MAX_INT32) | 0;
const max = clamp(options?.max || MAX_INT32, min, MAX_INT32) | 0;
return new Parser((state, context) => {
const result: T[] = [];
let lastState = state;
while (result.length < max) {
const start = state.i;
const newStateA = parser.run(state, context);
if (newStateA == null) break;
result.push((lastState = state = newStateA).v);
const newStateB = separator.run(newStateA, context);
if (newStateB == null) break;
state = newStateB;
if (!(start < state.i)) break;
}
if (options?.trailing === "allow") {
lastState = state;
}
return result.length < min ? null : updateState(lastState, result);
});
};