aboutsummaryrefslogtreecommitdiff
path: root/lib/statements.js
blob: b59c08f2ae39e4ca0fb83c492dd8f98384667964 (plain)
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
var getStatementEvaluators = function(evaluate) {
	return {
		'statement-sequence': function(dataset, children, context) {
			var retval = null;
			children.forEach(function(child) {
				retval = evaluate(child, context);
			});
			return retval;
		},

		'while': function(dataset, children, context) {
			var condition = children[0];
			var body = children[1];
			while (evaluate(condition, context)) {
				evaluate(body, context);
			}
		},

		'compare': function(dataset, children, context) {
			var operator = binaryOperators[dataset.op];
			var lhs = evaluate(children[0], context);
			var rhs = evaluate(children[1], context);
			var result = operator(lhs, rhs);
			return result;
		},

		'variable': function(dataset, children, context) {
			return context[dataset.name];
		},

		'constant': function(dataset, children, context) {
			return stringToType(dataset.val, dataset.type);
		},

		'branch': function(dataset, children, context) {
			var condition = children[0];
			var ifBody = children[1];

			// else is optional
			if (children.length > 2) {
				var elseBody = children[2];
			}

			if (evaluate(condition, context)) {
				return evaluate(ifBody, context);
			} else if (elseBody) {
				return evaluate(elseBody, context);
			}
		},

		'assign': function(dataset, children, context) {
			context[dataset.name] = evaluate(children[0], context);
			return context[dataset.name];
		},

		'bin-op': function(dataset, children, context) {
			var operator = binaryOperators[dataset.op];
			var lhs = evaluate(children[0], context);
			var rhs = evaluate(children[1], context);
			return operator(lhs, rhs);
		},

		'return': function(dataset, children, context) {
			return evaluate(children[0], context);
		},

		'print': function(dataset, children, context) {
			var args = children.map(function(child) {
				return evaluate(child, context);
			});
			console.log.apply(this, args);
		}
	};
};