autumn-macros 0.9.0

Proc macros for the Autumn web framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
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
//! `#[lifecycle]` attribute macro implementation.
//!
//! Applied to an enum, `#[lifecycle]` turns a plain state enum into a
//! statically-verified lifecycle. Given a declared `initial` state, one or more
//! `terminal` states, and a set of `transitions`, it generates two things:
//!
//! 1. **Metadata consts + `can_transition_to`** on the enum itself, referencing
//!    the enum's own variants — so a declared `initial`/`terminal`/transition
//!    endpoint that is not a real variant is a compile error *by construction*.
//! 2. **A typestate transition module** (named after the enum in `snake_case`)
//!    with one zero-size marker type per state and a `Machine<S>` whose
//!    consuming `to_<target>` methods exist *only* for declared edges — firing
//!    an undeclared transition simply does not compile.
//!
//! It also proves the declared graph structurally sound (issue #1675): an
//! unreachable state, or a reachable non-terminal state with no path to a
//! terminal, is a compile error naming the variant. See
//! [`check_graph_soundness`].
//!
//! ```ignore
//! use autumn_web::lifecycle;
//!
//! #[lifecycle(
//!     initial = Draft,
//!     terminal(Archived),
//!     transitions(
//!         Draft -> Published,
//!         Published -> Archived,
//!         Published -> Draft,
//!     )
//! )]
//! #[derive(Debug, Clone, Copy, PartialEq, Eq)]
//! pub enum ArticleState { Draft, Published, Archived }
//! ```

use std::collections::{BTreeMap, BTreeSet, VecDeque};

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Ident, ItemEnum, Token};

/// A single `From -> To` transition edge parsed from the `transitions(...)`
/// list.
struct Transition {
    from: Ident,
    to: Ident,
}

impl Parse for Transition {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let from: Ident = input.parse()?;
        input.parse::<Token![->]>()?;
        let to: Ident = input.parse()?;
        Ok(Self { from, to })
    }
}

/// Parsed `#[lifecycle(...)]` attribute arguments.
struct LifecycleArgs {
    initial: Ident,
    terminals: Vec<Ident>,
    transitions: Vec<Transition>,
}

impl Parse for LifecycleArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut initial: Option<Ident> = None;
        let mut terminals: Option<Vec<Ident>> = None;
        let mut transitions: Option<Vec<Transition>> = None;

        while !input.is_empty() {
            let key: Ident = input.parse()?;
            match key.to_string().as_str() {
                "initial" => {
                    if initial.is_some() {
                        return Err(syn::Error::new_spanned(
                            &key,
                            "duplicate `initial` — declare exactly one initial state",
                        ));
                    }
                    input.parse::<Token![=]>()?;
                    initial = Some(input.parse()?);
                }
                "terminal" => {
                    if terminals.is_some() {
                        return Err(syn::Error::new_spanned(
                            &key,
                            "duplicate `terminal` — declare all terminal states in one `terminal(...)`",
                        ));
                    }
                    let content;
                    syn::parenthesized!(content in input);
                    let idents: Punctuated<Ident, Token![,]> =
                        content.parse_terminated(Ident::parse, Token![,])?;
                    if idents.is_empty() {
                        return Err(syn::Error::new_spanned(
                            &key,
                            "`terminal(...)` requires at least one terminal state",
                        ));
                    }
                    terminals = Some(idents.into_iter().collect());
                }
                "transitions" => {
                    if transitions.is_some() {
                        return Err(syn::Error::new_spanned(
                            &key,
                            "duplicate `transitions` — declare all edges in one `transitions(...)`",
                        ));
                    }
                    let content;
                    syn::parenthesized!(content in input);
                    let edges: Punctuated<Transition, Token![,]> =
                        content.parse_terminated(Transition::parse, Token![,])?;
                    if edges.is_empty() {
                        return Err(syn::Error::new_spanned(
                            &key,
                            "`transitions(...)` requires at least one `From -> To` edge",
                        ));
                    }
                    transitions = Some(edges.into_iter().collect());
                }
                other => {
                    return Err(syn::Error::new_spanned(
                        &key,
                        format!(
                            "unknown `#[lifecycle]` argument `{other}` — expected `initial`, `terminal`, or `transitions`"
                        ),
                    ));
                }
            }

            // Allow (and consume) a separating comma between top-level args.
            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        let initial = initial.ok_or_else(|| {
            syn::Error::new(
                proc_macro2::Span::call_site(),
                "missing required `initial = <Variant>` in `#[lifecycle(...)]`",
            )
        })?;
        let terminals = terminals.ok_or_else(|| {
            syn::Error::new(
                proc_macro2::Span::call_site(),
                "missing required `terminal(<Variant>, ...)` in `#[lifecycle(...)]`",
            )
        })?;
        let transitions = transitions.ok_or_else(|| {
            syn::Error::new(
                proc_macro2::Span::call_site(),
                "missing required `transitions(<From> -> <To>, ...)` in `#[lifecycle(...)]`",
            )
        })?;

        Ok(Self {
            initial,
            terminals,
            transitions,
        })
    }
}

/// Convert a `PascalCase` variant ident (raw-ident-aware) into `snake_case`.
///
/// Raw identifiers (`r#type`) have their `r#` prefix stripped before casing so
/// the derived method/module name is a plain identifier. A digit following a
/// letter starts a new word boundary as well (`Step2` -> `step2`, `V2State` ->
/// `v2_state`).
fn snake_case(ident: &Ident) -> String {
    let name = ident.to_string();
    let name = name.strip_prefix("r#").unwrap_or(&name);
    let mut out = String::with_capacity(name.len() + 4);
    let mut prev_lower_or_digit = false;
    for ch in name.chars() {
        if ch.is_uppercase() {
            if prev_lower_or_digit {
                out.push('_');
            }
            for lower in ch.to_lowercase() {
                out.push(lower);
            }
            prev_lower_or_digit = false;
        } else {
            out.push(ch);
            prev_lower_or_digit = ch.is_ascii_lowercase() || ch.is_ascii_digit();
        }
    }
    out
}

/// Core implementation invoked by the thin `#[proc_macro_attribute]` wrapper.
pub fn lifecycle_macro(attr: TokenStream, item: TokenStream) -> TokenStream {
    let item_enum: ItemEnum = match syn::parse2(item) {
        Ok(e) => e,
        Err(_) => {
            return syn::Error::new(
                proc_macro2::Span::call_site(),
                "#[lifecycle] may only be applied to an enum",
            )
            .to_compile_error();
        }
    };

    let args: LifecycleArgs = match syn::parse2(attr) {
        Ok(a) => a,
        Err(err) => return err.to_compile_error(),
    };

    match expand(&item_enum, &args) {
        Ok(generated) => quote! {
            #item_enum
            #generated
        },
        Err(err) => {
            // Still emit the original enum so downstream references to it don't
            // cascade into a flood of "cannot find type" errors.
            let compile_err = err.to_compile_error();
            quote! {
                #item_enum
                #compile_err
            }
        }
    }
}

fn expand(item_enum: &ItemEnum, args: &LifecycleArgs) -> syn::Result<TokenStream> {
    let enum_ident = &item_enum.ident;

    // Collect the declared variant idents (as strings) for validation.
    let variants: Vec<&Ident> = item_enum.variants.iter().map(|v| &v.ident).collect();
    let is_variant = |ident: &Ident| variants.contains(&ident);

    // Validate `initial`.
    if !is_variant(&args.initial) {
        return Err(syn::Error::new_spanned(
            &args.initial,
            format!(
                "`initial` state `{}` is not a variant of enum `{}`",
                args.initial, enum_ident
            ),
        ));
    }

    // Validate `terminal`s.
    for t in &args.terminals {
        if !is_variant(t) {
            return Err(syn::Error::new_spanned(
                t,
                format!("`terminal` state `{t}` is not a variant of enum `{enum_ident}`"),
            ));
        }
    }

    // Validate transition endpoints and reject duplicate edges.
    let mut seen_edges: Vec<(String, String)> = Vec::new();
    for tr in &args.transitions {
        if !is_variant(&tr.from) {
            return Err(syn::Error::new_spanned(
                &tr.from,
                format!(
                    "transition source `{}` is not a variant of enum `{}`",
                    tr.from, enum_ident
                ),
            ));
        }
        if !is_variant(&tr.to) {
            return Err(syn::Error::new_spanned(
                &tr.to,
                format!(
                    "transition target `{}` is not a variant of enum `{}`",
                    tr.to, enum_ident
                ),
            ));
        }
        // Reject transitions *out of* a declared terminal state: a terminal
        // state must have no outgoing edges, otherwise it is not actually
        // terminal (an unsound "movable terminal").
        if args.terminals.contains(&tr.from) {
            return Err(syn::Error::new_spanned(
                &tr.from,
                format!(
                    "terminal state `{}` cannot have an outgoing transition to `{}`",
                    tr.from, tr.to
                ),
            ));
        }
        let key = (tr.from.to_string(), tr.to.to_string());
        if seen_edges.contains(&key) {
            return Err(syn::Error::new_spanned(
                &tr.to,
                format!("duplicate transition `{} -> {}`", tr.from, tr.to),
            ));
        }
        seen_edges.push(key);
    }

    // Endpoints are all real variants by here, so the graph checks can trust
    // every name they walk.
    check_graph_soundness(item_enum, args, &variants)?;

    let metadata = build_metadata(item_enum, args, &variants);
    let module = build_module(item_enum, args);

    Ok(quote! {
        #metadata
        #module
    })
}

/// Prove the declared graph structurally sound, at compile time (issue #1675).
///
/// Two properties the typestate itself cannot see, because each generated
/// transition method only knows its own edge:
///
/// - **reachability** — every variant is reachable from `initial`. An
///   unreachable variant is a state no machine can ever enter.
/// - **liveness** — every reachable non-terminal variant reaches some terminal.
///   A state that reaches none is a dead-end: a machine that enters it is stuck.
///
/// Every violation is reported, one diagnostic per offending variant, spanned at
/// the variant so `cargo` underlines it. An unreachable variant is reported only
/// as unreachable, never also as a dead-end: reachability is the root cause.
///
/// `autumn lifecycle check` runs the same two proofs over source. Keep the two
/// in step.
fn check_graph_soundness(
    item_enum: &ItemEnum,
    args: &LifecycleArgs,
    variants: &[&Ident],
) -> syn::Result<()> {
    let initial = args.initial.to_string();
    let terminals: BTreeSet<String> = args.terminals.iter().map(ToString::to_string).collect();
    let edges: Vec<(String, String)> = args
        .transitions
        .iter()
        .map(|tr| (tr.from.to_string(), tr.to.to_string()))
        .collect();

    let mut forward: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    let mut reverse: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for (from, to) in &edges {
        forward.entry(from).or_default().push(to);
        reverse.entry(to).or_default().push(from);
    }

    let reachable = walk(std::iter::once(initial.as_str()), &forward);
    // Reverse-walk from the terminals: the states that reach one.
    let live = walk(terminals.iter().map(String::as_str), &reverse);

    let mut error: Option<syn::Error> = None;
    let mut push = |err: syn::Error| match &mut error {
        Some(acc) => acc.combine(err),
        none => *none = Some(err),
    };

    // Declaration order, so the diagnostics read top-to-bottom with the enum.
    for variant in variants {
        let name = variant.to_string();
        if !reachable.contains(name.as_str()) {
            push(syn::Error::new_spanned(
                variant,
                format!(
                    "state `{name}` is unreachable from initial state `{initial}` of lifecycle \
                     `{}` — add a transition into it, or remove the variant",
                    item_enum.ident
                ),
            ));
        // The terminal test is redundant — terminals seed `live` — but it states
        // the rule a reader needs: a terminal is never a dead-end.
        } else if !terminals.contains(&name) && !live.contains(name.as_str()) {
            push(syn::Error::new_spanned(
                variant,
                format!(
                    "state `{name}` is a non-terminal dead-end of lifecycle `{}`: no declared \
                     transition path reaches a terminal state — add an outgoing transition, or \
                     declare it terminal",
                    item_enum.ident
                ),
            ));
        }
    }

    error.map_or(Ok(()), Err)
}

/// Breadth-first set of nodes reachable from any of `starts` over `adj`.
fn walk<'a>(
    starts: impl Iterator<Item = &'a str>,
    adj: &BTreeMap<&'a str, Vec<&'a str>>,
) -> BTreeSet<&'a str> {
    let mut seen: BTreeSet<&str> = BTreeSet::new();
    let mut queue: VecDeque<&str> = VecDeque::new();
    for start in starts {
        if seen.insert(start) {
            queue.push_back(start);
        }
    }
    while let Some(node) = queue.pop_front() {
        for &next in adj.get(node).into_iter().flatten() {
            if seen.insert(next) {
                queue.push_back(next);
            }
        }
    }
    seen
}

/// Build the metadata `impl` block on the enum: the four consts plus
/// `can_transition_to`.
fn build_metadata(item_enum: &ItemEnum, args: &LifecycleArgs, variants: &[&Ident]) -> TokenStream {
    let enum_ident = &item_enum.ident;
    let initial = &args.initial;

    let terminal_paths = args.terminals.iter().map(|t| quote!(#enum_ident::#t));
    let state_paths = variants.iter().map(|v| quote!(#enum_ident::#v));
    let transition_pairs = args
        .transitions
        .iter()
        .map(|tr| {
            let from = &tr.from;
            let to = &tr.to;
            quote!((#enum_ident::#from, #enum_ident::#to))
        })
        .collect::<Vec<_>>();

    // String-keyed transition table for `#[state_machine(lifecycle = ...)]`
    // derivation (issue #1911). Each edge is `(from_name, to_name, None)` — the
    // variant names as strings (matching the model's `String` column value),
    // with an always-`None` guard slot since lifecycle transitions are
    // unguarded. Shape mirrors the field-level inline table exactly.
    let transition_name_triples = args.transitions.iter().map(|tr| {
        let from = variant_name_str(&tr.from);
        let to = variant_name_str(&tr.to);
        quote!((#from, #to, ::core::option::Option::None))
    });

    let match_arms = args.transitions.iter().map(|tr| {
        let from = &tr.from;
        let to = &tr.to;
        quote!((#enum_ident::#from, #enum_ident::#to) => true)
    });

    quote! {
        impl #enum_ident {
            /// The declared initial state of this lifecycle.
            pub const LIFECYCLE_INITIAL: #enum_ident = #enum_ident::#initial;
            /// The declared terminal states of this lifecycle.
            pub const LIFECYCLE_TERMINALS: &'static [#enum_ident] = &[#(#terminal_paths),*];
            /// All states of this lifecycle, in declaration order.
            pub const LIFECYCLE_STATES: &'static [#enum_ident] = &[#(#state_paths),*];
            /// All declared `(from, to)` transition edges of this lifecycle.
            pub const LIFECYCLE_TRANSITIONS: &'static [(#enum_ident, #enum_ident)] = &[
                #(#transition_pairs),*
            ];

            /// Runtime check: is `to` a declared transition from `self`?
            pub fn can_transition_to(&self, to: &#enum_ident) -> bool {
                match (self, to) {
                    #(#match_arms,)*
                    _ => false,
                }
            }
        }

        impl ::autumn_web::Lifecycle for #enum_ident {
            const STATE_MACHINE_TRANSITIONS: &'static [(
                &'static str,
                &'static str,
                ::core::option::Option<&'static str>,
            )] = &[
                #(#transition_name_triples),*
            ];
        }
    }
}

/// Render a variant ident as the string used in the derived state-machine
/// table (raw-identifier `r#` prefix stripped), matching the typestate
/// module's `State::NAME`.
fn variant_name_str(ident: &Ident) -> String {
    let name = ident.to_string();
    name.strip_prefix("r#").unwrap_or(&name).to_string()
}

/// Build the typestate transition module named after the enum in `snake_case`.
fn build_module(item_enum: &ItemEnum, args: &LifecycleArgs) -> TokenStream {
    let enum_ident = &item_enum.ident;
    let mod_ident = format_ident!("{}", snake_case(enum_ident));
    let initial = &args.initial;

    let variants: Vec<&Ident> = item_enum.variants.iter().map(|v| &v.ident).collect();

    // One zero-size marker struct per state.
    let marker_structs = variants.iter().map(|v| {
        quote! {
            #[allow(non_snake_case)]
            pub struct #v;
        }
    });

    // Sealed + State impls for each marker.
    let state_impls = variants.iter().map(|v| {
        let name = v.to_string();
        let name = name.strip_prefix("r#").unwrap_or(&name).to_string();
        quote! {
            impl sealed::Sealed for #v {}
            impl State for #v {
                const NAME: &'static str = #name;
                const VALUE: super::#enum_ident = super::#enum_ident::#v;
            }
        }
    });

    // `start()` only on the initial state.
    let start_impl = quote! {
        impl Machine<#initial> {
            /// Begin the lifecycle at its declared initial state.
            pub fn start() -> Machine<#initial> {
                Machine { _state: ::core::marker::PhantomData }
            }
        }
    };

    // One consuming `to_<target>` method per declared edge, grouped by source
    // state so each source gets a single `impl Machine<Source>` block.
    let mut sources: Vec<&Ident> = Vec::new();
    for tr in &args.transitions {
        if !sources.contains(&&tr.from) {
            sources.push(&tr.from);
        }
    }
    let edge_impls = sources.iter().map(|source| {
        let methods = args
            .transitions
            .iter()
            .filter(|tr| &tr.from == *source)
            .map(|tr| {
                let target = &tr.to;
                let method = format_ident!("to_{}", snake_case(target));
                quote! {
                    /// Consume this machine and transition to the declared target state.
                    pub fn #method(self) -> Machine<#target> {
                        Machine { _state: ::core::marker::PhantomData }
                    }
                }
            });
        quote! {
            impl Machine<#source> {
                #(#methods)*
            }
        }
    });

    quote! {
        /// Typestate transition module for the lifecycle: firing an undeclared
        /// transition is a compile error because the method does not exist.
        pub mod #mod_ident {
            use core::marker::PhantomData;

            #(#marker_structs)*

            mod sealed {
                pub trait Sealed {}
            }

            /// A lifecycle state marker.
            pub trait State: sealed::Sealed {
                /// The variant name as a string.
                const NAME: &'static str;
                /// The corresponding enum value.
                const VALUE: super::#enum_ident;
            }

            #(#state_impls)*

            /// A lifecycle machine parameterized by its current state marker.
            pub struct Machine<S: State> {
                _state: PhantomData<S>,
            }

            #start_impl

            impl<S: State> Machine<S> {
                /// The current state as the runtime enum value.
                pub fn current(&self) -> super::#enum_ident {
                    S::VALUE
                }
            }

            #(#edge_impls)*
        }
    }
}

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

    fn expand_ok(attr: TokenStream, item: TokenStream) -> String {
        let item_enum: ItemEnum = syn::parse2(item).expect("enum should parse");
        let args: LifecycleArgs = syn::parse2(attr).expect("args should parse");
        expand(&item_enum, &args)
            .expect("expansion should succeed")
            .to_string()
    }

    fn sample_enum() -> TokenStream {
        quote! {
            pub enum ArticleState {
                Draft,
                Published,
                Archived,
            }
        }
    }

    fn sample_attr() -> TokenStream {
        quote! {
            initial = Draft,
            terminal(Archived),
            transitions(
                Draft -> Published,
                Published -> Archived,
                Published -> Draft,
            )
        }
    }

    #[test]
    fn emits_metadata_consts_with_expected_names_and_entries() {
        let out = expand_ok(sample_attr(), sample_enum());
        assert!(out.contains("LIFECYCLE_INITIAL"), "{out}");
        assert!(out.contains("LIFECYCLE_TERMINALS"), "{out}");
        assert!(out.contains("LIFECYCLE_STATES"), "{out}");
        assert!(out.contains("LIFECYCLE_TRANSITIONS"), "{out}");
        // Initial value.
        assert!(
            out.contains("LIFECYCLE_INITIAL : ArticleState = ArticleState :: Draft"),
            "{out}"
        );
        // Terminal list references the enum variant.
        assert!(out.contains("& [ArticleState :: Archived]"), "{out}");
        // States in declaration order.
        assert!(
            out.contains(
                "& [ArticleState :: Draft , ArticleState :: Published , ArticleState :: Archived]"
            ),
            "{out}"
        );
    }

    #[test]
    fn emits_lifecycle_trait_impl_with_string_transition_table() {
        let out = expand_ok(sample_attr(), sample_enum());
        // Implements the marker trait used by `#[state_machine(lifecycle = ...)]`.
        assert!(
            out.contains("impl :: autumn_web :: Lifecycle for ArticleState"),
            "{out}"
        );
        assert!(out.contains("const STATE_MACHINE_TRANSITIONS"), "{out}");
        // Edges rendered as (from_name, to_name, None) string triples.
        assert!(
            out.contains("(\"Draft\" , \"Published\" , :: core :: option :: Option :: None)"),
            "{out}"
        );
        assert!(
            out.contains("(\"Published\" , \"Archived\" , :: core :: option :: Option :: None)"),
            "{out}"
        );
    }

    #[test]
    fn lifecycle_transition_table_strips_raw_identifier_prefix() {
        let item = quote! {
            pub enum KindState {
                Draft,
                r#type,
            }
        };
        let attr = quote! {
            initial = Draft,
            terminal(r#type),
            transitions(Draft -> r#type)
        };
        let out = expand_ok(attr, item);
        // The stored string uses the bare `type`, not `r#type`.
        assert!(
            out.contains("(\"Draft\" , \"type\" , :: core :: option :: Option :: None)"),
            "{out}"
        );
    }

    #[test]
    fn can_transition_to_matches_declared_edges() {
        let out = expand_ok(sample_attr(), sample_enum());
        assert!(out.contains("fn can_transition_to"), "{out}");
        // Declared edge arm present.
        assert!(
            out.contains("(ArticleState :: Draft , ArticleState :: Published) => true"),
            "{out}"
        );
        // Fallthrough for undeclared edges.
        assert!(out.contains("_ => false"), "{out}");
    }

    #[test]
    fn transition_method_exists_on_source_state() {
        let out = expand_ok(sample_attr(), sample_enum());
        // Module named after enum in snake_case.
        assert!(out.contains("pub mod article_state"), "{out}");
        // `to_published` on the Draft source.
        assert!(out.contains("fn to_published"), "{out}");
        assert!(out.contains("fn to_archived"), "{out}");
        assert!(out.contains("fn to_draft"), "{out}");
    }

    #[test]
    fn terminal_state_has_no_outgoing_methods() {
        let out = expand_ok(sample_attr(), sample_enum());
        // No method transitions *into* an impl on Archived: Archived is a
        // source of no edges, so no `impl Machine < Archived >` block exists.
        assert!(
            !out.contains("impl Machine < Archived >"),
            "Archived is terminal and must have no outgoing method impl:\n{out}"
        );
    }

    #[test]
    fn start_only_on_initial_state() {
        let out = expand_ok(sample_attr(), sample_enum());
        // `start` lives inside `impl Machine < Draft >`.
        assert!(out.contains("impl Machine < Draft >"), "{out}");
        assert!(out.contains("fn start"), "{out}");
        // Ensure there is exactly one `fn start`.
        assert_eq!(out.matches("fn start").count(), 1, "{out}");
    }

    #[test]
    fn undeclared_initial_is_error() {
        let item_enum: ItemEnum = syn::parse2(sample_enum()).unwrap();
        let args: LifecycleArgs = syn::parse2(quote! {
            initial = Nonexistent,
            terminal(Archived),
            transitions(Draft -> Published)
        })
        .unwrap();
        let err = expand(&item_enum, &args).unwrap_err();
        assert!(
            err.to_string().contains("Nonexistent"),
            "error should name the offending ident: {err}"
        );
    }

    #[test]
    fn undeclared_terminal_is_error() {
        let item_enum: ItemEnum = syn::parse2(sample_enum()).unwrap();
        let args: LifecycleArgs = syn::parse2(quote! {
            initial = Draft,
            terminal(Ghost),
            transitions(Draft -> Published)
        })
        .unwrap();
        let err = expand(&item_enum, &args).unwrap_err();
        assert!(err.to_string().contains("Ghost"), "{err}");
    }

    #[test]
    fn undeclared_transition_endpoint_is_error() {
        let item_enum: ItemEnum = syn::parse2(sample_enum()).unwrap();
        let args: LifecycleArgs = syn::parse2(quote! {
            initial = Draft,
            terminal(Archived),
            transitions(Draft -> Nowhere)
        })
        .unwrap();
        let err = expand(&item_enum, &args).unwrap_err();
        assert!(err.to_string().contains("Nowhere"), "{err}");
    }

    #[test]
    fn terminal_source_transition_is_error() {
        let item_enum: ItemEnum = syn::parse2(sample_enum()).unwrap();
        let args: LifecycleArgs = syn::parse2(quote! {
            initial = Draft,
            terminal(Archived),
            transitions(
                Draft -> Archived,
                Archived -> Draft,
            )
        })
        .unwrap();
        let err = expand(&item_enum, &args).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("terminal state `Archived`"),
            "error should name the offending terminal: {msg}"
        );
        assert!(
            msg.contains("Draft"),
            "error should name the transition target: {msg}"
        );
    }

    #[test]
    fn duplicate_transition_edge_is_error() {
        let item_enum: ItemEnum = syn::parse2(sample_enum()).unwrap();
        let args: LifecycleArgs = syn::parse2(quote! {
            initial = Draft,
            terminal(Archived),
            transitions(
                Draft -> Published,
                Draft -> Published,
            )
        })
        .unwrap();
        let err = expand(&item_enum, &args).unwrap_err();
        assert!(err.to_string().contains("duplicate"), "{err}");
    }

    // ── Graph soundness (issue #1675, AC3) ───────────────────────────────
    //
    // The macro proves the *shape* of the declared graph, not just its
    // endpoints: every variant is reachable from `initial`, and every reachable
    // non-terminal reaches some terminal. `autumn lifecycle check` runs the
    // same two proofs over source; these keep the two in step.

    fn expand_err(attr: TokenStream, item: TokenStream) -> Vec<String> {
        let item_enum: ItemEnum = syn::parse2(item).expect("enum should parse");
        let args: LifecycleArgs = syn::parse2(attr).expect("args should parse");
        let err = expand(&item_enum, &args).expect_err("expansion should fail");
        err.into_iter().map(|e| e.to_string()).collect()
    }

    #[test]
    fn unreachable_state_is_a_compile_error_naming_the_state() {
        let errs = expand_err(
            quote! {
                initial = Draft,
                terminal(Archived),
                transitions(Draft -> Archived)
            },
            quote! {
                pub enum ArticleState { Draft, Published, Archived }
            },
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
        assert!(errs[0].contains("`Published`"), "{errs:?}");
        assert!(errs[0].contains("unreachable"), "{errs:?}");
        assert!(errs[0].contains("`Draft`"), "{errs:?}");
    }

    #[test]
    fn every_unreachable_state_is_reported_in_declaration_order() {
        let errs = expand_err(
            quote! {
                initial = Draft,
                terminal(Archived),
                transitions(Draft -> Archived)
            },
            quote! {
                pub enum ArticleState { Draft, Review, Published, Archived }
            },
        );
        assert_eq!(errs.len(), 2, "{errs:?}");
        assert!(errs[0].contains("`Review`"), "{errs:?}");
        assert!(errs[1].contains("`Published`"), "{errs:?}");
    }

    #[test]
    fn non_terminal_dead_end_is_a_compile_error_naming_the_state() {
        let errs = expand_err(
            quote! {
                initial = Draft,
                terminal(Archived),
                transitions(
                    Draft -> Published,
                    Draft -> Archived,
                )
            },
            quote! {
                pub enum ArticleState { Draft, Published, Archived }
            },
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
        assert!(errs[0].contains("`Published`"), "{errs:?}");
        assert!(errs[0].contains("dead-end"), "{errs:?}");
    }

    #[test]
    fn a_cycle_that_never_reaches_a_terminal_is_a_dead_end() {
        // Review <-> Revise spins forever: neither can reach `Archived`.
        let errs = expand_err(
            quote! {
                initial = Draft,
                terminal(Archived),
                transitions(
                    Draft -> Review,
                    Review -> Revise,
                    Revise -> Review,
                    Draft -> Archived,
                )
            },
            quote! {
                pub enum ArticleState { Draft, Review, Revise, Archived }
            },
        );
        assert_eq!(errs.len(), 2, "{errs:?}");
        assert!(errs[0].contains("`Review`"), "{errs:?}");
        assert!(errs[1].contains("`Revise`"), "{errs:?}");
    }

    #[test]
    fn an_unreachable_state_is_not_also_reported_as_a_dead_end() {
        // `Stuck` is unreachable *and* exit-less. Only the root cause is
        // reported, so the fix list stays one line per broken state.
        let errs = expand_err(
            quote! {
                initial = Draft,
                terminal(Archived),
                transitions(
                    Draft -> Archived,
                    Orphan -> Stuck,
                )
            },
            quote! {
                pub enum ArticleState { Draft, Orphan, Stuck, Archived }
            },
        );
        assert_eq!(errs.len(), 2, "{errs:?}");
        assert!(errs.iter().all(|e| e.contains("unreachable")), "{errs:?}");
    }

    #[test]
    fn unreachable_and_dead_end_are_reported_together_in_declaration_order() {
        // `Draft` is reachable but leads nowhere; `Review` and `Archived` are
        // orphans. Both kinds accumulate into one error list.
        let errs = expand_err(
            quote! {
                initial = Draft,
                terminal(Archived),
                transitions(Review -> Archived)
            },
            quote! {
                pub enum ArticleState { Draft, Review, Archived }
            },
        );
        assert_eq!(errs.len(), 3, "{errs:?}");
        assert!(
            errs[0].contains("`Draft`") && errs[0].contains("dead-end"),
            "{errs:?}"
        );
        assert!(
            errs[1].contains("`Review`") && errs[1].contains("unreachable"),
            "{errs:?}"
        );
        assert!(
            errs[2].contains("`Archived`") && errs[2].contains("unreachable"),
            "{errs:?}"
        );
    }

    #[test]
    fn a_self_loop_is_not_a_way_out() {
        // `Review -> Review` gives `Review` an outgoing edge, but no path to a
        // terminal.
        let errs = expand_err(
            quote! {
                initial = Draft,
                terminal(Archived),
                transitions(
                    Draft -> Review,
                    Review -> Review,
                    Draft -> Archived,
                )
            },
            quote! {
                pub enum ArticleState { Draft, Review, Archived }
            },
        );
        assert_eq!(errs.len(), 1, "{errs:?}");
        assert!(
            errs[0].contains("`Review`") && errs[0].contains("dead-end"),
            "{errs:?}"
        );
    }

    #[test]
    fn a_cycle_back_to_an_earlier_state_stays_sound() {
        // `Published -> Draft` is a legal loop: both still reach `Archived`.
        let out = expand_ok(sample_attr(), sample_enum());
        assert!(out.contains("pub mod article_state"), "{out}");
    }

    #[test]
    fn a_branch_to_a_second_terminal_stays_sound() {
        let out = expand_ok(
            quote! {
                initial = Draft,
                terminal(Archived, Rejected),
                transitions(
                    Draft -> Published,
                    Draft -> Rejected,
                    Published -> Archived,
                )
            },
            quote! {
                pub enum ArticleState { Draft, Published, Archived, Rejected }
            },
        );
        assert!(out.contains("pub mod article_state"), "{out}");
    }

    fn parse_args_err(attr: TokenStream) -> String {
        let res: syn::Result<LifecycleArgs> = syn::parse2(attr);
        match res {
            Ok(_) => panic!("expected a parse error"),
            Err(err) => err.to_string(),
        }
    }

    #[test]
    fn missing_initial_is_error() {
        let err = parse_args_err(quote! {
            terminal(Archived),
            transitions(Draft -> Published)
        });
        assert!(err.contains("initial"), "{err}");
    }

    #[test]
    fn missing_terminal_is_error() {
        let err = parse_args_err(quote! {
            initial = Draft,
            transitions(Draft -> Published)
        });
        assert!(err.contains("terminal"), "{err}");
    }

    #[test]
    fn missing_transitions_is_error() {
        let err = parse_args_err(quote! {
            initial = Draft,
            terminal(Archived)
        });
        assert!(err.contains("transitions"), "{err}");
    }

    #[test]
    fn snake_case_naming_for_multi_word_variants() {
        let item = quote! {
            pub enum ReviewState {
                Draft,
                InReview,
                Approved,
            }
        };
        let attr = quote! {
            initial = Draft,
            terminal(Approved),
            transitions(
                Draft -> InReview,
                InReview -> Approved,
            )
        };
        let out = expand_ok(attr, item);
        // Module: ReviewState -> review_state.
        assert!(out.contains("pub mod review_state"), "{out}");
        // Method: InReview -> to_in_review.
        assert!(out.contains("fn to_in_review"), "{out}");
    }

    #[test]
    fn snake_case_helper_cases() {
        assert_eq!(snake_case(&format_ident!("Draft")), "draft");
        assert_eq!(snake_case(&format_ident!("InReview")), "in_review");
        assert_eq!(snake_case(&format_ident!("ArticleState")), "article_state");
        // A word boundary is only inserted before an uppercase that follows a
        // lowercase or digit, so runs of capitals stay together.
        assert_eq!(snake_case(&format_ident!("HTTPState")), "httpstate");
        assert_eq!(snake_case(&format_ident!("Step2Review")), "step2_review");
    }
}