closed-trait-macros 0.2.0

Attribute macros for the closed-trait crate
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
use std::collections::HashSet;

use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, format_ident, quote};
use syn::ext::IdentExt;
use syn::parse::{ParseStream, Parser};
use syn::{
    Attribute, Error, GenericArgument, GenericParam, Generics, Ident, ItemTrait, LitStr, Meta,
    Path, PathArguments, Result, Token, Type, parse_quote,
};

use crate::sealed::{self, SealedType};
use crate::util::{argument, lifetimes, mentions, name_of, ours, rename, render, snake_case};

// The options, named once so that a match arm and the messages mentioning it
// cannot drift apart.
const ATTRS: &str = "attrs";
const CRATE: &str = "crate";
const MATCH_ANY: &str = "match_any";
const NAME: &str = "name";
const NO_BRIDGE: &str = "no_bridge";
const SKIP: &str = "skip";

// The groups, which are options taking options.
const OWNED: &str = "owned";
const REF: &str = "ref";
const MUT: &str = "mut";

/// Which of the three enums a group of options is about.
#[derive(Clone, Copy, PartialEq)]
pub(crate) enum Kind {
    Owned,
    Shared,
    Unique,
}

impl Kind {
    /// What the derived names end in.
    fn suffix(self) -> &'static str {
        match self {
            Kind::Owned => "",
            Kind::Shared => "Ref",
            Kind::Unique => "Mut",
        }
    }

    fn macro_suffix(self) -> &'static str {
        match self {
            Kind::Owned => "",
            Kind::Shared => "_ref",
            Kind::Unique => "_mut",
        }
    }
}

/// One of the three enums, as it was asked for.
pub(crate) struct Enumeration {
    pub(crate) ident: Ident,
    /// What to call its match macro, if `match_any` reached it.
    pub(crate) match_any: Option<Ident>,
    /// Whether the conversions written *on* this enum are to be left out.
    pub(crate) no_bridge: bool,
    /// Attributes to put on it verbatim. Never documentation: the enum's docs
    /// are generated.
    pub(crate) attrs: Vec<Attribute>,
}

/// A validated `#[enumerate]` invocation.
pub(crate) struct Input {
    /// The trait, still carrying its `#[sealed(..)]` attribute so that the
    /// attribute can expand after this one.
    pub(crate) item: ItemTrait,
    pub(crate) variants: Vec<Variant>,
    /// The enums' own parameter declarations, and the same names as the trait
    /// writes them in its supertrait bound.
    pub(crate) enum_params: Option<TokenStream>,
    pub(crate) enum_args: Option<TokenStream>,
    /// Each of the three, unless it was skipped.
    pub(crate) owned: Option<Enumeration>,
    pub(crate) shared: Option<Enumeration>,
    pub(crate) unique: Option<Enumeration>,
    /// Where the generated code should look for `Enumerable`. Defaults to
    /// `::closed_trait`, which is wrong for anyone who renamed the dependency
    /// or reaches the macros through a re-export.
    pub(crate) krate: Path,
}

pub(crate) struct Variant {
    pub(crate) ident: Ident,
    pub(crate) ty: Type,
    /// Parameters this variant's `Enumerable` impl declares.
    pub(crate) impl_params: Option<TokenStream>,
    /// Arguments it gives the enum, which the annotation may fix.
    pub(crate) enum_args: Option<TokenStream>,
}

impl Input {
    pub(crate) fn parse(args: TokenStream, item: ItemTrait) -> Result<Self> {
        let args = parse_args(args)?;
        repeated_attribute(&item)?;

        // A `for<..>` names parameters the trait never declared, and the enum can
        // only be named in the trait's own. Every entry is rewritten into those
        // before anything reads it, so nothing downstream has to know the
        // difference.
        let entries = sealed_types(&item)?
            .into_iter()
            .map(|entry| in_traits_terms(entry, &item))
            .collect::<Result<Vec<_>>>()?;
        let shared_params = enum_parameters(&item, &entries);
        let variants = entries
            .iter()
            .map(|entry| variant(entry, &item, &shared_params))
            .collect::<Result<Vec<_>>>()?;

        let declarations = shared_params.iter().map(|param| quote!(#param));
        let arguments = shared_params.iter().map(argument);

        duplicate_variants(&variants)?;

        let enum_ident = args
            .grouped
            .name
            .clone()
            .unwrap_or_else(|| format_ident!("Any{}", item.ident));
        duplicate_conversions(&variants, &enum_ident)?;

        let owned = args.resolve(Kind::Owned, &item);
        let shared = args.resolve(Kind::Shared, &item);
        let unique = args.resolve(Kind::Unique, &item);

        if owned.is_none() && shared.is_none() && unique.is_none() {
            return Err(Error::new(
                Span::call_site(),
                "every enum was skipped, which leaves `#[enumerate]` nothing to generate",
            ));
        }

        // A match macro has one arm per variant, so an entry pinned to one
        // instantiation of a generic trait has no arm it could belong to.
        let wants_macro = [&owned, &shared, &unique]
            .into_iter()
            .flatten()
            .any(|enumeration| enumeration.match_any.is_some());
        if wants_macro {
            dispatchable(&item, &entries, &shared_params)?;
        }

        Ok(Input {
            enum_params: (!shared_params.is_empty()).then(|| quote!(<#(#declarations),*>)),
            enum_args: (!shared_params.is_empty()).then(|| quote!(<#(#arguments),*>)),
            owned,
            shared,
            unique,
            item,
            variants,
            krate: args.krate.unwrap_or_else(|| parse_quote!(::closed_trait)),
        })
    }
}

/// Options for one enum, either written in a group or applying to all three.
#[derive(Default, Clone)]
struct Options {
    skip: bool,
    name: Option<Ident>,
    /// `None` when `match_any` was never asked for, `Some(None)` when it was
    /// asked for without a name.
    match_any: Option<Option<Ident>>,
    /// The span it was written at, so a `ref(no_bridge)` can be refused where
    /// it stands.
    no_bridge: Option<Span>,
    attrs: Option<Vec<Attribute>>,
}

impl Options {
    /// Specific options win over grouped ones, field by field.
    fn over(&self, grouped: &Options) -> Options {
        Options {
            skip: self.skip,
            name: self.name.clone(),
            match_any: self.match_any.clone().or_else(|| grouped.match_any.clone()),
            no_bridge: self.no_bridge.or(grouped.no_bridge),
            attrs: self.attrs.clone(),
        }
    }
}

#[derive(Default)]
struct Args {
    /// Written bare, and so applying to all three unless overridden.
    grouped: Options,
    owned: Options,
    shared: Options,
    unique: Options,
    krate: Option<Path>,
}

impl Args {
    fn specific(&self, kind: Kind) -> &Options {
        match kind {
            Kind::Owned => &self.owned,
            Kind::Shared => &self.shared,
            Kind::Unique => &self.unique,
        }
    }

    /// One enum's settled options, or `None` if it was skipped.
    fn resolve(&self, kind: Kind, item: &ItemTrait) -> Option<Enumeration> {
        let options = self.specific(kind).over(&self.grouped);
        if options.skip {
            return None;
        }

        // A grouped `name` is a base that each kind extends; a specific one is
        // the name itself.
        let ident = options.name.clone().unwrap_or_else(|| {
            let base = self
                .grouped
                .name
                .clone()
                .unwrap_or_else(|| format_ident!("Any{}", item.ident));
            format_ident!("{base}{}", kind.suffix(), span = base.span())
        });

        // As with `name`, a specific one is the name itself while a grouped
        // one is a base that each kind extends.
        let match_any = options.match_any.map(|_| {
            if let Some(Some(named)) = &self.specific(kind).match_any {
                return named.clone();
            }
            let base = self
                .grouped
                .match_any
                .clone()
                .flatten()
                .unwrap_or_else(|| format_ident!("match_any_{}", snake_case(&item.ident)));
            format_ident!("{base}{}", kind.macro_suffix(), span = base.span())
        });

        Some(Enumeration {
            ident,
            match_any,
            no_bridge: options.no_bridge.is_some(),
            attrs: options.attrs.unwrap_or_default(),
        })
    }
}

/// The grouped options, and the `owned(..)` / `ref(..)` / `mut(..)` groups.
fn parse_args(args: TokenStream) -> Result<Args> {
    let mut parsed = Args::default();
    if args.is_empty() {
        return Ok(parsed);
    }

    // Written twice, a group would silently merge into the first rather than
    // replace it, which is neither what either spelling says.
    let mut groups = HashSet::new();
    let parser = |stream: ParseStream| -> Result<()> {
        while !stream.is_empty() {
            // `parse_any`, because `crate`, `ref` and `mut` are all keywords
            // and a plain `Ident` parse would reject them as option names.
            let key = Ident::parse_any(stream)?;
            let name = key.to_string();

            match name.as_str() {
                // A group: the same options, but only for one of the three.
                OWNED | REF | MUT => {
                    let inner;
                    syn::parenthesized!(inner in stream);
                    if !groups.insert(name.clone()) {
                        return Err(Error::new_spanned(
                            &key,
                            format!("duplicate `{name}(..)` group"),
                        ));
                    }
                    let target = match name.as_str() {
                        OWNED => &mut parsed.owned,
                        REF => &mut parsed.shared,
                        _ => &mut parsed.unique,
                    };
                    parse_options(&inner, target, true)?;
                }
                // A string for the same reason `attrs` is one: it delimits the
                // path, so a malformed value says so instead of derailing the
                // rest of the list.
                CRATE => {
                    stream.parse::<Token![=]>()?;
                    if !stream.peek(LitStr) {
                        return Err(stream.error(format!(
                            r#"expected a string, as in `{CRATE} = "::my_reexport"`"#
                        )));
                    }
                    let literal = stream.parse::<LitStr>()?;
                    let value = literal.parse::<Path>().map_err(|_| {
                        Error::new_spanned(&literal, "expected a path to the `closed-trait` crate")
                    })?;
                    if parsed.krate.replace(value).is_some() {
                        return Err(duplicate(&key));
                    }
                }
                _ => option(&key, stream, &mut parsed.grouped, false)?,
            }

            if stream.is_empty() {
                break;
            }
            stream.parse::<Token![,]>()?;
        }
        Ok(())
    };
    parser.parse2(args)?;

    // Nothing is written on the shared enum, so asking to leave it out is a
    // mistake rather than a no-op. Only a `ref(..)` group is refused; a bare
    // `no_bridge` reaching it through the grouped options is not.
    if let Some(span) = parsed.shared.no_bridge {
        return Err(Error::new(
            span,
            format!(
                "`{NO_BRIDGE}` has nothing to leave out here: no conversion is written on the \
                 borrowing enum's shared form.\nWrite it on `{OWNED}` to drop `as_ref` and \
                 `as_mut` from the owned enum, or on `{MUT}` to drop the reborrowing `as_ref`"
            ),
        ));
    }

    Ok(parsed)
}

/// A comma separated list of options inside a group.
fn parse_options(stream: ParseStream, options: &mut Options, in_group: bool) -> Result<()> {
    while !stream.is_empty() {
        let key = Ident::parse_any(stream)?;
        option(&key, stream, options, in_group)?;

        if stream.is_empty() {
            break;
        }
        stream.parse::<Token![,]>()?;
    }
    Ok(())
}

/// An option written twice, which is a mistake rather than an override: the
/// second would either be ignored or merged into the first, and neither is what
/// writing it twice says.
fn duplicate(key: &Ident) -> Error {
    Error::new_spanned(key, format!("duplicate `{key}` option"))
}

/// One option, wherever it was written.
fn option(key: &Ident, stream: ParseStream, options: &mut Options, in_group: bool) -> Result<()> {
    match key.to_string().as_str() {
        SKIP if in_group => {
            if options.skip {
                return Err(duplicate(key));
            }
            options.skip = true;
        }
        MATCH_ANY => {
            let named = if stream.peek(syn::token::Paren) {
                let inner;
                syn::parenthesized!(inner in stream);
                if !inner.peek(LitStr) {
                    return Err(inner.error(format!(
                        r#"expected a string, as in `{MATCH_ANY}("match_shape")`"#
                    )));
                }
                let named = inner.parse::<LitStr>()?.parse::<Ident>()?;
                // Every other list here takes one, so this one does too.
                if inner.peek(Token![,]) {
                    inner.parse::<Token![,]>()?;
                }
                if !inner.is_empty() {
                    return Err(inner.error(format!(
                        "`{MATCH_ANY}` takes one name, which every enum extends: \
                         `{OWNED}({MATCH_ANY}(..))` names the macro for one of them"
                    )));
                }
                Some(named)
            } else {
                None
            };
            if options.match_any.replace(named).is_some() {
                return Err(duplicate(key));
            }
        }
        NO_BRIDGE => {
            if options.no_bridge.replace(key.span()).is_some() {
                return Err(duplicate(key));
            }
        }
        // A string, as every option carrying a name or a visibility is written
        // across these macros, so one spelling covers them all.
        NAME => {
            stream.parse::<Token![=]>()?;
            if !stream.peek(LitStr) {
                return Err(
                    stream.error(format!(r#"expected a string, as in `{NAME} = "Shapes"`"#))
                );
            }
            let value = stream.parse::<LitStr>()?.parse::<Ident>()?;
            if options.name.replace(value).is_some() {
                return Err(duplicate(key));
            }
        }
        // Only ever inside a group. What is valid differs between the three --
        // the shared enum already derives `Copy`, the unique one cannot derive
        // `Clone` at all -- so spreading one spelling across them would be a
        // trap rather than a convenience.
        ATTRS if !in_group => {
            return Err(Error::new_spanned(
                key,
                format!(
                    r#"`{ATTRS}` applies to one enum at a time, as in `{OWNED}({ATTRS} = "..")`"#
                ),
            ));
        }
        // A string, so the `#[..]` inside is unambiguous to both the parser and
        // to tooling. `parse_with` keeps error spans inside the literal rather
        // than on the attribute as a whole.
        ATTRS => {
            stream.parse::<Token![=]>()?;
            if !stream.peek(LitStr) {
                return Err(stream.error(format!(
                    r##"expected a string of attributes, as in `{ATTRS} = "#[derive(Debug)]"`"##
                )));
            }
            let literal = stream.parse::<LitStr>()?;
            let attrs = literal.parse_with(Attribute::parse_outer)?;
            // `///` desugars to `#[doc]`, so this catches both spellings.
            if let Some(doc) = attrs.iter().find(|attr| attr.path().is_ident("doc")) {
                return Err(Error::new_spanned(
                    doc,
                    format!(
                        "`{ATTRS}` cannot document the enum: its documentation is generated \
                         and is the same for every sealed trait"
                    ),
                ));
            }
            if options.attrs.replace(attrs).is_some() {
                return Err(duplicate(key));
            }
        }
        unknown => {
            let where_ = if in_group {
                format!("expected `{SKIP}`, `{NAME}`, `{MATCH_ANY}`, `{NO_BRIDGE}` or `{ATTRS}`")
            } else {
                format!(
                    "expected `{OWNED}`, `{REF}`, `{MUT}`, `{NAME}`, `{MATCH_ANY}`, \
                     `{NO_BRIDGE}` or `{CRATE}`"
                )
            };
            return Err(Error::new_spanned(
                key,
                format!("unknown option `{unknown}`, {where_}"),
            ));
        }
    }
    Ok(())
}

/// `#[enumerate]` written twice, which is one enum too many.
///
/// An attribute is handed the item with the attributes *below* it still
/// attached, so a second one is visible from the first. Only the spellings this
/// crate is reached by are read as a duplicate: another crate's `enumerate`
/// would be refused here for no reason, and rustc reports the duplicate enums
/// anyway.
///
/// Refusing here stops *this* expansion and leaves the one below to run, which
/// is the opposite of what `#[sealed]` does with its own duplicate, and for the
/// opposite reason: what this macro writes is named by the caller, so dropping
/// both would leave every use of `AnyShape` unresolved, while the enums the
/// duplicate would have written are the same ones.
fn repeated_attribute(item: &ItemTrait) -> Result<()> {
    match item.attrs.iter().find(|attr| ours(attr, "enumerate")) {
        Some(attr) => Err(Error::new_spanned(
            attr,
            format!(
                "`#[{}]` is written twice, and each one generates the enums.\nWrite it once, \
                 above the `#[sealed(..)]` it reads",
                render(attr.path()),
            ),
        )),
        None => Ok(()),
    }
}

/// `#[enumerate]` has to sit above it.
fn sealed_types(item: &ItemTrait) -> Result<Vec<SealedType>> {
    // Other crates export a `sealed` attribute too, so a qualified path ending
    // in `sealed` is only a candidate. The bare spelling is unambiguous and
    // wins outright; otherwise take the first candidate whose arguments
    // actually parse as a type list, and let a lone candidate report its own
    // error rather than being passed over.
    let candidates: Vec<_> = item
        .attrs
        .iter()
        .filter(|attr| {
            attr.path()
                .segments
                .last()
                .is_some_and(|segment| segment.ident == "sealed")
        })
        .collect();

    // Two lists are one too many, and saying so here matters as much as saying it
    // from `#[sealed]`: this macro runs first, and anything it generates from one
    // of the lists would refuse every type in the other.
    let mut seen = HashSet::new();
    for attr in &candidates {
        let path = render(attr.path());
        if !seen.insert(path.clone()) {
            return Err(Error::new_spanned(
                attr,
                format!(
                    "`#[{path}(..)]` is written twice, and a trait is sealed to one list.\nWrite \
                     one attribute listing every permitted type"
                ),
            ));
        }
    }

    let bare = candidates
        .iter()
        .find(|attr| attr.path().is_ident("sealed"));
    let chosen = match (bare, candidates.as_slice()) {
        (Some(attr), _) => Some(*attr),
        (None, [only]) => Some(*only),
        (None, several) => several
            .iter()
            .copied()
            .find(|attr| parse_sealed(attr).is_ok()),
    };

    let attr = chosen.ok_or_else(|| {
        Error::new_spanned(
            &item.ident,
            "`#[enumerate]` needs a `#[sealed(..)]` attribute written below it, \
             to know which types the enum should hold",
        )
    })?;

    // An empty seal is a trait nothing may implement, which `#[sealed]` allows.
    // There is no enum to make from it: one with no variants could be neither
    // constructed nor matched, and the borrowing pair could not even declare the
    // lifetime they carry.
    match parse_sealed(attr)? {
        types if types.is_empty() => Err(Error::new_spanned(
            attr,
            "`#[enumerate]` needs at least one type to make an enum from, and this \
             `#[sealed(..)]` lists none",
        )),
        types => Ok(types),
    }
}

fn parse_sealed(attr: &Attribute) -> Result<Vec<SealedType>> {
    // `#[sealed]` written bare is an empty list rather than a malformed one, so
    // the arguments are only required to parse when they are there at all.
    let tokens = match &attr.meta {
        Meta::Path(_) => TokenStream::new(),
        meta => meta.require_list()?.tokens.clone(),
    };
    Ok(sealed::Args::parse(tokens)?.types)
}

/// The enum's parameters: those of the trait that at least one entry names.
///
/// They can only come from the trait, because they have to be nameable in the
/// supertrait bound `Enumerable<AnyThing<..>>` that names the enum, and
/// nothing else is in scope there.
fn enum_parameters(item: &ItemTrait, entries: &[SealedType]) -> Vec<GenericParam> {
    item.generics
        .params
        .iter()
        .filter(|param| entries.iter().any(|entry| uses(&entry.ty, param)))
        .cloned()
        .collect()
}

/// A trait parameter carrying whatever the entry's binder asked of it as well.
///
/// `for<U: Debug> Held<U>: Keep<U>` says `Held<T>` implements `Keep<T>` only where
/// `T: Debug`, so the impls carrying it into the enum say the same. Without this
/// they would claim it for every `T`, and an `AnyKeep<T>` could hold a `Held<T>`
/// that does not implement the trait at all.
fn bounded(param: &GenericParam, entry: &SealedType) -> GenericParam {
    let name = name_of(param);
    let bound = entry
        .binder
        .iter()
        .flat_map(|binder| binder.params.iter())
        .find(|bound| name_of(bound) == name);

    // Only what the trait does not already ask: the two lists overlap whenever a
    // binder repeats a bound the trait declares, and `T: Debug + Debug` compiles
    // but reads as a mistake.
    match (param.clone(), bound) {
        (GenericParam::Type(mut param), Some(GenericParam::Type(bound))) => {
            let known: Vec<String> = param.bounds.iter().map(render).collect();
            let added = bound
                .bounds
                .iter()
                .filter(|bound| !known.contains(&render(bound)))
                .cloned()
                .collect::<Vec<_>>();
            param.bounds.extend(added);
            GenericParam::Type(param)
        }
        (GenericParam::Lifetime(mut param), Some(GenericParam::Lifetime(bound))) => {
            let known: Vec<String> = param.bounds.iter().map(render).collect();
            let added = bound
                .bounds
                .iter()
                .filter(|bound| !known.contains(&render(bound)))
                .cloned()
                .collect::<Vec<_>>();
            param.bounds.extend(added);
            GenericParam::Lifetime(param)
        }
        // A const parameter carries no bounds, and a mismatched kind is rustc's
        // to report against the instantiation.
        (param, _) => param,
    }
}

fn uses(ty: &impl ToTokens, param: &GenericParam) -> bool {
    match param {
        GenericParam::Lifetime(param) => lifetimes(ty).contains(&param.lifetime.ident),
        GenericParam::Type(param) => mentions(ty, &param.ident.to_string()),
        GenericParam::Const(param) => mentions(ty, &param.ident.to_string()),
    }
}

/// The entry's type written in the trait's own parameters.
///
/// A `for<..>` declares parameters the trait never did, and the enum is named in
/// a supertrait bound where only the trait's are in scope. The instantiation is
/// what ties the two together: in `for<U> Boxed<U>: Store<U>` on `trait Store<T>`,
/// `U` stands where `T` does, so the variant holds `Boxed<T>`.
///
/// A binder parameter the instantiation does not place stays free, and an entry
/// whose type needs one cannot be held at all.
fn in_traits_terms(entry: SealedType, item: &ItemTrait) -> Result<SealedType> {
    let Some(binder) = &entry.binder else {
        return Ok(entry);
    };

    // Positional, as the trait's parameters and the instantiation's arguments
    // line up: only an argument that is exactly a bound name places one.
    let arguments = entry
        .instantiation
        .as_ref()
        .map(instantiation_arguments)
        .unwrap_or_default();
    let renames: Vec<(String, TokenStream)> = item
        .generics
        .params
        .iter()
        .zip(arguments)
        .filter_map(|(param, given)| {
            let given = render(&given);
            let bound = binder
                .params
                .iter()
                .find(|bound| name_of_argument(bound) == given)?;
            Some((name_of_argument(bound), argument(param)))
        })
        .collect();

    for bound in &binder.params {
        let name = name_of_argument(bound);
        let used = match bound {
            GenericParam::Lifetime(bound) => lifetimes(&entry.ty)
                .iter()
                .any(|found| found == &bound.lifetime.ident),
            other => mentions(&entry.ty, &name_of(other)),
        };
        if !used || renames.iter().any(|(from, _)| from == &name) {
            continue;
        }

        // Only worth suggesting where the trait has a parameter to stand for.
        let remedy = match item.generics.params.is_empty() {
            true => format!(
                "Declare `{name}` on `{}` itself, or remove `#[enumerate]`",
                item.ident
            ),
            false => format!(
                "Write `: {}<..>` with `{name}` where that parameter goes, or remove \
                 `#[enumerate]`",
                item.ident,
            ),
        };
        return Err(Error::new_spanned(
            &entry.ty,
            format!(
                "`#[enumerate]` cannot hold `{}`: `{name}` is bound by the `for<..>` and the \
                 instantiation does not say which of `{}`'s parameters it stands for, so the \
                 generated enum could not be named in its supertrait bound.\n{remedy}",
                render(&entry.ty),
                item.ident,
            ),
        ));
    }

    // The instantiation is rewritten with it: it says which `Store` the type
    // implements, and must say so in the same parameters the type now uses.
    let instantiation = match &entry.instantiation {
        Some(path) => Some(syn::parse2(rename(path, &renames))?),
        None => None,
    };

    // Kept rather than dropped, renamed along with everything else: a bound the
    // binder wrote is the caller's, and the impls carrying the type into the enum
    // have to keep it. `for<U: Debug> Held<U>: Keep<U>` becomes `for<T: Debug>`,
    // and only `Held<T>` where `T: Debug` reaches `AnyKeep<T>`.
    let params = binder
        .params
        .iter()
        .map(|param| syn::parse2::<GenericParam>(rename(param, &renames)))
        .collect::<Result<_>>()?;
    let binder = Generics {
        params,
        ..binder.clone()
    };

    Ok(SealedType {
        ty: syn::parse2(rename(&entry.ty, &renames))?,
        binder: Some(binder),
        instantiation,
        ..entry
    })
}

/// The arguments an instantiation writes, as in `Store<i32>`.
fn instantiation_arguments(path: &Path) -> Vec<GenericArgument> {
    match path.segments.last().map(|segment| &segment.arguments) {
        Some(PathArguments::AngleBracketed(arguments)) => arguments.args.iter().cloned().collect(),
        _ => Vec::new(),
    }
}

/// The variant is named after the type's last path segment, so
/// `crate::shapes::Circle` becomes `Circle`.
fn variant(entry: &SealedType, item: &ItemTrait, shared: &[GenericParam]) -> Result<Variant> {
    let ty = &entry.ty;

    // The instantiation counts as much as the type does: `Plain: Keep<T>` names
    // `T` where `Plain` names nothing, and the impls carrying it into the enum
    // have to declare what they name.
    let declared: Vec<GenericParam> = item
        .generics
        .params
        .iter()
        .filter(|param| {
            uses(ty, param)
                || entry
                    .instantiation
                    .as_ref()
                    .is_some_and(|path| uses(path, param))
        })
        .map(|param| bounded(param, entry))
        .collect();

    let free: Vec<_> = lifetimes(ty)
        .into_iter()
        .filter(|name| {
            !item
                .generics
                .lifetimes()
                .any(|param| &param.lifetime.ident == name)
        })
        .collect();
    if let Some(lifetime) = free.first() {
        return Err(Error::new_spanned(
            ty,
            format!(
                "`#[enumerate]` cannot hold `{}`: `'{}` is not a parameter of `{}`, so the \
                 generated enum could not be named in its supertrait bound.\nDeclare `'{}` on \
                 `{}` itself, or remove `#[enumerate]`",
                render(ty),
                lifetime,
                item.ident,
                lifetime,
                item.ident,
            ),
        ));
    }

    let arguments = enum_arguments(entry, item, shared, &declared)?;
    let declarations = declared.iter().map(|param| quote!(#param));

    // An explicit `as Alias` names the variant; otherwise it is the type's last
    // path segment, which is why two entries can collide.
    let ident = match &entry.alias {
        Some(alias) => alias.clone(),
        None => {
            let Type::Path(path) = ty else {
                return Err(Error::new_spanned(
                    ty,
                    "`#[enumerate]` needs each sealed type to be a path so the variant can be \
                     named after it, or an explicit `as Name`",
                ));
            };
            path.path
                .segments
                .last()
                .map(|segment| segment.ident.clone())
                .ok_or_else(|| {
                    Error::new_spanned(ty, "expected a path with at least one segment")
                })?
        }
    };

    Ok(Variant {
        ident,
        ty: ty.clone(),
        impl_params: (!declared.is_empty()).then(|| quote!(<#(#declarations),*>)),
        enum_args: arguments,
    })
}

/// The arguments this entry gives the enum in its `Enumerable` impl.
///
/// Every one has to be determined by the entry's own type, since an impl cannot
/// carry a parameter its self type does not constrain. A type that names the
/// trait's parameters determines them directly; one that does not needs the
/// annotation to fix them.
fn enum_arguments(
    entry: &SealedType,
    item: &ItemTrait,
    shared: &[GenericParam],
    declared: &[GenericParam],
) -> Result<Option<TokenStream>> {
    if shared.is_empty() {
        return Ok(None);
    }

    let fixed = entry.instantiation.as_ref().map(|path| {
        let arguments = match path.segments.last().map(|segment| &segment.arguments) {
            Some(PathArguments::AngleBracketed(arguments)) => {
                arguments.args.iter().cloned().collect::<Vec<_>>()
            }
            _ => Vec::new(),
        };
        item.generics
            .params
            .iter()
            .zip(arguments)
            .map(|(param, argument)| (name_of(param), quote!(#argument)))
            .collect::<Vec<_>>()
    });

    let mut arguments = Vec::new();
    for param in shared {
        let name = name_of(param);
        let annotated = match &fixed {
            Some(fixed) => fixed
                .iter()
                .find(|(fixed, _)| fixed == &name)
                .map(|(_, tokens)| tokens.clone()),
            None => None,
        };

        let chosen = match annotated {
            Some(annotated) => annotated,
            None if declared.iter().any(|known| name_of(known) == name) => argument(param),
            // The entry says nothing about which instantiation it implements,
            // and `#[sealed]` refuses it for that on its own. Repeating its
            // wording at its span leaves one diagnostic rather than two saying
            // the same thing about the same entry.
            None => return Err(sealed::needs_instantiation(&entry.ty, item)),
        };
        arguments.push(chosen);
    }

    Ok(Some(quote!(<#(#arguments),*>)))
}

fn name_of_argument(param: &GenericParam) -> String {
    match param {
        GenericParam::Lifetime(param) => format!("'{}", param.lifetime.ident),
        other => name_of(other),
    }
}

/// Checks that the match can actually cover every entry.
///
/// The macro has one arm per variant of the enum at its own instantiation, so
/// every entry has to be one of them. Two things break that: an entry that
/// implements the trait at one fixed instantiation, and a trait parameter no
/// entry names, which would leave the bound with nothing to put in its place.
fn dispatchable(item: &ItemTrait, entries: &[SealedType], shared: &[GenericParam]) -> Result<()> {
    if let Some(unused) = item
        .generics
        .params
        .iter()
        .find(|param| !shared.iter().any(|used| name_of(used) == name_of(param)))
    {
        return Err(Error::new_spanned(
            unused,
            format!(
                "`#[enumerate({MATCH_ANY})]` needs every parameter of `{}` to appear in the \
                 sealed types, and `{}` appears in none of them, so the match has nothing to \
                 name.\nUse it in a sealed type, or drop the option",
                item.ident,
                name_of(unused),
            ),
        ));
    }

    // An instantiation only bars the entry when it *fixes* something: written in
    // the trait's own parameters it is the identity, and the entry is a variant of
    // every instantiation like any other.
    let wanted = render(&trait_bound(item, shared));
    let pinned = entries.iter().find_map(|entry| {
        let instantiation = entry.instantiation.as_ref()?;
        (render(instantiation) != wanted).then_some((entry, instantiation))
    });
    if let Some((entry, instantiation)) = pinned {
        return Err(Error::new_spanned(
            &entry.ty,
            format!(
                "`#[enumerate({MATCH_ANY})]` cannot match `{ty}`: it implements `{had}`, not \
                 `{want}`, so it is not a variant of every `{want}`.\nDrop the `{MATCH_ANY}` \
                 option, or make `{ty}` generic over the same parameters as `{trait_}`",
                ty = render(&entry.ty),
                had = render(instantiation),
                want = wanted,
                trait_ = item.ident,
            ),
        ));
    }

    Ok(())
}

/// The trait at the enum's own instantiation: `Shape`, or `Store<T>`.
pub(crate) fn trait_bound(item: &ItemTrait, shared: &[GenericParam]) -> TokenStream {
    let ident = &item.ident;
    let arguments = shared.iter().map(argument);
    let arguments = (!shared.is_empty()).then(|| quote!(<#(#arguments),*>));
    quote!(#ident #arguments)
}

/// Two entries mapping the same type into the same enum would each implement
/// `Enumerable` for it, leaving `into_enum` with two answers.
///
/// Sharing a type is otherwise fine: entries that pin different arguments land
/// in different enum types, so `Plain: Store<i32>` and `Plain: Store<f64>` can
/// coexist as long as the enum stays generic, which needs some entry to name
/// the parameter rather than fixing it.
fn duplicate_conversions(variants: &[Variant], enum_ident: &Ident) -> Result<()> {
    let key = |variant: &Variant| {
        let ty = &variant.ty;
        let args = &variant.enum_args;
        render(&quote!(#ty #args))
    };

    for (index, variant) in variants.iter().enumerate() {
        if variants[..index]
            .iter()
            .any(|earlier| key(earlier) == key(variant))
        {
            let ty = render(&variant.ty);
            let args = variant.enum_args.as_ref().map(render).unwrap_or_default();
            return Err(Error::new_spanned(
                &variant.ty,
                format!(
                    "`{ty}` is listed twice for the same `{enum_ident}{args}`, so `into_enum` \
                     would have two answers.\nEntries may share a type only when they pin \
                     different arguments, which needs the enum to stay generic: some entry has \
                     to name the parameter rather than fixing it"
                ),
            ));
        }
    }
    Ok(())
}

/// Two entries whose last path segment matches would produce one variant name
/// twice, which rustc reports against the generated enum rather than the list.
fn duplicate_variants(variants: &[Variant]) -> Result<()> {
    for (index, variant) in variants.iter().enumerate() {
        if let Some(earlier) = variants[..index]
            .iter()
            .find(|earlier| earlier.ident == variant.ident)
        {
            return Err(Error::new_spanned(
                &variant.ty,
                format!(
                    "`{}` and `{}` would both become the `{}` variant, since a variant is named \
                     after the type's last path segment.\nGive one an explicit name: \
                     `{} as SomeName`",
                    render(&earlier.ty),
                    render(&variant.ty),
                    variant.ident,
                    render(&variant.ty),
                ),
            ));
        }
    }
    Ok(())
}

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

    /// The three enums as the attribute settles them, in owned/ref/mut order.
    fn resolved(attr: TokenStream) -> [Option<Enumeration>; 3] {
        let args = parse_args(attr).expect("the attribute parses");
        let item: ItemTrait = parse_quote!(
            pub trait Shape {}
        );
        [
            args.resolve(Kind::Owned, &item),
            args.resolve(Kind::Shared, &item),
            args.resolve(Kind::Unique, &item),
        ]
    }

    fn names(attr: TokenStream) -> Vec<Option<String>> {
        resolved(attr)
            .iter()
            .map(|kind| kind.as_ref().map(|kind| kind.ident.to_string()))
            .collect()
    }

    fn macros(attr: TokenStream) -> Vec<Option<String>> {
        resolved(attr)
            .iter()
            .map(|kind| {
                kind.as_ref()
                    .and_then(|kind| kind.match_any.as_ref())
                    .map(|name| name.to_string())
            })
            .collect()
    }

    fn bridges(attr: TokenStream) -> Vec<Option<bool>> {
        resolved(attr)
            .iter()
            .map(|kind| kind.as_ref().map(|kind| !kind.no_bridge))
            .collect()
    }

    #[test]
    fn bare_gives_all_three_and_no_macros() {
        assert_eq!(
            names(quote!()),
            vec![
                Some("AnyShape".to_owned()),
                Some("AnyShapeRef".to_owned()),
                Some("AnyShapeMut".to_owned()),
            ]
        );
        assert_eq!(macros(quote!()), vec![None, None, None]);
        assert_eq!(bridges(quote!()), vec![Some(true); 3]);
    }

    #[test]
    fn a_grouped_name_is_a_base_each_kind_extends() {
        assert_eq!(
            names(quote!(name = "Shapes")),
            vec![
                Some("Shapes".to_owned()),
                Some("ShapesRef".to_owned()),
                Some("ShapesMut".to_owned()),
            ]
        );
    }

    #[test]
    fn a_specific_name_is_the_name_itself() {
        // and leaves the other two on the grouped base
        assert_eq!(
            names(quote!(name = "Shapes", ref(name = "View"))),
            vec![
                Some("Shapes".to_owned()),
                Some("View".to_owned()),
                Some("ShapesMut".to_owned()),
            ]
        );
    }

    #[test]
    fn a_grouped_macro_name_is_a_base_too() {
        assert_eq!(
            macros(quote!(match_any)),
            vec![
                Some("match_any_shape".to_owned()),
                Some("match_any_shape_ref".to_owned()),
                Some("match_any_shape_mut".to_owned()),
            ]
        );
        assert_eq!(
            macros(quote!(match_any("walk"))),
            vec![
                Some("walk".to_owned()),
                Some("walk_ref".to_owned()),
                Some("walk_mut".to_owned()),
            ]
        );
    }

    #[test]
    fn a_specific_macro_name_overrides_just_that_one() {
        assert_eq!(
            macros(quote!(match_any, mut(match_any("walk")))),
            vec![
                Some("match_any_shape".to_owned()),
                Some("match_any_shape_ref".to_owned()),
                Some("walk".to_owned()),
            ]
        );
    }

    #[test]
    fn a_macro_asked_for_in_one_group_only_reaches_that_one() {
        assert_eq!(
            macros(quote!(ref(match_any))),
            vec![None, Some("match_any_shape_ref".to_owned()), None]
        );
    }

    #[test]
    fn skip_drops_only_its_own_kind() {
        assert_eq!(
            names(quote!(ref(skip))),
            vec![
                Some("AnyShape".to_owned()),
                None,
                Some("AnyShapeMut".to_owned()),
            ]
        );
        assert_eq!(
            names(quote!(owned(skip), mut(skip))),
            vec![None, Some("AnyShapeRef".to_owned()), None]
        );
    }

    #[test]
    fn no_bridge_applies_to_the_enum_it_is_written_on() {
        assert_eq!(bridges(quote!(no_bridge)), vec![Some(false); 3]);
        assert_eq!(
            bridges(quote!(owned(no_bridge))),
            vec![Some(false), Some(true), Some(true)]
        );
        assert_eq!(
            bridges(quote!(mut(no_bridge))),
            vec![Some(true), Some(true), Some(false)]
        );
    }

    /// Nothing is written on the shared enum, so asking to leave it out is a
    /// mistake rather than a no-op.
    #[test]
    fn no_bridge_on_ref_is_refused() {
        assert!(refused(quote!(ref(no_bridge))).contains("nothing to leave out"));
    }

    /// The one option a group cannot take back: there is no positive spelling
    /// of `no_bridge`, so a grouped one stays on everywhere.
    #[test]
    fn a_grouped_no_bridge_cannot_be_undone_by_a_group() {
        assert_eq!(
            bridges(quote!(no_bridge, ref(name = "View"))),
            vec![Some(false); 3]
        );
    }

    #[test]
    fn attrs_reach_only_the_group_they_are_written_in() {
        let resolved = resolved(quote!(ref(attrs = "#[derive(Debug)]")));
        assert!(resolved[0].as_ref().expect("owned").attrs.is_empty());
        assert_eq!(resolved[1].as_ref().expect("ref").attrs.len(), 1);
        assert!(resolved[2].as_ref().expect("mut").attrs.is_empty());
    }

    /// `Args` has no `Debug`, syn's own impls being behind a feature, so the
    /// error comes out by hand rather than through `expect_err`.
    fn refused(attr: TokenStream) -> String {
        match parse_args(attr) {
            Err(error) => error.to_string(),
            Ok(_) => panic!("expected the attribute to be refused"),
        }
    }

    /// Every option is written at most once. A second one would be ignored,
    /// silently win over the first, or merge into it, and none of the three is
    /// what writing it twice says.
    #[test]
    fn every_option_forbids_duplicates() {
        let cases = [
            (quote!(name = "A", name = "B"), "name"),
            (quote!(crate = "::a", crate = "::b"), "crate"),
            (quote!(match_any("a"), match_any("b")), "match_any"),
            (quote!(no_bridge, no_bridge), "no_bridge"),
            (quote!(owned(skip, skip)), "skip"),
            (
                quote!(owned(
                    attrs = "#[derive(Debug)]",
                    attrs = "#[non_exhaustive]"
                )),
                "attrs",
            ),
        ];

        for (attr, option) in cases {
            let message = refused(attr);
            assert!(
                message.contains(&format!("duplicate `{option}`")),
                "`{option}` written twice gave {message}"
            );
        }
    }

    /// The groups too: a second one would merge into the first rather than
    /// replace it.
    #[test]
    fn every_group_forbids_duplicates() {
        for group in ["owned", "ref", "mut"] {
            let attr: TokenStream = format!("{group}(no_bridge), {group}(name = \"A\")")
                .parse()
                .expect("the options parse");
            let message = refused(attr);
            assert!(
                message.contains(&format!("duplicate `{group}(..)` group")),
                "`{group}` written twice gave {message}"
            );
        }
    }

    /// An attribute sees the ones written below it, so a second `#[enumerate]`
    /// is visible from the first. Only the spellings this crate is reached by
    /// count as one.
    #[test]
    fn a_second_enumerate_attribute_is_refused() {
        let refused = |item: ItemTrait| match Input::parse(TokenStream::new(), item) {
            Err(error) => error.to_string(),
            Ok(_) => panic!("expected the attribute to be refused"),
        };

        let message = refused(parse_quote!(
            #[enumerate]
            #[sealed(Square)]
            pub trait Shape {}
        ));
        assert!(message.contains("is written twice"), "{message}");

        let message = refused(parse_quote!(
            #[closed_trait::enumerate]
            #[sealed(Square)]
            pub trait Shape {}
        ));
        assert!(message.contains("is written twice"), "{message}");
    }

    /// Another crate's `enumerate` is not this one's, and rustc reports the
    /// duplicate enums if it turns out to be.
    #[test]
    fn another_crates_enumerate_is_left_alone() {
        let item: ItemTrait = parse_quote!(
            #[other::enumerate]
            #[sealed(Square)]
            pub trait Shape {}
        );
        assert!(Input::parse(TokenStream::new(), item).is_ok());
    }

    /// Every list here takes a trailing comma, including the one-item list a
    /// `match_any(..)` name is written in.
    #[test]
    fn a_trailing_comma_is_accepted_everywhere() {
        assert_eq!(
            names(quote!(name = "Shapes", ref(name = "View",),)),
            names(quote!(name = "Shapes", ref(name = "View")))
        );
        assert_eq!(
            macros(quote!(match_any("walk",),)),
            macros(quote!(match_any("walk")))
        );
        assert!(parse_args(quote!(owned(skip,),)).is_ok());
    }

    /// One name, which each enum extends. Naming them separately is what the
    /// groups are for.
    #[test]
    fn match_any_takes_one_name() {
        let message = refused(quote!(match_any("one", "two")));
        assert!(message.contains("takes one name"), "{message}");
    }

    #[test]
    fn bare_attrs_is_refused() {
        assert!(refused(quote!(attrs = "#[derive(Debug)]")).contains("one enum at a time"));
    }

    #[test]
    fn skip_is_refused_outside_a_group() {
        assert!(refused(quote!(skip)).contains("unknown option `skip`"));
    }

    /// A name is written as a string, as it is for every other macro here, so
    /// the bare identifier is refused with the spelling that works.
    #[test]
    fn a_bare_name_is_refused() {
        assert!(refused(quote!(name = Shapes)).contains(r#"`name = "Shapes"`"#));
        assert!(refused(quote!(ref(name = View))).contains(r#"`name = "Shapes"`"#));
        assert!(refused(quote!(match_any(walk))).contains(r#"`match_any("match_shape")`"#));
    }
}