Skip to main content

Pcc is a c compiler built on python and llvm.

Project description

Pcc

What is this?

Pcc is a C compiler based on ply + pycparser + llvmlite + llvm. We can run C programs like Python: pcc test.c to run C code. Pcc was inspired by: https://github.com/eliben/pykaleidoscope.

Notice

  1. Some code skeleton comes from pykaleidoscope.
  2. ply and pycparser are embedded into this project for debug use.

Development

Requires Python 3.13+ and uv.

uv sync          # install dependencies
uv run pytest    # run all 400+ tests (~10s parallel)

Run pcc

# Single file
uv run pcc hello.c

# Multi-file project (auto-collects all .c files, resolves .h includes)
uv run pcc myproject/

# Dump LLVM IR
uv run pcc --llvmdump test.c

Multi-file projects: put .c and .h files in a directory, one .c must contain main(). Pcc auto-discovers all .c files, merges them, and compiles.

Lua Compilation Goal

The target is to compile and run Lua 5.5.0 using pcc.

projects/lua-5.5.0/         - Lua 5.5.0 source code + Makefile
projects/lua-5.5.0/testes/  - Lua test suite

Test Structure

Tests in tests/test_lua.py compare three builds:

Build Method
pcc onelua.c → pcc preprocess/parse/codegen → LLVM IR → cc compile+link
native onelua.ccc -O0 single-file compile
makefile make with project Makefile (separate compilation of each .c, static lib + link)
# Run all Lua tests (slow marker, ~5 min with 4 workers)
uv run pytest tests/test_lua.py -m slow -v -n 4

# Individual file compilation through pcc pipeline
uv run pytest tests/test_lua.py::test_lua_source_compile -v
# pcc vs native (same onelua.c, test pcc as C compiler)
uv run pytest tests/test_lua.py::test_pcc_runtime_matches_native -v
# pcc vs Makefile-built lua (official reference)
uv run pytest tests/test_lua.py::test_pcc_runtime_matches_makefile -v
# Lua test suite with Makefile-built binary (baseline)
uv run pytest tests/test_lua.py::test_makefile_lua_test_suite -v```

Note: `heavy.lua` is excluded from automated tests (runs ~2 min+, may timeout). Run manually:
```bash
# Build Makefile lua, then run heavy.lua directly
cd projects/lua-5.5.0 && make CC=cc CWARNS= MYCFLAGS="-std=c99 -DLUA_USE_MACOSX" MYLDFLAGS= MYLIBS=
./lua testes/heavy.lua

Add C test cases

# Single file: add to c_tests/ with expected return value
echo '// EXPECT: 42
int main(){ return 42; }' > c_tests/mytest.c

# Multi-file project: create a directory with main.c
mkdir c_tests/myproject
# ... add .c and .h files, main.c must have: // EXPECT: N

# Run all C file tests
uv run pytest tests/test_c_files.py -v

Preprocessor

#include <stdio.h>          // system headers: 133 libc functions auto-declared
#include "mylib.h"          // user headers: read and inline file content
#define MAX_SIZE 100        // object-like macro
#define MAX(a,b) ((a)>(b)?(a):(b))  // function-like macro
#define DEBUG               // flag for conditional compilation
#ifdef / #ifndef / #if / #elif / #else / #endif  // conditional compilation
#if defined(X) && (VERSION >= 3)  // expression evaluation with defined()
#undef NAME                 // undefine macro

Built-in macros: NULL, EOF, EXIT_SUCCESS, EXIT_FAILURE, RAND_MAX, INT_MAX, INT_MIN, LLONG_MAX, CHAR_BIT, true, false, __STDC__

Built-in typedefs: size_t, ssize_t, ptrdiff_t, va_list, FILE, time_t, clock_t, pid_t

Supported C Features

Types

int, double, float, char, void, unsigned/signed/long/short (all combinations), size_t, int8_t..uint64_t, pointers (multi-level), arrays (multi-dim), structs (named, anonymous, nested, with array/pointer/function-pointer members, pointer-to-struct), unions, enums (with constant expressions), typedef (scalar, struct, pointer, function pointer), static local variables, const/volatile qualifiers

Operators

  • Arithmetic: + - * / %
  • Bitwise: & | ^ << >>
  • Comparison: < > <= >= == != (including pointer comparison)
  • Logical: && || (short-circuit evaluation)
  • Unary: -x +x !x ~x sizeof &x *p
  • Increment/Decrement: ++x x++ --x x-- (int and pointer, including struct members)
  • Assignment: = += -= *= /= %= <<= >>= &= |= ^= (including pointer +=/-=)
  • Ternary: a ? b : c
  • Pointer: p + n, p - n, p - q, p++, p[i]
  • Struct access: . and -> (including nested a.b.c and s->fn(args))
  • Chained: a = b = c = 5

Control Flow

if / else / else if, while, do-while, for (all variants including for(;;)), switch / case / default, goto / label, break, continue, return

Functions

Definitions, forward declarations, mutual recursion, void functions, variadic (...), pointer/array arguments, static local variables, function pointers (declaration, assignment, calling, as parameters, in structs, typedef'd), callback patterns

Libc Functions (133 total, auto-declared on first use)

Header Functions
stdio.h printf, fprintf, sprintf, snprintf, puts, putchar, getchar, fopen, fclose, fread, fwrite, fseek, ftell, fgets, fputs, scanf, sscanf, ...
stdlib.h malloc, calloc, realloc, free, abs, labs, atoi, atol, atof, strtol, strtod, rand, srand, exit, abort, qsort, bsearch, getenv, system, ...
string.h strlen, strcmp, strncmp, strcpy, strncpy, strcat, strncat, strchr, strrchr, strstr, memset, memcpy, memmove, memcmp, memchr, strtok, ...
ctype.h isalpha, isdigit, isalnum, isspace, isupper, islower, isprint, ispunct, isxdigit, toupper, tolower, ...
math.h sin, cos, tan, asin, acos, atan, atan2, exp, log, log2, log10, pow, sqrt, cbrt, hypot, ceil, floor, round, trunc, fmod, fabs, ...
time.h time, clock, difftime
unistd.h sleep, usleep, read, write, open, close, getpid, getppid
setjmp.h setjmp, longjmp
signal.h signal, raise

Literals

Decimal, hex (0xFF), octal (077), char ('a', '\n'), string ("hello\n"), double (3.14)

Other

C comments (/* */, //), array initializer lists (1D and multi-dim), string escape sequences (\n \t \\ \0 \r), implicit type promotion (int/char/double/pointer), array-to-pointer decay, NULL pointer support, opaque/forward-declared structs, two-pass codegen (types first, functions second)

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

python_cc-0.0.3.tar.gz (683.1 kB view details)

Uploaded Source

Built Distribution

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

python_cc-0.0.3-py3-none-any.whl (152.4 kB view details)

Uploaded Python 3

File details

Details for the file python_cc-0.0.3.tar.gz.

File metadata

  • Download URL: python_cc-0.0.3.tar.gz
  • Upload date:
  • Size: 683.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for python_cc-0.0.3.tar.gz
Algorithm Hash digest
SHA256 2341ca399dab4e94d0582908ee1ec27b63217c4bc44da196c61b5a836c81b56d
MD5 5220d8baec23e8af270924a52de5b576
BLAKE2b-256 ade94c0d5f55e4f5bebac123ccde6c9fa35576a1b7d0a1e9d47871a8a9b0f670

See more details on using hashes here.

Provenance

The following attestation bundles were made for python_cc-0.0.3.tar.gz:

Publisher: workflow.yml on jiamo/pcc

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file python_cc-0.0.3-py3-none-any.whl.

File metadata

  • Download URL: python_cc-0.0.3-py3-none-any.whl
  • Upload date:
  • Size: 152.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for python_cc-0.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 4fca9f24019f4ea3be520de5a84a6d1d5c13fae078cbdfa22f47d408b968840e
MD5 85c7675b0428979c4b9d4ef250aecd00
BLAKE2b-256 4922f9450961290665e22cc536bf07bf0ab14657c5361729202dc95507aa0946

See more details on using hashes here.

Provenance

The following attestation bundles were made for python_cc-0.0.3-py3-none-any.whl:

Publisher: workflow.yml on jiamo/pcc

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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