id_effect_proc_macro 0.3.0

Procedural `effect!` macro for the `effect` crate (proc-macro only; declarative macros live in `id_effect_macro`)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
//! Token-recursive expansion for `effect!` bodies.
//!
//! ## Operator
//!
//! `~expr` is a unary prefix "run-effect" operator — analogous to unary `-`. It expands to:
//!
//! ```text
//! (::id_effect::cap_into_bind(expr, r).await?)
//! ```
//!
//! `~` can appear anywhere a Rust expression can appear: in `let` bindings, conditions,
//! function arguments, match arms, nested blocks, etc.
//!
//! ## Block structure
//!
//! The outermost `effect!` body is split on top-level `;` to identify statement chunks and the
//! tail expression. `~` is expanded recursively in every chunk. The tail is wrapped in
//! `Result::Ok(...)`. If the body contains no `~`, the proc macro uses `Effect::new` (sync
//! `FnOnce(&mut R) -> Result<...>`); otherwise it uses `Effect::new_async` with
//! `Box::pin(async move { ... })` so `.await` on `cap_into_bind` is valid.
//!
//! Nested `{ }` blocks have their `~` expanded in-place but are **not** given an additional
//! `Ok(tail)` wrapper — they are plain Rust blocks, not effect blocks.
//!
//! ## Infix bind (`ident ~ expr`)
//!
//! At the start of a statement chunk, `name ~ expr` desugars to `let name = ~expr` before
//! prefix-`~` expansion (so Kelly-style `k ~ foo();` works).
//!
//! ## Precedence and method chains
//!
//! `~` binds to the immediately following primary expression (the call or path up to the
//! next call group). Method chains that follow belong to the outer expression:
//!
//! ```text
//! ~foo().bar   →   (into_bind(foo(), r).await?).bar
//! ```
//!
//! ## Known limitation
//!
//! The turbofish `>>` token (as in `Vec<Vec<u8>>`) is a single `Punct` in the token stream;
//! the angle-depth tracker does not handle it. This edge case is rare in effect call sites.

use proc_macro2::{Delimiter, TokenStream, TokenTree};
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{Expr, Type};

/// Returns `true` if the `effect!` body uses effect bind (`~`) anywhere (including nested groups).
///
/// Bind-free bodies expand to `Effect::new` instead of `Effect::new_async`, avoiding an `async`
/// state machine and `Box::pin` for the outer effect.
pub fn effect_body_contains_bind(tokens: TokenStream) -> bool {
  for tt in tokens {
    match tt {
      TokenTree::Punct(p) if p.as_char() == '~' => return true,
      TokenTree::Group(g) if effect_body_contains_bind(g.stream()) => return true,
      TokenTree::Group(_) => {}
      _ => {}
    }
  }
  false
}

/// Returns `true` if the body contains a `.await` that is **not** inside an `async` / `async move`
/// block.
///
/// `.await` nested only in `async move { ... }` (e.g. closures passed to `stream::unfold`) does
/// not require wrapping the whole `effect!` body in `async move` — the outer closure can stay
/// sync (`Effect::new`). Misclassifying those bodies as async breaks `Send` on streams that close
/// over non-`Send` effect HTTP futures.
///
/// Top-level `.await` (Drift connect, `cap_into_bind`, etc.) must use [`Effect::new_async`].
pub fn effect_body_contains_await(tokens: TokenStream) -> bool {
  fn walk(
    mut iter: std::iter::Peekable<impl Iterator<Item = TokenTree>>,
    mut prev_dot: bool,
  ) -> bool {
    // `peek` / extra `next` in the `async` arm need the same `Peekable` as this advance.
    #[allow(clippy::while_let_on_iterator)]
    while let Some(tt) = iter.next() {
      match tt {
        TokenTree::Punct(p) if p.as_char() == '.' => {
          prev_dot = true;
        }
        TokenTree::Ident(i) if i == "await" && prev_dot => return true,
        TokenTree::Ident(i) if i == "async" => {
          prev_dot = false;
          if matches!(iter.peek(), Some(TokenTree::Ident(m)) if m == "move") {
            iter.next();
          }
          match iter.next() {
            Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Brace => {
              // Skip `async [move] { ... }` and optional `.await` on that expr (`async { }.await`).
              if matches!(iter.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '.') {
                iter.next();
                if matches!(iter.peek(), Some(TokenTree::Ident(a)) if a == "await") {
                  iter.next();
                }
              }
            }
            Some(TokenTree::Group(g)) if walk(g.stream().into_iter().peekable(), false) => {
              return true;
            }
            Some(TokenTree::Group(_)) => {}
            Some(_) => {}
            None => {}
          }
        }
        TokenTree::Ident(_) => {
          prev_dot = false;
        }
        TokenTree::Group(g) => {
          if walk(g.stream().into_iter().peekable(), false) {
            return true;
          }
          prev_dot = false;
        }
        _ => {
          prev_dot = false;
        }
      }
    }
    false
  }

  walk(tokens.into_iter().peekable(), false)
}

/// Expand an `effect!(|r: &mut R| { ... })` body.
pub fn expand_closure_body(body: TokenStream, r: &syn::Ident, path: &TokenStream) -> TokenStream {
  expand_block(body, r, path)
}

/// Expand an `effect! { ... }` (bare) body, using `__effect_r` as the environment binding.
pub fn expand_bare_body(body: TokenStream, path: &TokenStream) -> TokenStream {
  let r = syn::Ident::new("__effect_r", proc_macro2::Span::call_site());
  expand_block(body, &r, path)
}

/// When the body tail is exactly one `~operand` (after ident-desugar), the async effect body should
/// return `into_bind(operand, r).await` directly. Wrapping `Ok((into_bind(...).await?))` triggers
/// `clippy::needless_question_mark` (the `?` + outer `Ok` cancel for `Result` tails).
fn try_expand_tail_as_into_bind_await(
  tail: TokenStream,
  r: &syn::Ident,
  path: &TokenStream,
) -> Option<TokenStream> {
  let mut iter = tail.into_iter().peekable();
  match iter.next()? {
    TokenTree::Punct(p) if p.as_char() == '~' => {}
    _ => return None,
  }
  let operand = collect_tilde_operand(&mut iter);
  if iter.next().is_some() {
    return None;
  }
  let expanded_operand = expand_tilde(operand, r, path);
  Some(quote! { #path::cap_into_bind(#expanded_operand, #r).await })
}

/// Split the outermost body on top-level `;`, expand `~` in each chunk, wrap tail in `Ok(...)`.
fn expand_block(body: TokenStream, r: &syn::Ident, path: &TokenStream) -> TokenStream {
  let chunks = split_semicolons(body);
  if chunks.is_empty() {
    return quote! { ::core::result::Result::Ok(()) };
  }

  let n = chunks.len();
  let mut stmts = Vec::new();
  for chunk in &chunks[..n - 1] {
    if chunk.is_empty() {
      continue;
    }
    let chunk = desugar_ident_tilde_bind(chunk.clone());
    let expanded = expand_tilde(chunk, r, path);
    stmts.push(quote! { #expanded ; });
  }

  let tail = &chunks[n - 1];
  if tail.is_empty() {
    quote! {
      #(#stmts)*
      ::core::result::Result::Ok(())
    }
  } else {
    let tail = desugar_ident_tilde_bind(tail.clone());
    if let Some(direct_tail) = try_expand_tail_as_into_bind_await(tail.clone(), r, path) {
      quote! {
        #(#stmts)*
        #direct_tail
      }
    } else {
      let expanded_tail = expand_tilde(tail, r, path);
      quote! {
        #(#stmts)*
        ::core::result::Result::Ok(#expanded_tail)
      }
    }
  }
}

/// `name ~ rest…` at chunk start → `let name = ~ rest…` (then [`expand_tilde`] handles `~`).
fn desugar_ident_tilde_bind(chunk: TokenStream) -> TokenStream {
  let v: Vec<TokenTree> = chunk.into_iter().collect();
  if v.len() < 2 {
    return TokenStream::from_iter(v);
  }
  match (&v[0], &v[1]) {
    (TokenTree::Ident(name), TokenTree::Punct(p)) if p.as_char() == '~' => {
      let name = name.clone();
      let rest = TokenStream::from_iter(v.into_iter().skip(2));
      quote! { let #name = ~ #rest }
    }
    _ => TokenStream::from_iter(v),
  }
}

struct RequireArgs {
  env: Option<Expr>,
  key: Type,
}

impl Parse for RequireArgs {
  fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
    let fork = input.fork();
    if fork.parse::<Expr>().is_ok() && fork.parse::<syn::Token![,]>().is_ok() {
      let env = input.parse::<Expr>()?;
      input.parse::<syn::Token![,]>()?;
      let key = input.parse::<Type>()?;
      Ok(RequireArgs {
        env: Some(env),
        key,
      })
    } else {
      let key = input.parse::<Type>()?;
      Ok(RequireArgs { env: None, key })
    }
  }
}

/// Expand `require!(Key)` to `Needs::<Key>::need(env)`.
fn expand_require_invocation(
  iter: &mut std::iter::Peekable<impl Iterator<Item = TokenTree>>,
  r: &syn::Ident,
  path: &TokenStream,
) -> TokenStream {
  match iter.next() {
    Some(TokenTree::Punct(p)) if p.as_char() == '!' => {}
    _ => return quote! { require },
  }

  let group = match iter.next() {
    Some(TokenTree::Group(g)) if g.delimiter() == Delimiter::Parenthesis => g,
    other => {
      return syn::Error::new_spanned(
        other.unwrap_or_else(|| {
          TokenTree::Punct(proc_macro2::Punct::new('!', proc_macro2::Spacing::Alone))
        }),
        "effect!: `require!` expects `require!(Key)` — `require!(env, Key)` was removed in 3.0",
      )
      .to_compile_error();
    }
  };

  match syn::parse2::<RequireArgs>(group.stream()) {
    Ok(args) => {
      if args.env.is_some() {
        return syn::Error::new_spanned(
          group,
          "require!(env, Key) was removed in id_effect 3.0; use require!(Key) inside effect!",
        )
        .to_compile_error();
      }
      let key = args.key;
      expand_tilde(quote! { #path::Needs::<#key>::need(#r) }, r, path)
    }
    Err(e) => e.to_compile_error(),
  }
}

/// Recursively walk `tokens`, rewriting every `~primary` as
/// `(::id_effect::cap_into_bind(primary, r).await?)` and `require!(Key)` as env lookup.
///
/// Recurses into `{ }`, `( )`, and `[ ]` groups so `~` is expanded at any nesting depth.
/// Nested groups are **not** given `Ok(tail)` wrapping — that is only for the outermost body.
fn expand_tilde(tokens: TokenStream, r: &syn::Ident, path: &TokenStream) -> TokenStream {
  let mut out = Vec::new();
  let mut iter = tokens.into_iter().peekable();

  // Operand collection calls `next`/`peek` on the same `Peekable` as this advance.
  #[allow(clippy::while_let_on_iterator)]
  while let Some(tt) = iter.next() {
    match &tt {
      TokenTree::Ident(i)
        if i == "require"
          && matches!(iter.peek(), Some(TokenTree::Punct(p)) if p.as_char() == '!') =>
      {
        out.extend(expand_require_invocation(&mut iter, r, path));
      }

      TokenTree::Punct(p) if p.as_char() == '~' => {
        let operand = collect_tilde_operand(&mut iter);
        if is_capability_key_operand(&operand) {
          out.extend(expand_tilde(
            quote! { #path::Needs::<#operand>::need(#r) },
            r,
            path,
          ));
        } else {
          // Recurse so nested `~` inside the operand is also expanded.
          let expanded_operand = expand_tilde(operand, r, path);
          let bound = quote! { #path::cap_into_bind(#expanded_operand, #r).await? };
          let group = proc_macro2::Group::new(Delimiter::Parenthesis, bound);
          out.push(TokenTree::Group(group));
        }
      }

      TokenTree::Group(g) => {
        let expanded_inner = expand_tilde(g.stream(), r, path);
        let new_group = proc_macro2::Group::new(g.delimiter(), expanded_inner);
        out.push(TokenTree::Group(new_group));
      }

      other => out.push(other.clone()),
    }
  }

  TokenStream::from_iter(out)
}

/// True when `~operand` is capability lookup (`~DatabaseKey`), not effect bind (`~query(1)`).
pub fn is_capability_key_operand(operand: &TokenStream) -> bool {
  if operand_has_top_level_call(operand) {
    return false;
  }
  let Ok(ty) = syn::parse2::<syn::Type>(operand.clone()) else {
    return false;
  };
  type_path_last_segment_ends_with_key(&ty)
}

fn operand_has_top_level_call(operand: &TokenStream) -> bool {
  let mut depth = 0usize;
  for tt in operand.clone() {
    match tt {
      TokenTree::Group(g) if g.delimiter() == Delimiter::Parenthesis && depth == 0 => return true,
      TokenTree::Punct(p) if p.as_char() == '<' => depth += 1,
      TokenTree::Punct(p) if p.as_char() == '>' && depth > 0 => depth -= 1,
      _ => {}
    }
  }
  false
}

fn type_path_last_segment_ends_with_key(ty: &syn::Type) -> bool {
  let path = match ty {
    syn::Type::Path(p) => &p.path,
    _ => return false,
  };
  let Some(seg) = path.segments.last() else {
    return false;
  };
  seg.ident.to_string().ends_with("Key")
}

/// Collect the operand of a `~` prefix operator.
///
/// `~` binds to the entire expression chain that follows it: idents, paths (`::`, `<...>`),
/// call/index groups, and method chains (`.method(...)`). Collection stops only at:
///
/// - `,` at depth 0 — argument separator in the surrounding call
/// - `>` at depth 0 — closing angle bracket of the enclosing turbofish
/// - end of the token stream (the containing chunk already had `;` stripped by `expand_block`)
///
/// Turbofish `::< >` sequences are tracked so commas and `>` inside generic arguments are
/// not treated as terminators.
///
/// Examples (all collected as one operand, no parens needed):
/// - `~succeed(40)` → `succeed(40)`
/// - `~raw.parse::<i32>().map_err(|e| ...)` → `raw.parse::<i32>().map_err(|e| ...)`
/// - `~parse_i32(s).map_error(f).catch(g)` → `parse_i32(s).map_error(f).catch(g)`
pub fn collect_tilde_operand(
  iter: &mut std::iter::Peekable<impl Iterator<Item = TokenTree>>,
) -> TokenStream {
  let mut result = Vec::new();
  let mut angle_depth: usize = 0;

  loop {
    match iter.peek() {
      None => break,

      Some(TokenTree::Punct(p)) => {
        match (p.as_char(), angle_depth) {
          // `,` at top level: argument separator — belongs to the surrounding call.
          (',', 0) => break,
          // `;` at top level: statement separator — belongs to the surrounding block.
          (';', 0) => break,
          // Open turbofish `<`.
          ('<', _) => {
            angle_depth += 1;
            result.push(iter.next().unwrap());
          }
          // Close turbofish `>` while inside angle brackets.
          ('>', d) if d > 0 => {
            angle_depth -= 1;
            result.push(iter.next().unwrap());
          }
          // `>` at depth 0 closes the surrounding turbofish — stop.
          ('>', 0) => break,
          // Everything else (`.`, `::`, `?`, operators, …) is part of the expression.
          _ => result.push(iter.next().unwrap()),
        }
      }

      // `( )` and `[ ]` groups are self-contained call-arg / index expressions — consume them.
      // `{ }` brace groups are block statements that follow an expression, not part of it — stop.
      Some(TokenTree::Group(g)) if g.delimiter() != Delimiter::Brace => {
        result.push(iter.next().unwrap());
      }
      Some(TokenTree::Group(_)) => break,

      Some(_) => result.push(iter.next().unwrap()),
    }
  }

  TokenStream::from_iter(result)
}

/// Returns `true` when `tt` is an identifier that starts a Rust block expression:
/// `if`, `while`, `for`, `loop`, `match`, `async`, or `unsafe`.
/// These expressions end with a `}` brace group and can be used as statements
/// without a trailing `;`, unlike ordinary expressions.
fn is_block_stmt_keyword(tt: &TokenTree) -> bool {
  match tt {
    TokenTree::Ident(id) => matches!(
      id.to_string().as_str(),
      "if" | "while" | "for" | "loop" | "match" | "async" | "unsafe"
    ),
    _ => false,
  }
}

/// Split `stream` on top-level `;`. Groups are opaque — inner `;` are not split on.
///
/// Additionally, a top-level `{ }` brace group that closes a **block-type expression**
/// (one whose first token is `if`, `while`, `for`, `loop`, `match`, `async`, or `unsafe`)
/// is treated as an implicit statement boundary, matching Rust's rule that these
/// expressions can appear as statements without a trailing `;`.
///
/// The split is suppressed when:
/// - the next token is `else` (the expression continues with an else-branch), or
/// - the brace group is the last token in the stream (it is the tail expression, not a statement).
fn split_semicolons(stream: TokenStream) -> Vec<TokenStream> {
  let mut out = Vec::new();
  let mut cur: Vec<TokenTree> = Vec::new();
  let mut iter = stream.into_iter().peekable();

  // Brace handling uses `peek` on the token after the current one.
  #[allow(clippy::while_let_on_iterator)]
  while let Some(tt) = iter.next() {
    let is_semicolon = matches!(&tt, TokenTree::Punct(p) if p.as_char() == ';');
    let is_brace = matches!(&tt, TokenTree::Group(g) if g.delimiter() == Delimiter::Brace);

    if is_semicolon {
      out.push(TokenStream::from_iter(cur.drain(..)));
    } else if is_brace {
      let first_is_block_kw = cur.first().is_some_and(is_block_stmt_keyword);
      cur.push(tt);
      let next = iter.peek();
      let continues_with_else =
        matches!(next, Some(TokenTree::Ident(id)) if id.to_string().as_str() == "else");
      let at_end_of_stream = next.is_none();
      if first_is_block_kw && !continues_with_else && !at_end_of_stream {
        out.push(TokenStream::from_iter(cur.drain(..)));
      }
    } else {
      cur.push(tt);
    }
  }

  out.push(TokenStream::from_iter(cur));
  out
}

#[cfg(test)]
mod tests {
  #![allow(unused_imports)]

  //! Coverage map for [`super`] (token transform for `effect!` bodies).
  //!
  //! ## Entry points
  //! - [`expand_bare_body`]: fixed env ident `__effect_r` (bare `effect! { ... }`).
  //! - [`expand_closure_body`]: caller-supplied `r` (`effect!(|r: &mut R| { ... })`).
  //!
  //! Both delegate to [`expand_block`].
  //!
  //! ## [`expand_block`] (combine with `split_semicolons` + per-chunk pipeline)
  //! - **`chunks.is_empty()`** — defensive; [`split_semicolons`] always pushes at least one chunk
  //!   (even for an empty stream), so this path is not reachable from the public expanders today.
  //! - **`n == 1`, tail empty** — e.g. empty body, or only top-level `;` / `;;` leaving final chunk empty.
  //! - **`n == 1`, tail non-empty** — single chunk, tail wrapped in `Result::Ok(tail)`.
  //! - **`n > 1`** — statement chunks: each non-empty chunk → `desugar_ident_tilde_bind` → `expand_tilde` →
  //!   stmt + `;`; last chunk is tail (`Ok` or `Ok(())` if empty).
  //! - **Empty non-final chunks** — skipped (`continue`), e.g. `;;` or leading `;`.
  //!
  //! ## [`split_semicolons`] (top-level `;` only)
  //! - Split on `TokenTree::Punct` `;` **outside** any `Group`; delimiters `{ }` `( )` `[ ]` are opaque.
  //!
  //! ## [`desugar_ident_tilde_bind`] (infix bind at chunk start)
  //! - **`< 2` tokens** — passthrough unchanged.
  //! - **`ident` + `~`** — rewrite to `let ident = ~ rest`.
  //! - **Else** — passthrough (not `ident~` at start).
  //!
  //! ## [`expand_tilde`] (prefix `~` anywhere in token tree)
  //! - **`~`** — replace with `(path::into_bind(operand, r).await?)` (parenthesized group); operand from
  //!   [`collect_tilde_operand`]; recurse into operand. The **sole** body tail `~operand` (see
  //!   [`try_expand_tail_as_into_bind_await`]) omits the inner `?` and outer `Ok` so the async block
  //!   returns `Result` directly (avoids `clippy::needless_question_mark`).
  //! - **`Group`** — recurse into inner stream, same delimiter.
  //! - **Other tokens** — copy through.
  //!
  //! ## [`collect_tilde_operand`] (what binds to prefix `~`)
  //! - **End of stream** — operand ends.
  //! - **`,` at `angle_depth == 0`** — stop (outer arg separator).
  //! - **`<`** — increment `angle_depth` (turbofish / generics).
  //! - **`>` with `angle_depth > 0`** — decrement (close generic angle).
  //! - **`>` with `angle_depth == 0`** — stop (closing enclosing turbofish from caller context).
  //! - **Any other punct** — part of operand (e.g. `.`, `::`, `?`).
  //! - **`Group`** — always consume whole group.
  //! - **Non-punct** — consume (ident, literal, …).
  //! - **Known limitation** — `>>` in `Vec<Vec<u8>>` is one `Punct` token; depth tracker does not model it.

  use super::*;
  use quote::quote;

  macro_rules! assert_ts_eq {
    ($a:expr, $e:expr) => {{
      let a = ($a).to_string();
      let e = ($e).to_string();
      assert_eq!(a, e, "\nactual:\n{a}\n\nexpected:\n{e}\n");
    }};
  }

  /// [`collect_tilde_operand`] expects the iterator *after* the `~` token.
  fn operand_after_tilde_prefix(full: TokenStream) -> TokenStream {
    let mut iter = full.into_iter().peekable();
    match iter.next() {
      Some(TokenTree::Punct(p)) if p.as_char() == '~' => collect_tilde_operand(&mut iter),
      o => panic!("expected leading `~`, got {o:?}"),
    }
  }

  fn r_custom() -> syn::Ident {
    syn::Ident::new("my_r", proc_macro2::Span::call_site())
  }

  #[test]
  fn effect_body_contains_bind_false_without_tilde() {
    assert!(!effect_body_contains_bind(quote! { let x = 1; x + 2 }));
  }

  #[test]
  fn effect_body_contains_bind_true_with_prefix_tilde() {
    assert!(effect_body_contains_bind(quote! { ~g() }));
  }

  #[test]
  fn effect_body_contains_bind_true_in_nested_group() {
    assert!(effect_body_contains_bind(
      quote! { if true { ~x() } else { 0 } }
    ));
  }

  // ---------------------------------------------------------------------------
  // expand_bare_body — integration: `__effect_r` + expand_block
  // ---------------------------------------------------------------------------
  mod expand_bare_body {
    use super::*;

    /// Branch: single final chunk empty after split → `Result::Ok(())`, no statements.
    mod with_empty_body {
      use super::*;

      #[test]
      fn returns_ok_unit() {
        let path = quote! { ::id_effect };
        let body = TokenStream::new();
        let out = expand_bare_body(body, &path);
        let expected = quote! { ::core::result::Result::Ok(()) };
        assert_eq!(out.to_string(), expected.to_string());
      }
    }

    /// Branch: `n == 1`, tail non-empty, no `~` → `Ok(tail)` only.
    mod with_tail_having_no_tilde_operator {
      use super::*;

      #[test]
      fn wraps_expression_in_ok() {
        let path = quote! { ::id_effect };
        let body = quote! { 41 };
        let out = expand_bare_body(body, &path);
        let expected = quote! { ::core::result::Result::Ok(41) };
        assert_eq!(out.to_string(), expected.to_string());
      }
    }

    /// Permutation: one top-level `;` with nothing after → final chunk empty → `Ok(())`.
    mod with_trailing_top_level_semicolon_only {
      use super::*;

      #[test]
      fn yields_ok_unit_with_empty_tail() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { ; }, &path);
        let expected = quote! { ::core::result::Result::Ok(()) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Permutation: `stmt;` then tail — one statement chunk + final tail chunk.
    mod with_one_statement_chunk_then_tail {
      use super::*;

      #[test]
      fn emits_statement_then_ok_wrapped_tail() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { let _x = 1 ; 2 }, &path);
        let expected = quote! {
          let _x = 1 ;
          ::core::result::Result::Ok(2)
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Permutation: multiple `stmt;` … `tail` — several non-final chunks + tail.
    mod with_multiple_statement_chunks_then_tail {
      use super::*;

      #[test]
      fn emits_each_statement_then_ok_wrapped_tail() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { 1 ; 2 ; 3 }, &path);
        let expected = quote! {
          1 ;
          2 ;
          ::core::result::Result::Ok(3)
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Branch: empty non-final chunks skipped — e.g. leading `;`, `;;`, or `a;;b` middle empty chunk.
    mod with_empty_chunks_from_leading_or_duplicate_semicolons {
      use super::*;

      #[test]
      fn skips_empty_first_chunk() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { ; 1 }, &path);
        let expected = quote! { ::core::result::Result::Ok(1) };
        assert_ts_eq!(out, expected);
      }

      #[test]
      fn skips_empty_middle_chunks() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { 1 ;; 2 }, &path);
        let expected = quote! {
          1 ;
          ::core::result::Result::Ok(2)
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Permutation: `;` only inside `{ ... }` — no extra top-level chunks from inner `;`.
    mod with_semicolon_only_inside_brace_group {
      use super::*;

      #[test]
      fn does_not_split_on_inner_semicolon() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { { 1 ; 2 } }, &path);
        let expected = quote! { ::core::result::Result::Ok({ 1 ; 2 }) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Permutation: inner `;` inside `( ... )` / `[ ... ]` — same opacity as braces.
    mod with_semicolon_only_inside_paren_or_bracket_group {
      use super::*;

      #[test]
      fn does_not_split_inside_paren_group() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { ( 1 ; 2 ) }, &path);
        let expected = quote! { ::core::result::Result::Ok(( 1 ; 2 )) };
        assert_ts_eq!(out, expected);
      }

      #[test]
      fn does_not_split_inside_bracket_group() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { [ 1 ; 2 ] }, &path);
        let expected = quote! { ::core::result::Result::Ok([ 1 ; 2 ]) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Syntax: `ident ~ expr` at start of a **statement** chunk → `let` + prefix `~` expansion.
    mod with_ident_tilde_bind_on_statement_chunk {
      use super::*;

      #[test]
      fn desugars_to_let_and_cap_into_bind() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { k ~ foo ( ) ; 1 }, &path);
        let expected = quote! {
          let k = (::id_effect::cap_into_bind(foo(), __effect_r).await?) ;
          ::core::result::Result::Ok(1)
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Syntax: `ident ~ expr` when that chunk is the **tail** — same desugar, tail wrapped in `Ok`.
    mod with_ident_tilde_bind_on_tail_chunk {
      use super::*;

      #[test]
      fn desugars_and_wraps_tail_in_ok() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { k ~ foo ( ) }, &path);
        let expected = quote! {
          ::core::result::Result::Ok(let k = (::id_effect::cap_into_bind(foo(), __effect_r).await?))
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Syntax: prefix `~` only on tail — `cap_into_bind(..., __effect_r)`.
    mod with_prefix_tilde_on_tail_simple_call {
      use super::*;

      #[test]
      fn expands_tilde_tail_to_cap_into_bind_await_without_ok_wrap() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { ~ foo ( ) }, &path);
        let expected = quote! {
          ::id_effect::cap_into_bind(foo(), __effect_r).await
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Syntax: `~path::segment(args)` / `~ident` — operand collection to end or group boundary.
    mod with_prefix_tilde_path_and_call_shapes {
      use super::*;

      #[test]
      fn expands_path_call() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { ~ bar :: baz ( ) }, &path);
        let expected = quote! {
          ::id_effect::cap_into_bind(bar::baz(), __effect_r).await
        };
        assert_ts_eq!(out, expected);
      }

      #[test]
      fn expands_plain_ident_operand() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { ~ x }, &path);
        let expected = quote! {
          ::id_effect::cap_into_bind(x, __effect_r).await
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Syntax: turbofish `~expr::method::<T>()` — angle depth in [`collect_tilde_operand`].
    mod with_prefix_tilde_turbofish_and_method_chain {
      use super::*;

      #[test]
      fn includes_turbofish_and_following_method_chain_in_operand() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(
          quote! { ~ raw . parse :: < i32 > ( ) . map_err ( | e | e ) },
          &path,
        );
        let expected = quote! {
          ::id_effect::cap_into_bind(raw.parse::<i32>().map_err(|e| e), __effect_r).await
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Operand stops at outer comma inside a parenthesized group (depth-0 comma).
    mod with_prefix_tilde_comma_terminator_at_depth_zero {
      use super::*;

      #[test]
      fn truncates_operand_before_following_comma() {
        let path = quote! { ::id_effect };
        let r = syn::Ident::new("__effect_r", proc_macro2::Span::call_site());
        let out = expand_tilde(quote! { ( ~ x , y ) }, &r, &path);
        let expected = quote! { ((::id_effect::cap_into_bind(x, __effect_r).await?), y) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Syntax: nested `~` inside operand (recursion in [`expand_tilde`]).
    mod with_nested_prefix_tilde_inside_operand {
      use super::*;

      #[test]
      fn expands_inner_tilde_first() {
        let path = quote! { ::id_effect };
        let r = syn::Ident::new("__effect_r", proc_macro2::Span::call_site());
        let out = expand_tilde(quote! { ~ ~ foo ( ) }, &r, &path);
        let expected = quote! {
          (::id_effect::cap_into_bind((::id_effect::cap_into_bind(foo(), __effect_r).await?), __effect_r).await?)
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Syntax: `~` inside nested `{ }` / `( )` / `[ ]` — expanded in place, **no** extra outer `Ok` on block.
    mod with_prefix_tilde_inside_nested_groups {
      use super::*;

      #[test]
      fn expands_inside_brace_group() {
        let path = quote! { ::id_effect };
        let r = syn::Ident::new("__effect_r", proc_macro2::Span::call_site());
        let out = expand_tilde(quote! { { ~ a ( ) } }, &r, &path);
        let expected = quote! { { (::id_effect::cap_into_bind(a(), __effect_r).await?) } };
        assert_ts_eq!(out, expected);
      }

      #[test]
      fn expands_inside_paren_group() {
        let path = quote! { ::id_effect };
        let r = syn::Ident::new("__effect_r", proc_macro2::Span::call_site());
        let out = expand_tilde(quote! { ( ~ b ( ) ) }, &r, &path);
        let expected = quote! { ((::id_effect::cap_into_bind(b(), __effect_r).await?)) };
        assert_ts_eq!(out, expected);
      }

      #[test]
      fn expands_inside_bracket_group() {
        let path = quote! { ::id_effect };
        let r = syn::Ident::new("__effect_r", proc_macro2::Span::call_site());
        let out = expand_tilde(quote! { [ ~ c ( ) ] }, &r, &path);
        let expected = quote! { [(::id_effect::cap_into_bind(c(), __effect_r).await?)] };
        assert_ts_eq!(out, expected);
      }
    }

    /// Permutation: non-`::effect` `path` token tree — `cap_into_bind` uses provided path prefix.
    mod with_custom_crate_path_token_stream {
      use super::*;

      #[test]
      fn uses_path_prefix_in_cap_into_bind() {
        let path = quote! { ::my_effect };
        let out = expand_bare_body(quote! { ~ z ( ) }, &path);
        let expected = quote! {
          ::my_effect::cap_into_bind(z(), __effect_r).await
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Two separate `>` tokens: collection stops after the first closing `>`, leaving `> ()` outside
    /// the `cap_into_bind` operand (see module docs on turbofish / `>>`).
    mod with_double_angle_bracket_turbofish_limitation {
      use super::*;

      #[test]
      fn does_not_match_ideal_operand_boundary() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { ~ v :: < u8 > > ( ) }, &path);
        let expected = quote! {
          ::core::result::Result::Ok((::id_effect::cap_into_bind(v::<u8>, __effect_r).await?) > ())
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// `if cond { ~f(); } tail` — the idiomatic Rust pattern: an `if` block used as
    /// a statement (no trailing `;` needed) followed by a return-value tail expression.
    /// `~` inside the if-body are expanded; the tail is wrapped in `Ok(...)`.
    mod with_if_block_statement_then_tail {
      use super::*;

      #[test]
      fn expands_tilde_in_if_body_and_ok_wraps_tail() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(quote! { if cond { ~ f ( ) ; } A :: default ( ) }, &path);
        let expected = quote! {
          if cond { (::id_effect::cap_into_bind(f(), __effect_r).await?) ; } ;
          ::core::result::Result::Ok(A :: default ())
        };
        assert_ts_eq!(out, expected);
      }

      /// Multiple `~` statements inside the if-body, all expanded correctly.
      #[test]
      fn expands_multiple_tildes_in_if_body_and_ok_wraps_tail() {
        let path = quote! { ::id_effect };
        let out = expand_bare_body(
          quote! { if n < 2 { ~ log_warn ( "msg" ) ; ~ fail ( err ) ; } A :: default ( ) },
          &path,
        );
        let expected = quote! {
          if n < 2 {
            (::id_effect::cap_into_bind(log_warn("msg"), __effect_r).await?) ;
            (::id_effect::cap_into_bind(fail(err), __effect_r).await?) ;
          } ;
          ::core::result::Result::Ok(A :: default ())
        };
        assert_ts_eq!(out, expected);
      }
    }
  }

  // ---------------------------------------------------------------------------
  // expand_closure_body — integration: caller-supplied `r` ident (same block logic as bare)
  // ---------------------------------------------------------------------------
  mod expand_closure_body {
    use super::*;

    /// Same as bare empty body but `into_bind(..., r)` must use the given ident, not `__effect_r`.
    mod with_empty_body {
      use super::*;

      #[test]
      fn yields_ok_unit_using_param_ident() {
        let path = quote! { ::id_effect };
        let r = r_custom();
        let out = expand_closure_body(TokenStream::new(), &r, &path);
        let expected = quote! { ::core::result::Result::Ok(()) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Same as bare literal tail; closure `r` appears in `cap_into_bind` when `~` is present.
    mod with_tail_having_no_tilde_operator {
      use super::*;

      #[test]
      fn wraps_expression_in_ok_like_bare() {
        let path = quote! { ::id_effect };
        let r = r_custom();
        let out = expand_closure_body(quote! { 41 }, &r, &path);
        let expected = quote! { ::core::result::Result::Ok(41) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Parity: statement + tail with custom `r`.
    mod with_one_statement_chunk_then_tail {
      use super::*;

      #[test]
      fn emits_statement_then_ok_wrapped_tail() {
        let path = quote! { ::id_effect };
        let r = r_custom();
        let out = expand_closure_body(quote! { 1 ; 2 }, &r, &path);
        let expected = quote! {
          1 ;
          ::core::result::Result::Ok(2)
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Parity: `~` expansion uses custom `r`.
    mod with_prefix_tilde_on_tail {
      use super::*;

      #[test]
      fn into_bind_second_arg_matches_param_ident() {
        let path = quote! { ::id_effect };
        let r = r_custom();
        let out = expand_closure_body(quote! { ~ g ( ) }, &r, &path);
        let expected = quote! {
          ::id_effect::cap_into_bind(g(), my_r).await
        };
        assert_ts_eq!(out, expected);
      }
    }
  }

  // ---------------------------------------------------------------------------
  // expand_block — direct (private); mirrors branches when public expanders are insufficient
  // (Module name avoids shadowing [`super::expand_block`].)
  // ---------------------------------------------------------------------------
  mod expand_block_branches {
    use super::*;

    /// Invariant: [`split_semicolons`] always yields ≥ 1 chunk, so `expand_block`'s `chunks.is_empty()`
    /// arm is not reachable from the public expanders today.
    mod defensive_empty_chunks {
      use super::*;

      #[test]
      fn split_semicolons_never_returns_empty_vec() {
        assert!(!split_semicolons(TokenStream::new()).is_empty());
      }
    }

    /// Direct check: custom `r` + path with non-empty multi-chunk body.
    mod with_explicit_r_and_path {
      use super::*;

      #[test]
      fn expands_like_integration() {
        let path = quote! { ::id_effect };
        let r = r_custom();
        let out = expand_block(quote! { 1 ; 2 }, &r, &path);
        let expected = quote! {
          1 ;
          ::core::result::Result::Ok(2)
        };
        assert_ts_eq!(out, expected);
      }
    }
  }

  // ---------------------------------------------------------------------------
  // split_semicolons — direct (module name avoids shadowing [`super::split_semicolons`].)
  // ---------------------------------------------------------------------------
  mod semicolon_splitting {
    use super::*;

    /// Branch: empty stream → exactly one empty chunk (so `expand_block` sees tail empty).
    mod empty_stream {
      use super::*;

      #[test]
      fn yields_single_empty_chunk() {
        let chunks = split_semicolons(TokenStream::new());
        assert_eq!(chunks.len(), 1);
        assert!(chunks[0].is_empty());
      }
    }

    /// Branch: no `;` → single chunk equals input.
    mod no_semicolon {
      use super::*;

      #[test]
      fn yields_single_chunk_identical_to_input() {
        let input = quote! { a + b };
        let chunks = split_semicolons(input.clone());
        assert_eq!(chunks.len(), 1);
        assert_ts_eq!(chunks[0].clone(), input);
      }
    }

    /// Branch: one top-level `;` → two chunks.
    mod one_top_level_semicolon {
      use super::*;

      #[test]
      fn yields_two_chunks() {
        let chunks = split_semicolons(quote! { a ; b });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { a });
        assert_ts_eq!(chunks[1].clone(), quote! { b });
      }
    }

    /// Branch: multiple top-level `;` → `k + 1` chunks for `k` separators.
    mod multiple_top_level_semicolons {
      use super::*;

      #[test]
      fn yields_one_more_chunk_than_separator_count() {
        let chunks = split_semicolons(quote! { a ; b ; c });
        assert_eq!(chunks.len(), 3);
        assert_ts_eq!(chunks[0].clone(), quote! { a });
        assert_ts_eq!(chunks[1].clone(), quote! { b });
        assert_ts_eq!(chunks[2].clone(), quote! { c });
      }
    }

    /// Permutation: trailing `;` → final chunk empty.
    mod trailing_semicolon {
      use super::*;

      #[test]
      fn last_chunk_empty() {
        let chunks = split_semicolons(quote! { x ; });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { x });
        assert!(chunks[1].is_empty());
      }
    }

    /// Permutation: leading `;` → first chunk empty.
    mod leading_semicolon {
      use super::*;

      #[test]
      fn first_chunk_empty() {
        let chunks = split_semicolons(quote! { ; y });
        assert_eq!(chunks.len(), 2);
        assert!(chunks[0].is_empty());
        assert_ts_eq!(chunks[1].clone(), quote! { y });
      }
    }

    /// Permutation: `;` nested in `{ }` — not a separator.
    mod semicolon_inside_brace_group {
      use super::*;

      #[test]
      fn single_top_level_chunk() {
        let input = quote! { { a ; b } };
        let chunks = split_semicolons(input.clone());
        assert_eq!(chunks.len(), 1);
        assert_ts_eq!(chunks[0].clone(), input);
      }
    }

    /// Permutation: `;` nested in `( )`.
    mod semicolon_inside_paren_group {
      use super::*;

      #[test]
      fn single_top_level_chunk() {
        let input = quote! { ( a ; b ) };
        let chunks = split_semicolons(input.clone());
        assert_eq!(chunks.len(), 1);
        assert_ts_eq!(chunks[0].clone(), input);
      }
    }

    /// Permutation: `;` nested in `[ ]`.
    mod semicolon_inside_bracket_group {
      use super::*;

      #[test]
      fn single_top_level_chunk() {
        let input = quote! { [ a ; b ] };
        let chunks = split_semicolons(input.clone());
        assert_eq!(chunks.len(), 1);
        assert_ts_eq!(chunks[0].clone(), input);
      }
    }

    /// Block-type expressions (`if`, `while`, …) used as statements without `;`.
    /// In Rust these can omit the trailing semicolon; the macro must recognise the
    /// implicit statement boundary so the following expression becomes the tail.
    mod block_expression_implicit_statement_boundary {
      use super::*;

      /// `if cond { body } tail` — the brace closes the if-expression; `tail` is a
      /// new chunk (the tail expression to be wrapped in `Ok`).
      #[test]
      fn if_block_followed_by_expression_splits_into_two_chunks() {
        let chunks = split_semicolons(quote! { if cond { body } tail });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { if cond { body } });
        assert_ts_eq!(chunks[1].clone(), quote! { tail });
      }

      /// `if cond { x } else { y } tail` — `else { y }` continues the expression,
      /// so there is no split after `{ x }`.  Split happens after `{ y }`.
      #[test]
      fn if_else_block_followed_by_expression_splits_after_else_branch() {
        let chunks = split_semicolons(quote! { if cond { x } else { y } tail });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { if cond { x } else { y } });
        assert_ts_eq!(chunks[1].clone(), quote! { tail });
      }

      /// `if cond { x } else if d { y } tail` — chained else-if, single split after the last `}`.
      #[test]
      fn chained_else_if_block_splits_after_final_branch() {
        let chunks = split_semicolons(quote! { if a { x } else if b { y } tail });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { if a { x } else if b { y } });
        assert_ts_eq!(chunks[1].clone(), quote! { tail });
      }

      /// `if cond { body }` as the **sole** expression — it is the tail, NOT a statement.
      /// No split should occur; the single chunk is wrapped in `Ok(...)` by `expand_block`.
      #[test]
      fn if_block_as_sole_expression_stays_as_single_chunk() {
        let input = quote! { if cond { body } };
        let chunks = split_semicolons(input.clone());
        assert_eq!(chunks.len(), 1);
        assert_ts_eq!(chunks[0].clone(), input);
      }

      /// `if cond { x } else { y }` as the sole expression — no following tokens, so
      /// no split; the whole if-else is the tail.
      #[test]
      fn if_else_block_as_sole_expression_stays_as_single_chunk() {
        let input = quote! { if cond { x } else { y } };
        let chunks = split_semicolons(input.clone());
        assert_eq!(chunks.len(), 1);
        assert_ts_eq!(chunks[0].clone(), input);
      }

      /// `while cond { body } tail` — same implicit-boundary rule for `while`.
      #[test]
      fn while_block_followed_by_expression_splits() {
        let chunks = split_semicolons(quote! { while cond { body } tail });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { while cond { body } });
        assert_ts_eq!(chunks[1].clone(), quote! { tail });
      }

      /// `match expr { arms } tail` — same for `match`.
      #[test]
      fn match_block_followed_by_expression_splits() {
        let chunks = split_semicolons(quote! { match expr { arms } tail });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { match expr { arms } });
        assert_ts_eq!(chunks[1].clone(), quote! { tail });
      }

      /// A standalone `{ block }` group (no preceding keyword) is never auto-split —
      /// the user must add `;` explicitly to make it a statement.
      #[test]
      fn bare_brace_block_without_keyword_is_not_auto_split() {
        let input = quote! { { a ; b } };
        let chunks = split_semicolons(input.clone());
        assert_eq!(chunks.len(), 1);
        assert_ts_eq!(chunks[0].clone(), input);
      }

      /// `let x = { foo() }; tail` — the brace is inside a `let`, which starts the
      /// chunk; `let` is not a block keyword so no auto-split at the brace.  The `;`
      /// is the real separator.
      #[test]
      fn let_with_brace_rhs_splits_at_semicolon_not_at_brace() {
        let chunks = split_semicolons(quote! { let x = { foo ( ) } ; tail });
        assert_eq!(chunks.len(), 2);
        assert_ts_eq!(chunks[0].clone(), quote! { let x = { foo ( ) } });
        assert_ts_eq!(chunks[1].clone(), quote! { tail });
      }
    }
  }

  // ---------------------------------------------------------------------------
  // desugar_ident_tilde_bind — direct (module name avoids shadowing [`super::desugar_ident_tilde_bind`].)
  // ---------------------------------------------------------------------------
  mod ident_tilde_desugar {
    use super::*;

    /// Branch: empty stream → unchanged.
    mod empty_chunk {
      use super::*;

      #[test]
      fn passthrough() {
        let input = TokenStream::new();
        assert_ts_eq!(desugar_ident_tilde_bind(input.clone()), input);
      }
    }

    /// Branch: single token → unchanged (`len < 2`).
    mod single_token {
      use super::*;

      #[test]
      fn passthrough() {
        let input = quote! { x };
        assert_ts_eq!(desugar_ident_tilde_bind(input.clone()), input);
      }
    }

    /// Branch: `ident` + punct other than `~` → unchanged.
    mod ident_then_non_tilde_punct {
      use super::*;

      #[test]
      fn passthrough() {
        let input = quote! { a + b };
        assert_ts_eq!(desugar_ident_tilde_bind(input.clone()), input);
      }
    }

    /// Branch: non-ident first token (literal, group, punct) + `~` → unchanged.
    mod non_ident_first_token {
      use super::*;

      #[test]
      fn passthrough() {
        let input = quote! { 1 ~ x };
        assert_ts_eq!(desugar_ident_tilde_bind(input.clone()), input);
      }
    }

    /// Branch: `ident ~ rest` → `let ident = ~ rest`.
    mod ident_tilde_at_start {
      use super::*;

      #[test]
      fn rewrites_to_let_with_prefix_tilde() {
        let out = desugar_ident_tilde_bind(quote! { k ~ foo ( ) });
        let expected = quote! { let k = ~ foo ( ) };
        assert_ts_eq!(out, expected);
      }
    }
  }

  // ---------------------------------------------------------------------------
  // expand_tilde — direct (module name avoids shadowing [`super::expand_tilde`].)
  // ---------------------------------------------------------------------------
  mod tilde_expansion {
    use super::*;

    fn r_env() -> syn::Ident {
      syn::Ident::new("r_env", proc_macro2::Span::call_site())
    }

    fn path_effect() -> TokenStream {
      quote! { ::id_effect }
    }

    /// Branch: empty → empty.
    mod empty_stream {
      use super::*;

      #[test]
      fn unchanged() {
        let r = r_env();
        let path = path_effect();
        let input = TokenStream::new();
        assert_ts_eq!(expand_tilde(input.clone(), &r, &path), input);
      }
    }

    /// Branch: no `~` → unchanged (modulo group recursion copying structure).
    mod no_tilde_operator {
      use super::*;

      #[test]
      fn passthrough() {
        let r = r_env();
        let path = path_effect();
        let input = quote! { a + b };
        assert_ts_eq!(expand_tilde(input.clone(), &r, &path), input);
      }
    }

    /// Branch: one `~` + operand.
    mod single_prefix_tilde {
      use super::*;

      #[test]
      fn wraps_into_bind_in_parens() {
        let r = r_env();
        let path = path_effect();
        let out = expand_tilde(quote! { ~ foo ( ) }, &r, &path);
        let expected = quote! { (::id_effect::cap_into_bind(foo(), r_env).await?) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Branch: two `~` in sequence (two operands).
    mod two_prefix_tildes {
      use super::*;

      #[test]
      fn expands_both_operands() {
        let r = r_env();
        let path = path_effect();
        // `;` is not an operand boundary for `collect_tilde_operand`; `,` at depth 0 is.
        let out = expand_tilde(quote! { ~ f ( ) , ~ g ( ) }, &r, &path);
        let expected = quote! {
          (::id_effect::cap_into_bind(f(), r_env).await?) , (::id_effect::cap_into_bind(g(), r_env).await?)
        };
        assert_ts_eq!(out, expected);
      }

      /// Two `~` separated by `;` inside a brace group — each should expand independently.
      /// Both `~f()` and `~g()` must become separate `cap_into_bind` calls; the `;` is a
      /// statement separator, not part of either operand.
      ///
      /// Currently FAILS: `;` is not a stop character in `collect_tilde_operand`, so the
      /// first `~` swallows `f() ; ~g()` as one operand.
      #[test]
      fn expands_both_operands_separated_by_semicolon_inside_block() {
        let r = r_env();
        let path = path_effect();
        let out = expand_tilde(quote! { { ~ f ( ) ; ~ g ( ) } }, &r, &path);
        let expected = quote! {
          { (::id_effect::cap_into_bind(f(), r_env).await?) ; (::id_effect::cap_into_bind(g(), r_env).await?) }
        };
        assert_ts_eq!(out, expected);
      }
    }

    /// Branch: `~` inside `{ ... }` — recurse, no Ok-wrap here.
    mod tilde_inside_brace_group {
      use super::*;

      #[test]
      fn expands_inside_group() {
        let r = r_env();
        let path = path_effect();
        let out = expand_tilde(quote! { { ~ a ( ) } }, &r, &path);
        let expected = quote! { { (::id_effect::cap_into_bind(a(), r_env).await?) } };
        assert_ts_eq!(out, expected);
      }
    }

    /// `require!(Key)` inside an effect body desugars to `Needs::<Key>::need(env)`.
    mod bare_require_in_effect_body {
      use super::*;

      #[test]
      fn expands_to_needs_need_with_closure_env() {
        let path = quote! { ::id_effect };
        let r = syn::Ident::new("env", proc_macro2::Span::call_site());
        let out = expand_closure_body(
          quote! { let n = * require ! ( CounterKey ) ; n + 1 },
          &r,
          &path,
        );
        let expected = quote! {
          let n = * ::id_effect::Needs::<CounterKey>::need(env) ;
          ::core::result::Result::Ok(n + 1)
        };
        assert_ts_eq!(out, expected);
      }

      #[test]
      fn legacy_two_arg_form_is_compile_error() {
        let path = quote! { ::id_effect };
        let r = syn::Ident::new("env", proc_macro2::Span::call_site());
        let out = expand_tilde(quote! { require ! ( env , CounterKey ) }, &r, &path);
        let s = out.to_string();
        assert!(
          s.contains("compile_error"),
          "expected compile_error for legacy require!(env, Key), got: {s}"
        );
      }
    }

    /// Branch: `~` inside `( ... )`.
    mod tilde_inside_paren_group {
      use super::*;

      #[test]
      fn expands_inside_group() {
        let r = r_env();
        let path = path_effect();
        let out = expand_tilde(quote! { ( ~ b ( ) ) }, &r, &path);
        let expected = quote! { ((::id_effect::cap_into_bind(b(), r_env).await?)) };
        assert_ts_eq!(out, expected);
      }
    }

    /// Branch: `~` inside `[ ... ]`.
    mod tilde_inside_bracket_group {
      use super::*;

      #[test]
      fn expands_inside_group() {
        let r = r_env();
        let path = path_effect();
        let out = expand_tilde(quote! { [ ~ c ( ) ] }, &r, &path);
        let expected = quote! { [(::id_effect::cap_into_bind(c(), r_env).await?)] };
        assert_ts_eq!(out, expected);
      }
    }

    /// Branch: nested groups with multiple `~`.
    mod nested_groups_with_multiple_tildes {
      use super::*;

      #[test]
      fn expands_depth_first_operands() {
        let r = r_env();
        let path = path_effect();
        let out = expand_tilde(quote! { { ~ u ( ) , ~ v ( ) } }, &r, &path);
        let expected = quote! {
          { (::id_effect::cap_into_bind(u(), r_env).await?) , (::id_effect::cap_into_bind(v(), r_env).await?) }
        };
        assert_ts_eq!(out, expected);
      }
    }
  }

  // ---------------------------------------------------------------------------
  // collect_tilde_operand — direct (module name avoids shadowing [`super::collect_tilde_operand`].)
  // ---------------------------------------------------------------------------
  mod tilde_operand_collection {
    use super::*;

    /// Operand empty (immediate `,` / `>` / end) — edge case.
    mod empty_operand {
      use super::*;

      #[test]
      fn collects_nothing_before_terminator_end() {
        assert!(operand_after_tilde_prefix(quote! { ~ }).is_empty());
      }

      #[test]
      fn collects_nothing_before_comma() {
        assert!(operand_after_tilde_prefix(quote! { ~ , y }).is_empty());
      }

      #[test]
      fn collects_nothing_before_gt_at_depth_zero() {
        assert!(operand_after_tilde_prefix(quote! { ~ > z }).is_empty());
      }
    }

    /// Stops at end of chunk stream.
    mod ends_at_eof {
      use super::*;

      #[test]
      fn collects_full_remaining_tokens() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ foo ( ) }),
          quote! { foo ( ) }
        );
      }
    }

    /// `,` at angle depth 0 stops.
    mod comma_at_depth_zero {
      use super::*;

      #[test]
      fn does_not_include_following_comma_or_args() {
        assert_ts_eq!(operand_after_tilde_prefix(quote! { ~ a , b }), quote! { a });
      }
    }

    /// `<` / `>` pairing inside generics.
    mod turbofish_angle_depth {
      use super::*;

      #[test]
      fn keeps_commas_inside_angles_in_operand() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ p :: < T , U > ( ) }),
          quote! { p :: < T , U > ( ) }
        );
      }

      #[test]
      fn closes_each_angle_with_greater_than() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ q :: < Vec < u8 > > ( ) }),
          quote! { q :: < Vec < u8 > > ( ) }
        );
      }
    }

    /// `>` at depth 0 stops (caller turbofish tail).
    mod greater_than_at_depth_zero {
      use super::*;

      #[test]
      fn stops_before_gt() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ a > tail }),
          quote! { a }
        );
      }
    }

    /// Whole `Group` following `~` is one token in operand.
    mod group_following_tilde {
      use super::*;

      /// `( )` and `[ ]` groups are call-arg / index expressions — always consumed.
      #[test]
      fn consumes_paren_and_bracket_groups() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ ( y ) }),
          quote! { ( y ) }
        );
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ [ z ] }),
          quote! { [ z ] }
        );
      }

      /// `{ }` brace group directly after `~` (with nothing before it) — stops immediately,
      /// producing an empty operand.  Use `~ ( { x } )` if a block-as-operand is intended.
      #[test]
      fn stops_before_leading_brace_group() {
        assert!(operand_after_tilde_prefix(quote! { ~ { x } }).is_empty());
      }

      /// A call like `~foo() { body }` — the `{ body }` brace group is a new block statement,
      /// not part of the call's argument list.  The operand should be just `foo()`;
      /// the `{ body }` brace group should stay in the surrounding token stream.
      ///
      /// Currently FAILS: `collect_tilde_operand` consumes all `Group` tokens unconditionally,
      /// so `{ body }` is eaten into the operand.
      #[test]
      fn stops_before_brace_group_after_call() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ foo ( ) { body } }),
          quote! { foo ( ) }
        );
      }
    }

    /// Method chain after call remains in operand (`.` not a stop).
    mod method_chain_after_primary {
      use super::*;

      #[test]
      fn includes_dot_calls_in_operand() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ foo ( ) . bar ( ) . baz }),
          quote! { foo ( ) . bar ( ) . baz }
        );
      }
    }

    /// Two separate `>` tokens: operand stops after the first `>` at depth 0 following generics.
    mod double_angle_bracket_limitation {
      use super::*;

      #[test]
      fn operand_boundary_differs_from_rust_parse() {
        assert_ts_eq!(
          operand_after_tilde_prefix(quote! { ~ v :: < u8 > > ( ) }),
          quote! { v :: < u8 > }
        );
      }
    }
  }
}