103 lines
3.4 KiB
C++
103 lines
3.4 KiB
C++
#include "codegen.h"
|
|
#include <string>
|
|
#include <vector>
|
|
#include <iostream>
|
|
|
|
std::string generateAssembly(const CompilerState& state) {
|
|
std::string result;
|
|
|
|
result += "global main\n";
|
|
result += "extern printf\n";
|
|
result += "extern GetAsyncKeyState\n\n";
|
|
|
|
result += "section .data\n";
|
|
for (const auto& v : state.variables) {
|
|
result += " " + v.first + " dd " + std::to_string(v.second) + "\n";
|
|
}
|
|
result += " fmt db '%d', 10, 0\n";
|
|
result += " pause_msg db 'Nacisnij ESC aby zamknac...', 10, 0\n\n";
|
|
|
|
result += "section .text\n";
|
|
|
|
// --- FUNKCJE ---
|
|
for (const auto& func : state.functions) {
|
|
result += func.first + ":\n";
|
|
result += " sub rsp, 40\n";
|
|
|
|
for (const std::string& cmd : func.second) {
|
|
|
|
result += " ; CMD: " + cmd + "\n";
|
|
|
|
if (cmd.find("PRINT:") == 0) {
|
|
std::string varName = cmd.substr(6);
|
|
if (state.variables.count(varName)) {
|
|
result += " mov edx, [" + varName + "]\n";
|
|
result += " lea rcx, [rel fmt]\n";
|
|
result += " call printf\n";
|
|
}
|
|
}
|
|
else if (cmd.find("IF:") == 0) {
|
|
int ifIndex = std::stoi(cmd.substr(3));
|
|
if (ifIndex >= 0 && ifIndex < state.ifBlocks.size()) {
|
|
const auto& ifBlock = state.ifBlocks[ifIndex];
|
|
|
|
if (state.variables.count(ifBlock.conditionVar)) {
|
|
std::string labelSkip = "skip_if_" + std::to_string(ifIndex);
|
|
|
|
result += " ; --- IF START [" + ifBlock.conditionVar + "] ---\n";
|
|
result += " mov eax, [" + ifBlock.conditionVar + "]\n";
|
|
|
|
result += " test eax, eax\n";
|
|
result += " jz " + labelSkip + "\n";
|
|
|
|
for (const std::string& innerPrint : ifBlock.prints) {
|
|
if (state.variables.count(innerPrint)) {
|
|
result += " mov edx, [" + innerPrint + "]\n";
|
|
result += " lea rcx, [rel fmt]\n";
|
|
result += " call printf\n";
|
|
}
|
|
}
|
|
result += labelSkip + ":\n";
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
result += " add rsp, 40\n";
|
|
result += " ret\n\n";
|
|
}
|
|
// ==main==
|
|
result += "main:\n";
|
|
result += " sub rsp, 40\n";
|
|
|
|
for (const std::string& call : state.printCalls) {
|
|
if (call.find("CALL_") == 0) {
|
|
std::string funcName = call.substr(5);
|
|
if (state.functions.count(funcName)) {
|
|
result += " call " + funcName + "\n";
|
|
}
|
|
}
|
|
}
|
|
|
|
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";
|
|
}
|
|
}
|
|
|
|
|
|
result += " lea rcx, [rel pause_msg]\n";
|
|
result += " call printf\n";
|
|
result += "pause_loop:\n";
|
|
result += " mov ecx, 27\n";
|
|
result += " call GetAsyncKeyState\n";
|
|
result += " test ax, 8000h\n";
|
|
result += " jz pause_loop\n";
|
|
result += " add rsp, 40\n";
|
|
result += " ret\n";
|
|
|
|
return result;
|
|
}
|