# RPy

> A Python-to-Roblox Luau transpiler. Write game logic in Python; RPy compiles it to Luau that runs natively in Roblox Studio.

## Quick Start

```powershell
# Install
pip install -e ".[dev]"

# Scaffold a new project
rpy setup myproject
cd myproject

# Transpile a file
rpy transpile src/main.py out/main.lua

# Transpile a directory
rpy transpile src/ out/

# Live Sync (Dev Server + Watcher)
rpy live src/ out/

# Validate without writing output
rpy validate src/

# With type annotations
rpy build src/ out/ --typed --verbose
```

## Example

**Python (input):**

```python
from roblox import Instance, workspace, Vector3

class NPC:
    def __init__(self, name, health):
        self.name = name
        self.health = health

    def take_damage(self, amount):
        self.health = self.health - amount
        if self.health <= 0:
            print(f"{self.name} defeated!")

guard = NPC("Guard", 100)
guard.take_damage(30)
```

**Luau (output):**

```lua
-- Generated by RPy — do not edit manually
local _RT = require(script.Parent.python_runtime)
local py_str = _RT.py_str

local NPC = {}
NPC.__index = NPC

function NPC.new(name, health)
    local self = setmetatable({}, NPC)
    self.name = name
    self.health = health
    return self
end

function NPC:take_damage(amount)
    self.health = (self.health - amount)
    if (self.health <= 0) then
        print(("" .. py_str(self.name) .. " defeated!"))
    end
end

local guard = NPC.new("Guard", 100)
guard:take_damage(30)
```

## Supported Python Subset (v1.0.0)

- **Variables & Logic**: Full support for variables, arithmetic, logical comparisons, and ternary operators.
- **Control Flow**: `if` / `elif` / `else`, `while`, and specialized `for i in range()` loops.
- **Functions**: Support for `def`, `return`, `lambda`, and `*args`.
- **Data Structures**: Lists, Dicts, and Tuples with 40+ method remaps to Luau's `table` library.
- **Async & Task**: Built-in `task` module support for `task.wait()`, `task.spawn()`, and `task.delay()`.
- **Standard Library**: Native mapping for `math`, `string`, `table`, `coroutine`, and `debug` libraries.
- **Roblox SDK**: Integrated `roblox` stubs for 100+ services and classes with autocompletion support.
- **Modern OOP**: Single inheritance classes with metatable-based state management.
- **Error Handling**: Full `try` / `except` / `finally` blocks transpiled to Luau `pcall`.
- **Package Management**: Native Wally integration via `rpy install` for Luau dependencies.
- **Intelligence Layer**: Fuzzy property suggestions, flow-sensitive type refinement, and nil-safety diagnostics.
- **Advanced Performance**: Compile-time macros (`@compile_time`), Recursive DCE, CSE, and LICM optimizations.

## Compiler Flags

| Flag | Effect |
|---|---|
| `--typed` | Emit Luau type annotations (`local x: number = 5`) |
| `--fast` | Skip `py_bool()` truthiness shim (Lua semantics) |
| `--no-runtime` | Don't prepend runtime `require()` |
| `--compile-time` | Enable build-time Python execution (Macros) |
| `--debug` | Enable detailed diagnostic logging |
| `--verbose` | Print detailed build output |

| Command | Description |
|---|---|
| `rpy transpile <src> <out>` | Transpile files/directories (Alias: `build`) |
| `rpy validate <src>` | Validate without writing output (Alias: `check`) |
| `rpy setup [dir]` | Scaffold a new RPy project (Alias: `init`) |
| `rpy live <src> <out>` | Real-time Dev Server & Studio Sync (Alias: `watch`) |

## Project Structure

```
RPy/
├── transpiler/          # Compiler pipeline
│   ├── parser.py        # Python source → AST
│   ├── transformer.py   # Scope analysis, import resolution
│   ├── generator.py     # AST → Luau code generation
│   ├── type_inferrer.py # Type inference for --typed mode
│   ├── errors.py        # Custom error hierarchy
│   └── ast_utils.py     # AST utility functions
├── runtime/
│   └── python_runtime.lua  # Luau runtime helpers (40+ functions)
├── sdk/
│   └── roblox.py        # IDE stubs for Roblox APIs (30+ services)
├── cli/
│   └── main.py          # CLI entry point (build/check/init/watch)
├── examples/            # Example RPy scripts
├── docs/                # Documentation
└── tests/               # 280+ unit & integration tests
```

## Documentation

- [`docs/supported_subset.md`](docs/supported_subset.md) — Exact Python feature list
- [`docs/semantic_map.md`](docs/semantic_map.md) — Python → Luau mapping reference
- [`docs/runtime_api.md`](docs/runtime_api.md) — Runtime helper function signatures

## License

MIT
