Compare commits
10 Commits
1d8d02f2a8
...
V0.0.5
| Author | SHA1 | Date | |
|---|---|---|---|
| 5a24fa900e | |||
|
|
9bbf8435c6 | ||
|
|
e250b2f5fb | ||
|
|
aa6d16bc52 | ||
|
|
5fbd0f98a2 | ||
|
|
196140f9b8 | ||
|
|
f192c5a367 | ||
|
|
b88279c841 | ||
|
|
1cf89efb4b | ||
|
|
1884950f6f |
7
PCCcompiler.slnx
Normal file
7
PCCcompiler.slnx
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
<Solution>
|
||||||
|
<Configurations>
|
||||||
|
<Platform Name="x64" />
|
||||||
|
<Platform Name="x86" />
|
||||||
|
</Configurations>
|
||||||
|
<Project Path="PCCcompiler/PCCcompiler.vcxproj" Id="60a99674-9bdb-4552-bfef-fc5b17de2cf8" />
|
||||||
|
</Solution>
|
||||||
146
PCCcompiler/PCCcompiler.vcxproj
Normal file
146
PCCcompiler/PCCcompiler.vcxproj
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||||
|
<ItemGroup Label="ProjectConfigurations">
|
||||||
|
<ProjectConfiguration Include="Debug|Win32">
|
||||||
|
<Configuration>Debug</Configuration>
|
||||||
|
<Platform>Win32</Platform>
|
||||||
|
</ProjectConfiguration>
|
||||||
|
<ProjectConfiguration Include="Release|Win32">
|
||||||
|
<Configuration>Release</Configuration>
|
||||||
|
<Platform>Win32</Platform>
|
||||||
|
</ProjectConfiguration>
|
||||||
|
<ProjectConfiguration Include="Debug|x64">
|
||||||
|
<Configuration>Debug</Configuration>
|
||||||
|
<Platform>x64</Platform>
|
||||||
|
</ProjectConfiguration>
|
||||||
|
<ProjectConfiguration Include="Release|x64">
|
||||||
|
<Configuration>Release</Configuration>
|
||||||
|
<Platform>x64</Platform>
|
||||||
|
</ProjectConfiguration>
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<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">
|
||||||
|
<VCProjectVersion>18.0</VCProjectVersion>
|
||||||
|
<Keyword>Win32Proj</Keyword>
|
||||||
|
<ProjectGuid>{60a99674-9bdb-4552-bfef-fc5b17de2cf8}</ProjectGuid>
|
||||||
|
<RootNamespace>PCCcompiler</RootNamespace>
|
||||||
|
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
|
||||||
|
</PropertyGroup>
|
||||||
|
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||||
|
<ConfigurationType>Application</ConfigurationType>
|
||||||
|
<UseDebugLibraries>true</UseDebugLibraries>
|
||||||
|
<PlatformToolset>v145</PlatformToolset>
|
||||||
|
<CharacterSet>Unicode</CharacterSet>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||||
|
<ConfigurationType>Application</ConfigurationType>
|
||||||
|
<UseDebugLibraries>false</UseDebugLibraries>
|
||||||
|
<PlatformToolset>v145</PlatformToolset>
|
||||||
|
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||||
|
<CharacterSet>Unicode</CharacterSet>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||||
|
<ConfigurationType>Application</ConfigurationType>
|
||||||
|
<UseDebugLibraries>true</UseDebugLibraries>
|
||||||
|
<PlatformToolset>v145</PlatformToolset>
|
||||||
|
<CharacterSet>Unicode</CharacterSet>
|
||||||
|
</PropertyGroup>
|
||||||
|
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||||
|
<ConfigurationType>Application</ConfigurationType>
|
||||||
|
<UseDebugLibraries>false</UseDebugLibraries>
|
||||||
|
<PlatformToolset>v145</PlatformToolset>
|
||||||
|
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||||
|
<CharacterSet>Unicode</CharacterSet>
|
||||||
|
</PropertyGroup>
|
||||||
|
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||||
|
<ImportGroup Label="ExtensionSettings">
|
||||||
|
</ImportGroup>
|
||||||
|
<ImportGroup Label="Shared">
|
||||||
|
</ImportGroup>
|
||||||
|
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||||
|
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||||
|
</ImportGroup>
|
||||||
|
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||||
|
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||||
|
</ImportGroup>
|
||||||
|
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||||
|
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||||
|
</ImportGroup>
|
||||||
|
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||||
|
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||||
|
</ImportGroup>
|
||||||
|
<PropertyGroup Label="UserMacros" />
|
||||||
|
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||||
|
<ClCompile>
|
||||||
|
<WarningLevel>Level3</WarningLevel>
|
||||||
|
<SDLCheck>true</SDLCheck>
|
||||||
|
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||||
|
<ConformanceMode>true</ConformanceMode>
|
||||||
|
<LanguageStandard>stdcpp20</LanguageStandard>
|
||||||
|
</ClCompile>
|
||||||
|
<Link>
|
||||||
|
<SubSystem>Console</SubSystem>
|
||||||
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
|
</Link>
|
||||||
|
</ItemDefinitionGroup>
|
||||||
|
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||||
|
<ClCompile>
|
||||||
|
<WarningLevel>Level3</WarningLevel>
|
||||||
|
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||||
|
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||||
|
<SDLCheck>true</SDLCheck>
|
||||||
|
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||||
|
<ConformanceMode>true</ConformanceMode>
|
||||||
|
<LanguageStandard>stdcpp20</LanguageStandard>
|
||||||
|
</ClCompile>
|
||||||
|
<Link>
|
||||||
|
<SubSystem>Console</SubSystem>
|
||||||
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
|
</Link>
|
||||||
|
</ItemDefinitionGroup>
|
||||||
|
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||||
|
<ClCompile>
|
||||||
|
<WarningLevel>Level3</WarningLevel>
|
||||||
|
<SDLCheck>true</SDLCheck>
|
||||||
|
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||||
|
<ConformanceMode>true</ConformanceMode>
|
||||||
|
<LanguageStandard>stdcpp20</LanguageStandard>
|
||||||
|
</ClCompile>
|
||||||
|
<Link>
|
||||||
|
<SubSystem>Console</SubSystem>
|
||||||
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
|
</Link>
|
||||||
|
</ItemDefinitionGroup>
|
||||||
|
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||||
|
<ClCompile>
|
||||||
|
<WarningLevel>Level3</WarningLevel>
|
||||||
|
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||||
|
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||||
|
<SDLCheck>true</SDLCheck>
|
||||||
|
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
|
||||||
|
<ConformanceMode>true</ConformanceMode>
|
||||||
|
<LanguageStandard>stdcpp20</LanguageStandard>
|
||||||
|
</ClCompile>
|
||||||
|
<Link>
|
||||||
|
<SubSystem>Console</SubSystem>
|
||||||
|
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||||
|
</Link>
|
||||||
|
</ItemDefinitionGroup>
|
||||||
|
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||||
|
<ImportGroup Label="ExtensionTargets">
|
||||||
|
</ImportGroup>
|
||||||
|
</Project>
|
||||||
51
PCCcompiler/PCCcompiler.vcxproj.filters
Normal file
51
PCCcompiler/PCCcompiler.vcxproj.filters
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||||
|
<ItemGroup>
|
||||||
|
<Filter Include="Pliki źródłowe">
|
||||||
|
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
||||||
|
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
||||||
|
</Filter>
|
||||||
|
<Filter Include="Pliki nagłówkowe">
|
||||||
|
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
||||||
|
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
|
||||||
|
</Filter>
|
||||||
|
<Filter Include="Pliki zasobów">
|
||||||
|
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
|
||||||
|
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
|
||||||
|
</Filter>
|
||||||
|
</ItemGroup>
|
||||||
|
<ItemGroup>
|
||||||
|
<ClCompile Include="main.cpp">
|
||||||
|
<Filter>Pliki źródłowe</Filter>
|
||||||
|
</ClCompile>
|
||||||
|
<ClCompile Include="utils.cpp">
|
||||||
|
<Filter>Pliki źródłowe</Filter>
|
||||||
|
</ClCompile>
|
||||||
|
<ClCompile Include="parser.cpp">
|
||||||
|
<Filter>Pliki źródłowe</Filter>
|
||||||
|
</ClCompile>
|
||||||
|
<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">
|
||||||
|
<Filter>Pliki nagłówkowe</Filter>
|
||||||
|
</ClInclude>
|
||||||
|
<ClInclude Include="parser.h">
|
||||||
|
<Filter>Pliki nagłówkowe</Filter>
|
||||||
|
</ClInclude>
|
||||||
|
<ClInclude Include="codegen.h">
|
||||||
|
<Filter>Pliki nagłówkowe</Filter>
|
||||||
|
</ClInclude>
|
||||||
|
<ClInclude Include="compiler_types.h">
|
||||||
|
<Filter>Pliki nagłówkowe</Filter>
|
||||||
|
</ClInclude>
|
||||||
|
<ClInclude Include="preprocessor.h">
|
||||||
|
<Filter>Pliki nagłówkowe</Filter>
|
||||||
|
</ClInclude>
|
||||||
|
</ItemGroup>
|
||||||
|
</Project>
|
||||||
264
PCCcompiler/codegen.cpp
Normal file
264
PCCcompiler/codegen.cpp
Normal file
@@ -0,0 +1,264 @@
|
|||||||
|
#include "codegen.h"
|
||||||
|
#include <iostream>
|
||||||
|
#include <sstream>
|
||||||
|
#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 result;
|
||||||
|
result += "global main\n";
|
||||||
|
result += "extern printf\n";
|
||||||
|
result += "extern getchar\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
|
||||||
|
|
||||||
|
// --- WYPISYWANIE STRINGÓW ---
|
||||||
|
for (const auto& pair : state.stringLiterals) {
|
||||||
|
// 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";
|
||||||
|
|
||||||
|
for (const auto& pair : state.functions) {
|
||||||
|
const Function& func = pair.second;
|
||||||
|
result += func.name + ":\n";
|
||||||
|
|
||||||
|
result += " push rbp\n";
|
||||||
|
result += " mov rbp, rsp\n";
|
||||||
|
result += " sub rsp, 256\n";
|
||||||
|
|
||||||
|
std::map<std::string, int> stackMap;
|
||||||
|
int currentStack = 8;
|
||||||
|
|
||||||
|
// 1. ARGUMENTY
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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);
|
||||||
|
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;
|
||||||
|
if (instr.arg1 == "input") {
|
||||||
|
result += " call getchar\n"; // Czeka na enter
|
||||||
|
break; // Wychodzimy, ¿eby nie robiæ standardowego call
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (func.returnType == "void") {
|
||||||
|
result += " leave\n ret\n";
|
||||||
|
}
|
||||||
|
result += "\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
11
PCCcompiler/codegen.h
Normal file
11
PCCcompiler/codegen.h
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
#ifndef CODEGEN_H
|
||||||
|
#define CODEGEN_H
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include "compiler_types.h"
|
||||||
|
|
||||||
|
// G³ówna funkcja generuj¹ca kod ASM na podstawie stanu kompilatora
|
||||||
|
std::string generateAssembly(const CompilerState& state);
|
||||||
|
|
||||||
|
#endif // CODEGEN_H
|
||||||
|
|
||||||
59
PCCcompiler/compiler_types.h
Normal file
59
PCCcompiler/compiler_types.h
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
#ifndef COMPILER_TYPES_H
|
||||||
|
#define COMPILER_TYPES_H
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
#include <map>
|
||||||
|
#include <stack>
|
||||||
|
|
||||||
|
// Typy operacji, które nasz kompilator rozumie
|
||||||
|
enum class OpType {
|
||||||
|
ASSIGN, // a = 5
|
||||||
|
ADD, // a = b + c
|
||||||
|
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
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pojedynczy rozkaz kompilatora (Intermediate Representation)
|
||||||
|
struct Instruction {
|
||||||
|
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 {
|
||||||
|
// Mapa wszystkich funkcji (klucz to nazwa)
|
||||||
|
std::map<std::string, Function> functions;
|
||||||
|
|
||||||
|
// Zmienne globalne (tylko nazwa -> wartoœæ pocz¹tkowa)
|
||||||
|
std::map<std::string, int> globals;
|
||||||
|
|
||||||
|
// Stan parsera
|
||||||
|
Function* currentFunction = nullptr; // WskaŸnik na aktualnie parsuj¹c¹ siê funkcjê
|
||||||
|
int labelCounter = 0; // Do generowania unikalnych nazw etykiet (L1, L2...)
|
||||||
|
std::stack<std::string> loopStack; // Do break/continue (przysz³oœciowo)
|
||||||
|
|
||||||
|
std::stack<std::string> blockStack;
|
||||||
|
|
||||||
|
std::map<std::string, std::string> stringLiterals;
|
||||||
|
int stringCounter = 0; // Licznik do generowania nazw str_1, str_2...
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
||||||
163
PCCcompiler/main.cpp
Normal file
163
PCCcompiler/main.cpp
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
#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 = "v0.0.5-beta";
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... wczytywanie pliku (to co miałeś) ...
|
||||||
|
std::string src((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||||
|
in.close();
|
||||||
|
|
||||||
|
// --- 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";
|
||||||
|
// 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");
|
||||||
|
|
||||||
|
// 1. Ustal bazową nazwę (bez rozszerzenia)
|
||||||
|
std::string baseName;
|
||||||
|
if (outputName.empty()) {
|
||||||
|
// 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 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Teraz budujemy ścieżki - czysto i ładnie
|
||||||
|
std::string asmPath = "output\\" + baseName + ".asm";
|
||||||
|
std::string objPath = "output\\" + baseName + ".obj";
|
||||||
|
std::string exePath = "output\\" + baseName + ".exe";
|
||||||
|
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
237
PCCcompiler/parser.cpp
Normal file
237
PCCcompiler/parser.cpp
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
#include "parser.h"
|
||||||
|
#include "utils.h"
|
||||||
|
#include <iostream>
|
||||||
|
#include <sstream>
|
||||||
|
#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) {
|
||||||
|
std::istringstream iss(src);
|
||||||
|
std::string line;
|
||||||
|
|
||||||
|
while (std::getline(iss, line)) {
|
||||||
|
line = trim(line);
|
||||||
|
if (line.empty() || line.substr(0, 2) == "//" || line[0] == '#') continue;
|
||||||
|
|
||||||
|
// --- 1. DEFINICJA FUNKCJI ---
|
||||||
|
// Warunki: zaczyna się od typu, ma '(', ma '{' i NIE ma '=' (żeby nie mylić ze zmienną)
|
||||||
|
bool startsWithType = (line.rfind("int ", 0) == 0 || line.rfind("void ", 0) == 0 || line.rfind("bool ", 0) == 0);
|
||||||
|
|
||||||
|
if (startsWithType && line.find("(") != std::string::npos && line.find("{") != std::string::npos && line.find("=") == std::string::npos) {
|
||||||
|
|
||||||
|
size_t openParen = line.find('(');
|
||||||
|
std::string typeRaw = line.substr(0, line.find(' '));
|
||||||
|
std::string nameRaw = line.substr(typeRaw.length(), openParen - typeRaw.length());
|
||||||
|
std::string funcName = trim(nameRaw);
|
||||||
|
|
||||||
|
Function newFunc;
|
||||||
|
newFunc.name = funcName;
|
||||||
|
newFunc.returnType = typeRaw;
|
||||||
|
newFunc.args = parseArgs(line);
|
||||||
|
|
||||||
|
state.functions[funcName] = newFunc;
|
||||||
|
state.currentFunction = &state.functions[funcName];
|
||||||
|
|
||||||
|
std::cout << "[PARSER] New Function: " << funcName << "\n";
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 2. ZAMYKANIE BLOKU '}' ---
|
||||||
|
if (line == "}") {
|
||||||
|
// Najpierw sprawdzamy, czy zamykamy IF-a (czy jest coś na stosie bloków)
|
||||||
|
if (!state.blockStack.empty()) {
|
||||||
|
std::string label = state.blockStack.top();
|
||||||
|
state.blockStack.pop();
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- JESTEŚMY W ŚRODKU FUNKCJI ---
|
||||||
|
if (state.currentFunction) {
|
||||||
|
Function& f = *state.currentFunction;
|
||||||
|
|
||||||
|
// 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, "", "" });
|
||||||
|
std::cout << " [PARSER] Return: " << val << "\n";
|
||||||
|
}
|
||||||
|
// B. PRINT
|
||||||
|
else if (line.substr(0, 5) == "print") {
|
||||||
|
size_t start = line.find('(') + 1;
|
||||||
|
size_t end = line.find(')');
|
||||||
|
if (start != std::string::npos && end != std::string::npos) {
|
||||||
|
std::string arg = trim(line.substr(start, end - start));
|
||||||
|
|
||||||
|
// Czy to bezpośredni napis? np. print("Hello")
|
||||||
|
if (arg.size() >= 2 && arg.front() == '"' && arg.back() == '"') {
|
||||||
|
std::string content = arg.substr(1, arg.size() - 2);
|
||||||
|
|
||||||
|
// Rejestrujemy
|
||||||
|
std::string label;
|
||||||
|
if (state.stringLiterals.count(content)) {
|
||||||
|
label = state.stringLiterals[content];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
label = "str_" + std::to_string(state.stringCounter++);
|
||||||
|
state.stringLiterals[content] = label;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dajemy znać generatorowi, że to typ STRING
|
||||||
|
f.instructions.push_back({ OpType::PRINT, label, "STRING", "" });
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// Zwykła zmienna (int lub string - generator musi zgadnąć lub my musimy wiedzieć)
|
||||||
|
// Na razie załóżmy, że jeśli zmienna ma w nazwie "msg" lub "txt", to string
|
||||||
|
// (To hack, w przyszłości dodamy tabelę typów zmiennych)
|
||||||
|
f.instructions.push_back({ OpType::PRINT, arg, "VAR", "" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// C. IF STATEMENT
|
||||||
|
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) {}
|
||||||
7
PCCcompiler/parser.h
Normal file
7
PCCcompiler/parser.h
Normal file
@@ -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
|
||||||
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
|
||||||
8
PCCcompiler/utils.cpp
Normal file
8
PCCcompiler/utils.cpp
Normal file
@@ -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);
|
||||||
|
}
|
||||||
6
PCCcompiler/utils.h
Normal file
6
PCCcompiler/utils.h
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
#ifndef UTILS_H
|
||||||
|
#define UTILS_H
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
std::string trim(const std::string& str);
|
||||||
|
#endif
|
||||||
27
README.md
27
README.md
@@ -1,2 +1,27 @@
|
|||||||
# 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"`.
|
||||||
|
- **Control Flow**: `if` statements support.
|
||||||
|
- **Functions**: Define and call `void` functions.
|
||||||
|
- **Native Compilation**: Compiles directly to x64 machine code.
|
||||||
|
|
||||||
|
## 🛠️ 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