aboutsummaryrefslogtreecommitdiff
path: root/repl.d
blob: 9ea36d660faab359010f3175aa05905b6881cc55 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
import std.stdio;
import std.string;
import std.conv;
import std.container : SList;
import std.container : DList;
import std.variant;

alias Token = Algebraic!(int, string);

auto dataStack = SList!int();

bool   defMode     = false;
string defModeWord = "";

DList!Token[string] wordMap;

void push(ref DList!Token stack, int value) {
	stack.insertBack(Token(value));
}

void push(ref DList!Token stack, string word) {
	stack.insertBack(Token(word));
}

void push(ref DList!Token[string] map, int value) {
	map[defModeWord].push(value);
}

void push(ref DList!Token[string] map, string word) {
	if ( defModeWord == "" ) {
		defModeWord      = word;
		map[defModeWord] = DList!Token();
	} else {
		map[defModeWord].push(word);
	}
}

void push(ref SList!int stack, int value) {
	if ( defMode ) {
		wordMap.push(value);
	} else {
		stack.insertFront(value);
	}
}

void push(ref SList!int stack, string word) {
	if ( defMode ) {
		if ( word == ";" ) {
			defMode     = false;
			defModeWord = "";
		} else {
			wordMap.push(word);
		}
	} else {
		switch ( word ) {
			case "ยง":
				defMode     = true;
				defModeWord = "";
				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; wordMap[word] ) {
					if ( token.type == typeid(int) ) {
						stack.push(*token.peek!int);
					} else {
						stack.push(*token.peek!string);
					}
				}
		}
	}
}

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

	return x;
}

void main() {
	while ( !stdin.eof ) {
		foreach ( word; stdin.readln.split ) {
			if ( word.isNumeric ) {
				dataStack.push(parse!int(word));
			} else {
				dataStack.push(word);
			}
		}
	}
}