Compare commits
9 Commits
V0.0.2-bet
...
0d016f8ae9
| Author | SHA1 | Date | |
|---|---|---|---|
| 0d016f8ae9 | |||
|
|
99b9ae450e | ||
|
|
9bbf8435c6 | ||
|
|
e250b2f5fb | ||
|
|
aa6d16bc52 | ||
|
|
5fbd0f98a2 | ||
|
|
196140f9b8 | ||
|
|
f192c5a367 | ||
|
|
b88279c841 |
@@ -22,12 +22,14 @@
|
|||||||
<ClCompile Include="codegen.cpp" />
|
<ClCompile Include="codegen.cpp" />
|
||||||
<ClCompile Include="main.cpp" />
|
<ClCompile Include="main.cpp" />
|
||||||
<ClCompile Include="parser.cpp" />
|
<ClCompile Include="parser.cpp" />
|
||||||
|
<ClCompile Include="preprocessor.cpp" />
|
||||||
<ClCompile Include="utils.cpp" />
|
<ClCompile Include="utils.cpp" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ClInclude Include="codegen.h" />
|
<ClInclude Include="codegen.h" />
|
||||||
<ClInclude Include="compiler_types.h" />
|
<ClInclude Include="compiler_types.h" />
|
||||||
<ClInclude Include="parser.h" />
|
<ClInclude Include="parser.h" />
|
||||||
|
<ClInclude Include="preprocessor.h" />
|
||||||
<ClInclude Include="utils.h" />
|
<ClInclude Include="utils.h" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<PropertyGroup Label="Globals">
|
<PropertyGroup Label="Globals">
|
||||||
|
|||||||
@@ -27,6 +27,9 @@
|
|||||||
<ClCompile Include="codegen.cpp">
|
<ClCompile Include="codegen.cpp">
|
||||||
<Filter>Pliki źródłowe</Filter>
|
<Filter>Pliki źródłowe</Filter>
|
||||||
</ClCompile>
|
</ClCompile>
|
||||||
|
<ClCompile Include="preprocessor.cpp">
|
||||||
|
<Filter>Pliki źródłowe</Filter>
|
||||||
|
</ClCompile>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<ClInclude Include="utils.h">
|
<ClInclude Include="utils.h">
|
||||||
@@ -41,5 +44,8 @@
|
|||||||
<ClInclude Include="compiler_types.h">
|
<ClInclude Include="compiler_types.h">
|
||||||
<Filter>Pliki nagłówkowe</Filter>
|
<Filter>Pliki nagłówkowe</Filter>
|
||||||
</ClInclude>
|
</ClInclude>
|
||||||
|
<ClInclude Include="preprocessor.h">
|
||||||
|
<Filter>Pliki nagłówkowe</Filter>
|
||||||
|
</ClInclude>
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
</Project>
|
</Project>
|
||||||
@@ -1,81 +1,280 @@
|
|||||||
#include "codegen.h"
|
#include "codegen.h"
|
||||||
#include <string>
|
#include <iostream>
|
||||||
|
#include <sstream>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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) {
|
std::string generateAssembly(const CompilerState& state) {
|
||||||
std::string result;
|
std::string result;
|
||||||
|
|
||||||
// --- NAG£ÓWEK I SEKCJA DATA ---
|
|
||||||
result += "global main\n";
|
result += "global main\n";
|
||||||
result += "extern printf\n";
|
result += "extern printf\n";
|
||||||
result += "extern GetAsyncKeyState\n\n";
|
result += "extern getchar\n";
|
||||||
|
result += "extern _getch\n"; // ZMIANA: Dodajemy _getch (zamiast lub obok getchar)
|
||||||
result += "section .data\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"; // NOWOŒÆ: Format dla stringów
|
||||||
|
|
||||||
// Generowanie zmiennych
|
// --- WYPISYWANIE STRINGÓW ---
|
||||||
for (const auto& v : state.variables) {
|
for (const auto& pair : state.stringLiterals) {
|
||||||
result += " " + v.first + " dd " + std::to_string(v.second) + "\n";
|
// Nazwa etykiety: db 'Tresc', 0
|
||||||
|
// Uwaga: ASM nie lubi pewnych znaków, ale zak³adamy proste litery
|
||||||
|
result += " " + pair.second + " db '" + pair.first + "', 0\n";
|
||||||
}
|
}
|
||||||
|
result += "section .text\n\n";
|
||||||
|
|
||||||
// Sta³e stringi
|
for (const auto& pair : state.functions) {
|
||||||
result += " fmt db '%d', 10, 0\n";
|
const Function& func = pair.second;
|
||||||
result += " pause_msg db 'Nacisnij ESC aby zamknac...', 10, 0\n\n";
|
result += func.name + ":\n";
|
||||||
|
|
||||||
result += "section .text\n";
|
result += " push rbp\n";
|
||||||
|
result += " mov rbp, rsp\n";
|
||||||
|
result += " sub rsp, 256\n";
|
||||||
|
|
||||||
// --- DEFINICJE FUNKCJI U¯YTKOWNIKA ---
|
std::map<std::string, int> stackMap;
|
||||||
for (const auto& func : state.functions) {
|
int currentStack = 8;
|
||||||
result += func.first + ":\n";
|
|
||||||
result += " sub rsp, 40\n"; // Shadow space
|
|
||||||
|
|
||||||
// Printy wewn¹trz funkcji
|
// 1. ARGUMENTY
|
||||||
for (const std::string& var : func.second) {
|
if (func.args.size() > 0) {
|
||||||
if (state.variables.count(var)) {
|
stackMap[func.args[0]] = currentStack;
|
||||||
result += " mov edx, [" + var + "]\n";
|
result += " mov [rbp-" + std::to_string(currentStack) + "], rcx ; arg " + func.args[0] + "\n";
|
||||||
result += " lea rcx, [rel fmt]\n";
|
currentStack += 8;
|
||||||
result += " call printf\n";
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. INSTRUKCJE
|
||||||
|
for (const auto& instr : func.instructions) {
|
||||||
|
|
||||||
|
// Rezerwacja miejsca dla nowych zmiennych (wynikowych)
|
||||||
|
// Dodajemy tu OpType::SUB i OpType::MUL
|
||||||
|
bool isWriteOp = (instr.type == OpType::ASSIGN ||
|
||||||
|
instr.type == OpType::ADD ||
|
||||||
|
instr.type == OpType::EQ ||
|
||||||
|
instr.type == OpType::SUB ||
|
||||||
|
instr.type == OpType::MUL);
|
||||||
|
|
||||||
|
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;
|
||||||
|
if (instr.arg3 == "STRING") {
|
||||||
|
result += " lea rax, [rel " + src + "]\n";
|
||||||
|
std::string dst = getVarLocation(instr.arg1, stackMap);
|
||||||
|
result += " mov qword " + dst + ", rax\n";
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
std::string srcLoc = getVarLocation(instr.arg2, stackMap);
|
||||||
|
std::string dst = getVarLocation(instr.arg1, stackMap);
|
||||||
|
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: {
|
||||||
|
// 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 += " 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::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::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";
|
||||||
|
}
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case OpType::LABEL: {
|
||||||
|
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 {
|
||||||
|
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::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.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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";
|
||||||
|
}
|
||||||
|
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";
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
result += " movsxd rcx, dword " + val + "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result += " call " + instr.arg1 + "\n";
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result += " add rsp, 40\n";
|
if (func.returnType == "void") {
|
||||||
result += " ret\n\n";
|
result += " leave\n ret\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";
|
|
||||||
}
|
}
|
||||||
|
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;
|
return result;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,28 +6,54 @@
|
|||||||
#include <map>
|
#include <map>
|
||||||
#include <stack>
|
#include <stack>
|
||||||
|
|
||||||
struct Expression {
|
// Typy operacji, które nasz kompilator rozumie
|
||||||
std::string leftVar;
|
enum class OpType {
|
||||||
std::string op;
|
ASSIGN, // a = 5
|
||||||
std::string rightVar;
|
ADD, // a = b + c
|
||||||
std::string resultVar;
|
SUB, // a = b - c
|
||||||
|
MUL, // a = b * c
|
||||||
|
EQ, // a == b
|
||||||
|
PRINT, // print(a)
|
||||||
|
JMP_FALSE, // if (false) skocz...
|
||||||
|
JMP, // else / pêtla
|
||||||
|
LABEL, // miejsce skoku
|
||||||
|
CALL, // wywo³anie funkcji
|
||||||
|
RETURN, // return x
|
||||||
|
NOP // pusta instrukcja
|
||||||
};
|
};
|
||||||
|
|
||||||
struct IfBlock {
|
// Pojedynczy rozkaz kompilatora (Intermediate Representation)
|
||||||
std::string conditionVar;
|
struct Instruction {
|
||||||
std::vector<std::string> prints;
|
OpType type;
|
||||||
|
std::string arg1;
|
||||||
|
std::string arg2;
|
||||||
|
std::string arg3;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 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
|
||||||
};
|
};
|
||||||
|
|
||||||
struct CompilerState {
|
struct CompilerState {
|
||||||
std::vector<Expression> expressions;
|
// Mapa wszystkich funkcji (klucz to nazwa)
|
||||||
std::vector<IfBlock> ifBlocks;
|
std::map<std::string, Function> functions;
|
||||||
std::map<std::string, int> variables;
|
|
||||||
std::vector<std::string> printCalls;
|
// Zmienne globalne (tylko nazwa -> wartoœæ pocz¹tkowa)
|
||||||
std::vector<std::string> globalPrints;
|
std::map<std::string, int> globals;
|
||||||
std::map<std::string, std::vector<std::string>> functions;
|
|
||||||
bool inFunction = false;
|
// Stan parsera
|
||||||
std::string currentFunction;
|
Function* currentFunction = nullptr; // WskaŸnik na aktualnie parsuj¹c¹ siê funkcjê
|
||||||
std::stack<bool> braceStack;
|
int labelCounter = 0; // Do generowania unikalnych nazw etykiet (L1, L2...)
|
||||||
|
std::stack<std::string> loopStack; // Do break/continue (przysz³oœciowo)
|
||||||
|
|
||||||
|
std::stack<std::string> blockStack;
|
||||||
|
|
||||||
|
std::map<std::string, std::string> stringLiterals;
|
||||||
|
int stringCounter = 0; // Licznik do generowania nazw str_1, str_2...
|
||||||
};
|
};
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -2,14 +2,24 @@
|
|||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
#include <cstdlib> // do std::system
|
#include <cstdlib>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <windows.h>
|
||||||
#include "compiler_types.h"
|
#include "compiler_types.h"
|
||||||
#include "parser.h"
|
#include "parser.h"
|
||||||
#include "codegen.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[]) {
|
int main(int argc, char* argv[]) {
|
||||||
std::string inputFile, outputName;
|
std::string inputFile, outputName;
|
||||||
std::string Version = "v1.5.0-modular"; // Zaktualizowałem wersję :)
|
std::string Version = "v0.0.5-beta";
|
||||||
bool showHelp = false, showVersion = false, showCredits = false;
|
bool showHelp = false, showVersion = false, showCredits = false;
|
||||||
|
|
||||||
// --- PARSOWANIE ARGUMENTÓW ---
|
// --- PARSOWANIE ARGUMENTÓW ---
|
||||||
@@ -68,10 +78,22 @@ int main(int argc, char* argv[]) {
|
|||||||
return 1;
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ... wczytywanie pliku (to co miałeś) ...
|
||||||
std::string src((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
std::string src((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||||
in.close();
|
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;
|
CompilerState state;
|
||||||
|
|
||||||
std::cout << "[INFO] Parsing code...\n";
|
std::cout << "[INFO] Parsing code...\n";
|
||||||
@@ -90,24 +112,31 @@ int main(int argc, char* argv[]) {
|
|||||||
// --- ZAPIS I KOMPILACJA ZEWNĘTRZNA ---
|
// --- ZAPIS I KOMPILACJA ZEWNĘTRZNA ---
|
||||||
std::system("if not exist output mkdir output");
|
std::system("if not exist output mkdir output");
|
||||||
|
|
||||||
std::string baseName = outputName.empty() ?
|
// 1. Ustal bazową nazwę (bez rozszerzenia)
|
||||||
inputFile.substr(0, inputFile.find_last_of(".")) : outputName;
|
std::string baseName;
|
||||||
|
|
||||||
// Upewnij się, że nazwa nie ma rozszerzenia .exe w środku ścieżki
|
|
||||||
if (outputName.empty()) {
|
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 {
|
else {
|
||||||
// Jeśli użytkownik podał nazwę bez .exe, dodaj ją
|
// Jeśli podano -o, sprawdź czy ma .exe i ewentualnie utnij
|
||||||
if (outputName.find(".exe") == std::string::npos) outputName += ".exe";
|
// (żebyśmy mogli dodać .asm i .obj bez bałaganu)
|
||||||
baseName = outputName;
|
size_t exePos = outputName.find(".exe");
|
||||||
|
if (exePos != std::string::npos)
|
||||||
|
baseName = outputName.substr(0, exePos);
|
||||||
|
else
|
||||||
|
baseName = outputName;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ścieżki wyjściowe
|
// Teraz budujemy ścieżki - czysto i ładnie
|
||||||
// Uwaga: zakładam proste nazewnictwo, można tu poprawić usuwanie ścieżek z nazwy pliku
|
|
||||||
std::string asmPath = "output\\" + baseName + ".asm";
|
std::string asmPath = "output\\" + baseName + ".asm";
|
||||||
std::string objPath = "output\\" + baseName + ".obj";
|
std::string objPath = "output\\" + baseName + ".obj";
|
||||||
std::string exePath = "output\\" + baseName;
|
std::string exePath = "output\\" + baseName + ".exe";
|
||||||
|
|
||||||
|
|
||||||
// Zapisz ASM
|
// Zapisz ASM
|
||||||
std::ofstream asmOut(asmPath);
|
std::ofstream asmOut(asmPath);
|
||||||
|
|||||||
@@ -2,182 +2,236 @@
|
|||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
#include <sstream>
|
#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;
|
||||||
|
}
|
||||||
|
|
||||||
void processSource(const std::string& src, CompilerState& state) {
|
void processSource(const std::string& src, CompilerState& state) {
|
||||||
std::istringstream iss(src);
|
std::istringstream iss(src);
|
||||||
std::string line;
|
std::string line;
|
||||||
|
|
||||||
std::cout << "Parsuje kod:\n";
|
|
||||||
|
|
||||||
while (std::getline(iss, line)) {
|
while (std::getline(iss, line)) {
|
||||||
line = trim(line);
|
line = trim(line);
|
||||||
if (line.empty()) continue;
|
if (line.empty() || line.substr(0, 2) == "//" || line[0] == '#') continue;
|
||||||
|
|
||||||
// FUNKCJE
|
// --- 1. DEFINICJA FUNKCJI ---
|
||||||
if (line.length() > 4 && line.substr(0, 4) == "void") {
|
// Warunki: zaczyna się od typu, ma '(', ma '{' i NIE ma '=' (żeby nie mylić ze zmienną)
|
||||||
size_t openParen = line.find("(", 4);
|
bool startsWithType = (line.rfind("int ", 0) == 0 || line.rfind("void ", 0) == 0 || line.rfind("bool ", 0) == 0);
|
||||||
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--;
|
|
||||||
|
|
||||||
// ZMIANA: używamy 'state' zamiast 'compilerState'
|
if (startsWithType && line.find("(") != std::string::npos && line.find("{") != std::string::npos && line.find("=") == std::string::npos) {
|
||||||
state.currentFunction = line.substr(nameStart, nameEnd - nameStart);
|
|
||||||
state.functions[state.currentFunction] = std::vector<std::string>();
|
size_t openParen = line.find('(');
|
||||||
state.inFunction = true;
|
std::string typeRaw = line.substr(0, line.find(' '));
|
||||||
std::cout << " FUNC " << state.currentFunction << "\n";
|
std::string nameRaw = line.substr(typeRaw.length(), openParen - typeRaw.length());
|
||||||
state.braceStack.push(true);
|
std::string funcName = trim(nameRaw);
|
||||||
continue;
|
|
||||||
}
|
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) {
|
// --- 2. ZAMYKANIE BLOKU '}' ---
|
||||||
if (!state.braceStack.empty()) {
|
if (line == "}") {
|
||||||
state.braceStack.pop();
|
// Najpierw sprawdzamy, czy zamykamy IF-a (czy jest coś na stosie bloków)
|
||||||
if (!state.braceStack.empty()) {
|
if (!state.blockStack.empty()) {
|
||||||
state.inFunction = false;
|
std::string label = state.blockStack.top();
|
||||||
state.currentFunction.clear();
|
state.blockStack.pop();
|
||||||
std::cout << " END FUNC\n";
|
if (state.currentFunction) {
|
||||||
|
state.currentFunction->instructions.push_back({ OpType::LABEL, label, "", "" });
|
||||||
}
|
}
|
||||||
|
std::cout << " [PARSER] } End IF block -> " << label << "\n";
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// Jeśli stos pusty, to koniec funkcji
|
||||||
|
state.currentFunction = nullptr;
|
||||||
|
std::cout << " [PARSER] } End Function\n";
|
||||||
}
|
}
|
||||||
continue;
|
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;
|
// --- JESTEŚMY W ŚRODKU FUNKCJI ---
|
||||||
size_t opPos;
|
if (state.currentFunction) {
|
||||||
|
Function& f = *state.currentFunction;
|
||||||
|
|
||||||
size_t eqPos2 = rightSide.find("==");
|
// A. RETURN
|
||||||
if (eqPos2 != std::string::npos && (eqPos2 + 1 < rightSide.length()) && rightSide[eqPos2 + 2] != '=') {
|
if (line.substr(0, 6) == "return") {
|
||||||
op = "==";
|
std::string val = trim(line.substr(6));
|
||||||
opPos = eqPos2;
|
if (!val.empty() && val.back() == ';') val.pop_back();
|
||||||
}
|
f.instructions.push_back({ OpType::RETURN, val, "", "" });
|
||||||
else {
|
std::cout << " [PARSER] Return: " << val << "\n";
|
||||||
opPos = rightSide.find('+');
|
}
|
||||||
if (opPos == std::string::npos) opPos = rightSide.find('-');
|
// B. PRINT
|
||||||
if (opPos != std::string::npos) op = rightSide.substr(opPos, 1);
|
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));
|
||||||
|
|
||||||
if (opPos != std::string::npos && !op.empty()) {
|
// Czy to bezpośredni napis? np. print("Hello")
|
||||||
std::string leftVar = trim(rightSide.substr(0, opPos));
|
if (arg.size() >= 2 && arg.front() == '"' && arg.back() == '"') {
|
||||||
std::string rightVar = trim(rightSide.substr(opPos + op.length()));
|
std::string content = arg.substr(1, arg.size() - 2);
|
||||||
|
|
||||||
// ZMIANA: używamy 'state'
|
// Rejestrujemy
|
||||||
Expression expr{ leftVar, op, rightVar, name };
|
std::string label;
|
||||||
state.expressions.push_back(expr);
|
if (state.stringLiterals.count(content)) {
|
||||||
state.variables[name] = 0;
|
label = state.stringLiterals[content];
|
||||||
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 (...) {
|
else {
|
||||||
// Usunięto '❌' żeby uniknąć warningów o kodowaniu (C4566)
|
label = "str_" + std::to_string(state.stringCounter++);
|
||||||
std::cout << " [X] BLAD: '" << rightSide << "'\n";
|
state.stringLiterals[content] = label;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// 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);
|
// Dajemy znać generatorowi, że to typ STRING
|
||||||
size_t valStart = valueRaw.find_first_not_of(" \t");
|
f.instructions.push_back({ OpType::PRINT, label, "STRING", "" });
|
||||||
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);
|
|
||||||
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 {
|
else {
|
||||||
state.globalPrints.push_back(varName);
|
// Zwykła zmienna (int lub string - generator musi zgadnąć lub my musimy wiedzieć)
|
||||||
std::cout << " PRINT " << varName << "\n";
|
// 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", "" });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
// 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
|
// C. IF STATEMENT
|
||||||
std::cout << " CALL FUNC " << funcName << "\n";
|
else if (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));
|
||||||
|
std::string labelName = "L_" + std::to_string(state.labelCounter++);
|
||||||
|
|
||||||
|
// Skok warunkowy
|
||||||
|
f.instructions.push_back({ OpType::JMP_FALSE, labelName, condition, "" });
|
||||||
|
state.blockStack.push(labelName);
|
||||||
|
|
||||||
|
std::cout << " [PARSER] IF (" << condition << ") -> Jump to " << labelName << "\n";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// D. PRZYPISANIE ZMIENNEJ (LUB DEKLARACJA)
|
||||||
|
// np. "int a = 5;" LUB "a = b + c;"
|
||||||
|
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));
|
||||||
|
|
||||||
|
bool isStringDecl = false; // Flaga, czy to string
|
||||||
|
if (!rightSide.empty() && rightSide.back() == ';') rightSide.pop_back();
|
||||||
|
|
||||||
|
// Obsługa nazwy zmiennej (usuwanie "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) { // NOWOŚĆ
|
||||||
|
varName = trim(leftSide.substr(7));
|
||||||
|
isStringDecl = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// 1. Czy to wywołanie funkcji? int x = func();
|
||||||
|
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);
|
||||||
|
|
||||||
|
// CALL func
|
||||||
|
f.instructions.push_back({ OpType::CALL, funcName, argsContent, "" });
|
||||||
|
// ASSIGN result (RAX) to variable
|
||||||
|
f.instructions.push_back({ OpType::ASSIGN, varName, "RAX", "" });
|
||||||
|
std::cout << " [PARSER] Call & Assign: " << varName << " = " << funcName << "()\n";
|
||||||
|
}
|
||||||
|
// 2. Czy to dodawanie? a + b
|
||||||
|
else if (rightSide.find("+") != std::string::npos) {
|
||||||
|
size_t opPos = rightSide.find("+");
|
||||||
|
std::string a = trim(rightSide.substr(0, opPos));
|
||||||
|
std::string b = trim(rightSide.substr(opPos + 1));
|
||||||
|
f.instructions.push_back({ OpType::ADD, varName, a, b });
|
||||||
|
}
|
||||||
|
// 3. NOWOŚĆ: Czy to odejmowanie? a - b
|
||||||
|
else if (rightSide.find("-") != std::string::npos) {
|
||||||
|
size_t opPos = rightSide.find("-");
|
||||||
|
std::string a = trim(rightSide.substr(0, opPos));
|
||||||
|
std::string b = trim(rightSide.substr(opPos + 1));
|
||||||
|
f.instructions.push_back({ OpType::SUB, varName, a, b }); // <--- Używamy SUB
|
||||||
|
}
|
||||||
|
// 4. NOWOŚĆ: Czy to mnożenie? a * b
|
||||||
|
else if (rightSide.find("*") != std::string::npos) {
|
||||||
|
size_t opPos = rightSide.find("*");
|
||||||
|
std::string a = trim(rightSide.substr(0, opPos));
|
||||||
|
std::string b = trim(rightSide.substr(opPos + 1));
|
||||||
|
f.instructions.push_back({ OpType::MUL, varName, a, b }); // <--- Używamy MUL
|
||||||
|
}
|
||||||
|
// 3. Czy to porównanie? a == b (Ważne: == może być w IFie, ale tu jesteśmy w linii z '=')
|
||||||
|
// UWAGA: To rzadkie w C++ (bool x = a == b), ale obsłużmy proste przypisanie wartości logicznej
|
||||||
|
else if (rightSide.find("==") != std::string::npos) {
|
||||||
|
size_t opPos = rightSide.find("==");
|
||||||
|
std::string a = trim(rightSide.substr(0, opPos));
|
||||||
|
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, "" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// E. SAMODZIELNE WYWOŁANIE FUNKCJI (bez =)
|
||||||
|
// np. func();
|
||||||
|
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) {}
|
||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
79
PCCcompiler/preprocessor.cpp
Normal file
79
PCCcompiler/preprocessor.cpp
Normal 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();
|
||||||
|
}
|
||||||
8
PCCcompiler/preprocessor.h
Normal file
8
PCCcompiler/preprocessor.h
Normal 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
|
||||||
29
README.md
29
README.md
@@ -1,2 +1,29 @@
|
|||||||
# PCCCompiler
|
# PCC Compiler (My C++ Compiler)
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
## 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*
|
||||||
|
|||||||
Reference in New Issue
Block a user