#include "parser.h" #include "utils.h" #include #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('('); size_t close = line.find(')'); if (open == std::string::npos || close == std::string::npos) return args; std::string inside = line.substr(open + 1, close - open - 1); if (inside.empty()) return args; std::stringstream ss(inside); std::string segment; while (std::getline(ss, segment, ',')) { segment = trim(segment); size_t space = segment.find_last_of(" \\t"); if (space != std::string::npos) { args.push_back(trim(segment.substr(space + 1))); } } return args; } std::string registerStringLiteral(CompilerState& state, std::string content) { std::string label = "str_" + std::to_string(state.stringCounter++); state.stringLiterals.push_back({ label, content }); return label; } 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) { 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); } } } void calculateExpressions(CompilerState& state) {}