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
|
import { _evaluate, callFn, getEvaluatedChildren } from "../core/eval";
import { ASTNode, FnPrim, StackFrame } from "../../ts-lang";
type SBUILTIN = (node: ASTNode, frame: StackFrame) => any;
export const V_SBUILTIN_Call: SBUILTIN = (node, frame) => {
const children = getEvaluatedChildren(node, frame);
const fn = children[0] as FnPrim | undefined;
if (!fn) {
throw new Error(
`Invalid params for function call: ${JSON.stringify(
children,
undefined,
2
)}`
);
}
return callFn(fn, children.slice(1), frame);
};
export const V_SBUILTIN_Map: SBUILTIN = (node, frame) => {
const children = getEvaluatedChildren(node, frame);
const fn = children[1] as FnPrim | undefined;
if (!fn?.fn) {
throw new Error(
`Invalid params for map: ${JSON.stringify(children, undefined, 2)}`
);
}
const values = children[0];
if (!Array.isArray(values)) {
// add to ts
throw new Error(`Can't map non-array value: ${values}`);
}
return values.map((v, i) => callFn(fn, [v, i], frame));
};
export const V_SBUILTIN_IfElse: SBUILTIN = (node, frame) => {
const children = node.children;
if (children.length !== 3) {
throw new Error(`Invalid args for "if": ${JSON.stringify(children)}`);
}
const cond = _evaluate(children[0], frame);
if (typeof cond !== "boolean") {
throw new Error(`Condition value ${JSON.stringify(cond)} is not a boolean`);
}
return cond ? _evaluate(children[1], frame) : _evaluate(children[2], frame);
};
export const nameToSBUILTIN: Record<string, SBUILTIN> = {
call: V_SBUILTIN_Call,
map: V_SBUILTIN_Map,
"?": V_SBUILTIN_IfElse,
};
|