-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcodegen.cpp
More file actions
33 lines (27 loc) · 879 Bytes
/
Copy pathcodegen.cpp
File metadata and controls
33 lines (27 loc) · 879 Bytes
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
#include "codegen.h"
#include <iostream>
#include <cctype>
using namespace std;
void CodeGenerator::generate(Node* root) {
generateExpr(root->right);
cout << "STORE " << root->left->value << endl;
}
void CodeGenerator::generateExpr(Node* node) {
if (!node) return;
if (node->value == "+" || node->value == "-" ||
node->value == "*" || node->value == "/") {
generateExpr(node->left);
generateExpr(node->right);
if (node->value == "+") cout << "ADD\n";
if (node->value == "-") cout << "SUB\n";
if (node->value == "*") cout << "MUL\n";
if (node->value == "/") cout << "DIV\n";
}
else {
// 🔥 differentiate variable vs number
if (isdigit(node->value[0]))
cout << "PUSH " << node->value << endl;
else
cout << "LOAD " << node->value << endl;
}
}