├── .gitattributes
├── .github
└── workflows
│ └── build.yml
├── .gitignore
├── CMakeLists.txt
├── LICENSE
├── README.md
├── gui
├── CppCompilerTmp.txt
├── code_editor.py
├── colors.py
├── main.py
├── out.txt
├── overlay.py
├── symbols.txt
└── syntax.py
├── images
└── ide.png
├── include
└── headers.h
├── out.txt
├── src
├── grammar
│ ├── lexer.l
│ └── parser.y
├── helpers
│ ├── CodeGenerationHelper.h
│ └── ScopeHelper.h
├── main.cpp
├── nodes
│ ├── Node.h
│ ├── conditions
│ │ ├── CaseNode.h
│ │ ├── IfElseCondNode.h
│ │ └── SwitchCondNode.h
│ ├── expressions
│ │ ├── AssignOpNode.h
│ │ ├── BinaryOpNode.h
│ │ ├── IdentifierNode.h
│ │ ├── LiteralNode.h
│ │ └── UnaryOpNode.h
│ ├── functions
│ │ ├── FunctionCallNode.h
│ │ ├── FunctionDeclarationNode.h
│ │ └── ReturnNode.h
│ ├── loops
│ │ ├── BreakNode.h
│ │ ├── ContinueNode.h
│ │ ├── DoWhileLoopNode.h
│ │ ├── ForLoopNode.h
│ │ └── WhileLoopNode.h
│ └── statements
│ │ ├── StmtBlockNode.h
│ │ └── VariableDeclarationNode.h
├── symbolTable
│ ├── SymbolTable.cpp
│ └── SymbolTable.h
└── utils
│ ├── enums.h
│ └── utils.h
└── tests
├── test.txt
├── test2.txt
├── test3.txt
├── test4.txt
├── test5(errors).txt
└── test6(bonus).txt
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | name: Build
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | tags:
7 | - '*'
8 |
9 | workflow_dispatch:
10 |
11 | env:
12 | FORCE_COLOR : 'true' # Force colors in console output
13 |
14 | jobs:
15 | Ubuntu:
16 | name: Ubuntu - GCC ${{ matrix.gcc_version }}
17 | runs-on: ubuntu-22.04
18 | env:
19 | CC : gcc-${{ matrix.gcc_version }}
20 | CXX: g++-${{ matrix.gcc_version }}
21 | TERM: 'xterm-256color'
22 |
23 | strategy:
24 | fail-fast: false
25 | matrix:
26 | gcc_version: [9, 10, 11]
27 |
28 | steps:
29 | - name: Checkout
30 | uses: actions/checkout@v3
31 |
32 | - name: Install Bison/Flex
33 | run: |
34 | sudo apt update
35 | sudo apt install bison flex -y
36 |
37 | - name: Build
38 | run: |
39 | mkdir cmake-build
40 | cd ./cmake-build
41 | cmake .. -DCMAKE_BUILD_TYPE=Release -DVERBOSE=OFF
42 | cmake --build . --config Release --clean-first
43 |
44 | - name: Upload Binary
45 | uses: actions/upload-artifact@v3
46 | with:
47 | name: C++ Compiler Ubuntu - GCC v${{ matrix.gcc_version }}
48 | path: ./cmake-build/CppCompiler
49 |
50 | - name: Set up Python 3.10
51 | uses: actions/setup-python@v3
52 | with:
53 | python-version: "3.10"
54 |
55 | - name: Install Python dependencies
56 | run: |
57 | sudo apt install libgl1-mesa-dev libicu-dev qtbase5-dev -y
58 | sudo pip install pyinstaller PyQt5 sip
59 |
60 | - name: Build GUI
61 | run: pyinstaller --clean --noupx --name CppCompiler_GUI --onefile --add-binary ./cmake-build/CppCompiler:. ./gui/main.py
62 |
63 | - name: Upload GUI Binary
64 | uses: actions/upload-artifact@v3
65 | with:
66 | name: C++ Compiler GUI Ubuntu - GCC v${{ matrix.gcc_version }}
67 | path: ./dist/CppCompiler_GUI
68 |
69 | - name: Rename Files
70 | run: |
71 | mv ./cmake-build/CppCompiler CppCompiler_linux_gcc_${{ matrix.gcc_version }}
72 | mv ./dist/CppCompiler_GUI CppCompiler_GUI_linux_gcc_${{ matrix.gcc_version }}
73 |
74 |
75 | - name: List Files
76 | if: always()
77 | run: ls -lRh
78 |
79 | - name: Release Files
80 | if: startsWith(github.ref, 'refs/tags/')
81 | uses: softprops/action-gh-release@v1
82 | with:
83 | name: "C++ Compiler v${{ github.event.release.tag_name }}"
84 | files: ./CppCompiler*
85 | env:
86 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
87 |
88 | ########################################################################################
89 |
90 | Windows:
91 | name: Windows - ${{ matrix.name }}
92 | runs-on: ${{ matrix.os }}
93 | strategy:
94 | fail-fast: false
95 | matrix:
96 | include:
97 | - cmake_generator: CodeBlocks - MinGW Makefiles
98 | cmake_platform_args: " "
99 | name: Mingw-w64 GCC 8
100 | output_name: mingw64_gcc_8
101 | os: windows-latest
102 |
103 | - cmake_generator: Visual Studio 16 2019
104 | cmake_platform_args: -A x64
105 | name: Visual Studio 2019
106 | output_name: vs2019
107 | os: windows-2019
108 |
109 | - cmake_generator: Visual Studio 17 2022
110 | cmake_platform_args: -A x64
111 | name: Visual Studio 2022
112 | output_name: vs2022
113 | os: windows-2022
114 |
115 | steps:
116 | - name: Checkout
117 | uses: actions/checkout@v3
118 |
119 | - name: Install Bison/Flex
120 | run: choco install winflexbison3
121 |
122 | - name: Build
123 | run: |
124 | mkdir cmake-build
125 | cd ./cmake-build
126 | cmake .. -DCMAKE_BUILD_TYPE=Release -DVERBOSE=OFF -G "${{ matrix.cmake_generator }}" ${{ matrix.cmake_platform_args }}
127 | cmake --build . --config Release --clean-first
128 |
129 | - name: Upload Binary
130 | uses: actions/upload-artifact@v3
131 | with:
132 | name: C++ Compiler Windows x64 - ${{ matrix.name }}
133 | path: |
134 | # Path varies from Visual Studio to MinGW
135 | ./cmake-build/CppCompiler.exe
136 | ./cmake-build/*/CppCompiler.exe
137 |
138 | - name: Rename Files
139 | shell: bash
140 | run: mv ./cmake-build/CppCompiler.exe ./CppCompiler.exe || mv ./cmake-build/*/CppCompiler.exe ./CppCompiler.exe
141 |
142 | - name: Set up Python 3.10
143 | uses: actions/setup-python@v3
144 | with:
145 | python-version: "3.10"
146 |
147 | - name: Install Python dependencies
148 | run: pip install pyinstaller PyQt5 sip
149 |
150 | - name: Build GUI
151 | run: pyinstaller --clean --noupx --name CppCompiler_GUI --onefile --add-binary="CppCompiler.exe;." ./gui/main.py
152 |
153 | - name: Upload GUI Binary
154 | uses: actions/upload-artifact@v3
155 | with:
156 | name: C++ Compiler GUI Windows x64 - ${{ matrix.name }}
157 | path: ./dist/CppCompiler_GUI.exe
158 |
159 | - name: Rename Files
160 | shell: bash
161 | run: |
162 | mv CppCompiler.exe CppCompiler_win64_${{ matrix.output_name }}.exe
163 | mv ./dist/CppCompiler_GUI.exe CppCompiler_GUI_win64_${{ matrix.output_name }}.exe
164 |
165 | - name: List Files
166 | if: always()
167 | shell: bash
168 | run: ls -lRh
169 |
170 | - name: Release Files
171 | if: startsWith(github.ref, 'refs/tags/')
172 | uses: softprops/action-gh-release@v1
173 | with:
174 | name: "C++ Compiler v${{ github.event.release.tag_name }}"
175 | files: ./CppCompiler*.exe
176 | env:
177 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
178 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # VS Code files
2 | .vscode/*
3 | !.vscode/settings.json
4 | !.vscode/tasks.json
5 | !.vscode/launch.json
6 | !.vscode/extensions.json
7 | *.code-workspace
8 |
9 | # Local History for Visual Studio Code
10 | .history/
11 |
12 | # CLion
13 | .idea/*
14 | cmake-build-debug/*
15 | cmake-build-release/*
16 | build/*
17 |
18 | # MacOS files
19 | .DS_Store
20 |
21 | # Compiled Object files
22 | *.slo
23 | *.lo
24 | *.o
25 | *.obj
26 |
27 | # Precompiled Headers
28 | *.gch
29 | *.pch
30 |
31 | # Compiled Dynamic libraries
32 | *.so
33 | *.dylib
34 | *.dll
35 |
36 | # Fortran module files
37 | *.mod
38 | *.smod
39 |
40 | # Compiled Static libraries
41 | *.lai
42 | *.la
43 | *.a
44 | *.lib
45 |
46 | # Executables
47 | *.exe
48 | *.out
49 | *.appears
50 |
51 |
52 |
53 | # Cmake
54 | CMakeLists.txt.user
55 | CMakeCache.txt
56 | CMakeFiles
57 | CMakeScripts
58 | Testing
59 | Makefile
60 | cmake_install.cmake
61 | install_manifest.txt
62 | compile_commands.json
63 | CTestTestfile.cmake
64 | _deps
65 |
66 |
67 | ## Ignore Visual Studio temporary files, build results, and
68 | ## files generated by popular Visual Studio add-ons.
69 | ##
70 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
71 |
72 | # User-specific files
73 | *.rsuser
74 | *.suo
75 | *.user
76 | *.userosscache
77 | *.sln.docstates
78 |
79 | # User-specific files (MonoDevelop/Xamarin Studio)
80 | *.userprefs
81 |
82 | # Mono auto generated files
83 | mono_crash.*
84 |
85 | # Build results
86 | [Dd]ebug/
87 | [Dd]ebugPublic/
88 | [Rr]elease/
89 | [Rr]eleases/
90 | x64/
91 | x86/
92 | [Ww][Ii][Nn]32/
93 | [Aa][Rr][Mm]/
94 | [Aa][Rr][Mm]64/
95 | bld/
96 | [Bb]in/
97 | [Oo]bj/
98 | [Ll]og/
99 | [Ll]ogs/
100 |
101 | # Visual Studio 2015/2017 cache/options directory
102 | .vs/
103 |
104 | # Visual Studio 2017 auto generated files
105 | Generated\ Files/
106 |
107 | # MSTest test Results
108 | [Tt]est[Rr]esult*/
109 | [Bb]uild[Ll]og.*
110 |
111 | # NUnit
112 | *.VisualState.xml
113 | TestResult.xml
114 | nunit-*.xml
115 |
116 | # Build Results of an ATL Project
117 | [Dd]ebugPS/
118 | [Rr]eleasePS/
119 | dlldata.c
120 |
121 | # Benchmark Results
122 | BenchmarkDotNet.Artifacts/
123 |
124 | # .NET Core
125 | project.lock.json
126 | project.fragment.lock.json
127 | artifacts/
128 |
129 | # ASP.NET Scaffolding
130 | ScaffoldingReadMe.txt
131 |
132 | # StyleCop
133 | StyleCopReport.xml
134 |
135 | # Files built by Visual Studio
136 | *_i.c
137 | *_p.c
138 | *_h.h
139 | *.ilk
140 | *.meta
141 | *.obj
142 | *.iobj
143 | *.pch
144 | *.pdb
145 | *.ipdb
146 | *.pgc
147 | *.pgd
148 | *.rsp
149 | *.sbr
150 | *.tlb
151 | *.tli
152 | *.tlh
153 | *.tmp
154 | *.tmp_proj
155 | *_wpftmp.csproj
156 | *.log
157 | *.tlog
158 | *.vspscc
159 | *.vssscc
160 | .builds
161 | *.pidb
162 | *.svclog
163 | *.scc
164 |
165 | # Chutzpah Test files
166 | _Chutzpah*
167 |
168 | # Visual C++ cache files
169 | ipch/
170 | *.aps
171 | *.ncb
172 | *.opendb
173 | *.opensdf
174 | *.sdf
175 | *.cachefile
176 | *.VC.db
177 | *.VC.VC.opendb
178 |
179 | # Visual Studio profiler
180 | *.psess
181 | *.vsp
182 | *.vspx
183 | *.sap
184 |
185 | # Visual Studio Trace Files
186 | *.e2e
187 |
188 | # TFS 2012 Local Workspace
189 | $tf/
190 |
191 | # Guidance Automation Toolkit
192 | *.gpState
193 |
194 | # ReSharper is a .NET coding add-in
195 | _ReSharper*/
196 | *.[Rr]e[Ss]harper
197 | *.DotSettings.user
198 |
199 | # TeamCity is a build add-in
200 | _TeamCity*
201 |
202 | # DotCover is a Code Coverage Tool
203 | *.dotCover
204 |
205 | # AxoCover is a Code Coverage Tool
206 | .axoCover/*
207 | !.axoCover/settings.json
208 |
209 | # Coverlet is a free, cross platform Code Coverage Tool
210 | coverage*.json
211 | coverage*.xml
212 | coverage*.info
213 |
214 | # Visual Studio code coverage results
215 | *.coverage
216 | *.coveragexml
217 |
218 | # NCrunch
219 | _NCrunch_*
220 | .*crunch*.local.xml
221 | nCrunchTemp_*
222 |
223 | # MightyMoose
224 | *.mm.*
225 | AutoTest.Net/
226 |
227 | # Web workbench (sass)
228 | .sass-cache/
229 |
230 | # Installshield output folder
231 | [Ee]xpress/
232 |
233 | # DocProject is a documentation generator add-in
234 | DocProject/buildhelp/
235 | DocProject/Help/*.HxT
236 | DocProject/Help/*.HxC
237 | DocProject/Help/*.hhc
238 | DocProject/Help/*.hhk
239 | DocProject/Help/*.hhp
240 | DocProject/Help/Html2
241 | DocProject/Help/html
242 |
243 | # Click-Once directory
244 | publish/
245 |
246 | # Publish Web Output
247 | *.[Pp]ublish.xml
248 | *.azurePubxml
249 | # Note: Comment the next line if you want to checkin your web deploy settings,
250 | # but database connection strings (with potential passwords) will be unencrypted
251 | *.pubxml
252 | *.publishproj
253 |
254 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
255 | # checkin your Azure Web App publish settings, but sensitive information contained
256 | # in these scripts will be unencrypted
257 | PublishScripts/
258 |
259 | # NuGet Packages
260 | *.nupkg
261 | # NuGet Symbol Packages
262 | *.snupkg
263 | # The packages folder can be ignored because of Package Restore
264 | **/[Pp]ackages/*
265 | # except build/, which is used as an MSBuild target.
266 | !**/[Pp]ackages/build/
267 | # Uncomment if necessary however generally it will be regenerated when needed
268 | #!**/[Pp]ackages/repositories.config
269 | # NuGet v3's project.json files produces more ignorable files
270 | *.nuget.props
271 | *.nuget.targets
272 |
273 | # Microsoft Azure Build Output
274 | csx/
275 | *.build.csdef
276 |
277 | # Microsoft Azure Emulator
278 | ecf/
279 | rcf/
280 |
281 | # Windows Store app package directories and files
282 | AppPackages/
283 | BundleArtifacts/
284 | Package.StoreAssociation.xml
285 | _pkginfo.txt
286 | *.appx
287 | *.appxbundle
288 | *.appxupload
289 |
290 | # Visual Studio cache files
291 | # files ending in .cache can be ignored
292 | *.[Cc]ache
293 | # but keep track of directories ending in .cache
294 | !?*.[Cc]ache/
295 |
296 | # Others
297 | ClientBin/
298 | ~$*
299 | *~
300 | *.dbmdl
301 | *.dbproj.schemaview
302 | *.jfm
303 | *.pfx
304 | *.publishsettings
305 | orleans.codegen.cs
306 |
307 | # Including strong name files can present a security risk
308 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
309 | #*.snk
310 |
311 | # Since there are multiple workflows, uncomment next line to ignore bower_components
312 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
313 | #bower_components/
314 |
315 | # RIA/Silverlight projects
316 | Generated_Code/
317 |
318 | # Backup & report files from converting an old project file
319 | # to a newer Visual Studio version. Backup files are not needed,
320 | # because we have git ;-)
321 | _UpgradeReport_Files/
322 | Backup*/
323 | UpgradeLog*.XML
324 | UpgradeLog*.htm
325 | ServiceFabricBackup/
326 | *.rptproj.bak
327 |
328 | # SQL Server files
329 | *.mdf
330 | *.ldf
331 | *.ndf
332 |
333 | # Business Intelligence projects
334 | *.rdl.data
335 | *.bim.layout
336 | *.bim_*.settings
337 | *.rptproj.rsuser
338 | *- [Bb]ackup.rdl
339 | *- [Bb]ackup ([0-9]).rdl
340 | *- [Bb]ackup ([0-9][0-9]).rdl
341 |
342 | # Microsoft Fakes
343 | FakesAssemblies/
344 |
345 | # GhostDoc plugin setting file
346 | *.GhostDoc.xml
347 |
348 | # Node.js Tools for Visual Studio
349 | .ntvs_analysis.dat
350 | node_modules/
351 |
352 | # Visual Studio 6 build log
353 | *.plg
354 |
355 | # Visual Studio 6 workspace options file
356 | *.opt
357 |
358 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
359 | *.vbw
360 |
361 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
362 | *.vbp
363 |
364 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
365 | *.dsw
366 | *.dsp
367 |
368 | # Visual Studio 6 technical files
369 | *.ncb
370 | *.aps
371 |
372 | # Visual Studio LightSwitch build output
373 | **/*.HTMLClient/GeneratedArtifacts
374 | **/*.DesktopClient/GeneratedArtifacts
375 | **/*.DesktopClient/ModelManifest.xml
376 | **/*.Server/GeneratedArtifacts
377 | **/*.Server/ModelManifest.xml
378 | _Pvt_Extensions
379 |
380 | # Paket dependency manager
381 | .paket/paket.exe
382 | paket-files/
383 |
384 | # FAKE - F# Make
385 | .fake/
386 |
387 | # CodeRush personal settings
388 | .cr/personal
389 |
390 | # Python Tools for Visual Studio (PTVS)
391 | __pycache__/
392 | *.pyc
393 |
394 | # Cake - Uncomment if you are using it
395 | # tools/**
396 | # !tools/packages.config
397 |
398 | # Tabs Studio
399 | *.tss
400 |
401 | # Telerik's JustMock configuration file
402 | *.jmconfig
403 |
404 | # BizTalk build output
405 | *.btp.cs
406 | *.btm.cs
407 | *.odx.cs
408 | *.xsd.cs
409 |
410 | # OpenCover UI analysis results
411 | OpenCover/
412 |
413 | # Azure Stream Analytics local run output
414 | ASALocalRun/
415 |
416 | # MSBuild Binary and Structured Log
417 | *.binlog
418 |
419 | # NVidia Nsight GPU debugger configuration file
420 | *.nvuser
421 |
422 | # MFractors (Xamarin productivity tool) working folder
423 | .mfractor/
424 |
425 | # Local History for Visual Studio
426 | .localhistory/
427 |
428 | # Visual Studio History (VSHistory) files
429 | .vshistory/
430 |
431 | # BeatPulse healthcheck temp database
432 | healthchecksdb
433 |
434 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
435 | MigrationBackup/
436 |
437 | # Ionide (cross platform F# VS Code tools) working folder
438 | .ionide/
439 |
440 | # Fody - auto-generated XML schema
441 | FodyWeavers.xsd
442 |
443 | # Windows Installer files from build outputs
444 | *.cab
445 | *.msi
446 | *.msix
447 | *.msm
448 | *.msp
449 |
450 | # JetBrains Rider
451 | *.sln.iml
452 |
--------------------------------------------------------------------------------
/CMakeLists.txt:
--------------------------------------------------------------------------------
1 | cmake_minimum_required(VERSION 3.10)
2 | set(PROJECT_NAME CppCompiler)
3 |
4 | project(${PROJECT_NAME})
5 | set(CMAKE_CXX_STANDARD 17)
6 |
7 | ######################################### Colored Output Config #########################################
8 |
9 | # set(CMAKE_COLOR_MAKEFILE ON)
10 |
11 | # if(NOT WIN32)
12 | # set(ENV{CLICOLOR_FORCE} "true")
13 | # endif()
14 |
15 | # if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
16 | # add_compile_options (-fdiagnostics-color=always)
17 | # elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang")
18 | # add_compile_options (-fcolor-diagnostics)
19 | # endif ()
20 |
21 | ########################################### Flex/Bison Config ###########################################
22 |
23 |
24 | option(VERBOSE "Add more message on searchig for flex/bison and others" ON)
25 |
26 | set(CMAKE_FIND_DEBUG_MODE ${VERBOSE})
27 | set(BISON_DEBUG ${VERBOSE})
28 | set(FLEX_DEBUG ${VERBOSE})
29 |
30 | message(STATUS "VERBOSE_MODE:" ${VERBOSE})
31 |
32 | find_package(BISON REQUIRED)
33 | find_package(FLEX REQUIRED)
34 |
35 | file(GLOB YACC_FILE src/grammar/parser.y)
36 | file(GLOB LEX_FILE src/grammar/lexer.l)
37 |
38 | set(GRAMMAR_BUILD_DIR ${CMAKE_CURRENT_BINARY_DIR}/src/grammar)
39 | file(MAKE_DIRECTORY ${GRAMMAR_BUILD_DIR})
40 |
41 | FLEX_TARGET(LEXER ${LEX_FILE} ${GRAMMAR_BUILD_DIR}/lexer.cpp COMPILE_FLAGS "--verbose")
42 |
43 | BISON_TARGET(PARSER ${YACC_FILE} ${GRAMMAR_BUILD_DIR}/parser.cpp COMPILE_FLAGS "--verbose")
44 |
45 | ADD_FLEX_BISON_DEPENDENCY(LEXER PARSER)
46 |
47 | #########################################################################################################
48 |
49 | file(GLOB_RECURSE CPP_FILES src/*.cpp)
50 | file(GLOB_RECURSE HEADER_FILES src/*.h include/*.h)
51 | set(SOURCE_FILES_LIST ${CPP_FILES} ${HEADER_FILES})
52 |
53 | # CMake List is semicolon separated string, for printing it is better to convert it to new line separated
54 | function(PRINT_NEW_LINE_LIST list)
55 | message(STATUS "${list}")
56 | if (ARGN)
57 | PRINT_NEW_LINE_LIST(${ARGN})
58 | else()
59 | message(STATUS "")
60 | endif()
61 | endfunction()
62 |
63 | message(STATUS "C++ Source files:")
64 | PRINT_NEW_LINE_LIST(${CPP_FILES})
65 |
66 | message(STATUS "C++ Header files:")
67 | PRINT_NEW_LINE_LIST(${HEADER_FILES})
68 |
69 | message(STATUS "FLEX OUTPUT files:")
70 | PRINT_NEW_LINE_LIST(${FLEX_LEXER_OUTPUTS})
71 |
72 | message(STATUS "BISON OUTPUT files:")
73 | PRINT_NEW_LINE_LIST(${BISON_PARSER_OUTPUTS})
74 |
75 | add_executable(${PROJECT_NAME} ${SOURCE_FILES_LIST} ${FLEX_LEXER_OUTPUTS} ${BISON_PARSER_OUTPUTS})
76 |
77 | target_include_directories(${PROJECT_NAME}
78 | PRIVATE
79 | ${CMAKE_CURRENT_SOURCE_DIR}/include
80 | ${GRAMMAR_BUILD_DIR})
81 |
82 | ########################################### For Visual Studio ###########################################
83 |
84 | # On Visual Studio the value of of __cplusplus is very old and does not reflect the true version of the compiler
85 | # This switch ensures __cplusplus value is updated
86 | # See: https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/
87 | if(MSVC)
88 | target_compile_options(${PROJECT_NAME} PUBLIC "/Zc:__cplusplus")
89 | endif()
90 |
91 | # Generate Folder Hierarchy instead of adding all files in the same folder
92 | source_group(TREE ${CMAKE_CURRENT_SOURCE_DIR} FILES ${SOURCE_FILES_LIST} ${LEX_FILE} ${YACC_FILE})
93 |
94 | # Group Cmake predefined projects in CMakePredefinedTargets folder (as ZERO_CHECK , ALL_BUILD)
95 | set_property(GLOBAL PROPERTY USE_FOLDERS ON)
96 |
97 | # Set this project as startup project
98 | set_property(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} PROPERTY VS_STARTUP_PROJECT ${PROJECT_NAME})
99 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # C++ Compiler
2 | Simple C++ like compiler using Bison/Flex
3 |
4 | We use C++ 17, Bison >= 3.0 because we use it to generate C++ files and use C++ variants instead of `%union`
5 |
6 | # Features
7 | * C++ like syntax
8 | * Used modern C++ features
9 | * Support functions, if conditions, loops, etc.
10 | * Support multiple operators as `+`, `-`, `*`, `/`, `++`, `--`, `** (exp)`, `and`, `or`, `not`, `&&`, `||`, `!`, `==`, `!=`, `<`, `>`, `<=`, `>=`, `<<`, `>>`
11 | * Expressive Warnings, and Errors
12 | * Warning on not used variables, functions, etc.
13 | * Warning on not initialized variables.
14 | * Simple GUI Text Editor
15 |
16 | 
17 |
18 | # Download
19 | You can find precompiled binaries (CLI, GUI) for Linux and Windows in the [releases](https://github.com/3omar-mostafa/CppCompiler/releases/latest)
20 |
21 | # How To Build
22 | ## Dependencies
23 | * Cmake >= 3.0
24 | * C++ compiler
25 | * Bison >= 3.0
26 | * Flex
27 |
28 | ## Install Dependencies
29 | * Ubuntu:
30 | ```bash
31 | sudo apt-get update
32 | sudo apt-get install build-essential bison flex cmake gcc g++
33 | ```
34 |
35 | * Windows:
36 | * [CMake](https://cmake.org/download/)
37 | * C++ Compiler: You can use [Visual Studio](https://visualstudio.microsoft.com/downloads/) or [mingw-w64](http://sourceforge.net/projects/mingw-w64/files/Toolchains%20targetting%20Win32/Personal%20Builds/mingw-builds/installer/mingw-w64-install.exe/download)
38 | * You can get new version of bison [from here](https://github.com/lexxmark/winflexbison/releases/tag/latest), extract the zip, and add the directory to the `PATH` environment variable
39 | * if your are using [chocolatey package manager](https://chocolatey.org/install), install bison/flex using
40 | ```
41 | choco install winflexbison3
42 | ```
43 |
44 |
45 | ## Build
46 | * Ubuntu:
47 | ```bash
48 | mkdir build
49 | cd build
50 | cmake .. -DCMAKE_BUILD_TYPE=Release
51 | cmake --build . --config Release --clean-first
52 | ```
53 | You will find executable called `CppCompiler` inside `build` directory
54 |
55 | Generated C++ grammar files inside `build/src/grammar/` directory
56 |
57 | ------------------------------------------------------------------------------------
58 |
59 | * Windows:
60 | * Using Visual Studio:
61 | ```cmd
62 | mkdir build
63 | cd build
64 | cmake .. -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 17 2022" -A x64
65 | cmake --build . --config Release --clean-first
66 | ```
67 |
68 | Visual Studio it is the default generator for windows, (i.e you can remove `-G "Visual Studio 17 2022"` and cmake will choose the installed version) but you can select a specific version:
69 |
70 | - "Visual Studio 11 2012"
71 | - "Visual Studio 14 2015"
72 | - "Visual Studio 15 2017"
73 | - "Visual Studio 16 2019"
74 | - "Visual Studio 17 2022"
75 |
76 | You will find executable called `CppCompiler.exe` inside `build/Release/` directory
77 |
78 | Generated C++ grammar files inside `build/src/grammar/` directory
79 |
80 | * Using Mingw-w64:
81 | ```cmd
82 | mkdir build
83 | cd build
84 | cmake .. -DCMAKE_BUILD_TYPE=Release -G "Mingw-w64 GCC 8"
85 | cmake --build . --config Release --clean-first
86 | ```
87 |
88 | You will find executable called `CppCompiler.exe` inside `build` directory
89 |
90 | Generated C++ grammar files inside `build/src/grammar/` directory
91 |
92 | # Usage
93 | The program takes one argument of the file to compile
94 |
95 | If no arguments are given, the program reads from standard input, saves output to `out.txt` and saves symbol table to `symbols.txt`
96 |
97 | Example:
98 | * Ubuntu
99 | ```bash
100 | CppCompiler test.txt out.txt symbols.txt
101 | ```
102 | * Windows
103 | ```cmd
104 | CppCompiler.exe test.txt out.txt symbols.txt
105 | ```
106 |
107 |
--------------------------------------------------------------------------------
/gui/CppCompilerTmp.txt:
--------------------------------------------------------------------------------
1 | int x = 4 * 5 + 6 / 2;
2 | const char y = 'c';
3 |
4 | {
5 | if(5 > 3)
6 | {
7 | int x=4;
8 | }
9 | else
10 | {
11 | int z = 2 * x;
12 | }
13 |
14 | while (3 >= 1) {
15 | int r = (4*3 + 5) / 2;
16 | }
17 |
18 | do {
19 | x = x + 4;
20 | } while(y == 1);
21 |
22 | for(int i=0; i<3; i=i+1){
23 | if (i == 1){
24 | int x = 3 + 4;
25 | x = x * 4.3;
26 | break;
27 | }
28 | int h = 3 && 2;
29 | }
30 | const int f = 3;
31 | }
32 |
--------------------------------------------------------------------------------
/gui/code_editor.py:
--------------------------------------------------------------------------------
1 | from PyQt5.QtWidgets import QWidget
2 | from PyQt5.QtGui import *
3 | from PyQt5.QtWidgets import *
4 | from PyQt5.QtCore import *
5 | from PyQt5.QtCore import QSize
6 |
7 | import syntax
8 | from colors import colors
9 |
10 | class LineNumberArea(QWidget):
11 |
12 | def __init__(self, editor):
13 | super(QWidget, self).__init__(editor)
14 | self.myeditor = editor
15 |
16 | def paintEvent(self, event):
17 | self.myeditor.lineNumberAreaPaintEvent(event)
18 |
19 |
20 | class CodeEditor(QPlainTextEdit):
21 |
22 |
23 | def __init__(self, parent=None):
24 | super(QPlainTextEdit, self).__init__(parent)
25 | self.lineNumberArea = LineNumberArea(self)
26 | self.blockCountChanged.connect(self.updateLineNumberAreaWidth)
27 | self.updateRequest.connect(self.updateLineNumberArea)
28 | self.cursorPositionChanged.connect(self.highlightCurrentLine)
29 | # self.setBackgroundVisible(True)
30 | self.setPalette(QPalette(colors["black"]))
31 | self.setStyleSheet("font-family: Consolas; font-size: 18px; color: #BDBDBD;")
32 | self.setTabStopWidth(40)
33 | self.updateLineNumberAreaWidth(0)
34 |
35 | def onTextChange(self):
36 | syntax.CPPHighlighter(self.document())
37 |
38 | def lineNumberAreaWidth(self):
39 | space = 10 + self.fontMetrics().width('9') * 3
40 | return space
41 |
42 |
43 | def updateLineNumberAreaWidth(self, _):
44 | self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)
45 |
46 |
47 | def updateLineNumberArea(self, rect, dy):
48 |
49 | if dy:
50 | self.lineNumberArea.scroll(0, dy)
51 | else:
52 | self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(),
53 | rect.height())
54 |
55 | if rect.contains(self.viewport().rect()):
56 | self.updateLineNumberAreaWidth(0)
57 |
58 |
59 | def resizeEvent(self, event):
60 | super(QPlainTextEdit, self).resizeEvent(event)
61 |
62 | cr = self.contentsRect()
63 | self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(),
64 | self.lineNumberAreaWidth(), cr.height()))
65 |
66 |
67 | def lineNumberAreaPaintEvent(self, event):
68 | mypainter = QPainter(self.lineNumberArea)
69 |
70 | mypainter.fillRect(event.rect(), colors["black"])
71 |
72 | block = self.firstVisibleBlock()
73 | blockNumber = block.blockNumber()
74 | top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
75 | bottom = top + self.blockBoundingRect(block).height()
76 |
77 | # Just to make sure I use the right font
78 | height = self.fontMetrics().height()
79 | while block.isValid() and (top <= event.rect().bottom()):
80 | if block.isVisible() and (bottom >= event.rect().top()):
81 | number = str(blockNumber + 1)
82 | mypainter.setPen(colors["white"])
83 | mypainter.drawText(0, int(top), int(self.lineNumberArea.width()), int(height),
84 | Qt.AlignHCenter, number)
85 |
86 | block = block.next()
87 | top = bottom
88 | bottom = top + self.blockBoundingRect(block).height()
89 | blockNumber += 1
90 |
91 |
92 | def highlightCurrentLine(self):
93 |
94 | extraSelections = []
95 |
96 | if not self.isReadOnly():
97 | selection = QTextEdit.ExtraSelection()
98 |
99 | selection.format.setBackground(colors['dark-purple'])
100 | selection.format.setProperty(QTextFormat.FullWidthSelection, True)
101 | selection.cursor = self.textCursor()
102 | selection.cursor.clearSelection()
103 | extraSelections.append(selection)
104 | self.setExtraSelections(extraSelections)
--------------------------------------------------------------------------------
/gui/colors.py:
--------------------------------------------------------------------------------
1 | from PyQt5.QtGui import QColor
2 |
3 | # grey #121212
4 | # black #292929
5 | # purple #BB86FC
6 | # dark-purple #1F1B24
7 | # teal #03DAC5
8 | # blue #3700b3
9 |
10 |
11 | # Color palette for GUI
12 | colors = {
13 | 'purple': QColor(187, 134, 252),
14 | 'dark-purple': QColor(31, 27, 36),
15 | 'teal': QColor(3, 218, 197),
16 | 'blue': QColor(3, 169, 244),
17 | 'black': QColor(18,18,18),
18 | 'grey': QColor(41,41,41),
19 | 'white': QColor(120, 120, 120),
20 | 'symbols': QColor(96, 125, 139),
21 | 'comments': QColor(255, 158, 128),
22 | }
--------------------------------------------------------------------------------
/gui/main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import os
3 | import sys
4 | import subprocess
5 |
6 | from subprocess import Popen, PIPE, STDOUT
7 |
8 | from PyQt5 import QtWidgets, QtCore
9 | from PyQt5.QtWidgets import *
10 | from PyQt5.QtGui import *
11 | from PyQt5.QtCore import Qt, QTimer, QPoint
12 |
13 | import syntax
14 |
15 | from overlay import Overlay
16 | from code_editor import CodeEditor
17 | from colors import colors
18 |
19 | import os.path
20 |
21 |
22 | class CppCompiler(QWidget):
23 |
24 | TITLE = "CppCompiler"
25 | BACKGROUND_COLOR = colors["grey"]
26 |
27 | def __init__(self, args):
28 | super(QWidget, self).__init__()
29 |
30 | # Compiler path
31 | self.cpp_compiler_path = "CppCompiler.exe" if sys.platform == "win32" else "CppCompiler"
32 | self.cpp_compiler_path = os.path.join(os.path.dirname(__file__), self.cpp_compiler_path)
33 | if sys.platform != "win32":
34 | os.chmod(self.cpp_compiler_path, 0o777)
35 |
36 | self.cpp_quadruples_path = "out.txt"
37 | self.cpp_symbols_table_path = "symbols.txt"
38 | self.cpp_tmp_path = "CppCompilerTmp.txt"
39 | self.file_path = ""
40 |
41 | self.left = 60
42 | self.top = 30
43 | self.width = int(self.getWindowSize()[1])
44 | self.height = int(self.getWindowSize()[0])
45 |
46 | # Animation
47 | self.compilingTask = TaskThread()
48 | self.compilingTask.task_finished.connect(self.on_compilation_finished)
49 |
50 | self.init_gui()
51 |
52 | def init_gui(self):
53 | self.setup_window()
54 | self.setup_window_title()
55 | self.setup_window_exit_btn()
56 | self.setup_code_editor()
57 | self.setup_quadruples_view()
58 | self.setup_symbol_table_view()
59 | self.setup_logs_view()
60 | self.setup_switch_btn()
61 | self.setup_compile_btn()
62 | self.setup_select_file_btn()
63 | self.setup_loading_animation()
64 | self.show()
65 |
66 | def setup_window(self):
67 | self.setWindowTitle(CppCompiler.TITLE)
68 | self.setGeometry(int(self.left), int(self.top), int(self.width), int(self.height))
69 |
70 | # Set window background color
71 | self.setAutoFillBackground(True)
72 | p = self.palette()
73 | p.setColor(self.backgroundRole(), CppCompiler.BACKGROUND_COLOR)
74 | self.setPalette(p)
75 |
76 | self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
77 |
78 | def setup_loading_animation(self):
79 | self.overlay = Overlay(self)
80 | self.overlay.hide()
81 |
82 | def setup_window_title(self):
83 | self.title = QLabel(self)
84 | self.title.setText(CppCompiler.TITLE)
85 | self.title.setStyleSheet("font-size: 28px; padding-bottom: 6px; font-weight: bold; color: #ccc; font-family: Courier New;")
86 | self.title.setGeometry(QtCore.QRect(20, 20, int(self.width - 40), 55))
87 | self.title.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
88 |
89 | def setup_window_exit_btn(self):
90 | self.windowExitBtn = QPushButton('×', parent=self)
91 | self.windowExitBtn.move(int(self.width - 55), 28)
92 | self.windowExitBtn.setCursor(Qt.PointingHandCursor)
93 | self.windowExitBtn.setStyleSheet(
94 | "border-radius: 0px; font-family: Courier New; font-size: 48px; color: #ffffff; background: #00ffffff; text-decoration: none;")
95 |
96 | self.windowExitBtn.clicked.connect(app.quit)
97 |
98 | def setup_code_editor(self):
99 | font = self.getFont()
100 | self.input_code_editor = CodeEditor(self)
101 | self.input_code_editor.setFont(font)
102 | self.input_code_editor.setGeometry(QtCore.QRect(
103 | 20, 100, int(self.width / 2 - 10), int(self.height * 5.5 / 9)))
104 | self.input_code_editor.setGraphicsEffect(self.getShadow())
105 | self.input_code_editor.show()
106 |
107 | self.highlight = syntax.CPPHighlighter(self.input_code_editor.document())
108 |
109 | def setup_quadruples_view(self):
110 | font = self.getFont()
111 | self.quadruples_view = CodeEditor(self)
112 | self.quadruples_view.setFont(font)
113 | self.quadruples_view.setGeometry(QtCore.QRect(
114 | int(self.width / 2 + 40), 100, int(self.width / 2 - 59), int(self.height * 5.5 / 9)))
115 | self.quadruples_view.setGraphicsEffect(self.getShadow())
116 | self.quadruples_view.setReadOnly(True)
117 | self.quadruples_view.show()
118 |
119 | def setup_symbol_table_view(self):
120 | font = self.getFont()
121 | self.symbols_view = CodeEditor(self)
122 | self.symbols_view.setFont(font)
123 | self.symbols_view.setGeometry(QtCore.QRect(
124 | int(self.width / 2 + 40), 100, int(self.width / 2 - 59), int(self.height * 5.5 / 9)))
125 | self.symbols_view.setGraphicsEffect(self.getShadow())
126 | self.symbols_view.setReadOnly(True)
127 | self.symbols_view.hide()
128 |
129 | def setup_logs_view(self):
130 | font = self.getFont()
131 | self.logs_view = CodeEditor(self)
132 | self.logs_view.setFont(font)
133 | self.logs_view.setGeometry(QtCore.QRect(
134 | 20, int(self.height * 7 / 9 + 20), self.width - 37, 167))
135 | self.logs_view.setGraphicsEffect(self.getShadow())
136 | self.logs_view.setReadOnly(True)
137 | self.logs_view.show()
138 |
139 | def setup_switch_btn(self):
140 | self.select_symbol_table_btn = HoverButton(
141 | 'Symbols', color="#000000", BKColor="#e0e0e0", hoverBKColor="#c8e0e0e0", parent=self)
142 | self.select_symbol_table_btn.move(
143 | self.width - self.select_symbol_table_btn.width() - 57, self.height - 278)
144 | self.select_symbol_table_btn.setCursor(Qt.PointingHandCursor)
145 | self.select_symbol_table_btn.setStyleSheet(
146 | "border-radius: 0px; font-family: Courier New; color: #000000; font-size: 18px; background: #e0e0e0; padding: 8px 18px 8px 18px; text-decoration: none;")
147 |
148 | self.select_quadruples_btn = HoverButton(
149 | 'Quadruples', color="#ffffff", BKColor="#50ae55", hoverBKColor="#c850ae55", parent=self)
150 | self.select_quadruples_btn.move(self.width - self.select_symbol_table_btn.width(
151 | ) - self.select_quadruples_btn.width() - 126, self.height - 278)
152 | self.select_quadruples_btn.setCursor(Qt.PointingHandCursor)
153 | self.select_quadruples_btn.setStyleSheet(
154 | "border-radius: 0px; font-family: Courier New; color: #ffffff; font-size: 18px; background: #50ae55; padding: 8px 18px 8px 18px; text-decoration: none;")
155 |
156 | self.select_quadruples_btn.clicked.connect(self.select_quadruples)
157 | self.select_symbol_table_btn.clicked.connect(self.select_symbol_table)
158 |
159 | def setup_select_file_btn(self):
160 | self.select_file_btn = HoverButton('Select', parent=self)
161 | self.select_file_btn.move(
162 | self.width - self.select_file_btn.width() - self.compile_btn.width() - 1508, self.height - 278)
163 | self.select_file_btn.setCursor(Qt.PointingHandCursor)
164 | self.select_file_btn.setStyleSheet(
165 | "border-radius: 0px; font-family: Courier New; color: #ffffff; font-size: 18px; background: #3498db; padding: 8px 25px 8px 25px; text-decoration: none;")
166 |
167 | self.select_file_btn.clicked.connect(self.select_file)
168 |
169 | def setup_compile_btn(self):
170 | self.compile_btn = HoverButton('Compile', parent=self)
171 | self.compile_btn.move(
172 | (self.width - self.compile_btn.width() - 896), self.height - 278)
173 | self.compile_btn.setCursor(Qt.PointingHandCursor)
174 | self.compile_btn.setStyleSheet(
175 | "border-radius: 0px; font-family: Courier New; color: #ffffff; font-size: 18px; background: #3498db; padding: 8px 20px 8px 20px; text-decoration: none;")
176 |
177 | self.compile_btn.clicked.connect(self.on_compilation_started)
178 |
179 | def getWindowSize(self):
180 | size = QtWidgets.QDesktopWidget().screenGeometry(-1)
181 | return (size.height() * 0.9, size.width() * 0.9)
182 |
183 | def getFont(self):
184 | font = QFont()
185 | font.setFamily('Courier New')
186 | font.setFixedPitch(True)
187 | font.setPointSize(12)
188 |
189 | return font
190 |
191 | def getShadow(self):
192 | shadow = QGraphicsDropShadowEffect(self)
193 | shadow.setBlurRadius(2)
194 | shadow.setOffset(0, 0)
195 |
196 | return shadow
197 |
198 | def select_quadruples(self):
199 | self.quadruples_view.show()
200 | self.symbols_view.hide()
201 | self.switch_btns(self.select_quadruples_btn,
202 | self.select_symbol_table_btn)
203 |
204 | def select_symbol_table(self):
205 | self.symbols_view.show()
206 | self.quadruples_view.hide()
207 | self.switch_btns(self.select_symbol_table_btn,
208 | self.select_quadruples_btn)
209 |
210 | def switch_btns(self, active, inactive):
211 | active.color = "#ffffff"
212 | active.BKColor = "#50ae55"
213 | active.hoverBKColor = "#c850ae55"
214 | active.setStyleSheet(
215 | "border-radius: 0px; font-family: Courier New; color: #ffffff; font-size: 18px; background: #50ae55; padding: 8px 18px 8px 18px; text-decoration: none;")
216 |
217 | inactive.color = "#000000"
218 | inactive.BKColor = "#e0e0e0"
219 | inactive.hoverBKColor = "#c8e0e0e0"
220 | inactive.setStyleSheet(
221 | "border-radius: 0px; font-family: Courier New; color: #000000; font-size: 18px; background: #e0e0e0; padding: 8px 18px 8px 18px; text-decoration: none;")
222 |
223 | def select_file(self, args=None):
224 | path = QFileDialog.getOpenFileName()[0]
225 |
226 | if (len(path.strip()) != 0):
227 | self.file_path = path
228 | with open(path, 'r') as content_file:
229 | content = content_file.read()
230 |
231 | self.input_code_editor.clear()
232 | self.quadruples_view.clear()
233 | self.logs_view.clear()
234 | self.symbols_view.clear()
235 |
236 | self.input_code_editor.insertPlainText(content)
237 |
238 | def on_compilation_started(self):
239 | if (len(self.input_code_editor.toPlainText()) == 0):
240 | return
241 |
242 | self.overlay.show()
243 | self.compilingTask.start()
244 |
245 | def on_compilation_finished(self):
246 | self.overlay.hide()
247 |
248 | def compile(self):
249 | print("Compiling")
250 |
251 | # Empty the output files
252 | open("out.txt", 'w').close()
253 | open("symbols.txt", 'w').close()
254 |
255 |
256 | with open(self.cpp_tmp_path, 'w') as f:
257 | f.write(self.input_code_editor.toPlainText())
258 |
259 | # Compile
260 | process = subprocess.run([self.cpp_compiler_path, self.cpp_tmp_path], text=True, capture_output=True)
261 |
262 | self.logs_view.clear()
263 |
264 | self.logs_view.setCurrentCharFormat(QTextCharFormat())
265 | self.logs_view.insertPlainText(process.stdout)
266 |
267 | errors_format = QTextCharFormat()
268 | errors_format.setForeground(Qt.red)
269 | errors_format.setFontWeight(QFont.Bold)
270 | self.logs_view.setCurrentCharFormat(errors_format)
271 | self.logs_view.insertPlainText(process.stderr)
272 |
273 | format = QTextCharFormat()
274 | format.setForeground(Qt.green) if process.returncode == 0 else format.setForeground(Qt.red)
275 | self.logs_view.setCurrentCharFormat(format)
276 |
277 | self.logs_view.insertPlainText(f"\n\nCompilation finished with exit code {process.returncode}\n")
278 |
279 | if not os.path.isfile(self.cpp_quadruples_path):
280 | return
281 |
282 | with open(self.cpp_quadruples_path, 'r') as f:
283 | content = f.read()
284 |
285 | self.quadruples_view.clear()
286 | self.quadruples_view.insertPlainText(content)
287 |
288 | if os.path.isfile(self.cpp_symbols_table_path):
289 | with open(self.cpp_symbols_table_path, 'r') as f:
290 | content = f.read()
291 |
292 | self.symbols_view.clear()
293 | self.symbols_view.insertPlainText(content)
294 |
295 | def resizeEvent(self, event):
296 | self.overlay.resize(event.size())
297 | event.accept()
298 |
299 | def center(self):
300 | qr = self.frameGeometry()
301 | cp = QDesktopWidget().availableGeometry().center()
302 | qr.moveCenter(cp)
303 | self.move(qr.topLeft())
304 |
305 | def mousePressEvent(self, event):
306 | self.oldPos = event.globalPos()
307 |
308 | def mouseMoveEvent(self, event):
309 | if (hasattr(self, 'oldPos')):
310 | delta = QPoint(event.globalPos() - self.oldPos)
311 | self.move(self.x() + delta.x(), self.y() + delta.y())
312 | self.oldPos = event.globalPos()
313 |
314 |
315 | class HoverButton(QToolButton):
316 |
317 | def __init__(self, text, BKColor="#3498db", hoverBKColor="#3cb0fd", color="#ffffff", padding="8px 18px 8px 18px",
318 | fontSize="18px", parent=None):
319 | super(HoverButton, self).__init__(parent)
320 |
321 | self.setMouseTracking(True)
322 | self.setText(text)
323 | self.BKColor = BKColor
324 | self.hoverBKColor = hoverBKColor
325 | self.color = color
326 | self.fontSize = fontSize
327 | self.padding = padding
328 |
329 | def enterEvent(self, event):
330 | self.setStyleSheet("border-radius: 0px; font-family: Courier New; color: " + self.color + "; font-size: " +
331 | self.fontSize + "; background: " + self.hoverBKColor + "; padding: " + self.padding + "; text-decoration: none;")
332 |
333 | def leaveEvent(self, event):
334 | self.setStyleSheet("border-radius: 0px; font-family: Courier New; color: " + self.color + "; font-size: " +
335 | self.fontSize + "; background: " + self.BKColor + "; padding: " + self.padding + "; text-decoration: none;")
336 |
337 |
338 | class TaskThread(QtCore.QThread):
339 |
340 | task_finished = QtCore.pyqtSignal()
341 |
342 | def run(self):
343 | cpp.compile()
344 |
345 | self.task_finished.emit()
346 |
347 |
348 | if __name__ == '__main__':
349 | app = QApplication(sys.argv)
350 | cpp = CppCompiler(sys.argv)
351 | sys.exit(app.exec_())
352 |
--------------------------------------------------------------------------------
/gui/out.txt:
--------------------------------------------------------------------------------
1 | PUSH INT 4
2 | PUSH INT 5
3 | MUL INT
4 | PUSH INT 6
5 | PUSH INT 2
6 | DIV INT
7 | ADD INT
8 | POP INT x
9 | PUSH CHAR 99
10 | POP CHAR y
11 | PUSH INT 5
12 | PUSH INT 3
13 | GT BOOL
14 | JMPZ L1
15 | PUSH INT 4
16 | POP INT x
17 | JMP L2
18 | L1:
19 | PUSH INT 2
20 | PUSH INT x
21 | MUL INT
22 | POP INT z
23 | L2:
24 | L3:
25 | PUSH INT 3
26 | PUSH INT 1
27 | GE BOOL
28 | JMPZ L4
29 | PUSH INT 4
30 | PUSH INT 3
31 | MUL INT
32 | PUSH INT 5
33 | ADD INT
34 | PUSH INT 2
35 | DIV INT
36 | POP INT r
37 | JMP L3
38 | L4:
39 | L7:
40 | PUSH INT 0
41 | POP INT i
42 | L8:
43 | PUSH INT i
44 | PUSH INT 3
45 | LT BOOL
46 | JMPZ L10
47 | PUSH INT i
48 | PUSH INT 1
49 | EQ BOOL
50 | JMPZ L11
51 | PUSH INT 3
52 | PUSH INT 4
53 | ADD INT
54 | POP INT x
55 | PUSH INT x
56 | CONV INT TO FLOAT
57 | PUSH FLOAT 4.3
58 | MUL FLOAT
59 | CONV FLOAT TO INT
60 | POP INT x
61 | JMP L10
62 | L11:
63 | PUSH INT 3
64 | PUSH INT 2
65 | AND BOOL
66 | CONV BOOL TO INT
67 | POP INT h
68 | L9:
69 | PUSH INT i
70 | PUSH INT 1
71 | ADD INT
72 | POP INT i
73 | JMP L8
74 | L10:
75 | PUSH INT 3
76 | POP INT f
77 |
78 |
--------------------------------------------------------------------------------
/gui/overlay.py:
--------------------------------------------------------------------------------
1 | import math, sys
2 | from PyQt5.QtCore import Qt, QTimer
3 | from PyQt5.QtGui import *
4 | from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
5 | from PyQt5.QtGui import *
6 | from PyQt5 import QtWidgets, QtCore
7 | from PyQt5.QtWidgets import *
8 | from PyQt5.QtCore import Qt, QTimer
9 |
10 | class Overlay(QWidget):
11 |
12 | def __init__(self, parent = None):
13 |
14 | QWidget.__init__(self, parent)
15 | palette = QPalette(self.palette())
16 | palette.setColor(palette.Background, Qt.transparent)
17 | self.setPalette(palette)
18 |
19 | def paintEvent(self, event):
20 |
21 | painter = QPainter()
22 | painter.begin(self)
23 | painter.setRenderHint(QPainter.Antialiasing)
24 | painter.fillRect(event.rect(), QBrush(QColor(255, 255, 255, 200)))
25 | painter.setPen(QPen(Qt.NoPen))
26 |
27 | for i in range(6):
28 | if (math.ceil(self.delayedCounter / 5) % 6) == i:
29 | painter.setBrush(QBrush(QColor(255, 100, 100)))
30 | else:
31 | painter.setBrush(QBrush(QColor(127, 127, 127)))
32 |
33 | painter.drawEllipse(
34 | int(self.width()/2 + 30 * math.cos(2 * math.pi * i / 6.0) - 10),
35 | int(self.height()/2 + 30 * math.sin(2 * math.pi * i / 6.0) - 10),
36 | 20, 20)
37 |
38 | painter.end()
39 |
40 | def showEvent(self, event):
41 |
42 | self.timer = self.startTimer(50)
43 | self.counter = 0
44 | self.delayedCounter = 0
45 |
46 | def timerEvent(self, event):
47 |
48 | self.counter += 1
49 | self.update()
50 |
51 | if (self.counter % 2 == 0):
52 | self.delayedCounter += 1
53 |
54 |
--------------------------------------------------------------------------------
/gui/symbols.txt:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3omar-mostafa/CppCompiler/2c20dd2dc510c06af830ab6f06dd598fdffdee51/gui/symbols.txt
--------------------------------------------------------------------------------
/gui/syntax.py:
--------------------------------------------------------------------------------
1 | # syntax.py
2 |
3 | import sys
4 |
5 | from PyQt5.QtCore import QRegExp
6 | from PyQt5.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter
7 | from colors import colors
8 |
9 |
10 | def format(color, style=''):
11 | """Return a QTextCharFormat with the given attributes.
12 | """
13 | _color = QColor()
14 | _color.setNamedColor(color)
15 |
16 | _format = QTextCharFormat()
17 | _format.setForeground(_color)
18 | if 'bold' in style:
19 | _format.setFontWeight(QFont.Bold)
20 | if 'italic' in style:
21 | _format.setFontItalic(True)
22 |
23 | return _format
24 |
25 |
26 | def format_custom(color, style=''):
27 | """Return a QTextCharFormat with custom colors.
28 | """
29 | _format = QTextCharFormat()
30 | _format.setForeground(color)
31 | if 'bold' in style:
32 | _format.setFontWeight(QFont.Bold)
33 | if 'italic' in style:
34 | _format.setFontItalic(True)
35 |
36 | return _format
37 |
38 |
39 | # Syntax styles that can be shared by all languages
40 | STYLES = {
41 | 'keyword': format_custom(colors["purple"]),
42 | 'types': format_custom(colors["teal"]),
43 | 'operator': format_custom(colors["symbols"]),
44 | 'brace': format('darkGray'),
45 | 'defclass': format('cyan', 'bold'),
46 | 'string': format_custom(colors["comments"]),
47 | 'string2': format_custom(colors["comments"]),
48 | 'comment': format('lightGreen', 'italic'),
49 | 'self': format('yellow', 'italic'),
50 | 'numbers': format_custom(colors["blue"]),
51 | }
52 |
53 |
54 | class CPPHighlighter (QSyntaxHighlighter):
55 | """Syntax highlighter for the C++ language.
56 | """
57 | # Types
58 | types = [
59 | 'bool',
60 | 'const',
61 | 'double',
62 | 'float',
63 | 'int',
64 | 'long',
65 | 'short',
66 | 'signed',
67 | 'struct',
68 | 'unsigned',
69 | 'void',
70 | 'string',
71 | 'char'
72 | ]
73 |
74 | # C++ keywords
75 | keywords = [
76 | 'alignas',
77 | 'alignof',
78 | 'and',
79 | 'and_eq',
80 | 'asm',
81 | 'atomic_cancel',
82 | 'atomic_commit',
83 | 'atomic_noexcept',
84 | 'auto',
85 | 'bitand',
86 | 'bitor',
87 | 'break',
88 | 'case',
89 | 'catch',
90 | 'char16_t',
91 | 'char32_t',
92 | 'class',
93 | 'compl',
94 | 'concept',
95 | 'constexpr',
96 | 'const_cast',
97 | 'continue',
98 | 'co_await',
99 | 'co_return',
100 | 'co_yield',
101 | 'decltype',
102 | 'default',
103 | 'delete',
104 | 'do',
105 | 'dynamic_cast',
106 | 'else',
107 | 'enum',
108 | 'explicit',
109 | 'export',
110 | 'extern',
111 | 'false',
112 | 'for',
113 | 'friend',
114 | 'goto',
115 | 'if',
116 | 'import',
117 | 'inline',
118 | 'module',
119 | 'mutable',
120 | 'namespace',
121 | 'new',
122 | 'noexcept',
123 | 'not',
124 | 'not_eq',
125 | 'nullptr',
126 | 'operator',
127 | 'or',
128 | 'or_eq',
129 | 'private',
130 | 'protected',
131 | 'public',
132 | 'register',
133 | 'reinterpret_cast',
134 | 'requires',
135 | 'return',
136 | 'sizeof',
137 | 'static',
138 | 'static_assert',
139 | 'static_cast',
140 | 'switch',
141 | 'synchronized',
142 | 'template',
143 | 'this',
144 | 'thread_local',
145 | 'throw',
146 | 'true',
147 | 'try',
148 | 'typedef',
149 | 'typeid',
150 | 'typename',
151 | 'union',
152 | 'using',
153 | 'virtual',
154 | 'volatile',
155 | 'wchar_t',
156 | 'while',
157 | 'xor',
158 | 'xor_eq'
159 | ]
160 |
161 | # C++ operators
162 | operators = [
163 | '=',
164 | # Comparison
165 | '==', '!=', '<', '<=', '>', '>=', '\!', '\&\&', '\|\|',
166 | # Arithmetic
167 | '\+', '-', '\*', '/', '//', '\%', '\*\*',
168 | # In-place
169 | '\+=', '-=', '\*=', '/=', '\%=',
170 | # Bitwise
171 | '\^', '\|', '\&', '\~', '>>', '<<', '\~',
172 | # General
173 | '\;', '\:', '\#', '\?',
174 | ]
175 |
176 | # C++ braces
177 | braces = [
178 | '\{', '\}', '\(', '\)', '\[', '\]',
179 | ]
180 |
181 | def __init__(self, document):
182 | QSyntaxHighlighter.__init__(self, document)
183 |
184 | # Multi-line strings (expression, flag, style)
185 | # FIXME: The triple-quotes in these two lines will mess up the
186 | # syntax highlighting from this point onward
187 | self.tri_single = (QRegExp("'''"), 1, STYLES['string2'])
188 | self.tri_double = (QRegExp('"""'), 2, STYLES['string2'])
189 |
190 | rules = []
191 |
192 | # Keyword, operator, and brace rules
193 | rules += [(r'\b%s\b' % w, 0, STYLES['types'])
194 | for w in CPPHighlighter.types]
195 | rules += [(r'\b%s\b' % w, 0, STYLES['keyword'])
196 | for w in CPPHighlighter.keywords]
197 | rules += [(r'%s' % o, 0, STYLES['operator'])
198 | for o in CPPHighlighter.operators]
199 | rules += [(r'%s' % b, 0, STYLES['brace'])
200 | for b in CPPHighlighter.braces]
201 |
202 | # All other rules
203 | rules += [
204 | # 'self'
205 | (r'\bself\b', 0, STYLES['self']),
206 |
207 | # Double-quoted string, possibly containing escape sequences
208 | (r'"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
209 | # Single-quoted string, possibly containing escape sequences
210 | (r"'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
211 |
212 | # 'def' followed by an identifier
213 | (r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
214 | # 'class' followed by an identifier
215 | (r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
216 |
217 |
218 | # Numeric literals
219 | (r'\b[+-]?[0-9]+[lL]?\b', 0, STYLES['numbers']),
220 | (r'\b[+-]?0[xX][0-9A-Fa-f]+[lL]?\b', 0, STYLES['numbers']),
221 | (r'\b[+-]?[0-9]+(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\b',
222 | 0, STYLES['numbers']),
223 |
224 | # From '#' until a newline
225 | (r'//[^\n]*', 0, STYLES['comment']),
226 | ]
227 |
228 | # Build a QRegExp for each pattern
229 | self.rules = [(QRegExp(pat), index, fmt)
230 | for (pat, index, fmt) in rules]
231 |
232 | def highlightBlock(self, text):
233 | """Apply syntax highlighting to the given block of text.
234 | """
235 | # Do other syntax formatting
236 | for expression, nth, format in self.rules:
237 | index = expression.indexIn(text, 0)
238 |
239 | while index >= 0:
240 | # We actually want the index of the nth match
241 | index = expression.pos(nth)
242 | length = len(expression.cap(nth))
243 | self.setFormat(index, length, format)
244 | index = expression.indexIn(text, index + length)
245 |
246 | self.setCurrentBlockState(0)
247 |
248 | # Do multi-line strings
249 | in_multiline = self.match_multiline(text, *self.tri_single)
250 | if not in_multiline:
251 | in_multiline = self.match_multiline(text, *self.tri_double)
252 |
253 | def match_multiline(self, text, delimiter, in_state, style):
254 | """Do highlighting of multi-line strings. ``delimiter`` should be a
255 | ``QRegExp`` for triple-single-quotes or triple-double-quotes, and
256 | ``in_state`` should be a unique integer to represent the corresponding
257 | state changes when inside those strings. Returns True if we're still
258 | inside a multi-line string when this function is finished.
259 | """
260 | # If inside triple-single quotes, start at 0
261 | if self.previousBlockState() == in_state:
262 | start = 0
263 | add = 0
264 | # Otherwise, look for the delimiter on this line
265 | else:
266 | start = delimiter.indexIn(text)
267 | # Move past this match
268 | add = delimiter.matchedLength()
269 |
270 | # As long as there's a delimiter match on this line...
271 | while start >= 0:
272 | # Look for the ending delimiter
273 | end = delimiter.indexIn(text, start + add)
274 | # Ending delimiter on this line?
275 | if end >= add:
276 | length = end - start + add + delimiter.matchedLength()
277 | self.setCurrentBlockState(0)
278 | # No; multi-line string
279 | else:
280 | self.setCurrentBlockState(in_state)
281 | length = len(text) - start + add
282 | # Apply formatting
283 | self.setFormat(start, length, style)
284 | # Look for the next match
285 | start = delimiter.indexIn(text, start + length)
286 |
287 | # Return True if still inside a multi-line string, False otherwise
288 | if self.currentBlockState() == in_state:
289 | return True
290 | else:
291 | return False
292 |
--------------------------------------------------------------------------------
/images/ide.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/3omar-mostafa/CppCompiler/2c20dd2dc510c06af830ab6f06dd598fdffdee51/images/ide.png
--------------------------------------------------------------------------------
/include/headers.h:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 |
5 | #include "../src/nodes/Node.h"
6 | #include "../src/nodes/expressions/AssignOpNode.h"
7 | #include "../src/nodes/expressions/BinaryOpNode.h"
8 | #include "../src/nodes/expressions/IdentifierNode.h"
9 | #include "../src/nodes/expressions/LiteralNode.h"
10 | #include "../src/nodes/expressions/UnaryOpNode.h"
11 |
12 | #include "../src/nodes/statements/VariableDeclarationNode.h"
13 | #include "../src/nodes/statements/StmtBlockNode.h"
14 | #include "../src/nodes/conditions/IfElseCondNode.h"
15 | #include "../src/nodes/conditions/SwitchCondNode.h"
16 | #include "../src/nodes/conditions/CaseNode.h"
17 | #include "../src/nodes/loops/WhileLoopNode.h"
18 | #include "../src/nodes/loops/DoWhileLoopNode.h"
19 | #include "../src/nodes/loops/ForLoopNode.h"
20 | #include "../src/nodes/loops/BreakNode.h"
21 | #include "../src/nodes/loops/ContinueNode.h"
22 | #include "../src/nodes/functions/FunctionDeclarationNode.h"
23 | #include "../src/nodes/functions/FunctionCallNode.h"
24 | #include "../src/nodes/functions/ReturnNode.h"
25 |
26 | #include "../src/utils/enums.h"
--------------------------------------------------------------------------------
/out.txt:
--------------------------------------------------------------------------------
1 | PUSH INT 4
2 | PUSH INT 5
3 | MUL INT
4 | PUSH INT 6
5 | PUSH INT 2
6 | DIV INT
7 | ADD INT
8 | POP INT x
9 | PUSH CHAR 99
10 | POP CHAR y
11 | PUSH INT 5
12 | PUSH INT 3
13 | GT BOOL
14 | JMPZ L1
15 | PUSH INT 4
16 | POP INT x
17 | JMP L2
18 | L1:
19 | PUSH INT 2
20 | PUSH INT x
21 | MUL INT
22 | POP INT z
23 | L2:
24 | L3:
25 | PUSH INT 3
26 | PUSH INT 1
27 | GE BOOL
28 | JMPZ L4
29 | PUSH INT 4
30 | PUSH INT 3
31 | MUL INT
32 | PUSH INT 5
33 | ADD INT
34 | PUSH INT 2
35 | DIV INT
36 | POP INT r
37 | JMP L3
38 | L4:
39 | L7:
40 | PUSH INT 0
41 | POP INT i
42 | L8:
43 | PUSH INT i
44 | PUSH INT 3
45 | LT BOOL
46 | JMPZ L10
47 | PUSH INT i
48 | PUSH INT 1
49 | EQ BOOL
50 | JMPZ L11
51 | PUSH INT 3
52 | PUSH INT 4
53 | ADD INT
54 | POP INT x
55 | PUSH INT x
56 | CONV INT TO FLOAT
57 | PUSH FLOAT 4.3
58 | MUL FLOAT
59 | CONV FLOAT TO INT
60 | POP INT x
61 | JMP L10
62 | L11:
63 | PUSH INT 3
64 | PUSH INT 2
65 | AND BOOL
66 | CONV BOOL TO INT
67 | POP INT h
68 | L9:
69 | PUSH INT i
70 | PUSH INT 1
71 | ADD INT
72 | POP INT i
73 | JMP L8
74 | L10:
75 | PUSH INT 3
76 | POP INT f
77 |
78 |
--------------------------------------------------------------------------------
/src/grammar/lexer.l:
--------------------------------------------------------------------------------
1 |
2 | /*
3 | Comments can start with // or /*
4 | But MUST be indented, or have at least one space before the comment.
5 | */
6 |
7 | /*
8 | Options Documentation: https://ftp.gnu.org/old-gnu/Manuals/flex-2.5.4/html_node/flex_17.html
9 | */
10 |
11 | /*
12 | Makes the generated scanner run in debug mode. Whenever a pattern is recognized and the global yy_flex_debug is non-zero (which is the default), the scanner will write to stderr a line of the form:
13 | --accepting rule at line 53 ("the matched text")
14 | The line number refers to the location of the rule in the file defining the scanner (i.e., the file that was fed to flex).
15 | Messages are also generated when the scanner backs up, accepts the default rule, reaches the end of its input buffer (or encounters a NUL; at this point, the two look the same as far as the scanner's concerned), or reaches an end-of-file.
16 | */
17 |
18 | /*
19 | Causes the default rule (that unmatched scanner input is echoed to stdout) to be suppressed.
20 | If the scanner encounters input that does not match any of its rules, it aborts with an error.
21 | This option is useful for finding holes in a scanner's rule set.
22 | */
23 | %option nodefault
24 |
25 | /*
26 | Makes the scanner not call `yywrap()' upon an end-of-file,
27 | but simply assume that there are no more files to scan
28 | (until the user points yyin at a new file and calls `yylex()' again)
29 | */
30 | %option noyywrap
31 |
32 |
33 | %option warn
34 |
35 | /*
36 | Creates global variable `yylineno` which contains the current line read from input
37 | */
38 | %option yylineno
39 | /*
40 | Disable interactive mode (read line by line from standard input)
41 | This removes calls `isatty()` function, which makes it compatible with Microsoft Visual Studio
42 | */
43 | %option never-interactive
44 |
45 | /*
46 | Disable including header file, which is only available at linux
47 | Which makes it compatible with Microsoft Visual Studio
48 | Note: This is equivalent to #define YY_NO_UNISTD_H
49 | */
50 | %option nounistd
51 |
52 | %{
53 | #include
54 | #include
55 |
56 | #include "parser.hpp"
57 | #include "location.hpp"
58 |
59 | #undef YY_DECL
60 | // Give Flex the prototype of yylex we want which is compatible with Bison C++ variants
61 | #define YY_DECL yy::parser::symbol_type yylex()
62 |
63 |
64 | int countLines(std::string text) {
65 | int lines = 0;
66 | for(char c: text) {
67 | lines += c == '\n';
68 | }
69 | return lines;
70 | }
71 |
72 | std::string yyfilename;
73 |
74 | yy::location loc; // Global location object, used to store the location current token
75 |
76 | #define YY_USER_INIT loc.initialize(&yyfilename)
77 |
78 | // Code run each time a pattern is matched.
79 | // Move the location forward by the length of the matched token
80 | // and move the current line number forward by the number of newlines
81 | #define YY_USER_ACTION loc.columns(yyleng); loc.lines(countLines(yytext));
82 |
83 | %}
84 |
85 |
86 | DIGIT [0-9]
87 | INTEGER [0-9]+
88 | FLOAT (([0-9]*\.[0-9]+)|([0-9]+\.[0-9]*))
89 | EXP ([eE][-+]?{INTEGER})
90 | REAL ({INTEGER}{EXP}|{FLOAT}{EXP}?)
91 | LETTER [a-zA-Z_]
92 | CHAR \'.\'
93 | STRING \".*\"
94 | IDENTIFIER {LETTER}({LETTER}|{DIGIT})*
95 | LINE_COMMENT "//"(.)*
96 | MULTILINE_COMMENT [/][*]+([^*/][^*]*[*]+)+[/]
97 |
98 |
99 | %%
100 |
101 | %{
102 | // Code run each time yylex is called.
103 | // This section MUST be inside %% not before it to include it inside yylex function
104 |
105 | // Move the location one step forward
106 | // Note that the step is not 1, it is the length of the last matched token
107 | loc.step();
108 | %}
109 |
110 | "int" {return yy::parser::make_TYPE_INT(loc);}
111 | "float" {return yy::parser::make_TYPE_FLOAT(loc);}
112 | "char" {return yy::parser::make_TYPE_CHAR(loc);}
113 | "bool" {return yy::parser::make_TYPE_BOOL(loc);}
114 | "void" {return yy::parser::make_TYPE_VOID(loc);}
115 | "string" {return yy::parser::make_TYPE_STRING(loc);}
116 |
117 | "const" {return yy::parser::make_CONST(loc);}
118 |
119 | "if" {return yy::parser::make_IF(loc);}
120 | "else" {return yy::parser::make_ELSE(loc);}
121 | "switch" {return yy::parser::make_SWITCH(loc);}
122 | "case" {return yy::parser::make_CASE(loc);}
123 | "default" {return yy::parser::make_DEFAULT(loc);}
124 | "for" {return yy::parser::make_FOR(loc);}
125 | "do" {return yy::parser::make_DO(loc);}
126 | "while" {return yy::parser::make_WHILE(loc);}
127 | "break" {return yy::parser::make_BREAK(loc);}
128 | "continue" {return yy::parser::make_CONTINUE(loc);}
129 | "return" {return yy::parser::make_RETURN(loc);}
130 |
131 | "++" {return yy::parser::make_INC(loc);}
132 | "--" {return yy::parser::make_DEC(loc);}
133 | "==" {return yy::parser::make_EQ(loc);}
134 | "!=" {return yy::parser::make_NE(loc);}
135 | ">=" {return yy::parser::make_GE(loc);}
136 | "<=" {return yy::parser::make_LE(loc);}
137 | "<<" {return yy::parser::make_SHL(loc);}
138 | ">>" {return yy::parser::make_SHR(loc);}
139 | "&&"|"and" {return yy::parser::make_AND(loc);}
140 | "||"|"or" {return yy::parser::make_OR(loc);}
141 | "!"|"not" {return yy::parser::make_NOT(loc);}
142 | "**" {return yy::parser::make_POWER(loc);}
143 |
144 | [-+*/=;<>(){}[\],:] {return yy::parser::symbol_type(yytext[0], loc);}
145 |
146 | "true" {return yy::parser::make_BOOL(true, loc);}
147 | "false" {return yy::parser::make_BOOL(false, loc);}
148 |
149 | {INTEGER} {return yy::parser::make_INTEGER(yytext, loc);}
150 | {REAL} {return yy::parser::make_REAL(yytext, loc);}
151 | {CHAR} {return yy::parser::make_CHAR(yytext[1], loc);}
152 | {STRING} {return yy::parser::make_STRING(yytext, loc);}
153 | {IDENTIFIER} {return yy::parser::make_IDENTIFIER(new IdentifierNode(loc, yytext), loc);}
154 | {LINE_COMMENT} {}
155 | {MULTILINE_COMMENT} {}
156 | [ ]+ {loc.step();} /* skip empty spaces */
157 | [\t]+ { /*
158 | Skip tabs (assume tab = 4 spaces)
159 | Note: tab is treated as one character, but we want to treat it as 4
160 | So we increment the location by 3 times number of tab characters,
161 | not by 4 times because every time yylex is called, it will increment the location
162 | */
163 | loc.columns(3 * yyleng); loc.step();
164 | }
165 | [\n]+ {loc.step();} /* skip new lines */
166 | [\r] {} /* ignore new lines of CRLF Line Endings to convert it to LF only */
167 | <> {return yy::parser::make_EOF(loc);}
168 | . {throw yy::parser::syntax_error(loc, "[LEXER] invalid character: " + std::string(yytext));}
169 |
170 | %%
171 |
172 |
--------------------------------------------------------------------------------
/src/grammar/parser.y:
--------------------------------------------------------------------------------
1 | // Bison minimum version
2 | %require "3.0"
3 |
4 | // Generate C++ files instead of C
5 | %language "c++"
6 |
7 | // Enable C++ Variants (Allow using C++ data types in token data types)
8 | // i.e. use `%token IDENTIFIER` instead of union
9 | // Documentation: https://www.gnu.org/software/bison/manual/html_node/C_002b_002b-Variants.html
10 | %define api.value.type variant
11 |
12 | // Request that symbols be handled as a whole (type, value, location) in the lexer
13 | // i.e. use `return yy::parser::make_IDENTIFIER(yytext, loc)` in lexer
14 | %define api.token.constructor
15 |
16 | // Enable Location Tracking
17 | // Documentation: https://www.gnu.org/software/bison/manual/html_node/Tracking-Locations.html
18 | // Documentation: https://www.gnu.org/software/bison/manual/html_node/C_002b_002b-Location-Values.html
19 | %locations
20 |
21 | // The name of location file to generate
22 | %define api.location.file "location.hpp"
23 |
24 | // Enable parser tracing and detailed error messages
25 | %define parse.trace
26 | %define parse.error verbose
27 | %define parse.lac full
28 |
29 | // This option checks that symbols must be constructed and destroyed properly.
30 | %define parse.assert
31 |
32 | // Add a prefix to the token names to avoid conflicts.
33 | %define api.token.prefix {TOKEN_}
34 |
35 | %code requires {
36 | #include "headers.h"
37 | #include
38 |
39 | }
40 |
41 | %code {
42 | // Forward declaration for yylex created by the lexer (flex)
43 | yy::parser::symbol_type yylex();
44 | Node* programRoot = nullptr;
45 | }
46 |
47 | // `provides` makes this section available to the lexer (code it put in the header file)
48 | %code provides {
49 | namespace yy{
50 | void printLocation(const yy::parser::location_type& location);
51 | std::string getLine(const std::string& filename, int line);
52 | }
53 | }
54 |
55 | %code {
56 | namespace yy{
57 | void printLocation(const yy::parser::location_type& location) {
58 | printf(" [@ %d:%d -> %d:%d]\n", location.begin.line, location.begin.column, location.end.line, location.end.column);
59 | }
60 | }
61 | }
62 |
63 | %token INTEGER
64 | %token REAL
65 | %token CHAR
66 | %token BOOL
67 | %token STRING
68 | %token IDENTIFIER
69 |
70 | %token INC DEC
71 |
72 | %token TYPE_INT TYPE_FLOAT TYPE_CHAR TYPE_BOOL TYPE_VOID TYPE_STRING
73 | %token CONST
74 |
75 | %token IF ELSE SWITCH CASE DEFAULT FOR DO WHILE CONTINUE BREAK RETURN
76 |
77 | %nterm statement
78 | %nterm statement_list
79 | %nterm variable_declaration_statement variable_declaration
80 | %nterm loop_statement
81 | %nterm switch_statement
82 | %nterm case_statement
83 | %nterm if_statement
84 | %nterm expr
85 | %nterm literal
86 | %nterm function_declaration_statemnt
87 | %nterm return_statement
88 | %nterm arguments func_args
89 | %nterm parameters func_params
90 | %nterm data_type
91 | %nterm program
92 |
93 | %right '='
94 | %left AND OR NOT
95 | %left GE LE EQ NE '>' '<'
96 | %left SHL SHR
97 | %left '+' '-'
98 | %left '*' '/'
99 | %right POWER
100 | %right UNARY_MINUS
101 | %right PRE_INC PRE_DEC
102 | %left POST_INC POST_DEC
103 |
104 | %token EOF 0;
105 |
106 | %nonassoc IFUNMATCHED
107 | %nonassoc ELSE
108 | %%
109 |
110 | %start program;
111 |
112 | program:
113 | statement_list { $program = nullptr; programRoot = new StmtBlockNode(@$, *$statement_list); delete $statement_list; $statement_list = nullptr; }
114 | | /* empty */ { $program = nullptr; programRoot = new StmtBlockNode(@$);}
115 | ;
116 |
117 | statement:
118 | variable_declaration_statement {$statement = $variable_declaration_statement;}
119 | | if_statement {$statement = $if_statement;}
120 | | switch_statement {$statement = $switch_statement;}
121 | | case_statement {$statement = $case_statement;}
122 | | loop_statement {$statement = $loop_statement;}
123 | | function_declaration_statemnt {$statement = $function_declaration_statemnt;}
124 | | return_statement {$statement = $return_statement;}
125 | | '{''}' {$statement = new StmtBlockNode(@$);}
126 | | '{'statement_list'}' {$statement = new StmtBlockNode(@$, *$statement_list); delete $statement_list; $statement_list = nullptr;}
127 | | expr ';' {$statement = $expr;}
128 | ;
129 |
130 | statement_list:
131 | statement {$$ = new StmtListNode(); $$->push_back($statement);}
132 | | statement_list[rhs] statement {$$ = $rhs; $$->push_back($statement);}
133 | ;
134 |
135 | variable_declaration_statement:
136 | variable_declaration ';' { $$ = $variable_declaration;}
137 | ;
138 |
139 | variable_declaration:
140 | data_type IDENTIFIER { $$ = new VariableDeclarationNode(@$, $data_type, $IDENTIFIER); }
141 | | data_type IDENTIFIER '=' expr { $$ = new VariableDeclarationNode(@$, $data_type, $IDENTIFIER, $expr); }
142 | | CONST data_type IDENTIFIER '=' expr { $$ = new VariableDeclarationNode(@$, $data_type, $IDENTIFIER, $expr, true); }
143 | ;
144 |
145 | if_statement:
146 | IF '(' expr ')' statement %prec IFUNMATCHED {$$ = new IfElseCondNode(@$,$expr , $statement);}
147 | | IF '(' expr ')' statement[if_body] ELSE statement[else_body] {$$ = new IfElseCondNode(@$,$expr , $if_body, $else_body);}
148 | ;
149 |
150 | switch_statement:
151 | SWITCH '(' expr ')' statement {$$ = new SwitchCondNode(@$, $expr, $statement);}
152 | ;
153 |
154 | case_statement:
155 | CASE expr ':' statement {$$ = new CaseNode(@$, $expr, $statement);}
156 | | DEFAULT ':' statement {$$ = new CaseNode(@$, NULL, $statement);}
157 | ;
158 |
159 | loop_statement:
160 | FOR '(' variable_declaration_statement[varDec] expr[cond] ';' expr[step] ')' statement {$$ = new ForLoopNode(@$, $varDec, $cond, $step, $statement);}
161 | | WHILE '(' expr ')' statement {$$ = new WhileLoopNode(@$, $expr, $statement);}
162 | | DO statement WHILE '(' expr ')' ';' {$$ = new DoWhileLoopNode(@$, $expr, $statement);}
163 | | CONTINUE ';' {$$ = new ContinueNode(@$);}
164 | | BREAK ';' {$$ = new BreakNode(@$);}
165 | ;
166 |
167 | function_declaration_statemnt:
168 | data_type IDENTIFIER '(' func_params ')' statement { $$ = new FunctionDeclarationNode(@$, $data_type, $IDENTIFIER, *$func_params, $statement);
169 | delete $func_params;
170 | $func_params = nullptr; }
171 | ;
172 |
173 | parameters:
174 | variable_declaration {$$ = new VarDecList(); $$->push_back($variable_declaration);}
175 | | parameters[rhs] ',' variable_declaration {$$ = $rhs; $$->push_back($variable_declaration);}
176 | ;
177 |
178 | func_params:
179 | parameters {$$ = $parameters;}
180 | | /* empty */ {$$ = new VarDecList();}
181 | ;
182 |
183 | arguments:
184 | expr {$$ = new ExpressionList(); $$->push_back($expr);}
185 | | arguments[rhs] ',' expr {$$ = $rhs; $$->push_back($expr);}
186 | ;
187 |
188 | func_args:
189 | arguments {$$ = $arguments;}
190 | | /* empty */ {$$ = new ExpressionList();}
191 | ;
192 |
193 | return_statement:
194 | RETURN ';' {$$ = new ReturnNode(@$, NULL);}
195 | | RETURN expr ';' {$$ = new ReturnNode(@$, $expr);}
196 | ;
197 |
198 | data_type:
199 | TYPE_INT { $data_type = DTYPE_INT;}
200 | | TYPE_FLOAT { $data_type = DTYPE_FLOAT;}
201 | | TYPE_CHAR { $data_type = DTYPE_CHAR;}
202 | | TYPE_BOOL { $data_type = DTYPE_BOOL;}
203 | | TYPE_VOID { $data_type = DTYPE_VOID; }
204 | ;
205 |
206 | expr[result]:
207 | literal { $result = $literal;}
208 | | expr[left] '+' expr[right] { $result = new BinaryOpNode(@$, $left, OPR_ADD, $right);}
209 | | expr[left] '-' expr[right] { $result = new BinaryOpNode(@$, $left, OPR_SUB, $right);}
210 | | '-' expr[right] %prec UNARY_MINUS { $result = new UnaryOpNode(@$, OPR_UNARY_MINUS, $right);}
211 | | expr[left] '*' expr[right] { $result = new BinaryOpNode(@$, $left, OPR_MUL, $right);}
212 | | expr[left] '/' expr[right] { $result = new BinaryOpNode(@$, $left, OPR_DIV, $right);}
213 | | expr[left] POWER expr[right] { $result = new BinaryOpNode(@$, $left, OPR_POW, $right);}
214 | | expr[left] AND expr[right] { $result = new BinaryOpNode(@$, $left, OPR_AND, $right);}
215 | | expr[left] OR expr[right] { $result = new BinaryOpNode(@$, $left, OPR_OR, $right);}
216 | | NOT expr[right] { $result = new UnaryOpNode(@$, OPR_NOT, $right);}
217 | | expr[left] '>' expr[right] { $result = new BinaryOpNode(@$, $left, OPR_GREATER, $right);}
218 | | expr[left] GE expr[right] { $result = new BinaryOpNode(@$, $left, OPR_GREATER_EQUAL, $right);}
219 | | expr[left] '<' expr[right] { $result = new BinaryOpNode(@$, $left, OPR_LESS, $right);}
220 | | expr[left] LE expr[right] { $result = new BinaryOpNode(@$, $left, OPR_LESS_EQUAL, $right);}
221 | | expr[left] EQ expr[right] { $result = new BinaryOpNode(@$, $left, OPR_EQUAL, $right);}
222 | | expr[left] NE expr[right] { $result = new BinaryOpNode(@$, $left, OPR_NOT_EQUAL, $right);}
223 | | expr[left] SHL expr[right] { $result = new BinaryOpNode(@$, $left, OPR_SHL, $right);}
224 | | expr[left] SHR expr[right] { $result = new BinaryOpNode(@$, $left, OPR_SHR, $right);}
225 | | '(' expr[left] ')' { $result = $left;}
226 | | IDENTIFIER { $result = $IDENTIFIER;}
227 | | IDENTIFIER '=' expr[right] { $result = new AssignOpNode(@$, $IDENTIFIER, $right);}
228 | | IDENTIFIER '(' func_args ')' { $result = new FunctionCallNode(@$, $IDENTIFIER, *$func_args); delete $func_args; $func_args = nullptr;}
229 | | INC IDENTIFIER %prec PRE_INC { $result = new UnaryOpNode(@$, OPR_PRE_INC, $IDENTIFIER);}
230 | | DEC IDENTIFIER %prec PRE_DEC { $result = new UnaryOpNode(@$, OPR_PRE_DEC, $IDENTIFIER);}
231 | | IDENTIFIER INC %prec POST_INC { $result = new UnaryOpNode(@$, OPR_POST_INC, $IDENTIFIER);}
232 | | IDENTIFIER DEC %prec POST_DEC { $result = new UnaryOpNode(@$, OPR_POST_DEC, $IDENTIFIER);}
233 | ;
234 |
235 | literal:
236 | INTEGER { $literal = new LiteralNode(@$, $INTEGER, DTYPE_INT);}
237 | | BOOL { $literal = new LiteralNode(@$, std::to_string($BOOL), DTYPE_BOOL);}
238 | | REAL { $literal = new LiteralNode(@$, $REAL, DTYPE_FLOAT);}
239 | | CHAR { $literal = new LiteralNode(@$, std::to_string($CHAR), DTYPE_CHAR);}
240 | %%
241 |
242 |
243 | void yy::parser::error(const location_type &loc, const std::string &err_message)
244 | {
245 | Utils::log(err_message, loc, "error");
246 | exit(1);
247 | }
248 |
--------------------------------------------------------------------------------
/src/helpers/CodeGenerationHelper.h:
--------------------------------------------------------------------------------
1 | #ifndef GENERATION_HELPER
2 | #define GENERATION_HELPER
3 |
4 | #include
5 | #include
6 |
7 | class CodeGenerationHelper
8 | {
9 | int labelNum = 1;
10 | std::stack continueLabelStack;
11 | std::stack breakLabelStack;
12 |
13 | CodeGenerationHelper() = default;
14 |
15 | public:
16 |
17 | static CodeGenerationHelper* getInstance()
18 | {
19 | static CodeGenerationHelper instance;
20 | return &instance;
21 | }
22 |
23 | std::string getNewLabel()
24 | {
25 | return "L" + std::to_string(labelNum++);
26 | }
27 |
28 | void addContinueLabel(const std::string& label)
29 | {
30 | continueLabelStack.push(label);
31 | }
32 |
33 | void addBreakLabel(const std::string& label)
34 | {
35 | breakLabelStack.push(label);
36 | }
37 |
38 | void removeContinueLabel()
39 | {
40 | continueLabelStack.pop();
41 | }
42 |
43 | void removeBreakLabel()
44 | {
45 | breakLabelStack.pop();
46 | }
47 |
48 | std::string getContinueLabel()
49 | {
50 | return continueLabelStack.top();
51 | }
52 |
53 | std::string getBreakLabel()
54 | {
55 | return breakLabelStack.top();
56 | }
57 | };
58 |
59 | #endif
--------------------------------------------------------------------------------
/src/helpers/ScopeHelper.h:
--------------------------------------------------------------------------------
1 | #ifndef ANALYSIS_HELPER
2 | #define ANALYSIS_HELPER
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include
9 | #include
10 |
11 | #include "../nodes/Node.h"
12 | #include "../symbolTable/SymbolTable.h"
13 | #include "../utils/enums.h"
14 | #include "../utils/utils.h"
15 |
16 | class FunctionDeclarationNode;
17 |
18 | using namespace std;
19 |
20 | class Scope
21 | {
22 | public:
23 | ScopeType type; // The type of the scope
24 | Node *ptr; // A pointer to the node of the scope
25 | SymbolTable table; // The symbol table of this scope
26 |
27 | explicit Scope(ScopeType type, Node* ptr = nullptr)
28 | {
29 | this->type = type;
30 | this->ptr = ptr;
31 | }
32 | };
33 |
34 | class ScopeHelper
35 | {
36 | vector scopes;
37 | string symbolTableStr;
38 |
39 | void initSymbolTableString()
40 | {
41 | string tmp;
42 | tmp += "+---------+---------------------+----------------+-------+\n";
43 | tmp += "| scope | identifier | type | used |\n";
44 | tmp += "+---------+---------------------+----------------+-------+\n";
45 | symbolTableStr = tmp + symbolTableStr;
46 | }
47 |
48 | void updateSymbolTableString(SymbolTable t, int scope)
49 | {
50 | string scopeStr;
51 | switch (scope)
52 | {
53 | case SCOPE_LOOP:
54 | scopeStr = "loop";
55 | break;
56 | case SCOPE_IF:
57 | scopeStr = "if";
58 | break;
59 | case SCOPE_SWITCH:
60 | scopeStr = "switch";
61 | break;
62 | case SCOPE_FUNCTION:
63 | scopeStr = "func";
64 | break;
65 | case SCOPE_BLOCK:
66 | scopeStr = "block";
67 | break;
68 | default:
69 | scopeStr = "global";
70 | break;
71 | }
72 |
73 | stringstream ss;
74 | for (auto& [name, info] : t.getTable())
75 | {
76 | ss << "| " << left << setw(8) << scopeStr;
77 | ss << "| " << left << setw(20) << name;
78 | ss << "| " << left << setw(15) << Utils::typeToQuad(info.type);
79 | ss << "| " << left << setw(6) << info.used << "|\n";
80 | ss << "+---------+---------------------+----------------+-------+\n";
81 | }
82 | symbolTableStr = ss.str() + symbolTableStr;
83 | }
84 |
85 | ScopeHelper() = default;
86 |
87 | public:
88 | bool declareParams = false;
89 |
90 | static ScopeHelper* getInstance()
91 | {
92 | static ScopeHelper instance;
93 | return &instance;
94 | }
95 |
96 | void pushScope(ScopeType type, Node* scopePtr = nullptr)
97 | {
98 | scopes.push_back(new Scope(type, scopePtr));
99 | }
100 |
101 | void popScope()
102 | {
103 | Scope *scope = scopes.back();
104 | scopes.pop_back();
105 |
106 | for (auto& [name, info]: scope->table.getTable())
107 | {
108 | if (info.used <= 0)
109 | {
110 | if (info.entryType == TYPE_VAR)
111 | {
112 | Utils::log("the value of variable '" + name + "' is never used", info.loc, "warning");
113 | } else if (info.entryType == TYPE_FUNC && name != "main")
114 | {
115 | Utils::log("the function '" + name + "' is never called", info.loc, "warning");
116 | }
117 | }
118 | }
119 |
120 | updateSymbolTableString(scope->table, scopes.empty() ? 0 : scope->type);
121 |
122 | delete scope;
123 | }
124 |
125 | bool isInsideGlobalScope()
126 | {
127 | return scopes.size() == 1;
128 | }
129 |
130 | bool isInsideSwitchScope()
131 | {
132 | for (int i = (int)scopes.size() - 1; i >= 0; --i)
133 | {
134 | if (scopes[i]->type == SCOPE_SWITCH)
135 | {
136 | return true;
137 | }
138 | }
139 |
140 | return false;
141 | }
142 |
143 | FunctionDeclarationNode* isInsideFunctionScope()
144 | {
145 | for (int i = (int)scopes.size() - 1; i >= 0; --i)
146 | {
147 | if (scopes[i]->type == SCOPE_FUNCTION)
148 | {
149 | return reinterpret_cast(scopes[i]->ptr);
150 | }
151 | }
152 |
153 | return nullptr;
154 | }
155 |
156 | bool isInsideLoopScope()
157 | {
158 | for (int i = (int)scopes.size() - 1; i >= 0; --i)
159 | {
160 | if (scopes[i]->type == SCOPE_LOOP)
161 | {
162 | return true;
163 | }
164 | }
165 |
166 | return false;
167 | }
168 |
169 | EntryInfo* addSymbol(yy::location loc, const string& name, DataType type, EntryType entryType = TYPE_VAR,
170 | const vector& paramsTypes = {}, int used = 0, bool initialized = false)
171 | {
172 | SymbolTable& symbolTable = scopes.back()->table;
173 |
174 | auto info = symbolTable.insert(loc, name, type, entryType, paramsTypes, used, initialized);
175 | if (!info)
176 | {
177 | return nullptr;
178 | }
179 |
180 | return info;
181 | }
182 |
183 | EntryInfo* lookup(const string &name)
184 | {
185 | for (int i = (int)scopes.size() - 1; i >= 0; --i)
186 | {
187 | if (auto info = scopes[i]->table.lookup(name))
188 | {
189 | return info;
190 | }
191 | }
192 |
193 | return nullptr;
194 | }
195 |
196 | string getSymbolTableString()
197 | {
198 | initSymbolTableString();
199 | return symbolTableStr;
200 | }
201 | };
202 |
203 | #endif
--------------------------------------------------------------------------------
/src/main.cpp:
--------------------------------------------------------------------------------
1 | #include
2 | #include
3 | #include
4 | #include "nodes/Node.h"
5 |
6 | extern FILE *yyin;
7 | extern std::string yyfilename;
8 | extern Node *programRoot;
9 |
10 | void writeToFile(const string& data, const string& filename);
11 |
12 | int main(int argc, char *argv[])
13 | {
14 | std::string outFile = "out.txt", symbolOutFile = "symbols.txt";
15 |
16 | switch (argc)
17 | {
18 | case 3:
19 | outFile = argv[2];
20 | break;
21 | case 4:
22 | outFile = argv[2];
23 | symbolOutFile = argv[3];
24 | break;
25 | }
26 |
27 | if (argc >= 2)
28 | {
29 | yyin = fopen(argv[1], "r");
30 | if (yyin == nullptr)
31 | {
32 | fprintf(stderr, "error: could not open the input file %s", argv[1]);
33 | exit(1);
34 | }
35 | yyfilename = argv[1];
36 | std::cout << "Compiling " << argv[1] << std::endl;
37 | }
38 | else
39 | {
40 | std::cerr << "No files were given, reading input from stdin" << std::endl;
41 | }
42 |
43 | yy::parser parser;
44 | parser.parse();
45 |
46 |
47 | std::cout << "Start Analyzing \n";
48 | bool analyze = programRoot->analyzeSemantic();
49 | if (!analyze)
50 | {
51 | std::cerr << "Semantic Error Can not generate quadruples\n";
52 | exit(1);
53 | }
54 | std::cout << "Finished Semantic analysis\n";
55 |
56 | std::string quad = programRoot->generateCode();
57 |
58 | std::cout << "Finished code generation\n";
59 |
60 | writeToFile(quad, outFile);
61 |
62 | ScopeHelper *scopeHelper = ScopeHelper::getInstance();
63 | writeToFile(scopeHelper->getSymbolTableString(), symbolOutFile);
64 |
65 | return 0;
66 | }
67 |
68 | void writeToFile(const string& data, const string& filename)
69 | {
70 | if (filename.empty())
71 | {
72 | return;
73 | }
74 |
75 | ofstream fout(filename);
76 |
77 | if (!fout.is_open())
78 | {
79 | fprintf(stderr, "error: could not write in file '%s'!\n", filename.c_str());
80 | return;
81 | }
82 |
83 | fout << data << endl;
84 |
85 | fout.close();
86 | }
87 |
--------------------------------------------------------------------------------
/src/nodes/Node.h:
--------------------------------------------------------------------------------
1 | #ifndef NODE
2 | #define NODE
3 |
4 | #include
5 | #include
6 | #include
7 |
8 | #include "location.hpp"
9 |
10 | #include "../utils/enums.h"
11 | #include "../utils/utils.h"
12 | #include "../symbolTable/SymbolTable.h"
13 | #include "../helpers/CodeGenerationHelper.h"
14 |
15 | class Node;
16 | #include "../helpers/ScopeHelper.h"
17 |
18 | using namespace std;
19 |
20 | class Node
21 | {
22 |
23 | public:
24 | yy::location loc;
25 | explicit Node(yy::location loc)
26 | {
27 | this->loc = loc;
28 | }
29 | virtual bool analyzeSemantic(bool used = false) = 0;
30 | virtual string generateCode() = 0;
31 |
32 | virtual ~Node() = default;
33 | };
34 |
35 | class ExpressionNode : public Node
36 | {
37 | public:
38 | DataType type; // int, float, ...
39 | EntryType entryType; // variable, const, function
40 |
41 | explicit ExpressionNode(yy::location loc) : Node(loc)
42 | {
43 | }
44 | bool analyzeSemantic(bool used = false) override = 0;
45 | string generateCode() override = 0;
46 |
47 | virtual ~ExpressionNode() = default;
48 | };
49 |
50 | typedef vector StmtListNode;
51 |
52 | #endif
--------------------------------------------------------------------------------
/src/nodes/conditions/CaseNode.h:
--------------------------------------------------------------------------------
1 | #ifndef CASE_NODE
2 | #define CASE_NODE
3 | #include "../Node.h"
4 |
5 | class CaseNode : public Node
6 | {
7 |
8 | public:
9 | ExpressionNode *cond;
10 | Node *body;
11 | CaseNode(yy::location loc, ExpressionNode *cond, Node *body) : Node(loc)
12 | {
13 | this->cond = cond;
14 | this->body = body;
15 | }
16 |
17 | bool analyzeSemantic(bool used = false) override
18 | {
19 | auto scopeHelper = ScopeHelper::getInstance();
20 |
21 | if (!scopeHelper->isInsideSwitchScope())
22 | {
23 | Utils::log("case label not within switch statement", loc, "error");
24 | return false;
25 | }
26 |
27 | bool check = true;
28 |
29 | if (cond)
30 | { // case label
31 | check = cond->analyzeSemantic(true);
32 |
33 | if (check && cond->entryType != TYPE_CONST)
34 | {
35 | Utils::log("constant expression required in case label", cond->loc, "error");
36 | check &= false;
37 | }
38 | if (check && !Utils::isIntegerType(cond->type))
39 | {
40 | Utils::log("case quantity not an integer", cond->loc, "error");
41 | check &= false;
42 | }
43 | }
44 |
45 | check &= body->analyzeSemantic();
46 |
47 | return check;
48 | }
49 |
50 | string generateCode() override
51 | {
52 | return "";
53 | }
54 |
55 | ~CaseNode() override
56 | {
57 | delete cond;
58 | cond = nullptr;
59 | delete body;
60 | body = nullptr;
61 | }
62 | };
63 | #endif
--------------------------------------------------------------------------------
/src/nodes/conditions/IfElseCondNode.h:
--------------------------------------------------------------------------------
1 | #ifndef IF_COND_NODE
2 | #define IF_COND_NODE
3 | #include "../Node.h"
4 |
5 | class IfElseCondNode : public Node
6 | {
7 | ExpressionNode *cond;
8 | Node *ifBody;
9 | Node *elseBody;
10 |
11 | public:
12 | IfElseCondNode(yy::location loc, ExpressionNode *cond, Node *ifBody, Node *elseBody = nullptr) : Node(loc)
13 | {
14 | this->cond = cond;
15 | this->ifBody = ifBody;
16 | this->elseBody = elseBody;
17 | }
18 |
19 | bool analyzeSemantic(bool used = false) override
20 | {
21 | auto scopeHelper = ScopeHelper::getInstance();
22 |
23 | if (scopeHelper->isInsideGlobalScope())
24 | {
25 | Utils::log("if statement is not allowed in global scope", loc, "error");
26 | return false;
27 | }
28 |
29 | bool check = true;
30 | scopeHelper->pushScope(SCOPE_IF, this);
31 |
32 | if (!(cond->analyzeSemantic(true) && ifBody->analyzeSemantic()))
33 | check &= false;
34 |
35 | if (cond->type == DTYPE_VOID)
36 | {
37 | Utils::log("invalid conversion from '" + Utils::typeToQuad(cond->type) + "' to 'bool'", cond->loc, "error");
38 | check &= false;
39 | }
40 |
41 | if (elseBody != nullptr)
42 | {
43 | if (!elseBody->analyzeSemantic())
44 | check &= false;
45 | }
46 |
47 | scopeHelper->popScope();
48 |
49 | return check;
50 | }
51 |
52 | string generateCode() override
53 | {
54 | /*
55 | -------------COND------------
56 | JMPZ L1
57 | -------------BODY------------
58 |
59 | L1:
60 | ------COND-NOT-SATISFIED-----
61 |
62 | =============================
63 | --------------OR-------------
64 | =============================
65 |
66 | -------------COND------------
67 | JMPZ L1
68 | -------------BODY------------
69 | JMP L2
70 |
71 | L1: (ELSE)
72 | ------COND-NOT-SATISFIED-----
73 |
74 | L2:
75 | ------COND-SATISFIED-EXIT----
76 |
77 | */
78 |
79 | auto genHelper = CodeGenerationHelper::getInstance();
80 |
81 | string quad;
82 | string l1 = genHelper->getNewLabel();
83 | quad = cond->generateCode();
84 | quad += Utils::opToQuad(OPR_JMPZ, cond->type) + " " + l1 + "\n";
85 | quad += ifBody->generateCode();
86 |
87 | if (elseBody != nullptr)
88 | {
89 | string l2 = genHelper->getNewLabel();
90 | quad += Utils::opToQuad(OPR_JMP, cond->type) + " " + l2 + "\n";
91 | quad += l1 + ":\n";
92 | quad += elseBody->generateCode();
93 | quad += l2 + ":\n";
94 | }
95 | else
96 | {
97 | quad += l1 + ":\n";
98 | }
99 |
100 | return quad;
101 | }
102 |
103 | ~IfElseCondNode() override
104 | {
105 | delete cond;
106 | delete ifBody;
107 | delete elseBody;
108 | cond = nullptr;
109 | ifBody = nullptr;
110 | elseBody = nullptr;
111 | }
112 | };
113 | #endif
--------------------------------------------------------------------------------
/src/nodes/conditions/SwitchCondNode.h:
--------------------------------------------------------------------------------
1 | #ifndef SWITCH_COND_NODE
2 | #define SWITCH_COND_NODE
3 | #include "../Node.h"
4 | #include "CaseNode.h"
5 |
6 | class SwitchCondNode : public Node
7 | {
8 | ExpressionNode *cond;
9 | Node *body;
10 |
11 | vector caseLabels;
12 | vector caseStmts;
13 |
14 | public:
15 | bool hasDefaultLabel;
16 |
17 | SwitchCondNode(yy::location loc, ExpressionNode *cond, Node *body) : Node(loc)
18 | {
19 | this->cond = cond;
20 | this->body = body;
21 | this->hasDefaultLabel = false;
22 | }
23 |
24 | virtual void populate()
25 | {
26 | StmtBlockNode *block = dynamic_cast(body);
27 |
28 | if (block == nullptr)
29 | {
30 | addCaseBlock(body);
31 | return;
32 | }
33 |
34 | for (auto& statement: block->stmtList)
35 | {
36 | addCaseBlock(statement);
37 | }
38 | }
39 |
40 | virtual void addCaseBlock(Node *stmt)
41 | {
42 | CaseNode *caseLabel;
43 |
44 | while (caseLabel = dynamic_cast(stmt))
45 | {
46 | caseLabels.push_back(caseLabel->cond);
47 | caseStmts.emplace_back();
48 |
49 | stmt = caseLabel->body;
50 | }
51 |
52 | if (!caseStmts.empty())
53 | {
54 | caseStmts.back().push_back(stmt);
55 | }
56 | }
57 |
58 | bool analyzeSemantic(bool used = false) override
59 | {
60 | auto scopeHelper = ScopeHelper::getInstance();
61 |
62 | if (scopeHelper->isInsideGlobalScope())
63 | {
64 | Utils::log("switch statement is not allowed in global scope", loc, "error");
65 | return false;
66 | }
67 |
68 | populate();
69 |
70 | bool check = true;
71 | scopeHelper->pushScope(SCOPE_SWITCH, this);
72 |
73 | for (auto& caseLabel: caseLabels)
74 | {
75 | if (caseLabel == nullptr && hasDefaultLabel)
76 | {
77 | Utils::log("multiple default labels in one switch", loc, "error");
78 | check &= false;
79 | break;
80 | } else if (caseLabel == nullptr)
81 | hasDefaultLabel = true;
82 | }
83 |
84 | if (!(cond->analyzeSemantic(true) && body->analyzeSemantic()))
85 | check &= false;
86 |
87 | if (cond->type == DTYPE_VOID)
88 | {
89 | Utils::log("invalid conversion from '" + Utils::typeToQuad(cond->type) + "' to 'bool'", cond->loc, "error");
90 | check &= false;
91 | }
92 |
93 | scopeHelper->popScope();
94 | return check;
95 | }
96 |
97 | string generateCode() override
98 | {
99 | /*
100 | -------------COND------------
101 | JMPZ L1
102 | -------------BODY------------
103 |
104 | L1:
105 | ------COND-NOT-SATISFIED-----
106 |
107 | =============================
108 | --------------OR-------------
109 | =============================
110 |
111 | -------------COND------------
112 | JMPZ L1
113 | -------------BODY------------
114 | JMP L2
115 |
116 | L1: (ELSE)
117 | ------COND-NOT-SATISFIED-----
118 |
119 | L2:
120 | ------COND-SATISFIED-EXIT----
121 |
122 | */
123 |
124 | auto genHelper = CodeGenerationHelper::getInstance();
125 |
126 | string quad;
127 | vector> labelPairs;
128 | string defaultLabel;
129 | string breakLabel = genHelper->getNewLabel();
130 |
131 | quad += cond->generateCode();
132 | quad += Utils::opToQuad(OPR_POP, cond->type) + " SWITCH_COND_" + breakLabel + "\n";
133 | genHelper->addBreakLabel(breakLabel);
134 |
135 | for (auto& caseLabel: caseLabels)
136 | {
137 | string l1 = genHelper->getNewLabel();
138 | if (caseLabel == nullptr)
139 | {
140 | defaultLabel = l1;
141 | labelPairs.emplace_back("", l1);
142 | } else
143 | {
144 | string l2 = genHelper->getNewLabel();
145 | labelPairs.emplace_back(l1, l2);
146 | }
147 | }
148 |
149 | for (int i = 0; i < caseLabels.size(); i++)
150 | {
151 | if (caseLabels[i])
152 | {
153 | DataType resultType = max(cond->type, caseLabels[i]->type);
154 |
155 | quad += labelPairs[i].first + ":\n";
156 | quad += Utils::opToQuad(OPR_PUSH, cond->type) + " SWITCH_COND_" + genHelper->getBreakLabel() + "\n";
157 | quad += Utils::convTypeToQuad(cond->type, resultType);
158 | quad += caseLabels[i]->generateCode();
159 | quad += Utils::convTypeToQuad(caseLabels[i]->type, resultType);
160 | quad += Utils::opToQuad(OPR_EQUAL, resultType) + "\n";
161 | quad += Utils::opToQuad(OPR_JMPZ, DTYPE_BOOL) + " ";
162 |
163 | if (i == caseLabels.size() - 1)
164 | {
165 | quad += (hasDefaultLabel ? defaultLabel : breakLabel) + "\n";
166 | } else if (labelPairs[i + 1].first.empty())
167 | {
168 | quad += ((i + 1 == caseLabels.size() - 1) ? defaultLabel : labelPairs[i + 2].first) + "\n";
169 | } else
170 | { // my next is case
171 | quad += labelPairs[i + 1].first + "\n";
172 | }
173 | }
174 |
175 | quad += labelPairs[i].second + ":\n";
176 |
177 | for (auto& statement: caseStmts[i])
178 | {
179 | quad += statement->generateCode();
180 | }
181 | }
182 |
183 | genHelper->removeBreakLabel();
184 | quad += breakLabel + ":\n";
185 |
186 | return quad;
187 | }
188 |
189 | ~SwitchCondNode() override
190 | {
191 | delete cond;
192 | cond = nullptr;
193 | delete body;
194 | body = nullptr;
195 |
196 | // TODO: Check switch destructor
197 | }
198 | };
199 |
200 | #endif
--------------------------------------------------------------------------------
/src/nodes/expressions/AssignOpNode.h:
--------------------------------------------------------------------------------
1 | #ifndef ASSIGN_OP_NODE
2 | #define ASSIGN_OP_NODE
3 | #include "../Node.h"
4 | #include "IdentifierNode.h"
5 |
6 | class AssignOpNode : public ExpressionNode
7 | {
8 | IdentifierNode *lhs;
9 | ExpressionNode *rhs;
10 |
11 | public:
12 | AssignOpNode(yy::location loc, IdentifierNode *lhs, ExpressionNode *rhs) : ExpressionNode(loc)
13 | {
14 | this->lhs = lhs;
15 | this->rhs = rhs;
16 | }
17 |
18 | bool analyzeSemantic(bool used = false) override
19 | {
20 | auto scopeHelper = ScopeHelper::getInstance();
21 |
22 | if (scopeHelper->isInsideGlobalScope())
23 | {
24 | Utils::log("assign statement is not allowed in global scope", loc, "error");
25 | return false;
26 | }
27 |
28 | if (!(rhs->analyzeSemantic(true) & lhs->analyzeSemantic(false)))
29 | return false;
30 |
31 | if (lhs->type == DTYPE_VOID || rhs->type == DTYPE_VOID)
32 | {
33 | Utils::log("invalid conversion from '" + Utils::typeToQuad(rhs->type) + "' to '" + Utils::typeToQuad(lhs->type) + "'", rhs->loc, "error");
34 | return false;
35 | }
36 |
37 | if (lhs->entryType == TYPE_CONST)
38 | {
39 | Utils::log("assignment of read-only (const) variable '" + lhs->name + "'", lhs->loc, "error");
40 | return false;
41 | }
42 |
43 | EntryInfo *info = scopeHelper->lookup(lhs->name);
44 | info->initialized = true;
45 |
46 | type = lhs->type;
47 | entryType = lhs->entryType;
48 | return true;
49 | }
50 |
51 | string generateCode() override
52 | {
53 | string quad;
54 | quad = rhs->generateCode();
55 | quad += Utils::convTypeToQuad(rhs->type, type);
56 | quad += Utils::opToQuad(OPR_POP, type) + " " + lhs->name + "\n";
57 | return quad;
58 | }
59 |
60 | ~AssignOpNode() override
61 | {
62 | delete lhs;
63 | lhs = nullptr;
64 | delete rhs;
65 | rhs = nullptr;
66 | }
67 | };
68 | #endif
--------------------------------------------------------------------------------
/src/nodes/expressions/BinaryOpNode.h:
--------------------------------------------------------------------------------
1 | #ifndef BINARY_OP_NODE
2 | #define BINARY_OP_NODE
3 |
4 | #include "../Node.h"
5 |
6 | class BinaryOpNode : public ExpressionNode
7 | {
8 | Operator op;
9 | ExpressionNode *lhs;
10 | ExpressionNode *rhs;
11 |
12 | public:
13 | BinaryOpNode(yy::location loc, ExpressionNode *lhs, Operator op, ExpressionNode *rhs) : ExpressionNode(loc)
14 | {
15 | this->lhs = lhs;
16 | this->op = op;
17 | this->rhs = rhs;
18 | }
19 |
20 | bool analyzeSemantic(bool used = false) override
21 | {
22 | auto scopeHelper = ScopeHelper::getInstance();
23 |
24 | if (!(lhs->analyzeSemantic(true) && rhs->analyzeSemantic(true)))
25 | return false;
26 |
27 | if (lhs->type == DTYPE_VOID || rhs->type == DTYPE_VOID)
28 | {
29 | Utils::log("invalid operands of types '" + Utils::typeToQuad(lhs->type) + "' and '" + Utils::typeToQuad(rhs->type) + "'", loc, "error");
30 | return false;
31 | }
32 | if (Utils::isLogical(op))
33 | type = DTYPE_BOOL;
34 | else
35 | type = std::max(lhs->type, rhs->type);
36 |
37 | entryType = (lhs->entryType == EntryType::TYPE_CONST) && (rhs->entryType == EntryType::TYPE_CONST)
38 | ? EntryType::TYPE_CONST
39 | : EntryType::TYPE_VAR;
40 | return true;
41 | }
42 |
43 | string generateCode() override
44 | {
45 | /*
46 | PUSH DATATYPE LHS
47 | PUSH DATATYPE RHS
48 | OPERATION
49 | */
50 | string quad;
51 | DataType op_type = std::max(lhs->type, rhs->type);
52 |
53 | quad = lhs->generateCode();
54 | quad += Utils::convTypeToQuad(lhs->type, op_type);
55 |
56 | quad += rhs->generateCode();
57 | quad += Utils::convTypeToQuad(rhs->type, op_type);
58 |
59 | quad += Utils::opToQuad(op, type) + "\n";
60 |
61 | return quad;
62 | }
63 |
64 | ~BinaryOpNode() override
65 | {
66 | delete lhs;
67 | lhs = nullptr;
68 | delete rhs;
69 | rhs = nullptr;
70 | }
71 | };
72 |
73 | #endif
--------------------------------------------------------------------------------
/src/nodes/expressions/IdentifierNode.h:
--------------------------------------------------------------------------------
1 | #ifndef IDENTIFIER_NODE
2 | #define IDENTIFIER_NODE
3 | #include "../Node.h"
4 |
5 | class IdentifierNode : public ExpressionNode
6 | {
7 | public:
8 | string name;
9 | IdentifierNode(yy::location loc, const string &name) : ExpressionNode(loc)
10 | {
11 | this->name = name;
12 | }
13 |
14 | bool analyzeSemantic(bool used)
15 | {
16 | auto scopeHelper = ScopeHelper::getInstance();
17 |
18 | EntryInfo* info = scopeHelper->lookup(name);
19 | if (!info)
20 | {
21 | Utils::log("'" + name + "' was not declared in this scope", loc, "error");
22 | return false;
23 | }
24 | type = info->type;
25 | entryType = info->entryType;
26 |
27 | if (used)
28 | {
29 | info->used += 1;
30 | }
31 |
32 | if (used && !info->initialized)
33 | {
34 | Utils::log("variable '" + name + "' used without being initialized", loc, "error");
35 | return false;
36 | }
37 | return true;
38 | }
39 |
40 | string generateCode() override
41 | {
42 | return Utils::opToQuad(OPR_PUSH, type) + " " + name + "\n";
43 | }
44 | };
45 | #endif
--------------------------------------------------------------------------------
/src/nodes/expressions/LiteralNode.h:
--------------------------------------------------------------------------------
1 | #ifndef LITERAL_NODE
2 | #define LITERAL_NODE
3 |
4 | #include "../Node.h"
5 |
6 | class LiteralNode : public ExpressionNode
7 | {
8 | string value;
9 |
10 | public:
11 | LiteralNode(yy::location loc, const string &value, DataType type) : ExpressionNode(loc)
12 | {
13 | this->type = type;
14 | this->value = value;
15 | this->entryType = EntryType::TYPE_CONST;
16 | }
17 |
18 | bool analyzeSemantic(bool used = false) override
19 | {
20 | return true;
21 | }
22 |
23 | string generateCode() override
24 | {
25 | return Utils::opToQuad(OPR_PUSH, type) + " " + value + "\n";
26 | }
27 | };
28 |
29 | #endif
--------------------------------------------------------------------------------
/src/nodes/expressions/UnaryOpNode.h:
--------------------------------------------------------------------------------
1 | #ifndef UNARY_OP_NODE
2 | #define UNARY_OP_NODE
3 |
4 | #include "../Node.h"
5 |
6 | class UnaryOpNode : public ExpressionNode
7 | {
8 | Operator op;
9 | ExpressionNode* operand;
10 | bool isUsed = false;
11 |
12 | public:
13 | UnaryOpNode(yy::location loc, Operator op, ExpressionNode* operand) : ExpressionNode(loc)
14 | {
15 | this->op = op;
16 | this->operand = operand;
17 | }
18 |
19 | bool analyzeSemantic(bool used = false) override
20 | {
21 | this->isUsed = used;
22 |
23 | auto scopeHelper = ScopeHelper::getInstance();
24 |
25 | if (!(operand->analyzeSemantic(true)))
26 | return false;
27 |
28 | if (operand->type == DTYPE_VOID)
29 | {
30 | Utils::log("invalid operand of type '" + Utils::typeToQuad(operand->type), loc, "error");
31 | return false;
32 | }
33 |
34 | if (op == OPR_PRE_INC || op == OPR_PRE_DEC || op == OPR_POST_INC || op == OPR_POST_DEC)
35 | {
36 | auto* identifier = dynamic_cast(operand);
37 | if (identifier == nullptr)
38 | {
39 | Utils::log("++/-- can only be applied to variables", loc, "error");
40 | return false;
41 | }
42 |
43 | EntryInfo* info = scopeHelper->lookup(identifier->name);
44 |
45 | if (info && info->entryType == TYPE_FUNC)
46 | {
47 | Utils::log("++/-- cannot be applied to functions", loc, "error");
48 | return false;
49 | }
50 |
51 | if (info && info->entryType == TYPE_CONST)
52 | {
53 | Utils::log("can not use ++/-- on read-only (const) variable '" + identifier->name + "'", loc, "error");
54 | return false;
55 | }
56 | }
57 |
58 | if (Utils::isLogical(op))
59 | type = DTYPE_BOOL;
60 | else
61 | type = operand->type;
62 |
63 | entryType = operand->entryType; // check if constant
64 | return true;
65 | }
66 |
67 | string generateCode() override
68 | {
69 | string quad;
70 |
71 | quad = operand->generateCode();
72 | quad += Utils::convTypeToQuad(operand->type, type);
73 |
74 | auto* identifier = dynamic_cast(operand);
75 |
76 | if (op == OPR_PRE_INC || op == OPR_PRE_DEC)
77 | {
78 | quad += Utils::opToQuad(op, type) + "\n";
79 | quad += Utils::opToQuad(OPR_POP, type) + " " + identifier->name + "\n";
80 | if (isUsed)
81 | quad += Utils::opToQuad(OPR_PUSH, type) + " " + identifier->name + "\n";
82 | } else if (op == OPR_POST_INC || op == OPR_POST_DEC)
83 | {
84 | if (isUsed)
85 | quad += Utils::opToQuad(OPR_PUSH, type) + " " + identifier->name + "\n";
86 | quad += Utils::opToQuad(op, type) + "\n";
87 | quad += Utils::opToQuad(OPR_POP, type) + " " + identifier->name + "\n";
88 | } else
89 | {
90 | quad += Utils::opToQuad(op, type) + "\n";
91 | }
92 |
93 | return quad;
94 | }
95 |
96 | ~UnaryOpNode() override
97 | {
98 | delete operand;
99 | operand = nullptr;
100 | }
101 | };
102 |
103 | #endif
--------------------------------------------------------------------------------
/src/nodes/functions/FunctionCallNode.h:
--------------------------------------------------------------------------------
1 | #ifndef FUNCTION_CALL_NODE
2 | #define FUNCTION_CALL_NODE
3 |
4 | #include
5 | #include
6 | #include
7 |
8 | #include "../../utils/enums.h"
9 | #include "../../utils/utils.h"
10 | #include "../expressions/IdentifierNode.h"
11 | #include "FunctionDeclarationNode.h"
12 |
13 |
14 | typedef vector ExpressionList;
15 |
16 | class FunctionCallNode : public ExpressionNode
17 | {
18 | IdentifierNode* identifier;
19 | ExpressionList args;
20 | std::vector functionParamsTypes;
21 |
22 | public:
23 | FunctionCallNode(yy::location loc, IdentifierNode *identifier, vector args)
24 | : ExpressionNode(loc)
25 | {
26 | this->identifier = identifier;
27 | this->args = std::move(args);
28 | }
29 |
30 | bool analyzeSemantic(bool used = false) override
31 | {
32 | auto scopeHelper = ScopeHelper::getInstance();
33 |
34 | if (scopeHelper->isInsideGlobalScope())
35 | {
36 | Utils::log("function call is not allowed in global scope", loc, "error");
37 | return false;
38 | }
39 |
40 | bool check = true;
41 |
42 | EntryInfo* info = scopeHelper->lookup(identifier->name);
43 | if (!info)
44 | {
45 | Utils::log("'" + identifier->name + "' was not declared in this scope", loc, "error");
46 | check &= false;
47 | } else
48 | {
49 | type = info->type;
50 | entryType = TYPE_CONST;
51 | info->used += 1;
52 | functionParamsTypes = info->paramsTypes;
53 | }
54 |
55 | for (auto& arg: args)
56 | {
57 | check &= arg->analyzeSemantic();
58 | }
59 |
60 | if (args.size() != functionParamsTypes.size())
61 | {
62 | Utils::log("wrong number of arguments", loc, "error");
63 | check &= false;
64 | }
65 |
66 | return check;
67 | }
68 |
69 | string generateCode() override
70 | {
71 | string quad;
72 |
73 | for (int i = (int) args.size() - 1; i >= 0; --i)
74 | {
75 | quad += args[i]->generateCode();
76 | quad += Utils::convTypeToQuad(args[i]->type, functionParamsTypes[i]);
77 | }
78 |
79 | quad += "CALL " + identifier->name + " \n";
80 | return quad;
81 | }
82 |
83 | ~FunctionCallNode() override
84 | {
85 | delete identifier;
86 | identifier = nullptr;
87 | for (auto& arg: args)
88 | {
89 | delete arg;
90 | arg = nullptr;
91 | }
92 |
93 | }
94 | };
95 |
96 | #endif // FUNCTION_CALL_NODE
97 |
--------------------------------------------------------------------------------
/src/nodes/functions/FunctionDeclarationNode.h:
--------------------------------------------------------------------------------
1 | #ifndef FUNCTION_DECLARATION_NODE
2 | #define FUNCTION_DECLARATION_NODE
3 |
4 | #include
5 | #include
6 |
7 | #include "../../utils/enums.h"
8 | #include "../../utils/utils.h"
9 | #include "../statements/VariableDeclarationNode.h"
10 |
11 | typedef vector VarDecList;
12 |
13 | class FunctionDeclarationNode : public Node
14 | {
15 | IdentifierNode* identifier;
16 | Node* body;
17 | EntryType entryType;
18 |
19 | public:
20 | DataType type;
21 | VarDecList params;
22 |
23 | FunctionDeclarationNode(yy::location loc, DataType type, IdentifierNode* identifier,
24 | vector params, Node* body) : Node(loc)
25 | {
26 | this->type = type;
27 | this->identifier = identifier;
28 | this->params = std::move(params);
29 | this->body = body;
30 | this->entryType = TYPE_FUNC;
31 | }
32 |
33 | bool analyzeSemantic(bool used = false) override
34 | {
35 | auto scopeHelper = ScopeHelper::getInstance();
36 |
37 | if (!scopeHelper->isInsideGlobalScope())
38 | {
39 | Utils::log("function declaration is allowed only in global scope", identifier->loc, "error");
40 | return false;
41 | }
42 |
43 | bool check = true;
44 |
45 | std::vector paramsTypes;
46 | for (auto& param: params)
47 | {
48 | paramsTypes.push_back(param->type);
49 | }
50 |
51 | if (!scopeHelper->addSymbol(identifier->loc, identifier->name, type, entryType, paramsTypes, 0, true))
52 | {
53 | Utils::log("'" + identifier->name + "' is already declared", identifier->loc, "error");
54 | check = false;
55 | }
56 |
57 | scopeHelper->pushScope(SCOPE_FUNCTION, this);
58 |
59 | scopeHelper->declareParams = true;
60 |
61 | for (auto& param: params)
62 | {
63 | check &= param->analyzeSemantic();
64 | }
65 |
66 | scopeHelper->declareParams = false;
67 |
68 | check &= body->analyzeSemantic();
69 |
70 | scopeHelper->popScope();
71 |
72 | return check;
73 | }
74 |
75 | string generateCode() override
76 | {
77 | string quad;
78 |
79 | quad += "PROC " + identifier->name + " \n";
80 | for (auto ¶m : params)
81 | {
82 | quad += Utils::opToQuad(OPR_POP, param->type) + " " + param->identifier->name + "\n";
83 | }
84 |
85 | quad += body->generateCode();
86 | quad += "END " + identifier->name + " \n";
87 | return quad;
88 | }
89 |
90 | ~FunctionDeclarationNode() override
91 | {
92 | delete identifier;
93 | delete body;
94 | identifier = nullptr;
95 | body = nullptr;
96 |
97 | for (auto ¶m : params)
98 | {
99 | delete param;
100 | param = nullptr;
101 | }
102 | }
103 | };
104 |
105 | #endif // FUNCTION_DECLARATION_NODE
106 |
--------------------------------------------------------------------------------
/src/nodes/functions/ReturnNode.h:
--------------------------------------------------------------------------------
1 | #ifndef RETURN_NODE
2 | #define RETURN_NODE
3 |
4 | #include
5 | #include
6 | #include
7 |
8 | #include "../../utils/enums.h"
9 | #include "../Node.h"
10 |
11 | class ReturnNode : public Node
12 | {
13 | ExpressionNode *exp;
14 | FunctionDeclarationNode *function;
15 |
16 | public:
17 | ReturnNode(yy::location loc, ExpressionNode* exp) : Node(loc)
18 | {
19 | this->exp = exp;
20 | }
21 |
22 | bool analyzeSemantic(bool used = false) override
23 | {
24 | auto scopeHelper = ScopeHelper::getInstance();
25 |
26 | if (scopeHelper->isInsideGlobalScope())
27 | {
28 | Utils::log("return is not allowed in global scope", loc, "error");
29 | return false;
30 | }
31 |
32 | bool check = true;
33 |
34 | function = scopeHelper->isInsideFunctionScope();
35 | if (!function)
36 | {
37 | Utils::log("return statement not within function", loc, "error");
38 | check &= false;
39 | }
40 |
41 | if (exp && function->type == DTYPE_VOID) {
42 | Utils::log("return statement can not have value in void functions", loc, "error");
43 | check &= false;
44 | }
45 |
46 | if (!exp && function->type != DTYPE_VOID) {
47 | Utils::log("return statement must have value in non-void functions", loc, "error");
48 | check &= false;
49 | }
50 |
51 | if (exp) {
52 | check &= exp->analyzeSemantic(true);
53 | }
54 |
55 | return check;
56 | }
57 |
58 | string generateCode() override
59 | {
60 | string quad;
61 |
62 | if (exp) {
63 | quad += exp->generateCode();
64 | quad += Utils::convTypeToQuad(exp->type, function->type);
65 | }
66 | quad += "RET\n";
67 | return quad;
68 | }
69 |
70 | ~ReturnNode() override
71 | {
72 | delete exp;
73 | exp = nullptr;
74 | }
75 | };
76 |
77 | #endif // RETURN_NODE
78 |
--------------------------------------------------------------------------------
/src/nodes/loops/BreakNode.h:
--------------------------------------------------------------------------------
1 | #ifndef BREAK_NODE
2 | #define BREAK_NODE
3 | #include "../Node.h"
4 |
5 | class BreakNode : public Node
6 | {
7 |
8 | public:
9 | explicit BreakNode(yy::location loc) : Node(loc) {}
10 |
11 | bool analyzeSemantic(bool used = false) override
12 | {
13 | auto scopeHelper = ScopeHelper::getInstance();
14 |
15 | if (!(scopeHelper->isInsideLoopScope() || scopeHelper->isInsideSwitchScope()))
16 | {
17 | Utils::log("break statement not within loop or switch", loc, "error");
18 | return false;
19 | }
20 | return true;
21 | }
22 |
23 | string generateCode() override
24 | {
25 | auto genHelper = CodeGenerationHelper::getInstance();
26 |
27 | string quad;
28 | string l1 = genHelper->getBreakLabel();
29 | quad += Utils::opToQuad(OPR_JMP, DTYPE_INT) + " " + l1 + "\n";
30 |
31 | return quad;
32 | }
33 | };
34 | #endif
--------------------------------------------------------------------------------
/src/nodes/loops/ContinueNode.h:
--------------------------------------------------------------------------------
1 | #ifndef CONTINUE_NODE
2 | #define CONTINUE_NODE
3 | #include "../Node.h"
4 |
5 | class ContinueNode : public Node
6 | {
7 |
8 | public:
9 | explicit ContinueNode(yy::location loc) : Node(loc) {}
10 |
11 | bool analyzeSemantic(bool used = false) override
12 | {
13 | auto scopeHelper = ScopeHelper::getInstance();
14 |
15 | if (!scopeHelper->isInsideLoopScope())
16 | {
17 | Utils::log("continue statement not within loop", loc, "error");
18 | return false;
19 | }
20 | return true;
21 | }
22 |
23 | string generateCode() override
24 | {
25 | auto genHelper = CodeGenerationHelper::getInstance();
26 |
27 | string quad;
28 | string l1 = genHelper->getContinueLabel();
29 | quad += Utils::opToQuad(OPR_JMP, DTYPE_INT) + " " + l1 + "\n";
30 |
31 | return quad;
32 | }
33 | };
34 | #endif
--------------------------------------------------------------------------------
/src/nodes/loops/DoWhileLoopNode.h:
--------------------------------------------------------------------------------
1 | #ifndef DO_WHILE_LOOP_NODE
2 | #define DO_WHILE_LOOP_NODE
3 | #include "../Node.h"
4 |
5 | class DoWhileLoopNode : public Node
6 | {
7 | ExpressionNode *cond;
8 | Node *body;
9 |
10 | public:
11 | DoWhileLoopNode(yy::location loc, ExpressionNode *cond, Node *body) : Node(loc)
12 | {
13 | this->cond = cond;
14 | this->body = body;
15 | }
16 |
17 | bool analyzeSemantic(bool used = false) override
18 | {
19 | auto scopeHelper = ScopeHelper::getInstance();
20 |
21 | if (scopeHelper->isInsideGlobalScope())
22 | {
23 | Utils::log("do-while loop is not allowed in global scope", loc, "error");
24 | return false;
25 | }
26 |
27 | bool check = true;
28 | scopeHelper->pushScope(SCOPE_LOOP, this);
29 |
30 | if (!(cond->analyzeSemantic(true) & body->analyzeSemantic()))
31 | check &= false;
32 |
33 | if (cond->type == DTYPE_VOID)
34 | {
35 | Utils::log("invalid conversion from '" + Utils::typeToQuad(cond->type) + "' to 'bool'", cond->loc, "error");
36 | check &= false;
37 | }
38 |
39 | scopeHelper->popScope();
40 |
41 | return check;
42 | }
43 |
44 | string generateCode() override
45 | {
46 | /*
47 | L1:
48 | ----------DO-BODY-------
49 |
50 | L2: (FOR CONTINUE)
51 | --------WHILE-COND------
52 | JMPNZ L2
53 |
54 | L3: (FOR BREAK)
55 | ----------EXIT----------
56 |
57 | */
58 |
59 | auto genHelper = CodeGenerationHelper::getInstance();
60 |
61 | string quad;
62 | string l1 = genHelper->getNewLabel();
63 | string l2 = genHelper->getNewLabel();
64 | string l3 = genHelper->getNewLabel();
65 |
66 | quad += l1 + ":\n";
67 |
68 | genHelper->addContinueLabel(l2);
69 | genHelper->addBreakLabel(l3);
70 |
71 | quad += body->generateCode();
72 |
73 | genHelper->removeContinueLabel();
74 | genHelper->removeBreakLabel();
75 |
76 | quad += l2 + ":\n";
77 | quad += cond->generateCode();
78 | quad += Utils::opToQuad(OPR_JMPNZ, cond->type) + " " + l1 + "\n";
79 | quad += l3 + ":\n";
80 |
81 | return quad;
82 | }
83 |
84 | ~DoWhileLoopNode() override
85 | {
86 | delete cond;
87 | delete body;
88 |
89 | cond = nullptr;
90 | body = nullptr;
91 | }
92 | };
93 | #endif
--------------------------------------------------------------------------------
/src/nodes/loops/ForLoopNode.h:
--------------------------------------------------------------------------------
1 | #ifndef FOR_LOOP_NODE
2 | #define FOR_LOOP_NODE
3 | #include "../Node.h"
4 | #include "../statements/VariableDeclarationNode.h"
5 |
6 | class ForLoopNode : public Node
7 | {
8 | VariableDeclarationNode *varDec;
9 | ExpressionNode *cond;
10 | ExpressionNode *step;
11 | Node *body;
12 |
13 | public:
14 | ForLoopNode(yy::location loc, VariableDeclarationNode *varDec, ExpressionNode *cond, ExpressionNode *step, Node *body) : Node(loc)
15 | {
16 | this->varDec = varDec;
17 | this->cond = cond;
18 | this->step = step;
19 | this->body = body;
20 | }
21 |
22 | bool analyzeSemantic(bool used = false) override
23 | {
24 | auto scopeHelper = ScopeHelper::getInstance();
25 |
26 | if (scopeHelper->isInsideGlobalScope())
27 | {
28 | Utils::log("for loop is not allowed in global scope", loc, "error");
29 | return false;
30 | }
31 |
32 | bool check = true;
33 | scopeHelper->pushScope(SCOPE_LOOP, this);
34 |
35 | if (!(varDec->analyzeSemantic() & cond->analyzeSemantic(true)
36 | & step->analyzeSemantic() & body->analyzeSemantic()))
37 | {
38 | check &= false;
39 | }
40 |
41 | if (cond->type == DTYPE_VOID)
42 | {
43 | Utils::log("invalid conversion from '" + Utils::typeToQuad(cond->type) + "' to 'bool'", cond->loc, "error");
44 | check &= false;
45 | }
46 |
47 | scopeHelper->popScope();
48 |
49 | return check;
50 | }
51 |
52 | string generateCode() override
53 | {
54 | /*
55 | --------INIT-------
56 | L1:
57 | --------COND-------
58 | JMPZ L3
59 | --------BODY-------
60 |
61 | L2: (FOR CONTINUE)
62 | --------STEP-------
63 | JMP L1
64 |
65 | L3: (FOR BREAK)
66 | --------EXIT-------
67 |
68 | */
69 |
70 | auto genHelper = CodeGenerationHelper::getInstance();
71 |
72 | string quad;
73 | string l1 = genHelper->getNewLabel();
74 | string l2 = genHelper->getNewLabel();
75 | string l3 = genHelper->getNewLabel();
76 |
77 | quad = varDec->generateCode();
78 | quad += l1 + ":\n";
79 | quad += cond->generateCode();
80 | quad += Utils::opToQuad(OPR_JMPZ, cond->type) + " " + l3 + "\n";
81 |
82 | genHelper->addContinueLabel(l2);
83 | genHelper->addBreakLabel(l3);
84 |
85 | quad += body->generateCode();
86 |
87 | genHelper->removeContinueLabel();
88 | genHelper->removeBreakLabel();
89 |
90 | quad += l2 + ":\n";
91 | quad += step->generateCode();
92 | quad += Utils::opToQuad(OPR_JMP, cond->type) + " " + l1 + "\n";
93 | quad += l3 + ":\n";
94 |
95 | return quad;
96 | }
97 |
98 | ~ForLoopNode() override
99 | {
100 | delete varDec;
101 | delete cond;
102 | delete step;
103 | delete body;
104 |
105 | varDec = nullptr;
106 | cond = nullptr;
107 | step = nullptr;
108 | body = nullptr;
109 | }
110 | };
111 | #endif
--------------------------------------------------------------------------------
/src/nodes/loops/WhileLoopNode.h:
--------------------------------------------------------------------------------
1 | #ifndef WHILE_LOOP_NODE
2 | #define WHILE_LOOP_NODE
3 | #include "../Node.h"
4 |
5 | class WhileLoopNode : public Node
6 | {
7 | ExpressionNode *cond;
8 | Node *body;
9 |
10 | public:
11 | WhileLoopNode(yy::location loc, ExpressionNode *cond, Node *body) : Node(loc)
12 | {
13 | this->cond = cond;
14 | this->body = body;
15 | }
16 |
17 | bool analyzeSemantic(bool used = false) override
18 | {
19 | auto scopeHelper = ScopeHelper::getInstance();
20 |
21 | if (scopeHelper->isInsideGlobalScope())
22 | {
23 | Utils::log("while loop is not allowed in global scope", loc, "error");
24 | return false;
25 | }
26 |
27 | bool check = true;
28 | scopeHelper->pushScope(SCOPE_LOOP, this);
29 |
30 | if (!(cond->analyzeSemantic(true) & body->analyzeSemantic()))
31 | check &= false;
32 |
33 | if (cond->type == DTYPE_VOID)
34 | {
35 | Utils::log("invalid conversion from '" + Utils::typeToQuad(cond->type) + "' to 'bool'", cond->loc, "error");
36 | check &= false;
37 | }
38 |
39 | scopeHelper->popScope();
40 |
41 | return true;
42 | }
43 |
44 | string generateCode() override
45 | {
46 | /*
47 | L1: (FOR CONTINUE)
48 | --------WHILE-COND------
49 |
50 | --------WHILE-BODY------
51 |
52 | L2: (FOR BREAK)
53 | ----------EXIT----------
54 |
55 | */
56 |
57 | auto genHelper = CodeGenerationHelper::getInstance();
58 |
59 | string quad;
60 | string l1 = genHelper->getNewLabel();
61 | string l2 = genHelper->getNewLabel();
62 |
63 | quad = l1 + ":\n";
64 | quad += cond->generateCode();
65 | quad += Utils::opToQuad(OPR_JMPZ, cond->type) + " " + l2 + "\n";
66 |
67 | genHelper->addContinueLabel(l1);
68 | genHelper->addBreakLabel(l2);
69 |
70 | quad += body->generateCode();
71 |
72 | genHelper->removeContinueLabel();
73 | genHelper->removeBreakLabel();
74 |
75 | quad += Utils::opToQuad(OPR_JMP, cond->type) + " " + l1 + "\n";
76 | quad += l2 + ":\n";
77 |
78 | return quad;
79 | }
80 |
81 | ~WhileLoopNode() override
82 | {
83 | delete cond;
84 | delete body;
85 |
86 | cond = nullptr;
87 | body = nullptr;
88 | }
89 | };
90 | #endif
--------------------------------------------------------------------------------
/src/nodes/statements/StmtBlockNode.h:
--------------------------------------------------------------------------------
1 | #ifndef BLOCK_NODE
2 | #define BLOCK_NODE
3 |
4 | #include "../../utils/enums.h"
5 | #include "../Node.h"
6 | #include
7 |
8 | class StmtBlockNode : public Node
9 | {
10 | public:
11 | StmtListNode stmtList;
12 |
13 | explicit StmtBlockNode(yy::location loc) : Node(loc) {}
14 |
15 | StmtBlockNode(yy::location loc, const StmtListNode &stmtList) : Node(loc)
16 | {
17 | this->stmtList = stmtList;
18 | }
19 |
20 | bool analyzeSemantic(bool used = false) override
21 | {
22 | auto scopeHelper = ScopeHelper::getInstance();
23 |
24 | if (scopeHelper->isInsideGlobalScope())
25 | {
26 | Utils::log("Block is not allowed in global scope", loc, "error");
27 | return false;
28 | }
29 |
30 | bool check = true;
31 |
32 | scopeHelper->pushScope(SCOPE_BLOCK, this);
33 |
34 | for (auto& statement: stmtList)
35 | {
36 | check &= statement->analyzeSemantic();
37 | }
38 |
39 | scopeHelper->popScope();
40 | return check;
41 | }
42 |
43 | string generateCode() override
44 | {
45 | string quad;
46 |
47 | for (auto& statement: stmtList)
48 | {
49 | quad += statement->generateCode();
50 | }
51 | return quad;
52 | }
53 |
54 | ~StmtBlockNode() override
55 | {
56 | for (auto& statement: stmtList)
57 | {
58 | delete statement;
59 | statement = nullptr;
60 | }
61 | }
62 | };
63 |
64 | #endif
65 |
--------------------------------------------------------------------------------
/src/nodes/statements/VariableDeclarationNode.h:
--------------------------------------------------------------------------------
1 | #ifndef VARIABLE_DECLARATION_NODE
2 | #define VARIABLE_DECLARATION_NODE
3 |
4 | #include "../../utils/enums.h"
5 | #include "../expressions/IdentifierNode.h"
6 | #include
7 |
8 | class VariableDeclarationNode : public Node
9 | {
10 | ExpressionNode *value;
11 | EntryType entryType;
12 |
13 | public:
14 | DataType type;
15 | IdentifierNode *identifier;
16 |
17 | VariableDeclarationNode(yy::location loc, DataType type, IdentifierNode *identifier, ExpressionNode *value = nullptr, bool constant = false)
18 | : Node(loc)
19 | {
20 | this->type = type;
21 | this->identifier = identifier;
22 | this->value = value;
23 | this->entryType = constant ? EntryType::TYPE_CONST : EntryType::TYPE_VAR;
24 | }
25 |
26 | bool analyzeSemantic(bool used = false) override
27 | {
28 | auto scopeHelper = ScopeHelper::getInstance();
29 |
30 | if (type == DTYPE_VOID)
31 | {
32 | Utils::log("Variable '" + identifier->name + "' declared as void", identifier->loc, "error");
33 | return false;
34 | }
35 |
36 | bool initialized = false;
37 |
38 | if (value != nullptr)
39 | {
40 | initialized = true;
41 | if (!value->analyzeSemantic(true))
42 | return false;
43 |
44 | if (value->type == DTYPE_VOID)
45 | {
46 | Utils::log("invalid conversion from '" + Utils::typeToQuad(value->type) + "' to '" + Utils::typeToQuad(type) + "'", value->loc, "error");
47 | return false;
48 | }
49 | }
50 |
51 | if (entryType == TYPE_CONST && value == nullptr)
52 | {
53 | Utils::log("uninitialized const '" + identifier->name + "'", identifier->loc, "error");
54 | return false;
55 | }
56 |
57 | if (scopeHelper->declareParams)
58 | {
59 | initialized = true;
60 | }
61 |
62 | if (!scopeHelper->addSymbol(identifier->loc, identifier->name, type, entryType, {}, 0, initialized))
63 | {
64 | Utils::log("Variable '" + identifier->name + "' is already declared in this scope", identifier->loc, "error");
65 | return false;
66 | }
67 |
68 | return true;
69 | }
70 |
71 | string generateCode() override
72 | {
73 | string quad;
74 | if (value != nullptr)
75 | {
76 | quad += value->generateCode();
77 | quad += Utils::convTypeToQuad(value->type, type);
78 | quad += Utils::opToQuad(OPR_POP, type) + " " + identifier->name + "\n";
79 | }
80 | return quad;
81 | }
82 |
83 | ~VariableDeclarationNode() override
84 | {
85 | delete value;
86 | value = nullptr;
87 | }
88 | };
89 |
90 | #endif // VARIABLE_DECLARATION_NODE
91 |
--------------------------------------------------------------------------------
/src/symbolTable/SymbolTable.cpp:
--------------------------------------------------------------------------------
1 | #include "SymbolTable.h"
2 |
3 |
4 | EntryInfo* SymbolTable::insert(yy::location loc, const std::string &name, DataType type, EntryType entryType, const std::vector ¶msTypes, int used, bool initialized)
5 | {
6 | if (table.find(name) != table.end())
7 | return nullptr;
8 | table[name] = EntryInfo(loc, type, entryType, paramsTypes, used, initialized);
9 | return &(table[name]);
10 | }
11 |
12 | EntryInfo* SymbolTable::lookup(const std::string& name)
13 | {
14 | if (table.find(name) == table.end())
15 | return nullptr;
16 | return &(table[name]);
17 | }
18 |
19 | std::unordered_map SymbolTable::getTable()
20 | {
21 | return table;
22 | }
23 |
--------------------------------------------------------------------------------
/src/symbolTable/SymbolTable.h:
--------------------------------------------------------------------------------
1 | #ifndef __SYMBOL_TABLE__
2 | #define __SYMBOL_TABLE__
3 |
4 | #include
5 | #include
6 | #include
7 | #include
8 | #include "../utils/enums.h"
9 | #include "../utils/utils.h"
10 | #include "location.hpp"
11 | #include
12 | #include
13 |
14 |
15 | struct EntryInfo
16 | {
17 | DataType type;
18 | EntryType entryType;
19 | std::vector paramsTypes; // params of function
20 | yy::location loc;
21 | int used;
22 | bool initialized;
23 |
24 | EntryInfo() = default;
25 |
26 | explicit EntryInfo(yy::location loc, DataType type, EntryType entryType = TYPE_VAR, const std::vector ¶msTypes = {}, int used = 0, bool initialized = false)
27 | {
28 | this->loc = loc;
29 | this->type = type;
30 | this->entryType = entryType;
31 | this->paramsTypes = paramsTypes;
32 | this->used = used;
33 | this->initialized = initialized;
34 | }
35 |
36 | std::string to_string() const
37 | {
38 | std::string kind = (entryType == TYPE_VAR) ? "Variable" : (entryType == TYPE_CONST) ? "Constant" : "Function";
39 |
40 | std::stringstream ss;
41 | ss << std::left;
42 | ss << "datatype: " << std::setw(5) << Utils::typeToQuad(type) << ", ";
43 | ss << "kind: " << std::setw(8) << kind << ", ";
44 | ss << "is_used: " << std::setw(5) << (used ? "true" : "false") << ", ";
45 | ss << "is_initialized: " << std::setw(5) << (initialized ? "true" : "false") << ", ";
46 | ss << "location: " << loc;
47 | return ss.str();
48 | }
49 | };
50 |
51 | class SymbolTable
52 | {
53 | private:
54 | std::unordered_map table;
55 |
56 | public:
57 | SymbolTable() = default;
58 |
59 | EntryInfo* insert(yy::location loc, const std::string& name, DataType type, EntryType entryType = TYPE_VAR,
60 | const std::vector& paramsTypes = {}, int used = 0, bool initialized = false);
61 |
62 | std::unordered_map getTable();
63 |
64 | EntryInfo* lookup(const std::string& name);
65 | };
66 |
67 | #endif //__SYMBOL_TABLE__
--------------------------------------------------------------------------------
/src/utils/enums.h:
--------------------------------------------------------------------------------
1 | #ifndef __ENUMS__H
2 | #define __ENUMS__H
3 |
4 | enum DataType
5 | {
6 | DTYPE_VOID = 100,
7 | DTYPE_BOOL,
8 | DTYPE_CHAR,
9 | DTYPE_INT,
10 | DTYPE_FLOAT
11 | };
12 |
13 | enum EntryType
14 | {
15 | TYPE_VAR = 200,
16 | TYPE_CONST,
17 | TYPE_FUNC,
18 | };
19 |
20 | enum Operator
21 | {
22 | OPR_ASSIGN = 300, // a = b
23 | OPR_ADD, // a + b
24 | OPR_SUB, // a - b
25 | OPR_MUL, // a * b
26 | OPR_DIV, // a / b
27 | OPR_POW, // a ** b
28 | OPR_SHL, // a << 1
29 | OPR_SHR, // a >> 1
30 | OPR_AND, // a && b
31 | OPR_OR, // a || b
32 | OPR_NOT, // !a
33 | OPR_GREATER, // a > b
34 | OPR_GREATER_EQUAL, // a >= b
35 | OPR_LESS, // a < b
36 | OPR_LESS_EQUAL, // a <= b
37 | OPR_EQUAL, // a == b
38 | OPR_NOT_EQUAL, // a != b
39 | OPR_UNARY_MINUS, // -a
40 |
41 | OPR_PRE_INC, // ++a
42 | OPR_PRE_DEC, // --a
43 | OPR_POST_INC, // a++
44 | OPR_POST_DEC, // a--
45 |
46 | OPR_PUSH,
47 | OPR_POP,
48 | OPR_RET,
49 | OPR_JMP,
50 | OPR_JMPZ,
51 | OPR_JMPNZ,
52 | };
53 |
54 | enum ScopeType
55 | {
56 | SCOPE_BLOCK = 400,
57 | SCOPE_FUNCTION,
58 | SCOPE_LOOP,
59 | SCOPE_IF,
60 | SCOPE_SWITCH,
61 | };
62 |
63 | #endif // __ENUMS__H
--------------------------------------------------------------------------------
/src/utils/utils.h:
--------------------------------------------------------------------------------
1 | #ifndef __UTILS__H
2 | #define __UTILS__H
3 | #include "enums.h"
4 | #include
5 | #include
6 | #include
7 |
8 | namespace Utils
9 | {
10 | // Note: If you remove inline keyword, you will have to separate the header and the implementation file
11 | // Otherwise you will get a linker error.
12 | inline bool isLogical(Operator op)
13 | {
14 | return (op >= OPR_AND && op <= OPR_NOT_EQUAL);
15 | }
16 |
17 | inline std::string scopeToString(ScopeType scope)
18 | {
19 | switch (scope)
20 | {
21 | case SCOPE_BLOCK:
22 | return "Block";
23 | case SCOPE_FUNCTION:
24 | return "Function";
25 | case SCOPE_LOOP:
26 | return "Loop";
27 | case SCOPE_IF:
28 | return "If";
29 | case SCOPE_SWITCH:
30 | return "Switch";
31 | default:
32 | return "";
33 | }
34 | }
35 |
36 | inline std::string typeToQuad(DataType type)
37 | {
38 | switch (type)
39 | {
40 | case DTYPE_VOID:
41 | return "VOID";
42 | case DTYPE_BOOL:
43 | return "BOOL";
44 | case DTYPE_CHAR:
45 | return "CHAR";
46 | case DTYPE_INT:
47 | return "INT";
48 | case DTYPE_FLOAT:
49 | return "FLOAT";
50 | default:
51 | return "";
52 | }
53 | }
54 |
55 | inline std::string opToQuad(Operator op, DataType type)
56 | {
57 | switch (op)
58 | {
59 | case OPR_ADD:
60 | return "ADD " + typeToQuad(type);
61 | case OPR_SUB:
62 | return "SUB " + typeToQuad(type);
63 | case OPR_MUL:
64 | return "MUL " + typeToQuad(type);
65 | case OPR_DIV:
66 | return "DIV " + typeToQuad(type);
67 | case OPR_POW:
68 | return "POW " + typeToQuad(type);
69 | case OPR_SHL:
70 | return "SHL " + typeToQuad(type);
71 | case OPR_SHR:
72 | return "SHR " + typeToQuad(type);
73 | case OPR_AND:
74 | return "AND " + typeToQuad(type);
75 | case OPR_OR:
76 | return "OR " + typeToQuad(type);
77 | case OPR_NOT:
78 | return "NOT " + typeToQuad(type);
79 | case OPR_GREATER:
80 | return "GT " + typeToQuad(type);
81 | case OPR_GREATER_EQUAL:
82 | return "GE " + typeToQuad(type);
83 | case OPR_LESS:
84 | return "LT " + typeToQuad(type);
85 | case OPR_LESS_EQUAL:
86 | return "LE " + typeToQuad(type);
87 | case OPR_EQUAL:
88 | return "EQ " + typeToQuad(type);
89 | case OPR_PRE_INC:
90 | case OPR_POST_INC:
91 | return "INC " + typeToQuad(type);
92 | case OPR_PRE_DEC:
93 | case OPR_POST_DEC:
94 | return "DEC " + typeToQuad(type);
95 | case OPR_NOT_EQUAL:
96 | return "NEQ " + typeToQuad(type);
97 | case OPR_PUSH:
98 | return "PUSH " + typeToQuad(type);
99 | case OPR_POP:
100 | return "POP " + typeToQuad(type);
101 | case OPR_RET:
102 | return "RET";
103 | case OPR_JMP:
104 | return "JMP";
105 | case OPR_JMPZ:
106 | return "JMPZ";
107 | case OPR_JMPNZ:
108 | return "JMPNZ";
109 | case OPR_UNARY_MINUS:
110 | return "NEG " + typeToQuad(type);
111 | default:
112 | return "";
113 | }
114 | }
115 |
116 | inline std::string convTypeToQuad(DataType in_type, DataType out_type)
117 | {
118 | return (in_type != out_type ? ("CONV " + typeToQuad(in_type) + " TO " + typeToQuad(out_type) + "\n") : "");
119 | }
120 |
121 | inline std::string replaceTabsWithSpaces(const std::string &str)
122 | {
123 | std::string ret;
124 | ret.reserve(str.size());
125 | for (char c: str)
126 | {
127 | ret += (c == '\t') ? std::string(4, ' ') : std::string(1, c);
128 | }
129 | return ret;
130 | }
131 |
132 | inline bool isIntegerType(DataType type)
133 | {
134 | return (type == DTYPE_BOOL || type == DTYPE_CHAR || type == DTYPE_INT);
135 | }
136 |
137 | inline std::string getLine(const std::string& filename, int line) {
138 | std::ifstream file(filename);
139 | std::string s;
140 |
141 | for (int i = 1; i <= line; i++)
142 | std::getline(file, s);
143 |
144 | return replaceTabsWithSpaces(s);
145 | }
146 |
147 | inline void log(const std::string &message, const yy::location &loc, const std::string &logType)
148 | {
149 | const std::string& sourceCodeLine = getLine(*loc.begin.filename, loc.begin.line);
150 | int endColumn = loc.end.line != loc.begin.line ? sourceCodeLine.length() : loc.end.column;
151 |
152 | fprintf(stderr, "%s:%d:%d: %s: %s\n", loc.begin.filename->c_str(), loc.begin.line, loc.begin.column, logType.c_str(), message.c_str());
153 | fprintf(stderr, "%s\n", sourceCodeLine.c_str());
154 | fprintf(stderr, "%*s", loc.begin.column, "^");
155 | fprintf(stderr, "%s", std::string(std::max(0, endColumn - loc.begin.column - 1), '~').c_str());
156 | fprintf(stderr, "\n");
157 | }
158 |
159 | }
160 |
161 | #endif // __UTILS__H
--------------------------------------------------------------------------------
/tests/test.txt:
--------------------------------------------------------------------------------
1 | void foo() {
2 | //This is a line comment
3 | bool flag = true;
4 | return;
5 | }
6 |
7 | /*
8 | This is a multiline comment
9 | */
10 | int add(int x, char y) {
11 | return x+y;
12 | }
13 |
14 | void main() {
15 | int x = 0;
16 | const char y = 'a';
17 | int z = add(x,y);
18 | if (x==2) {
19 | if (y=='b') {
20 | int x=1;
21 | }
22 | } else {
23 | foo();
24 | z=0;
25 | }
26 | for(int i=0; i<5; i=i+1) {continue;}
27 | while(true){}
28 | do {x = 2<<2;} while(z>0);
29 | switch (y) {
30 | case 'a' : {break;}
31 | case 'b' : {break;}
32 | }
33 | }
--------------------------------------------------------------------------------
/tests/test2.txt:
--------------------------------------------------------------------------------
1 | int x = 4 * 5 + 6 / 2;
2 | const char y = 'c';
3 |
4 | void main(){
5 | if(5 > 3)
6 | {
7 | int x=4;
8 | }
9 | else
10 | {
11 | int z = 2 * x;
12 | }
13 |
14 | while (3 >= 1) {
15 | int r = (4*3 + 5) / 2;
16 | }
17 |
18 | do {
19 | x = x + 4;
20 | } while(y == 1);
21 |
22 | for(int i=0; i<3; i=i+1){
23 | if (i == 1){
24 | int x = 3 + 4;
25 | x = x * 4.3;
26 | break;
27 | }
28 | int h = 3 && 2;
29 | }
30 | const int f = 3;
31 | }
32 |
--------------------------------------------------------------------------------
/tests/test3.txt:
--------------------------------------------------------------------------------
1 | int x = 10;
2 | const float y = 10;
3 |
4 | int main()
5 | {
6 | if(y == 10)
7 | {
8 | x = x * y;
9 | }
10 | else
11 | {
12 | x = x + 1;
13 | }
14 | }
15 |
16 |
--------------------------------------------------------------------------------
/tests/test4.txt:
--------------------------------------------------------------------------------
1 | int foo(float x,float y)
2 | {
3 | return x * y;
4 | }
5 |
6 | int main()
7 | {
8 | int sum = 0;
9 | for(int i = 10; i < 50;i=i+1)
10 | {
11 | sum = sum + foo(i,i*2);
12 | }
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/tests/test5(errors).txt:
--------------------------------------------------------------------------------
1 | // in z = 10
2 |
3 | int x = 5;
4 | int x = 10;
5 |
6 | void foo()
7 | {
8 | return 5;
9 | }
10 |
11 |
12 | char y;
13 |
14 | void foo2()
15 | {
16 | y = y + 1;
17 | }
--------------------------------------------------------------------------------
/tests/test6(bonus).txt:
--------------------------------------------------------------------------------
1 | if(true)
2 | {
3 | }
4 |
5 | void foo(int y, float z)
6 | {
7 | while(true)
8 | {
9 | if(true)
10 | {
11 | continue;
12 | }
13 | break;
14 | }
15 | }
16 |
17 | void main()
18 | {
19 | foo(7);
20 | char y = 'a';
21 | switch (y) {
22 | case 'a' : {break;}
23 | case 'b' : {break;}
24 | default: {break;}
25 | default: {break;}
26 | }
27 | }
--------------------------------------------------------------------------------