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
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
//! HIR normalization pass: lift inline sequences/conditionals to block-level.
//!
//! This runs on a **cloned** HIR before LIR lowering. The stored HIR in the
//! project DB stays pristine — the LSP sees the original structure.
//!
//! The transform expands inline `InlineSequence` / `InlineConditional` content
//! parts into block-level `Sequence` / `Conditional` statements. Each branch
//! gets the surrounding text spliced in, producing complete content lines that
//! the recognizer can match as `Plain` or `Template`.
//!
//! ## Post-stage-3 role: the fallback for lines the variant model declines
//!
//! Since the #3274 flip, a line that [`claims_variant_line`] admits — every
//! inline alternative plain-kinded and textual, no conditional, no glue —
//! is NOT lifted: it passes through whole and LIR lowering enumerates it
//! into one variant group over shared alternative containers. The lift is
//! the compilation model for everything the claim declines, and stage 3
//! (#3275) established by reachability analysis that **all of it is
//! load-bearing residue** — none of it retired:
//!
//! * combo-kind lines (`shuffle|once`, `shuffle|stopping`) keep the lift
//!   **by ruling** (2026-08-29): each rendering stays a whole line in the
//!   line table — a translation unit and a VO slot — which moving them to
//!   the shared-inline fragment path would break;
//! * conditional-bearing and structural-branch (divert/glue/nested) lines
//!   can never be whole-line variants, so they lift; the once→stopping
//!   exhausted-branch synthesis stays reachable through exactly these
//!   lines (e.g. a plain `{!…}` beside an inline conditional), as does
//!   [`synthesized_else_branch`] through every lifted no-else conditional;
//! * a cloned **stateful** alternative shares ONE visit-count state across
//!   every branch (the #3275 mixed-line ruling) while each clone keeps its
//!   own body: clone 0 keeps the stamped id, every other clone gets a
//!   derived `container_id` and records the original as its `counter_id`
//!   (#3401, `stamp::rederive_cloned_parts`), and codegen selects that
//!   clone's branch from the ORIGINAL container's count (`TouchVisit`, the
//!   variant path's mechanism). Cloned lines therefore still lift into
//!   whole-line renderings — one line-table entry each, per ruling (1)
//!   above — and the per-lift-level revocation that used to give an
//!   unclaimable branch its own counter is gone.
//!
//! ## Source-order evaluation across a lift (issue #3395, RULED 2026-09-02)
//!
//! Lifting evaluates the construct's own selection first — a conditional's
//! condition, a sequence's visit-count touch or shuffle draw — and only then
//! the branch line that carries the cloned prefix. Ink evaluates a line left
//! to right, so a prefix interpolation with a side effect (`{bump()}{n ==
//! 1:yes|no}`) or a prefix read the condition then mutates (`{n}{bump() ==
//! 1:yes|no}`) observed the wrong state. The lift therefore **hoists**: every
//! `Interpolation` left of the lifted construct (spans included) is first
//! evaluated, in source order, into a hidden `~ temp` ([`TempDecl::synthetic`],
//! named with [`SYNTHETIC_TEMP_PREFIX`]), and the clones spliced into the
//! branches read that temp instead. Each expression still evaluates exactly
//! once; stateful alternatives in the prefix stay shared clones (#3275,
//! unchanged); the suffix is handled at the next lift level, which is where
//! ink evaluates it anyway. A read of a temp this pass minted at an outer
//! level is never re-hoisted — the value is immutable, so re-copying it
//! would only multiply temps. Codegen gives a synthetic temp's direct-call
//! value display-position semantics (the call's printed output is captured
//! into the value the same way `emit_slot_expr` captures it for a call in a
//! slot), so `a{shout()}{cond:…}` still prints `shout`'s text inline where
//! ink prints it, rather than as its own earlier line.
//!
//! [`claims_variant_line`]: crate::lir::lower::recognize::claims_variant_line

use super::types::{
    Block, CondBranch, Conditional, Content, ContentPart, Expr, HirFile, Name, Path, Sequence,
    SequenceBranch, SequenceType, Stmt, Tag, TempDecl,
};

/// Name prefix of every temp the lift-order hoist mints (`$lift0`,
/// `$lift1`, …, numbered per file in hoist order). `$` is not an ink
/// identifier character (`brink_syntax::lexer::is_ident_char` — ASCII
/// alphanumerics, `_`, and the C# reference's Unicode letter ranges), so no
/// authored `~ temp` can ever share a name with one, and
/// `lir::lower::temps::alloc_temps`'s name-keyed slot dedup can never alias
/// the two. The name is otherwise author-invisible: the debugger hides the
/// row (`synthetic`), and only an `.inkt` dump or an XLIFF slot name
/// (`docs/intl-spec.md`, `slot_info`) ever shows it.
pub const SYNTHETIC_TEMP_PREFIX: &str = "$lift";

/// Whether `name` is a temp [`normalize_file`]'s hoist minted (see
/// [`SYNTHETIC_TEMP_PREFIX`]).
#[must_use]
pub fn is_synthetic_temp_name(name: &str) -> bool {
    name.starts_with(SYNTHETIC_TEMP_PREFIX)
}

/// Per-file counter behind [`SYNTHETIC_TEMP_PREFIX`] names — one per
/// [`normalize_file`] call, so names are unique within the file and
/// deterministic across the two compile roads (both normalize each file
/// exactly once, in the same statement order).
#[derive(Default)]
struct Hoister {
    next: u32,
}

impl Hoister {
    fn fresh(&mut self) -> String {
        let n = self.next;
        self.next += 1;
        format!("{SYNTHETIC_TEMP_PREFIX}{n}")
    }
}

// ─── Public entry point ─────────────────────────────────────────────

/// Normalize an entire HIR file by lifting inline sequences/conditionals
/// in all blocks (root, knot bodies, stitch bodies).
pub fn normalize_file(hir: &mut HirFile) {
    let mut hoister = Hoister::default();
    normalize_block(&mut hir.root_content, &mut hoister);
    for knot in &mut hir.knots {
        normalize_block(&mut knot.body, &mut hoister);
        for stitch in &mut knot.stitches {
            normalize_block(&mut stitch.body, &mut hoister);
        }
    }
}

// ─── Block normalization ────────────────────────────────────────────

/// Walk a block's statements, lifting inline constructs to block-level
/// and recursing into contained blocks.
fn normalize_block(block: &mut Block, hoister: &mut Hoister) {
    let old_stmts = std::mem::take(&mut block.stmts);
    let mut new_stmts = Vec::with_capacity(old_stmts.len());

    let mut iter = old_stmts.into_iter().peekable();
    while let Some(stmt) = iter.next() {
        match stmt {
            Stmt::Content(content) => {
                // #3274 (stage-2 flip): a line the variant model claims —
                // all inline alternatives textual and plain-kinded, every
                // enumerated variant recognizable — is NOT lifted. It
                // passes through whole so LIR lowering can enumerate it
                // into one variant group over SHARED alternative
                // containers, which is what makes two stateful
                // alternatives on one line advance together (ink's
                // documented semantics, #3271) instead of the cartesian
                // clone giving each spliced copy its own visit count.
                if crate::lir::lower::recognize::claims_variant_line(&content) {
                    new_stmts.push(Stmt::Content(content));
                    continue;
                }

                // Check if the next stmt is EndOfLine — we absorb it into branches.
                let trailing_eol = matches!(iter.peek(), Some(Stmt::EndOfLine));

                match try_lift_inline(content, trailing_eol, hoister) {
                    Ok(lifted_stmts) => {
                        // Consume the EndOfLine we peeked at.
                        if trailing_eol {
                            let _ = iter.next();
                        }
                        new_stmts.extend(lifted_stmts);
                    }
                    Err(content) => {
                        // No inline construct — pass through.
                        new_stmts.push(Stmt::Content(content));
                    }
                }
            }
            // Recurse into contained blocks for all structural statements.
            Stmt::ChoiceSet(mut cs) => {
                for choice in &mut cs.choices {
                    normalize_block(&mut choice.body, hoister);
                }
                normalize_block(&mut cs.continuation, hoister);
                new_stmts.push(Stmt::ChoiceSet(cs));
            }
            Stmt::LabeledBlock(mut lb) => {
                normalize_block(&mut lb, hoister);
                new_stmts.push(Stmt::LabeledBlock(lb));
            }
            Stmt::Conditional(mut cond) => {
                for branch in &mut cond.branches {
                    normalize_block(&mut branch.body, hoister);
                }
                new_stmts.push(Stmt::Conditional(cond));
            }
            Stmt::Sequence(mut seq) => {
                for branch in &mut seq.branches {
                    normalize_block(&mut branch.body, hoister);
                }
                new_stmts.push(Stmt::Sequence(seq));
            }
            other => new_stmts.push(other),
        }
    }

    block.stmts = new_stmts;

    // Recurse into any newly created Sequence/Conditional branches
    // (handles cartesian product from multiple inline constructs).
    for stmt in &mut block.stmts {
        match stmt {
            Stmt::Sequence(seq) => {
                for branch in &mut seq.branches {
                    normalize_block(&mut branch.body, hoister);
                }
            }
            Stmt::Conditional(cond) => {
                for branch in &mut cond.branches {
                    normalize_block(&mut branch.body, hoister);
                }
            }
            _ => {}
        }
    }
}

// ─── Inline lifting ─────────────────────────────────────────────────

/// Try to lift the first `InlineSequence` or `InlineConditional` from a
/// Content's parts into a block-level statement.
///
/// Returns `Ok(stmts)` with the replacement statements, or `Err(content)`
/// if no inline construct was found (caller passes through unchanged).
fn try_lift_inline(
    content: Content,
    trailing_eol: bool,
    hoister: &mut Hoister,
) -> Result<Vec<Stmt>, Content> {
    let Some(idx) = lift_index(&content.parts) else {
        return Err(content);
    };

    let mut prefix: Vec<ContentPart> = content.parts[..idx].to_vec();
    let suffix: Vec<ContentPart> = content.parts[idx + 1..].to_vec();
    let tags = &content.tags;
    let ptr = content.ptr;

    // #3395: evaluate the prefix's interpolations BEFORE the construct —
    // the lifted statement below runs the construct's selection first, and
    // ink runs the prefix first. `prefix` is rewritten in place to read the
    // hoisted temps, so every clone spliced below shares the one
    // evaluation.
    let mut stmts = hoist_prefix(&mut prefix, hoister, ptr);

    let lifted = match &content.parts[idx] {
        ContentPart::InlineSequence(seq) => {
            let mut branches = Vec::with_capacity(seq.branches.len() + 1);
            for (branch_idx, branch) in seq.branches.iter().enumerate() {
                let mut b = branch.body.clone();
                // #3275 (stage 3a): ids are stamped BEFORE this lift, so
                // the prefix/suffix spliced into each branch can carry
                // stamped container/lambda ids — clones after the first
                // re-derive them, except a cloned stateful alternative,
                // which keeps its id in every clone (shared visit-count
                // state, the ruled ink semantics).
                let salt = lift_salt(nonce_of(seq.container_id), branch_idx);
                let (p, s, t) = salted_splice_sources(&prefix, &suffix, tags, salt);
                splice_around(&mut b, &p, &s, &t, ptr);
                if trailing_eol {
                    b.stmts.push(Stmt::EndOfLine);
                }
                // `splice_around` (suffix) and the EndOfLine push can both
                // change the trailing stmt, so the cloned branch's `tail` may
                // be stale — recompute it (harmless today, load-bearing at the
                // S3 cutover). This pass runs on cloned HIR right before LIR.
                b.recompute_tail();
                branches.push(SequenceBranch {
                    ptr: branch.ptr,
                    body: b,
                });
            }

            // `once` sequences exhaust their branches and then produce nothing.
            // When prefix/suffix text exists, it must still be emitted after
            // exhaustion. Add an extra "exhausted" branch with just prefix+suffix
            // and change to `stopping` so the last branch repeats forever.
            //
            // This is only valid for plain `once` (sequential). `shuffle | once`
            // would shuffle the extra branch into the pool — skip the conversion
            // and fall back to the existing inline sequence lowering for that case.
            let is_plain_once =
                seq.kind.contains(SequenceType::ONCE) && !seq.kind.contains(SequenceType::SHUFFLE);
            let kind = if is_plain_once && (!prefix.is_empty() || !suffix.is_empty()) {
                let mut exhausted = Block::default();
                let salt = lift_salt(nonce_of(seq.container_id), seq.branches.len());
                let (p, s, t) = salted_splice_sources(&prefix, &suffix, tags, salt);
                splice_around(&mut exhausted, &p, &s, &t, ptr);
                if trailing_eol {
                    exhausted.stmts.push(Stmt::EndOfLine);
                }
                exhausted.recompute_tail();
                // Synthesized branch, not sourced from a real arm — the
                // whole sequence's own span is the narrowest available
                // fallback (matches the "no dedicated source node" posture
                // documented on `SequenceBranch`). Its container id is
                // derived from the wrapper's (#3275): no pristine node
                // exists to have been stamped, and the stamp walk cannot
                // predict this synthesis (it depends on prefix/suffix).
                exhausted.container_id = seq
                    .container_id
                    .map(|id| super::stamp::derive_id(id, "exhausted", 0));
                branches.push(SequenceBranch {
                    ptr: seq.ptr,
                    body: exhausted,
                });
                // Replace `once` with `stopping` so the exhausted branch repeats.
                (seq.kind & !SequenceType::ONCE) | SequenceType::STOPPING
            } else {
                seq.kind
            };

            Stmt::Sequence(Sequence {
                ptr: seq.ptr,
                kind,
                branches,
                // Inherited from the pristine stamp (#3275) — the lift
                // never re-mints ids. A clone's `counter_id` (#3401) names
                // the original it shares state with.
                container_id: seq.container_id,
                counter_id: seq.counter_id,
            })
        }
        ContentPart::InlineConditional(cond) => {
            let mut branches = Vec::with_capacity(cond.branches.len() + 1);
            let nonce = conditional_nonce(cond);
            for (branch_idx, branch) in cond.branches.iter().enumerate() {
                let mut body = branch.body.clone();
                let salt = lift_salt(nonce, branch_idx);
                let (p, s, t) = salted_splice_sources(&prefix, &suffix, tags, salt);
                splice_around(&mut body, &p, &s, &t, ptr);
                if trailing_eol {
                    body.stmts.push(Stmt::EndOfLine);
                }
                body.recompute_tail();
                branches.push(CondBranch {
                    ptr: branch.ptr,
                    // B1b (issue #1475): a lifted inline `{if EXPR as n: …}`
                    // keeps its binding — this rebuild is a body rewrite
                    // (prefix/suffix splice), not a re-lowering, so dropping
                    // it here would silently unbind the arm.
                    condition: branch.condition.clone(),
                    binding: branch.binding.clone(),
                    body,
                    // Inherited from the pristine stamp (#3275).
                    container_id: branch.container_id,
                });
            }

            // If no else branch exists, the all-false path still has to carry
            // whatever the line owes regardless of which arm ran: the
            // surrounding text (without this, "A " in `A {cond:B}` would be
            // lost when `cond` is false) AND the line's own end-of-line
            // (#3530). The newline is owed even with no prefix or suffix at
            // all: ink suppresses a line's `\n` only when the line produced
            // no content, and a condition that *prints* is content — so
            // `{f():a}` with a printing, false `f` still ends its line.
            // Synthesizing an arm holding only an `EndOfLine` is safe for the
            // silent case, because the runtime drops a newline with no
            // content before it, leaving `{false:a}` emitting nothing.
            let has_else = branches.iter().any(|b| b.condition.is_none());
            if !has_else && (!prefix.is_empty() || !suffix.is_empty() || trailing_eol) {
                branches.push(synthesized_else_branch(
                    cond,
                    &prefix,
                    &suffix,
                    tags,
                    ptr,
                    trailing_eol,
                ));
            }

            Stmt::Conditional(Conditional {
                ptr: cond.ptr,
                kind: cond.kind.clone(),
                branches,
            })
        }
        _ => unreachable!("position() matched only InlineSequence/InlineConditional"),
    };
    stmts.push(lifted);
    Ok(stmts)
}

// ─── Lift-order hoist (#3395) ───────────────────────────────────────

/// Hoist every `Interpolation` in `prefix` (recursing into spans) into a
/// synthetic `~ temp`, in source order, rewriting each one in place to read
/// its temp. Returns the declarations, in the order they must run. See the
/// module doc's "Source-order evaluation across a lift".
///
/// A bare read of a temp this pass already minted (at an outer lift level)
/// is left alone: it is immutable after its one declaration, so re-hoisting
/// it would only add a temp per lift level.
///
/// The declarations borrow the enclosing line's provenance, when it has
/// one: the `DebugInfo` entry for a hoisted evaluation then anchors to the
/// line it belongs to, which is where an author stepping through it expects
/// to land. A line with no provenance (in-crate tests) gets a synthetic
/// anchor.
fn hoist_prefix(
    prefix: &mut [ContentPart],
    hoister: &mut Hoister,
    line_ptr: Option<crate::Provenance>,
) -> Vec<Stmt> {
    let mut out = Vec::new();
    hoist_parts(prefix, hoister, line_ptr, &mut out);
    out
}

fn hoist_parts(
    parts: &mut [ContentPart],
    hoister: &mut Hoister,
    line_ptr: Option<crate::Provenance>,
    out: &mut Vec<Stmt>,
) {
    for part in parts {
        match part {
            ContentPart::Interpolation(expr) => {
                if is_synthetic_read(expr) {
                    continue;
                }
                let text = hoister.fresh();
                let name = Name {
                    text: text.clone(),
                    range: rowan::TextRange::default(),
                };
                let value = std::mem::replace(expr, synthetic_read(text));
                out.push(Stmt::TempDecl(TempDecl {
                    ptr: line_ptr.unwrap_or_else(|| {
                        crate::Provenance::synthetic(
                            crate::provenance::NodeClass::TempDecl,
                            rowan::TextRange::default(),
                        )
                    }),
                    name,
                    value: Some(value),
                    annotation: None,
                    synthetic: true,
                }));
            }
            ContentPart::Span(span) => hoist_parts(&mut span.children, hoister, line_ptr, out),
            ContentPart::Text(_)
            | ContentPart::Glue
            | ContentPart::Spring
            | ContentPart::InlineConditional(_)
            | ContentPart::InlineSequence(_) => {}
        }
    }
}

/// `{$liftN}` — the read that replaces a hoisted interpolation.
fn synthetic_read(text: String) -> Expr {
    Expr::Path(Path {
        segments: vec![Name {
            text,
            range: rowan::TextRange::default(),
        }],
        range: rowan::TextRange::default(),
        crosses_module_wall: false,
    })
}

fn is_synthetic_read(expr: &Expr) -> bool {
    matches!(expr, Expr::Path(p) if p.segments.len() == 1 && is_synthetic_temp_name(&p.segments[0].text))
}

/// Which inline construct [`try_lift_inline`] lifts.
///
/// A label-bearing `InlineConditional` lifts FIRST when one exists
/// (#3272): whichever construct lifts first is the one that is NOT
/// cloned — every other construct on the line gets spliced into each of
/// its branches. Cloning a labeled construct (a `(dup)` choice inside an
/// `{if …}`) stamps one label's `DefinitionId` onto two containers, which
/// codegen's #1673 uniqueness guard correctly refuses as E060 — an
/// internal-error wording for legal-looking source. Lifting the label
/// carrier first keeps the label on exactly one container; the constructs
/// cloned into its branches are then handled by the recursive normalize
/// pass (a textual alternative becomes a per-branch variant line — an
/// accepted per-branch state split on these mixed lines, #3274's item 3).
/// Otherwise: the first inline construct, the long-standing order.
fn lift_index(parts: &[ContentPart]) -> Option<usize> {
    parts
        .iter()
        .position(|p| match p {
            ContentPart::InlineConditional(cond) => {
                cond.branches.iter().any(|b| block_contains_label(&b.body))
            }
            _ => false,
        })
        .or_else(|| {
            parts.iter().position(|p| {
                matches!(
                    p,
                    ContentPart::InlineSequence(_) | ContentPart::InlineConditional(_)
                )
            })
        })
}

// ─── Label detection (#3272) ────────────────────────────────────────

/// Whether a block contains any labeled construct — a labeled choice, a
/// labeled gather/continuation, or a labeled block — at any depth.
///
/// Used by [`try_lift_inline`] to decide lift order: a construct carrying
/// a label must never be CLONED by the lift (one authored label must name
/// exactly one container), so the inline construct containing it lifts
/// first. Inline constructs nested in content parts recurse too — a label
/// can hide inside a branch's own inline conditional.
fn block_contains_label(block: &Block) -> bool {
    block.label.is_some() || block.stmts.iter().any(stmt_contains_label)
}

fn stmt_contains_label(stmt: &Stmt) -> bool {
    match stmt {
        Stmt::ChoiceSet(cs) => {
            cs.continuation.label.is_some()
                || cs
                    .choices
                    .iter()
                    .any(|c| c.label.is_some() || block_contains_label(&c.body))
                || block_contains_label(&cs.continuation)
        }
        Stmt::LabeledBlock(b) => block_contains_label(b),
        Stmt::Conditional(cond) => cond.branches.iter().any(|b| block_contains_label(&b.body)),
        Stmt::Sequence(seq) => seq.branches.iter().any(|b| block_contains_label(&b.body)),
        Stmt::Content(c) => c.parts.iter().any(content_part_contains_label),
        _ => false,
    }
}

fn content_part_contains_label(part: &ContentPart) -> bool {
    match part {
        ContentPart::InlineConditional(cond) => {
            cond.branches.iter().any(|b| block_contains_label(&b.body))
        }
        ContentPart::InlineSequence(seq) => {
            seq.branches.iter().any(|b| block_contains_label(&b.body))
        }
        ContentPart::Span(span) => span.children.iter().any(content_part_contains_label),
        _ => false,
    }
}

// ─── Splice helper ──────────────────────────────────────────────────

/// Append `extra` onto `parts`, merging into the last element when both the
/// last element of `parts` and the next element of `extra` are `Text`
/// (collapsing doubled whitespace at the seam, e.g. `"Hello "` + `" world"`
/// → `"Hello world"`) — otherwise identical to `parts.extend_from_slice`.
///
/// Splicing prefix/branch/suffix content parts (below) used to leave them
/// as separate adjacent `Text` entries — structurally fine, but it meant a
/// spliced branch's recognizer pass (`lir::lower::recognize::try_recognize`,
/// which only matches a *single* `Text` part as `Plain`, or an
/// interpolation-bearing run as `Template`) could never match a spliced
/// line, no matter how plain its text was. Every branch fell back to
/// `EmitContent`, which still emits one line-table entry **per fragment**
/// — the exact "runtime assembles text from parts, translators see shredded
/// fragments" shape the 2026-03-15 ruling (issue #1667) retired. Merging
/// here, at the one place every splice funnels through, is what actually
/// lets the recognizer see one flat line and produce one `LineEntry` per
/// branch — this pass already did the structural half of the ruling (branch
/// lifting + splicing, added the same day as the ruling); merging was the
/// missing half.
fn extend_merging_text(parts: &mut Vec<ContentPart>, extra: &[ContentPart]) {
    for part in extra {
        if let (Some(ContentPart::Text(last)), ContentPart::Text(next)) = (parts.last_mut(), part) {
            if last.ends_with(char::is_whitespace) && next.starts_with(char::is_whitespace) {
                last.push_str(next.trim_start());
            } else {
                last.push_str(next);
            }
        } else {
            parts.push(part.clone());
        }
    }
}

/// The synthesized else branch a no-else lifted conditional gets when
/// prefix/suffix text must still emit on the all-false path. Not sourced
/// from a real arm — falls back to the whole conditional's own span (see
/// `SequenceBranch`'s doc for the same posture). Its id is derived from
/// the last authored branch's (#3275): a `hir::Conditional` has no
/// wrapper id to derive from, and the stamp walk cannot predict this
/// synthesis (it depends on prefix/suffix).
fn synthesized_else_branch(
    cond: &Conditional,
    prefix: &[ContentPart],
    suffix: &[ContentPart],
    tags: &[Tag],
    ptr: Option<crate::Provenance>,
    trailing_eol: bool,
) -> CondBranch {
    let mut else_body = Block::default();
    let salt = lift_salt(conditional_nonce(cond), cond.branches.len());
    let (p, s, t) = salted_splice_sources(prefix, suffix, tags, salt);
    splice_around(&mut else_body, &p, &s, &t, ptr);
    if trailing_eol {
        else_body.stmts.push(Stmt::EndOfLine);
    }
    else_body.recompute_tail();
    CondBranch {
        ptr: cond.ptr,
        condition: None,
        binding: None,
        body: else_body,
        container_id: cond
            .branches
            .last()
            .and_then(|b| b.container_id)
            .map(|id| super::stamp::derive_id(id, "synth-else", 0)),
    }
}

/// The lifting construct's identity for [`lift_salt`]: a sequence's
/// wrapper id, or `0` when the construct was never stamped. An unstamped
/// construct's clones carry no ids to re-derive, so the nonce is moot
/// there; `0` just keeps the salt deterministic.
fn nonce_of(id: Option<brink_format::DefinitionId>) -> u64 {
    id.map_or(0, brink_format::DefinitionId::to_raw)
}

/// A `hir::Conditional` has no wrapper id; its first stamped branch id is
/// unique to the construct and serves the same purpose.
fn conditional_nonce(cond: &Conditional) -> u64 {
    nonce_of(cond.branches.first().and_then(|b| b.container_id))
}

/// The per-branch salt for one lift level. `0` (branch 0) keeps the stamped
/// ids — the first clone is the one container each id stays live on
/// (#3275). Every other branch mixes the lifting construct's own identity
/// with its index, so two lift LEVELS can never cancel: with a bare index
/// the clone at (outer 0, inner 1) and the clone at (outer 1, inner 0) both
/// derived to `derive(id, 1)` — the identity at 0 made the composition
/// commutative — and three inline conditionals on one line collided on a
/// `DefinitionId` (issue #3386, E060).
fn lift_salt(nonce: u64, branch_idx: usize) -> u64 {
    if branch_idx == 0 {
        return 0;
    }
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    std::hash::Hash::hash(&nonce, &mut hasher);
    std::hash::Hash::hash(&(branch_idx as u64), &mut hasher);
    std::hash::Hasher::finish(&hasher).max(1)
}

/// Clone the spliced prefix/suffix/tags for the branch at `salt`,
/// re-deriving cloned container/lambda ids (#3275 stage 3a — see
/// `stamp.rs`'s clone-id section). `salt == 0` keeps the stamped ids: the
/// first branch's clone is the one container each stamped id stays live
/// on. A cloned stateful alternative keeps its id at EVERY salt (shared
/// visit-count state, ruled 2026-08-29); LIR emits that shared container
/// once. Un-stamped parts (in-crate tests that normalize without
/// stamping) pass through unchanged — derivation only rewrites ids that
/// exist.
fn salted_splice_sources(
    prefix: &[ContentPart],
    suffix: &[ContentPart],
    tags: &[Tag],
    salt: u64,
) -> (Vec<ContentPart>, Vec<ContentPart>, Vec<Tag>) {
    let mut p = prefix.to_vec();
    let mut s = suffix.to_vec();
    let mut t = tags.to_vec();
    super::stamp::rederive_cloned_parts(&mut p, salt);
    super::stamp::rederive_cloned_parts(&mut s, salt);
    for tag in &mut t {
        super::stamp::rederive_cloned_parts(&mut tag.parts, salt);
    }
    (p, s, t)
}

/// Splice prefix/suffix text around a branch block's content.
///
/// Handles these cases:
/// - **Single Content stmt**: parts = prefix + original + suffix, merge tags
/// - **Empty block**: create new Content with prefix + suffix
/// - **Multiple stmts, first is Content**: prepend prefix to first Content's parts
/// - **Multiple stmts, last is Content**: append suffix to last Content's parts
/// - **No Content stmts** (e.g., just Divert): insert new Content at position 0
fn splice_around(
    block: &mut Block,
    prefix: &[ContentPart],
    suffix: &[ContentPart],
    tags: &[Tag],
    ptr: Option<crate::Provenance>,
) {
    let has_prefix = !prefix.is_empty();
    let has_suffix = !suffix.is_empty();

    if !has_prefix && !has_suffix && tags.is_empty() {
        return;
    }

    // Empty block — create a new Content with prefix + suffix.
    if block.stmts.is_empty() {
        let mut parts = prefix.to_vec();
        extend_merging_text(&mut parts, suffix);
        if !parts.is_empty() || !tags.is_empty() {
            block.stmts.push(Stmt::Content(Content {
                ptr,
                parts,
                tags: tags.to_vec(),
            }));
        }
        return;
    }

    // Single Content stmt — splice into it directly.
    if block.stmts.len() == 1
        && let Stmt::Content(ref mut c) = block.stmts[0]
    {
        let mut new_parts = prefix.to_vec();
        let original = std::mem::take(&mut c.parts);
        extend_merging_text(&mut new_parts, &original);
        extend_merging_text(&mut new_parts, suffix);
        c.parts = new_parts;
        c.tags.extend_from_slice(tags);
        // The branch's own `ptr` (if any) covers only the branch body's own
        // node — narrower than the whole spliced line once prefix/suffix
        // text is actually merged in (review finding, #3202). When that's
        // happening and the caller handed us a real enclosing-line `ptr`,
        // it is the more correct answer and must win over the branch's own,
        // even though the branch's own is already `Some` (e.g.
        // `wrap_content_as_block`/native's per-branch provenance) — the
        // `c.ptr.is_none()` half of this condition is what covers the
        // no-splice case, where the branch's own body genuinely is the
        // whole line and there is nothing to prefer over it except an
        // actual gap.
        if ((has_prefix || has_suffix) && ptr.is_some()) || c.ptr.is_none() {
            c.ptr = ptr;
        }
        return;
    }

    // Multiple stmts — find first and last Content to splice prefix/suffix.
    let first_content_idx = block
        .stmts
        .iter()
        .position(|s| matches!(s, Stmt::Content(_)));
    let last_content_idx = block
        .stmts
        .iter()
        .rposition(|s| matches!(s, Stmt::Content(_)));

    if let (Some(first), Some(last)) = (first_content_idx, last_content_idx) {
        // Prepend prefix to first Content.
        if has_prefix && let Stmt::Content(ref mut c) = block.stmts[first] {
            let mut new_parts = prefix.to_vec();
            let original = std::mem::take(&mut c.parts);
            extend_merging_text(&mut new_parts, &original);
            c.parts = new_parts;
            c.tags.extend_from_slice(tags);
            // Same enclosing-line-wins rule as the single-Content-stmt case
            // above (review finding, #3202) — `has_prefix` is always true
            // in this branch, so the splice is genuinely happening here.
            if ptr.is_some() || c.ptr.is_none() {
                c.ptr = ptr;
            }
        } else if !tags.is_empty()
            && let Stmt::Content(ref mut c) = block.stmts[first]
        {
            c.tags.extend_from_slice(tags);
        }
        // Append suffix to last Content.
        if has_suffix && let Stmt::Content(ref mut c) = block.stmts[last] {
            extend_merging_text(&mut c.parts, suffix);
        }
    } else {
        // No Content stmts at all — insert a new Content at position 0.
        let mut parts = prefix.to_vec();
        extend_merging_text(&mut parts, suffix);
        if !parts.is_empty() || !tags.is_empty() {
            block.stmts.insert(
                0,
                Stmt::Content(Content {
                    ptr,
                    parts,
                    tags: tags.to_vec(),
                }),
            );
        }
    }
}

#[cfg(test)]
#[expect(clippy::panic)]
mod tests {
    use super::super::types::*;
    use super::normalize_file;

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

    fn dummy_ptr() -> crate::Provenance {
        crate::Provenance::synthetic(
            crate::provenance::NodeClass::Content,
            rowan::TextRange::new(rowan::TextSize::new(0), rowan::TextSize::new(6)),
        )
    }

    fn dummy_tag_ptr() -> crate::Provenance {
        crate::Provenance::synthetic(
            crate::provenance::NodeClass::Tag,
            rowan::TextRange::new(rowan::TextSize::new(6), rowan::TextSize::new(10)),
        )
    }

    fn dummy_choice_ptr() -> crate::Provenance {
        crate::Provenance::synthetic(
            crate::provenance::NodeClass::Choice,
            rowan::TextRange::new(rowan::TextSize::new(0), rowan::TextSize::new(8)),
        )
    }

    fn text(s: &str) -> ContentPart {
        ContentPart::Text(s.to_string())
    }

    fn mk_content(parts: Vec<ContentPart>) -> Content {
        Content {
            ptr: Some(dummy_ptr()),
            parts,
            tags: Vec::new(),
        }
    }

    fn mk_content_with_tags(parts: Vec<ContentPart>, tags: Vec<Tag>) -> Content {
        Content {
            ptr: Some(dummy_ptr()),
            parts,
            tags,
        }
    }

    fn mk_inline_seq(kind: SequenceType, branches: Vec<Vec<ContentPart>>) -> ContentPart {
        let ptr = dummy_ptr();
        ContentPart::InlineSequence(Sequence {
            ptr,
            kind,
            branches: branches
                .into_iter()
                .map(|parts| {
                    let stmts = if parts.is_empty() {
                        Vec::new()
                    } else {
                        vec![Stmt::Content(Content {
                            ptr: Some(ptr),
                            parts,
                            tags: Vec::new(),
                        })]
                    };
                    let tail = crate::tail_from_stmts(&stmts);
                    SequenceBranch {
                        ptr,
                        body: Block {
                            label: None,
                            stmts,
                            container_id: None,
                            tail,
                        },
                    }
                })
                .collect(),
            container_id: None,
            counter_id: None,
        })
    }

    fn mk_inline_cond(branches: Vec<(Option<Expr>, Vec<ContentPart>)>) -> ContentPart {
        let ptr = dummy_ptr();
        ContentPart::InlineConditional(Conditional {
            ptr,
            kind: CondKind::InitialCondition,
            branches: branches
                .into_iter()
                .map(|(condition, parts)| {
                    let stmts = if parts.is_empty() {
                        Vec::new()
                    } else {
                        vec![Stmt::Content(Content {
                            ptr: Some(ptr),
                            parts,
                            tags: Vec::new(),
                        })]
                    };
                    let tail = crate::tail_from_stmts(&stmts);
                    CondBranch {
                        ptr,
                        condition,
                        binding: None,
                        body: Block {
                            label: None,
                            stmts,
                            container_id: None,
                            tail,
                        },
                        container_id: None,
                    }
                })
                .collect(),
        })
    }

    fn mk_tag(s: &str) -> Tag {
        Tag {
            parts: vec![ContentPart::Text(s.to_string())],
            ptr: dummy_tag_ptr(),
        }
    }

    fn mk_block(stmts: Vec<Stmt>) -> Block {
        let tail = crate::tail_from_stmts(&stmts);
        Block {
            label: None,
            stmts,
            container_id: None,
            tail,
        }
    }

    fn mk_hir(stmts: Vec<Stmt>) -> HirFile {
        HirFile {
            root_content: mk_block(stmts),
            knots: Vec::new(),
            variables: Vec::new(),
            constants: Vec::new(),
            lists: Vec::new(),
            structs: Vec::new(),
            externals: Vec::new(),
            includes: Vec::new(),
            module: None,
            imports: Vec::new(),
            visibility: Vec::new(),
            was_directives: Vec::new(),
            allow_scopes: Vec::new(),
            element_matches: Vec::new(),
            cue_names: Vec::new(),
            native: false,
            claim_handlers: Vec::new(),
            dispatch_handlers: Vec::new(),
        }
    }

    /// Extract the text parts from a Content stmt, concatenated.
    fn content_text(content: &Content) -> String {
        content
            .parts
            .iter()
            .filter_map(|p| {
                if let ContentPart::Text(s) = p {
                    Some(s.as_str())
                } else {
                    None
                }
            })
            .collect()
    }

    // ─── Tests ──────────────────────────────────────────────────────

    /// Regression (S1 review F1): an inline-conditional branch whose body is
    /// a bare divert carries `tail == Diverge` at construction. The lift
    /// prepends surrounding text and appends a trailing `EndOfLine`, so the
    /// lifted branch no longer ends in a terminator — its `tail` must flip to
    /// `Unit`. `normalize.rs` runs on cloned HIR right before LIR, so a stale
    /// `tail` here is the closest one to the eventual consumer.
    #[test]
    fn lifted_conditional_branch_with_divert_recomputes_tail() {
        let divert_body = mk_block(vec![Stmt::Divert(Divert {
            ptr: None,
            target: DivertTarget {
                path: DivertPath::End,
                args: Vec::new(),
            },
        })]);
        assert!(
            matches!(divert_body.tail, Tail::Diverge(_)),
            "precondition: a bare-divert body has a Diverge tail"
        );
        let inline_cond = ContentPart::InlineConditional(Conditional {
            ptr: dummy_ptr(),
            kind: CondKind::InitialCondition,
            branches: vec![CondBranch {
                ptr: dummy_ptr(),
                condition: Some(Expr::Bool(true)),
                binding: None,
                body: divert_body,
                container_id: None,
            }],
        });
        // Surrounding text forces the prefix/else-synthesis path; the trailing
        // EndOfLine drives the trailing-eol append inside the lift.
        let content = mk_content(vec![text("A "), inline_cond]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);

        normalize_file(&mut hir);

        let cond = hir
            .root_content
            .stmts
            .iter()
            .find_map(|s| match s {
                Stmt::Conditional(c) => Some(c),
                _ => None,
            })
            .expect("inline conditional lifted to a Conditional stmt");
        // Every lifted branch body's tail must match its stmts — no stale
        // Diverge left behind after the EndOfLine append.
        for branch in &cond.branches {
            assert_eq!(
                branch.body.tail,
                crate::tail_from_stmts(&branch.body.stmts),
                "lifted branch tail must match its stmts (not stale): {:?}",
                branch.body
            );
        }
    }

    #[test]
    fn simple_sequence_lift() {
        // "It's " + {stopping: "a fine", "a good"} + " day." — plus a
        // trailing Glue: an all-textual stateful line is claimed by the
        // #3274 variant path and no longer lifts, and Glue is one of the
        // shapes the claim refuses, so this keeps exercising the lift.
        let content = mk_content(vec![
            text("It's "),
            mk_inline_seq(
                SequenceType::STOPPING,
                vec![vec![text("a fine")], vec![text("a good")]],
            ),
            text(" day."),
            ContentPart::Glue,
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        // Should be a single Sequence stmt.
        assert_eq!(hir.root_content.stmts.len(), 1);
        let Stmt::Sequence(seq) = &hir.root_content.stmts[0] else {
            panic!("expected Sequence, got {:?}", hir.root_content.stmts[0]);
        };
        assert_eq!(seq.kind, SequenceType::STOPPING);
        assert_eq!(seq.branches.len(), 2);

        // Branch 0: Content("It's a fine day.") + EndOfLine
        assert_eq!(seq.branches[0].body.stmts.len(), 2);
        let Stmt::Content(c0) = &seq.branches[0].body.stmts[0] else {
            panic!("expected Content");
        };
        assert_eq!(content_text(c0), "It's a fine day.");
        assert!(matches!(seq.branches[0].body.stmts[1], Stmt::EndOfLine));

        // Branch 1: Content("It's a good day.") + EndOfLine
        let Stmt::Content(c1) = &seq.branches[1].body.stmts[0] else {
            panic!("expected Content");
        };
        assert_eq!(content_text(c1), "It's a good day.");
        assert!(matches!(seq.branches[1].body.stmts[1], Stmt::EndOfLine));
    }

    #[test]
    fn simple_conditional_lift() {
        // "I'm " + {happy: "very", "not"} + " pleased."
        let cond_expr = Expr::Bool(true);
        let content = mk_content(vec![
            text("I'm "),
            mk_inline_cond(vec![
                (Some(cond_expr), vec![text("very")]),
                (None, vec![text("not")]),
            ]),
            text(" pleased."),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        assert_eq!(hir.root_content.stmts.len(), 1);
        let Stmt::Conditional(cond) = &hir.root_content.stmts[0] else {
            panic!("expected Conditional");
        };
        assert_eq!(cond.branches.len(), 2);

        let Stmt::Content(c0) = &cond.branches[0].body.stmts[0] else {
            panic!("expected Content");
        };
        assert_eq!(content_text(c0), "I'm very pleased.");

        let Stmt::Content(c1) = &cond.branches[1].body.stmts[0] else {
            panic!("expected Content");
        };
        assert_eq!(content_text(c1), "I'm not pleased.");
    }

    #[test]
    fn tag_propagation() {
        // Trailing Glue keeps this off the #3274 variant path (see
        // simple_sequence_lift) so tag propagation through the lift stays
        // covered.
        let content = mk_content_with_tags(
            vec![
                text("Hello "),
                mk_inline_seq(
                    SequenceType::CYCLE,
                    vec![vec![text("world")], vec![text("there")]],
                ),
                ContentPart::Glue,
            ],
            vec![mk_tag("greeting")],
        );
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let Stmt::Sequence(seq) = &hir.root_content.stmts[0] else {
            panic!("expected Sequence");
        };

        // Tags should be on the first content of each branch.
        let Stmt::Content(c0) = &seq.branches[0].body.stmts[0] else {
            panic!("expected Content");
        };
        assert_eq!(c0.tags.len(), 1);

        let Stmt::Content(c1) = &seq.branches[1].body.stmts[0] else {
            panic!("expected Content");
        };
        assert_eq!(c1.tags.len(), 1);
    }

    #[test]
    fn eol_absorption() {
        // Without trailing EOL — no EndOfLine in branches.
        // Trailing Glue keeps this off the #3274 variant path (see
        // simple_sequence_lift).
        let content = mk_content(vec![
            text("a "),
            mk_inline_seq(
                SequenceType::STOPPING,
                vec![vec![text("x")], vec![text("y")]],
            ),
            text(" b"),
            ContentPart::Glue,
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content)]);
        normalize_file(&mut hir);

        let Stmt::Sequence(seq) = &hir.root_content.stmts[0] else {
            panic!("expected Sequence");
        };
        // No EndOfLine since there was no trailing EOL.
        assert_eq!(seq.branches[0].body.stmts.len(), 1);
    }

    #[test]
    fn empty_branch_gets_prefix_suffix() {
        // "It's " + {shuffle|once: "a", "", "c"} + " fine" — a combo kind:
        // stage 1's admission routes combos to the lift (their exhaustion
        // logic lives there), so this keeps exercising the splice; the
        // plain-stopping spelling of this line is #3274 variant-claimed
        // and no longer lifts.
        let content = mk_content(vec![
            text("It's "),
            mk_inline_seq(
                SequenceType::SHUFFLE | SequenceType::ONCE,
                vec![vec![text("a")], vec![], vec![text("c")]],
            ),
            text(" fine"),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let Stmt::Sequence(seq) = &hir.root_content.stmts[0] else {
            panic!("expected Sequence");
        };
        assert_eq!(seq.branches.len(), 3);

        // Branch 1 (empty) should still get prefix+suffix, seam-collapsed to
        // a single space — issue #1667: `extend_merging_text` now merges
        // adjacent `Text` parts at every splice seam (prefix/branch/suffix)
        // so the recognizer sees one flat `Text` part and can match `Plain`.
        // Before that fix, "It's " + "" + " fine" stayed three separate
        // parts (never recognized, always `EmitContent`); at runtime the
        // unrecognized path's `Spring` opcodes collapsed the same double
        // whitespace anyway, so this also matches actual rendered output,
        // not just the new intermediate shape.
        let Stmt::Content(c1) = &seq.branches[1].body.stmts[0] else {
            panic!("expected Content in empty branch");
        };
        assert_eq!(content_text(c1), "It's fine");
        assert_eq!(
            c1.parts.len(),
            1,
            "prefix+suffix should merge into a single Text part so the \
             recognizer can match Plain"
        );
    }

    #[test]
    fn no_inline_passes_through() {
        let content = mk_content(vec![text("Just plain text.")]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        // Should be unchanged: Content + EndOfLine.
        assert_eq!(hir.root_content.stmts.len(), 2);
        assert!(matches!(hir.root_content.stmts[0], Stmt::Content(_)));
        assert!(matches!(hir.root_content.stmts[1], Stmt::EndOfLine));
    }

    #[test]
    fn recursion_into_choice_body() {
        // A choice with an inline conditional in its body (a conditional:
        // inline sequences of this shape are #3274 variant-claimed and no
        // longer lift, and this test is about recursion into the body).
        let body_content = mk_content(vec![
            text("It's "),
            mk_inline_cond(vec![
                (Some(Expr::Bool(true)), vec![text("a")]),
                (None, vec![text("b")]),
            ]),
        ]);
        let choice = Choice {
            ptr: dummy_choice_ptr(),
            is_sticky: false,
            is_fallback: false,
            label: None,
            condition: None,
            binding: None,
            start_content: Some(mk_content(vec![text("Pick")])),
            bracket_content: None,
            inner_content: None,
            tags: Vec::new(),
            body: mk_block(vec![Stmt::Content(body_content), Stmt::EndOfLine]),
            container_id: None,
        };
        let cs = ChoiceSet {
            choices: vec![choice],
            continuation: mk_block(vec![]),
            context: ChoiceSetContext::Weave,
            depth: 1,
            gather_id: None,
        };
        let mut hir = mk_hir(vec![Stmt::ChoiceSet(Box::new(cs))]);
        normalize_file(&mut hir);

        // The choice body should have been normalized.
        let Stmt::ChoiceSet(ref cs) = hir.root_content.stmts[0] else {
            panic!("expected ChoiceSet");
        };
        assert_eq!(cs.choices[0].body.stmts.len(), 1);
        assert!(matches!(cs.choices[0].body.stmts[0], Stmt::Conditional(_)));
    }

    #[test]
    fn recursion_into_conditional_branches() {
        // Inner inline conditional, not a sequence — see
        // recursion_into_choice_body for why.
        let body_content = mk_content(vec![
            text("Hello "),
            mk_inline_cond(vec![
                (Some(Expr::Bool(true)), vec![text("x")]),
                (None, vec![text("y")]),
            ]),
        ]);
        let cond = Conditional {
            ptr: dummy_ptr(),
            kind: CondKind::IfElse,
            branches: vec![CondBranch {
                ptr: dummy_ptr(),
                condition: Some(Expr::Bool(true)),
                binding: None,
                body: mk_block(vec![Stmt::Content(body_content), Stmt::EndOfLine]),
                container_id: None,
            }],
        };
        let mut hir = mk_hir(vec![Stmt::Conditional(cond)]);
        normalize_file(&mut hir);

        let Stmt::Conditional(ref c) = hir.root_content.stmts[0] else {
            panic!("expected Conditional");
        };
        // The branch body should have been normalized — a lifted
        // Conditional instead of Content+EOL.
        assert_eq!(c.branches[0].body.stmts.len(), 1);
        assert!(matches!(c.branches[0].body.stmts[0], Stmt::Conditional(_)));
    }

    /// #3274 (stage-2 flip): a line the variant model claims — every
    /// inline alternative plain-kinded and textual — is NOT lifted. The
    /// cartesian lift is exactly what gave each spliced clone of the
    /// second alternative its own visit count (#3271); the un-lifted line
    /// reaches LIR whole, where enumeration compiles it over SHARED
    /// alternative containers.
    #[test]
    fn variant_claimed_line_is_not_lifted() {
        let content = mk_content(vec![
            text("Line: "),
            mk_inline_seq(
                SequenceType::STOPPING,
                vec![vec![text("a")], vec![text("b")]],
            ),
            text(" "),
            mk_inline_seq(
                SequenceType::STOPPING,
                vec![vec![text("x")], vec![text("y")]],
            ),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        assert_eq!(
            hir.root_content.stmts.len(),
            2,
            "claimed line passes through whole: {:?}",
            hir.root_content.stmts
        );
        assert!(matches!(hir.root_content.stmts[0], Stmt::Content(_)));
        assert!(matches!(hir.root_content.stmts[1], Stmt::EndOfLine));
    }

    /// A `shuffle|once` combination is NOT claimed (stage 1's admission
    /// routes combos to the fallback where their exhaustion logic lives) —
    /// the lift must still run for it.
    #[test]
    fn combo_kind_line_still_lifts() {
        let content = mk_content(vec![
            text("Line: "),
            mk_inline_seq(
                SequenceType::SHUFFLE | SequenceType::ONCE,
                vec![vec![text("a")], vec![text("b")]],
            ),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);
        assert!(
            matches!(hir.root_content.stmts[0], Stmt::Sequence(_)),
            "combo kinds keep the lift: {:?}",
            hir.root_content.stmts[0]
        );
    }

    /// #3272: an inline conditional whose branch carries a LABELED choice
    /// lifts FIRST, whatever its position on the line — whichever
    /// construct lifts first is the one that is not cloned, and cloning a
    /// labeled construct stamps one label onto two containers (the E060
    /// internal error on legal-looking source).
    #[test]
    fn label_bearing_conditional_lifts_first() {
        fn count_labeled(block: &Block) -> usize {
            block
                .stmts
                .iter()
                .map(|s| match s {
                    Stmt::ChoiceSet(cs) => {
                        cs.choices
                            .iter()
                            .map(|c| usize::from(c.label.is_some()) + count_labeled(&c.body))
                            .sum::<usize>()
                            + count_labeled(&cs.continuation)
                    }
                    Stmt::LabeledBlock(b) => count_labeled(b),
                    Stmt::Conditional(c) => c.branches.iter().map(|b| count_labeled(&b.body)).sum(),
                    Stmt::Sequence(sq) => sq.branches.iter().map(|b| count_labeled(&b.body)).sum(),
                    _ => 0,
                })
                .sum()
        }

        let labeled_choice = Choice {
            ptr: dummy_choice_ptr(),
            is_sticky: false,
            is_fallback: false,
            label: Some(Name {
                text: "dup".to_string(),
                range: rowan::TextRange::new(rowan::TextSize::new(0), rowan::TextSize::new(3)),
            }),
            condition: None,
            binding: None,
            start_content: Some(mk_content(vec![text("Pick me")])),
            bracket_content: None,
            inner_content: None,
            tags: Vec::new(),
            body: mk_block(vec![]),
            container_id: None,
        };
        let cs = ChoiceSet {
            choices: vec![labeled_choice],
            continuation: mk_block(vec![]),
            context: ChoiceSetContext::Weave,
            depth: 1,
            gather_id: None,
        };
        let cond_body = mk_block(vec![Stmt::ChoiceSet(Box::new(cs))]);
        let tail = crate::tail_from_stmts(&cond_body.stmts);
        let inline_cond = ContentPart::InlineConditional(Conditional {
            ptr: dummy_ptr(),
            kind: CondKind::InitialCondition,
            branches: vec![CondBranch {
                ptr: dummy_ptr(),
                condition: Some(Expr::Bool(true)),
                binding: None,
                body: Block {
                    label: None,
                    stmts: cond_body.stmts,
                    container_id: None,
                    tail,
                },
                container_id: None,
            }],
        });
        // The shuffle alternative comes FIRST in part order — the old
        // first-construct rule would lift it and clone the labeled
        // conditional into both branches.
        let content = mk_content(vec![
            text("Pre "),
            mk_inline_seq(
                SequenceType::SHUFFLE,
                vec![vec![text("one")], vec![text("two")]],
            ),
            text(" mid "),
            inline_cond,
            text(" post."),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let Stmt::Conditional(cond) = &hir.root_content.stmts[0] else {
            panic!(
                "label-bearing conditional must lift first, got {:?}",
                hir.root_content.stmts[0]
            );
        };
        // The labeled choice exists exactly once across the whole tree.
        let total: usize = cond.branches.iter().map(|b| count_labeled(&b.body)).sum();
        assert_eq!(total, 1, "the labeled choice must not be cloned");
    }

    /// Regression (review finding, #3202): the enclosing line's own `ptr`
    /// must win over a lifted branch's own (narrower) `ptr` once
    /// prefix/suffix text is actually spliced in — a real branch-node `ptr`
    /// is not proof the branch already covers the whole line.
    ///
    /// Before this fix, `splice_around`'s `if c.ptr.is_none() { c.ptr = ptr }`
    /// only ever filled in a location when the branch itself had none. Once
    /// callers started stamping a real (but narrower) branch-node `ptr`
    /// (`wrap_content_as_block`/native's per-branch provenance, both fixed
    /// for #3181), that fallback stopped firing — so a lifted line like
    /// `"Ready {h: high|low} now."` kept only the branch's own sub-range
    /// (e.g. just `" high"`) instead of the whole line's byte-exact span,
    /// even though the whole-line `ptr` was sitting right there, passed to
    /// `splice_around` and ignored.
    fn range(lo: u32, hi: u32) -> rowan::TextRange {
        rowan::TextRange::new(rowan::TextSize::new(lo), rowan::TextSize::new(hi))
    }

    #[test]
    fn spliced_branch_takes_enclosing_line_location_over_its_own_narrower_one() {
        // Whole line "Ready {h: high|low} now." spans 0..25; the branch's
        // own inline-conditional-body node ("high") spans only 8..12 —
        // deliberately narrower and disjoint-looking from the enclosing
        // span's numbers, so a test failure can't be mistaken for the two
        // ranges coincidentally matching.
        let enclosing_ptr =
            crate::Provenance::synthetic(crate::provenance::NodeClass::Content, range(0, 25));
        let branch_ptr =
            crate::Provenance::synthetic(crate::provenance::NodeClass::Content, range(8, 12));

        let branch_body_stmts = vec![Stmt::Content(Content {
            ptr: Some(branch_ptr),
            parts: vec![text("high")],
            tags: Vec::new(),
        })];
        let tail = crate::tail_from_stmts(&branch_body_stmts);
        let inline_cond = ContentPart::InlineConditional(Conditional {
            ptr: dummy_ptr(),
            kind: CondKind::InitialCondition,
            branches: vec![CondBranch {
                ptr: dummy_ptr(),
                condition: Some(Expr::Bool(true)),
                binding: None,
                body: Block {
                    label: None,
                    stmts: branch_body_stmts,
                    container_id: None,
                    tail,
                },
                container_id: None,
            }],
        });
        let content = Content {
            ptr: Some(enclosing_ptr),
            parts: vec![text("Ready "), inline_cond, text(" now.")],
            tags: Vec::new(),
        };
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);

        normalize_file(&mut hir);

        let Stmt::Conditional(cond) = &hir.root_content.stmts[0] else {
            panic!("expected Conditional, got {:?}", hir.root_content.stmts[0]);
        };
        let Stmt::Content(spliced) = &cond.branches[0].body.stmts[0] else {
            panic!(
                "expected spliced Content, got {:?}",
                cond.branches[0].body.stmts[0]
            );
        };
        assert_eq!(content_text(spliced), "Ready high now.");
        assert_eq!(
            spliced.ptr,
            Some(enclosing_ptr),
            "spliced branch must carry the whole line's location, not its own narrower one: {:?}",
            spliced.ptr
        );
    }

    #[test]
    fn cloned_sequence_keeps_its_id_on_clone_zero_and_counts_on_it_elsewhere() {
        // #3401: `{a|b}{c|d|e} <>` — the glue keeps every line off the
        // variant path. `{a|b}` lifts and clones `{c|d|e}` into both
        // branches; each clone lifts again into whole-line renderings
        // (`ac|ad|ae`, `bc|bd|be`), so the clone in branch 1 needs its own
        // wrapper id — and must count on the original's.
        use brink_format::{DefinitionId, DefinitionTag};
        let id = |raw: u64| DefinitionId::new(DefinitionTag::Address, raw);
        let ContentPart::InlineSequence(mut outer) = mk_inline_seq(
            SequenceType::STOPPING,
            vec![vec![text("a")], vec![text("b")]],
        ) else {
            panic!("mk_inline_seq builds an InlineSequence");
        };
        outer.container_id = Some(id(1));
        let ContentPart::InlineSequence(mut inner) = mk_inline_seq(
            SequenceType::STOPPING,
            vec![vec![text("c")], vec![text("d")], vec![text("e")]],
        ) else {
            panic!("mk_inline_seq builds an InlineSequence");
        };
        inner.container_id = Some(id(2));
        let content = mk_content(vec![
            ContentPart::InlineSequence(outer),
            ContentPart::InlineSequence(inner),
            ContentPart::Glue,
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let Stmt::Sequence(seq) = &hir.root_content.stmts[0] else {
            panic!("expected Sequence, got {:?}", hir.root_content.stmts[0]);
        };
        assert_eq!(seq.container_id, Some(id(1)));
        assert_eq!(seq.counter_id, None);
        assert_eq!(seq.branches.len(), 2);
        let clones: Vec<&Sequence> = seq
            .branches
            .iter()
            .map(|b| {
                let Stmt::Sequence(inner) = &b.body.stmts[0] else {
                    panic!("expected the clone to lift, got {:?}", b.body.stmts);
                };
                inner
            })
            .collect();
        // Clone 0 IS the original: stamped id, counts on itself.
        assert_eq!(clones[0].container_id, Some(id(2)));
        assert_eq!(clones[0].counter_id, None);
        // Clone 1: a distinct body under a derived id, counting on the original.
        assert_ne!(clones[1].container_id, Some(id(2)));
        assert!(clones[1].container_id.is_some());
        assert_eq!(clones[1].counter_id, Some(id(2)));
        for (clone, prefix) in clones.iter().zip(["a", "b"]) {
            let Stmt::Content(c) = &clone.branches[0].body.stmts[0] else {
                panic!("expected a whole-line rendering");
            };
            assert_eq!(content_text(c), format!("{prefix}c"));
        }
    }

    // ─── #3395: source-order hoist ───────────────────────────────────

    fn call(name: &str) -> Expr {
        Expr::Call(
            Path {
                segments: vec![Name {
                    text: name.to_string(),
                    range: rowan::TextRange::default(),
                }],
                range: rowan::TextRange::default(),
                crosses_module_wall: false,
            },
            Vec::new(),
        )
    }

    fn read(name: &str) -> Expr {
        Expr::Path(Path {
            segments: vec![Name {
                text: name.to_string(),
                range: rowan::TextRange::default(),
            }],
            range: rowan::TextRange::default(),
            crosses_module_wall: false,
        })
    }

    /// The temp a `Stmt::TempDecl` declares, asserting it is synthetic.
    fn synthetic_decl(stmt: &Stmt) -> &TempDecl {
        let Stmt::TempDecl(decl) = stmt else {
            panic!("expected a hoisted TempDecl, got {stmt:?}");
        };
        assert!(decl.synthetic, "hoisted temp must be flagged synthetic");
        assert!(
            super::is_synthetic_temp_name(&decl.name.text),
            "hoisted temp name {:?} must carry the synthetic prefix",
            decl.name.text
        );
        decl
    }

    /// `{bump()}{cond:yes|no}` — the #3395 headline shape. The call is
    /// evaluated into a synthetic temp BEFORE the lifted conditional, and
    /// both branch lines read the temp instead of re-running the call.
    #[test]
    fn prefix_interpolation_is_hoisted_before_the_lifted_conditional() {
        let content = mk_content(vec![
            ContentPart::Interpolation(call("bump")),
            mk_inline_cond(vec![
                (Some(read("cond")), vec![text("yes")]),
                (None, vec![text("no")]),
            ]),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let stmts = &hir.root_content.stmts;
        assert_eq!(
            stmts.len(),
            2,
            "hoisted temp + lifted conditional: {stmts:?}"
        );
        let decl = synthetic_decl(&stmts[0]);
        assert_eq!(decl.value, Some(call("bump")));
        assert!(decl.annotation.is_none());

        let Stmt::Conditional(cond) = &stmts[1] else {
            panic!("expected the lifted Conditional, got {:?}", stmts[1]);
        };
        for branch in &cond.branches {
            let Stmt::Content(c) = &branch.body.stmts[0] else {
                panic!("expected a spliced line, got {:?}", branch.body.stmts);
            };
            assert_eq!(
                c.parts[0],
                ContentPart::Interpolation(read(&decl.name.text)),
                "every clone must read the hoisted temp, not re-evaluate the call"
            );
            assert!(
                !c.parts
                    .iter()
                    .any(|p| *p == ContentPart::Interpolation(call("bump"))),
                "the call must evaluate exactly once"
            );
        }
    }

    /// `{n}{f() == 1:yes|no}` — a pure read is hoisted too: the condition's
    /// own side effect must not be visible to the prefix.
    #[test]
    fn prefix_read_is_hoisted_ahead_of_an_effectful_condition() {
        let content = mk_content(vec![
            ContentPart::Interpolation(read("n")),
            mk_inline_cond(vec![(Some(call("f")), vec![text("yes")])]),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let stmts = &hir.root_content.stmts;
        let decl = synthetic_decl(&stmts[0]);
        assert_eq!(decl.value, Some(read("n")));
        assert!(matches!(&stmts[1], Stmt::Conditional(_)));
    }

    /// Two interpolations left of the construct hoist in source order into
    /// distinct temps; text and glue between them are untouched.
    #[test]
    fn prefix_interpolations_hoist_in_source_order_with_distinct_temps() {
        let content = mk_content(vec![
            text("a "),
            ContentPart::Interpolation(call("first")),
            ContentPart::Glue,
            ContentPart::Interpolation(call("second")),
            mk_inline_seq(
                SequenceType::STOPPING,
                vec![vec![text("x")], vec![text("y")]],
            ),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let stmts = &hir.root_content.stmts;
        assert_eq!(stmts.len(), 3, "{stmts:?}");
        let first = synthetic_decl(&stmts[0]);
        let second = synthetic_decl(&stmts[1]);
        assert_eq!(first.value, Some(call("first")));
        assert_eq!(second.value, Some(call("second")));
        assert_ne!(first.name.text, second.name.text);

        let Stmt::Sequence(seq) = &stmts[2] else {
            panic!("expected the lifted Sequence, got {:?}", stmts[2]);
        };
        let Stmt::Content(c) = &seq.branches[0].body.stmts[0] else {
            panic!("expected a spliced line");
        };
        assert_eq!(
            &c.parts[..4],
            &[
                text("a "),
                ContentPart::Interpolation(read(&first.name.text)),
                ContentPart::Glue,
                ContentPart::Interpolation(read(&second.name.text)),
            ]
        );
    }

    /// Two constructs on one line: the outer lift hoists the prefix; the
    /// inner lift (inside each branch) sees the outer temp's read in ITS
    /// prefix and must not hoist it again — it hoists only the genuinely
    /// new interpolation between the two constructs.
    #[test]
    fn a_synthetic_read_is_not_rehoisted_at_the_next_lift_level() {
        let content = mk_content(vec![
            ContentPart::Interpolation(call("a")),
            mk_inline_cond(vec![
                (Some(read("p")), vec![text("P")]),
                (None, vec![text("Q")]),
            ]),
            ContentPart::Interpolation(call("b")),
            mk_inline_cond(vec![
                (Some(read("q")), vec![text("R")]),
                (None, vec![text("S")]),
            ]),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let stmts = &hir.root_content.stmts;
        assert_eq!(stmts.len(), 2, "{stmts:?}");
        let outer = synthetic_decl(&stmts[0]);
        let Stmt::Conditional(cond) = &stmts[1] else {
            panic!("expected the outer Conditional");
        };
        for branch in &cond.branches {
            // Inside each branch: exactly ONE new temp (for `b`), then the
            // inner conditional whose lines read both temps.
            let inner_stmts = &branch.body.stmts;
            assert_eq!(inner_stmts.len(), 2, "{inner_stmts:?}");
            let inner = synthetic_decl(&inner_stmts[0]);
            assert_eq!(inner.value, Some(call("b")));
            assert_ne!(inner.name.text, outer.name.text);
            let Stmt::Conditional(inner_cond) = &inner_stmts[1] else {
                panic!("expected the inner Conditional");
            };
            for ib in &inner_cond.branches {
                let Stmt::Content(c) = &ib.body.stmts[0] else {
                    panic!("expected a spliced line");
                };
                let reads: Vec<&ContentPart> = c
                    .parts
                    .iter()
                    .filter(|p| matches!(p, ContentPart::Interpolation(_)))
                    .collect();
                assert_eq!(
                    reads,
                    vec![
                        &ContentPart::Interpolation(read(&outer.name.text)),
                        &ContentPart::Interpolation(read(&inner.name.text)),
                    ],
                    "reads must be the two temps, in order, with no re-hoist copy"
                );
            }
        }
    }

    /// An interpolation nested in a span left of the construct hoists too —
    /// the span keeps its shape, its child now reads the temp.
    #[test]
    fn span_nested_prefix_interpolation_is_hoisted() {
        let span = ContentPart::Span(SpanPart {
            ptr: dummy_ptr(),
            name: "b".to_string(),
            attrs: Vec::new(),
            children: vec![ContentPart::Interpolation(call("f"))],
        });
        let content = mk_content(vec![
            span,
            mk_inline_cond(vec![
                (Some(read("c")), vec![text("x")]),
                (None, vec![text("y")]),
            ]),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let stmts = &hir.root_content.stmts;
        let decl = synthetic_decl(&stmts[0]);
        let Stmt::Conditional(cond) = &stmts[1] else {
            panic!("expected the lifted Conditional");
        };
        let Stmt::Content(c) = &cond.branches[0].body.stmts[0] else {
            panic!("expected a spliced line");
        };
        let ContentPart::Span(s) = &c.parts[0] else {
            panic!("the span must survive the splice, got {:?}", c.parts[0]);
        };
        assert_eq!(
            s.children,
            vec![ContentPart::Interpolation(read(&decl.name.text))]
        );
    }

    /// No interpolation left of the construct → nothing to hoist; the lift
    /// is byte-identical to before #3395 (interpolations in the SUFFIX are
    /// the next lift level's prefix, or stay inline when nothing follows).
    #[test]
    fn suffix_only_interpolations_are_not_hoisted() {
        let content = mk_content(vec![
            text("a "),
            mk_inline_cond(vec![
                (Some(read("c")), vec![text("x")]),
                (None, vec![text("y")]),
            ]),
            ContentPart::Interpolation(call("after")),
        ]);
        let mut hir = mk_hir(vec![Stmt::Content(content), Stmt::EndOfLine]);
        normalize_file(&mut hir);

        let stmts = &hir.root_content.stmts;
        assert_eq!(stmts.len(), 1, "no temp expected: {stmts:?}");
        let Stmt::Conditional(cond) = &stmts[0] else {
            panic!("expected the lifted Conditional");
        };
        let Stmt::Content(c) = &cond.branches[0].body.stmts[0] else {
            panic!("expected a spliced line");
        };
        // `"a "` and `"x"` merged into one text part at the splice seam, so
        // the suffix interpolation is the LAST part, still un-hoisted.
        assert_eq!(
            c.parts.last(),
            Some(&ContentPart::Interpolation(call("after")))
        );
    }
}