luxid-macros 0.1.2

Procedural macros for the Luxid web framework
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
//! `#[luxid::model(..)]` — declares a model's relations.
//!
//! Relations are declared in the attribute arguments rather than as bodiless
//! `fn` items: `fn posts();` is not parseable Rust, so that spelling would
//! greet users with a syntax error from inside a macro. Declaring them here
//! keeps the impl block free for ordinary methods.
//!
//! ```ignore
//! #[luxid::model(
//!     has_many(posts = Post, fk = "user_id"),
//!     belongs_to(team = Team),
//! )]
//! impl User {}
//! ```
//!
//! Each declaration generates an accessor reading the model's relations bag,
//! and one arm of `Relatable::load_relation`, which loads that relation for a
//! whole batch of parents in a single query.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::{FnArg, ImplItem, ItemImpl, LitStr, Path, Token, Type, parse_macro_input};

#[derive(Clone, Copy, PartialEq)]
enum Kind {
    HasMany,
    HasOne,
    BelongsTo,
}

impl Kind {
    fn parse(ident: &syn::Ident) -> Option<Self> {
        match ident.to_string().as_str() {
            "has_many" => Some(Self::HasMany),
            "has_one" => Some(Self::HasOne),
            "belongs_to" => Some(Self::BelongsTo),
            _ => None,
        }
    }

    fn loader(self) -> TokenStream2 {
        match self {
            Self::HasMany => quote!(load_has_many),
            Self::HasOne => quote!(load_has_one),
            Self::BelongsTo => quote!(load_belongs_to),
        }
    }
}

struct Declaration {
    kind: Kind,
    name: syn::Ident,
    target: Type,
    local_key: syn::Ident,
    foreign_key: syn::Ident,
}

impl Parse for Declaration {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let keyword: syn::Ident = input.parse()?;

        let Some(kind) = Kind::parse(&keyword) else {
            return Err(syn::Error::new_spanned(
                &keyword,
                "expected `has_many`, `has_one`, `belongs_to`, or `crate`",
            ));
        };

        let content;
        syn::parenthesized!(content in input);

        // `name = Target`
        let name: syn::Ident = content.parse()?;
        content.parse::<Token![=]>()?;
        let target: Type = content.parse()?;

        let mut foreign: Option<syn::Ident> = None;
        let mut local: Option<syn::Ident> = None;

        while content.peek(Token![,]) {
            content.parse::<Token![,]>()?;
            if content.is_empty() {
                break;
            }

            let key: syn::Ident = content.parse()?;
            content.parse::<Token![=]>()?;
            let value: LitStr = content.parse()?;
            let column = syn::Ident::new(&value.value(), value.span());

            match key.to_string().as_str() {
                "fk" => foreign = Some(column),
                "local_key" => local = Some(column),
                _ => {
                    return Err(syn::Error::new_spanned(
                        &key,
                        "expected `fk` or `local_key`",
                    ));
                }
            }
        }

        // Conventions: the owner is joined on `id`; the side holding the
        // foreign key names it after the relation.
        let (local_key, foreign_key) = match kind {
            Kind::HasMany | Kind::HasOne => {
                let Some(foreign) = foreign else {
                    return Err(syn::Error::new_spanned(
                        &keyword,
                        "specify the foreign key on the related model, e.g. `fk = \"user_id\"`",
                    ));
                };
                (
                    local.unwrap_or_else(|| syn::Ident::new("id", name.span())),
                    foreign,
                )
            }
            Kind::BelongsTo => (
                foreign.unwrap_or_else(|| format_ident!("{}_id", name)),
                local.unwrap_or_else(|| syn::Ident::new("id", name.span())),
            ),
        };

        Ok(Self {
            kind,
            name,
            target,
            local_key,
            foreign_key,
        })
    }
}

struct Args {
    krate: Option<Path>,
    declarations: Vec<Declaration>,
}

impl Parse for Args {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut krate = None;
        let mut declarations = Vec::new();

        while !input.is_empty() {
            if input.peek(Token![crate]) {
                input.parse::<Token![crate]>()?;
                input.parse::<Token![=]>()?;
                krate = Some(input.parse()?);
            } else {
                declarations.push(input.parse()?);
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(Self {
            krate,
            declarations,
        })
    }
}

pub fn model(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as Args);
    let block = parse_macro_input!(item as ItemImpl);

    match expand(args, block) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

/// A `#[scope]` function: takes the query, returns the query, plus any extra
/// arguments the caller supplies.
struct Scope {
    name: syn::Ident,
    inner: syn::Ident,
    query_ty: Type,
    extra: Vec<(syn::Ident, Type)>,
}

/// Pull `#[scope]` functions out of the impl block, renaming them so the
/// generated wrappers can own the public names.
fn take_scopes(block: &mut ItemImpl) -> syn::Result<Vec<Scope>> {
    let mut scopes = Vec::new();

    for item in &mut block.items {
        let ImplItem::Fn(func) = item else { continue };

        let Some(index) = func
            .attrs
            .iter()
            .position(|attr| attr.path().is_ident("scope"))
        else {
            continue;
        };
        func.attrs.remove(index);

        let name = func.sig.ident.clone();

        let Some(FnArg::Typed(first)) = func.sig.inputs.first() else {
            return Err(syn::Error::new_spanned(
                &func.sig,
                "a #[scope] takes the query as its first argument, \
                 e.g. `fn active(query: Query<users::Entity>) -> Query<users::Entity>`",
            ));
        };
        let query_ty = (*first.ty).clone();

        let mut extra = Vec::new();
        for argument in func.sig.inputs.iter().skip(1) {
            let FnArg::Typed(argument) = argument else {
                return Err(syn::Error::new_spanned(
                    argument,
                    "a #[scope] is an associated function and cannot take `self`",
                ));
            };
            let syn::Pat::Ident(ident) = &*argument.pat else {
                return Err(syn::Error::new_spanned(
                    &argument.pat,
                    "#[scope] arguments must be plain identifiers",
                ));
            };

            extra.push((ident.ident.clone(), (*argument.ty).clone()));
        }

        let inner = format_ident!("__luxid_scope_{}", name);
        func.sig.ident = inner.clone();

        scopes.push(Scope {
            name,
            inner,
            query_ty,
            extra,
        });
    }

    Ok(scopes)
}

fn expand(args: Args, block: ItemImpl) -> syn::Result<TokenStream2> {
    if block.trait_.is_some() {
        return Err(syn::Error::new_spanned(
            &block.self_ty,
            "#[luxid::model] expects a plain inherent impl, e.g. `impl User {}`",
        ));
    }

    let mut block = block;
    let scopes = take_scopes(&mut block)?;

    let self_ty = block.self_ty.clone();
    let krate = args
        .krate
        .map(|path| quote!(#path))
        .unwrap_or_else(|| quote!(::luxid));

    let mut accessors = Vec::new();
    let mut arms = Vec::new();

    for declaration in &args.declarations {
        let Declaration {
            kind,
            name,
            target,
            local_key,
            foreign_key,
        } = declaration;

        let relation = name.to_string();
        let docs = format!("The `{relation}` relation. Load it with `.with(\"{relation}\")`.");

        accessors.push(match kind {
            Kind::HasMany => quote! {
                #[doc = #docs]
                pub fn #name(&self) -> #krate::Result<&[#target]> {
                    #krate::__private::Relatable::relations(self)
                        .many::<#target>(<Self as #krate::__private::Lucid>::MODEL, #relation)
                }
            },
            Kind::HasOne | Kind::BelongsTo => quote! {
                #[doc = #docs]
                pub fn #name(&self) -> #krate::Result<::std::option::Option<&#target>> {
                    #krate::__private::Relatable::relations(self)
                        .one::<#target>(<Self as #krate::__private::Lucid>::MODEL, #relation)
                }
            },
        });

        let loader = kind.loader();

        arms.push(quote! {
            #relation => {
                #krate::__private::#loader::<Self, #target>(
                    parents,
                    #krate::__private::ColumnRef::column(&Self::#local_key),
                    #krate::__private::ColumnRef::column(&<#target>::#foreign_key),
                    #relation,
                )
                .await
            }
        });
    }

    let declared: Vec<String> = args
        .declarations
        .iter()
        .map(|d| d.name.to_string())
        .collect();
    let declared = declared.join(", ");

    let scope_tokens = expand_scopes(&self_ty, &scopes, &krate)?;

    // A model with no declared relations gets no `Relatable` impl, so `.with(..)`
    // on it is a trait-bound error rather than a runtime "no such relation".
    let relatable = if args.declarations.is_empty() {
        quote!()
    } else {
        quote! {
        impl #krate::__private::Relatable for #self_ty {
            fn relations(&self) -> &#krate::__private::Relations {
                &self.relations
            }

            fn relations_mut(&mut self) -> &mut #krate::__private::Relations {
                &mut self.relations
            }

            fn load_relation(
                name: ::std::string::String,
                parents: &mut ::std::vec::Vec<Self>,
            ) -> #krate::__private::BoxFuture<'_, #krate::Result<()>> {
                ::std::boxed::Box::pin(async move {
                    match name.as_str() {
                        #(#arms)*
                        unknown => ::std::result::Result::Err(#krate::Error::internal(
                            ::std::format!(
                                "`{}` has no relation `{}`. Declared relations: [{}].",
                                <Self as #krate::__private::Lucid>::MODEL,
                                unknown,
                                #declared,
                            ),
                        )),
                    }
                })
            }
        }
        }
    };

    Ok(quote! {
        #block

        impl #self_ty {
            #(#accessors)*
        }

        #relatable

        #scope_tokens
    })
}

/// Scopes become two things: a starter on the model (`User::active()`) that
/// needs no import, and a trait on the query (`User::query().active()`) for
/// mid-chain use, which does.
fn expand_scopes(
    self_ty: &Type,
    scopes: &[Scope],
    krate: &TokenStream2,
) -> syn::Result<TokenStream2> {
    if scopes.is_empty() {
        return Ok(quote!());
    }

    let Type::Path(path) = self_ty else {
        return Err(syn::Error::new_spanned(self_ty, "expected a named type"));
    };
    let Some(ident) = path.path.segments.last().map(|segment| &segment.ident) else {
        return Err(syn::Error::new_spanned(self_ty, "expected a named type"));
    };

    let trait_ident = format_ident!("{}Scopes", ident);
    let query_ty = scopes[0].query_ty.clone();

    let mut signatures = Vec::new();
    let mut implementations = Vec::new();
    let mut starters = Vec::new();

    for scope in scopes {
        let Scope {
            name, inner, extra, ..
        } = scope;

        let params = extra.iter().map(|(name, ty)| quote!(#name: #ty));
        let params2 = params.clone();
        let params3 = params.clone();
        let forwarded = extra.iter().map(|(name, _)| quote!(#name));
        let forwarded2 = forwarded.clone();

        let docs = format!("The `{name}` scope.");

        signatures.push(quote! {
            #[doc = #docs]
            fn #name(self, #(#params),*) -> Self;
        });

        implementations.push(quote! {
            fn #name(self, #(#params2),*) -> Self {
                <#self_ty>::#inner(self, #(#forwarded),*)
            }
        });

        starters.push(quote! {
            #[doc = #docs]
            pub fn #name(#(#params3),*) -> #query_ty {
                <#self_ty>::#inner(<#self_ty as #krate::__private::Lucid>::query(), #(#forwarded2),*)
            }
        });
    }

    Ok(quote! {
        #[doc = "Scopes for this model. Import it to chain them onto a query."]
        pub trait #trait_ident {
            #(#signatures)*
        }

        impl #trait_ident for #query_ty {
            #(#implementations)*
        }

        impl #self_ty {
            #(#starters)*
        }
    })
}