diff options
Diffstat (limited to 'cli/napi_sym')
| -rw-r--r-- | cli/napi_sym/Cargo.toml | 18 | ||||
| -rw-r--r-- | cli/napi_sym/lib.rs | 46 |
2 files changed, 64 insertions, 0 deletions
diff --git a/cli/napi_sym/Cargo.toml b/cli/napi_sym/Cargo.toml new file mode 100644 index 000000000..797ddf0bf --- /dev/null +++ b/cli/napi_sym/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "napi_sym" +version = "0.1.0" +edition = "2021" +license = "MIT" +readme = "../README.md" +description = "proc macro for writing N-API symbols" + +[lib] +path = "./lib.rs" +proc-macro = true + +[dependencies] +proc-macro2 = "1" +quote = "1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +syn = { version = "1", features = ["full", "extra-traits"] } diff --git a/cli/napi_sym/lib.rs b/cli/napi_sym/lib.rs new file mode 100644 index 000000000..caef3da65 --- /dev/null +++ b/cli/napi_sym/lib.rs @@ -0,0 +1,46 @@ +// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license. + +use proc_macro::TokenStream; +use quote::quote; +use serde::Deserialize; + +static NAPI_EXPORTS: &str = + include_str!("../../tools/napi/symbol_exports.json"); + +#[derive(Deserialize)] +struct SymbolExports { + pub symbols: Vec<String>, +} + +#[proc_macro_attribute] +pub fn napi_sym(_attr: TokenStream, item: TokenStream) -> TokenStream { + let func = syn::parse::<syn::ItemFn>(item).expect("expected a function"); + + let exports: SymbolExports = + serde_json::from_str(NAPI_EXPORTS).expect("failed to parse exports"); + let name = &func.sig.ident; + assert!( + exports.symbols.contains(&name.to_string()), + "tools/napi/symbol_exports.json is out of sync!" + ); + + let block = &func.block; + let inputs = &func.sig.inputs; + let output = &func.sig.output; + let ret_ty = match output { + syn::ReturnType::Default => panic!("expected a return type"), + syn::ReturnType::Type(_, ty) => quote! { #ty }, + }; + TokenStream::from(quote! { + // SAFETY: it's an NAPI function. + #[no_mangle] + pub unsafe extern "C" fn #name(#inputs) -> napi_status { + let mut inner = || -> #ret_ty { + #block + }; + inner() + .map(|_| napi_ok) + .unwrap_or_else(|e| e.into()) + } + }) +} |
