Phasor 3.3.0
Stack VM based Programming Language
Loading...
Searching...
No Matches
CodeGen.hpp
Go to the documentation of this file.
1#pragma once
2#include "../AST/AST.hpp"
3#ifndef CMAKE_PCH
4#include <Value.hpp>
5#endif
6#include "../ISA/ISA.hpp"
7#include <phsint.hpp>
8#include <map>
9#include <unordered_map>
10#include <string>
11#include <vector>
12
13#include <platform.h>
14
15namespace Phasor
16{
21{
26
27 // Default constructor
29 {
30 }
31
32 // Full constructor
33 Instruction(OpCode op, i32 op1 = 0, i32 op2 = 0, i32 op3 = 0)
34 : op(op), operand1(op1), operand2(op2), operand3(op3)
35 {
36 }
37};
38
41{
42 std::string name;
45 std::vector<std::string> fieldNames;
46};
47
50{
51 std::vector<Instruction> instructions;
52 std::vector<Value> constants;
53 std::unordered_map<std::string, int> variables;
54 std::unordered_map<std::string, int> functionEntries;
55 std::unordered_map<std::string, int> functionParamCounts;
56 int nextVarIndex = 0;
57
58 // Struct section (planned usage by future struct codegen)
59 std::vector<StructInfo> structs;
60 std::unordered_map<std::string, int> structEntries;
61
63 int addConstant(const Value &value)
64 {
65 constants.push_back(value);
66 return static_cast<int>(constants.size()) - 1;
67 }
68
70 int addStringConstant(const std::string &s)
71 {
72 auto it = stringConstantCache.find(s);
73 if (it != stringConstantCache.end())
74 {
75 return it->second;
76 }
77 int idx = addConstant(Value(s));
79 return idx;
80 }
81
82 std::unordered_map<std::string, int> stringConstantCache;
83
85 int getOrCreateVar(const std::string &name)
86 {
87 auto it = variables.find(name);
88 if (it != variables.end())
89 {
90 return it->second;
91 }
92 int index = nextVarIndex++;
93 variables[name] = index;
94 return index;
95 }
96
98 void emit(OpCode op, i32 op1 = 0, i32 op2 = 0, i32 op3 = 0)
99 {
100 instructions.emplace_back(op, op1, op2, op3);
101 }
102};
103
108{
109 public:
119 Bytecode generate(const AST::Program &program, const std::unordered_map<std::string, int> &existingVars = {},
120 int nextVarIdx = 0, bool replMode = false);
121
122 private:
124 bool isRepl = false;
125 // Inferred types for variables (simple, flow-insensitive mapping)
126 std::unordered_map<std::string, ValueType> inferredTypes;
127
128 // Register allocation for v2.0
130 std::vector<bool> registerInUse;
131
134 {
135 for (size_t i = 0; i < MAX_REGISTERS; i++)
136 {
137 if (i >= registerInUse.size())
138 {
139 registerInUse.resize(i + 1, false);
140 }
141 if (!registerInUse[i])
142 {
143 registerInUse[i] = true;
144 return static_cast<u8>(i);
145 }
146 }
147 throw std::runtime_error("Out of registers");
148 }
149
151 void freeRegister(u8 reg)
152 {
153 if (reg < registerInUse.size())
154 {
155 registerInUse[reg] = false;
156 }
157 }
158
161 {
162 registerInUse.clear();
163 nextRegister = 0;
164 }
165
167 static bool isLiteralExpression(const AST::Expression *expr, Value &outValue);
168
173 ValueType inferExpressionType(const AST::Expression *expr, bool &known);
174
175 void generateStatement(const AST::Statement *stmt);
176 void generateExpression(const AST::Expression *expr, bool resultNeeded = true);
177 void generateVarDecl(const AST::VarDecl *varDecl);
178 void generateExpressionStmt(const AST::ExpressionStmt *exprStmt);
179 void generatePrintStmt(const AST::PrintStmt *printStmt);
180 void generateImportStmt(const AST::ImportStmt *importStmt);
181 void generateExportStmt(const AST::ExportStmt *exportStmt);
182 void generateNumberExpr(const AST::NumberExpr *numExpr);
183 void generateStringExpr(const AST::StringExpr *strExpr);
184 void generateIdentifierExpr(const AST::IdentifierExpr *identExpr);
185 void generateUnaryExpr(const AST::UnaryExpr *unaryExpr);
186 void generateCallExpr(const AST::CallExpr *callExpr);
187 void generateBinaryExpr(const AST::BinaryExpr *binExpr);
188 void generateBlockStmt(const AST::BlockStmt *blockStmt);
189 void generateIfStmt(const AST::IfStmt *ifStmt);
190 void generateWhileStmt(const AST::WhileStmt *whileStmt);
191 void generateForStmt(const AST::ForStmt *forStmt);
192 void generateReturnStmt(const AST::ReturnStmt *returnStmt);
194 const AST::UnsafeBlockStmt *unsafeStmt);
195 void generateFunctionDecl(const AST::FunctionDecl *funcDecl);
196 void generateBooleanExpr(const AST::BooleanExpr *boolExpr);
197 void generateNullExpr(const AST::NullExpr *nullExpr);
199 const AST::AssignmentExpr *assignExpr);
200 void generateStructDecl(const AST::StructDecl *decl);
203 void generatePostfixExpr(const AST::PostfixExpr *expr, bool resultNeeded = true);
204 void generateBreakStmt();
206 void generateSwitchStmt(const AST::SwitchStmt *switchStmt);
207 void generateArrayLiteralExpr(const AST::ArrayLiteralExpr *arrayLit, bool resultNeeded);
208 void generateArrayAccessExpr(const AST::ArrayAccessExpr *arrayAccess, bool resultNeeded);
209
210 // Loop context for break/continue
211 std::vector<int> loopStartStack; // Stack of loop start positions
212 std::vector<std::vector<int>> breakJumpsStack; // Stack of break jump positions to patch
213 std::vector<std::vector<int>> continueJumpsStack; // Stack of continue jump positions to patch
214
215 int switchCounter = 0; // Monotonic counter for unique switch temp variable names
216};
217
218} // namespace Phasor
Code generator for Phasor VM.
Definition CodeGen.hpp:108
void generateForStmt(const AST::ForStmt *forStmt)
Generate bytecode from For Statement.
Definition CodeGen.cpp:795
Bytecode bytecode
Generated bytecode.
Definition CodeGen.hpp:123
void generateCallExpr(const AST::CallExpr *callExpr)
Generate bytecode from Call Expression.
Definition CodeGen.cpp:367
void generateVarDecl(const AST::VarDecl *varDecl)
Generate bytecode from Variable Declaration.
Definition CodeGen.cpp:230
void generateIfStmt(const AST::IfStmt *ifStmt)
Generate bytecode from If Statement.
Definition CodeGen.cpp:732
void generatePostfixExpr(const AST::PostfixExpr *expr, bool resultNeeded=true)
Definition CodeGen.cpp:1059
std::vector< std::vector< int > > breakJumpsStack
Definition CodeGen.hpp:212
void generateUnaryExpr(const AST::UnaryExpr *unaryExpr)
Generate bytecode from Unary Expression.
Definition CodeGen.cpp:343
void generateArrayLiteralExpr(const AST::ArrayLiteralExpr *arrayLit, bool resultNeeded)
Definition CodeGen.cpp:1168
void generateStructInstanceExpr(const AST::StructInstanceExpr *expr)
Definition CodeGen.cpp:1019
void generateNullExpr(const AST::NullExpr *nullExpr)
Generate bytecode from Null Expression.
Definition CodeGen.cpp:953
void generateFunctionDecl(const AST::FunctionDecl *funcDecl)
Generate bytecode from Function Declaration.
Definition CodeGen.cpp:907
std::unordered_map< std::string, ValueType > inferredTypes
Definition CodeGen.hpp:126
Bytecode generate(const AST::Program &program, const std::unordered_map< std::string, int > &existingVars={}, int nextVarIdx=0, bool replMode=false)
Generate bytecode from program.
Definition CodeGen.cpp:9
void generateArrayAccessExpr(const AST::ArrayAccessExpr *arrayAccess, bool resultNeeded)
Definition CodeGen.cpp:1184
u8 nextRegister
Next available register.
Definition CodeGen.hpp:129
void generateWhileStmt(const AST::WhileStmt *whileStmt)
Generate bytecode from While Statement.
Definition CodeGen.cpp:757
void generateSwitchStmt(const AST::SwitchStmt *switchStmt)
Definition CodeGen.cpp:1124
void generateBlockStmt(const AST::BlockStmt *blockStmt)
Generate bytecode from Block Statement.
Definition CodeGen.cpp:724
void generateBooleanExpr(const AST::BooleanExpr *boolExpr)
Generate bytecode from Boolean Expression.
Definition CodeGen.cpp:941
void generateStructDecl(const AST::StructDecl *decl)
Definition CodeGen.cpp:1085
std::vector< int > loopStartStack
Definition CodeGen.hpp:211
void generatePrintStmt(const AST::PrintStmt *printStmt)
Generate bytecode from Print Statement.
Definition CodeGen.cpp:288
void generateStringExpr(const AST::StringExpr *strExpr)
Generate bytecode from String Expression.
Definition CodeGen.cpp:331
void generateExpression(const AST::Expression *expr, bool resultNeeded=true)
Generate bytecode from Expression.
Definition CodeGen.cpp:166
ValueType inferExpressionType(const AST::Expression *expr, bool &known)
Simple expression type inference (conservative).
Definition CodeGen.cpp:64
std::vector< std::vector< int > > continueJumpsStack
Definition CodeGen.hpp:213
void generateExportStmt(const AST::ExportStmt *exportStmt)
Generate bytecode from Export Statement.
Definition CodeGen.cpp:300
void generateUnsafeBlockStmt(const AST::UnsafeBlockStmt *unsafeStmt)
Generate bytecode from Unsafe Block Statement.
Definition CodeGen.cpp:902
void freeRegister(u8 reg)
Free a register.
Definition CodeGen.hpp:151
void generateBinaryExpr(const AST::BinaryExpr *binExpr)
Generate bytecode from Binary Expression.
Definition CodeGen.cpp:469
void generateExpressionStmt(const AST::ExpressionStmt *exprStmt)
Generate bytecode from Expression Statement.
Definition CodeGen.cpp:265
void generateImportStmt(const AST::ImportStmt *importStmt)
Generate bytecode from Import Statement.
Definition CodeGen.cpp:294
void generateStatement(const AST::Statement *stmt)
Generate bytecode from Statement.
Definition CodeGen.cpp:90
static bool isLiteralExpression(const AST::Expression *expr, Value &outValue)
Check if expression is a compile-time literal.
Definition CodeGen.cpp:25
void generateIdentifierExpr(const AST::IdentifierExpr *identExpr)
Generate bytecode from Identifier Expression.
Definition CodeGen.cpp:337
bool isRepl
REPL mode.
Definition CodeGen.hpp:124
void generateAssignmentExpr(const AST::AssignmentExpr *assignExpr)
Generate bytecode from Assignment Expression.
Definition CodeGen.cpp:958
void generateNumberExpr(const AST::NumberExpr *numExpr)
Generate bytecode from Numeral Expression.
Definition CodeGen.cpp:306
std::vector< bool > registerInUse
Track which registers are in use.
Definition CodeGen.hpp:130
u8 allocateRegister()
Allocate a new register.
Definition CodeGen.hpp:133
void resetRegisters()
Reset register allocator.
Definition CodeGen.hpp:160
void generateFieldAccessExpr(const AST::FieldAccessExpr *expr)
Definition CodeGen.cpp:1052
void generateReturnStmt(const AST::ReturnStmt *returnStmt)
Generate bytecode from Return Statement.
Definition CodeGen.cpp:889
A value in the Phasor VM.
Definition Value.hpp:59
static Phasor::u64 s[2]
Definition random.cpp:7
The Phasor Programming Language and Runtime.
Definition AST.hpp:13
ValueType
Runtime value types for the VM.
Definition Value.hpp:43
uint8_t u8
Definition phsint.hpp:9
int32_t i32
Definition phsint.hpp:15
OpCode
Definition ISA.hpp:12
@ HALT
Stop execution.
Definition ISA.hpp:75
#define MAX_REGISTERS
Definition platform.h:19
Array Access Expression Node.
Definition AST.hpp:315
Array Literal Expression Node.
Definition AST.hpp:335
Assignment Expression Node.
Definition AST.hpp:390
Binary Expression Node.
Definition AST.hpp:253
Block Statement Node.
Definition AST.hpp:496
Boolean Expression Node.
Definition AST.hpp:139
Call Expression Node.
Definition AST.hpp:369
Export Statement Node.
Definition AST.hpp:482
Expression Statement Node.
Definition AST.hpp:429
Expression Node.
Definition AST.hpp:55
Field Access Expression Node.
Definition AST.hpp:735
For Statement Node.
Definition AST.hpp:592
Function Declaration Node.
Definition AST.hpp:639
Identifier Expression Node.
Definition AST.hpp:126
If Statement Node.
Definition AST.hpp:548
Import Statement Node.
Definition AST.hpp:469
NULL Expression Node.
Definition AST.hpp:152
Numeral Expression Node.
Definition AST.hpp:99
Postfix Expression Node.
Definition AST.hpp:195
Print Statement Node.
Definition AST.hpp:442
Program Node.
Definition AST.hpp:65
Return Statement Node.
Definition AST.hpp:513
Statement Node.
Definition AST.hpp:60
String Expression Node.
Definition AST.hpp:112
Struct Declaration Node.
Definition AST.hpp:692
Struct Instance Expression Node.
Definition AST.hpp:713
Switch Statement Node.
Definition AST.hpp:765
Unary Expression Node.
Definition AST.hpp:221
Unsafe Block Statement Node.
Definition AST.hpp:625
Variable Declaration Node.
Definition AST.hpp:411
While Statement Node.
Definition AST.hpp:573
Complete bytecode structure.
Definition CodeGen.hpp:50
std::unordered_map< std::string, int > variables
Variable name -> index mapping.
Definition CodeGen.hpp:53
int addStringConstant(const std::string &s)
Add a string constant with deduplication.
Definition CodeGen.hpp:70
void emit(OpCode op, i32 op1=0, i32 op2=0, i32 op3=0)
Emit an instruction with operands.
Definition CodeGen.hpp:98
std::unordered_map< std::string, int > functionParamCounts
Function name -> parameter count.
Definition CodeGen.hpp:55
std::vector< Instruction > instructions
List of instructions.
Definition CodeGen.hpp:51
std::unordered_map< std::string, int > functionEntries
Function name -> instruction index mapping.
Definition CodeGen.hpp:54
int nextVarIndex
Next available variable index.
Definition CodeGen.hpp:56
std::unordered_map< std::string, int > stringConstantCache
Dedup cache for string constants.
Definition CodeGen.hpp:82
int getOrCreateVar(const std::string &name)
Get or create a variable index.
Definition CodeGen.hpp:85
std::vector< Value > constants
Constant pool.
Definition CodeGen.hpp:52
int addConstant(const Value &value)
Add a constant to the pool and return its index.
Definition CodeGen.hpp:63
std::vector< StructInfo > structs
List of struct descriptors.
Definition CodeGen.hpp:59
std::unordered_map< std::string, int > structEntries
Struct name -> index in structs.
Definition CodeGen.hpp:60
i32 operand1
First operand.
Definition CodeGen.hpp:23
Instruction(OpCode op, i32 op1=0, i32 op2=0, i32 op3=0)
Definition CodeGen.hpp:33
i32 operand2
Second operand.
Definition CodeGen.hpp:24
OpCode op
Operation code.
Definition CodeGen.hpp:22
i32 operand3
Third operand.
Definition CodeGen.hpp:25
Struct metadata stored alongside bytecode (struct section).
Definition CodeGen.hpp:41
int firstConstIndex
Index into constants for the first default value.
Definition CodeGen.hpp:43
std::vector< std::string > fieldNames
Field names in declaration order.
Definition CodeGen.hpp:45
int fieldCount
Number of fields in this struct.
Definition CodeGen.hpp:44
std::string name
Struct name.
Definition CodeGen.hpp:42