From 1884950f6fa9c87287047493b420645914aff698 Mon Sep 17 00:00:00 2001 From: mmichlol Date: Fri, 6 Feb 2026 16:04:23 +0100 Subject: [PATCH] modernize code --- .gitignore | 436 ++++++++++++++++++++++++ PCCcompiler.slnx | 7 + PCCcompiler/PCCcompiler.vcxproj | 144 ++++++++ PCCcompiler/PCCcompiler.vcxproj.filters | 45 +++ PCCcompiler/codegen.cpp | 81 +++++ PCCcompiler/codegen.h | 11 + PCCcompiler/compiler_types.h | 33 ++ PCCcompiler/main.cpp | 134 ++++++++ PCCcompiler/parser.cpp | 183 ++++++++++ PCCcompiler/parser.h | 7 + PCCcompiler/utils.cpp | 8 + PCCcompiler/utils.h | 6 + 12 files changed, 1095 insertions(+) create mode 100644 .gitignore create mode 100644 PCCcompiler.slnx create mode 100644 PCCcompiler/PCCcompiler.vcxproj create mode 100644 PCCcompiler/PCCcompiler.vcxproj.filters create mode 100644 PCCcompiler/codegen.cpp create mode 100644 PCCcompiler/codegen.h create mode 100644 PCCcompiler/compiler_types.h create mode 100644 PCCcompiler/main.cpp create mode 100644 PCCcompiler/parser.cpp create mode 100644 PCCcompiler/parser.h create mode 100644 PCCcompiler/utils.cpp create mode 100644 PCCcompiler/utils.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c0e2944 --- /dev/null +++ b/.gitignore @@ -0,0 +1,436 @@ +# ---> VisualStudio +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +# but not Directory.Build.rsp, as it configures directory-level build defaults +!Directory.Build.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml + +# ---> C++ +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + diff --git a/PCCcompiler.slnx b/PCCcompiler.slnx new file mode 100644 index 0000000..5aa5c35 --- /dev/null +++ b/PCCcompiler.slnx @@ -0,0 +1,7 @@ + + + + + + + diff --git a/PCCcompiler/PCCcompiler.vcxproj b/PCCcompiler/PCCcompiler.vcxproj new file mode 100644 index 0000000..4385ef8 --- /dev/null +++ b/PCCcompiler/PCCcompiler.vcxproj @@ -0,0 +1,144 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + + + + + + + + + + + + + 18.0 + Win32Proj + {60a99674-9bdb-4552-bfef-fc5b17de2cf8} + PCCcompiler + 10.0 + + + + Application + true + v145 + Unicode + + + Application + false + v145 + true + Unicode + + + Application + true + v145 + Unicode + + + Application + false + v145 + true + Unicode + + + + + + + + + + + + + + + + + + + + + + Level3 + true + WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + _DEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + Level3 + true + true + true + NDEBUG;_CONSOLE;%(PreprocessorDefinitions) + true + stdcpp20 + + + Console + true + + + + + + \ No newline at end of file diff --git a/PCCcompiler/PCCcompiler.vcxproj.filters b/PCCcompiler/PCCcompiler.vcxproj.filters new file mode 100644 index 0000000..7fa01c4 --- /dev/null +++ b/PCCcompiler/PCCcompiler.vcxproj.filters @@ -0,0 +1,45 @@ + + + + + {4FC737F1-C7A5-4376-A066-2A32D752A2FF} + cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx + + + {93995380-89BD-4b04-88EB-625FBE52EBFB} + h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd + + + {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + + + Pliki źródłowe + + + Pliki źródłowe + + + Pliki źródłowe + + + Pliki źródłowe + + + + + Pliki nagłówkowe + + + Pliki nagłówkowe + + + Pliki nagłówkowe + + + Pliki nagłówkowe + + + \ No newline at end of file diff --git a/PCCcompiler/codegen.cpp b/PCCcompiler/codegen.cpp new file mode 100644 index 0000000..b193802 --- /dev/null +++ b/PCCcompiler/codegen.cpp @@ -0,0 +1,81 @@ +#include "codegen.h" +#include +#include + +std::string generateAssembly(const CompilerState& state) { + std::string result; + + // --- NAGWEK I SEKCJA DATA --- + result += "global main\n"; + result += "extern printf\n"; + result += "extern GetAsyncKeyState\n\n"; + + result += "section .data\n"; + + // Generowanie zmiennych + for (const auto& v : state.variables) { + result += " " + v.first + " dd " + std::to_string(v.second) + "\n"; + } + + // Stae stringi + result += " fmt db '%d', 10, 0\n"; + result += " pause_msg db 'Nacisnij ESC aby zamknac...', 10, 0\n\n"; + + result += "section .text\n"; + + // --- DEFINICJE FUNKCJI UYTKOWNIKA --- + for (const auto& func : state.functions) { + result += func.first + ":\n"; + result += " sub rsp, 40\n"; // Shadow space + + // Printy wewntrz 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 += " 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"; + } + } + + // Wywoania funkcji zdefiniowanych wczeniej + 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"; + + // Wyjcie z programu + result += " add rsp, 40\n"; + result += " ret\n"; + + return result; +} diff --git a/PCCcompiler/codegen.h b/PCCcompiler/codegen.h new file mode 100644 index 0000000..a1491d5 --- /dev/null +++ b/PCCcompiler/codegen.h @@ -0,0 +1,11 @@ +#ifndef CODEGEN_H +#define CODEGEN_H + +#include +#include "compiler_types.h" + +// Gwna funkcja generujca kod ASM na podstawie stanu kompilatora +std::string generateAssembly(const CompilerState& state); + +#endif // CODEGEN_H + diff --git a/PCCcompiler/compiler_types.h b/PCCcompiler/compiler_types.h new file mode 100644 index 0000000..fdfd95c --- /dev/null +++ b/PCCcompiler/compiler_types.h @@ -0,0 +1,33 @@ +#ifndef COMPILER_TYPES_H +#define COMPILER_TYPES_H + +#include +#include +#include +#include + +struct Expression { + std::string leftVar; + std::string op; + std::string rightVar; + std::string resultVar; +}; + +struct IfBlock { + std::string conditionVar; + std::vector prints; +}; + +struct CompilerState { + std::vector expressions; + std::vector ifBlocks; + std::map variables; + std::vector printCalls; + std::vector globalPrints; + std::map> functions; + bool inFunction = false; + std::string currentFunction; + std::stack braceStack; +}; + +#endif diff --git a/PCCcompiler/main.cpp b/PCCcompiler/main.cpp new file mode 100644 index 0000000..b52fe4a --- /dev/null +++ b/PCCcompiler/main.cpp @@ -0,0 +1,134 @@ +#include +#include +#include +#include +#include // do std::system +#include "compiler_types.h" +#include "parser.h" +#include "codegen.h" + +int main(int argc, char* argv[]) { + std::string inputFile, outputName; + std::string Version = "v1.5.0-modular"; // Zaktualizowałem wersję :) + bool showHelp = false, showVersion = false, showCredits = false; + + // --- PARSOWANIE ARGUMENTÓW --- + for (int i = 1; i < argc; i++) { + std::string arg = argv[i]; + + if (arg == "--help" || arg == "-h") { + showHelp = true; + } + else if (arg == "--version" || arg == "-v") { + showVersion = true; + } + else if (arg == "--credits" || arg == "-c") { + showCredits = true; + } + else if (arg.substr(0, 2) == "-o") { + if (arg.size() > 2) { + outputName = arg.substr(2); + } + else if (i + 1 < argc) { + outputName = argv[++i]; + } + } + else { + inputFile = arg; + } + } + + // --- OBSŁUGA INFORMACYJNA --- + if (showVersion) { + std::cout << "PCC Compiler " << Version << " (x64, Modular structure)\n"; + return 0; + } + + if (showCredits) { + std::cout << "Created by: Michal Lewandowski\n"; + std::cout << "Contact : slawek.1q2w3e4r@gmail.com\n"; // Twój email z oryginału + std::cout << "Docs: https://nodrop.xyz/PCC_docs.html\n"; + return 0; + } + + if (showHelp || inputFile.empty()) { + std::cout << "PCC Compiler " << Version << "\n"; + std::cout << "Usage: PCC [Options] File.pcc\n\n"; + std::cout << "Options:\n"; + std::cout << " -h, --help Show Help\n"; + std::cout << " -v, --version Show Version\n"; + std::cout << " -o Name Exe Name (output\\Name.exe)\n"; + return 0; + } + + // --- WCZYTYWANIE PLIKU --- + std::ifstream in(inputFile); + if (!in) { + std::cerr << "Error: Cannot open file " << inputFile << "\n"; + return 1; + } + + std::string src((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + in.close(); + + // --- LOGIKA KOMPILATORA --- + CompilerState state; + + std::cout << "[INFO] Parsing code...\n"; + // 1. Parsowanie tekstu do struktur + processSource(src, state); + + std::cout << "[INFO] Calculating expressions...\n"; + // 2. Obliczanie matematyki + calculateExpressions(state); + + std::cout << "[INFO] Generating Assembly...\n"; + // 3. Generowanie kodu ASM + std::string asmCode = generateAssembly(state); + + + // --- 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 + if (outputName.empty()) { + if (baseName.find(".exe") == std::string::npos) baseName += ".exe"; + } + else { + // Jeśli użytkownik podał nazwę bez .exe, dodaj ją + if (outputName.find(".exe") == std::string::npos) outputName += ".exe"; + baseName = outputName; + } + + // Ścieżki wyjściowe + // Uwaga: zakładam proste nazewnictwo, można tu poprawić usuwanie ścieżek z nazwy pliku + std::string asmPath = "output\\" + baseName + ".asm"; + std::string objPath = "output\\" + baseName + ".obj"; + std::string exePath = "output\\" + baseName; + + // Zapisz ASM + std::ofstream asmOut(asmPath); + asmOut << asmCode; + asmOut.close(); + std::cout << "ASM saved to: " << asmPath << "\n"; + + // Uruchom NASM + std::string nasmCmd = "nasm -f win64 \"" + asmPath + "\" -o \"" + objPath + "\""; + if (std::system(nasmCmd.c_str()) != 0) { + std::cerr << "NASM Error! Check if NASM is in PATH.\n"; + return 1; + } + + // Uruchom GoLink + std::string linkCmd = "go-link.exe /console /entry:main \"" + objPath + "\" msvcrt.dll kernel32.dll user32.dll \"" + exePath + "\""; + if (std::system(linkCmd.c_str()) != 0) { + std::cerr << "GoLink Error! Check if go-link.exe is in PATH.\n"; + return 1; + } + + std::cout << "SUCCESS! Executable created: " << exePath << "\n"; + return 0; +} diff --git a/PCCcompiler/parser.cpp b/PCCcompiler/parser.cpp new file mode 100644 index 0000000..dc5f812 --- /dev/null +++ b/PCCcompiler/parser.cpp @@ -0,0 +1,183 @@ +#include "parser.h" +#include "utils.h" +#include +#include +#include "compiler_types.h" + +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; + + // 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--; + + // ZMIANA: używamy 'state' zamiast 'compilerState' + state.currentFunction = line.substr(nameStart, nameEnd - nameStart); + state.functions[state.currentFunction] = std::vector(); + state.inFunction = true; + std::cout << " FUNC " << state.currentFunction << "\n"; + state.braceStack.push(true); + 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"; + } + } + 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; + + 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); + 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"; + } + } + } + } + // 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"; + } + } + } +} + +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; + } + } +} diff --git a/PCCcompiler/parser.h b/PCCcompiler/parser.h new file mode 100644 index 0000000..57f50d4 --- /dev/null +++ b/PCCcompiler/parser.h @@ -0,0 +1,7 @@ +#ifndef PARSER_H +#define PARSER_H +#include "compiler_types.h" + +void processSource(const std::string& src, CompilerState& state); +void calculateExpressions(CompilerState& state); +#endif diff --git a/PCCcompiler/utils.cpp b/PCCcompiler/utils.cpp new file mode 100644 index 0000000..d898b15 --- /dev/null +++ b/PCCcompiler/utils.cpp @@ -0,0 +1,8 @@ +#include "utils.h" + +std::string trim(const std::string& str) { + size_t first = str.find_first_not_of(" \t"); + if (first == std::string::npos) return ""; + size_t last = str.find_last_not_of(" \t"); + return str.substr(first, last - first + 1); +} diff --git a/PCCcompiler/utils.h b/PCCcompiler/utils.h new file mode 100644 index 0000000..4d87dea --- /dev/null +++ b/PCCcompiler/utils.h @@ -0,0 +1,6 @@ +#ifndef UTILS_H +#define UTILS_H +#include + +std::string trim(const std::string& str); +#endif