A simple Swift compiler implementation written in Rust. This project implements a basic lexer, parser, and LLVM code generator for a subset of the Swift programming language.
- Lexer: Tokenizes Swift source code
- Parser: Builds an Abstract Syntax Tree (AST) with operator precedence
- LLVM Code Generator: Generates LLVM IR from the AST
- Native Execution: Compiles and executes code via LLVM toolchain
- Arithmetic Operations: Supports basic math operations (+, -, *, /)
- Variable Declaration: Support for
letdeclarations with type inference - Variable References: Use declared variables in expressions
- Command-line Options: Verbose mode for detailed compilation output
cargo buildcargo run -- example/Test.swiftFor detailed compilation output including tokens, AST, and LLVM IR:
cargo run -- --verbose example/Test.swift
# or
cargo run -- -v example/Test.swift--verboseor-v: Enable verbose output showing all compilation stages
This will:
- Read the Swift source file
- Tokenize the input (Frontend: Lexical Analysis)
- Parse the tokens into an AST (Frontend: Syntax Analysis)
- Generate LLVM IR code (Frontend: IR Generation)
- Save LLVM IR to
target/llvm/output.ll - Execute the code using LLVM toolchain (if installed)
Currently, the compiler supports:
printstatements- Integer literals
- Variable declarations with
let - Variable references in expressions
- Arithmetic expressions (+, -, *, /)
- Expression parsing with operator precedence
- Abstract Syntax Tree (AST) generation
- LLVM IR generation with stack allocation for variables
- Rust 1.56 or later
- Cargo
- LLVM toolchain (optional, for code execution)
brew install llvm
export PATH="/opt/homebrew/opt/llvm/bin:$PATH"sudo apt-get install llvm # Ubuntu/Debian
# or
sudo yum install llvm # RHEL/CentOSTo check for compilation errors without building:
cargo checkThe compiler follows a modular architecture:
-
Frontend (Source → LLVM IR):
lexer.rs: Converts source code into tokensparser.rs: Builds AST from tokens with operator precedencecodegen.rs: Generates LLVM IR from AST
-
Backend (LLVM IR → Execution):
llvm_backend.rs: Handles LLVM toolchain interaction- Saves IR to files
- Executes via LLVM interpreter (lli)
- Can compile to native code (llc + clang)
-
Orchestration:
compiler.rs: Coordinates the compilation pipelinemain.rs: CLI interface
When you run the compiler, it generates:
target/llvm/output.ll- LLVM IR codetarget/llvm/output.s- Assembly code (when using llc)target/llvm/output- Native executable (when using clang)
Apache 2.0