marine_macro_impl/parsed_type/
foreign_mod_arg.rs

1/*
2 * Copyright 2020 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use super::ParsedType;
18use quote::quote;
19
20/// This trait could be used to generate raw args needed to construct a wrapper of an import
21/// function.
22pub(crate) trait ForeignModArgGlueCodeGenerator {
23    fn generate_raw_args(&self, arg_start_id: usize) -> proc_macro2::TokenStream;
24}
25
26impl ForeignModArgGlueCodeGenerator for ParsedType {
27    fn generate_raw_args(&self, arg_start_id: usize) -> proc_macro2::TokenStream {
28        let arg = crate::new_ident!(format!("arg_{}", arg_start_id));
29
30        match self {
31            ParsedType::Utf8Str(_) | ParsedType::Utf8String(_) => {
32                quote! { #arg.as_ptr() as _, #arg.len() as _ }
33            }
34            ParsedType::Vector(..) => {
35                quote! { #arg.0 as _, #arg.1 as _ }
36            }
37            ParsedType::Record(..) => quote! {
38                #arg.__m_generated_serialize() as _
39            },
40            ty @ ParsedType::Boolean(_) => {
41                let deref_sign = maybe_deref(ty);
42                quote! { #deref_sign#arg as _ }
43            }
44            // this branch shouldn't be unite with booleans because otherwise
45            // conversion errors could be lost due to `as _` usage
46            ty => {
47                let deref_sign = maybe_deref(ty);
48                quote! { #deref_sign#arg }
49            }
50        }
51    }
52}
53
54fn maybe_deref(ty: &ParsedType) -> proc_macro2::TokenStream {
55    use crate::parsed_type::PassingStyle;
56
57    let passing_style = crate::parsed_type::passing_style_of(ty);
58
59    match passing_style {
60        PassingStyle::ByValue => proc_macro2::TokenStream::new(),
61        _ => quote! { * },
62    }
63}