hooks-macro-core 0.4.0

Compile-time, async hooks
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
use std::borrow::Cow;

use darling::{ast::NestedMeta, FromMeta};
use proc_macro2::Span;
use quote::{quote_spanned, ToTokens};
use syn::spanned::Spanned;

use crate::{
    captures::capture_lifetimes,
    detect_hooks, detected_hooks_to_tokens,
    utils::{
        chain::Chain,
        either::Either,
        empty_or_trailing::AutoEmptyOrTrailing,
        group::angled,
        map::map_to_tokens,
        path_or_lit::PathOrLit,
        phantom::{make_phantom_or_ref, PhantomOfTy},
        repeat::Repeat,
        type_generics::TypeGenericsWithoutBraces,
    },
    DetectedHooksTokens,
};

#[cfg_attr(feature = "extra-traits", derive(PartialEq, Eq))]
#[derive(Debug, Default, FromMeta)]
#[non_exhaustive]
#[darling(default)]
pub struct HookArgs {
    /// Defaults to `::hooks::core`
    pub hooks_core_path: Option<PathOrLit<syn::Path>>,

    /// When a hook fn borrows from a lifetime,
    /// this bound might need to be explicitly specified.
    ///
    /// Note that all lifetimes declared in fn generics are auto captured by `#[hook]`.
    /// Thus, `#[hook(bounds = "...")]` is only required for
    /// elided lifetimes and outer lifetimes.
    ///
    /// ```compile_fail
    /// # extern crate hooks_dev as hooks;
    /// # use hooks::prelude::*;
    /// #[hook]
    /// fn use_borrow(v: &str) -> usize {
    ///     v.len()
    /// }
    /// ```
    ///
    /// ```
    /// # extern crate hooks_dev as hooks;
    /// # use hooks::prelude::*;
    /// #[hook(bounds = "'_")]
    /// fn use_borrow(v: &str) -> usize {
    ///     v.len()
    /// }
    /// ```
    ///
    /// This is equivalent to `type Bounds = impl ...` in
    /// [`hook_fn!(...);`](https://docs.rs/hooks-core/1.0.0-alpha.10/hooks_core/macro.hook_fn.html)
    ///
    /// ```
    /// # extern crate hooks_dev as hooks;
    /// # use hooks::prelude::*;
    /// hook_fn!(
    ///     type Bounds = impl '_;
    ///     fn use_borrow(v: &str) -> usize {
    ///         v.len()
    ///     }
    /// );
    /// ```
    pub bounds: Option<syn::punctuated::Punctuated<syn::TypeParamBound, syn::Token![+]>>,
}

impl HookArgs {
    #[inline]
    pub fn transform_item_fn(
        self,
        mut item_fn: syn::ItemFn,
    ) -> (syn::ItemFn, Option<darling::Error>) {
        let error = self.transform_item_fn_in_place(&mut item_fn);
        (item_fn, error)
    }

    pub fn transform_item_fn_in_place(self, item_fn: &mut syn::ItemFn) -> Option<darling::Error> {
        // let mut errors = darling::error::Accumulator::default();

        let hooks_core_path = self.hooks_core_path.map_or_else(
            || syn::Path {
                leading_colon: Some(Default::default()),
                segments: syn::punctuated::Punctuated::from_iter([
                    syn::PathSegment::from(syn::Ident::new("hooks", Span::call_site())),
                    syn::PathSegment::from(syn::Ident::new("core", Span::call_site())),
                ]),
            },
            PathOrLit::unwrap,
        );

        let bounds = self.bounds;

        let lifetimes_from_fn_generics = item_fn.sig.generics.lifetimes().map(|lt| &lt.lifetime);
        let lifetimes_from_bounds = bounds.iter().flatten().filter_map(|bound| match bound {
            syn::TypeParamBound::Lifetime(lt) => Some(lt),
            _ => None,
        });
        let lifetimes = lifetimes_from_fn_generics.chain(lifetimes_from_bounds);

        let captures = capture_lifetimes(
            lifetimes,
            quote_spanned!(hooks_core_path.span() => #hooks_core_path::Captures),
        );

        // Trait bounds only
        let bounds = bounds.map(|bounds| {
            bounds
                .into_pairs()
                .filter_map(|pair| {
                    let (bound, punc) = pair.into_tuple();
                    match bound {
                        syn::TypeParamBound::Trait(tb) => {
                            Some(syn::punctuated::Pair::new(tb, punc))
                        }
                        _ => None,
                    }
                })
                .collect::<syn::punctuated::Punctuated<syn::TraitBound, _>>()
        });

        let bounds = match (captures, bounds) {
            (Some(captures), Some(bounds)) => Some({
                let mut ts = captures;

                ts.extend([
                    //
                    quote_spanned!(item_fn.sig.fn_token.span() =>  +),
                    bounds.into_token_stream(),
                ]);

                ts
            }),
            (a, b) => a.or(b.map(ToTokens::into_token_stream)),
        };

        let sig = &mut item_fn.sig;

        let span_fn_name = sig.ident.span();

        let generics = &sig.generics;

        let (impl_generics, type_generics, where_clause) = generics.split_for_impl();

        let hooks_value_struct_field_ty = map_to_tokens(&generics.params, |params| {
            params.pairs().filter_map(|p| {
                make_phantom_or_ref(p.value()).map(|v| {
                    Chain(
                        v,
                        p.punct()
                            .map_or_else(|| Cow::Owned(Default::default()), |v| Cow::Borrowed(*v)),
                    )
                })
            })
        });

        let mut output_ty: syn::Type = {
            let fn_rt = &mut sig.output;
            let span;
            match fn_rt {
                syn::ReturnType::Default => {
                    span = span_fn_name;
                    let output_ty = syn::Type::Tuple(syn::TypeTuple {
                        paren_token: syn::token::Paren(span),
                        elems: Default::default(),
                    });
                    *fn_rt = syn::ReturnType::Type(
                        syn::Token![->](span),
                        Box::new(syn::Type::Verbatim(utils::UpdateHookUninitialized(
                            &hooks_core_path,
                            span,
                            quote_spanned!(span=> ()),
                            bounds,
                        ))),
                    );

                    output_ty
                }
                syn::ReturnType::Type(ra, ty) => {
                    span = ra.span();
                    let it = utils::UpdateHookUninitialized(&hooks_core_path, span, &**ty, bounds);
                    std::mem::replace(&mut **ty, syn::Type::Verbatim(it))
                }
            }
        };

        // T,
        let fn_type_generics_eot = AutoEmptyOrTrailing(TypeGenericsWithoutBraces(&generics.params));

        // HooksImplTrait0: Debug, HooksImplTrait1: Any,
        //      introduced by impl trait in return position
        let it_impl_generics_eot = extract_impl_trait_as_type_params(&mut output_ty);

        // HooksImplTrait0, HooksImplTrait1,
        let it_type_generics_eot = map_to_tokens(&it_impl_generics_eot, |v| {
            v.iter().map(|pair| Chain(&pair.0.ident, &pair.1))
        });

        // PhantomData<T>, PhantomData<HooksImplTrait0>, PhantomData<HooksImplTrait1>,
        let hook_types_phantoms_eot;
        // <T: Clone, HooksImplTrait0: Debug, HooksImplTrait1: Any,>
        let hook_types_impl_generics;
        // <T, HooksImplTrait0, HooksImplTrait1,>
        let hook_types_type_generics;
        // _, _,
        let it_generics_elided_without_braces_eot;

        if it_impl_generics_eot.is_empty() {
            hook_types_phantoms_eot = Either::A(&hooks_value_struct_field_ty);
            hook_types_impl_generics = Either::A(impl_generics);
            hook_types_type_generics = Either::A(&type_generics);
            it_generics_elided_without_braces_eot = None;
        } else {
            hook_types_phantoms_eot = Either::B(Chain(
                &hooks_value_struct_field_ty,
                map_to_tokens(&it_impl_generics_eot, |v| {
                    v.iter()
                        .map(|pair| Chain(PhantomOfTy(&pair.0.ident), pair.1))
                }),
            ));

            hook_types_impl_generics = Either::B(angled(Chain(
                AutoEmptyOrTrailing(&sig.generics.params),
                map_to_tokens(&it_impl_generics_eot, |v| v.iter()),
            )));

            hook_types_type_generics =
                Either::B(angled(Chain(&fn_type_generics_eot, &it_type_generics_eot)));

            it_generics_elided_without_braces_eot = Some(Repeat(
                Chain(<syn::Token![_]>::default(), <syn::Token![,]>::default()),
                it_impl_generics_eot.len(),
            ));
        };

        // T: Clone,
        // The generics comes from `fn`, so there won't be default types like `<T = i32>`
        let fn_impl_generics_without_braces_eot = AutoEmptyOrTrailing(&sig.generics.params);

        let mut impl_use_hook = std::mem::take(&mut item_fn.block.stmts);

        let used_hooks = detect_hooks(impl_use_hook.iter_mut(), &hooks_core_path);

        let DetectedHooksTokens {
            fn_arg_data_pat: arg_hooks_data,
            fn_stmts_extract_data: impl_extract_hooks_data,
        } = detected_hooks_to_tokens(used_hooks.hooks, &hooks_core_path, sig.fn_token.span);

        item_fn.block.stmts.push(syn::Stmt::Expr(
            syn::Expr::Verbatim(
                //
                quote_spanned! { span_fn_name =>
                    enum __HooksImplNever {}

                    struct __HooksValueOfThisHook #hook_types_impl_generics
                    #where_clause
                    {
                        __: (
                            __HooksImplNever,
                            #hook_types_phantoms_eot
                        )
                    }

                    impl<
                        'hook,
                        #fn_impl_generics_without_braces_eot
                        #(#it_impl_generics_eot)*
                    > #hooks_core_path::HookValue<'hook> for
                        __HooksValueOfThisHook #hook_types_type_generics
                        #where_clause {
                        type Value = #output_ty;
                    }

                    #hooks_core_path::fn_hook::use_fn_hook::<
                        __HooksValueOfThisHook<
                            #fn_type_generics_eot
                            #it_generics_elided_without_braces_eot
                        >, _, _
                    >
                    (
                        move |#arg_hooks_data| {
                            #impl_extract_hooks_data

                            #(#impl_use_hook)*
                        }
                    )
                },
            ),
            None,
        ));

        // errors.finish().err()
        None
    }

    pub fn from_punctuated_meta_list(
        meta_list: syn::punctuated::Punctuated<NestedMeta, syn::Token![,]>,
    ) -> darling::Result<Self> {
        let args: Vec<NestedMeta> = meta_list.into_iter().collect();
        Self::from_list(&args)
    }
}

fn replace_impl_trait_in_type(
    ty: &mut syn::Type,
    f: &mut impl FnMut(&mut syn::TypeImplTrait) -> syn::Type,
) {
    match ty {
        syn::Type::Array(ta) => replace_impl_trait_in_type(&mut ta.elem, f),
        syn::Type::BareFn(_) => {}
        syn::Type::Group(g) => replace_impl_trait_in_type(&mut g.elem, f),
        syn::Type::ImplTrait(it) => {
            // TODO: resolve `impl Trait` in it.bounds
            // f(it.bounds)

            *ty = f(it)
        }
        syn::Type::Infer(_) => {}
        syn::Type::Macro(_) => {}
        syn::Type::Never(_) => {}
        syn::Type::Paren(p) => {
            let is_impl_trait = matches!(&*p.elem, syn::Type::ImplTrait(_));
            replace_impl_trait_in_type(&mut p.elem, f);

            const DUMMY_TYPE: syn::Type = syn::Type::Path(syn::TypePath {
                qself: None,
                path: syn::Path {
                    leading_colon: None,
                    segments: syn::punctuated::Punctuated::new(),
                },
            });
            // also remove the paren for (HookImplTrait0)
            if is_impl_trait {
                let new_ty = std::mem::replace(&mut *p.elem, DUMMY_TYPE);
                *ty = new_ty;
            }
        }
        syn::Type::Path(tp) => {
            if let Some(qself) = &mut tp.qself {
                replace_impl_trait_in_type(&mut qself.ty, f);
            }
            for seg in tp.path.segments.iter_mut() {
                match &mut seg.arguments {
                    syn::PathArguments::None => {}
                    syn::PathArguments::AngleBracketed(a) => {
                        for arg in a.args.iter_mut() {
                            match arg {
                                syn::GenericArgument::Lifetime(_) => {}
                                syn::GenericArgument::Type(ty) => {
                                    replace_impl_trait_in_type(ty, f);
                                }
                                syn::GenericArgument::Const(_) => {}
                                syn::GenericArgument::Constraint(_) => {}
                                syn::GenericArgument::AssocType(assoc) => {
                                    replace_impl_trait_in_type(&mut assoc.ty, f);
                                }
                                syn::GenericArgument::AssocConst(_) => {}
                                _ => {}
                            }
                        }
                    }
                    syn::PathArguments::Parenthesized(_) => {
                        // TODO: resolve `impl Trait` in path like `Fn(impl Trait) -> impl Trait`
                    }
                }
            }
            // TODO: resolve `impl Trait` in path like `Struct<impl Trait>`
        }
        syn::Type::Ptr(ptr) => replace_impl_trait_in_type(&mut ptr.elem, f),
        syn::Type::Reference(r) => replace_impl_trait_in_type(&mut r.elem, f),
        syn::Type::Slice(s) => replace_impl_trait_in_type(&mut s.elem, f),
        syn::Type::TraitObject(_) => {
            // TODO: resolve `impl Trait` in to.bounds
            // f(to.bounds)
        }
        syn::Type::Tuple(t) => {
            for elem in t.elems.iter_mut() {
                replace_impl_trait_in_type(elem, f);
            }
        }
        syn::Type::Verbatim(_) => {}
        _ => {}
    }
}

/// The returned Punctuated is guaranteed to be `empty_or_trailing`
fn extract_impl_trait_as_type_params(
    output_ty: &mut syn::Type,
) -> Vec<Chain<syn::TypeParam, syn::Token![,]>> {
    let mut ret = vec![];
    replace_impl_trait_in_type(output_ty, &mut |ty| {
        let id = ret.len();
        let span = ty.impl_token.span;

        let ident = syn::Ident::new(&format!("HooksImplTrait{id}"), span);

        ret.push(Chain(
            syn::TypeParam {
                attrs: vec![],
                ident: ident.clone(),
                colon_token: Some(syn::Token![:](span)),
                bounds: std::mem::take(&mut ty.bounds),
                eq_token: None,
                default: None,
            },
            syn::Token![,](span),
        ));

        syn::Type::Path(syn::TypePath {
            qself: None,
            path: ident.into(),
        })
    });
    ret
}

mod utils {
    use darling::ToTokens;
    use proc_macro2::{Span, TokenStream};
    use quote::quote_spanned;
    use syn::spanned::Spanned;

    use crate::utils::chain::Chain;

    #[allow(non_snake_case)]
    pub fn UpdateHookUninitialized(
        hooks_core_path: &impl ToTokens,
        span: Span,
        value_ty: impl ToTokens,
        bounds: Option<impl ToTokens>,
    ) -> TokenStream {
        let bounds = bounds.map(|bounds| {
            let bounds = bounds.into_token_stream();

            Chain(syn::Token![+](bounds.span()), bounds)
        });

        quote_spanned! {span=>
            impl #hooks_core_path::UpdateHookUninitialized<
                Uninitialized =
                    impl #hooks_core_path::HookPollNextUpdate
                        + #hooks_core_path::HookUnmount
                        + ::core::default::Default
                        #bounds
                ,
                Hook = impl #hooks_core_path::Hook + for<'hook> #hooks_core_path::HookValue<'hook, Value = #value_ty>
                #bounds
            >
        }
    }
}