Files
PCCCompiler/PCCcompiler/codegen.cpp
2026-02-06 16:04:23 +01:00

82 lines
2.4 KiB
C++

#include "codegen.h"
#include <string>
#include <vector>
std::string generateAssembly(const CompilerState& state) {
std::string result;
// --- NAG£ÓWEK I SEKCJA DATA ---
result += "global main\n";
result += "extern printf\n";
result += "extern GetAsyncKeyState\n\n";
result += "section .data\n";
// Generowanie zmiennych
for (const auto& v : state.variables) {
result += " " + v.first + " dd " + std::to_string(v.second) + "\n";
}
// Sta³e stringi
result += " fmt db '%d', 10, 0\n";
result += " pause_msg db 'Nacisnij ESC aby zamknac...', 10, 0\n\n";
result += "section .text\n";
// --- DEFINICJE FUNKCJI U¯YTKOWNIKA ---
for (const auto& func : state.functions) {
result += func.first + ":\n";
result += " sub rsp, 40\n"; // Shadow space
// Printy wewn¹trz funkcji
for (const std::string& var : func.second) {
if (state.variables.count(var)) {
result += " mov edx, [" + var + "]\n";
result += " lea rcx, [rel fmt]\n";
result += " call printf\n";
}
}
result += " add rsp, 40\n";
result += " ret\n\n";
}
// --- FUNKCJA MAIN ---
result += "main:\n";
result += " sub rsp, 40\n";
// Globalne printy (poza funkcjami)
for (const std::string& var : state.globalPrints) {
if (state.variables.count(var)) {
result += " mov edx, [" + var + "]\n";
result += " lea rcx, [rel fmt]\n";
result += " call printf\n";
}
}
// Wywo³ania funkcji zdefiniowanych wczeœniej
for (const std::string& call : state.printCalls) {
if (call.find("CALL_") == 0) {
std::string funcName = call.substr(5); // Usuñ prefiks "CALL_"
if (state.functions.count(funcName)) {
result += " call " + funcName + "\n";
}
}
}
// --- PAUSE LOOP (Czekanie na ESC) ---
result += " lea rcx, [rel pause_msg]\n";
result += " call printf\n";
result += "pause_loop:\n";
result += " mov ecx, 27\n"; // VK_ESCAPE
result += " call GetAsyncKeyState\n";
result += " test ax, 8000h\n";
result += " jz pause_loop\n";
// Wyjœcie z programu
result += " add rsp, 40\n";
result += " ret\n";
return result;
}