-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser-3.ts
449 lines (350 loc) · 10.4 KB
/
parser-3.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// Another improved system for parsing text. Slightly based on Arcsecond. #parser
export type ToArray<N extends number, T, A extends T[] = []> = number extends N
? T[]
: N extends A["length"]
? A
: ToArray<N, T, [...A, T]>
export type Transformer<T> = (match: string, ...groups: string[]) => T
export class Parser<T> {
constructor(readonly parse: <S>(result: Result<S>) => Result<T>) {}
chain<U>(fn: (result: Result<T>) => Result<U>): Parser<U> {
return new Parser<U>((result) => {
return fn(this.parse(result))
})
}
data<U>(data: U): Parser<U> {
return this.chain((result) => result.setData(data))
}
map<U>(mapper: (data: T) => U): Parser<U> {
return this.chain((result) => {
if (!result.ok) return result.fail()
return result.setData(mapper(result.data))
})
}
key<K extends keyof T>(key: K): Parser<T[K]> {
return this.map((data) => data[key])
}
keys<K extends (keyof T)[]>(...keys: K): Parser<{ [I in keyof K]: T[K[I]] }> {
return this.map((data) => keys.map((key) => data[key])) as any
}
pick<K extends (keyof T)[]>(
...keys: K
): Parser<{
[I in keyof K as K[I & number]]: T[K[I]]
}> {
return this.map((data) => {
const object: any = Object.create(null)
keys.forEach((key) => (object[key] = data[key]))
return object
})
}
or<U>(onError: Parser<U>): Parser<T | U> {
return this.chain<T | U>((result) => {
if (!result.ok) {
return onError.parse(result.succeed(result.index, undefined!))
}
return result
})
}
and<U>(onOk: Parser<U>): Parser<U> {
return this.chain<U>((result) => {
if (!result.ok) return result.fail()
return onOk.parse(result)
})
}
except(exception: Parser<unknown>): Parser<T> {
return new Parser((result) => {
if (!result.ok) return result.fail()
const output = this.parse(result)
if (!output.ok) return result.fail()
const next = exception.parse(result)
if (next.ok) return result.fail()
return output
})
}
}
export class Result<T> {
static of(source: string): Result<never> {
return Result.ok(source, 0, undefined!)
}
private static ok<T>(source: string, index: number, data: T): Result<T> {
return new Result<T>(source, index, true, data)
}
private static error(source: string, index: number): Result<never> {
return new Result<never>(source, index, false, undefined!)
}
private constructor(
readonly source: string,
readonly index: number,
readonly ok: boolean,
readonly data: T,
) {}
fail() {
return Result.error(this.source, this.index)
}
succeed<U>(nextIndex: number, data: U): Result<U> {
return Result.ok(this.source, nextIndex, data)
}
setData<U>(data: U): Result<U> {
if (!this.ok) return this.fail()
return this.succeed(this.index, data)
}
setIndex(index: number): Result<T> {
if (this.ok) {
return this.succeed(index, this.data)
} else {
return Result.error(this.source, index)
}
}
}
export const { of: init } = Result
export function data<T>(data: T): Parser<T> {
return new Parser<T>((result) => {
if (!result.ok) return result.fail()
return result.setData(data)
})
}
export function text(text: string): Parser<void>
export function text<T>(text: string, data: T): Parser<T>
export function text<T>(text: string, data?: T): Parser<T> {
return new Parser((result) => {
if (!result.ok) return result.fail()
const { index } = result
const end = index + text.length
if (result.source.slice(index, end) == text) {
return result.succeed<T>(end, data!)
} else {
return result.fail()
}
})
}
export function regex(pattern: RegExp): Parser<void>
export function regex<T>(pattern: RegExp, data: Transformer<T>): Parser<T>
export function regex<T>(pattern: RegExp, data?: Transformer<T>): Parser<T> {
if (!pattern.source.startsWith("^")) {
throw new SyntaxError("A matching pattern must have a ^ assertion.")
}
if (pattern.global) {
throw new SyntaxError("A matching pattern must not be global.")
}
if (pattern.multiline) {
throw new SyntaxError(
"A matching pattern must not be multiline. This interferes with the ^ assertion.",
)
}
return new Parser((result) => {
if (!result.ok) return result.fail()
const { index } = result
const slice = result.source.slice(index)
const match = slice.match(pattern)
if (match) {
return result.succeed<T>(
index + match[0]!.length,
data?.(...(match as [string, ...string[]]))!,
)
} else {
return result.fail()
}
})
}
export function char(): Parser<void>
export function char<T>(data: (character: string) => T): Parser<T>
export function char<T>(data?: (character: string) => T): Parser<T> {
return new Parser((result) => {
if (!result.ok) return result.fail()
const { source, index } = result
const character = source.slice(index, index + 1)
if (character.length == 1) {
return result.succeed(index + 1, data?.(character)!)
}
return result.fail()
})
}
export function optional<T>(parser: Parser<T>): Parser<T | undefined> {
return new Parser((result) => {
if (!result.ok) return result.fail()
const nextResult = parser.parse(result)
if (nextResult.ok) return nextResult
return result.succeed(result.index, undefined)
})
}
export function lookahead<T>(parser: Parser<T>): Parser<T> {
return new Parser((result) => {
return parser.parse(result).setIndex(result.index)
})
}
export function any<T extends readonly any[]>(
...parsers: { [K in keyof T]: Parser<T[K]> }
): Parser<T[number]> {
return new Parser<T[number]>((result: Result<unknown>) => {
if (!result.ok) return result.fail()
for (const parser of parsers) {
const next = parser.parse(result)
if (next.ok) return next
}
return result.fail()
})
}
export function sequence<T extends readonly any[]>(
...parsers: { [K in keyof T]: Parser<T[K]> }
): Parser<T> {
return new Parser<T>((result: Result<unknown>) => {
if (!result.ok) return result.fail()
const original = result
const data: any[] = []
for (const parser of parsers) {
result = parser.parse(result)
if (!result.ok) return original.fail()
data.push(result.data)
}
return result.setData(data as unknown as T)
})
}
export function many<T>(parser: Parser<T>): Parser<T[]> {
return new Parser<T[]>((result: Result<unknown>) => {
if (!result.ok) return result.fail()
const data: T[] = []
while (true) {
result = parser.parse(result)
if (!result.ok) {
return result.succeed(result.index, data)
}
data.push(result.data as T)
}
})
}
export function many1<T>(parser: Parser<T>): Parser<T[]> {
return new Parser<T[]>((result: Result<unknown>) => {
if (!result.ok) return result.fail()
const original = result
const data: T[] = []
while (true) {
result = parser.parse(result)
if (!result.ok) {
if (data.length < 1) {
return original.fail()
}
return result.succeed(result.index, data)
}
data.push(result.data as T)
}
})
}
export function sepBy<T>(
parser: Parser<T>,
separator: Parser<unknown>,
): Parser<T[]> {
return new Parser<T[]>((result: Result<unknown>) => {
if (!result.ok) {
return result.succeed(result.index, [])
}
let isFirst = true
const data: T[] = []
while (true) {
if (!isFirst) {
result = separator.parse(result)
if (!result.ok) {
return result.succeed(result.index, data)
}
}
result = parser.parse(result)
if (!result.ok) {
return result.succeed(result.index, data)
}
data.push(result.data as T)
isFirst = false
}
})
}
export function sepBy1<T>(
parser: Parser<T>,
separator: Parser<unknown>,
): Parser<T[]> {
return new Parser<T[]>((result: Result<unknown>) => {
if (!result.ok) {
return result.fail()
}
let isFirst = true
const data: T[] = []
const original = result
while (true) {
if (!isFirst) {
result = separator.parse(result)
if (!result.ok) {
if (data.length < 1) {
return original.fail()
}
return result.succeed(result.index, data)
}
}
result = parser.parse(result)
if (!result.ok) {
if (data.length < 1) {
return original.fail()
}
return result.succeed(result.index, data)
}
data.push(result.data as T)
isFirst = false
}
})
}
export function repeat<T, N extends number>(
parser: Parser<T>,
repeats: N,
): Parser<ToArray<N, T>>
export function repeat<T>(parser: Parser<T>, repeats: number): Parser<T[]> {
return new Parser<T[]>((result: Result<unknown>) => {
if (!result.ok) return result.fail()
const original = result
const data: T[] = []
for (let index = 0; index < repeats; index++) {
const temp = parser.parse(result)
if (!temp.ok) return original.fail()
data.push(temp.data)
result = temp
}
return result.setData(data)
})
}
export function maybe<T>(parser: Parser<T>): Parser<T | undefined> {
return any(parser, data(undefined))
}
export function coroutine<T = any, U = any>(
coroutine: () => Generator<Parser<U>, T, U>,
): Parser<T> {
return new Parser<T>((result: Result<unknown>) => {
const original = result
try {
const generator = coroutine()
let lastData: U
while (true) {
const { done, value } = result.ok
? generator.next(lastData!)
: generator.throw(
new Error("The last result had an error state.", {
cause: result,
}),
)
if (done) {
return result.succeed(result.index, value)
}
const temp = value.parse(result)
lastData = temp.data
result = temp
}
} catch (error) {
return original.fail()
}
})
}
export function deferred<T>(getter: () => Parser<T>) {
let value: Parser<T> | undefined
return new Parser<T>((result) => {
return (value ||= getter()).parse(result)
})
}
export const Whitespace = regex(/^\s+/, () => true)
export const OptionalWhitespace = regex(/^\s*/, (match) => match != "")
export const Digits = regex(/^\d+/, (match) => match)
export const Number = regex(/^\d+(?:\.\d+)?(?:e[+-]?\d+)?/, (match) => match)