fproxy_derive 0.0.2

Macro's needed by fproxy
Documentation
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
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509

use std::{fmt::Display};

use proc_macro::{TokenStream};
use proc_macro2::{Literal, Span, TokenStream as Quote};
use quote::{quote, ToTokens};
use syn::{parse::{Parse, ParseStream}, punctuated::Punctuated, token::{Comma, Pub}, Attribute, FnArg, Ident, ImplItem, ImplItemFn, ItemImpl, ItemTrait, Lifetime, LitByteStr, Pat, Receiver, ReturnType, Signature, Token, TraitItem, TraitItemFn, Type, TypeImplTrait, TypeParamBound, Visibility};

use crate::tfident;


struct Args {
  tag: bool,
}

impl Parse for Args {
  fn parse(input: ParseStream) -> syn::Result<Self> {
    let mut vec = Vec::new();
    loop {
      if let Ok(l) = input.parse::<Literal>() {
        vec.push(l.to_string().trim_matches('\"').to_string());
      }
      if input.parse::<Token![,]>().is_err() {
        break;
      }
    }
    Ok(Args{
      tag: vec.contains(&format!("tag")),
    })
  }
}
impl Default for Args {
  fn default() -> Self {
    Args { tag: false }
  }
}

pub(crate) struct ItemDetails {
  args: Args,
  ident: Ident,
  is_trait: bool,
}
impl ItemDetails {
  fn from_impl(args: &TokenStream, input: &ItemImpl) -> Self {
    ItemDetails { 
      args: syn::parse(args.clone())
        .expect("failed to parse args"),
      ident: match input.self_ty.as_ref() {
        Type::Path(type_path) => type_path.path.get_ident().expect("expected struct").clone(),
        _ => crate::macro_panic!("expected struct"),
      }, 
      is_trait: false,
    }
  }
}

impl From<&ItemTrait> for ItemDetails {
  fn from(item: &ItemTrait) -> Self {
    ItemDetails { 
      args: Args::default(),
      ident: item.ident.clone(), 
      is_trait: true, 
    }
  }
}

impl Display for ItemDetails {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str(&format!("{}", &self.ident))
  }
}
impl ToTokens for ItemDetails {
  fn to_tokens(&self, tokens: &mut Quote) {
    self.ident.to_tokens(tokens);
  }
}


pub(crate) struct FunctionDetails {
  // the elements of the function relevant to this macro.
  vis: Visibility,
  sig: Signature,
  // specific details about the function.
  tag: bool,
  slf: Option<Receiver>,  // The self parameter, if present.
  prv: bool,              // Whether the function is private.
  new: bool,              // Whether the function is constructor.
  lib: bool,              // Whether the library is owned by the proxy (needed for the constructor).
  ignore: bool,           // Whether the function is explicitly ignored.
  returns_impl: Option<Punctuated<TypeParamBound, Token![+]>>, // Whether the function returns `impl T`
}
impl FunctionDetails {

  fn new(attrs: Vec<Attribute>, vis: Visibility, sig: Signature) -> Self {
    
    // This is bad.
    let tag = attrs
      .iter()
      .filter(|atr| atr.to_token_stream().to_string().contains("fproxy"))
      .next()
      .map_or(String::new(), |atr| atr.to_token_stream().to_string());

    let mut fun = FunctionDetails {
        vis,
        sig,
        tag: tag.contains("tag"),
        slf: None,
        prv: false,
        new: tag.contains("new"),
        lib: tag.contains("lib"),
        ignore: tag.contains("ignore"),
        returns_impl: None,
    };
    
    if let Some(FnArg::Receiver(slf)) = fun.sig.inputs.first() {
      fun.slf = Some(slf.clone());
    }
    fun.prv = !matches!(fun.vis, Visibility::Public(_));

    if let ReturnType::Type(_, typ) = fun.sig.output.clone() {
      if let Type::ImplTrait(TypeImplTrait { impl_token: _, bounds }) = *typ {
        fun.returns_impl = Some(bounds);
      }
    }

    if fun.new && fun.slf.is_some() {
      crate::macro_panic!("function {} is annotated with #[fproxy::imp(\"new\"), it cannot have a self paramter", &fun.sig.ident);
    }

    fun
  }

  /// Given the ident of the type for which this function is 
  /// implemented, generate the `extern "C"` name.
  fn extern_c_name(&self, ident: &Ident) -> Ident {
    Ident::new(&format!("_fproxy_{ident}_{}", &self.sig.ident), ident.span())
  }
  fn output(&self, ident: &Ident) -> Quote {
    match self.sig.output.clone() {
      ReturnType::Default => quote!(()),
      ReturnType::Type(_, mut typ) => {
        match typ.as_mut() {
          Type::Path(path) if path.path.segments.first().unwrap().ident.to_string() == "Self" => {
            return quote!(#ident);
          },
          Type::Reference(refr) => {
            refr.lifetime = Some(Lifetime::new("'static", Span::call_site()));
          }
          Type::ImplTrait(TypeImplTrait { impl_token: _, bounds }) => {
            return quote!(Box<dyn #bounds>);
          },
          _ => (),
        };
        return quote!(#typ);
      },
    }
  }

  fn should_ignore(&self, item: &ItemDetails) -> bool {
    (!self.slf.is_some() && !self.new) ||
    self.prv || 
    self.ignore ||
    (item.args.tag && !self.tag)
  }
  fn self_as_trait(&self, item: &ItemDetails) -> Option<Quote> {
    if item.is_trait {
      if let Some(slf) = &self.slf {
        let refr = slf.reference.clone().map(|(and, _)| and);
        let mutb = &slf.mutability;
        return Some(quote! {#refr #mutb dyn #item});
      }
    } 
    None
  }


}

impl From<&ImplItemFn> for FunctionDetails {
  fn from(fun: &ImplItemFn) -> Self {
    FunctionDetails::new( 
      fun.attrs.clone(), 
      fun.vis.clone(), 
      fun.sig.clone(), 
    )
  }
}
impl From<&TraitItemFn> for FunctionDetails {
  fn from(fun: &TraitItemFn) -> Self {
    FunctionDetails::new(
      fun.attrs.clone(), 
      Visibility::Public(Pub::default()), 
      fun.sig.clone(), 
    )
  }
}


pub(crate) fn imp(args: TokenStream, input: ItemImpl) -> TokenStream {

  let item = ItemDetails::from_impl(&args, &input);
  let tfident = tfident(&item.ident);

  fn iter(input: &ItemImpl) -> impl Iterator<Item = FunctionDetails> {
    input.items
      .iter()
      .filter_map(|item| match item {
        ImplItem::Fn(fun) => Some(fun),
        _ => None,
      })
      .map(FunctionDetails::from)
  }

  let funs = make_funs(&item, iter(&input));
  let c_funs = make_c_funs(&item, iter(&input));

  quote! {

    impl #tfident<'_> {
      #funs
    }

    #input

    #c_funs

  }
    .into()
}
pub(crate) fn imp_trait(_: TokenStream, input: ItemTrait) -> TokenStream {

  let item = ItemDetails::from(&input);
  let tfident = tfident(&item.ident);

  fn iter(input: &ItemTrait) -> impl Iterator<Item = FunctionDetails> {
    input.items
      .iter()
      .filter_map(|item| {
        match item {
          TraitItem::Fn(fun) => {
            Some(FunctionDetails::from(fun))
          },
          _ => None,
        }
      })
  }

  let funs = make_funs(&item, iter(&input));
  let c_funs = make_c_funs(&item, iter(&input));


  quote! {

    impl #tfident<'_> {
      #funs
    }

    #c_funs

  }
    .into()
}

fn make_funs(ident: &ItemDetails, funs: impl Iterator<Item = FunctionDetails>) -> Quote {
  funs
    .map(|fun| imp_fun(ident, &fun))
    .fold(Quote::new(), |q, fun| quote!(#q #fun))
}
fn make_c_funs(ident: &ItemDetails, funs: impl Iterator<Item = FunctionDetails>) -> Quote {
  funs
    .map(|fun| imp_c_fun(ident, &fun))
    .fold(Quote::new(), |q, fun| quote!(#q #fun))
}


fn imp_c_fun(item: &ItemDetails, fun: &FunctionDetails) -> Quote {
  
  if fun.should_ignore(item) {
    return quote!();
  }

  let input = Input::from(fun);
  let fname = fun.extern_c_name(&item.ident);

  // The c function takes FReprC parameters, convert them back to 
  // the original rust types.
  //let mut input_names = input.names(|name| {
  //  quote!(fproxy::FFromC::from_c(#name))
  //});
  let mut input_names = input.patterns(|name, typ| {
    quote!(<#typ as fproxy::FFromC>::from_c(#name))
  });

  // The input needs to be FReprC.
  // The original input is mapped to there C types.
  let mut input = input.fold(|q, (ident, typ)| {
    quote!(#q #ident: <#typ as fproxy::FToC>::CType)
  });

  if !fun.new {
    input_names = if let Some(slf) = fun.self_as_trait(item) {
      quote!(
        <#slf as fproxy::FFromC>::from_c(handle), 
        #input_names
      )
    } else {
      quote!(
        fproxy::FFromC::from_c(handle), 
        #input_names
      )
    };
    input = quote!(handle: *const (), #input);
  }

  let name = &fun.sig.ident;

  let body = if let Some(bounds) = &fun.returns_impl {
    quote! {
      fproxy::FToC::to_c(
        Box::new(
          #item::#name(#input_names)
        ) as Box<dyn #bounds>
      )
    }
  } else {
    quote! {
      fproxy::FToC::to_c(
        #item::#name(#input_names)
      )
    }
  };

  let output = fun.output(&item.ident);

  quote! {
    /// Inputs and outputs to `extern "C"` functions are `CType`s.
    #[unsafe(no_mangle)]
    unsafe extern "C" fn #fname(#input) -> <#output as fproxy::FToC>::CType {
      #body
    }
  } 
}
fn imp_fun(item: &ItemDetails, fun: &FunctionDetails) -> Quote {

  if fun.should_ignore(item) {
    return quote!();
  }

  let output = fun.output(&item.ident);
  let input = Input::from(fun);
  let mut input = input.fold(|q, (ident, typ)| {
    quote!(#q #ident: #typ)
  });

  // The function either needs a self (which has a library) or 
  // a library in order to execute in the dll.
  if let Some(mut slf) = fun.slf.clone() {
    if let Some((_, l)) = &mut slf.reference {
      *l = Some(Lifetime::new("'l", Span::call_site()));
    } 
    input = quote!(#slf, #input);
  } else {
    if fun.lib {
      input = quote!(lib: &str, #input);
    } else {
      input = quote!(lib: &'l fproxy::libloading::Library, #input);
    }
  }

  let name = &fun.sig.ident;
  let body = make_body(item, fun);

  // Inputs and outputs to proxies are proxies.
  quote! {
   pub fn #name<'l>(#input) -> <#output as fproxy::FAsProxy<'l>>::FSelf {
      let res = #body;
      res
    }
  }
}

fn make_body(item: &ItemDetails, fun: &FunctionDetails) -> Quote {

  let input = Input::from(fun);
  let output = fun.output(&item.ident);
  let fname = fun.extern_c_name(&item.ident);
  let fn_bytes = LitByteStr::new(fname.to_string().as_bytes(), Span::call_site());
  let input_names = input.names(|name| {
    quote!(fproxy::FToC::to_c(#name))
  });
  let input = input.patterns(|ident, typ| {
    quote!(#ident: <#typ as fproxy::FToC>::CType)
  });

  if fun.new {

    let mut _lib = quote! { lib };
    if fun.lib {
      _lib = quote! {
        {
          let mut lib = std::path::PathBuf::from(lib);
          #[cfg(target_os = "windows")]
          lib.set_extension("dll");
          #[cfg(target_os = "macos")] {
            let name = lib.file_name().unwrap().to_str().unwrap();
            let name = format!("lib{name}");
            lib.set_file_name(name);
            lib.set_extension("dylib");
          }
          Library::new(lib.into_os_string().as_os_str()).unwrap()
        }
      };
    }

    quote! {
      {
        unsafe {
          use fproxy::libloading::{Library, Symbol};
          use fproxy::{FToC};
          let lib = #_lib;
          let func: Symbol<unsafe extern "C" fn(#input) -> <#item as FToC>::CType> = 
            lib.get(#fn_bytes).unwrap();
          Self {
            handle: func(#input_names),
            lib,
          }
            .into()
        }
      }
    }

  } else {

    quote! {
      {
        unsafe {
          use fproxy::libloading::{Symbol};
          let func: Symbol<unsafe extern "C" fn(*const (), #input) -> <#output as fproxy::FToC>::CType> = 
            self.lib.get(#fn_bytes).unwrap();
          fproxy::FProxyFrom::<'l>::proxy_from(
            func(self.handle, #input_names), 
            &self.lib
          )
        }
      }
    }

  }
}


/// Dismantles the input into tuples of `Ident` and `Type`. </br>
struct Input {
  names_and_types: Vec<(Ident, Type)>,
}
impl Input {

  //fn name(name: &Ident) -> Quote {
  //  quote!(#name)
  //}
  //fn pattern(ident: &Ident, typ: &Type) -> Quote {
  //  quote!(#ident: #typ)
  //}

  fn fold(&self, f: impl FnMut(Quote, &(Ident, Type)) -> Quote) -> Quote {
    self.names_and_types
      .iter()
      .fold(Quote::new(), f)
  }

  fn names(&self, f: impl Fn(&Ident) -> Quote) -> Quote {
    self.fold(|q, (ident, _)| {
      let name = f(ident);
      quote!(#q #name)
    })
  }
  fn patterns(&self, f: impl Fn(&Ident, &Type) -> Quote) -> Quote {
    self.fold(|q, (ident, typ)| {
      let pattern = f(ident, typ);
      quote!(#q #pattern)
    })
  }

}

impl From<&FunctionDetails> for Input { 
  fn from(fun: &FunctionDetails) -> Self {

    let punct = &fun.sig.inputs;

    /// Remove the `self` parameter and convert to identifiers and types. </br>
    /// The macro needs the type of `self` in order to do the requiered conversions. </br>
    fn remove_self(args: &Punctuated<FnArg, Comma>) -> impl Iterator<Item = (Ident, Type)> {
      args
        .iter()
        .filter(|arg| !matches!(arg, FnArg::Receiver(_)))
        .map(|arg| {
          let FnArg::Typed(typed) = arg else { crate::macro_panic!() }; // should be fine since self is removed
          let Pat::Ident(ident) = typed.pat.as_ref() else { crate::macro_panic!() }; // can function parameters be anything else?
          (ident.ident.clone(), typed.ty.as_ref().clone())
        })
    }

    Input { 
      names_and_types: remove_self(punct).collect()
    }
  }
}