-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser-2.ts
391 lines (331 loc) · 9.86 KB
/
parser-2.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
// An improved system for parsing text. #parser
export type Pattern = string | RegExp
export type Matcher<T, U> = (parser: Parser<T>) => Parser<U>
export class Parser<T = unknown> {
static of(source: string) {
return Parser.ok(source, 0, "")
}
private static ok(source: string, index: number): Parser<never>
private static ok<T>(source: string, index: number, data: T): Parser<T>
private static ok<T>(source: string, index: number, data?: T) {
return new Parser<T>(source, index, true, data)
}
private static error(source: string, index: number) {
return new Parser<never>(source, index, false)
}
private constructor(
private readonly source: string,
private readonly index: number,
private readonly ok: boolean,
readonly data: T = undefined!,
) {}
tap(fn: (data: T) => void): this {
if (this.ok) {
fn(this.data)
}
return this
}
map<U>(fn: (data: T) => U): Parser<U> {
if (!this.ok) {
return Parser.error(this.source, this.index)
}
return Parser.ok(this.source, this.index, fn(this.data))
}
match(matcher: Pattern): Parser<never>
match<U>(
matcher: Pattern,
map: (match: string, ...groups: string[]) => U,
): Parser<U>
match<U>(
matcher: Pattern,
map?: (match: string, ...groups: string[]) => U,
): Parser<U | undefined>
match<U>(
matcher: Pattern,
map?: (match: string, ...groups: string[]) => U,
): Parser<U> {
if (!this.ok) {
return Parser.error(this.source, this.index)
}
if (typeof matcher == "string") {
if (
this.source.slice(this.index, this.index + matcher.length) == matcher
) {
return Parser.ok<U>(
this.source,
this.index + matcher.length,
map?.(matcher)!,
)
} else {
return Parser.error(this.source, this.index)
}
} else if (matcher instanceof RegExp) {
if (!matcher.source.startsWith("^")) {
throw new SyntaxError(
"If a regular expression is used as a matcher, it must have a ^ assertion.",
)
}
let match = this.source.slice(this.index).match(matcher)
if (match) {
return Parser.ok<U>(
this.source,
this.index + match[0]!.length,
map?.(...(match as [string, ...string[]]))!,
)
} else {
return Parser.error(this.source, this.index)
}
}
throw new TypeError(
`A ${typeof matcher} was passed to .match(). Pass a string or regular expression.`,
)
}
static match(matcher: Pattern): (parser: Parser) => Parser<never>
static match<U>(
matcher: Pattern,
map: (match: string, ...groups: string[]) => U,
): (parser: Parser) => Parser<U>
static match<U>(
matcher: Pattern,
map?: (match: string, ...groups: string[]) => U,
): (parser: Parser) => Parser<U | undefined>
static match<U>(
matcher: Pattern,
map?: (match: string, ...groups: string[]) => U,
): (parser: Parser) => Parser<U | undefined> {
return (parser) => parser.match<U>(matcher, map)
}
chain<U = never>(matcher: Matcher<T, U>): Parser<U> {
if (!this.ok) {
return Parser.error(this.source, this.index)
}
if (typeof matcher == "function") {
return matcher(this)
}
throw new TypeError(
`A ${typeof matcher} was passed to .chain(). Pass a function instead.`,
)
}
thru(matcher: Matcher<T, unknown>): Parser<T> {
if (!this.ok) {
return Parser.error(this.source, this.index)
}
return this.chain(matcher).map(() => this.data)
}
lookahead<U = never>(
matcher: Matcher<T, U>,
map?: (match: string, ...groups: string[]) => U,
): Parser<U> {
if (!this.ok) {
return Parser.error(this.source, this.index)
}
const result = this.chain<U>(matcher)
if (!result.ok) {
return Parser.error(this.source, this.index)
}
return Parser.ok(this.source, this.index, result.data)
}
or<U>(fn: () => Parser<U>): Parser<T | U> {
if (this.ok) {
return this
} else {
return fn()
}
}
unwrap(error: string) {
if (this.ok) {
return this.data
} else {
throw new TypeError(`Expected ${error || "a successful Parser"}.`)
}
}
unwrapOr(value: T) {
if (this.ok) {
return this.data
} else {
return value
}
}
discriminate<U>(matchers: Record<string, Matcher<T, U>>): Parser<U> {
if (!this.ok) {
return Parser.error(this.source, this.index)
}
for (const key in matchers) {
if (this.source.slice(this.index, this.index + key.length) == key) {
return this.chain<U>(matchers[key]!)
}
}
return Parser.error(this.source, this.index)
}
static discriminate<U>(
matchers: Record<string, Matcher<unknown, U>>,
): <T>(parser: Parser<T>) => Parser<U> {
return (parser) => parser.discriminate(matchers)
}
any<U extends readonly any[]>(
...matchers: { [K in keyof U]: Matcher<T, U[K]> }
): Parser<U[number]> {
for (const matcher of matchers) {
const result: Parser<U[number]> = this.chain<U[number]>(matcher)
if (result.ok) {
return result
}
}
return Parser.error(this.source, this.index)
}
static any<U extends readonly U[]>(
...matchers: { [K in keyof U]: Matcher<unknown, U> }
): <T>(parser: Parser<T>) => Parser<U> {
return (parser) => parser.any(...matchers)
}
sequence<U extends readonly any[]>(
...matchers: { [K in keyof U]: Matcher<unknown, U[K]> }
): Parser<U> {
let result: Parser<unknown> = this
let data: any[] = []
for (const matcher of matchers) {
result = result.chain<unknown>(matcher)
data.push(result.data)
}
return result.map(() => data as any as U)
}
static sequence<U extends readonly any[]>(
...matchers: { [K in keyof U]: Matcher<unknown, U[K]> }
): <T>(parser: Parser<T>) => Parser<U> {
return (parser) => parser.sequence<U>(...matchers)
}
optionalWhitespace() {
return this.match(/^\s*/, () => this.data)
}
static optionalWhitespace<T>(parser: Parser<T>) {
return parser.optionalWhitespace()
}
whitespace() {
return this.match(/^\s+/, () => this.data)
}
static whitespace<T>(parser: Parser<T>) {
return parser.whitespace()
}
many<U>(matcher: Matcher<unknown, U>): Parser<U[]> {
let result: Parser<unknown> = this
let data: U[] = []
while (true) {
if (!result.ok) {
return Parser.ok(this.source, this.index, data)
}
result = result.chain<U>(matcher).tap((item) => data.push(item))
}
}
static many<U>(
matcher: Matcher<unknown, U>,
): (parser: Parser<unknown>) => Parser<U[]> {
return (parser) => parser.many(matcher)
}
many1<U>(matcher: Matcher<unknown, U>): Parser<U[]> {
let result: Parser<unknown> = this
let data: U[] = []
while (true) {
if (!result.ok) {
if (data.length < 1) {
return Parser.error(this.source, this.index)
}
return Parser.ok(this.source, this.index, data)
}
result = result.chain<U>(matcher).tap((item) => data.push(item))
}
}
static many1<U>(
matcher: Matcher<unknown, U>,
): (parser: Parser<unknown>) => Parser<U[]> {
return (parser) => parser.many1(matcher)
}
}
const matchers = {
expr(parser: Parser): Parser<string> {
return parser.discriminate({
"#": matchers.number,
"+": matchers.add,
"-": matchers.subtract,
"*": matchers.multiply,
"/": matchers.divide,
"&": matchers.and,
"|": matchers.or,
"?": matchers.conditional,
":": matchers.list,
";": matchers.list,
})
},
number(parser: Parser): Parser<string> {
return parser
.match("#")
.optionalWhitespace()
.match(/^\d+(\.\d+)?(\.e[+-]?\d+)?/, (match) => match)
},
add(parser: Parser): Parser<string> {
return parser
.match("+")
.optionalWhitespace()
.sequence(matchers.expr, Parser.optionalWhitespace, matchers.expr)
.map(([first, _, second]) => `(${first} + ${second})`)
},
subtract(parser: Parser): Parser<string> {
return parser
.match("-")
.optionalWhitespace()
.sequence(matchers.expr, Parser.optionalWhitespace, matchers.expr)
.map(([first, _, second]) => `(${first} - ${second})`)
},
multiply(parser: Parser): Parser<string> {
return parser
.match("*")
.optionalWhitespace()
.sequence(matchers.expr, Parser.optionalWhitespace, matchers.expr)
.map(([first, _, second]) => `(${first} * ${second})`)
},
divide(parser: Parser): Parser<string> {
return parser
.match("/")
.optionalWhitespace()
.sequence(matchers.expr, Parser.optionalWhitespace, matchers.expr)
.map(([first, _, second]) => `(${first} / ${second})`)
},
and(parser: Parser): Parser<string> {
return parser
.match("&")
.optionalWhitespace()
.sequence(matchers.expr, Parser.optionalWhitespace, matchers.expr)
.map(([first, _, second]) => `(${first} && ${second})`)
},
or(parser: Parser): Parser<string> {
return parser
.match("|")
.optionalWhitespace()
.sequence(matchers.expr, Parser.optionalWhitespace, matchers.expr)
.map(([first, _, second]) => `(${first} || ${second})`)
},
conditional(parser: Parser): Parser<string> {
return parser
.match("?")
.optionalWhitespace()
.sequence(
matchers.expr,
Parser.optionalWhitespace,
matchers.expr,
Parser.optionalWhitespace,
matchers.expr,
)
.map(
([condition, _, ifTrue, _1, ifFalse]) =>
`(${condition} ? ${ifTrue} : ${ifFalse})`,
)
},
list(parser: Parser): Parser<string> {
return parser
.many(Parser.sequence(Parser.match(":"), matchers.expr))
.map((items) => items.map((e) => e[1]).join(", "))
.map((list) => `[${list}]`)
.match(";")
},
}
const parser = Parser.of(":#9:#8;")
const result = matchers.expr(parser)