Skip to main content

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

Project description

C99 Compiler

PyPI version Python 3.11+ License: MIT Tests

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.11 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.1.tar.gz (227.5 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.1-py3-none-any.whl (133.2 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for pyc99-0.1.1.tar.gz
Algorithm Hash digest
SHA256 60135c45c56b4954243f74971d9cc3ce2fa8f0c0e347b55b3a8d15be2dce66d9
MD5 b4e1745d3b5cb7b48907e47e684f046a
BLAKE2b-256 7ee939c37ab5112535640921553cd288fd473c80f9e49010b7d7d6ed2a1f10e1

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for pyc99-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 51bb43702e23fb878487be6b563cf1f41d401a7eb562837751b0bfccf7889831
MD5 ed07a1972ca7ebdcb4f5ada17715534a
BLAKE2b-256 4db9fe159b299e6d8a8405bd1fdbca5b154cb4902ef20d5d0975bf036cd20c5f

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