aboutsummaryrefslogtreecommitdiff
path: root/repl.d
blob: 7026b306320b70ca305d19d302af0555ac0808c0 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import std.stdio;
import std.string;
import std.conv;
import std.typecons;

import std.container : SList;
import std.container : DList;

SList!int               stack;
DList!string[string]    words;
Nullable!(DList!string) definition;

void push(ref SList!int stack, int value) {
	if ( definition.isNull ) {
		stack.insertFront(value);
	} else {
		definition.insertBack(to!string(value));
	}
}

int pop(ref SList!int stack) {
	auto x = stack.front;
	stack.removeFront;

	return x;
}

void append(ref Nullable!(DList!string) definition, string token) {
	if ( token == ";" ) {
		auto wordToBeDefined = definition.front;

		if ( wordToBeDefined.isNumeric ) {
			throw new Exception("words may not be numeric");
		} else {
			definition.removeFront;
			words[wordToBeDefined] = definition;
			definition.nullify;
		}
	} else {
		definition.insertBack(token);
	}
}

void evaluate(string word) {
	switch ( word ) {
		case "ยง":
			definition = DList!string();
			break;
		case "+":
			auto a = stack.pop();
			auto b = stack.pop();

			stack.push(a + b);
			break;
		case "*":
			auto a = stack.pop();
			auto b = stack.pop();

			stack.push(a * b);
			break;
		case ".":
			writeln(stack.front);
			break;
		default:
			foreach ( token; words[word] ) {
				if ( token.isNumeric ) {
					stack.push(parse!int(token));
				} else {
					evaluate(token);
				}
			}
	}
}

void main() {
	while ( !stdin.eof ) {
		foreach ( token; stdin.readln.split ) {
			if ( definition.isNull ) {
				if ( token.isNumeric ) {
					stack.push(parse!int(token));
				} else {
					evaluate(token);
				}
			} else {
				definition.append(token);
			}
		}
	}
}