brink-analyzer 0.0.17

Cross-file semantic analysis 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
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
//! TM-4b struct construction-literal semantic checks (docs/typed-mode-spec.md
//! §6).
//!
//! Strict-mode-only (`types = strict`): "missing/extra fields at
//! construction: compile error (strict) / construction fault (gradual)" —
//! under `types = gradual` a project never runs [`check`] at all (mirrors
//! `strict::check`'s own gating), deferring entirely to the runtime fault
//! PR #664 already built (`RecordGetDyn`'s missing-field fault). Wired into
//! `strict::check` alongside E065/E066/E067, behind the same
//! `TypePolicy::Strict` + `dialect = brink` guard `strict::config_error`
//! already enforces.
//!
//! Three checks, each naming the offending field, all strict-only per the
//! spec's own wording ("missing/extra fields at construction: compile error
//! (strict) / construction fault (gradual)"):
//! - **Missing** (`E069`): a declared field with no initializer in the
//!   literal.
//! - **Extra** (`E070`): an initializer for a field the shape doesn't
//!   declare.
//! - **Mistyped** (`E071`): an initializer whose *statically
//!   classifiable* type disagrees with the field's declared type.
//!   Literal-shaped initializers (int/float/bool/string/array/map/nested
//!   struct literals) classify from their own shape alone. A variable-,
//!   call-, or index-valued initializer (issue #670) instead consults the
//!   inference substrate already threaded into `strict::check`: a `Path`
//!   resolving to a param/temp reads its finalized type from that def's own
//!   `BodyTypes::locals`; a `Path` resolving to a global `VAR`/`CONST` reads
//!   its declaration-derived type (`infer::collect_globals`, the same
//!   source `infer::body` itself reads through the firewall); a call reads
//!   the resolved callee's `InferredSig::return_ty`; an index expression
//!   recurses into its base's classified type and takes the
//!   array-element/map-value type. Whenever that resolution lands on
//!   `Unknown` or `Conflicted` (unresolved, unannotated, or genuinely
//!   contradictory), the field stays silently unchecked — same "Unknown
//!   never disagrees" spirit as `annotations::mismatches`.
//!
//! An unresolved shape name (`E068`, already reported by
//! `resolve::resolve_struct_ref`) is not re-reported here — a construction
//! against a shape that doesn't exist has no declared fields to check
//! against.
//!
//! [`check_duplicates`] (`E084`, issue #675) is a fourth, *policy-
//! independent* check: a construction literal supplying the same field
//! name more than once is flagged under both `types = gradual` and
//! `types = strict` — it doesn't need the shape to resolve, so it's wired
//! into `per_file_diagnostics` unconditionally within a file (no
//! `TypePolicy` gate) rather than behind `strict::config_error` the way
//! [`check`] is. Its `dialect`/`is_native` gating is wider than `check`'s
//! own brink-only block, though: B5 (issue #1464, #1103 cascade ruling
//! (A)) made `TypeName { … }` construction reach `StructLiteral` from the
//! native surface (`Point { x: 1 }`) as well as the brink dialect's own
//! `#{…}` spelling, so the caller runs this under `dialect = Brink ||
//! is_native` — same reasoning `map_keys::check_duplicate_keys`'s own doc
//! gives for `E138`.

use std::collections::{BTreeMap, BTreeSet};

use brink_format::DefinitionId;
use brink_ir::hir::visit::{self, HirVisitor};
use brink_ir::{
    AssignOp, BlockStmt, Diagnostic, DiagnosticCode, Expr, FileId, HirFile, Knot, ResolutionMap,
    Stitch, StructLiteral, SymbolIndex, SymbolKind,
};
use rowan::TextRange;

use crate::annotations;
use crate::infer::{
    FieldAssignMismatch, InferenceResult, InferredSig, Ty, is_string_numeric_concat,
};
use crate::resolve::ImportScope;

/// One declared struct shape: fields in declaration order, name -> declared
/// type (`Ty::Unknown` if the field's own annotation doesn't resolve —
/// e.g. an unrecognized type name, already flagged elsewhere by
/// `annotations::check`'s `E061`).
///
/// Originally `pub(crate)` (issue #831) so `ref_projection`'s strict-mode
/// path-segment check could reuse this exact shape table for `ref
/// lvalue-path` field segments — "reuse existing machinery"
/// (docs/t1e-spec.md §6) rather than building a second one. Promoted to a
/// crate-public API (issue #858) so out-of-crate tooling (e.g. `brink-ide`
/// struct-field ref-path completion, T1e-3's deferred "path continuations
/// after a `.`/`[`" item) can query declared shapes without duplicating this
/// table.
pub struct ShapeInfo {
    fields: Vec<(String, Ty)>,
}

impl ShapeInfo {
    /// The declared type of `name`, or `None` if the shape has no such
    /// field.
    #[must_use]
    pub fn field_ty(&self, name: &str) -> Option<&Ty> {
        self.fields.iter().find(|(n, _)| n == name).map(|(_, t)| t)
    }

    /// Whether the shape declares a field named `name`.
    #[must_use]
    pub fn has_field(&self, name: &str) -> bool {
        self.fields.iter().any(|(n, _)| n == name)
    }
}

/// Every declared `STRUCT` shape in the project — a referrer-scoped lookup
/// table (issue #2241).
///
/// A bare struct name is **not** a unique key: the stdlib mount (#2080) lets
/// a project's own `struct Cue { … }` coexist with a same-named
/// `struct Cue { … }` a mounted std preset declares (M-2d module
/// coexistence, `manifest::is_cross_declared_module_collision`) — both are
/// genuinely distinct `Struct` symbols with distinct `DefinitionId`s, the
/// same shape `brink_ir::lir::lower::structs::ShapeTable` already handles one
/// layer down (issue #2238). This table used to be a flat
/// `BTreeMap<String, ShapeInfo>` populated by plain last-`insert`-wins —
/// whichever file's declaration was iterated last silently overwrote every
/// earlier same-named one, with no per-caller scope to break the tie.
/// [`ShapeTable::resolve`] is the fix: every caller with an [`ImportScope`]
/// in hand resolves the *right* candidate through the same
/// `Candidacy`-based module scoping [`crate::resolve::lookup_by_name`]
/// already applies to every other symbol kind — instead of a global winner
/// or a second, diverging std-exclusion policy (2026-08-04 peer-root
/// ruling, `docs/decision-log.md`). [`ShapeTable::get_by_def`] is for
/// callers that already hold an exact `DefinitionId` (e.g. a construction
/// literal's shape name, resolved with full module-scope `Candidacy` by
/// `resolve::resolve_struct_ref` and recorded in the project's
/// `ResolutionMap` — see [`check`]).
///
/// Public (issue #858) so tooling outside `brink-analyzer` can resolve a
/// `STRUCT`'s declared fields — e.g. offering field-name completions after
/// `npc.` in a `ref lvalue-path` — without re-deriving the shape table this
/// crate already builds for its own construction-literal checks
/// ([`check`]) and `ref`-projection path-segment validation.
#[must_use]
pub fn declared_shapes(files: &[(FileId, &HirFile)], index: &SymbolIndex) -> ShapeTable {
    // No manifest access at this call site (`structs::check` isn't
    // threaded a `HostManifest` — struct field types aren't in T1d-2's
    // scope), so `Handle<K>` field types resolve `None` here, same as any
    // other name `TypeNames` doesn't recognize — consistent with
    // `annotations::resolve`'s documented "unresolved -> silent" contract.
    let names = annotations::TypeNames::new(index, None);
    let mut by_def = BTreeMap::new();
    for &(file, hir) in files {
        for s in &hir.structs {
            // NOT actually an invariant (review finding on #2240/#2258):
            // `annotations::def_id_for` is exact-file-only, with no
            // fallback arm at all — unlike `lir::lower::structs`'
            // `decls::lookup_global`, which at least rescues a surviving
            // non-std sibling before giving up. So this lookup misses on
            // *every* true intra-module duplicate this file's own
            // declaration lost to (`E023` dropped its symbol-index entry),
            // not only the narrower std-declared-survivor case `E181`
            // reports one layer down. When it misses, this decl silently
            // contributes nothing to `by_def` — a fourth, still-undiagnosed
            // silent-drop site of the exact class `E181` exists to make
            // loud (see that code's own doc and `build_shape_table`'s),
            // just with no diagnostic sink wired here yet.
            let Some(def_id) =
                annotations::def_id_for(index, file, SymbolKind::Struct, &s.name.text)
            else {
                continue;
            };
            if by_def.contains_key(&def_id) {
                continue;
            }
            let fields = s
                .fields
                .iter()
                .map(|f| {
                    let ty = annotations::resolve(&f.ty, &names).unwrap_or(Ty::Unknown);
                    (f.name.text.clone(), ty)
                })
                .collect();
            by_def.insert(def_id, ShapeInfo { fields });
        }
    }
    ShapeTable { by_def }
}

/// [`declared_shapes`]' referrer-scoped lookup table — see that function's
/// doc for the coexistence story this exists to resolve correctly.
#[derive(Default)]
pub struct ShapeTable {
    /// Every shape by its own symbol-index identity — the canonical store,
    /// unambiguous by construction.
    by_def: BTreeMap<DefinitionId, ShapeInfo>,
}

impl ShapeTable {
    /// Number of declared shapes in the project — referrer-free, since a
    /// count needs no disambiguation.
    #[must_use]
    pub fn len(&self) -> usize {
        self.by_def.len()
    }

    /// Whether the project declares no `STRUCT` shapes at all.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.by_def.is_empty()
    }

    /// Resolve a shape already pinned to an exact `DefinitionId` — no
    /// referrer ambiguity possible, since the identity was already resolved
    /// once, correctly, by whatever recorded it (e.g. a construction
    /// literal's `RefKind::Struct` resolution, `resolve::resolve_struct_ref`).
    #[must_use]
    pub fn get_by_def(&self, id: DefinitionId) -> Option<&ShapeInfo> {
        self.by_def.get(&id)
    }

    /// Scope-aware lookup (issue #2241, corrected per #2245/#2246's
    /// peer-root ruling — `docs/decision-log.md`, 2026-08-04): when more
    /// than one declared `STRUCT` shares `name`, resolve through the same
    /// `Candidacy`-based module scoping every other symbol kind uses —
    /// [`crate::resolve::lookup_by_name`], the exact function
    /// `resolve::resolve_struct_ref` already calls for `SymbolKind::Struct`.
    /// This used to hand-roll its own `find(info.file == referrer)
    /// .or_else(find(!is_reserved_root_module))` fallback — a bolt-on std
    /// gate the ruling calls out by name as one of the five symptom gates
    /// to unwind, not a second, diverging implementation of the same
    /// policy. Returns
    /// `None` when `name` names no declared `STRUCT` at all, or
    /// [`crate::resolve::lookup_by_name`] itself resolves to none (e.g.
    /// every candidate sharing the name is std-declared and out of
    /// `scope`).
    #[must_use]
    pub fn resolve(
        &self,
        name: &str,
        scope: &ImportScope,
        index: &SymbolIndex,
    ) -> Option<&ShapeInfo> {
        let def_id = crate::resolve::lookup_by_name(index, scope, name, &[SymbolKind::Struct])?;
        self.by_def.get(&def_id)
    }
}

/// Strict-mode construction checks over every struct literal in the
/// project. Callers only reach this once `strict::config_error` has
/// confirmed `types = strict` + `dialect = brink` (mirrors
/// `strict::check`'s own entry condition).
///
/// `inference`/`resolutions` (issue #670): the same whole-project
/// `InferenceResult`/`ResolutionMap` `strict::check` already computes for
/// its own escape/mismatch checks — this is what lets the mistyped-field
/// check (`E071`) classify a variable/call/index-valued initializer instead
/// of only literal-shaped ones (see the module doc).
#[must_use]
pub fn check(
    files: &[(FileId, &HirFile)],
    index: &SymbolIndex,
    inference: &InferenceResult,
    resolutions: &ResolutionMap,
) -> Vec<Diagnostic> {
    let shapes = declared_shapes(files, index);
    // No manifest access at this call site, same as `declared_shapes` above
    // — a global's own annotation resolving against `Handle<K>` isn't in
    // this check's scope any more than a struct field's is.
    let globals = crate::infer::collect_globals(files, index, None);
    let mut out = Vec::new();
    for &(file, hir) in files {
        let resolution_by_range = resolution_index(resolutions, file);
        let mut v = ConstructionVisitor {
            file,
            shapes: &shapes,
            index,
            globals: &globals,
            signatures: &inference.signatures,
            bodies: &inference.bodies,
            resolution_by_range: &resolution_by_range,
            current_knot_name: None,
            knot_locals: None,
            stitch_locals: None,
            lambda_locals: Vec::new(),
            diagnostics: &mut out,
        };
        // Issue #2098: `ConstructionVisitor::enter_expr` has no state that
        // needs resetting between the block tree and a file-level
        // declaration's own initializer (`locals` is already `None` at this
        // scope) — so the shared entry point covers both in one drive, and
        // the hand-rolled `check_expr`/`expr_children` mirror of
        // `visit::visit`'s own descent this used to need is gone.
        visit::visit_with_decl_initializers(hir, &mut v);
    }
    out
}

// ─── Issue #1900: plain struct-field assignment target checking ──────

/// Strict-mode-only: every [`crate::infer::FieldAssignMismatch`] fact body
/// inference recorded (`~ p.x = expr`, a dotted assignment target — see that
/// type's own doc for why the field chain is left unresolved until now),
/// walked against [`declared_shapes`]/[`ShapeInfo`] to resolve the specific
/// field's declared type and reported as `E063` — the same code
/// `strict::check_typed_assign_mismatches` reports for a *bare* assignment
/// target (issue #1877); this is that check's dotted sibling, split into
/// its own issue (#1900) because the root's declared type is not the
/// field's, so the bare-name comparison doesn't apply as-is. Callers only
/// reach this once `strict::config_error` has confirmed `types = strict` +
/// `dialect = brink` (mirrors [`check`]'s own entry condition).
///
/// Walks `inference.bodies` directly (keyed by `DefinitionId`, itself
/// `Ord`) rather than re-deriving a per-file `def_ids` list the way
/// `strict::check_typed_assign_mismatches` does — every fact already
/// carries its own diagnostic range, so grouping by file first buys nothing
/// extra here. Correction (issue #1900 review finding): the caller
/// (`strict::check`) does *not* sort this aggregate — `strict::check` and
/// `strict_diagnostics` only concatenate each check's output in a fixed
/// call order, with no sort in either. The only downstream ordering is
/// `brink_db::queries::mod::partition_diagnostics` grouping by `FileId` for
/// the salsa query path; the pure `analyze_with_options` path has no
/// ordering step at all. Iterating `inference.bodies` (`Ord`-keyed by
/// `DefinitionId`) still makes this function's own output deterministic —
/// just not because anything downstream re-sorts it.
#[must_use]
pub fn check_assignments(
    files: &[(FileId, &HirFile)],
    index: &SymbolIndex,
    inference: &InferenceResult,
) -> Vec<Diagnostic> {
    let shapes = declared_shapes(files, index);
    // Per-file scope, keyed the same way `resolve::resolve` and `ufcs::resolve`
    // build one per file — `check_field_assign_mismatch` doesn't loop `files`
    // itself (it's driven by `inference.bodies`, keyed by `DefinitionId`), so
    // the scope for the fact's own declaring file is looked up here instead.
    let scopes: BTreeMap<FileId, ImportScope> = files
        .iter()
        .map(|&(file, hir)| {
            let scope = ImportScope::new(hir.module.as_ref().map(|m| m.name.clone()), &hir.imports);
            (file, scope)
        })
        .collect();
    let mut out = Vec::new();
    for (def, body) in &inference.bodies {
        let Some(info) = index.symbols.get(def) else {
            continue;
        };
        let Some(scope) = scopes.get(&info.file) else {
            continue;
        };
        for fact in &body.field_assign_mismatches {
            check_field_assign_mismatch(fact, info.file, scope, index, &shapes, &mut out);
        }
    }
    out
}

/// Walk one [`FieldAssignMismatch`]'s field chain from its already-resolved
/// root type down to the specific field being assigned, comparing the
/// result against the RHS's own type. Silently unclassifiable (no
/// diagnostic) whenever the walk hits a non-`Struct` type or an unresolved
/// shape name (`E068` already covers that separately) — matching
/// [`check_literal`]'s own "unresolved -> silent" contract for the same
/// reason: with no resolved shape to check the name against, "Unknown never
/// disagrees" still holds.
///
/// Issue #1944: a field name the *resolved* shape doesn't declare is a
/// different case — the shape itself is known, so the name can actually be
/// checked, and now is: `E185`, the plain-assignment-target mirror of
/// [`check_literal`]'s own `E070` (construction-literal unknown field).
/// Fired only from inside this already-`Some(shape)` branch — an Unknown/
/// untyped root never reaches here at all (the loop returns above, on the
/// first segment, the moment `current` isn't a resolved `Ty::Struct`), so
/// the "Unknown never disagrees" posture for an *unresolved* receiver is
/// untouched. A chained target (`o.i.a = v`, 3+ segments) never reaches this
/// function in the first place — `check_declared_field_assign_target`'s own
/// `segments.len() == 2` fence means no [`FieldAssignMismatch`] fact is ever
/// recorded for one; LIR's `try_lower_field_assignment` already rejects it
/// outright with `E074`.
///
/// BLOCKING review finding (issue #1900): the `+=` string-numeric
/// display-concat carve-out (issue #1911, `body::is_string_numeric_concat`)
/// applies to a dotted target exactly like it applies to a bare one — `~
/// v.s += 5` on a `string`-declared field desugars to the identical runtime
/// `String`/`Int`|`Float` `Add` arm as `~ v.s = v.s + 5` — but body
/// inference can't decide that carve-out itself: it only ever resolves the
/// *root's* type (`Ty::Struct("S")`, never `string`) when it records the
/// fact, well before the field's own declared type is known. So the
/// carve-out has to be re-applied here, once `current` has been walked all
/// the way down to the field's actual declared type.
fn check_field_assign_mismatch(
    fact: &FieldAssignMismatch,
    file: FileId,
    scope: &ImportScope,
    index: &SymbolIndex,
    shapes: &ShapeTable,
    out: &mut Vec<Diagnostic>,
) {
    let mut current = fact.root_ty.clone();
    for segment in &fact.path {
        let Ty::Struct(shape_name) = &current else {
            return;
        };
        let Some(shape) = shapes.resolve(shape_name, scope, index) else {
            return;
        };
        let Some(field_ty) = shape.field_ty(&segment.text) else {
            // Issue #1944: the receiver's shape resolved, but it declares
            // no field with this name — the E070 mirror for a plain
            // assignment target. Stop the walk here (there is no further
            // field type to compare the RHS against, and continuing would
            // only risk a confusing second diagnostic on the same target).
            out.push(Diagnostic {
                file,
                range: segment.range,
                message: format!(
                    "{}: `{}` has no field `{}`",
                    DiagnosticCode::E185.title(),
                    shape_name,
                    segment.text
                ),
                code: DiagnosticCode::E185,
            });
            return;
        };
        current = field_ty.clone();
    }
    // BLOCKING review finding (issue #1944, PR #2901): `found` can now reach
    // here unresolved (an `EXTERNAL` call with no declared return type,
    // e.g.) since `check_declared_field_assign_target` no longer bails out
    // on an unresolved RHS before recording the fact — that early return was
    // exactly what kept E185 (below) unreachable for such an RHS. Guarded
    // explicitly rather than folded into the `assignable` check that
    // follows: `assignable(T, Unknown)` is `true` (unify, infer/ty.rs:477),
    // but `assignable(T, Conflicted)` is not, so relying on `assignable`
    // alone would start false-firing E063 for an unresolved RHS instead of
    // staying silent on it.
    if fact.found.is_unresolved() {
        return;
    }
    if current.is_unresolved() || crate::infer::assignable(&current, &fact.found) {
        return;
    }
    // Issue #1911's carve-out, re-applied here (BLOCKING review finding,
    // issue #1900) now that `current` is the field's own resolved declared
    // type, not the root's — see this function's own doc.
    if fact.op == AssignOp::Add && is_string_numeric_concat(&current, &fact.found) {
        return;
    }
    // `path` is never empty by construction (the recording site only ever
    // records a fact for a multi-segment target — `segments[1..]` is
    // therefore non-empty), but a defensive `None` here (rather than
    // `expect`, denied in production code) just silently skips the
    // diagnostic instead of panicking if that invariant ever changes.
    let Some(last) = fact.path.last() else {
        return;
    };
    let dotted: Vec<&str> = std::iter::once(fact.root.as_str())
        .chain(fact.path.iter().map(|n| n.text.as_str()))
        .collect();
    out.push(Diagnostic {
        file,
        range: last.range,
        message: format!(
            "`{}` has type `{}` but its declared type is `{}`",
            dotted.join("."),
            fact.found.display(),
            current.display()
        ),
        code: DiagnosticCode::E063,
    });
}

/// `TextRange` has no `Ord` impl, so a `Path`/`Call` reference's range keys
/// this file-local `BTreeMap` as a `(start, end)` `u32` pair — mirrors
/// `infer::mod`'s and `strict`'s own identically-named helper (each module
/// owns its own copy rather than centralizing; the codebase's established
/// convention for this exact utility).
fn range_key(range: TextRange) -> (u32, u32) {
    (range.start().into(), range.end().into())
}

/// This file's own reference resolutions, projected to a range-keyed lookup
/// — mirrors `strict::resolution_index`, narrowed to one file at a time (a
/// `Path`'s range is only unique within its own file).
fn resolution_index(
    resolutions: &ResolutionMap,
    file: FileId,
) -> BTreeMap<(u32, u32), DefinitionId> {
    resolutions
        .iter()
        .filter(|r| r.file == file)
        .map(|r| (range_key(r.range), r.target))
        .collect()
}

/// Everything [`classify_expr_ty`] needs to resolve a non-literal
/// initializer's type: the project symbol index, declaration-derived
/// global types, every inferable def's finalized signature (for a
/// call-valued initializer's return type), this file's range→`DefinitionId`
/// resolutions, and — when the struct literal sits inside a knot/stitch
/// body — that def's own finalized `BodyTypes::locals` (`None` at file
/// scope, where only globals are in play).
///
/// `pub(crate)` (issue #983) so `conversions::check`'s own non-literal
/// `int()`/`float()` argument classification can reuse this exact
/// inference-substrate plumbing instead of re-deriving it — same "reuse
/// existing machinery" precedent `ref_projection` follows for
/// [`ShapeInfo`].
pub(crate) struct MistypeCtx<'a> {
    pub(crate) index: &'a SymbolIndex,
    pub(crate) globals: &'a BTreeMap<DefinitionId, Ty>,
    pub(crate) signatures: &'a BTreeMap<DefinitionId, InferredSig>,
    pub(crate) resolution_by_range: &'a BTreeMap<(u32, u32), DefinitionId>,
    pub(crate) locals: Option<&'a BTreeMap<String, Ty>>,
}

/// Issue #2773's shared lambda-frame helper: the name set a lambda literal
/// itself binds — its own param row, plus (for a block body) every name the
/// block's own statements introduce (`TempDecl`, a `for` loop's var/val, an
/// `if`/`while` `as` binding, recursed through nested `if`/`while`/`for` via
/// [`crate::infer::lambda_own_bindings`]) — pruned out of `outer_locals`
/// (a bare-name-keyed `BodyTypes::locals`-shaped map), with the lambda's own
/// explicitly `: T`-annotated param types seeded back in under their own
/// names.
///
/// This is the fix for the hazard class issue #2773 tracks: `resolved_symbol_ty`
/// (below) resolves a `Param`/`Temp` `Path` by **bare name** out of
/// `ctx.locals`, with no shadowing frame of its own — so a lambda-own
/// binding that shares a name with a *different-typed* outer local gets
/// silently attributed the outer binding's type for any expression inside
/// the lambda's own body. Before this helper existed, every consumer of
/// [`MistypeCtx::locals`]/`BodyTypes::locals` that reads it from
/// [`brink_ir::hir::visit::HirVisitor::enter_expr`] — `conversions.rs`,
/// `coalesce.rs`, this file's own [`ConstructionVisitor`], `ufcs.rs`,
/// `range_refinement.rs`, `contains_domain.rs` — inherited this hazard
/// automatically the moment `hir::visit::walk_expr`'s pre-existing
/// `Expr::Lambda` descent (issue #1685) reached an expression inside a
/// lambda body, because nothing signaled that a new scope had opened. Every
/// one of those `HirVisitor` impls now pushes a pruned frame (built by this
/// function) in [`brink_ir::hir::visit::HirVisitor::enter_lambda`] and pops
/// it in `exit_lambda`.
///
/// `option_conditions.rs`'s condition-position walk (issue #2764/#2768)
/// composes with this same function instead of keeping its own private copy
/// — it cannot use the `enter_lambda`/`exit_lambda` hooks directly (its walk
/// is hand-rolled, not `HirVisitor`-driven, because it needs to distinguish
/// "this is a condition position" from an arbitrary expression — see that
/// module's own doc), but the pruning logic itself is identical, so it is
/// not re-implemented a second time.
///
/// Falls back to an empty pruned base when `outer_locals` is `None` (a
/// file-scope lambda, e.g. a `var f = |x: Option<int>| { … }` initializer)
/// rather than staying `None` itself: an annotated param must still be
/// classifiable there. `outer_locals` and the returned map both use "absent
/// name" identically for `MistypeCtx::locals`'s own `Option`-wrapped
/// `ctx.locals?` reads, so this is not a behavior change for the
/// pre-existing pruning path.
#[must_use]
pub(crate) fn pruned_locals_for_lambda(
    l: &brink_ir::LambdaExpr,
    index: &SymbolIndex,
    outer_locals: Option<&BTreeMap<String, Ty>>,
) -> BTreeMap<String, Ty> {
    let stmts: &[BlockStmt] = match &l.body {
        brink_ir::LambdaBody::Block { stmts, .. } => stmts,
        brink_ir::LambdaBody::Expr(_) => &[],
    };
    let mut body_names: BTreeMap<String, (TextRange, Option<brink_ir::TypeExpr>)> = BTreeMap::new();
    crate::infer::lambda_own_bindings(stmts, &mut body_names);
    let body_bound_names: BTreeSet<String> = body_names.keys().cloned().collect();

    let mut own_names = body_names;
    for p in &l.params {
        own_names
            .entry(p.name.text.clone())
            .or_insert((p.name.range, None));
    }

    let mut pruned: BTreeMap<String, Ty> = outer_locals.map_or_else(BTreeMap::new, |locals| {
        locals
            .iter()
            .filter(|(name, _)| !own_names.contains_key(*name))
            .map(|(name, ty)| (name.clone(), ty.clone()))
            .collect()
    });

    let type_names = annotations::TypeNames::new(index, None);
    for p in &l.params {
        if body_bound_names.contains(&p.name.text) {
            continue;
        }
        if let Some(te) = &p.annotation
            && let Some(ty) = annotations::resolve(te, &type_names)
        {
            pruned.insert(p.name.text.clone(), ty);
        }
    }

    pruned
}

struct ConstructionVisitor<'a> {
    file: FileId,
    shapes: &'a ShapeTable,
    index: &'a SymbolIndex,
    globals: &'a BTreeMap<DefinitionId, Ty>,
    signatures: &'a BTreeMap<DefinitionId, InferredSig>,
    bodies: &'a BTreeMap<DefinitionId, crate::infer::BodyTypes>,
    resolution_by_range: &'a BTreeMap<(u32, u32), DefinitionId>,
    /// The currently-open knot's own name — `enter_stitch` needs it to
    /// reconstruct the qualified `knot.stitch` name a stitch is indexed
    /// under (mirrors `strict::check_value_calls`' own lookup).
    current_knot_name: Option<String>,
    /// The enclosing knot's own finalized locals, set for the duration of
    /// its body (and every stitch nested inside it — `visit::visit` walks a
    /// knot's own body before descending into its stitches, so a stitch's
    /// `enter_stitch` overrides this with its *own* locals rather than
    /// inheriting the parent knot's).
    knot_locals: Option<&'a BTreeMap<String, Ty>>,
    /// The currently-open stitch's own finalized locals, if any — takes
    /// priority over `knot_locals` while set.
    stitch_locals: Option<&'a BTreeMap<String, Ty>>,
    /// Issue #2773: a stack of pruned-locals frames, one per currently-open
    /// lambda literal (innermost last) — pushed in `enter_lambda`, popped in
    /// `exit_lambda`. Takes priority over `stitch_locals`/`knot_locals`
    /// while non-empty, so an expression inside a lambda's own body sees its
    /// own bindings' types (or "unclassifiable") instead of a same-named
    /// outer binding's.
    lambda_locals: Vec<BTreeMap<String, Ty>>,
    diagnostics: &'a mut Vec<Diagnostic>,
}

impl ConstructionVisitor<'_> {
    fn current_locals(&self) -> Option<&BTreeMap<String, Ty>> {
        self.lambda_locals
            .last()
            .or_else(|| self.stitch_locals.or(self.knot_locals))
    }

    /// The `DefinitionId` a knot/stitch's own name resolves to, mirroring
    /// `strict::check_escapes`'/`check_value_calls`' own lookup — a top-level
    /// stitch promoted to knot status is indexed under `SymbolKind::Stitch`
    /// (#626), hence the `knot.ptr`-derived `kind`.
    fn knot_def_id(&self, knot: &Knot) -> Option<DefinitionId> {
        let kind = knot.symbol_kind();
        annotations::def_id_for(self.index, self.file, kind, &knot.name.text)
    }
}

impl HirVisitor for ConstructionVisitor<'_> {
    fn visit_exprs(&self) -> bool {
        true
    }

    fn enter_knot(&mut self, knot: &Knot) {
        self.current_knot_name = Some(knot.name.text.clone());
        self.knot_locals = self
            .knot_def_id(knot)
            .and_then(|id| self.bodies.get(&id))
            .map(|b| &b.locals);
    }

    fn exit_knot(&mut self, _knot: &Knot) {
        self.current_knot_name = None;
        self.knot_locals = None;
    }

    fn enter_stitch(&mut self, stitch: &Stitch) {
        // Stitches are indexed by qualified `knot.stitch` name (mirrors
        // `strict::check_escapes`'/`check_value_calls`' own lookup).
        // `visit::visit` only ever calls `enter_stitch` nested inside an
        // `enter_knot`/`exit_knot` pair, so `current_knot_name` is always
        // set here.
        self.stitch_locals = self.current_knot_name.as_ref().and_then(|knot_name| {
            let qualified = format!("{knot_name}.{}", stitch.name.text);
            annotations::def_id_for(self.index, self.file, SymbolKind::Stitch, &qualified)
                .and_then(|id| self.bodies.get(&id))
                .map(|b| &b.locals)
        });
    }

    fn exit_stitch(&mut self, _stitch: &Stitch) {
        self.stitch_locals = None;
    }

    fn enter_expr(&mut self, expr: &Expr) {
        if let Expr::StructLiteral(sl) = expr {
            // Built from direct field projections (not `self.ctx()`/
            // `self.current_locals()`) so the borrow checker sees this only
            // borrows `index`/`globals`/`signatures`/`resolution_by_range`/
            // the three locals fields, disjoint from the `self.diagnostics`
            // reborrow below — a method call opaquely borrows the whole
            // `&self` receiver for as long as its return value lives, which
            // would conflict with `self.diagnostics` inside the same call.
            let ctx = MistypeCtx {
                index: self.index,
                globals: self.globals,
                signatures: self.signatures,
                resolution_by_range: self.resolution_by_range,
                locals: self
                    .lambda_locals
                    .last()
                    .or_else(|| self.stitch_locals.or(self.knot_locals)),
            };
            check_literal(sl, self.file, self.shapes, &ctx, self.diagnostics);
        }
    }

    fn enter_lambda(&mut self, l: &brink_ir::LambdaExpr) {
        let pruned = pruned_locals_for_lambda(l, self.index, self.current_locals());
        self.lambda_locals.push(pruned);
    }

    fn exit_lambda(&mut self, _l: &brink_ir::LambdaExpr) {
        self.lambda_locals.pop();
    }
}

/// Duplicate-field diagnostic (`E084`, issue #675) — unlike [`check`]'s
/// missing/extra/mistyped diagnostics above, this doesn't need the shape to
/// resolve (a repeated field name is detectable from the literal's own
/// field list alone) and runs under *both* `types` policies: a duplicate
/// field is a structural authoring mistake, not a type-checking concern.
/// Callers wire this in under `dialect = Brink || is_native` (wider than
/// every other TM-4c construction-literal check, matching `E138`'s own
/// wiring — see the module doc) rather than gating it behind
/// `strict::config_error` the way [`check`] is.
#[must_use]
pub fn check_duplicates(files: &[(FileId, &HirFile)]) -> Vec<Diagnostic> {
    let mut out = Vec::new();
    for &(file, hir) in files {
        let mut v = DuplicateFieldVisitor {
            file,
            diagnostics: &mut out,
        };
        // Issue #2098: `DuplicateFieldVisitor::enter_expr` carries no
        // per-position state at all, so the shared entry point covers the
        // block tree and every file-level declaration's own initializer in
        // one drive — the hand-rolled `check_duplicates_expr`/`expr_children`
        // mirror of `visit::visit`'s own descent this used to need is gone.
        visit::visit_with_decl_initializers(hir, &mut v);
    }
    out
}

struct DuplicateFieldVisitor<'a> {
    file: FileId,
    diagnostics: &'a mut Vec<Diagnostic>,
}

impl HirVisitor for DuplicateFieldVisitor<'_> {
    fn visit_exprs(&self) -> bool {
        true
    }

    fn enter_expr(&mut self, expr: &Expr) {
        if let Expr::StructLiteral(sl) = expr {
            check_literal_duplicates(sl, self.file, self.diagnostics);
        }
    }
}

/// Flag every field-name occurrence in `sl` beyond its first — one
/// diagnostic per repeated initializer, naming the field and pointing at
/// the *repeated* occurrence (not the first, so authors see exactly which
/// initializer is the redundant one).
fn check_literal_duplicates(sl: &StructLiteral, file: FileId, out: &mut Vec<Diagnostic>) {
    let mut seen: crate::determinism::LookupSet<&str> = crate::determinism::LookupSet::new();
    for (name, _value) in &sl.fields {
        if !seen.insert(name.text.as_str()) {
            out.push(Diagnostic {
                file,
                range: name.range,
                message: format!(
                    "{}: field `{}` is initialized more than once",
                    DiagnosticCode::E084.title(),
                    name.text
                ),
                code: DiagnosticCode::E084,
            });
        }
    }
}

/// Check one struct literal against its declared shape (if resolvable — an
/// unresolved shape name has nothing to check against, and is already
/// diagnosed separately by `resolve::resolve_struct_ref`'s `E068`).
///
/// Issue #2241: `sl.shape`'s own name is a `RefKind::Struct` reference the
/// analyzer already resolved with full module-scope `Candidacy`
/// (`resolve::resolve_struct_ref`, walked into the `ResolutionMap` every
/// construction literal's shape name gets — `symbols::project`'s `walk_expr`
/// registers one for every `Expr::StructLiteral`, unconditionally). Consuming
/// that recorded resolution by range (`ctx.resolution_by_range`) rather than
/// re-deriving the shape from `sl.shape.text` by bare name is exactly the
/// "lowering consumes analyzer types" fix PR #2248 already applied on the LIR
/// side for this same reference kind — this is its analyzer-side twin. A
/// missing entry here means `resolve_struct_ref` itself couldn't resolve the
/// name (already reported as `E068`), so there is nothing to check against,
/// same as before.
fn check_literal(
    sl: &StructLiteral,
    file: FileId,
    shapes: &ShapeTable,
    ctx: &MistypeCtx<'_>,
    out: &mut Vec<Diagnostic>,
) {
    let Some(shape) = ctx
        .resolution_by_range
        .get(&range_key(sl.shape.range))
        .and_then(|def_id| shapes.get_by_def(*def_id))
    else {
        return;
    };

    // Extra fields (strict-only, since `check` only ever runs under strict
    // per its own doc — the module's `structs::check` is only reached from
    // `strict::check`).
    for (name, _value) in &sl.fields {
        if !shape.has_field(&name.text) {
            out.push(Diagnostic {
                file,
                range: name.range,
                message: format!(
                    "{}: `{}` has no field `{}`",
                    DiagnosticCode::E070.title(),
                    sl.shape.text,
                    name.text
                ),
                code: DiagnosticCode::E070,
            });
        }
    }

    // Missing fields (strict-only, since `check` only ever runs under
    // strict per its own doc).
    for (field_name, _ty) in &shape.fields {
        if !sl.fields.iter().any(|(n, _)| &n.text == field_name) {
            out.push(Diagnostic {
                file,
                range: sl.ptr.text_range(),
                message: format!(
                    "{}: `{}` is missing field `{field_name}`",
                    DiagnosticCode::E069.title(),
                    sl.shape.text
                ),
                code: DiagnosticCode::E069,
            });
        }
    }

    // Mistyped fields — only for classifiable initializers (see module doc:
    // literal-shaped classify from their own shape; variable/call/index-
    // valued ones consult `ctx`'s inference substrate).
    for (name, value) in &sl.fields {
        let Some(declared_ty) = shape.field_ty(&name.text) else {
            continue; // already flagged as an extra field above
        };
        if declared_ty.is_unresolved() {
            continue; // the field's own annotation didn't resolve (E061)
        }
        let Some(actual_ty) = classify_expr_ty(value, ctx) else {
            continue; // not classifiable — see module doc
        };
        // Row-insensitive (issue #1680): a `fn`-typed field's declared type
        // carries the top effect row and the initializer's carries its real
        // creation target, so rows must not decide this comparison — see
        // `infer::assignable`.
        if !crate::infer::assignable(declared_ty, &actual_ty) {
            out.push(Diagnostic {
                file,
                range: name.range,
                message: format!(
                    "{}: field `{}` declared `{}` but initialized with `{}`",
                    DiagnosticCode::E071.title(),
                    name.text,
                    declared_ty.display(),
                    actual_ty.display()
                ),
                code: DiagnosticCode::E071,
            });
        }
    }
}

/// Classify a struct-field initializer's type when it's statically obvious
/// from its own shape — literals, and (recursively) array/map/struct
/// literals. Anything else (a variable/call/index/…) returns `None` here;
/// [`classify_expr_ty`] is the entry point [`check_literal`] actually calls,
/// falling back to the inference-substrate classification for those forms
/// (issue #670) before finally treating an unclassifiable expression as
/// silently clean — the same "Unknown never disagrees" posture
/// `annotations::mismatches` takes.
fn literal_ty(expr: &Expr) -> Option<Ty> {
    match expr {
        Expr::Int(_) => Some(Ty::Int),
        Expr::Float(_) => Some(Ty::Float),
        Expr::Bool(_) => Some(Ty::Bool),
        Expr::String(s) => match s.parts.as_slice() {
            [] | [brink_ir::StringPart::Literal(_)] => Some(Ty::String),
            _ => None, // interpolated — not purely a literal
        },
        Expr::ArrayLiteral(a) => {
            let elems: Vec<Ty> = a.elements.iter().map(literal_ty).collect::<Option<_>>()?;
            Some(Ty::Array(Box::new(crate::infer::unify_all(elems))))
        }
        Expr::MapLiteral(m) => {
            let mut keys = Vec::with_capacity(m.entries.len());
            let mut vals = Vec::with_capacity(m.entries.len());
            for (k, v) in &m.entries {
                keys.push(literal_ty(k)?);
                vals.push(literal_ty(v)?);
            }
            Some(Ty::Map(
                Box::new(crate::infer::unify_all(keys)),
                Box::new(crate::infer::unify_all(vals)),
            ))
        }
        Expr::StructLiteral(sl) => Some(Ty::Struct(sl.shape.text.clone())),
        _ => None,
    }
}

/// Classify a struct-field initializer's type — [`literal_ty`]'s
/// literal-shaped classification first, falling back to the non-literal
/// forms issue #670 adds: a `Path` (variable), a `Call` (function), or an
/// `Index` expression, each resolved through `ctx`'s inference substrate.
/// `None` — "not classifiable" — whenever the resolved type is itself
/// `Unknown`/`Conflicted`, or the expression shape isn't handled at all
/// (e.g. a field access, an infix expression): the same "Unknown never
/// disagrees" posture [`literal_ty`] and `annotations::mismatches` both take.
///
/// `pub(crate)` (issue #983) — see [`MistypeCtx`]'s doc for why.
pub(crate) fn classify_expr_ty(expr: &Expr, ctx: &MistypeCtx<'_>) -> Option<Ty> {
    if let Some(ty) = literal_ty(expr) {
        return Some(ty);
    }
    match expr {
        Expr::Path(p) => resolved_symbol_ty(p.range, ctx),
        Expr::Call(path, _args) => {
            // Only a direct call to a known inferable knot/stitch is
            // classified here — a call through a function *value* is T1c's
            // own domain (`strict::check_value_calls`'s `ValueCallFact`s),
            // not this diagnostic's.
            let def = ctx.resolution_by_range.get(&range_key(path.range))?;
            let sig = ctx.signatures.get(def)?;
            (!sig.return_ty.is_unresolved()).then(|| sig.return_ty.clone())
        }
        Expr::Index(idx) => {
            let base_ty = classify_expr_ty(&idx.base, ctx)?;
            match base_ty {
                Ty::Array(elem) if !elem.is_unresolved() => Some(*elem),
                Ty::Map(_key, val) if !val.is_unresolved() => Some(*val),
                _ => None,
            }
        }
        _ => None,
    }
}

/// Resolve a `Path` expression's own range to a concrete [`Ty`]: a
/// param/temp reads the enclosing def's finalized `BodyTypes::locals`
/// (`ctx.locals`, `None` at file scope — see [`MistypeCtx`]'s doc); a
/// global `VAR`/`CONST` reads `infer::collect_globals`'s declaration-derived
/// type; a `LIST`/list-item name is nominally `List<L>`. Mirrors
/// `infer::body::InferPass::ty_of_def`'s own dispatch exactly (the same
/// firewall a body's own inference already enforces), just read post hoc
/// from the finalized results instead of live during a body solve.
fn resolved_symbol_ty(range: TextRange, ctx: &MistypeCtx<'_>) -> Option<Ty> {
    let def = *ctx.resolution_by_range.get(&range_key(range))?;
    let info = ctx.index.symbols.get(&def)?;
    let ty = match info.kind {
        SymbolKind::Param | SymbolKind::Temp => ctx.locals?.get(&info.name)?.clone(),
        SymbolKind::Variable | SymbolKind::Constant => ctx.globals.get(&def)?.clone(),
        SymbolKind::List => Ty::List(info.name.clone()),
        SymbolKind::ListItem => {
            let (list, _item) = info.name.split_once('.')?;
            Ty::List(list.to_string())
        }
        SymbolKind::Knot
        | SymbolKind::Stitch
        | SymbolKind::External
        | SymbolKind::Struct
        | SymbolKind::Label => {
            return None;
        }
    };
    if ty.is_unresolved() { None } else { Some(ty) }
}

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

    fn build(src: &str) -> (HirFile, SymbolIndex) {
        let parsed = brink_syntax::parse(src);
        let (hir, manifest, _diag) = lower(FileId(0), &parsed.tree());
        let (index, _diag) = crate::symbol_index(&[(FileId(0), &manifest)]);
        (hir, (*index).clone())
    }

    /// Like [`build`], but also computes real resolutions and a whole-project
    /// [`InferenceResult`] — needed by every test exercising the non-literal
    /// (variable/call/index) classification issue #670 adds, since that path
    /// consults exactly this substrate.
    fn build_with_inference(src: &str) -> (HirFile, SymbolIndex, ResolutionMap, InferenceResult) {
        let parsed = brink_syntax::parse(src);
        let (hir, manifest, _diag) = lower(FileId(0), &parsed.tree());
        let (index, _diag) = crate::symbol_index(&[(FileId(0), &manifest)]);
        let (resolutions, _diag) =
            crate::resolve(FileId(0), &manifest, &index, &crate::ImportScope::default());
        let inference = crate::infer_project(
            &[(FileId(0), &hir)],
            &index,
            &resolutions,
            None,
            &BTreeMap::new(),
        );
        (hir, (*index).clone(), (*resolutions).clone(), inference)
    }

    /// [`check`] driven by [`build_with_inference`]'s output — the harness
    /// every non-literal-classification test below shares.
    fn check_all(src: &str) -> Vec<Diagnostic> {
        let (hir, index, resolutions, inference) = build_with_inference(src);
        check(&[(FileId(0), &hir)], &index, &inference, &resolutions)
    }

    /// [`build_with_inference`]'s native-surface twin. Lambdas exist only on
    /// the native surface, so the #1764 fixtures below must go through
    /// `lower_native` (the same reason `coalesce`'s `build_native` exists).
    fn build_native(src: &str) -> (HirFile, SymbolIndex, ResolutionMap, InferenceResult) {
        let parsed = brink_syntax_native::parse(src);
        assert!(parsed.errors().is_empty(), "{:?}", parsed.errors());
        let (hir, manifest, _diag) = brink_ir::hir::lower_native::lower(FileId(0), &parsed.tree());
        let (index, _diag) = crate::symbol_index(&[(FileId(0), &manifest)]);
        let (resolutions, _diag) =
            crate::resolve(FileId(0), &manifest, &index, &crate::ImportScope::default());
        let inference = crate::infer_project(
            &[(FileId(0), &hir)],
            &index,
            &resolutions,
            None,
            &BTreeMap::new(),
        );
        (hir, (*index).clone(), (*resolutions).clone(), inference)
    }

    /// [`check`] over native source — [`check_all`]'s native twin.
    fn check_all_native(src: &str) -> Vec<Diagnostic> {
        let (hir, index, resolutions, inference) = build_native(src);
        check(&[(FileId(0), &hir)], &index, &inference, &resolutions)
    }

    /// [`check_assignments_all`]'s native-surface twin — [`build_native`]'s
    /// output run through [`check_assignments`] rather than [`check`]. Only
    /// the native surface has lambdas, so the lambda-frame regression test
    /// below (issue #2906 BLOCKING review finding) needs this rather than
    /// `check_assignments_all`.
    fn check_assignments_all_native(src: &str) -> Vec<Diagnostic> {
        let (hir, index, _resolutions, inference) = build_native(src);
        check_assignments(&[(FileId(0), &hir)], &index, &inference)
    }

    #[test]
    fn clean_construction_produces_no_diagnostics() {
        let diags = check_all(
            "STRUCT Point = #{x: float, y: float}\n\
             === main ===\n~ p = Point#{x: 1.0, y: 2.0}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn missing_field_is_e069_naming_the_field() {
        let diags = check_all(
            "STRUCT Point = #{x: float, y: float}\n\
             === main ===\n~ p = Point#{x: 1.0}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E069);
        assert!(diags[0].message.contains('y'), "{:?}", diags[0].message);
    }

    #[test]
    fn extra_field_is_e070_naming_the_field() {
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n~ p = Point#{x: 1.0, z: 2.0}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E070);
        assert!(diags[0].message.contains('z'), "{:?}", diags[0].message);
    }

    #[test]
    fn mistyped_field_is_e071_naming_the_field() {
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n~ p = Point#{x: \"hi\"}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
        assert!(diags[0].message.contains('x'), "{:?}", diags[0].message);
    }

    #[test]
    fn int_initializer_for_a_float_field_is_the_legal_coercion() {
        // §4's directional int -> float coercion applies here too.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n~ p = Point#{x: 1}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    // ── issue #670: variable/call/index-valued initializers ────────────

    #[test]
    fn global_variable_valued_initializer_fires_when_provably_mistyped() {
        // `v`'s declaration-derived type is a concrete `string` (its own
        // literal initializer) — disagrees with `Point.x`'s declared
        // `float`, so this now fires exactly like a literal `"hi"` would.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             VAR v = \"hi\"\n=== main ===\n~ p = Point#{x: v}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
        assert!(diags[0].message.contains('x'), "{:?}", diags[0].message);
    }

    #[test]
    fn global_variable_valued_initializer_of_the_right_type_is_clean() {
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             VAR v = 1.0\n=== main ===\n~ p = Point#{x: v}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn param_variable_valued_initializer_fires_when_provably_mistyped() {
        // `n`'s only use in the body is compared against a string literal,
        // so its inferred `BodyTypes::locals` type is a concrete `string` —
        // disagrees with `Point.x`'s declared `float`.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main(n) ===\n\
             {n == \"a\":\n  yes\n}\n~ p = Point#{x: n}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    // ─── issue #2793: the ordinary (non-lambda) fn/knot annotated-param
    // half of #2786's `BodyTypes::locals` visibility fix ─────────────────

    /// #2786 overlaid an *ordinary* `fn`/knot param's own written annotation
    /// onto `pass.locals` whenever the body walk left it absent — the exact
    /// same mechanism `option_conditions.rs`'s
    /// `annotated_fn_param_option_condition_is_e116` pins for E116, here for
    /// this file's E071 field-mismatch check instead. `n`'s only other
    /// appearance is the `Point#{x: n}` field initializer itself — no other
    /// statement observes it (mirrors
    /// `unused_param_variable_valued_initializer_stays_silent_when_unknown`
    /// just below, minus the annotation), so pre-#2786 this param stayed
    /// `Unknown` in `pass.locals`. Unlike `coalesce.rs`'s `or` chains and
    /// `contains_domain.rs`'s `contains` needle (both #2793 findings where a
    /// sibling `infer_intrinsic`/`infer_infix` arm's own `observe` call
    /// forces the param's locals entry to something else *before* the
    /// annotation overlay runs), a struct literal's field values are never
    /// `observe`d against their declared field type during the main walk
    /// (`infer::body::InferPass::infer_expr`'s own `Expr::StructLiteral` arm
    /// doc: "Field-type propagation through a struct's declared shape is
    /// out of scope for this slice") — so this position has no such
    /// pre-emption, and the annotation overlay is what finally supplies the
    /// classification: `n: string` disagrees with `Point.x: float`, so this
    /// must now fire — the new true positive #2793 asks each consumer to
    /// confirm.
    #[test]
    fn annotated_fn_param_field_mismatch_is_e071() {
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main(n: string) ===\n~ p = Point#{x: n}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
        assert!(diags[0].message.contains('x'), "{:?}", diags[0].message);
    }

    /// Negative control alongside
    /// [`annotated_fn_param_field_mismatch_is_e071`]: an ordinary annotated
    /// param whose declared type already agrees with the field's declared
    /// type must stay clean.
    #[test]
    fn annotated_fn_param_field_agreement_stays_clean() {
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main(n: float) ===\n~ p = Point#{x: n}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn unused_param_variable_valued_initializer_stays_silent_when_unknown() {
        // `n` is never used anywhere else in the body, so it stays `Unknown`
        // — "Unknown never disagrees" holds even for a variable initializer.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main(n) ===\n~ p = Point#{x: n}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn call_valued_initializer_fires_when_provably_mistyped() {
        // `label()`'s only `~ return` is a string literal, so its
        // finalized `InferredSig::return_ty` is a concrete `string`.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === function label() ===\n~ return \"a\"\n\
             === main ===\n~ p = Point#{x: label()}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    #[test]
    fn call_valued_initializer_of_the_right_type_is_clean() {
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === function label() ===\n~ return 1.0\n\
             === main ===\n~ p = Point#{x: label()}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn index_valued_initializer_fires_when_provably_mistyped() {
        // `xs` is a local `~ temp` bound to a `#[...]` array-of-strings
        // literal, so its finalized locals type is `Array<string>` — indexing
        // it yields `string`, disagreeing with `Point.x`'s declared `float`.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n\
             ~ temp xs = #[\"a\", \"b\"]\n~ p = Point#{x: xs[0]}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    #[test]
    fn index_valued_initializer_of_the_right_type_is_clean() {
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n\
             ~ temp xs = #[1.0, 2.0]\n~ p = Point#{x: xs[0]}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn index_valued_initializer_stays_silent_when_unknown() {
        // `xs` is only ever indexed, never assigned/observed to a concrete
        // type elsewhere — reading through an `Unknown` base never learns an
        // array shape (`infer::body`'s own `Expr::Index` arm), so this stays
        // silent rather than false-flagging.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === main(xs) ===\n~ p = Point#{x: xs[0]}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn unresolved_shape_name_is_not_double_reported_here() {
        // No `STRUCT Bogus` declared — `resolve::resolve_struct_ref` already
        // reports E068 elsewhere; this pass has nothing to check against.
        let diags = check_all("=== main ===\n~ p = Bogus#{x: 1}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn nested_struct_literal_field_is_checked_by_shape_name() {
        let diags = check_all(
            "STRUCT Inner = #{v: float}\nSTRUCT Outer = #{inner: Inner}\n\
             === main ===\n~ o = Outer#{inner: Inner#{v: 1.0}}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn nested_struct_literal_mistyped_field_still_flags_outer() {
        let diags = check_all(
            "STRUCT Wrong = #{v: float}\nSTRUCT Inner = #{v: float}\nSTRUCT Outer = #{inner: Inner}\n\
             === main ===\n~ o = Outer#{inner: Wrong#{v: 1.0}}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    #[test]
    fn struct_literal_inside_var_initializer_is_checked() {
        let diags = check_all("STRUCT Point = #{x: float}\nVAR p = Point#{x: \"hi\"}\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    #[test]
    fn variable_valued_initializer_inside_var_initializer_uses_global_scope_only() {
        // A struct literal in a file-level VAR/CONST initializer has no
        // enclosing knot/stitch body — only a reference to *another* global
        // is classifiable there (never a param/temp, which can't exist at
        // file scope). `other`'s declared type disagrees with `Point.x`.
        let diags =
            check_all("STRUCT Point = #{x: float}\nVAR other = \"hi\"\nVAR p = Point#{x: other}\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    #[test]
    fn stitch_local_variable_valued_initializer_fires_when_provably_mistyped() {
        // Every other non-literal-classification test above only ever
        // exercises knot scope (`main`), file scope, or `main(n)`'s own
        // params — never a stitch body. This drives the `enter_stitch`/
        // `stitch_locals` dispatch path specifically: `t`'s finalized
        // `BodyTypes::locals` type (a concrete `string`, from its own
        // literal initializer) disagrees with `Point.x`'s declared `float`.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === room ===\n= inside\n~ temp t = \"hi\"\n~ p = Point#{x: t}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
        assert!(diags[0].message.contains('x'), "{:?}", diags[0].message);
    }

    #[test]
    fn mistyped_variable_field_diagnostic_is_order_independent() {
        // Issue #670's own scope names "order-independence property tests
        // per the #627 discipline" as a deliverable — mirrors strict.rs's
        // `escape_diagnostics_are_order_independent` forward/reversed
        // pattern. `v`'s mistyped classification (and the resulting E071)
        // must not depend on which position its field initializer occupies
        // in the literal.
        let forward = "STRUCT Point = #{x: float, y: float}\n\
             VAR v = \"hi\"\n=== main ===\n~ p = Point#{x: v, y: 1.0}\n-> DONE\n";
        let reversed = "STRUCT Point = #{x: float, y: float}\n\
             VAR v = \"hi\"\n=== main ===\n~ p = Point#{y: 1.0, x: v}\n-> DONE\n";

        let diags_f = check_all(forward);
        let diags_r = check_all(reversed);

        assert_eq!(diags_f.len(), 1, "{diags_f:?}");
        assert_eq!(diags_f[0].code, DiagnosticCode::E071);
        assert!(diags_f[0].message.contains('x'), "{:?}", diags_f[0].message);

        assert_eq!(diags_r.len(), 1, "{diags_r:?}");
        assert_eq!(diags_r[0].code, DiagnosticCode::E071);
        assert!(diags_r[0].message.contains('x'), "{:?}", diags_r[0].message);
    }

    // ─── check_assignments (E063, issue #1900) ─────────────────────────

    /// [`check_assignments`] driven by [`build_with_inference`]'s output —
    /// mirrors [`check_all`] for the plain-assignment sibling check.
    fn check_assignments_all(src: &str) -> Vec<Diagnostic> {
        let (hir, index, _resolutions, inference) = build_with_inference(src);
        check_assignments(&[(FileId(0), &hir)], &index, &inference)
    }

    #[test]
    fn field_assignment_mismatch_on_var_is_e063_naming_the_dotted_target() {
        // The issue's own repro: `p.x`'s declared `float` disagrees with the
        // RHS `string`.
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float, y: float}\n\
             VAR p: Point = Point#{x: 0.0, y: 0.0}\n\
             === main ===\n~ p.x = \"wrong\"\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E063);
        assert!(diags[0].message.contains("p.x"), "{:?}", diags[0].message);
    }

    #[test]
    fn field_assignment_of_the_declared_type_is_clean() {
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float, y: float}\n\
             VAR p: Point = Point#{x: 0.0, y: 0.0}\n\
             === main ===\n~ p.x = 1.0\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn field_assignment_int_initializer_for_a_float_field_is_the_legal_coercion() {
        // §4's directional int -> float coercion applies here too, same as
        // `int_initializer_for_a_float_field_is_the_legal_coercion` above.
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\nVAR p: Point = Point#{x: 0.0}\n\
             === main ===\n~ p.x = 1\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn field_assignment_mismatch_on_annotated_temp_is_e063() {
        // The second of the issue's two named root sources: an annotated `~
        // temp`'s own ascription, not a global.
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n~ temp p: Point = Point#{x: 0.0}\n~ p.x = \"wrong\"\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E063);
    }

    #[test]
    fn field_assignment_mismatch_on_unannotated_temp_with_construction_literal_initializer_is_e063_issue_2906()
     {
        // Issue #2906: before this fix, `check_declared_field_assign_target`
        // only ever resolved a Temp root's shape from `self.annotated` (an
        // explicit `~ temp p: Point = …` ascription) — an *unannotated* `~
        // temp p = Point#{…}` has no ascription, so this test used to pin
        // silence here even though the shape is plainly knowable from the
        // construction-literal initializer itself. That was the recording-
        // site gap the issue reports, not a genuine "no shape to check
        // against" case — `check_declared_field_assign_target` now also
        // consults the initializer's own inferred `Ty::Struct` shape when
        // there is no explicit ascription, so this fires `E063` exactly like
        // the annotated spelling does (see
        // `field_assignment_mismatch_on_annotated_temp_is_e063` above).
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n~ temp p = Point#{x: 0.0}\n~ p.x = \"wrong\"\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E063);
    }

    #[test]
    fn field_assignment_on_genuinely_unresolved_temp_stays_silent() {
        // The genuine "Unknown never disagrees" case, distinct from the one
        // above (issue #2906): a `~ temp` whose value is never statically
        // knowable at all — here, an unannotated `EXTERNAL` call with no
        // declared return type — never resolves past `Ty::Unknown`, so
        // there is truly no shape to check the field name or value against.
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             EXTERNAL make_point()\n\
             === main ===\n~ temp p = make_point()\n~ p.x = \"wrong\"\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn field_assignment_to_a_nonexistent_field_is_e185_issue_1944() {
        // Issue #1944: before this fix, a field name the resolved shape
        // doesn't declare was silently accepted here — this test itself
        // used to pin that as `diags.is_empty()`, which was the exact hole
        // the issue reports (a plain assignment to an unknown field
        // compiled clean under strict, with no E070-equivalent for a
        // non-literal target). The shape *is* resolved here (`p: Point`),
        // so the name can actually be checked — unlike an Unknown/untyped
        // receiver, where "Unknown never disagrees" still applies (see
        // `field_assignment_to_a_nonexistent_field_on_unresolved_receiver_stays_silent`
        // below).
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             VAR p: Point = Point#{x: 0.0}\n\
             === main ===\n~ p.bogus = \"wrong\"\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E185);
        assert!(diags[0].message.contains("bogus"), "{:?}", diags[0].message);
    }

    /// Sibling should-NOT-fire case (issue #1944 design constraint,
    /// corrected per review finding): an unannotated function parameter's
    /// root never resolves past `Ty::Unknown` — there is genuinely no shape
    /// anywhere to check the field name against — so "Unknown never
    /// disagrees" holds for the *receiver* exactly as it does for `E063`
    /// (see `field_assignment_on_genuinely_unresolved_temp_stays_silent`
    /// above, E063's own sibling). Issue #2906 closed the *other* silent
    /// case this test used to also cover — an unannotated `~ temp p =
    /// Point#{x: 0.0}` — by widening the recording site's fallback to the
    /// initializer's own inferred shape (see
    /// `field_assignment_to_a_nonexistent_field_on_unannotated_temp_with_construction_literal_initializer_is_e185_issue_2906`
    /// below); a function param has no initializer at all to fall back to,
    /// so it stays the genuine "no shape anywhere" case.
    #[test]
    fn field_assignment_to_a_nonexistent_field_on_unresolved_receiver_stays_silent() {
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             === function f(p) ===\n~ p.bogus = \"wrong\"\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn field_assignment_to_a_nonexistent_field_on_unannotated_temp_with_construction_literal_initializer_is_e185_issue_2906()
     {
        // Issue #2906: the `E185` twin of
        // `field_assignment_mismatch_on_unannotated_temp_with_construction_literal_initializer_is_e063_issue_2906`
        // above — same recording-site widening, same seam
        // (`check_field_assign_mismatch`), the unknown-field-name arm
        // instead of the type-mismatch arm.
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             === main ===\n~ temp p = Point#{x: 0.0}\n~ p.bogus = 1\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E185);
        assert!(diags[0].message.contains("bogus"), "{:?}", diags[0].message);
    }

    #[test]
    fn field_assignment_to_a_nonexistent_field_on_unannotated_temp_reassigned_to_a_different_struct_stays_silent()
     {
        // Issue #2906's own conservative-reassignment carve-out: `p`'s
        // initializer resolves to `Point`, but `p` is reassigned to a
        // different, incompatible-shaped struct before the field write. The
        // initializer-inferred shape lives in a declaration-time-only map
        // (mirroring `self.annotated`'s own "recorded once, consulted as a
        // fallback" shape) that a later plain reassignment never touches —
        // so this is NOT caught by `Ty::unify` driving `self.locals["p"]` to
        // `Ty::Conflicted` the way a bare `check_declared_assign_target`
        // fact would be. It is the explicit `reassigned_temps` bookkeeping
        // this fix adds (every bare `~ p = expr` reassignment anywhere in
        // the body, recorded during the walk) that withdraws the pending
        // fact post-walk instead.
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             STRUCT Other = #{y: float}\n\
             === main ===\n~ temp p = Point#{x: 0.0}\n~ p = Other#{y: 1.0}\n\
             ~ p.bogus = 1\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn field_assignment_to_a_nonexistent_field_on_unannotated_temp_reassigned_to_an_unknown_shape_stays_silent()
     {
        // Issue #2906's harder conservative case, called out explicitly by
        // the issue: `p` is reassigned to an *unresolvable* value (an
        // unannotated `EXTERNAL` call's return) rather than a different
        // concrete struct. `Ty::unify(Ty::Struct(_), Ty::Unknown)` is the
        // identity rule — it stays `Ty::Struct("Point")`, NOT `Conflicted`
        // — so `self.locals` alone can never distinguish "p was never
        // reassigned" from "p was reassigned to something unresolvable".
        // Without the explicit `reassigned_temps` tracking this fix adds,
        // the widened fallback would still trust the stale `Point` shape
        // here and false-fire `E185` on a receiver that might legitimately
        // be any shape at this point.
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             EXTERNAL make_thing()\n\
             === main ===\n~ temp p = Point#{x: 0.0}\n~ p = make_thing()\n\
             ~ p.bogus = 1\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// BLOCKING review finding on issue #2906's own PR: `temp_init_shapes`
    /// used to be excluded from [`FrameSnapshot`] on the claim that a
    /// lambda-local shadow's imprecision here was under-detection-only,
    /// never a false positive. It was a false positive — a lambda-local `~
    /// temp p = …` of a *different* struct permanently clobbered the
    /// *outer* `p`'s entry, surviving past the lambda's own frame, so the
    /// outer `p.y = 1.0` (legal — `p` is an `Other`, which does declare
    /// `y`) read the lambda's stale `Point` shape instead and false-fired
    /// `E185` (`Point` has no field `y`). Reproduced against PR head
    /// 98d2ad24 verbatim from the review finding. Native surface only —
    /// lambdas don't exist on the ink-compat surface.
    #[test]
    fn dotted_assign_target_outer_temp_survives_a_lambda_local_shadow_of_the_same_name() {
        let diags = check_assignments_all_native(
            "struct Point { x: float }\n\
             struct Other { y: float }\n\
             fn main() {\n\
             \x20 let p = Other { y: 0.0 };\n\
             \x20 let f = ||: int { let p = Point { x: 0.0 }; 0 };\n\
             \x20 p.y = 1.0;\n\
             }\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// BLOCKING review finding on issue #2906's own PR: `record_ref_param_writes`
    /// only ever folded a `ref`-out call-site rebind into `record_write`/
    /// `record_fn_write` (the effect-row summary), never into
    /// `reassigned_temps` — so `resolve_pending_field_assign_mismatches`
    /// stayed blind to a `ref`-out param rebinding the caller's local to an
    /// entirely different, unresolvable-shaped value. `ref`-out params are
    /// idiomatic ink, not an exotic shape; a callee that always rebinds its
    /// `ref` param is common (`reset`, `swap`, …). Reproduced against PR
    /// head 98d2ad24 verbatim from the review finding: `p` is a `Point` at
    /// its own declaration, but `reset(ref p)` rebinds it to an `Other`
    /// before the dotted write, so `p.bogus = 1` must stay silent exactly
    /// like the bare-reassignment carve-out above already does.
    #[test]
    fn dotted_assign_target_stays_silent_after_a_ref_out_param_rebind() {
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             STRUCT Other = #{y: float}\n\
             === function reset(ref q) ===\n~ q = Other#{y: 1.0}\n~ return\n\
             === main ===\n~ temp p = Point#{x: 0.0}\n~ reset(ref p)\n\
             ~ p.bogus = 1\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// BLOCKING review finding (smaller) on issue #2906's own PR:
    /// `register_temp_init_shape` used to unconditionally clear
    /// `reassigned_temps` on every same-named `TempDecl` redeclaration —
    /// erasing reassignment history a fact staged *earlier* (between the
    /// reassignment and the redeclaration) depended on, since
    /// `pending_inferred_field_assign_mismatches` is resolved once, post-walk.
    /// Reproduced against PR head 98d2ad24 verbatim from the review finding:
    /// `p` is reassigned to an unresolvable `make_thing()` result before the
    /// dotted write (already covered by the "reassigned to an unknown
    /// shape" carve-out above), then redeclared again afterward — the
    /// redeclaration must not retroactively un-withdraw the staged fact.
    #[test]
    fn dotted_assign_target_reassignment_history_survives_a_later_redeclaration_of_the_same_name() {
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             EXTERNAL make_thing()\n\
             === main ===\n~ temp p = Point#{x: 0.0}\n~ p = make_thing()\n\
             ~ p.bogus = 1\n~ temp p = Point#{x: 0.0}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// Sibling enumeration (issue #1944): `BlockStmt::Assignment` — the T1b
    /// `~ { … }` block form — reports E185 exactly like `Stmt::Assignment`
    /// above. `infer_block_stmt`'s `BlockStmt::Assignment` arm calls the
    /// identical `check_declared_field_assign_target`, recording the same
    /// `FieldAssignMismatch` fact `check_field_assign_mismatch` walks
    /// regardless of which statement form produced it — the two call sites
    /// are structural mirrors, not independently-checked paths.
    #[test]
    fn field_assignment_to_a_nonexistent_field_inside_a_block_stmt_is_e185_issue_1944() {
        let diags = check_assignments_all(
            "STRUCT Point = #{x: float}\n\
             VAR p: Point = Point#{x: 0.0}\n\
             === main ===\n~ {\n    p.bogus = \"wrong\"\n}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E185);
    }

    #[test]
    fn bare_var_assignment_is_not_double_reported_by_check_assignments() {
        // A single-segment target is `check_declared_assign_target`'s job
        // (issue #1877 / E063 via `strict::check_typed_assign_mismatches`),
        // never this dotted-target check's — `check_assignments` must stay
        // silent for it (no double-report across the two checks).
        let diags = check_assignments_all("VAR v: int = 5\n=== main ===\n~ v = \"hi\"\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    // ─── check_duplicates (E084, issue #675) ──────────────────────────

    #[test]
    fn duplicate_field_is_e084_naming_the_field() {
        let (hir, _index) = build(
            "STRUCT Point = #{x: float, y: float}\n\
             === main ===\n~ p = Point#{x: 1.0, x: 2.0, y: 3.0}\n-> DONE\n",
        );
        let diags = check_duplicates(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E084);
        assert!(diags[0].message.contains('x'), "{:?}", diags[0].message);
    }

    #[test]
    fn duplicate_field_points_at_the_repeated_occurrence_not_the_first() {
        let src =
            "STRUCT Point = #{x: float}\n=== main ===\n~ p = Point#{x: 1.0, x: 2.0}\n-> DONE\n";
        let (hir, _index) = build(src);
        let diags = check_duplicates(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        let second_x = src.rfind("x: 2.0").expect("second x initializer");
        assert_eq!(usize::from(diags[0].range.start()), second_x);
    }

    #[test]
    fn clean_construction_has_no_duplicate_diagnostic() {
        let (hir, _index) = build(
            "STRUCT Point = #{x: float, y: float}\n\
             === main ===\n~ p = Point#{x: 1.0, y: 2.0}\n-> DONE\n",
        );
        let diags = check_duplicates(&[(FileId(0), &hir)]);
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn duplicate_field_flagged_even_under_gradual_and_unresolved_shape() {
        // No `types = strict` context needed here (this build() harness
        // never runs `strict::check`'s gate) — and the shape name doesn't
        // even need to resolve, unlike `check`'s missing/extra/mistyped
        // trio: a repeated field name is a mistake regardless.
        let (hir, _index) = build("=== main ===\n~ p = Bogus#{x: 1, x: 2}\n-> DONE\n");
        let diags = check_duplicates(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E084);
    }

    #[test]
    fn duplicate_field_inside_var_initializer_is_checked() {
        let (hir, _index) = build("STRUCT Point = #{x: float}\nVAR p = Point#{x: 1.0, x: 2.0}\n");
        let diags = check_duplicates(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E084);
    }

    // ─── issue #1764: a lambda's statements in a VAR/CONST initializer ──

    /// Coverage for a lambda's statements in a VAR/CONST initializer comes
    /// from `visit::visit_with_decl_initializers` (which reaches the
    /// initializer at all) composed with `walk_expr`'s `Expr::Lambda` arm
    /// (which already descends a lambda's statements) — there is no
    /// separate hand-rolled recursion for this position (issue #2098). A
    /// block-bodied lambda's `let` is a statement, not the body's value
    /// expression.
    #[test]
    fn a_duplicate_field_in_a_lambda_statement_of_a_var_initializer_is_reported() {
        let (hir, _index, _res, _inf) = build_native(
            "struct Point { x: float }\nvar f = ||: int {\n  let p = Point { x: 1.0, x: 2.0 };\n  0\n};\n",
        );
        let diags = check_duplicates(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E084);
    }

    /// The shape-agreement trio reaches the same position — a literal-valued
    /// initializer classifies without any locals, so `MistypeCtx::locals =
    /// None` is no obstacle here.
    #[test]
    fn a_mistyped_field_in_a_lambda_statement_of_a_var_initializer_is_reported() {
        let diags = check_all_native(
            "struct Point { x: float }\nvar f = ||: int {\n  let p = Point { x: \"hi\" };\n  0\n};\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
        assert!(diags[0].message.contains('x'), "{:?}", diags[0].message);
    }

    /// The tail position was already covered — pinned so a later refactor
    /// can't trade one half of the body for the other.
    #[test]
    fn a_mistyped_field_in_a_lambda_tail_of_a_var_initializer_is_still_reported() {
        let diags = check_all_native(
            "struct Point { x: float }\nvar f = ||: Point {\n  let a = 1;\n  Point { x: \"hi\" }\n};\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    // ─── issue #2773: a lambda-own binding must not inherit an outer
    // same-named local's type ────────────────────────────────────────

    /// Reproduces the hazard issue #2773 tracks, live in this file's own
    /// `ConstructionVisitor` before its `enter_lambda`/`exit_lambda` frame
    /// existed: `resolved_symbol_ty` reads `ctx.locals` (bare-name-keyed
    /// `BodyTypes::locals`) with no shadowing frame of its own, and
    /// `ConstructionVisitor` is `HirVisitor`-driven — `hir::visit::walk_expr`
    /// has descended into a lambda's own block body since issue #1685, so
    /// every `enter_expr` this visitor received for an expression inside the
    /// lambda body was already reading the *enclosing* `build`'s locals,
    /// unpruned. `build`'s own temp `x` is `array`-typed
    /// (`[1, 2, 3]`); the lambda's own `x: int` param shadows it. Pre-fix,
    /// `Point { x: x }`'s field initializer resolved `x` to the outer
    /// `array` — never assignable to `Point.x: float` — a false-positive
    /// `E071`. `int` *is* legally assignable to `float` (the directional
    /// coercion `int_initializer_for_a_float_field_is_the_legal_coercion`
    /// pins above), so the fixed behavior is clean.
    #[test]
    fn lambda_param_shadowing_outer_local_of_a_different_type_is_not_misclassified() {
        let diags = check_all_native(
            "struct Point { x: float }\n\
             fn build() {\n  let x = [1, 2, 3];\n  let f = |x: int| {\n    let p = Point { x: x };\n  };\n}\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// The pruning must not silence a *genuine* mistype inside the lambda's
    /// own body — only the outer binding's type is discarded, not
    /// classification itself. The lambda's own `x: string` param really is
    /// the wrong type for `Point.x: float`.
    #[test]
    fn lambda_param_own_annotation_still_flags_a_genuine_mistype() {
        let diags = check_all_native(
            "struct Point { x: float }\n\
             fn build() {\n  let x = [1, 2, 3];\n  let f = |x: string| {\n    let p = Point { x: x };\n  };\n}\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E071);
    }

    #[test]
    fn three_way_duplicate_flags_every_repeat_after_the_first() {
        let (hir, _index) = build(
            "STRUCT Point = #{x: float}\n\
             === main ===\n~ p = Point#{x: 1.0, x: 2.0, x: 3.0}\n-> DONE\n",
        );
        let diags = check_duplicates(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 2, "{diags:?}");
        assert!(diags.iter().all(|d| d.code == DiagnosticCode::E084));
    }

    // ─── issue #2241: declared_shapes is referrer-scoped, not last-wins ──

    /// Build a project file coexisting with a "std"-shaped file (M-2d
    /// cross-declared-module coexistence, mirroring the real stdlib mount
    /// #2080) — each declares its own `STRUCT Cue`, with the project's own
    /// carrying MORE fields than the coexisting file's same-named one.
    /// Returns everything [`check`] needs to validate the project's own
    /// construction literal.
    ///
    /// No `#@module` directive in either source: the module tag a real
    /// compile derives from `#@module`/the native path is supplied directly
    /// here via `ModuleMap`, exactly as `manifest::tests`'s own
    /// `cross_declared_module_duplicate_coexists_under_brink` does — this
    /// test only needs the tag on the index, not the parsed source's own
    /// (irrelevant) `HirFile::module`.
    fn build_project_with_std_homonym(
        project_src: &str,
        std_src: &str,
    ) -> (
        FileId,
        HirFile,
        FileId,
        HirFile,
        SymbolIndex,
        ResolutionMap,
        InferenceResult,
    ) {
        let project_file = FileId(0);
        let std_file = FileId(1);

        let project_parsed = brink_syntax::parse(project_src);
        let (project_hir, project_manifest, _diag) = lower(project_file, &project_parsed.tree());
        let std_parsed = brink_syntax::parse(std_src);
        let (std_hir, std_manifest, _diag) = lower(std_file, &std_parsed.tree());

        let mut modules = crate::ModuleMap::new();
        modules.insert(
            project_file,
            crate::ResolvedModule {
                name: "story::main".to_string(),
                declared: true,
                was: None,
            },
        );
        modules.insert(
            std_file,
            crate::ResolvedModule {
                name: "std::conventions::screenplay".to_string(),
                declared: true,
                was: None,
            },
        );

        let (index, diag) = crate::symbol_index_with_modules(
            &[(project_file, &project_manifest), (std_file, &std_manifest)],
            &modules,
            crate::Dialect::Brink,
            false,
        );
        assert!(
            diag.is_empty(),
            "cross-declared-module `Cue`s must coexist with no diagnostic: {diag:?}"
        );

        let project_scope =
            crate::ImportScope::new(Some("story::main".to_string()), &project_hir.imports);
        let (project_resolutions, _diag) =
            crate::resolve(project_file, &project_manifest, &index, &project_scope);
        let std_scope = crate::ImportScope::new(
            Some("std::conventions::screenplay".to_string()),
            &std_hir.imports,
        );
        let (std_resolutions, _diag) = crate::resolve(std_file, &std_manifest, &index, &std_scope);

        let mut resolutions: ResolutionMap = (*project_resolutions).clone();
        resolutions.extend((*std_resolutions).iter().cloned());

        let files = [(project_file, &project_hir), (std_file, &std_hir)];
        let inference = crate::infer_project(&files, &index, &resolutions, None, &BTreeMap::new());

        (
            project_file,
            project_hir,
            std_file,
            std_hir,
            (*index).clone(),
            resolutions,
            inference,
        )
    }

    /// The wave's own headline scenario: a project's own `STRUCT Cue`
    /// coexists with a same-named `STRUCT Cue` from a distinct declared
    /// module (mirrors `std/conventions/screenplay.brink`'s real one-field
    /// `Cue`). Before this fix, `declared_shapes` built a flat
    /// `BTreeMap<String, ShapeInfo>` via plain last-`insert`-wins — with
    /// `files` ordered `[project, std]` below, std's `ShapeInfo` is inserted
    /// LAST and silently overwrites the project's own in the table, even
    /// though the construction literal itself lives in the project file and
    /// `resolve::resolve_struct_ref` already resolves it to the PROJECT's own
    /// `Cue` (never std's — the referrer's own module wins that tie-break).
    /// The missing-field check would then validate against std's one-field
    /// shape, which the literal's sole `speaker` initializer already
    /// satisfies — a silent E069 false negative: "accepted when it should
    /// error" (issue #2241's own words).
    ///
    /// Rule 20a: verified this test FAILS on the pre-fix code (reverting
    /// `declared_shapes` to the flat bare-name `BTreeMap::insert` and
    /// `check_literal` to `shapes.get(&sl.shape.text)`) — the assertion
    /// below (`diags.len() == 1`, `E069` naming `voiceover`) fails with
    /// `diags` empty instead, because std's one-field shape (which won the
    /// last-insert race with `files = [project, std]`) sees the literal's
    /// sole `speaker` field as complete.
    #[test]
    fn construction_check_resolves_the_referrers_own_shape_when_std_and_project_share_a_name() {
        let project_src = "STRUCT Cue = #{speaker: string, voiceover: string}\n\
             === main ===\n~ p = Cue#{speaker: \"A\"}\n-> DONE\n";
        let std_src = "STRUCT Cue = #{speaker: string}\nHello.\n";

        let (project_file, project_hir, std_file, std_hir, index, resolutions, inference) =
            build_project_with_std_homonym(project_src, std_src);

        // Deliberately `[project, std]` — std's shape is inserted LAST into
        // the pre-fix flat table, exposing the last-wins bug.
        let files = [(project_file, &project_hir), (std_file, &std_hir)];
        let diags = check(&files, &index, &inference, &resolutions);

        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E069);
        assert!(
            diags[0].message.contains("voiceover"),
            "the missing-field diagnostic must name the PROJECT's own missing field \
             (`voiceover`), proving the check validated the literal against the project's own \
             2-field `Cue` shape rather than the coexisting file's 1-field one: {diags:?}"
        );
    }

    /// F2 review finding (#2253): [`ShapeTable::resolve`] is the path
    /// [`check_assignments`]/[`check_field_assign_mismatch`] (E063) uses —
    /// unlike [`check`]/[`check_literal`] above, which never calls
    /// `resolve` at all (it goes through [`ShapeTable::get_by_def`] with an
    /// identity already resolved by `resolve::resolve_struct_ref`). This
    /// exercises the multi-candidate branch `resolve` exists to handle,
    /// through its own dedicated consumer rather than a proxy.
    ///
    /// Project and std each declare their own `STRUCT Cue`, deliberately
    /// with *different* declared types for the same field name (`x: float`
    /// vs `x: string`) so a wrong resolution doesn't just report the wrong
    /// message — it silently reports NOTHING: assigning the string
    /// `"wrong"` to `p.x` disagrees with the project's own `float`, but
    /// would agree with std's `string`. If `resolve` ever picked std's
    /// `Cue` for a reference inside the project file, this regresses to an
    /// empty `diags` exactly like the pre-fix last-insert-wins bug did for
    /// E069 above.
    ///
    /// Rule 20a: verified this test FAILS (empty `diags` instead of one
    /// `E063`) against `ShapeTable::resolve` reverted to always return the
    /// std candidate (i.e. simulating a resolution that ignores the
    /// referrer's own module) — restored before committing.
    #[test]
    fn check_assignments_resolves_the_referrers_own_shape_when_std_and_project_share_a_name() {
        let project_src = "STRUCT Cue = #{x: float}\n\
             VAR p: Cue = Cue#{x: 0.0}\n\
             === main ===\n~ p.x = \"wrong\"\n-> DONE\n";
        let std_src = "STRUCT Cue = #{x: string}\nHello.\n";

        let (project_file, project_hir, std_file, std_hir, index, _resolutions, inference) =
            build_project_with_std_homonym(project_src, std_src);

        let files = [(project_file, &project_hir), (std_file, &std_hir)];
        let diags = check_assignments(&files, &index, &inference);

        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E063);
        assert!(
            diags[0].message.contains("float"),
            "the mismatch must be reported against the PROJECT's own `float`-declared `x`, not \
             std's `string`-declared one — which would silently accept the identically-typed \
             \"wrong\" RHS and produce zero diagnostics: {diags:?}"
        );
    }
}