Phasor 3.1.1
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#include <Value.hpp>
4#include "../ISA/ISA.hpp"
5#include <cstdint>
6#include <map>
7#include <string>
8#include <vector>
9
10#include <platform.h>
11
12namespace Phasor
13{
18{
20 int32_t operand1;
21 int32_t operand2;
22 int32_t operand3;
23
24 // Default constructor
26 {
27 }
28
29 // Full constructor
30 Instruction(OpCode op, int32_t op1 = 0, int32_t op2 = 0, int32_t op3 = 0)
31 : op(op), operand1(op1), operand2(op2), operand3(op3)
32 {
33 }
34};
35
38{
39 std::string name;
42 std::vector<std::string> fieldNames;
43};
44
47{
48 std::vector<Instruction> instructions;
49 std::vector<Value> constants;
50 std::map<std::string, int> variables;
51 std::map<std::string, int> functionEntries;
52 std::map<std::string, int> functionParamCounts;
53 int nextVarIndex = 0;
54
55 // Struct section (planned usage by future struct codegen)
56 std::vector<StructInfo> structs;
57 std::map<std::string, int> structEntries;
58
60 int addConstant(const Value &value)
61 {
62 constants.push_back(value);
63 return static_cast<int>(constants.size()) - 1;
64 }
65
67 int getOrCreateVar(const std::string &name)
68 {
69 auto it = variables.find(name);
70 if (it != variables.end())
71 {
72 return it->second;
73 }
74 int index = nextVarIndex++;
75 variables[name] = index;
76 return index;
77 }
78
80 void emit(OpCode op, int32_t op1 = 0, int32_t op2 = 0, int32_t op3 = 0)
81 {
82 instructions.push_back(Instruction(op, op1, op2, op3));
83 }
84};
85
90{
91 public:
101 Bytecode generate(const AST::Program &program, const std::map<std::string, int> &existingVars = {},
102 int nextVarIdx = 0, bool replMode = false);
103
104 private:
106 bool isRepl = false;
107 // Inferred types for variables (simple, flow-insensitive mapping)
108 std::map<std::string, ValueType> inferredTypes;
109
110 // Register allocation for v2.0
111 uint8_t nextRegister = 0;
112 std::vector<bool> registerInUse;
113
116 {
117 for (size_t i = 0; i < MAX_REGISTERS; i++)
118 {
119 if (i >= registerInUse.size())
120 {
121 registerInUse.resize(i + 1, false);
122 }
123 if (!registerInUse[i])
124 {
125 registerInUse[i] = true;
126 return static_cast<uint8_t>(i);
127 }
128 }
129 throw std::runtime_error("Out of registers");
130 }
131
133 void freeRegister(uint8_t reg)
134 {
135 if (reg < registerInUse.size())
136 {
137 registerInUse[reg] = false;
138 }
139 }
140
143 {
144 registerInUse.clear();
145 nextRegister = 0;
146 }
147
149 bool isLiteralExpression(const AST::Expression *expr, Value &outValue);
150
155 ValueType inferExpressionType(const AST::Expression *expr, bool &known);
156
157 void generateStatement(const AST::Statement *stmt);
158 void generateExpression(const AST::Expression *expr);
159 void generateVarDecl(const AST::VarDecl *varDecl);
160 void generateExpressionStmt(const AST::ExpressionStmt *exprStmt);
161 void generatePrintStmt(const AST::PrintStmt *printStmt);
162 void generateImportStmt(const AST::ImportStmt *importStmt);
163 void generateExportStmt(const AST::ExportStmt *exportStmt);
164 void generateNumberExpr(const AST::NumberExpr *numExpr);
165 void generateStringExpr(const AST::StringExpr *strExpr);
166 void generateIdentifierExpr(const AST::IdentifierExpr *identExpr);
167 void generateUnaryExpr(const AST::UnaryExpr *unaryExpr);
168 void generateCallExpr(const AST::CallExpr *callExpr);
169 void generateBinaryExpr(const AST::BinaryExpr *binExpr);
170 void generateBlockStmt(const AST::BlockStmt *blockStmt);
171 void generateIfStmt(const AST::IfStmt *ifStmt);
172 void generateWhileStmt(const AST::WhileStmt *whileStmt);
173 void generateForStmt(const AST::ForStmt *forStmt);
174 void generateReturnStmt(const AST::ReturnStmt *returnStmt);
176 const AST::UnsafeBlockStmt *unsafeStmt);
177 void generateFunctionDecl(const AST::FunctionDecl *funcDecl);
178 void generateBooleanExpr(const AST::BooleanExpr *boolExpr);
179 void generateNullExpr(const AST::NullExpr *nullExpr);
181 const AST::AssignmentExpr *assignExpr);
182 void generateStructDecl(const AST::StructDecl *decl);
185 void generatePostfixExpr(const AST::PostfixExpr *expr);
186 void generateBreakStmt();
188 void generateSwitchStmt(const AST::SwitchStmt *switchStmt);
189
190 // Loop context for break/continue
191 std::vector<int> loopStartStack; // Stack of loop start positions
192 std::vector<std::vector<int>> breakJumpsStack; // Stack of break jump positions to patch
193 std::vector<std::vector<int>> continueJumpsStack; // Stack of continue jump positions to patch
194};
195
196} // namespace Phasor
Code generator for Phasor VM.
Definition CodeGen.hpp:90
void generateForStmt(const AST::ForStmt *forStmt)
Generate bytecode from For Statement.
Definition CodeGen.cpp:778
Bytecode bytecode
Generated bytecode.
Definition CodeGen.hpp:105
void generateCallExpr(const AST::CallExpr *callExpr)
Generate bytecode from Call Expression.
Definition CodeGen.cpp:347
std::map< std::string, ValueType > inferredTypes
Definition CodeGen.hpp:108
void generateVarDecl(const AST::VarDecl *varDecl)
Generate bytecode from Variable Declaration.
Definition CodeGen.cpp:220
void generateIfStmt(const AST::IfStmt *ifStmt)
Generate bytecode from If Statement.
Definition CodeGen.cpp:715
std::vector< std::vector< int > > breakJumpsStack
Definition CodeGen.hpp:192
void generateUnaryExpr(const AST::UnaryExpr *unaryExpr)
Generate bytecode from Unary Expression.
Definition CodeGen.cpp:323
void generatePostfixExpr(const AST::PostfixExpr *expr)
Definition CodeGen.cpp:1027
uint8_t nextRegister
Next available register.
Definition CodeGen.hpp:111
void generateStructInstanceExpr(const AST::StructInstanceExpr *expr)
Definition CodeGen.cpp:982
void generateNullExpr(const AST::NullExpr *nullExpr)
Generate bytecode from Null Expression.
Definition CodeGen.cpp:927
void generateFunctionDecl(const AST::FunctionDecl *funcDecl)
Generate bytecode from Function Declaration.
Definition CodeGen.cpp:881
void generateWhileStmt(const AST::WhileStmt *whileStmt)
Generate bytecode from While Statement.
Definition CodeGen.cpp:740
void generateSwitchStmt(const AST::SwitchStmt *switchStmt)
Definition CodeGen.cpp:1109
Bytecode generate(const AST::Program &program, const std::map< std::string, int > &existingVars={}, int nextVarIdx=0, bool replMode=false)
Generate bytecode from program.
Definition CodeGen.cpp:7
void generateBlockStmt(const AST::BlockStmt *blockStmt)
Generate bytecode from Block Statement.
Definition CodeGen.cpp:707
void generateBooleanExpr(const AST::BooleanExpr *boolExpr)
Generate bytecode from Boolean Expression.
Definition CodeGen.cpp:915
void generateStructDecl(const AST::StructDecl *decl)
Definition CodeGen.cpp:1067
uint8_t allocateRegister()
Allocate a new register.
Definition CodeGen.hpp:115
std::vector< int > loopStartStack
Definition CodeGen.hpp:191
void generatePrintStmt(const AST::PrintStmt *printStmt)
Generate bytecode from Print Statement.
Definition CodeGen.cpp:268
void generateStringExpr(const AST::StringExpr *strExpr)
Generate bytecode from String Expression.
Definition CodeGen.cpp:311
void freeRegister(uint8_t reg)
Free a register.
Definition CodeGen.hpp:133
ValueType inferExpressionType(const AST::Expression *expr, bool &known)
Simple expression type inference (conservative).
Definition CodeGen.cpp:62
void generateExpression(const AST::Expression *expr)
Generate bytecode from Expression.
Definition CodeGen.cpp:164
std::vector< std::vector< int > > continueJumpsStack
Definition CodeGen.hpp:193
void generateExportStmt(const AST::ExportStmt *exportStmt)
Generate bytecode from Export Statement.
Definition CodeGen.cpp:280
void generateUnsafeBlockStmt(const AST::UnsafeBlockStmt *unsafeStmt)
Generate bytecode from Unsafe Block Statement.
Definition CodeGen.cpp:876
void generateBinaryExpr(const AST::BinaryExpr *binExpr)
Generate bytecode from Binary Expression.
Definition CodeGen.cpp:454
void generateExpressionStmt(const AST::ExpressionStmt *exprStmt)
Generate bytecode from Expression Statement.
Definition CodeGen.cpp:255
void generateImportStmt(const AST::ImportStmt *importStmt)
Generate bytecode from Import Statement.
Definition CodeGen.cpp:274
void generateStatement(const AST::Statement *stmt)
Generate bytecode from Statement.
Definition CodeGen.cpp:88
bool isLiteralExpression(const AST::Expression *expr, Value &outValue)
Check if expression is a compile-time literal.
Definition CodeGen.cpp:23
void generateIdentifierExpr(const AST::IdentifierExpr *identExpr)
Generate bytecode from Identifier Expression.
Definition CodeGen.cpp:317
bool isRepl
REPL mode.
Definition CodeGen.hpp:106
void generateAssignmentExpr(const AST::AssignmentExpr *assignExpr)
Generate bytecode from Assignment Expression.
Definition CodeGen.cpp:932
void generateNumberExpr(const AST::NumberExpr *numExpr)
Generate bytecode from Numeral Expression.
Definition CodeGen.cpp:286
std::vector< bool > registerInUse
Track which registers are in use.
Definition CodeGen.hpp:112
void resetRegisters()
Reset register allocator.
Definition CodeGen.hpp:142
void generateFieldAccessExpr(const AST::FieldAccessExpr *expr)
Definition CodeGen.cpp:1015
void generateReturnStmt(const AST::ReturnStmt *returnStmt)
Generate bytecode from Return Statement.
Definition CodeGen.cpp:863
A value in the Phasor VM.
Definition Value.hpp:67
The Phasor Programming Language and Runtime.
Definition AST.hpp:11
OpCode
Definition ISA.hpp:12
@ HALT
Stop execution.
Definition ISA.hpp:75
ValueType
Runtime value types for the VM.
Definition Value.hpp:51
#define MAX_REGISTERS
Definition platform.h:19
Assignment Expression Node.
Definition AST.hpp:385
Binary Expression Node.
Definition AST.hpp:251
Block Statement Node.
Definition AST.hpp:489
Boolean Expression Node.
Definition AST.hpp:137
Call Expression Node.
Definition AST.hpp:365
Export Statement Node.
Definition AST.hpp:475
Expression Node.
Definition AST.hpp:53
Expression Statement Node.
Definition AST.hpp:422
Field Access Expression Node.
Definition AST.hpp:714
For Statement Node.
Definition AST.hpp:583
Function Declaration Node.
Definition AST.hpp:624
Identifier Expression Node.
Definition AST.hpp:124
If Statement Node.
Definition AST.hpp:539
Import Statement Node.
Definition AST.hpp:462
NULL Expression Node.
Definition AST.hpp:150
Numeral Expression Node.
Definition AST.hpp:97
Postfix Expression Node.
Definition AST.hpp:193
Print Statement Node.
Definition AST.hpp:435
Program Node.
Definition AST.hpp:63
Return Statement Node.
Definition AST.hpp:506
Statement Node.
Definition AST.hpp:58
String Expression Node.
Definition AST.hpp:110
Struct Declaration Node.
Definition AST.hpp:671
Struct Instance Expression Node.
Definition AST.hpp:692
Switch Statement Node.
Definition AST.hpp:744
Unary Expression Node.
Definition AST.hpp:219
Unsafe Block Statement Node.
Definition AST.hpp:610
Variable Declaration Node.
Definition AST.hpp:406
While Statement Node.
Definition AST.hpp:564
Complete bytecode structure.
Definition CodeGen.hpp:47
std::vector< StructInfo > structs
List of struct descriptors.
Definition CodeGen.hpp:56
std::vector< Value > constants
Constant pool.
Definition CodeGen.hpp:49
std::map< std::string, int > functionEntries
Function name -> instruction index mapping.
Definition CodeGen.hpp:51
int nextVarIndex
Next available variable index.
Definition CodeGen.hpp:53
std::map< std::string, int > functionParamCounts
Function name -> parameter count.
Definition CodeGen.hpp:52
int getOrCreateVar(const std::string &name)
Get or create a variable index.
Definition CodeGen.hpp:67
std::map< std::string, int > structEntries
Struct name -> index in structs.
Definition CodeGen.hpp:57
std::map< std::string, int > variables
Variable name -> index mapping.
Definition CodeGen.hpp:50
int addConstant(const Value &value)
Add a constant to the pool and return its index.
Definition CodeGen.hpp:60
void emit(OpCode op, int32_t op1=0, int32_t op2=0, int32_t op3=0)
Emit an instruction with operands.
Definition CodeGen.hpp:80
std::vector< Instruction > instructions
List of instructions.
Definition CodeGen.hpp:48
Instruction with up to 5 operands Format: instruction operand1, operand2, operand3 Each instruction u...
Definition CodeGen.hpp:18
int32_t operand1
First operand.
Definition CodeGen.hpp:20
int32_t operand2
Second operand.
Definition CodeGen.hpp:21
Instruction(OpCode op, int32_t op1=0, int32_t op2=0, int32_t op3=0)
Definition CodeGen.hpp:30
int32_t operand3
Third operand.
Definition CodeGen.hpp:22
OpCode op
Operation code.
Definition CodeGen.hpp:19
Struct metadata stored alongside bytecode (struct section).
Definition CodeGen.hpp:38
int firstConstIndex
Index into constants for the first default value.
Definition CodeGen.hpp:40
std::vector< std::string > fieldNames
Field names in declaration order.
Definition CodeGen.hpp:42
int fieldCount
Number of fields in this struct.
Definition CodeGen.hpp:41
std::string name
Struct name.
Definition CodeGen.hpp:39