Skip to content

Commit

Permalink
feat(wasm): add proc macro for error to bindgen
Browse files Browse the repository at this point in the history
  • Loading branch information
Vexcited committed Dec 29, 2024
1 parent bd9ac78 commit a4c6c95
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 1 deletion.
23 changes: 23 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions wasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,10 @@ syn = { version = "2.0", features = ["full"] }
quote = "1.0"
proc-macro2 = "1.0"

[dev-dependencies]
wasm-bindgen = "0.2"
thiserror = "2"
js-sys = "0.3"

[lib]
proc-macro = true
9 changes: 9 additions & 0 deletions wasm/examples/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#[derive(thiserror::Error, Debug, wasm::Error)]
pub enum Error {
#[error("no redirection was made, make sure the instance URL is correct")]
InvalidRedirection(),
}

fn main() {
println!("Hello, world!");
}
18 changes: 17 additions & 1 deletion wasm/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
extern crate proc_macro;

use syn::{parse_macro_input, ItemFn, Attribute, FnArg, parse_quote};
use syn::{parse_macro_input, ItemFn, Attribute, FnArg, parse_quote, DeriveInput};
use proc_macro::TokenStream;
use quote::quote;

Expand Down Expand Up @@ -41,3 +41,19 @@ pub fn setup_allocator(_input: TokenStream) -> TokenStream {

TokenStream::from(expanded)
}

#[proc_macro_derive(Error)]
pub fn derive_wasm_error(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;

let expanded = quote! {
impl From<#name> for wasm_bindgen::JsValue {
fn from(error: #name) -> Self {
js_sys::Error::new(&error.to_string()).into()
}
}
};

TokenStream::from(expanded)
}

0 comments on commit a4c6c95

Please sign in to comment.