diff --git a/PCCcompiler/codegen.cpp b/PCCcompiler/codegen.cpp index 36f61a1..dd43a93 100644 --- a/PCCcompiler/codegen.cpp +++ b/PCCcompiler/codegen.cpp @@ -13,7 +13,6 @@ bool isNumber(const std::string& s) { 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 @@ -27,15 +26,19 @@ 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"; } @@ -69,27 +70,39 @@ std::string generateAssembly(const CompilerState& state) { result += " push rbp\n"; result += " mov rbp, rsp\n"; - result += " sub rsp, 288\n"; + result += " sub rsp, 512\n"; // Zwiększyłem stos dla bezpieczeństwa obiektów std::map stackMap; int currentStack = 8; // ARGUMENTY FUNKCJI + // RCX, RDX, R8, R9 - konwencja Windows x64 (shadow space obsługuje caller) + // Jeœli funkcja jest metodš, pierwszym argumentem jest 'this' (wskaŸnik na obiekt) + + int argIdx = 0; 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; + argIdx++; } 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; + argIdx++; + } + if (func.args.size() > 2) { + stackMap[func.args[2]] = currentStack; + result += " mov [rbp-" + std::to_string(currentStack) + "], r8 ; arg " + func.args[2] + "\n"; + currentStack += 8; + argIdx++; } // GENEROWANIE INSTRUKCJI for (const auto& instr : func.instructions) { - // Rezerwacja miejsca na stosie + // Rezerwacja miejsca na stosie dla zmiennych bool isWriteOp = (instr.type == OpType::ASSIGN || instr.type == OpType::ADD || instr.type == OpType::EQ || @@ -101,63 +114,154 @@ std::string generateAssembly(const CompilerState& state) { instr.type == OpType::LOGIC_OR || instr.type == OpType::MSGBOX || instr.type == OpType::ARRAY_DECLARE || - instr.type == OpType::ARRAY_SET); + instr.type == OpType::ARRAY_SET || + instr.type == OpType::ALLOC_OBJECT || + instr.type == OpType::LOAD_FIELD); if (isWriteOp && stackMap.find(instr.arg1) == stackMap.end() && instr.arg1 != "RAX") { stackMap[instr.arg1] = currentStack; - currentStack += 8; + + // Dla obiektów i tablic alokujemy więcej miejsca + if (instr.type == OpType::ALLOC_OBJECT) { + int size = std::stoi(instr.arg2); + currentStack += size; + } + else if (instr.type == OpType::ARRAY_DECLARE) { + int size = std::stoi(instr.arg2); + currentStack += (size * 8); + } + else { + currentStack += 8; // domyœlnie zmienna int/ptr + } } 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" + // Jeœli Ÿródłem jest wynik funkcji (RAX), nie generujemy "mov rax, eax" + if (instr.arg2 == "RAX") { 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 + // POPRAWIONE: Tylko dwa backslashe, tak jak w reszcie kodu result += " mov " + dst + ", rax\n"; } - else if (instr.arg3 == "STRING") { - // Przypisanie stringa: ładujemy ADRES (LEA) - result += " lea rax, [rel " + src + "]\n"; + else if (instr.arg3.find("ARRAY_IDX:") == 0) { + std::string indexStr = instr.arg3.substr(10); + std::string arrName = instr.arg2; std::string dst = getVarLocation(instr.arg1, stackMap); - // Zapisujemy adres w zmiennej lokalnej (wskaŸnik 64-bit qword) - result += " mov qword " + dst + ", rax\n"; + int baseOffset = stackMap[arrName]; + + if (isNumber(indexStr)) result += " mov rcx, " + indexStr + "\\n"; + else result += " mov rcx, " + getVarLocation(indexStr, stackMap) + "\\n"; + + result += " imul rcx, 8\\n"; + result += " mov rdx, rbp\\n"; + result += " sub rdx, " + std::to_string(baseOffset) + "\\n"; + result += " sub rdx, rcx\\n"; + result += " mov rax, [rdx]\\n"; + result += " mov " + dst + ", rax\\n"; + } + else if (instr.arg3 == "STRING") { + std::string src = instr.arg2; + result += " lea rax, [rel " + src + "]\\n"; + std::string dst = getVarLocation(instr.arg1, stackMap); + 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"; + std::string src = instr.arg2; + if (isNumber(src)) result += " mov rax, " + src + "\\n"; + else result += " mov rax, " + srcLoc + "\\n"; + + result += " mov " + dst + ", rax\\n"; } break; } + + case OpType::ALLOC_OBJECT: { + // Miejsce na stosie zostało zarezerwowane wyżej w pętli (currentStack += size) + // Możemy opcjonalnie wyzerować pamięć (memset), ale na razie pomijamy dla prostoty + // Komentarz w ASM + result += " ; Alloc Object " + instr.arg1 + " size: " + instr.arg2 + "\n"; + break; + } + case OpType::STORE_FIELD: { + // STORE_FIELD objName, offset, value + std::string objName = instr.arg1; + int offset = std::stoi(instr.arg2); + std::string valStr = instr.arg3; + + // 1. Gdzie jest obiekt? (jego baza) + // Obiekt na stosie zaczyna się pod [RBP - stackMap[objName]] + // Pola sš kolejne w dół stosu (bo stos roœnie w dół, ale struktura ma dodatnie offsety... + // W C lokalne struktury: &obj to najniższy adres. + // U nas stackMap[obj] to "górny" adres (pierwsze zarezerwowane 8 bajtów). + // Przyjmijmy: adres_pola = (RBP - stackMap[objName]) - offset + + // Pobierz wartoœć do zapisania + if (isNumber(valStr)) { + result += " mov rax, " + valStr + "\n"; + } + else { + result += " mov rax, " + getVarLocation(valStr, stackMap) + "\n"; + } + + int baseOffset = 0; + + // SprawdŸ czy objName to "this" + if (objName == "this") { + // "this" jest wskaŸnikiem! Trzeba go załadować + std::string thisPtrLoc = getVarLocation("this", stackMap); + result += " mov rdx, " + thisPtrLoc + "\n"; // RDX = adres obiektu + // Adres pola = RDX - offset (tutaj uwaga: jeœli alokujemy na stosie "w dół", to pola majš ujemne offsety względem bazy?) + // Zróbmy proœciej: w 'ALLOC_OBJECT' rezerwujemy blok. + // [RBP - base] to poczštek (pole 0). + // [RBP - base - 8] to pole 1 (offset 8). + // Czyli adres = RBP - base - offset. + + // ALE: "this" przekazany do funkcji to wskaŸnik na ten obszar w pamięci. + // Jeœli przekazujemy adres zmiennej lokalnej (LEA), to wskaŸnik pokazuje na [RBP-base]. + // Więc [RDX - offset] powinno zadziałać. + result += " sub rdx, " + std::to_string(offset) + "\n"; + result += " mov [rdx], rax\n"; + } + else { + // Obiekt lokalny na stosie + baseOffset = stackMap[objName]; + result += " mov rdx, rbp\n"; + result += " sub rdx, " + std::to_string(baseOffset) + "\n"; + result += " sub rdx, " + std::to_string(offset) + "\n"; + result += " mov [rdx], rax\n"; + } + break; + } + case OpType::LOAD_FIELD: { + // LOAD_FIELD destVar, objName, offset + std::string destVar = instr.arg1; // gdzie zapisać wynik + std::string objName = instr.arg2; // skšd czytać + int offset = std::stoi(instr.arg3); // offset pola + + // 1. Oblicz adres pola + if (objName == "this") { + std::string thisPtrLoc = getVarLocation("this", stackMap); + result += " mov rdx, " + thisPtrLoc + "\n"; + result += " sub rdx, " + std::to_string(offset) + "\n"; + } + else { + int baseOffset = stackMap[objName]; + result += " mov rdx, rbp\n"; + result += " sub rdx, " + std::to_string(baseOffset) + "\n"; + result += " sub rdx, " + std::to_string(offset) + "\n"; + } + + // 2. Pobierz wartoœć + result += " mov rax, [rdx]\n"; + + // 3. Zapisz do zmiennej docelowej + std::string destLoc = getVarLocation(destVar, stackMap); + result += " mov " + destLoc + ", rax\n"; + break; + } case OpType::ADD: { std::string op1 = getVarLocation(instr.arg2, stackMap); std::string op2 = getVarLocation(instr.arg3, stackMap); @@ -214,7 +318,7 @@ std::string generateAssembly(const CompilerState& state) { else { result += " idiv dword " + op2 + "\n"; } - result += " mov " + dst + ", edx\n"; // Reszta + result += " mov " + dst + ", edx\n"; break; } case OpType::EQ: { @@ -262,23 +366,10 @@ std::string generateAssembly(const CompilerState& state) { } 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"; - - } + 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: { @@ -286,60 +377,32 @@ std::string generateAssembly(const CompilerState& state) { 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)" + // Obsłużone przy alokacji stosu break; } case OpType::ARRAY_SET: { - std::string arrName = instr.arg1; // t - std::string indexStr = instr.arg2; // i - std::string valStr = instr.arg3; // val + std::string arrName = instr.arg1; + std::string indexStr = instr.arg2; + std::string valStr = instr.arg3; - // 1. Obliczamy wartoœć do wpisania - if (isNumber(valStr)) { - result += " mov rax, " + valStr + "\n"; - } + 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) + result += " mov rax, " + valLoc + "\n"; } int baseOffset = stackMap[arrName]; - // Ładujemy indeks do RCX - if (isNumber(indexStr)) { - result += " mov rcx, " + indexStr + "\n"; - } + if (isNumber(indexStr)) result += " mov rcx, " + indexStr + "\n"; else { std::string idxLoc = getVarLocation(indexStr, stackMap); - result += " mov rcx, " + idxLoc + "\n"; // Pobierz indeks ze zmiennej + result += " mov rcx, " + idxLoc + "\n"; } - // 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 += " sub rdx, " + std::to_string(baseOffset) + "\n"; + result += " sub rdx, rcx\n"; result += " mov [rdx], rax\n"; break; } @@ -348,7 +411,6 @@ std::string generateAssembly(const CompilerState& state) { 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"; @@ -371,11 +433,7 @@ std::string generateAssembly(const CompilerState& state) { break; } case OpType::CALL: { - if (instr.arg1 == "input") { - result += " call _getch\n"; - break; - } - if (instr.arg1 == "read_key") { + if (instr.arg1 == "input" || instr.arg1 == "read_key") { result += " call _getch\n"; break; } @@ -391,30 +449,56 @@ std::string generateAssembly(const CompilerState& state) { break; } - // Standardowe wywołanie funkcji + // Call metody/funkcji + std::string funcName = instr.arg1; 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); + std::stringstream ss(argsRaw); + std::string segment; + while (std::getline(ss, segment, ',')) { + callArgs.push_back(segment); } } + + // Przygotowanie argumentów dla Windows x64 (RCX, RDX, R8, R9) + // Argument 0 (RCX) - ewentualnie 'this' + if (callArgs.size() > 0) { + // Czy to 'this' (nazwa obiektu)? + std::string arg0 = callArgs[0]; + if (state.varTypes.count(arg0) && state.classes.count(state.varTypes.at(arg0))) { + // Przekazujemy ADRES obiektu (pointer) + // Obiekt jest na stosie: [RBP - offset] + // Adres to: RBP - offset + int offset = stackMap.at(arg0); + result += " lea rcx, [rbp-" + std::to_string(offset) + "]\n"; + } + else if (arg0 == "this") { + // Przekazujemy this dalej + result += " mov rcx, [rbp+16]\n"; // zakładajšc że this jest w shadow space? nie, my go kopiujemy na stos + // Wróćmy do logiki argumentów: argumenty funkcji sš kopiowane na stos lokalny. + // arg0 ("this") jest w stackMap["this"]. + std::string loc = getVarLocation("this", stackMap); + result += " mov rcx, " + loc + "\n"; + } + else { + // Zwykła zmienna / liczba + std::string val = getVarLocation(arg0, stackMap); + if (isNumber(val)) result += " mov rcx, " + val + "\n"; + else result += " movsxd rcx, dword " + val + "\n"; + } + } + 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"; + + // ... (dalsze argumenty R8, R9 jeœli potrzebujesz) + + result += " call " + funcName + "\n"; break; } case OpType::RETURN: { @@ -427,41 +511,23 @@ std::string generateAssembly(const CompilerState& state) { 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"; - } + if (text.find("str_") == 0) 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"; - } + 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 += " mov rcx, 0\n"; + result += " mov r9, 0\n"; result += " call MessageBoxA\n"; break; } diff --git a/PCCcompiler/compiler_types.h b/PCCcompiler/compiler_types.h index 63c4b06..a026ca6 100644 --- a/PCCcompiler/compiler_types.h +++ b/PCCcompiler/compiler_types.h @@ -16,11 +16,11 @@ enum class OpType { MOD, // a = b % c EQ, // a == b PRINT, // print(int) - PRINT_STRING, // print(string) - NOWE + PRINT_STRING, // print(string) JMP_FALSE, // if (false) skocz... ARRAY_DECLARE, // int t[10]; ARRAY_SET, // t[0] = 5; - ARRAY_GET, // x = t[0]; - to obsłużymy w ASSIGN, ale warto mieć typ + ARRAY_GET, // x = t[0]; JMP, // else / pętla LOGIC_AND, // && LOGIC_OR, // || @@ -28,6 +28,9 @@ enum class OpType { CALL, // wywołanie funkcji RETURN, // return x MSGBOX, // msg box + ALLOC_OBJECT, // alokacja obiektu na stosie - NOWE + STORE_FIELD, // zapis do pola obiektu - NOWE + LOAD_FIELD, // odczyt z pola obiektu - NOWE NOP // pusta instrukcja }; @@ -47,11 +50,37 @@ struct Function { std::vector instructions; }; +// Definicja pola klasy +struct ClassField { + std::string name; + std::string type; // "int", "string", itp. + int offset; // offset w bajtach od poczštku obiektu +}; + +// Definicja metody klasy +struct ClassMethod { + std::string name; + std::string returnType; + std::vector args; + std::string mangledName; // np. "User_setAge" +}; + +// Definicja klasy +struct ClassDef { + std::string name; + std::vector fields; + std::vector methods; + int totalSize; // rozmiar całego obiektu w bajtach +}; + // GŁÓWNY STAN KOMPILATORA struct CompilerState { // Mapa funkcji std::map functions; + // Mapa klas (NOWE) + std::map classes; + // Zmienne globalne std::map globals; @@ -61,6 +90,7 @@ struct CompilerState { // Stan parsera Function* currentFunction = nullptr; + std::string currentClass = ""; // (NOWE) - nazwa aktualnie parsowanej klasy int labelCounter = 0; // Stosy bloków diff --git a/PCCcompiler/parser.cpp b/PCCcompiler/parser.cpp index aac81f3..722127e 100644 --- a/PCCcompiler/parser.cpp +++ b/PCCcompiler/parser.cpp @@ -4,6 +4,17 @@ #include #include +// =================================================================== +// DEKLARACJE WSTĘPNE +// =================================================================== +// Musimy zadeklarować tę funkcję wcześniej, bo uĹźywają jej i klasy i main +bool handleAssignment(const std::string& line, Function& f, CompilerState& state); +bool parseInstruction(const std::string& line, Function& f, CompilerState& state); + +// =================================================================== +// POMOCNICZE FUNKCJE PARSOWANIA +// =================================================================== + std::vector parseArgs(const std::string& line) { std::vector args; size_t open = line.find('('); @@ -17,8 +28,7 @@ std::vector parseArgs(const std::string& line) { std::string segment; while (std::getline(ss, segment, ',')) { segment = trim(segment); - // segment to np. "int a". Szukamy ostatniej spacji, by wziąć nazwę "a" - size_t space = segment.find_last_of(" \t"); + size_t space = segment.find_last_of(" \\t"); if (space != std::string::npos) { args.push_back(trim(segment.substr(space + 1))); } @@ -26,49 +36,584 @@ 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::vector lines; - { - std::istringstream iss(src); - std::string t; - while (std::getline(iss, t)) lines.push_back(trim(t)); +int getClassFieldOffset(CompilerState& state, const std::string& fieldName) { + if (state.currentClass.empty()) return -1; + if (state.classes.count(state.currentClass) == 0) return -1; + + const auto& fields = state.classes[state.currentClass].fields; + for (const auto& f : fields) { + if (f.name == fieldName) return f.offset; } + return -1; +} + +// =================================================================== +// FUNKCJE POMOCNICZE DO OBSŁUGI WARUNKÓW +// =================================================================== + +std::string processCondition(const std::string& conditionRaw, Function& f, CompilerState& state) { + std::string cond = trim(conditionRaw); + + int fieldOffset = getClassFieldOffset(state, cond); + if (fieldOffset != -1) { + std::string tmp = "_cond_fld_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::LOAD_FIELD, tmp, "this", std::to_string(fieldOffset) }); + cond = tmp; + } + + if (cond.find("==") != std::string::npos) { + size_t opPos = cond.find("=="); + std::string a = trim(cond.substr(0, opPos)); + std::string b = trim(cond.substr(opPos + 2)); + + int offA = getClassFieldOffset(state, a); + if (offA != -1) { + std::string t = "_c_a_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::LOAD_FIELD, t, "this", std::to_string(offA) }); + a = t; + } + int offB = getClassFieldOffset(state, b); + if (offB != -1) { + std::string t = "_c_b_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::LOAD_FIELD, t, "this", std::to_string(offB) }); + b = t; + } + + std::string tmp = "_cond_tmp_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::EQ, tmp, a, b }); + return tmp; + } + else if (cond.find("!=") != std::string::npos) { + size_t opPos = cond.find("!="); + std::string a = trim(cond.substr(0, opPos)); + std::string b = trim(cond.substr(opPos + 2)); + std::string tmp = "_cond_tmp_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::EQ, tmp, a, b }); + return tmp; + } + + return cond; +} + +// =================================================================== +// FUNKCJE OBSŁUGI BLOKÓW +// =================================================================== + +void handleBlockClose(CompilerState& state, const std::vector& lines, size_t i) { + if (state.blockStack.empty()) { + state.currentFunction = nullptr; + return; + } + + bool nextIsElse = false; + size_t j = i + 1; + while (j < lines.size()) { + std::string nl = trim(lines[j]); + if (nl.empty() || nl.rfind("//", 0) == 0) { j++; continue; } + if (nl.rfind("else", 0) == 0) nextIsElse = true; + break; + } + + std::string blockInfo = state.blockStack.top(); + + if (blockInfo.rfind("WHILE|", 0) == 0) { + state.blockStack.pop(); + size_t p1 = blockInfo.find('|'); + size_t p2 = blockInfo.rfind('|'); + std::string labelStart = blockInfo.substr(p1 + 1, p2 - p1 - 1); + std::string labelEnd = blockInfo.substr(p2 + 1); + + if (state.currentFunction) { + state.currentFunction->instructions.push_back({ OpType::JMP, labelStart, "", "" }); + state.currentFunction->instructions.push_back({ OpType::LABEL, labelEnd, "", "" }); + } + return; + } + + if (blockInfo.rfind("IF|", 0) == 0) { + state.blockStack.pop(); + size_t p1 = blockInfo.find('|'); + size_t p2 = blockInfo.rfind('|'); + std::string labelElse = blockInfo.substr(p1 + 1, p2 - p1 - 1); + std::string labelEnd = blockInfo.substr(p2 + 1); + + if (nextIsElse) { + if (state.currentFunction) { + state.currentFunction->instructions.push_back({ OpType::JMP, labelEnd, "", "" }); + state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" }); + } + state.blockStack.push(labelEnd); + } + else { + if (state.currentFunction) { + state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" }); + } + } + return; + } + + state.blockStack.pop(); + if (state.currentFunction) { + state.currentFunction->instructions.push_back({ OpType::LABEL, blockInfo, "", "" }); + } +} + +// =================================================================== +// FUNKCJE OBSŁUGI INSTRUKCJI +// =================================================================== + +bool handleReturn(const std::string& line, Function& f, CompilerState& state) { + if (line.substr(0, 6) != "return") return false; + std::string val = trim(line.substr(6)); + if (!val.empty() && val.back() == ';') val.pop_back(); + + int fieldOffset = getClassFieldOffset(state, val); + if (fieldOffset != -1) { + std::string tmp = "_ret_tmp_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::LOAD_FIELD, tmp, "this", std::to_string(fieldOffset) }); + val = tmp; + } + f.instructions.push_back({ OpType::RETURN, val, "", "" }); + return true; +} + +bool handleStringDeclaration(const std::string& line, Function& f, CompilerState& state) { + if (line.substr(0, 6) != "string") return false; + size_t eqPos = line.find("="); + if (eqPos == std::string::npos) return false; + std::string name = trim(line.substr(7, eqPos - 7)); + size_t quoteStart = line.find("\"", eqPos); + size_t quoteEnd = line.rfind("\""); + + if (quoteStart != std::string::npos && quoteEnd > quoteStart) { + std::string content = line.substr(quoteStart + 1, quoteEnd - quoteStart - 1); + std::string label = registerStringLiteral(state, content); + state.varTypes[name] = "string"; + f.instructions.push_back({ OpType::ASSIGN, name, label, "" }); + return true; + } + return false; +} + +bool handleArrayDeclaration(const std::string& line, Function& f, CompilerState& state) { + if (line.substr(0, 3) != "int" || line.find("[") == std::string::npos || line.find("=") != std::string::npos) return false; + size_t openBracket = line.find("["); + size_t closeBracket = line.find("]"); + + if (openBracket != std::string::npos && closeBracket > openBracket) { + std::string name = trim(line.substr(3, openBracket - 3)); + std::string sizeStr = trim(line.substr(openBracket + 1, closeBracket - openBracket - 1)); + state.varTypes[name] = "array"; + f.instructions.push_back({ OpType::ARRAY_DECLARE, name, sizeStr, "" }); + std::cout << " [PARSER] Array Decl: " << name << "[" << sizeStr << "]\\n"; + return true; + } + return false; +} + +bool handlePrint(const std::string& line, Function& f, CompilerState& state) { + if (line.substr(0, 5) != "print") return false; + size_t open = line.find("("); + size_t close = line.rfind(")"); + if (open == std::string::npos || close <= open) return false; + std::string content = trim(line.substr(open + 1, close - open - 1)); + + if (content.find("[") != std::string::npos && content.back() == ']') { + size_t opIdx = content.find("["); + std::string arrName = content.substr(0, opIdx); + std::string arrIdx = content.substr(opIdx + 1, content.length() - opIdx - 2); + std::string tmp = "_p_tmp_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::ASSIGN, tmp, arrName, "ARRAY_IDX:" + arrIdx }); + f.instructions.push_back({ OpType::PRINT, tmp, "", "" }); + } + else if (content.find(".") != std::string::npos) { + size_t dotPos = content.find("."); + std::string objName = content.substr(0, dotPos); + std::string fieldName = content.substr(dotPos + 1); + if (state.varTypes.count(objName) && state.classes.count(state.varTypes[objName])) { + std::string className = state.varTypes[objName]; + int offset = -1; + for (auto& field : state.classes[className].fields) { + if (field.name == fieldName) { offset = field.offset; break; } + } + if (offset != -1) { + std::string tmp = "_p_tmp_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::LOAD_FIELD, tmp, objName, std::to_string(offset) }); + f.instructions.push_back({ OpType::PRINT, tmp, "", "" }); + } + } + } + else if (getClassFieldOffset(state, content) != -1) { + int offset = getClassFieldOffset(state, content); + std::string tmp = "_p_tmp_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::LOAD_FIELD, tmp, "this", std::to_string(offset) }); + f.instructions.push_back({ OpType::PRINT, tmp, "", "" }); + } + else 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, "", "" }); + } + else if (state.varTypes.count(content) && state.varTypes[content] == "string") { + f.instructions.push_back({ OpType::PRINT_STRING, content, "", "" }); + } + else { + f.instructions.push_back({ OpType::PRINT, content, "", "" }); + } + return true; +} + +bool handleIf(const std::string& line, Function& f, CompilerState& state) { + if (line.rfind("if", 0) != 0) return false; + size_t openParen = line.find("("); + size_t closeParen = line.rfind(")"); + if (openParen == std::string::npos) return false; + std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1)); + std::string finalCond = processCondition(conditionRaw, f, state); + std::string labelElse = "L_" + std::to_string(state.labelCounter++); + std::string labelEnd = "L_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::JMP_FALSE, labelElse, finalCond, "" }); + state.blockStack.push("IF|" + labelElse + "|" + labelEnd); + return true; +} + +bool handleWhile(const std::string& line, Function& f, CompilerState& state) { + if (line.substr(0, 5) != "while") return false; + size_t openParen = line.find("("); + size_t closeParen = line.rfind(")"); + if (openParen == std::string::npos) return false; + std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1)); + std::string labelStart = "L_" + std::to_string(state.labelCounter++); + std::string labelEnd = "L_" + std::to_string(state.labelCounter++); + f.instructions.push_back({ OpType::LABEL, labelStart, "", "" }); + std::string finalCond = processCondition(conditionRaw, f, state); + f.instructions.push_back({ OpType::JMP_FALSE, labelEnd, finalCond, "" }); + state.blockStack.push("WHILE|" + labelStart + "|" + labelEnd); + return true; +} + +bool handleMsgbox(const std::string& line, Function& f, CompilerState& state) { + if (line.substr(0, 6) != "msgbox") return false; + size_t open = line.find("("); + size_t close = line.rfind(")"); + if (open == std::string::npos) return false; + std::string args = line.substr(open + 1, close - open - 1); + size_t comma = args.find(","); + if (comma == std::string::npos) return false; + std::string arg1 = trim(args.substr(0, comma)); + std::string arg2 = trim(args.substr(comma + 1)); + std::string l1 = (arg1.front() == '"') ? registerStringLiteral(state, arg1.substr(1, arg1.size() - 2)) : arg1; + std::string l2 = (arg2.front() == '"') ? registerStringLiteral(state, arg2.substr(1, arg2.size() - 2)) : arg2; + f.instructions.push_back({ OpType::MSGBOX, l1, l2, "" }); + return true; +} + +bool handleAssignment(const std::string& line, Function& f, CompilerState& state) { + // Specjalny przypadek: samodzielne wywołanie metody/funkcji bez "=" + if (line.find("=") == std::string::npos) { + if (line.find("(") != std::string::npos && line.find(")") != std::string::npos) { + // Metoda: u.setAge(5); + if (line.find(".") != std::string::npos) { + size_t dotPos = line.find("."); + size_t openParen = line.find("("); + std::string objName = trim(line.substr(0, dotPos)); + std::string methodName = trim(line.substr(dotPos + 1, openParen - dotPos - 1)); + std::string argsContent = line.substr(openParen + 1, line.rfind(")") - openParen - 1); + + if (state.varTypes.count(objName)) { + std::string className = state.varTypes[objName]; + std::string mangledName = className + "_" + methodName; + std::string fullArgs = objName; + if (!argsContent.empty()) fullArgs += "," + argsContent; + f.instructions.push_back({ OpType::CALL, mangledName, fullArgs, "" }); + return true; + } + } + // Zwykła funkcja: func(); + size_t open = line.find('('); + std::string funcName = trim(line.substr(0, open)); + std::string argsContent = line.substr(open + 1, line.find(')') - open - 1); + f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" }); + return true; + } + return false; + } + + size_t eqPos = line.find('='); + std::string leftSide = trim(line.substr(0, eqPos)); + std::string rightSide = trim(line.substr(eqPos + 1)); + if (!rightSide.empty() && rightSide.back() == ';') rightSide.pop_back(); + + // 1. Zapis do pola: u.age = 5 + if (leftSide.find(".") != std::string::npos && leftSide.find("[") == std::string::npos) { + size_t dotPos = leftSide.find("."); + std::string objName = trim(leftSide.substr(0, dotPos)); + std::string fieldName = trim(leftSide.substr(dotPos + 1)); + std::string className = state.varTypes[objName]; + ClassDef& cls = state.classes[className]; + int offset = -1; + for (auto& field : cls.fields) { + if (field.name == fieldName) { offset = field.offset; break; } + } + f.instructions.push_back({ OpType::STORE_FIELD, objName, std::to_string(offset), rightSide }); + return true; + } + // 2. Zapis do pola wewnątrz metody: age = 5 + else { + int fieldOffset = getClassFieldOffset(state, leftSide); + if (fieldOffset != -1) { + f.instructions.push_back({ OpType::STORE_FIELD, "this", std::to_string(fieldOffset), rightSide }); + return true; + } + } + + // Tablice + if (leftSide.find("[") != std::string::npos) { + size_t open = leftSide.find("["); + size_t close = leftSide.find("]"); + std::string arrName = trim(leftSide.substr(0, open)); + std::string index = trim(leftSide.substr(open + 1, close - open - 1)); + f.instructions.push_back({ OpType::ARRAY_SET, arrName, index, rightSide }); + return true; + } + + std::string varName = leftSide; + if (leftSide.rfind("int ", 0) == 0) varName = trim(leftSide.substr(4)); + else if (leftSide.rfind("bool ", 0) == 0) varName = trim(leftSide.substr(5)); + else if (leftSide.rfind("string ", 0) == 0) varName = trim(leftSide.substr(7)); + + // Odczyt pola: x = u.age + if (rightSide.find(".") != std::string::npos && rightSide.find("(") == std::string::npos) { + size_t dot = rightSide.find("."); + std::string obj = rightSide.substr(0, dot); + std::string fld = rightSide.substr(dot + 1); + if (state.varTypes.count(obj)) { + std::string cName = state.varTypes[obj]; + int off = -1; + for (auto& ff : state.classes[cName].fields) if (ff.name == fld) off = ff.offset; + if (off != -1) { + f.instructions.push_back({ OpType::LOAD_FIELD, varName, obj, std::to_string(off) }); + return true; + } + } + } + + // Tablice odczyt + if (rightSide.find("[") != std::string::npos && rightSide.back() == ']') { + size_t open = rightSide.find("["); + size_t close = rightSide.find("]"); + std::string arrName = trim(rightSide.substr(0, open)); + std::string index = trim(rightSide.substr(open + 1, close - open - 1)); + f.instructions.push_back({ OpType::ASSIGN, varName, arrName, "ARRAY_IDX:" + index }); + return true; + } + + // Wywołanie metody po prawej stronie: x = u.getAge() + if (rightSide.find("(") != std::string::npos && rightSide.find(")") != std::string::npos) { + if (rightSide.find(".") != std::string::npos) { + size_t dot = rightSide.find("."); + size_t op = rightSide.find("("); + std::string obj = trim(rightSide.substr(0, dot)); + std::string met = trim(rightSide.substr(dot + 1, op - dot - 1)); + std::string args = rightSide.substr(op + 1, rightSide.find(")") - op - 1); + std::string cName = state.varTypes[obj]; + std::string mangled = cName + "_" + met; + std::string fullArgs = obj; + if (!args.empty()) fullArgs += "," + args; + f.instructions.push_back({ OpType::CALL, mangled, fullArgs, "" }); + f.instructions.push_back({ OpType::ASSIGN, varName, "RAX", "" }); + return true; + } + // Zwykła funkcja + size_t open = rightSide.find('('); + std::string funcName = trim(rightSide.substr(0, open)); + std::string argsContent = rightSide.substr(open + 1, rightSide.find(')') - open - 1); + f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" }); + f.instructions.push_back({ OpType::ASSIGN, varName, "RAX", "" }); + return true; + } + + // Arytmetyka + struct Operator { std::string symbol; OpType type; size_t length; }; + std::vector operators = { + {"&&", OpType::LOGIC_AND, 2}, {"||", OpType::LOGIC_OR, 2}, {"==", OpType::EQ, 2}, + {"+", OpType::ADD, 1}, {"-", OpType::SUB, 1}, {"*", OpType::MUL, 1}, {"/", OpType::DIV, 1}, {"%", OpType::MOD, 1} + }; + for (const auto& op : operators) { + size_t opPos = rightSide.find(op.symbol); + if (opPos != std::string::npos) { + std::string a = trim(rightSide.substr(0, opPos)); + std::string b = trim(rightSide.substr(opPos + op.length)); + int offA = getClassFieldOffset(state, a); + if (offA != -1) { std::string t = "_opa" + std::to_string(state.labelCounter++); f.instructions.push_back({ OpType::LOAD_FIELD, t, "this", std::to_string(offA) }); a = t; } + int offB = getClassFieldOffset(state, b); + if (offB != -1) { std::string t = "_opb" + std::to_string(state.labelCounter++); f.instructions.push_back({ OpType::LOAD_FIELD, t, "this", std::to_string(offB) }); b = t; } + f.instructions.push_back({ op.type, varName, a, b }); + return true; + } + } + + if (rightSide.size() >= 2 && rightSide.front() == '"') { + std::string content = rightSide.substr(1, rightSide.size() - 2); + std::string label = registerStringLiteral(state, content); + state.varTypes[varName] = "string"; + f.instructions.push_back({ OpType::ASSIGN, varName, label, "" }); + return true; + } + + int fOff = getClassFieldOffset(state, rightSide); + if (fOff != -1) { + f.instructions.push_back({ OpType::LOAD_FIELD, varName, "this", std::to_string(fOff) }); + } + else { + f.instructions.push_back({ OpType::ASSIGN, varName, rightSide, "" }); + } + return true; +} + +bool handleFunctionCall(const std::string& line, Function& f) { + if (line.find("(") == std::string::npos || line.find(")") == std::string::npos) return false; + size_t open = line.find('('); + std::string funcName = trim(line.substr(0, open)); + std::string argsContent = line.substr(open + 1, line.find(')') - open - 1); + f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" }); + return true; +} + +// Funkcja zbiorcza parsująca jedną linię (dla processSource i dla metody w klasie) +bool parseInstruction(const std::string& line, Function& f, CompilerState& state) { + if (line.rfind("else", 0) == 0) return true; + + if (handleReturn(line, f, state)) return true; + if (handleStringDeclaration(line, f, state)) return true; + if (handleArrayDeclaration(line, f, state)) return true; + if (handlePrint(line, f, state)) return true; + if (handleIf(line, f, state)) return true; + if (handleWhile(line, f, state)) return true; + if (handleMsgbox(line, f, state)) return true; + + // handleAssignment obsługuje teĹź wywołania metod i operacje + if (handleAssignment(line, f, state)) return true; + + // Deklaracja obiektu: User u; + if (state.classes.count(line.substr(0, line.find(" "))) > 0) { + size_t spacePos = line.find(" "); + std::string className = line.substr(0, spacePos); + std::string varName = trim(line.substr(spacePos + 1)); + if (varName.back() == ';') varName.pop_back(); + state.varTypes[varName] = className; + int size = state.classes[className].totalSize; + f.instructions.push_back({ OpType::ALLOC_OBJECT, varName, std::to_string(size), "" }); + return true; + } + + return false; +} + +// =================================================================== +// PARSOWANIE KLASY (TERAZ PARSUJE CIAŁA METOD!) +// =================================================================== + +void parseClassDefinition(const std::vector& lines, size_t& i, CompilerState& state) { + std::string line = trim(lines[i]); + size_t bracePos = line.find("{"); + std::string className = trim(line.substr(6, bracePos - 6)); + + ClassDef classDef; + classDef.name = className; + int currentOffset = 0; + i++; + + while (i < lines.size()) { + line = trim(lines[i]); + if (line == "}") break; + if (line.empty() || line.rfind("//", 0) == 0) { i++; continue; } + + if (line.back() == ';' && line.find("(") == std::string::npos && line.find("=") == std::string::npos) { + size_t spacePos = line.find(" "); + std::string type = line.substr(0, spacePos); + std::string name = trim(line.substr(spacePos + 1, line.size() - spacePos - 2)); + ClassField field; field.name = name; field.type = type; field.offset = currentOffset; + if (type == "int" || type == "bool") currentOffset += 8; + else if (type == "string") currentOffset += 8; + classDef.fields.push_back(field); + std::cout << " [CLASS] Field: " << type << " " << name << " @ offset " << field.offset << "\n"; + } + else if (line.find("(") != std::string::npos && line.find("{") != std::string::npos) { + size_t openParen = line.find("("); + size_t spacePos = line.find(" "); + std::string returnType = line.substr(0, spacePos); + std::string methodName = trim(line.substr(spacePos + 1, openParen - spacePos - 1)); + + ClassMethod method; + method.name = methodName; method.returnType = returnType; + method.args = parseArgs(line); + method.mangledName = className + "_" + methodName; + classDef.methods.push_back(method); + + Function newFunc; + newFunc.name = method.mangledName; + newFunc.returnType = returnType; + newFunc.args = method.args; + newFunc.args.insert(newFunc.args.begin(), "this"); + state.functions[method.mangledName] = newFunc; + + // --- TUTAJ PARSUJEMY WNĘTRZE METODY --- + state.currentFunction = &state.functions[method.mangledName]; + state.currentClass = className; + state.classes[className] = classDef; // Rejestrujemy tymczasowo, by widzieć pola + + i++; // WejdĹş do środka metody + while (i < lines.size()) { + std::string mLine = trim(lines[i]); + if (mLine == "}") break; // Koniec metody + if (!mLine.empty() && mLine.rfind("//", 0) != 0) { + parseInstruction(mLine, *state.currentFunction, state); + } + i++; + } + state.currentFunction = nullptr; + state.currentClass = ""; + } + i++; + } + classDef.totalSize = currentOffset; + state.classes[className] = classDef; + std::cout << "[PARSER] Class " << className << " registered size=" << currentOffset << "\n"; +} + +// =================================================================== +// GŁÓWNA PĘTLA +// =================================================================== + +void processSource(const std::string& src, CompilerState& state) { + std::vector lines; + std::istringstream iss(src); + std::string t; + while (std::getline(iss, t)) lines.push_back(trim(t)); for (size_t i = 0; i < lines.size(); i++) { std::string line = trim(lines[i]); if (line.empty() || line.substr(0, 2) == "//" || line[0] == '#') continue; if (line.find("} else") != std::string::npos) { - // najpierw obsłuĹź zamknięcie bloku - std::string saved = line; - line = "}"; - // ... uruchom kod obsługi "}" (najlepiej przenieś go do funkcji pomocniczej) - // potem obsłuĹź else: - line = "else"; - // ... uruchom kod obsługi else + handleBlockClose(state, lines, i); continue; } + if (line.rfind("class ", 0) == 0 && line.find("{") != std::string::npos) { + parseClassDefinition(lines, i, state); + continue; + } - // ========================================================= - // 1. DEFINICJA FUNKCJI (np. void main() { ) - // ========================================================= bool startsWithType = (line.rfind("int ", 0) == 0 || line.rfind("void ", 0) == 0 || line.rfind("bool ", 0) == 0); if (startsWithType && line.find("(") != std::string::npos && line.find("{") != std::string::npos && line.find("=") == std::string::npos) { - size_t openParen = line.find('('); std::string typeRaw = line.substr(0, line.find(' ')); std::string nameRaw = line.substr(typeRaw.length(), openParen - typeRaw.length()); @@ -78,365 +623,19 @@ void processSource(const std::string& src, CompilerState& state) { newFunc.name = funcName; newFunc.returnType = typeRaw; newFunc.args = parseArgs(line); - state.functions[funcName] = newFunc; state.currentFunction = &state.functions[funcName]; - std::cout << "[PARSER] New Function: " << funcName << "\n"; continue; } - // ========================================================= - // 2. ZAMYKANIE BLOKU '}' (Koniec funkcji, IF‑a lub WHILE‑a) - // ========================================================= if (line == "}") { - - // lookahead: czy następna sensowna linia to "else" / "else {" - bool nextIsElse = false; - size_t j = i + 1; - while (j < lines.size()) { - std::string nl = trim(lines[j]); - if (nl.empty() || nl.rfind("//", 0) == 0) { j++; continue; } - if (nl.rfind("else", 0) == 0) nextIsElse = true; - break; - } - - if (!state.blockStack.empty()) { - std::string blockInfo = state.blockStack.top(); - - // --- WHILE --- - if (blockInfo.rfind("WHILE|", 0) == 0) { - state.blockStack.pop(); - - size_t p1 = blockInfo.find('|'); - size_t p2 = blockInfo.rfind('|'); - std::string labelStart = blockInfo.substr(p1 + 1, p2 - p1 - 1); - std::string labelEnd = blockInfo.substr(p2 + 1); - - if (state.currentFunction) { - state.currentFunction->instructions.push_back({ OpType::JMP, labelStart, "", "" }); - state.currentFunction->instructions.push_back({ OpType::LABEL, labelEnd, "", "" }); - } - continue; - } - - // --- IF (specjalny wpis IF|else|end) --- - if (blockInfo.rfind("IF|", 0) == 0) { - state.blockStack.pop(); - - size_t p1 = blockInfo.find('|'); - size_t p2 = blockInfo.rfind('|'); - std::string labelElse = blockInfo.substr(p1 + 1, p2 - p1 - 1); - std::string labelEnd = blockInfo.substr(p2 + 1); - - if (nextIsElse) { - // zamykamy blok IF, ale zaraz będzie ELSE: - // 1) przeskocz ELSE po wykonaniu IF - // 2) wstaw początek ELSE - if (state.currentFunction) { - state.currentFunction->instructions.push_back({ OpType::JMP, labelEnd, "", "" }); - state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" }); - } - // Teraz oczekujemy na '}' kończące ELSE -> ma wstawić LABEL labelEnd - state.blockStack.push(labelEnd); - } - else { - // if bez else: labelElse jest po prostu "koniec if" - if (state.currentFunction) { - state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" }); - } - } - continue; - } - - // --- zwykły LABEL na stosie (np. koniec ELSE: labelEnd) --- - state.blockStack.pop(); - if (state.currentFunction) { - state.currentFunction->instructions.push_back({ OpType::LABEL, blockInfo, "", "" }); - } - continue; - } - - // jeśli stos pusty -> zamykamy funkcję - state.currentFunction = nullptr; + handleBlockClose(state, lines, i); continue; } - // ========================================================= - // JESTEŚMY W ŚRODKU FUNKCJI - // ========================================================= if (state.currentFunction) { - Function& f = *state.currentFunction; - - // A. RETURN - if (line.substr(0, 6) == "return") { - std::string val = trim(line.substr(6)); - if (!val.empty() && val.back() == ';') val.pop_back(); - f.instructions.push_back({ OpType::RETURN, val, "", "" }); - continue; - } - - // B. DEKLARACJA STRINGA: 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)); - size_t quoteStart = line.find("\"", eqPos); - size_t quoteEnd = line.rfind("\""); - - if (quoteStart != std::string::npos && quoteEnd > quoteStart) { - std::string content = line.substr(quoteStart + 1, quoteEnd - quoteStart - 1); - std::string label = registerStringLiteral(state, content); - state.varTypes[name] = "string"; - f.instructions.push_back({ OpType::ASSIGN, name, label, "" }); - } - } - continue; - } - - // C. DEKLARACJA TABLICY: int t[10]; - else if (line.substr(0, 3) == "int" && line.find("[") != std::string::npos && line.find("=") == std::string::npos) { - size_t openBracket = line.find("["); - size_t closeBracket = line.find("]"); - - if (openBracket != std::string::npos && closeBracket > openBracket) { - std::string name = trim(line.substr(3, openBracket - 3)); - std::string sizeStr = trim(line.substr(openBracket + 1, closeBracket - openBracket - 1)); - - state.varTypes[name] = "array"; - f.instructions.push_back({ OpType::ARRAY_DECLARE, name, sizeStr, "" }); - std::cout << " [PARSER] Array Decl: " << name << "[" << sizeStr << "]\n"; - } - continue; - } - - // D. 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)); - - // Czy to element tablicy? print(t[0]) - if (content.find("[") != std::string::npos && content.back() == ']') { - size_t opIdx = content.find("["); - std::string arrName = content.substr(0, opIdx); - std::string arrIdx = content.substr(opIdx + 1, content.length() - opIdx - 2); - - // Hack: UĹźywamy tymczasowej zmiennej do wydruku - std::string tmp = "_p_tmp_" + std::to_string(state.labelCounter++); - f.instructions.push_back({ OpType::ASSIGN, tmp, arrName, "ARRAY_IDX:" + arrIdx }); - f.instructions.push_back({ OpType::PRINT, tmp, "", "" }); - } - // Literał tekstowy - else 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, "", "" }); - } - // Zmienna string - else if (state.varTypes.count(content) && state.varTypes[content] == "string") { - f.instructions.push_back({ OpType::PRINT_STRING, content, "", "" }); - } - // Liczba - else { - f.instructions.push_back({ OpType::PRINT, content, "", "" }); - } - } - continue; - } - - // E. IF STATEMENT (z ulepszoną obsługą else) - else if (line.rfind("if", 0) == 0) { - size_t openParen = line.find("("); - size_t closeParen = line.rfind(")"); - if (openParen != std::string::npos && closeParen > openParen) { - std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1)); - - std::string labelElse = "L_" + std::to_string(state.labelCounter++); - std::string labelEnd = "L_" + std::to_string(state.labelCounter++); - f.instructions.push_back({ OpType::JMP_FALSE, labelElse, conditionRaw, "" }); - state.blockStack.push("IF|" + labelElse + "|" + labelEnd); - } - continue; - } - - - // F. WHILE LOOP - else if (line.substr(0, 5) == "while") { - size_t openParen = line.find("("); - size_t closeParen = line.rfind(")"); - if (openParen != std::string::npos && closeParen > openParen) { - std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1)); - - // 1. Generujemy etykiety - std::string labelStart = "L_" + std::to_string(state.labelCounter++); - std::string labelEnd = "L_" + std::to_string(state.labelCounter++); - - // 2. Wstawiamy etykietę START (tu będziemy wracać) - f.instructions.push_back({ OpType::LABEL, labelStart, "", "" }); - - // 3. OBLICZANIE WARUNKU (Tu był błąd - brakowało tego!) - // Jeśli warunek to np. "j - 3", musimy to policzyć do zmiennej tymczasowej - std::string finalCondVar = conditionRaw; - - // Prosta obsługa odejmowania w warunku (np. while (i - 10)) - if (conditionRaw.find("-") != std::string::npos) { - size_t opPos = conditionRaw.find("-"); - std::string a = trim(conditionRaw.substr(0, opPos)); - std::string b = trim(conditionRaw.substr(opPos + 1)); - std::string tmp = "_while_tmp_" + std::to_string(state.labelCounter); - - f.instructions.push_back({ OpType::SUB, tmp, a, b }); - finalCondVar = tmp; - } - // Prosta obsługa "==" (np. while (i == 10)) - else if (conditionRaw.find("==") != std::string::npos) { - size_t opPos = conditionRaw.find("=="); - std::string a = trim(conditionRaw.substr(0, opPos)); - std::string b = trim(conditionRaw.substr(opPos + 2)); - std::string tmp = "_while_tmp_" + std::to_string(state.labelCounter); - - f.instructions.push_back({ OpType::EQ, tmp, a, b }); - finalCondVar = tmp; - } - - // 4. Skaczemy do END jeśli warunek (obliczona zmienna) jest fałszywy - f.instructions.push_back({ OpType::JMP_FALSE, labelEnd, finalCondVar, "" }); - - // 5. Wrzucamy info na stos - state.blockStack.push("WHILE|" + labelStart + "|" + labelEnd); - } - continue; - } - - // G. MSGBOX - else if (line.substr(0, 6) == "msgbox") { - // ... (Twoja logika msgbox, jest OK) ... - size_t open = line.find("("); - size_t close = line.rfind(")"); - if (open != std::string::npos && close > open) { - std::string args = line.substr(open + 1, close - open - 1); - size_t comma = args.find(","); - if (comma != std::string::npos) { - std::string arg1 = trim(args.substr(0, comma)); - std::string arg2 = trim(args.substr(comma + 1)); - - std::string l1 = (arg1.front() == '"') ? registerStringLiteral(state, arg1.substr(1, arg1.size() - 2)) : arg1; - std::string l2 = (arg2.front() == '"') ? registerStringLiteral(state, arg2.substr(1, arg2.size() - 2)) : arg2; - - f.instructions.push_back({ OpType::MSGBOX, l1, l2, "" }); - } - } - continue; - } - - else if (line.rfind("else", 0) == 0) { - continue; - } - - // ========================================================= - // H. PRZYPISANIE / OPERACJE (Linie z "=") - // ========================================================= - else if (line.find("=") != std::string::npos) { - size_t eqPos = line.find('='); - std::string leftSide = trim(line.substr(0, eqPos)); - std::string rightSide = trim(line.substr(eqPos + 1)); - if (!rightSide.empty() && rightSide.back() == ';') rightSide.pop_back(); - - // 1. CZY TO ZAPIS DO TABLICY? t[0] = 5 - if (leftSide.find("[") != std::string::npos) { - size_t open = leftSide.find("["); - size_t close = leftSide.find("]"); - std::string arrName = trim(leftSide.substr(0, open)); - std::string index = trim(leftSide.substr(open + 1, close - open - 1)); - - f.instructions.push_back({ OpType::ARRAY_SET, arrName, index, rightSide }); - continue; - } - - // Pobieramy nazwę zmiennej (usuwamy "int ", "bool ") - std::string varName = leftSide; - if (leftSide.rfind("int ", 0) == 0) varName = trim(leftSide.substr(4)); - else if (leftSide.rfind("bool ", 0) == 0) varName = trim(leftSide.substr(5)); - else if (leftSide.rfind("string ", 0) == 0) varName = trim(leftSide.substr(7)); - - // 2. CZY TO ODCZYT Z TABLICY? x = t[0] - if (rightSide.find("[") != std::string::npos && rightSide.back() == ']') { - size_t open = rightSide.find("["); - size_t close = rightSide.find("]"); - std::string arrName = trim(rightSide.substr(0, open)); - std::string index = trim(rightSide.substr(open + 1, close - open - 1)); - - // Specjalna flaga w arg3: ARRAY_IDX:indeks - f.instructions.push_back({ OpType::ASSIGN, varName, arrName, "ARRAY_IDX:" + index }); - } - // 3. Wywołanie funkcji: x = func() - else if (rightSide.find("(") != std::string::npos && rightSide.find(")") != std::string::npos) { - size_t open = rightSide.find('('); - std::string funcName = trim(rightSide.substr(0, open)); - std::string argsContent = rightSide.substr(open + 1, rightSide.find(')') - open - 1); - - f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" }); - f.instructions.push_back({ OpType::ASSIGN, varName, "RAX", "" }); - } - // 4. Operacje arytmetyczne - else if (rightSide.find("+") != std::string::npos) { - size_t opPos = rightSide.find("+"); - f.instructions.push_back({ OpType::ADD, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) }); - } - else if (rightSide.find("-") != std::string::npos) { - size_t opPos = rightSide.find("-"); - f.instructions.push_back({ OpType::SUB, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) }); - } - else if (rightSide.find("*") != std::string::npos) { - size_t opPos = rightSide.find("*"); - f.instructions.push_back({ OpType::MUL, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) }); - } - else if (rightSide.find("/") != std::string::npos) { - size_t opPos = rightSide.find("/"); - f.instructions.push_back({ OpType::DIV, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) }); - } - else if (rightSide.find("%") != std::string::npos) { - size_t opPos = rightSide.find("%"); - f.instructions.push_back({ OpType::MOD, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) }); - } - // 5. Logika - else if (rightSide.find("&&") != std::string::npos) { - size_t opPos = rightSide.find("&&"); - f.instructions.push_back({ OpType::LOGIC_AND, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 2)) }); - } - else if (rightSide.find("||") != std::string::npos) { - size_t opPos = rightSide.find("||"); - f.instructions.push_back({ OpType::LOGIC_OR, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 2)) }); - } - else if (rightSide.find("==") != std::string::npos) { - size_t opPos = rightSide.find("=="); - f.instructions.push_back({ OpType::EQ, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 2)) }); - } - // 6. Zwykłe przypisanie stringa - else if (rightSide.size() >= 2 && rightSide.front() == '"') { - std::string content = rightSide.substr(1, rightSide.size() - 2); - std::string label = registerStringLiteral(state, content); - state.varTypes[varName] = "string"; - f.instructions.push_back({ OpType::ASSIGN, varName, label, "" }); - } - // 7. Zwykłe przypisanie wartości - else { - f.instructions.push_back({ OpType::ASSIGN, varName, rightSide, "" }); - } - continue; - } - - // I. SAMODZIELNE WYWOŁANIE FUNKCJI (np. input(); ) - else if (line.find("(") != std::string::npos && line.find(")") != std::string::npos) { - size_t open = line.find('('); - std::string funcName = trim(line.substr(0, open)); - std::string argsContent = line.substr(open + 1, line.find(')') - open - 1); - - f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" }); - std::cout << " [PARSER] Call void: " << funcName << "\n"; - } + parseInstruction(line, *state.currentFunction, state); } } }