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
//! [`project_manifest`]: derive a [`SymbolManifest`] from an already-lowered
//! [`HirFile`] (B0.4, `docs/hir-admission-contract.md` Q3(b),
//! `docs/b0-sequencing.md` §B0.4, issue #1173).
//!
//! Before this pass existed, a frontend built the `HirFile` body and the
//! `SymbolManifest` as two independent, hand-kept-consistent artifacts
//! (D3, `docs/hir-admission-contract.md` §3) — every declared symbol, every
//! local, every unresolved reference had to be pushed to *both* the HIR tree
//! and the manifest, by hand, at the exact point of construction, and
//! nothing ever cross-checked that they agreed. `project_manifest` deletes
//! that obligation: given a well-formed `HirFile`, it derives the *entire*
//! `SymbolManifest` structurally. A frontend that emits correct HIR can no
//! longer emit an inconsistent manifest, because it never emits a manifest
//! at all — the pipeline projects one.
//!
//! # Design notes (judgment calls — see the B0.4 gate report)
//!
//! - **Per-reference scope, without a stored field.** The contract's named
//!   gap (Q3(b): "the gap is per-reference scope context") is closed by
//!   *structural derivation*, not by adding a `scope` field to every `Expr`.
//!   [`Scope`] is `{knot, stitch}` — exactly the two container levels the
//!   admission contract fixes for v1 (Q4(b)) — so a depth-bounded walk that
//!   tracks "which knot/stitch am I structurally inside" while descending
//!   the tree recovers the same scope the original interleaved lowering
//!   computed from `LowerScope::current_knot`/`current_stitch`. This is the
//!   same technique `brink_analyzer::admission`'s `Collector` already uses
//!   for its `prefix` string (proven correct: the B0.3 corpus-wide
//!   admission-clean gate is green against it) — this walker mirrors that
//!   one's traversal shape, extended to build manifest entries instead of
//!   just validating ranges.
//! - **Declaration-metadata fields are additive HIR fields, not
//!   re-derived.** `visibility`/`was`/`doc` (and, for `EXTERNAL`, per-param
//!   names) are computed at lowering time from a declaration's own local
//!   directive/`///`-comment syntax — there is no way to recover *which*
//!   directive attaches to *which* declaration from `HirFile.visibility`/
//!   `was_directives` alone (those are flat, file-level occurrence lists
//!   for the dialect gate, carrying no back-pointer to a declaration). So
//!   B0.4 added `doc`/`visibility`/`was` fields directly to `Knot`, `Stitch`,
//!   `VarDecl`, `ConstDecl`, `ListDecl`, `StructDecl` (visibility only —
//!   `STRUCT` never parses a `#@was`), `ExternalDecl` (plus `params`,
//!   replacing the name-losing `param_count: u8` as the manifest's source).
//! - **Vec order is NOT asserted byte-identical to the legacy manifest for
//!   `unresolved`/`locals`/`labels`.** The legacy interleaved lowering has
//!   at least two accidental orderings baked into its recursion (root
//!   content's refs land *last*, after every knot's; a knot's *stitches*'
//!   refs land before the knot's *own* body's) that are artifacts of
//!   `lower_knot_body`'s call sequencing, not a documented contract, and
//!   nothing downstream keys off manifest vector position (resolution joins
//!   by range/name — see `resolve.rs`'s `lookup_local_in_scope`, which
//!   picks the closest-*preceding* local by `range.start()`, not vector
//!   index). This walker uses natural top-down structural order instead.
//!   The differential burn-in test
//!   (`crates/internal/brink-test-harness/tests/b04_manifest_burn_in.rs`)
//!   compares those three fields order-insensitively (sorted by range) and
//!   every other field (which *does* provably match legacy order — see that
//!   test's module doc) byte-for-byte.

use rowan::TextRange;

use crate::hir::{
    Block, BlockStmt, Choice, ChoiceSet, CondKind, Conditional, Content, ContentPart, DivertPath,
    DivertTarget, ElseBranch, ForStmt, HirFile, IfStmt, Knot, LambdaBody, LambdaExpr, LogicBlock,
    Param, Path, Return, ReturnKind, Sequence, Stmt, StringPart, Tag, WhileStmt,
};
use crate::host_manifest::DocBlock;
use crate::{Expr, ParamInfo, Scope, SymbolKind, VisibilityMark};

use super::{DeclaredSymbol, LocalSymbol, RefKind, SymbolManifest, UnresolvedRef};

/// Derive the [`SymbolManifest`] a well-formed `HirFile` implies.
///
/// See the module doc for the design rationale. This function never emits
/// diagnostics — a `HirFile` handed to it is assumed already lowered
/// (diagnostics are the frontend's problem, not the projection's).
#[must_use]
pub fn project_manifest(hir: &HirFile) -> SymbolManifest {
    let mut p = Projector::default();

    // Root content precedes the first knot — no knot/stitch scope prefix,
    // same carve-out `brink_analyzer::admission`'s walker uses.
    p.walk_block(&hir.root_content, None, None);

    for v in &hir.variables {
        p.declare(
            SymbolKind::Variable,
            v.name.text.clone(),
            v.name.range,
            Vec::new(),
            None,
            v.visibility,
            v.was.clone(),
            v.doc.clone(),
        );
        // Issue #2249: `VAR`'s TM-2 annotation, same as a struct field's
        // (see the `hir.structs` loop below) — no HIR reference registered
        // for it anywhere until now.
        if let Some(ann) = &v.annotation {
            p.walk_type_annotation(ann, None, None);
        }
        p.walk_expr(&v.value, None, None);
    }
    for c in &hir.constants {
        p.declare(
            SymbolKind::Constant,
            c.name.text.clone(),
            c.name.range,
            Vec::new(),
            None,
            c.visibility,
            c.was.clone(),
            c.doc.clone(),
        );
        if let Some(ann) = &c.annotation {
            p.walk_type_annotation(ann, None, None);
        }
        p.walk_expr(&c.value, None, None);
    }
    for l in &hir.lists {
        p.declare(
            SymbolKind::List,
            l.name.text.clone(),
            l.name.range,
            Vec::new(),
            None,
            l.visibility,
            l.was.clone(),
            l.doc.clone(),
        );
        for m in &l.members {
            let qualified = format!("{}.{}", l.name.text, m.name.text);
            p.manifest.list_items.push(DeclaredSymbol {
                name: qualified,
                range: m.name.range,
                params: Vec::new(),
                detail: None,
                visibility: None,
                was: None,
            });
        }
    }
    for s in &hir.structs {
        p.declare(
            SymbolKind::Struct,
            s.name.text.clone(),
            s.name.range,
            Vec::new(),
            None,
            s.visibility,
            None,
            s.doc.clone(),
        );
        // Issue #2249: a field's own TM-2 type annotation is a nominal
        // grammar that has no HIR reference registered elsewhere — unlike
        // a construction literal's shape name (`RefKind::Struct`, issue
        // #2246), `hir::lower::types` takes no `sink`, so nothing upstream
        // of this projection ever saw it as a "reference" at all. Walking
        // it here (rather than leaving it for `brink-ir::lir::lower`'s own
        // `decls::lookup_global`/`ShapeTable::resolve` primitive to
        // re-derive) is exactly what lets that lowering-side duplicate be
        // deleted in favor of consuming `brink-analyzer`'s recorded
        // resolution — see `RefKind::Type`'s own doc.
        for f in &s.fields {
            p.walk_type_annotation(&f.ty, None, None);
        }
    }
    for e in &hir.externals {
        p.declare(
            SymbolKind::External,
            e.name.text.clone(),
            e.name.range,
            e.params.clone(),
            None,
            e.visibility,
            e.was.clone(),
            e.doc.clone(),
        );
    }
    // `hir.includes`: `IncludeSite` carries no manifest entry (F-A — the
    // manifest has no `includes` bucket; the analyzer reads `HirFile`
    // directly for INCLUDE-graph wiring).

    for knot in &hir.knots {
        p.project_knot(knot);
    }

    p.manifest
}

// ─── The projector ──────────────────────────────────────────────────

#[derive(Default)]
struct Projector {
    manifest: SymbolManifest,
}

impl Projector {
    fn scope_of(knot: Option<&str>, stitch: Option<&str>) -> Scope {
        Scope {
            knot: knot.map(str::to_string),
            stitch: stitch.map(str::to_string),
        }
    }

    fn qualify_label(knot: Option<&str>, stitch: Option<&str>, label: &str) -> String {
        match (knot, stitch) {
            (Some(k), Some(s)) => format!("{k}.{s}.{label}"),
            (Some(k), None) => format!("{k}.{label}"),
            _ => label.to_string(),
        }
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "mirrors EffectSink::declare_full's shape"
    )]
    fn declare(
        &mut self,
        kind: SymbolKind,
        name: String,
        range: TextRange,
        params: Vec<ParamInfo>,
        detail: Option<String>,
        visibility: Option<VisibilityMark>,
        was: Option<(String, TextRange)>,
        doc: Option<DocBlock>,
    ) {
        if let Some(doc) = doc {
            self.manifest.docs.insert((kind, name.clone()), doc);
        }
        let sym = DeclaredSymbol {
            name,
            range,
            params,
            detail,
            visibility,
            was,
        };
        match kind {
            SymbolKind::Knot => self.manifest.knots.push(sym),
            SymbolKind::Stitch => self.manifest.stitches.push(sym),
            SymbolKind::Variable => self.manifest.variables.push(sym),
            SymbolKind::Constant => self.manifest.constants.push(sym),
            SymbolKind::List => self.manifest.lists.push(sym),
            SymbolKind::Struct => self.manifest.structs.push(sym),
            SymbolKind::External => self.manifest.externals.push(sym),
            SymbolKind::Label => self.manifest.labels.push(sym),
            SymbolKind::ListItem => self.manifest.list_items.push(sym),
            // Param/Temp are never declared this way (see `push_local`).
            SymbolKind::Param | SymbolKind::Temp => {}
        }
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "mirrors declare's shape (issue #2287: module_qualified is a plain \
                  positional passthrough, not a new structural concern)"
    )]
    fn push_ref(
        &mut self,
        path: String,
        range: TextRange,
        kind: RefKind,
        knot: Option<&str>,
        stitch: Option<&str>,
        arg_count: Option<usize>,
        module_qualified: bool,
    ) {
        // Mirrors `EffectSink::add_unresolved`'s empty-path guard — a
        // malformed parse can yield an empty path/identifier.
        if path.is_empty() {
            return;
        }
        self.manifest.unresolved.push(UnresolvedRef {
            path,
            range,
            kind,
            scope: Self::scope_of(knot, stitch),
            arg_count,
            module_qualified,
        });
    }

    /// [`Self::push_ref`] for an ordinary (never module-qualified) `Path`
    /// reference — every ref kind except a divert target, which is the only
    /// one that can carry `::` (see [`divert_path_text`]). Shrinks
    /// `walk_expr`'s repeated 7-argument calls back to one line each.
    fn push_path_ref(
        &mut self,
        path: &Path,
        kind: RefKind,
        knot: Option<&str>,
        stitch: Option<&str>,
        arg_count: Option<usize>,
    ) {
        self.push_ref(
            path_text(path),
            path.range,
            kind,
            knot,
            stitch,
            arg_count,
            false,
        );
    }

    #[expect(
        clippy::too_many_arguments,
        reason = "mirrors declare's shape (issue #530: annotation is a plain \
                  positional passthrough, not a new structural concern)"
    )]
    fn push_local(
        &mut self,
        name: String,
        range: TextRange,
        kind: SymbolKind,
        knot: Option<&str>,
        stitch: Option<&str>,
        param_detail: Option<ParamInfo>,
        annotation: Option<crate::TypeExpr>,
    ) {
        self.manifest.locals.push(LocalSymbol {
            name,
            range,
            scope: Self::scope_of(knot, stitch),
            kind,
            param_detail,
            annotation,
        });
    }

    /// Register a TM-2 [`crate::TypeExpr`] annotation's bare nominal leaf
    /// name as an unresolved [`RefKind::Type`] reference (issue #2249): a
    /// struct field's declared type, or a `VAR`/`CONST`/`temp` annotation.
    ///
    /// Only the `Named` leaf is registered. `Generic`/`Fn` annotations
    /// (`List<L>`, `fn(T…): R`) never name a struct at their own top level
    /// — their *head* (`List`, `fn`) is a fixed grammar keyword, never a
    /// declared symbol — so there is nothing to resolve there; this
    /// mirrors the two lowering sites this reference kind replaces
    /// (`lir::lower::structs::record_global_annotation`,
    /// `lir::lower::context::record_temp_annotation`), which likewise only
    /// ever matched a bare `TypeExpr::Named`, never descended into a
    /// generic's args. A future generic-element struct reference (e.g.
    /// `Array<Cue>`) is out of this issue's scope.
    fn walk_type_annotation(
        &mut self,
        ty: &crate::TypeExpr,
        knot: Option<&str>,
        stitch: Option<&str>,
    ) {
        if let crate::TypeExpr::Named { name, range } = ty {
            self.push_ref(
                name.clone(),
                *range,
                RefKind::Type,
                knot,
                stitch,
                None,
                false,
            );
        }
    }

    fn push_label(&mut self, name: String, range: TextRange) {
        self.manifest.labels.push(DeclaredSymbol {
            name,
            range,
            params: Vec::new(),
            detail: None,
            visibility: None,
            was: None,
        });
    }

    // ─── Containers ─────────────────────────────────────────────────

    fn project_knot(&mut self, knot: &Knot) {
        let bucket = knot.symbol_kind();
        let detail = if knot.is_function {
            Some("function".to_owned())
        } else {
            None
        };
        self.declare(
            bucket,
            knot.name.text.clone(),
            knot.name.range,
            param_infos(&knot.params),
            detail,
            knot.visibility,
            knot.was.clone(),
            knot.doc.clone(),
        );

        // A container's own params are scoped under its own name as
        // `current_knot` — true for a real knot *and* for a promoted
        // top-level stitch (`lower_top_level_stitch` sets
        // `scope.current_knot = Some(name_text)` before registering its
        // params as locals, exactly like `lower_knot`).
        for param in &knot.params {
            self.push_local(
                param.name.text.clone(),
                param.name.range,
                SymbolKind::Param,
                Some(knot.name.text.as_str()),
                None,
                Some(param_info(param)),
                param.annotation.clone(),
            );
            // Issue #2272: a param's own TM-2 annotation is a nominal
            // grammar reference in exactly the same sense as a `VAR`/
            // `CONST`/struct-field annotation (issue #2249's own
            // `walk_type_annotation` sites, above) — `push_local` above
            // only records the annotation as `LocalSymbol.annotation` (a
            // side-table field consumed by `signature()`'s firewall), it
            // never registers an HIR reference for it, so a struct used
            // only as a parameter type read as unreferenced by the symbol
            // index (goto-def/rename/find-references all missed it).
            if let Some(ann) = &param.annotation {
                self.walk_type_annotation(ann, Some(&knot.name.text), None);
            }
        }
        // Issue #2272: the knot/function-header return-type annotation
        // (`Knot::return_type`, TM-2 `): type ===`) — same gap as the param
        // loop just above, but for the one TM-2 annotation site
        // `project_manifest` never walked at all until now (unlike a
        // param's, which was at least stored, just not referenced).
        if let Some(rt) = &knot.return_type {
            self.walk_type_annotation(rt, Some(&knot.name.text), None);
        }

        self.walk_block(&knot.body, Some(&knot.name.text), None);

        for st in &knot.stitches {
            let qualified = format!("{}.{}", knot.name.text, st.name.text);
            self.declare(
                SymbolKind::Stitch,
                qualified,
                st.name.range,
                param_infos(&st.params),
                None,
                st.visibility,
                st.was.clone(),
                st.doc.clone(),
            );
            for param in &st.params {
                self.push_local(
                    param.name.text.clone(),
                    param.name.range,
                    SymbolKind::Param,
                    Some(knot.name.text.as_str()),
                    Some(st.name.text.as_str()),
                    Some(param_info(param)),
                    param.annotation.clone(),
                );
                // Issue #2272: same param-annotation registration as a
                // knot-level param above, scoped under this stitch.
                if let Some(ann) = &param.annotation {
                    self.walk_type_annotation(ann, Some(&knot.name.text), Some(&st.name.text));
                }
            }
            // Issue #2272: a stitch's own return-type annotation — same
            // gap as the knot's above.
            if let Some(rt) = &st.return_type {
                self.walk_type_annotation(rt, Some(&knot.name.text), Some(&st.name.text));
            }
            self.walk_block(&st.body, Some(&knot.name.text), Some(&st.name.text));
        }
    }

    // ─── Blocks / statements (mirrors `brink_analyzer::admission`'s
    // `Collector` traversal shape) ────────────────────────────────────

    fn walk_block(&mut self, block: &Block, knot: Option<&str>, stitch: Option<&str>) {
        if let Some(name) = &block.label {
            let qualified = Self::qualify_label(knot, stitch, &name.text);
            self.push_label(qualified, name.range);
        }
        for stmt in &block.stmts {
            self.walk_stmt(stmt, knot, stitch);
        }
    }

    fn walk_stmt(&mut self, stmt: &Stmt, knot: Option<&str>, stitch: Option<&str>) {
        match stmt {
            Stmt::Content(c) => self.walk_content(c, knot, stitch),
            Stmt::Divert(d) => self.walk_divert_target(&d.target, knot, stitch),
            Stmt::TunnelCall(t) => {
                for target in &t.targets {
                    self.walk_divert_target(target, knot, stitch);
                }
            }
            Stmt::ThreadStart(t) => self.walk_divert_target(&t.target, knot, stitch),
            Stmt::TempDecl(t) => {
                if let Some(e) = &t.value {
                    self.walk_expr(e, knot, stitch);
                }
                // Issue #2249: a `~ temp name: type` annotation, same TM-2
                // treatment as a struct field's or a `VAR`/`CONST`'s.
                if let Some(ann) = &t.annotation {
                    self.walk_type_annotation(ann, knot, stitch);
                }
                self.push_local(
                    t.name.text.clone(),
                    t.name.range,
                    SymbolKind::Temp,
                    knot,
                    stitch,
                    None,
                    t.annotation.clone(),
                );
            }
            Stmt::Assignment(a) => {
                self.walk_expr(&a.target, knot, stitch);
                self.walk_expr(&a.value, knot, stitch);
            }
            Stmt::Return(r) => self.walk_return(r, knot, stitch),
            Stmt::ChoiceSet(cs) => self.walk_choice_set(cs, knot, stitch),
            Stmt::LabeledBlock(b) => self.walk_block(b, knot, stitch),
            Stmt::Conditional(c) => self.walk_conditional(c, knot, stitch),
            Stmt::Sequence(s) => self.walk_sequence(s, knot, stitch),
            Stmt::ExprStmt(e) | Stmt::AttachElement(e) => self.walk_expr(e, knot, stitch),
            Stmt::EndOfLine | Stmt::EndElementRun => {}
            Stmt::LogicBlock(lb) => self.walk_logic_block(lb, knot, stitch),
            Stmt::Await(a) => {
                if let Some(e) = &a.condition {
                    self.walk_expr(e, knot, stitch);
                }
            }
        }
    }

    /// Shared by `Stmt::Return`/`BlockStmt::Return` (issue #2173 review
    /// finding on #2156): a tunnel redirect (`->-> target(args)`) stores its
    /// call args in `onwards_args`, not on the `DivertTarget` expression
    /// itself, so the generic `Expr::DivertTarget` arm in `walk_expr` (which
    /// always pushes `arg_count: None`) would silently lose them. When
    /// `r.value` is a bare `Expr::DivertTarget` under `ReturnKind::
    /// TunnelRedirect`, push the ref directly with
    /// `Some(r.onwards_args.len())` so `check_divert_arity` can check it;
    /// any other return-value shape (including a plain `-> target` stored
    /// value under `ReturnKind::Explicit`, which is never a redirect and
    /// never has onwards args) falls through to the ordinary `walk_expr`
    /// path with `arg_count: None`, unchanged.
    fn walk_return(&mut self, r: &Return, knot: Option<&str>, stitch: Option<&str>) {
        match (&r.value, r.kind) {
            (Some(Expr::DivertTarget(p)), ReturnKind::TunnelRedirect) => {
                let (path, module_qualified) = divert_path_text(p);
                self.push_ref(
                    path,
                    p.range,
                    RefKind::Divert,
                    knot,
                    stitch,
                    Some(r.onwards_args.len()),
                    module_qualified,
                );
            }
            (Some(e), _) => self.walk_expr(e, knot, stitch),
            (None, _) => {}
        }
        for e in &r.onwards_args {
            self.walk_expr(e, knot, stitch);
        }
    }

    fn walk_divert_target(
        &mut self,
        target: &DivertTarget,
        knot: Option<&str>,
        stitch: Option<&str>,
    ) {
        if let DivertPath::Path(p) = &target.path {
            // Issue #2156: carry the divert's own call-arg count through so
            // `brink-analyzer::resolve::resolve_divert` can arity-check it
            // (`E176`) exactly like `RefKind::Function` already does for an
            // ordinary call — this used to be hardcoded `None` regardless
            // of `target.args.len()`, which is why the check could never
            // fire for a divert on either dialect (see `E176`'s own doc
            // comment in `hir::diagnostics` for the full history).
            let (path, module_qualified) = divert_path_text(p);
            self.push_ref(
                path,
                p.range,
                RefKind::Divert,
                knot,
                stitch,
                Some(target.args.len()),
                module_qualified,
            );
        }
        for e in &target.args {
            self.walk_expr(e, knot, stitch);
        }
    }

    fn walk_content(&mut self, content: &Content, knot: Option<&str>, stitch: Option<&str>) {
        for part in &content.parts {
            self.walk_content_part(part, knot, stitch);
        }
        for tag in &content.tags {
            self.walk_tag(tag, knot, stitch);
        }
    }

    fn walk_content_part(&mut self, part: &ContentPart, knot: Option<&str>, stitch: Option<&str>) {
        match part {
            ContentPart::Interpolation(e) => self.walk_expr(e, knot, stitch),
            ContentPart::InlineConditional(c) => self.walk_conditional(c, knot, stitch),
            ContentPart::InlineSequence(s) => self.walk_sequence(s, knot, stitch),
            // A span is presentational (§4.3) — its children still carry
            // real references (an interpolation may sit inside `<b>…</b>`),
            // so the symbol index must see into it, same reasoning as
            // `hir::visit::walk_content_part`.
            ContentPart::Span(span) => {
                for child in &span.children {
                    self.walk_content_part(child, knot, stitch);
                }
            }
            ContentPart::Text(_) | ContentPart::Glue | ContentPart::Spring => {}
        }
    }

    /// Tag contents are one of `hir::visit`'s documented walker gaps — tag
    /// interpolations register real refs during lowering, same carve-out
    /// `brink_analyzer::admission` documents.
    fn walk_tag(&mut self, tag: &Tag, knot: Option<&str>, stitch: Option<&str>) {
        for part in &tag.parts {
            self.walk_content_part(part, knot, stitch);
        }
    }

    fn walk_choice_set(&mut self, cs: &ChoiceSet, knot: Option<&str>, stitch: Option<&str>) {
        for choice in &cs.choices {
            self.walk_choice(choice, knot, stitch);
        }
        self.walk_block(&cs.continuation, knot, stitch);
    }

    fn walk_choice(&mut self, choice: &Choice, knot: Option<&str>, stitch: Option<&str>) {
        if let Some(name) = &choice.label {
            let qualified = Self::qualify_label(knot, stitch, &name.text);
            self.push_label(qualified, name.range);
        }
        if let Some(e) = &choice.condition {
            self.walk_expr(e, knot, stitch);
        }
        if let Some(c) = &choice.start_content {
            self.walk_content(c, knot, stitch);
        }
        if let Some(c) = &choice.bracket_content {
            self.walk_content(c, knot, stitch);
        }
        if let Some(c) = &choice.inner_content {
            self.walk_content(c, knot, stitch);
        }
        for tag in &choice.tags {
            self.walk_tag(tag, knot, stitch);
        }
        // Guard-`as` binding (issue #1508) — same treatment as
        // `walk_conditional`'s `branch.binding`/`walk_if_stmt`'s
        // `i.binding`: index it as an ordinary local, scoped to the
        // choice's own body, so a `{n}` read inside resolves instead of
        // raising E025.
        self.push_as_binding(choice.binding.as_ref(), knot, stitch);
        self.walk_block(&choice.body, knot, stitch);
    }

    fn walk_conditional(&mut self, cond: &Conditional, knot: Option<&str>, stitch: Option<&str>) {
        if let CondKind::Switch(e) = &cond.kind {
            self.walk_expr(e, knot, stitch);
        }
        for branch in &cond.branches {
            if let Some(e) = &branch.condition {
                self.walk_expr(e, knot, stitch);
            }
            self.push_as_binding(branch.binding.as_ref(), knot, stitch);
            self.walk_block(&branch.body, knot, stitch);
        }
    }

    /// Index an `as` binding (B1b, issue #1475) as an ordinary local, so
    /// reads of the bound name inside the success arm resolve — and so
    /// hover/go-to-def/rename see it exactly as they see a `for`-loop
    /// variable or a block `let` (`walk_for_stmt`'s precedent).
    fn push_as_binding(
        &mut self,
        binding: Option<&crate::Name>,
        knot: Option<&str>,
        stitch: Option<&str>,
    ) {
        if let Some(name) = binding {
            self.push_local(
                name.text.clone(),
                name.range,
                SymbolKind::Temp,
                knot,
                stitch,
                None,
                None,
            );
        }
    }

    fn walk_sequence(&mut self, seq: &Sequence, knot: Option<&str>, stitch: Option<&str>) {
        for branch in &seq.branches {
            self.walk_block(&branch.body, knot, stitch);
        }
    }

    fn walk_logic_block(&mut self, lb: &LogicBlock, knot: Option<&str>, stitch: Option<&str>) {
        for bs in &lb.stmts {
            self.walk_block_stmt(bs, knot, stitch);
        }
    }

    fn walk_block_stmt(&mut self, bs: &BlockStmt, knot: Option<&str>, stitch: Option<&str>) {
        match bs {
            BlockStmt::TempDecl(t) => {
                if let Some(e) = &t.value {
                    self.walk_expr(e, knot, stitch);
                }
                // Issue #2249: block-scoped `temp`'s TM-2 annotation — same
                // treatment as `Stmt::TempDecl`'s (T1b's block-scoped
                // twin).
                if let Some(ann) = &t.annotation {
                    self.walk_type_annotation(ann, knot, stitch);
                }
                self.push_local(
                    t.name.text.clone(),
                    t.name.range,
                    SymbolKind::Temp,
                    knot,
                    stitch,
                    None,
                    t.annotation.clone(),
                );
            }
            BlockStmt::Assignment(a) => {
                self.walk_expr(&a.target, knot, stitch);
                self.walk_expr(&a.value, knot, stitch);
            }
            BlockStmt::Return(r) => self.walk_return(r, knot, stitch),
            BlockStmt::If(i) => self.walk_if_stmt(i, knot, stitch),
            BlockStmt::While(w) => self.walk_while_stmt(w, knot, stitch),
            BlockStmt::For(f) => self.walk_for_stmt(f, knot, stitch),
            BlockStmt::Break(_) | BlockStmt::Continue(_) => {}
            BlockStmt::ExprStmt(e) => self.walk_expr(e, knot, stitch),
            BlockStmt::Await(a) => {
                if let Some(e) = &a.condition {
                    self.walk_expr(e, knot, stitch);
                }
            }
        }
    }

    fn walk_if_stmt(&mut self, i: &IfStmt, knot: Option<&str>, stitch: Option<&str>) {
        self.walk_expr(&i.condition, knot, stitch);
        self.push_as_binding(i.binding.as_ref(), knot, stitch);
        for s in &i.body {
            self.walk_block_stmt(s, knot, stitch);
        }
        match &i.else_branch {
            Some(ElseBranch::ElseIf(inner)) => self.walk_if_stmt(inner, knot, stitch),
            Some(ElseBranch::Else(stmts)) => {
                for s in stmts {
                    self.walk_block_stmt(s, knot, stitch);
                }
            }
            None => {}
        }
    }

    fn walk_while_stmt(&mut self, w: &WhileStmt, knot: Option<&str>, stitch: Option<&str>) {
        self.walk_expr(&w.condition, knot, stitch);
        self.push_as_binding(w.binding.as_ref(), knot, stitch);
        for s in &w.body {
            self.walk_block_stmt(s, knot, stitch);
        }
    }

    fn walk_for_stmt(&mut self, f: &ForStmt, knot: Option<&str>, stitch: Option<&str>) {
        self.walk_expr(&f.iterable, knot, stitch);
        self.push_local(
            f.var_name.text.clone(),
            f.var_name.range,
            SymbolKind::Temp,
            knot,
            stitch,
            None,
            None,
        );
        // Two-binding map iteration (`for k, v in m`, B2 issue #1461): the
        // second binding is a local too, for hover/goto-def/rename parity
        // with the first.
        if let Some(val_name) = &f.val_name {
            self.push_local(
                val_name.text.clone(),
                val_name.range,
                SymbolKind::Temp,
                knot,
                stitch,
                None,
                None,
            );
        }
        for s in &f.body {
            self.walk_block_stmt(s, knot, stitch);
        }
    }

    // ─── Expressions ────────────────────────────────────────────────

    fn walk_expr(&mut self, expr: &Expr, knot: Option<&str>, stitch: Option<&str>) {
        match expr {
            Expr::Int(_) | Expr::Float(_) | Expr::Bool(_) | Expr::Null => {}
            Expr::String(s) => {
                for part in &s.parts {
                    if let StringPart::Interpolation(e) = part {
                        self.walk_expr(e, knot, stitch);
                    }
                }
            }
            Expr::Path(p) => {
                self.push_path_ref(p, RefKind::Variable, knot, stitch, None);
            }
            Expr::DivertTarget(p) => {
                let (path, module_qualified) = divert_path_text(p);
                self.push_ref(
                    path,
                    p.range,
                    RefKind::Divert,
                    knot,
                    stitch,
                    None,
                    module_qualified,
                );
            }
            Expr::ListLiteral(items) => {
                for p in items {
                    self.push_path_ref(p, RefKind::List, knot, stitch, None);
                }
            }
            Expr::Prefix(_, inner) | Expr::Postfix(inner, _) => {
                self.walk_expr(inner, knot, stitch);
            }
            Expr::Infix(ie) => {
                self.walk_expr(&ie.lhs, knot, stitch);
                self.walk_expr(&ie.rhs, knot, stitch);
            }
            Expr::Call(path, args) => {
                // `path.range` here — the callee `Path`'s own *whole* span —
                // is the origin of the call-path `ResolvedRef::range`
                // contract four downstream consumers key lookups on
                // unchanged; see that field's doc (issue #1561). Never
                // narrow this to a sub-segment.
                self.push_path_ref(path, RefKind::Function, knot, stitch, Some(args.len()));
                for a in args {
                    self.walk_expr(a, knot, stitch);
                }
            }
            Expr::ArrayLiteral(a) => {
                for e in &a.elements {
                    self.walk_expr(e, knot, stitch);
                }
            }
            Expr::MapLiteral(m) => {
                for (k, v) in &m.entries {
                    self.walk_expr(k, knot, stitch);
                    self.walk_expr(v, knot, stitch);
                }
            }
            Expr::Index(idx) => {
                self.walk_expr(&idx.base, knot, stitch);
                self.walk_expr(&idx.index, knot, stitch);
            }
            Expr::Range(r) => {
                self.walk_expr(&r.start, knot, stitch);
                self.walk_expr(&r.end, knot, stitch);
            }
            Expr::StructLiteral(sl) => {
                self.push_ref(
                    sl.shape.text.clone(),
                    sl.shape.range,
                    RefKind::Struct,
                    knot,
                    stitch,
                    None,
                    false,
                );
                for (_, v) in &sl.fields {
                    self.walk_expr(v, knot, stitch);
                }
            }
            Expr::FieldAccess(fa) => self.walk_expr(&fa.base, knot, stitch),
            Expr::FnLiteral(fl) => {
                // `arg_count` stays `None` here (never `Some(fl.args.len())`)
                // — `#fn` binds a *prefix* of the param row, unlike a direct
                // call, so full-arity checking doesn't apply (see
                // `hir::lower::expr::sigils`'s `FnLiteral` lowering doc).
                self.push_path_ref(&fl.target, RefKind::Function, knot, stitch, None);
                for a in &fl.args {
                    self.walk_expr(a, knot, stitch);
                }
            }
            Expr::RefArg(ra) => self.walk_expr(&ra.operand, knot, stitch),
            // A lambda (issue #1685) introduces locals — its params — and
            // then a body that reads them. The params are recorded with the
            // same `SymbolKind::Temp` a `for` binding and a `let` get: they
            // are bindings a construct introduces inside a body, not
            // declaration-header params, and recording them is what lets a
            // reference to `g` inside `|g| g.awake` resolve at all (as well
            // as giving hover/goto-def/rename the same handle they have on
            // every other local).
            Expr::Lambda(l) => self.walk_lambda(l, knot, stitch),
            // Block capture (issue #1839): the captured run is real body
            // content — a reference/call inside it needs the identical
            // symbol-table entries (hover/goto-def/rename) it would get at
            // its original top-level position, so it walks through
            // `walk_stmt` exactly as it did before capture.
            Expr::Fragment(stmts) => {
                for s in stmts {
                    self.walk_stmt(s, knot, stitch);
                }
            }
        }
    }

    /// A lambda (issue #1685) introduces locals — its params — and then a
    /// body that reads them. The params are recorded with the same
    /// `SymbolKind::Temp` a `for` binding and a `let` get: they are
    /// bindings a construct introduces inside a body, not
    /// declaration-header params, and recording them is what lets a
    /// reference to `g` inside `|g| g.awake` resolve at all (as well as
    /// giving hover/goto-def/rename the same handle they have on every
    /// other local).
    fn walk_lambda(&mut self, l: &LambdaExpr, knot: Option<&str>, stitch: Option<&str>) {
        for p in &l.params {
            self.push_local(
                p.name.text.clone(),
                p.name.range,
                SymbolKind::Temp,
                knot,
                stitch,
                None,
                None,
            );
            // Issue #2272: a lambda param's own TM-2 annotation, same
            // registration gap as a knot/stitch param's (`project_knot`,
            // above) — a struct used only as a lambda param's type read as
            // unreferenced. `push_local` above deliberately still passes
            // `None` for the annotation slot itself (lambda params are
            // recorded as ordinary `SymbolKind::Temp` locals, which have no
            // `signature()`-firewall consumer of their own the way a
            // knot/stitch param's `LocalSymbol.annotation` does) — this
            // walk is only the reference registration, independent of that.
            if let Some(ann) = &p.annotation {
                self.walk_type_annotation(ann, knot, stitch);
            }
        }
        // Issue #2272: the lambda's own `: type` return annotation
        // (`LambdaExpr::return_type`) — same gap as its params just above.
        if let Some(rt) = &l.return_type {
            self.walk_type_annotation(rt, knot, stitch);
        }
        match &l.body {
            LambdaBody::Expr(e) => self.walk_expr(e, knot, stitch),
            LambdaBody::Block { stmts, tail } => {
                for s in stmts {
                    self.walk_block_stmt(s, knot, stitch);
                }
                if let Some(t) = tail {
                    self.walk_expr(t, knot, stitch);
                }
            }
        }
    }
}

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

fn param_info(p: &Param) -> ParamInfo {
    ParamInfo {
        name: p.name.text.clone(),
        is_ref: p.is_ref,
        is_divert: p.is_divert,
    }
}

fn param_infos(params: &[Param]) -> Vec<ParamInfo> {
    params.iter().map(param_info).collect()
}

/// Dot-joined path text (`crate::hir::lower::helpers::path_full_name`'s
/// twin — duplicated rather than reached-into, since that helper is
/// `pub(crate)` to `hir::lower` and this module has no other reason to
/// depend on the lowering module tree).
fn path_text(path: &Path) -> String {
    path.segments
        .iter()
        .map(|s| s.text.as_str())
        .collect::<Vec<_>>()
        .join(".")
}

/// The divert-target twin of [`path_text`] (issue #2287): a divert path
/// that crossed a module wall (`-> barter::haggle`, `Path::
/// crosses_module_wall`) is joined with `::` instead of `.`, so the
/// qualifier prefix and the bare target name split back apart cleanly in
/// `brink_analyzer::resolve::lookup_qualified_divert` — joining it with `.`
/// like every other path would make it indistinguishable from ink's own
/// dotted `knot.stitch` addressing, which is exactly the defect issue #2287
/// reported (`unresolved divert target: barter.haggle`, note the dot).
/// Returns the joined text and whether the wall was crossed, both destined
/// for `UnresolvedRef::path`/`UnresolvedRef::module_qualified`.
fn divert_path_text(path: &Path) -> (String, bool) {
    if path.crosses_module_wall {
        let text = path
            .segments
            .iter()
            .map(|s| s.text.as_str())
            .collect::<Vec<_>>()
            .join("::");
        (text, true)
    } else {
        (path_text(path), false)
    }
}

// ─── Tests ──────────────────────────────────────────────────────────
//
// These are the projection's *own* unit tests — the ones B0.3's admission
// check #1 (manifest⇄HIR agreement) retires into, per
// `docs/b0-sequencing.md` §B0.4: "you cannot disagree with yourself once
// the manifest IS a projection of HIR". Direct, fixture-driven assertions
// on `project_manifest`'s output for the shapes that matter — declared
// symbols with every metadata channel (doc/visibility/was/params), locals
// with their scope, every `RefKind`, and label qualification. The
// differential burn-in test
// (`crates/internal/brink-test-harness/tests/b04_manifest_burn_in.rs`) is
// the corpus-wide proof this matches production; these are the readable,
// single-purpose regression tests for each shape.

#[cfg(test)]
#[expect(
    clippy::panic,
    reason = "test-only unwrap_or_else(|| panic!(...)) assertion helpers"
)]
mod tests {
    use brink_syntax::parse;

    use super::*;
    use crate::FileId;

    fn lower(source: &str) -> HirFile {
        let parsed = parse(source);
        let tree = parsed.tree();
        let (hir, _legacy_manifest, diags) = crate::hir::lower(FileId(0), &tree);
        assert!(diags.is_empty(), "unexpected diagnostics: {diags:?}");
        hir
    }

    #[test]
    fn docs_project_for_every_declaration_kind() {
        let hir = lower(
            "\
/// An external.
EXTERNAL ping(x)
/// A variable.
VAR health = 100
/// A constant.
CONST SPEED = 0.5
/// A list.
LIST mood = happy, sad
/// A knot.
== hub ==
intro
/// A nested stitch.
= market
stalls
/// A function knot.
== function damage(weapon) ==
~ return 1
",
        );
        let manifest = project_manifest(&hir);

        let doc_text = |kind: SymbolKind, name: &str| {
            manifest
                .docs
                .get(&(kind, name.to_string()))
                .unwrap_or_else(|| panic!("doc for {kind:?} {name}"))
                .doc
                .clone()
        };
        assert_eq!(
            doc_text(SymbolKind::External, "ping").as_deref(),
            Some("An external.")
        );
        assert_eq!(
            doc_text(SymbolKind::Variable, "health").as_deref(),
            Some("A variable.")
        );
        assert_eq!(
            doc_text(SymbolKind::Constant, "SPEED").as_deref(),
            Some("A constant.")
        );
        assert_eq!(
            doc_text(SymbolKind::List, "mood").as_deref(),
            Some("A list.")
        );
        assert_eq!(
            doc_text(SymbolKind::Knot, "hub").as_deref(),
            Some("A knot.")
        );
        assert_eq!(
            doc_text(SymbolKind::Stitch, "hub.market").as_deref(),
            Some("A nested stitch."),
            "nested stitch docs are keyed by qualified name"
        );
        assert_eq!(
            doc_text(SymbolKind::Knot, "damage").as_deref(),
            Some("A function knot.")
        );
    }

    #[test]
    fn visibility_and_was_project_onto_declared_symbols() {
        let hir = lower(
            "\
== hub ==
#@was(old_hub)
#@private
Hello
-> END

#@was(old_health)
VAR health = 100
",
        );
        let manifest = project_manifest(&hir);

        assert_eq!(
            manifest.variables[0].was.as_ref().map(|(n, _)| n.as_str()),
            Some("old_health")
        );
        assert_eq!(manifest.knots[0].visibility, Some(VisibilityMark::Private));
        assert_eq!(
            manifest.knots[0].was.as_ref().map(|(n, _)| n.as_str()),
            Some("old_hub")
        );
    }

    #[test]
    fn external_params_keep_their_names_not_just_a_count() {
        let hir = lower("EXTERNAL greet(name, times)\n");
        let manifest = project_manifest(&hir);

        let ext = &manifest.externals[0];
        assert_eq!(
            ext.params
                .iter()
                .map(|p| p.name.as_str())
                .collect::<Vec<_>>(),
            vec!["name", "times"]
        );
    }

    #[test]
    fn list_items_project_with_qualified_names() {
        let hir = lower("LIST mood = happy, (sad), angry\n");
        let manifest = project_manifest(&hir);

        let names: Vec<_> = manifest
            .list_items
            .iter()
            .map(|s| s.name.as_str())
            .collect();
        assert_eq!(names, vec!["mood.happy", "mood.sad", "mood.angry"]);
    }

    #[test]
    fn promoted_top_level_stitch_declares_bare_stitch_not_knot() {
        let hir = lower("= market\nstalls\n-> END\n");
        let manifest = project_manifest(&hir);

        assert!(manifest.knots.is_empty(), "no real knot in this file");
        assert_eq!(manifest.stitches.len(), 1);
        assert_eq!(manifest.stitches[0].name, "market");
    }

    #[test]
    fn params_project_as_locals_scoped_to_their_container() {
        let hir = lower(
            "\
== hub(gold) ==
= market(item)
buy {item} for {gold}
-> END
",
        );
        let manifest = project_manifest(&hir);

        let hub_gold = manifest
            .locals
            .iter()
            .find(|l| l.name == "gold")
            .expect("knot param `gold` is a local");
        assert_eq!(hub_gold.kind, SymbolKind::Param);
        assert_eq!(hub_gold.scope.knot.as_deref(), Some("hub"));
        assert_eq!(hub_gold.scope.stitch, None);

        let market_item = manifest
            .locals
            .iter()
            .find(|l| l.name == "item")
            .expect("stitch param `item` is a local");
        assert_eq!(market_item.scope.knot.as_deref(), Some("hub"));
        assert_eq!(market_item.scope.stitch.as_deref(), Some("market"));
    }

    #[test]
    fn temp_decl_and_for_loop_binding_project_as_temp_locals() {
        let hir = lower(
            "\
== hub ==
~ temp x = 1
~ { for y in #[1, 2, 3] { } }
-> END
",
        );
        let manifest = project_manifest(&hir);

        let temp_names: Vec<_> = manifest
            .locals
            .iter()
            .filter(|l| l.kind == SymbolKind::Temp)
            .map(|l| l.name.as_str())
            .collect();
        assert!(temp_names.contains(&"x"), "{temp_names:?}");
        assert!(temp_names.contains(&"y"), "{temp_names:?}");
    }

    #[test]
    fn every_ref_kind_projects_with_the_right_scope_and_arg_count() {
        let hir = lower(
            "\
VAR g = 0
LIST L = a, b
STRUCT Point = #{ x: int }
EXTERNAL beep(n)

== hub ==
{g}
~ beep(1, 2)
~ temp chosen = (a, b)
~ temp p = Point#{ x: 1 }
-> away

=== away ===
-> END
",
        );
        let manifest = project_manifest(&hir);

        let find = |kind: RefKind, path: &str| {
            manifest
                .unresolved
                .iter()
                .find(|r| r.kind == kind && r.path == path)
                .unwrap_or_else(|| {
                    panic!(
                        "expected a {kind:?} ref to `{path}`: {:?}",
                        manifest.unresolved
                    )
                })
        };

        let variable = find(RefKind::Variable, "g");
        assert_eq!(variable.scope.knot.as_deref(), Some("hub"));
        assert_eq!(variable.arg_count, None);

        let func = find(RefKind::Function, "beep");
        assert_eq!(func.arg_count, Some(2));

        let list = find(RefKind::List, "a");
        assert_eq!(list.arg_count, None);

        let strukt = find(RefKind::Struct, "Point");
        assert_eq!(strukt.arg_count, None);

        // Issue #2156: a bare `-> away` (no call-args syntax) now records
        // `Some(0)`, not `None` — `arg_count` is always `Some(target.args.len())`
        // for a divert ref (0 for a bare divert), so `resolve_divert`'s arity
        // check (`E176`) can run uniformly rather than being permanently
        // gated off by a hardcoded `None`.
        let divert = find(RefKind::Divert, "away");
        assert_eq!(divert.arg_count, Some(0));
    }

    #[test]
    fn choice_and_gather_labels_project_with_qualified_names() {
        let hir = lower(
            "\
== hub ==
* (opener) [Go] Onward.
- (settle) Settled.
-> END
",
        );
        let manifest = project_manifest(&hir);

        let names: Vec<_> = manifest.labels.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"hub.opener"), "{names:?}");
        assert!(names.contains(&"hub.settle"), "{names:?}");
    }
}