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
use crate::utils::extract_type_from_option;
use crate::Input;

use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote as q;
use syn::{Ident, Type};

pub struct RustExternParams(Vec<TokenStream2>);
pub struct RustTransforms(Vec<TokenStream2>);
pub struct RustArgs(Vec<Ident>);

impl From<&Vec<Input>> for RustExternParams {
  fn from(inputs: &Vec<Input>) -> Self {
    let mut stream = vec![];

    for input in inputs {
      let variable = Ident::new(&input.variable, Span::call_site());
      let c_type = rust_c_type(&input.rust_type);
      stream.push(q!(#variable: #c_type))
    }

    Self(stream)
  }
}

impl From<&Vec<Input>> for RustTransforms {
  fn from(inputs: &Vec<Input>) -> Self {
    let mut stream = vec![];

    for input in inputs {
      let variable = Ident::new(&input.variable, Span::call_site());
      let cast = cast_c_type_to_rust(&input.rust_type, &input.variable, &input.ty);
      stream.push(q!(let #variable = #cast;))
    }

    Self(stream)
  }
}

impl From<&Vec<Input>> for RustArgs {
  fn from(inputs: &Vec<Input>) -> Self {
    let mut stream = vec![];

    for input in inputs {
      stream.push(Ident::new(&input.variable, Span::call_site()))
    }

    Self(stream)
  }
}

impl From<RustExternParams> for Vec<TokenStream2> {
  fn from(types: RustExternParams) -> Self {
    types.0
  }
}

impl From<RustTransforms> for Vec<TokenStream2> {
  fn from(types: RustTransforms) -> Self {
    types.0
  }
}

impl From<RustArgs> for Vec<Ident> {
  fn from(types: RustArgs) -> Self {
    types.0
  }
}

fn rust_c_type(ty: &str) -> TokenStream2 {
  match ty {
    "String" => q!(*const ::std::os::raw::c_char),
    "i64" => q!(::std::os::raw::c_long),
    "f64" => q!(::std::os::raw::c_double),
    "bool" => q!(::std::os::raw::c_char), // i8
    serialized if !serialized.starts_with("Option<") => q!(*const u8),
    "Option<String>" => q!(*const ::std::os::raw::c_char),
    "Option<i64>" => q!(*const ::std::os::raw::c_long),
    "Option<f64>" => q!(*const ::std::os::raw::c_double),
    "Option<bool>" => q!(*const ::std::os::raw::c_char), // i8
    serialized if serialized.starts_with("Option<") => q!(*const u8),
    _ => unreachable!(),
  }
}

fn cast_c_type_to_rust(str_ty: &str, variable: &str, ty: &Type) -> TokenStream2 {
  match str_ty {
    "String" => {
      let variable = Ident::new(variable, Span::call_site());
      q!(cstr!(#variable).to_string())
    }
    "i64" => {
      let variable = Ident::new(variable, Span::call_site());
      q!(#variable)
    }
    "f64" => {
      let variable = Ident::new(variable, Span::call_site());
      q!(#variable)
    }
    "bool" => {
      let variable = Ident::new(variable, Span::call_site());
      q!(#variable != 0)
    }
    serialized if !serialized.starts_with("Option<") => {
      let variable_name = variable;
      let variable = Ident::new(variable, Span::call_site());
      let deserialize = deserialize(variable, variable_name, ty, str_ty);
      q! {
        {
          #deserialize
        }
      }
    }
    "Option<String>" => {
      let variable_name = variable;
      let variable = Ident::new(variable, Span::call_site());
      q! {
        match unsafe { #variable.as_ref() } {
          Some(val) => {
            match unsafe { CStr::from_ptr(val).to_str() } {
              Ok(s) => Some(s.to_string()),
              Err(e) => {
                panic!("An invalid string {:?} was received for {}. {:?}", val, #variable_name, e);
              }
            }
          },
          None => None
        }
      }
    }
    "Option<i64>" => {
      let variable = Ident::new(variable, Span::call_site());
      q! {
        match unsafe { #variable.as_ref() } {
          Some(val) => Some(*val),
          None => None
        }
      }
    }
    "Option<f64>" => {
      let variable = Ident::new(variable, Span::call_site());
      q! {
        match unsafe { #variable.as_ref() } {
          Some(val) => Some(*val),
          None => None
        }
      }
    }
    "Option<bool>" => {
      let variable = Ident::new(variable, Span::call_site());
      q! {
        match unsafe { #variable.as_ref() } {
          Some(val) => Some(*val != 0),
          None => None
        }
      }
    }
    serialized if serialized.starts_with("Option<") => {
      let variable_name = variable;
      let variable = Ident::new(variable, Span::call_site());
      let ty = extract_type_from_option(ty).unwrap();
      let str_ty = q!(#ty).to_string().split_whitespace().collect::<String>();

      let deserialize = deserialize(variable.clone(), variable_name, ty, str_ty.as_str());

      q! {
        {
          match unsafe { #variable.as_ref() } {
            None => None,
            Some(#variable) => {
              Some({
                #deserialize
              })
            }
          }
        }
      }
    }

    _ => unreachable!(),
  }
}

fn deserialize(variable: Ident, variable_name: &str, ty: &Type, str_ty: &str) -> TokenStream2 {
  q! {
    let data = unsafe {
      // read the first 8 bytes to get the length of the full payload (which includes the length byte)
      let length = ::std::slice::from_raw_parts::<u8>(#variable, 1 as usize)[0];
      // read the payload from the pointer
      ::std::slice::from_raw_parts(#variable, length as usize)
    };
    // deserialize, skipping the known 8 byte length field
    ::membrane::bincode::deserialize::<#ty>(&data[8..]).expect(
      format!("Deserialization error at variable '{}' of type '{}'", #variable_name, #str_ty).as_str()
    )
  }
}