brink-ir 0.0.17

Intermediate representations for inkle's ink narrative scripting language
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
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
//! Container ID stamping pass.
//!
//! Assigns `DefinitionId`s to every HIR node that will become a synthetic
//! LIR container (choice targets, gathers, conditional branches, sequence
//! wrappers). Runs after analysis, before LIR lowering.
//!
//! This replaces the LIR planning pass by pushing structural identity
//! upstream: the LIR lowerer reads pre-stamped IDs directly from HIR
//! nodes instead of re-walking the tree with synchronized counters.
//!
//! # Counter scoping and edit stability (ruled 2026-08-29)
//!
//! Anonymous ids hash from hierarchical scope paths whose numbered
//! segments come from three counters — choice (`c-N`), gather (`g-N`),
//! and the shared conditional/sequence counter (`b-N`/`s-N`). All three
//! are **weave-block-local**: fresh wherever the walk enters a body whose
//! scope path narrows to something unique to that body (a choice body, a
//! sequence branch, a label anchor), threaded through everything that
//! continues the enclosing weave (gather continuations, conditional
//! branch bodies, unlabeled blocks). The payoff is edit locality: an
//! insertion shifts anonymous ids only for later siblings *in the same
//! weave block*, never across the whole knot. (The `b-`/`s-` counter was
//! scope-global until the ruling — one counter per knot threaded through
//! all nesting — a relic of the two synchronized walks the pristine-HIR
//! stamping move retired; renumbering it was a one-time break for
//! anonymous save state.)
//!
//! A **label anchors its subtree**: a labeled choice's or labeled block's
//! descendants scope under `#lbl:{label_id}` rather than the positional
//! path, so naming a container makes everything inside it independent of
//! sibling edits — the strongest form of the E157 remediation.

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

use brink_format::{DefinitionId, DefinitionTag};

use crate::FileId;
use crate::determinism::LookupMap;
use crate::hir;
use crate::symbols::{SymbolIndex, SymbolInfo, SymbolKind};

/// The structural scope path every *anonymous* container in `file_path`'s
/// root-level weave hangs off (#1504).
///
/// A knot scopes its children under the knot name, so two files' *distinctly
/// named* knots can never mint the same anonymous path. Root content has no
/// such prefix at all: with an empty root scope path, file A's first root
/// choice and file B's first root choice both hash `c-0` and — because
/// address allocation is a pure hash with no collision avoidance — receive
/// the **same** `DefinitionId`. That id is the linker's address key
/// (last-write-wins) and the save key for visit counts, so the collision
/// miscompiles: picking a choice from the included file runs the entry file's
/// choice body.
///
/// ⚠ "Two files' knots can never mint the same anonymous path" stops being
/// true the moment two files legitimately declare a **same-named** knot
/// (M-2d, #790: `native_module_path` always differs per file, so
/// `insert_symbol` lets the pair coexist rather than raising a
/// duplicate-definition diagnostic) — `stamp_container_ids`'s per-knot loop
/// used to qualify by the bare knot name alone and collided on every
/// unlabeled descendant container exactly like this function's own root
/// content used to (issue #2229, the 4th M-2d collision site; #2197/#2213/
/// #2215/#2226 are the other three). That loop now qualifies its own scope
/// path through this same function — the fix this doc's own false
/// invariant should have named from the start.
///
/// Qualifying by the *file* rather than by the owning module is deliberate.
/// An `INCLUDE`d file with no `#@module` of its own inherits its includer's
/// module (`docs/modules-spec.md` §1), so a module qualifier leaves exactly
/// the shape #1504 was filed against still colliding; two distinct files
/// always have distinct paths. See `docs/root-content-identity-findings.md`.
///
/// The `#` prefix is what makes the qualifier collision-proof against
/// authored scope paths: `#` is not legal in a knot, stitch or label name,
/// and the synthesized segments are all `c-N`/`g-N`/`b-N`/`s-N` — `-` not
/// being legal in an authored identifier either. (Choice segments only
/// actually spell `c-N` since #2229's review pass: `stamp_stmt` used to
/// write bare `c{n}`, contra this very sentence, which an authored knot
/// legally named `c0` could equal — colliding with a root anonymous
/// choice's subtree the moment knot interiors joined this shared `#file:`
/// namespace.)
///
/// `None` (a file whose path the caller did not supply — only in-crate test
/// harnesses do that) yields an empty qualifier, i.e. the pre-#1504 paths.
#[must_use]
pub fn root_content_scope_path(file_path: Option<&str>) -> String {
    match file_path {
        Some(path) if !path.is_empty() => format!("#file:{path}"),
        _ => String::new(),
    }
}

/// Stamp container IDs on all HIR files.
///
/// Must be called after analysis (needs `SymbolIndex` for labeled containers)
/// and before LIR lowering.
///
/// `file_paths` supplies each file's registered project path, which
/// qualifies both the root-content scope path (see
/// [`root_content_scope_path`]) and, since issue #2229, every knot's own
/// interior scope path the same way (root-scope-prefixed via [`qualify`]).
/// Name-based lookups (`label_scope`) stay unqualified throughout: an
/// author's label — root-level or knot-scoped — is addressed by its bare
/// (optionally knot/stitch-qualified) name from anywhere in the project,
/// and the analyzer's `SymbolIndex` keys it that way.
#[expect(
    clippy::implicit_hasher,
    reason = "internal API, no need to generalize"
)]
pub fn stamp_container_ids(
    files: &mut [(FileId, hir::HirFile)],
    index: &SymbolIndex,
    file_paths: &LookupMap<FileId, String>,
) {
    for (file_id, hir_file) in files {
        // Root content — scoped by the owning file (#1504), counters start
        // at 0. The *label* scope stays empty: root labels are addressed by
        // bare name.
        let mut seq = 0;
        let root_scope = root_content_scope_path(file_paths.get(file_id).map(String::as_str));
        stamp_block(
            &mut hir_file.root_content,
            *file_id,
            &root_scope,
            "",
            index,
            &mut seq,
        );

        // File-scope `VAR`/`CONST` initializers (issue #1727) — these are
        // flat, non-recursive `HirFile` vecs, not part of `root_content`'s
        // block tree, so `stamp_block` above never reaches them. A default
        // that is itself a lambda literal (issue #1774,
        // `lir::lower::decls::eval_const_lambda`) is lowered with an
        // **empty** `ctx.scope_path` qualified by the same file's
        // `root_scope` prefix (`GlobalLambdaCtx`'s `set_path_prefix` call in
        // `collect_globals`) — exactly `root_scope` itself, the same
        // qualifier root content's own anonymous containers use.
        for cst in &mut hir_file.constants {
            stamp_lambdas_in_expr(&mut cst.value, *file_id, &root_scope, "", index);
        }
        for var in &mut hir_file.variables {
            stamp_lambdas_in_expr(&mut var.value, *file_id, &root_scope, "", index);
        }

        for knot in &mut hir_file.knots {
            // `knot_path` (the *label* scope) stays bare — it must match
            // the unqualified `{knot}.{label}` naming
            // `insert_symbol`/`lookup_label_id` key `SymbolIndex.by_name`
            // by (`manifest.rs`'s `format!("{k}.{s}.", …)`), addressed by
            // bare name from anywhere in the project. `knot_scope` (the
            // *anonymous-container hashing* scope) gets the same per-file
            // `#file:{path}` qualifier root content already carries
            // ([`root_content_scope_path`], #1504) — this is the 4th M-2d
            // collision site (#2229): two files legitimately declaring a
            // same-named knot (their `native_module_path`s always differ,
            // so `insert_symbol` lets them coexist, #790) previously
            // stamped every *unlabeled* descendant container at the same
            // structural position (`start.0.c-0`) to the identical
            // `DefinitionId`, tripping the #1673 duplicate-id `E060`
            // codegen guard the moment both files' container trees were
            // walked. `root_scope` is already file-qualified and empty for
            // a caller that supplied no file path (in-crate test
            // harnesses), so `qualify` degrades to the pre-#2229 bare
            // `knot_path` in that case — byte-identical single-file/no-path
            // behavior.
            let knot_path = &knot.name.text;
            let knot_scope = qualify(&root_scope, knot_path);
            let mut seq = 0;
            stamp_block(
                &mut knot.body,
                *file_id,
                &knot_scope,
                knot_path,
                index,
                &mut seq,
            );

            for stitch in &mut knot.stitches {
                let stitch_path = format!("{knot_path}.{}", stitch.name.text);
                let stitch_scope = qualify(&root_scope, &stitch_path);
                let mut seq = 0;
                stamp_block(
                    &mut stitch.body,
                    *file_id,
                    &stitch_scope,
                    &stitch_path,
                    index,
                    &mut seq,
                );
            }
        }
    }
}

/// Stamp container IDs on all structural statements in a block.
fn stamp_block(
    block: &mut hir::Block,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
    seq_counter: &mut usize,
) {
    let mut choice_counter = 0usize;
    let mut gather_counter = 0usize;

    for stmt in &mut block.stmts {
        stamp_stmt(
            stmt,
            file,
            scope_path,
            label_scope,
            index,
            seq_counter,
            &mut choice_counter,
            &mut gather_counter,
        );
    }
}

/// Stamp container IDs on a single statement and recurse into children.
///
/// `file`: the file whose declarations this statement belongs to — see
/// [`lookup_label_id`]'s doc. Threaded down from [`stamp_block`] for the
/// primary weave walk and from every lambda-stamping call site (issue
/// #2215) so a labeled gather/choice/block reached through a
/// content-embedded inline conditional/sequence
/// (`stamp_lambdas_in_content_part`'s `InlineConditional`/
/// `InlineSequence` arms, or transitively via `stamp_lambdas_in_expr`'s
/// `Fragment` arm when a block-capture's own captured content line
/// carries one of these mid-line) gets the same same-file-preferred label
/// lookup the primary walk already gets — every call site has a real
/// `FileId` in scope, so there is no longer an unscoped case to fall back
/// to.
#[expect(
    clippy::too_many_lines,
    reason = "structural match over all statement types"
)]
#[expect(
    clippy::too_many_arguments,
    reason = "issue #2197 added `file` for label self-identity; a context struct isn't worth it \
              for one more threaded parameter"
)]
fn stamp_stmt(
    stmt: &mut hir::Stmt,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
    seq_counter: &mut usize,
    choice_counter: &mut usize,
    gather_counter: &mut usize,
) {
    match stmt {
        hir::Stmt::ChoiceSet(cs) => {
            // Gather container ID — from label lookup or scope path.
            let gather_id = if let Some(ref label) = cs.continuation.label {
                let label_path = qualify(label_scope, &label.text);
                lookup_label_id(index, file, &label_path)
                    .unwrap_or_else(|| alloc_address(&format!("{scope_path}.g-{gather_counter}")))
            } else {
                alloc_address(&format!("{scope_path}.g-{gather_counter}"))
            };
            cs.gather_id = Some(gather_id);
            cs.continuation.container_id = Some(gather_id);
            *gather_counter += 1;

            // Choice target container IDs. The synthesized segment is
            // `c-{n}` — dash-separated like `g-N`/`b-N`/`s-N`, exactly as
            // [`root_content_scope_path`]'s doc always claimed — NOT the
            // bare `c{n}` this used to spell. The dash is load-bearing
            // (issue #2229 review): `c0` is a perfectly legal authored
            // knot name, and once knot interiors share the root `#file:`
            // namespace, an authored knot `c0` hashes the same scope as a
            // root-level anonymous choice's subtree (`{root}.c0`),
            // colliding every same-position descendant (`E060`). `-` is
            // not legal in any authored identifier, so a dashed segment
            // can never equal one.
            for choice in &mut cs.choices {
                let choice_id = if let Some(ref label) = choice.label {
                    let label_path = qualify(label_scope, &label.text);
                    lookup_label_id(index, file, &label_path).unwrap_or_else(|| {
                        alloc_address(&format!("{scope_path}.c-{choice_counter}"))
                    })
                } else {
                    alloc_address(&format!("{scope_path}.c-{choice_counter}"))
                };
                choice.container_id = Some(choice_id);
                *choice_counter += 1;

                // A lambda in the choice's own condition/content (issue
                // #1727) is lowered *before* `ctx.scope_path` narrows to the
                // choice's own scope (`lir::lower::mod.rs`'s
                // `lower_choice`: the block scope opens, then
                // condition/content lower, and only the *body* lowering
                // below gets the narrowed `.c-{n}` scope) — so these stamp
                // at the parent `scope_path`, not `child_scope`.
                if let Some(cond) = &mut choice.condition {
                    stamp_lambdas_in_expr(cond, file, scope_path, label_scope, index);
                }
                for c in [
                    &mut choice.start_content,
                    &mut choice.bracket_content,
                    &mut choice.inner_content,
                ]
                .into_iter()
                .flatten()
                {
                    stamp_lambdas_in_content(c, file, scope_path, label_scope, index);
                }
                for tag in &mut choice.tags {
                    for part in &mut tag.parts {
                        stamp_lambdas_in_content_part(part, file, scope_path, label_scope, index);
                    }
                }

                // Recurse into choice body with narrowed scope. A *labeled*
                // choice anchors its descendants on the label's own id
                // (ruled 2026-08-29, #3234 follow-up): the label id is
                // name-hashed — stable under any sibling edit — so hanging
                // the subtree off `#lbl:{id}` instead of the positional
                // `.c-{n}` makes the label insulate everything inside it,
                // not just the choice's own visit state. `#`/`$` are both
                // illegal in authored identifiers, so the anchor can never
                // equal an authored scope segment (same argument as
                // [`root_content_scope_path`]'s `#file:` qualifier), and
                // uniqueness is inherited from the label id itself.
                let child_scope = if choice.label.is_some() {
                    format!("#lbl:{choice_id}")
                } else {
                    format!("{scope_path}.c-{}", *choice_counter - 1)
                };
                let mut child_choice_counter = 0;
                let mut child_gather_counter = 0;
                let mut child_seq_counter = 0;
                for body_stmt in &mut choice.body.stmts {
                    stamp_stmt(
                        body_stmt,
                        file,
                        &child_scope,
                        label_scope,
                        index,
                        &mut child_seq_counter,
                        &mut child_choice_counter,
                        &mut child_gather_counter,
                    );
                }
            }

            // Recurse into continuation — shares parent scope and counters.
            for cont_stmt in &mut cs.continuation.stmts {
                stamp_stmt(
                    cont_stmt,
                    file,
                    scope_path,
                    label_scope,
                    index,
                    seq_counter,
                    choice_counter,
                    gather_counter,
                );
            }
        }

        hir::Stmt::LabeledBlock(block) => {
            if block.label.is_some() {
                let label_path = block
                    .label
                    .as_ref()
                    .map(|l| qualify(label_scope, &l.text))
                    .unwrap_or_default();
                let label_id = lookup_label_id(index, file, &label_path)
                    .unwrap_or_else(|| alloc_address(&label_path));
                block.container_id = Some(label_id);

                // Register as gather target for the lowerer.
                *gather_counter += 1;

                // Anchor descendants on the label id (same rule as a
                // labeled choice's body above): the subtree's anonymous
                // ids become independent of the block's own position.
                let child_scope = format!("#lbl:{label_id}");
                let mut child_seq = 0;
                let mut child_choice = 0;
                let mut child_gather = 0;
                for s in &mut block.stmts {
                    stamp_stmt(
                        s,
                        file,
                        &child_scope,
                        label_scope,
                        index,
                        &mut child_seq,
                        &mut child_choice,
                        &mut child_gather,
                    );
                }
            } else {
                for s in &mut block.stmts {
                    stamp_stmt(
                        s,
                        file,
                        scope_path,
                        label_scope,
                        index,
                        seq_counter,
                        choice_counter,
                        gather_counter,
                    );
                }
            }
        }

        hir::Stmt::Conditional(cond) => {
            let cond_idx = *seq_counter;
            *seq_counter += 1;
            let cond_scope = format!("b-{cond_idx}");

            // The switch expression (`{expr: - val: …}`) and each branch's
            // own condition lower *before* `ctx.scope_path` narrows to that
            // branch (`lir::lower::mod.rs`'s `Stmt::Conditional` arm: the
            // condition/`as`-binding lowers, then `ctx.scope_path =
            // branch_scope` is set) — issue #1727 stamps a lambda there at
            // the parent `scope_path`, matching that order.
            if let hir::CondKind::Switch(e) = &mut cond.kind {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }

            for (branch_idx, branch) in cond.branches.iter_mut().enumerate() {
                let branch_scope = if scope_path.is_empty() {
                    format!("{cond_scope}.{branch_idx}")
                } else {
                    format!("{scope_path}.{cond_scope}.{branch_idx}")
                };
                let branch_id = alloc_address(&branch_scope);
                branch.container_id = Some(branch_id);

                if let Some(bc) = &mut branch.condition {
                    stamp_lambdas_in_expr(bc, file, scope_path, label_scope, index);
                }

                // Recurse into branch body — shares parent choice/gather counters.
                for s in &mut branch.body.stmts {
                    stamp_stmt(
                        s,
                        file,
                        &branch_scope,
                        label_scope,
                        index,
                        seq_counter,
                        choice_counter,
                        gather_counter,
                    );
                }
            }
        }

        hir::Stmt::Sequence(seq) => {
            let seq_idx = *seq_counter;
            *seq_counter += 1;
            let display_name = format!("s-{seq_idx}");
            let child_scope = if scope_path.is_empty() {
                display_name.clone()
            } else {
                format!("{scope_path}.{display_name}")
            };
            let wrapper_id = alloc_address(&child_scope);
            seq.container_id = Some(wrapper_id);

            // Each branch gets its own container ID.
            for (branch_idx, branch) in seq.branches.iter_mut().enumerate() {
                let branch_path = if child_scope.is_empty() {
                    format!("{branch_idx}")
                } else {
                    format!("{child_scope}.{branch_idx}")
                };
                let branch_id = alloc_address(&branch_path);
                branch.body.container_id = Some(branch_id);

                // Sequence branches get fresh counters, and recurse under
                // the BRANCH's own path, not the wrapper's. Recursing under
                // the wrapper (`child_scope`) with fresh per-branch
                // counters stamped a choice in branch 0 and a choice in
                // branch 1 both as `{wrapper}.c-0` — one `DefinitionId` on
                // two containers, tripping the #1673 E060 guard on legal
                // ink (a block-level `{stopping:}` with a choice in two
                // branches). The branch index in the path is what keeps
                // fresh counters collision-free.
                let mut bseq = 0;
                let mut bc = 0;
                let mut gc = 0;
                for s in &mut branch.body.stmts {
                    stamp_stmt(
                        s,
                        file,
                        &branch_path,
                        label_scope,
                        index,
                        &mut bseq,
                        &mut bc,
                        &mut gc,
                    );
                }
            }
        }

        // None of these statement types ever produce a *structural*
        // container (choice/gather/branch/sequence-wrapper) — but every one
        // of them can carry an embedded `Expr::Lambda` (issue #1727), so
        // each still needs a scan at the current `scope_path`. T1b `~ { … }`
        // blocks (docs/t1b-surface-spec.md §2): `BlockStmt` is a closed set
        // with no variant for any *weave* concept, so nothing inside a
        // logic block can ever need a synthetic LIR container — the seam
        // rule enforces that by construction, not by a check here — but a
        // logic block's statements are exactly where a `let f = |x| …;`
        // most commonly lives, so `LogicBlock` gets the fullest walk below.
        hir::Stmt::Content(content) => {
            // #3275 (stage 3a): EVERY top-level inline construct on a weave
            // content line stamps here, on the PRISTINE tree — with exactly
            // the scope paths and counter values the post-normalize walk
            // used to derive for the lifted `Stmt::Sequence`/
            // `Stmt::Conditional` (the lift preserves statement position,
            // so a single-construct line's ids are byte-identical to the
            // pre-3a scheme). `normalize_file`'s lift now INHERITS these
            // ids instead of a later walk re-minting them, so an id exists
            // before any clone does and a cloned stateful alternative can
            // share its container (ruled 2026-08-29 on #3275). A
            // variant-claimed line stamps identically — its branches are
            // textual, so the branch recursion is a no-op — which is why
            // this arm no longer consults `claims_variant_line` at all.
            for part in &mut content.parts {
                stamp_inline_part(
                    part,
                    file,
                    scope_path,
                    label_scope,
                    index,
                    seq_counter,
                    choice_counter,
                    gather_counter,
                );
            }
            // Lambda scan for the non-structural parts (interpolations,
            // spans) and tags. The inline constructs were fully covered
            // above — branch bodies via `stamp_stmt`, conditions inside
            // `stamp_inline_part` — and running the content-embedded scan
            // over them too would re-stamp their branch bodies under the
            // fresh-counter convention, clobbering the structural ids just
            // minted.
            for part in &mut content.parts {
                if !matches!(
                    part,
                    hir::ContentPart::InlineSequence(_) | hir::ContentPart::InlineConditional(_)
                ) {
                    stamp_lambdas_in_content_part(part, file, scope_path, label_scope, index);
                }
            }
            for tag in &mut content.tags {
                for part in &mut tag.parts {
                    stamp_lambdas_in_content_part(part, file, scope_path, label_scope, index);
                }
            }
        }
        hir::Stmt::Divert(d) => {
            for a in &mut d.target.args {
                stamp_lambdas_in_expr(a, file, scope_path, label_scope, index);
            }
        }
        hir::Stmt::TunnelCall(t) => {
            for target in &mut t.targets {
                for a in &mut target.args {
                    stamp_lambdas_in_expr(a, file, scope_path, label_scope, index);
                }
            }
        }
        hir::Stmt::ThreadStart(t) => {
            for a in &mut t.target.args {
                stamp_lambdas_in_expr(a, file, scope_path, label_scope, index);
            }
        }
        hir::Stmt::TempDecl(t) => {
            if let Some(e) = &mut t.value {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }
        }
        hir::Stmt::Assignment(a) => {
            stamp_lambdas_in_expr(&mut a.target, file, scope_path, label_scope, index);
            stamp_lambdas_in_expr(&mut a.value, file, scope_path, label_scope, index);
        }
        hir::Stmt::Return(r) => {
            if let Some(e) = &mut r.value {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }
            for a in &mut r.onwards_args {
                stamp_lambdas_in_expr(a, file, scope_path, label_scope, index);
            }
        }
        // Issue #2108: the attach handler's call expression could embed a
        // lambda the same way any other call argument can — scan it like
        // `ExprStmt` does. `EndElementRun` carries no expression, like
        // `EndOfLine`.
        hir::Stmt::ExprStmt(e) | hir::Stmt::AttachElement(e) => {
            stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
        }
        hir::Stmt::EndOfLine | hir::Stmt::EndElementRun => {}
        hir::Stmt::LogicBlock(lb) => {
            stamp_lambdas_in_block_stmts(&mut lb.stmts, file, scope_path, label_scope, index);
        }
        // `await` (docs/flow-suspension-spec.md §3): the resume-container
        // synthesis (§3, a synthetic container id + tunnel-return stack) is
        // FS-2's later step, gated behind the FS-3 runtime; the construct is
        // fenced at LIR lowering (E052) here and stamps no container yet —
        // but its condition expression is still ordinary HIR that could
        // embed a lambda, so it still gets scanned.
        hir::Stmt::Await(a) => {
            if let Some(c) = &mut a.condition {
                stamp_lambdas_in_expr(c, file, scope_path, label_scope, index);
            }
        }
    }
}

/// Stamp a weave content line's top-level inline construct (#3275, stage
/// 3a) with the scope paths and counter consumption the post-normalize
/// walk used to apply to its LIFTED form — `try_lift_inline` inherits
/// these ids, never re-mints. Non-construct parts pass through untouched
/// (the caller's lambda scan covers them). Only TOP-LEVEL parts stamp
/// structurally: a construct nested inside a `Span` stays on the
/// content-embedded convention (`stamp_lambdas_in_content_part`), matching
/// LIR's inline lowering, which never lifts span children.
#[expect(
    clippy::too_many_arguments,
    reason = "same threaded walk state as `stamp_stmt`, same #2197 tradeoff"
)]
fn stamp_inline_part(
    part: &mut hir::ContentPart,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
    seq_counter: &mut usize,
    choice_counter: &mut usize,
    gather_counter: &mut usize,
) {
    match part {
        hir::ContentPart::InlineSequence(seq) => {
            // Mirrors the `Stmt::Sequence` arm: wrapper `s-{n}`, branch
            // `.{idx}`, branch bodies at the BRANCH's own path with all
            // three counters fresh (see that arm's comment for why the
            // branch index in the path is what keeps fresh counters
            // collision-free).
            let seq_idx = *seq_counter;
            *seq_counter += 1;
            let display_name = format!("s-{seq_idx}");
            let child_scope = if scope_path.is_empty() {
                display_name
            } else {
                format!("{scope_path}.{display_name}")
            };
            seq.container_id = Some(alloc_address(&child_scope));
            for (branch_idx, branch) in seq.branches.iter_mut().enumerate() {
                let branch_path = format!("{child_scope}.{branch_idx}");
                branch.body.container_id = Some(alloc_address(&branch_path));
                let mut bseq = 0;
                let mut bc = 0;
                let mut gc = 0;
                for s in &mut branch.body.stmts {
                    stamp_stmt(
                        s,
                        file,
                        &branch_path,
                        label_scope,
                        index,
                        &mut bseq,
                        &mut bc,
                        &mut gc,
                    );
                }
            }
        }
        hir::ContentPart::InlineConditional(cond) => {
            // Mirrors the `Stmt::Conditional` arm: branch scope
            // `{scope}.b-{n}.{idx}`, all three counters shared with the
            // enclosing scope.
            let cond_idx = *seq_counter;
            *seq_counter += 1;
            let cond_scope = format!("b-{cond_idx}");
            if let hir::CondKind::Switch(e) = &mut cond.kind {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }
            for (branch_idx, branch) in cond.branches.iter_mut().enumerate() {
                let branch_scope = if scope_path.is_empty() {
                    format!("{cond_scope}.{branch_idx}")
                } else {
                    format!("{scope_path}.{cond_scope}.{branch_idx}")
                };
                branch.container_id = Some(alloc_address(&branch_scope));
                if let Some(bc) = &mut branch.condition {
                    stamp_lambdas_in_expr(bc, file, scope_path, label_scope, index);
                }
                for s in &mut branch.body.stmts {
                    stamp_stmt(
                        s,
                        file,
                        &branch_scope,
                        label_scope,
                        index,
                        seq_counter,
                        choice_counter,
                        gather_counter,
                    );
                }
            }
        }
        _ => {}
    }
}

// ─── Clone id derivation (#3275, stage 3a) ─────────────────────────────
//
// `normalize_file`'s lift splices prefix/suffix content into every branch
// of the lifted construct — CLONING any other inline construct (and any
// lambda) that shared the line. Ids are stamped before the lift now, so a
// clone arrives carrying its original's id; two containers must never
// share one (#1673). The rules, per the 2026-08-29 #3275 ruling:
//
// * a cloned STATEFUL alternative (`ContentPart::InlineSequence`) shares
//   the original's visit-count STATE — ink's "advances each time the line
//   is viewed" — without sharing its body: the clone's wrapper and branch
//   ids re-derive like everything else, and `Sequence::counter_id` records
//   the original, which codegen reads and advances (`TouchVisit`) to pick
//   the clone's branch (#3401). Clone 0 keeps the original id, so exactly
//   one container carries the counted state — a bodied wrapper when that
//   site lifts, or the variant path's empty stub when it claims.
// * everything else (a cloned stateless conditional's branches, cloned
//   lambdas, anonymous containers inside cloned branch bodies) re-derives
//   per clone from the original id + a salt that mixes the LIFTING
//   construct's own identity with the host branch index
//   (`normalize.rs`'s `lift_salt`) — clone bodies differ (different
//   spliced text), so they must be distinct containers, and the salt must
//   not compose commutatively across lift levels (issue #3386).
// * clone 0 keeps original ids (`salt == 0` is the identity), so the
//   stamped id stays live on exactly one container and derivation only
//   touches genuine duplicates.

/// Derive a deterministic child id from a stamped one. Same
/// `DefaultHasher` scheme as [`alloc_address`], so derived ids live in the
/// same address space and are stable across recompiles.
#[must_use]
pub(crate) fn derive_id(base: DefinitionId, kind: &str, salt: u64) -> DefinitionId {
    let mut hasher = DefaultHasher::new();
    Hash::hash(&base, &mut hasher);
    Hash::hash(kind, &mut hasher);
    Hash::hash(&salt, &mut hasher);
    DefinitionId::new(DefinitionTag::Address, hasher.finish())
}

/// Re-derive every container/lambda id in a cloned run of content parts
/// (see the module section comment above). `salt == 0` is a no-op. A
/// cloned stateful alternative gets its own wrapper id like everything
/// else, but remembers the original as its `counter_id` (#3401): its branch
/// index is computed from the ORIGINAL container's visit count, so every
/// clone advances one shared state while keeping a distinct body.
pub(crate) fn rederive_cloned_parts(parts: &mut [hir::ContentPart], salt: u64) {
    rederive_parts_inner(parts, salt);
}

/// The #3401 clone rule for a stateful alternative: a derived wrapper id
/// (this clone's body is its own container), branch ids derived like any
/// cloned block, and `counter_id` pinned to the ORIGINAL — a clone of a
/// clone keeps the first original, never a derived intermediate.
fn rederive_cloned_sequence(seq: &mut hir::Sequence, salt: u64) {
    if let Some(id) = seq.container_id {
        seq.counter_id.get_or_insert(id);
        seq.container_id = Some(derive_id(id, "clone", salt));
    }
    for branch in &mut seq.branches {
        if let Some(id) = branch.body.container_id {
            branch.body.container_id = Some(derive_id(id, "clone", salt));
        }
        rederive_block_inner(&mut branch.body, salt);
    }
}

fn rederive_parts_inner(parts: &mut [hir::ContentPart], salt: u64) {
    if salt == 0 {
        return;
    }
    for part in parts {
        match part {
            hir::ContentPart::InlineSequence(seq) => rederive_cloned_sequence(seq, salt),
            hir::ContentPart::InlineConditional(cond) => {
                if let hir::CondKind::Switch(e) = &mut cond.kind {
                    rederive_cloned_expr(e, salt);
                }
                for branch in &mut cond.branches {
                    if let Some(id) = branch.container_id {
                        branch.container_id = Some(derive_id(id, "clone", salt));
                    }
                    if let Some(c) = &mut branch.condition {
                        rederive_cloned_expr(c, salt);
                    }
                    rederive_block_inner(&mut branch.body, salt);
                }
            }
            hir::ContentPart::Interpolation(e) => rederive_cloned_expr(e, salt),
            hir::ContentPart::Span(span) => {
                rederive_parts_inner(&mut span.children, salt);
            }
            hir::ContentPart::Text(_) | hir::ContentPart::Glue | hir::ContentPart::Spring => {}
        }
    }
}

fn rederive_block_inner(block: &mut hir::Block, salt: u64) {
    if let Some(id) = block.container_id {
        block.container_id = Some(derive_id(id, "clone", salt));
    }
    for stmt in &mut block.stmts {
        rederive_stmt_inner(stmt, salt);
    }
}

fn rederive_stmt_inner(stmt: &mut hir::Stmt, salt: u64) {
    match stmt {
        hir::Stmt::ChoiceSet(cs) => rederive_choice_set(cs, salt),
        hir::Stmt::LabeledBlock(block) => {
            // A label-bearing construct is never cloned (`lift_index`
            // lifts it first) — this arm only sees anonymous blocks.
            for s in &mut block.stmts {
                rederive_stmt_inner(s, salt);
            }
        }
        hir::Stmt::Conditional(cond) => {
            for branch in &mut cond.branches {
                if let Some(id) = branch.container_id {
                    branch.container_id = Some(derive_id(id, "clone", salt));
                }
                rederive_block_inner(&mut branch.body, salt);
            }
        }
        hir::Stmt::Sequence(seq) => rederive_cloned_sequence(seq, salt),
        hir::Stmt::Content(content) => {
            rederive_parts_inner(&mut content.parts, salt);
            for tag in &mut content.tags {
                rederive_parts_inner(&mut tag.parts, salt);
            }
        }
        hir::Stmt::Divert(d) => {
            for a in &mut d.target.args {
                rederive_cloned_expr(a, salt);
            }
        }
        hir::Stmt::TunnelCall(t) => {
            for target in &mut t.targets {
                for a in &mut target.args {
                    rederive_cloned_expr(a, salt);
                }
            }
        }
        hir::Stmt::ThreadStart(t) => {
            for a in &mut t.target.args {
                rederive_cloned_expr(a, salt);
            }
        }
        hir::Stmt::TempDecl(t) => {
            if let Some(e) = &mut t.value {
                rederive_cloned_expr(e, salt);
            }
        }
        hir::Stmt::Assignment(a) => {
            rederive_cloned_expr(&mut a.target, salt);
            rederive_cloned_expr(&mut a.value, salt);
        }
        hir::Stmt::Return(r) => {
            if let Some(e) = &mut r.value {
                rederive_cloned_expr(e, salt);
            }
            for a in &mut r.onwards_args {
                rederive_cloned_expr(a, salt);
            }
        }
        hir::Stmt::ExprStmt(e) | hir::Stmt::AttachElement(e) => {
            rederive_cloned_expr(e, salt);
        }
        hir::Stmt::LogicBlock(lb) => {
            for s in &mut lb.stmts {
                rederive_cloned_block_stmt(s, salt);
            }
        }
        hir::Stmt::Await(a) => {
            if let Some(c) = &mut a.condition {
                rederive_cloned_expr(c, salt);
            }
        }
        hir::Stmt::EndOfLine | hir::Stmt::EndElementRun => {}
    }
}

/// The `BlockStmt` half of the cloned-lambda walk: `BlockStmt` mints no
/// container ids of its own, but its expressions can hold nested lambdas.
fn rederive_cloned_block_stmt(stmt: &mut hir::BlockStmt, salt: u64) {
    match stmt {
        hir::BlockStmt::TempDecl(t) => {
            if let Some(e) = &mut t.value {
                rederive_cloned_expr(e, salt);
            }
        }
        hir::BlockStmt::Assignment(a) => {
            rederive_cloned_expr(&mut a.target, salt);
            rederive_cloned_expr(&mut a.value, salt);
        }
        hir::BlockStmt::Return(r) => {
            if let Some(e) = &mut r.value {
                rederive_cloned_expr(e, salt);
            }
            for a in &mut r.onwards_args {
                rederive_cloned_expr(a, salt);
            }
        }
        hir::BlockStmt::If(i) => rederive_cloned_if(i, salt),
        hir::BlockStmt::While(w) => {
            rederive_cloned_expr(&mut w.condition, salt);
            for s in &mut w.body {
                rederive_cloned_block_stmt(s, salt);
            }
        }
        hir::BlockStmt::For(f) => {
            rederive_cloned_expr(&mut f.iterable, salt);
            for s in &mut f.body {
                rederive_cloned_block_stmt(s, salt);
            }
        }
        hir::BlockStmt::ExprStmt(e) => rederive_cloned_expr(e, salt),
        _ => {}
    }
}

fn rederive_choice_set(cs: &mut hir::ChoiceSet, salt: u64) {
    if let Some(id) = cs.gather_id {
        let derived = derive_id(id, "clone", salt);
        cs.gather_id = Some(derived);
        cs.continuation.container_id = Some(derived);
    }
    for choice in &mut cs.choices {
        if let Some(id) = choice.container_id {
            choice.container_id = Some(derive_id(id, "clone", salt));
        }
        if let Some(c) = &mut choice.condition {
            rederive_cloned_expr(c, salt);
        }
        rederive_block_inner(&mut choice.body, salt);
    }
    for s in &mut cs.continuation.stmts {
        rederive_stmt_inner(s, salt);
    }
}

fn rederive_cloned_if(i: &mut hir::IfStmt, salt: u64) {
    rederive_cloned_expr(&mut i.condition, salt);
    for s in &mut i.body {
        rederive_cloned_block_stmt(s, salt);
    }
    match &mut i.else_branch {
        Some(hir::ElseBranch::ElseIf(nested)) => rederive_cloned_if(nested, salt),
        Some(hir::ElseBranch::Else(stmts)) => {
            for s in stmts {
                rederive_cloned_block_stmt(s, salt);
            }
        }
        None => {}
    }
}

/// Re-derive `LambdaExpr::container_id`s in a cloned expression. Mirrors
/// [`stamp_lambdas_in_expr`]'s reachability, minus the structural walks a
/// clone can't contain (a fragment's statements go through
/// [`rederive_cloned_stmt`]).
fn rederive_cloned_expr(expr: &mut hir::Expr, salt: u64) {
    match expr {
        hir::Expr::Lambda(l) => {
            if let Some(id) = l.container_id {
                l.container_id = Some(derive_id(id, "clone", salt));
            }
            match &mut l.body {
                hir::LambdaBody::Expr(e) => rederive_cloned_expr(e, salt),
                hir::LambdaBody::Block { stmts, tail } => {
                    for s in stmts.iter_mut() {
                        rederive_cloned_block_stmt(s, salt);
                    }
                    if let Some(t) = tail {
                        rederive_cloned_expr(t, salt);
                    }
                }
            }
        }
        hir::Expr::Prefix(_, inner) | hir::Expr::Postfix(inner, _) => {
            rederive_cloned_expr(inner, salt);
        }
        hir::Expr::Infix(ie) => {
            rederive_cloned_expr(&mut ie.lhs, salt);
            rederive_cloned_expr(&mut ie.rhs, salt);
        }
        hir::Expr::Call(_, args) => {
            for a in args {
                rederive_cloned_expr(a, salt);
            }
        }
        hir::Expr::ArrayLiteral(a) => {
            for e in &mut a.elements {
                rederive_cloned_expr(e, salt);
            }
        }
        hir::Expr::MapLiteral(m) => {
            for (k, v) in &mut m.entries {
                rederive_cloned_expr(k, salt);
                rederive_cloned_expr(v, salt);
            }
        }
        hir::Expr::Index(idx) => {
            rederive_cloned_expr(&mut idx.base, salt);
            rederive_cloned_expr(&mut idx.index, salt);
        }
        hir::Expr::Range(r) => {
            rederive_cloned_expr(&mut r.start, salt);
            rederive_cloned_expr(&mut r.end, salt);
        }
        hir::Expr::StructLiteral(sl) => {
            for (_, v) in &mut sl.fields {
                rederive_cloned_expr(v, salt);
            }
        }
        hir::Expr::FieldAccess(fa) => rederive_cloned_expr(&mut fa.base, salt),
        hir::Expr::FnLiteral(fl) => {
            for a in &mut fl.args {
                rederive_cloned_expr(a, salt);
            }
        }
        hir::Expr::RefArg(ra) => rederive_cloned_expr(&mut ra.operand, salt),
        hir::Expr::String(s) => {
            for part in &mut s.parts {
                if let hir::StringPart::Interpolation(inner) = part {
                    rederive_cloned_expr(inner, salt);
                }
            }
        }
        hir::Expr::Fragment(stmts) => {
            for s in stmts {
                rederive_stmt_inner(s, salt);
            }
        }
        hir::Expr::Path(_)
        | hir::Expr::DivertTarget(_)
        | hir::Expr::ListLiteral(_)
        | hir::Expr::Int(_)
        | hir::Expr::Float(_)
        | hir::Expr::Bool(_)
        | hir::Expr::Null => {}
    }
}

// ─── Lambda stamping (issue #1727) ─────────────────────────────────────
//
// A lifted lambda's `DefinitionId` used to be minted independently in LIR
// lowering (`IdAllocator::alloc_lambda_address`), hashing a path built from
// the *live*, mutated `ctx.scope_path` — the same value the structural
// stamping above mirrors, one statement at a time, as it descends. That
// made a lambda nested inside a `Conditional`/`Sequence`/`ChoiceSet` body
// unreproducible from a fresh HIR-time walk, because nothing walked
// *expressions* at all.
//
// RULED 2026-08-02 (`docs/decision-log.md`): invert the direction. HIR
// mints the id here — using the exact same `scope_path` values the
// structural stamping above already tracks for exactly this reason — and
// `lir::lower::lambda::lower_lambda` only *consumes* `LambdaExpr::
// container_id`, never re-derives it. The functions below extend every
// `stamp_stmt`/`stamp_block` recursion site with an expression walk
// (mirroring `lir::lower::lambda::FreeScan`'s descent, minus binder
// tracking — a lambda's identity depends only on structural scope, never on
// which names are in scope) that finds and stamps every `Expr::Lambda`,
// including ones nested inside another lambda's own body.

/// Recursively stamp every `Expr::Lambda` reachable from `expr` — including
/// a lambda nested inside another lambda's body — with a content-derived
/// container id: `{scope_path}.#lambda-{source start offset}`, the exact
/// scheme `IdAllocator::alloc_lambda_address` used to derive independently.
fn stamp_lambdas_in_expr(
    expr: &mut hir::Expr,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
) {
    match expr {
        hir::Expr::Lambda(l) => stamp_lambda(l, file, scope_path, label_scope, index),
        hir::Expr::Prefix(_, inner) | hir::Expr::Postfix(inner, _) => {
            stamp_lambdas_in_expr(inner, file, scope_path, label_scope, index);
        }
        hir::Expr::Infix(ie) => {
            stamp_lambdas_in_expr(&mut ie.lhs, file, scope_path, label_scope, index);
            stamp_lambdas_in_expr(&mut ie.rhs, file, scope_path, label_scope, index);
        }
        hir::Expr::Call(_, args) => {
            for a in args {
                stamp_lambdas_in_expr(a, file, scope_path, label_scope, index);
            }
        }
        hir::Expr::ArrayLiteral(a) => {
            for e in &mut a.elements {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }
        }
        hir::Expr::MapLiteral(m) => {
            for (k, v) in &mut m.entries {
                stamp_lambdas_in_expr(k, file, scope_path, label_scope, index);
                stamp_lambdas_in_expr(v, file, scope_path, label_scope, index);
            }
        }
        hir::Expr::Index(idx) => {
            stamp_lambdas_in_expr(&mut idx.base, file, scope_path, label_scope, index);
            stamp_lambdas_in_expr(&mut idx.index, file, scope_path, label_scope, index);
        }
        hir::Expr::Range(r) => {
            stamp_lambdas_in_expr(&mut r.start, file, scope_path, label_scope, index);
            stamp_lambdas_in_expr(&mut r.end, file, scope_path, label_scope, index);
        }
        hir::Expr::StructLiteral(sl) => {
            for (_, v) in &mut sl.fields {
                stamp_lambdas_in_expr(v, file, scope_path, label_scope, index);
            }
        }
        hir::Expr::FieldAccess(fa) => {
            stamp_lambdas_in_expr(&mut fa.base, file, scope_path, label_scope, index);
        }
        hir::Expr::FnLiteral(fl) => {
            for a in &mut fl.args {
                stamp_lambdas_in_expr(a, file, scope_path, label_scope, index);
            }
        }
        hir::Expr::RefArg(ra) => {
            stamp_lambdas_in_expr(&mut ra.operand, file, scope_path, label_scope, index);
        }
        hir::Expr::String(s) => {
            for part in &mut s.parts {
                if let hir::StringPart::Interpolation(inner) = part {
                    stamp_lambdas_in_expr(inner, file, scope_path, label_scope, index);
                }
            }
        }
        // Block capture (issue #1839): a captured run's statements keep
        // their own `Stmt::Content`/`EndOfLine` shape and lower through the
        // ordinary per-statement path at the *current* `ctx.scope_path`,
        // unchanged (`lir::lower::expr`'s `Fragment` arm reuses `ctx`
        // as-is, never pushing a new scope) — so a lambda inside one stamps
        // at this same `scope_path`, with fresh local counters exactly like
        // a choice body gets (this fragment is its own isolated statement
        // list, not sharing the enclosing frame's structural counters).
        // `file` is threaded through (issue #2215) so that traversal still
        // gets the same same-file-preferred [`lookup_label_id`] lookup the
        // primary weave walk gets — see that function's doc for the
        // collision this closes. Note a top-level labeled
        // gather/choice/block is never itself one of `stmts` here:
        // `capture_block`'s terminator (`is_plain_content_line`,
        // `hir::lower_native::element`) stops the captured run at any
        // `CONTENT_LINE` bearing a `LABEL`/`CHOICE_POINT`/`DIVERT_STMT`/
        // `TUNNEL_CALL`, specifically so it can never be absorbed into a
        // `Stmt::LabeledBlock`/`Stmt::ChoiceSet`. A label only reaches this
        // arm transitively, through a captured plain content line's own
        // mid-line inline conditional/sequence — the same
        // `InlineConditional`/`InlineSequence` shape handled below, just
        // one level deeper.
        hir::Expr::Fragment(stmts) => {
            let mut seq = 0;
            let mut cc = 0;
            let mut gc = 0;
            for s in stmts {
                stamp_stmt(
                    s,
                    file,
                    scope_path,
                    label_scope,
                    index,
                    &mut seq,
                    &mut cc,
                    &mut gc,
                );
            }
        }
        hir::Expr::Path(_)
        | hir::Expr::DivertTarget(_)
        | hir::Expr::ListLiteral(_)
        | hir::Expr::Int(_)
        | hir::Expr::Float(_)
        | hir::Expr::Bool(_)
        | hir::Expr::Null => {}
    }
}

/// Stamp `l.container_id` from its own source position, then recurse into
/// its body to stamp any lambda nested inside it. A nested lambda's own
/// scope path is the qualified path just minted for `l` — matching
/// `lir::lower::lambda::lower_lambda`'s child `LowerCtx::scope_path`, which
/// is set to exactly that string before lowering the outer lambda's body.
fn stamp_lambda(
    l: &mut hir::LambdaExpr,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
) {
    let offset = u32::from(l.ptr.text_range().start());
    let own_path = qualify(scope_path, &format!("#lambda-{offset}"));
    l.container_id = Some(alloc_address(&own_path));

    match &mut l.body {
        hir::LambdaBody::Expr(e) => stamp_lambdas_in_expr(e, file, &own_path, label_scope, index),
        hir::LambdaBody::Block { stmts, tail } => {
            stamp_lambdas_in_block_stmts(stmts, file, &own_path, label_scope, index);
            if let Some(t) = tail {
                stamp_lambdas_in_expr(t, file, &own_path, label_scope, index);
            }
        }
    }
}

/// Walk a T1b `~ { … }` block-statement list for embedded lambdas.
/// `BlockStmt` never mutates `ctx.scope_path` in LIR lowering (its `If`/
/// `While`/`For` bodies are lexical scopes only, never LIR containers — see
/// the seam rule at `hir::Stmt::LogicBlock`'s doc), so every statement here
/// stamps at the *same* `scope_path` the caller passed in.
fn stamp_lambdas_in_block_stmts(
    stmts: &mut [hir::BlockStmt],
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
) {
    for s in stmts {
        stamp_lambdas_in_block_stmt(s, file, scope_path, label_scope, index);
    }
}

fn stamp_lambdas_in_block_stmt(
    stmt: &mut hir::BlockStmt,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
) {
    match stmt {
        hir::BlockStmt::TempDecl(t) => {
            if let Some(e) = &mut t.value {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }
        }
        hir::BlockStmt::Assignment(a) => {
            stamp_lambdas_in_expr(&mut a.target, file, scope_path, label_scope, index);
            stamp_lambdas_in_expr(&mut a.value, file, scope_path, label_scope, index);
        }
        hir::BlockStmt::Return(r) => {
            if let Some(e) = &mut r.value {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }
            for a in &mut r.onwards_args {
                stamp_lambdas_in_expr(a, file, scope_path, label_scope, index);
            }
        }
        hir::BlockStmt::If(i) => stamp_lambdas_in_if_stmt(i, file, scope_path, label_scope, index),
        hir::BlockStmt::While(w) => {
            stamp_lambdas_in_expr(&mut w.condition, file, scope_path, label_scope, index);
            stamp_lambdas_in_block_stmts(&mut w.body, file, scope_path, label_scope, index);
        }
        hir::BlockStmt::For(f) => {
            stamp_lambdas_in_expr(&mut f.iterable, file, scope_path, label_scope, index);
            stamp_lambdas_in_block_stmts(&mut f.body, file, scope_path, label_scope, index);
        }
        hir::BlockStmt::ExprStmt(e) => {
            stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
        }
        hir::BlockStmt::Await(a) => {
            if let Some(c) = &mut a.condition {
                stamp_lambdas_in_expr(c, file, scope_path, label_scope, index);
            }
        }
        hir::BlockStmt::Break(_) | hir::BlockStmt::Continue(_) => {}
    }
}

fn stamp_lambdas_in_if_stmt(
    i: &mut hir::IfStmt,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
) {
    stamp_lambdas_in_expr(&mut i.condition, file, scope_path, label_scope, index);
    stamp_lambdas_in_block_stmts(&mut i.body, file, scope_path, label_scope, index);
    match &mut i.else_branch {
        Some(hir::ElseBranch::ElseIf(nested)) => {
            stamp_lambdas_in_if_stmt(nested, file, scope_path, label_scope, index);
        }
        Some(hir::ElseBranch::Else(stmts)) => {
            stamp_lambdas_in_block_stmts(stmts, file, scope_path, label_scope, index);
        }
        None => {}
    }
}

/// Walk a `Content` line's interpolations/inline conditionals/inline
/// sequences/spans and tags for embedded lambdas.
fn stamp_lambdas_in_content(
    content: &mut hir::Content,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
) {
    for part in &mut content.parts {
        stamp_lambdas_in_content_part(part, file, scope_path, label_scope, index);
    }
    for tag in &mut content.tags {
        for part in &mut tag.parts {
            stamp_lambdas_in_content_part(part, file, scope_path, label_scope, index);
        }
    }
}

/// A content-embedded inline conditional/sequence (`ContentPart::
/// InlineConditional`/`InlineSequence`) leaves `ctx.scope_path` unchanged in
/// LIR lowering (`lir::lower::content::lower_content_part` never pushes a
/// scope for these, unlike the weave-statement `Stmt::Conditional`/
/// `Stmt::Sequence` forms that reuse the same `hir::Conditional`/`Sequence`
/// structs) — so their branch bodies stamp at the *same* `scope_path`,
/// with fresh local structural counters since these bodies are not part of
/// the enclosing frame's own folded weave.
///
/// `file` is threaded through the branch bodies' `stamp_stmt` calls (issue
/// #2215): native's annotated-brace family shares one grammar rule for a
/// `{if …}`/alternation block regardless of whether it sits on its own line
/// or is embedded mid-line in a `CONTENT_LINE` (`hir::lower_native::cond`'s
/// module doc), so a branch body reached only through this content-embedded
/// path can still contain a full `Stmt::ChoiceSet`/`Stmt::LabeledBlock` with
/// its own `(label)` — collision-prone exactly like the primary weave
/// walk's, see [`lookup_label_id`]'s doc.
fn stamp_lambdas_in_content_part(
    part: &mut hir::ContentPart,
    file: FileId,
    scope_path: &str,
    label_scope: &str,
    index: &SymbolIndex,
) {
    match part {
        hir::ContentPart::Interpolation(e) => {
            stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
        }
        hir::ContentPart::InlineConditional(cond) => {
            if let hir::CondKind::Switch(e) = &mut cond.kind {
                stamp_lambdas_in_expr(e, file, scope_path, label_scope, index);
            }
            for b in &mut cond.branches {
                if let Some(c) = &mut b.condition {
                    stamp_lambdas_in_expr(c, file, scope_path, label_scope, index);
                }
                let mut seq = 0;
                let mut cc = 0;
                let mut gc = 0;
                for s in &mut b.body.stmts {
                    stamp_stmt(
                        s,
                        file,
                        scope_path,
                        label_scope,
                        index,
                        &mut seq,
                        &mut cc,
                        &mut gc,
                    );
                }
            }
        }
        hir::ContentPart::InlineSequence(seq) => {
            for b in &mut seq.branches {
                let mut sc = 0;
                let mut cc = 0;
                let mut gc = 0;
                for s in &mut b.body.stmts {
                    stamp_stmt(
                        s,
                        file,
                        scope_path,
                        label_scope,
                        index,
                        &mut sc,
                        &mut cc,
                        &mut gc,
                    );
                }
            }
        }
        hir::ContentPart::Span(span) => {
            for child in &mut span.children {
                stamp_lambdas_in_content_part(child, file, scope_path, label_scope, index);
            }
        }
        hir::ContentPart::Text(_) | hir::ContentPart::Glue | hir::ContentPart::Spring => {}
    }
}

// ─── Helpers ──────────────────────────────────────────────────────────

/// Create a `DefinitionId` for a synthetic container from its scope path.
///
/// Uses the same `DefaultHasher` scheme as the LIR planner's `IdAllocator`.
fn alloc_address(path: &str) -> DefinitionId {
    let mut hasher = DefaultHasher::new();
    path.hash(&mut hasher);
    DefinitionId::new(DefinitionTag::Address, hasher.finish())
}

/// Look up a labeled container in the analyzer's `SymbolIndex`.
///
/// Returns the analyzer-assigned `DefinitionId` for labels so that
/// diverts resolved by the analyzer point to the same container.
///
/// **File-scoped** (issue #2197 — see `lir::lower::lookup_container_id`'s
/// doc for the full collision this mirrors): M-2d
/// (`is_cross_declared_module_collision`) lets a same-name label/gather/
/// choice in two different *declared* modules coexist in `index.by_name`,
/// so an unscoped `.find()` can pick either one for *both* files stamping
/// a container of that name — silently minting the same `DefinitionId`
/// for two distinct containers. Preferring the entry declared in `file`
/// is the correct self-identity semantic regardless of module-visibility
/// policy.
///
/// Every call site (issue #2215) now has a real `FileId` in scope: the
/// primary weave walk (`stamp_block`/`stamp_stmt`) always did, and the
/// separate lambda-stamping traversal (`stamp_lambdas_in_expr`'s
/// `Fragment` arm, `stamp_lambdas_in_content_part`'s `InlineConditional`/
/// `InlineSequence` arms) now threads one through too — those call sites
/// share the exact same collision this function's file-scoped lookup
/// fixes, reachable through an explicitly *labeled* gather/choice/block
/// nested inside a content-embedded inline conditional/sequence (or, one
/// level deeper, inside such a construct's own mid-line inline
/// conditional/sequence when it sits within a block-capture's captured
/// content line — see the `Fragment` arm's own doc for why a labeled
/// container can never be a top-level statement of a capture), declared
/// identically in two *coexisting* declared modules (confirmed live via
/// the real production compile path, not merely theoretical — see the
/// `brink-test-harness` regression this issue adds).
fn lookup_label_id(index: &SymbolIndex, file: FileId, name: &str) -> Option<DefinitionId> {
    fn is_container(info: &SymbolInfo) -> bool {
        matches!(
            info.kind,
            SymbolKind::Knot | SymbolKind::Stitch | SymbolKind::Label
        )
    }
    index.by_name.get(name).and_then(|ids| {
        if let Some(id) = ids.iter().find(|&&id| {
            index
                .symbols
                .get(&id)
                .is_some_and(|info| is_container(info) && info.file == file)
        }) {
            return Some(*id);
        }
        ids.iter()
            .find(|&&id| index.symbols.get(&id).is_some_and(is_container))
            .copied()
    })
}

/// Qualify a name with a scope path prefix.
fn qualify(scope_path: &str, name: &str) -> String {
    if scope_path.is_empty() {
        name.to_string()
    } else {
        format!("{scope_path}.{name}")
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::panic)]

    use super::*;
    use crate::hir::{ContentPart, Stmt};

    /// Parse ink source, assemble the root-weave `HirFile` the way
    /// `brink-db`'s `lower_file` does, and stamp it against an index that
    /// resolves the one label these fixtures use (`opt`) to a name-hashed
    /// id — the analyzer's real resolution behavior. The label-anchoring
    /// tests assert exactly the stability that resolution provides; the
    /// empty-index fallback is positional and would test the wrong thing.
    /// (The full-pipeline analog runs in `brink-test-harness`, where a
    /// real `symbol_index` is buildable — in-crate, the analyzer dev-dep
    /// would link a second `brink-ir` and its types don't unify.)
    fn stamped(src: &str) -> hir::HirFile {
        let parse = brink_syntax::parse(src);
        let tree = parse.tree();
        let (root_content, _top_knots, _d1) = crate::hir::lower::lower_top_level(FileId(0), &tree);
        let (mut hir_file, _d2) = crate::hir::lower::lower_declarations(FileId(0), &tree);
        hir_file.root_content = root_content;

        let mut index = SymbolIndex::default();
        let label_id = alloc_address("opt");
        index.by_name.insert("opt".to_owned(), vec![label_id]);
        index.symbols.insert(
            label_id,
            SymbolInfo {
                kind: SymbolKind::Label,
                file: FileId(0),
                range: rowan::TextRange::default(),
                id: label_id,
                name: "opt".to_owned(),
                params: Vec::new(),
                detail: None,
                scope: None,
                param_detail: None,
                module: None,
                visibility: crate::symbols::Visibility::Public,
            },
        );

        let mut files = [(FileId(0), hir_file)];
        stamp_container_ids(&mut files, &index, &LookupMap::default());
        let [(_, out)] = files;
        out
    }

    fn as_choice_set(stmt: &Stmt) -> &hir::ChoiceSet {
        match stmt {
            Stmt::ChoiceSet(cs) => cs,
            other => panic!("expected ChoiceSet, got {other:?}"),
        }
    }

    /// First inline conditional's first-branch container id inside a block.
    fn first_inline_cond_branch_id(block: &hir::Block) -> DefinitionId {
        for stmt in &block.stmts {
            if let Stmt::Content(c) = stmt {
                for part in &c.parts {
                    if let ContentPart::InlineConditional(cond) = part {
                        return cond.branches[0]
                            .container_id
                            .expect("branch must be stamped");
                    }
                }
            }
        }
        panic!("no inline conditional found in block");
    }

    /// The #1673/E060 pin: a block-level `{stopping:}` with a once-only
    /// choice in TWO branches is legal ink. Recursing branch bodies under
    /// the wrapper's scope with fresh per-branch counters stamped both
    /// choices `{wrapper}.c-0` — one id on two containers. Branch bodies
    /// now recurse under the branch's own indexed path.
    #[test]
    fn sequence_branch_choices_get_distinct_ids() {
        let hir_file = stamped("{stopping:\n- one\n  * choice A\n- two\n  * choice B\n}\n");
        let seq = hir_file
            .root_content
            .stmts
            .iter()
            .find_map(|s| match s {
                Stmt::Sequence(seq) => Some(seq),
                _ => None,
            })
            .expect("block sequence must lower");
        let ids: Vec<DefinitionId> = seq
            .branches
            .iter()
            .map(|b| {
                let cs = b
                    .body
                    .stmts
                    .iter()
                    .find_map(|s| match s {
                        Stmt::ChoiceSet(cs) => Some(cs),
                        _ => None,
                    })
                    .expect("branch must hold a choice set");
                cs.choices[0].container_id.expect("choice must be stamped")
            })
            .collect();
        assert!(
            ids.len() >= 2,
            "fixture must produce two branches, got {}",
            ids.len()
        );
        assert_ne!(
            ids[0], ids[1],
            "choices in two branches of one sequence must never share an id"
        );
    }

    /// Weave-block-local counters (ruled 2026-08-29): an edit inside one
    /// choice's body must not shift anonymous conditional/sequence ids
    /// inside a SIBLING choice's body. Under the old scope-global counter
    /// the sibling's `b-{n}` moved on every earlier insertion.
    #[test]
    fn sibling_choice_body_ids_survive_edit_in_other_body() {
        let before = stamped("* first\n  {x: a | b}\n* second\n  {y: c | d}\n");
        let after = stamped("* first\n  {z: e | f}\n  {x: a | b}\n* second\n  {y: c | d}\n");

        let second_branch_id = |hf: &hir::HirFile| {
            let cs = as_choice_set(&hf.root_content.stmts[0]);
            first_inline_cond_branch_id(&cs.choices[1].body)
        };
        assert_eq!(
            second_branch_id(&before),
            second_branch_id(&after),
            "an insertion in `first`'s body must not renumber `second`'s body"
        );
    }

    /// Label anchoring (ruled 2026-08-29): a labeled choice's descendants
    /// scope under `#lbl:{id}` — name-hashed, position-independent — so an
    /// unlabeled sibling inserted BEFORE the labeled choice leaves the
    /// whole subtree's ids untouched. The unlabeled contrast case pins
    /// that the anonymous exposure (E157's subject) still exists without
    /// a label.
    #[test]
    fn label_insulates_choice_subtree_from_earlier_siblings() {
        let before = stamped("* (opt) labeled\n  {p: q | r}\n");
        let after = stamped("* padding\n* (opt) labeled\n  {p: q | r}\n");

        let labeled = |hf: &hir::HirFile| {
            let cs = as_choice_set(&hf.root_content.stmts[0]);
            let choice = cs
                .choices
                .iter()
                .find(|c| c.label.is_some())
                .expect("labeled choice present");
            (
                choice.container_id.expect("stamped"),
                first_inline_cond_branch_id(&choice.body),
            )
        };
        assert_eq!(
            labeled(&before),
            labeled(&after),
            "a label must insulate the choice AND its subtree from sibling insertions"
        );

        // Contrast: without the label, the same insertion shifts the
        // choice's own positional id (c-0 → c-1) — the E157 exposure.
        let before_anon = stamped("* labeled\n  {p: q | r}\n");
        let after_anon = stamped("* padding\n* labeled\n  {p: q | r}\n");
        let anon_choice_id = |hf: &hir::HirFile, idx: usize| {
            as_choice_set(&hf.root_content.stmts[0]).choices[idx]
                .container_id
                .expect("stamped")
        };
        assert_ne!(
            anon_choice_id(&before_anon, 0),
            anon_choice_id(&after_anon, 1),
            "an unlabeled choice's id is positional and must shift — the E157 exposure"
        );
    }
}