Metadata-Version: 2.5
Name: pydorust
Version: 0.1.1
Summary: A Python library inspired by Rust
Project-URL: Homepage, https://git.ruject.fun/RuJect/pydorust
Project-URL: Repository, https://git.ruject.fun/RuJect/pydorust.git
Project-URL: Issues, https://git.ruject.fun/RuJect/pydorust/issues
Author-email: rus07tam <rus07tam+contact@ruject.fun>
License: MIT
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Requires-Dist: exceptiongroup>=1.3.1
Requires-Dist: pytest>=9.1.1
Requires-Dist: typing-extensions>=4.16.0
Description-Content-Type: text/markdown

# pydorust

A Python library bringing Rust programming language paradigms, semantics, and strict typing patterns to Python. Rather than attempting to enforce strict physical memory safety (which is fundamentally limited by Python's nature), `pydorust` is designed to provide familiar Rust semantics and structural patterns like macros, traits, algebraic data types, strict error handling (panics, `Option`, `Result`), and semantic synchronization primitives.

## Installation

```bash
pip install pydorust
```

---

## The Macro System (`pydorust.macros`)

The Macro system brings advanced, abstract metaprogramming to Python, conceptually similar to Rust's macro system. It allows you to transform syntax and generate code dynamically in a secure environment.

### CLI & Plugins

Macros can be evaluated dynamically at runtime, but their true power shines when transforming the Python AST prior to execution. `pydorust` includes a dedicated CLI utility (`python -m pydorust.macros`) and plugins (for `hatch` and `pytest`) to seamlessly expand macros as part of your build step or test suite.

### Core Macro APIs

- **`@m_define`**: The standard decorator used to register an AST macro. It takes a function that accepts a `MacroContext` and AST nodes, and returns transformed AST nodes. This is an imperative way to write macros (directly mutating AST).
- **`@m_define_declarative`**: A specialized, built-in macro used to define *other* macros declaratively using a template approach (inspired by Rust's `macro_rules!`). You write a standard Python function body where arguments act as variables. In the template body, variable references prefixed with `__q_` (e.g., `__q_myvar`) are replaced dynamically by the AST inputs.
- **`@m_decorator`**: A helper that wraps a macro so it can be used directly as a standard Python decorator. Functionally similar to `m_derive`, but utilizes native Python decorator syntax to pass the decorated function/class as the node.
- **`m_derive`**: Invokes a macro and automatically passes the *next* AST node (the one immediately following the `m_derive` call) as the primary node, alongside any additional arguments.
- **`m_call`**: Directly invokes a macro with the provided arguments, where the very first argument explicitly acts as the AST node.

### Example: Defining a Custom Macro

```python
import ast
from pydorust.macros import m_define, MacroContext, MacroResult

@m_define
def compile_error(ctx: MacroContext, node: ast.AST, /, *args: ast.AST) -> MacroResult:
    # Extracts the string literal argument passed to the macro
    msg = ctx.except_literal(str, node)
    raise RuntimeError(
        f"Compile Error at {ctx.filename}:{getattr(node, 'lineno', 1)}: {msg}"
    )

# When expanded via CLI, plugins, or m_call, this raises an error based on the AST provided.
```

---

## Traits System (`pydorust.trait`)

`pydorust` introduces Rust-style **Traits**, allowing you to decouple method definitions from class inheritance. This enables true ad-hoc polymorphism.

- **`Trait`**: The base class for defining new traits. Use decorators like `@trait_method` (for requirements) and `@default_method` (for defaults).
- **`@impl`**: Implements a trait for a specific data type.

### Example: Creating and Implementing a Trait

```python
from pydorust.trait import Trait, impl, trait_method, default_method

class Display(Trait):
    @trait_method
    def fmt(self) -> str: 
        """Required method for formatting."""

    @default_method
    def print(self) -> None:
        """Default provided method."""
        print(self.fmt())

# Implement `Display` for the built-in `int` type!
@impl(Display, for_type=int)
class IntDisplay:
    def fmt(self: int) -> str:
        return f"Integer value: {self}"

# Call the trait method directly
Display.print(42)  # Outputs: Integer value: 42
```

---

## Types (`pydorust.types`)

Rust is famous for eliminating `NullReferenceException` using the `Option` enum and handling errors gracefully using `Result`. `pydorust` implements these explicitly.

### `Option` (Replacing `None`)

```python
from pydorust.types import Option, Some, Null, ret_option

# Using a decorator to convert returns of None into `Null`, and values into `Some`
@ret_option
def divide(a: float, b: float) -> float | None:
    if b == 0.0:
        return None
    return a / b

result: Option[float] = divide(10.0, 2.0)
print(result.unwrap_or(0.0))  # 5.0

bad_result = divide(10.0, 0.0)
print(bad_result.is_null())   # True
```

### `Result` (Replacing Exceptions)

The `Result` module provides `Ok(value)` and `Err(error)`, along with combinators like `.map()`, `.and_then()`, and `.unwrap()` to cleanly chain operations that might fail without massive `try/except` blocks.

---

## Thread Synchronization (`pydorust.sync`)

Provides semantic synchronization primitives mirroring Rust's standard library. While these tools cannot physically isolate or protect the inner state of Python objects from being mutated externally, they enforce semantic structure. By utilizing Context Managers as guards, `pydorust` helps prevent lock leaks and logically synchronizes your concurrent code.

### Example: `Mutex`

```python
import threading
from pydorust.sync import Mutex

# Wrap the data inside the Mutex
data = Mutex([1, 2, 3])

def worker():
    # .lock() returns a MutexGuard. The lock is released when the block exits.
    with data.lock() as guard:
        guard.value.append(4)

t = threading.Thread(target=worker)
t.start(); t.join()

with data.lock() as guard:
    print(guard.value) # [1, 2, 3, 4]
```

*(Also includes `RwLock` for multi-reader / single-writer scenarios).*

---

## Algebraic Data Types (`pydorust.adt`)

Using the `Variant` and `Enum` classes, you can build tagged unions/variants to guarantee data shapes securely.

### Example

```python
from pydorust.adt import Variant, Enum

class Point2D(Variant):
    x: int
    y: int

class Point3D(Variant):
    x: int
    y: int
    z: int

class ShapePoint(Enum):
    D2 = Point2D
    D3 = Point3D

p = ShapePoint.D2(x=10, y=20)
print(isinstance(p, ShapePoint)) # True
```

---

## Other Features

### Unrecoverable Errors (`pydorust.panics`)

Provides deterministic app termination for unrecoverable states.

- `panic("message")`: Immediately terminates the execution.
- `unimplemented()`: Drop-in for missing functionality (crashes if reached).
- `unreachable()`: For code paths that logically shouldn't be executed.

### Unsafe Markers (`pydorust.unsafe`)

In Rust, dangerous operations that break memory safety guarantees must be wrapped in `unsafe {}`. `pydorust` emulates this semantic contract using decorators.

```python
from pydorust.unsafe import unsafe_func, unsafe_call

@unsafe_func
def dangerous_operation():
    print("Doing something unsafe...")

# dangerous_operation()  # type error
unsafe_call(dangerous_operation)
```

### Low-Level Memory (`pydorust.mem`)

Exposes `unsafe` wrappers around `ctypes.pythonapi` memory management tools, granting you direct control over allocations with `alloc(size)` and `free(ptr)`. Always use carefully via `RawBuffer` or explicit `unsafe_call`.
