/
controlflow.ts
80 lines (72 loc) · 1.94 KB
/
controlflow.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
import type { Fn } from "@thi.ng/api";
import type { FnBody1 } from "../api/function";
import type {
Branch,
ControlFlow,
ForLoop,
Sym,
Term,
Ternary,
WhileLoop,
} from "../api/nodes";
import type { BoolTerm } from "../api/terms";
import type { Type } from "../api/types";
import { decl, scope } from "./scope";
export const ifThen = (
test: BoolTerm,
truthy: Term<any>[],
falsey?: Term<any>[]
): Branch => ({
tag: "if",
type: "void",
test,
t: scope(truthy),
f: falsey ? scope(falsey) : undefined,
});
export const ternary = <A extends Type, B extends A>(
test: BoolTerm,
t: Term<A>,
f: Term<B>
): Ternary<A> => ({
tag: "ternary",
type: t.type,
test,
t,
f,
});
// prettier-ignore
export function forLoop<T extends Type>(test: Fn<Sym<T>, BoolTerm>, body: FnBody1<T>): ForLoop;
// prettier-ignore
export function forLoop<T extends Type>(init: Sym<T> | undefined, test: Fn<Sym<T>, BoolTerm>, body: FnBody1<T>): ForLoop;
// prettier-ignore
export function forLoop<T extends Type>(init: Sym<T> | undefined, test: Fn<Sym<T>, BoolTerm>, iter: Fn<Sym<T>, Term<any>>, body: FnBody1<T>): ForLoop;
export function forLoop(...xs: any[]): ForLoop {
const [init, test, iter, body] =
xs.length === 2
? [, xs[0], , xs[1]]
: xs.length === 3
? [xs[0], xs[1], , xs[2]]
: xs;
return {
tag: "for",
type: "void",
init: init ? decl(init) : undefined,
test: test(init!),
iter: iter ? iter(init!) : undefined,
scope: scope(body(init!)),
};
}
export const whileLoop = (test: BoolTerm, body: Term<any>[]): WhileLoop => ({
tag: "while",
type: "void",
test,
scope: scope(body),
});
const ctrl = (id: string): ControlFlow => ({
tag: "ctrl",
type: "void",
id,
});
export const brk = ctrl("break");
export const cont = ctrl("continue");
export const discard = ctrl("discard");