Skip to content

Repository files navigation

mycc — My C Compiler

A compiler for a subset of C that produces x86-32 assembly (Intel syntax), written in C++. Not finished and abandonded for now. I had another attempt and I tried to write C compiler in python (pythonc project on github) but it is stopped for now as well.

Architecture

The compiler implements a classic pipeline:

Source → [Scanner] → Tokens → [Parser] → AST → [ASTTranslatorX86] → x86-32 Assembly
Component Files Description
Lexer frontend.cpp FSM-based scanner; tokenizes identifiers, decimal/hex/binary/octal/float literals, and whitespace
AST AST.h, AST.cpp Nodes for types, expressions, variable declarations, function definitions, and calls
Code Generator ASTTranslator.h, ASTTranslator.cpp Visitor over the AST; emits x86-32 assembly with stack frame and register management
Assembly Writer AsmWriter.h, AsmWriter.cpp Low-level emitter for x86-32 Intel-syntax instructions and directives

Supported Language Features

  • Types: int (4 bytes), char (1 byte)
  • Expressions: numeric literals, addition
  • Variables: global (BSS section) and local (stack-allocated) variable declarations and assignments
  • Functions: definitions with parameters, local variables, and calls (including external C library functions like putchar, printf)

Building

No build system is included. Compile with:

g++ -std=c++11 *.cpp -o mycc

Running

The compiler currently builds its AST programmatically (parser integration is in progress). Run the binary to emit assembly to stdout:

./mycc

Example output for a program that calls putchar(66) (prints B):

.section .text
.globl main
.type main, @function
main:
    push ebp
    mov ebp, esp
    sub esp, 8
    mov eax, 66
    mov [i], eax
    mov eax, [i]
    push eax
    call putchar
    add esp, 4
    ...

Key Design Notes

  • Visitor pattern cleanly separates AST structure from code generation.
  • Scope stack (GlobVariableContext / LocalVariableContext) tracks global vs. local variable storage.
  • Value hierarchy (AccValue, MemValue, ConstantValue) models where a computed value lives (register, stack, or immediate) to drive register allocation and spilling.
  • Stack slots are 4-byte aligned; the function epilogue uses leave + ret.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages