-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.cpp
More file actions
97 lines (82 loc) · 2.41 KB
/
generator.cpp
File metadata and controls
97 lines (82 loc) · 2.41 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
#include "generator.hpp"
#define APPEND(fst, snd) fst.insert(fst.end(), snd.begin(), snd.end())
std::vector<command_type> makeProgram(std::vector<command_type> code) {
code.push_back(Command::HALT);
return code;
}
std::vector<command_type> environment(command_type size, std::vector<command_type> code) {
std::vector<command_type> result = {Command::PUSH, size};
APPEND(result, code);
result.push_back(Command::POP);
result.push_back(size);
return result;
}
std::vector<command_type> concat(std::vector<command_type> fst, std::vector<command_type> snd) {
APPEND(fst, snd);
return fst;
}
std::vector<command_type> loadConstant(command_type value) {
return { Command::LOADC, value };
}
std::vector<command_type> loadVariable() {
return {
Command::LOAD
};
}
std::vector<command_type> loadVariable(command_type addr) {
return {
Command::LOADC, addr,
Command::LOAD
};
}
std::vector<command_type> storeVariable() {
return {
Command::STORE
};
}
std::vector<command_type> storeVariable(command_type addr) {
return {
Command::LOADC, addr,
Command::STORE
};
}
std::vector<command_type> assign(command_type addr, std::vector<command_type> value) {
return concat(value, storeVariable(addr));
}
std::vector<command_type> if_expr(command_type end_label, std::vector<command_type> condition, std::vector<command_type> then_part) {
// condition
// jmpz END
// then_part
// END:
auto result = concat(condition, {Command::JMPZ, end_label});
APPEND(result, then_part);
return result;
}
std::vector<command_type> if_expr(command_type else_label, command_type end_label, std::vector<command_type> condition, std::vector<command_type> then_part, std::vector<command_type> else_part) {
// condition
// jmpz ELSE
// then_part
// jmp END
// ELSE:
// else_part
// END
auto result = if_expr(else_label, condition, concat(then_part, {Command::JMP, end_label}));
return concat(result, else_part);
}
std::vector<command_type> addition(command_type op1, command_type op2) {
return {
Command::LOADC, op1,
Command::LOADC, op2,
Command::ADD
};
}
std::vector<command_type> addition(std::vector<command_type> op1, std::vector<command_type> op2) {
APPEND(op1, op2);
op1.push_back(Command::ADD);
return op1;
}
std::vector<command_type> equals(std::vector<command_type> op1, std::vector<command_type> op2) {
APPEND(op1, op2);
op1.push_back(Command::EQ);
return op1;
}