Skip to main content

pg_proto_fsm/
lib.rs

1//! Protocol grammar to typestate, runtime FSM, and railroad-diagram generation.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use proc_macro::TokenStream;
6use quote::{format_ident, quote};
7use railroad::{
8    Choice, Diagram, Empty, End, Node, NonTerminal, Repeat, Sequence, Start, Stylesheet, Terminal,
9    svg::{self, HDir},
10};
11use syn::{
12    Ident, Pat, Path, Result, Token, Type, Visibility, braced, bracketed,
13    parse::{Parse, ParseStream},
14    parse_macro_input,
15    visit_mut::{self, VisitMut},
16};
17
18/// Custom keywords accepted by the protocol grammar DSL.
19mod keyword {
20    syn::custom_keyword!(initial);
21    syn::custom_keyword!(messages);
22    syn::custom_keyword!(associations);
23    syn::custom_keyword!(interface);
24    syn::custom_keyword!(seal);
25    syn::custom_keyword!(inbound);
26    syn::custom_keyword!(outbound);
27    syn::custom_keyword!(direction);
28    syn::custom_keyword!(role);
29    syn::custom_keyword!(wire);
30    syn::custom_keyword!(message);
31    syn::custom_keyword!(associate);
32    syn::custom_keyword!(none);
33}
34
35struct Protocol {
36    visibility: Visibility,
37    module: Ident,
38    initial: Ident,
39    messages: Option<MessageTypes>,
40    associations: Option<Associations>,
41    states: Vec<State>,
42}
43
44struct Associations {
45    interface: Path,
46    seal: Path,
47    inbound: AssociationLane,
48    outbound: AssociationLane,
49}
50
51struct AssociationLane {
52    direction: Type,
53    role: Type,
54    wire: Type,
55    message: Type,
56}
57
58struct StateAssociations {
59    inbound: Vec<Type>,
60    outbound: Vec<Type>,
61}
62
63struct MessageTypes {
64    internal: Type,
65    external: Type,
66}
67
68struct State {
69    name: Ident,
70    choice: ChoiceKind,
71    transitions: Vec<Transition>,
72    associations: Option<StateAssociations>,
73}
74
75#[derive(Clone, Copy)]
76enum ChoiceKind {
77    Internal,
78    External,
79    Mixed,
80}
81
82struct Transition {
83    choice: Option<ChoiceKind>,
84    event: Ident,
85    method: Ident,
86    payload: Option<Type>,
87    target: Ident,
88    cleanliness: Option<Ident>,
89    projection: Option<Pat>,
90}
91
92impl Parse for Protocol {
93    fn parse(input: ParseStream<'_>) -> Result<Self> {
94        let visibility = input.parse()?;
95        input.parse::<Token![mod]>()?;
96        let module = input.parse()?;
97        let content;
98        braced!(content in input);
99        content.parse::<keyword::initial>()?;
100        let initial = content.parse()?;
101        content.parse::<Token![;]>()?;
102        let messages = if content.peek(keyword::messages) {
103            content.parse::<keyword::messages>()?;
104            let message_content;
105            braced!(message_content in content);
106            let internal_name: Ident = message_content.parse()?;
107            if internal_name != "internal" {
108                return Err(syn::Error::new(internal_name.span(), "expected `internal`"));
109            }
110            message_content.parse::<Token![:]>()?;
111            let internal = message_content.parse()?;
112            message_content.parse::<Token![,]>()?;
113            let external_name: Ident = message_content.parse()?;
114            if external_name != "external" {
115                return Err(syn::Error::new(external_name.span(), "expected `external`"));
116            }
117            message_content.parse::<Token![:]>()?;
118            let external = message_content.parse()?;
119            if message_content.peek(Token![,]) {
120                message_content.parse::<Token![,]>()?;
121            }
122            Some(MessageTypes { internal, external })
123        } else {
124            None
125        };
126        let associations = if content.peek(keyword::associations) {
127            Some(content.parse()?)
128        } else {
129            None
130        };
131        let mut states = Vec::new();
132        while !content.is_empty() {
133            states.push(content.parse()?);
134        }
135        Ok(Self {
136            visibility,
137            module,
138            initial,
139            messages,
140            associations,
141            states,
142        })
143    }
144}
145
146impl Parse for Associations {
147    fn parse(input: ParseStream<'_>) -> Result<Self> {
148        input.parse::<keyword::associations>()?;
149        let content;
150        braced!(content in input);
151        content.parse::<keyword::interface>()?;
152        content.parse::<Token![:]>()?;
153        let interface = content.parse()?;
154        content.parse::<Token![;]>()?;
155        content.parse::<keyword::seal>()?;
156        content.parse::<Token![:]>()?;
157        let seal = content.parse()?;
158        content.parse::<Token![;]>()?;
159        content.parse::<keyword::inbound>()?;
160        let inbound = parse_lane(&content)?;
161        content.parse::<keyword::outbound>()?;
162        let outbound = parse_lane(&content)?;
163        if !content.is_empty() {
164            return Err(content.error("unexpected association configuration"));
165        }
166        Ok(Self {
167            interface,
168            seal,
169            inbound,
170            outbound,
171        })
172    }
173}
174
175fn parse_lane(input: ParseStream<'_>) -> Result<AssociationLane> {
176    let content;
177    braced!(content in input);
178    content.parse::<keyword::direction>()?;
179    content.parse::<Token![:]>()?;
180    let direction = content.parse()?;
181    content.parse::<Token![;]>()?;
182    content.parse::<keyword::role>()?;
183    content.parse::<Token![:]>()?;
184    let role = content.parse()?;
185    content.parse::<Token![;]>()?;
186    content.parse::<keyword::wire>()?;
187    content.parse::<Token![:]>()?;
188    let wire = content.parse()?;
189    content.parse::<Token![;]>()?;
190    content.parse::<keyword::message>()?;
191    content.parse::<Token![:]>()?;
192    let message = content.parse()?;
193    content.parse::<Token![;]>()?;
194    if !content.is_empty() {
195        return Err(content.error("unexpected association lane configuration"));
196    }
197    Ok(AssociationLane {
198        direction,
199        role,
200        wire,
201        message,
202    })
203}
204
205impl Parse for State {
206    fn parse(input: ParseStream<'_>) -> Result<Self> {
207        let name = input.parse()?;
208        let choice_name: Ident = input.parse()?;
209        let choice = match choice_name.to_string().as_str() {
210            "internal" => ChoiceKind::Internal,
211            "external" => ChoiceKind::External,
212            "mixed" => ChoiceKind::Mixed,
213            _ => {
214                return Err(syn::Error::new(
215                    choice_name.span(),
216                    "expected `internal`, `external`, or `mixed` choice",
217                ));
218            }
219        };
220        let content;
221        braced!(content in input);
222        let associations = if content.peek(keyword::associate) {
223            Some(content.parse()?)
224        } else {
225            None
226        };
227        let transitions = content
228            .parse_terminated(Transition::parse, Token![,])?
229            .into_iter()
230            .collect();
231        Ok(Self {
232            name,
233            choice,
234            transitions,
235            associations,
236        })
237    }
238}
239
240impl Parse for StateAssociations {
241    fn parse(input: ParseStream<'_>) -> Result<Self> {
242        input.parse::<keyword::associate>()?;
243        let content;
244        braced!(content in input);
245        content.parse::<keyword::inbound>()?;
246        content.parse::<Token![:]>()?;
247        let inbound = parse_association_types(&content)?;
248        content.parse::<Token![;]>()?;
249        content.parse::<keyword::outbound>()?;
250        content.parse::<Token![:]>()?;
251        let outbound = parse_association_types(&content)?;
252        content.parse::<Token![;]>()?;
253        if !content.is_empty() {
254            return Err(content.error("unexpected state association"));
255        }
256        Ok(Self { inbound, outbound })
257    }
258}
259
260fn parse_association_types(input: ParseStream<'_>) -> Result<Vec<Type>> {
261    if input.peek(keyword::none) {
262        input.parse::<keyword::none>()?;
263        return Ok(Vec::new());
264    }
265    if input.peek(syn::token::Bracket) {
266        let content;
267        bracketed!(content in input);
268        let types = content.parse_terminated(Type::parse, Token![,])?;
269        if types.is_empty() {
270            return Err(content.error("association list cannot be empty; use `none`"));
271        }
272        return Ok(types.into_iter().collect());
273    }
274    Ok(vec![input.parse()?])
275}
276
277impl Parse for Transition {
278    fn parse(input: ParseStream<'_>) -> Result<Self> {
279        let first: Ident = input.parse()?;
280        let (choice, event) = match first.to_string().as_str() {
281            "internal" => (Some(ChoiceKind::Internal), input.parse()?),
282            "external" => (Some(ChoiceKind::External), input.parse()?),
283            _ => (None, first),
284        };
285        let method_content;
286        syn::parenthesized!(method_content in input);
287        let method = method_content.parse()?;
288        let payload = if method_content.peek(Token![:]) {
289            method_content.parse::<Token![:]>()?;
290            Some(method_content.parse()?)
291        } else {
292            None
293        };
294        if !method_content.is_empty() {
295            return Err(method_content.error("unexpected transition method tokens"));
296        }
297        input.parse::<Token![=>]>()?;
298        let target = input.parse()?;
299        let cleanliness = if input.peek(syn::token::Bracket) {
300            let content;
301            syn::bracketed!(content in input);
302            Some(content.parse()?)
303        } else {
304            None
305        };
306        let projection = if input.peek(Token![<=]) {
307            input.parse::<Token![<=]>()?;
308            Some(Pat::parse_multi(input)?)
309        } else {
310            None
311        };
312        Ok(Self {
313            choice,
314            event,
315            method,
316            payload,
317            target,
318            cleanliness,
319            projection,
320        })
321    }
322}
323
324/// Generates typestate witnesses, a runtime FSM, and a railroad SVG from one grammar.
325///
326/// The grammar uses `Event(method) => NextState` transitions grouped by source
327/// state. An optional `[Cleanliness]` replaces the orthogonal cleanliness index
328/// on transport-carrying generated sessions.
329#[proc_macro]
330pub fn protocol(input: TokenStream) -> TokenStream {
331    let protocol = parse_macro_input!(input as Protocol);
332    expand(protocol)
333        .unwrap_or_else(syn::Error::into_compile_error)
334        .into()
335}
336
337fn expand_associations(protocol: &Protocol) -> Result<Vec<proc_macro2::TokenStream>> {
338    let Some(associations) = &protocol.associations else {
339        return Ok(Vec::new());
340    };
341    let interface = &associations.interface;
342    let seal = &associations.seal;
343    protocol
344        .states
345        .iter()
346        .flat_map(|state| {
347            [
348                (
349                    &associations.inbound,
350                    state.associations.as_ref().map(|value| &value.inbound),
351                ),
352                (
353                    &associations.outbound,
354                    state.associations.as_ref().map(|value| &value.outbound),
355                ),
356            ]
357            .into_iter()
358            .map(move |(lane, connections)| {
359                let state_name = &state.name;
360                let direction = &lane.direction;
361                let role = &lane.role;
362                let wire = &lane.wire;
363                let message = instantiate_message_type(&lane.message, state_name)?;
364                let connections = connections.expect("validated state associations");
365                Ok(quote! {
366                    #(
367                        impl #seal<#direction, #role, #wire> for #connections {}
368
369                        impl #interface<#direction, #role, #wire> for #connections {
370                            type ProtocolPhase = #state_name;
371                            type Message = #message;
372                        }
373                    )*
374                })
375            })
376        })
377        .collect()
378}
379
380#[allow(clippy::too_many_lines)]
381fn expand(protocol: Protocol) -> Result<proc_macro2::TokenStream> {
382    validate(&protocol)?;
383    let association_impls = expand_associations(&protocol)?;
384    let Protocol {
385        visibility,
386        module,
387        initial,
388        messages,
389        associations: _,
390        states,
391    } = protocol;
392    let state_names = states.iter().map(|state| &state.name).collect::<Vec<_>>();
393    let events = states
394        .iter()
395        .flat_map(|state| state.transitions.iter())
396        .fold(BTreeMap::new(), |mut events, transition| {
397            events
398                .entry(transition.event.to_string())
399                .or_insert(&transition.event);
400            events
401        })
402        .into_values()
403        .collect::<Vec<_>>();
404    let cleanliness_names = states
405        .iter()
406        .flat_map(|state| state.transitions.iter())
407        .filter_map(|transition| transition.cleanliness.as_ref())
408        .fold(BTreeMap::new(), |mut names, cleanliness| {
409            names.entry(cleanliness.to_string()).or_insert(cleanliness);
410            names
411        })
412        .into_values();
413    let module_name = &module;
414    let transition_descriptors = states.iter().flat_map(|state| {
415        let source = &state.name;
416        state.transitions.iter().map(move |transition| {
417            let event = &transition.event;
418            let target = &transition.target;
419            let choice = match transition.choice.unwrap_or(state.choice) {
420                ChoiceKind::Internal => quote!(ChoiceKind::Internal),
421                ChoiceKind::External => quote!(ChoiceKind::External),
422                ChoiceKind::Mixed => unreachable!("validated mixed transition has a direction"),
423            };
424            quote!(RuntimeTransition {
425                id: concat!(stringify!(#module_name), ".", stringify!(#source), ".", stringify!(#event)),
426                source: RuntimeState::#source,
427                event: Event::#event,
428                target: RuntimeState::#target,
429                choice: #choice,
430            })
431        })
432    });
433    let choice_arms = states.iter().map(|state| {
434        let name = &state.name;
435        let choice = match state.choice {
436            ChoiceKind::Internal => quote!(ChoiceKind::Internal),
437            ChoiceKind::External => quote!(ChoiceKind::External),
438            ChoiceKind::Mixed => quote!(ChoiceKind::Mixed),
439        };
440        quote!(RuntimeState::#name => #choice)
441    });
442    let projection_functions = messages.as_ref().map(|messages| {
443        let internal_type = &messages.internal;
444        let external_type = &messages.external;
445        let internal_arms = states.iter().flat_map(|state| {
446            let source = &state.name;
447            state.transitions.iter().filter_map(move |transition| {
448                let choice = transition.choice.unwrap_or(state.choice);
449                (matches!(choice, ChoiceKind::Internal))
450                    .then_some(transition.projection.as_ref())
451                    .flatten()
452                    .map(|pattern| {
453                        let event = &transition.event;
454                        quote!((RuntimeState::#source, #pattern) => Some(Event::#event))
455                    })
456            })
457        });
458        let external_arms = states.iter().flat_map(|state| {
459            let source = &state.name;
460            state.transitions.iter().filter_map(move |transition| {
461                let choice = transition.choice.unwrap_or(state.choice);
462                (matches!(choice, ChoiceKind::External))
463                    .then_some(transition.projection.as_ref())
464                    .flatten()
465                    .map(|pattern| {
466                        let event = &transition.event;
467                        quote!((RuntimeState::#source, #pattern) => Some(Event::#event))
468                    })
469            })
470        });
471        quote! {
472            /// Projects a role-initiated wire message into its protocol event.
473            #[must_use]
474            pub fn project_internal(
475                state: RuntimeState,
476                message: &#internal_type,
477            ) -> Option<Event> {
478                match (state, message) {
479                    #(#internal_arms,)*
480                    _ => None,
481                }
482            }
483
484            /// Projects a peer-initiated wire message into its protocol event.
485            #[must_use]
486            pub fn project_external(
487                state: RuntimeState,
488                message: &#external_type,
489            ) -> Option<Event> {
490                match (state, message) {
491                    #(#external_arms,)*
492                    _ => None,
493                }
494            }
495        }
496    });
497    let phase_message_types = messages.as_ref().map_or_else(Vec::new, |messages| {
498        let internal_type = &messages.internal;
499        let external_type = &messages.external;
500
501        states.iter().map(|state| {
502            let state_name = &state.name;
503            let internal_name = format_ident!("{}InternalMessage", state_name);
504            let external_name = format_ident!("{}ExternalMessage", state_name);
505
506            let directional = |kind: ChoiceKind, wire_type: &Type, type_name: &Ident| {
507                let transitions = state
508                    .transitions
509                    .iter()
510                    .filter(|transition| {
511                        transition.projection.is_some()
512                            && matches!(
513                                (transition.choice.unwrap_or(state.choice), kind),
514                                (ChoiceKind::Internal, ChoiceKind::Internal)
515                                    | (ChoiceKind::External, ChoiceKind::External)
516                            )
517                    })
518                    .collect::<Vec<_>>();
519                let variants = transitions
520                    .iter()
521                    .map(|transition| &transition.event)
522                    .collect::<Vec<_>>();
523                let borrow_variants = variants.clone();
524                let wrapper_names = transitions
525                    .iter()
526                    .map(|transition| {
527                        format_ident!("{}{}{}TransitionMessage", state_name, transition.event, match kind {
528                            ChoiceKind::Internal => "Internal",
529                            ChoiceKind::External => "External",
530                            ChoiceKind::Mixed => unreachable!("a message direction cannot be mixed"),
531                        })
532                    })
533                    .collect::<Vec<_>>();
534                let wrapper_definitions = wrapper_names.iter().zip(transitions.iter()).map(|(wrapper, transition)| {
535                    let event = &transition.event;
536                    let wrapper_projector = match kind {
537                        ChoiceKind::Internal => quote!(project_internal),
538                        ChoiceKind::External => quote!(project_external),
539                        ChoiceKind::Mixed => unreachable!("a message direction cannot be mixed"),
540                    };
541                    quote! {
542                        #[doc = concat!("Validated wire message for one legal `", stringify!(#state_name), "` transition.")]
543                        pub struct #wrapper(#wire_type);
544
545                        impl #wrapper {
546                            /// Borrows the validated wire message.
547                            #[must_use]
548                            pub const fn as_wire(&self) -> &#wire_type {
549                                &self.0
550                            }
551
552                            /// Returns the validated wire message.
553                            #[must_use]
554                            pub fn into_wire(self) -> #wire_type {
555                                self.0
556                            }
557
558                            /// Mutates or replaces the wire value while preserving this transition variant.
559                            ///
560                            /// # Errors
561                            ///
562                            /// Returns the replacement when it no longer denotes this phase transition.
563                            pub fn try_map_wire(
564                                self,
565                                map: impl FnOnce(#wire_type) -> #wire_type,
566                            ) -> ::core::result::Result<Self, #wire_type> {
567                                let message = map(self.0);
568                                if #wrapper_projector(RuntimeState::#state_name, &message)
569                                    == Some(Event::#event)
570                                {
571                                    Ok(Self(message))
572                                } else {
573                                    Err(message)
574                                }
575                            }
576                        }
577                    }
578                });
579                let enum_wrappers = wrapper_names.clone();
580                let match_variants = transitions.iter().map(|transition| {
581                    let event = &transition.event;
582                    let wrapper = format_ident!("{}{}{}TransitionMessage", state_name, event, match kind {
583                        ChoiceKind::Internal => "Internal",
584                        ChoiceKind::External => "External",
585                        ChoiceKind::Mixed => unreachable!("a message direction cannot be mixed"),
586                    });
587                    quote!(Some(Event::#event) => Ok(Self::#event(#wrapper(message))))
588                });
589                let wire_variants = variants
590                    .iter()
591                    .map(|event| quote!(Self::#event(message) => message.into_wire()));
592                let event_variants = transitions.iter().map(|transition| {
593                    let event = &transition.event;
594                    quote!(Self::#event(_) => Event::#event)
595                });
596                let projector = match kind {
597                    ChoiceKind::Internal => quote!(project_internal),
598                    ChoiceKind::External => quote!(project_external),
599                    ChoiceKind::Mixed => unreachable!("a message direction cannot be mixed"),
600                };
601                let direction = match kind {
602                    ChoiceKind::Internal => "role-initiated",
603                    ChoiceKind::External => "peer-initiated",
604                    ChoiceKind::Mixed => unreachable!("a message direction cannot be mixed"),
605                };
606                let projection_name = format_ident!(
607                    "{}{}Projection",
608                    state_name,
609                    match kind {
610                        ChoiceKind::Internal => "Internal",
611                        ChoiceKind::External => "External",
612                        ChoiceKind::Mixed => unreachable!("a message direction cannot be mixed"),
613                    }
614                );
615                let projection_method = match kind {
616                    ChoiceKind::Internal => format_ident!("project_internal_message"),
617                    ChoiceKind::External => format_ident!("project_external_message"),
618                    ChoiceKind::Mixed => unreachable!("a message direction cannot be mixed"),
619                };
620                let projection_variants = transitions.iter().zip(wrapper_names.iter()).map(
621                    |(transition, wrapper)| {
622                        let event = &transition.event;
623                        let target = &transition.target;
624                        let cleanliness = transition.cleanliness.as_ref().map_or_else(
625                            || quote!(SourceCleanliness),
626                            |cleanliness| quote!(#cleanliness),
627                        );
628                        quote! {
629                            #[doc = concat!("The [`Event::", stringify!(#event), "`] transition and its correctly typed next connection.")]
630                            #event {
631                                /// Connection after applying the selected message transition.
632                                connection: Conn<Transport, #target, #cleanliness>,
633                                /// Validated message which selected this transition.
634                                message: #wrapper,
635                                /// Retains the source cleanliness parameter even when replaced.
636                                source_cleanliness: ::core::marker::PhantomData<SourceCleanliness>,
637                            }
638                        }
639                    },
640                );
641                let projection_arms = transitions.iter().map(|transition| {
642                    let event = &transition.event;
643                    quote! {
644                        #type_name::#event(message) => #projection_name::#event {
645                            connection: TypedSession {
646                                transport,
647                                _state: ::core::marker::PhantomData,
648                            },
649                            message,
650                            source_cleanliness: ::core::marker::PhantomData,
651                        }
652                    }
653                });
654
655                quote! {
656                    #(#wrapper_definitions)*
657
658                    #[doc = concat!("Owned ", #direction, " messages legal in [`", stringify!(#state_name), "`].")]
659                    pub enum #type_name {
660                        #(
661                            #[doc = concat!("The [`Event::", stringify!(#variants), "`] transition.")]
662                            #variants(#enum_wrappers),
663                        )*
664                    }
665
666                    #[doc = concat!("Typed next-connection projection for [`", stringify!(#type_name), "`].")]
667                    pub enum #projection_name<Transport, SourceCleanliness> {
668                        #(#projection_variants,)*
669                        #[doc(hidden)]
670                        __Impossible {
671                            never: ::core::convert::Infallible,
672                            marker: ::core::marker::PhantomData<(Transport, SourceCleanliness)>,
673                        },
674                    }
675
676                    impl<Transport, SourceCleanliness>
677                        TypedSession<Transport, #state_name, SourceCleanliness>
678                    {
679                        #[doc = concat!("Projects one [`", stringify!(#type_name), "`] into its message-selected next connection.")]
680                        #[must_use]
681                        #[allow(unreachable_patterns)]
682                        pub fn #projection_method(
683                            self,
684                            message: #type_name,
685                        ) -> #projection_name<Transport, SourceCleanliness> {
686                            let transport = self.transport;
687                            match message {
688                                #(#projection_arms,)*
689                                _ => unreachable!(),
690                            }
691                        }
692                    }
693
694                    impl #type_name {
695                        /// Returns the protocol event represented by this message.
696                        #[must_use]
697                        #[allow(unreachable_patterns)]
698                        pub const fn event(&self) -> Event {
699                            match self {
700                                #(#event_variants,)*
701                                _ => unreachable!(),
702                            }
703                        }
704
705                        /// Borrows the underlying decoded wire message.
706                        #[must_use]
707                        #[allow(unreachable_patterns)]
708                        pub const fn as_wire(&self) -> &#wire_type {
709                            match self {
710                                #(Self::#borrow_variants(message) => message.as_wire(),)*
711                                _ => unreachable!(),
712                            }
713                        }
714
715                        /// Returns the underlying decoded wire message.
716                        #[must_use]
717                        #[allow(unreachable_patterns)]
718                        pub fn into_wire(self) -> #wire_type {
719                            match self {
720                                #(#wire_variants,)*
721                                _ => unreachable!(),
722                            }
723                        }
724                    }
725
726                    impl ::core::convert::TryFrom<#wire_type> for #type_name {
727                        type Error = #wire_type;
728
729                        fn try_from(message: #wire_type) -> ::core::result::Result<Self, #wire_type> {
730                            match #projector(RuntimeState::#state_name, &message) {
731                                #(#match_variants,)*
732                                _ => Err(message),
733                            }
734                        }
735                    }
736
737                    impl ::core::convert::From<#type_name> for #wire_type {
738                        fn from(message: #type_name) -> Self {
739                            message.into_wire()
740                        }
741                    }
742
743                    impl ::core::convert::AsRef<#wire_type> for #type_name {
744                        fn as_ref(&self) -> &#wire_type {
745                            self.as_wire()
746                        }
747                    }
748                }
749            };
750
751            let internal = directional(ChoiceKind::Internal, internal_type, &internal_name);
752            let external = directional(ChoiceKind::External, external_type, &external_name);
753            quote! {
754                #internal
755                #external
756            }
757        }).collect::<Vec<_>>()
758    });
759    let typestate_impls = states.iter().map(|state| {
760        let source = &state.name;
761        let methods = state.transitions.iter().map(|transition| {
762            let method = &transition.method;
763            let target = &transition.target;
764            quote! {
765                #[doc = concat!("Applies `", stringify!(#method), "` and enters [`", stringify!(#target), "`].")]
766                #[must_use]
767                pub const fn #method(self) -> Session<#target> {
768                    Session { _phase: ::core::marker::PhantomData }
769                }
770            }
771        });
772        quote! {
773            impl Session<#source> {
774                #(#methods)*
775            }
776        }
777    });
778    let dual_typestate_impls = states.iter().map(|state| {
779        let source = &state.name;
780        let methods = state.transitions.iter().map(|transition| {
781            let method = &transition.method;
782            let target = &transition.target;
783            quote! {
784                #[doc = concat!("Applies the dual `", stringify!(#method), "` transition and enters [`", stringify!(#target), "`].")]
785                #[must_use]
786                pub const fn #method(self) -> DualSession<#target> {
787                    DualSession { _phase: ::core::marker::PhantomData }
788                }
789            }
790        });
791        quote! {
792            impl DualSession<#source> {
793                #(#methods)*
794            }
795        }
796    });
797    let typed_session_impls = states.iter().map(|state| {
798        let source = &state.name;
799        let methods = state.transitions.iter().map(|transition| {
800            let method = &transition.method;
801            let target = &transition.target;
802            let cleanliness = transition
803                .cleanliness
804                .as_ref()
805                .map_or_else(|| quote!(Cleanliness), |cleanliness| quote!(#cleanliness));
806            if let Some(payload) = &transition.payload {
807                quote! {
808                    #[doc = concat!("Handles the payload for `", stringify!(#method), "`; success enters [`", stringify!(#target), "`] and failure returns the unchanged session.")]
809                    pub fn #method<Output, Error>(
810                        mut self,
811                        payload: #payload,
812                        handle: impl FnOnce(
813                            &mut Transport,
814                            #payload,
815                        ) -> ::core::result::Result<Output, Error>,
816                    ) -> ::core::result::Result<
817                        (TypedSession<Transport, #target, #cleanliness>, Output),
818                        (Self, Error),
819                    > {
820                        match handle(&mut self.transport, payload) {
821                            Ok(output) => Ok((TypedSession {
822                                transport: self.transport,
823                                _state: ::core::marker::PhantomData,
824                            }, output)),
825                            Err(error) => Err((self, error)),
826                        }
827                    }
828                }
829            } else {
830                quote! {
831                    #[doc = concat!("Applies `", stringify!(#method), "` and enters [`", stringify!(#target), "`].")]
832                    #[must_use]
833                    pub fn #method(self) -> TypedSession<Transport, #target, #cleanliness> {
834                        TypedSession {
835                            transport: self.transport,
836                            _state: ::core::marker::PhantomData,
837                        }
838                    }
839                }
840            }
841        });
842        quote! {
843            impl<Transport, Cleanliness> TypedSession<Transport, #source, Cleanliness> {
844                #(#methods)*
845            }
846        }
847    });
848    let dual_typed_session_impls = states.iter().map(|state| {
849        let source = &state.name;
850        let methods = state.transitions.iter().map(|transition| {
851            let method = &transition.method;
852            let target = &transition.target;
853            let cleanliness = transition
854                .cleanliness
855                .as_ref()
856                .map_or_else(|| quote!(Cleanliness), |cleanliness| quote!(#cleanliness));
857            if let Some(payload) = &transition.payload {
858                quote! {
859                    #[doc = concat!("Handles the dual payload for `", stringify!(#method), "`; success enters [`", stringify!(#target), "`] and failure returns the unchanged session.")]
860                    pub fn #method<Output, Error>(
861                        mut self,
862                        payload: #payload,
863                        handle: impl FnOnce(
864                            &mut Transport,
865                            #payload,
866                        ) -> ::core::result::Result<Output, Error>,
867                    ) -> ::core::result::Result<
868                        (DualTypedSession<Transport, #target, #cleanliness>, Output),
869                        (Self, Error),
870                    > {
871                        match handle(&mut self.transport, payload) {
872                            Ok(output) => Ok((DualTypedSession {
873                                transport: self.transport,
874                                _state: ::core::marker::PhantomData,
875                            }, output)),
876                            Err(error) => Err((self, error)),
877                        }
878                    }
879                }
880            } else {
881                quote! {
882                    #[doc = concat!("Applies the dual `", stringify!(#method), "` transition and enters [`", stringify!(#target), "`].")]
883                    #[must_use]
884                    pub fn #method(self) -> DualTypedSession<Transport, #target, #cleanliness> {
885                        DualTypedSession {
886                            transport: self.transport,
887                            _state: ::core::marker::PhantomData,
888                        }
889                    }
890                }
891            }
892        });
893        quote! {
894            impl<Transport, Cleanliness> DualTypedSession<Transport, #source, Cleanliness> {
895                #(#methods)*
896            }
897        }
898    });
899    let svg = railroad_svg(&initial, &states);
900    let diagram_name = format_ident!("{}_RAILROAD_SVG", module.to_string().to_uppercase());
901    let module_doc = format!(
902        "Generated `{module}` protocol grammar.\n\n\
903         ## Railroad diagram\n\n\
904         <style>.width-limiter:has(.pg-proto-railroad) {{ max-width: none; }}</style>\n\
905         <div class=\"pg-proto-railroad\" style=\"overflow-x: auto\">\n\
906         {svg}\n\
907         </div>\n\n\
908         `▷` denotes a choice or action initiated by this role; `◁` denotes one \
909         received from or offered by its peer. Repeated rails are protocol \
910         self-loops and bracketed labels are cleanliness effects."
911    );
912
913    Ok(quote! {
914        #[doc = #module_doc]
915        #visibility mod #module {
916            #(
917                #[doc = concat!("Protocol phase marker for `", stringify!(#state_names), "`.")]
918                #[derive(Clone, Copy, Debug, Eq, PartialEq)]
919                pub enum #state_names {}
920            )*
921
922            #(
923                #[doc = concat!("Cleanliness marker for `", stringify!(#cleanliness_names), "`.")]
924                #[derive(Clone, Copy, Debug, Eq, PartialEq)]
925                pub enum #cleanliness_names {}
926            )*
927
928            /// Runtime representation of a generated protocol phase.
929            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
930            pub enum RuntimeState {
931                #(#[doc = concat!("The [`", stringify!(#state_names), "`] phase.")] #state_names),*
932            }
933
934            /// Events accepted by the generated protocol grammar.
935            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
936            pub enum Event {
937                #(#[doc = concat!("The `", stringify!(#events), "` transition event.")] #events),*
938            }
939
940            /// Complete event alphabet for exhaustive and differential testing.
941            pub const ALL_EVENTS: &[Event] = &[#(Event::#events),*];
942
943            /// Which role selects a transition at a protocol state.
944            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
945            pub enum ChoiceKind {
946                /// This role selects the transition.
947                Internal,
948                /// The peer selects the transition.
949                External,
950                /// Legal transitions include choices by both roles.
951                Mixed,
952            }
953
954            /// Directional operations on [`ChoiceKind`].
955            impl ChoiceKind {
956                /// Returns the choice direction seen by the peer role.
957                #[must_use]
958                pub const fn dual(self) -> Self {
959                    match self {
960                        Self::Internal => Self::External,
961                        Self::External => Self::Internal,
962                        Self::Mixed => Self::Mixed,
963                    }
964                }
965            }
966
967            /// One edge in the generated runtime transition table.
968            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
969            pub struct RuntimeTransition {
970                /// Stable catalogue identifier generated from protocol, phase, and event.
971                pub id: &'static str,
972                /// Phase from which the event is legal.
973                pub source: RuntimeState,
974                /// Event which advances the protocol.
975                pub event: Event,
976                /// Phase entered after the event.
977                pub target: RuntimeState,
978                /// Role which selects this event.
979                pub choice: ChoiceKind,
980            }
981
982            /// Canonical runtime transition table generated from the grammar.
983            pub const TRANSITIONS: &[RuntimeTransition] = &[#(#transition_descriptors),*];
984
985            #projection_functions
986            #(#phase_message_types)*
987            #(#association_impls)*
988
989            /// Looks up one legal transition from `state` for `event`.
990            #[must_use]
991            pub fn transition(
992                state: RuntimeState,
993                event: Event,
994            ) -> Option<RuntimeTransition> {
995                TRANSITIONS
996                    .iter()
997                    .copied()
998                    .find(|transition| transition.source == state && transition.event == event)
999            }
1000
1001            /// Rejected runtime transition with the unchanged state and event.
1002            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1003            pub struct TransitionError {
1004                /// State in which the event was rejected.
1005                pub state: RuntimeState,
1006                /// Event which was not legal in `state`.
1007                pub event: Event,
1008            }
1009
1010            /// Failure to project or apply a wire message in a runtime state.
1011            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1012            pub struct ProjectionError {
1013                /// State in which projection or advancement failed.
1014                pub state: RuntimeState,
1015            }
1016
1017            /// Executable runtime mirror of the generated typestate API.
1018            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1019            pub struct RuntimeFsm {
1020                state: RuntimeState,
1021            }
1022
1023            /// Runtime state-machine construction, inspection, and advancement.
1024            impl RuntimeFsm {
1025                /// Creates an FSM in the grammar's initial state.
1026                #[must_use]
1027                pub const fn new() -> Self {
1028                    Self { state: RuntimeState::#initial }
1029                }
1030
1031                /// Returns the current runtime phase.
1032                #[must_use]
1033                pub const fn state(&self) -> RuntimeState {
1034                    self.state
1035                }
1036
1037                /// Returns who selects transitions in the current phase.
1038                #[must_use]
1039                pub const fn choice(&self) -> ChoiceKind {
1040                    match self.state { #(#choice_arms),* }
1041                }
1042
1043                /// Returns the current phase's choice as seen by the peer.
1044                #[must_use]
1045                pub const fn dual_choice(&self) -> ChoiceKind {
1046                    self.choice().dual()
1047                }
1048
1049                /// Returns the direction of one legal event from the current state.
1050                #[must_use]
1051                pub fn event_choice(&self, event: Event) -> Option<ChoiceKind> {
1052                    transition(self.state, event).map(|transition| transition.choice)
1053                }
1054
1055                /// Returns the direction of one legal event for the dual role.
1056                #[must_use]
1057                pub fn dual_event_choice(&self, event: Event) -> Option<ChoiceKind> {
1058                    match self.event_choice(event) {
1059                        Some(choice) => Some(choice.dual()),
1060                        None => None,
1061                    }
1062                }
1063
1064                /// Advances the FSM with `event` without changing it on error.
1065                pub fn step(&mut self, event: Event) -> Result<(), TransitionError> {
1066                    match transition(self.state, event) {
1067                        Some(transition) => {
1068                            self.state = transition.target;
1069                            Ok(())
1070                        }
1071                        None => Err(TransitionError {
1072                            state: self.state,
1073                            event,
1074                        }),
1075                    }
1076                }
1077
1078                /// Projects a wire message using the current state, then advances.
1079                ///
1080                /// The projector is state-aware because one wire message can denote
1081                /// different protocol events in nested or mixed sessions.
1082                pub fn step_projected<Message>(
1083                    &mut self,
1084                    message: &Message,
1085                    project: impl FnOnce(RuntimeState, &Message) -> Option<Event>,
1086                ) -> Result<Event, ProjectionError> {
1087                    let state = self.state;
1088                    let event = project(state, message).ok_or(ProjectionError { state })?;
1089                    match self.step(event) {
1090                        Ok(()) => Ok(event),
1091                        Err(_) => Err(ProjectionError { state }),
1092                    }
1093                }
1094            }
1095
1096            impl Default for RuntimeFsm {
1097                fn default() -> Self { Self::new() }
1098            }
1099
1100            /// Zero-sized typestate witness for this protocol role.
1101            #[must_use]
1102            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1103            pub struct Session<Phase> {
1104                _phase: ::core::marker::PhantomData<Phase>,
1105            }
1106
1107            /// Typestate witness for the role dual to [`Session`].
1108            #[must_use]
1109            #[derive(Clone, Copy, Debug, Eq, PartialEq)]
1110            pub struct DualSession<Phase> {
1111                _phase: ::core::marker::PhantomData<Phase>,
1112            }
1113
1114            /// Transport-carrying typestate for this protocol role.
1115            #[must_use = "dropping a generated typed session abandons its protocol state"]
1116            #[derive(Debug)]
1117            pub struct TypedSession<Transport, Phase, Cleanliness = ()> {
1118                transport: Transport,
1119                _state: ::core::marker::PhantomData<(Phase, Cleanliness)>,
1120            }
1121
1122            /// Generated connection carrying transport, protocol phase, and cleanliness.
1123            pub type Conn<Transport, Phase, Cleanliness = ()> =
1124                TypedSession<Transport, Phase, Cleanliness>;
1125
1126            /// Transport-carrying typestate for the peer role.
1127            #[must_use = "dropping a generated dual session abandons its protocol state"]
1128            #[derive(Debug)]
1129            pub struct DualTypedSession<Transport, Phase, Cleanliness = ()> {
1130                transport: Transport,
1131                _state: ::core::marker::PhantomData<(Phase, Cleanliness)>,
1132            }
1133
1134            impl Session<#initial> {
1135                /// Creates a witness in the grammar's initial phase.
1136                #[must_use]
1137                pub const fn new() -> Self {
1138                    Self { _phase: ::core::marker::PhantomData }
1139                }
1140            }
1141
1142            impl DualSession<#initial> {
1143                /// Creates a dual witness in the grammar's initial phase.
1144                #[must_use]
1145                pub const fn new() -> Self {
1146                    Self { _phase: ::core::marker::PhantomData }
1147                }
1148            }
1149
1150            impl<Transport, Cleanliness> TypedSession<Transport, #initial, Cleanliness> {
1151                /// Attaches `transport` to a session in the initial phase.
1152                #[must_use]
1153                pub const fn with_transport(transport: Transport) -> Self {
1154                    Self { transport, _state: ::core::marker::PhantomData }
1155                }
1156            }
1157
1158            impl<Transport, Cleanliness> DualTypedSession<Transport, #initial, Cleanliness> {
1159                /// Attaches `transport` to a dual session in the initial phase.
1160                #[must_use]
1161                pub const fn with_transport(transport: Transport) -> Self {
1162                    Self { transport, _state: ::core::marker::PhantomData }
1163                }
1164            }
1165
1166            impl<Transport, Phase, Cleanliness> TypedSession<Transport, Phase, Cleanliness> {
1167                /// Replaces the transport representation without changing protocol indices.
1168                #[must_use]
1169                pub fn map_transport<Next>(
1170                    self,
1171                    map: impl FnOnce(Transport) -> Next,
1172                ) -> TypedSession<Next, Phase, Cleanliness> {
1173                    TypedSession {
1174                        transport: map(self.transport),
1175                        _state: ::core::marker::PhantomData,
1176                    }
1177                }
1178
1179                /// Deliberately leaves the generated typestate API and returns its transport.
1180                #[must_use]
1181                pub fn into_transport(self) -> Transport {
1182                    self.transport
1183                }
1184            }
1185
1186            impl<Transport, Phase, Cleanliness> DualTypedSession<Transport, Phase, Cleanliness> {
1187                /// Replaces the dual transport representation without changing protocol indices.
1188                #[must_use]
1189                pub fn map_transport<Next>(
1190                    self,
1191                    map: impl FnOnce(Transport) -> Next,
1192                ) -> DualTypedSession<Next, Phase, Cleanliness> {
1193                    DualTypedSession {
1194                        transport: map(self.transport),
1195                        _state: ::core::marker::PhantomData,
1196                    }
1197                }
1198
1199                /// Deliberately leaves the generated dual API and returns its transport.
1200                #[must_use]
1201                pub fn into_transport(self) -> Transport {
1202                    self.transport
1203                }
1204            }
1205
1206            #(#typestate_impls)*
1207            #(#dual_typestate_impls)*
1208            #(#typed_session_impls)*
1209            #(#dual_typed_session_impls)*
1210
1211            /// Raw SVG embedded in this module's railroad-diagram documentation.
1212            pub const #diagram_name: &str = #svg;
1213        }
1214    })
1215}
1216
1217fn validate(protocol: &Protocol) -> Result<()> {
1218    validate_associations(protocol)?;
1219    if protocol.messages.is_none()
1220        && let Some(transition) = protocol
1221            .states
1222            .iter()
1223            .flat_map(|state| &state.transitions)
1224            .find(|transition| transition.projection.is_some())
1225    {
1226        return Err(syn::Error::new(
1227            transition.event.span(),
1228            "transition projection requires a `messages` declaration",
1229        ));
1230    }
1231    let states = protocol
1232        .states
1233        .iter()
1234        .map(|state| state.name.to_string())
1235        .collect::<BTreeSet<_>>();
1236    if !states.contains(&protocol.initial.to_string()) {
1237        return Err(syn::Error::new(
1238            protocol.initial.span(),
1239            "initial state is not declared",
1240        ));
1241    }
1242    for state in &protocol.states {
1243        match state.choice {
1244            ChoiceKind::Mixed
1245                if state
1246                    .transitions
1247                    .iter()
1248                    .any(|transition| transition.choice.is_none()) =>
1249            {
1250                return Err(syn::Error::new(
1251                    state.name.span(),
1252                    "every transition in a mixed state needs `internal` or `external`",
1253                ));
1254            }
1255            ChoiceKind::Internal | ChoiceKind::External
1256                if state
1257                    .transitions
1258                    .iter()
1259                    .any(|transition| transition.choice.is_some()) =>
1260            {
1261                return Err(syn::Error::new(
1262                    state.name.span(),
1263                    "transition directions are only valid in a mixed state",
1264                ));
1265            }
1266            _ => {}
1267        }
1268        let mut methods = BTreeSet::new();
1269        for transition in &state.transitions {
1270            if !states.contains(&transition.target.to_string()) {
1271                return Err(syn::Error::new(
1272                    transition.target.span(),
1273                    "transition target is not declared",
1274                ));
1275            }
1276            if !methods.insert(transition.method.to_string()) {
1277                return Err(syn::Error::new(
1278                    transition.method.span(),
1279                    "duplicate transition method in state",
1280                ));
1281            }
1282        }
1283    }
1284    Ok(())
1285}
1286
1287fn validate_associations(protocol: &Protocol) -> Result<()> {
1288    match &protocol.associations {
1289        Some(associations) => {
1290            if protocol.messages.is_none() {
1291                return Err(syn::Error::new_spanned(
1292                    &associations.interface,
1293                    "associations require a `messages` declaration",
1294                ));
1295            }
1296            validate_message_template(&associations.inbound.message)?;
1297            validate_message_template(&associations.outbound.message)?;
1298            let mut implementations = BTreeSet::new();
1299            for state in &protocol.states {
1300                let Some(state_associations) = &state.associations else {
1301                    return Err(syn::Error::new(
1302                        state.name.span(),
1303                        "state requires an `associate` block",
1304                    ));
1305                };
1306                validate_association_types(&state_associations.inbound)?;
1307                validate_association_types(&state_associations.outbound)?;
1308                for (lane, connections) in [
1309                    (&associations.inbound, &state_associations.inbound),
1310                    (&associations.outbound, &state_associations.outbound),
1311                ] {
1312                    let direction = &lane.direction;
1313                    let role = &lane.role;
1314                    let wire = &lane.wire;
1315                    let lane_key = quote!(#direction, #role, #wire).to_string();
1316                    for connection in connections {
1317                        let connection_key = quote!(#connection).to_string();
1318                        if !implementations.insert((lane_key.clone(), connection_key)) {
1319                            return Err(syn::Error::new_spanned(
1320                                connection,
1321                                "connection type has a duplicate association for this direction, role, and wire type",
1322                            ));
1323                        }
1324                    }
1325                }
1326            }
1327        }
1328        None => {
1329            if let Some(state) = protocol
1330                .states
1331                .iter()
1332                .find(|state| state.associations.is_some())
1333            {
1334                return Err(syn::Error::new(
1335                    state.name.span(),
1336                    "state association requires an `associations` declaration",
1337                ));
1338            }
1339        }
1340    }
1341    Ok(())
1342}
1343
1344fn validate_association_types(types: &[Type]) -> Result<()> {
1345    let mut seen = BTreeSet::new();
1346    for ty in types {
1347        if !seen.insert(quote!(#ty).to_string()) {
1348            return Err(syn::Error::new_spanned(
1349                ty,
1350                "duplicate connection type in association lane",
1351            ));
1352        }
1353    }
1354    Ok(())
1355}
1356
1357fn validate_message_template(message: &Type) -> Result<()> {
1358    let (message, count) = replace_message_placeholder(message, None);
1359    match count {
1360        1 => Ok(()),
1361        0 => Err(syn::Error::new_spanned(
1362            message,
1363            "association message type requires exactly one bare `internal` or `external` placeholder",
1364        )),
1365        _ => Err(syn::Error::new_spanned(
1366            message,
1367            "association message type contains more than one message placeholder",
1368        )),
1369    }
1370}
1371
1372fn instantiate_message_type(message: &Type, state: &Ident) -> Result<Type> {
1373    let (message, count) = replace_message_placeholder(message, Some(state));
1374    if count == 1 {
1375        Ok(message)
1376    } else {
1377        Err(syn::Error::new_spanned(
1378            message,
1379            "association message type requires exactly one message placeholder",
1380        ))
1381    }
1382}
1383
1384fn replace_message_placeholder(message: &Type, state: Option<&Ident>) -> (Type, usize) {
1385    let mut message = message.clone();
1386    let mut replacer = MessagePlaceholderReplacer {
1387        state: state.cloned(),
1388        count: 0,
1389    };
1390    replacer.visit_type_mut(&mut message);
1391    (message, replacer.count)
1392}
1393
1394#[derive(Default)]
1395struct MessagePlaceholderReplacer {
1396    state: Option<Ident>,
1397    count: usize,
1398}
1399
1400impl VisitMut for MessagePlaceholderReplacer {
1401    fn visit_type_mut(&mut self, ty: &mut Type) {
1402        let Type::Path(type_path) = ty else {
1403            visit_mut::visit_type_mut(self, ty);
1404            return;
1405        };
1406        if type_path.qself.is_none() && type_path.path.segments.len() == 1 {
1407            let segment = &type_path.path.segments[0];
1408            let direction = segment.ident.to_string();
1409            if segment.arguments.is_empty() && matches!(direction.as_str(), "internal" | "external")
1410            {
1411                self.count += 1;
1412                if let Some(state) = &self.state {
1413                    let suffix = if direction == "internal" {
1414                        "InternalMessage"
1415                    } else {
1416                        "ExternalMessage"
1417                    };
1418                    let replacement = format_ident!("{state}{suffix}");
1419                    *ty = syn::parse_quote!(#replacement);
1420                }
1421                return;
1422            }
1423        }
1424        visit_mut::visit_type_mut(self, ty);
1425    }
1426}
1427
1428fn railroad_svg(initial: &Ident, states: &[State]) -> String {
1429    const SVG_GUTTER: i64 = 12;
1430
1431    let states_by_name = states
1432        .iter()
1433        .map(|state| (state.name.to_string(), state))
1434        .collect::<BTreeMap<_, _>>();
1435    let mut expanded = BTreeSet::new();
1436    let root = Sequence::new(vec![
1437        Box::new(Start) as Box<dyn Node>,
1438        railroad_state_node(initial, &states_by_name, &mut expanded),
1439        Box::new(End),
1440    ]);
1441    let mut diagram = Diagram::new_with_stylesheet(root, &Stylesheet::Light);
1442    diagram.add_css(
1443        "svg.railroad a.link tspan { text-decoration: underline; } \
1444         svg.railroad a.link:hover tspan { text-decoration-thickness: 2px; }",
1445    );
1446    let content_width = diagram.width();
1447    let content_height = diagram.height();
1448    let width = content_width + SVG_GUTTER;
1449    let height = content_height + SVG_GUTTER;
1450    diagram
1451        .attr("width".to_owned())
1452        .or_insert_with(|| width.to_string());
1453    diagram
1454        .attr("height".to_owned())
1455        .or_insert_with(|| height.to_string());
1456    diagram
1457        .attr("style".to_owned())
1458        .or_insert_with(|| "display: block; max-width: none".to_owned());
1459    diagram
1460        .attr("data-content-width".to_owned())
1461        .or_insert_with(|| content_width.to_string());
1462    diagram
1463        .attr("data-content-height".to_owned())
1464        .or_insert_with(|| content_height.to_string());
1465
1466    let svg = diagram.to_string().replace(
1467        &format!("viewBox=\"0 0 {content_width} {content_height}\""),
1468        &format!("viewBox=\"0 0 {width} {height}\""),
1469    );
1470
1471    // rustdoc feeds doc attributes through a Markdown parser. Newlines inside
1472    // the SVG's style element would be interpreted as Markdown paragraphs,
1473    // producing invalid CSS. Keeping the embedded SVG on one line makes it a
1474    // single raw HTML block while retaining intrinsic dimensions for scrolling.
1475    svg.replace(['\r', '\n'], " ")
1476}
1477
1478fn railroad_state_node(
1479    name: &Ident,
1480    states: &BTreeMap<String, &State>,
1481    expanded: &mut BTreeSet<String>,
1482) -> Box<dyn Node> {
1483    let name = name.to_string();
1484    if !expanded.insert(name.clone()) {
1485        return Box::new(NonTerminal::new(name));
1486    }
1487
1488    let state = states
1489        .get(&name)
1490        .expect("validated transition target has a protocol phase");
1491    let self_loops = state
1492        .transitions
1493        .iter()
1494        .filter(|transition| transition.target == state.name)
1495        .map(|transition| transition_node(transition, state.choice))
1496        .collect::<Vec<_>>();
1497    let mut exits = Vec::new();
1498    for transition in state
1499        .transitions
1500        .iter()
1501        .filter(|transition| transition.target != state.name)
1502    {
1503        exits.push(Box::new(Sequence::new(vec![
1504            transition_node(transition, state.choice),
1505            railroad_state_node(&transition.target, states, expanded),
1506        ])) as Box<dyn Node>);
1507    }
1508
1509    let mut nodes = vec![Box::new(NonTerminal::new(name)) as Box<dyn Node>];
1510    if !self_loops.is_empty() {
1511        nodes.push(Box::new(Repeat::new(Choice::new(self_loops), Empty)));
1512    }
1513    if exits.is_empty() {
1514        nodes.push(Box::new(Terminal::new("end".to_owned())));
1515    } else {
1516        nodes.push(Box::new(Choice::new(exits)));
1517    }
1518    Box::new(Sequence::new(nodes))
1519}
1520
1521fn transition_node(transition: &Transition, state_choice: ChoiceKind) -> Box<dyn Node> {
1522    let choice = match transition.choice.unwrap_or(state_choice) {
1523        ChoiceKind::Internal => "▷",
1524        ChoiceKind::External => "◁",
1525        ChoiceKind::Mixed => unreachable!("validated mixed transition has a direction"),
1526    };
1527    let cleanliness = transition
1528        .cleanliness
1529        .as_ref()
1530        .map_or_else(String::new, |cleanliness| format!(" [{cleanliness}]"));
1531    let (prefix, payload, suffix, url) = match &transition.payload {
1532        Some(payload) => {
1533            let rendered = quote!(#payload).to_string().replace(' ', "");
1534            (
1535                format!("{choice} {}(", transition.event),
1536                Some(rendered),
1537                format!("){cleanliness}"),
1538                payload_doc_url(payload),
1539            )
1540        }
1541        None => (
1542            format!("{choice} {}", transition.event),
1543            None,
1544            cleanliness,
1545            None,
1546        ),
1547    };
1548    Box::new(TransitionTerminal {
1549        prefix,
1550        payload,
1551        suffix,
1552        url,
1553    })
1554}
1555
1556#[derive(Debug)]
1557struct TransitionTerminal {
1558    prefix: String,
1559    payload: Option<String>,
1560    suffix: String,
1561    url: Option<String>,
1562}
1563
1564impl TransitionTerminal {
1565    fn label_width(&self) -> usize {
1566        self.prefix.chars().count()
1567            + self
1568                .payload
1569                .as_ref()
1570                .map_or(0, |value| value.chars().count())
1571            + self.suffix.chars().count()
1572    }
1573}
1574
1575impl Node for TransitionTerminal {
1576    fn entry_height(&self) -> i64 {
1577        11
1578    }
1579
1580    fn height(&self) -> i64 {
1581        22
1582    }
1583
1584    fn width(&self) -> i64 {
1585        i64::try_from(self.label_width()).expect("transition label width fits i64") * 9 + 24
1586    }
1587
1588    fn draw(&self, x: i64, y: i64, _h_dir: HDir) -> svg::Element {
1589        let rect = svg::Element::new("rect")
1590            .set("x", &x)
1591            .set("y", &y)
1592            .set("height", &self.height())
1593            .set("width", &self.width())
1594            .set("rx", &10)
1595            .set("ry", &10);
1596        let mut text = svg::Element::new("text")
1597            .set("x", &(x + self.width() / 2))
1598            .set("y", &(y + self.entry_height() + 5));
1599        text.push(svg::Element::new("tspan").text(&self.prefix));
1600        if let Some(payload) = &self.payload {
1601            let payload = svg::Element::new("tspan").text(payload);
1602            match &self.url {
1603                Some(url) => {
1604                    text.push(
1605                        svg::Element::new("a")
1606                            .set("xlink:href", url)
1607                            .set("class", &"link")
1608                            .add(payload),
1609                    );
1610                }
1611                None => {
1612                    text.push(payload);
1613                }
1614            }
1615        }
1616        text.push(svg::Element::new("tspan").text(&self.suffix));
1617        svg::Element::new("g")
1618            .set("class", &"terminal")
1619            .add(rect)
1620            .add(text)
1621    }
1622}
1623
1624fn payload_doc_url(payload: &Type) -> Option<String> {
1625    let payload = quote!(#payload).to_string().replace(' ', "");
1626    if payload.contains("bytes::Bytes") {
1627        return Some("https://docs.rs/bytes/1/bytes/struct.Bytes.html".to_owned());
1628    }
1629    let (module, name) = payload.strip_prefix("crate::")?.rsplit_once("::")?;
1630    let kind = match (module, name) {
1631        ("codec", "BackendMessage" | "TransactionStatus") => "enum",
1632        ("codec", _) | ("server_auth", "SaslInitialResponse") | ("startup", "StartupMessage") => {
1633            "struct"
1634        }
1635        _ => return None,
1636    };
1637    Some(format!("../../{module}/{kind}.{name}.html"))
1638}