From 3916b4ff7ad1e68884a0e2cb9757d7c05fc17f8b Mon Sep 17 00:00:00 2001 From: mmichlol Date: Sat, 7 Feb 2026 19:44:03 +0100 Subject: [PATCH] String Update --- PCCcompiler/codegen.cpp | 321 +++++++++++++++-------------------- PCCcompiler/compiler_types.h | 51 ++++-- PCCcompiler/parser.cpp | 104 +++++++----- 3 files changed, 232 insertions(+), 244 deletions(-) diff --git a/PCCcompiler/codegen.cpp b/PCCcompiler/codegen.cpp index fe91189..5866b71 100644 --- a/PCCcompiler/codegen.cpp +++ b/PCCcompiler/codegen.cpp @@ -37,7 +37,8 @@ std::string getVarLocation(const std::string& name, const std::map 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; @@ -66,7 +73,7 @@ std::string generateAssembly(const CompilerState& state) { std::map stackMap; int currentStack = 8; - // 1. ARGUMENTY + // 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"; @@ -78,11 +85,10 @@ std::string generateAssembly(const CompilerState& state) { currentStack += 8; } - // 2. INSTRUKCJE + // GENEROWANIE INSTRUKCJI for (const auto& instr : func.instructions) { - // Rezerwacja miejsca dla nowych zmiennych (wynikowych) - // Dodajemy tu OpType::SUB i OpType::MUL + // Rezerwacja miejsca na stosie bool isWriteOp = (instr.type == OpType::ASSIGN || instr.type == OpType::ADD || instr.type == OpType::EQ || @@ -90,7 +96,7 @@ std::string generateAssembly(const CompilerState& state) { instr.type == OpType::MUL || instr.type == OpType::DIV || instr.type == OpType::MOD || - instr.type == OpType::LOGIC_AND || + instr.type == OpType::LOGIC_AND || instr.type == OpType::LOGIC_OR); if (isWriteOp && stackMap.find(instr.arg1) == stackMap.end() && instr.arg1 != "RAX") { @@ -102,14 +108,23 @@ std::string generateAssembly(const CompilerState& state) { case OpType::ASSIGN: { std::string src = instr.arg2; 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); - result += " mov eax, " + srcLoc + "\n"; + + if (isNumber(src)) { + result += " mov eax, " + src + "\n"; + } + else { + result += " mov eax, " + srcLoc + "\n"; + } result += " mov " + dst + ", eax\n"; } break; @@ -124,29 +139,55 @@ std::string generateAssembly(const CompilerState& state) { break; } case OpType::SUB: { - // a = b - c 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"; // sub = odejmowanie + result += " sub eax, " + op2 + "\n"; result += " mov " + dst + ", eax\n"; break; } case OpType::MUL: { - // a = b * c 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"; - // Mnożenie w x86 jest specyficzne: imul eax, operand - // Wynik ląduje w eax (i edx jeśli duży, ale ignorujemy nadmiar dla prostoty) 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); @@ -158,34 +199,59 @@ std::string generateAssembly(const CompilerState& state) { 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: { - // PARSOWANIE WARUNKU: np. "suma == 30" lub "test" std::string condRaw = instr.arg2; size_t eqPos = condRaw.find("=="); - if (eqPos != std::string::npos) { - // Mamy porównanie w IFie (a == b) 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 + " ; jump if NOT equal\n"; + result += " jne " + instr.arg1 + "\n"; } else { - // Zwykła zmienna boolowska (if test) std::string cond = getVarLocation(condRaw, stackMap); result += " mov eax, " + cond + "\n"; result += " test eax, eax\n"; - result += " jz " + instr.arg1 + " ; jump if zero\n"; + result += " jz " + instr.arg1 + "\n"; } break; } case OpType::JMP: { - // Skok bezwarunkowy (używany na końcu pętli while) result += " jmp " + instr.arg1 + "\n"; break; } @@ -193,50 +259,54 @@ std::string generateAssembly(const CompilerState& state) { result += instr.arg1 + ":\n"; break; } - case OpType::RETURN: { + case OpType::PRINT: { + // Instrukcja PRINT zwykła (liczba) std::string val = getVarLocation(instr.arg1, stackMap); - if (val.empty() || val == ";"); - else { - result += " mov eax, " + val + " ; return value\n"; - } - result += " leave\n"; - result += " ret\n"; + result += " mov edx, " + val + "\n"; + result += " lea rcx, [rel fmt_int]\n"; + result += " call printf\n"; break; } - case OpType::PRINT: { - if (instr.arg2 == "STRING") { - result += " lea rdx, [rel " + instr.arg1 + "]\n"; - result += " lea rcx, [rel fmt_str]\n"; - result += " call printf\n"; + case OpType::PRINT_STRING: { + // Instrukcja PRINT_STRING (tekst) + std::string target = instr.arg1; + if (target.find("str_") == 0) { + // Literał: print("tekst") + result += " lea rdx, [rel " + target + "]\n"; } else { - std::string val = getVarLocation(instr.arg1, stackMap); - result += " mov edx, " + val + "\n"; - result += " lea rcx, [rel fmt_int]\n"; - result += " call printf\n"; + // Zmienna: print(s) -> s trzyma adres + std::string val = getVarLocation(target, stackMap); + result += " mov rdx, " + val + "\n"; } + result += " lea rcx, [rel fmt_str]\n"; + result += " call printf\n"; break; } case OpType::CALL: { - // Parsowanie argumentów - std::string argsRaw = instr.arg2; - std::vector callArgs; - // --- SPECJALNE FUNKCJE SYSTEMOWE --- - - // 1. input() - czeka na ENTER (stare) if (instr.arg1 == "input") { result += " call getchar\n"; break; } - - // 2. read_key() - zwraca kod wciśniętego klawisza (NOWOŚĆ) if (instr.arg1 == "read_key") { - result += " call _getch\n"; // Zwraca kod znaku w EAX - // Jeśli to klawisz specjalny (strzałki), _getch zwraca 0 lub 224, - // a potem trzeba wywołać go drugi raz. - // Na razie zróbmy prosto: zwracamy to co zwrócił pierwszy _getch. + 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) { @@ -247,137 +317,26 @@ std::string generateAssembly(const CompilerState& state) { callArgs.push_back(argsRaw); } } - - // Obsługa RDX (arg 2) if (callArgs.size() > 1) { std::string val = getVarLocation(callArgs[1], stackMap); - if (isNumber(val)) { - // Jeśli liczba: mov rdx, 100 - result += " mov rdx, " + val + "\n"; - } - else { - // Jeśli zmienna/pamięć: movsxd rdx, dword [rbp-8] - result += " movsxd rdx, dword " + val + "\n"; - } + if (isNumber(val)) result += " mov rdx, " + val + "\n"; + else result += " movsxd rdx, dword " + val + "\n"; } - - // Obsługa RCX (arg 1) 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"; - } + if (isNumber(val)) result += " mov rcx, " + val + "\n"; + else result += " movsxd rcx, dword " + val + "\n"; } - - // ... wewnątrz case OpType::CALL ... - if (instr.arg1 == "sys_seed") { - result += " mov rcx, 0\n"; - result += " call time\n"; // Pobierz czas - result += " mov rcx, rax\n"; // Czas jako argument dla srand - result += " call srand\n"; // Inicjuj generator - break; - } - if (instr.arg1 == "sys_rand") { - result += " call rand\n"; // Wynik w EAX - break; - } - result += " call " + instr.arg1 + "\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"; // Rozszerza EAX na EDX:EAX (konieczne przed dzieleniem) - - // IDIV nie przyjmuje stałej (np. 10), musi być rejestr - if (isdigit(op2[0]) || op2[0] == '-') { - result += " mov ecx, " + op2 + "\n"; - result += " idiv ecx\n"; + case OpType::RETURN: { + std::string val = getVarLocation(instr.arg1, stackMap); + if (!val.empty() && val != ";") { + result += " mov eax, " + val + "\n"; } - else { - result += " idiv dword " + op2 + "\n"; - } - result += " mov " + dst + ", eax\n"; // Wynik dzielenia - 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"; // Rozszerza EAX - - 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"; // EDX to reszta z dzielenia! - break; - } - case OpType::LOGIC_AND: { - // a && b - // Algorytm: result = (op1 != 0) * (op2 != 0) - // Ale w ASM łatwiej: - // cmp op1, 0 -> setne al - // cmp op2, 0 -> setne bl - // and al, bl - - std::string op1 = getVarLocation(instr.arg2, stackMap); - std::string op2 = getVarLocation(instr.arg3, stackMap); - std::string dst = getVarLocation(instr.arg1, stackMap); - - // Sprawdzamy op1 - result += " mov eax, " + op1 + "\n"; - result += " cmp eax, 0\n"; - result += " setne al\n"; // al = 1 jeśli eax != 0 - - // Sprawdzamy op2 (używamy ECX jako pomocniczy) - if (isdigit(op2[0])) result += " mov ecx, " + op2 + "\n"; - else result += " mov ecx, " + op2 + "\n"; - - result += " cmp ecx, 0\n"; - result += " setne cl\n"; // cl = 1 jeśli ecx != 0 - - // Logiczne AND na bajtach - result += " and al, cl\n"; - - // Zapisujemy wynik (rozszerzamy bajt do dword) - result += " movzx eax, al\n"; - result += " mov " + dst + ", eax\n"; - break; - } - case OpType::LOGIC_OR: { - // a || b - 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"; - - // Logiczne OR - result += " or al, cl\n"; - - result += " movzx eax, al\n"; - result += " mov " + dst + ", eax\n"; + result += " leave\n"; + result += " ret\n"; break; } } @@ -390,4 +349,4 @@ std::string generateAssembly(const CompilerState& state) { } return result; -} \ No newline at end of file +} diff --git a/PCCcompiler/compiler_types.h b/PCCcompiler/compiler_types.h index ed63c22..42e33f4 100644 --- a/PCCcompiler/compiler_types.h +++ b/PCCcompiler/compiler_types.h @@ -6,27 +6,28 @@ #include #include -// Typy operacji, które nasz kompilator rozumie +// Typy operacji enum class OpType { ASSIGN, // a = 5 ADD, // a = b + c SUB, // a = b - c MUL, // a = b * c + DIV, // a = b / c + MOD, // a = b % c EQ, // a == b - PRINT, // print(a) + PRINT, // print(int) + PRINT_STRING, // print(string) - NOWE JMP_FALSE, // if (false) skocz... JMP, // else / pętla - LOGIC_AND, // && - LOGIC_OR, // || + LOGIC_AND, // && + LOGIC_OR, // || LABEL, // miejsce skoku CALL, // wywołanie funkcji RETURN, // return x - DIV, // dzielenie - MOD, // Reszta z dzelenia (%) NOP // pusta instrukcja }; -// Pojedynczy rozkaz kompilatora (Intermediate Representation) +// Pojedynczy rozkaz struct Instruction { OpType type; std::string arg1; @@ -37,27 +38,43 @@ struct Instruction { // Definicja funkcji struct Function { std::string name; - std::string returnType; // "int", "void", "bool" - std::vector args; // Nazwy argumentów (np. "a", "b") - std::vector instructions; // Lista rozkazów w funkcji + std::string returnType; + std::vector args; + std::vector instructions; }; +// GŁÓWNY STAN KOMPILATORA struct CompilerState { - // Mapa wszystkich funkcji (klucz to nazwa) + // Mapa funkcji std::map functions; - // Zmienne globalne (tylko nazwa -> wartość początkowa) + // Zmienne globalne std::map globals; - // Stan parsera - Function* currentFunction = nullptr; // Wskaźnik na aktualnie parsującą się funkcję - int labelCounter = 0; // Do generowania unikalnych nazw etykiet (L1, L2...) - std::stack loopStack; // Do break/continue (przyszłościowo) + // Zarządzanie stosem + std::map stackMap; + int stackOffset = 0; + // Stan parsera + Function* currentFunction = nullptr; + int labelCounter = 0; + + // Stosy bloków + std::stack loopStack; std::stack blockStack; - std::map stringLiterals; + // --- SEKCJA STRINGÓW (TU BYŁY BŁĘDY) --- + + // Lista literałów do sekcji .data (np. "str_0" -> "Hello") + // Musi być VECTOR, bo iterujemy po nim. + std::vector> stringLiterals; + + // Licznik do generowania nazw str_0, str_1... int stringCounter = 0; + + // Mapa typów zmiennych (np. "imie" -> "string") + // Musi być MAP, bo szukamy po nazwie. + std::map varTypes; }; #endif diff --git a/PCCcompiler/parser.cpp b/PCCcompiler/parser.cpp index d485c9b..82e7411 100644 --- a/PCCcompiler/parser.cpp +++ b/PCCcompiler/parser.cpp @@ -26,6 +26,20 @@ std::vector parseArgs(const std::string& line) { return args; } +// Funkcja wyciÄ…gajÄ…ca "tekst" i rejestrujÄ…ca go w state +// Rejestruje tekst i zwraca jego etykietÄ™ (np. str_5) +std::string registerStringLiteral(CompilerState& state, std::string content) { + // UĹĽywamy stringCounter z CompilerState + std::string label = "str_" + std::to_string(state.stringCounter++); + + // Dodajemy do WEKTORA (push_back dziaĹ‚a tylko na wektorze/liĹ›cie) + state.stringLiterals.push_back({ label, content }); + + return label; +} + + + void processSource(const std::string& src, CompilerState& state) { std::istringstream iss(src); std::string line; @@ -106,39 +120,57 @@ void processSource(const std::string& src, CompilerState& state) { f.instructions.push_back({ OpType::RETURN, val, "", "" }); std::cout << " [PARSER] Return: " << val << "\n"; } - // B. PRINT - else if (line.substr(0, 5) == "print") { - size_t start = line.find('(') + 1; - size_t end = line.find(')'); - if (start != std::string::npos && end != std::string::npos) { - std::string arg = trim(line.substr(start, end - start)); + // --- 4. ZMIENNE TYPU STRING --- +// string s = "hello"; + else if (line.substr(0, 6) == "string") { + size_t eqPos = line.find("="); + if (eqPos != std::string::npos) { + std::string name = trim(line.substr(7, eqPos - 7)); - // Czy to bezpoĹ›redni napis? np. print("Hello") - if (arg.size() >= 2 && arg.front() == '"' && arg.back() == '"') { - std::string content = arg.substr(1, arg.size() - 2); + size_t quoteStart = line.find("\"", eqPos); + size_t quoteEnd = line.rfind("\""); - // Rejestrujemy - std::string label; - if (state.stringLiterals.count(content)) { - label = state.stringLiterals[content]; - } - else { - label = "str_" + std::to_string(state.stringCounter++); - state.stringLiterals[content] = label; - } + if (quoteStart != std::string::npos && quoteEnd > quoteStart) { + std::string content = line.substr(quoteStart + 1, quoteEnd - quoteStart - 1); - // Dajemy znać generatorowi, ĹĽe to typ STRING - f.instructions.push_back({ OpType::PRINT, label, "STRING", "" }); - } - else { - // ZwykĹ‚a zmienna (int lub string - generator musi zgadnąć lub my musimy wiedzieć) - // Na razie załóżmy, ĹĽe jeĹ›li zmienna ma w nazwie "msg" lub "txt", to string - // (To hack, w przyszĹ‚oĹ›ci dodamy tabelÄ™ typĂłw zmiennych) - f.instructions.push_back({ OpType::PRINT, arg, "VAR", "" }); + // Rejestracja w wektorze + std::string label = registerStringLiteral(state, content); + + // Rejestracja typu w mapie (mapa obsĹ‚uguje []) + state.varTypes[name] = "string"; + + // Instrukcja + f.instructions.push_back({ OpType::ASSIGN, name, label, "" }); } } } + // --- DRUKOWANIE (PRINT) --- + else if (line.substr(0, 5) == "print") { + size_t open = line.find("("); + size_t close = line.rfind(")"); + if (open != std::string::npos && close > open) { + std::string content = trim(line.substr(open + 1, close - open - 1)); + + // 1. LiteraĹ‚: print("tekst") + if (content.front() == '"' && content.back() == '"') { + std::string text = content.substr(1, content.length() - 2); + std::string label = registerStringLiteral(state, text); + f.instructions.push_back({ OpType::PRINT_STRING, label, "", "" }); + } + // 2. Zmienna: print(x) - sprawdzamy typ + // UĹĽywamy .count() na mapie varTypes (poprawne) + else if (state.varTypes.count(content) && state.varTypes[content] == "string") { + f.instructions.push_back({ OpType::PRINT_STRING, content, "", "" }); + } + // 3. Liczba + else { + f.instructions.push_back({ OpType::PRINT, content, "", "" }); + } + } + } + + // C. IF STATEMENT // --- IF (ZAAWANSOWANY) --- else if (line.substr(0, 2) == "if") { @@ -352,26 +384,6 @@ void processSource(const std::string& src, CompilerState& state) { std::string b = trim(rightSide.substr(opPos + 2)); f.instructions.push_back({ OpType::EQ, varName, a, b }); } - else if (rightSide.size() >= 2 && rightSide.front() == '"' && rightSide.back() == '"') - { - { - // WyciÄ…gamy treść bez cudzysĹ‚owĂłw - std::string content = rightSide.substr(1, rightSide.size() - 2); - - // Rejestrujemy stringa w sekcji danych, jeĹ›li jeszcze go nie ma - std::string label; - if (state.stringLiterals.count(content)) { - label = state.stringLiterals[content]; - } - else { - label = "str_" + std::to_string(state.stringCounter++); - state.stringLiterals[content] = label; - } - - // Generujemy instrukcjÄ™ przypisania ADRESU etykiety do zmiennej - f.instructions.push_back({ OpType::ASSIGN, varName, label, "STRING" }); - } - } // 4. ZwykĹ‚e przypisanie: a = 5 else { f.instructions.push_back({ OpType::ASSIGN, varName, rightSide, "" });