14 Commits

Author SHA1 Message Date
mmichlol
d736f2786e Large Functions Update 2026-02-07 21:29:34 +01:00
mmichlol
3916b4ff7a String Update 2026-02-07 19:44:03 +01:00
mmichlol
c37a122850 Loop Update 2026-02-07 18:47:07 +01:00
mmichlol
fdcbc31cca added random int func 2026-02-07 16:01:02 +01:00
mmichlol
4f1a21e9c2 Added random int generator 2026-02-07 15:54:01 +01:00
mmichlol
5edf6ed382 added Random Int Generator 2026-02-07 15:53:25 +01:00
mmichlol
99b9ae450e Keyboard and Input Update 2026-02-07 14:02:42 +01:00
mmichlol
9bbf8435c6 include Update 2026-02-07 11:57:44 +01:00
mmichlol
e250b2f5fb README update 2026-02-07 11:37:46 +01:00
mmichlol
aa6d16bc52 added more functions 2026-02-07 11:33:50 +01:00
mmichlol
5fbd0f98a2 added int func(int x, int y), return int 2026-02-06 21:01:12 +01:00
mmichlol
196140f9b8 fixed parser 2026-02-06 18:21:58 +01:00
mmichlol
f192c5a367 README.md update 2026-02-06 17:01:46 +01:00
mmichlol
b88279c841 fixed IF statment 2026-02-06 16:51:47 +01:00
10 changed files with 1122 additions and 242 deletions

View File

@@ -22,12 +22,14 @@
<ClCompile Include="codegen.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="parser.cpp" />
<ClCompile Include="preprocessor.cpp" />
<ClCompile Include="utils.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="codegen.h" />
<ClInclude Include="compiler_types.h" />
<ClInclude Include="parser.h" />
<ClInclude Include="preprocessor.h" />
<ClInclude Include="utils.h" />
</ItemGroup>
<PropertyGroup Label="Globals">

View File

@@ -27,6 +27,9 @@
<ClCompile Include="codegen.cpp">
<Filter>Pliki źródłowe</Filter>
</ClCompile>
<ClCompile Include="preprocessor.cpp">
<Filter>Pliki źródłowe</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="utils.h">
@@ -41,5 +44,8 @@
<ClInclude Include="compiler_types.h">
<Filter>Pliki nagłówkowe</Filter>
</ClInclude>
<ClInclude Include="preprocessor.h">
<Filter>Pliki nagłówkowe</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -1,81 +1,490 @@
#include "codegen.h"
#include <string>
#include <iostream>
#include <sstream>
#include <vector>
std::string generateAssembly(const CompilerState& state) {
std::string result;
// Pomocnicza funkcja: sprawdza czy string to czysta liczba
bool isNumber(const std::string& s) {
if (s.empty()) return false;
size_t start = (s[0] == '-') ? 1 : 0;
for (size_t i = start; i < s.length(); i++) {
if (!isdigit(s[i])) return false;
}
return true;
}
// --- NAG£ÓWEK I SEKCJA DATA ---
// 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 cleanName = name;
// Usuwamy ewentualne spacje
size_t first = cleanName.find_first_not_of(" \t");
if (first != std::string::npos) cleanName = cleanName.substr(first);
size_t last = cleanName.find_last_not_of(" \t");
if (last != std::string::npos) cleanName = cleanName.substr(0, last + 1);
if (cleanName.empty()) return "0";
if (isNumber(cleanName)) return cleanName;
if (cleanName == "RAX") return "eax";
if (locals.count(cleanName)) {
int offset = locals.at(cleanName);
return "[rbp-" + std::to_string(offset) + "]";
}
// Zwracamy orygina³ (jeœli to np. nazwa etykiety), ale to zazwyczaj b³¹d dla zmiennych
return cleanName;
}
std::string generateAssembly(const CompilerState& state) {
// 1. NAG£ÓWEK I DEKLARACJE EXTERN
std::string result = "default rel\n";
result += "global main\n";
result += "extern printf\n";
result += "extern GetAsyncKeyState\n\n";
result += "extern getchar\n";
result += "extern _getch\n";
result += "extern rand\n";
result += "extern srand\n";
result += "extern time\n";
result += "extern MessageBoxA\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
// Generowanie zmiennych
for (const auto& v : state.variables) {
result += " " + v.first + " dd " + std::to_string(v.second) + "\n";
// 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";
}
// Sta³e stringi
result += " fmt db '%d', 10, 0\n";
result += " pause_msg db 'Nacisnij ESC aby zamknac...', 10, 0\n\n";
// 3. SEKCJA TEXT (Kod programu)
result += "section .text\n";
// --- DEFINICJE FUNKCJI U¯YTKOWNIKA ---
for (const auto& func : state.functions) {
result += func.first + ":\n";
result += " sub rsp, 40\n"; // Shadow space
for (const auto& pair : state.functions) {
const Function& func = pair.second;
result += func.name + ":\n";
// Printy wewn¹trz funkcji
for (const std::string& var : func.second) {
if (state.variables.count(var)) {
result += " mov edx, [" + var + "]\n";
result += " lea rcx, [rel fmt]\n";
result += " call printf\n";
result += " push rbp\n";
result += " mov rbp, rsp\n";
result += " sub rsp, 256\n";
std::map<std::string, int> stackMap;
int currentStack = 8;
// 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";
currentStack += 8;
}
if (func.args.size() > 1) {
stackMap[func.args[1]] = currentStack;
result += " mov [rbp-" + std::to_string(currentStack) + "], rdx ; arg " + func.args[1] + "\n";
currentStack += 8;
}
// GENEROWANIE INSTRUKCJI
for (const auto& instr : func.instructions) {
// Rezerwacja miejsca na stosie
bool isWriteOp = (instr.type == OpType::ASSIGN ||
instr.type == OpType::ADD ||
instr.type == OpType::EQ ||
instr.type == OpType::SUB ||
instr.type == OpType::MUL ||
instr.type == OpType::DIV ||
instr.type == OpType::MOD ||
instr.type == OpType::LOGIC_AND ||
instr.type == OpType::LOGIC_OR ||
instr.type == OpType::MSGBOX ||
instr.type == OpType::ARRAY_DECLARE ||
instr.type == OpType::ARRAY_SET);
if (isWriteOp && stackMap.find(instr.arg1) == stackMap.end() && instr.arg1 != "RAX") {
stackMap[instr.arg1] = currentStack;
currentStack += 8;
}
switch (instr.type) {
case OpType::ASSIGN: {
std::string src = instr.arg2;
// ODCZYT TABLICY: x = t[i]
if (instr.arg3.find("ARRAY_IDX:") == 0) {
std::string indexStr = instr.arg3.substr(10); // Pobierz "i"
std::string arrName = instr.arg2; // Pobierz "t"
std::string dst = getVarLocation(instr.arg1, stackMap);
int baseOffset = stackMap[arrName];
// £adujemy indeks do RCX
if (isNumber(indexStr)) result += " mov rcx, " + indexStr + "\n";
else result += " mov rcx, " + getVarLocation(indexStr, stackMap) + "\n";
result += " imul rcx, 8\n"; // index * 8
// Obliczamy adres
result += " mov rdx, rbp\n";
result += " sub rdx, " + std::to_string(baseOffset) + "\n";
result += " sub rdx, rcx\n";
// Odczytujemy wartoϾ z tablicy do RAX
result += " mov rax, [rdx]\n";
// Zapisujemy do zmiennej docelowej
result += " mov " + dst + ", rax\n"; // Lub eax, zale¿y jak masz
}
else 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;
}
case OpType::ADD: {
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 += " add eax, " + op2 + "\n";
result += " mov " + dst + ", eax\n";
break;
}
case OpType::SUB: {
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";
result += " mov " + dst + ", eax\n";
break;
}
case OpType::MUL: {
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 += " 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);
std::string dst = getVarLocation(instr.arg1, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cmp eax, " + op2 + "\n";
result += " sete al\n";
result += " movzx eax, al\n";
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: {
std::string condRaw = instr.arg2;
size_t eqPos = condRaw.find("==");
if (eqPos != std::string::npos) {
std::string leftStr = condRaw.substr(0, eqPos);
std::string rightStr = condRaw.substr(eqPos + 2);
std::string op1 = getVarLocation(leftStr, stackMap);
std::string op2 = getVarLocation(rightStr, stackMap);
result += " mov eax, " + op1 + "\n";
result += " cmp eax, " + op2 + "\n";
result += " jne " + instr.arg1 + "\n";
}
else {
std::string cond = getVarLocation(condRaw, stackMap);
result += " mov eax, " + cond + "\n";
result += " test eax, eax\n";
result += " jz " + instr.arg1 + "\n";
}
break;
}
case OpType::JMP: {
result += " jmp " + instr.arg1 + "\n";
break;
}
case OpType::ARRAY_DECLARE: {
std::string name = instr.arg1;
int size = std::stoi(instr.arg2);
// Rezerwujemy miejsce dla ca³ej tablicy
// t[0] bêdzie pod aktualnym currentStack
stackMap[name] = currentStack;
// Przesuwamy wskaŸnik stosu o (rozmiar * 8 bajtów)
// Zak³adamy, ¿e ka¿dy element to 64-bit (dla bezpieczeñstwa i prostoty assemblera)
currentStack += (size * 8);
// W ASM nie musimy generowaæ ¿adnego kodu! (Miejsce ju¿ jest z sub rsp, 256)
// O ile tablica mieœci siê w tych 256 bajtach.
// Jeœli chcesz byæ PRO: dodaj na pocz¹tku funkcji "sub rsp, (currentStack + zapas)"
break;
}
case OpType::ARRAY_SET: {
std::string arrName = instr.arg1; // t
std::string indexStr = instr.arg2; // i
std::string valStr = instr.arg3; // val
// 1. Obliczamy wartoϾ do wpisania
if (isNumber(valStr)) {
result += " mov rax, " + valStr + "\n";
}
else {
std::string valLoc = getVarLocation(valStr, stackMap);
// Jeœli to zmienna ze stosu, to movsxd (rozszerzenie znaku) lub mov
result += " mov rax, " + valLoc + "\n"; // Zak³adamy 64-bit (lub eax dla 32)
}
// 2. Obliczamy adres elementu tablicy
// Adres = [rbp - offset_bazowy - (index * 8)]
// U nas stackMap trzyma offset_bazowy.
// Poniewa¿ stos roœnie w DÓ£, a my rezerwowaliœmy w DÓ£:
// t[0] -> offset
// t[1] -> offset + 8
// Czekaj, rbp-8, rbp-16...
// Im wiêkszy offset w stackMap, tym ni¿ej w pamiêci.
// stackMap["t"] = 8. [rbp-8].
// t[1] powinno byæ [rbp-16].
// Czyli Wzór: [rbp - (base_offset + index*8)]
int baseOffset = stackMap[arrName];
// £adujemy indeks do RCX
if (isNumber(indexStr)) {
result += " mov rcx, " + indexStr + "\n";
}
else {
std::string idxLoc = getVarLocation(indexStr, stackMap);
result += " mov rcx, " + idxLoc + "\n"; // Pobierz indeks ze zmiennej
}
// Obliczamy przesuniêcie bajtowe: index * 8
result += " imul rcx, 8\n";
// Poniewa¿ adres to RBP - (base + index*8) -> RBP - base - index*8
// Musimy to sprytnie zmontowaæ.
// Obliczmy finalny adres w RDX.
result += " mov rdx, rbp\n";
result += " sub rdx, " + std::to_string(baseOffset) + "\n"; // RDX = adres t[0]
result += " sub rdx, rcx\n"; // RDX = adres t[i]
// Zapisujemy wartoϾ (RAX) pod adres (RDX)
result += " mov [rdx], rax\n";
break;
}
case OpType::LABEL: {
result += instr.arg1 + ":\n";
break;
}
case OpType::PRINT: {
// Instrukcja PRINT zwyk³a (liczba)
std::string val = getVarLocation(instr.arg1, stackMap);
result += " mov edx, " + val + "\n";
result += " lea rcx, [rel fmt_int]\n";
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: {
if (instr.arg1 == "input") {
result += " call getchar\n";
break;
}
if (instr.arg1 == "read_key") {
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) {
callArgs.push_back(argsRaw.substr(0, comma));
callArgs.push_back(argsRaw.substr(comma + 1));
}
else {
callArgs.push_back(argsRaw);
}
}
if (callArgs.size() > 1) {
std::string val = getVarLocation(callArgs[1], stackMap);
if (isNumber(val)) result += " mov rdx, " + val + "\n";
else result += " movsxd rdx, dword " + val + "\n";
}
if (callArgs.size() > 0) {
std::string val = getVarLocation(callArgs[0], stackMap);
if (isNumber(val)) result += " mov rcx, " + val + "\n";
else result += " movsxd rcx, dword " + val + "\n";
}
result += " call " + instr.arg1 + "\n";
break;
}
case OpType::RETURN: {
std::string val = getVarLocation(instr.arg1, stackMap);
if (!val.empty() && val != ";") {
result += " mov eax, " + val + "\n";
}
result += " leave\n";
result += " ret\n";
break;
}
case OpType::MSGBOX: {
// Konwencja Windows x64:
// RCX = HWND (0 = brak okna nadrzêdnego)
// RDX = TreϾ (Text)
// R8 = Tytu³ (Caption)
// R9 = Typ (0 = przycisk OK)
std::string title = instr.arg1;
std::string text = instr.arg2;
// --- 1. Ustawiamy RDX (TreϾ) ---
if (text.find("str_") == 0) {
// Jeœli to litera³ (np. str_5), ³adujemy jego adres (LEA)
result += " lea rdx, [rel " + text + "]\n";
}
else {
// Jeœli to zmienna, pobieramy jej wartoœæ ze stosu (która jest adresem)
std::string loc = getVarLocation(text, stackMap);
result += " mov rdx, " + loc + "\n";
}
// --- 2. Ustawiamy R8 (Tytu³) ---
if (title.find("str_") == 0) {
result += " lea r8, [rel " + title + "]\n";
}
else {
std::string loc = getVarLocation(title, stackMap);
result += " mov r8, " + loc + "\n";
}
// --- 3. Pozosta³e argumenty (Sta³e) ---
result += " mov rcx, 0\n"; // HWND = NULL
result += " mov r9, 0\n"; // MB_OK
// --- 4. Wywo³anie ---
// Stos (shadow space) jest ju¿ przygotowany na pocz¹tku funkcji (sub rsp, 256)
result += " call MessageBoxA\n";
break;
}
}
}
result += " add rsp, 40\n";
result += " ret\n\n";
}
// --- FUNKCJA MAIN ---
result += "main:\n";
result += " sub rsp, 40\n";
// Globalne printy (poza funkcjami)
for (const std::string& var : state.globalPrints) {
if (state.variables.count(var)) {
result += " mov edx, [" + var + "]\n";
result += " lea rcx, [rel fmt]\n";
result += " call printf\n";
if (func.returnType == "void") {
result += " leave\n ret\n";
}
result += "\n";
}
// Wywo³ania funkcji zdefiniowanych wczeœniej
for (const std::string& call : state.printCalls) {
if (call.find("CALL_") == 0) {
std::string funcName = call.substr(5); // Usuñ prefiks "CALL_"
if (state.functions.count(funcName)) {
result += " call " + funcName + "\n";
}
}
}
// --- PAUSE LOOP (Czekanie na ESC) ---
result += " lea rcx, [rel pause_msg]\n";
result += " call printf\n";
result += "pause_loop:\n";
result += " mov ecx, 27\n"; // VK_ESCAPE
result += " call GetAsyncKeyState\n";
result += " test ax, 8000h\n";
result += " jz pause_loop\n";
// Wyjœcie z programu
result += " add rsp, 40\n";
result += " ret\n";
return result;
}

View File

@@ -6,28 +6,72 @@
#include <map>
#include <stack>
struct Expression {
std::string leftVar;
std::string op;
std::string rightVar;
std::string resultVar;
// 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(int)
PRINT_STRING, // print(string) - NOWE
JMP_FALSE, // if (false) skocz...
ARRAY_DECLARE, // int t[10];
ARRAY_SET, // t[0] = 5;
ARRAY_GET, // x = t[0]; - to obs³u¿ymy w ASSIGN, ale warto mieæ typ
JMP, // else / pêtla
LOGIC_AND, // &&
LOGIC_OR, // ||
LABEL, // miejsce skoku
CALL, // wywo³anie funkcji
RETURN, // return x
MSGBOX, // msg box
NOP // pusta instrukcja
};
struct IfBlock {
std::string conditionVar;
std::vector<std::string> prints;
// Pojedynczy rozkaz
struct Instruction {
OpType type;
std::string arg1;
std::string arg2;
std::string arg3;
};
// Definicja funkcji
struct Function {
std::string name;
std::string returnType;
std::vector<std::string> args;
std::vector<Instruction> instructions;
};
// G£ÓWNY STAN KOMPILATORA
struct CompilerState {
std::vector<Expression> expressions;
std::vector<IfBlock> ifBlocks;
std::map<std::string, int> variables;
std::vector<std::string> printCalls;
std::vector<std::string> globalPrints;
std::map<std::string, std::vector<std::string>> functions;
bool inFunction = false;
std::string currentFunction;
std::stack<bool> braceStack;
// Mapa funkcji
std::map<std::string, Function> functions;
// Zmienne globalne
std::map<std::string, int> globals;
// 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::vector<std::pair<std::string, std::string>> stringLiterals;
// Licznik do generowania nazw str_0, str_1...
int stringCounter = 0;
std::map<std::string, std::string> varTypes;
};
#endif

View File

@@ -2,14 +2,24 @@
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib> // do std::system
#include <cstdlib>
#include <filesystem>
#include <windows.h>
#include "compiler_types.h"
#include "parser.h"
#include "codegen.h"
#include "preprocessor.h"
std::string getExecutablePath() {
char buffer[MAX_PATH];
GetModuleFileNameA(NULL, buffer, MAX_PATH);
std::string::size_type pos = std::string(buffer).find_last_of("\\/");
return std::string(buffer).substr(0, pos);
}
int main(int argc, char* argv[]) {
std::string inputFile, outputName;
std::string Version = "v1.5.0-modular"; // Zaktualizowałem wersję :)
std::string Version = "v0.0.7-beta";
bool showHelp = false, showVersion = false, showCredits = false;
// --- PARSOWANIE ARGUMENTÓW ---
@@ -68,10 +78,22 @@ int main(int argc, char* argv[]) {
return 1;
}
// ... wczytywanie pliku (to co miałeś) ...
std::string src((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
in.close();
// --- LOGIKA KOMPILATORA ---
// --- PREPROCESSOR START ---
std::cout << "[INFO] Preprocessing...\n";
// 1. Ścieżka projektu (tam gdzie plik wejściowy)
std::filesystem::path p(inputFile);
std::string projectDir = p.parent_path().string();
// 2. Ścieżka kompilatora (tam gdzie PCC.exe i folder std)
std::string compilerDir = getExecutablePath();
// Uruchamiamy z obiema ścieżkami
src = preprocessSource(src, projectDir, compilerDir);
CompilerState state;
std::cout << "[INFO] Parsing code...\n";
@@ -90,24 +112,31 @@ int main(int argc, char* argv[]) {
// --- ZAPIS I KOMPILACJA ZEWNĘTRZNA ---
std::system("if not exist output mkdir output");
std::string baseName = outputName.empty() ?
inputFile.substr(0, inputFile.find_last_of(".")) : outputName;
// Upewnij się, że nazwa nie ma rozszerzenia .exe w środku ścieżki
// 1. Ustal bazową nazwę (bez rozszerzenia)
std::string baseName;
if (outputName.empty()) {
if (baseName.find(".exe") == std::string::npos) baseName += ".exe";
// Jeśli nie podano -o, weź nazwę pliku wejściowego i utnij .pcc
size_t lastDot = inputFile.find_last_of(".");
if (lastDot != std::string::npos)
baseName = inputFile.substr(0, lastDot);
else
baseName = inputFile;
}
else {
// Jeśli użytkownik podał nazwę bez .exe, dodaj ją
if (outputName.find(".exe") == std::string::npos) outputName += ".exe";
baseName = outputName;
// Jeśli podano -o, sprawdź czy ma .exe i ewentualnie utnij
// (żebyśmy mogli dodać .asm i .obj bez bałaganu)
size_t exePos = outputName.find(".exe");
if (exePos != std::string::npos)
baseName = outputName.substr(0, exePos);
else
baseName = outputName;
}
// Ścieżki wyjściowe
// Uwaga: zakładam proste nazewnictwo, można tu poprawić usuwanie ścieżek z nazwy pliku
// Teraz budujemy ścieżki - czysto i ładnie
std::string asmPath = "output\\" + baseName + ".asm";
std::string objPath = "output\\" + baseName + ".obj";
std::string exePath = "output\\" + baseName;
std::string exePath = "output\\" + baseName + ".exe";
// Zapisz ASM
std::ofstream asmOut(asmPath);

View File

@@ -2,182 +2,423 @@
#include "utils.h"
#include <iostream>
#include <sstream>
#include "compiler_types.h"
#include <vector>
std::vector<std::string> parseArgs(const std::string& line) {
std::vector<std::string> 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);
// segment to np. "int a". Szukamy ostatniej spacji, by wziąć nazwę "a"
size_t space = segment.find_last_of(" \t");
if (space != std::string::npos) {
args.push_back(trim(segment.substr(space + 1)));
}
}
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;
std::cout << "Parsuje kod:\n";
while (std::getline(iss, line)) {
line = trim(line);
if (line.empty()) continue;
if (line.empty() || line.substr(0, 2) == "//" || line[0] == '#') continue;
// FUNKCJE
if (line.length() > 4 && line.substr(0, 4) == "void") {
size_t openParen = line.find("(", 4);
size_t closeParen = line.find(")", openParen);
if (openParen != std::string::npos && closeParen != std::string::npos) {
size_t nameStart = 4;
while (nameStart < openParen && (line[nameStart] == ' ' || line[nameStart] == '\t')) nameStart++;
size_t nameEnd = openParen;
while (nameEnd > nameStart && (line[nameEnd - 1] == ' ' || line[nameEnd - 1] == '\t')) nameEnd--;
// =========================================================
// 1. DEFINICJA FUNKCJI (np. void main() { )
// =========================================================
bool startsWithType = (line.rfind("int ", 0) == 0 || line.rfind("void ", 0) == 0 || line.rfind("bool ", 0) == 0);
if (startsWithType && line.find("(") != std::string::npos && line.find("{") != std::string::npos && line.find("=") == std::string::npos) {
// ZMIANA: używamy 'state' zamiast 'compilerState'
state.currentFunction = line.substr(nameStart, nameEnd - nameStart);
state.functions[state.currentFunction] = std::vector<std::string>();
state.inFunction = true;
std::cout << " FUNC " << state.currentFunction << "\n";
state.braceStack.push(true);
continue;
}
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;
}
// }
else if (line.find("}") != std::string::npos) {
if (!state.braceStack.empty()) {
state.braceStack.pop();
if (!state.braceStack.empty()) {
state.inFunction = false;
state.currentFunction.clear();
std::cout << " END FUNC\n";
// =========================================================
// 2. ZAMYKANIE BLOKU '}' (Koniec funkcji, IF-a lub WHILE)
// =========================================================
if (line == "}") {
if (!state.blockStack.empty()) {
std::string blockInfo = state.blockStack.top();
state.blockStack.pop();
// Sprawdzamy czy to pętla WHILE (znacznik "WHILE|...")
bool isWhile = (blockInfo.length() > 6 && blockInfo.substr(0, 6) == "WHILE|");
if (isWhile) {
size_t firstPipe = blockInfo.find('|');
size_t secondPipe = blockInfo.rfind('|');
std::string labelStart = blockInfo.substr(firstPipe + 1, secondPipe - firstPipe - 1);
std::string labelEnd = blockInfo.substr(secondPipe + 1);
if (state.currentFunction) {
state.currentFunction->instructions.push_back({ OpType::JMP, labelStart, "", "" });
state.currentFunction->instructions.push_back({ OpType::LABEL, labelEnd, "", "" });
}
std::cout << " [PARSER] } End WHILE loop\n";
}
else {
// To zwykły IF
if (state.currentFunction) {
state.currentFunction->instructions.push_back({ OpType::LABEL, blockInfo, "", "" });
}
std::cout << " [PARSER] } End IF block -> " << blockInfo << "\n";
}
}
else {
// Koniec funkcji
state.currentFunction = nullptr;
std::cout << " [PARSER] } End Function\n";
}
continue;
}
// INT
if (line.length() > 3 && line.substr(0, 3) == "int") {
size_t eqPos = line.find("=", 4);
if (eqPos != std::string::npos) {
size_t semiPos = line.find(";", eqPos);
if (semiPos != std::string::npos) {
std::string name = trim(line.substr(4, eqPos - 4));
std::string rightSide = trim(line.substr(eqPos + 1, semiPos - eqPos - 1));
std::string op;
size_t opPos;
// =========================================================
// JESTEŚMY W ŚRODKU FUNKCJI
// =========================================================
if (state.currentFunction) {
Function& f = *state.currentFunction;
size_t eqPos2 = rightSide.find("==");
if (eqPos2 != std::string::npos && (eqPos2 + 1 < rightSide.length()) && rightSide[eqPos2 + 2] != '=') {
op = "==";
opPos = eqPos2;
}
else {
opPos = rightSide.find('+');
if (opPos == std::string::npos) opPos = rightSide.find('-');
if (opPos != std::string::npos) op = rightSide.substr(opPos, 1);
}
if (opPos != std::string::npos && !op.empty()) {
std::string leftVar = trim(rightSide.substr(0, opPos));
std::string rightVar = trim(rightSide.substr(opPos + op.length()));
// ZMIANA: używamy 'state'
Expression expr{ leftVar, op, rightVar, name };
state.expressions.push_back(expr);
state.variables[name] = 0;
std::cout << " " << op << " EXPR " << name << " = " << leftVar << " " << op << " " << rightVar << "\n";
}
else {
try {
int value = std::stoi(rightSide);
state.variables[name] = value;
std::cout << " VAR " << name << " = " << value << "\n";
}
catch (...) {
// Usunięto '❌' żeby uniknąć warningów o kodowaniu (C4566)
std::cout << " [X] BLAD: '" << rightSide << "'\n";
}
}
}
}
}
// BOOL
else if (!state.inFunction && line.length() > 4 && line.substr(0, 4) == "bool") {
size_t eqPos = line.find("=", 5);
if (eqPos != std::string::npos) {
size_t semiPos = line.find(";", eqPos);
if (semiPos != std::string::npos) {
std::string nameRaw = line.substr(5, eqPos - 5);
size_t nameStart = nameRaw.find_first_not_of(" \t");
size_t nameEnd = nameRaw.find_last_not_of(" \t");
std::string name = nameRaw.substr(nameStart, nameEnd - nameStart + 1);
std::string valueRaw = line.substr(eqPos + 1, semiPos - eqPos - 1);
size_t valStart = valueRaw.find_first_not_of(" \t");
size_t valEnd = valueRaw.find_last_not_of(" \t");
std::string valueStr = valueRaw.substr(valStart, valEnd - valStart + 1);
bool value = (valueStr == "true" || valueStr == "1");
state.variables[name] = value ? 1 : 0;
std::cout << " BOOL '" << name << "' = " << (value ? "true" : "false") << "\n";
}
}
}
// IF
else if (line.length() > 3 && line.substr(0, 2) == "if") {
size_t openParen = line.find("(");
size_t closeParen = line.find(")");
if (openParen != std::string::npos && closeParen > openParen) {
std::string condition = trim(line.substr(openParen + 1, closeParen - openParen - 1));
IfBlock newIf;
newIf.conditionVar = condition;
state.ifBlocks.push_back(newIf); // ZMIANA: state.ifBlocks
std::cout << " IF [" << condition << "] { <- blok #" << state.ifBlocks.size() - 1 << "\n";
state.braceStack.push(false);
// A. RETURN
if (line.substr(0, 6) == "return") {
std::string val = trim(line.substr(6));
if (!val.empty() && val.back() == ';') val.pop_back();
f.instructions.push_back({ OpType::RETURN, val, "", "" });
continue;
}
}
// PRINT
else if (line.length() > 5 && line.substr(0, 5) == "print") {
size_t openParen = line.find("(", 5);
size_t closeParen = line.rfind(")");
if (openParen != std::string::npos && closeParen > openParen) {
std::string varName = line.substr(openParen + 1, closeParen - openParen - 1);
size_t varStart = varName.find_first_not_of(" \t");
size_t varEnd = varName.find_last_not_of(" \t");
if (varStart != std::string::npos) {
varName = varName.substr(varStart, varEnd - varStart + 1);
if (state.inFunction && !state.currentFunction.empty()) {
state.functions[state.currentFunction].push_back(varName);
std::cout << " FUNC PRINT " << state.currentFunction << ": " << varName << "\n";
}
else {
state.globalPrints.push_back(varName);
std::cout << " PRINT " << varName << "\n";
// B. DEKLARACJA STRINGA: string s = "hello";
else if (line.substr(0, 6) == "string") {
size_t eqPos = line.find("=");
if (eqPos != std::string::npos) {
std::string name = trim(line.substr(7, eqPos - 7));
size_t quoteStart = line.find("\"", eqPos);
size_t quoteEnd = line.rfind("\"");
if (quoteStart != std::string::npos && quoteEnd > quoteStart) {
std::string content = line.substr(quoteStart + 1, quoteEnd - quoteStart - 1);
std::string label = registerStringLiteral(state, content);
state.varTypes[name] = "string";
f.instructions.push_back({ OpType::ASSIGN, name, label, "" });
}
}
continue;
}
}
// WYWOLYWANIE FUNKCJI;
else if (line.length() > 3 && line.find("();") != std::string::npos) {
size_t openParen = line.find("(");
if (openParen != std::string::npos) {
std::string funcName = line.substr(0, openParen);
size_t nameStart = funcName.find_first_not_of(" \t");
size_t nameEnd = funcName.find_last_not_of(" \t");
funcName = funcName.substr(nameStart, nameEnd - nameStart + 1);
state.printCalls.push_back("CALL_" + funcName); // ZMIANA: state
std::cout << " CALL FUNC " << funcName << "\n";
// C. DEKLARACJA TABLICY: int t[10];
else if (line.substr(0, 3) == "int" && line.find("[") != std::string::npos && line.find("=") == std::string::npos) {
size_t openBracket = line.find("[");
size_t closeBracket = line.find("]");
if (openBracket != std::string::npos && closeBracket > openBracket) {
std::string name = trim(line.substr(3, openBracket - 3));
std::string sizeStr = trim(line.substr(openBracket + 1, closeBracket - openBracket - 1));
state.varTypes[name] = "array";
f.instructions.push_back({ OpType::ARRAY_DECLARE, name, sizeStr, "" });
std::cout << " [PARSER] Array Decl: " << name << "[" << sizeStr << "]\n";
}
continue;
}
// D. DRUKOWANIE (PRINT)
else if (line.substr(0, 5) == "print") {
size_t open = line.find("(");
size_t close = line.rfind(")");
if (open != std::string::npos && close > open) {
std::string content = trim(line.substr(open + 1, close - open - 1));
// Czy to element tablicy? print(t[0])
if (content.find("[") != std::string::npos && content.back() == ']') {
size_t opIdx = content.find("[");
std::string arrName = content.substr(0, opIdx);
std::string arrIdx = content.substr(opIdx + 1, content.length() - opIdx - 2);
// Hack: Używamy tymczasowej zmiennej do wydruku
std::string tmp = "_p_tmp_" + std::to_string(state.labelCounter++);
f.instructions.push_back({ OpType::ASSIGN, tmp, arrName, "ARRAY_IDX:" + arrIdx });
f.instructions.push_back({ OpType::PRINT, tmp, "", "" });
}
// Literał tekstowy
else if (content.front() == '"' && content.back() == '"') {
std::string text = content.substr(1, content.length() - 2);
std::string label = registerStringLiteral(state, text);
f.instructions.push_back({ OpType::PRINT_STRING, label, "", "" });
}
// Zmienna string
else if (state.varTypes.count(content) && state.varTypes[content] == "string") {
f.instructions.push_back({ OpType::PRINT_STRING, content, "", "" });
}
// Liczba
else {
f.instructions.push_back({ OpType::PRINT, content, "", "" });
}
}
continue;
}
// E. IF STATEMENT
else if (line.substr(0, 2) == "if") {
size_t openParen = line.find("(");
size_t closeParen = line.rfind(")");
if (openParen != std::string::npos && closeParen > openParen) {
std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1));
std::string finalConditionVar = conditionRaw;
// Logika && i || (uproszczona)
size_t andPos = conditionRaw.find("&&");
size_t orPos = conditionRaw.find("||");
if (andPos != std::string::npos) {
std::string partA = trim(conditionRaw.substr(0, andPos));
std::string partB = trim(conditionRaw.substr(andPos + 2));
std::string tempA = "_tmp_and_a_" + std::to_string(state.labelCounter);
std::string tempB = "_tmp_and_b_" + std::to_string(state.labelCounter);
std::string tempRes = "_tmp_and_res_" + std::to_string(state.labelCounter);
// A
if (partA.find("==") != std::string::npos) {
size_t eq = partA.find("==");
f.instructions.push_back({ OpType::EQ, tempA, trim(partA.substr(0, eq)), trim(partA.substr(eq + 2)) });
}
else f.instructions.push_back({ OpType::ASSIGN, tempA, partA, "" });
// B
if (partB.find("==") != std::string::npos) {
size_t eq = partB.find("==");
f.instructions.push_back({ OpType::EQ, tempB, trim(partB.substr(0, eq)), trim(partB.substr(eq + 2)) });
}
else f.instructions.push_back({ OpType::ASSIGN, tempB, partB, "" });
f.instructions.push_back({ OpType::LOGIC_AND, tempRes, tempA, tempB });
finalConditionVar = tempRes;
}
else if (orPos != std::string::npos) {
// ... (Tutaj można dodać logikę OR analogicznie jak wyżej, skracam dla czytelności)
}
else if (conditionRaw.find("==") != std::string::npos) {
size_t eq = conditionRaw.find("==");
std::string tempRes = "_tmp_eq_" + std::to_string(state.labelCounter);
f.instructions.push_back({ OpType::EQ, tempRes, trim(conditionRaw.substr(0, eq)), trim(conditionRaw.substr(eq + 2)) });
finalConditionVar = tempRes;
}
std::string labelName = "L_" + std::to_string(state.labelCounter++);
f.instructions.push_back({ OpType::JMP_FALSE, labelName, finalConditionVar, "" });
state.blockStack.push(labelName);
}
continue;
}
// F. WHILE LOOP
else if (line.substr(0, 5) == "while") {
size_t openParen = line.find("(");
size_t closeParen = line.rfind(")");
if (openParen != std::string::npos && closeParen > openParen) {
std::string conditionRaw = trim(line.substr(openParen + 1, closeParen - openParen - 1));
// 1. Generujemy etykiety
std::string labelStart = "L_" + std::to_string(state.labelCounter++);
std::string labelEnd = "L_" + std::to_string(state.labelCounter++);
// 2. Wstawiamy etykietę START (tu będziemy wracać)
f.instructions.push_back({ OpType::LABEL, labelStart, "", "" });
// 3. OBLICZANIE WARUNKU (Tu był błąd - brakowało tego!)
// Jeśli warunek to np. "j - 3", musimy to policzyć do zmiennej tymczasowej
std::string finalCondVar = conditionRaw;
// Prosta obsługa odejmowania w warunku (np. while (i - 10))
if (conditionRaw.find("-") != std::string::npos) {
size_t opPos = conditionRaw.find("-");
std::string a = trim(conditionRaw.substr(0, opPos));
std::string b = trim(conditionRaw.substr(opPos + 1));
std::string tmp = "_while_tmp_" + std::to_string(state.labelCounter);
f.instructions.push_back({ OpType::SUB, tmp, a, b });
finalCondVar = tmp;
}
// Prosta obsługa "==" (np. while (i == 10))
else if (conditionRaw.find("==") != std::string::npos) {
size_t opPos = conditionRaw.find("==");
std::string a = trim(conditionRaw.substr(0, opPos));
std::string b = trim(conditionRaw.substr(opPos + 2));
std::string tmp = "_while_tmp_" + std::to_string(state.labelCounter);
f.instructions.push_back({ OpType::EQ, tmp, a, b });
finalCondVar = tmp;
}
// 4. Skaczemy do END jeśli warunek (obliczona zmienna) jest fałszywy
f.instructions.push_back({ OpType::JMP_FALSE, labelEnd, finalCondVar, "" });
// 5. Wrzucamy info na stos
state.blockStack.push("WHILE|" + labelStart + "|" + labelEnd);
}
continue;
}
// G. MSGBOX
else if (line.substr(0, 6) == "msgbox") {
// ... (Twoja logika msgbox, jest OK) ...
size_t open = line.find("(");
size_t close = line.rfind(")");
if (open != std::string::npos && close > open) {
std::string args = line.substr(open + 1, close - open - 1);
size_t comma = args.find(",");
if (comma != std::string::npos) {
std::string arg1 = trim(args.substr(0, comma));
std::string arg2 = trim(args.substr(comma + 1));
std::string l1 = (arg1.front() == '"') ? registerStringLiteral(state, arg1.substr(1, arg1.size() - 2)) : arg1;
std::string l2 = (arg2.front() == '"') ? registerStringLiteral(state, arg2.substr(1, arg2.size() - 2)) : arg2;
f.instructions.push_back({ OpType::MSGBOX, l1, l2, "" });
}
}
continue;
}
// =========================================================
// H. PRZYPISANIE / OPERACJE (Linie z "=")
// =========================================================
else if (line.find("=") != std::string::npos) {
size_t eqPos = line.find('=');
std::string leftSide = trim(line.substr(0, eqPos));
std::string rightSide = trim(line.substr(eqPos + 1));
if (!rightSide.empty() && rightSide.back() == ';') rightSide.pop_back();
// 1. CZY TO ZAPIS DO TABLICY? t[0] = 5
if (leftSide.find("[") != std::string::npos) {
size_t open = leftSide.find("[");
size_t close = leftSide.find("]");
std::string arrName = trim(leftSide.substr(0, open));
std::string index = trim(leftSide.substr(open + 1, close - open - 1));
f.instructions.push_back({ OpType::ARRAY_SET, arrName, index, rightSide });
continue;
}
// Pobieramy nazwę zmiennej (usuwamy "int ", "bool ")
std::string varName = leftSide;
if (leftSide.rfind("int ", 0) == 0) varName = trim(leftSide.substr(4));
else if (leftSide.rfind("bool ", 0) == 0) varName = trim(leftSide.substr(5));
else if (leftSide.rfind("string ", 0) == 0) varName = trim(leftSide.substr(7));
// 2. CZY TO ODCZYT Z TABLICY? x = t[0]
if (rightSide.find("[") != std::string::npos && rightSide.back() == ']') {
size_t open = rightSide.find("[");
size_t close = rightSide.find("]");
std::string arrName = trim(rightSide.substr(0, open));
std::string index = trim(rightSide.substr(open + 1, close - open - 1));
// Specjalna flaga w arg3: ARRAY_IDX:indeks
f.instructions.push_back({ OpType::ASSIGN, varName, arrName, "ARRAY_IDX:" + index });
}
// 3. Wywołanie funkcji: x = func()
else if (rightSide.find("(") != std::string::npos && rightSide.find(")") != std::string::npos) {
size_t open = rightSide.find('(');
std::string funcName = trim(rightSide.substr(0, open));
std::string argsContent = rightSide.substr(open + 1, rightSide.find(')') - open - 1);
f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" });
f.instructions.push_back({ OpType::ASSIGN, varName, "RAX", "" });
}
// 4. Operacje arytmetyczne
else if (rightSide.find("+") != std::string::npos) {
size_t opPos = rightSide.find("+");
f.instructions.push_back({ OpType::ADD, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) });
}
else if (rightSide.find("-") != std::string::npos) {
size_t opPos = rightSide.find("-");
f.instructions.push_back({ OpType::SUB, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) });
}
else if (rightSide.find("*") != std::string::npos) {
size_t opPos = rightSide.find("*");
f.instructions.push_back({ OpType::MUL, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) });
}
else if (rightSide.find("/") != std::string::npos) {
size_t opPos = rightSide.find("/");
f.instructions.push_back({ OpType::DIV, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) });
}
else if (rightSide.find("%") != std::string::npos) {
size_t opPos = rightSide.find("%");
f.instructions.push_back({ OpType::MOD, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 1)) });
}
// 5. Logika
else if (rightSide.find("&&") != std::string::npos) {
size_t opPos = rightSide.find("&&");
f.instructions.push_back({ OpType::LOGIC_AND, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 2)) });
}
else if (rightSide.find("||") != std::string::npos) {
size_t opPos = rightSide.find("||");
f.instructions.push_back({ OpType::LOGIC_OR, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 2)) });
}
else if (rightSide.find("==") != std::string::npos) {
size_t opPos = rightSide.find("==");
f.instructions.push_back({ OpType::EQ, varName, trim(rightSide.substr(0, opPos)), trim(rightSide.substr(opPos + 2)) });
}
// 6. Zwykłe przypisanie stringa
else if (rightSide.size() >= 2 && rightSide.front() == '"') {
std::string content = rightSide.substr(1, rightSide.size() - 2);
std::string label = registerStringLiteral(state, content);
state.varTypes[varName] = "string";
f.instructions.push_back({ OpType::ASSIGN, varName, label, "" });
}
// 7. Zwykłe przypisanie wartości
else {
f.instructions.push_back({ OpType::ASSIGN, varName, rightSide, "" });
}
continue;
}
// I. SAMODZIELNE WYWOŁANIE FUNKCJI (np. input(); )
else if (line.find("(") != std::string::npos && line.find(")") != std::string::npos) {
size_t open = line.find('(');
std::string funcName = trim(line.substr(0, open));
std::string argsContent = line.substr(open + 1, line.find(')') - open - 1);
f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" });
std::cout << " [PARSER] Call void: " << funcName << "\n";
}
}
}
}
void calculateExpressions(CompilerState& state) {
for (const auto& expr : state.expressions) {
if (state.variables.count(expr.leftVar) && state.variables.count(expr.rightVar)) {
int left = state.variables[expr.leftVar];
int right = state.variables[expr.rightVar];
int result = 0;
if (expr.op == "+") result = left + right;
else if (expr.op == "==") result = (left == right);
state.variables[expr.resultVar] = result;
}
}
}
void calculateExpressions(CompilerState& state) {}

View File

@@ -0,0 +1,79 @@
#include "preprocessor.h"
#include <iostream>
#include <sstream>
#include <fstream>
#include <filesystem>
#include <regex>
namespace fs = std::filesystem;
// Funkcja pomocnicza do wczytania pliku
std::string loadFileContent(const std::string& path) {
std::ifstream in(path);
if (!in) {
std::cerr << "[PREPROCESSOR] Error: Could not open included file: " << path << "\n";
return "";
}
return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
}
std::string preprocessSource(const std::string& src, const std::string& projectDir, const std::string& compilerDir) {
std::istringstream iss(src);
std::string line;
std::stringstream output;
while (std::getline(iss, line)) {
// Szukamy: #include "..." lub #include <...>
// U¿ywamy prostego find, ¿eby by³o szybko
std::string trimLine = line;
// Usuwamy bia³e znaki z pocz¹tku
size_t first = trimLine.find_first_not_of(" \t");
if (first != std::string::npos) trimLine = trimLine.substr(first);
if (trimLine.rfind("#include", 0) == 0) {
// Mamy include!
size_t openQuote = trimLine.find('"');
size_t closeQuote = trimLine.rfind('"');
size_t openAngle = trimLine.find('<');
size_t closeAngle = trimLine.rfind('>');
std::string includePath;
bool isStdLib = false;
// Wersja: #include "plik.pcc"
if (openQuote != std::string::npos && closeQuote > openQuote) {
includePath = trimLine.substr(openQuote + 1, closeQuote - openQuote - 1);
}
// Wersja: #include <plik.pcc>
else if (openAngle != std::string::npos && closeAngle > openAngle) {
includePath = trimLine.substr(openAngle + 1, closeAngle - openAngle - 1);
isStdLib = true;
}
if (!includePath.empty()) {
std::string fullPath;
if (isStdLib) {
fullPath = compilerDir + "/std/" + includePath;
std::cout << "[PREPROCESSOR] Including STD lib: " << fullPath << "\n";
}
else {
// Plik lokalny: Szukamy w folderze projektu
if (projectDir.empty()) fullPath = includePath;
else fullPath = projectDir + "/" + includePath;
std::cout << "[PREPROCESSOR] Including local file: " << fullPath << "\n";
}
std::string content = loadFileContent(fullPath);
std::string processedContent = preprocessSource(content, projectDir, compilerDir);
output << "\n// --- BEGIN INCLUDE: " << includePath << " ---\n";
output << processedContent;
output << "\n// --- END INCLUDE ---\n";
}
}
else {
output << line << "\n";
}
}
return output.str();
}

View File

@@ -0,0 +1,8 @@
#ifndef PREPROCESSOR_H
#define PREPROCESSOR_H
#include <string>
std::string preprocessSource(const std::string& src, const std::string& projectDir, const std::string& compilerDir);
#endif

View File

@@ -1,2 +1,29 @@
# PCCCompiler
# PCC Compiler (My C++ Compiler)
![Version](https://img.shields.io/badge/version-0.0.6-blue.svg)
![Status](https://img.shields.io/badge/status-BETA-orange.svg)
![Platform](https://img.shields.io/badge/platform-Windows%20x64-lightgrey.svg)
## Docs
https://nodrop.xyz/docs/docs.html
**PCC Compiler** is a custom programming language compiler built from scratch in C++. It translates PCC code into x64 Assembly (NASM), which is then linked into a standalone Windows executable.
## 🚀 Features
- **Custom Syntax**: C-like syntax easy for beginners.
- **Variables**: Support for `int`, `bool` and `string`.
- **include files**: you can include base files from compiler `#include <main.pcc>` or your own files `#include "myfile.pcc"`.
- **KeyBoard and Inputs Support**: now you can control keyboard inputs using `#include <Input.pcc>`.
- **Control Flow**: `if` statements support.
- **Functions**: Define and call `void` functions.
- **Native Compilation**: Compiles directly to x64 machine code.
- **More Informations**: For more informations check PCC Docs.
## 🛠️ Usage
1. Download the latest release from the [Releases](../../releases) page.
2. Unzip the archive to C:/PCC/
3. Run `start.bat` as Administrator.
4. Compile your code: `PCC.exe code.pcc`.
---
*Created by Michał Lewandowski*

35
push.bat Normal file
View File

@@ -0,0 +1,35 @@
@echo off
echo --- AUTO GIT PUSHER ---
echo.
:: 1. Dodajemy wszystkie pliki
echo [1/3] Adding files...
git add .
:: 2. Pytamy o nazwę commita
echo.
set /p commit_msg="Enter commit message: "
:: Jeśli użytkownik nic nie wpisze, ustaw domyślną
if "%commit_msg%"=="" set commit_msg="Auto update"
:: 3. Robimy commit
echo.
echo [2/3] Committing...
git commit -m "%commit_msg%"
:: 4. Wysyłamy (używamy origin, który już skonfigurowałeś)
echo.
echo [3/3] Pushing to Gitea...
git push origin main
:: Jeśli push się nie uda (np. konflikt), spróbuj wymusić
if %errorlevel% neq 0 (
echo.
echo [WARNING] Standard push failed. Trying force push...
git push origin main --force
)
echo.
echo DONE!
pause