forked from VisceralLogic/basic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
for.cpp
76 lines (62 loc) · 1.68 KB
/
for.cpp
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
#include "for.h"
#include "basic.h"
#include "next.h"
std::map<const For*, const Next*> For::nextLine;
std::map<const For*, bool> For::initial;
// initialize with all necessary information
For::For(DoubleExpression *start, DoubleExpression *stop, DoubleExpression *step, std::string var){
this->start = start;
this->stop = stop;
this->step = step;
this->var = var;
initial[this] = true;
}
// clean up pointers
For::~For(){
delete start;
delete stop;
delete step;
initial.erase(this);
nextLine.erase(this);
}
// run this line of the program
bool For::execute(bool next) const{
double s = 1.0; // default step size
double val;
if( step != NULL )
s = step->value(); // evaluate the step every time
if( initial[this] ){ // start the loop
val = start->value();
} else { // increment the loop
val = Basic::instance()->resolve(var) + s;
}
initial[this] = true; // reset
Basic::instance()->assign(var, val); // store the value
// check for loop termination
if( (s > 0 && val > stop->value()) || (s < 0 && val < stop->value()) ){
Basic::instance()->gotoProgram(nextLine[this]);
}
if (next)
{
Basic::instance()->nextLine(); // continue to next line
}
return true;
}
// list this line
void For::list(std::ostream& os) const{
os << "FOR " << var << " = " << start->list() << " TO " << stop->list();
if( step != NULL )
os << " STEP " << step->list();
}
// run before main program execution
void For::preExecute() const{
Basic::instance()->pushFor(this);
}
// register NEXT statement
void For::registerNext(const Next *next) const{
nextLine[this] = next;
}
// called from NEXT statement
void For::doNext() const{
initial[this] = false;
}