-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCodeGen.h
More file actions
72 lines (56 loc) · 2.14 KB
/
Copy pathCodeGen.h
File metadata and controls
72 lines (56 loc) · 2.14 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
//This files takes AST as a input and gives TAC as output
// File: include/CodeGen.h
// Purpose: INTERMEDIATE CODE GENERATION (Phase 4)
// Translates the AST into Three-Address Code (TAC),
// a simple IR (Intermediate Representation) that looks
// like assembly but is still platform-independent.
// Input: AST
//Output: TAC Three address code
// int x = 5 + 3 * 2;
//AST::
// =
// x +
// 5 *
// 3 2
// t0 = 3 * 2
// t1 = 5 + t0
// x = t1
#ifndef CODEGEN_H
#define CODEGEN_H
#include "AST.h"
#include <string>
#include <vector>
// A single Three-Address Code instruction
struct TACInstruction {
std::string result; // Destination operand e.g. "t0" or "x"
std::string op; // Operator or opcode e.g. "+" or "GOTO" or "PRINT"
std::string arg1; // First source operand
std::string arg2; // Second source operand (empty for unary ops)
// Format instruction as readable string e.g. "t0 = 5 + 3"
std::string toString() const;
};
class CodeGen {
public:
CodeGen();
public:
// generate() – walk AST, emit TAC instructions
std::vector<TACInstruction> generate(const std::vector<ASTNodePtr>& stmts);
// Print all generated instructions to stdout
void printInstructions() const;
private:
std::vector<TACInstruction> instructions_; // Accumulated TAC
int tempCount_; // Counter for unique temp names: t0, t1, t2 …
int labelCount_; // Counter for unique labels: L0, L1, L2 …
std::string newTemp(); // Allocate next temp name
std::string newLabel(); // Allocate next label name
// Emit a TAC instruction into instructions_
void emit(const std::string& result,
const std::string& op,
const std::string& arg1 = "",
const std::string& arg2 = "");
// Recursively generate code for an expression; returns temp holding result
std::string genExpr(const ASTNode* node);
// Generate code for a statement (no return value needed)
void genStmt(const ASTNode* node);
};
#endif // CODEGEN_H