yeter-macros 0.5.0

Procedural macros for yeter
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
use proc_macro2::{Ident, Span, TokenStream};
use proc_macro_error::*;
use quote::quote;
use syn::punctuated::Punctuated;
use syn::{
    parse_quote, Attribute, Expr, ExprField, ExprPath, ExprTuple, FnArg, ForeignItemFn,
    GenericArgument, GenericParam, Index, ItemFn, Member, Pat, PatIdent, PatType, Path,
    PathArguments, PathSegment, ReturnType, Signature, Token, Type, TypePath, TypeReference,
    TypeTuple, Visibility, WhereClause,
};

fn fn_arg_to_type(arg: &FnArg) -> &Type {
    match arg {
        FnArg::Receiver(_) => unimplemented!(),
        FnArg::Typed(arg) => arg.ty.as_ref(),
    }
}

fn build_type_tuple(types: impl Iterator<Item = Type>) -> Type {
    let mut elems = types.collect::<Punctuated<_, Token![,]>>();
    if !elems.is_empty() {
        elems.push_punct(Default::default());
    }

    Type::Tuple(TypeTuple {
        paren_token: Default::default(),
        elems,
    })
}

fn build_unit_tuple() -> Type {
    build_type_tuple([].into_iter())
}

fn arg_name(arg: &FnArg) -> Option<Ident> {
    match arg {
        FnArg::Receiver(_) => Some(Ident::new("self", Span::call_site())),
        FnArg::Typed(pat_type) => {
            if let Pat::Ident(name) = pat_type.pat.as_ref() {
                Some(name.ident.clone())
            } else {
                None
            }
        }
    }
}

fn arg_names<'a>(args: impl Iterator<Item = &'a FnArg>) -> Vec<Ident> {
    args.enumerate()
        .map(|(n, arg)| {
            arg_name(arg).unwrap_or_else(|| Ident::new(&format!("arg{n}"), Span::mixed_site()))
        })
        .collect()
}

fn calling_tuple_args(idents: impl Iterator<Item = (Ident, Type)>) -> Punctuated<FnArg, Token![,]> {
    idents
        .map(|(name, typ)| {
            FnArg::Typed(PatType {
                attrs: Default::default(),
                pat: Box::new(Pat::Ident(PatIdent {
                    attrs: Default::default(),
                    by_ref: None,
                    mutability: None,
                    subpat: None,
                    ident: name,
                })),
                colon_token: Default::default(),
                ty: Box::new(typ),
            })
        })
        .collect()
}

fn build_ident_tuple(idents: impl Iterator<Item = Ident>) -> Expr {
    let mut elems = idents
        .map(ident_to_expr)
        .collect::<Punctuated<_, Token![,]>>();
    if !elems.is_empty() {
        elems.push_punct(Default::default());
    }

    ExprTuple {
        attrs: Default::default(),
        paren_token: Default::default(),
        elems,
    }
    .into()
}

fn ident_to_expr(id: Ident) -> Expr {
    ExprPath {
        attrs: Default::default(),
        qself: Default::default(),
        path: Path::from(id),
    }
    .into()
}

/// Converts generic arguments to generic params (effectively dismissing all ": ???" bounds)
fn use_generic_args(
    generics: &Punctuated<GenericParam, Token![,]>,
) -> Punctuated<GenericArgument, Token![,]> {
    generics
        .iter()
        .map(|p| match p {
            GenericParam::Type(t) => GenericArgument::Type(
                TypePath {
                    qself: None,
                    path: t.ident.clone().into(),
                }
                .into(),
            ),
            GenericParam::Lifetime(l) => GenericArgument::Lifetime(l.lifetime.clone()),
            GenericParam::Const(c) => GenericArgument::Const(ident_to_expr(c.ident.clone())),
        })
        .collect()
}

fn generic_args_phantom(generics: &Punctuated<GenericArgument, Token![,]>) -> Type {
    build_type_tuple(generics.iter().filter_map(|a| {
        match a {
            GenericArgument::Binding(_) => unreachable!(),
            GenericArgument::Constraint(_) => unreachable!(),
            GenericArgument::Type(t) => Some(t.clone()),
            GenericArgument::Const(_) => None,
            GenericArgument::Lifetime(lt) => Some(
                TypeReference {
                    lifetime: Some(lt.clone()),
                    mutability: None,
                    and_token: Default::default(),
                    elem: Box::new(build_unit_tuple()),
                }
                .into(),
            ),
        }
    }))
}

#[proc_macro_error]
#[proc_macro_attribute]
pub fn query(
    attr: proc_macro::TokenStream,
    item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    if !attr.is_empty() {
        emit_error!(
            TokenStream::from(attr),
            "#[yeter::query] doesn't expect any attributes"
        );
    }

    let mut function_no_impl;
    let mut function_impl;
    let function = {
        if let Ok(f) = syn::parse::<ForeignItemFn>(item.clone()) {
            function_no_impl = f;
            &mut function_no_impl as &mut dyn FunctionItem
        } else if let Ok(f) = syn::parse::<ItemFn>(item.clone()) {
            function_impl = f;
            &mut function_impl as &mut dyn FunctionItem
        } else {
            let item = TokenStream::from(item);
            return (quote! { compile_error!("expected fn item"); #item }).into();
        }
    };

    let query_attrs = function.take_attrs();
    let fn_args = &function.sig().inputs;
    let query_args = fn_args
        .iter()
        .skip(1)
        .map(fn_arg_to_type)
        .cloned()
        .collect::<Vec<_>>();

    let db_ident_fallback = Ident::new("db", Span::call_site());
    match fn_args.first() {
        // self, &self, &mut self
        Some(receiver @ FnArg::Receiver(_)) => {
            emit_error!(
                receiver,
                "#[yeter::query] can't be used on instance methods";
                hint = "did you mean `db: &yeter::Database`?";
            );

            &db_ident_fallback
        }
        Some(FnArg::Typed(pat_type)) => match pat_type.pat.as_ref() {
            Pat::Ident(ident) => &ident.ident,
            _ => {
                emit_error!(
                    pat_type.pat,
                    "simple database argument pattern expected";
                    help = "use a simple argument declaration such as `db: &yeter::Database`";
                );

                &db_ident_fallback
            }
        },
        None => {
            emit_error!(
                function.sig(), "a query must take a database as its first argument";
                note = "no arguments were specified";
            );

            &db_ident_fallback
        }
    };

    let fn_arg_count = fn_args.len() as u32;
    let query_arg_count = if fn_arg_count == 0 {
        0
    } else {
        fn_arg_count - 1
    };

    let unit_type;

    let query_vis = &function.vis();
    let query_name = &function.sig().ident;
    let generics = &function.sig().generics;
    let generics_params = &generics.params;
    let generics_where = &generics.where_clause;
    let generics_args = use_generic_args(generics_params);
    let generics_phantom = generic_args_phantom(&generics_args);

    let input_type = build_type_tuple(query_args.iter().cloned());
    let output_type = match &function.sig().output {
        ReturnType::Default => {
            unit_type = build_unit_tuple();
            &unit_type
        }
        ReturnType::Type(_, typ) => typ.as_ref(),
    };

    let calling_arg_names = arg_names(fn_args.iter().skip(1));

    let calling_tuple_args = calling_tuple_args(calling_arg_names.iter().cloned().zip(query_args));
    let calling_tuple = build_ident_tuple(calling_arg_names.into_iter());

    let call_ident_span = Span::call_site().located_at(query_name.span());
    // When Span::def_site is stable, we will be able to properly create hygienic idents
    let call_ident = Ident::new(&format!("__yeter_{query_name}"), call_ident_span);

    let to_function_impl = function.to_function_impl(&call_ident, generics_params, output_type);
    let to_function_call = function.to_function_call(&call_ident, query_arg_count);
    let to_additional_impl = function.to_additional_impl(
        query_name,
        generics_params,
        &generics_args,
        generics_where,
        output_type,
    );

    let expanded = quote! {
        #(#query_attrs)*
        #query_vis fn #query_name<#generics_params>(db: &::yeter::Database, #calling_tuple_args) -> ::std::rc::Rc<#output_type>
            #generics_where
        {
            #to_function_impl
            db.run::<_, #query_name::<#generics_args>>(#to_function_call, #calling_tuple)
        }

        #[allow(non_camel_case_types)]
        #[doc(hidden)]
        #query_vis enum #query_name<#generics_params> {
            Phantom(std::convert::Infallible, std::marker::PhantomData<#generics_phantom>),
        }

        impl<#generics_params> ::yeter::QueryDef for #query_name<#generics_args> #generics_where {
            type Input = #input_type;
            type Output = #output_type;
        }

        #to_additional_impl
    };

    set_dummy(expanded.clone()); // Still produce these tokens if an error was emitted
    expanded.into()
}

trait FunctionItem {
    fn take_attrs(&mut self) -> Vec<Attribute>;
    fn vis(&self) -> &Visibility;
    fn sig(&self) -> &Signature;

    fn to_function_impl(
        &self,
        _call_ident: &Ident,
        _generics_params: &Punctuated<GenericParam, Token![,]>,
        _output_type: &Type,
    ) -> TokenStream {
        quote! {}
    }

    fn to_function_call(&self, _call_ident: &Ident, _query_arg_count: u32) -> TokenStream;

    fn to_additional_impl(
        &self,
        _query_name: &Ident,
        _generics_params: &Punctuated<GenericParam, Token![,]>,
        _generics_args: &Punctuated<GenericArgument, Token![,]>,
        _generics_where: &Option<WhereClause>,
        _output_type: &Type,
    ) -> TokenStream {
        quote! {}
    }
}

fn guess_option_inner_type(option: &Type) -> Type {
    if let Type::Path(path) = option {
        match path.path.segments.last() {
            Some(seg) if seg.ident != "Option" => {
                emit_error!(seg.ident, "expected `Option` type",);
            }
            Some(PathSegment {
                arguments: PathArguments::AngleBracketed(angle),
                ..
            }) if angle.args.len() == 1 => match angle.args.first().unwrap() {
                GenericArgument::Type(t) => return t.clone(),
                o => {
                    emit_error!(o, "unexpected generic argument for Option type",);
                }
            },
            Some(seg) => {
                emit_error!(seg, "expected Option<T> return type",);
            }
            None => {
                emit_error!(path, "expected Option<T> return type",);
            }
        }
    };

    parse_quote! { Option<()> }
}

impl FunctionItem for ForeignItemFn {
    fn take_attrs(&mut self) -> Vec<Attribute> {
        std::mem::take(&mut self.attrs)
    }

    fn vis(&self) -> &Visibility {
        &self.vis
    }

    fn sig(&self) -> &Signature {
        &self.sig
    }

    fn to_function_call(&self, _call_ident: &Ident, _query_arg_count: u32) -> TokenStream {
        quote! {
            |_db, _input| None
        }
    }

    fn to_additional_impl(
        &self,
        query_name: &Ident,
        generics_params: &Punctuated<GenericParam, Token![,]>,
        generics_args: &Punctuated<GenericArgument, Token![,]>,
        generics_where: &Option<WhereClause>,
        output_type: &Type,
    ) -> TokenStream {
        // Output should be an option; we try to guess what could be inside
        let output_type = guess_option_inner_type(output_type);

        quote! {
            impl<#generics_params> ::yeter::InputQueryDef for #query_name<#generics_args> #generics_where {
                type OptionalOutput = #output_type;
            }
        }
    }
}

impl FunctionItem for ItemFn {
    fn take_attrs(&mut self) -> Vec<Attribute> {
        std::mem::take(&mut self.attrs)
    }

    fn vis(&self) -> &Visibility {
        &self.vis
    }

    fn sig(&self) -> &Signature {
        &self.sig
    }

    fn to_function_impl(
        &self,
        call_ident: &Ident,
        _generics_params: &Punctuated<GenericParam, Token![,]>,
        _output_type: &Type,
    ) -> TokenStream {
        let mut s = self.clone();
        s.sig.ident = call_ident.clone();

        quote! {
            #[allow(clippy::needless_lifetimes)]
            #s
        }
    }

    fn to_function_call(&self, call_ident: &Ident, query_arg_count: u32) -> TokenStream {
        let db_ident = Ident::new("db", Span::mixed_site());
        let input_ident = Ident::new("input", Span::mixed_site());
        let input_ident_expr = Box::new(ident_to_expr(input_ident.clone()));
        let calling_args = (0..query_arg_count)
            .map(|n| {
                Expr::Field(ExprField {
                    attrs: Default::default(),
                    base: input_ident_expr.clone(),
                    dot_token: Default::default(),
                    member: Member::Unnamed(Index {
                        index: n,
                        span: Span::mixed_site(),
                    }),
                })
            })
            .collect::<Punctuated<_, Token![,]>>();

        quote! {
            |#db_ident, #input_ident| #call_ident(#db_ident, #calling_args)
        }
    }
}