zlink-macros 0.7.0

Macros providing the high-level zlink API
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use syn::{Attribute, Error, Ident, LitStr};

use crate::utils::skip_unknown_meta;

/// The grammar a resolved Varlink name must follow.
///
/// Varlink names fields, parameters and enum variants one way, and types, methods and errors
/// another, so every name falls under one of these two rules.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Grammar {
    /// The field-name rule, `[A-Za-z][A-Za-z0-9_]*`. Fields, parameters and enum variants.
    Field,
    /// The type-name rule, `[A-Z][A-Za-z0-9]*`. Types, methods and errors.
    Type,
}

/// Where a resolved name came from, which decides what a rejection points at and suggests.
#[derive(Debug, Clone, Copy)]
pub(crate) enum NameSource<'a> {
    /// An explicit `#[zlink(rename = "...")]`.
    Rename(&'a LitStr),
    /// A Rust ident, possibly with a case convention applied to it.
    Ident(&'a Ident),
}

/// Reject `name` if Varlink cannot express it under `grammar`, describing it as `what`.
///
/// Only ever called on a *resolved* name: unrawing and `rename`/`rename_all` decide what a thing is
/// called, and this decides whether that answer is sayable. Checking any earlier would reject
/// perfectly good Rust, e.g. `r#type`, which resolves to the valid `type`.
pub(crate) fn validate(
    name: &str,
    grammar: Grammar,
    what: &str,
    source: NameSource<'_>,
) -> Result<(), Error> {
    if !grammar.accepts(name) {
        // Pointing at the rename literal is precise enough on its own; suggesting a rename to
        // someone who just wrote one would only be noise.
        let hint = match source {
            NameSource::Rename(_) => "",
            NameSource::Ident(_) => ", so name it explicitly with `#[zlink(rename = \"...\")]`",
        };
        let msg = format!(
            "`{name}` is not a valid Varlink {what}: it must match `{}`{hint}",
            grammar.pattern(),
        );

        return Err(match source {
            NameSource::Rename(lit) => Error::new_spanned(lit, msg),
            NameSource::Ident(ident) => Error::new_spanned(ident, msg),
        });
    }

    Ok(())
}

/// Reject an interface name Varlink cannot express, reporting against `lit`'s span.
///
/// Kept apart from [`validate`]: an interface name is always a literal the user wrote out (never a
/// resolved ident), and its grammar is neither the field nor the type rule but reverse-domain
/// notation.
pub(crate) fn validate_interface(lit: &LitStr) -> Result<(), Error> {
    let name = lit.value();
    if !zlink_idl::is_valid_interface_name(&name) {
        return Err(Error::new_spanned(
            lit,
            format!(
                "`{name}` is not a valid Varlink interface name: it must be in reverse-domain \
                 notation, e.g. `org.example.Foo`"
            ),
        ));
    }

    Ok(())
}

impl Grammar {
    /// Whether Varlink can express `name` under this rule.
    fn accepts(self, name: &str) -> bool {
        match self {
            Self::Field => zlink_idl::is_valid_field_name(name),
            Self::Type => zlink_idl::is_valid_type_name(name),
        }
    }

    /// The rule as it reads in the Varlink specification.
    fn pattern(self) -> &'static str {
        match self {
            Self::Field => "[A-Za-z][A-Za-z0-9_]*",
            Self::Type => "[A-Z][A-Za-z0-9]*",
        }
    }
}

/// The case convention requested by `#[zlink(rename_all = "...")]`.
///
/// The variants mirror serde's rename rules so the semantics are familiar. Note that the field and
/// variant rules differ, because the source convention differs: fields are `snake_case`, variants
/// are `PascalCase`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RenameAll {
    Lower,
    Upper,
    Pascal,
    Camel,
    Snake,
    ScreamingSnake,
    Kebab,
    ScreamingKebab,
}

impl RenameAll {
    /// Apply the convention to a struct field name, whose source convention is `snake_case`.
    pub(crate) fn apply_to_field(self, field: &str) -> String {
        match self {
            Self::Lower | Self::Snake => field.to_owned(),
            Self::Upper | Self::ScreamingSnake => field.to_ascii_uppercase(),
            Self::Pascal => {
                let mut pascal = String::new();
                let mut capitalize = true;
                for ch in field.chars() {
                    if ch == '_' {
                        capitalize = true;
                    } else if capitalize {
                        pascal.push(ch.to_ascii_uppercase());
                        capitalize = false;
                    } else {
                        pascal.push(ch);
                    }
                }
                pascal
            }
            Self::Camel => {
                let pascal = Self::Pascal.apply_to_field(field);
                match pascal.get(..1) {
                    Some(first) => first.to_ascii_lowercase() + &pascal[1..],
                    None => pascal,
                }
            }
            Self::Kebab => field.replace('_', "-"),
            Self::ScreamingKebab => Self::ScreamingSnake.apply_to_field(field).replace('_', "-"),
        }
    }

    /// Apply the convention to an enum variant name, whose source convention is `PascalCase`.
    pub(crate) fn apply_to_variant(self, variant: &str) -> String {
        match self {
            Self::Pascal => variant.to_owned(),
            Self::Lower => variant.to_ascii_lowercase(),
            Self::Upper => variant.to_ascii_uppercase(),
            Self::Camel => match variant.get(..1) {
                Some(first) => first.to_ascii_lowercase() + &variant[1..],
                None => variant.to_owned(),
            },
            Self::Snake => {
                let mut snake = String::new();
                for (i, ch) in variant.char_indices() {
                    if i > 0 && ch.is_uppercase() {
                        snake.push('_');
                    }
                    snake.push(ch.to_ascii_lowercase());
                }
                snake
            }
            Self::ScreamingSnake => Self::Snake.apply_to_variant(variant).to_ascii_uppercase(),
            Self::Kebab => Self::Snake.apply_to_variant(variant).replace('_', "-"),
            Self::ScreamingKebab => Self::ScreamingSnake
                .apply_to_variant(variant)
                .replace('_', "-"),
        }
    }

    /// Whether this convention could ever produce a name valid under `grammar`.
    ///
    /// Some conventions can satisfy a grammar for no input at all: `snake_case`, say, always
    /// lowercases the first character, which the type-name rule (uppercase-first) rejects for
    /// every possible name. Offering such a pairing is a footgun, so it is refused up front rather
    /// than left for the per-name check to reject one produced name at a time.
    ///
    /// Probing a single-word sample rather than re-encoding that reasoning keeps the parser the one
    /// authority on the grammar: a word carries the first-character and character-set rules without
    /// the separators that only longer names introduce, so if a convention cannot make even this
    /// fit, no name ever will.
    fn can_produce(self, grammar: Grammar) -> bool {
        grammar.accepts(&self.apply_to_variant("Word"))
    }

    pub(crate) fn parse(lit: &LitStr) -> Result<Self, Error> {
        let rule = match lit.value().as_str() {
            "lowercase" => Self::Lower,
            "UPPERCASE" => Self::Upper,
            "PascalCase" => Self::Pascal,
            "camelCase" => Self::Camel,
            "snake_case" => Self::Snake,
            "SCREAMING_SNAKE_CASE" => Self::ScreamingSnake,
            "kebab-case" => Self::Kebab,
            "SCREAMING-KEBAB-CASE" => Self::ScreamingKebab,
            unknown => {
                return Err(Error::new_spanned(
                    lit,
                    format!(
                        "`{unknown}` is not a known case convention, expected one of: {}",
                        VALID_RENAME_ALL.join(", "),
                    ),
                ));
            }
        };

        Ok(rule)
    }
}

/// The name a struct field should carry in the IDL and on the wire.
///
/// `#[zlink(rename)]` wins over an inherited `rename_all`, which wins over the Rust ident.
pub(crate) fn field_name(
    attrs: &[Attribute],
    ident: &Ident,
    rename_all: Option<RenameAll>,
) -> Result<String, Error> {
    resolve(
        attrs,
        ident,
        rename_all,
        RenameAll::apply_to_field,
        Grammar::Field,
        "field name",
    )
}

/// The name an enum variant should carry in the IDL and on the wire.
///
/// `#[zlink(rename)]` wins over an inherited `rename_all`, which wins over the Rust ident.
#[cfg(feature = "introspection")]
pub(crate) fn enum_variant_name(
    attrs: &[Attribute],
    ident: &Ident,
    rename_all: Option<RenameAll>,
) -> Result<String, Error> {
    resolve(
        attrs,
        ident,
        rename_all,
        RenameAll::apply_to_variant,
        Grammar::Field,
        "enum variant name",
    )
}

/// The name an error variant should carry in the IDL and on the wire.
///
/// `#[zlink(rename)]` wins over an inherited `rename_all`, which wins over the Rust ident.
///
/// Kept apart from [`enum_variant_name`] because the two obey different grammars: an error is named
/// like a type, an enum variant like a field. Sharing one function would leave the choice of rule
/// to whichever caller happened to reach for it.
pub(crate) fn error_name(
    attrs: &[Attribute],
    ident: &Ident,
    rename_all: Option<RenameAll>,
) -> Result<String, Error> {
    resolve(
        attrs,
        ident,
        rename_all,
        RenameAll::apply_to_variant,
        Grammar::Type,
        "error name",
    )
}

/// Reject a container-level `#[zlink(rename)]` with `msg`, for derives where it means nothing.
///
/// Silently ignoring it would let users ship IDL that does not say what they wrote.
pub(crate) fn reject_container_rename(attrs: &[Attribute], msg: &str) -> Result<(), Error> {
    match parse_rename(attrs)? {
        Some(lit) => Err(Error::new_spanned(lit, msg)),
        None => Ok(()),
    }
}

/// The container's `#[zlink(rename_all = "...")]`, if any, checked against `grammar`.
///
/// A convention that could never produce a name valid under `grammar` -- `snake_case` where a type
/// name is wanted, say -- is rejected here, against the attribute's own span, rather than left for
/// the per-name check to reject one produced name at a time.
pub(crate) fn parse_rename_all(
    attrs: &[Attribute],
    grammar: Grammar,
) -> Result<Option<RenameAll>, Error> {
    let Some(lit) = parse_zlink_lit_str(attrs, "rename_all")? else {
        return Ok(None);
    };

    let rule = RenameAll::parse(&lit)?;
    if !rule.can_produce(grammar) {
        return Err(Error::new_spanned(
            &lit,
            format!(
                "`{}` can never produce a name matching the Varlink grammar `{}`, so it cannot \
                 apply here. Drop `rename_all`, use a convention that fits (e.g. `UPPERCASE` or \
                 `PascalCase`), or name items individually with `#[zlink(rename = \"...\")]`",
                lit.value(),
                grammar.pattern(),
            ),
        ));
    }

    Ok(Some(rule))
}

/// The item's `#[zlink(rename = "...")]`, if any.
pub(crate) fn parse_rename(attrs: &[Attribute]) -> Result<Option<LitStr>, Error> {
    parse_zlink_lit_str(attrs, "rename")
}

/// The unraw'd name of an ident: its leading `r#`, if any, stripped off.
///
/// `r#` (e.g. `r#type`) is Rust syntax that lets a keyword be used as an identifier; it is never
/// part of the name itself, so it must not leak into the IDL or onto the wire.
pub(crate) fn unraw(ident: &Ident) -> String {
    let name = ident.to_string();

    match name.strip_prefix("r#") {
        Some(stripped) => stripped.to_owned(),
        None => name,
    }
}

fn resolve<F>(
    attrs: &[Attribute],
    ident: &Ident,
    rename_all: Option<RenameAll>,
    apply: F,
    grammar: Grammar,
    what: &str,
) -> Result<String, Error>
where
    F: FnOnce(RenameAll, &str) -> String,
{
    // An explicit rename is a name the user wrote out, so it is taken verbatim -- mangling it would
    // defeat the point of the attribute -- but it still has to be a name Varlink can say.
    if let Some(lit) = parse_rename(attrs)? {
        let name = lit.value();
        validate(&name, grammar, what, NameSource::Rename(&lit))?;

        return Ok(name);
    }

    let unrawed = unraw(ident);
    let name = match rename_all {
        Some(rule) => apply(rule, &unrawed),
        None => unrawed,
    };
    validate(&name, grammar, what, NameSource::Ident(ident))?;

    Ok(name)
}

/// The string value of `#[zlink(<key> = "...")]`, if present.
///
/// Parse errors are reported rather than swallowed, which is what the rename attributes need in
/// order to reject bad input.
fn parse_zlink_lit_str(attrs: &[Attribute], key: &str) -> Result<Option<LitStr>, Error> {
    let mut result = None;

    for attr in attrs {
        if !attr.path().is_ident("zlink") {
            continue;
        }

        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident(key) {
                let lit: LitStr = meta.value()?.parse()?;
                if result.is_some() {
                    return Err(meta.error(format!("duplicate `{key}` attribute")));
                }
                result = Some(lit);
            } else {
                skip_unknown_meta(&meta)?;
            }

            Ok(())
        })?;
    }

    Ok(result)
}

const VALID_RENAME_ALL: &[&str] = &[
    "lowercase",
    "UPPERCASE",
    "PascalCase",
    "camelCase",
    "snake_case",
    "SCREAMING_SNAKE_CASE",
    "kebab-case",
    "SCREAMING-KEBAB-CASE",
];

#[cfg(test)]
mod tests {
    use super::*;
    use syn::parse_quote;

    #[test]
    fn field_conventions() {
        let cases = [
            (RenameAll::Lower, "user_name"),
            (RenameAll::Upper, "USER_NAME"),
            (RenameAll::Pascal, "UserName"),
            (RenameAll::Camel, "userName"),
            (RenameAll::Snake, "user_name"),
            (RenameAll::ScreamingSnake, "USER_NAME"),
            (RenameAll::Kebab, "user-name"),
            (RenameAll::ScreamingKebab, "USER-NAME"),
        ];

        for (rule, expected) in cases {
            assert_eq!(rule.apply_to_field("user_name"), expected, "rule: {rule:?}");
        }
    }

    #[test]
    fn variant_conventions() {
        let cases = [
            (RenameAll::Lower, "username"),
            (RenameAll::Upper, "USERNAME"),
            (RenameAll::Pascal, "UserName"),
            (RenameAll::Camel, "userName"),
            (RenameAll::Snake, "user_name"),
            (RenameAll::ScreamingSnake, "USER_NAME"),
            (RenameAll::Kebab, "user-name"),
            (RenameAll::ScreamingKebab, "USER-NAME"),
        ];

        for (rule, expected) in cases {
            assert_eq!(
                rule.apply_to_variant("UserName"),
                expected,
                "rule: {rule:?}"
            );
        }
    }

    #[test]
    fn rename_beats_rename_all() {
        let attrs: Vec<Attribute> = vec![parse_quote!(#[zlink(rename = "ID")])];
        let ident: Ident = parse_quote!(user_id);
        let name = field_name(&attrs, &ident, Some(RenameAll::Camel)).unwrap();

        assert_eq!(name, "ID");
    }

    #[test]
    fn rename_all_applies_without_rename() {
        let attrs: Vec<Attribute> = vec![];
        let ident: Ident = parse_quote!(user_id);
        let name = field_name(&attrs, &ident, Some(RenameAll::Camel)).unwrap();

        assert_eq!(name, "userId");
    }

    #[test]
    fn ident_used_without_any_attr() {
        let attrs: Vec<Attribute> = vec![];
        let ident: Ident = parse_quote!(user_id);

        assert_eq!(field_name(&attrs, &ident, None).unwrap(), "user_id");
    }

    #[test]
    fn unraw_strips_the_prefix() {
        let ident: Ident = parse_quote!(r#type);

        assert_eq!(unraw(&ident), "type");
    }

    #[test]
    fn unraw_leaves_a_normal_ident_unchanged() {
        let ident: Ident = parse_quote!(user_id);

        assert_eq!(unraw(&ident), "user_id");
    }

    #[test]
    fn rename_all_parsed_alongside_other_keys() {
        let attrs: Vec<Attribute> =
            vec![parse_quote!(#[zlink(crate = "crate", rename_all = "camelCase")])];

        assert_eq!(
            parse_rename_all(&attrs, Grammar::Field).unwrap(),
            Some(RenameAll::Camel)
        );
    }

    #[test]
    fn unknown_rename_all_value_rejected() {
        let attrs: Vec<Attribute> = vec![parse_quote!(#[zlink(rename_all = "bogus")])];
        let err = parse_rename_all(&attrs, Grammar::Field)
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("bogus"),
            "message should name the bad value: {err}"
        );
        assert!(
            err.contains("camelCase"),
            "message should list valid values: {err}"
        );
    }

    #[test]
    fn container_rename_rejected_with_message() {
        let attrs: Vec<Attribute> = vec![parse_quote!(#[zlink(rename = "Foo")])];
        let err = reject_container_rename(&attrs, "nope")
            .unwrap_err()
            .to_string();

        assert_eq!(err, "nope");
    }

    /// A raw-ident param unraws to a valid field name and must survive validation: this pins the
    /// order (unraw, then validate). Validating `r#type` verbatim would reject legitimate Rust.
    #[test]
    fn raw_ident_field_resolves_then_validates() {
        let attrs: Vec<Attribute> = vec![];
        let ident: Ident = parse_quote!(r#type);

        assert_eq!(field_name(&attrs, &ident, None).unwrap(), "type");
    }

    /// The error-name counterpart: `r#Fn` unraws to the valid error name `Fn`.
    #[test]
    fn raw_ident_error_variant_resolves_then_validates() {
        let attrs: Vec<Attribute> = vec![];
        let ident: Ident = parse_quote!(r#Fn);

        assert_eq!(error_name(&attrs, &ident, None).unwrap(), "Fn");
    }

    /// Enum variants follow field rules, which admit a lowercase first letter.
    #[cfg(feature = "introspection")]
    #[test]
    fn enum_variant_lowercase_is_accepted() {
        let attrs: Vec<Attribute> = vec![];
        let ident: Ident = parse_quote!(Active);

        assert_eq!(
            enum_variant_name(&attrs, &ident, Some(RenameAll::Lower)).unwrap(),
            "active"
        );
    }

    /// The very same lowercase name is rejected as an error name, which follows type rules.
    #[test]
    fn error_name_lowercase_is_rejected() {
        let attrs: Vec<Attribute> = vec![];
        let ident: Ident = parse_quote!(Active);
        let err = error_name(&attrs, &ident, Some(RenameAll::Lower))
            .unwrap_err()
            .to_string();

        assert!(err.contains("`active`"), "must name the bad name: {err}");
        assert!(err.contains("error name"), "must name the context: {err}");
    }

    /// A bad `rename` is reported against its own value, not the ident it overrode, and offers no
    /// "use rename" hint to someone who already wrote one. This is how the error lands on the
    /// literal's span.
    #[test]
    fn invalid_rename_reports_the_literal_not_the_ident() {
        let attrs: Vec<Attribute> = vec![parse_quote!(#[zlink(rename = "not valid!")])];
        let ident: Ident = parse_quote!(good_field);
        let err = field_name(&attrs, &ident, None).unwrap_err().to_string();

        assert!(err.contains("`not valid!`"), "must quote the rename: {err}");
        assert!(
            !err.contains("good_field"),
            "must not blame the ident: {err}"
        );
        assert!(
            !err.contains("`#[zlink(rename"),
            "no hint on a rename: {err}"
        );
    }

    /// A bad ident, by contrast, is pointed at the `rename` escape hatch.
    #[test]
    fn invalid_ident_suggests_rename() {
        let attrs: Vec<Attribute> = vec![];
        let ident: Ident = parse_quote!(_foo);
        let err = field_name(&attrs, &ident, None).unwrap_err().to_string();

        assert!(err.contains("`_foo`"), "must name the bad ident: {err}");
        assert!(err.contains("rename"), "must offer the escape hatch: {err}");
    }

    #[test]
    fn interface_names_validated() {
        let good: LitStr = parse_quote!("org.example.Foo");
        assert!(validate_interface(&good).is_ok());

        // A `_` is not allowed in an interface segment (unlike a field name).
        let bad: LitStr = parse_quote!("org.example.bad_name");
        let err = validate_interface(&bad).unwrap_err().to_string();

        assert!(
            err.contains("`org.example.bad_name`"),
            "must quote it: {err}"
        );
        assert!(
            err.contains("interface name"),
            "must name the context: {err}"
        );
    }

    /// A convention that can sometimes yield a valid type name -- `SCREAMING_SNAKE_CASE` does for a
    /// single-word variant -- is accepted; the per-name check catches the names that do not fit.
    #[test]
    fn rename_all_that_can_sometimes_fit_the_type_grammar_is_accepted() {
        let attrs: Vec<Attribute> =
            vec![parse_quote!(#[zlink(rename_all = "SCREAMING_SNAKE_CASE")])];

        assert_eq!(
            parse_rename_all(&attrs, Grammar::Type).unwrap(),
            Some(RenameAll::ScreamingSnake)
        );
    }

    /// A convention that can never yield a valid type name -- `snake_case` always lowercases the
    /// first letter -- is refused up front, against the attribute's own span.
    #[test]
    fn rename_all_that_never_fits_the_type_grammar_is_rejected() {
        let attrs: Vec<Attribute> = vec![parse_quote!(#[zlink(rename_all = "snake_case")])];
        let err = parse_rename_all(&attrs, Grammar::Type)
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("`snake_case`"),
            "must name the convention: {err}"
        );
        assert!(
            err.contains("[A-Z][A-Za-z0-9]*"),
            "must name the grammar it cannot meet: {err}"
        );
    }

    /// The field grammar admits a lowercase first letter, so every convention can fit it -- even
    /// the ones the type grammar refuses.
    #[test]
    fn every_rename_all_fits_the_field_grammar() {
        for value in VALID_RENAME_ALL {
            let attr: Attribute = parse_quote!(#[zlink(rename_all = #value)]);
            assert!(
                parse_rename_all(&[attr], Grammar::Field).unwrap().is_some(),
                "`{value}` should be accepted for a field name"
            );
        }
    }
}