pub fn func_param(id: &Id) -> Ident
Expand description

Convert a parameter name from its Id name to its Rust Ident representation.

Examples found in repository?
src/module_trait.rs (line 36)
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
pub fn define_module_trait(m: &Module, settings: &CodegenSettings) -> TokenStream {
    let traitname = names::trait_name(&m.name);
    let traitmethods = m.funcs().map(|f| {
        // Check if we're returning an entity anotated with a lifetime,
        // in which case, we'll need to annotate the function itself, and
        // hence will need an explicit lifetime (rather than anonymous)
        let (lifetime, is_anonymous) = if f
            .params
            .iter()
            .chain(&f.results)
            .any(|ret| ret.tref.needs_lifetime())
        {
            (quote!('a), false)
        } else {
            (anon_lifetime(), true)
        };
        let funcname = names::func(&f.name);
        let args = f.params.iter().map(|arg| {
            let arg_name = names::func_param(&arg.name);
            let arg_typename = names::type_ref(&arg.tref, lifetime.clone());
            let arg_type = if passed_by_reference(&*arg.tref.type_()) {
                quote!(&#arg_typename)
            } else {
                quote!(#arg_typename)
            };
            quote!(#arg_name: #arg_type)
        });

        let result = match f.results.len() {
            0 if f.noreturn => quote!(wiggle::anyhow::Error),
            0 => quote!(()),
            1 => {
                let (ok, err) = match &**f.results[0].tref.type_() {
                    witx::Type::Variant(v) => match v.as_expected() {
                        Some(p) => p,
                        None => unimplemented!("anonymous variant ref {:?}", v),
                    },
                    _ => unimplemented!(),
                };

                let ok = match ok {
                    Some(ty) => names::type_ref(ty, lifetime.clone()),
                    None => quote!(()),
                };
                let err = match err {
                    Some(ty) => match settings.errors.for_abi_error(ty) {
                        Some(ErrorType::User(custom)) => {
                            let tn = custom.typename();
                            quote!(super::#tn)
                        }
                        Some(ErrorType::Generated(g)) => g.typename(),
                        None => names::type_ref(ty, lifetime.clone()),
                    },
                    None => quote!(()),
                };
                quote!(Result<#ok, #err>)
            }
            _ => unimplemented!(),
        };

        let asyncness = if settings.get_async(&m, &f).is_sync() {
            quote!()
        } else {
            quote!(async)
        };

        if is_anonymous {
            quote!(#asyncness fn #funcname(&mut self, #(#args),*) -> #result; )
        } else {
            quote!(#asyncness fn #funcname<#lifetime>(&mut self, #(#args),*) -> #result;)
        }
    });

    quote! {
        #[wiggle::async_trait]
        pub trait #traitname {
            #(#traitmethods)*
        }
    }
}
More examples
Hide additional examples
src/funcs.rs (line 246)
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
    fn emit(
        &mut self,
        inst: &Instruction<'_>,
        operands: &mut Vec<TokenStream>,
        results: &mut Vec<TokenStream>,
    ) {
        let wrap_err = |location: &str| {
            let modulename = self.module.name.as_str();
            let funcname = self.funcname;
            quote! {
                |e| {
                    wiggle::GuestError::InFunc {
                        modulename: #modulename,
                        funcname: #funcname,
                        location: #location,
                        err: Box::new(wiggle::GuestError::from(e)),
                    }
                }
            }
        };

        let mut try_from = |ty: TokenStream| {
            let val = operands.pop().unwrap();
            let wrap_err = wrap_err(&format!("convert {}", ty));
            results.push(quote!(#ty::try_from(#val).map_err(#wrap_err)?));
        };

        match inst {
            Instruction::GetArg { nth } => {
                let param = &self.params[*nth];
                results.push(quote!(#param));
            }

            Instruction::PointerFromI32 { ty } | Instruction::ConstPointerFromI32 { ty } => {
                let val = operands.pop().unwrap();
                let pointee_type = names::type_ref(ty, anon_lifetime());
                results.push(quote! {
                    wiggle::GuestPtr::<#pointee_type>::new(memory, #val as u32)
                });
            }

            Instruction::ListFromPointerLength { ty } => {
                let ptr = &operands[0];
                let len = &operands[1];
                let ty = match &**ty.type_() {
                    witx::Type::Builtin(witx::BuiltinType::Char) => quote!(str),
                    _ => {
                        let ty = names::type_ref(ty, anon_lifetime());
                        quote!([#ty])
                    }
                };
                results.push(quote! {
                    wiggle::GuestPtr::<#ty>::new(memory, (#ptr as u32, #len as u32));
                })
            }

            Instruction::CallInterface { func, .. } => {
                // Use the `tracing` crate to log all arguments that are going
                // out, and afterwards we call the function with those bindings.
                let mut args = Vec::new();
                for (i, param) in func.params.iter().enumerate() {
                    let name = names::func_param(&param.name);
                    let val = &operands[i];
                    self.src.extend(quote!(let #name = #val;));
                    if passed_by_reference(param.tref.type_()) {
                        args.push(quote!(&#name));
                    } else {
                        args.push(quote!(#name));
                    }
                }
                if self
                    .settings
                    .tracing
                    .enabled_for(self.module.name.as_str(), self.funcname)
                    && func.params.len() > 0
                {
                    let args = func
                        .params
                        .iter()
                        .map(|param| {
                            let name = names::func_param(&param.name);
                            if param.impls_display() {
                                quote!( #name = wiggle::tracing::field::display(&#name) )
                            } else {
                                quote!( #name = wiggle::tracing::field::debug(&#name) )
                            }
                        })
                        .collect::<Vec<_>>();
                    self.src.extend(quote! {
                        wiggle::tracing::event!(wiggle::tracing::Level::TRACE, #(#args),*);
                    });
                }

                let trait_name = names::trait_name(&self.module.name);
                let ident = names::func(&func.name);
                if self.settings.get_async(&self.module, &func).is_sync() {
                    self.src.extend(quote! {
                        let ret = #trait_name::#ident(ctx, #(#args),*);
                    })
                } else {
                    self.src.extend(quote! {
                        let ret = #trait_name::#ident(ctx, #(#args),*).await;
                    })
                };
                if self
                    .settings
                    .tracing
                    .enabled_for(self.module.name.as_str(), self.funcname)
                {
                    self.src.extend(quote! {
                        wiggle::tracing::event!(
                            wiggle::tracing::Level::TRACE,
                            result = wiggle::tracing::field::debug(&ret),
                        );
                    });
                }

                if func.results.len() > 0 {
                    results.push(quote!(ret));
                } else if func.noreturn {
                    self.src.extend(quote!(return Err(ret);));
                }
            }

            // Lowering an enum is typically simple but if we have an error
            // transformation registered for this enum then what we're actually
            // doing is lowering from a user-defined error type to the error
            // enum, and *then* we lower to an i32.
            Instruction::EnumLower { ty } => {
                let val = operands.pop().unwrap();
                let val = match self.settings.errors.for_name(ty) {
                    Some(ErrorType::User(custom)) => {
                        let method = names::user_error_conversion_method(&custom);
                        self.bound(quote::format_ident!("UserErrorConversion"));
                        quote!(UserErrorConversion::#method(ctx, #val)?)
                    }
                    Some(ErrorType::Generated(_)) => quote!(#val.downcast()?),
                    None => val,
                };
                results.push(quote!(#val as i32));
            }

            Instruction::ResultLower { err: err_ty, .. } => {
                let err = self.blocks.pop().unwrap();
                let ok = self.blocks.pop().unwrap();
                let val = operands.pop().unwrap();
                let err_typename = names::type_ref(err_ty.unwrap(), anon_lifetime());
                results.push(quote! {
                    match #val {
                        Ok(e) => { #ok; <#err_typename as wiggle::GuestErrorType>::success() as i32 }
                        Err(e) => { #err }
                    }
                });
            }

            Instruction::VariantPayload => results.push(quote!(e)),

            Instruction::Return { amt: 0 } => {
                self.src.extend(quote!(return Ok(())));
            }
            Instruction::Return { amt: 1 } => {
                let val = operands.pop().unwrap();
                self.src.extend(quote!(return Ok(#val)));
            }
            Instruction::Return { .. } => unimplemented!(),

            Instruction::TupleLower { amt } => {
                let names = (0..*amt)
                    .map(|i| Ident::new(&format!("t{}", i), Span::call_site()))
                    .collect::<Vec<_>>();
                let val = operands.pop().unwrap();
                self.src.extend(quote!( let (#(#names,)*) = #val;));
                results.extend(names.iter().map(|i| quote!(#i)));
            }

            Instruction::Store { ty } => {
                let ptr = operands.pop().unwrap();
                let val = operands.pop().unwrap();
                let wrap_err = wrap_err(&format!("write {}", ty.name.as_str()));
                let pointee_type = names::type_(&ty.name);
                self.src.extend(quote! {
                    wiggle::GuestPtr::<#pointee_type>::new(memory, #ptr as u32)
                        .write(#val)
                        .map_err(#wrap_err)?;
                });
            }

            Instruction::Load { ty } => {
                let ptr = operands.pop().unwrap();
                let wrap_err = wrap_err(&format!("read {}", ty.name.as_str()));
                let pointee_type = names::type_(&ty.name);
                results.push(quote! {
                    wiggle::GuestPtr::<#pointee_type>::new(memory, #ptr as u32)
                        .read()
                        .map_err(#wrap_err)?
                });
            }

            Instruction::HandleFromI32 { ty } => {
                let val = operands.pop().unwrap();
                let ty = names::type_(&ty.name);
                results.push(quote!(#ty::from(#val)));
            }

            // Smaller-than-32 numerical conversions are done with `TryFrom` to
            // ensure we're not losing bits.
            Instruction::U8FromI32 => try_from(quote!(u8)),
            Instruction::S8FromI32 => try_from(quote!(i8)),
            Instruction::Char8FromI32 => try_from(quote!(u8)),
            Instruction::U16FromI32 => try_from(quote!(u16)),
            Instruction::S16FromI32 => try_from(quote!(i16)),

            // Conversions with matching bit-widths but different signededness
            // use `as` since we're basically just reinterpreting the bits.
            Instruction::U32FromI32 | Instruction::UsizeFromI32 => {
                let val = operands.pop().unwrap();
                results.push(quote!(#val as u32));
            }
            Instruction::U64FromI64 => {
                let val = operands.pop().unwrap();
                results.push(quote!(#val as u64));
            }

            // Conversions to enums/bitflags use `TryFrom` to ensure that the
            // values are valid coming in.
            Instruction::EnumLift { ty }
            | Instruction::BitflagsFromI64 { ty }
            | Instruction::BitflagsFromI32 { ty } => {
                let ty = names::type_(&ty.name);
                try_from(quote!(#ty))
            }

            // No conversions necessary for these, the native wasm type matches
            // our own representation.
            Instruction::If32FromF32
            | Instruction::If64FromF64
            | Instruction::S32FromI32
            | Instruction::S64FromI64 => results.push(operands.pop().unwrap()),

            // There's a number of other instructions we could implement but
            // they're not exercised by WASI at this time. As necessary we can
            // add code to implement them.
            other => panic!("no implementation for {:?}", other),
        }
    }