1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
extern crate arrayvec;
#[macro_use]
extern crate failure;
#[macro_use]
extern crate proc_macro_hack;
#[macro_use]
extern crate quote;
extern crate syn;

extern crate wasm_wrapper_gen_shared;

use failure::{Error, ResultExt};

use wasm_wrapper_gen_shared::{extract_func_info, get_argument_types, get_ret_type,
                              transform_macro_input_to_items, SupportedArgumentType,
                              SupportedRetType, TransformedRustIdent};


#[derive(Debug, Clone)]
/// Small constructed ident struct supporting up to four suffixes.
struct ConstructedArgIdent {
    base: &'static str,
    number_suffix: u32,
    suffixes: arrayvec::ArrayVec<[&'static str; 4]>,
}

impl ConstructedArgIdent {
    fn new(base: &'static str, number_suffix: u32) -> Self {
        ConstructedArgIdent {
            base,
            number_suffix,
            suffixes: arrayvec::ArrayVec::new(),
        }
    }

    fn with_suffix(&self, suffix: &'static str) -> Self {
        let mut cloned = self.clone(); // this is a cheap copy
        cloned.suffixes.push(suffix);
        cloned
    }
}

impl quote::ToTokens for ConstructedArgIdent {
    fn to_tokens(&self, tokens: &mut quote::Tokens) {
        let mut ident = format!("{}{}", self.base, self.number_suffix);
        for suffix in &self.suffixes {
            ident.push_str(suffix);
        }
        tokens.append(ident);
    }
}

proc_macro_item_impl! {
    pub fn __js_fn_impl(input: &str) -> String {
        match process_all_functions(input) {
            Ok(v) => v,
            Err(e) => {
                panic!("js_fn macro failed: {}", e);
            }
        }
    }
}

fn process_all_functions(input: &str) -> Result<String, Error> {
    let token_trees = syn::parse_token_trees(input)
        .map_err(|e| format_err!("failed to parse macro input as an item: {}", e))?;

    let ast = transform_macro_input_to_items(token_trees)?;

    let mut full_out = quote::Tokens::new();
    for item in &ast {
        let output = process_item(item)
            .with_context(|e| format!("failed to process function '{:?}': {}", item, e))?;

        full_out.append(output);
    }
    Ok(full_out.to_string())
}

fn process_item(item: &syn::Item) -> Result<quote::Tokens, Error> {
    let (item, decl, block) = extract_func_info(item)?;

    let out = generate_function_wrapper(item, decl, block)?;

    Ok(out)
}

fn generate_function_wrapper(
    item: &syn::Item,
    decl: &syn::FnDecl,
    code: &syn::Block,
) -> Result<quote::Tokens, Error> {
    let callable_body = generate_callable_body(item, decl, code)?;

    let argument_types = get_argument_types(decl)?;
    let ret_ty = get_ret_type(decl)?;

    let argument_names = (0..argument_types.len() as u32)
        .map(|index| ConstructedArgIdent::new("__arg", index))
        .collect::<Vec<_>>();

    let mut function_body = quote::Tokens::new();

    for (ty, arg_name) in argument_types.iter().zip(&argument_names) {
        function_body.append(setup_for_argument(&arg_name, ty)?);
    }

    let mut arg_names_as_argument_list = quote::Tokens::new();
    for arg_name in &argument_names {
        arg_names_as_argument_list.append(quote! { #arg_name, });
    }

    function_body.append(quote! {
        // TODO: handle results as well...
        let result: #ret_ty = (#callable_body)(#arg_names_as_argument_list);
    });

    function_body.append(return_handling(&ret_ty)?);

    let func_ident = TransformedRustIdent::new(&item.ident);

    let mut real_arguments_list = quote::Tokens::new();
    for (ty, arg_name) in argument_types.iter().zip(&argument_names) {
        expand_argument_into(arg_name, ty, &mut real_arguments_list)?;
    }

    let ret_def = WrittenReturnType(ret_ty);

    let full_definition = quote! {
        #[no_mangle]
        #[doc(hidden)]
        pub extern "C" fn #func_ident (#real_arguments_list) #ret_def {
            #function_body
        }
    };

    Ok(full_definition)
    // let temp_ident = &item.ident;
    // let temp_str = full_definition.to_string();
    // Ok(quote! {
    //     fn #temp_ident() -> &'static str {
    //         #temp_str
    //     }
    // })
}

fn expand_argument_into(
    arg_name: &ConstructedArgIdent,
    type_type: &SupportedArgumentType,
    tokens: &mut quote::Tokens,
) -> Result<(), Error> {
    match *type_type {
        SupportedArgumentType::IntegerSliceRef(int_ty) => {
            let ptr_arg_name = arg_name.with_suffix("_ptr");
            let length_arg_name = arg_name.with_suffix("_len");
            tokens.append(quote! {
                #ptr_arg_name: *const #int_ty,
                #length_arg_name: usize,
            });
        }
        SupportedArgumentType::IntegerSliceMutRef(int_ty)
        | SupportedArgumentType::IntegerVec(int_ty) => {
            let ptr_arg_name = arg_name.with_suffix("_ptr");
            let length_arg_name = arg_name.with_suffix("_len");
            tokens.append(quote! {
                #ptr_arg_name: *mut #int_ty,
                #length_arg_name: usize,
            });
        }
        SupportedArgumentType::Integer(int_ty) => tokens.append(quote! {
            #arg_name: #int_ty,
        }),
    }

    Ok(())
}

struct WrittenReturnType(SupportedRetType);

impl quote::ToTokens for WrittenReturnType {
    fn to_tokens(&self, tokens: &mut quote::Tokens) {
        match self.0 {
            SupportedRetType::Unit => (),
            SupportedRetType::Integer(int_ty) => {
                tokens.append(quote! { -> #int_ty });
            }
            SupportedRetType::IntegerVec(_) => {
                tokens.append(quote! { -> *const usize });
            }
        }
    }
}

fn setup_for_argument(
    arg_name: &ConstructedArgIdent,
    ty: &SupportedArgumentType,
) -> Result<quote::Tokens, Error> {
    let tokens = match *ty {
        SupportedArgumentType::IntegerSliceRef(int_ty) => {
            // TODO: coordinate _ptr / _len suffixes
            let ptr_arg_name = arg_name.with_suffix("_ptr");
            let length_arg_name = arg_name.with_suffix("_len");
            quote! {
                let #arg_name: &[#int_ty] = unsafe {
                    ::std::slice::from_raw_parts(#ptr_arg_name, #length_arg_name)
                };
            }
        }
        SupportedArgumentType::IntegerSliceMutRef(int_ty) => {
            let ptr_arg_name = arg_name.with_suffix("_ptr");
            let length_arg_name = arg_name.with_suffix("_len");
            quote! {
                let #arg_name: &mut [#int_ty] = unsafe {
                    ::std::slice::from_raw_parts_mut(#ptr_arg_name, #length_arg_name)
                };
            }
        }
        SupportedArgumentType::IntegerVec(int_ty) => {
            let ptr_arg_name = arg_name.with_suffix("_ptr");
            let length_arg_name = arg_name.with_suffix("_len");
            quote! {
                let #arg_name: Vec<#int_ty> = unsafe {
                    ::std::vec::Vec::from_raw_parts(#ptr_arg_name,
                        #length_arg_name, #length_arg_name)
                };
            }
        }
        SupportedArgumentType::Integer(_) => quote::Tokens::new(), // no setup for simple integers
    };

    Ok(tokens)
}

fn return_handling(ty: &SupportedRetType) -> Result<quote::Tokens, Error> {
    let tokens = match *ty {
        SupportedRetType::Unit | SupportedRetType::Integer(_) => quote! { result },
        SupportedRetType::IntegerVec(int_ty) => {
            quote! {
                {
                    let result_ptr = result.as_slice().as_ptr() as *mut #int_ty;
                    let result_len = result.len();
                    let result_cap = result.capacity();
                    let to_return = Box::new([result_ptr as usize, result_len, result_cap]);
                    ::std::mem::forget(result);
                    ::std::boxed::Box::into_raw(to_return) as *const usize
                }
            }
        }
    };

    Ok(tokens)
}

fn generate_callable_body(
    _item: &syn::Item,
    decl: &syn::FnDecl,
    code: &syn::Block,
) -> Result<quote::Tokens, Error> {
    // we'll see what works best here.
    // This set of if statements is for if we've been given a path to the implementing function.
    //
    // In this case, we want to just call the function at that path with the same arguments the
    // function declaration takes.
    if let Some(statement) = code.stmts.first() {
        if let syn::Stmt::Expr(ref inner_expr) = *statement {
            if let syn::ExprKind::Path(_, _) = inner_expr.node {
                return Ok(quote! {
                    // output the path alone so that it can be called like (path::to::func)(args)
                    (#inner_expr)
                });
            }
        }
    }

    // if it isn't our special case of a path, we can assume the full code
    // to call the inner function has been written out. We'll give the code
    // then a copy of the inputs and call it
    let mut arguments = quote::Tokens::new();
    for input in &decl.inputs {
        arguments.append(quote! {
            #input,
        });
    }
    Ok(quote! {
        // syn::Block ToTokens includes '{}' always already.
        (|#arguments| #code )
    })
}