-
Notifications
You must be signed in to change notification settings - Fork 2
/
lambda.ts
1037 lines (914 loc) · 27.8 KB
/
lambda.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
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// A lambda calculus parser that runs at compile time and runtime. #typesystem
export function parse<T extends string>(
text: T,
): parse.ToNode<parse.ToTree<parse.Lex<parse.PreLex<T>>>> {
return parse.toNode(parse.toTree(parse.lex(parse.preLex(text))))
}
export namespace parse {
type ReplaceLambdaWithBackslash<
T extends string,
H extends string = "",
> = T extends `${infer A}λ${infer B}`
? ReplaceLambdaWithBackslash<B, `${H}${A}\\`>
: `${H}${T}`
type RemoveComments<T extends string, H extends string = ""> = T extends
| `${infer A}#${string}\n${infer B}`
| `${infer A}#${string}\r${infer B}`
? RemoveComments<B, `${H}${A}`>
: T extends `${infer A}#${string}`
? A
: `${H}${T}`
type FindAndRemoveAliases<
T extends string,
A extends [name: string, body: string][] = [],
> = T extends `${infer Name}=${infer Body};${infer Rest}`
? FindAndRemoveAliases<Rest, [...A, [Name, Body]]>
: [T, A]
type PutBackAliases<
T extends string,
A extends [name: string, body: string][],
> = A extends [
[infer Name extends string, infer Body extends string],
...infer Rest extends [name: string, body: string][],
]
? PutBackAliases<`(\\${Name} ${T})(${Body})`, Rest>
: T
export type PreLex<T extends string> = FindAndRemoveAliases<
RemoveComments<ReplaceLambdaWithBackslash<T>>
> extends [
infer T extends string,
infer A extends [name: string, body: string][],
]
? PutBackAliases<T, A>
: never
/**
* - Changes `λ` to `\`
* - Removes `#`-style comments
* - Replaces aliases (`name = body;`) with lambda expressions
*/
export function preLex<T extends string>(text: T): PreLex<T>
export function preLex(text: string): string {
const aliases: (readonly [name: string, body: string])[] = []
text = text
.replace(/λ/g, "\\")
.replace(/#[^\n\r]*$/gm, "")
.replace(/([^\s=.\\λ();]+)\s*=\s*([^=;]+);/g, (_, name, body) => {
aliases.push([name, body])
return ""
})
for (const [name, body] of aliases) {
text = `(\\${name} ${text})(${body})`
}
return text
}
export type Token =
| { readonly type: "name"; readonly name: string }
| { readonly type: "backslash"; readonly name: string }
| { readonly type: "lParen" }
| { readonly type: "rParen" }
const whitespace = /^\s/
type MergeNameIntoBackslash<
N extends string,
R extends readonly Token[],
> = N extends ""
? R
: R extends readonly [
...infer Body extends readonly Token[],
{ readonly type: "backslash"; readonly name: "" },
]
? readonly [...Body, { readonly type: "backslash"; readonly name: N }]
: readonly [...R, { readonly type: "name"; readonly name: N }]
type Split<
T extends string,
R extends readonly {
readonly type: "backslash"
readonly name: string
}[] = readonly [],
> = T extends `${infer Head}${infer Tail}`
? Split<
Tail,
readonly [...R, { readonly type: "backslash"; readonly name: Head }]
>
: R
export type Lex<
T extends string,
N extends string = "",
R extends readonly Token[] = readonly [],
> = T extends ` ${infer Rest}` | `\n${infer Rest}` | `\r${infer Rest}`
? Lex<Rest, "", MergeNameIntoBackslash<N, R>>
: T extends `\\${infer Rest}`
? Lex<
Rest,
"",
readonly [
...MergeNameIntoBackslash<N, R>,
{ readonly type: "backslash"; readonly name: "" },
]
>
: T extends `(${infer Rest}`
? Lex<
Rest,
"",
readonly [...MergeNameIntoBackslash<N, R>, { readonly type: "lParen" }]
>
: T extends `)${infer Rest}`
? Lex<
Rest,
"",
readonly [...MergeNameIntoBackslash<N, R>, { readonly type: "rParen" }]
>
: T extends `.${infer Rest}`
? MergeNameIntoBackslash<N, R> extends readonly [
...infer Head extends readonly Token[],
{
readonly type: "backslash"
readonly name: infer Name extends string
},
]
? Lex<Rest, "", readonly [...Head, ...Split<Name>]>
: never
: T extends `${infer Char}${infer Rest}`
? Lex<Rest, `${N}${Char}`, R>
: MergeNameIntoBackslash<N, R>
export namespace Lex {
export type Debug<
T extends readonly Token[],
S extends string = "",
> = T extends readonly [
infer Head extends Token,
...infer Rest extends readonly Token[],
]
? Debug<
Rest,
`${S} ${Head extends { readonly type: "lParen" }
? "("
: Head extends { readonly type: "rParen" }
? ")"
: Head extends {
readonly type: "name"
readonly name: infer Name extends string
}
? Name
: Head extends {
readonly type: "backslash"
readonly name: infer Name extends string
}
? `\\${Name}`
: ""}`
>
: S
}
export function lex<T extends string>(text: T): Lex<T>
export function lex(text: string): readonly Token[] {
const output: Token[] = []
const { length } = text
let index = 0
let name = ""
while (index < length) {
const char = text[index]
if (!char) {
break
}
if (
char.match(whitespace) ||
char == "\\" ||
char == "(" ||
char == ")" ||
char == "."
) {
const previous = output[output.length - 1]
if (name) {
if (previous?.type == "backslash" && previous.name == "") {
;(previous as any).name = name
} else {
output.push({ type: "name", name })
}
name = ""
}
if (
(char == "\\" || char == "(" || char == ")") &&
previous?.type == "backslash" &&
(previous.name == "" || char == ")")
) {
throw new Error("Found unexpected " + char + " after backslash.")
}
if (char == "\\") {
output.push({ type: "backslash", name: "" })
}
if (char == "(" || char == ")") {
output.push({ type: char == "(" ? "lParen" : "rParen" })
}
if (char == ".") {
const last = output.pop()
if (last?.type != "backslash") {
throw new Error(
"A '.' token can only be parsed directly after a backslash.",
)
}
for (const character of last.name) {
output.push({ type: "backslash", name: character })
}
}
} else {
name += char
}
index++
}
if (name) {
const previous = output[output.length - 1]
if (previous?.type == "backslash" && previous.name == "") {
;(previous as any).name = name
} else {
output.push({ type: "name", name })
}
name = ""
}
return output
}
export type Tree =
| { readonly type: "name"; readonly name: string }
| {
readonly type: "lambda"
readonly name: string
readonly body: readonly Tree[]
}
| readonly Tree[]
export namespace Tree {
type ToArray<
T extends readonly Tree[],
S extends string = "",
> = T extends readonly [
infer Head extends Tree,
...infer Tail extends readonly Tree[],
]
? S extends ""
? ToArray<Tail, Debug<Head>>
: ToArray<Tail, `${S}, ${Debug<Head>}`>
: `[${S}]`
export type Debug<T extends Tree> = T extends {
readonly type: "name"
readonly name: infer Name extends string
}
? `{ "type": "name", "name": "${Name}" }`
: T extends {
readonly type: "lambda"
readonly name: infer Name extends string
readonly body: infer Body extends readonly Tree[]
}
? `{ "type": "lambda", "name": "${Name}", "body": ${ToArray<Body>} }`
: T extends readonly Tree[]
? ToArray<T>
: never
}
type FlatTree =
| Tree
| { readonly type: "backslash"; readonly name: string }
| "paren"
type Fold<
T extends readonly FlatTree[],
I extends readonly Tree[] = readonly [],
> = T extends readonly [
...infer Head extends readonly FlatTree[],
infer Tail extends FlatTree,
]
? Tail extends "paren"
? readonly [...Head, I]
: Tail extends {
readonly type: "backslash"
readonly name: infer Name extends string
}
? Fold<
[
...Head,
{ readonly type: "lambda"; readonly name: Name; readonly body: I },
]
>
: Tail extends Tree
? Fold<Head, readonly [Tail, ...I]>
: never
: I
function fold<T extends readonly FlatTree[]>(tree: T): Fold<T>
function fold(
tree: readonly FlatTree[],
): readonly [...(readonly FlatTree[]), Tree] | readonly Tree[] {
const inserted: Tree[] = []
for (let index = tree.length - 1; index >= 0; index--) {
const head = tree.slice(0, index)
const tail = tree[index]
if (!tail) {
return inserted
}
if (tail === "paren") {
return head.concat(inserted) as [...typeof head, typeof inserted]
}
if ("type" in tail && tail.type === "backslash") {
return fold(
head.concat({ type: "lambda", name: tail.name, body: inserted }),
)
}
inserted.unshift(tail)
}
return inserted
}
type ToFlatTree<
T extends readonly Token[],
O extends readonly FlatTree[] = readonly [],
> = T extends readonly [
infer Head extends Token,
...infer Tail extends readonly Token[],
]
? Head extends { readonly type: "lParen" }
? ToFlatTree<Tail, readonly [...O, "paren"]>
: Head extends { readonly type: "rParen" }
? ToFlatTree<Tail, Fold<O>>
: Head extends { readonly type: "backslash"; readonly name: string }
? ToFlatTree<Tail, readonly [...O, Head]>
: Head extends { readonly type: "name"; readonly name: string }
? ToFlatTree<Tail, readonly [...O, Head]>
: never
: O
function toFlatTree<T extends readonly Token[]>(tokens: T): ToFlatTree<T>
function toFlatTree(tokens: readonly Token[]): readonly FlatTree[] {
let output: FlatTree[] = []
for (const token of tokens) {
if (token.type == "lParen") {
output.push("paren")
} else if (token.type == "rParen") {
output = fold(output) as unknown as FlatTree[]
} else {
output.push(token)
}
}
return output
}
// prettier-ignore
// esbuild can't handle "extends infer U extends Tree"
export type ToTree<T extends readonly Token[]> = Fold<
ToFlatTree<T>
> extends (infer U extends Tree)
? U
: never
export function toTree<T extends readonly Token[]>(tokens: T): ToTree<T>
export function toTree(tokens: readonly Token[]): readonly Tree[] {
return fold(toFlatTree(tokens) as readonly FlatTree[]) as readonly Tree[]
}
export namespace toTree {
function indent(text: string) {
return text.replace(/\n/g, "\n ")
}
export function debug(tree: Tree): string {
if (Array.isArray(tree)) {
return "(\n " + indent(tree.map(debug).join("\n")) + "\n)"
}
if (tree.type == "name") {
return "name " + tree.name
}
if (tree.type == "lambda") {
return "lambda " + tree.name + "\n " + indent(debug(tree.body))
}
throw new Error("Encountered unexpected tree type: " + tree)
}
}
type ArrayToNodeWithInitial<
A extends readonly Tree[],
S extends Node.Node,
> = A extends readonly [
infer Head extends Tree,
...infer Tail extends readonly Tree[],
]
? // @ts-ignore
ArrayToNodeWithInitial<Tail, Node.Application<S, ToNode<Head>>>
: S
type ArrayToNode<A extends readonly Tree[]> = A extends readonly [
infer Head extends Tree,
...infer Tail extends readonly Tree[],
]
? ArrayToNodeWithInitial<Tail, ToNode<Head>>
: never
export type ToNode<T extends Tree> = T extends {
readonly type: "name"
readonly name: infer Name extends string
}
? Node.Name<Name>
: T extends {
readonly type: "lambda"
readonly name: infer Name extends string
readonly body: infer Body extends readonly Tree[]
}
? Node.Lambda<Name, ArrayToNode<Body>>
: T extends readonly Tree[]
? ArrayToNode<T>
: never
export function toNode<T extends Tree>(tree: T): ToNode<T>
export function toNode(tree: Tree): Node.Node {
if (Array.isArray(tree)) {
if (!tree[0]) {
throw new Error("Found ) directly after (.")
}
// @ts-ignore
let output: Node.Node = toNode(tree[0])
for (let index = 1; index < tree.length; index++) {
output = new Node.Application(output, toNode(tree[index]!))
}
return output
}
if (tree.type == "lambda") {
return new Node.Lambda(tree.name, toNode(tree.body))
}
if (tree.type == "name") {
return new Node.Name(tree.name)
}
throw new Error("Received unknown node type: ", { cause: tree })
}
}
export namespace Node {
export interface PartialString {
readonly content: string
readonly endsWithLambda: boolean
readonly hasTopLevelApplication: boolean
readonly startsWithDottedLambda: boolean
}
type Equal<A, B> = A extends B ? (B extends A ? true : false) : false
export type Rename<
T extends Node,
Old extends string,
New extends string,
> = T extends Name<infer U>
? Equal<U, Old> extends true
? Name<New>
: Name<U>
: T extends Application<infer L, infer R>
? // @ts-ignore
Application<Rename<L, Old, New>, Rename<R, Old, New>>
: T extends Lambda<infer N extends string, infer B extends Node>
? Equal<N, Old> extends true
? Lambda<N, B>
: Lambda<N, Rename<B, Old, New>>
: never
export type Includes<
T extends readonly string[],
U extends string,
> = T extends readonly [U, ...any]
? true
: T extends readonly [any, ...infer Rest extends readonly string[]]
? Includes<Rest, U>
: false
export type UniqueName<Avoid extends readonly string[]> = Includes<
Avoid,
"a"
> extends false
? "a"
: Includes<Avoid, "b"> extends false
? "b"
: Includes<Avoid, "c"> extends false
? "c"
: Includes<Avoid, "d"> extends false
? "d"
: Includes<Avoid, "e"> extends false
? "e"
: Includes<Avoid, "f"> extends false
? "f"
: Includes<Avoid, "g"> extends false
? "g"
: Includes<Avoid, "h"> extends false
? "h"
: Includes<Avoid, "i"> extends false
? "i"
: Includes<Avoid, "j"> extends false
? "j"
: Includes<Avoid, "k"> extends false
? "k"
: Includes<Avoid, "l"> extends false
? "l"
: Includes<Avoid, "m"> extends false
? "m"
: Includes<Avoid, "n"> extends false
? "n"
: Includes<Avoid, "o"> extends false
? "o"
: Includes<Avoid, "p"> extends false
? "p"
: Includes<Avoid, "q"> extends false
? "q"
: Includes<Avoid, "r"> extends false
? "r"
: Includes<Avoid, "s"> extends false
? "s"
: Includes<Avoid, "t"> extends false
? "t"
: Includes<Avoid, "u"> extends false
? "u"
: Includes<Avoid, "v"> extends false
? "v"
: Includes<Avoid, "w"> extends false
? "w"
: Includes<Avoid, "x"> extends false
? "x"
: Includes<Avoid, "y"> extends false
? "y"
: Includes<Avoid, "z"> extends false
? "z"
: // @ts-ignore
UniqueNameX<[0], Avoid>
// @ts-ignore
export type UniqueNameX<
X extends readonly any[],
Avoid extends readonly string[],
> = Includes<Avoid, `x${X["length"]}`> extends false
? `x${X["length"]}`
: // @ts-ignore
UniqueNameX<[...X, 0], Avoid>
export type Replace<
T extends Node,
Old extends string,
New extends Node,
> = T extends Name<infer U>
? Equal<U, Old> extends true
? New
: Name<U>
: T extends Application<infer L, infer R>
? // @ts-ignore
Application<Replace<L, Old, New>, Replace<R, Old, New>>
: T extends Lambda<infer U, infer B>
? Equal<U, Old> extends true
? Lambda<U, B>
: IsFree<New, U> extends true
? // @ts-ignore
Lambda<
// @ts-ignore
UniqueName<readonly [T["name"], ...T["locals"], ...New["locals"]]>,
Replace<
B,
Old,
Rename<
New,
U,
UniqueName<readonly [T["name"], ...T["locals"], ...New["locals"]]>
>
>
>
: Lambda<U, Replace<B, Old, New>>
: never
export type IsFree<T extends Node, N extends string> = T extends Name<infer U>
? Equal<N, U>
: T extends Application<infer L extends Node, infer R extends Node>
? IsFree<L, N> extends true
? true
: IsFree<R, N> extends true
? true
: false
: T extends Lambda<infer U extends string, infer B extends Node>
? Equal<N, U> extends true
? false
: IsFree<B, N>
: never
export abstract class Node {
abstract readonly canEval: boolean
abstract readonly locals: readonly string[]
abstract rename(oldName: string, newName: Name<string>): Node
abstract replace(oldName: string, newNode: Node): Node
abstract toCompactString(): PartialString
abstract toPartialString(): PartialString & {
readonly startsWithDottedLambda: false
}
toString(compact: true): ReturnType<this["toCompactString"]>["content"]
toString(compact: false): ReturnType<this["toPartialString"]>["content"]
toString(compact: boolean): string {
return compact
? this.toCompactString().content
: this.toPartialString().content
}
}
// @ts-ignore Technically, `out T` is the wrong variance, but I don't really care.
export class Name<out T extends string> extends Node {
static unique(avoid: readonly string[]): Name<string> {
for (const char of "abcdefghijklmnopqrstuvwxyz") {
if (!avoid.includes(char)) {
return new Name(char)
}
}
for (let i = 1; ; i++) {
if (!avoid.includes(`x${i}`)) {
return new Name(`x${i}`)
}
}
}
readonly canEval: false = false
readonly locals: readonly [T]
constructor(readonly name: T) {
super()
this.locals = [name]
}
rename<Old extends string, New extends string>(
oldName: Old,
newName: Name<New>,
): Rename<this, Old, New>
rename(oldName: string, newName: Name<string>): Name<string> {
if (oldName == this.name) {
return newName
}
// @ts-ignore
return this
}
replace<O extends string, N extends Node>(
oldName: O,
newNode: N,
): Equal<O, T> extends true ? N : this
replace(oldName: string, newNode: Node): Node {
if (oldName == this.name) {
return newNode
}
// @ts-ignore
return this
}
// #region toString
toCompactString(): {
readonly content: T
readonly endsWithLambda: false
readonly hasTopLevelApplication: false
readonly startsWithDottedLambda: false
} {
return {
content: this.name,
endsWithLambda: false,
hasTopLevelApplication: false,
startsWithDottedLambda: false,
}
}
toPartialString(): {
readonly content: T
readonly endsWithLambda: false
readonly hasTopLevelApplication: false
readonly startsWithDottedLambda: false
} {
return {
content: this.name,
endsWithLambda: false,
hasTopLevelApplication: false,
startsWithDottedLambda: false,
}
}
// #endregion
}
type IsSingleCharacter<T extends string> = T extends `${string}${infer U}`
? U extends ""
? true
: false
: false
type SkipFirstCharacter<T extends string> = T extends `${string}${infer U}`
? U
: ""
type ExcludeFromArray<
T extends string,
A extends readonly string[],
C extends readonly string[] = readonly [],
> = A extends readonly [T, ...infer Rest extends readonly string[]]
? ExcludeFromArray<T, Rest, C>
: A extends readonly [
infer Head extends string,
...infer Tail extends readonly string[],
]
? ExcludeFromArray<T, Tail, readonly [...C, Head]>
: C
// @ts-ignore
export class Lambda<
// @ts-ignore
out T extends string,
in out B extends Node,
> extends Node {
readonly canEval: B["canEval"]
readonly locals: ExcludeFromArray<T, B["locals"]>
constructor(readonly name: T, readonly body: B) {
super()
this.canEval = body.canEval
this.locals = body.locals.filter((local) => local != name) as any
}
// @ts-ignore
rename<Old extends string, New extends string>(
oldName: Old,
newName: Name<New>,
): // @ts-ignore
Rename<this, Old, New>
rename(oldName: string, newName: Name<string>): Node {
if (oldName == this.name) {
return this
}
// @ts-ignore
return new Lambda(this.name, this.body.rename(oldName, newName))
}
// @ts-ignore
replace<O extends string, N extends Node>(
oldName: O,
newNode: N,
): // @ts-ignore
Replace<this, O, N>
replace(oldName: string, newNode: Node): Node {
if (oldName == this.name) {
return this
}
if (newNode.locals.includes(this.name)) {
const unique = Name.unique([
this.name,
...this.locals,
...newNode.locals,
])
return new Lambda(
unique.name,
this.body.rename(this.name, unique).replace(oldName, newNode),
)
}
return new Lambda(this.name, this.body.replace(oldName, newNode))
}
// #region toString
toCompactString(): // prettier-ignore
ReturnType<
B["toCompactString"]
> extends (infer B extends PartialString)
? IsSingleCharacter<T> extends false
? {
readonly content: `λ${T} ${B["content"]}`
readonly endsWithLambda: true
readonly hasTopLevelApplication: false
readonly startsWithDottedLambda: false
}
: B["startsWithDottedLambda"] extends true
? {
readonly content: `λ${T}${SkipFirstCharacter<B["content"]>}`
readonly endsWithLambda: true
readonly hasTopLevelApplication: false
readonly startsWithDottedLambda: true
}
: {
readonly content: `λ${T}.${B["content"]}`
readonly endsWithLambda: true
readonly hasTopLevelApplication: false
readonly startsWithDottedLambda: true
}
: never
toCompactString(): PartialString {
const body = this.body.toCompactString()
if (this.name.length != 1) {
return {
content: `λ${this.name} ${body.content}`,
endsWithLambda: true,
hasTopLevelApplication: false,
startsWithDottedLambda: false,
}
}
if (body.startsWithDottedLambda) {
return {
content: "λ" + this.name + body.content.slice(1),
endsWithLambda: true,
hasTopLevelApplication: false,
startsWithDottedLambda: true,
}
}
return {
content: `λ${this.name}.${body.content}`,
endsWithLambda: true,
hasTopLevelApplication: false,
startsWithDottedLambda: true,
}
}
toPartialString(): {
readonly content: `λ${T} ${ReturnType<B["toPartialString"]>["content"]}`
readonly endsWithLambda: true
readonly hasTopLevelApplication: false
readonly startsWithDottedLambda: false
}
toPartialString(): PartialString {
const body = this.body.toPartialString()
return {
content: `λ${this.name} ${body.content}`,
endsWithLambda: true,
hasTopLevelApplication: false,
startsWithDottedLambda: false,
}
}
// #endregion
}
export class Application<L extends Node, R extends Node> extends Node {
readonly canEval: L extends Lambda<string, Node>
? true
: L["canEval"] extends true
? true
: R["canEval"] extends true
? true
: false
readonly locals: readonly [...L["locals"], ...R["locals"]]
constructor(readonly left: L, readonly right: R) {
super()
this.canEval = (left instanceof Lambda ||
left.canEval ||
right.canEval) as any
this.locals = [...left.locals, ...right.locals] as any
}
rename<Old extends string, New extends string>(
oldName: Old,
newName: Name<New>,
): Application<Rename<L, Old, New>, Rename<R, Old, New>> {
return new Application(
this.left.rename(oldName, newName),
this.right.rename(oldName, newName),
) as any
}
// @ts-ignore
replace<O extends string, N extends Node>(
oldName: O,
// @ts-ignore
newNode: N,
): // @ts-ignore
Replace<this, O, N>
replace(oldName: string, newNode: Node): Node {
return new Application(
this.left.replace(oldName, newNode),
this.right.replace(oldName, newNode),
)
}
// #region toString
toCompactString(): // prettier-ignore
ReturnType<
L["toCompactString"]
> extends (infer L extends PartialString)
? ReturnType<R["toCompactString"]> extends (infer R extends PartialString)
? {
readonly content: `${L["endsWithLambda"] extends true
? `(${L["content"]})`
: L["content"]}${R["hasTopLevelApplication"] extends true
? `(${R["content"]})`
: R["content"]}`
readonly endsWithLambda: R["endsWithLambda"]
readonly hasTopLevelApplication: true
readonly startsWithDottedLambda: false
}
: never
: never
toCompactString(): PartialString {
const left = this.left.toCompactString()
const right = this.right.toCompactString()
return {
content:
(left.endsWithLambda ? `(${left.content})` : left.content) +
(right.hasTopLevelApplication ? `(${right.content})` : right.content),
endsWithLambda: right.endsWithLambda,
hasTopLevelApplication: true,
startsWithDottedLambda: false,
}
}
toPartialString(): // prettier-ignore
ReturnType<
L["toPartialString"]
> extends (infer L extends PartialString)
? ReturnType<R["toPartialString"]> extends (infer R extends PartialString)
? {
readonly content: `${L["endsWithLambda"] extends true
? `(${L["content"]})`
: L["content"]} ${R["hasTopLevelApplication"] extends true
? `(${R["content"]})`
: R["content"]}`
readonly endsWithLambda: R["endsWithLambda"]
readonly hasTopLevelApplication: true
readonly startsWithDottedLambda: false
}
: never
: never
toPartialString(): PartialString {
const left = this.left.toPartialString()
const right = this.right.toPartialString()
return {
content:
(left.endsWithLambda ? `(${left.content})` : left.content) +
" " +
(right.hasTopLevelApplication ? `(${right.content})` : right.content),
endsWithLambda: right.endsWithLambda,
hasTopLevelApplication: true,
startsWithDottedLambda: false,