Metadata-Version: 2.4
Name: embeddedpy
Version: 1.0.0
Summary: Write complete C99 using valid Python syntax: compile .py source into full C source files, declaration headers, or linkable libraries — the same program also runs directly under CPython
Author: lubanqihao9875
License-Expression: MIT
Project-URL: Homepage, https://github.com/lubanqihao9875/embeddedpy
Project-URL: Documentation, https://lubanqihao9875.github.io/embeddedpyDocs
Project-URL: Repository, https://github.com/lubanqihao9875/embeddedpy
Project-URL: Issues, https://github.com/lubanqihao9875/embeddedpy/issues
Keywords: embedded,compiler,python-to-c
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Classifier: Topic :: Software Development :: Code Generators
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# embeddedpy

Write **C99** using **Python syntax**.

Source is `.py`: types are imported from `embeddedpy.types`, pointers and memory use a purely functional API, C declaration qualifiers are written as decorators, and preprocessing is written as Python conditional expressions and module-level calls. The compiler turns this source into portable C99 code (a complete program, a declaration header, or a linkable library), where every type definition and every layout is determined solely by the information you write.

Overall principle: **only information known to the user should be written by the user, and written only once**; anything that can be derived from what is already written is computed by the compiler. Every C capability must have a Python shape: operators/expressions go through module functions or methods, declaration qualifiers go through decorators, type construction goes through base classes and parameterized types, preprocessing/text-layer goes through module-level calls; `c.emit(...)` is used for the long tail of C constructs that have no dedicated shape.

## Features

- Fixed-width numeric types: `int8/16/32/64`, `uint8/16/32/64`, `float32/64`
- Single-byte characters: `char` / `schar` / `uchar`
- Fixed-length arrays: `Array[T]` + `make_array(T, N)`; the length is not part of the type
- Purely functional pointer API: `ptr.ref / peek / poke / skip / field / cast / from_int`
- Heap memory: `mem.alloc / free / realloc`; string/byte intermediate values go through two static pools each with an independent upper bound; the total size `arena_cap` and the allocation ratio `arena_manual_ratio` (0..1) are configurable. The automatic pool (frame-based rollback inside function bodies, return-value ownership moved up to the caller) and the manual pool (module-level data, cleared only by `mem.arena_reset()` and not affecting in-function data) have independent capacities
- Aggregate types: whole-assignment `b = a` is rejected at compile time; an independent copy uses `copy_aggregate`; arrays / structs land in compile-time fixed-size C objects, not in the arena and not on the heap
- Aggregate types: `Struct` / `Union` / `Bits[N]`; `@c.packed` and `@c.word(W)` determine layout; storage type and padding are computed by the compiler
- Declaration qualifiers: `@c.inline` / `@c.section("...")` / `@c.aligned(N)` / `@c.weak` / `@c.visibility("...")` / `@c.extern_function`
- C interop: `c.include("x.h")`, `c.extern_type("T")`, `c.typedef(...)`, `c.define(...)`
- Conditional compilation: `if c.defined("X") and c.macro("V") >= 2:` / `elif` / `else` generate `#if / #elif / #else / #endif`; `c.define / c.include` inside the block are emitted in place; `c.pragma / error / warning / undef` are named single-line directives, and `c.emit(...)` is the long-tail fallback
- Byte strings: `b"..."`, `b[0]` yields `uchar` (keeps the byte form, does not participate in arithmetic); an explicit `uint8(b[0])` is needed for numeric use, used for protocol / text parsing
- Enums: `class Mode(Enum)` + `auto()`, members can serve as the compile-time length for `make_array`
- Modifiers: `const[T]` / `volatile[T]` (written in annotations); `sizeof(T)` generates a real `sizeof`
- Bit builtins and barriers: `c.clz / ctz / popcount` use GCC / Clang's `__builtin_*`; `c.barrier()` emits a compiler barrier

## Installation

```bash
pip install embeddedpy
```

## Quick Start

Write a `hello.py`:

```python
from embeddedpy.types import int32

def add(a: int32, b: int32) -> int32:
    return a + b

result: int32 = add(2, 3)
print("2 + 3 =", result)
```

The same file can be run directly or compiled to C:

```bash
python hello.py            # CPython track
embeddedpy build hello.py  # generate C source file
embeddedpy check hello.py  # check only, no file written
```

The output form is chosen by `output_type`: `program`, `header`, `library`.

## Import by Category

Language symbols are split into modules by purpose, one category per line, so you can tell at a glance what each is:

```python
from embeddedpy.types import int32, uint8                     # fixed-width scalars
from embeddedpy.types import Ptr, Func, Struct, Union, Bits  # type construction
from embeddedpy.types import Enum, const, volatile           # enums and qualifiers
from embeddedpy.arrays import make_array                      # fixed-length arrays
from embeddedpy.pointers import ptr                           # pointer API
from embeddedpy.enums import auto                             # enum auto-increment
from embeddedpy.memory import mem, sizeof                     # heap memory and type sizing
from embeddedpy.memory import copy_aggregate                  # aggregate type copies
from embeddedpy.io import io, File                            # file I/O
from embeddedpy.strings import strings                        # text buffers
from embeddedpy.interop import c                             # C interop
```

The compiler validates imported names per module: writing `from embeddedpy.arrays import int32` raises `embeddedpy.arrays has no attribute named int32`; names from different categories are never mixed.

## Two Top-Level Packages: Language Library / Compiler

A single distribution ships both the **library** and the **command**, but the source tree is split into two top-level packages:

| Package | What it is | Used by |
|---|---|---|
| `embeddedpy` | **Language library**: the category modules above | User source via `from embeddedpy.types import int32` |
| `embeddedpy.compiler` | **Compiler**: gates, type checking, code generation, CLI | Command `embeddedpy` / `python -m embeddedpy.compiler`, and host programs |

The dependency direction is "compiler → language library"; the language library does not import the compiler — names imported via `from embeddedpy...` belong to the language semantics layer and do not expose the compiler's internals.

Host program (using the compiler as a library):

```python
from embeddedpy.compiler import compile_file, check_source, CompileConfig
```

Compile to C:

```bash
embeddedpy build hello.py                # writes to build/hello.c by default
embeddedpy build hello.py --output out.c # specify output
embeddedpy check hello.py                # language and type checking only (no file written)
embeddedpy build --help                  # list all options
```

## Multi-File Projects

Multi-file projects are organized with `import`, and namespaces are automatically isolated. Imports resolve from a single project root: for a flat project it is the entry file's directory; for a package project it is derived from the consecutive `__init__.py` chain (the top-level package's parent directory). A dotted name maps to the directory levels under that root, so `lib/filters.py` is imported as `lib.filters`.

Flat sibling modules:

```python
# multi_sensor.py
from embeddedpy.types import int32
def read(p: int32) -> int32:
    return p + 1
```
```python
# main.py
import multi_sensor
from embeddedpy.types import int32
result: int32 = multi_sensor.read(41)
print("multi_sensor.read(41) =", result)
```

Modules under a subdirectory are imported by dotted path; `lib/filters.py` becomes `import lib.filters`:

```python
# lib/filters.py
from embeddedpy.types import int32
def smooth(v: int32) -> int32:
    return v * 2
```
```python
# main.py
import lib.filters
from embeddedpy.types import int32
result: int32 = lib.filters.smooth(3)
print("lib.filters.smooth(3) =", result)
```

The compiler inlines all modules into **the same `.c`**: symbols from imported modules are prefixed with the module key (the dotted path relative to the project root, joined with `__`), combined with the purpose prefix into `f_lib__filters__smooth` / `f_multi_sensor__read` (global variables use the `g_` prefix); the entry module gets no module prefix (the entry module's **top-level statements** are inlined into C's `int main()`). `__` is the module namespace separator; directory names, module names and top-level definition names must not contain it.

Importing a module checks it in full, but the generated C keeps only the top-level functions: `main`, functions referenced by top-level statements, `@c.export` / `@c.extern_function` / `@c.weak` functions, and all the functions they call transitively; the rest are not written into the `.c`. Removal happens after type checking (so type errors in removed functions are still reported), and the whole pass is skipped if the source uses `c.emit` / `c.asm` / `c.goto` / `c.label` — the AST cannot see symbol names embedded in strings, so removal cannot be guaranteed safe.

## Configurable Build Form

What form the compiler produces is decided by `CompileConfig`. There are only three entry points, and the **verb must be written explicitly**:

```bash
embeddedpy build [SOURCE] [options]     # compile entry to C
embeddedpy check [SOURCE] [options]     # check only, no file written
embeddedpy --help                       # help (embeddedpy build --help lists all options)
```

Options have **only long names, no short options** (no `-o` / `-h`).

The 14 settings that determine the output are **configurable in both directions and share the same names** between TOML and the command line: TOML uses snake_case, the command line uses kebab-case.

| `[tool.embeddedpy]` key | command line |
|---|---|
| `source` | positional argument `SOURCE` |
| `line_output` | `--line-output {noline,line,both}` |
| `output_type` | `--output-type {program,header,library}` |
| `output` | `--output PATH` |
| `output_dir` | `--output-dir DIR` |
| `output_name` | `--output-name NAME` |
| `include` | `--include HEADER` (repeatable) |
| `exclude` | `--exclude HEADER` (repeatable) |
| `assets_dir` | `--assets-dir DIR` |
| `arena_cap` | `--arena-cap N` |
| `arena_manual_ratio` | `--arena-manual-ratio R` |
| `link_script` | `--link-script PATH` |
| `link_flags` | `--link-flags FLAG` (repeatable) |
| `link_libs` | `--link-libs LIB` (repeatable) |

`link_script` points to the link script: the compiler only checks that it exists and copies it to the output directory; after a successful `build` it prints a copyable link command to stderr (`link_flags` / `link_libs` are spliced in, and the compiler is specified by the `CC` environment variable, defaulting to `cc`). **The compiler does not run linking**; when all three are empty, no hint is printed.

For the array-typed `include` / `exclude` / `link_flags` / `link_libs`, providing them on the command line **replaces** the array in the config wholesale rather than appending; if `output` is set then `output_dir` / `output_name` are ignored. `check` and `build` share the same options and the same config, except `check` ignores keys unrelated to output (without error).

```bash
embeddedpy build hello.py --line-output noline   # don't write #line directives, produce clean C
embeddedpy build hello.py --output-dir out       # override output directory
embeddedpy build hello.py --output-name demo     # override output name
```

The compiler reads only the `[tool.embeddedpy]` section of `pyproject.toml` at the project root; if it is not found there, no further lookup is done. Priority: **default < config file < command-line options**.

```toml
[tool.embeddedpy]
line_output = "line"      # noline | line | both
output_type = "program"    # program = complete program, header = declaration set, library = linkable implementation

# output location: directory and name can be configured separately or together
output_dir = "build"      # directory (defaults to build)
output_name = "hello"     # name, without .c (defaults to the source file name)
# output = "build/hello.c"   # or write the full path at once

# include = ["stdio.h", "stdint.h"]   # 8 system headers by default; setting this replaces them wholesale
# exclude = ["math.h"]                # removed from the final set
# arena_cap = 8192                  # total bytes for both pools; lower for embedded, higher for string-heavy use
# arena_manual_ratio = 0.5           # manual-pool fraction (0..1); changing it only adjusts allocation, total RAM unchanged
# link_script = "ld/stm32f4.ld"      # link script: only validated + copied, not linked by the compiler
# link_flags = ["-mcpu=cortex-m4", "-mthumb", "-nostartfiles"]
# link_libs = ["m"]                  # written as -lm each
```

**Relative paths are based on the "config file's directory"**, so `output_dir = "build"` means "project_root/build/", without awkward `../` paths; when there is no config file, the base is the entry file's directory. If `output_dir` is not set it also defaults to `build`; if `output_name` is not set it defaults to the source file name (`main.py` uses its containing folder name).

## Current Boundaries and Known Limitations

- Dictionaries / sets are not supported; `Str` / `Bytes` have **immutable value semantics**, not mutable buffers
- Arrays are fixed-length (fixed at compile time); variable length relies on `mem.*` heap memory
- `const` on pointer parameters is not supported
- `sizeof` accepts only types, not variables / structs / enums
- **The output only requires C99**: just compile with `cc -std=c99`. Bit builtins, barriers, and declaration qualifiers are GCC / Clang extensions

### Scope of Two-Track Consistency

Two-track consistency means programs that **have runtime output and have equivalent implementations on both tracks** produce byte-for-byte identical output. Capabilities that only take effect on the artifact track are not compared: conditional compilation (`c.defined` / `c.macro`, where the CPython track always takes `else`, a clear branch point), bare preprocessing calls, section descriptors, `@c.export`, declaration qualifiers, link configuration, and `.h` mode. These capabilities have no comparable output on the CPython track, so no mock should be (or needs to be) built for them.

### Known Two-Track Divergence: Scalar Aliasing

`ptr.ref(x)` (`x` is a scalar) gets a value copy on the CPython track, and `ptr.poke` writes to that copy; on the C track it gets `&x` and writes back to the original variable. So after `poke` you **must read with `ptr.peek(p)`** for the two tracks to agree; directly doing `print(x)` diverges (C track shows the new value, CPython track shows the original).

This rule **does not support write-back**: the CPython track hands the `.py` source verbatim to the interpreter, so `ptr.ref` only receives a value and cannot get the variable binding, making write-back impossible. For writable targets, choose array elements, struct fields, or `mem.alloc` heap memory.


### f-string Support Scope

The format spec only supports `[align][0][width][.precision][type]`; floats must explicitly specify the type (`.2f`). `^` centering, `,` thousands separator, `#` prefix, non-zero fill characters, nested fields, and `!r`/`!s`/`!a` conversions are **not supported** and cause a compile-time error; for complex formatting, concatenate strings yourself.

### Naming Constraints for `c.define`

The assignment form requires the macro name and the binding name to match: `N = c.define("N", 4)`; a mismatched name (`a = c.define("b", 1)`) causes a compile-time error. Only when the names match can the macro value be used as a compile-time constant (`make_array(int32, N)`).

A bare call `c.define("N", 4)` only emits one `#define`; the name does not enter scope and does not participate in constant evaluation. A macro name must not collide with the compiler's inlined runtime identifiers (such as `b`, `i`, `py_arena_alloc`, `NULL`), otherwise textual substitution would pollute the generated C — a collision triggers an error.

## Project Links

- [Documentation](https://lubanqihao9875.github.io/embeddedpyDocs)
- [Repository](https://github.com/lubanqihao9875/embeddedpy)
- [Issues](https://github.com/lubanqihao9875/embeddedpy/issues)
