asupersync-macros 0.3.0

Proc macros for asupersync structured concurrency runtime
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
//! Implementation of the `session_protocol!` macro.
//!
//! Generates typestate-encoded session types from a protocol DSL,
//! producing paired channel constructors with compile-time protocol safety.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
    Ident, Token, Type, braced,
    parse::{Parse, ParseStream},
    parse_macro_input,
    punctuated::Punctuated,
};

// ============================================================================
// AST
// ============================================================================

struct ProtocolDef {
    name: Ident,
    type_params: Vec<Ident>,
    obligation: ObligationSpec,
    messages: Vec<MessageDef>,
    body: SessionBody,
}

/// How the obligation kind is specified.
enum ObligationSpec {
    /// Fixed variant: `for SendPermit` → `ObligationKind::SendPermit`.
    Fixed(Ident),
    /// Parameterized: `(kind: ObligationKind)` → constructor takes `kind` param.
    Param(Ident, Box<Type>),
}

struct MessageDef {
    name: Ident,
    fields: Vec<FieldDef>,
}

struct FieldDef {
    name: Ident,
    ty: Type,
}

enum SessionBody {
    End,
    Continue,
    Send(Type, Box<Self>),
    Recv(Type, Box<Self>),
    Select(Box<Self>, Box<Self>),
    Offer(Box<Self>, Box<Self>),
    Loop(Box<Self>),
}

// ============================================================================
// Parser
// ============================================================================

impl Parse for ProtocolDef {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name: Ident = input.parse()?;

        let type_params = if input.peek(Token![<]) {
            let _: Token![<] = input.parse()?;
            let params: Punctuated<Ident, Token![,]> = Punctuated::parse_separated_nonempty(input)?;
            let _: Token![>] = input.parse()?;
            params.into_iter().collect()
        } else {
            Vec::new()
        };

        // Parse obligation spec: either `for Variant` or `(param: Type)`
        let obligation = if input.peek(Token![for]) {
            let _: Token![for] = input.parse()?;
            let variant: Ident = input.parse()?;
            ObligationSpec::Fixed(variant)
        } else if input.peek(syn::token::Paren) {
            let paren_content;
            syn::parenthesized!(paren_content in input);
            let param_name: Ident = paren_content.parse()?;
            let _: Token![:] = paren_content.parse()?;
            let param_type: Type = paren_content.parse()?;
            ObligationSpec::Param(param_name, Box::new(param_type))
        } else {
            return Err(syn::Error::new(
                input.span(),
                "expected `for ObligationKind` or `(param: Type)` after protocol name",
            ));
        };

        let content;
        braced!(content in input);

        let mut messages = Vec::new();
        while !content.is_empty() {
            if content.peek(Ident) {
                let fork = content.fork();
                if let Ok(ident) = fork.parse::<Ident>()
                    && ident == "msg"
                {
                    let _: Ident = content.parse()?;
                    let msg = parse_message_def(&content)?;
                    messages.push(msg);
                    continue;
                }
            }
            break;
        }

        let body = parse_session_body(&content)?;

        validate_body(&body, false).map_err(|msg| syn::Error::new(name.span(), msg))?;

        Ok(Self {
            name,
            type_params,
            obligation,
            messages,
            body,
        })
    }
}

fn parse_message_def(input: ParseStream) -> syn::Result<MessageDef> {
    let name: Ident = input.parse()?;

    let fields = if input.peek(syn::token::Brace) {
        let fields_content;
        braced!(fields_content in input);
        let mut fields = Vec::new();
        while !fields_content.is_empty() {
            let fname: Ident = fields_content.parse()?;
            let _: Token![:] = fields_content.parse()?;
            let fty: Type = fields_content.parse()?;
            fields.push(FieldDef {
                name: fname,
                ty: fty,
            });
            if fields_content.peek(Token![,]) {
                let _: Token![,] = fields_content.parse()?;
            }
        }
        fields
    } else {
        Vec::new()
    };

    let _: Token![;] = input
        .parse()
        .map_err(|_| syn::Error::new(name.span(), "expected `;` after message definition"))?;

    Ok(MessageDef { name, fields })
}

fn parse_session_body(input: ParseStream) -> syn::Result<SessionBody> {
    if input.peek(Token![loop]) {
        let _: Token![loop] = input.parse()?;
        let content;
        braced!(content in input);
        let body = parse_session_body(&content)?;
        return Ok(SessionBody::Loop(Box::new(body)));
    }

    if input.peek(Token![continue]) {
        let _: Token![continue] = input.parse()?;
        return Ok(SessionBody::Continue);
    }

    let kw: Ident = input.parse().map_err(|_| {
        syn::Error::new(
            input.span(),
            "expected session action: send, recv, select, offer, end, loop, or continue",
        )
    })?;

    match kw.to_string().as_str() {
        "end" => Ok(SessionBody::End),
        "send" => {
            let ty: Type = input.parse()?;
            let _: Token![=>] = input
                .parse()
                .map_err(|_| syn::Error::new(kw.span(), "expected `=>` after send type"))?;
            let cont = parse_session_body(input)?;
            Ok(SessionBody::Send(ty, Box::new(cont)))
        }
        "recv" => {
            let ty: Type = input.parse()?;
            let _: Token![=>] = input
                .parse()
                .map_err(|_| syn::Error::new(kw.span(), "expected `=>` after recv type"))?;
            let cont = parse_session_body(input)?;
            Ok(SessionBody::Recv(ty, Box::new(cont)))
        }
        "select" => {
            let content;
            braced!(content in input);
            let left = parse_session_body(&content)?;
            let _: Token![,] = content.parse().map_err(|_| {
                syn::Error::new(kw.span(), "select requires two branches separated by `,`")
            })?;
            let right = parse_session_body(&content)?;
            if content.peek(Token![,]) {
                let _: Token![,] = content.parse()?;
            }
            Ok(SessionBody::Select(Box::new(left), Box::new(right)))
        }
        "offer" => {
            let content;
            braced!(content in input);
            let left = parse_session_body(&content)?;
            let _: Token![,] = content.parse().map_err(|_| {
                syn::Error::new(kw.span(), "offer requires two branches separated by `,`")
            })?;
            let right = parse_session_body(&content)?;
            if content.peek(Token![,]) {
                let _: Token![,] = content.parse()?;
            }
            Ok(SessionBody::Offer(Box::new(left), Box::new(right)))
        }
        other => Err(syn::Error::new(
            kw.span(),
            format!(
                "unknown session action `{other}`, expected: send, recv, select, offer, end, loop, continue"
            ),
        )),
    }
}

// ============================================================================
// Validation
// ============================================================================

fn validate_body(body: &SessionBody, in_loop: bool) -> Result<(), String> {
    match body {
        SessionBody::End => Ok(()),
        SessionBody::Continue => {
            if in_loop {
                Ok(())
            } else {
                Err("`continue` used outside of `loop` block".to_string())
            }
        }
        SessionBody::Send(_, cont) | SessionBody::Recv(_, cont) => validate_body(cont, in_loop),
        SessionBody::Select(a, b) | SessionBody::Offer(a, b) => {
            validate_body(a, in_loop)?;
            validate_body(b, in_loop)
        }
        SessionBody::Loop(inner) => {
            if in_loop {
                Err("nested `loop` blocks are not supported".to_string())
            } else {
                validate_body(inner, true)
            }
        }
    }
}

fn extract_loop_body(body: &SessionBody) -> Option<&SessionBody> {
    match body {
        SessionBody::Loop(inner) => Some(inner),
        SessionBody::Send(_, c) | SessionBody::Recv(_, c) => extract_loop_body(c),
        SessionBody::Select(a, b) | SessionBody::Offer(a, b) => {
            extract_loop_body(a).or_else(|| extract_loop_body(b))
        }
        SessionBody::End | SessionBody::Continue => None,
    }
}

// ============================================================================
// Type generation
// ============================================================================

/// Generate initiator's session type (direct encoding).
fn gen_init(body: &SessionBody, tp: &[Ident]) -> TokenStream2 {
    match body {
        SessionBody::End | SessionBody::Continue => quote! { End },
        SessionBody::Send(ty, c) => {
            let c = gen_init(c, tp);
            quote! { Send<#ty, #c> }
        }
        SessionBody::Recv(ty, c) => {
            let c = gen_init(c, tp);
            quote! { Recv<#ty, #c> }
        }
        SessionBody::Select(a, b) => {
            let a = gen_init(a, tp);
            let b = gen_init(b, tp);
            quote! { Select<#a, #b> }
        }
        SessionBody::Offer(a, b) => {
            let a = gen_init(a, tp);
            let b = gen_init(b, tp);
            quote! { Offer<#a, #b> }
        }
        SessionBody::Loop(_) => {
            if tp.is_empty() {
                quote! { InitiatorLoop }
            } else {
                quote! { InitiatorLoop<#(#tp),*> }
            }
        }
    }
}

/// Generate responder's session type (dual: Send↔Recv, Select↔Offer).
fn gen_resp(body: &SessionBody, tp: &[Ident]) -> TokenStream2 {
    match body {
        SessionBody::End | SessionBody::Continue => quote! { End },
        SessionBody::Send(ty, c) => {
            let c = gen_resp(c, tp);
            quote! { Recv<#ty, #c> }
        }
        SessionBody::Recv(ty, c) => {
            let c = gen_resp(c, tp);
            quote! { Send<#ty, #c> }
        }
        SessionBody::Select(a, b) => {
            let a = gen_resp(a, tp);
            let b = gen_resp(b, tp);
            quote! { Offer<#a, #b> }
        }
        SessionBody::Offer(a, b) => {
            let a = gen_resp(a, tp);
            let b = gen_resp(b, tp);
            quote! { Select<#a, #b> }
        }
        SessionBody::Loop(_) => {
            if tp.is_empty() {
                quote! { ResponderLoop }
            } else {
                quote! { ResponderLoop<#(#tp),*> }
            }
        }
    }
}

/// Generate loop body type for initiator.
fn gen_init_loop(body: &SessionBody) -> TokenStream2 {
    match body {
        SessionBody::End | SessionBody::Continue => quote! { End },
        SessionBody::Send(ty, c) => {
            let c = gen_init_loop(c);
            quote! { Send<#ty, #c> }
        }
        SessionBody::Recv(ty, c) => {
            let c = gen_init_loop(c);
            quote! { Recv<#ty, #c> }
        }
        SessionBody::Select(a, b) => {
            let a = gen_init_loop(a);
            let b = gen_init_loop(b);
            quote! { Select<#a, #b> }
        }
        SessionBody::Offer(a, b) => {
            let a = gen_init_loop(a);
            let b = gen_init_loop(b);
            quote! { Offer<#a, #b> }
        }
        SessionBody::Loop(_) => quote! { compile_error!("nested loop") },
    }
}

/// Generate loop body type for responder (dual).
fn gen_resp_loop(body: &SessionBody) -> TokenStream2 {
    match body {
        SessionBody::End | SessionBody::Continue => quote! { End },
        SessionBody::Send(ty, c) => {
            let c = gen_resp_loop(c);
            quote! { Recv<#ty, #c> }
        }
        SessionBody::Recv(ty, c) => {
            let c = gen_resp_loop(c);
            quote! { Send<#ty, #c> }
        }
        SessionBody::Select(a, b) => {
            let a = gen_resp_loop(a);
            let b = gen_resp_loop(b);
            quote! { Offer<#a, #b> }
        }
        SessionBody::Offer(a, b) => {
            let a = gen_resp_loop(a);
            let b = gen_resp_loop(b);
            quote! { Select<#a, #b> }
        }
        SessionBody::Loop(_) => quote! { compile_error!("nested loop") },
    }
}

// ============================================================================
// Module generation
// ============================================================================

fn gen_transport_constructor(
    tp_clause: &TokenStream2,
    ob_extra_param: &TokenStream2,
    ob_expr: &TokenStream2,
) -> TokenStream2 {
    quote! {
        /// Create a transport-backed initiator/responder session pair.
        pub fn new_session_with_transport #tp_clause (
            channel_id: u64,
            #ob_extra_param
            buffer: usize,
        ) -> (
            Chan<Initiator, InitiatorSession #tp_clause>,
            Chan<Responder, ResponderSession #tp_clause>,
        ) {
            let (tx_i2r, rx_i2r) =
                crate::channel::mpsc::channel::<Box<dyn std::any::Any + std::marker::Send>>(buffer);
            let (tx_r2i, rx_r2i) =
                crate::channel::mpsc::channel::<Box<dyn std::any::Any + std::marker::Send>>(buffer);
            (
                Chan::new_with_transport(
                    channel_id,
                    #ob_expr,
                    SessionTransport {
                        tx: tx_i2r,
                        rx: rx_r2i,
                    },
                ),
                Chan::new_with_transport(
                    channel_id,
                    #ob_expr,
                    SessionTransport {
                        tx: tx_r2i,
                        rx: rx_i2r,
                    },
                ),
            )
        }
    }
}

fn generate_protocol(def: &ProtocolDef) -> TokenStream2 {
    let mod_name = &def.name;
    let tp = &def.type_params;

    let tp_clause = if tp.is_empty() {
        quote! {}
    } else {
        quote! { <#(#tp),*> }
    };

    // Obligation kind expression used in Chan::new_raw calls.
    let (ob_expr, ob_extra_param) = match &def.obligation {
        ObligationSpec::Fixed(variant) => (quote! { ObligationKind::#variant }, quote! {}),
        ObligationSpec::Param(name, ty) => (quote! { #name }, quote! { #name: #ty, }),
    };

    let msg_structs: Vec<TokenStream2> = def
        .messages
        .iter()
        .map(|msg| {
            let n = &msg.name;
            if msg.fields.is_empty() {
                quote! {
                    #[derive(Debug, Clone, Copy)]
                    pub struct #n;
                }
            } else {
                let fields: Vec<TokenStream2> = msg
                    .fields
                    .iter()
                    .map(|f| {
                        let fname = &f.name;
                        let fty = &f.ty;
                        quote! { pub #fname: #fty }
                    })
                    .collect();
                quote! {
                    #[derive(Debug, Clone)]
                    pub struct #n {
                        #(#fields,)*
                    }
                }
            }
        })
        .collect();

    let initiator_type = gen_init(&def.body, tp);
    let responder_type = gen_resp(&def.body, tp);
    let transport_constructor = gen_transport_constructor(&tp_clause, &ob_extra_param, &ob_expr);

    let loop_code = extract_loop_body(&def.body).map_or_else(
        || quote! {},
        |loop_body| {
            let il = gen_init_loop(loop_body);
            let rl = gen_resp_loop(loop_body);

            quote! {
                /// One iteration of the protocol loop (initiator side).
                pub type InitiatorLoop #tp_clause = #il;

                /// One iteration of the protocol loop (responder side).
                pub type ResponderLoop #tp_clause = #rl;

                /// Create a fresh loop iteration (μ-unfolding).
                pub fn renew_loop #tp_clause (
                    channel_id: u64,
                    #ob_extra_param
                ) -> (
                    Chan<Initiator, InitiatorLoop #tp_clause>,
                    Chan<Responder, ResponderLoop #tp_clause>,
                ) {
                    (
                        Chan::new_raw(channel_id, #ob_expr),
                        Chan::new_raw(channel_id, #ob_expr),
                    )
                }
            }
        },
    );

    quote! {
        #[allow(unused_imports, missing_docs)]
        #[allow(clippy::type_complexity)]
        pub mod #mod_name {
            use super::{Chan, End, Initiator, Offer, Recv, Responder, Select, Send, SessionTransport};
            use crate::record::ObligationKind;

            #(#msg_structs)*

            #loop_code
            #transport_constructor

            /// Initiator's session type.
            pub type InitiatorSession #tp_clause = #initiator_type;

            /// Responder's session type.
            pub type ResponderSession #tp_clause = #responder_type;

            /// Create a paired initiator/responder session.
            pub fn new_session #tp_clause (
                channel_id: u64,
                #ob_extra_param
            ) -> (
                Chan<Initiator, InitiatorSession #tp_clause>,
                Chan<Responder, ResponderSession #tp_clause>,
            ) {
                (
                    Chan::new_raw(channel_id, #ob_expr),
                    Chan::new_raw(channel_id, #ob_expr),
                )
            }
        }
    }
}

/// Entry point for the `session_protocol!` proc-macro.
pub fn session_protocol_impl(input: TokenStream) -> TokenStream {
    let def = parse_macro_input!(input as ProtocolDef);
    TokenStream::from(generate_protocol(&def))
}

// ============================================================================
// Tests
// ============================================================================

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

    fn parse_ok(input: proc_macro2::TokenStream) -> ProtocolDef {
        syn::parse2::<ProtocolDef>(input).expect("should parse")
    }

    fn parse_err(input: proc_macro2::TokenStream) -> String {
        match syn::parse2::<ProtocolDef>(input) {
            Err(e) => e.to_string(),
            Ok(_) => panic!("expected parse error but succeeded"),
        }
    }

    // -- Parsing --

    #[test]
    fn parse_simple_protocol() {
        let def = parse_ok(quote! {
            test_proto for SendPermit {
                msg Foo;
                send Foo => end
            }
        });
        assert_eq!(def.name, "test_proto");
        assert!(def.type_params.is_empty());
        assert!(matches!(&def.obligation, ObligationSpec::Fixed(v) if v == "SendPermit"));
        assert_eq!(def.messages.len(), 1);
        assert_eq!(def.messages[0].name, "Foo");
        assert!(def.messages[0].fields.is_empty());
    }

    #[test]
    fn parse_protocol_with_generics() {
        let def = parse_ok(quote! {
            proto<T> for SendPermit {
                send T => end
            }
        });
        assert_eq!(def.type_params.len(), 1);
        assert_eq!(def.type_params[0], "T");
    }

    #[test]
    fn parse_protocol_with_select() {
        let def = parse_ok(quote! {
            proto for SendPermit {
                msg Reserve;
                msg Abort;
                send Reserve => select {
                    send Reserve => end,
                    send Abort => end,
                }
            }
        });
        assert_eq!(def.messages.len(), 2);
        assert!(matches!(def.body, SessionBody::Send(_, _)));
    }

    #[test]
    fn parse_protocol_with_loop() {
        let def = parse_ok(quote! {
            proto for Lease {
                msg Acquire;
                msg Renew;
                msg Release;
                send Acquire => loop {
                    select {
                        send Renew => continue,
                        send Release => end,
                    }
                }
            }
        });
        assert_eq!(def.messages.len(), 3);
        // Body is Send(Acquire, Loop(Select(...)))
        match &def.body {
            SessionBody::Send(_, cont) => assert!(matches!(**cont, SessionBody::Loop(_))),
            _ => panic!("expected Send"),
        }
    }

    #[test]
    fn parse_message_with_fields() {
        let def = parse_ok(quote! {
            proto for IoOp {
                msg Reserve { kind: ObligationKind };
                msg Abort { reason: String };
                send Reserve => end
            }
        });
        assert_eq!(def.messages.len(), 2);
        assert_eq!(def.messages[0].fields.len(), 1);
        assert_eq!(def.messages[0].fields[0].name, "kind");
        assert_eq!(def.messages[1].fields.len(), 1);
        assert_eq!(def.messages[1].fields[0].name, "reason");
    }

    #[test]
    fn parse_protocol_with_offer() {
        parse_ok(quote! {
            proto for SendPermit {
                recv Foo => offer {
                    recv Bar => end,
                    recv Baz => end,
                }
            }
        });
    }

    #[test]
    fn parse_parameterized_obligation() {
        let def = parse_ok(quote! {
            proto(kind: ObligationKind) {
                send Foo => end
            }
        });
        assert!(matches!(&def.obligation, ObligationSpec::Param(n, _) if n == "kind"));
    }

    #[test]
    fn parse_error_continue_outside_loop() {
        let err = parse_err(quote! {
            proto for SendPermit {
                send Foo => continue
            }
        });
        assert!(err.contains("continue"), "error: {err}");
    }

    #[test]
    fn parse_error_nested_loop() {
        let err = parse_err(quote! {
            proto for SendPermit {
                loop { loop { end } }
            }
        });
        assert!(err.contains("nested"), "error: {err}");
    }

    #[test]
    fn parse_error_unknown_keyword() {
        let err = parse_err(quote! {
            proto for SendPermit {
                unknown Foo => end
            }
        });
        assert!(err.contains("unknown"), "error: {err}");
    }

    #[test]
    fn parse_error_missing_for() {
        let err = parse_err(quote! {
            proto { end }
        });
        assert!(err.contains("for"), "error: {err}");
    }

    #[test]
    fn parse_trailing_comma_in_select() {
        parse_ok(quote! {
            proto for SendPermit {
                select {
                    end,
                    end,
                }
            }
        });
    }

    // -- Code generation --

    #[test]
    fn gen_simple_produces_module() {
        let def = parse_ok(quote! {
            test_mod for SendPermit {
                msg Foo;
                send Foo => end
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(code.contains("pub mod test_mod"), "missing module: {code}");
        assert!(code.contains("InitiatorSession"), "missing type: {code}");
        assert!(code.contains("ResponderSession"), "missing type: {code}");
        assert!(code.contains("new_session"), "missing constructor: {code}");
        assert!(code.contains("pub struct Foo"), "missing message: {code}");
    }

    #[test]
    fn gen_dual_send_becomes_recv() {
        let def = parse_ok(quote! {
            proto for SendPermit {
                send Foo => end
            }
        });
        let code = generate_protocol(&def).to_string();
        // Initiator: Send<Foo, End>
        assert!(
            code.contains("Send < Foo"),
            "initiator missing Send: {code}"
        );
        // Responder: Recv<Foo, End> (dual)
        assert!(
            code.contains("Recv < Foo"),
            "responder missing Recv: {code}"
        );
    }

    #[test]
    fn gen_dual_select_becomes_offer() {
        let def = parse_ok(quote! {
            proto for SendPermit {
                select { end, end }
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(code.contains("Select"), "initiator missing Select: {code}");
        assert!(code.contains("Offer"), "responder missing Offer: {code}");
    }

    #[test]
    fn gen_loop_produces_renew() {
        let def = parse_ok(quote! {
            proto for Lease {
                loop {
                    select {
                        send Renew => continue,
                        send Release => end,
                    }
                }
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(code.contains("InitiatorLoop"), "missing loop type: {code}");
        assert!(code.contains("ResponderLoop"), "missing loop type: {code}");
        assert!(code.contains("renew_loop"), "missing renew fn: {code}");
    }

    #[test]
    fn gen_no_loop_skips_renew() {
        let def = parse_ok(quote! {
            proto for SendPermit {
                send Foo => end
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(
            !code.contains("renew_loop"),
            "should not have renew: {code}"
        );
        assert!(
            !code.contains("InitiatorLoop"),
            "should not have loop type: {code}"
        );
    }

    #[test]
    fn gen_transport_constructor() {
        let def = parse_ok(quote! {
            proto for SendPermit {
                send Foo => end
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(
            code.contains("new_session_with_transport"),
            "missing transport constructor: {code}"
        );
        assert!(
            code.contains("Chan :: new_with_transport"),
            "transport constructor should wire transport-backed channels: {code}"
        );
    }

    #[test]
    fn gen_generic_protocol() {
        let def = parse_ok(quote! {
            proto<T> for SendPermit {
                msg Reserve;
                send Reserve => select {
                    send T => end,
                    send Reserve => end,
                }
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(
            code.contains("InitiatorSession < T >"),
            "missing generic session type: {code}"
        );
        assert!(
            code.contains("new_session < T >"),
            "missing generic constructor: {code}"
        );
    }

    #[test]
    fn gen_message_with_fields_not_copy() {
        let def = parse_ok(quote! {
            proto for IoOp {
                msg Abort { reason: String };
                send Abort => end
            }
        });
        let code = generate_protocol(&def).to_string();
        // Struct with fields should derive Debug, Clone but NOT Copy
        assert!(code.contains("Debug , Clone"), "missing derives: {code}");
        // Check it's not deriving Copy (the word Copy should not appear
        // near the struct definition for field-bearing messages)
        let abort_section = code.split("pub struct Abort").nth(1).unwrap_or("");
        // The derive for this struct should NOT include Copy
        assert!(
            !abort_section.starts_with(" ;"), // has fields, not unit
            "should have fields: {code}"
        );
    }

    #[test]
    fn gen_unit_message_is_copy() {
        let def = parse_ok(quote! {
            proto for SendPermit {
                msg Foo;
                send Foo => end
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(
            code.contains("Debug , Clone , Copy"),
            "unit struct should be Copy: {code}"
        );
    }

    #[test]
    fn gen_obligation_kind_in_constructor() {
        let def = parse_ok(quote! {
            proto for Lease {
                send Foo => end
            }
        });
        let code = generate_protocol(&def).to_string();
        assert!(
            code.contains("ObligationKind :: Lease"),
            "wrong obligation: {code}"
        );
    }

    #[test]
    fn gen_parameterized_obligation_in_constructor() {
        let def = parse_ok(quote! {
            proto(kind: ObligationKind) {
                send Foo => end
            }
        });
        let code = generate_protocol(&def).to_string();
        // Constructor should take `kind` parameter
        assert!(
            code.contains("kind : ObligationKind"),
            "missing param: {code}"
        );
        // Should use `kind` directly, not `ObligationKind::kind`
        assert!(
            !code.contains("ObligationKind :: kind"),
            "should use param directly: {code}"
        );
    }
}