-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstacker.h
111 lines (96 loc) · 1.86 KB
/
stacker.h
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
class Stack {
public:
double* items;
int pointer;
Stack ();
~Stack ();
void reset () { pointer = 0; }
void push (double x) { items[pointer++] = x; }
double pop (void) { return items[--pointer]; }
};
extern Stack stack;
template<typename T>
class Symbols {
char** names;
T* values;
int count;
public:
Symbols ();
int lookup(const char* name);
int add (const char* name);
int add (const char* name, T val);
T get (int index);
void set (int index, T val);
};
extern Symbols<double> variables;
typedef double (*pfunc) (double);
extern Symbols<pfunc> functions;
class Instruction {
public:
virtual void execute () = 0;
};
class Push: public Instruction {
double val;
public:
Push (double x) { val = x; }
void execute () { stack.push(val); }
};
class PushVariable: public Instruction {
int var;
public:
PushVariable (int varIndex) { var = varIndex; }
void execute () {
double val = variables.get(var);
stack.push(val);
}
};
class Add: public Instruction {
public:
void execute () {
double a = stack.pop();
double b = stack.pop ();
stack.push(a+b);
}
};
class Sub: public Instruction {
public:
void execute () {
double b = stack.pop();
double a = stack.pop ();
stack.push(a-b);
}
};
class Mul: public Instruction {
public:
void execute () {
double a = stack.pop();
double b = stack.pop ();
stack.push(a*b);
}
};
class Div: public Instruction {
public:
void execute () {
double b = stack.pop();
double a = stack.pop ();
stack.push(a/b);
}
};
class FunctionCall: public Instruction {
pfunc fn;
public:
FunctionCall (pfunc f) { fn = f; }
void execute () {
double x = stack.pop ();
x = (*fn)(x);
stack.push (x);
}
};
class Program {
Instruction** instructions;
int pc;
public:
Program ();
void add(Instruction*);
void execute ();
};