Skip to main content

Educational C99 compiler written in Python - compiles C to x86/ARM assembly

Project description

C99 Compiler

An educational C99 compiler written in Python, demonstrating compiler construction principles and C language implementation.

Features

  • Full C99 Support: Implements most C99 language features including:

    • All primitive types (int, char, float, double, void)
    • Pointers, arrays, and multi-dimensional arrays
    • Structs, unions, and enums
    • Function pointers and variadic functions
    • Type qualifiers (const, volatile, restrict)
    • Storage classes (static, extern, auto, register)
    • Preprocessor directives (#define, #include, #ifdef, etc.)
  • Multiple Target Architectures:

    • x86-64 (Intel and AT&T syntax)
    • ARM (32-bit and 64-bit)
  • Comprehensive Testing: 1100+ test cases covering:

    • C99 conformance tests
    • Real-world program compilation
    • Integration tests
    • Unit tests for all compiler phases

Project Structure

.
├── src/
│   ├── lexer/          # Tokenization and lexical analysis
│   ├── parser/         # Syntax analysis and AST construction
│   ├── preprocessor/   # C preprocessor implementation
│   ├── semantic/       # Semantic analysis and type checking
│   ├── ir/             # Intermediate representation
│   ├── codegen/        # Code generation for target architectures
│   │   ├── x86/        # x86-64 code generator
│   │   └── arm/        # ARM code generator
│   └── utils/          # Utility functions and error reporting
├── tests/
│   ├── conformance/    # C99 conformance tests
│   ├── integration/    # End-to-end integration tests
│   └── unit/           # Unit tests for individual components
└── examples/           # Example C programs

Installation

From PyPI (Recommended)

pip install pyc99

From Source

# Clone the repository
git clone https://github.com/scobi84/pyc99.git
cd pyc99

# Install in development mode
pip install -e .

# Or install with development dependencies
pip install -e ".[dev]"

Requirements

  • Python 3.8 or higher
  • click library (installed automatically)

Usage

Compiling a C Program

# Compile to x86-64 assembly
pyc99 input.c -S -o output.s

# Compile for ARM
pyc99 input.c -S -t arm -o output.s

# Compile to object file
pyc99 input.c -c -o output.o

# Compile and link to executable (requires system assembler/linker)
pyc99 input.c -o program

# Compile multiple files
pyc99 main.c utils.c helpers.c -o program

# With optimization
pyc99 input.c -O1 -o program

# Verbose output
pyc99 input.c -v -o program

Command Line Options

Usage: pyc99 [OPTIONS] SOURCE_FILES...

Options:
  -t, --target [x86|arm]          Target architecture (default: x86)
  -o, --output PATH               Output file name
  -O, --optimization [0|1]        Optimization level (default: 0)
  -S, --assembly-only             Generate assembly only
  -c, --compile-only              Generate object file only
  -I, --include PATH              Add include search path
  -v, --verbose                   Verbose output
  -d, --debug                     Debug output
  --stop-after [preprocess|lex|parse|semantic|ir|optimize|codegen]
                                  Stop after specified phase
  --help                          Show this message and exit

Running Tests

# Run all tests
python3 -m pytest tests/

# Run specific test categories
python3 -m pytest tests/conformance/     # C99 conformance tests
python3 -m pytest tests/integration/     # Integration tests
python3 -m pytest tests/unit/            # Unit tests

# Run with verbose output
python3 -m pytest tests/ -v

# Run specific test file
python3 -m pytest tests/conformance/test_c99_expressions.py

Examples

See the examples/ directory for sample C programs:

  • hello_world.c - Basic hello world
  • fibonacci.c - Recursive Fibonacci
  • struct_example.c - Struct usage
  • pointer_example.c - Pointer manipulation
  • And many more...

C99 Compliance

The compiler implements approximately 95% of the C99 standard. See C99_COMPLIANCE_ROADMAP.md for detailed feature coverage.

Implemented Features

✅ All basic types and type qualifiers ✅ Pointers, arrays, and pointer arithmetic ✅ Structs, unions, and enums ✅ Function declarations and definitions ✅ Control flow (if, while, for, switch, etc.) ✅ Operators and expressions ✅ Preprocessor directives ✅ Type casting and conversions ✅ Function pointers ✅ Variadic functions ✅ Inline functions ✅ Compound literals ✅ Designated initializers

Known Limitations

  • Variable-length arrays (VLA) - partial support
  • Some complex declarator combinations
  • _Complex and _Imaginary types not implemented
  • Some edge cases in type compatibility

Architecture

The compiler follows a traditional multi-pass architecture:

  1. Preprocessing: Handles #include, #define, conditional compilation
  2. Lexical Analysis: Tokenizes source code
  3. Parsing: Builds Abstract Syntax Tree (AST)
  4. Semantic Analysis: Type checking, symbol resolution
  5. IR Generation: Converts AST to intermediate representation
  6. Code Generation: Emits target assembly code

Development

Running Individual Compiler Phases

from src.lexer.tokenizer import Tokenizer
from src.parser.parser import Parser
from src.semantic.analyzer import SemanticAnalyzer

# Tokenize
tokenizer = Tokenizer(source_code, "file.c")

# Parse
parser = Parser(tokenizer)
ast = parser.parse_translation_unit()

# Semantic analysis
from src.utils.error_reporter import ErrorReporter
error_reporter = ErrorReporter()
analyzer = SemanticAnalyzer(ast, error_reporter)
analyzer.analyze()

Contributing

This is an educational project demonstrating compiler construction. Feel free to:

  • Report bugs or issues
  • Suggest improvements
  • Add more test cases
  • Improve documentation

License

Educational/Academic use

Acknowledgments

Built as an educational project to demonstrate:

  • Compiler design and implementation
  • C language semantics
  • Code generation techniques
  • Software testing practices

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyc99-0.1.0.tar.gz (229.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyc99-0.1.0-py3-none-any.whl (133.1 kB view details)

Uploaded Python 3

File details

Details for the file pyc99-0.1.0.tar.gz.

File metadata

  • Download URL: pyc99-0.1.0.tar.gz
  • Upload date:
  • Size: 229.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for pyc99-0.1.0.tar.gz
Algorithm Hash digest
SHA256 aaf433bc77d3eb29230c95d7766e387609aa86c25354bc86b98047581fa45cde
MD5 401e11bfdb2a1dc1542c80447405c112
BLAKE2b-256 df02ec96e80ea41721d7b7b70c40d796be1d271abb2b483fb4e15e8c30c5c320

See more details on using hashes here.

File details

Details for the file pyc99-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: pyc99-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 133.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.5

File hashes

Hashes for pyc99-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 3a30f10466f815c745d8879f8fb36d4ffb5efbd229841a4688071f9b5a3bbffe
MD5 0285dc431440739d3a973814866801b6
BLAKE2b-256 443bcc530747b332dc5008c0fc211de3e4a65d7f643294f5783244da5eed4853

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page