-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheval.ts
73 lines (59 loc) · 1.94 KB
/
eval.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
import { Error, Expr, ShouldNotGetHere, Type, Value } from './header.ts';
import { OPS_BBB, OPS_NNB, OPS_NNN } from './ops.ts';
const log = console.log;
function typeError(expr: Expr, t: Type, desc: string): Error | null {
return {
tag: 'Error',
message: `Expected ${desc} to be ${t}, got ${expr.tag}`,
loc: expr.loc,
};
}
export function evaluate(expr: Expr): Value {
let result;
switch (expr.tag) {
case 'Name':
throw ShouldNotGetHere;
case 'Bool':
case 'Num':
return expr;
case 'If': {
if (evaluate(expr.cond)) {
return evaluate(expr.then);
} else {
return evaluate(expr.else);
}
}
case 'Binary': {
let a = evaluate(expr.left);
let b = evaluate(expr.right);
let err;
let func = OPS_NNN[expr.op];
if (func !== undefined) {
if (a.tag !== 'Num') throw typeError(a, 'Num', 'left operand');
if (b.tag !== 'Num') throw typeError(b, 'Num', 'right operand');
if (expr.op === '/' && b.value === 0) {
throw { message: 'Divide by zero', loc: expr.loc };
}
let value = func(a.value, b.value);
//log(value);
return { tag: 'Num', value, loc: expr.loc };
}
let func2 = OPS_NNB[expr.op];
if (func2 !== undefined) {
if (a.tag !== 'Num') throw typeError(a, 'Num', 'left operand');
if (b.tag !== 'Num') throw typeError(b, 'Num', 'right operand');
let value = func2(a.value, b.value);
return { tag: 'Bool', value, loc: expr.loc };
}
let func3 = OPS_BBB[expr.op];
if (func3 !== undefined) {
if (a.tag !== 'Bool') throw typeError(a, 'Bool', 'left operand');
if (b.tag !== 'Bool') throw typeError(b, 'Bool', 'right operand');
let value = func3(a.value, b.value);
return { tag: 'Bool', value, loc: expr.loc };
}
}
default: // 'Error' or some other node
throw ShouldNotGetHere;
}
}