wasm-bindgen-macro-support-0.2.99/.cargo_vcs_info.json0000644000000001620000000000100163200ustar { "git": { "sha1": "04ca6f34ae52454910c7c4fa15c7bfde0126db79" }, "path_in_vcs": "crates/macro-support" }wasm-bindgen-macro-support-0.2.99/Cargo.toml0000644000000034410000000000100143210ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.57" name = "wasm-bindgen-macro-support" version = "0.2.99" authors = ["The wasm-bindgen Developers"] build = false include = [ "/LICENSE-*", "/src", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = """ The part of the implementation of the `#[wasm_bindgen]` attribute that is not in the shared backend crate """ homepage = "https://rustwasm.github.io/wasm-bindgen/" documentation = "https://docs.rs/wasm-bindgen" readme = false license = "MIT OR Apache-2.0" repository = "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/macro-support" [lib] name = "wasm_bindgen_macro_support" path = "src/lib.rs" [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "2.0" features = [ "visit", "visit-mut", "full", ] [dependencies.wasm-bindgen-backend] version = "=0.2.99" default-features = false [dependencies.wasm-bindgen-shared] version = "=0.2.99" [features] default = ["std"] extra-traits = ["syn/extra-traits"] spans = ["wasm-bindgen-backend/spans"] std = ["wasm-bindgen-backend/std"] strict-macro = [] [lints.clippy] large_enum_variant = "allow" new_without_default = "allow" overly_complex_bool_expr = "allow" too_many_arguments = "allow" type_complexity = "allow" wasm-bindgen-macro-support-0.2.99/Cargo.toml.orig000064400000000000000000000017361046102023000200070ustar 00000000000000[package] authors = ["The wasm-bindgen Developers"] description = """ The part of the implementation of the `#[wasm_bindgen]` attribute that is not in the shared backend crate """ documentation = "https://docs.rs/wasm-bindgen" edition = "2021" homepage = "https://rustwasm.github.io/wasm-bindgen/" include = ["/LICENSE-*", "/src"] license = "MIT OR Apache-2.0" name = "wasm-bindgen-macro-support" repository = "https://github.com/rustwasm/wasm-bindgen/tree/master/crates/macro-support" rust-version = "1.57" version = "0.2.99" [features] default = ["std"] extra-traits = ["syn/extra-traits"] spans = ["wasm-bindgen-backend/spans"] std = ["wasm-bindgen-backend/std"] strict-macro = [] [dependencies] proc-macro2 = "1.0" quote = '1.0' syn = { version = '2.0', features = ['visit', 'visit-mut', 'full'] } wasm-bindgen-backend = { path = "../backend", version = "=0.2.99", default-features = false } wasm-bindgen-shared = { path = "../shared", version = "=0.2.99" } [lints] workspace = true wasm-bindgen-macro-support-0.2.99/LICENSE-APACHE000064400000000000000000000251371046102023000170450ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. wasm-bindgen-macro-support-0.2.99/LICENSE-MIT000064400000000000000000000020411046102023000165420ustar 00000000000000Copyright (c) 2014 Alex Crichton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. wasm-bindgen-macro-support-0.2.99/src/lib.rs000064400000000000000000000134761046102023000170270ustar 00000000000000//! This crate contains the part of the implementation of the `#[wasm_bindgen]` optsibute that is //! not in the shared backend crate. #![doc(html_root_url = "https://docs.rs/wasm-bindgen-macro-support/0.2")] extern crate proc_macro2; extern crate quote; #[macro_use] extern crate syn; #[macro_use] extern crate wasm_bindgen_backend as backend; extern crate wasm_bindgen_shared as shared; pub use crate::parser::BindgenAttrs; use crate::parser::MacroParse; use backend::{Diagnostic, TryToTokens}; use proc_macro2::TokenStream; use quote::ToTokens; use quote::TokenStreamExt; use syn::parse::{Parse, ParseStream, Result as SynResult}; mod parser; /// Takes the parsed input from a `#[wasm_bindgen]` macro and returns the generated bindings pub fn expand(attr: TokenStream, input: TokenStream) -> Result { parser::reset_attrs_used(); let item = syn::parse2::(input)?; let opts = syn::parse2(attr)?; let mut tokens = proc_macro2::TokenStream::new(); let mut program = backend::ast::Program::default(); item.macro_parse(&mut program, (Some(opts), &mut tokens))?; program.try_to_tokens(&mut tokens)?; // If we successfully got here then we should have used up all attributes // and considered all of them to see if they were used. If one was forgotten // that's a bug on our end, so sanity check here. parser::check_unused_attrs(&mut tokens); Ok(tokens) } /// Takes the parsed input from a `wasm_bindgen::link_to` macro and returns the generated link pub fn expand_link_to(input: TokenStream) -> Result { parser::reset_attrs_used(); let opts = syn::parse2(input)?; let mut tokens = proc_macro2::TokenStream::new(); let link = parser::link_to(opts)?; link.try_to_tokens(&mut tokens)?; Ok(tokens) } /// Takes the parsed input from a `#[wasm_bindgen]` macro and returns the generated bindings pub fn expand_class_marker( attr: TokenStream, input: TokenStream, ) -> Result { parser::reset_attrs_used(); let mut item = syn::parse2::(input)?; let opts: ClassMarker = syn::parse2(attr)?; let mut program = backend::ast::Program::default(); item.macro_parse(&mut program, &opts)?; // This is where things are slightly different, we are being expanded in the // context of an impl so we can't inject arbitrary item-like tokens into the // output stream. If we were to do that then it wouldn't parse! // // Instead what we want to do is to generate the tokens for `program` into // the header of the function. This'll inject some no_mangle functions and // statics and such, and they should all be valid in the context of the // start of a function. // // We manually implement `ToTokens for ImplItemFn` here, injecting our // program's tokens before the actual method's inner body tokens. let mut tokens = proc_macro2::TokenStream::new(); tokens.append_all( item.attrs .iter() .filter(|attr| matches!(attr.style, syn::AttrStyle::Outer)), ); item.vis.to_tokens(&mut tokens); item.sig.to_tokens(&mut tokens); let mut err = None; item.block.brace_token.surround(&mut tokens, |tokens| { if let Err(e) = program.try_to_tokens(tokens) { err = Some(e); } parser::check_unused_attrs(tokens); // same as above tokens.append_all( item.attrs .iter() .filter(|attr| matches!(attr.style, syn::AttrStyle::Inner(_))), ); tokens.append_all(&item.block.stmts); }); if let Some(err) = err { return Err(err); } Ok(tokens) } struct ClassMarker { class: syn::Ident, js_class: String, wasm_bindgen: syn::Path, wasm_bindgen_futures: syn::Path, } impl Parse for ClassMarker { fn parse(input: ParseStream) -> SynResult { let class = input.parse::()?; input.parse::()?; let mut js_class = input.parse::()?.value(); js_class = js_class .strip_prefix("r#") .map(String::from) .unwrap_or(js_class); let mut wasm_bindgen = None; let mut wasm_bindgen_futures = None; loop { if input.parse::>()?.is_some() { let ident = input.parse::()?; if ident == "wasm_bindgen" { if wasm_bindgen.is_some() { return Err(syn::Error::new( ident.span(), "found duplicate `wasm_bindgen`", )); } input.parse::()?; wasm_bindgen = Some(input.parse::()?); } else if ident == "wasm_bindgen_futures" { if wasm_bindgen_futures.is_some() { return Err(syn::Error::new( ident.span(), "found duplicate `wasm_bindgen_futures`", )); } input.parse::()?; wasm_bindgen_futures = Some(input.parse::()?); } else { return Err(syn::Error::new( ident.span(), "expected `wasm_bindgen` or `wasm_bindgen_futures`", )); } } else { break; } } Ok(ClassMarker { class, js_class, wasm_bindgen: wasm_bindgen.unwrap_or_else(|| syn::parse_quote! { wasm_bindgen }), wasm_bindgen_futures: wasm_bindgen_futures .unwrap_or_else(|| syn::parse_quote! { wasm_bindgen_futures }), }) } } wasm-bindgen-macro-support-0.2.99/src/parser.rs000064400000000000000000002150611046102023000175470ustar 00000000000000use std::cell::{Cell, RefCell}; use std::char; use std::collections::HashMap; use std::str::Chars; use ast::OperationKind; use backend::ast::{self, ThreadLocal}; use backend::util::{ident_ty, ShortHash}; use backend::Diagnostic; use proc_macro2::{Ident, Span, TokenStream, TokenTree}; use quote::ToTokens; use syn::ext::IdentExt; use syn::parse::{Parse, ParseStream, Result as SynResult}; use syn::spanned::Spanned; use syn::visit_mut::VisitMut; use syn::{ItemFn, Lit, MacroDelimiter, ReturnType}; use crate::ClassMarker; thread_local!(static ATTRS: AttributeParseState = Default::default()); /// Javascript keywords which are not keywords in Rust. const JS_KEYWORDS: [&str; 20] = [ "class", "case", "catch", "debugger", "default", "delete", "export", "extends", "finally", "function", "import", "instanceof", "new", "null", "switch", "this", "throw", "var", "void", "with", ]; #[derive(Default)] struct AttributeParseState { parsed: Cell, checks: Cell, unused_attrs: RefCell>, } /// Parsed attributes from a `#[wasm_bindgen(..)]`. #[cfg_attr(feature = "extra-traits", derive(Debug))] pub struct BindgenAttrs { /// List of parsed attributes pub attrs: Vec<(Cell, BindgenAttr)>, } macro_rules! attrgen { ($mac:ident) => { $mac! { (catch, Catch(Span)), (constructor, Constructor(Span)), (method, Method(Span)), (static_method_of, StaticMethodOf(Span, Ident)), (js_namespace, JsNamespace(Span, Vec, Vec)), (module, Module(Span, String, Span)), (raw_module, RawModule(Span, String, Span)), (inline_js, InlineJs(Span, String, Span)), (getter, Getter(Span, Option)), (setter, Setter(Span, Option)), (indexing_getter, IndexingGetter(Span)), (indexing_setter, IndexingSetter(Span)), (indexing_deleter, IndexingDeleter(Span)), (structural, Structural(Span)), (r#final, Final(Span)), (readonly, Readonly(Span)), (js_name, JsName(Span, String, Span)), (js_class, JsClass(Span, String, Span)), (inspectable, Inspectable(Span)), (is_type_of, IsTypeOf(Span, syn::Expr)), (extends, Extends(Span, syn::Path)), (no_deref, NoDeref(Span)), (vendor_prefix, VendorPrefix(Span, Ident)), (variadic, Variadic(Span)), (typescript_custom_section, TypescriptCustomSection(Span)), (skip_typescript, SkipTypescript(Span)), (skip_jsdoc, SkipJsDoc(Span)), (main, Main(Span)), (start, Start(Span)), (wasm_bindgen, WasmBindgen(Span, syn::Path)), (js_sys, JsSys(Span, syn::Path)), (wasm_bindgen_futures, WasmBindgenFutures(Span, syn::Path)), (skip, Skip(Span)), (typescript_type, TypeScriptType(Span, String, Span)), (getter_with_clone, GetterWithClone(Span)), (static_string, StaticString(Span)), (thread_local, ThreadLocal(Span)), (thread_local_v2, ThreadLocalV2(Span)), // For testing purposes only. (assert_no_shim, AssertNoShim(Span)), } }; } macro_rules! methods { ($(($name:ident, $variant:ident($($contents:tt)*)),)*) => { $(methods!(@method $name, $variant($($contents)*));)* fn enforce_used(self) -> Result<(), Diagnostic> { // Account for the fact this method was called ATTRS.with(|state| state.checks.set(state.checks.get() + 1)); let mut errors = Vec::new(); for (used, attr) in self.attrs.iter() { if used.get() { continue } let span = match attr { $(BindgenAttr::$variant(span, ..) => span,)* }; errors.push(Diagnostic::span_error(*span, "unused wasm_bindgen attribute")); } Diagnostic::from_vec(errors) } fn check_used(self) { // Account for the fact this method was called ATTRS.with(|state| { state.checks.set(state.checks.get() + 1); state.unused_attrs.borrow_mut().extend( self.attrs .iter() .filter_map(|(used, attr)| if used.get() { None } else { Some(attr) }) .map(|attr| { match attr { $(BindgenAttr::$variant(span, ..) => { syn::parse_quote_spanned!(*span => $name) })* } }) ); }); } }; (@method $name:ident, $variant:ident(Span, String, Span)) => { fn $name(&self) -> Option<(&str, Span)> { self.attrs .iter() .find_map(|a| match &a.1 { BindgenAttr::$variant(_, s, span) => { a.0.set(true); Some((&s[..], *span)) } _ => None, }) } }; (@method $name:ident, $variant:ident(Span, Vec, Vec)) => { fn $name(&self) -> Option<(&[String], &[Span])> { self.attrs .iter() .find_map(|a| match &a.1 { BindgenAttr::$variant(_, ss, spans) => { a.0.set(true); Some((&ss[..], &spans[..])) } _ => None, }) } }; (@method $name:ident, $variant:ident(Span, $($other:tt)*)) => { #[allow(unused)] fn $name(&self) -> Option<&$($other)*> { self.attrs .iter() .find_map(|a| match &a.1 { BindgenAttr::$variant(_, s) => { a.0.set(true); Some(s) } _ => None, }) } }; (@method $name:ident, $variant:ident($($other:tt)*)) => { #[allow(unused)] fn $name(&self) -> Option<&$($other)*> { self.attrs .iter() .find_map(|a| match &a.1 { BindgenAttr::$variant(s) => { a.0.set(true); Some(s) } _ => None, }) } }; } impl BindgenAttrs { /// Find and parse the wasm_bindgen attributes. fn find(attrs: &mut Vec) -> Result { let mut ret = BindgenAttrs::default(); loop { let pos = attrs .iter() .enumerate() .find(|&(_, m)| m.path().segments[0].ident == "wasm_bindgen") .map(|a| a.0); let pos = match pos { Some(i) => i, None => return Ok(ret), }; let attr = attrs.remove(pos); let tokens = match attr.meta { syn::Meta::Path(_) => continue, syn::Meta::List(syn::MetaList { delimiter: MacroDelimiter::Paren(_), tokens, .. }) => tokens, syn::Meta::List(_) | syn::Meta::NameValue(_) => { bail_span!(attr, "malformed #[wasm_bindgen] attribute") } }; let mut attrs: BindgenAttrs = syn::parse2(tokens)?; ret.attrs.append(&mut attrs.attrs); attrs.check_used(); } } fn get_thread_local(&self) -> Result, Diagnostic> { let mut thread_local = self.thread_local_v2().map(|_| ThreadLocal::V2); if let Some(span) = self.thread_local() { if thread_local.is_some() { return Err(Diagnostic::span_error( *span, "`thread_local` can't be used with `thread_local_v2`", )); } else { thread_local = Some(ThreadLocal::V1) } } Ok(thread_local) } attrgen!(methods); } impl Default for BindgenAttrs { fn default() -> BindgenAttrs { // Add 1 to the list of parsed attribute sets. We'll use this counter to // sanity check that we call `check_used` an appropriate number of // times. ATTRS.with(|state| state.parsed.set(state.parsed.get() + 1)); BindgenAttrs { attrs: Vec::new() } } } impl Parse for BindgenAttrs { fn parse(input: ParseStream) -> SynResult { let mut attrs = BindgenAttrs::default(); if input.is_empty() { return Ok(attrs); } let opts = syn::punctuated::Punctuated::<_, syn::token::Comma>::parse_terminated(input)?; attrs.attrs = opts.into_iter().map(|c| (Cell::new(false), c)).collect(); Ok(attrs) } } macro_rules! gen_bindgen_attr { ($(($method:ident, $($variants:tt)*),)*) => { /// The possible attributes in the `#[wasm_bindgen]`. #[cfg_attr(feature = "extra-traits", derive(Debug))] pub enum BindgenAttr { $($($variants)*,)* } } } attrgen!(gen_bindgen_attr); impl Parse for BindgenAttr { fn parse(input: ParseStream) -> SynResult { let original = input.fork(); let attr: AnyIdent = input.parse()?; let attr = attr.0; let attr_span = attr.span(); let attr_string = attr.to_string(); let raw_attr_string = format!("r#{}", attr_string); macro_rules! parsers { ($(($name:ident, $($contents:tt)*),)*) => { $( if attr_string == stringify!($name) || raw_attr_string == stringify!($name) { parsers!( @parser $($contents)* ); } )* }; (@parser $variant:ident(Span)) => ({ return Ok(BindgenAttr::$variant(attr_span)); }); (@parser $variant:ident(Span, Ident)) => ({ input.parse::()?; let ident = input.parse::()?.0; return Ok(BindgenAttr::$variant(attr_span, ident)) }); (@parser $variant:ident(Span, Option)) => ({ if input.parse::().is_ok() { if input.peek(syn::LitStr) { let litstr = input.parse::()?; return Ok(BindgenAttr::$variant(attr_span, Some(litstr.value()))) } let ident = input.parse::()?.0; return Ok(BindgenAttr::$variant(attr_span, Some(ident.to_string()))) } else { return Ok(BindgenAttr::$variant(attr_span, None)); } }); (@parser $variant:ident(Span, syn::Path)) => ({ input.parse::()?; return Ok(BindgenAttr::$variant(attr_span, input.parse()?)); }); (@parser $variant:ident(Span, syn::Expr)) => ({ input.parse::()?; return Ok(BindgenAttr::$variant(attr_span, input.parse()?)); }); (@parser $variant:ident(Span, String, Span)) => ({ input.parse::()?; let (val, span) = match input.parse::() { Ok(str) => (str.value(), str.span()), Err(_) => { let ident = input.parse::()?.0; (ident.to_string(), ident.span()) } }; return Ok(BindgenAttr::$variant(attr_span, val, span)) }); (@parser $variant:ident(Span, Vec, Vec)) => ({ input.parse::()?; let (vals, spans) = match input.parse::() { Ok(exprs) => { let mut vals = vec![]; let mut spans = vec![]; for expr in exprs.elems.iter() { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(ref str), .. }) = expr { vals.push(str.value()); spans.push(str.span()); } else { return Err(syn::Error::new(expr.span(), "expected string literals")); } } (vals, spans) }, Err(_) => { let ident = input.parse::()?.0; (vec![ident.to_string()], vec![ident.span()]) } }; return Ok(BindgenAttr::$variant(attr_span, vals, spans)) }); } attrgen!(parsers); Err(original.error(if attr_string.starts_with('_') { "unknown attribute: it's safe to remove unused attributes entirely." } else { "unknown attribute" })) } } struct AnyIdent(Ident); impl Parse for AnyIdent { fn parse(input: ParseStream) -> SynResult { input.step(|cursor| match cursor.ident() { Some((ident, remaining)) => Ok((AnyIdent(ident), remaining)), None => Err(cursor.error("expected an identifier")), }) } } /// Conversion trait with context. /// /// Used to convert syn tokens into an AST, that we can then use to generate glue code. The context /// (`Ctx`) is used to pass in the attributes from the `#[wasm_bindgen]`, if needed. trait ConvertToAst { /// What we are converting to. type Target; /// Convert into our target. /// /// Since this is used in a procedural macro, use panic to fail. fn convert(self, context: Ctx) -> Result; } impl ConvertToAst<(&ast::Program, BindgenAttrs)> for &mut syn::ItemStruct { type Target = ast::Struct; fn convert( self, (program, attrs): (&ast::Program, BindgenAttrs), ) -> Result { if !self.generics.params.is_empty() { bail_span!( self.generics, "structs with #[wasm_bindgen] cannot have lifetime or \ type parameters currently" ); } let mut fields = Vec::new(); let js_name = attrs .js_name() .map(|s| s.0.to_string()) .unwrap_or(self.ident.unraw().to_string()); let is_inspectable = attrs.inspectable().is_some(); let getter_with_clone = attrs.getter_with_clone(); for (i, field) in self.fields.iter_mut().enumerate() { match field.vis { syn::Visibility::Public(..) => {} _ => continue, } let (js_field_name, member) = match &field.ident { Some(ident) => (ident.unraw().to_string(), syn::Member::Named(ident.clone())), None => (i.to_string(), syn::Member::Unnamed(i.into())), }; let attrs = BindgenAttrs::find(&mut field.attrs)?; if attrs.skip().is_some() { attrs.check_used(); continue; } let js_field_name = match attrs.js_name() { Some((name, _)) => name.to_string(), None => js_field_name, }; let comments = extract_doc_comments(&field.attrs); let getter = shared::struct_field_get(&js_name, &js_field_name); let setter = shared::struct_field_set(&js_name, &js_field_name); fields.push(ast::StructField { rust_name: member, js_name: js_field_name, struct_name: self.ident.clone(), readonly: attrs.readonly().is_some(), ty: field.ty.clone(), getter: Ident::new(&getter, Span::call_site()), setter: Ident::new(&setter, Span::call_site()), comments, generate_typescript: attrs.skip_typescript().is_none(), generate_jsdoc: attrs.skip_jsdoc().is_none(), getter_with_clone: attrs.getter_with_clone().or(getter_with_clone).copied(), wasm_bindgen: program.wasm_bindgen.clone(), }); attrs.check_used(); } let generate_typescript = attrs.skip_typescript().is_none(); let comments: Vec = extract_doc_comments(&self.attrs); attrs.check_used(); Ok(ast::Struct { rust_name: self.ident.clone(), js_name, fields, comments, is_inspectable, generate_typescript, wasm_bindgen: program.wasm_bindgen.clone(), }) } } fn get_ty(mut ty: &syn::Type) -> &syn::Type { while let syn::Type::Group(g) = ty { ty = &g.elem; } ty } fn get_expr(mut expr: &syn::Expr) -> &syn::Expr { while let syn::Expr::Group(g) = expr { expr = &g.expr; } expr } impl<'a> ConvertToAst<(&ast::Program, BindgenAttrs, &'a Option)> for syn::ForeignItemFn { type Target = ast::ImportKind; fn convert( self, (program, opts, module): (&ast::Program, BindgenAttrs, &'a Option), ) -> Result { let mut wasm = function_from_decl( &self.sig.ident, &opts, self.sig.clone(), self.attrs.clone(), self.vis.clone(), FunctionPosition::Extern, Some(&["default"]), )? .0; let catch = opts.catch().is_some(); let variadic = opts.variadic().is_some(); let js_ret = if catch { // TODO: this assumes a whole bunch: // // * The outer type is actually a `Result` // * The error type is a `JsValue` // * The actual type is the first type parameter // // should probably fix this one day... extract_first_ty_param(wasm.ret.as_ref())? } else { wasm.ret.clone() }; let operation_kind = operation_kind(&opts); let kind = if opts.method().is_some() { let class = wasm.arguments.first().ok_or_else(|| { err_span!(self, "imported methods must have at least one argument") })?; let class = match get_ty(&class.ty) { syn::Type::Reference(syn::TypeReference { mutability: None, elem, .. }) => &**elem, _ => bail_span!( class.ty, "first argument of method must be a shared reference" ), }; let class_name = match get_ty(class) { syn::Type::Path(syn::TypePath { qself: None, ref path, }) => path, _ => bail_span!(class, "first argument of method must be a path"), }; let class_name = extract_path_ident(class_name)?; let class_name = opts .js_class() .map(|p| p.0.into()) .unwrap_or_else(|| class_name.to_string()); let kind = ast::MethodKind::Operation(ast::Operation { is_static: false, kind: operation_kind, }); ast::ImportFunctionKind::Method { class: class_name, ty: class.clone(), kind, } } else if let Some(cls) = opts.static_method_of() { let class = opts .js_class() .map(|p| p.0.into()) .unwrap_or_else(|| cls.to_string()); let ty = ident_ty(cls.clone()); let kind = ast::MethodKind::Operation(ast::Operation { is_static: true, kind: operation_kind, }); ast::ImportFunctionKind::Method { class, ty, kind } } else if opts.constructor().is_some() { let class = match js_ret { Some(ref ty) => ty, _ => bail_span!(self, "constructor returns must be bare types"), }; let class_name = match get_ty(class) { syn::Type::Path(syn::TypePath { qself: None, ref path, }) => path, _ => bail_span!(self, "return value of constructor must be a bare path"), }; let class_name = extract_path_ident(class_name)?; let class_name = opts .js_class() .map(|p| p.0.into()) .unwrap_or_else(|| class_name.to_string()); ast::ImportFunctionKind::Method { class: class_name, ty: class.clone(), kind: ast::MethodKind::Constructor, } } else { ast::ImportFunctionKind::Normal }; let shim = { let ns = match kind { ast::ImportFunctionKind::Normal => (0, "n"), ast::ImportFunctionKind::Method { ref class, .. } => (1, &class[..]), }; let data = (ns, self.sig.to_token_stream().to_string(), module); format!( "__wbg_{}_{}", wasm.name .chars() .filter(|c| c.is_ascii_alphanumeric()) .collect::(), ShortHash(data) ) }; if let Some(span) = opts.r#final() { if opts.structural().is_some() { let msg = "cannot specify both `structural` and `final`"; return Err(Diagnostic::span_error(*span, msg)); } } let assert_no_shim = opts.assert_no_shim().is_some(); let mut doc_comment = String::new(); // Extract the doc comments from our list of attributes. wasm.rust_attrs.retain(|attr| { /// Returns the contents of the passed `#[doc = "..."]` attribute, /// or `None` if it isn't one. fn get_docs(attr: &syn::Attribute) -> Option { if attr.path().is_ident("doc") { if let syn::Meta::NameValue(syn::MetaNameValue { value: syn::Expr::Lit(syn::ExprLit { lit: Lit::Str(str), .. }), .. }) = &attr.meta { Some(str.value()) } else { None } } else { None } } if let Some(docs) = get_docs(attr) { if !doc_comment.is_empty() { // Add newlines between the doc comments doc_comment.push('\n'); } // Add this doc comment to the complete docs doc_comment.push_str(&docs); // Remove it from the list of regular attributes false } else { true } }); let ret = ast::ImportKind::Function(ast::ImportFunction { function: wasm, assert_no_shim, kind, js_ret, catch, variadic, structural: opts.structural().is_some() || opts.r#final().is_none(), rust_name: self.sig.ident, shim: Ident::new(&shim, Span::call_site()), doc_comment, wasm_bindgen: program.wasm_bindgen.clone(), wasm_bindgen_futures: program.wasm_bindgen_futures.clone(), }); opts.check_used(); Ok(ret) } } impl ConvertToAst<(&ast::Program, BindgenAttrs)> for syn::ForeignItemType { type Target = ast::ImportKind; fn convert( self, (program, attrs): (&ast::Program, BindgenAttrs), ) -> Result { let js_name = attrs .js_name() .map(|s| s.0) .map_or_else(|| self.ident.to_string(), |s| s.to_string()); let typescript_type = attrs.typescript_type().map(|s| s.0.to_string()); let is_type_of = attrs.is_type_of().cloned(); let shim = format!( "__wbg_instanceof_{}_{}", self.ident, ShortHash((attrs.js_namespace().map(|(ns, _)| ns), &self.ident)) ); let mut extends = Vec::new(); let mut vendor_prefixes = Vec::new(); let no_deref = attrs.no_deref().is_some(); for (used, attr) in attrs.attrs.iter() { match attr { BindgenAttr::Extends(_, e) => { extends.push(e.clone()); used.set(true); } BindgenAttr::VendorPrefix(_, e) => { vendor_prefixes.push(e.clone()); used.set(true); } _ => {} } } attrs.check_used(); Ok(ast::ImportKind::Type(ast::ImportType { vis: self.vis, attrs: self.attrs, doc_comment: None, instanceof_shim: shim, is_type_of, rust_name: self.ident, typescript_type, js_name, extends, vendor_prefixes, no_deref, wasm_bindgen: program.wasm_bindgen.clone(), })) } } impl<'a> ConvertToAst<(&ast::Program, BindgenAttrs, &'a Option)> for syn::ForeignItemStatic { type Target = ast::ImportKind; fn convert( self, (program, opts, module): (&ast::Program, BindgenAttrs, &'a Option), ) -> Result { if let syn::StaticMutability::Mut(_) = self.mutability { bail_span!(self.mutability, "cannot import mutable globals yet") } if let Some(span) = opts.static_string() { return Err(Diagnostic::span_error( *span, "static strings require a string literal", )); } let default_name = self.ident.to_string(); let js_name = opts .js_name() .map(|p| p.0) .unwrap_or(&default_name) .to_string(); let shim = format!( "__wbg_static_accessor_{}_{}", self.ident, ShortHash((&js_name, module, &self.ident)), ); let thread_local = opts.get_thread_local()?; opts.check_used(); Ok(ast::ImportKind::Static(ast::ImportStatic { ty: *self.ty, vis: self.vis, rust_name: self.ident.clone(), js_name, shim: Ident::new(&shim, Span::call_site()), wasm_bindgen: program.wasm_bindgen.clone(), thread_local, })) } } impl<'a> ConvertToAst<(&ast::Program, BindgenAttrs, &'a Option)> for syn::ItemStatic { type Target = ast::ImportKind; fn convert( self, (program, opts, module): (&ast::Program, BindgenAttrs, &'a Option), ) -> Result { if let syn::StaticMutability::Mut(_) = self.mutability { bail_span!(self.mutability, "cannot import mutable globals yet") } let string = if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(string), .. }) = *self.expr.clone() { string.value() } else { bail_span!( self.expr, "statics with a value can only be string literals" ) }; if opts.static_string().is_none() { bail_span!( self, "static strings require `#[wasm_bindgen(static_string)]`" ) } let thread_local = if let Some(thread_local) = opts.get_thread_local()? { thread_local } else { bail_span!( self, "static strings require `#[wasm_bindgen(thread_local_v2)]`" ) }; let shim = format!( "__wbg_string_{}_{}", self.ident, ShortHash((&module, &self.ident)), ); opts.check_used(); Ok(ast::ImportKind::String(ast::ImportString { ty: *self.ty, vis: self.vis, rust_name: self.ident.clone(), shim: Ident::new(&shim, Span::call_site()), wasm_bindgen: program.wasm_bindgen.clone(), js_sys: program.js_sys.clone(), string, thread_local, })) } } impl ConvertToAst for syn::ItemFn { type Target = ast::Function; fn convert(self, attrs: BindgenAttrs) -> Result { match self.vis { syn::Visibility::Public(_) => {} _ if attrs.start().is_some() => {} _ => bail_span!(self, "can only #[wasm_bindgen] public functions"), } if self.sig.constness.is_some() { bail_span!( self.sig.constness, "can only #[wasm_bindgen] non-const functions" ); } let ret = function_from_decl( &self.sig.ident, &attrs, self.sig.clone(), self.attrs, self.vis, FunctionPosition::Free, Some(&["default"]), )?; attrs.check_used(); Ok(ret.0) } } pub(crate) fn is_js_keyword(keyword: &str, skip: Option<&[&str]>) -> bool { JS_KEYWORDS .iter() .filter(|keyword| skip.filter(|skip| skip.contains(keyword)).is_none()) .any(|this| *this == keyword) } /// Returns whether `self` is passed by reference or by value. fn get_self_method(r: syn::Receiver) -> ast::MethodSelf { // The tricky part here is that `r` can have many forms. E.g. `self`, // `&self`, `&mut self`, `self: Self`, `self: &Self`, `self: &mut Self`, // `self: Box`, `self: Rc`, etc. // Luckily, syn always populates the `ty` field with the type of `self`, so // e.g. `&self` gets the type `&Self`. So we only have check whether the // type is a reference or not. match &*r.ty { syn::Type::Reference(ty) => { if ty.mutability.is_some() { ast::MethodSelf::RefMutable } else { ast::MethodSelf::RefShared } } _ => ast::MethodSelf::ByValue, } } enum FunctionPosition<'a> { Extern, Free, Impl { self_ty: &'a Ident }, } /// Construct a function (and gets the self type if appropriate) for our AST from a syn function. #[allow(clippy::too_many_arguments)] fn function_from_decl( decl_name: &syn::Ident, opts: &BindgenAttrs, sig: syn::Signature, attrs: Vec, vis: syn::Visibility, position: FunctionPosition, skip_keywords: Option<&[&str]>, ) -> Result<(ast::Function, Option), Diagnostic> { if sig.variadic.is_some() { bail_span!(sig.variadic, "can't #[wasm_bindgen] variadic functions"); } if !sig.generics.params.is_empty() { bail_span!( sig.generics, "can't #[wasm_bindgen] functions with lifetime or type parameters", ); } assert_no_lifetimes(&sig)?; let syn::Signature { inputs, output, .. } = sig; // A helper function to replace `Self` in the function signature of methods. // E.g. `fn get(&self) -> Option` to `fn get(&self) -> Option` // The following comment explains why this is necessary: // https://github.com/rustwasm/wasm-bindgen/issues/3105#issuecomment-1275160744 let replace_self = |mut t: syn::Type| { if let FunctionPosition::Impl { self_ty } = position { // This uses a visitor to replace all occurrences of `Self` with // the actual type identifier. The visitor guarantees that we find // all occurrences of `Self`, even if deeply nested and even if // future Rust versions add more places where `Self` can appear. struct SelfReplace(Ident); impl VisitMut for SelfReplace { fn visit_ident_mut(&mut self, i: &mut proc_macro2::Ident) { if i == "Self" { *i = self.0.clone(); } } } let mut replace = SelfReplace(self_ty.clone()); replace.visit_type_mut(&mut t); } t }; // A helper function to replace argument names that are JS keywords. // E.g. this will replace `fn foo(class: u32)` to `fn foo(_class: u32)` let replace_colliding_arg = |i: &mut syn::PatType| { if let syn::Pat::Ident(ref mut i) = *i.pat { let ident = i.ident.to_string(); if is_js_keyword(ident.as_str(), skip_keywords) { i.ident = Ident::new(format!("_{}", ident).as_str(), i.ident.span()); } } }; let mut method_self = None; let mut arguments = Vec::new(); for arg in inputs.into_iter() { match arg { syn::FnArg::Typed(mut c) => { // typical arguments like foo: u32 replace_colliding_arg(&mut c); c.ty = Box::new(replace_self(*c.ty)); arguments.push(c); } syn::FnArg::Receiver(r) => { // the self argument, so self, &self, &mut self, self: Box, etc. // `self` is only allowed for `fn`s inside an `impl` block. match position { FunctionPosition::Free => { bail_span!( r.self_token, "the `self` argument is only allowed for functions in `impl` blocks.\n\n\ If the function is already in an `impl` block, did you perhaps forget to add `#[wasm_bindgen]` to the `impl` block?" ); } FunctionPosition::Extern => { bail_span!( r.self_token, "the `self` argument is not allowed for `extern` functions.\n\n\ Did you perhaps mean `this`? For more information on importing JavaScript functions, see:\n\ https://rustwasm.github.io/docs/wasm-bindgen/examples/import-js.html" ); } FunctionPosition::Impl { .. } => {} } // We need to know *how* `self` is passed to the method (by // value or by reference) to generate the correct JS shim. assert!(method_self.is_none()); method_self = Some(get_self_method(r)); } } } let ret = match output { syn::ReturnType::Default => None, syn::ReturnType::Type(_, ty) => Some(replace_self(*ty)), }; let (name, name_span, renamed_via_js_name) = if let Some((js_name, js_name_span)) = opts.js_name() { let kind = operation_kind(opts); let prefix = match kind { OperationKind::Setter(_) => "set_", _ => "", }; let name = if prefix.is_empty() && opts.method().is_none() && is_js_keyword(js_name, skip_keywords) { format!("_{}", js_name) } else { format!("{}{}", prefix, js_name) }; (name, js_name_span, true) } else { let name = if !matches!(position, FunctionPosition::Impl { .. }) && opts.method().is_none() && is_js_keyword(&decl_name.to_string(), skip_keywords) { format!("_{}", decl_name.unraw()) } else { decl_name.unraw().to_string() }; (name, decl_name.span(), false) }; Ok(( ast::Function { arguments, name_span, name, renamed_via_js_name, ret, rust_attrs: attrs, rust_vis: vis, r#unsafe: sig.unsafety.is_some(), r#async: sig.asyncness.is_some(), generate_typescript: opts.skip_typescript().is_none(), generate_jsdoc: opts.skip_jsdoc().is_none(), variadic: opts.variadic().is_some(), }, method_self, )) } pub(crate) trait MacroParse { /// Parse the contents of an object into our AST, with a context if necessary. /// /// The context is used to have access to the attributes on `#[wasm_bindgen]`, and to allow /// writing to the output `TokenStream`. fn macro_parse(self, program: &mut ast::Program, context: Ctx) -> Result<(), Diagnostic>; } impl<'a> MacroParse<(Option, &'a mut TokenStream)> for syn::Item { fn macro_parse( self, program: &mut ast::Program, (opts, tokens): (Option, &'a mut TokenStream), ) -> Result<(), Diagnostic> { match self { syn::Item::Fn(mut f) => { let opts = opts.unwrap_or_default(); if let Some(path) = opts.wasm_bindgen() { program.wasm_bindgen = path.clone(); } if let Some(path) = opts.js_sys() { program.js_sys = path.clone(); } if let Some(path) = opts.wasm_bindgen_futures() { program.wasm_bindgen_futures = path.clone(); } if opts.main().is_some() { opts.check_used(); return main(program, f, tokens); } let no_mangle = f .attrs .iter() .enumerate() .find(|(_, m)| m.path().is_ident("no_mangle")); if let Some((i, _)) = no_mangle { f.attrs.remove(i); } let comments = extract_doc_comments(&f.attrs); // If the function isn't used for anything other than being exported to JS, // it'll be unused when not building for the Wasm target and produce a // `dead_code` warning. So, add `#[allow(dead_code)]` before it to avoid that. tokens.extend(quote::quote! { #[allow(dead_code)] }); f.to_tokens(tokens); if opts.start().is_some() { if !f.sig.generics.params.is_empty() { bail_span!(&f.sig.generics, "the start function cannot have generics",); } if !f.sig.inputs.is_empty() { bail_span!(&f.sig.inputs, "the start function cannot have arguments",); } } let method_kind = ast::MethodKind::Operation(ast::Operation { is_static: true, kind: operation_kind(&opts), }); let rust_name = f.sig.ident.clone(); let start = opts.start().is_some(); program.exports.push(ast::Export { comments, function: f.convert(opts)?, js_class: None, method_kind, method_self: None, rust_class: None, rust_name, start, wasm_bindgen: program.wasm_bindgen.clone(), wasm_bindgen_futures: program.wasm_bindgen_futures.clone(), }); } syn::Item::Struct(mut s) => { let opts = opts.unwrap_or_default(); program.structs.push((&mut s).convert((program, opts))?); s.to_tokens(tokens); } syn::Item::Impl(mut i) => { let opts = opts.unwrap_or_default(); (&mut i).macro_parse(program, opts)?; i.to_tokens(tokens); } syn::Item::ForeignMod(mut f) => { let opts = match opts { Some(opts) => opts, None => BindgenAttrs::find(&mut f.attrs)?, }; f.macro_parse(program, opts)?; } syn::Item::Enum(mut e) => { let opts = match opts { Some(opts) => opts, None => BindgenAttrs::find(&mut e.attrs)?, }; e.macro_parse(program, (tokens, opts))?; } syn::Item::Const(mut c) => { let opts = match opts { Some(opts) => opts, None => BindgenAttrs::find(&mut c.attrs)?, }; c.macro_parse(program, opts)?; } _ => { bail_span!( self, "#[wasm_bindgen] can only be applied to a function, \ struct, enum, impl, or extern block", ); } } Ok(()) } } impl MacroParse for &mut syn::ItemImpl { fn macro_parse(self, program: &mut ast::Program, opts: BindgenAttrs) -> Result<(), Diagnostic> { if self.defaultness.is_some() { bail_span!( self.defaultness, "#[wasm_bindgen] default impls are not supported" ); } if self.unsafety.is_some() { bail_span!( self.unsafety, "#[wasm_bindgen] unsafe impls are not supported" ); } if let Some((_, path, _)) = &self.trait_ { bail_span!(path, "#[wasm_bindgen] trait impls are not supported"); } if !self.generics.params.is_empty() { bail_span!( self.generics, "#[wasm_bindgen] generic impls aren't supported" ); } let name = match get_ty(&self.self_ty) { syn::Type::Path(syn::TypePath { qself: None, ref path, }) => path, _ => bail_span!( self.self_ty, "unsupported self type in #[wasm_bindgen] impl" ), }; let mut errors = Vec::new(); for item in self.items.iter_mut() { if let Err(e) = prepare_for_impl_recursion(item, name, program, &opts) { errors.push(e); } } Diagnostic::from_vec(errors)?; opts.check_used(); Ok(()) } } // Prepare for recursion into an `impl` block. Here we want to attach an // internal attribute, `__wasm_bindgen_class_marker`, with any metadata we need // to pass from the impl to the impl item. Recursive macro expansion will then // expand the `__wasm_bindgen_class_marker` attribute. // // Note that we currently do this because inner items may have things like cfgs // on them, so we want to expand the impl first, let the insides get cfg'd, and // then go for the rest. fn prepare_for_impl_recursion( item: &mut syn::ImplItem, class: &syn::Path, program: &ast::Program, impl_opts: &BindgenAttrs, ) -> Result<(), Diagnostic> { let method = match item { syn::ImplItem::Fn(m) => m, syn::ImplItem::Const(_) => { bail_span!( &*item, "const definitions aren't supported with #[wasm_bindgen]" ); } syn::ImplItem::Type(_) => bail_span!( &*item, "type definitions in impls aren't supported with #[wasm_bindgen]" ), syn::ImplItem::Macro(_) => { // In theory we want to allow this, but we have no way of expanding // the macro and then placing our magical attributes on the expanded // functions. As a result, just disallow it for now to hopefully // ward off buggy results from this macro. bail_span!(&*item, "macros in impls aren't supported"); } syn::ImplItem::Verbatim(_) => panic!("unparsed impl item?"), other => bail_span!(other, "failed to parse this item as a known item"), }; let ident = extract_path_ident(class)?; let js_class = impl_opts .js_class() .map(|s| s.0.to_string()) .unwrap_or(ident.to_string()); let wasm_bindgen = &program.wasm_bindgen; let wasm_bindgen_futures = &program.wasm_bindgen_futures; method.attrs.insert( 0, syn::Attribute { pound_token: Default::default(), style: syn::AttrStyle::Outer, bracket_token: Default::default(), meta: syn::parse_quote! { #wasm_bindgen::prelude::__wasm_bindgen_class_marker(#class = #js_class, wasm_bindgen = #wasm_bindgen, wasm_bindgen_futures = #wasm_bindgen_futures) }, }, ); Ok(()) } impl MacroParse<&ClassMarker> for &mut syn::ImplItemFn { fn macro_parse( self, program: &mut ast::Program, ClassMarker { class, js_class, wasm_bindgen, wasm_bindgen_futures, }: &ClassMarker, ) -> Result<(), Diagnostic> { program.wasm_bindgen = wasm_bindgen.clone(); program.wasm_bindgen_futures = wasm_bindgen_futures.clone(); match self.vis { syn::Visibility::Public(_) => {} _ => return Ok(()), } if self.defaultness.is_some() { panic!("default methods are not supported"); } if self.sig.constness.is_some() { bail_span!( self.sig.constness, "can only #[wasm_bindgen] non-const functions", ); } let opts = BindgenAttrs::find(&mut self.attrs)?; let comments = extract_doc_comments(&self.attrs); let (function, method_self) = function_from_decl( &self.sig.ident, &opts, self.sig.clone(), self.attrs.clone(), self.vis.clone(), FunctionPosition::Impl { self_ty: class }, None, )?; let method_kind = if opts.constructor().is_some() { ast::MethodKind::Constructor } else { let is_static = method_self.is_none(); let kind = operation_kind(&opts); ast::MethodKind::Operation(ast::Operation { is_static, kind }) }; program.exports.push(ast::Export { comments, function, js_class: Some(js_class.to_string()), method_kind, method_self, rust_class: Some(class.clone()), rust_name: self.sig.ident.clone(), start: false, wasm_bindgen: program.wasm_bindgen.clone(), wasm_bindgen_futures: program.wasm_bindgen_futures.clone(), }); opts.check_used(); Ok(()) } } fn string_enum( enum_: syn::ItemEnum, program: &mut ast::Program, js_name: String, generate_typescript: bool, comments: Vec, ) -> Result<(), Diagnostic> { let mut variants = vec![]; let mut variant_values = vec![]; for v in enum_.variants.iter() { let (_, expr) = match &v.discriminant { Some(pair) => pair, None => { bail_span!(v, "all variants of a string enum must have a string value"); } }; match get_expr(expr) { syn::Expr::Lit(syn::ExprLit { attrs: _, lit: syn::Lit::Str(str_lit), }) => { variants.push(v.ident.clone()); variant_values.push(str_lit.value()); } expr => bail_span!( expr, "enums with #[wasm_bindgen] cannot mix string and non-string values", ), } } program.imports.push(ast::Import { module: None, js_namespace: None, kind: ast::ImportKind::Enum(ast::StringEnum { vis: enum_.vis, name: enum_.ident, js_name, variants, variant_values, comments, rust_attrs: enum_.attrs, generate_typescript, wasm_bindgen: program.wasm_bindgen.clone(), }), }); Ok(()) } /// Represents a possibly negative numeric value as base 10 digits. struct NumericValue<'a> { negative: bool, base10_digits: &'a str, } impl<'a> NumericValue<'a> { fn from_expr(expr: &'a syn::Expr) -> Option { match get_expr(expr) { syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(int_lit), .. }) => Some(Self { negative: false, base10_digits: int_lit.base10_digits(), }), syn::Expr::Unary(syn::ExprUnary { op: syn::UnOp::Neg(_), expr, .. }) => Self::from_expr(expr).map(|n| n.neg()), _ => None, } } fn parse(&self) -> Option { let mut value = self.base10_digits.parse::().ok()?; if self.negative { value = -value; } Some(value) } fn neg(self) -> Self { Self { negative: !self.negative, base10_digits: self.base10_digits, } } } impl<'a> MacroParse<(&'a mut TokenStream, BindgenAttrs)> for syn::ItemEnum { fn macro_parse( self, program: &mut ast::Program, (tokens, opts): (&'a mut TokenStream, BindgenAttrs), ) -> Result<(), Diagnostic> { if self.variants.is_empty() { bail_span!(self, "cannot export empty enums to JS"); } for variant in self.variants.iter() { match variant.fields { syn::Fields::Unit => (), _ => bail_span!( variant.fields, "enum variants with associated data are not supported with #[wasm_bindgen]" ), } } let generate_typescript = opts.skip_typescript().is_none(); let js_name = opts .js_name() .map(|s| s.0) .map_or_else(|| self.ident.to_string(), |s| s.to_string()); let comments = extract_doc_comments(&self.attrs); opts.check_used(); // Check if the enum is a string enum, by checking whether any variant has a string discriminant. let is_string_enum = self.variants.iter().any(|v| { if let Some((_, expr)) = &v.discriminant { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }) = get_expr(expr) { return true; } } false }); if is_string_enum { return string_enum(self, program, js_name, generate_typescript, comments); } match self.vis { syn::Visibility::Public(_) => {} _ => bail_span!(self, "only public enums are allowed with #[wasm_bindgen]"), } // Go through all variants once first to determine whether the enum is // signed or unsigned. We don't need to actually parse the discriminant // values yet, we just need to know their sign. The actual parsing is // done in a second pass. let signed = self.variants.iter().any(|v| match &v.discriminant { Some((_, expr)) => NumericValue::from_expr(expr).map_or(false, |n| n.negative), None => false, }); let underlying_min = if signed { i32::MIN as i64 } else { 0 }; let underlying_max = if signed { i32::MAX as i64 } else { u32::MAX as i64 }; let mut last_discriminant: Option = None; let mut discriminant_map: HashMap = HashMap::new(); let variants = self .variants .iter() .map(|v| { let value: i64 = match &v.discriminant { Some((_, expr)) => match NumericValue::from_expr(expr).and_then(|n| n.parse()) { Some(value) => value, _ => bail_span!( expr, "C-style enums with #[wasm_bindgen] may only have \ numeric literal values that fit in a 32-bit integer as discriminants. \ Expressions or variables are not supported.", ), }, None => { // Use the same algorithm as rustc to determine the next discriminant // https://doc.rust-lang.org/reference/items/enumerations.html#implicit-discriminants last_discriminant.map_or(0, |last| last + 1) } }; last_discriminant = Some(value); // check that the value fits within the underlying type let underlying = if signed { "i32" } else { "u32" }; let numbers = if signed { "signed numbers" } else { "unsigned numbers" }; if value < underlying_min { bail_span!( v, "C-style enums with #[wasm_bindgen] can only support {0} that can be represented by `{2}`, \ but `{1}` is too small for `{2}`", numbers, value, underlying ); } if value > underlying_max { bail_span!( v, "C-style enums with #[wasm_bindgen] can only support {0} that can be represented by `{2}`, \ but `{1}` is too large for `{2}`", numbers, value, underlying ); } // detect duplicate discriminants if let Some(old) = discriminant_map.insert(value, v) { bail_span!( v, "discriminant value `{}` is already used by {} in this enum", value, old.ident ); } let comments = extract_doc_comments(&v.attrs); Ok(ast::Variant { name: v.ident.clone(), // due to the above checks, we know that the value fits // within 32 bits, so this cast doesn't lose any information value: value as u32, comments, }) }) .collect::, Diagnostic>>()?; // To make all the code handling holes simpler, we only consider // non-negative holes. This allows us to use `u32` to represent holes. let hole = (0..=underlying_max) .find(|v| !discriminant_map.contains_key(v)) .unwrap() as u32; self.to_tokens(tokens); program.enums.push(ast::Enum { rust_name: self.ident, js_name, signed, variants, comments, hole, generate_typescript, wasm_bindgen: program.wasm_bindgen.clone(), }); Ok(()) } } impl MacroParse for syn::ItemConst { fn macro_parse(self, program: &mut ast::Program, opts: BindgenAttrs) -> Result<(), Diagnostic> { // Shortcut if opts.typescript_custom_section().is_none() { bail_span!(self, "#[wasm_bindgen] will not work on constants unless you are defining a #[wasm_bindgen(typescript_custom_section)]."); } let typescript_custom_section = match get_expr(&self.expr) { syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(litstr), .. }) => ast::LitOrExpr::Lit(litstr.value()), expr => ast::LitOrExpr::Expr(expr.clone()), }; program .typescript_custom_sections .push(typescript_custom_section); opts.check_used(); Ok(()) } } impl MacroParse for syn::ItemForeignMod { fn macro_parse(self, program: &mut ast::Program, opts: BindgenAttrs) -> Result<(), Diagnostic> { let mut errors = Vec::new(); if let Some(other) = self.abi.name.filter(|l| l.value() != "C") { errors.push(err_span!( other, "only foreign mods with the `C` ABI are allowed" )); } let js_namespace = opts.js_namespace().map(|(s, _)| s.to_owned()); let module = module_from_opts(program, &opts) .map_err(|e| errors.push(e)) .unwrap_or_default(); for item in self.items.into_iter() { let ctx = ForeignItemCtx { module: module.clone(), js_namespace: js_namespace.clone(), }; if let Err(e) = item.macro_parse(program, ctx) { errors.push(e); } } Diagnostic::from_vec(errors)?; opts.check_used(); Ok(()) } } struct ForeignItemCtx { module: Option, js_namespace: Option>, } impl MacroParse for syn::ForeignItem { fn macro_parse( mut self, program: &mut ast::Program, ctx: ForeignItemCtx, ) -> Result<(), Diagnostic> { let item_opts = { let attrs = match self { syn::ForeignItem::Fn(ref mut f) => &mut f.attrs, syn::ForeignItem::Type(ref mut t) => &mut t.attrs, syn::ForeignItem::Static(ref mut s) => &mut s.attrs, syn::ForeignItem::Verbatim(v) => { let mut item: syn::ItemStatic = syn::parse(v.into()).expect("only foreign functions/types allowed for now"); let item_opts = BindgenAttrs::find(&mut item.attrs)?; let kind = item.convert((program, item_opts, &ctx.module))?; program.imports.push(ast::Import { module: None, js_namespace: None, kind, }); return Ok(()); } _ => panic!("only foreign functions/types allowed for now"), }; BindgenAttrs::find(attrs)? }; let js_namespace = item_opts .js_namespace() .map(|(s, _)| s.to_owned()) .or(ctx.js_namespace); let module = ctx.module; let kind = match self { syn::ForeignItem::Fn(f) => f.convert((program, item_opts, &module))?, syn::ForeignItem::Type(t) => t.convert((program, item_opts))?, syn::ForeignItem::Static(s) => s.convert((program, item_opts, &module))?, _ => panic!("only foreign functions/types allowed for now"), }; program.imports.push(ast::Import { module, js_namespace, kind, }); Ok(()) } } pub fn module_from_opts( program: &mut ast::Program, opts: &BindgenAttrs, ) -> Result, Diagnostic> { if let Some(path) = opts.wasm_bindgen() { program.wasm_bindgen = path.clone(); } if let Some(path) = opts.js_sys() { program.js_sys = path.clone(); } if let Some(path) = opts.wasm_bindgen_futures() { program.wasm_bindgen_futures = path.clone(); } let mut errors = Vec::new(); let module = if let Some((name, span)) = opts.module() { if opts.inline_js().is_some() { let msg = "cannot specify both `module` and `inline_js`"; errors.push(Diagnostic::span_error(span, msg)); } if opts.raw_module().is_some() { let msg = "cannot specify both `module` and `raw_module`"; errors.push(Diagnostic::span_error(span, msg)); } Some(ast::ImportModule::Named(name.to_string(), span)) } else if let Some((name, span)) = opts.raw_module() { if opts.inline_js().is_some() { let msg = "cannot specify both `raw_module` and `inline_js`"; errors.push(Diagnostic::span_error(span, msg)); } Some(ast::ImportModule::RawNamed(name.to_string(), span)) } else if let Some((js, span)) = opts.inline_js() { let i = program.inline_js.len(); program.inline_js.push(js.to_string()); Some(ast::ImportModule::Inline(i, span)) } else { None }; Diagnostic::from_vec(errors)?; Ok(module) } /// Get the first type parameter of a generic type, errors on incorrect input. fn extract_first_ty_param(ty: Option<&syn::Type>) -> Result, Diagnostic> { let t = match ty { Some(t) => t, None => return Ok(None), }; let path = match *get_ty(t) { syn::Type::Path(syn::TypePath { qself: None, ref path, }) => path, _ => bail_span!(t, "must be Result<...>"), }; let seg = path .segments .last() .ok_or_else(|| err_span!(t, "must have at least one segment"))?; let generics = match seg.arguments { syn::PathArguments::AngleBracketed(ref t) => t, _ => bail_span!(t, "must be Result<...>"), }; let generic = generics .args .first() .ok_or_else(|| err_span!(t, "must have at least one generic parameter"))?; let ty = match generic { syn::GenericArgument::Type(t) => t, other => bail_span!(other, "must be a type parameter"), }; match get_ty(ty) { syn::Type::Tuple(t) if t.elems.is_empty() => return Ok(None), _ => {} } Ok(Some(ty.clone())) } /// Extract the documentation comments from a Vec of attributes fn extract_doc_comments(attrs: &[syn::Attribute]) -> Vec { attrs .iter() .filter_map(|a| { // if the path segments include an ident of "doc" we know this // this is a doc comment if a.path().segments.iter().any(|s| s.ident == "doc") { let tokens = match &a.meta { syn::Meta::Path(_) => None, syn::Meta::List(list) => Some(list.tokens.clone()), syn::Meta::NameValue(name_value) => Some(name_value.value.to_token_stream()), }; Some( // We want to filter out any Puncts so just grab the Literals tokens.into_iter().flatten().filter_map(|t| match t { TokenTree::Literal(lit) => { let quoted = lit.to_string(); Some(try_unescape("ed).unwrap_or(quoted)) } _ => None, }), ) } else { None } }) //Fold up the [[String]] iter we created into Vec .fold(vec![], |mut acc, a| { acc.extend(a); acc }) } // Unescapes a quoted string. char::escape_debug() was used to escape the text. fn try_unescape(mut s: &str) -> Option { s = s.strip_prefix('"').unwrap_or(s); s = s.strip_suffix('"').unwrap_or(s); let mut result = String::with_capacity(s.len()); let mut chars = s.chars(); while let Some(c) = chars.next() { if c == '\\' { let c = chars.next()?; match c { 't' => result.push('\t'), 'r' => result.push('\r'), 'n' => result.push('\n'), '\\' | '\'' | '"' => result.push(c), 'u' => { if chars.next() != Some('{') { return None; } let (c, next) = unescape_unicode(&mut chars)?; result.push(c); if next != '}' { return None; } } _ => return None, } } else { result.push(c); } } Some(result) } fn unescape_unicode(chars: &mut Chars) -> Option<(char, char)> { let mut value = 0; for (i, c) in chars.enumerate() { match (i, c.to_digit(16)) { (0..=5, Some(num)) => value = (value << 4) | num, (1.., None) => return Some((char::from_u32(value)?, c)), _ => break, } } None } /// Check there are no lifetimes on the function. fn assert_no_lifetimes(sig: &syn::Signature) -> Result<(), Diagnostic> { struct Walk { diagnostics: Vec, } impl<'ast> syn::visit::Visit<'ast> for Walk { fn visit_lifetime(&mut self, i: &'ast syn::Lifetime) { self.diagnostics.push(err_span!( i, "it is currently not sound to use lifetimes in function \ signatures" )); } } let mut walk = Walk { diagnostics: Vec::new(), }; syn::visit::Visit::visit_signature(&mut walk, sig); Diagnostic::from_vec(walk.diagnostics) } /// Extracts the last ident from the path fn extract_path_ident(path: &syn::Path) -> Result { for segment in path.segments.iter() { match segment.arguments { syn::PathArguments::None => {} _ => bail_span!(path, "paths with type parameters are not supported yet"), } } match path.segments.last() { Some(value) => Ok(value.ident.clone()), None => { bail_span!(path, "empty idents are not supported"); } } } pub fn reset_attrs_used() { ATTRS.with(|state| { state.parsed.set(0); state.checks.set(0); state.unused_attrs.borrow_mut().clear(); }) } pub fn check_unused_attrs(tokens: &mut TokenStream) { ATTRS.with(|state| { assert_eq!(state.parsed.get(), state.checks.get()); let unused_attrs = &*state.unused_attrs.borrow(); if !unused_attrs.is_empty() { tokens.extend(quote::quote! { // Anonymous scope to prevent name clashes. const _: () = { #(let #unused_attrs: ();)* }; }); } }) } fn operation_kind(opts: &BindgenAttrs) -> ast::OperationKind { let mut operation_kind = ast::OperationKind::Regular; if let Some(g) = opts.getter() { operation_kind = ast::OperationKind::Getter(g.clone()); } if let Some(s) = opts.setter() { operation_kind = ast::OperationKind::Setter(s.clone()); } if opts.indexing_getter().is_some() { operation_kind = ast::OperationKind::IndexingGetter; } if opts.indexing_setter().is_some() { operation_kind = ast::OperationKind::IndexingSetter; } if opts.indexing_deleter().is_some() { operation_kind = ast::OperationKind::IndexingDeleter; } operation_kind } pub fn link_to(opts: BindgenAttrs) -> Result { let mut program = ast::Program::default(); let module = module_from_opts(&mut program, &opts)?.ok_or_else(|| { Diagnostic::span_error(Span::call_site(), "`link_to!` requires a module.") })?; if let ast::ImportModule::Named(p, s) | ast::ImportModule::RawNamed(p, s) = &module { if !p.starts_with("./") && !p.starts_with("../") && !p.starts_with('/') { return Err(Diagnostic::span_error( *s, "`link_to!` does not support module paths.", )); } } opts.enforce_used()?; program.linked_modules.push(module); Ok(ast::LinkToModule(program)) } fn main(program: &ast::Program, mut f: ItemFn, tokens: &mut TokenStream) -> Result<(), Diagnostic> { if f.sig.ident != "main" { bail_span!(&f.sig.ident, "the main function has to be called main"); } if let Some(constness) = f.sig.constness { bail_span!(&constness, "the main function cannot be const"); } if !f.sig.generics.params.is_empty() { bail_span!(&f.sig.generics, "the main function cannot have generics"); } if !f.sig.inputs.is_empty() { bail_span!(&f.sig.inputs, "the main function cannot have arguments"); } let r#return = f.sig.output; f.sig.output = ReturnType::Default; let body = f.block; let wasm_bindgen = &program.wasm_bindgen; let wasm_bindgen_futures = &program.wasm_bindgen_futures; if f.sig.asyncness.take().is_some() { f.block = Box::new( syn::parse2(quote::quote! { { async fn __wasm_bindgen_generated_main() #r#return #body #wasm_bindgen_futures::spawn_local( async move { use #wasm_bindgen::__rt::Main; let __ret = __wasm_bindgen_generated_main(); (&mut &mut &mut #wasm_bindgen::__rt::MainWrapper(Some(__ret.await))).__wasm_bindgen_main() }, ) } }) .unwrap(), ); } else { f.block = Box::new( syn::parse2(quote::quote! { { fn __wasm_bindgen_generated_main() #r#return #body use #wasm_bindgen::__rt::Main; let __ret = __wasm_bindgen_generated_main(); (&mut &mut &mut #wasm_bindgen::__rt::MainWrapper(Some(__ret))).__wasm_bindgen_main() } }) .unwrap(), ); } f.to_tokens(tokens); Ok(()) } #[cfg(test)] mod tests { #[test] fn test_try_unescape() { use super::try_unescape; assert_eq!(try_unescape("hello").unwrap(), "hello"); assert_eq!(try_unescape("\"hello").unwrap(), "hello"); assert_eq!(try_unescape("hello\"").unwrap(), "hello"); assert_eq!(try_unescape("\"hello\"").unwrap(), "hello"); assert_eq!(try_unescape("hello\\\\").unwrap(), "hello\\"); assert_eq!(try_unescape("hello\\n").unwrap(), "hello\n"); assert_eq!(try_unescape("hello\\u"), None); assert_eq!(try_unescape("hello\\u{"), None); assert_eq!(try_unescape("hello\\u{}"), None); assert_eq!(try_unescape("hello\\u{0}").unwrap(), "hello\0"); assert_eq!(try_unescape("hello\\u{000000}").unwrap(), "hello\0"); assert_eq!(try_unescape("hello\\u{0000000}"), None); } }