-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patheval.js
More file actions
63 lines (53 loc) · 1.58 KB
/
eval.js
File metadata and controls
63 lines (53 loc) · 1.58 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
import { std, specials, Special } from './standard-library.js';
import { Context } from './context.js';
const globalContext = new Context(std);
function evalItem(obj, ctx = globalContext) {
if (obj instanceof Array)
return evaluate(obj, ctx);
switch (obj?.type) {
case 'root':
return (...x) => x;
case 'special':
if (obj.token.slice(0,2) === 'f.')
return specials['f'];
return specials[obj.token];
case 'number':
return Number(obj.token);
case 'string':
let s = obj.token;
s = s.replace('\\n', '\n');
s = s.replace('\\t', '\t');
s = s.replace('\\"', '\"');
return s;
case 'name':
return ctx.get(obj.token);
}
}
function evaluate(ast, ctx = globalContext) {
if (!(ast instanceof Array))
return evalItem(ast, ctx);
if (ast.length === 0)
return [];
const first = evalItem(ast[0], ctx);
if (first instanceof Special)
return first.process(ast, ctx);
const rest = [];
for (let i = 1; i < ast.length; i++) {
rest.push(evalItem(ast[i], ctx));
}
if (first instanceof Function)
return first.apply(undefined, rest);
// obj / maps act like functions where keys are arg
else if (first instanceof Object && rest.length === 1)
return first[rest[0]];
throw new Error(`Invalid evaluation: (${ast[0]?.token}:${first} -- ${rest})`);
}
// exports
export const evalAst = evaluate;
export { evaluate };
export { globalContext };
export function evalProgram(ast, ctx = globalContext) {
const result = evaluate(ast, ctx);
if (ast?.[0]?.type === 'root') return result;
return [result];
}