wasm_wrapper_gen_shared/
processing.rs

1use std::fmt;
2
3use {quote, syn};
4
5use MacroError;
6
7use types::{SupportedArgumentType, SupportedRetType};
8
9pub fn extract_func_info(
10    item: &syn::Item,
11) -> Result<(&syn::Item, &syn::FnDecl, &syn::Block), MacroError> {
12    match item.node {
13        syn::ItemKind::Fn(ref decleration, _, _, _, _, ref block) => {
14            Ok((item, &**decleration, block))
15        }
16        ref kind => Err(MacroError::InvalidItemKind { kind: kind.clone() })?,
17    }
18}
19
20pub fn get_argument_types(decl: &syn::FnDecl) -> Result<Vec<SupportedArgumentType>, MacroError> {
21    Ok(decl.inputs
22        .iter()
23        .map(|input| match *input {
24            syn::FnArg::SelfRef(_, _) | syn::FnArg::SelfValue(_) => {
25                Err(MacroError::InvalidArgument { arg: input.clone() })
26            }
27            syn::FnArg::Captured(_, ref ty) | syn::FnArg::Ignored(ref ty) => Ok(ty.clone()),
28        })
29        .map(|ty_result| ty_result.and_then(|ty| SupportedArgumentType::new(&ty)))
30        .collect::<Result<_, _>>()?)
31}
32
33pub fn get_ret_type(decl: &syn::FnDecl) -> Result<SupportedRetType, MacroError> {
34    match decl.output {
35        syn::FunctionRetTy::Default => Ok(SupportedRetType::unit()),
36        syn::FunctionRetTy::Ty(ref ty) => SupportedRetType::new(ty),
37    }
38}
39
40// TODO: find and store doc-comments in here for use in generating JS code comments.
41pub struct JsFnInfo {
42    pub rust_name: String,
43    pub args_ty: Vec<SupportedArgumentType>,
44    pub ret_ty: SupportedRetType,
45}
46
47
48impl JsFnInfo {
49    pub fn try_from(item: &syn::Item) -> Result<Self, MacroError> {
50        let (item, decl, _) = extract_func_info(item)?;
51
52        let argument_types = get_argument_types(decl)?;
53        let ret_ty = match decl.output {
54            syn::FunctionRetTy::Default => SupportedRetType::unit(),
55            syn::FunctionRetTy::Ty(ref ty) => SupportedRetType::new(ty)?,
56        };
57
58        Ok(JsFnInfo {
59            rust_name: item.ident.to_string(),
60            args_ty: argument_types,
61            ret_ty: ret_ty,
62        })
63    }
64}
65
66static TRANSFORMED_FUNC_PREFX: &'static str = "__js_fn_";
67
68#[derive(Debug, Clone)]
69pub struct TransformedRustIdent<T> {
70    name: T,
71}
72
73impl<T> TransformedRustIdent<T> {
74    pub fn new(name: T) -> TransformedRustIdent<T> {
75        TransformedRustIdent { name }
76    }
77}
78
79impl<T: fmt::Display> quote::ToTokens for TransformedRustIdent<T> {
80    fn to_tokens(&self, tokens: &mut quote::Tokens) {
81        tokens.append(format!("{}{}", TRANSFORMED_FUNC_PREFX, self.name));
82    }
83}
84
85impl<T: fmt::Display> fmt::Display for TransformedRustIdent<T> {
86    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
87        write!(f, "{}{}", TRANSFORMED_FUNC_PREFX, self.name)
88    }
89}