-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
131 lines (108 loc) · 1.74 KB
/
stack.cpp
File metadata and controls
131 lines (108 loc) · 1.74 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//
// Stack functions
//
// NOTE: This stacks grows *downward*, not upward.
//
#include "doctest.h"
#include "consVM.h"
const int STACK_SIZE = 1000;
Cell* stack[STACK_SIZE];
Cell** sp;
Cell** stack_base;
void init_stack()
{
stack_base = stack + STACK_SIZE;
sp = stack_base;
}
Cell* top()
{
if (sp == stack_base) {
throw LispError("top: stack underflow", true);
}
return *sp;
}
void push(Cell* p)
{
--sp;
if (sp < &stack[0]) {
throw LispError("push: stack overflow", true);
}
*sp = p;
}
Cell* pop()
{
if (sp == stack_base) {
throw LispError("pop: stack underflow", true);
}
return *sp++;
}
Cell* down(int n)
{
if (&sp[n] > stack_base) {
throw LispError("down: stack underflow", true);
}
return sp[n];
}
void drop(int n)
{
sp += n;
if (sp > stack_base) {
throw LispError("drop: stack underflow", true);
}
}
void collapse(int n)
{
Cell* p = pop();
drop(n);
push(p);
}
int mark_stack()
{
Cell** p = sp;
int n_marked = 0;
while (p < stack_base)
{
n_marked += mark(*p);
p++;
}
return n_marked;
}
// -------------------------------------
//
// Unit tests
//
TEST_CASE("down() works") {
Cell* x = atom("x");
Cell* y = atom("y");
Cell* z = atom("z");
push(x);
push(y);
push(z);
REQUIRE(down(0) == z);
REQUIRE(down(1) == y);
REQUIRE(down(2) == x);
}
TEST_CASE("drop() works") {
Cell* x = atom("x");
Cell* y = atom("y");
Cell* z = atom("z");
push(x);
push(y);
push(z);
drop(2);
REQUIRE(top() == x);
}
TEST_CASE("collapse() works") {
Cell* w = atom("w");
Cell* x = atom("x");
Cell* y = atom("y");
Cell* z = atom("z");
push(w);
push(x);
push(y);
push(z);
REQUIRE(top() == z);
collapse(2);
REQUIRE(top() == z);
REQUIRE(down(1) == w);
}