blob: fd101bd0646803f86d96506563c2fd651ac590c5 (
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
|
module primitives.conditional;
import std.variant;
import std.typecons;
import std.container : DList;
import state.stack;
bool handle(string word) {
switch ( word ) {
case "if" : unary_op_if; return true;
case "then" : n_ary_op_then; return true;
case "else" : n_ary_op_else; return true;
default : return capture(Token(word));
}
}
bool handle(Token token) {
return token.visit!(
(int ) => capture(token),
(bool ) => capture(token),
(string word) => handle(word)
);
}
bool dischargeable() {
return concluded && !buffer.isNull;
}
Stack!Token discharge() {
if ( concluded ) {
Stack!Token result = buffer[];
buffer.nullify;
return result;
} else {
throw new Exception("unconcluded conditional may not be discharged");
}
}
private {
Nullable!(DList!Token) buffer;
bool concluded = true;
bool drop_mode = false;
void unary_op_if() {
if ( concluded ) {
buffer = DList!Token();
drop_mode = !stack.pop.get!bool;
concluded = false;
} else {
throw new Exception("conditionals may not be nested directly");
}
}
void n_ary_op_then() {
if ( concluded ) {
throw new Exception("`then` without preceding `if`");
} else {
drop_mode = !drop_mode;
}
}
void n_ary_op_else() {
if ( concluded ) {
throw new Exception("`else` without preceding `if`");
} else {
drop_mode = false;
concluded = true;
}
}
bool capture(Token token) {
if ( concluded && buffer.isNull ) {
return false;
} else {
if ( !drop_mode ) {
buffer.insertBack(token);
}
return true;
}
}
}
|