Skip to main content

Python-to-WebAssembly compiler using WASM GC

Project description

p2w - Python to WebAssembly Compiler

p2w compiles a substantial subset of Python to WebAssembly, leveraging WASM GC for automatic memory management.

Features

Supported Python Features

  • Data types: integers (arbitrary precision), floats, booleans, strings, bytes, lists, tuples, dicts, sets
  • Control flow: if/elif/else, for/while loops, break/continue, match statements
  • Functions: definitions, default arguments, *args/**kwargs, closures, lambdas, decorators
  • Classes: inheritance, properties, static/class methods, special methods (__init__, __str__, etc.)
  • Comprehensions: list, dict, set, generator expressions
  • Exception handling: try/except/finally, raise, exception chaining
  • Context managers: with statement
  • Generators: yield, generator functions
  • Other: f-strings, type annotations (ignored at runtime), walrus operator, unpacking

JavaScript Interop

p2w provides seamless JavaScript interoperability via the js module:

import js

canvas = js.document.getElementById("chart")
ctx = canvas.getContext("2d")
ctx.fillRect(0, 0, 100, 100)
js.console.log("Hello from Python!")

What Works

Browser Demos

The demos/ directory contains two (somewhat) working browser demos:

  • data-dashboard: Bar chart visualization using Canvas API
  • simulation: Physics simulation with real-time rendering

Golden Programs

The programs/internal/ directory contains 104 test programs covering the supported Python subset. These serve as both regression tests and documentation of working features, including:

  • Classes with inheritance, properties, and special methods
  • Generators and comprehensions
  • Exception handling with chaining
  • Context managers
  • Match statements
  • F-strings and string operations
  • Collection types and methods

Benchmarks

Two benchmark suites validate correctness and measure performance:

programs/benchmarks/ - Classic benchmarks adapted for p2w:

  • fibonacci, primes, sieve, matmul
  • fannkuch, binarytrees, nbody
  • mandelbrot, spectralnorm, fasta
  • pystone

programs/benchmarks-alioth/ - Benchmarks from the Debian Benchmark Game with GCC baseline comparison:

  • binarytrees, nbody, spectralnorm, mandelbrot, fannkuchredux
  • Includes a runner script for automated comparison against GCC (-O3 -ffast-math)

Installation

# Clone the repository
git clone https://git.sr.ht/~sfermigier/p2w
cd p2w

# Install with uv
uv sync

Usage

Command Line

# Compile Python to WAT
uv run p2w source.py > output.wat

# Convert WAT to WASM (requires wabt)
wat2wasm output.wat -o output.wasm

As a Library

from p2w import compile_to_wat

source = """
def fib(n):
    a, b = 0, 1
    for _ in range(n):
        a, b = b, a + b
    return a

print(fib(10))
"""

wat_code = compile_to_wat(source)

Examples

Fibonacci

def fib(n: int) -> int:
    a, b = 0, 1
    for i in range(n):
        a, b = b, a + b
    return a

print(f"fib(30) = {fib(30)}")

Browser Demo

The demos/ directory contains browser examples:

  • data-dashboard: Interactive bar chart visualization
  • simulation: Physics simulation

To run a demo:

cd demos/data-dashboard
make  # Builds app.wasm
# Serve with any HTTP server and open index.html

Development

# Run tests
make test

# Run linting and type checking
make lint

# Format code
make format

# Run tests with coverage
make test-cov

Test Structure

  • tests/a_unit/ - Unit tests
  • tests/b_integration/ - Integration tests
  • tests/c_e2e/ - End-to-end tests

Architecture

p2w follows a straightforward compilation pipeline:

  1. Parse: Python source -> AST (using Python's ast module)
  2. Analyze: Scope analysis, type inference
  3. Compile: AST -> WAT (WebAssembly Text format)
  4. Assemble: WAT -> WASM (via external tools like wat2wasm)

The compiler generates WAT code that uses WASM 3.0 GC features for automatic memory management of Python objects.

Requirements

  • Python 3.12+
  • wabt (for wat2wasm)
  • A WASM runtime with GC support (e.g., recent Chrome/Firefox, wasmtime with GC enabled)

Prior Art and References

It's too long at this point to cite every influence and/or alternative. Here are a few that stand out:

License

MIT

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

p2w-0.2.1.tar.gz (195.2 kB view details)

Uploaded Source

Built Distribution

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

p2w-0.2.1-py3-none-any.whl (231.2 kB view details)

Uploaded Python 3

File details

Details for the file p2w-0.2.1.tar.gz.

File metadata

  • Download URL: p2w-0.2.1.tar.gz
  • Upload date:
  • Size: 195.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for p2w-0.2.1.tar.gz
Algorithm Hash digest
SHA256 7c8b41da262bba1b8667e315cf3a1506a7a903fd6b11836f65febcd6c87b521c
MD5 88c7c2882e1b0427d3408b47868e25f8
BLAKE2b-256 c482b0fc27bae80ab7015ce4d1b1b7f7b1749f887a73dcd56f88554c0cbe1ce4

See more details on using hashes here.

File details

Details for the file p2w-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: p2w-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 231.2 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.26 {"installer":{"name":"uv","version":"0.9.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for p2w-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b96af1c8d035a94b02d4441598c994356964bee1ca87b6f7500e895b9c71598d
MD5 ce825cdf8132d68db31375f7b290dd5e
BLAKE2b-256 83f6b7dd552f0d00a910f4d351d86b64b47ad492271455211c1099e45152b724

See more details on using hashes here.

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