A complete compiler for the P language (a Pascal-like teaching language), built end to end: lexer → parser → AST → semantic analyzer → RISC-V code generation. The generated assembly runs on a real RISC-V target.
.p source
│ scanner.l (lex/flex) — tokenize
▼
tokens
│ parser.y (yacc/bison) — parse to a grammar
▼
parse
│ include/AST + lib/AST (Visitor) — build the AST
▼
AST
│ lib/sema/SemanticAnalyzer.cpp — scope & type checking (symbol table)
▼
checked AST
│ lib/codegen/CodeGenerator.cpp — emit RISC-V assembly
▼
RISC-V .S
| Stage | Implementation | What it does |
|---|---|---|
| Lexical analysis | src/scanner.l (235 lines) |
flex scanner: tokens, keywords, literals, comments |
| Syntactic analysis | src/parser.y (798 lines) |
bison grammar for the full P language |
| AST | src/include/AST/ + src/lib/AST/ (17 node types) |
Visitor-pattern AST built during parsing |
| Semantic analysis | src/lib/sema/SemanticAnalyzer.cpp (739 lines) |
scoped symbol table, type checking, error reporting |
| Code generation | src/lib/codegen/CodeGenerator.cpp (541 lines) |
emits RISC-V assembly from the checked AST |
The AST uses the visitor pattern (AstNodeVisitor): the semantic analyzer and code generator are both visitors that walk the same tree, so each stage is decoupled from the node definitions.
- Full front-to-back pipeline — from source text all the way to working RISC-V assembly, passing the course's basic, advance, and bonus test suites (see
test/). - Symbol table with scope management handles nested functions, local vs. global variables, and parameter binding for both type checking and stack-frame layout during codegen.
- RISC-V backend manages register/stack allocation, control flow (if/while/for with generated branch labels), function calls, and I/O.
The project targets a RISC-V toolchain and is built inside the course Docker image:
cd src && make # builds the `compiler` binary (flex + bison + g++)
./compiler <input.p> --save-path <output_dir> # emits RISC-V assembly
# or run the test suite
cd test && makePer-phase design write-ups are in docs/ (phase1_lexical … phase5_codegen).
Coursework for Introduction to Compiler Design at NYCU (Fall 2023), taught by Prof. Yi-Ping You; developed incrementally across five assignments and consolidated here as one project. The lex/yacc scaffolding and test harness were course-provided; the scanner rules, grammar, AST classes, semantic analyzer, and code generator are my own. Cleaned up (generated scanner.c/parser.cpp, build artifacts, and executables removed) and documented for release.