python-cc 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pcc/util.py ADDED
@@ -0,0 +1,121 @@
1
+
2
+ _contracts = {}
3
+
4
+
5
+ class Contract:
6
+ @classmethod
7
+ def __init_subclass__(cls):
8
+ # Apply checked decorator
9
+ _contracts[cls.__name__] = cls
10
+
11
+ @classmethod
12
+ def check(cls, value):
13
+ pass
14
+
15
+ def __set__(self, instance, value):
16
+ print("setting")
17
+ self.check(value)
18
+ instance.__dict__[self.name] = value
19
+
20
+ def __set_name__(self, owner, name):
21
+ print("setting name")
22
+ self.name = name
23
+
24
+
25
+ class Typed(Contract):
26
+ type = None
27
+
28
+ @classmethod
29
+ def check(cls, value):
30
+ assert isinstance(value, cls.type), f'Expected {cls.type}'
31
+ # does this super().check(value) is need?
32
+
33
+
34
+ class Integer(Typed):
35
+ type = int
36
+
37
+ @classmethod
38
+ def check(cls, value):
39
+ print("check Int")
40
+ assert isinstance(value, int), 'Expect Int'
41
+ super().check(value)
42
+
43
+
44
+ class Positive(Typed):
45
+ @classmethod
46
+ def check(cls, value):
47
+ print("check Positive is ", value)
48
+ assert value > 0, 'Must be > 0'
49
+ super().check(value)
50
+
51
+
52
+ class PositiveInteger(Integer, Positive):
53
+ # the super in Inter , and Postivie why
54
+ # what if it super
55
+ pass
56
+
57
+
58
+ from functools import wraps
59
+ from inspect import signature
60
+
61
+
62
+ def checked(func):
63
+ sig = signature(func) # can be bind here
64
+ # ann = func.__annotations__
65
+ ann = ChainMap(
66
+ func.__annotations__,
67
+ func.__globals__.get('__annotations__', {})
68
+ # what the func :dx is __annotations__ in modu
69
+ )
70
+ print("ann is ", ann)
71
+ @wraps(func)
72
+ def wrapper(*args, **kwargs):
73
+ bound = sig.bind(*args, **kwargs)
74
+ for name, val in bound.arguments.items():
75
+ if name in ann:
76
+ print("check ", name)
77
+ ann[name].check(val)
78
+ return func(*args, **kwargs)
79
+ return wrapper
80
+
81
+ from collections import ChainMap
82
+
83
+
84
+ class BaseMeta(type):
85
+ @classmethod
86
+ def __prepare__(cls, *args):
87
+ return ChainMap({}, _contracts)
88
+
89
+ def __new__(meta, name, bases, methods):
90
+ methods = methods.maps[0] # the origin dict
91
+ return super().__new__(meta, name, bases, methods)
92
+
93
+
94
+ class Base(metaclass=BaseMeta):
95
+ @classmethod
96
+ def __init_subclass__(cls):
97
+ # Apply checked decorator
98
+ for name, val in cls.__dict__.items():
99
+ if callable(val):
100
+ setattr(cls, name, checked(val))
101
+
102
+ for name, val in cls.__annotations__.items():
103
+ contract = val()
104
+ contract.__set_name__(cls, name)
105
+ setattr(cls, name, contract)
106
+
107
+ def __init__(self, *args):
108
+ ann = self.__annotations__
109
+ assert len(args) == len(ann), f"Expect"
110
+
111
+ # 3.6 Order
112
+ for name, val in zip(ann, args):
113
+ setattr(self, name, val)
114
+
115
+
116
+ def __repr__(self):
117
+ args = ",".join(repr(getattr(self, name)) for name in self.__annotations__)
118
+ return f'{type(self).__name__}({args})'
119
+
120
+
121
+ print("__contracts ", _contracts)
@@ -0,0 +1,182 @@
1
+ Metadata-Version: 2.4
2
+ Name: python-cc
3
+ Version: 0.0.2
4
+ Summary: Pcc is a c compiler built on python and llvm.
5
+ Project-URL: Homepage, http://pypi.python.org/pypi/pcc/
6
+ License-Expression: BSD-3-Clause
7
+ License-File: LICENSE
8
+ Keywords: c,compiler,llvm,ply
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: click
11
+ Requires-Dist: llvmlite==0.46.0
12
+ Description-Content-Type: text/markdown
13
+
14
+ Pcc
15
+ ====================
16
+
17
+ What is this?
18
+ --------------------
19
+ Pcc is a C compiler based on ply + pycparser + llvmlite + llvm.
20
+ We can run C programs like Python: `pcc test.c` to run C code.
21
+ Pcc was inspired by: https://github.com/eliben/pykaleidoscope.
22
+
23
+ Notice
24
+ --------------------
25
+ 1. Some code skeleton comes from pykaleidoscope.
26
+ 2. ply and pycparser are embedded into this project for debug use.
27
+
28
+ Development
29
+ --------------------
30
+
31
+ Requires Python 3.13+ and [uv](https://docs.astral.sh/uv/).
32
+
33
+ ```bash
34
+ uv sync # install dependencies
35
+ uv run pytest # run all 400+ tests (~10s parallel)
36
+ ```
37
+
38
+ Run pcc
39
+ --------------------
40
+
41
+ ```bash
42
+ # Single file
43
+ uv run pcc hello.c
44
+
45
+ # Multi-file project (auto-collects all .c files, resolves .h includes)
46
+ uv run pcc myproject/
47
+
48
+ # Dump LLVM IR
49
+ uv run pcc --llvmdump test.c
50
+ ```
51
+
52
+ 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.
53
+
54
+ Lua Compilation Goal
55
+ --------------------
56
+
57
+ The target is to compile and run [Lua 5.5.0](https://github.com/lua/lua) using pcc.
58
+
59
+ ```
60
+ projects/lua-5.5.0/ - Lua 5.5.0 source code + Makefile
61
+ projects/lua-5.5.0/testes/ - Lua test suite
62
+ ```
63
+
64
+ ### Test Structure
65
+
66
+ Tests in `tests/test_lua.py` compare three builds:
67
+
68
+ | Build | Method |
69
+ |-------|--------|
70
+ | **pcc** | `onelua.c` → pcc preprocess/parse/codegen → LLVM IR → cc compile+link |
71
+ | **native** | `onelua.c` → `cc -O0` single-file compile |
72
+ | **makefile** | `make` with project Makefile (separate compilation of each .c, static lib + link) |
73
+
74
+ ```bash
75
+ # Run all Lua tests (slow marker, ~5 min with 4 workers)
76
+ uv run pytest tests/test_lua.py -m slow -v -n 4
77
+
78
+ # Individual file compilation through pcc pipeline
79
+ uv run pytest tests/test_lua.py::test_lua_source_compile -v
80
+ # pcc vs native (same onelua.c, test pcc as C compiler)
81
+ uv run pytest tests/test_lua.py::test_pcc_runtime_matches_native -v
82
+ # pcc vs Makefile-built lua (official reference)
83
+ uv run pytest tests/test_lua.py::test_pcc_runtime_matches_makefile -v
84
+ # Lua test suite with Makefile-built binary (baseline)
85
+ uv run pytest tests/test_lua.py::test_makefile_lua_test_suite -v```
86
+
87
+ Note: `heavy.lua` is excluded from automated tests (runs ~2 min+, may timeout). Run manually:
88
+ ```bash
89
+ # Build Makefile lua, then run heavy.lua directly
90
+ cd projects/lua-5.5.0 && make CC=cc CWARNS= MYCFLAGS="-std=c99 -DLUA_USE_MACOSX" MYLDFLAGS= MYLIBS=
91
+ ./lua testes/heavy.lua
92
+ ```
93
+
94
+ Add C test cases
95
+ --------------------
96
+
97
+ ```bash
98
+ # Single file: add to c_tests/ with expected return value
99
+ echo '// EXPECT: 42
100
+ int main(){ return 42; }' > c_tests/mytest.c
101
+
102
+ # Multi-file project: create a directory with main.c
103
+ mkdir c_tests/myproject
104
+ # ... add .c and .h files, main.c must have: // EXPECT: N
105
+
106
+ # Run all C file tests
107
+ uv run pytest tests/test_c_files.py -v
108
+ ```
109
+
110
+ Preprocessor
111
+ --------------------
112
+
113
+ ```c
114
+ #include <stdio.h> // system headers: 133 libc functions auto-declared
115
+ #include "mylib.h" // user headers: read and inline file content
116
+ #define MAX_SIZE 100 // object-like macro
117
+ #define MAX(a,b) ((a)>(b)?(a):(b)) // function-like macro
118
+ #define DEBUG // flag for conditional compilation
119
+ #ifdef / #ifndef / #if / #elif / #else / #endif // conditional compilation
120
+ #if defined(X) && (VERSION >= 3) // expression evaluation with defined()
121
+ #undef NAME // undefine macro
122
+ ```
123
+
124
+ Built-in macros: `NULL`, `EOF`, `EXIT_SUCCESS`, `EXIT_FAILURE`, `RAND_MAX`, `INT_MAX`, `INT_MIN`, `LLONG_MAX`, `CHAR_BIT`, `true`, `false`, `__STDC__`
125
+
126
+ Built-in typedefs: `size_t`, `ssize_t`, `ptrdiff_t`, `va_list`, `FILE`, `time_t`, `clock_t`, `pid_t`
127
+
128
+ Supported C Features
129
+ --------------------
130
+
131
+ ### Types
132
+ `int`, `double`, `float`, `char`, `void`, `unsigned`/`signed`/`long`/`short` (all combinations),
133
+ `size_t`, `int8_t`..`uint64_t`,
134
+ pointers (multi-level), arrays (multi-dim),
135
+ structs (named, anonymous, nested, with array/pointer/function-pointer members, pointer-to-struct),
136
+ unions, enums (with constant expressions), typedef (scalar, struct, pointer, function pointer),
137
+ `static` local variables, `const`/`volatile` qualifiers
138
+
139
+ ### Operators
140
+ - Arithmetic: `+` `-` `*` `/` `%`
141
+ - Bitwise: `&` `|` `^` `<<` `>>`
142
+ - Comparison: `<` `>` `<=` `>=` `==` `!=` (including pointer comparison)
143
+ - Logical: `&&` `||` (short-circuit evaluation)
144
+ - Unary: `-x` `+x` `!x` `~x` `sizeof` `&x` `*p`
145
+ - Increment/Decrement: `++x` `x++` `--x` `x--` (int and pointer, including struct members)
146
+ - Assignment: `=` `+=` `-=` `*=` `/=` `%=` `<<=` `>>=` `&=` `|=` `^=` (including pointer `+=`/`-=`)
147
+ - Ternary: `a ? b : c`
148
+ - Pointer: `p + n`, `p - n`, `p - q`, `p++`, `p[i]`
149
+ - Struct access: `.` and `->` (including nested `a.b.c` and `s->fn(args)`)
150
+ - Chained: `a = b = c = 5`
151
+
152
+ ### Control Flow
153
+ `if` / `else` / `else if`, `while`, `do-while`, `for` (all variants including `for(;;)`),
154
+ `switch` / `case` / `default`, `goto` / `label`, `break`, `continue`, `return`
155
+
156
+ ### Functions
157
+ Definitions, forward declarations, mutual recursion, void functions, variadic (`...`),
158
+ pointer/array arguments, `static` local variables, function pointers (declaration, assignment,
159
+ calling, as parameters, in structs, typedef'd), callback patterns
160
+
161
+ ### Libc Functions (133 total, auto-declared on first use)
162
+
163
+ | Header | Functions |
164
+ |--------|-----------|
165
+ | stdio.h | printf, fprintf, sprintf, snprintf, puts, putchar, getchar, fopen, fclose, fread, fwrite, fseek, ftell, fgets, fputs, scanf, sscanf, ... |
166
+ | stdlib.h | malloc, calloc, realloc, free, abs, labs, atoi, atol, atof, strtol, strtod, rand, srand, exit, abort, qsort, bsearch, getenv, system, ... |
167
+ | string.h | strlen, strcmp, strncmp, strcpy, strncpy, strcat, strncat, strchr, strrchr, strstr, memset, memcpy, memmove, memcmp, memchr, strtok, ... |
168
+ | ctype.h | isalpha, isdigit, isalnum, isspace, isupper, islower, isprint, ispunct, isxdigit, toupper, tolower, ... |
169
+ | math.h | sin, cos, tan, asin, acos, atan, atan2, exp, log, log2, log10, pow, sqrt, cbrt, hypot, ceil, floor, round, trunc, fmod, fabs, ... |
170
+ | time.h | time, clock, difftime |
171
+ | unistd.h | sleep, usleep, read, write, open, close, getpid, getppid |
172
+ | setjmp.h | setjmp, longjmp |
173
+ | signal.h | signal, raise |
174
+
175
+ ### Literals
176
+ Decimal, hex (`0xFF`), octal (`077`), char (`'a'`, `'\n'`), string (`"hello\n"`), double (`3.14`)
177
+
178
+ ### Other
179
+ C comments (`/* */`, `//`), array initializer lists (1D and multi-dim),
180
+ string escape sequences (`\n \t \\ \0 \r`), implicit type promotion (int/char/double/pointer),
181
+ array-to-pointer decay, `NULL` pointer support, opaque/forward-declared structs,
182
+ two-pass codegen (types first, functions second)
@@ -0,0 +1,36 @@
1
+ pcc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ pcc/__main__.py,sha256=3YkyRxX4BusheQG4ZPjRQeizi-JtQm47PJ4Gjg4hN2Q,63
3
+ pcc/pcc.py,sha256=2Br8aTR4FJOWRUnYzJyFYcb2eCGeydZj0A4TfcPBHJg,1263
4
+ pcc/preprocessor.py,sha256=Oyo4jHljOU2keRr_pc3EFkwwBgOyYt22mqTdnf3KjG8,16950
5
+ pcc/project.py,sha256=aftpOUbU4Fdiu4GFddq4imV1LFkaxnZBh4Er79I7qOg,2244
6
+ pcc/util.py,sha256=IY8wvUIYKN1ghueiFZ0p0MaeLsoRk9NfVpK7qX6Ui6w,2925
7
+ pcc/ast/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ pcc/ast/ast.py,sha256=4KnKPR_jTCyQooR7Tp41oRuPkG-pxcon_vFRNQlS23I,5139
9
+ pcc/ast/ast_transforms.py,sha256=Vif7WwLpdQJURrH4Boq9wE65S0j126_3ytFT7q6gDac,3569
10
+ pcc/ast/c_ast.py,sha256=wWtyQlfVOn9GwWx2-5sr7VZdcmhNH2t0MJYMiAxct98,23457
11
+ pcc/codegen/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
12
+ pcc/codegen/c_codegen.py,sha256=E68pyr8emmSu382HLBkM2czYHT1808q4eR1nghLGLKA,174177
13
+ pcc/evaluater/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
14
+ pcc/evaluater/c_evaluator.py,sha256=C_tRzh41YypZ5KP-z47TjKfl-w5OW1syLWvJYdzvolI,7962
15
+ pcc/generator/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ pcc/generator/c_generator.py,sha256=9JxBzfePRt2ftmPLaw6xi1gOFGQ8jBgQo2r_9xJl0eA,13574
17
+ pcc/lex/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ pcc/lex/c_lexer.py,sha256=AV_n9-i2mQG3KTJyPZFTp4JUUxHvFA7swPg1oOiWZc4,14686
19
+ pcc/lex/lexer.py,sha256=r2yyDfjAY4sAjRKEEi37oLDfairo7ywInoNblFHh5XU,2384
20
+ pcc/lex/token.py,sha256=Zpk7ZJwVM2RU0pRdWMzcg7uxH_XmTXcP4Y1CrlB9Xoc,486
21
+ pcc/parse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
22
+ pcc/parse/c_parser.py,sha256=VrDrNCbHWnRFRHBH6rjTnkuz5WL6JtE9vEEEiphITRQ,62187
23
+ pcc/parse/file_parser.py,sha256=KM2f_kMGHtm4RqHs-m-BGgpYmmPsoIYAcOYYjSXn0oA,2531
24
+ pcc/parse/parser.py,sha256=DCyHmsZ754LvwhN70yMAgAe-i8rTRUWogbP35Pwpm4Q,11289
25
+ pcc/parse/plyparser.py,sha256=N6VLwCNfOcyCGJLHoI4MYQB1UCfeW3sXm5w4fLy_g88,1595
26
+ pcc/ply/__init__.py,sha256=aj21cSa-ByoZ6VI8MvmvvBKSeK9-N5HDZzGkzXnRboo,102
27
+ pcc/ply/cpp.py,sha256=ayTgot4U4VqnOU7T0V-JP76JknMr-CdAIRc_IsxXafE,33368
28
+ pcc/ply/ctokens.py,sha256=MKksnN40TehPhgVfxCJhjj_BjL943apreABKYz-bl0Y,3177
29
+ pcc/ply/lex.py,sha256=vNquS8ghLQV8zIUUiXDGgCHiru_UONIvAQulELYuFdU,42889
30
+ pcc/ply/yacc.py,sha256=bfaaw5G1TlmyBFie8eaW9xciGHHPn7LxYDQd6MXDeOA,135805
31
+ pcc/ply/ygen.py,sha256=2JYNeYtrPz1JzLSLO3d4GsS8zJU8jY_I_CR1VI9gWrA,2251
32
+ python_cc-0.0.2.dist-info/METADATA,sha256=IjtRZR_v0qt3ve6bt_MeOx8dHas78x3jsXiJnErE5SE,6971
33
+ python_cc-0.0.2.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
34
+ python_cc-0.0.2.dist-info/entry_points.txt,sha256=uU4oElC1UO58fXUT-dudsgAkE9T_db34M5L0LYrwUP0,37
35
+ python_cc-0.0.2.dist-info/licenses/LICENSE,sha256=YNLCjRnSvfe7qlmCnnpZUjQmXoERoBzLdNJdbE0tATo,1211
36
+ python_cc-0.0.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pcc = pcc.pcc:main
@@ -0,0 +1,25 @@
1
+ This is free and unencumbered software released into the public domain.
2
+
3
+ Anyone is free to copy, modify, publish, use, compile, sell, or
4
+ distribute this software, either in source code form or as a compiled
5
+ binary, for any purpose, commercial or non-commercial, and by any
6
+ means.
7
+
8
+ In jurisdictions that recognize copyright laws, the author or authors
9
+ of this software dedicate any and all copyright interest in the
10
+ software to the public domain. We make this dedication for the benefit
11
+ of the public at large and to the detriment of our heirs and
12
+ successors. We intend this dedication to be an overt act of
13
+ relinquishment in perpetuity of all present and future rights to this
14
+ software under copyright law.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20
+ OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22
+ OTHER DEALINGS IN THE SOFTWARE.
23
+
24
+ For more information, please refer to <http://unlicense.org>
25
+