-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparser-7.ts
More file actions
589 lines (509 loc) · 16.3 KB
/
parser-7.ts
File metadata and controls
589 lines (509 loc) · 16.3 KB
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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
// An (extremely) type safe system for parsing text. Works with `--noEmit`.
// #typesystem
// #region Error, Ok, ErrorState, OkState, State, IsStateGeneric,
// ok(), error(), initial()
export type Error<
Index extends number,
Source extends string,
Value extends string,
> = {
readonly index: Index
readonly ok: false
readonly source: Source
readonly value: Value
}
export type Ok<Index extends number, Source extends string, Value> = {
readonly index: Index
readonly ok: true
readonly source: Source
readonly value: Value
}
export type ErrorState = Error<number, string, string>
export type OkState = Ok<number, string, unknown>
export type State = ErrorState | OkState
export type IsStateGeneric<T extends State> =
string extends T["source"] ? true
: number extends T["index"] ? true
: false
export function ok<Previous extends State, Index extends number, Value>(
previous: Previous,
index: Index,
value: Value,
): ok<Previous, Index, Value> {
return {
index,
ok: true,
source: previous.source as Previous["source"],
value,
} as const satisfies State
}
export type ok<Previous extends State, Index extends number, Value> = {
readonly index: Index
readonly ok: true
readonly source: Previous["source"]
readonly value: Value
}
export function error<Previous extends State, Value extends string>(
previous: Previous,
value: Value,
): error<Previous, Value> {
return {
index: previous.index as Previous["index"],
ok: false,
source: previous.source as Previous["source"],
value,
} as const satisfies State
}
export type error<Previous extends State, Value extends string> = {
readonly index: Previous["index"]
readonly ok: false
readonly source: Previous["source"]
readonly value: Value
}
export function initial<Source extends string>(
source: Source,
): initial<Source> {
return {
index: 0,
ok: true,
source,
value: undefined,
} as const satisfies State
}
export type initial<Source extends string> = {
readonly index: 0
readonly ok: true
readonly source: Source
readonly value: undefined
}
// #endregion
// #region Expand, Parser, Parse, ValueOf
// For some odd reason, Expand<T> isn't always assignable to T, so we need to
// use Extract to make sure it always works. I just hope Extract won't violate
// the whole reason we use Expand.
type Expand<T> = Extract<
T extends infer O ? { [K in keyof O]: O[K] } : never,
T
>
export abstract class Parser {
declare readonly input: OkState
protected abstract t(state: this["input"]): State
p<state extends State>(state: state): Parse<this, state>
p<state extends State>(state: state): State {
if (state.ok) {
return this.t(state as OkState)
} else {
return state
}
}
parse<source extends string>(source: source) {
return this.p(initial(source))
}
}
export type Parse<parser extends Parser, state extends State> =
state extends OkState ?
Expand<
ReturnType<
// @ts-ignore
(parser & { readonly input: state })["t"]
>
>
: state extends ErrorState ? state
: never
export type ValueOf<parser extends Parser> = (Parse<parser, OkState> & {
ok: true
})["value"]
// #endregion
// text
{
class TextParser<text extends string> extends Parser {
constructor(readonly text: text) {
super()
}
t(state: this["input"]): String.startsWith<
(typeof state)["source"],
text,
(typeof state)["index"]
> extends infer S ?
S extends true ?
ok<
typeof state,
Number.add<(typeof state)["index"], String.length<text>>,
text
>
: error<typeof state, `Expected '${text}'.`>
: never {
if (state.source.startsWith(this.text, state.index)) {
return ok(
state,
state.index + this.text.length,
this.text,
) as any
} else {
return error(state, `Expected '${this.text}'.`) as any
}
}
}
var text = <Text extends string>(text: Text) => new TextParser(text)
}
// many
{
type ParseMany<
Matcher extends Parser,
State extends OkState,
Output extends any[],
> =
IsStateGeneric<State> extends true ?
ok<State, number, ValueOf<Matcher>[]>
: Parse<Matcher, State> extends infer S ?
S extends OkState ?
ParseMany<Matcher, S, [...Output, S["value"]]>
: ok<State, State["index"], Output>
: never
class ManyParser<matcher extends Parser> extends Parser {
constructor(readonly matcher: matcher) {
super()
}
protected t(state: this["input"]): ParseMany<matcher, typeof state, []>
protected t(state: this["input"]): State {
const output: any[] = []
let _state: OkState = state
while (true) {
const temp = this.matcher.p(_state)
if (!temp.ok) {
return ok(_state, _state.index, output)
}
output.push(temp.value)
_state = temp
}
}
}
var many = <Matcher extends Parser>(matcher: Matcher) =>
new ManyParser(matcher)
}
// optional
{
class OptionalParser<Matcher extends Parser> extends Parser {
constructor(readonly matcher: Matcher) {
super()
}
protected t(state: this["input"]): Parse<
Matcher,
typeof state
> extends infer S ?
S extends OkState ?
S
: ok<typeof state, (typeof state)["index"], undefined>
: never
protected t(state: this["input"]): State {
const next = this.matcher.p(state)
if (next.ok) {
return next
}
return ok(state, state.index, undefined)
}
}
var optional = <Matcher extends Parser>(matcher: Matcher) =>
new OptionalParser(matcher)
}
// seq
{
type ParseSequence<
Matchers extends readonly Parser[],
originalState extends OkState,
state extends OkState,
output extends any[],
> =
Matchers extends (
[
infer Matcher extends Parser,
...infer Rest extends readonly Parser[],
]
) ?
Parse<Matcher, state> extends infer S ?
S extends State ?
S extends OkState ?
ParseSequence<
Rest,
originalState,
S,
[...output, S["value"]]
>
: S extends ErrorState ? error<originalState, S["value"]>
: never
: never
: never
: ok<state, state["index"], output>
class SequenceParser<Matchers extends readonly Parser[]> extends Parser {
readonly matchers: Matchers
constructor(...matchers: Matchers) {
super()
this.matchers = matchers
}
protected t(
originalState: this["input"],
): ParseSequence<
Matchers,
typeof originalState,
typeof originalState,
[]
>
protected t(originalState: this["input"]): State {
const output: any[] = []
let state: OkState = originalState
for (const matcher of this.matchers) {
const next = matcher.p(state)
if (next.ok) {
output.push(next.value)
state = next
} else {
return error(originalState, next.value)
}
}
return ok(state, state.index, output)
}
}
var seq = <Matchers extends readonly Parser[]>(...matchers: Matchers) =>
new SequenceParser(...matchers)
}
// lookahead
{
class LookaheadParser<Matcher extends Parser> extends Parser {
constructor(readonly matcher: Matcher) {
super()
}
protected t(state: this["input"]): Parse<
Matcher,
typeof state
> extends infer next ?
next extends State ?
next extends OkState ?
ok<typeof state, (typeof state)["index"], next["value"]>
: next extends ErrorState ? error<typeof state, next["value"]>
: never
: never
: never
protected t(state: this["input"]): State {
const next = this.matcher.p(state)
if (next.ok) {
return ok(state, state.index, next.value)
} else {
return error(state, next.value)
}
}
}
var lookahead = <Matcher extends Parser>(matcher: Matcher) =>
new LookaheadParser(matcher)
}
// choice
{
type ParseChoice<
Matchers extends readonly Parser[],
state extends OkState,
> =
Matchers extends (
[
infer Matcher extends Parser,
...infer Rest extends readonly Parser[],
]
) ?
Parse<Matcher, state> extends infer S ?
S extends OkState ?
S
: ParseChoice<Rest, state>
: never
: error<state, "None of the matchers passed to 'choice' succeeded.">
class ChoiceParser<Matchers extends readonly Parser[]> extends Parser {
readonly matchers: Matchers
constructor(...matchers: Matchers) {
super()
this.matchers = matchers
}
protected t(state: this["input"]): ParseChoice<Matchers, typeof state>
protected t(state: this["input"]): State {
for (const matcher of this.matchers) {
const next = matcher.p(state)
if (next.ok) {
return next
}
}
return error(
state,
"None of the matchers passed to 'choice' succeeded.",
)
}
}
var choice = <Matchers extends readonly Parser[]>(...matchers: Matchers) =>
new ChoiceParser(...matchers)
}
// anyChar
{
class AnyCharacterParser extends Parser {
protected t(state: this["input"]): String.charAt<
(typeof state)["source"],
(typeof state)["index"]
> extends infer S ?
S extends string ?
S extends "" ?
error<typeof state, "Found EOF; expected character.">
: ok<typeof state, Number.plusOne<(typeof state)["index"]>, S>
: never
: never
protected t(state: this["input"]): State {
const char = state.source[state.index]
if (char) {
return ok(state, state.index + 1, char)
}
return error(state, "Found EOF; expected character.")
}
}
var anyChar = new AnyCharacterParser()
}
// char
{
class CharacterParser<characters extends string> extends Parser {
constructor(readonly characters: characters) {
super()
}
protected t(state: this["input"]): String.charAt<
(typeof state)["source"],
(typeof state)["index"]
> extends infer S ?
S extends string ?
S extends "" ?
error<typeof state, "Found EOF; expected character.">
: characters extends `${string}${S}${string}` ?
ok<typeof state, Number.plusOne<(typeof state)["index"]>, S>
: error<
typeof state,
`Found ${S}; expected one of '${characters}'.`
>
: never
: never
protected t(state: this["input"]): State {
const char = state.source.charAt(state.index)
if (char == "") {
return error(state, "Found EOF; expected character.")
}
if (this.characters.includes(char)) {
return ok(state, state.index + 1, char)
}
return error(
state,
`Found ${char}; expected one of '${this.characters}'.`,
)
}
}
var char = <Characters extends string>(characters: Characters) =>
new CharacterParser(characters)
}
// map
{
abstract class Mapped extends Parser {
protected abstract matcher: Parser
declare value: ValueOf<
// @ts-ignore
this["matcher"]
>
// @ts-ignore
protected abstract map(
value: // @ts-ignore
this["value"],
)
protected t(state: this["input"]): Parse<
// @ts-ignore
this["matcher"],
typeof state
> extends infer next ?
next extends OkState ?
ok<
next,
next["index"],
ReturnType<
// @ts-ignore
(this & { readonly value: next["value"] })["map"]
>
>
: next extends ErrorState ? next
: never
: never
protected t(state: this["input"]): State {
const next = this.matcher.p(state)
if (next.ok) {
return ok(next, next.index, this.map(next.value as any))
} else {
return next
}
}
}
_Mapped = Mapped
}
var _Mapped // assigned in block above
const Mapped = _Mapped
// many1
{
class Many1Parser<Matcher extends Parser> extends Parser {
seq: ReturnType<typeof seq<[Matcher, ReturnType<typeof many<Matcher>>]>>
constructor(matcher: Matcher) {
super()
this.seq = seq(matcher, many(matcher))
}
protected t(state: this["input"]): Parse<
this["seq"],
typeof state
> extends infer result ?
result extends ErrorState ? result
: result extends OkState ?
result["value"] extends (
[infer First, infer Many extends any[]]
) ?
ok<result, result["index"], [First, ...Many]>
: never
: never
: never
protected t(state: this["input"]): State {
const result = this.seq.p(state) as State
if (!result.ok) {
return result
}
return ok(result, result.index, [
(result.value as any)[0],
...(result.value as any)[1],
])
}
}
var many1 = <Matcher extends Parser>(matcher: Matcher) =>
new Many1Parser(matcher)
}
const hello = text("hello")
const manyHellos = many(hello)
const result = manyHellos.parse("hellohellogoodbyehello")
console.log(result)
// The object above is the type annotation of `result`. TypeScript knows that
// `result` contains those exact properties, in that exact order.
const hellosWithSpaces = seq(text("hello"), many(text(" hello")))
const result2 = hellosWithSpaces.parse("hello hello hello world")
console.log(result2)
// They match perfectly! The `readonly` annotation just tell TypeScript
// that we shouldn't modify the object.
// This is an error.
// result2.index = 23
// If I spread out the value, TypeScript will let me modify it.
const result3 = { ...result2 }
result3.index = 17
// But not to 23, because 23 != 17.
// Now it's happy.
// Final example: a basic arithmetic parser.
const digit = char("0123456789")
const number = many1(digit)
const addSubPart = seq(char("+-"), number)
const expression = seq(number, many(addSubPart))
// That should work.
// That means we went over the type system's limits.
// I'll try reducing the complexity.
// That didn't work.
// Let's try removing spaces.
// It worked!!!!
const result4 = expression.parse("23+45")
console.log(JSON.stringify(result4, null, 2))
// Time to double-check. And yup, they match.