{"id":50757646,"url":"https://github.com/yumin-chen/wasm-rust","last_synced_at":"2026-06-11T06:32:13.978Z","repository":{"id":330942902,"uuid":"1124515366","full_name":"yumin-chen/wasm-rust","owner":"yumin-chen","description":"Rust-to-WebAssembly compilation system that makes Rust truly WASM-native, not merely a language that targets WebAssembly.","archived":false,"fork":false,"pushed_at":"2025-12-30T10:37:47.000Z","size":325,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-01-10T18:19:59.820Z","etag":null,"topics":["rust","rust-to-wasm","webassembly"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yumin-chen.png","metadata":{"files":{"readme":"ReadMe.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-29T06:37:57.000Z","updated_at":"2025-12-30T10:37:52.000Z","dependencies_parsed_at":"2026-01-01T12:01:15.606Z","dependency_job_id":null,"html_url":"https://github.com/yumin-chen/wasm-rust","commit_stats":null,"previous_names":["yumin-chen/wasm-rust"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/yumin-chen/wasm-rust","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yumin-chen%2Fwasm-rust","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yumin-chen%2Fwasm-rust/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yumin-chen%2Fwasm-rust/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yumin-chen%2Fwasm-rust/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yumin-chen","download_url":"https://codeload.github.com/yumin-chen/wasm-rust/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yumin-chen%2Fwasm-rust/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34186385,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-11T02:00:06.485Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["rust","rust-to-wasm","webassembly"],"created_at":"2026-06-11T06:32:13.027Z","updated_at":"2026-06-11T06:32:13.959Z","avatar_url":"https://github.com/yumin-chen.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# WasmRust — Rust-to-WebAssembly Compiler\n\n**WasmRust** is a research-driven, production-oriented Rust-to-WebAssembly compilation system. It aims to make **Rust truly WASM-native**, not merely a language that targets WebAssembly.\n\nWasmRust extends Rust through **minimal, evidence-based compiler and library enhancements**, closing gaps in binary size, compilation speed, component interoperability, and host friction — all while preserving Rust’s safety guarantees. The focus of WasmRust is on **compilation correctness, binary size, and iteration speed**.\n\n\u003e **Core Principle:**\n\u003e WasmRust = rustc + WASM specialization, not a new language.\n\n---\n\n## ✨ Motivation\n\nDespite Rust’s dominance in the WASM ecosystem (`wasmtime`, `wasmer`, `wit-bindgen`), developers face:\n\n* **Large binaries** – even simple programs can be 35 KB; alternative WASM-first languages can be smaller.\n* **Slow compilation** – LLVM backend + borrow checking slows iteration.\n* **JS interop friction** – glue layers add overhead and complexity.\n* **Steep learning curve** – ownership and lifetimes can be barriers.\n* **WASM Component Model misalignment** – Rust semantics do not always map cleanly to WASM interfaces.\n\nWasmRust asks:\n\n\u003e *What would Rust look like if WASM were a first-class execution model?*\n\n---\n\n## What Is WasmRust?\n\nWasmRust is a **specialized Rust toolchain** that keeps the Rust frontend unchanged (parser, HIR, MIR, borrow checker) and augments code generation for WASM, providing library-level primitives that map directly to WASM concepts.\n\n```text\n┌─────────────────────────────────────────────┐\n│                 rustc frontend              │\n│   (parsing, HIR, MIR, borrow checking)       │\n│                 UNCHANGED                   │\n└───────────────────┬─────────────────────────┘\n                    ▼\n┌─────────────────────────────────────────────┐\n│           WASM-specialized codegen           │\n│   ┌────────────────┬────────────────────┐   │\n│   │ Cranelift WASM │ LLVM WASM           │   │\n│   │ (dev builds)   │ (release builds)    │   │\n│   └────────────────┴────────────────────┘   │\n└─────────────────────────────────────────────┘\n                    ▼\n┌─────────────────────────────────────────────┐\n│         crates/wasm (zero-cost APIs)         │\n│   externref, threads, components, memory    │\n└─────────────────────────────────────────────┘\n```\n---\n\n## 🌍 Design Philosophy\n\n1. **WASM-native semantics**: Model WebAssembly concepts (memory, resources, components) directly.\n2. **Safety without bloat**: Retain Rust’s memory safety while avoiding unnecessary runtime overhead.\n3. **Incremental adoption**: Interoperate with existing Rust, `wasm-bindgen`, and WASI code.\n4. **Global and federated**: Avoid centralized registries and vendor lock-in.\n5. **Evidence-driven**: Features are justified through benchmarks, size, or correctness.\n\n---\n\n## 🏗 Architecture Overview\n\nWasmRust is structured as a **five-layer stack**:\n\n- Layer 5 — **Tooling \u0026 Ecosystem**: Registries, debugging, profiler\n- Layer 4 — **Compiler**: WasmIR, Cranelift, LLVM, PGO\n- Layer 3 — **Runtime Semantics**: Multi-memory, regions, threads\n- Layer 2 — **Component Model**: WIT-native imports/exports\n- Layer 1 — **Core Language** Linear types, effects, concurrency\n\n---\n\n### The 5 Layers in Detail\n\n#### Layer 1 — Core Language Extensions \u0026 `crates/wasm`\n\nThe foundation of WasmRust is the `crates/wasm` library. It is `no_std`, dependency-free, runtime-free, and compiler-agnostic. Most WASM semantics belong at the library boundary, providing the compiler with semantic hooks for optimization and allowing stable Rust users to adopt WASM-first APIs today.\n\n*   **Linear Types**: Enforce use-once semantics for WASM resources to prevent leaks.\n    ```rust\n    #[wasm::linear]\n    struct CanvasContext(wasm::Handle);\n\n    impl CanvasContext {\n        fn draw(\u0026mut self) { /* ... */ }\n        // This consuming method moves ownership, preventing further use.\n        fn into_bitmap(self) -\u003e ImageData { /* ... */ }\n    }\n    ```\n*   **Structured Concurrency**: Scoped threads with automatic joining and lifetime-bound safety.\n    ```rust\n    use wasm::thread::scope;\n\n    #[wasm::export]\n    fn parallel_transform(data: SharedSlice\u003cf32\u003e) -\u003e Result\u003c(), Error\u003e {\n        scope(|s| {\n            for chunk in data.chunks(1000) {\n                s.spawn(|| process(chunk)); // Lifetime tied to scope\n            }\n            // All threads are automatically joined here\n        })?;\n        Ok(())\n    }\n    ```\n*   **Effect System**: Track side effects like JS calls or I/O at the type level to enable optimizations like dead-effect elimination.\n    ```rust\n    #[wasm::effect(js_call, atomic_read)]\n    fn fetch_and_cache(url: \u0026str) -\u003e Result\u003cVec\u003cu8\u003e, Error\u003e {\n        let data = js::fetch(url)?;\n        CACHE.store(url, data);\n        Ok(data)\n    }\n    ```\n##### Why a Separate Crate?\n\n*   Most WebAssembly semantics are best expressed at the library level, not within the compiler.\n*   It allows for the explicit modeling of WebAssembly concepts, such as `externref`, shared memory, and components.\n*   It enables stable Rust users to adopt Wasm-first APIs today.\n*   It provides a semantic hook for the compiler to perform optimizations.\n*   This approach mirrors the evolution of `core`, `alloc`, and `std` as a set of layered abstractions.\n\n* **Linear Types**: Enforce use-once semantics for WASM resources to prevent leaks.\n  ```rust\n  #[wasm::linear]\n  struct CanvasContext(wasm::Handle);\n\n  impl CanvasContext {\n      fn draw(\u0026mut self) { /* ... */ }\n      // This consuming method moves ownership, preventing further use.\n      fn into_bitmap(self) -\u003e ImageData { /* ... */ }\n  }\n  ```\n* **Structured Concurrency**: Scoped threads with automatic joining and lifetime-bound safety.\n  ```rust\n  use wasm::thread::scope;\n\n  #[wasm::export]\n  fn parallel_transform(data: SharedSlice\u003cf32\u003e) -\u003e Result\u003c(), Error\u003e {\n      scope(|s| {\n          for chunk in data.chunks(1000) {\n              s.spawn(|| process(chunk)); // Lifetime tied to scope\n          }\n          // All threads are automatically joined here\n      })?;\n      Ok(())\n  }\n  ```\n* **Effect System**: Track side effects like JS calls or I/O at the type level to enable optimizations like dead-effect elimination.\n  ```rust\n  #[wasm::effect(js_call, atomic_read)]\n  fn fetch_and_cache(url: \u0026str) -\u003e Result\u003cVec\u003cu8\u003e, Error\u003e {\n      let data = js::fetch(url)?;\n      CACHE.store(url, data);\n      Ok(data)\n  }\n  ```\n\n#### Layer 2 — Component Model\n\nTreats WIT as a first-class interface, enabling type-safe, bidirectional Rust ↔ WASM code generation without glue code.\n\n```rust\n#[wasm::wit]\ninterface crypto {\n    resource key-pair {\n        constructor(algorithm: string);\n        sign: func(data: bytes) -\u003e bytes;\n    }\n}\n```\n\n#### Layer 3 — Runtime Semantics\n\n*   **Multi-region memory**: First-class support for data residency and isolation.\n*   **Streaming compilation hints**: Optimize binary layout for faster Time-to-Interactive in browsers.\n\n#### Layer 4 — Compiler Strategy\n\n*   **Cranelift-first dev builds** for fast iteration (~2s for 10k LOC).\n*   **LLVM release builds** for aggressive optimizations, `wasm-opt`, and Profile-Guided Optimization.\n*   **WasmIR**: A stable intermediate representation that captures linearity, reference types, and ownership invariants.\n\n#### Layer 5 — Tooling \u0026 Ecosystem\n\n*   **Federated registries** to avoid centralized lock-in and geopolitical restrictions.\n*   **WASM-aware debugging tools** for memory visualization and inspection.\n\n---\n\n## Core Features\n\n| Feature           | Description                                              |\n| ----------------- | -------------------------------------------------------- |\n| WASM-native types | `ExternRef`, `FuncRef`, `SharedSlice`, `Pod`             |\n| Linear types      | Enforce move-only semantics for WASM resources           |\n| Component Model   | Compiler-verified ABI, WIT bindings                      |\n| JS Interop        | Zero-copy, predictable boundary cost                     |\n| Threading         | Scoped concurrency, fallback in unsupported environments |\n\n---\n\n## Compilation Pipeline\n\n```mermaid\ngraph LR\n    A[Rust Source] --\u003e B[HIR/MIR]\n    B --\u003e C[WasmIR]\n    C --\u003e D{Build Profile}\n    D --\u003e|Dev| E[Cranelift]\n    D --\u003e|Release| F[LLVM]\n    E --\u003e G[Fast WASM]\n    F --\u003e H[Optimized WASM]\n    H --\u003e I[wasm-opt]\n    I --\u003e J[Component Wrapper]\n```\n\n**WasmIR** is a stable intermediate representation that encodes:\n\n*   Linear memory operations with bounds checking.\n*   Reference types (`externref`, `funcref`) with lifetime tracking.\n*   Component Model calling conventions.\n*   Capability annotations for optimization.\n*   Ownership and linearity invariants.\n---\n## Repository Structure\n\n```\nwasm-rust/\n├── compiler/                # rustc extensions \u0026 backends\n│   ├── codegen-cranelift/   # WASM-tuned Cranelift backend\n│   ├── codegen-llvm/        # WASM-optimized LLVM backend\n│   ├── verifier/            # Invariant checker pass [planned]\n│   └── lints/               # wasm-recognition lint group [planned]\n│\n├── crates/\n│   ├── wasm/                # Core zero-cost WASM abstractions\n│   └── wasm-macros/         # Proc macros for Component Model / WIT [planned]\n│\n├── tooling/\n│   └── cargo-wasm/          # WASM-aware Cargo frontend [planned]\n│\n├── docs/\n│   ├── PRD-WasmRust.md      # WasmRust Prouct Requirements Document\n│   ├── TSD-WasmRust.md      # WasmRust Technical Specification Document\n│   ├── SAFETY.md            # Unsafe invariants per type / crate\n│   ├── compiler-contract.md # Formal compiler ↔ crate contracts\n│   ├── RFCs/\n│   └── architecture/\n│\n└── ReadMe.md\n```\n\u003e Each crate has its own `ReadMe.md` and `Safety.md` files that describe its unsafe invariants and compiler contracts.\n\n---\n\n## Incremental Adoption\n\n#### What Works Without WasmRust?\nEverything in `crates/wasm`: it compiles on **stable Rust**, produces valid WASM, and has no dependency on a custom compiler. WasmRust **enhances**, but does not gate, functionality.\n\n#### What Requires the WasmRust Compiler?\nNative Component Model emission, Cranelift-accelerated builds, and advanced optimizations like PGO and WASM-aware thin monomorphization. These cannot be achieved from a library alone.\n\n---\n\n## Contracts \u0026 Governance\n\n*   **Language Surface Contract**: Core (80%): Standard Rust; Extensions (15%): `wasm` crate; Plugins (4%): `-Z` flags; Hard Fork (\u003c1%): Minimal changes if required. Should upstream Rust introduce conflicting changes, a six-month deprecation window with automatic migration tools will be provided.\n*   **Compiler ↔ Crate Contract**: The WasmRust compiler assumes certain invariants when compiling code that uses `crates/wasm`. Unsafe operations must maintain these invariants, which are documented in `SAFETY.md`. The `wasm-recognition` lint group will detect misuses. Key invariants include:\n    *   `ExternRef\u003cT\u003e` and `FuncRef` are opaque handles with valid lifetime markers.\n    *   `SharedSlice\u003cT\u003e` contains only `Pod` types; aliasing and bounds are enforced.\n    *   Linear types (`#[wasm::linear]`) follow move semantics; the compiler assumes no implicit copies.\n    *   Component imports/exports use WIT-derived types; the ABI must match exactly.\n*   **Governance \u0026 Direction**: \n    *   Upstream-friendly design.\n    *   Library APIs stabilize before compiler features.\n    *   Avoids ecosystem fragmentation.\n    *   RFC-driven feature evolution.\n\n---\n\n## Notes on SAFETY.md\n\n* Contains **formal unsafe invariants** per type.\n* Used by the compiler **verifier pass** and **lint group**.\n* Serves as authoritative documentation for both crate users and compiler developers.\n\n---\n\n## Host Profile Support\n\n| Host Profile | Threading                     | JS Interop      | Component Model | Memory Regions |\n| ------------ | ----------------------------- | --------------- | --------------- | -------------- |\n| Browser      | SharedArrayBuffer + COOP/COEP | Direct calls    | Partial         | No             |\n| Node.js      | Worker threads                | Native bindings | Polyfill        | No             |\n| Wasmtime     | wasi-threads                  | Host functions  | Full            | Configurable   |\n| Embedded     | No                            | No              | Partial         | No             |\n\n\u003e Performance guarantees apply only to supported profiles.\n\n---\n\n## Testing and Verification\n\n*   Property-Based Testing: binary size, monomorphization, ownership enforcement, threading safety.\n*   Cross-Language ABI Testing: Zig, C, and other WASM components.\n*   Reproducible Builds and Performance Benchmarks.\n\n---\n\n## Comparative Snapshot\n\n| Metric          | WasmRust    | Rust+bindgen | Zig   | AssemblyScript |\n| --------------- | ----------- | ------------ | ----- | -------------- |\n| Binary size     | ~2 KB       | ~35 KB       | ~1 KB | ~8 KB          |\n| Compile time    | ~3s         | ~12s         | ~2s   | ~4s            |\n| Memory safety   | ✅           | ✅            | ⚠️    | ⚠️             |\n| Component Model | ✅           | ❌            | ⚠️    | ❌              |\n| Thread Safety   | ✅           | ⚠️ Unsafe    | ⚠️    | ⚠️             |\n\n---\n\n## 🚀 Roadmap\n\n**Phase 1 — Proof of Concept (3 months)**\n* `wasm` crate: core WASM abstractions\n* Cranelift backend for dev builds\n* Benchmark comparisons\n\n**Phase 2 — Component Model (6 months)**\n* WIT ↔ Rust bidirectional codegen\n* `cargo-wasm` with federated registry\n* DevTools memory visualization\n\n**Phase 3 — Standardization (12 months)**\n* RFCs for Layer 1 features\n* Collaboration with Bytecode Alliance\n* W3C WebAssembly CG presentation\n\n---\n\n## Non-Goals\n\n* A Rust fork or new language\n* Replacing `wasm-bindgen` initially\n* A JavaScript framework or runtime\n\n---\n\n## Where to Start\n\n*   📦 Use `crates/wasm` for low-level WASM code today.\n*   📖 Read tech specs in [`docs/TSD-WasmRust.md`](docs/TSD-WasmRust.md).\n*   🧪 Experiment with Cranelift WASM builds (nightly).\n*   🛠️ Contribute to core abstractions before compiler work.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyumin-chen%2Fwasm-rust","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyumin-chen%2Fwasm-rust","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyumin-chen%2Fwasm-rust/lists"}