#include "codegen.h" #include #include #include // Pomocnicza funkcja: sprawdza czy string to czysta liczba bool isNumber(const std::string& s) { if (s.empty()) return false; size_t start = (s[0] == '-') ? 1 : 0; for (size_t i = start; i < s.length(); i++) { if (!isdigit(s[i])) return false; } return true; } // Zamienia nazwę zmiennej na adres pamięci [rbp-X] lub liczbę std::string getVarLocation(const std::string& name, const std::map& locals) { std::string cleanName = name; // Usuwamy ewentualne spacje size_t first = cleanName.find_first_not_of(" \t"); if (first != std::string::npos) cleanName = cleanName.substr(first); size_t last = cleanName.find_last_not_of(" \t"); if (last != std::string::npos) cleanName = cleanName.substr(0, last + 1); if (cleanName.empty()) return "0"; if (isNumber(cleanName)) return cleanName; if (cleanName == "RAX") return "eax"; if (locals.count(cleanName)) { int offset = locals.at(cleanName); return "[rbp-" + std::to_string(offset) + "]"; } // Zwracamy oryginał (jeśli to np. nazwa etykiety), ale to zazwyczaj błąd dla zmiennych return cleanName; } std::string generateAssembly(const CompilerState& state) { // 1. NAGŁÓWEK I DEKLARACJE EXTERN std::string result = "default rel\n"; result += "global main\n"; result += "extern printf\n"; result += "extern getchar\n"; result += "extern _getch\n"; result += "extern rand\n"; result += "extern srand\n"; result += "extern time\n"; result += "extern MessageBoxA\n"; // 2. SEKCJA DATA (Tylko raz!) result += "section .data\n"; result += " fmt_int db \"%lld\", 10, 0\n"; // Format dla liczb result += " fmt_str db \"%s\", 10, 0\n"; // Format dla stringów // Zrzucamy stringi: ETYKIETA db "TRESC", 0 for (const auto& p : state.stringLiterals) { // p.first -> Etykieta (np. str_0) // p.second -> Treść (np. Hello World) result += " " + p.first + " db \"" + p.second + "\", 0\n"; } // 3. SEKCJA TEXT (Kod programu) result += "section .text\n"; for (const auto& pair : state.functions) { const Function& func = pair.second; result += func.name + ":\n"; result += " push rbp\n"; result += " mov rbp, rsp\n"; result += " sub rsp, 288\n"; std::map stackMap; int currentStack = 8; // ARGUMENTY FUNKCJI if (func.args.size() > 0) { stackMap[func.args[0]] = currentStack; result += " mov [rbp-" + std::to_string(currentStack) + "], rcx ; arg " + func.args[0] + "\n"; currentStack += 8; } if (func.args.size() > 1) { stackMap[func.args[1]] = currentStack; result += " mov [rbp-" + std::to_string(currentStack) + "], rdx ; arg " + func.args[1] + "\n"; currentStack += 8; } // GENEROWANIE INSTRUKCJI for (const auto& instr : func.instructions) { // Rezerwacja miejsca na stosie bool isWriteOp = (instr.type == OpType::ASSIGN || instr.type == OpType::ADD || instr.type == OpType::EQ || instr.type == OpType::SUB || instr.type == OpType::MUL || instr.type == OpType::DIV || instr.type == OpType::MOD || instr.type == OpType::LOGIC_AND || instr.type == OpType::LOGIC_OR || instr.type == OpType::MSGBOX || instr.type == OpType::ARRAY_DECLARE || instr.type == OpType::ARRAY_SET); if (isWriteOp && stackMap.find(instr.arg1) == stackMap.end() && instr.arg1 != "RAX") { stackMap[instr.arg1] = currentStack; currentStack += 8; } switch (instr.type) { case OpType::ASSIGN: { std::string src = instr.arg2; // ODCZYT TABLICY: x = t[i] if (instr.arg3.find("ARRAY_IDX:") == 0) { std::string indexStr = instr.arg3.substr(10); // Pobierz "i" std::string arrName = instr.arg2; // Pobierz "t" std::string dst = getVarLocation(instr.arg1, stackMap); int baseOffset = stackMap[arrName]; // Ładujemy indeks do RCX if (isNumber(indexStr)) result += " mov rcx, " + indexStr + "\n"; else result += " mov rcx, " + getVarLocation(indexStr, stackMap) + "\n"; result += " imul rcx, 8\n"; // index * 8 // Obliczamy adres result += " mov rdx, rbp\n"; result += " sub rdx, " + std::to_string(baseOffset) + "\n"; result += " sub rdx, rcx\n"; // Odczytujemy wartość z tablicy do RAX result += " mov rax, [rdx]\n"; // Zapisujemy do zmiennej docelowej result += " mov " + dst + ", rax\n"; } else if (instr.arg3 == "STRING") { // Przypisanie stringa: ładujemy ADRES (LEA) result += " lea rax, [rel " + src + "]\n"; std::string dst = getVarLocation(instr.arg1, stackMap); // Zapisujemy adres w zmiennej lokalnej (wskaźnik 64-bit qword) result += " mov qword " + dst + ", rax\n"; } else { // Zwykłe przypisanie liczby std::string srcLoc = getVarLocation(instr.arg2, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); if (isNumber(src)) { result += " mov eax, " + src + "\n"; } else { result += " mov eax, " + srcLoc + "\n"; } result += " mov " + dst + ", eax\n"; } break; } case OpType::ADD: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " add eax, " + op2 + "\n"; result += " mov " + dst + ", eax\n"; break; } case OpType::SUB: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " sub eax, " + op2 + "\n"; result += " mov " + dst + ", eax\n"; break; } case OpType::MUL: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " imul eax, " + op2 + "\n"; result += " mov " + dst + ", eax\n"; break; } case OpType::DIV: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " cdq\n"; if (isdigit(op2[0]) || op2[0] == '-') { result += " mov ecx, " + op2 + "\n"; result += " idiv ecx\n"; } else { result += " idiv dword " + op2 + "\n"; } result += " mov " + dst + ", eax\n"; break; } case OpType::MOD: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " cdq\n"; if (isdigit(op2[0]) || op2[0] == '-') { result += " mov ecx, " + op2 + "\n"; result += " idiv ecx\n"; } else { result += " idiv dword " + op2 + "\n"; } result += " mov " + dst + ", edx\n"; // Reszta break; } case OpType::EQ: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " cmp eax, " + op2 + "\n"; result += " sete al\n"; result += " movzx eax, al\n"; result += " mov " + dst + ", eax\n"; break; } case OpType::LOGIC_AND: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " cmp eax, 0\n"; result += " setne al\n"; if (isdigit(op2[0])) result += " mov ecx, " + op2 + "\n"; else result += " mov ecx, " + op2 + "\n"; result += " cmp ecx, 0\n"; result += " setne cl\n"; result += " and al, cl\n"; result += " movzx eax, al\n"; result += " mov " + dst + ", eax\n"; break; } case OpType::LOGIC_OR: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); std::string dst = getVarLocation(instr.arg1, stackMap); result += " mov eax, " + op1 + "\n"; result += " cmp eax, 0\n"; result += " setne al\n"; if (isdigit(op2[0])) result += " mov ecx, " + op2 + "\n"; else result += " mov ecx, " + op2 + "\n"; result += " cmp ecx, 0\n"; result += " setne cl\n"; result += " or al, cl\n"; result += " movzx eax, al\n"; result += " mov " + dst + ", eax\n"; break; } case OpType::JMP_FALSE: { std::string condRaw = instr.arg2; size_t eqPos = condRaw.find("=="); if (eqPos != std::string::npos) { std::string leftStr = condRaw.substr(0, eqPos); std::string rightStr = condRaw.substr(eqPos + 2); std::string op1 = getVarLocation(leftStr, stackMap); std::string op2 = getVarLocation(rightStr, stackMap); result += " mov eax, " + op1 + "\n"; result += " cmp eax, " + op2 + "\n"; result += " jne " + instr.arg1 + "\n"; } else { std::string cond = getVarLocation(condRaw, stackMap); result += " mov eax, " + cond + "\n"; result += " test eax, eax\n"; result += " je " + instr.arg1 + "\n"; } break; } case OpType::JMP: { result += " jmp " + instr.arg1 + "\n"; break; } case OpType::ARRAY_DECLARE: { std::string name = instr.arg1; int size = std::stoi(instr.arg2); // Rezerwujemy miejsce dla całej tablicy // t[0] będzie pod aktualnym currentStack stackMap[name] = currentStack; // Przesuwamy wskaźnik stosu o (rozmiar * 8 bajtów) // Zakładamy, że każdy element to 64-bit (dla bezpieczeństwa i prostoty assemblera) currentStack += (size * 8); // W ASM nie musimy generować żadnego kodu! (Miejsce już jest z sub rsp, 256) // O ile tablica mieści się w tych 256 bajtach. // Jeśli chcesz być PRO: dodaj na początku funkcji "sub rsp, (currentStack + zapas)" break; } case OpType::ARRAY_SET: { std::string arrName = instr.arg1; // t std::string indexStr = instr.arg2; // i std::string valStr = instr.arg3; // val // 1. Obliczamy wartość do wpisania if (isNumber(valStr)) { result += " mov rax, " + valStr + "\n"; } else { std::string valLoc = getVarLocation(valStr, stackMap); // Jeśli to zmienna ze stosu, to movsxd (rozszerzenie znaku) lub mov result += " mov rax, " + valLoc + "\n"; // Zakładamy 64-bit (lub eax dla 32) } int baseOffset = stackMap[arrName]; // Ładujemy indeks do RCX if (isNumber(indexStr)) { result += " mov rcx, " + indexStr + "\n"; } else { std::string idxLoc = getVarLocation(indexStr, stackMap); result += " mov rcx, " + idxLoc + "\n"; // Pobierz indeks ze zmiennej } // Obliczamy przesunięcie bajtowe: index * 8 result += " imul rcx, 8\n"; // Ponieważ adres to RBP - (base + index*8) -> RBP - base - index*8 // Musimy to sprytnie zmontować. // Obliczmy finalny adres w RDX. result += " mov rdx, rbp\n"; result += " sub rdx, " + std::to_string(baseOffset) + "\n"; // RDX = adres t[0] result += " sub rdx, rcx\n"; // RDX = adres t[i] // Zapisujemy wartość (RAX) pod adres (RDX) result += " mov [rdx], rax\n"; break; } case OpType::LABEL: { result += instr.arg1 + ":\n"; break; } case OpType::PRINT: { // Instrukcja PRINT zwykła (liczba) std::string val = getVarLocation(instr.arg1, stackMap); result += " mov edx, " + val + "\n"; result += " lea rcx, [rel fmt_int]\n"; result += " xor eax, eax\n"; result += " call printf\n"; break; } case OpType::PRINT_STRING: { std::string target = instr.arg1; if (target.rfind("str_", 0) == 0) { result += " lea rdx, [rel " + target + "]\n"; } else { std::string val = getVarLocation(target, stackMap); result += " mov rdx, " + val + "\n"; } result += " lea rcx, [rel fmt_str]\n"; result += " xor eax, eax\n"; result += " call printf\n"; break; } case OpType::CALL: { if (instr.arg1 == "input") { result += " call _getch\n"; break; } if (instr.arg1 == "read_key") { result += " call _getch\n"; break; } if (instr.arg1 == "sys_seed") { result += " mov rcx, 0\n"; result += " call time\n"; result += " mov rcx, rax\n"; result += " call srand\n"; break; } if (instr.arg1 == "sys_rand") { result += " call rand\n"; break; } // Standardowe wywołanie funkcji std::string argsRaw = instr.arg2; std::vector callArgs; if (!argsRaw.empty()) { size_t comma = argsRaw.find(','); if (comma != std::string::npos) { callArgs.push_back(argsRaw.substr(0, comma)); callArgs.push_back(argsRaw.substr(comma + 1)); } else { callArgs.push_back(argsRaw); } } if (callArgs.size() > 1) { std::string val = getVarLocation(callArgs[1], stackMap); if (isNumber(val)) result += " mov rdx, " + val + "\n"; else result += " movsxd rdx, dword " + val + "\n"; } if (callArgs.size() > 0) { std::string val = getVarLocation(callArgs[0], stackMap); if (isNumber(val)) result += " mov rcx, " + val + "\n"; else result += " movsxd rcx, dword " + val + "\n"; } result += " call " + instr.arg1 + "\n"; break; } case OpType::RETURN: { std::string val = getVarLocation(instr.arg1, stackMap); if (!val.empty() && val != ";") { result += " mov eax, " + val + "\n"; } result += " leave\n"; result += " ret\n"; break; } case OpType::MSGBOX: { // Konwencja Windows x64: // RCX = HWND (0 = brak okna nadrzędnego) // RDX = Treść (Text) // R8 = Tytuł (Caption) // R9 = Typ (0 = przycisk OK) std::string title = instr.arg1; std::string text = instr.arg2; // --- 1. Ustawiamy RDX (Treść) --- if (text.find("str_") == 0) { // Jeśli to literał (np. str_5), ładujemy jego adres (LEA) result += " lea rdx, [rel " + text + "]\n"; } else { // Jeśli to zmienna, pobieramy jej wartość ze stosu (która jest adresem) std::string loc = getVarLocation(text, stackMap); result += " mov rdx, " + loc + "\n"; } // --- 2. Ustawiamy R8 (Tytuł) --- if (title.find("str_") == 0) { result += " lea r8, [rel " + title + "]\n"; } else { std::string loc = getVarLocation(title, stackMap); result += " mov r8, " + loc + "\n"; } // --- 3. Pozostałe argumenty (Stałe) --- result += " mov rcx, 0\n"; // HWND = NULL result += " mov r9, 0\n"; // MB_OK // --- 4. Wywołanie --- // Stos (shadow space) jest już przygotowany na początku funkcji (sub rsp, 256) result += " call MessageBoxA\n"; break; } } } if (func.returnType == "void") { result += " leave\n ret\n"; } result += "\n"; } return result; }