• Stars
    star
    1,062
  • Rank 43,462 (Top 0.9 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created about 5 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Runtime for executing procedural macros as WebAssembly

Watt

github crates.io docs.rs

Watt is a runtime for executing Rust procedural macros compiled as WebAssembly.

[dependencies]
watt = "0.5"

Compiler support: requires rustc 1.42+


Rationale

  • Faster compilation.โ€ƒBy compiling macros ahead-of-time to Wasm, we save all downstream users of the macro from having to compile the macro logic or its dependencies themselves.

    Instead, what they compile is a small self-contained Wasm runtime (~3 seconds, shared by all macros) and a tiny proc macro shim for each macro crate to hand off Wasm bytecode into the Watt runtime (~0.3 seconds per proc-macro crate you depend on). This is much less than the 20+ seconds it can take to compile complex procedural macros and their dependencies.

  • Isolation.โ€ƒThe Watt runtime is 100% safe code with zero dependencies. While running in this environment, a macro's only possible interaction with the world is limited to consuming tokens and producing tokens. This is true regardless of how much unsafe code the macro itself might contain! Modulo bugs in the Rust compiler or standard library, it is impossible for a macro to do anything other than shuffle tokens around.

  • Determinism.โ€ƒFrom a build system point of view, a macro backed by Wasm has the advantage that it can be treated as a purely deterministic function from input to output. There is no possibility of implicit dependencies, such as via the filesystem, which aren't visible to or taken into account by the build system.


Getting started

Start by implementing and testing your proc macro as you normally would, using whatever dependencies you want (syn, quote, etc). You will end up with something that looks like:

use proc_macro::TokenStream;

#[proc_macro]
pub fn the_macro(input: TokenStream) -> TokenStream {
    /* ... */
}

#[proc_macro_derive] and #[proc_macro_attribute] are supported as well; everything is analogous to what will be shown here for #[proc_macro].

When your macro is ready, there are just a few changes we need to make to the signature and the Cargo.toml. In your lib.rs, change each of your macro entry points to a no_mangle extern "C" function, and change the TokenStream in the signature from proc_macro to proc_macro2.

It will look like:

use proc_macro2::TokenStream;

#[no_mangle]
pub extern "C" fn the_macro(input: TokenStream) -> TokenStream {
    /* same as before */
}

Now in your macro's Cargo.toml which used to contain this:

# my_macros/Cargo.toml

[lib]
proc-macro = true

change it instead to say:

[lib]
crate-type = ["cdylib"]

[patch.crates-io]
proc-macro2 = { git = "https://github.com/dtolnay/watt" }

This crate will be the binary that we compile to Wasm. Compile it by running:

$ cargo build --release --target wasm32-unknown-unknown

Next we need to make a small proc-macro shim crate to hand off the compiled Wasm bytes into the Watt runtime. It's fine to give this the same crate name as the previous crate, since the other one won't be getting published to crates.io. In a new Cargo.toml, put:

[lib]
proc-macro = true

[dependencies]
watt = "0.5"

And in its src/lib.rs, define real proc macros corresponding to each of the ones previously defined as no_mangle extern "C" functions in the other crate:

use proc_macro::TokenStream;
use watt::WasmMacro;

static MACRO: WasmMacro = WasmMacro::new(WASM);
static WASM: &[u8] = include_bytes!("my_macros.wasm");

#[proc_macro]
pub fn the_macro(input: TokenStream) -> TokenStream {
    MACRO.proc_macro("the_macro", input)
}

Finally, copy the compiled Wasm binary from target/wasm32-unknown-unknown/release/my_macros.wasm under your implementation crate, to the src directory of your shim crate, and it's ready to publish!


Remaining work

  • Performance.โ€ƒWatt compiles pretty fast, but so far I have not put any effort toward optimizing the runtime. That means macro expansion can potentially take longer than with a natively compiled proc macro.

    Note that the performance overhead of the Wasm environment is partially offset by the fact that our proc macros are compiled to Wasm in release mode, so downstream cargo build will be running a release-mode macro when it would have been running debug-mode for a traditional proc macro.

    A neat approach would be to provide some kind of cargo install watt-runtime which installs an optimized Wasm runtime locally, which the Watt crate can detect and hand off code to if available. That way we avoid running things in a debug-mode runtime altogether. The experimental beginnings of this can be found under the jit/ directory.

  • Tooling.โ€ƒThe getting started section shows there are a lot of steps to building a macro for Watt, and a pretty hacky patching in of proc-macro2. Ideally this would all be more straightforward, including easy tooling for doing reproducible builds of the Wasm artifact for confirming that it was indeed compiled from the publicly available sources.

  • RFCs.โ€ƒThe advantages of fast compile time, isolation, and determinism may make it worthwhile to build first-class support for Wasm proc macros into rustc and Cargo. The toolchain could ship its own high performance Wasm runtime, which is an even better outcome than Watt because that runtime can be heavily optimized and consumers of macros don't need to compile it.


This can't be real

To assist in convincing you that this is real, here is serde_derive compiled to Wasm. It was compiled from the commit serde-rs/serde@1afae183. Feel free to try it out as:

// [dependencies]
// serde = "1.0"
// serde_json = "1.0"
// wa-serde-derive = "0.1"

use wa_serde_derive::Serialize;

#[derive(Serialize)]
struct Watt {
    msg: &'static str,
}

fn main() {
    let w = Watt { msg: "hello from wasm!" };
    println!("{}", serde_json::to_string(&w).unwrap());
}

Acknowledgements

The current underlying Wasm runtime is a fork of the Rust-WASM project by Yoann Blein and Hugo Guiroux, a simple and spec-compliant WebAssembly interpreter.


License

Everything outside of the `runtime` directory is licensed under either of Apache License, Version 2.0 or MIT license at your option. The `runtime` directory is licensed under the ISC license.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

More Repositories

1

cxx

Safe interop between Rust and C++
Rust
5,106
star
2

anyhow

Flexible concrete Error type built on std::error::Error
Rust
4,193
star
3

thiserror

derive(Error) for struct and enum error types
Rust
3,352
star
4

proc-macro-workshop

Learn to write Rust procedural macrosโ€ƒโ€ƒ[Rust Latam conference, Montevideo Uruguay, March 2019]
Rust
2,988
star
5

syn

Parser for Rust source code
Rust
2,681
star
6

cargo-expand

Subcommand to show result of macro expansion
Rust
2,644
star
7

async-trait

Type erasure for async trait methods
Rust
1,495
star
8

case-studies

Analysis of various tricky Rust code
Rust
1,340
star
9

rust-quiz

Medium to hard Rust questions with explanations
Rust
1,318
star
10

quote

Rust quasi-quoting
Rust
1,231
star
11

typetag

Serde serializable and deserializable trait objects
Rust
888
star
12

paste

Macros for all your token pasting needs
Rust
852
star
13

serde-yaml

Strongly typed YAML library for Rust
Rust
804
star
14

no-panic

Attribute macro to require that the compiler prove a function can't ever panic
Rust
758
star
15

inventory

Typed distributed plugin registration
Rust
714
star
16

rust-toolchain

Concise GitHub Action for installing a Rust toolchain
Shell
621
star
17

trybuild

Test harness for ui tests of compiler diagnostics
Rust
615
star
18

miniserde

Data structure serialization library with several opposite design goals from Serde
Rust
612
star
19

reflect

Compile-time reflection API for developing robust procedural macros (proof of concept)
Rust
602
star
20

request-for-implementation

Crates that don't exist, but should
597
star
21

proc-macro2

Rust
545
star
22

indoc

Indented document literals for Rust
Rust
537
star
23

prettyplease

A minimal `syn` syntax tree pretty-printer
Rust
517
star
24

erased-serde

Type-erased Serialize, Serializer and Deserializer traits
Rust
503
star
25

semver

Parser and evaluator for Cargo's flavor of Semantic Versioning
Rust
500
star
26

dyn-clone

Clone trait that is object-safe
Rust
486
star
27

ryu

Fast floating point to string conversion
Rust
471
star
28

linkme

Safe cross-platform linker shenanigans
Rust
399
star
29

cargo-llvm-lines

Count lines of LLVM IR per generic function
Rust
398
star
30

semver-trick

How to avoid complicated coordinated upgrades
Rust
383
star
31

efg

Conditional compilation using boolean expression syntax, rather than any(), all(), not()
Rust
297
star
32

rust-faq

Frequently Asked Questions ยท The Rust Programming Language
262
star
33

rustversion

Conditional compilation according to rustc compiler version
Rust
256
star
34

itoa

Fast function for printing integer primitives to a decimal string
Rust
248
star
35

path-to-error

Find out path at which a deserialization error occurred
Rust
241
star
36

cargo-tally

Graph the number of crates that depend on your crate over time
Rust
212
star
37

proc-macro-hack

Procedural macros in expression position
Rust
203
star
38

monostate

Type that deserializes only from one specific value
Rust
194
star
39

colorous

Color schemes for charts and maps
Rust
193
star
40

readonly

Struct fields that are made read-only accessible to other modules
Rust
187
star
41

dissimilar

Diff library with semantic cleanup, based on Google's diff-match-patch
Rust
175
star
42

star-history

Graph history of GitHub stars of a user or repo over time
Rust
156
star
43

ref-cast

Safely cast &T to &U where the struct U contains a single field of type T.
Rust
154
star
44

automod

Pull in every source file in a directory as a module
Rust
129
star
45

inherent

Make trait methods callable without the trait in scope
Rust
128
star
46

ghost

Define your own PhantomData
Rust
115
star
47

faketty

Wrapper to exec a command in a pty, even if redirecting the output
Rust
113
star
48

dtoa

Fast functions for printing floating-point primitives to a decimal string
Rust
110
star
49

clang-ast

Rust
108
star
50

seq-macro

Macro to repeat sequentially indexed copies of a fragment of code
Rust
102
star
51

remain

Compile-time checks that an enum or match is written in sorted order
Rust
99
star
52

mashup

Concatenate identifiers in a macro invocation
Rust
96
star
53

noisy-clippy

Rust
84
star
54

tt-call

Token tree calling convention
Rust
77
star
55

basic-toml

Minimal TOML library with few dependencies
Rust
76
star
56

squatternaut

A snapshot of name squatting on crates.io
Rust
73
star
57

serde-ignored

Find out about keys that are ignored when deserializing data
Rust
68
star
58

enumn

Convert number to enum
Rust
66
star
59

bootstrap

Bootstrapping rustc from source
Shell
62
star
60

essay

docs.rs as a publishing platform?
Rust
62
star
61

db-dump

Library for scripting analyses against crates.io's database dumps
Rust
60
star
62

scratch

Compile-time temporary directory shared by multiple crates and erased by `cargo clean`
Rust
59
star
63

gflags

Command line flags library that does not require a central list of all the flags
Rust
55
star
64

install

Fast `cargo install` action using a GitHub-based binary cache
Shell
55
star
65

serde-starlark

Serde serializer for generating Starlark build targets
Rust
53
star
66

oqueue

Non-interleaving multithreaded output queue
Rust
53
star
67

build-alert

Rust
51
star
68

unicode-ident

Determine whether characters have the XID_Start or XID_Continue properties
Rust
51
star
69

lalrproc

Proof of concept of procedural macro input parsed by LALRPOP
Rust
50
star
70

dragonbox

Rust
50
star
71

sha1dir

Checksum of a directory tree
Rust
38
star
72

hackfn

Fake implementation of `std::ops::Fn` for user-defined data types
Rust
38
star
73

reduce

iter.reduce(fn) in Rust
Rust
37
star
74

link-cplusplus

Link libstdc++ or libc++ automatically or manually
Rust
36
star
75

argv

Non-allocating iterator over command line arguments
Rust
33
star
76

get-all-crates

Download .crate files of all versions of all crates from crates.io
Rust
31
star
77

threadbound

Make any value Sync but only available on its original thread
Rust
31
star
78

dircnt

Count directory entriesโ€”`ls | wc -l` but faster
Rust
27
star
79

unsafe-libyaml

libyaml transpiled to rust by c2rust
Rust
27
star
80

serde-stacker

Serializer and Deserializer adapters that avoid stack overflows by dynamically growing the stack
Rust
27
star
81

cargo-unlock

Remove Cargo.lock lockfile
Rust
25
star
82

respan

Macros to erase scope information from tokens
Rust
24
star
83

isatty

libc::isatty that also works on Windows
Rust
21
star
84

iota

Related constants in Rust: 1 << iota
Rust
20
star
85

foreach

18
star
86

bufsize

bytes::BufMut implementation to count buffer size
Rust
18
star
87

hire

How to hire dtolnay
18
star
88

precise

Full precision decimal representation of f64
Rust
17
star
89

dashboard

15
star
90

rustflags

Parser for CARGO_ENCODED_RUSTFLAGS
Rust
13
star
91

libfyaml-rs

Rust binding for libfyaml
Rust
11
star
92

install-buck2

Install precompiled Buck2 build system
6
star
93

mailingset

Set-algebraic operations on mailing lists
Python
5
star
94

.github

5
star
95

jq-gdb

gdb pretty-printer for jv objects
Python
1
star