A educational compiler written in C++.
SpecterCC follows a classic compiler pipeline:
Source Code
|
Lexer
|
Parser
|
AST
|
Semantic Analyzer
|
Code Generator
|
Assembly
- Lexer: Tokenizes source code into a stream of tokens
- Parser: Constructs an Abstract Syntax Tree (AST) from tokens
- Semantic Analyzer: Type checking and symbol resolution
- Code Generator: Generates x86-64 assembly code
- Basic types: int, float, double, char, bool, void
- Variables and assignments
- Arithmetic operators: +, -, *, /, %
- Comparison operators: ==, !=, <, <=, >, >=
- Logical operators: &&, ||, !
- Control flow: if/else, while
- Functions with parameters and return values
- Block scoping
- C preprocessor integration (#define macros, conditional compilation)
mkdir build && cd build
cmake ..
make./spectercc <input-file> [-o <output-file>] [-S] [-c] [-E] [-P]Options:
-o <file>: Write output to<file>(default:a.outfor executable,out.sfor assembly)-S: Generate assembly only (stops before assembling)-c: Compile to object file only (stops before linking)-E: Preprocess only (run C preprocessor and output result)-P: Enable preprocessing with system C preprocessor before compilation
Compile to executable (default behavior):
./spectercc examples/simple.spc -o simple
./simpleGenerate assembly only:
./spectercc examples/simple.spc -S -o simple.sGenerate object file only:
./spectercc examples/simple.spc -c -o simple.oUse C preprocessor (for #define macros):
./spectercc myfile.spc -P -o myprogramPreprocess only (debug preprocessor output):
./spectercc myfile.spc -E -o output.iThe compiler now handles assembly and linking internally, producing a ready-to-run executable by default!
See the examples/ directory for sample programs:
simple.spc: Basic variable assignmentarithmetic.spc: Arithmetic operations and function callsconditional.spc: If/else statementsloop.spc: While loops and factorial calculation
SpecterCC supports a C-like syntax:
int factorial(int n) {
int result;
result = 1;
while (n > 1) {
result = result * n;
n = n - 1;
}
return result;
}
int main() {
int f;
f = factorial(5);
return f;
}SpecterCC supports C preprocessor directives through integration with the system C preprocessor (gcc -E).
With the -P flag, you can use:
#definefor simple macros#definewith parameters:#define ADD(a,b) ((a)+(b))- Conditional compilation:
#ifdef,#ifndef,#if,#else,#endif - File inclusion:
#include(but see limitations below)
#define MAX_VALUE 100
#define DOUBLE(x) ((x) * 2)
int main() {
int x;
x = DOUBLE(MAX_VALUE);
return x;
}Compile with:
./spectercc myfile.spc -P -o myprogramImportant: While #include <stdio.h> is now acepted, it brings in complex C features (function pointers, complex types, etc.) that SpecterCC doesn't support. Including system headers will likely cause parsing errors.
Recommendation: Use -P for your own #define macros and custom headers, but avoid including standard system headers like stdio.h, stdlib.h, etc.