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 <cstdint>
8#include <map>
9#include <unordered_map>
10#include <string>
11#include <vector>
12
13#include <platform.h>
14
15namespace Phasor
16{
21{
23 int32_t operand1;
24 int32_t operand2;
25 int32_t operand3;
26
27 // Default constructor
29 {
30 }
31
32 // Full constructor
33 Instruction(OpCode op, int32_t op1 = 0, int32_t op2 = 0, int32_t 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, int32_t op1 = 0, int32_t op2 = 0, int32_t 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
129 uint8_t nextRegister = 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<uint8_t>(i);
145 }
146 }
147 throw std::runtime_error("Out of registers");
148 }
149
151 void freeRegister(uint8_t 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
208 // Loop context for break/continue
209 std::vector<int> loopStartStack; // Stack of loop start positions
210 std::vector<std::vector<int>> breakJumpsStack; // Stack of break jump positions to patch
211 std::vector<std::vector<int>> continueJumpsStack; // Stack of continue jump positions to patch
212
213 int switchCounter = 0; // Monotonic counter for unique switch temp variable names
214};
215
216} // 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:786
Bytecode bytecode
Generated bytecode.
Definition CodeGen.hpp:123
void generateCallExpr(const AST::CallExpr *callExpr)
Generate bytecode from Call Expression.
Definition CodeGen.cpp:358
void generateVarDecl(const AST::VarDecl *varDecl)
Generate bytecode from Variable Declaration.
Definition CodeGen.cpp:221
void generateIfStmt(const AST::IfStmt *ifStmt)
Generate bytecode from If Statement.
Definition CodeGen.cpp:723
void generatePostfixExpr(const AST::PostfixExpr *expr, bool resultNeeded=true)
Definition CodeGen.cpp:1041
std::vector< std::vector< int > > breakJumpsStack
Definition CodeGen.hpp:210
void generateUnaryExpr(const AST::UnaryExpr *unaryExpr)
Generate bytecode from Unary Expression.
Definition CodeGen.cpp:334
uint8_t nextRegister
Next available register.
Definition CodeGen.hpp:129
void generateStructInstanceExpr(const AST::StructInstanceExpr *expr)
Definition CodeGen.cpp:1001
void generateNullExpr(const AST::NullExpr *nullExpr)
Generate bytecode from Null Expression.
Definition CodeGen.cpp:944
void generateFunctionDecl(const AST::FunctionDecl *funcDecl)
Generate bytecode from Function Declaration.
Definition CodeGen.cpp:898
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:8
void generateWhileStmt(const AST::WhileStmt *whileStmt)
Generate bytecode from While Statement.
Definition CodeGen.cpp:748
void generateSwitchStmt(const AST::SwitchStmt *switchStmt)
Definition CodeGen.cpp:1106
void generateBlockStmt(const AST::BlockStmt *blockStmt)
Generate bytecode from Block Statement.
Definition CodeGen.cpp:715
void generateBooleanExpr(const AST::BooleanExpr *boolExpr)
Generate bytecode from Boolean Expression.
Definition CodeGen.cpp:932
void generateStructDecl(const AST::StructDecl *decl)
Definition CodeGen.cpp:1067
uint8_t allocateRegister()
Allocate a new register.
Definition CodeGen.hpp:133
std::vector< int > loopStartStack
Definition CodeGen.hpp:209
void generatePrintStmt(const AST::PrintStmt *printStmt)
Generate bytecode from Print Statement.
Definition CodeGen.cpp:279
void generateStringExpr(const AST::StringExpr *strExpr)
Generate bytecode from String Expression.
Definition CodeGen.cpp:322
void generateExpression(const AST::Expression *expr, bool resultNeeded=true)
Generate bytecode from Expression.
Definition CodeGen.cpp:165
void freeRegister(uint8_t reg)
Free a register.
Definition CodeGen.hpp:151
ValueType inferExpressionType(const AST::Expression *expr, bool &known)
Simple expression type inference (conservative).
Definition CodeGen.cpp:63
std::vector< std::vector< int > > continueJumpsStack
Definition CodeGen.hpp:211
void generateExportStmt(const AST::ExportStmt *exportStmt)
Generate bytecode from Export Statement.
Definition CodeGen.cpp:291
void generateUnsafeBlockStmt(const AST::UnsafeBlockStmt *unsafeStmt)
Generate bytecode from Unsafe Block Statement.
Definition CodeGen.cpp:893
void generateBinaryExpr(const AST::BinaryExpr *binExpr)
Generate bytecode from Binary Expression.
Definition CodeGen.cpp:460
void generateExpressionStmt(const AST::ExpressionStmt *exprStmt)
Generate bytecode from Expression Statement.
Definition CodeGen.cpp:256
void generateImportStmt(const AST::ImportStmt *importStmt)
Generate bytecode from Import Statement.
Definition CodeGen.cpp:285
void generateStatement(const AST::Statement *stmt)
Generate bytecode from Statement.
Definition CodeGen.cpp:89
static bool isLiteralExpression(const AST::Expression *expr, Value &outValue)
Check if expression is a compile-time literal.
Definition CodeGen.cpp:24
void generateIdentifierExpr(const AST::IdentifierExpr *identExpr)
Generate bytecode from Identifier Expression.
Definition CodeGen.cpp:328
bool isRepl
REPL mode.
Definition CodeGen.hpp:124
void generateAssignmentExpr(const AST::AssignmentExpr *assignExpr)
Generate bytecode from Assignment Expression.
Definition CodeGen.cpp:949
void generateNumberExpr(const AST::NumberExpr *numExpr)
Generate bytecode from Numeral Expression.
Definition CodeGen.cpp:297
std::vector< bool > registerInUse
Track which registers are in use.
Definition CodeGen.hpp:130
void resetRegisters()
Reset register allocator.
Definition CodeGen.hpp:160
void generateFieldAccessExpr(const AST::FieldAccessExpr *expr)
Definition CodeGen.cpp:1034
void generateReturnStmt(const AST::ReturnStmt *returnStmt)
Generate bytecode from Return Statement.
Definition CodeGen.cpp:880
A value in the Phasor VM.
Definition Value.hpp:58
static uint64_t s[2]
Definition random.cpp:6
The Phasor Programming Language and Runtime.
Definition AST.hpp:12
OpCode
Definition ISA.hpp:12
@ HALT
Stop execution.
Definition ISA.hpp:75
ValueType
Runtime value types for the VM.
Definition Value.hpp:42
#define MAX_REGISTERS
Definition platform.h:19
Assignment Expression Node.
Definition AST.hpp:389
Binary Expression Node.
Definition AST.hpp:252
Block Statement Node.
Definition AST.hpp:495
Boolean Expression Node.
Definition AST.hpp:138
Call Expression Node.
Definition AST.hpp:368
Export Statement Node.
Definition AST.hpp:481
Expression Statement Node.
Definition AST.hpp:428
Expression Node.
Definition AST.hpp:54
Field Access Expression Node.
Definition AST.hpp:734
For Statement Node.
Definition AST.hpp:591
Function Declaration Node.
Definition AST.hpp:638
Identifier Expression Node.
Definition AST.hpp:125
If Statement Node.
Definition AST.hpp:547
Import Statement Node.
Definition AST.hpp:468
NULL Expression Node.
Definition AST.hpp:151
Numeral Expression Node.
Definition AST.hpp:98
Postfix Expression Node.
Definition AST.hpp:194
Print Statement Node.
Definition AST.hpp:441
Program Node.
Definition AST.hpp:64
Return Statement Node.
Definition AST.hpp:512
Statement Node.
Definition AST.hpp:59
String Expression Node.
Definition AST.hpp:111
Struct Declaration Node.
Definition AST.hpp:691
Struct Instance Expression Node.
Definition AST.hpp:712
Switch Statement Node.
Definition AST.hpp:764
Unary Expression Node.
Definition AST.hpp:220
Unsafe Block Statement Node.
Definition AST.hpp:624
Variable Declaration Node.
Definition AST.hpp:410
While Statement Node.
Definition AST.hpp:572
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
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
void emit(OpCode op, int32_t op1=0, int32_t op2=0, int32_t op3=0)
Emit an instruction with operands.
Definition CodeGen.hpp:98
std::unordered_map< std::string, int > structEntries
Struct name -> index in structs.
Definition CodeGen.hpp:60
int32_t operand1
First operand.
Definition CodeGen.hpp:23
int32_t operand2
Second operand.
Definition CodeGen.hpp:24
Instruction(OpCode op, int32_t op1=0, int32_t op2=0, int32_t op3=0)
Definition CodeGen.hpp:33
int32_t operand3
Third operand.
Definition CodeGen.hpp:25
OpCode op
Operation code.
Definition CodeGen.hpp:22
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