aboutsummaryrefslogtreecommitdiff
path: root/src/primitives/conditional.d
blob: ee89ea54ac436b2164a4d21be4966d42c4ebd046 (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
module src.primitives.conditional;

import std.variant;
import std.typecons;
import std.container : DList;

import src.stack;

Nullable!(DList!Token) buffer;
bool                   concluded = true;
bool                   drop_mode = false;

void capture(Token token) {
	if ( !drop_mode ) {
		buffer.insertBack(token);
	}
}

bool drop(Token token) {
	if ( concluded && buffer.isNull ) {
		return false;
	}

	if ( token.type == typeid(string) ) {
		switch ( *token.peek!string ) {
			case "if"   : eval_if;        break;
			case "then" : eval_then;      break;
			case "else" : eval_else;      break;
			default     : capture(token); break; 
		}
	} else {
		capture(token);
	}

	return true;
}

void eval_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 eval_then() {
	if ( concluded  ) {
		throw new Exception("`then` without preceding `if`");
	} else {
		drop_mode = !drop_mode;
	}
}

void eval_else() {
	if ( concluded ) {
		throw new Exception("`else` without preceding `if`");	
	} else {
		drop_mode = false;
		concluded = true;
	}
}

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");	
	}
}