added classes and bug fix
This commit is contained in:
@@ -13,7 +13,6 @@ bool isNumber(const std::string& s) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Zamienia nazwê zmiennej na adres pamiêci [rbp-X] lub liczbê
|
|
||||||
std::string getVarLocation(const std::string& name, const std::map<std::string, int>& locals) {
|
std::string getVarLocation(const std::string& name, const std::map<std::string, int>& locals) {
|
||||||
std::string cleanName = name;
|
std::string cleanName = name;
|
||||||
// Usuwamy ewentualne spacje
|
// Usuwamy ewentualne spacje
|
||||||
@@ -27,15 +26,19 @@ std::string getVarLocation(const std::string& name, const std::map<std::string,
|
|||||||
|
|
||||||
if (cleanName == "RAX") return "eax";
|
if (cleanName == "RAX") return "eax";
|
||||||
|
|
||||||
|
// USUNIÊTO: if (cleanName == "this") return "[rbp+16]";
|
||||||
|
// Teraz "this" wpadnie do bloku poni¿ej i zostanie znalezione w mapie locals.
|
||||||
|
|
||||||
if (locals.count(cleanName)) {
|
if (locals.count(cleanName)) {
|
||||||
int offset = locals.at(cleanName);
|
int offset = locals.at(cleanName);
|
||||||
return "[rbp-" + std::to_string(offset) + "]";
|
return "[rbp-" + std::to_string(offset) + "]";
|
||||||
}
|
}
|
||||||
|
|
||||||
// Zwracamy orygina³ (jeœli to np. nazwa etykiety), ale to zazwyczaj b³¹d dla zmiennych
|
// Zwracamy orygina³ (jeœli to np. nazwa etykiety)
|
||||||
return cleanName;
|
return cleanName;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
std::string generateAssembly(const CompilerState& state) {
|
std::string generateAssembly(const CompilerState& state) {
|
||||||
// 1. NAG£ÓWEK I DEKLARACJE EXTERN
|
// 1. NAG£ÓWEK I DEKLARACJE EXTERN
|
||||||
std::string result = "default rel\n";
|
std::string result = "default rel\n";
|
||||||
@@ -55,8 +58,6 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
|
|
||||||
// Zrzucamy stringi: ETYKIETA db "TRESC", 0
|
// Zrzucamy stringi: ETYKIETA db "TRESC", 0
|
||||||
for (const auto& p : state.stringLiterals) {
|
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";
|
result += " " + p.first + " db \"" + p.second + "\", 0\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,27 +70,39 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
|
|
||||||
result += " push rbp\n";
|
result += " push rbp\n";
|
||||||
result += " mov rbp, rsp\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<std::string, int> stackMap;
|
std::map<std::string, int> stackMap;
|
||||||
int currentStack = 8;
|
int currentStack = 8;
|
||||||
|
|
||||||
// ARGUMENTY FUNKCJI
|
// 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) {
|
if (func.args.size() > 0) {
|
||||||
stackMap[func.args[0]] = currentStack;
|
stackMap[func.args[0]] = currentStack;
|
||||||
result += " mov [rbp-" + std::to_string(currentStack) + "], rcx ; arg " + func.args[0] + "\n";
|
result += " mov [rbp-" + std::to_string(currentStack) + "], rcx ; arg " + func.args[0] + "\n";
|
||||||
currentStack += 8;
|
currentStack += 8;
|
||||||
|
argIdx++;
|
||||||
}
|
}
|
||||||
if (func.args.size() > 1) {
|
if (func.args.size() > 1) {
|
||||||
stackMap[func.args[1]] = currentStack;
|
stackMap[func.args[1]] = currentStack;
|
||||||
result += " mov [rbp-" + std::to_string(currentStack) + "], rdx ; arg " + func.args[1] + "\n";
|
result += " mov [rbp-" + std::to_string(currentStack) + "], rdx ; arg " + func.args[1] + "\n";
|
||||||
currentStack += 8;
|
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
|
// GENEROWANIE INSTRUKCJI
|
||||||
for (const auto& instr : func.instructions) {
|
for (const auto& instr : func.instructions) {
|
||||||
|
|
||||||
// Rezerwacja miejsca na stosie
|
// Rezerwacja miejsca na stosie dla zmiennych
|
||||||
bool isWriteOp = (instr.type == OpType::ASSIGN ||
|
bool isWriteOp = (instr.type == OpType::ASSIGN ||
|
||||||
instr.type == OpType::ADD ||
|
instr.type == OpType::ADD ||
|
||||||
instr.type == OpType::EQ ||
|
instr.type == OpType::EQ ||
|
||||||
@@ -101,61 +114,152 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
instr.type == OpType::LOGIC_OR ||
|
instr.type == OpType::LOGIC_OR ||
|
||||||
instr.type == OpType::MSGBOX ||
|
instr.type == OpType::MSGBOX ||
|
||||||
instr.type == OpType::ARRAY_DECLARE ||
|
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") {
|
if (isWriteOp && stackMap.find(instr.arg1) == stackMap.end() && instr.arg1 != "RAX") {
|
||||||
stackMap[instr.arg1] = currentStack;
|
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) {
|
switch (instr.type) {
|
||||||
case OpType::ASSIGN: {
|
case OpType::ASSIGN: {
|
||||||
std::string src = instr.arg2;
|
// Jeœli Ÿród³em jest wynik funkcji (RAX), nie generujemy "mov rax, eax"
|
||||||
// ODCZYT TABLICY: x = t[i]
|
if (instr.arg2 == "RAX") {
|
||||||
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);
|
std::string dst = getVarLocation(instr.arg1, stackMap);
|
||||||
|
// POPRAWIONE: Tylko dwa backslashe, tak jak w reszcie kodu
|
||||||
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";
|
result += " mov " + dst + ", rax\n";
|
||||||
}
|
}
|
||||||
else if (instr.arg3 == "STRING") {
|
else if (instr.arg3.find("ARRAY_IDX:") == 0) {
|
||||||
// Przypisanie stringa: ³adujemy ADRES (LEA)
|
std::string indexStr = instr.arg3.substr(10);
|
||||||
result += " lea rax, [rel " + src + "]\n";
|
std::string arrName = instr.arg2;
|
||||||
std::string dst = getVarLocation(instr.arg1, stackMap);
|
std::string dst = getVarLocation(instr.arg1, stackMap);
|
||||||
// Zapisujemy adres w zmiennej lokalnej (wskaŸnik 64-bit qword)
|
int baseOffset = stackMap[arrName];
|
||||||
result += " mov qword " + dst + ", rax\n";
|
|
||||||
|
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 {
|
else {
|
||||||
// Zwyk³e przypisanie liczby
|
|
||||||
std::string srcLoc = getVarLocation(instr.arg2, stackMap);
|
std::string srcLoc = getVarLocation(instr.arg2, stackMap);
|
||||||
std::string dst = getVarLocation(instr.arg1, stackMap);
|
std::string dst = getVarLocation(instr.arg1, stackMap);
|
||||||
|
|
||||||
if (isNumber(src)) {
|
std::string src = instr.arg2;
|
||||||
result += " mov eax, " + src + "\n";
|
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 {
|
else {
|
||||||
result += " mov eax, " + srcLoc + "\n";
|
result += " mov rax, " + getVarLocation(valStr, stackMap) + "\n";
|
||||||
}
|
}
|
||||||
result += " mov " + dst + ", eax\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;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::ADD: {
|
case OpType::ADD: {
|
||||||
@@ -214,7 +318,7 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
else {
|
else {
|
||||||
result += " idiv dword " + op2 + "\n";
|
result += " idiv dword " + op2 + "\n";
|
||||||
}
|
}
|
||||||
result += " mov " + dst + ", edx\n"; // Reszta
|
result += " mov " + dst + ", edx\n";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::EQ: {
|
case OpType::EQ: {
|
||||||
@@ -262,23 +366,10 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
}
|
}
|
||||||
case OpType::JMP_FALSE: {
|
case OpType::JMP_FALSE: {
|
||||||
std::string condRaw = instr.arg2;
|
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);
|
std::string cond = getVarLocation(condRaw, stackMap);
|
||||||
result += " mov eax, " + cond + "\n";
|
result += " mov eax, " + cond + "\n";
|
||||||
result += " test eax, eax\n";
|
result += " test eax, eax\n";
|
||||||
result += " je " + instr.arg1 + "\n";
|
result += " je " + instr.arg1 + "\n";
|
||||||
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::JMP: {
|
case OpType::JMP: {
|
||||||
@@ -286,60 +377,32 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::ARRAY_DECLARE: {
|
case OpType::ARRAY_DECLARE: {
|
||||||
std::string name = instr.arg1;
|
// Obs³u¿one przy alokacji stosu
|
||||||
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;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::ARRAY_SET: {
|
case OpType::ARRAY_SET: {
|
||||||
std::string arrName = instr.arg1; // t
|
std::string arrName = instr.arg1;
|
||||||
std::string indexStr = instr.arg2; // i
|
std::string indexStr = instr.arg2;
|
||||||
std::string valStr = instr.arg3; // val
|
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 {
|
else {
|
||||||
std::string valLoc = getVarLocation(valStr, stackMap);
|
std::string valLoc = getVarLocation(valStr, stackMap);
|
||||||
// Jeœli to zmienna ze stosu, to movsxd (rozszerzenie znaku) lub mov
|
result += " mov rax, " + valLoc + "\n";
|
||||||
result += " mov rax, " + valLoc + "\n"; // Zak³adamy 64-bit (lub eax dla 32)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
int baseOffset = stackMap[arrName];
|
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 {
|
else {
|
||||||
std::string idxLoc = getVarLocation(indexStr, stackMap);
|
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";
|
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 += " mov rdx, rbp\n";
|
||||||
result += " sub rdx, " + std::to_string(baseOffset) + "\n"; // RDX = adres t[0]
|
result += " sub rdx, " + std::to_string(baseOffset) + "\n";
|
||||||
result += " sub rdx, rcx\n"; // RDX = adres t[i]
|
result += " sub rdx, rcx\n";
|
||||||
|
|
||||||
// Zapisujemy wartoϾ (RAX) pod adres (RDX)
|
|
||||||
result += " mov [rdx], rax\n";
|
result += " mov [rdx], rax\n";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -348,7 +411,6 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::PRINT: {
|
case OpType::PRINT: {
|
||||||
// Instrukcja PRINT zwyk³a (liczba)
|
|
||||||
std::string val = getVarLocation(instr.arg1, stackMap);
|
std::string val = getVarLocation(instr.arg1, stackMap);
|
||||||
result += " mov edx, " + val + "\n";
|
result += " mov edx, " + val + "\n";
|
||||||
result += " lea rcx, [rel fmt_int]\n";
|
result += " lea rcx, [rel fmt_int]\n";
|
||||||
@@ -371,11 +433,7 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::CALL: {
|
case OpType::CALL: {
|
||||||
if (instr.arg1 == "input") {
|
if (instr.arg1 == "input" || instr.arg1 == "read_key") {
|
||||||
result += " call _getch\n";
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
if (instr.arg1 == "read_key") {
|
|
||||||
result += " call _getch\n";
|
result += " call _getch\n";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -391,30 +449,56 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Standardowe wywo³anie funkcji
|
// Call metody/funkcji
|
||||||
|
std::string funcName = instr.arg1;
|
||||||
std::string argsRaw = instr.arg2;
|
std::string argsRaw = instr.arg2;
|
||||||
std::vector<std::string> callArgs;
|
std::vector<std::string> callArgs;
|
||||||
|
|
||||||
if (!argsRaw.empty()) {
|
if (!argsRaw.empty()) {
|
||||||
size_t comma = argsRaw.find(',');
|
std::stringstream ss(argsRaw);
|
||||||
if (comma != std::string::npos) {
|
std::string segment;
|
||||||
callArgs.push_back(argsRaw.substr(0, comma));
|
while (std::getline(ss, segment, ',')) {
|
||||||
callArgs.push_back(argsRaw.substr(comma + 1));
|
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 {
|
else {
|
||||||
callArgs.push_back(argsRaw);
|
// 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) {
|
if (callArgs.size() > 1) {
|
||||||
std::string val = getVarLocation(callArgs[1], stackMap);
|
std::string val = getVarLocation(callArgs[1], stackMap);
|
||||||
if (isNumber(val)) result += " mov rdx, " + val + "\n";
|
if (isNumber(val)) result += " mov rdx, " + val + "\n";
|
||||||
else result += " movsxd rdx, dword " + val + "\n";
|
else result += " movsxd rdx, dword " + val + "\n";
|
||||||
}
|
}
|
||||||
if (callArgs.size() > 0) {
|
|
||||||
std::string val = getVarLocation(callArgs[0], stackMap);
|
// ... (dalsze argumenty R8, R9 jeœli potrzebujesz)
|
||||||
if (isNumber(val)) result += " mov rcx, " + val + "\n";
|
|
||||||
else result += " movsxd rcx, dword " + val + "\n";
|
result += " call " + funcName + "\n";
|
||||||
}
|
|
||||||
result += " call " + instr.arg1 + "\n";
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::RETURN: {
|
case OpType::RETURN: {
|
||||||
@@ -427,41 +511,23 @@ std::string generateAssembly(const CompilerState& state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case OpType::MSGBOX: {
|
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 title = instr.arg1;
|
||||||
std::string text = instr.arg2;
|
std::string text = instr.arg2;
|
||||||
|
|
||||||
// --- 1. Ustawiamy RDX (TreϾ) ---
|
if (text.find("str_") == 0) result += " lea rdx, [rel " + text + "]\n";
|
||||||
if (text.find("str_") == 0) {
|
|
||||||
// Jeœli to litera³ (np. str_5), ³adujemy jego adres (LEA)
|
|
||||||
result += " lea rdx, [rel " + text + "]\n";
|
|
||||||
}
|
|
||||||
else {
|
else {
|
||||||
// Jeœli to zmienna, pobieramy jej wartoœæ ze stosu (która jest adresem)
|
|
||||||
std::string loc = getVarLocation(text, stackMap);
|
std::string loc = getVarLocation(text, stackMap);
|
||||||
result += " mov rdx, " + loc + "\n";
|
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 {
|
else {
|
||||||
std::string loc = getVarLocation(title, stackMap);
|
std::string loc = getVarLocation(title, stackMap);
|
||||||
result += " mov r8, " + loc + "\n";
|
result += " mov r8, " + loc + "\n";
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 3. Pozosta³e argumenty (Sta³e) ---
|
result += " mov rcx, 0\n";
|
||||||
result += " mov rcx, 0\n"; // HWND = NULL
|
result += " mov r9, 0\n";
|
||||||
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";
|
result += " call MessageBoxA\n";
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,11 +16,11 @@ enum class OpType {
|
|||||||
MOD, // a = b % c
|
MOD, // a = b % c
|
||||||
EQ, // a == b
|
EQ, // a == b
|
||||||
PRINT, // print(int)
|
PRINT, // print(int)
|
||||||
PRINT_STRING, // print(string) - NOWE
|
PRINT_STRING, // print(string)
|
||||||
JMP_FALSE, // if (false) skocz...
|
JMP_FALSE, // if (false) skocz...
|
||||||
ARRAY_DECLARE, // int t[10];
|
ARRAY_DECLARE, // int t[10];
|
||||||
ARRAY_SET, // t[0] = 5;
|
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
|
JMP, // else / pêtla
|
||||||
LOGIC_AND, // &&
|
LOGIC_AND, // &&
|
||||||
LOGIC_OR, // ||
|
LOGIC_OR, // ||
|
||||||
@@ -28,6 +28,9 @@ enum class OpType {
|
|||||||
CALL, // wywo³anie funkcji
|
CALL, // wywo³anie funkcji
|
||||||
RETURN, // return x
|
RETURN, // return x
|
||||||
MSGBOX, // msg box
|
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
|
NOP // pusta instrukcja
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -47,11 +50,37 @@ struct Function {
|
|||||||
std::vector<Instruction> instructions;
|
std::vector<Instruction> 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<std::string> args;
|
||||||
|
std::string mangledName; // np. "User_setAge"
|
||||||
|
};
|
||||||
|
|
||||||
|
// Definicja klasy
|
||||||
|
struct ClassDef {
|
||||||
|
std::string name;
|
||||||
|
std::vector<ClassField> fields;
|
||||||
|
std::vector<ClassMethod> methods;
|
||||||
|
int totalSize; // rozmiar ca³ego obiektu w bajtach
|
||||||
|
};
|
||||||
|
|
||||||
// G£ÓWNY STAN KOMPILATORA
|
// G£ÓWNY STAN KOMPILATORA
|
||||||
struct CompilerState {
|
struct CompilerState {
|
||||||
// Mapa funkcji
|
// Mapa funkcji
|
||||||
std::map<std::string, Function> functions;
|
std::map<std::string, Function> functions;
|
||||||
|
|
||||||
|
// Mapa klas (NOWE)
|
||||||
|
std::map<std::string, ClassDef> classes;
|
||||||
|
|
||||||
// Zmienne globalne
|
// Zmienne globalne
|
||||||
std::map<std::string, int> globals;
|
std::map<std::string, int> globals;
|
||||||
|
|
||||||
@@ -61,6 +90,7 @@ struct CompilerState {
|
|||||||
|
|
||||||
// Stan parsera
|
// Stan parsera
|
||||||
Function* currentFunction = nullptr;
|
Function* currentFunction = nullptr;
|
||||||
|
std::string currentClass = ""; // (NOWE) - nazwa aktualnie parsowanej klasy
|
||||||
int labelCounter = 0;
|
int labelCounter = 0;
|
||||||
|
|
||||||
// Stosy bloków
|
// Stosy bloków
|
||||||
|
|||||||
@@ -4,6 +4,17 @@
|
|||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
// ===================================================================
|
||||||
|
// 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<std::string> parseArgs(const std::string& line) {
|
std::vector<std::string> parseArgs(const std::string& line) {
|
||||||
std::vector<std::string> args;
|
std::vector<std::string> args;
|
||||||
size_t open = line.find('(');
|
size_t open = line.find('(');
|
||||||
@@ -17,8 +28,7 @@ std::vector<std::string> parseArgs(const std::string& line) {
|
|||||||
std::string segment;
|
std::string segment;
|
||||||
while (std::getline(ss, segment, ',')) {
|
while (std::getline(ss, segment, ',')) {
|
||||||
segment = trim(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) {
|
if (space != std::string::npos) {
|
||||||
args.push_back(trim(segment.substr(space + 1)));
|
args.push_back(trim(segment.substr(space + 1)));
|
||||||
}
|
}
|
||||||
@@ -26,72 +36,81 @@ std::vector<std::string> parseArgs(const std::string& line) {
|
|||||||
return args;
|
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) {
|
std::string registerStringLiteral(CompilerState& state, std::string content) {
|
||||||
// Używamy stringCounter z CompilerState
|
|
||||||
std::string label = "str_" + std::to_string(state.stringCounter++);
|
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 });
|
state.stringLiterals.push_back({ label, content });
|
||||||
|
|
||||||
return label;
|
return label;
|
||||||
}
|
}
|
||||||
|
|
||||||
void processSource(const std::string& src, CompilerState& state) {
|
int getClassFieldOffset(CompilerState& state, const std::string& fieldName) {
|
||||||
std::istringstream iss(src);
|
if (state.currentClass.empty()) return -1;
|
||||||
std::vector<std::string> lines;
|
if (state.classes.count(state.currentClass) == 0) return -1;
|
||||||
{
|
|
||||||
std::istringstream iss(src);
|
const auto& fields = state.classes[state.currentClass].fields;
|
||||||
std::string t;
|
for (const auto& f : fields) {
|
||||||
while (std::getline(iss, t)) lines.push_back(trim(t));
|
if (f.name == fieldName) return f.offset;
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
for (size_t i = 0; i < lines.size(); i++) {
|
// ===================================================================
|
||||||
std::string line = trim(lines[i]);
|
// FUNKCJE POMOCNICZE DO OBSŁUGI WARUNKÓW
|
||||||
if (line.empty() || line.substr(0, 2) == "//" || line[0] == '#') continue;
|
// ===================================================================
|
||||||
|
|
||||||
if (line.find("} else") != std::string::npos) {
|
std::string processCondition(const std::string& conditionRaw, Function& f, CompilerState& state) {
|
||||||
// najpierw obsłuż zamknięcie bloku
|
std::string cond = trim(conditionRaw);
|
||||||
std::string saved = line;
|
|
||||||
line = "}";
|
int fieldOffset = getClassFieldOffset(state, cond);
|
||||||
// ... uruchom kod obsługi "}" (najlepiej przenieś go do funkcji pomocniczej)
|
if (fieldOffset != -1) {
|
||||||
// potem obsłuż else:
|
std::string tmp = "_cond_fld_" + std::to_string(state.labelCounter++);
|
||||||
line = "else";
|
f.instructions.push_back({ OpType::LOAD_FIELD, tmp, "this", std::to_string(fieldOffset) });
|
||||||
// ... uruchom kod obsługi else
|
cond = tmp;
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
// 1. DEFINICJA FUNKCJI (np. void main() { )
|
if (offA != -1) {
|
||||||
// =========================================================
|
std::string t = "_c_a_" + std::to_string(state.labelCounter++);
|
||||||
bool startsWithType = (line.rfind("int ", 0) == 0 || line.rfind("void ", 0) == 0 || line.rfind("bool ", 0) == 0);
|
f.instructions.push_back({ OpType::LOAD_FIELD, t, "this", std::to_string(offA) });
|
||||||
if (startsWithType && line.find("(") != std::string::npos && line.find("{") != std::string::npos && line.find("=") == std::string::npos) {
|
a = t;
|
||||||
|
}
|
||||||
size_t openParen = line.find('(');
|
int offB = getClassFieldOffset(state, b);
|
||||||
std::string typeRaw = line.substr(0, line.find(' '));
|
if (offB != -1) {
|
||||||
std::string nameRaw = line.substr(typeRaw.length(), openParen - typeRaw.length());
|
std::string t = "_c_b_" + std::to_string(state.labelCounter++);
|
||||||
std::string funcName = trim(nameRaw);
|
f.instructions.push_back({ OpType::LOAD_FIELD, t, "this", std::to_string(offB) });
|
||||||
|
b = t;
|
||||||
Function newFunc;
|
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================================
|
std::string tmp = "_cond_tmp_" + std::to_string(state.labelCounter++);
|
||||||
// 2. ZAMYKANIE BLOKU '}' (Koniec funkcji, IF‑a lub WHILE‑a)
|
f.instructions.push_back({ OpType::EQ, tmp, a, b });
|
||||||
// =========================================================
|
return tmp;
|
||||||
if (line == "}") {
|
}
|
||||||
|
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<std::string>& lines, size_t i) {
|
||||||
|
if (state.blockStack.empty()) {
|
||||||
|
state.currentFunction = nullptr;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// lookahead: czy następna sensowna linia to "else" / "else {"
|
|
||||||
bool nextIsElse = false;
|
bool nextIsElse = false;
|
||||||
size_t j = i + 1;
|
size_t j = i + 1;
|
||||||
while (j < lines.size()) {
|
while (j < lines.size()) {
|
||||||
@@ -101,13 +120,10 @@ void processSource(const std::string& src, CompilerState& state) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!state.blockStack.empty()) {
|
|
||||||
std::string blockInfo = state.blockStack.top();
|
std::string blockInfo = state.blockStack.top();
|
||||||
|
|
||||||
// --- WHILE ---
|
|
||||||
if (blockInfo.rfind("WHILE|", 0) == 0) {
|
if (blockInfo.rfind("WHILE|", 0) == 0) {
|
||||||
state.blockStack.pop();
|
state.blockStack.pop();
|
||||||
|
|
||||||
size_t p1 = blockInfo.find('|');
|
size_t p1 = blockInfo.find('|');
|
||||||
size_t p2 = blockInfo.rfind('|');
|
size_t p2 = blockInfo.rfind('|');
|
||||||
std::string labelStart = blockInfo.substr(p1 + 1, p2 - p1 - 1);
|
std::string labelStart = blockInfo.substr(p1 + 1, p2 - p1 - 1);
|
||||||
@@ -117,69 +133,60 @@ void processSource(const std::string& src, CompilerState& state) {
|
|||||||
state.currentFunction->instructions.push_back({ OpType::JMP, labelStart, "", "" });
|
state.currentFunction->instructions.push_back({ OpType::JMP, labelStart, "", "" });
|
||||||
state.currentFunction->instructions.push_back({ OpType::LABEL, labelEnd, "", "" });
|
state.currentFunction->instructions.push_back({ OpType::LABEL, labelEnd, "", "" });
|
||||||
}
|
}
|
||||||
continue;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- IF (specjalny wpis IF|else|end) ---
|
|
||||||
if (blockInfo.rfind("IF|", 0) == 0) {
|
if (blockInfo.rfind("IF|", 0) == 0) {
|
||||||
state.blockStack.pop();
|
state.blockStack.pop();
|
||||||
|
|
||||||
size_t p1 = blockInfo.find('|');
|
size_t p1 = blockInfo.find('|');
|
||||||
size_t p2 = blockInfo.rfind('|');
|
size_t p2 = blockInfo.rfind('|');
|
||||||
std::string labelElse = blockInfo.substr(p1 + 1, p2 - p1 - 1);
|
std::string labelElse = blockInfo.substr(p1 + 1, p2 - p1 - 1);
|
||||||
std::string labelEnd = blockInfo.substr(p2 + 1);
|
std::string labelEnd = blockInfo.substr(p2 + 1);
|
||||||
|
|
||||||
if (nextIsElse) {
|
if (nextIsElse) {
|
||||||
// zamykamy blok IF, ale zaraz będzie ELSE:
|
|
||||||
// 1) przeskocz ELSE po wykonaniu IF
|
|
||||||
// 2) wstaw początek ELSE
|
|
||||||
if (state.currentFunction) {
|
if (state.currentFunction) {
|
||||||
state.currentFunction->instructions.push_back({ OpType::JMP, labelEnd, "", "" });
|
state.currentFunction->instructions.push_back({ OpType::JMP, labelEnd, "", "" });
|
||||||
state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" });
|
state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" });
|
||||||
}
|
}
|
||||||
// Teraz oczekujemy na '}' kończące ELSE -> ma wstawić LABEL labelEnd
|
|
||||||
state.blockStack.push(labelEnd);
|
state.blockStack.push(labelEnd);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
// if bez else: labelElse jest po prostu "koniec if"
|
|
||||||
if (state.currentFunction) {
|
if (state.currentFunction) {
|
||||||
state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" });
|
state.currentFunction->instructions.push_back({ OpType::LABEL, labelElse, "", "" });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
continue;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- zwykły LABEL na stosie (np. koniec ELSE: labelEnd) ---
|
|
||||||
state.blockStack.pop();
|
state.blockStack.pop();
|
||||||
if (state.currentFunction) {
|
if (state.currentFunction) {
|
||||||
state.currentFunction->instructions.push_back({ OpType::LABEL, blockInfo, "", "" });
|
state.currentFunction->instructions.push_back({ OpType::LABEL, blockInfo, "", "" });
|
||||||
}
|
}
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// jeśli stos pusty -> zamykamy funkcję
|
// ===================================================================
|
||||||
state.currentFunction = nullptr;
|
// FUNKCJE OBSŁUGI INSTRUKCJI
|
||||||
continue;
|
// ===================================================================
|
||||||
}
|
|
||||||
|
|
||||||
// =========================================================
|
bool handleReturn(const std::string& line, Function& f, CompilerState& state) {
|
||||||
// JESTEŚMY W ŚRODKU FUNKCJI
|
if (line.substr(0, 6) != "return") return false;
|
||||||
// =========================================================
|
|
||||||
if (state.currentFunction) {
|
|
||||||
Function& f = *state.currentFunction;
|
|
||||||
|
|
||||||
// A. RETURN
|
|
||||||
if (line.substr(0, 6) == "return") {
|
|
||||||
std::string val = trim(line.substr(6));
|
std::string val = trim(line.substr(6));
|
||||||
if (!val.empty() && val.back() == ';') val.pop_back();
|
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, "", "" });
|
f.instructions.push_back({ OpType::RETURN, val, "", "" });
|
||||||
continue;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// B. DEKLARACJA STRINGA: string s = "hello";
|
bool handleStringDeclaration(const std::string& line, Function& f, CompilerState& state) {
|
||||||
else if (line.substr(0, 6) == "string") {
|
if (line.substr(0, 6) != "string") return false;
|
||||||
size_t eqPos = line.find("=");
|
size_t eqPos = line.find("=");
|
||||||
if (eqPos != std::string::npos) {
|
if (eqPos == std::string::npos) return false;
|
||||||
std::string name = trim(line.substr(7, eqPos - 7));
|
std::string name = trim(line.substr(7, eqPos - 7));
|
||||||
size_t quoteStart = line.find("\"", eqPos);
|
size_t quoteStart = line.find("\"", eqPos);
|
||||||
size_t quoteEnd = line.rfind("\"");
|
size_t quoteEnd = line.rfind("\"");
|
||||||
@@ -189,254 +196,446 @@ void processSource(const std::string& src, CompilerState& state) {
|
|||||||
std::string label = registerStringLiteral(state, content);
|
std::string label = registerStringLiteral(state, content);
|
||||||
state.varTypes[name] = "string";
|
state.varTypes[name] = "string";
|
||||||
f.instructions.push_back({ OpType::ASSIGN, name, label, "" });
|
f.instructions.push_back({ OpType::ASSIGN, name, label, "" });
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
}
|
return false;
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// C. DEKLARACJA TABLICY: int t[10];
|
bool handleArrayDeclaration(const std::string& line, Function& f, CompilerState& state) {
|
||||||
else if (line.substr(0, 3) == "int" && line.find("[") != std::string::npos && line.find("=") == std::string::npos) {
|
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 openBracket = line.find("[");
|
||||||
size_t closeBracket = line.find("]");
|
size_t closeBracket = line.find("]");
|
||||||
|
|
||||||
if (openBracket != std::string::npos && closeBracket > openBracket) {
|
if (openBracket != std::string::npos && closeBracket > openBracket) {
|
||||||
std::string name = trim(line.substr(3, openBracket - 3));
|
std::string name = trim(line.substr(3, openBracket - 3));
|
||||||
std::string sizeStr = trim(line.substr(openBracket + 1, closeBracket - openBracket - 1));
|
std::string sizeStr = trim(line.substr(openBracket + 1, closeBracket - openBracket - 1));
|
||||||
|
|
||||||
state.varTypes[name] = "array";
|
state.varTypes[name] = "array";
|
||||||
f.instructions.push_back({ OpType::ARRAY_DECLARE, name, sizeStr, "" });
|
f.instructions.push_back({ OpType::ARRAY_DECLARE, name, sizeStr, "" });
|
||||||
std::cout << " [PARSER] Array Decl: " << name << "[" << sizeStr << "]\n";
|
std::cout << " [PARSER] Array Decl: " << name << "[" << sizeStr << "]\\n";
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
continue;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// D. DRUKOWANIE (PRINT)
|
bool handlePrint(const std::string& line, Function& f, CompilerState& state) {
|
||||||
else if (line.substr(0, 5) == "print") {
|
if (line.substr(0, 5) != "print") return false;
|
||||||
size_t open = line.find("(");
|
size_t open = line.find("(");
|
||||||
size_t close = line.rfind(")");
|
size_t close = line.rfind(")");
|
||||||
if (open != std::string::npos && close > open) {
|
if (open == std::string::npos || close <= open) return false;
|
||||||
std::string content = trim(line.substr(open + 1, close - open - 1));
|
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() == ']') {
|
if (content.find("[") != std::string::npos && content.back() == ']') {
|
||||||
size_t opIdx = content.find("[");
|
size_t opIdx = content.find("[");
|
||||||
std::string arrName = content.substr(0, opIdx);
|
std::string arrName = content.substr(0, opIdx);
|
||||||
std::string arrIdx = content.substr(opIdx + 1, content.length() - opIdx - 2);
|
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++);
|
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::ASSIGN, tmp, arrName, "ARRAY_IDX:" + arrIdx });
|
||||||
f.instructions.push_back({ OpType::PRINT, tmp, "", "" });
|
f.instructions.push_back({ OpType::PRINT, tmp, "", "" });
|
||||||
}
|
}
|
||||||
// Literał tekstowy
|
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() == '"') {
|
else if (content.front() == '"' && content.back() == '"') {
|
||||||
std::string text = content.substr(1, content.length() - 2);
|
std::string text = content.substr(1, content.length() - 2);
|
||||||
std::string label = registerStringLiteral(state, text);
|
std::string label = registerStringLiteral(state, text);
|
||||||
f.instructions.push_back({ OpType::PRINT_STRING, label, "", "" });
|
f.instructions.push_back({ OpType::PRINT_STRING, label, "", "" });
|
||||||
}
|
}
|
||||||
// Zmienna string
|
|
||||||
else if (state.varTypes.count(content) && state.varTypes[content] == "string") {
|
else if (state.varTypes.count(content) && state.varTypes[content] == "string") {
|
||||||
f.instructions.push_back({ OpType::PRINT_STRING, content, "", "" });
|
f.instructions.push_back({ OpType::PRINT_STRING, content, "", "" });
|
||||||
}
|
}
|
||||||
// Liczba
|
|
||||||
else {
|
else {
|
||||||
f.instructions.push_back({ OpType::PRINT, content, "", "" });
|
f.instructions.push_back({ OpType::PRINT, content, "", "" });
|
||||||
}
|
}
|
||||||
}
|
return true;
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// E. IF STATEMENT (z ulepszoną obsługą else)
|
bool handleIf(const std::string& line, Function& f, CompilerState& state) {
|
||||||
else if (line.rfind("if", 0) == 0) {
|
if (line.rfind("if", 0) != 0) return false;
|
||||||
size_t openParen = line.find("(");
|
size_t openParen = line.find("(");
|
||||||
size_t closeParen = line.rfind(")");
|
size_t closeParen = line.rfind(")");
|
||||||
if (openParen != std::string::npos && closeParen > openParen) {
|
if (openParen == std::string::npos) return false;
|
||||||
std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1));
|
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 labelElse = "L_" + std::to_string(state.labelCounter++);
|
||||||
std::string labelEnd = "L_" + std::to_string(state.labelCounter++);
|
std::string labelEnd = "L_" + std::to_string(state.labelCounter++);
|
||||||
f.instructions.push_back({ OpType::JMP_FALSE, labelElse, conditionRaw, "" });
|
f.instructions.push_back({ OpType::JMP_FALSE, labelElse, finalCond, "" });
|
||||||
state.blockStack.push("IF|" + labelElse + "|" + labelEnd);
|
state.blockStack.push("IF|" + labelElse + "|" + labelEnd);
|
||||||
}
|
return true;
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool handleWhile(const std::string& line, Function& f, CompilerState& state) {
|
||||||
// F. WHILE LOOP
|
if (line.substr(0, 5) != "while") return false;
|
||||||
else if (line.substr(0, 5) == "while") {
|
|
||||||
size_t openParen = line.find("(");
|
size_t openParen = line.find("(");
|
||||||
size_t closeParen = line.rfind(")");
|
size_t closeParen = line.rfind(")");
|
||||||
if (openParen != std::string::npos && closeParen > openParen) {
|
if (openParen == std::string::npos) return false;
|
||||||
std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1));
|
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 labelStart = "L_" + std::to_string(state.labelCounter++);
|
||||||
std::string labelEnd = "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, "", "" });
|
f.instructions.push_back({ OpType::LABEL, labelStart, "", "" });
|
||||||
|
std::string finalCond = processCondition(conditionRaw, f, state);
|
||||||
// 3. OBLICZANIE WARUNKU (Tu był błąd - brakowało tego!)
|
f.instructions.push_back({ OpType::JMP_FALSE, labelEnd, finalCond, "" });
|
||||||
// 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);
|
state.blockStack.push("WHILE|" + labelStart + "|" + labelEnd);
|
||||||
}
|
return true;
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// G. MSGBOX
|
bool handleMsgbox(const std::string& line, Function& f, CompilerState& state) {
|
||||||
else if (line.substr(0, 6) == "msgbox") {
|
if (line.substr(0, 6) != "msgbox") return false;
|
||||||
// ... (Twoja logika msgbox, jest OK) ...
|
|
||||||
size_t open = line.find("(");
|
size_t open = line.find("(");
|
||||||
size_t close = line.rfind(")");
|
size_t close = line.rfind(")");
|
||||||
if (open != std::string::npos && close > open) {
|
if (open == std::string::npos) return false;
|
||||||
std::string args = line.substr(open + 1, close - open - 1);
|
std::string args = line.substr(open + 1, close - open - 1);
|
||||||
size_t comma = args.find(",");
|
size_t comma = args.find(",");
|
||||||
if (comma != std::string::npos) {
|
if (comma == std::string::npos) return false;
|
||||||
std::string arg1 = trim(args.substr(0, comma));
|
std::string arg1 = trim(args.substr(0, comma));
|
||||||
std::string arg2 = trim(args.substr(comma + 1));
|
std::string arg2 = trim(args.substr(comma + 1));
|
||||||
|
|
||||||
std::string l1 = (arg1.front() == '"') ? registerStringLiteral(state, arg1.substr(1, arg1.size() - 2)) : arg1;
|
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;
|
std::string l2 = (arg2.front() == '"') ? registerStringLiteral(state, arg2.substr(1, arg2.size() - 2)) : arg2;
|
||||||
|
|
||||||
f.instructions.push_back({ OpType::MSGBOX, l1, l2, "" });
|
f.instructions.push_back({ OpType::MSGBOX, l1, l2, "" });
|
||||||
}
|
return true;
|
||||||
}
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
else if (line.rfind("else", 0) == 0) {
|
bool handleAssignment(const std::string& line, Function& f, CompilerState& state) {
|
||||||
continue;
|
// 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;
|
||||||
}
|
}
|
||||||
|
|
||||||
// =========================================================
|
|
||||||
// H. PRZYPISANIE / OPERACJE (Linie z "=")
|
|
||||||
// =========================================================
|
|
||||||
else if (line.find("=") != std::string::npos) {
|
|
||||||
size_t eqPos = line.find('=');
|
size_t eqPos = line.find('=');
|
||||||
std::string leftSide = trim(line.substr(0, eqPos));
|
std::string leftSide = trim(line.substr(0, eqPos));
|
||||||
std::string rightSide = trim(line.substr(eqPos + 1));
|
std::string rightSide = trim(line.substr(eqPos + 1));
|
||||||
if (!rightSide.empty() && rightSide.back() == ';') rightSide.pop_back();
|
if (!rightSide.empty() && rightSide.back() == ';') rightSide.pop_back();
|
||||||
|
|
||||||
// 1. CZY TO ZAPIS DO TABLICY? t[0] = 5
|
// 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) {
|
if (leftSide.find("[") != std::string::npos) {
|
||||||
size_t open = leftSide.find("[");
|
size_t open = leftSide.find("[");
|
||||||
size_t close = leftSide.find("]");
|
size_t close = leftSide.find("]");
|
||||||
std::string arrName = trim(leftSide.substr(0, open));
|
std::string arrName = trim(leftSide.substr(0, open));
|
||||||
std::string index = trim(leftSide.substr(open + 1, close - open - 1));
|
std::string index = trim(leftSide.substr(open + 1, close - open - 1));
|
||||||
|
|
||||||
f.instructions.push_back({ OpType::ARRAY_SET, arrName, index, rightSide });
|
f.instructions.push_back({ OpType::ARRAY_SET, arrName, index, rightSide });
|
||||||
continue;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pobieramy nazwę zmiennej (usuwamy "int ", "bool ")
|
|
||||||
std::string varName = leftSide;
|
std::string varName = leftSide;
|
||||||
if (leftSide.rfind("int ", 0) == 0) varName = trim(leftSide.substr(4));
|
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("bool ", 0) == 0) varName = trim(leftSide.substr(5));
|
||||||
else if (leftSide.rfind("string ", 0) == 0) varName = trim(leftSide.substr(7));
|
else if (leftSide.rfind("string ", 0) == 0) varName = trim(leftSide.substr(7));
|
||||||
|
|
||||||
// 2. CZY TO ODCZYT Z TABLICY? x = t[0]
|
// 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() == ']') {
|
if (rightSide.find("[") != std::string::npos && rightSide.back() == ']') {
|
||||||
size_t open = rightSide.find("[");
|
size_t open = rightSide.find("[");
|
||||||
size_t close = rightSide.find("]");
|
size_t close = rightSide.find("]");
|
||||||
std::string arrName = trim(rightSide.substr(0, open));
|
std::string arrName = trim(rightSide.substr(0, open));
|
||||||
std::string index = trim(rightSide.substr(open + 1, close - open - 1));
|
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 });
|
f.instructions.push_back({ OpType::ASSIGN, varName, arrName, "ARRAY_IDX:" + index });
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
// 3. Wywołanie funkcji: x = func()
|
|
||||||
else if (rightSide.find("(") != std::string::npos && rightSide.find(")") != std::string::npos) {
|
// 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('(');
|
size_t open = rightSide.find('(');
|
||||||
std::string funcName = trim(rightSide.substr(0, open));
|
std::string funcName = trim(rightSide.substr(0, open));
|
||||||
std::string argsContent = rightSide.substr(open + 1, rightSide.find(')') - open - 1);
|
std::string argsContent = rightSide.substr(open + 1, rightSide.find(')') - open - 1);
|
||||||
|
|
||||||
f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" });
|
f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" });
|
||||||
f.instructions.push_back({ OpType::ASSIGN, varName, "RAX", "" });
|
f.instructions.push_back({ OpType::ASSIGN, varName, "RAX", "" });
|
||||||
|
return true;
|
||||||
}
|
}
|
||||||
// 4. Operacje arytmetyczne
|
|
||||||
else if (rightSide.find("+") != std::string::npos) {
|
// Arytmetyka
|
||||||
size_t opPos = rightSide.find("+");
|
struct Operator { std::string symbol; OpType type; size_t length; };
|
||||||
f.instructions.push_back({ OpType::ADD, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) });
|
std::vector<Operator> 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;
|
||||||
}
|
}
|
||||||
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("*");
|
if (rightSide.size() >= 2 && rightSide.front() == '"') {
|
||||||
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 content = rightSide.substr(1, rightSide.size() - 2);
|
||||||
std::string label = registerStringLiteral(state, content);
|
std::string label = registerStringLiteral(state, content);
|
||||||
state.varTypes[varName] = "string";
|
state.varTypes[varName] = "string";
|
||||||
f.instructions.push_back({ OpType::ASSIGN, varName, label, "" });
|
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) });
|
||||||
}
|
}
|
||||||
// 7. Zwykłe przypisanie wartości
|
|
||||||
else {
|
else {
|
||||||
f.instructions.push_back({ OpType::ASSIGN, varName, rightSide, "" });
|
f.instructions.push_back({ OpType::ASSIGN, varName, rightSide, "" });
|
||||||
}
|
}
|
||||||
continue;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// I. SAMODZIELNE WYWOŁANIE FUNKCJI (np. input(); )
|
bool handleFunctionCall(const std::string& line, Function& f) {
|
||||||
else if (line.find("(") != std::string::npos && line.find(")") != std::string::npos) {
|
if (line.find("(") == std::string::npos || line.find(")") == std::string::npos) return false;
|
||||||
size_t open = line.find('(');
|
size_t open = line.find('(');
|
||||||
std::string funcName = trim(line.substr(0, open));
|
std::string funcName = trim(line.substr(0, open));
|
||||||
std::string argsContent = line.substr(open + 1, line.find(')') - open - 1);
|
std::string argsContent = line.substr(open + 1, line.find(')') - open - 1);
|
||||||
|
|
||||||
f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" });
|
f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" });
|
||||||
std::cout << " [PARSER] Call void: " << funcName << "\n";
|
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<std::string>& 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<std::string> 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) {
|
||||||
|
handleBlockClose(state, lines, i);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line.rfind("class ", 0) == 0 && line.find("{") != std::string::npos) {
|
||||||
|
parseClassDefinition(lines, i, state);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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());
|
||||||
|
std::string funcName = trim(nameRaw);
|
||||||
|
|
||||||
|
Function newFunc;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (line == "}") {
|
||||||
|
handleBlockClose(state, lines, i);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.currentFunction) {
|
||||||
|
parseInstruction(line, *state.currentFunction, state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user