queryweave-codegen 0.2.1

The code generation behind queryweave's derives, for proc-macro crates with their own naming conventions and integrations.
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
/// What a `Filters` struct is, which decides what is generated for it.
#[derive(Debug, PartialEq, Eq)]
pub enum Role {
    /// A root model: it owns its generated types and publishes them through
    /// `queryweave::Filterable`.
    Root,
    /// A mirror of `model` (deriving `Filters`: a root model, or another
    /// mirror), named by
    /// `#[filters(mirrors = path)]`: its generated types convert into the
    /// model's, which it names through `queryweave::Filterable`, never by
    /// rebuilding their names.
    Mirror {
        /// The mirrored model.
        model: syn::Path,
        /// The integrations its generated code opts into, in the order of
        /// the conventions' integrations.
        integrations: Vec<crate::integrations::Active>,
    },
}

/// What the code generated for a `Filters` struct links to.
#[derive(Debug, PartialEq, Eq)]
pub struct MappingPaths {
    /// The struct's role.
    pub role: Role,
    /// The path of the runtime crate the generated code names: the one given
    /// by `#[queryweave(crate = path)]`, or the conventions' default:
    /// `C::api_crate()` for a mirror with an integration naming the API
    /// runtime (e.g. `serde`), `C::core_crate()` otherwise.
    pub runtime: syn::Path,
    /// The names of the generated types: the conventions', with the struct's
    /// renames (`#[filters(query = Name, ...)]`).
    pub names: crate::conventions::FiltersNames,
}

/// The generated types of each role, by their `#[filters(...)]` option.
const ROOT_TYPES: [&str; 4] = ["query", "filter_options", "sort_field", "sort_details"];
const MIRROR_TYPES: [&str; 5] = [
    "query_params",
    "filter_options",
    "sort_field",
    "sort_details",
    "page",
];

/// The name `key`'s generated type has in `names`.
fn name_of<'a>(names: &'a crate::conventions::FiltersNames, key: &str) -> &'a syn::Ident {
    match key {
        "query" => &names.query,
        "filter_options" => &names.filters,
        "sort_field" => &names.sort_field,
        "sort_details" => &names.sort_details,
        "page" => &names.page,
        _ => &names.query_params,
    }
}

/// The names of the generated types of a struct with the role's `types`:
/// the conventions' `names`, with `renames`.
///
/// # Errors
///
/// Returns an error at each rename of a type the role does not generate, and
/// at each generated type whose name another one (or the struct) has.
fn apply_renames(
    mut names: crate::conventions::FiltersNames,
    renames: &crate::parse_top_level_meta::filters::Renames,
    types: &[&str],
) -> syn::Result<crate::conventions::FiltersNames> {
    let mut errors = crate::errors::Errors::default();
    for (key, name) in renames.written() {
        if !types.contains(&key) {
            let (role, generates) = if types.contains(&"query") {
                ("a root model", "A root model generates")
            } else {
                ("a mirror", "A mirror generates")
            };
            errors.push(syn::Error::new(
                name.span(),
                crate::errors::message(
                    &format!("`{key}` names a type {role} does not generate"),
                    &format!("{generates}: {}", types.join(", ")),
                ),
            ));
            continue;
        }
        let slot = match key {
            "query" => &mut names.query,
            "filter_options" => &mut names.filters,
            "sort_field" => &mut names.sort_field,
            "sort_details" => &mut names.sort_details,
            "page" => &mut names.page,
            _ => &mut names.query_params,
        };
        *slot = name.clone();
    }
    errors.finish(())?;

    // Every generated type needs a name of its own, other than the struct's.
    let mut errors = crate::errors::Errors::default();
    let mut taken = vec![(String::from("the struct itself"), &names.input)];
    for key in types {
        let name = name_of(&names, key);
        if let Some((other, _)) = taken.iter().find(|(_, taken)| *taken == name) {
            errors.push(syn::Error::new(
                name.span(),
                crate::errors::message(
                    &format!("The generated `{key}` type and {other} are both named `{name}`"),
                    &format!("Rename one of them, e.g. #[filters({key} = OtherName)]"),
                ),
            ));
        }
        taken.push((format!("the generated `{key}` type"), name));
    }

    errors.finish(names)
}

/// The struct's role, from `#[filters(mirrors = path)]`, and the runtime crate
/// its generated code names.
///
/// A root model maps onto no other type, so it cannot rename a field onto one
/// with `#[equivalent_field(name)]`, and has no integrations. A mirror's
/// integrations (the conventions' `C::integrations()` its flags name) must
/// each have the ones it requires, and agree on the sort direction and page
/// types they provide.
///
/// # Errors
///
/// Returns an error at each `#[equivalent_field(...)]` and integration flag
/// of a root model, and at each flag of a mirror lacking a required
/// integration or disagreeing with an earlier one.
pub fn generate_paths<C: crate::conventions::Conventions>(
    parsed: &crate::parse::filters::Parsed<'_>,
    mirrors: Option<syn::Path>,
    integrations: &crate::parse_top_level_meta::filters::Integrations,
    renames: &crate::parse_top_level_meta::filters::Renames,
    runtime_crate: Option<syn::Path>,
) -> syn::Result<MappingPaths> {
    let Some(model) = mirrors else {
        let (names, ()) = crate::errors::both(
            apply_renames(parsed.idents.clone(), renames, &ROOT_TYPES),
            check_root(parsed, integrations),
        )?;
        return Ok(MappingPaths {
            role: Role::Root,
            runtime: runtime_crate.unwrap_or_else(C::core_crate),
            names,
        });
    };

    crate::attributes::reject_self_link(&model, &parsed.idents.input, "filters", "mirrors")?;
    let names = apply_renames(parsed.idents.clone(), renames, &MIRROR_TYPES)?;
    let integrations = resolve(&C::integrations(), integrations);
    let runtime = runtime_crate.unwrap_or_else(|| {
        if integrations
            .iter()
            .any(|active| active.integration.names_api_runtime())
        {
            C::api_crate()
        } else {
            C::core_crate()
        }
    });
    check_integrations(&integrations, &names, &runtime)?;

    Ok(MappingPaths {
        role: Role::Mirror {
            model,
            integrations,
        },
        runtime,
        names,
    })
}

/// The integrations of `registry` the flags name, in `registry`'s order (the
/// flags were read against it, so each names one).
pub fn resolve(
    registry: &[&'static dyn crate::integrations::Integration],
    integrations: &crate::parse_top_level_meta::filters::Integrations,
) -> Vec<crate::integrations::Active> {
    registry
        .iter()
        .filter_map(|integration| {
            integrations
                .flags()
                .iter()
                .find(|flag| *flag == integration.name())
                .map(|flag| crate::integrations::Active {
                    integration: *integration,
                    flag: flag.clone(),
                })
        })
        .collect()
}

/// Each integration has the ones it requires, and they agree on the sort
/// direction and page types they provide.
fn check_integrations(
    integrations: &[crate::integrations::Active],
    names: &crate::conventions::FiltersNames,
    runtime: &syn::Path,
) -> syn::Result<()> {
    let mut errors = crate::errors::Errors::default();
    for crate::integrations::Active { integration, flag } in integrations {
        for (required, reason) in integration.requires() {
            if !integrations
                .iter()
                .any(|other| other.integration.name() == *required)
            {
                errors.push(syn::Error::new(
                    flag.span(),
                    crate::errors::message(
                        &format!("`{flag}` needs `{required}`: {reason}"),
                        &format!(
                            "Add `{required}` to the options: #[filters(mirrors = path, {required}, {flag})]"
                        ),
                    ),
                ));
            }
        }
    }
    let provided = integrations
        .iter()
        .map(|active| {
            let context = active.context(names, runtime);
            (
                &active.flag,
                active.integration.sort_direction(&context),
                active.integration.page(&context),
            )
        })
        .collect::<Vec<_>>();
    check_agreement(
        provided
            .iter()
            .map(|(flag, sort_direction, _)| (*flag, sort_direction.as_ref())),
        &mut errors,
        "sort direction",
    );
    check_agreement(
        provided
            .iter()
            .map(|(flag, _, page)| (*flag, page.as_ref())),
        &mut errors,
        "page type",
    );

    errors.finish(())
}

/// Report, at its flag, each integration providing a `what` other than the
/// first one's, given each flag with what its integration provides.
fn check_agreement<'a>(
    provided: impl Iterator<Item = (&'a syn::Ident, Option<&'a proc_macro2::TokenStream>)>,
    errors: &mut crate::errors::Errors,
    what: &str,
) {
    let mut first: Option<(&syn::Ident, String)> = None;
    for (flag, tokens) in provided {
        let Some(tokens) = tokens.map(ToString::to_string) else {
            continue;
        };
        match &first {
            None => first = Some((flag, tokens)),
            Some((first_flag, first_tokens)) if *first_tokens != tokens => {
                errors.push(syn::Error::new(
                    flag.span(),
                    crate::errors::message(
                        &format!(
                            "`{first_flag}` and `{flag}` need different {what}s: `{first_tokens}` and `{tokens}`"
                        ),
                        "Opt into integrations agreeing on it, e.g. by removing one of them",
                    ),
                ));
            },
            Some(_) => {},
        }
    }
}

/// A root model has no integrations and renames no field.
fn check_root(
    parsed: &crate::parse::filters::Parsed<'_>,
    integrations: &crate::parse_top_level_meta::filters::Integrations,
) -> syn::Result<()> {
    let mut errors = crate::errors::Errors::default();
    // A root model's generated types hand data to the persistence layer;
    // the integrations are for the types mirroring it (e.g. an API DTO).
    for flag in integrations.flags() {
        errors.push(syn::Error::new(
            flag.span(),
            crate::errors::message(
                &format!("`{flag}` only applies to a mirror (a struct with #[filters(mirrors = path)])"),
                "Link the struct to the model it mirrors with #[filters(mirrors = path)], or remove the option",
            ),
        ));
    }
    for attribute in parsed
        .named_fields
        .named
        .iter()
        .flat_map(|field| &field.attrs)
        .filter(|attribute| attribute.path().is_ident("equivalent_field"))
    {
        errors.push(syn::Error::new_spanned(
            attribute,
            crate::errors::message(
                "#[equivalent_field(...)] only applies to a mirror (a struct with #[filters(mirrors = path)])",
                "Link the struct to the model it mirrors with #[filters(mirrors = path)], or remove the attribute",
            ),
        ));
    }

    errors.finish(())
}

#[cfg(test)]
mod tests {

    fn parsed(named_fields: &syn::FieldsNamed) -> crate::parse::filters::Parsed<'_> {
        crate::parse::filters::Parsed {
            idents: <crate::conventions::DefaultConventions as crate::conventions::Conventions>::filters_names(
                &quote::format_ident!("UserDto"),
            )
            .unwrap(),
            named_fields,
        }
    }

    use crate::conventions::DefaultConventions;
    use crate::parse_top_level_meta::filters::Integrations;

    fn integrations(serde: bool, utoipa: bool, validator: bool) -> Integrations {
        let names = [
            ("serde", serde),
            ("utoipa", utoipa),
            ("validator", validator),
        ]
        .into_iter()
        .filter_map(|(name, written)| written.then_some(name))
        .collect::<Vec<_>>();
        Integrations::of(&names)
    }

    // A mirror (de)serialized or documented names the API runtime crate, the
    // core one otherwise.
    #[rstest::rstest]
    #[case::plain(integrations(false, false, false), syn::parse_quote!(::queryweave))]
    #[case::serde_and_validator(integrations(true, false, true), syn::parse_quote!(::queryweave_api))]
    #[case::serde(integrations(true, false, false), syn::parse_quote!(::queryweave_api))]
    #[case::utoipa(integrations(false, true, false), syn::parse_quote!(::queryweave_api))]
    #[case::all(integrations(true, true, true), syn::parse_quote!(::queryweave_api))]
    fn test_generating_paths_keeps_the_mirrored_model(
        #[case] integrations: Integrations,
        #[case] runtime: syn::Path,
    ) {
        let named_fields = syn::parse_quote!({ #[filter(sw)] username: String });
        let path = syn::parse_str::<syn::Path>("domain::models::user::UserModel").unwrap();

        pretty_assertions::assert_eq!(
            super::generate_paths::<DefaultConventions>(
                &parsed(&named_fields),
                Some(path.clone()),
                &integrations,
                &crate::parse_top_level_meta::filters::Renames::default(),
                None
            )
            .unwrap(),
            super::MappingPaths {
                role: super::Role::Mirror {
                    model: path,
                    integrations: super::resolve(&crate::integrations::BUILT_IN, &integrations),
                },
                runtime,
                names: parsed(&named_fields).idents,
            }
        );
    }

    // validator serializes the rejected value: it needs serde.
    #[rstest::rstest]
    #[case::alone(integrations(false, false, true))]
    #[case::with_utoipa(integrations(false, true, true))]
    fn test_generating_paths_rejects_validator_without_serde(#[case] integrations: Integrations) {
        let named_fields = syn::parse_quote!({ #[filter(sw)] username: String });

        assert!(
            super::generate_paths::<DefaultConventions>(
                &parsed(&named_fields),
                Some(syn::parse_quote!(UserModel)),
                &integrations,
                &crate::parse_top_level_meta::filters::Renames::default(),
                None,
            )
            .is_err()
        );
    }

    // The integrations are a mirror's: each one written on a root model is
    // reported.
    #[test]
    fn test_generating_paths_rejects_integrations_on_a_root() {
        let named_fields = syn::parse_quote!({ #[filter(sw)] username: String });

        let error = super::generate_paths::<DefaultConventions>(
            &parsed(&named_fields),
            None,
            &integrations(true, false, true),
            &crate::parse_top_level_meta::filters::Renames::default(),
            None,
        )
        .unwrap_err();

        assert_eq!(error.into_iter().count(), 2);
    }

    /// An integration named `name` providing `direction` as its sort direction.
    struct Direction(&'static str, &'static str);

    impl crate::integrations::Integration for Direction {
        fn name(&self) -> &'static str {
            self.0
        }

        fn sort_direction(
            &self,
            _context: &crate::integrations::Context<'_>,
        ) -> Option<proc_macro2::TokenStream> {
            self.1.parse().ok()
        }
    }

    static ONE: Direction = Direction("one", "crate::One");
    static SAME: Direction = Direction("same", "crate::One");
    static OTHER: Direction = Direction("other", "crate::Other");

    /// `check_integrations` on the integrations of `registry` named `names`.
    fn check(
        registry: &[&'static dyn crate::integrations::Integration],
        names: &[&str],
    ) -> syn::Result<()> {
        let idents = <DefaultConventions as crate::conventions::Conventions>::filters_names(
            &quote::format_ident!("UserDto"),
        )?;
        super::check_integrations(
            &super::resolve(registry, &Integrations::of(names)),
            &idents,
            &syn::parse_quote!(::queryweave),
        )
    }

    // The integrations providing a sort direction must agree on it; the ones
    // providing none follow.
    #[test]
    fn test_integrations_must_agree_on_the_sort_direction() {
        let registry: [&'static dyn crate::integrations::Integration; 4] =
            [&ONE, &SAME, &OTHER, crate::integrations::BUILT_IN[2]];

        assert!(check(&registry, &["one", "same"]).is_ok());
        assert!(check(&registry, &["one", "other"]).is_err());
        assert!(check(&registry, &["other"]).is_ok());
        // The built-in ones agree on `SortDirectionDto`.
        assert!(
            check(
                &crate::integrations::BUILT_IN,
                &["serde", "utoipa", "validator"]
            )
            .is_ok()
        );
    }

    /// `generate_paths` on `UserDto`, a root or a mirror, with `renames`.
    fn with_renames(
        mirrors: Option<&str>,
        renames: &crate::parse_top_level_meta::filters::Renames,
    ) -> syn::Result<super::MappingPaths> {
        let named_fields = syn::parse_quote!({ #[filter(sw)] username: String });
        super::generate_paths::<DefaultConventions>(
            &parsed(&named_fields),
            mirrors.map(|path| syn::parse_str(path).unwrap()),
            &Integrations::default(),
            renames,
            None,
        )
    }

    // A rename replaces its type's conventions name; the others keep theirs.
    #[test]
    fn test_renames_replace_the_conventions_names() {
        let renames = crate::parse_top_level_meta::filters::Renames {
            query_params: Some(quote::format_ident!("UserSearchParams")),
            sort_field: Some(quote::format_ident!("UserSortKey")),
            ..Default::default()
        };

        let names = with_renames(Some("UserModel"), &renames).unwrap().names;

        assert_eq!(names.query_params, "UserSearchParams");
        assert_eq!(names.sort_field, "UserSortKey");
        assert_eq!(names.sort_details, "UserSortDetailsDto");
    }

    // A root has no query parameters and a mirror no query model to rename.
    #[test]
    fn test_renames_must_name_a_type_of_the_role() {
        let query_params = crate::parse_top_level_meta::filters::Renames {
            query_params: Some(quote::format_ident!("UserSearchParams")),
            ..Default::default()
        };
        let query = crate::parse_top_level_meta::filters::Renames {
            query: Some(quote::format_ident!("UserSearch")),
            ..Default::default()
        };

        assert!(with_renames(None, &query_params).is_err());
        assert!(with_renames(Some("UserModel"), &query).is_err());
        assert!(with_renames(None, &query).is_ok());
    }

    // Two generated types, or one and the struct, cannot share a name.
    #[test]
    fn test_renames_cannot_clash() {
        let same = crate::parse_top_level_meta::filters::Renames {
            sort_field: Some(quote::format_ident!("UserSort")),
            sort_details: Some(quote::format_ident!("UserSort")),
            ..Default::default()
        };
        let struct_name = crate::parse_top_level_meta::filters::Renames {
            filter_options: Some(quote::format_ident!("UserDto")),
            ..Default::default()
        };

        assert!(with_renames(Some("UserModel"), &same).is_err());
        assert!(with_renames(Some("UserModel"), &struct_name).is_err());
    }

    // A struct mirroring itself never reaches a root model.
    #[test]
    fn test_generating_paths_rejects_a_struct_mirroring_itself() {
        let named_fields = syn::parse_quote!({ #[filter(sw)] username: String });

        for path in ["Self", "UserDto"] {
            assert!(
                super::generate_paths::<DefaultConventions>(
                    &parsed(&named_fields),
                    Some(syn::parse_str(path).unwrap()),
                    &Integrations::default(),
                    &crate::parse_top_level_meta::filters::Renames::default(),
                    None,
                )
                .is_err()
            );
        }
    }

    // The flags resolve to the registry's integrations, in its order.
    #[test]
    fn test_resolving_keeps_the_registry_order() {
        let resolved = super::resolve(
            &crate::integrations::BUILT_IN,
            &Integrations::of(&["validator", "serde"]),
        );

        assert_eq!(
            resolved
                .iter()
                .map(|active| active.integration.name())
                .collect::<Vec<_>>(),
            ["serde", "validator"]
        );
    }

    // A root model's code names the core runtime crate.
    #[test]
    fn test_generating_paths_without_a_mirrored_model_is_a_root() {
        let named_fields = syn::parse_quote!({ #[filter(sw)] username: String });

        pretty_assertions::assert_eq!(
            super::generate_paths::<DefaultConventions>(
                &parsed(&named_fields),
                None,
                &Integrations::default(),
                &crate::parse_top_level_meta::filters::Renames::default(),
                None
            )
            .unwrap(),
            super::MappingPaths {
                role: super::Role::Root,
                runtime: syn::parse_quote!(::queryweave),
                names: parsed(&named_fields).idents,
            }
        );
    }

    // `#[queryweave(crate = path)]` overrides the conventions' default.
    #[test]
    fn test_generating_paths_takes_the_given_runtime_crate() {
        let named_fields = syn::parse_quote!({ #[filter(sw)] username: String });

        let mapping_paths = super::generate_paths::<DefaultConventions>(
            &parsed(&named_fields),
            None,
            &Integrations::default(),
            &crate::parse_top_level_meta::filters::Renames::default(),
            Some(syn::parse_quote!(my::runtime)),
        )
        .unwrap();

        pretty_assertions::assert_eq!(mapping_paths.runtime, syn::parse_quote!(my::runtime));
    }

    // Each renamed field of a root model is reported.
    #[test]
    fn test_generating_paths_rejects_equivalent_fields_on_a_root() {
        let named_fields = syn::parse_quote!({
            #[filter(sw)]
            #[equivalent_field(name)]
            username: String,
            #[filter(eq)]
            #[equivalent_field(mail)]
            email: String,
        });

        let error = super::generate_paths::<DefaultConventions>(
            &parsed(&named_fields),
            None,
            &Integrations::default(),
            &crate::parse_top_level_meta::filters::Renames::default(),
            None,
        )
        .unwrap_err();

        assert_eq!(error.into_iter().count(), 2);
    }
}