String Update

This commit is contained in:
mmichlol
2026-02-07 19:44:03 +01:00
parent c37a122850
commit 3916b4ff7a
3 changed files with 232 additions and 244 deletions

View File

@@ -37,7 +37,8 @@ std::string getVarLocation(const std::string& name, const std::map<std::string,
}
std::string generateAssembly(const CompilerState& state) {
std::string result;
// 1. NAG£ÓWEK I DEKLARACJE EXTERN
std::string result = "default rel\n";
result += "global main\n";
result += "extern printf\n";
result += "extern getchar\n";
@@ -45,15 +46,21 @@ std::string generateAssembly(const CompilerState& state) {
result += "extern rand\n";
result += "extern srand\n";
result += "extern time\n";
result += "section .data\n";
result += " fmt db '%d', 10, 0\n";
result += "section .data\n";
result += " fmt_int db '%d', 10, 0\n"; // Format dla liczb
result += " fmt_str db '%s', 10, 0\n"; // Format dla stringów
// --- WYPISYWANIE STRINGÓW ---
for (const auto& pair : state.stringLiterals) { result += " " + pair.second + " db '" + pair.first + "', 0\n"; }
result += "section .text\n\n";
// 2. SEKCJA DATA (Tylko raz!)
result += "section .data\n";
result += " fmt_int db \"%lld\", 10, 0\n"; // Format dla liczb
result += " fmt_str db \"%s\", 10, 0\n"; // Format dla stringów
// Zrzucamy stringi: ETYKIETA db "TRESC", 0
for (const auto& p : state.stringLiterals) {
// p.first -> Etykieta (np. str_0)
// p.second -> TreϾ (np. Hello World)
result += " " + p.first + " db \"" + p.second + "\", 0\n";
}
// 3. SEKCJA TEXT (Kod programu)
result += "section .text\n";
for (const auto& pair : state.functions) {
const Function& func = pair.second;
@@ -66,7 +73,7 @@ std::string generateAssembly(const CompilerState& state) {
std::map<std::string, int> stackMap;
int currentStack = 8;
// 1. ARGUMENTY
// ARGUMENTY FUNKCJI
if (func.args.size() > 0) {
stackMap[func.args[0]] = currentStack;
result += " mov [rbp-" + std::to_string(currentStack) + "], rcx ; arg " + func.args[0] + "\n";
@@ -78,11 +85,10 @@ std::string generateAssembly(const CompilerState& state) {
currentStack += 8;
}
// 2. INSTRUKCJE
// GENEROWANIE INSTRUKCJI
for (const auto& instr : func.instructions) {
// Rezerwacja miejsca dla nowych zmiennych (wynikowych)
// Dodajemy tu OpType::SUB i OpType::MUL
// Rezerwacja miejsca na stosie
bool isWriteOp = (instr.type == OpType::ASSIGN ||
instr.type == OpType::ADD ||
instr.type == OpType::EQ ||
@@ -102,14 +108,23 @@ std::string generateAssembly(const CompilerState& state) {
case OpType::ASSIGN: {
std::string src = instr.arg2;
if (instr.arg3 == "STRING") {
// Przypisanie stringa: ³adujemy ADRES (LEA)
result += " lea rax, [rel " + src + "]\n";
std::string dst = getVarLocation(instr.arg1, stackMap);
// Zapisujemy adres w zmiennej lokalnej (wskaŸnik 64-bit qword)
result += " mov qword " + dst + ", rax\n";
}
else {
// Zwyk³e przypisanie liczby
std::string srcLoc = getVarLocation(instr.arg2, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
if (isNumber(src)) {
result += " mov eax, " + src + "\n";
}
else {
result += " mov eax, " + srcLoc + "\n";
}
result += " mov " + dst + ", eax\n";
}
break;
@@ -124,29 +139,55 @@ std::string generateAssembly(const CompilerState& state) {
break;
}
case OpType::SUB: {
// a = b - c
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " sub eax, " + op2 + "\n"; // sub = odejmowanie
result += " sub eax, " + op2 + "\n";
result += " mov " + dst + ", eax\n";
break;
}
case OpType::MUL: {
// a = b * c
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
// Mno¿enie w x86 jest specyficzne: imul eax, operand
// Wynik l¹duje w eax (i edx jeœli du¿y, ale ignorujemy nadmiar dla prostoty)
result += " imul eax, " + op2 + "\n";
result += " mov " + dst + ", eax\n";
break;
}
case OpType::DIV: {
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cdq\n";
if (isdigit(op2[0]) || op2[0] == '-') {
result += " mov ecx, " + op2 + "\n";
result += " idiv ecx\n";
}
else {
result += " idiv dword " + op2 + "\n";
}
result += " mov " + dst + ", eax\n";
break;
}
case OpType::MOD: {
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cdq\n";
if (isdigit(op2[0]) || op2[0] == '-') {
result += " mov ecx, " + op2 + "\n";
result += " idiv ecx\n";
}
else {
result += " idiv dword " + op2 + "\n";
}
result += " mov " + dst + ", edx\n"; // Reszta
break;
}
case OpType::EQ: {
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
@@ -158,34 +199,59 @@ std::string generateAssembly(const CompilerState& state) {
result += " mov " + dst + ", eax\n";
break;
}
case OpType::LOGIC_AND: {
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cmp eax, 0\n";
result += " setne al\n";
if (isdigit(op2[0])) result += " mov ecx, " + op2 + "\n";
else result += " mov ecx, " + op2 + "\n";
result += " cmp ecx, 0\n";
result += " setne cl\n";
result += " and al, cl\n";
result += " movzx eax, al\n";
result += " mov " + dst + ", eax\n";
break;
}
case OpType::LOGIC_OR: {
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cmp eax, 0\n";
result += " setne al\n";
if (isdigit(op2[0])) result += " mov ecx, " + op2 + "\n";
else result += " mov ecx, " + op2 + "\n";
result += " cmp ecx, 0\n";
result += " setne cl\n";
result += " or al, cl\n";
result += " movzx eax, al\n";
result += " mov " + dst + ", eax\n";
break;
}
case OpType::JMP_FALSE: {
// PARSOWANIE WARUNKU: np. "suma == 30" lub "test"
std::string condRaw = instr.arg2;
size_t eqPos = condRaw.find("==");
if (eqPos != std::string::npos) {
// Mamy porównanie w IFie (a == b)
std::string leftStr = condRaw.substr(0, eqPos);
std::string rightStr = condRaw.substr(eqPos + 2);
std::string op1 = getVarLocation(leftStr, stackMap);
std::string op2 = getVarLocation(rightStr, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cmp eax, " + op2 + "\n";
result += " jne " + instr.arg1 + " ; jump if NOT equal\n";
result += " jne " + instr.arg1 + "\n";
}
else {
// Zwyk³a zmienna boolowska (if test)
std::string cond = getVarLocation(condRaw, stackMap);
result += " mov eax, " + cond + "\n";
result += " test eax, eax\n";
result += " jz " + instr.arg1 + " ; jump if zero\n";
result += " jz " + instr.arg1 + "\n";
}
break;
}
case OpType::JMP: {
// Skok bezwarunkowy (u¿ywany na koñcu pêtli while)
result += " jmp " + instr.arg1 + "\n";
break;
}
@@ -193,50 +259,54 @@ std::string generateAssembly(const CompilerState& state) {
result += instr.arg1 + ":\n";
break;
}
case OpType::RETURN: {
std::string val = getVarLocation(instr.arg1, stackMap);
if (val.empty() || val == ";");
else {
result += " mov eax, " + val + " ; return value\n";
}
result += " leave\n";
result += " ret\n";
break;
}
case OpType::PRINT: {
if (instr.arg2 == "STRING") {
result += " lea rdx, [rel " + instr.arg1 + "]\n";
result += " lea rcx, [rel fmt_str]\n";
result += " call printf\n";
}
else {
// Instrukcja PRINT zwyk³a (liczba)
std::string val = getVarLocation(instr.arg1, stackMap);
result += " mov edx, " + val + "\n";
result += " lea rcx, [rel fmt_int]\n";
result += " call printf\n";
break;
}
case OpType::PRINT_STRING: {
// Instrukcja PRINT_STRING (tekst)
std::string target = instr.arg1;
if (target.find("str_") == 0) {
// Litera³: print("tekst")
result += " lea rdx, [rel " + target + "]\n";
}
else {
// Zmienna: print(s) -> s trzyma adres
std::string val = getVarLocation(target, stackMap);
result += " mov rdx, " + val + "\n";
}
result += " lea rcx, [rel fmt_str]\n";
result += " call printf\n";
break;
}
case OpType::CALL: {
// Parsowanie argumentów
std::string argsRaw = instr.arg2;
std::vector<std::string> callArgs;
// --- SPECJALNE FUNKCJE SYSTEMOWE ---
// 1. input() - czeka na ENTER (stare)
if (instr.arg1 == "input") {
result += " call getchar\n";
break;
}
// 2. read_key() - zwraca kod wciœniêtego klawisza (NOWOŒÆ)
if (instr.arg1 == "read_key") {
result += " call _getch\n"; // Zwraca kod znaku w EAX
// Jeœli to klawisz specjalny (strza³ki), _getch zwraca 0 lub 224,
// a potem trzeba wywo³aæ go drugi raz.
// Na razie zróbmy prosto: zwracamy to co zwróci³ pierwszy _getch.
result += " call _getch\n";
break;
}
if (instr.arg1 == "sys_seed") {
result += " mov rcx, 0\n";
result += " call time\n";
result += " mov rcx, rax\n";
result += " call srand\n";
break;
}
if (instr.arg1 == "sys_rand") {
result += " call rand\n";
break;
}
// Standardowe wywo³anie funkcji
std::string argsRaw = instr.arg2;
std::vector<std::string> callArgs;
if (!argsRaw.empty()) {
size_t comma = argsRaw.find(',');
if (comma != std::string::npos) {
@@ -247,137 +317,26 @@ std::string generateAssembly(const CompilerState& state) {
callArgs.push_back(argsRaw);
}
}
// Obs³uga RDX (arg 2)
if (callArgs.size() > 1) {
std::string val = getVarLocation(callArgs[1], stackMap);
if (isNumber(val)) {
// Jeœli liczba: mov rdx, 100
result += " mov rdx, " + val + "\n";
if (isNumber(val)) result += " mov rdx, " + val + "\n";
else result += " movsxd rdx, dword " + val + "\n";
}
else {
// Jeœli zmienna/pamiêæ: movsxd rdx, dword [rbp-8]
result += " movsxd rdx, dword " + val + "\n";
}
}
// Obs³uga RCX (arg 1)
if (callArgs.size() > 0) {
std::string val = getVarLocation(callArgs[0], stackMap);
if (isNumber(val)) {
result += " mov rcx, " + val + "\n";
if (isNumber(val)) result += " mov rcx, " + val + "\n";
else result += " movsxd rcx, dword " + val + "\n";
}
else {
result += " movsxd rcx, dword " + val + "\n";
}
}
// ... wewn¹trz case OpType::CALL ...
if (instr.arg1 == "sys_seed") {
result += " mov rcx, 0\n";
result += " call time\n"; // Pobierz czas
result += " mov rcx, rax\n"; // Czas jako argument dla srand
result += " call srand\n"; // Inicjuj generator
break;
}
if (instr.arg1 == "sys_rand") {
result += " call rand\n"; // Wynik w EAX
break;
}
result += " call " + instr.arg1 + "\n";
break;
}
case OpType::DIV: {
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cdq\n"; // Rozszerza EAX na EDX:EAX (konieczne przed dzieleniem)
// IDIV nie przyjmuje sta³ej (np. 10), musi byæ rejestr
if (isdigit(op2[0]) || op2[0] == '-') {
result += " mov ecx, " + op2 + "\n";
result += " idiv ecx\n";
case OpType::RETURN: {
std::string val = getVarLocation(instr.arg1, stackMap);
if (!val.empty() && val != ";") {
result += " mov eax, " + val + "\n";
}
else {
result += " idiv dword " + op2 + "\n";
}
result += " mov " + dst + ", eax\n"; // Wynik dzielenia
break;
}
case OpType::MOD: {
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cdq\n"; // Rozszerza EAX
if (isdigit(op2[0]) || op2[0] == '-') {
result += " mov ecx, " + op2 + "\n";
result += " idiv ecx\n";
}
else {
result += " idiv dword " + op2 + "\n";
}
result += " mov " + dst + ", edx\n"; // EDX to reszta z dzielenia!
break;
}
case OpType::LOGIC_AND: {
// a && b
// Algorytm: result = (op1 != 0) * (op2 != 0)
// Ale w ASM ³atwiej:
// cmp op1, 0 -> setne al
// cmp op2, 0 -> setne bl
// and al, bl
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
// Sprawdzamy op1
result += " mov eax, " + op1 + "\n";
result += " cmp eax, 0\n";
result += " setne al\n"; // al = 1 jeœli eax != 0
// Sprawdzamy op2 (u¿ywamy ECX jako pomocniczy)
if (isdigit(op2[0])) result += " mov ecx, " + op2 + "\n";
else result += " mov ecx, " + op2 + "\n";
result += " cmp ecx, 0\n";
result += " setne cl\n"; // cl = 1 jeœli ecx != 0
// Logiczne AND na bajtach
result += " and al, cl\n";
// Zapisujemy wynik (rozszerzamy bajt do dword)
result += " movzx eax, al\n";
result += " mov " + dst + ", eax\n";
break;
}
case OpType::LOGIC_OR: {
// a || b
std::string op1 = getVarLocation(instr.arg2, stackMap);
std::string op2 = getVarLocation(instr.arg3, stackMap);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cmp eax, 0\n";
result += " setne al\n";
if (isdigit(op2[0])) result += " mov ecx, " + op2 + "\n";
else result += " mov ecx, " + op2 + "\n";
result += " cmp ecx, 0\n";
result += " setne cl\n";
// Logiczne OR
result += " or al, cl\n";
result += " movzx eax, al\n";
result += " mov " + dst + ", eax\n";
result += " leave\n";
result += " ret\n";
break;
}
}

View File

@@ -6,14 +6,17 @@
#include <map>
#include <stack>
// Typy operacji, które nasz kompilator rozumie
// Typy operacji
enum class OpType {
ASSIGN, // a = 5
ADD, // a = b + c
SUB, // a = b - c
MUL, // a = b * c
DIV, // a = b / c
MOD, // a = b % c
EQ, // a == b
PRINT, // print(a)
PRINT, // print(int)
PRINT_STRING, // print(string) - NOWE
JMP_FALSE, // if (false) skocz...
JMP, // else / pêtla
LOGIC_AND, // &&
@@ -21,12 +24,10 @@ enum class OpType {
LABEL, // miejsce skoku
CALL, // wywo³anie funkcji
RETURN, // return x
DIV, // dzielenie
MOD, // Reszta z dzelenia (%)
NOP // pusta instrukcja
};
// Pojedynczy rozkaz kompilatora (Intermediate Representation)
// Pojedynczy rozkaz
struct Instruction {
OpType type;
std::string arg1;
@@ -37,27 +38,43 @@ struct Instruction {
// Definicja funkcji
struct Function {
std::string name;
std::string returnType; // "int", "void", "bool"
std::vector<std::string> args; // Nazwy argumentów (np. "a", "b")
std::vector<Instruction> instructions; // Lista rozkazów w funkcji
std::string returnType;
std::vector<std::string> args;
std::vector<Instruction> instructions;
};
// G£ÓWNY STAN KOMPILATORA
struct CompilerState {
// Mapa wszystkich funkcji (klucz to nazwa)
// Mapa funkcji
std::map<std::string, Function> functions;
// Zmienne globalne (tylko nazwa -> wartoœæ pocz¹tkowa)
// Zmienne globalne
std::map<std::string, int> globals;
// Stan parsera
Function* currentFunction = nullptr; // WskaŸnik na aktualnie parsuj¹c¹ siê funkcjê
int labelCounter = 0; // Do generowania unikalnych nazw etykiet (L1, L2...)
std::stack<std::string> loopStack; // Do break/continue (przysz³oœciowo)
// Zarz¹dzanie stosem
std::map<std::string, int> stackMap;
int stackOffset = 0;
// Stan parsera
Function* currentFunction = nullptr;
int labelCounter = 0;
// Stosy bloków
std::stack<std::string> loopStack;
std::stack<std::string> blockStack;
std::map<std::string, std::string> stringLiterals;
// --- SEKCJA STRINGÓW (TU BY£Y B£ÊDY) ---
// Lista litera³ów do sekcji .data (np. "str_0" -> "Hello")
// Musi byæ VECTOR, bo iterujemy po nim.
std::vector<std::pair<std::string, std::string>> stringLiterals;
// Licznik do generowania nazw str_0, str_1...
int stringCounter = 0;
// Mapa typów zmiennych (np. "imie" -> "string")
// Musi byæ MAP, bo szukamy po nazwie.
std::map<std::string, std::string> varTypes;
};
#endif

View File

@@ -26,6 +26,20 @@ std::vector<std::string> parseArgs(const std::string& line) {
return args;
}
// Funkcja wyciągająca "tekst" i rejestrująca go w state
// Rejestruje tekst i zwraca jego etykietę (np. str_5)
std::string registerStringLiteral(CompilerState& state, std::string content) {
// Używamy stringCounter z CompilerState
std::string label = "str_" + std::to_string(state.stringCounter++);
// Dodajemy do WEKTORA (push_back działa tylko na wektorze/liście)
state.stringLiterals.push_back({ label, content });
return label;
}
void processSource(const std::string& src, CompilerState& state) {
std::istringstream iss(src);
std::string line;
@@ -106,38 +120,56 @@ void processSource(const std::string& src, CompilerState& state) {
f.instructions.push_back({ OpType::RETURN, val, "", "" });
std::cout << " [PARSER] Return: " << val << "\n";
}
// B. PRINT
// --- 4. ZMIENNE TYPU STRING ---
// string s = "hello";
else if (line.substr(0, 6) == "string") {
size_t eqPos = line.find("=");
if (eqPos != std::string::npos) {
std::string name = trim(line.substr(7, eqPos - 7));
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);
// Rejestracja w wektorze
std::string label = registerStringLiteral(state, content);
// Rejestracja typu w mapie (mapa obsługuje [])
state.varTypes[name] = "string";
// Instrukcja
f.instructions.push_back({ OpType::ASSIGN, name, label, "" });
}
}
}
// --- DRUKOWANIE (PRINT) ---
else if (line.substr(0, 5) == "print") {
size_t start = line.find('(') + 1;
size_t end = line.find(')');
if (start != std::string::npos && end != std::string::npos) {
std::string arg = trim(line.substr(start, end - start));
size_t open = line.find("(");
size_t close = line.rfind(")");
if (open != std::string::npos && close > open) {
std::string content = trim(line.substr(open + 1, close - open - 1));
// Czy to bezpośredni napis? np. print("Hello")
if (arg.size() >= 2 && arg.front() == '"' && arg.back() == '"') {
std::string content = arg.substr(1, arg.size() - 2);
// Rejestrujemy
std::string label;
if (state.stringLiterals.count(content)) {
label = state.stringLiterals[content];
// 1. Literał: print("tekst")
if (content.front() == '"' && content.back() == '"') {
std::string text = content.substr(1, content.length() - 2);
std::string label = registerStringLiteral(state, text);
f.instructions.push_back({ OpType::PRINT_STRING, label, "", "" });
}
// 2. Zmienna: print(x) - sprawdzamy typ
// Używamy .count() na mapie varTypes (poprawne)
else if (state.varTypes.count(content) && state.varTypes[content] == "string") {
f.instructions.push_back({ OpType::PRINT_STRING, content, "", "" });
}
// 3. Liczba
else {
label = "str_" + std::to_string(state.stringCounter++);
state.stringLiterals[content] = label;
f.instructions.push_back({ OpType::PRINT, content, "", "" });
}
}
}
// Dajemy znać generatorowi, że to typ STRING
f.instructions.push_back({ OpType::PRINT, label, "STRING", "" });
}
else {
// Zwykła zmienna (int lub string - generator musi zgadnąć lub my musimy wiedzieć)
// Na razie załóżmy, że jeśli zmienna ma w nazwie "msg" lub "txt", to string
// (To hack, w przyszłości dodamy tabelę typów zmiennych)
f.instructions.push_back({ OpType::PRINT, arg, "VAR", "" });
}
}
}
// C. IF STATEMENT
// --- IF (ZAAWANSOWANY) ---
@@ -352,26 +384,6 @@ void processSource(const std::string& src, CompilerState& state) {
std::string b = trim(rightSide.substr(opPos + 2));
f.instructions.push_back({ OpType::EQ, varName, a, b });
}
else if (rightSide.size() >= 2 && rightSide.front() == '"' && rightSide.back() == '"')
{
{
// Wyciągamy treść bez cudzysłowów
std::string content = rightSide.substr(1, rightSide.size() - 2);
// Rejestrujemy stringa w sekcji danych, jeśli jeszcze go nie ma
std::string label;
if (state.stringLiterals.count(content)) {
label = state.stringLiterals[content];
}
else {
label = "str_" + std::to_string(state.stringCounter++);
state.stringLiterals[content] = label;
}
// Generujemy instrukcję przypisania ADRESU etykiety do zmiennej
f.instructions.push_back({ OpType::ASSIGN, varName, label, "STRING" });
}
}
// 4. Zwykłe przypisanie: a = 5
else {
f.instructions.push_back({ OpType::ASSIGN, varName, rightSide, "" });