Waspy
A Python to WebAssembly compiler written in Rust.

Overview
Waspy translates Python functions into WebAssembly. The implementation supports basic arithmetic operations, control flow, and multiple functions with enhanced type support.
Compilation Pipeline
Overview
&
&
Current Features
- Compiles Python functions to WebAssembly
- Supports multiple functions in a single WebAssembly module
- Compiles multiple files into a single module
- Handles control flow with if/else, while and for loops, including
breakandcontinue - Processes variable declarations and assignments
- Supports type annotations for function parameters and return values
- Enables function calls between compiled functions
- Includes an expanded type system: integers, floats, booleans, strings
- Complete string operations support (slicing, concatenation, 20+ methods, formatting)
- Supports arithmetic operations (
+,-,*,/,%,//,**) - Processes comparison operators (
==,!=,<,<=,>,>=) - Handles boolean operators (
and,or) - Provides improved error handling with detailed error messages
- Performs automatic WebAssembly optimization using Binaryen
- Detects and handles project structure and dependencies
- Supports module-level variables and class definitions with heap-allocated instances — multiple live instances per class, usable as function arguments and return values
- Object-oriented Python: single inheritance with
super(),isinstance/issubclassover the class hierarchy,@staticmethod/@classmethod/@property(with setters),@dataclass(generated__init__/__eq__/__repr__), and abstract base classes viaabc.ABC - Collections: lists, dicts, sets, tuples, and ranges — literals, indexing, methods, and membership (
in/not in), with full-precision f64 elements and hash-table sets - Exception handling with
try/except/finallyandraise - Lambdas, basic closures, and list comprehensions
- Bundled standard library runtime:
sys,os(incl.os.path),math,random,json,re,datetime,logging,collections,itertools,functools
Limitations
- Object instances are never reclaimed — the bump allocator has no
free, so every instance lives until the module is torn down and__del__is not invoked - Collections have a fixed compile-time capacity — growing one past its initial size (e.g.
.appendbeyond a literal's length) overflows into the next region; runtime growth/reallocation is not yet implemented - Generators do not preserve execution state —
yieldcompiles as a placeholder - Closures lack full variable-capture analysis
- Only stdlib modules import; user-written
.pymodules and file I/O are not supported withover a custom context manager does not yet compile (#5)- No garbage collection or reference counting — the bump allocator never frees
Installation
Or add to your Cargo.toml
[dependencies] waspy = "0.12.0"
Quick Start
Using the Library
use compile_python_to_wasm;
With Compiler Options:
use ;
let options = CompilerOptions ;
let wasm = compile_python_to_wasm_with_options?;
Verbosity Levels
Waspy supports different verbosity levels for logging output:
Verbosity::Quiet- Minimal output (errors only)Verbosity::Normal- Standard output (default)Verbosity::Verbose- Detailed outputVerbosity::Debug- Detail for debugging
If your project has --verbose or --debug flags, use the from_flags helper:
use ;
// Map CLI flags to verbosity level
let options = CompilerOptions ;
For multiple files compilation:
use compile_multiple_python_files;
let sources = vec!;
let wasm = compile_multiple_python_files?;
For unoptimized WebAssembly (useful for debugging or further processing):
use compile_python_to_wasm_with_options;
let wasm = compile_python_to_wasm_with_options?;
Compiling Projects:
use compile_python_project;
let wasm = compile_python_project?;
Example Python Code
= 1
= 1
= *
= + 1
return
return
return
Using the Generated WebAssembly
The compiled WebAssembly can be used in various environments:
// Browser or Node.js
.;
Implementation Details
Multiple Functions
Waspy supports multiple function definitions:
- Each function is compiled to a separate WebAssembly function
- All functions are exported with their original names
- Functions can call other functions within the same module
- Functions from multiple files can be compiled into a single module
Type System
The type system now includes:
- Type Annotations: Support for Python's type hints on function params and return values
- Integers: Mapped to WebAssembly's
i32type - Floats: Supported as
f64with conversion toi32when necessary - Booleans: Represented as
i32(0forfalse,1fortrue) - Strings: Support for string operations with compile-time optimization
- Type Coercion: Automatic conversion between compatible types when needed
Control Flow
The compiler supports basic control flow constructs:
- If/Else Statements: Conditional execution using WebAssembly's block and branch instructions
- While and For Loops: Implemented using WebAssembly's loop and branch instructions
- Break and Continue: Early loop exit and next-iteration skip, including correct
behavior when nested inside
if/tryblocks and in nested loops - Comparison Operators: All standard Python comparison operators
- Boolean Operators: Support for
andandorwith short-circuit evaluation
Variable Support
Waspy handles variables through WebAssembly locals:
- Local variables are allocated in the function's local variable space
- Assignment statements modify these locals
- Variables can be statically typed with annotations
- Type inference for variables based on usage
Error Handling
Enhanced error reporting system:
- Detailed error messages with source location information
- Specific error types for different issues (parsing, type errors, etc.)
- Warnings for potential problems that don't prevent compilation
Examples
Waspy includes several examples to demonstrate its functionality:
# Basic compiler example
# Advanced compiler with options
# Multi-file compilation
# Project compilation
# Type system demonstration
Contributing
Contributions are welcome! See CONTRIBUTING.md for details on how to get started.
Roadmap
The path to 1.0 focuses on the remaining correctness and runtime gaps:
- Remaining object-model gaps: virtual dispatch through
self(vtables) and multiple inheritance - Growable collections (runtime reallocation past a literal's fixed capacity) and hashed
dictlookups (sets already use an open-addressing table) - Generators that preserve execution state
- Full closure capture analysis
- User-written
.pymodule imports, module caching, and file I/O - Garbage collection / reference counting for the bump-allocated heap
