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
//! B3a — UFCS (uniform function call syntax) resolution: `recv.name(args)`
//! (issue #1482; D1–D5 RULED 2026-07-26, `docs/decision-log.md` "UFCS
//! resolution pass designed: type-directed, in the analyzer, five rulings").
//!
//! ## Why this lives in `brink-analyzer`
//!
//! UFCS resolution is **type-directed name resolution**: field-access-wins
//! is unanswerable without the receiver's type, so the verdict cannot be
//! reached in the frontend or in HIR lowering. The native lowering already
//! produces `Expr::Call(Path, args)` for a dotted callee unchanged (see
//! `brink-ir`'s `hir::lower_native::expr::lower_call`) — this module is the
//! pass that decides what that shape *means*.
//!
//! ## The algorithm, per call site
//!
//! For `recv.name(args)` — an `Expr::Call` whose callee `Path` has more than
//! one segment and whose head names a *value* in scope:
//!
//! 1. Infer the receiver's type (`recv` = every segment but the last).
//! 2. The type declares a field `name` → **field access wins**. The field
//!    must be function-typed; the call is a call *through the field's
//!    value* ([`UfcsVerdict::FieldCall`], rows per #872).
//!    **D1**: a matching but non-callable field is a **hard error**
//!    ([`DiagnosticCode::E140`]) — never a fall-through to a free function,
//!    so a call's meaning never hinges on a field's type.
//! 3. Else resolve `name` as a free function in **ordinary lexical scope
//!    only** (D4 — no method sets, no inherent impls: any in-scope free
//!    function is method-callable) — file `use` + the T1b/NS stdlib
//!    prelude (`len`, `push`, `sort_by`, …) — and record the desugar to
//!    `name(recv, args)` ([`UfcsVerdict::FreeFnDesugar`] for an index
//!    symbol, [`UfcsVerdict::PreludeDesugar`] for a prelude verb, which has
//!    no index symbol to point at).
//! 4. Neither → one diagnostic naming **both** attempts
//!    ([`DiagnosticCode::E141`]).
//!
//! **D3**: an unknown receiver type at the resolution point is an error
//! demanding an annotation ([`DiagnosticCode::E142`]), *not* a deferral —
//! there is deliberately no deferral machinery here. The improvement
//! (smarter inference ordering) is tracked separately and is additive.
//!
//! **D5 — auto-ref** (issue #1462, landed on top of this pass): the desugar
//! is by value *unless* the resolved free function's first parameter is
//! declared `ref`. Then the receiver is passed by reference
//! ([`UfcsVerdict::FreeFnAutoRef`]) and the desugar spells the projection
//! explicitly — `party.members.heal(5)` → `heal(ref party.members, 5)` —
//! riding the T1e ref-argument/projection machinery
//! (`brink_ir::lir::lower::expr::lower_call_args`) for a **durable** root,
//! or (**RULED 2026-07-27**, issue #1531) a frame-local read/call/
//! write-back RMW expansion for a **frame-local** root one field deep
//! (`brink_ir::lir::lower::blocks::try_lower_frame_local_auto_ref_stmt`) —
//! never a parallel path for the durable case. A receiver that cannot be
//! written through is refused with [`DiagnosticCode::E143`] rather than
//! silently desugared by value, which would drop the mutation: see
//! [`UfcsVisitor::auto_ref_fault`] for exactly which receivers those are. A
//! non-`ref` first parameter is unaffected — plain by-value desugar, with
//! no lvalue requirement on the receiver.
//!
//! ## Scope fences
//!
//! - Only the final pre-`(` segment gets this treatment; a bare `a.b` (an
//!   `Expr::FieldAccess`, or a dotted `Expr::Path`) is untouched.
//! - Each call in `a.b().c()` resolves independently — this pass keys
//!   verdicts by call-site range, never by chain.
//! - **The ink dialect is untouched by construction.** ink's own
//!   `FunctionCall` lowering always builds a *single-segment* callee path
//!   (`brink-ir`'s `hir::lower::expr::references`), and its computed-callee
//!   `CallExpr` is a structural `E104`. A multi-segment `Expr::Call` path
//!   can therefore only originate in the native frontend, so no dialect
//!   flag is needed to keep this pass off the ink corpus.
//! - The explicit free-call spelling (`name(recv, args)`) is unaffected.
//!
//! ## The side table (D2)
//!
//! The verdict is recorded in a **side table** keyed by node
//! ([`SideTable`]), not written back into the HIR — HIR stays immutable,
//! matching the analyzer's existing "inference results travel beside the
//! tree" posture (`infer::InferenceResult`).
//!
//! The table is published as the seam (`brink_analyzer::ufcs_resolution`)
//! the two ruled consumers read. **LIR lowering is wired** (issue #1506,
//! `brink-db`'s `ufcs_resolution_query` translates this table into
//! `brink-ir`'s own lowering-facing mirror at the query boundary) — it now
//! emits either a call through the field's value or the desugared free
//! call for real. A resolved site LIR lowering cannot find a verdict for
//! (a caller that never ran this pass) still refuses with
//! [`DiagnosticCode::E144`] rather than lowering against the receiver's own
//! id, which would be a silently wrong program — but that is a defensive
//! fallback now, not the unconditional behavior. IDE hover/go-to-def
//! (issue #1507, `brink-ide`'s `ufcs_hover` module) is wired too — it reads
//! the same memoized table (`brink_db::ProjectDb::ufcs_verdict`) to name the
//! real target rather than the receiver the [`ResolutionMap`] records for
//! the callee path.
//!
//! [`SideTable`] is deliberately generic over its payload: it is
//! `(node → verdict)` plumbing, so a second payload kind can ride the same
//! keying and the same lookup without a parallel structure being invented.
//! Issue #1492 did exactly that — `crate::coalesce`'s [`CoalesceTable`]
//! is a `SideTable<CoalesceChain>` carrying `or`-coalescing's recorded
//! operand/result types to the same LIR-lowering consumer, on this keying,
//! with no second mechanism.
//!
//! [`CoalesceTable`]: crate::CoalesceTable
//! [`CoalesceChain`]: crate::CoalesceChain

use std::collections::BTreeMap;

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

use crate::annotations;
use crate::infer::{InferenceResult, InferredSig, Ty, assignable, ref_assignable};
use crate::resolve::ImportScope;
use crate::structs::{ShapeTable, declared_shapes};

// ─── The side table (D2) ─────────────────────────────────────────────

/// Identity of one HIR node for side-table purposes: the file it lives in
/// plus its source range.
///
/// `TextRange` has no `Ord` impl (ranges have no single natural total
/// order), so the range travels as a `(start, end)` `u32` pair — the same
/// `range_key` convention `infer`, `strict`, and `structs` each already use
/// for their own range-keyed maps. A range is only unique *within* a file,
/// hence the [`FileId`] half: side-table entries must never be merged
/// across files.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct NodeKey {
    /// The file the node was lowered from.
    pub file: FileId,
    /// The node's source range, as `(start, end)`.
    pub range: (u32, u32),
}

impl NodeKey {
    /// The key for a node at `range` in `file`.
    #[must_use]
    pub fn new(file: FileId, range: TextRange) -> Self {
        Self {
            file,
            range: (range.start().into(), range.end().into()),
        }
    }
}

/// A `(node → payload)` side channel: analysis verdicts recorded *beside*
/// the HIR rather than written into it (D2 — the HIR stays immutable).
///
/// Generic over the payload so a second kind of verdict can ride the same
/// plumbing instead of a parallel structure being invented for it. Backed by
/// a `BTreeMap` so iteration order is deterministic (house rule — never
/// iterate a `HashMap` where order affects output); [`Self::iter`] is what a
/// consumer that wants *every* verdict (e.g. an IDE building an overlay)
/// walks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SideTable<V> {
    entries: BTreeMap<NodeKey, V>,
}

impl<V> Default for SideTable<V> {
    fn default() -> Self {
        Self {
            entries: BTreeMap::new(),
        }
    }
}

impl<V> SideTable<V> {
    /// An empty table.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Record `value` for the node at `key`, returning any previous entry.
    pub fn insert(&mut self, key: NodeKey, value: V) -> Option<V> {
        self.entries.insert(key, value)
    }

    /// The payload recorded for the node at `key`, if any.
    #[must_use]
    pub fn get(&self, key: NodeKey) -> Option<&V> {
        self.entries.get(&key)
    }

    /// The payload recorded for the node at `range` in `file`, if any — the
    /// convenience spelling for a consumer holding an HIR node rather than a
    /// pre-built [`NodeKey`].
    #[must_use]
    pub fn at(&self, file: FileId, range: TextRange) -> Option<&V> {
        self.get(NodeKey::new(file, range))
    }

    /// Every recorded entry, in deterministic `(file, range)` order.
    pub fn iter(&self) -> impl Iterator<Item = (NodeKey, &V)> {
        self.entries.iter().map(|(k, v)| (*k, v))
    }

    /// How many nodes carry a payload.
    #[must_use]
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether no node carries a payload.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}

/// What one `recv.name(args)` call site resolved to (D2's "node → resolved
/// target"). Consumed by LIR lowering — which of the two code shapes to
/// emit — and by IDE hover/go-to-def, which needs the *real* target rather
/// than the receiver the [`ResolutionMap`] records for the callee path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UfcsVerdict {
    /// Field access won (step 2): the receiver's type declares a
    /// function-typed field with the called name, so the call is a call
    /// *through that field's value*.
    FieldCall {
        /// The receiver's inferred type.
        receiver: Ty,
        /// The field name — the call's final pre-`(` path segment.
        field: String,
        /// The field's declared type. Always a [`Ty::Fn`] — a
        /// non-callable match is `E140`, never a verdict.
        field_ty: Ty,
        /// Issue #1918: this verdict's own arity fact. Unlike
        /// [`Self::FreeFnDesugar`]/[`Self::FreeFnAutoRef`], a field call has
        /// no receiver-prepending desugar — `npc.on_greet(3)` lowers
        /// straight to `lir::ExprKind::CallValue { callee, args }` calling the
        /// field's own `fn(...)` value with the *written* arguments only
        /// (`brink_ir::lir::lower::expr::lower_ufcs_call`'s `FieldCall`
        /// arm), so a mismatch here is a plain expected/got pair, not a
        /// per-argument [`UfcsArgMismatch`]. Computed unconditionally
        /// alongside this verdict, like every other verdict's own arg-check
        /// fields; reported only by strict mode ([`check_strict`], `E063`)
        /// — this verdict is structurally `strict::check_value_calls`'s T1c
        /// "call through a function value" domain, just reached via field
        /// access, and this reuses that check's own
        /// `ValueCallKind::ArityMismatch` wording verbatim. Gradual mode
        /// relies on the runtime `FunctionValueArity` fault
        /// `Opcode::CallValue` already raises for every call through a
        /// function value — the same bytecode shape this verdict lowers
        /// to, so arity is enforced there regardless of static policy.
        arity_mismatch: Option<UfcsArityMismatch>,
        /// Issue #1918: this verdict's own per-argument type mismatches —
        /// the `FieldCall` sibling of [`Self::FreeFnDesugar`]'s own
        /// `arg_mismatches`. **Differs from that sibling's index
        /// convention**: a field call passes no receiver argument, so
        /// `index` here is 0-based over the *written* arguments only —
        /// matching `strict::check_value_calls`'s own
        /// `ValueCallKind::ArgMismatch` convention, not
        /// [`UfcsArgMismatch::index`]'s "receiver counts as 0" default (see
        /// that field's own doc for the exception this carves out).
        /// Reported only by strict mode (`E063`), same gate as
        /// `arity_mismatch` above.
        arg_mismatches: Vec<UfcsArgMismatch>,
    },
    /// **D5 auto-ref** (issue #1462): a free function won (step 3) *and* its
    /// first parameter is declared `ref`, so the call desugars to
    /// `name(ref recv, args)` — the receiver spelled as an explicit T1e
    /// ref-argument/projection, so the callee's writes land in the
    /// receiver's own cell instead of in a copy.
    ///
    /// Only ever recorded for a receiver that can actually be written
    /// through ([`UfcsVisitor::auto_ref_fault`]); anything else is `E143`.
    FreeFnAutoRef {
        /// The receiver's inferred type.
        receiver: Ty,
        /// The free function's name, as written.
        name: String,
        /// The definition the desugared call targets.
        target: DefinitionId,
        /// Issue #1881: statically-checkable argument-type mismatches
        /// between the desugared call `name(recv, args)` and `target`'s
        /// already-known declared param types, computed unconditionally
        /// alongside this verdict — see [`UfcsArgMismatch`]'s own doc.
        /// Reported only by strict mode ([`check_strict`], `E063`).
        arg_mismatches: Vec<UfcsArgMismatch>,
    },
    /// A free function won (step 3): the call desugars to
    /// `name(recv, args)`, by value.
    FreeFnDesugar {
        /// The receiver's inferred type.
        receiver: Ty,
        /// The free function's name, as written.
        name: String,
        /// The definition the desugared call targets.
        target: DefinitionId,
        /// Issue #1881: identical posture to [`Self::FreeFnAutoRef`]'s own
        /// `arg_mismatches` field — the by-value desugar shape.
        arg_mismatches: Vec<UfcsArgMismatch>,
    },
    /// A T1b/NS stdlib prelude name won (step 3, D4's "file `use` + prelude"
    /// candidate set): the call desugars to `name(recv, args)` exactly like
    /// [`Self::FreeFnDesugar`], but the target is a VM-native intrinsic
    /// (`resolve::is_t1b_stdlib_name`/`resolve::is_builtin_function`), not an
    /// index symbol — there is no [`DefinitionId`] to record. `xs.len()`,
    /// `inventory.push(sword)`, `a.sort_by(c)` all land here.
    PreludeDesugar {
        /// The receiver's inferred type.
        receiver: Ty,
        /// The prelude function's name, as written.
        name: String,
        /// Issue #1919: statically-checkable argument-domain mismatches
        /// between the desugared call `name(recv, args)` and the verb's
        /// own container-projected domain (the receiver's element/key/
        /// value type — a prelude verb has no [`DefinitionId`] and so no
        /// declared param list to compare against), computed
        /// unconditionally alongside this verdict — see
        /// [`UfcsVisitor::check_ufcs_prelude_arg_types`]'s own doc.
        /// Reported only by strict mode ([`check_strict`], `E063`), the
        /// same code [`Self::FreeFnDesugar`]'s own `arg_mismatches` uses.
        arg_mismatches: Vec<UfcsArgMismatch>,
    },
}

/// One statically-checkable argument-type mismatch at a UFCS-desugared free
/// function call (`recv.name(args)` → `name(recv, args)`) — issue #1881,
/// the UFCS sibling of `infer::DirectCallArgMismatch` (#1864/PR #1875,
/// direct calls) and `infer::TypedAssignMismatch` (#1877/PR #1899,
/// declaration initializers and assignments). Reported by [`check_strict`]
/// as `E063`, the same code the other two siblings use — no new code minted
/// for this position (docs/t1c-spec.md §8's "existing TM-3 machinery"
/// posture, extended here rather than a parallel checker).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UfcsArgMismatch {
    /// The mismatched argument's 0-based position in the **desugared** call
    /// `name(recv, args)` — `0` names the receiver itself (the desugar's
    /// first positional slot); `i` for `i >= 1` names the `(i - 1)`-th
    /// *written* argument. Matches the "receiver counts as the first
    /// argument" convention this call site's own arity-mismatch diagnostic
    /// already uses (see [`UfcsVisitor::try_free_fn_desugar`]).
    ///
    /// **Exception (issue #1918):** a [`UfcsVerdict::FieldCall`]'s own
    /// `arg_mismatches` does not follow this convention — a field call has
    /// no receiver-prepending desugar, so `index` there is 0-based over the
    /// *written* arguments only (`0` names the first written argument, not
    /// the receiver); see that variant's own field doc.
    pub index: usize,
    /// The desugared target's declared parameter type at `index`.
    pub expected: Ty,
    /// The receiver's (`index == 0`) or written argument's statically
    /// classified type.
    pub found: Ty,
}

/// A [`UfcsVerdict::FieldCall`]'s own arity fact (issue #1918) — a call
/// through a struct's fn-typed field expects/supplies a plain count, not a
/// per-argument type, so this is a separate fact from [`UfcsArgMismatch`]
/// rather than a shoehorned entry in that list. See that verdict's own
/// `arity_mismatch` field doc for the full rationale (why this is checked
/// at all, and why it's strict-mode-only).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UfcsArityMismatch {
    /// The field's declared `fn(T…): R` row's own parameter count.
    pub expected: usize,
    /// The call site's own written argument count.
    pub got: usize,
}

/// Every UFCS call site's verdict for one project.
pub type UfcsTable = SideTable<UfcsVerdict>;

/// Translate a [`UfcsTable`] into `brink-ir`'s own lowering-facing mirror
/// (`brink_ir::lir::UfcsLookup`/`UfcsVerdict`) — issue #1506's one
/// conversion point, so the `UfcsVerdict` → `brink_ir::lir::UfcsVerdict`
/// mapping lives in exactly one place rather than once per caller.
/// `brink-ir` sits below this crate in the crate graph (this crate depends
/// on `brink-ir`, never the reverse), so it cannot provide this itself —
/// see `brink_ir::lir::UfcsVerdict`'s own doc. Every LIR-lowering caller
/// shares this: `brink-db`'s `ufcs_resolution_query` (the production path)
/// and [`assemble_analyzer_tables`](crate::assemble_analyzer_tables) — the
/// salsa-free path used by `brink-test-harness`
/// (`corpus::compile_and_explore_from_brink_native`) and any other caller
/// with no salsa layer of its own to memoize the table in.
#[must_use]
pub fn to_lir_lookup(table: &UfcsTable) -> brink_ir::lir::UfcsLookup {
    let entries = table
        .iter()
        .map(|(key, verdict)| {
            let range = TextRange::new(key.range.0.into(), key.range.1.into());
            let mirrored = match verdict {
                UfcsVerdict::FieldCall { .. } => brink_ir::lir::UfcsVerdict::FieldCall,
                UfcsVerdict::FreeFnAutoRef { target, .. } => {
                    brink_ir::lir::UfcsVerdict::FreeFnAutoRef { target: *target }
                }
                UfcsVerdict::FreeFnDesugar { target, .. } => {
                    brink_ir::lir::UfcsVerdict::FreeFnDesugar { target: *target }
                }
                UfcsVerdict::PreludeDesugar { name, .. } => {
                    brink_ir::lir::UfcsVerdict::PreludeDesugar { name: name.clone() }
                }
            };
            (key.file, range, mirrored)
        })
        .collect();
    brink_ir::lir::UfcsLookup::from_entries(entries)
}

// ─── The pass ────────────────────────────────────────────────────────

/// Resolve every UFCS-shaped call in the project, returning the verdict
/// side table plus the diagnostics the four outcomes above produce.
///
/// `inference` supplies the receiver types (the pass is type-directed by
/// construction); `resolutions` identifies which dotted callee paths are
/// UFCS-shaped at all — a path already resolving to a knot/stitch/external
/// is an ordinary qualified call and is left completely alone.
///
/// Callers gate this on [`project_has_ufcs_call`] so a project without a
/// single dotted-callee call never pays for whole-project inference on this
/// pass's account.
///
/// **Issue #2096** (the `ufcs.rs` half of #1774's re-verification
/// remainder — `comparator_contract.rs`'s own copy of the same gap was
/// fixed by #2085): this used to drive [`UfcsVisitor`] with plain
/// [`visit::visit`], which never reaches a file-level `VAR`/`CONST`
/// initializer — so a UFCS-shaped call inside a decl-default lambda's own
/// body (`const callGreet = |g| g.greet(3)`, legal since #1774's ruling)
/// was never visited by this pass at all, and fell through to LIR
/// lowering's defensive `E144` fallback (`brink_ir::lir::lower::expr`'s own
/// doc). **The shared-visitor question (issue #1571/#2098), re-asked for
/// this pass's own shape**: unlike `comparator_contract`'s hand-rolled
/// `collect_sites`/`collect_expr` walk (which is not `HirVisitor`-driven at
/// all, and so could not adopt the shared entry point without a larger
/// refactor), [`UfcsVisitor`] already *is* a [`HirVisitor`] driven by
/// `visit::visit` — the exact shape [`visit::visit_with_decl_initializers`]
/// was built to extend. Switching costs one line and needs no new
/// `enter_var_decl`/`enter_const_decl` hooks: `current_knot_name`/
/// `knot_body`/`stitch_body` are already reset to `None` by every
/// `exit_knot`/`exit_stitch`, and `lambda_locals` is empty once every lambda
/// pushed during the block-tree walk has been popped — so by the time the
/// walk reaches the file-level declarations (which
/// `visit_with_decl_initializers` visits *after* the block tree), this
/// visitor's state is already exactly what it was before any knot ran, the
/// same "no state needs resetting" case `structs::check`'s own #2098 switch
/// documents. See `structs::check`'s identical switch for the precedent.
#[must_use]
pub fn resolve(
    files: &[(FileId, &HirFile)],
    index: &SymbolIndex,
    resolutions: &ResolutionMap,
    inference: &InferenceResult,
) -> (UfcsTable, Vec<Diagnostic>) {
    let shapes = declared_shapes(files, index);
    let globals = crate::infer::collect_globals(files, index, None);
    let mut table = UfcsTable::new();
    let mut diagnostics = Vec::new();

    for &(file, hir) in files {
        let resolution_by_range = resolution_index(resolutions, file);
        let scope = ImportScope::new(hir.module.as_ref().map(|m| m.name.clone()), &hir.imports);
        let mut v = UfcsVisitor {
            file,
            index,
            scope: &scope,
            shapes: &shapes,
            globals: &globals,
            bodies: &inference.bodies,
            signatures: &inference.signatures,
            resolution_by_range: &resolution_by_range,
            current_knot_name: None,
            knot_body: None,
            stitch_body: None,
            lambda_locals: Vec::new(),
            table: &mut table,
            diagnostics: &mut diagnostics,
        };
        visit::visit_with_decl_initializers(hir, &mut v);
    }

    (table, diagnostics)
}

/// The **strict-mode-only** diagnostics that fall out of the verdict table:
///
/// - Issue #1540 (second symptom): a typed check keyed on an intrinsic's
///   receiver must see the UFCS spelling of that intrinsic too.
///
///   `infer::body::infer_call` deliberately branches away for a
///   multi-segment callee *before* `infer_intrinsic` runs (a UFCS receiver
///   is not the thing being called, so classifying it as a
///   call-through-a-value would be a false `E066` on every legal method
///   call — see that function's own note). Issue #1909 later gave that
///   branch a result type for the *free-function* desugar
///   (`infer::body::InferPass::infer_ufcs_free_fn_result`), but
///   deliberately not for a prelude verb, precisely because routing one
///   through `infer_intrinsic` would record the `array_remove_calls` fact
///   below a second time and double-report this very `E149`. The
///   consequence stands: `arr.remove(0)` records none of the facts
///   `remove(arr, 0)` records, so
///   every intrinsic-receiver diagnostic silently stopped at the free-call
///   spelling. This pass is where the UFCS spelling gets them back: the
///   verdict table already carries the receiver's resolved `Ty` next to the
///   verb's name, which is exactly the `(receiver type, verb)` pair those
///   checks key on — no second inference, and no `TypePolicy` threaded into
///   [`resolve`] (which stays policy-independent, as LIR lowering and the
///   IDE need it to be).
///
/// - Issue #1881: a `FreeFnDesugar`/`FreeFnAutoRef` verdict's own
///   `arg_mismatches` (computed unconditionally alongside the verdict by
///   [`UfcsVisitor::try_free_fn_desugar`]) — the UFCS sibling of
///   `strict::check_direct_call_args` (#1864/PR #1875) and
///   `strict::check_typed_assign_mismatches` (#1877/PR #1899): a UFCS
///   receiver resolves to a *value*, so `InferenceResult::signatures` has
///   no entry for it the way a direct call's callee does, which is exactly
///   why this class of mismatch couldn't be checked by extending either of
///   those two passes — the resolved free-function *target*'s signature is
///   only ever available here, where this pass has already resolved it.
///
/// - Issue #1919: a `PreludeDesugar` verdict's own `arg_mismatches`
///   ([`UfcsVisitor::check_ufcs_prelude_arg_types`]) — the prelude sibling
///   of the `FreeFnDesugar` bullet above, for the collection verbs whose
///   domain is a plain container projection (`xs.push(v)`, `m.get(k)`, and
///   the rest of that family). `remove`'s array leg stays the hand-written
///   `E149` check just below rather than folding into this fact: the two
///   are disjoint diagnostic families keyed on the same `(receiver, name)`
///   pair, not a double-report risk.
///
/// - Issue #1918: a `FieldCall` verdict's own `arity_mismatch`/
///   `arg_mismatches` ([`UfcsVisitor::check_field_call_args`]) — left
///   uncovered by #1881/PR #1914, which deliberately scoped to the
///   `FreeFnDesugar`/`FreeFnAutoRef` bullet above and flagged this gap in
///   review rather than filing it (issue comment on #1881). Structurally
///   `strict::check_value_calls`'s T1c "call through a function value"
///   domain, reached via field access instead of a bare name — a call
///   through the field's `Ty::Fn` value directly, with no receiver-
///   prepending desugar, so it gets its own arity fact
///   ([`UfcsArityMismatch`]) rather than folding into a per-argument
///   `UfcsArgMismatch` at index `0`.
///
/// Strict-mode-only **by convention, not by construction**, exactly like
/// `coalesce::resolve`'s `E066` half: production reaches this only from
/// `strict::check`, after `strict::config_error` has confirmed
/// `types = strict` + `dialect = brink`. A caller that surfaces these
/// without that gate would emit strict-only codes under `types = gradual`.
///
/// Gated on [`project_has_ufcs_call`] internally so a project with no
/// dotted-callee call anywhere pays nothing — the same laziness
/// `whole_project_diagnostics` applies to [`resolve`]'s own diagnostics.
#[must_use]
pub fn check_strict(
    files: &[(FileId, &HirFile)],
    index: &SymbolIndex,
    resolutions: &ResolutionMap,
    inference: &InferenceResult,
) -> Vec<Diagnostic> {
    if !files.iter().any(|&(_, hir)| project_has_ufcs_call(hir)) {
        return Vec::new();
    }
    // The unconditional `E140`–`E144` half is discarded here: it is already
    // reported by `whole_project_diagnostics`' own call to `resolve`, and
    // double-reporting it under strict would be a regression.
    let (table, _unconditional) = resolve(files, index, resolutions, inference);
    table
        .iter()
        .flat_map(|(key, verdict)| strict_verdict_diagnostics(key, verdict))
        .collect()
}

/// One verdict's strict-mode diagnostics, if it has any.
///
/// `E149` (issue #1540) — `remove` went map-only in issue #1484 with no
/// compatibility shim, so an array receiver means the site wants
/// `remove_at`. The free-call spelling of this exact check lives in
/// `strict::check_array_remove_calls`, reading the fact
/// `infer::body`'s `remove` arm records; the two spellings must agree, so
/// the receiver test here (`Ty::Array`) is deliberately the same one.
///
/// `E063` (issue #1881, widened to `PreludeDesugar` by issue #1919, and to
/// `FieldCall` by issue #1918) — every recorded [`UfcsArgMismatch`] on a
/// `FreeFnDesugar`/`FreeFnAutoRef`/`PreludeDesugar`/`FieldCall` verdict,
/// reported the same way `strict::check_direct_call_args` reports
/// `DirectCallArgMismatch` — plus, for `FieldCall` alone, its own
/// [`UfcsArityMismatch`] (that verdict has no receiver-prepending desugar to
/// fold an arity fact into `UfcsArgMismatch`'s index-`0` slot the way the
/// other three verdicts do), phrased identically to
/// `strict::check_value_calls`'s own `ValueCallKind::ArityMismatch` — the
/// T1c "call through a value" domain this verdict structurally is.
///
/// Every future collection-typed check that keys on `(receiver type, verb)`
/// belongs in this match rather than in a parallel walk — that is the point
/// of routing through the verdict table at all.
fn strict_verdict_diagnostics(key: NodeKey, verdict: &UfcsVerdict) -> Vec<Diagnostic> {
    match verdict {
        UfcsVerdict::PreludeDesugar {
            receiver,
            name,
            arg_mismatches,
        } => {
            let mut out: Vec<Diagnostic> = arg_mismatches
                .iter()
                .map(|mismatch| ufcs_arg_mismatch_diagnostic(key, name, mismatch))
                .collect();
            if let ("remove", Ty::Array(_)) = (name.as_str(), receiver) {
                out.push(Diagnostic {
                    file: key.file,
                    range: TextRange::new(key.range.0.into(), key.range.1.into()),
                    message: DiagnosticCode::E149.title().to_owned(),
                    code: DiagnosticCode::E149,
                });
            }
            out
        }
        UfcsVerdict::FreeFnDesugar {
            name,
            arg_mismatches,
            ..
        }
        | UfcsVerdict::FreeFnAutoRef {
            name,
            arg_mismatches,
            ..
        } => arg_mismatches
            .iter()
            .map(|mismatch| ufcs_arg_mismatch_diagnostic(key, name, mismatch))
            .collect(),
        UfcsVerdict::FieldCall {
            field,
            arity_mismatch,
            arg_mismatches,
            ..
        } => {
            let mut out: Vec<Diagnostic> = Vec::new();
            if let Some(arity) = arity_mismatch {
                out.push(field_call_arity_diagnostic(key, field, *arity));
            }
            out.extend(
                arg_mismatches
                    .iter()
                    .map(|mismatch| field_call_arg_mismatch_diagnostic(key, field, mismatch)),
            );
            out
        }
    }
}

/// A [`UfcsVerdict::FieldCall`]'s own [`UfcsArgMismatch`] as a diagnostic
/// — issue #1918. Like [`field_call_arity_diagnostic`] just below, the
/// wording matches `strict::check_value_calls`'s own
/// `ValueCallKind::ArgMismatch` phrasing exactly ("call **through**", the
/// T1c domain this verdict structurally is) — deliberately NOT
/// [`ufcs_arg_mismatch_diagnostic`]'s desugared-call "call to" phrasing,
/// so both halves of a `FieldCall` verdict (arity and argument type) speak
/// with one voice. `mismatch.index` here is 0-based over the *written*
/// arguments (no receiver prepend — see [`UfcsArgMismatch::index`]'s
/// Exception paragraph), so `+ 1` yields the same 1-based "argument N"
/// numbering `check_value_calls` reports.
fn field_call_arg_mismatch_diagnostic(
    key: NodeKey,
    field: &str,
    mismatch: &UfcsArgMismatch,
) -> Diagnostic {
    Diagnostic {
        file: key.file,
        range: TextRange::new(key.range.0.into(), key.range.1.into()),
        message: format!(
            "argument {} of call through `{field}` has type `{}` but its known type expects `{}`",
            mismatch.index + 1,
            mismatch.found.display(),
            mismatch.expected.display(),
        ),
        code: DiagnosticCode::E063,
    }
}

/// A [`UfcsVerdict::FieldCall`]'s own [`UfcsArityMismatch`] as a diagnostic
/// — issue #1918. The message wording matches
/// `strict::check_value_calls`'s own `ValueCallKind::ArityMismatch`
/// phrasing exactly (the T1c "call through a value" sibling this verdict
/// structurally is), naming the field rather than a bare callee name.
fn field_call_arity_diagnostic(
    key: NodeKey,
    field: &str,
    mismatch: UfcsArityMismatch,
) -> Diagnostic {
    Diagnostic {
        file: key.file,
        range: TextRange::new(key.range.0.into(), key.range.1.into()),
        message: format!(
            "call through `{field}` supplies {got} argument(s) but its known type expects \
             {expected}",
            got = mismatch.got,
            expected = mismatch.expected,
        ),
        code: DiagnosticCode::E063,
    }
}

/// One [`UfcsArgMismatch`] as a diagnostic — the message wording matches
/// `strict::check_direct_call_args`'s own `E063` phrasing exactly (the
/// direct-call sibling this parallels), just against the *desugared* call's
/// own argument numbering (`index` `0` is the receiver).
fn ufcs_arg_mismatch_diagnostic(
    key: NodeKey,
    name: &str,
    mismatch: &UfcsArgMismatch,
) -> Diagnostic {
    Diagnostic {
        file: key.file,
        range: TextRange::new(key.range.0.into(), key.range.1.into()),
        message: format!(
            "argument {} of call to `{name}` has type `{}` but its known type expects `{}`",
            mismatch.index + 1,
            mismatch.found.display(),
            mismatch.expected.display(),
        ),
        code: DiagnosticCode::E063,
    }
}

/// Cheap structural scan: does any call in `hir` have a multi-segment
/// callee path? The laziness gate for [`resolve`]'s caller — a project
/// (every ink project, by construction; see the module doc) with no
/// dotted-callee call never triggers whole-project inference on this pass's
/// account, mirroring `whole_project_diagnostics`' own `needs_effects`
/// gate.
///
/// Issue #2096: must see a decl-default lambda's own body too, or the
/// laziness gate itself would skip [`resolve`] entirely for a project whose
/// only UFCS-shaped call sits inside one — the exact fix [`resolve`]'s own
/// walk just got would never run. `visit::visit_with_decl_initializers`
/// (not plain `visit::visit`), same reasoning as that doc.
#[must_use]
pub fn project_has_ufcs_call(hir: &HirFile) -> bool {
    struct Scan {
        found: bool,
    }
    impl HirVisitor for Scan {
        fn visit_exprs(&self) -> bool {
            true
        }
        fn enter_expr(&mut self, expr: &Expr) {
            if let Expr::Call(path, _) = expr
                && path.segments.len() > 1
            {
                self.found = true;
            }
        }
    }
    let mut scan = Scan { found: false };
    visit::visit_with_decl_initializers(hir, &mut scan);
    scan.found
}

/// This file's own reference resolutions, projected to a range-keyed lookup
/// — mirrors `structs::resolution_index` (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| ((r.range.start().into(), r.range.end().into()), r.target))
        .collect()
}

/// Walks one file's knot/stitch bodies, tracking the enclosing def's
/// finalized locals so a receiver's head segment can be typed. Structurally
/// a twin of `structs::ConstructionVisitor` — same `enter_knot`/
/// `enter_stitch` locals bookkeeping, for the same reason (`BodyTypes` is
/// keyed by def, `locals` by name).
struct UfcsVisitor<'a> {
    file: FileId,
    index: &'a SymbolIndex,
    scope: &'a ImportScope,
    shapes: &'a ShapeTable,
    globals: &'a BTreeMap<DefinitionId, Ty>,
    bodies: &'a BTreeMap<DefinitionId, crate::infer::BodyTypes>,
    /// Every inferable def's finalized signature (issue #1881) — the UFCS
    /// desugar's *target* (a knot/stitch, never the receiver) has its
    /// declared param types here, the same firewall-facing projection a
    /// direct call's `known_sigs` lookup reads. See
    /// [`UfcsVisitor::try_free_fn_desugar`]'s own argument-type check.
    signatures: &'a BTreeMap<DefinitionId, InferredSig>,
    resolution_by_range: &'a BTreeMap<(u32, u32), DefinitionId>,
    current_knot_name: Option<String>,
    /// The enclosing knot's own `BodyTypes` (issue #1881 widened this from
    /// `locals` alone to the whole `BodyTypes`, so [`Self::current_body`]
    /// can also read back the enclosing def's own recorded
    /// `ufcs_call_args` — see [`Self::current_locals`] for the `locals`
    /// projection every earlier call site still wants).
    knot_body: Option<&'a crate::infer::BodyTypes>,
    stitch_body: Option<&'a crate::infer::BodyTypes>,
    /// Issue #2773: a stack of pruned-locals frames, one per currently-open
    /// lambda literal (innermost last). Mirrors
    /// `structs::ConstructionVisitor`'s identical field/hook pair exactly —
    /// see that field's own doc. Composes with the same
    /// `structs::pruned_locals_for_lambda` helper even though this visitor
    /// has no `MistypeCtx` of its own — the helper takes the raw
    /// `index`/`outer_locals` pair, not a `MistypeCtx`, for exactly this
    /// reason.
    lambda_locals: Vec<BTreeMap<String, Ty>>,
    table: &'a mut UfcsTable,
    diagnostics: &'a mut Vec<Diagnostic>,
}

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

    fn enter_knot(&mut self, knot: &Knot) {
        self.current_knot_name = Some(knot.name.text.clone());
        self.knot_body =
            annotations::def_id_for(self.index, self.file, knot.symbol_kind(), &knot.name.text)
                .and_then(|id| self.bodies.get(&id));
    }

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

    fn enter_stitch(&mut self, stitch: &Stitch) {
        self.stitch_body = 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))
        });
    }

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

    fn enter_expr(&mut self, expr: &Expr) {
        if let Expr::Call(path, args) = expr {
            self.resolve_call(path, args.len());
        }
    }

    fn enter_lambda(&mut self, l: &brink_ir::LambdaExpr) {
        let pruned = crate::structs::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();
    }
}

/// The receiver half of one UFCS call site, resolved: everything the two
/// resolution steps and D5's auto-ref gate need to know about `recv` in
/// `recv.name(args)`.
struct Receiver<'a> {
    /// The definition the head segment resolved to (a param/temp/`VAR`/
    /// `CONST` — [`UfcsVisitor::value_receiver_def`]).
    def: DefinitionId,
    /// Every segment before the final pre-`(` one, head first.
    segments: &'a [brink_ir::Name],
    /// The receiver as written (`party.members`), for diagnostics.
    text: String,
    /// The receiver's inferred type ([`UfcsVisitor::receiver_ty`]) — never
    /// `Unknown`/`Conflicted`, which is `E142` one step earlier.
    ty: Ty,
}

impl UfcsVisitor<'_> {
    /// The innermost enclosing def's own `BodyTypes` — a stitch's own body
    /// wins over its enclosing knot's, exactly like [`Self::current_locals`]
    /// already preferred.
    fn current_body(&self) -> Option<&crate::infer::BodyTypes> {
        self.stitch_body.or(self.knot_body)
    }

    fn current_locals(&self) -> Option<&BTreeMap<String, Ty>> {
        self.lambda_locals
            .last()
            .or_else(|| self.current_body().map(|b| &b.locals))
    }

    /// The single call-site decision. Returns without touching the table or
    /// the diagnostics for any call that is not UFCS-shaped.
    fn resolve_call(&mut self, path: &HirPath, arg_count: usize) {
        let Some((method, receiver_segs)) = path.segments.split_last() else {
            return;
        };
        if receiver_segs.is_empty() {
            // A bare `name(args)` — ordinary direct call, never UFCS.
            return;
        }
        let Some(head_def) = self.value_receiver_def(path) else {
            // The callee path resolves to a real callable (a
            // module-qualified free call, an ink `knot.stitch()` visit) —
            // an ordinary qualified call, not method-call syntax.
            return;
        };

        let receiver_text = receiver_segs
            .iter()
            .map(|s| s.text.as_str())
            .collect::<Vec<_>>()
            .join(".");

        let Some(receiver_ty) = self.receiver_ty(head_def, receiver_segs) else {
            // D3: no deferral machinery — demand an annotation.
            self.push(
                path.range,
                DiagnosticCode::E142,
                &format!(
                    "cannot resolve `{receiver_text}.{method}(…)`: the type of `{receiver_text}` \
                     is not known here, so it is undecidable whether `{method}` is one of its \
                     fields — annotate the receiver",
                    method = method.text,
                ),
            );
            return;
        };

        let receiver = Receiver {
            def: head_def,
            segments: receiver_segs,
            text: receiver_text,
            ty: receiver_ty,
        };

        // Step 2 — field access wins outright (D1).
        if self.try_field_call(path, method, &receiver, arg_count) {
            return;
        }

        // Step 3 — a free function in ordinary lexical scope (D4), by value
        // or auto-ref'd (D5).
        if self.try_free_fn_desugar(path, method, &receiver, arg_count) {
            return;
        }

        // Step 4 — neither; one diagnostic naming both attempts.
        self.push(
            path.range,
            DiagnosticCode::E141,
            &format!(
                "cannot resolve `{receiver_text}.{method}(…)`: `{recv_ty}` declares no field \
                 `{method}`, and no function `{method}` is in scope here",
                method = method.text,
                receiver_text = receiver.text,
                recv_ty = receiver.ty.display(),
            ),
        );
    }

    /// Step 2 (D1). Returns `true` when the receiver's type declares a field
    /// of the called name — the call is settled either way, as a
    /// [`UfcsVerdict::FieldCall`] or as the `E140` hard error, and never
    /// falls through to step 3.
    fn try_field_call(
        &mut self,
        path: &HirPath,
        method: &brink_ir::Name,
        receiver: &Receiver<'_>,
        arg_count: usize,
    ) -> bool {
        let receiver_ty = &receiver.ty;
        let receiver_text = &receiver.text;
        let Ty::Struct(shape_name) = receiver_ty else {
            return false;
        };
        let Some(field_ty) = self
            .shapes
            .resolve(shape_name, self.scope, self.index)
            .and_then(|shape| shape.field_ty(&method.text))
        else {
            return false;
        };
        if matches!(field_ty, Ty::Fn(..)) {
            // Issue #1918: this verdict's own argument checking — computed
            // here (unconditionally, like every other verdict's own
            // arg-check fields) and carried on the verdict for
            // `check_strict` to report as `E063`. See
            // `Self::check_field_call_args`'s own doc.
            let (arity_mismatch, arg_mismatches) =
                self.check_field_call_args(path.range, field_ty, arg_count);
            let verdict = UfcsVerdict::FieldCall {
                receiver: receiver_ty.clone(),
                field: method.text.clone(),
                field_ty: field_ty.clone(),
                arity_mismatch,
                arg_mismatches,
            };
            self.table
                .insert(NodeKey::new(self.file, path.range), verdict);
        } else {
            let message = format!(
                "field `{field}` on `{shape_name}` is not callable (its type is `{found}`) — \
                 field access wins over a free function of the same name, so this is never \
                 re-read as `{field}({receiver_text}, …)`",
                field = method.text,
                found = field_ty.display(),
            );
            self.push(path.range, DiagnosticCode::E140, &message);
        }
        true
    }

    /// Step 3 (D4/D5). Returns `true` when a free function of the called
    /// name is in ordinary lexical scope, or the name is a T1b/NS stdlib
    /// prelude verb (D4's candidate set is "ordinary lexical scope only
    /// (file `use` + prelude)" — `resolve::is_t1b_stdlib_name`/
    /// `resolve::is_builtin_function`, e.g. `len`/`push`/`sort_by`, are not
    /// index symbols and would otherwise fall through to the `E141` "no
    /// function in scope" diagnostic, which is false: `push(xs, v)` compiles
    /// today).
    ///
    /// **D5** picks the desugar's shape from the target's *first declared
    /// parameter*: `ref` → [`UfcsVerdict::FreeFnAutoRef`] (the receiver is
    /// passed by reference, provided it can be written through — otherwise
    /// `E143`, see [`Self::auto_ref_fault`]); anything else → the plain
    /// by-value [`UfcsVerdict::FreeFnDesugar`], with no lvalue requirement on
    /// the receiver at all. The prelude verbs have no user-declared params to
    /// read, so they are always the by-value shape here — the collection
    /// mutators' own lvalue discipline is LIR lowering's ruled RMW expansion
    /// (`brink_ir::lir::lower::blocks::try_lower_mutator_stmt`), unchanged.
    fn try_free_fn_desugar(
        &mut self,
        path: &HirPath,
        method: &brink_ir::Name,
        receiver: &Receiver<'_>,
        arg_count: usize,
    ) -> bool {
        let Some(target) = crate::resolve::lookup_by_name(
            self.index,
            self.scope,
            &method.text,
            &[SymbolKind::Knot, SymbolKind::External],
        ) else {
            // No index symbol of this name — the T1b/NS stdlib prelude is
            // the other half of D4's candidate set. It has no `DefinitionId`
            // (VM-native, resolved at LIR lowering) and so no arity to check
            // here.
            if crate::resolve::is_t1b_stdlib_name(&method.text)
                || crate::resolve::is_builtin_function(&method.text)
            {
                // Issue #1919: the prelude sibling of the `arg_mismatches`
                // computed below for the free-fn desugar — see
                // `check_ufcs_prelude_arg_types`'s own doc for why this is
                // safe to compute here (D1's field-access-wins check has
                // already run by the time this verdict is reached) and why
                // it cannot double-report `E149` (a disjoint diagnostic
                // family from the domain mismatches this checks).
                let arg_mismatches =
                    self.check_ufcs_prelude_arg_types(path.range, &receiver.ty, &method.text);
                let verdict = UfcsVerdict::PreludeDesugar {
                    receiver: receiver.ty.clone(),
                    name: method.text.clone(),
                    arg_mismatches,
                };
                self.table
                    .insert(NodeKey::new(self.file, path.range), verdict);
                return true;
            }
            return false;
        };
        let first_param_is_ref = self
            .index
            .symbols
            .get(&target)
            .and_then(|info| info.params.first())
            .is_some_and(|p| p.is_ref);
        if first_param_is_ref && let Some(cause) = self.auto_ref_fault(receiver) {
            let message = format!(
                "cannot mutate `{receiver_text}` through `{name}`: `{name}`'s first parameter is \
                 `ref`, so `{receiver_text}.{name}(…)` auto-refs its receiver (D5) — but {cause}. \
                 Bind the receiver to a durable cell, or call a by-value function on it",
                name = method.text,
                receiver_text = receiver.text,
            );
            self.push(path.range, DiagnosticCode::E143, &message);
            return true;
        }
        // Every other resolved call gets an arity check (`resolve::
        // check_arity`) before it is declared resolved; this desugar owes
        // the same — the receiver counts as the first argument.
        let expected = self
            .index
            .symbols
            .get(&target)
            .map(|info| info.params.len());
        let actual = arg_count + 1;
        if let Some(expected) = expected
            && expected != actual
        {
            let message = format!(
                "`{name}` expects {expected} argument(s), got {actual} \
                 (`{receiver_text}.{name}(…)` desugars to `{name}({receiver_text}, …)`, counting \
                 the receiver as the first argument)",
                name = method.text,
                receiver_text = receiver.text,
            );
            self.push(path.range, DiagnosticCode::E031, &message);
        }
        // Issue #1881: the argument-type half of this call site's check —
        // computed here (unconditionally, like everything else in this
        // resolution pass) and carried on the verdict for `check_strict` to
        // report as `E063`.
        let arg_mismatches = self.check_ufcs_arg_types(path.range, target, receiver);
        let verdict = if first_param_is_ref {
            UfcsVerdict::FreeFnAutoRef {
                receiver: receiver.ty.clone(),
                name: method.text.clone(),
                target,
                arg_mismatches,
            }
        } else {
            UfcsVerdict::FreeFnDesugar {
                receiver: receiver.ty.clone(),
                name: method.text.clone(),
                target,
                arg_mismatches,
            }
        };
        self.table
            .insert(NodeKey::new(self.file, path.range), verdict);
        true
    }

    /// Issue #1881: the desugared call's argument-type check — `target`'s
    /// already-known declared param types (`self.signatures`, this pass's
    /// own `InferenceResult::signatures` projection) against the receiver
    /// (param `0`) and every *written* argument (param `1..`, read back
    /// from `infer::body`'s own recorded [`super::UfcsCallArgs`] fact for
    /// this exact call-site `range` — this pass has no expression-type
    /// inference of its own, see that struct's own doc for why the split
    /// lives here).
    ///
    /// Mirrors `infer::body::InferPass::infer_call`'s own direct-call check
    /// (`assignable`, skipping whenever either side is `Unknown`/
    /// `Conflicted`) with one simplification: unlike a direct call's
    /// argument, nothing in `infer::body`'s own walk ever `observe`s a
    /// UFCS receiver or written argument against `target`'s declared param
    /// type — the multi-segment branch in `infer_call` runs no `observe`
    /// call at all (issue #1909's `infer_ufcs_free_fn_result` gave that
    /// branch a *result type*, deliberately read-only in the receiver and
    /// silent on the arguments, exactly so this stays true). So there
    /// is no `arg_is_observed_local`-style double-report risk against
    /// `E066` to guard against here, unlike `DirectCallArgMismatch`'s own
    /// exclusion.
    ///
    /// **The D5 auto-ref interaction** (both call sites — `first_param_is_ref`
    /// or not — share this one check): a `ref` first param's entry in
    /// `self.signatures` is *not* a special "reference" `Ty` — `InferredSig`
    /// carries no such variant. `body::infer_def_body` derives every
    /// param's row (`ref` included) from `pass.locals`, the type the body
    /// itself observed that parameter holding — i.e. the **referent's**
    /// own type, exactly what `receiver.ty` (a value type, never wrapped)
    /// already is. So comparing `receiver.ty` against `sig.params[0]` with
    /// the same plain `assignable` this whole function otherwise uses is
    /// correct for `FreeFnAutoRef` too, not just `FreeFnDesugar` — no
    /// auto-ref-specific unwrapping needed, and none of the false positives
    /// #1895 shipped by assuming a receiver's call-site type must literally
    /// equal a param's declared spelling.
    fn check_ufcs_arg_types(
        &self,
        range: TextRange,
        target: DefinitionId,
        receiver: &Receiver<'_>,
    ) -> Vec<UfcsArgMismatch> {
        let Some(sig) = self.signatures.get(&target) else {
            return Vec::new();
        };
        let empty: Vec<Ty> = Vec::new();
        let written: &[Ty] = self
            .current_body()
            .and_then(|b| b.ufcs_call_args.iter().find(|f| f.range == range))
            .map_or(empty.as_slice(), |f| f.args.as_slice());
        // Issue #1995/#1920: which positions are declared `ref` lives on
        // the symbol index's own `params` — `InferredSig` (`sig`, above)
        // carries no `is_ref` bit, exactly like the direct-call sibling in
        // `infer::body::InferPass::infer_call`.
        let ref_positions = self.index.symbols.get(&target);
        let is_ref_param = |i: usize| {
            ref_positions
                .and_then(|info| info.params.get(i))
                .is_some_and(|p| p.is_ref)
        };

        let mut mismatches = Vec::new();
        // Index 0: the receiver itself — `name(recv, args)`'s first
        // positional slot, same "receiver counts as the first argument"
        // convention this call site's own arity-mismatch diagnostic uses.
        // D5's auto-ref desugar makes this slot `ref` whenever
        // `first_param_is_ref` selected `FreeFnAutoRef` — the exact write-
        // back-through-the-caller's-cell case the invariant check exists
        // for.
        if let Some(param_ty) = sig.params.first()
            && !param_ty.is_unresolved()
            && if is_ref_param(0) {
                !ref_assignable(param_ty, &receiver.ty)
            } else {
                !assignable(param_ty, &receiver.ty)
            }
        {
            mismatches.push(UfcsArgMismatch {
                index: 0,
                expected: param_ty.clone(),
                found: receiver.ty.clone(),
            });
        }
        for (i, arg_ty) in written.iter().enumerate() {
            if arg_ty.is_unresolved() {
                continue;
            }
            let Some(param_ty) = sig.params.get(i + 1) else {
                continue;
            };
            let ty_disagrees = if is_ref_param(i + 1) {
                !ref_assignable(param_ty, arg_ty)
            } else {
                !assignable(param_ty, arg_ty)
            };
            if !param_ty.is_unresolved() && ty_disagrees {
                mismatches.push(UfcsArgMismatch {
                    index: i + 1,
                    expected: param_ty.clone(),
                    found: arg_ty.clone(),
                });
            }
        }
        mismatches
    }

    /// Issue #1919: `PreludeDesugar`'s own argument-domain check — the T1b/
    /// NS-A1 stdlib-verb sibling of [`Self::check_ufcs_arg_types`] (issue
    /// #1881, `FreeFnDesugar`/`FreeFnAutoRef`). A prelude verb has no
    /// [`DefinitionId`] and no declared parameter list
    /// ([`UfcsVerdict::PreludeDesugar`]'s own doc) — its "signature" instead
    /// lives as `infer::body::InferPass::infer_intrinsic`'s own per-verb
    /// domain rules, keyed off the receiver's *inferred container type*
    /// (an array's element type, a map's key/value types).
    ///
    /// This mirrors that domain knowledge declaratively, for the verbs
    /// whose domain is a plain container projection, rather than calling
    /// `infer_intrinsic` itself: that method needs a live `Expr` for its
    /// receiver-write arms (`push`/`insert`/… call
    /// `record_write(args.first())`, resolving an `Expr::Path` back through
    /// the `ResolutionMap` — keyed at the *whole call's* own range, so a
    /// synthetic receiver-only `Expr` would resolve to nothing there) and
    /// mutates the body-inference walk's own `self.locals`/
    /// `self.array_remove_calls` state, neither of which this post-hoc,
    /// already-fully-resolved verdict pass has access to (see
    /// `check_strict`'s own module doc for why the `E149` half stays a
    /// hand-written twin rather than an `infer_intrinsic` call, for the
    /// same reason).
    ///
    /// Unlike [`infer::body::InferPass::infer_ufcs_free_fn_result`]
    /// (issue #1909), which has to decline a `Ty::Struct` receiver because
    /// D1's field-access-wins rule has not run yet at body-inference time,
    /// this check runs no such risk: [`Self::resolve_call`] always tries
    /// [`Self::try_field_call`] (D1) before [`Self::try_free_fn_desugar`]
    /// (D3/D4), so a `PreludeDesugar` verdict is only ever constructed once
    /// field access has already lost.
    ///
    /// `remove`'s *array* leg is deliberately excluded from the domain
    /// table below: that shape is `E149` (issue #1540), already reported
    /// unconditionally for this exact verdict by
    /// [`strict_verdict_diagnostics`] — a disjoint diagnostic family from
    /// the domain mismatches this method reports, so there is no risk of
    /// double-reporting between the two.
    fn check_ufcs_prelude_arg_types(
        &self,
        range: TextRange,
        receiver: &Ty,
        name: &str,
    ) -> Vec<UfcsArgMismatch> {
        let expected: Vec<Ty> = match (name, receiver) {
            ("push" | "heap_push" | "index_of" | "contains", Ty::Array(elem)) => {
                vec![(**elem).clone()]
            }
            ("contains" | "get" | "remove", Ty::Map(k, _)) => vec![(**k).clone()],
            ("contains_value", Ty::Map(_, v)) => vec![(**v).clone()],
            ("insert", Ty::Map(k, v)) => vec![(**k).clone(), (**v).clone()],
            _ => return Vec::new(),
        };
        let empty: Vec<Ty> = Vec::new();
        let written: &[Ty] = self
            .current_body()
            .and_then(|b| b.ufcs_call_args.iter().find(|f| f.range == range))
            .map_or(empty.as_slice(), |f| f.args.as_slice());

        let mut mismatches = Vec::new();
        for (i, expected_ty) in expected.iter().enumerate() {
            let Some(arg_ty) = written.get(i) else {
                continue;
            };
            if arg_ty.is_unresolved() {
                continue;
            }
            if !assignable(expected_ty, arg_ty) {
                mismatches.push(UfcsArgMismatch {
                    index: i + 1,
                    expected: expected_ty.clone(),
                    found: arg_ty.clone(),
                });
            }
        }
        mismatches
    }

    /// Issue #1918: `FieldCall`'s own argument checking — structurally
    /// `strict::check_value_calls`'s T1c "call through a function value"
    /// domain (the issue's own framing: `recv.name(args)` resolving through
    /// a struct's fn-typed field *is* a call through a value, just reached
    /// via field access instead of a bare name), reached here rather than
    /// through that pass because a UFCS receiver is deliberately invisible
    /// to `infer::body::infer_call`'s own T1c branch (see
    /// [`Self::check_ufcs_arg_types`]'s own doc for why — the same reason
    /// applies here) — this pass has already resolved the field's own
    /// `Ty::Fn` row by the time a `FieldCall` verdict is being built, which
    /// `infer::body` never does for a multi-segment callee.
    ///
    /// **No receiver-prepending desugar, unlike [`Self::check_ufcs_arg_types`]
    /// (`FreeFnDesugar`/`FreeFnAutoRef`).** Those two desugar
    /// `recv.name(args)` into `name(recv, args)`, so the receiver becomes
    /// the desugared call's own first argument and gets checked at index
    /// `0`. A field call has no such rewrite: `npc.on_greet(3)` calls the
    /// field's own `fn(...)` value directly with the *written* arguments
    /// only (`brink_ir::lir::lower::expr::lower_ufcs_call`'s `FieldCall`
    /// arm lowers straight to `lir::ExprKind::CallValue { callee, args }`, no
    /// synthetic receiver argument) — the receiver's own type already did
    /// its only job selecting this field via `try_field_call`'s
    /// `Ty::Struct` match, so it is never checked as an argument here. Every
    /// [`UfcsArgMismatch`] this returns is therefore `index`-0-based over
    /// the written arguments alone, matching
    /// `strict::check_value_calls`'s own `ValueCallKind::ArgMismatch`
    /// convention rather than [`UfcsArgMismatch::index`]'s "receiver counts
    /// as 0" default.
    ///
    /// **The arity half reads `arg_count`** — the call site's own
    /// AST-derived written-argument count (`resolve_call`'s own
    /// `args.len()`), always available — rather than `current_body()`'s
    /// best-effort `ufcs_call_args` projection, exactly like
    /// [`Self::try_free_fn_desugar`]'s own `E031` arity check does for the
    /// same reason: a missing `BodyTypes` (global-initializer position, see
    /// [`Self::check_ufcs_arg_types`]'s own doc) must degrade only the
    /// per-argument *type* half, never arity — an arity fact this cheap to
    /// derive structurally has no excuse to go missing alongside a body
    /// lookup failure it doesn't actually depend on.
    fn check_field_call_args(
        &self,
        range: TextRange,
        field_ty: &Ty,
        arg_count: usize,
    ) -> (Option<UfcsArityMismatch>, Vec<UfcsArgMismatch>) {
        let Ty::Fn(params, _ret, _) = field_ty else {
            // `try_field_call` only ever calls this once `field_ty` has
            // already matched `Ty::Fn(..)` — kept defensive (no panic
            // outside a test helper; house rule) rather than assuming the
            // caller's own invariant holds.
            return (None, Vec::new());
        };
        let arity_mismatch = (arg_count != params.len()).then_some(UfcsArityMismatch {
            expected: params.len(),
            got: arg_count,
        });

        let empty: Vec<Ty> = Vec::new();
        let written: &[Ty] = self
            .current_body()
            .and_then(|b| b.ufcs_call_args.iter().find(|f| f.range == range))
            .map_or(empty.as_slice(), |f| f.args.as_slice());

        let mut mismatches = Vec::new();
        for (i, param_ty) in params.iter().enumerate() {
            let Some(arg_ty) = written.get(i) else {
                continue;
            };
            if arg_ty.is_unresolved() || param_ty.is_unresolved() {
                continue;
            }
            if !assignable(param_ty, arg_ty) {
                mismatches.push(UfcsArgMismatch {
                    index: i,
                    expected: param_ty.clone(),
                    found: arg_ty.clone(),
                });
            }
        }
        (arity_mismatch, mismatches)
    }

    /// **D5's receiver gate.** `Some(cause)` when auto-ref cannot write
    /// through this receiver, phrased as the tail of the `E143` message;
    /// `None` when it can.
    ///
    /// The desugar rides the T1e ref-argument machinery verbatim
    /// (`brink_ir::lir::lower::expr::lower_call_args`), so it inherits that
    /// machinery's own rules rather than inventing a second set:
    ///
    /// - A **bare** receiver (`gold.bump(1)`) binds like any unmarked
    ///   ref-argument: a frame slot (param/temp) or a global `VAR` both work
    ///   — `lower_ref_path_call_arg`'s `RefTemp`/`RefGlobal` pair.
    /// - A **projection off a durable cell** (`party.leader.heal(5)` where
    ///   `party` is a `VAR`) becomes a real `lir::CallArg::RefProjection`,
    ///   whose root must be durable (`docs/t1e-spec.md` §2, the `E080` rule
    ///   `ref_projection::check_durable_root` enforces for the explicitly
    ///   spelled form) — that requirement is unchanged by this gate.
    /// - A **projection off a frame-local** (`g.hp.heal(5)` where `g` is a
    ///   `let`/param) is legal too, **RULED 2026-07-27** (issue #1531,
    ///   `docs/decision-log.md`): a frame-local cell is a valid projection
    ///   root, and the mutation needs no effect row because it is
    ///   unobservable outside the frame. `RefProjection`'s own root stays
    ///   durable-only (`docs/format-v4-rfc.md` §1), so LIR lowering does not
    ///   reuse that machinery for this case — it splices a read/call/
    ///   write-back RMW sequence instead (`brink_ir::lir::lower::blocks::
    ///   try_lower_frame_local_auto_ref_stmt`), the same discipline plain
    ///   assignment (`g.hp = 5`) already uses. That lowering only has a
    ///   statement-shaped expansion, so it covers a **single field level**
    ///   only — the same boundary `try_lower_field_assignment` draws
    ///   (`E074` for a deeper chain); this gate mirrors that boundary by
    ///   only clearing a two-segment receiver (root + one field).
    /// - A `CONST` is never writable at any depth.
    ///
    /// The ruled rvalue receivers (`[1,2].push(3)`, `a.sorted().push(x)` —
    /// "mutating a temporary loses the mutation") reach this gate as soon as
    /// they are spellable: today's native grammar admits only a dotted path
    /// as a call's callee (`brink-syntax-native`'s `parser::expr::
    /// path_or_call`), so a literal or a call cannot yet sit in receiver
    /// position at all.
    fn auto_ref_fault(&self, receiver: &Receiver<'_>) -> Option<String> {
        let head = receiver.segments.first().map_or("", |s| s.text.as_str());
        // A frame-local projection root is legal (issue #1531) only one
        // field level deep — `head.field`, i.e. exactly two receiver
        // segments. Anything deeper has no lowering (LIR's RMW expansion is
        // single-level, matching `try_lower_field_assignment`'s own `E074`
        // boundary), so it still faults here.
        let frame_local = || {
            (receiver.segments.len() > 2).then(|| {
                format!(
                    "`{head}` is a temp/param — a frame-local projection can only reach one \
                     field level (`{head}.field`); this receiver goes deeper than that"
                )
            })
        };
        match self.index.symbols.get(&receiver.def) {
            Some(info) => match info.kind {
                SymbolKind::Variable => None,
                SymbolKind::Constant => Some(format!("`{head}` is a CONST, not a mutable cell")),
                SymbolKind::Param | SymbolKind::Temp => frame_local(),
                // `value_receiver_def` admits no other kind as a receiver.
                _ => Some(format!(
                    "`{head}` is not a value that can be written through"
                )),
            },
            // Absent from `brink-db`'s narrowed index projection: a local
            // temp/param, exactly as `value_receiver_def`/`head_ty` already
            // treat it (and `ref_projection::check_durable_root`'s own
            // `LocalVar` fallback).
            None => frame_local(),
        }
    }

    /// The resolved definition of `path`'s head when `path` is a
    /// *method-call-shaped* callee: the resolver recorded the head value (a
    /// param/temp/VAR/CONST) as the callee's target rather than a callable
    /// definition. `None` for an ordinary qualified call (a module-qualified
    /// free call, an ink `knot.stitch()` visit).
    ///
    /// This is the mirror of `resolve::resolve_function`'s own UFCS-shaped
    /// fallback — the two must agree, or a call would either be diagnosed
    /// twice or not at all. `resolve_function`'s lookup is project-wide
    /// (`resolve::lookup_by_name`), not file-scoped, so this returns the
    /// same project-wide [`DefinitionId`] rather than re-deriving one from
    /// the head's name alone — [`Self::head_ty`] types it from exactly that
    /// id, the same way `structs::resolved_symbol_ty` types any other
    /// resolved reference.
    fn value_receiver_def(&self, path: &HirPath) -> Option<DefinitionId> {
        // `path.range` here is the callee `Path`'s whole span — this lookup
        // is one of the four consumers keyed on the call-path
        // `ResolvedRef::range` contract (issue #1561); see that field's doc.
        let key = (path.range.start().into(), path.range.end().into());
        let &target = self.resolution_by_range.get(&key)?;
        match self.index.symbols.get(&target) {
            Some(info)
                if matches!(
                    info.kind,
                    SymbolKind::Param
                        | SymbolKind::Temp
                        | SymbolKind::Variable
                        | SymbolKind::Constant
                ) =>
            {
                Some(target)
            }
            // brink-db's narrowed index projection can strip locals; the
            // definition tag still identifies them (mirrors
            // `infer::body::infer_call`'s own `is_value_callee`).
            None if target.tag() == brink_format::DefinitionTag::LocalVar => Some(target),
            Some(_) | None => None,
        }
    }

    /// The receiver's type: the head segment's own type (typed from
    /// `head_def`, the definition `resolve::resolve_function` actually
    /// bound the head to), then each further segment walked through the
    /// declared shape table. `None` whenever any step lands on an unknown or
    /// conflicted type — the D3 case.
    fn receiver_ty(&self, head_def: DefinitionId, segments: &[brink_ir::Name]) -> Option<Ty> {
        let (head, rest) = segments.split_first()?;
        let mut ty = self.head_ty(head_def, head)?;
        for seg in rest {
            let Ty::Struct(shape_name) = &ty else {
                return None;
            };
            let field = self
                .shapes
                .resolve(shape_name, self.scope, self.index)?
                .field_ty(&seg.text)?
                .clone();
            ty = field;
        }
        (!ty.is_unknown() && ty != Ty::Conflicted).then_some(ty)
    }

    /// The head segment's type, read from `def` — the *resolved* definition,
    /// exactly as `structs::resolved_symbol_ty` reads any other resolved
    /// reference: a param/temp reads the enclosing def's finalized local *by
    /// name* (`def`'s own name — locals are keyed by name, not id); a global
    /// `VAR`/`CONST` reads `infer::collect_globals`'s declaration-derived
    /// type *by id*, project-wide, never file-scoped. Dispatching on `def`'s
    /// own kind (rather than trying `current_locals()` by `head.text` first,
    /// unconditionally) also means a body-local shadowing a same-named
    /// global after the call site can never be mistaken for the global the
    /// resolver actually bound.
    fn head_ty(&self, def: DefinitionId, head: &brink_ir::Name) -> Option<Ty> {
        match self.index.symbols.get(&def) {
            Some(info) => match info.kind {
                SymbolKind::Param | SymbolKind::Temp => {
                    self.current_locals()?.get(&info.name).cloned()
                }
                SymbolKind::Variable | SymbolKind::Constant => self.globals.get(&def).cloned(),
                _ => None,
            },
            // brink-db's narrowed index projection can strip locals (see
            // `value_receiver_def`'s own fallback); the enclosing body's
            // finalized locals are keyed by name and unaffected by that
            // projection, so fall back to `head.text`.
            None => self.current_locals()?.get(&head.text).cloned(),
        }
    }

    fn push(&mut self, range: TextRange, code: DiagnosticCode, detail: &str) {
        self.diagnostics.push(Diagnostic {
            file: self.file,
            range,
            message: format!("{}: {detail}", code.title()),
            code,
        });
    }
}