brink-analyzer 0.0.16

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
//! TM-3 completion: `int(x)`/`float(x)` strict-mode domain compile error
//! (`docs/typed-mode-spec.md` §4, maintainer ruling 2026-07-13, issue #659,
//! ruling 2: "Divert/list/collection inputs: compile error under `types =
//! strict`, runtime fault under gradual").
//!
//! Strict-mode-only, mirroring `structs::check`'s own gating (wired into
//! `strict::check` alongside E065-E071): under `types = gradual` this module
//! is never invoked at all, deferring entirely to the runtime fault the
//! `int`/`float` VM ops already implement
//! (`RuntimeError::InvalidConversionDomain`).
//!
//! `string(x)` accepts every type (ruling 2: "everything, display form") and
//! is never checked here — only `int`/`float` have a restricted domain.
//!
//! Scoped to **statically classifiable** arguments — a divert-target
//! expression (`-> knot`), a LIST literal, or a `#[...]`/`#{...}`/`Name#{...}`
//! collection/struct literal passed *directly* as the argument, **plus**
//! (issue #983, mirroring `structs::check`'s own `E071` extension for issue
//! #670) a variable-, call-, or index-valued argument whose type is
//! statically known through the project's whole-project inference
//! substrate: a `Path` resolving to a param/temp reads that def's finalized
//! `BodyTypes::locals`; a `Path` resolving to a global `VAR`/`CONST` reads
//! its declaration-derived type; a `Call` reads the resolved callee's
//! `InferredSig::return_ty`; an `Index` recurses into its base's classified
//! type and takes the array-element/map-value type. Reuses
//! `structs::classify_expr_ty`/`structs::MistypeCtx` verbatim — the same
//! firewall `infer::body` itself reads through — rather than re-deriving an
//! independent copy. Whenever that resolution lands on `Unknown` or
//! `Conflicted` (unresolved, unannotated, or genuinely contradictory), the
//! argument stays silently unchecked, preserving gradual-mode conservatism
//! exactly as before. The runtime fault (`InvalidConversionDomain`) is
//! always the backstop that still catches every case at execution time even
//! under `types = strict` — this pass is a compile-time convenience for the
//! statically-provable cases, not the sole enforcement.
//!
//! Shadowing: an unresolved call to `int`/`float` is the builtin (per the
//! stdlib slice-1 ruling, T1b-surface-spec §5); a call that *did* resolve
//! (an author-defined `int`/`float` knot) is an ordinary function call and
//! is never flagged here.

use std::collections::BTreeMap;

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

use crate::annotations;
use crate::infer::{InferenceResult, InferredSig, Ty};
use crate::structs::{self, MistypeCtx};

/// The two domain-restricted conversion intrinsics — `string()` accepts
/// every type (ruling 2) and is deliberately excluded.
fn domain_checked_name(name: &str) -> bool {
    matches!(name, "int" | "float")
}

/// Strict-mode-only conversion-domain checks over every `int(x)`/`float(x)`
/// call in the project. Callers only reach this once `strict::config_error`
/// has confirmed `types = strict` + `dialect = brink` (mirrors
/// `structs::check`'s own entry condition).
///
/// `index`/`inference` (issue #983): the same whole-project `SymbolIndex`/
/// `InferenceResult` `strict::check` already computes for its own
/// escape/mismatch checks and threads into `structs::check` — this is what
/// lets the domain check classify a variable/call/index-valued argument
/// 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> {
    // No manifest access at this call site, mirroring `structs::check`'s own
    // note — a global's `Handle<K>` annotation resolving 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 = ConversionVisitor {
            file,
            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: `ConversionVisitor::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
}

struct ConversionVisitor<'a> {
    file: FileId,
    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 `structs::ConstructionVisitor`'s identical field.
    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, until `enter_stitch`
    /// overrides it with the stitch's own). Mirrors
    /// `structs::ConstructionVisitor`'s identical field.
    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). Mirrors
    /// `structs::ConstructionVisitor`'s identical field/hook pair exactly —
    /// see that field's own doc.
    lambda_locals: Vec<BTreeMap<String, Ty>>,
    diagnostics: &'a mut Vec<Diagnostic>,
}

impl ConversionVisitor<'_> {
    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 — mirrors
    /// `structs::ConstructionVisitor::knot_def_id` exactly (same #626
    /// top-level-stitch-promoted-to-knot rationale).
    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 ConversionVisitor<'_> {
    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
        // `structs::ConstructionVisitor::enter_stitch` exactly.
        // `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) {
        // Built from direct field projections (not `self.ctx()`) so the
        // borrow checker sees this only borrows the locals-shaped fields,
        // disjoint from the `self.diagnostics` reborrow below — see
        // `structs::ConstructionVisitor::enter_expr`'s identical comment.
        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_call(expr, self.file, &ctx, self.diagnostics);
    }

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

/// If `expr` is an unresolved (builtin, not author-shadowed) call to
/// `int`/`float` whose single argument is statically out-of-domain — either
/// a literal-shaped argument (see [`literal_out_of_domain_kind`]) or, since
/// issue #983, a variable/call/index-valued argument whose inference-
/// substrate-resolved type (via `ctx`) falls outside the permitted
/// int/float/bool/string domain — push `E078`. Anything else — resolved
/// calls (shadowed), other names, wrong arity (flagged separately as
/// `E031`), or an argument whose type isn't statically obvious (`Unknown`/
/// `Conflicted`) — is silently clean.
fn check_call(expr: &Expr, file: FileId, ctx: &MistypeCtx<'_>, out: &mut Vec<Diagnostic>) {
    let Expr::Call(path, args) = expr else {
        return;
    };
    let [seg] = path.segments.as_slice() else {
        return;
    };
    if !domain_checked_name(&seg.text) {
        return;
    }
    if ctx.resolution_by_range.contains_key(&range_key(path.range)) {
        return; // resolved to an author-defined symbol — shadows the builtin
    }
    let [arg] = args.as_slice() else {
        return; // wrong arity — E031's job, not this pass's
    };
    let Some(kind) = classify_out_of_domain(arg, ctx) else {
        return;
    };
    out.push(Diagnostic {
        file,
        range: path.range,
        message: format!(
            "{}: `{}(x)` cannot accept a {kind} value under `types = strict` — permitted \
             domain: int, float, string, bool (docs/typed-mode-spec.md §4)",
            DiagnosticCode::E078.title(),
            seg.text,
        ),
        code: DiagnosticCode::E078,
    });
}

/// Classify an argument expression as statically out-of-domain for
/// `int`/`float`: [`literal_out_of_domain_kind`]'s direct-literal
/// classification first, falling back (issue #983) to the non-literal forms
/// #670's `structs::classify_expr_ty` already resolves through the project's
/// inference substrate — a `Path` (variable), a `Call` (function), or an
/// `Index` expression. `None` — "in-domain or not classifiable" — whenever
/// the resolved type is itself int/float/bool/string, `Unknown`, or
/// `Conflicted`, or the expression shape isn't handled at all: the same
/// "Unknown never disagrees" posture `structs::check`'s `E071` takes.
fn classify_out_of_domain(expr: &Expr, ctx: &MistypeCtx<'_>) -> Option<&'static str> {
    if let Some(kind) = literal_out_of_domain_kind(expr) {
        return Some(kind);
    }
    let ty = structs::classify_expr_ty(expr, ctx)?;
    domain_kind_for_ty(&ty)
}

/// Classify an argument expression as statically out-of-domain for
/// `int`/`float` from its own literal shape alone, or `None` if it's
/// in-domain or not classifiable this way (a variable/call/index — handled
/// by [`classify_out_of_domain`]'s inference-substrate fallback instead).
fn literal_out_of_domain_kind(expr: &Expr) -> Option<&'static str> {
    match expr {
        Expr::DivertTarget(_) => Some("divert"),
        Expr::ListLiteral(_) => Some("list"),
        Expr::ArrayLiteral(_) => Some("array"),
        Expr::MapLiteral(_) => Some("map"),
        Expr::StructLiteral(_) => Some("struct"),
        _ => None,
    }
}

/// Map an inference-substrate-resolved [`Ty`] to its `E078` "kind" word,
/// naming exactly the same five categories [`literal_out_of_domain_kind`]
/// does (divert/list/array/map/struct) — the permitted domain
/// (int/float/bool/string) and anything not statically resolved
/// (`Unknown`/`Conflicted`) fall through to `None`. `Ty::Fn`/`Ty::Handle`
/// also fall through here: neither `structs::literal_ty` nor this pass's own
/// direct-literal classification treats those as classifiable field/argument
/// shapes either (no manifest is threaded into this call site — see
/// `check`'s own doc — so `Ty::Handle` can't in practice arise from
/// `collect_globals(..., None)` here anyway), so extending the domain
/// vocabulary to cover them is left out of this issue's scope rather than
/// invented ad hoc.
fn domain_kind_for_ty(ty: &Ty) -> Option<&'static str> {
    match ty {
        Ty::Divert => Some("divert"),
        Ty::List(_) => Some("list"),
        Ty::Array(_) => Some("array"),
        Ty::Map(_, _) => Some("map"),
        Ty::Struct(_) => Some("struct"),
        _ => None,
    }
}

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` (same rationale: 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()
}

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

    /// Computes real resolutions and a whole-project [`InferenceResult`] —
    /// needed by every test, since [`check`] now always consults that
    /// substrate for its variable/call/index-valued argument classification
    /// (issue #983). Mirrors `structs::tests::build_with_inference` exactly.
    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 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)
    }

    /// [`check_all`]'s native-surface twin — lambdas exist only on the
    /// native surface, so the #1764 fixtures below need `lower_native`.
    fn check_all_native(src: &str) -> Vec<Diagnostic> {
        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(),
        );
        check(&[(FileId(0), &hir)], &index, &inference, &resolutions)
    }

    /// 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).
    #[test]
    fn a_bad_conversion_in_a_lambda_statement_of_a_var_initializer_is_e078() {
        let diags = check_all_native("var f = ||: int {\n  let x = int(Map { 1: 2 });\n  0\n};\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("map"), "{:?}", 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_bad_conversion_in_a_lambda_tail_of_a_var_initializer_is_still_e078() {
        let diags = check_all_native("var f = ||: int {\n  let a = 1;\n  int(Map { 1: 2 })\n};\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
    }

    // ─── 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
    /// `ConversionVisitor` before its `enter_lambda`/`exit_lambda` frame
    /// existed: `build`'s own temp `x` is `array`-typed (`[1, 2, 3]`); the
    /// lambda's own `x: int` param shadows it. Pre-fix, `int(x)` resolved
    /// `x` to the outer `array` — out of `int`'s domain — a false-positive
    /// `E078`. `int` is squarely inside `int`'s own domain, so the fixed
    /// behavior is clean.
    #[test]
    fn lambda_param_shadowing_outer_array_local_is_not_misclassified_as_out_of_domain() {
        let diags = check_all_native(
            "fn build() {\n  let x = [1, 2, 3];\n  let f = |x: int| {\n    int(x)\n  };\n}\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// The pruning must not silence a genuinely out-of-domain conversion
    /// inside the lambda's own body — the lambda's own `x: Map<int, int>`
    /// param really is out of `int`'s domain.
    #[test]
    fn lambda_param_own_annotation_still_flags_a_genuine_out_of_domain_conversion() {
        let diags = check_all_native(
            "fn build() {\n  let x = [1, 2, 3];\n  let f = |x: Map<int, int>| {\n    int(x)\n  };\n}\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
    }

    /// Review finding on issue #2773: every fixture above exercises only
    /// `LambdaBody::Block` — `pruned_locals_for_lambda`'s own
    /// `LambdaBody::Expr(_) => &[]` arm (a bare-expression body binds no
    /// extra names beyond its own params) was reachable in this file's
    /// `enter_lambda`, but nothing pinned that the pruned frame is actually
    /// pushed for that shape too. Same fixture as
    /// `lambda_param_shadowing_outer_array_local_is_not_misclassified_as_out_of_domain`,
    /// with the lambda's block body (`{ int(x) }`) collapsed to a bare
    /// expression body (`int(x)`) — if a future edit made the `Expr(_)` arm
    /// skip the frame push, this would regress to a false-positive `E078`
    /// while every block-bodied fixture above stayed green.
    #[test]
    fn lambda_expr_body_param_shadowing_outer_array_local_is_not_misclassified() {
        let diags =
            check_all_native("fn build() {\n  let x = [1, 2, 3];\n  let f = |x: int| int(x);\n}\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    // ─── 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
    /// (`infer::body::infer_def_body`) — the exact same mechanism
    /// `annotated_fn_param_option_condition_is_e116` pins for
    /// `option_conditions.rs`'s E116, just for this file's E078 domain check
    /// instead. `x`'s only other appearance is the `int(x)` call itself — no
    /// other statement in `build`'s body ever *observes* `x`, so pre-#2786
    /// this param stayed `Unknown` in `pass.locals` and
    /// `classify_out_of_domain` fell through silently (mirrors
    /// `unused_param_variable_valued_argument_stays_silent_when_unknown`
    /// above, just annotated). Post-#2786 the annotation itself supplies the
    /// classification: `x: Map<int, int>` is out of `int`'s domain, so this
    /// must now fire — the new true positive #2793 asks each consumer to
    /// confirm.
    ///
    /// The call sits inside a `let` (a `TempDecl`), not the bare tail
    /// expression `int(x)`: an ordinary `fn`'s block tail is only wired
    /// through an explicit `return`/binding statement, unlike a *lambda*'s
    /// own `LambdaBody::Block` tail (the lambda fixtures above use exactly
    /// that bare-tail shape) — unrelated to #2793's own fix, just the
    /// well-formed way to place this call in an ordinary `fn` body.
    #[test]
    fn annotated_fn_param_out_of_domain_conversion_is_e078() {
        let diags = check_all_native("fn build(x: Map<int, int>) {\n  let y = int(x);\n}\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("map"), "{:?}", diags[0].message);
    }

    /// Negative control alongside
    /// [`annotated_fn_param_out_of_domain_conversion_is_e078`]: an ordinary
    /// annotated param whose declared type is already in `int`'s permitted
    /// domain must stay clean, exactly like every other in-domain fixture in
    /// this file.
    #[test]
    fn annotated_fn_param_in_domain_conversion_stays_clean() {
        let diags = check_all_native("fn build(x: float) {\n  let y = int(x);\n}\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn int_of_a_divert_target_literal_is_e078() {
        let diags =
            check_all("=== knot ===\nHello.\n-> DONE\n=== main ===\n~ x = int(-> knot)\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("divert"));
    }

    #[test]
    fn float_of_an_array_literal_is_e078() {
        let diags = check_all("=== main ===\n~ x = float(#[1, 2])\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("array"));
    }

    #[test]
    fn int_of_a_map_literal_is_e078() {
        let diags = check_all("=== main ===\n~ x = int(#{\"a\": 1})\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert!(diags[0].message.contains("map"));
    }

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

    #[test]
    fn int_of_a_list_literal_is_e078() {
        let diags = check_all("LIST Colors = red, blue\n=== main ===\n~ x = int((red))\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert!(diags[0].message.contains("list"));
    }

    #[test]
    fn int_of_a_numeric_literal_is_clean() {
        let diags = check_all("=== main ===\n~ x = int(2.9)\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn int_of_a_string_literal_is_clean() {
        let diags = check_all("=== main ===\n~ x = int(\"42\")\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn int_of_an_in_domain_variable_is_clean() {
        // `gold`'s declaration-derived type is a concrete `int` — in-domain,
        // so this stays clean (not because it's unclassifiable, but because
        // its resolved type is permitted).
        let diags = check_all("VAR gold = 5\n=== main ===\n~ x = int(gold)\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn string_of_a_divert_target_is_never_checked() {
        // Ruling 2: `string()` accepts every type.
        let diags = check_all(
            "=== knot ===\nHello.\n-> DONE\n=== main ===\n~ x = string(-> knot)\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn author_defined_int_shadowing_the_builtin_is_never_checked() {
        let diags = check_all(
            "=== function int(x) ===\n~ return 0\n=== main ===\n~ y = int(-> main)\n-> DONE\n",
        );
        assert!(
            diags.is_empty(),
            "a resolved call to the author's own `int` must never be flagged: {diags:?}"
        );
    }

    #[test]
    fn wrong_arity_int_call_is_not_flagged_here() {
        // E031's job, not this pass's — this pass only checks the arg when
        // arity is exactly 1.
        let diags = check_all("=== main ===\n~ x = int(1, 2)\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    // ── issue #983: variable/call/index-valued arguments ────────────────

    #[test]
    fn global_variable_valued_argument_fires_when_provably_mistyped() {
        // `v`'s declaration-derived type is a concrete `divert` (its own
        // divert-target initializer) — out of `int`/`float`'s permitted
        // domain, so this now fires exactly like a literal `-> knot`
        // argument would. (Issue #1540 widened `collect_globals` to full
        // `Ty` fidelity, so a global's `array`/`map`/`struct`-literal
        // initializer now drives this same dispatch too — see
        // `global_array_valued_argument_fires_since_the_value_ty_widening`
        // just below. `divert` stays the fixture here because it is the
        // shape this issue's own scope introduced.)
        let diags = check_all(
            "=== knot ===\nHello.\n-> DONE\nVAR v = -> knot\n=== main ===\n~ x = int(v)\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(
            diags[0].message.contains("divert"),
            "{:?}",
            diags[0].message
        );
    }

    /// Issue #1540: the collection shapes that used to be dropped on the
    /// way into `collect_globals` now reach this dispatch. Before the
    /// `Sig::value_ty` widening this compiled clean — a latent miss, not a
    /// design choice — while the `temp` twin
    /// (`temp_variable_valued_argument_fires_when_provably_mistyped`)
    /// reported for the identical value.
    #[test]
    fn global_array_valued_argument_fires_since_the_value_ty_widening() {
        let diags = check_all("VAR xs = #[1, 2]\n=== main ===\n~ x = int(xs)\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("array"), "{:?}", diags[0].message);
    }

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

    #[test]
    fn unused_param_variable_valued_argument_stays_silent_when_unknown() {
        // `n` is never used anywhere else in the body, so it stays
        // `Unknown` — "Unknown never disagrees" holds here exactly as it
        // does for `structs::check`'s `E071`.
        let diags = check_all("=== main(n) ===\n~ x = int(n)\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn temp_variable_valued_argument_fires_when_provably_mistyped() {
        // `xs`'s finalized `BodyTypes::locals` type is `Map<string, int>`
        // (its own literal initializer) — out of domain.
        let diags = check_all("=== main ===\n~ temp xs = #{\"a\": 1}\n~ x = int(xs)\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("map"), "{:?}", diags[0].message);
    }

    #[test]
    fn call_valued_argument_fires_when_provably_mistyped() {
        // `shape()`'s only `~ return` is a `STRUCT` literal, so its
        // finalized `InferredSig::return_ty` is a concrete struct type —
        // out of domain.
        let diags = check_all(
            "STRUCT Point = #{x: float}\n\
             === function shape() ===\n~ return Point#{x: 1.0}\n\
             === main ===\n~ y = int(shape())\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(
            diags[0].message.contains("struct"),
            "{:?}",
            diags[0].message
        );
    }

    #[test]
    fn call_valued_argument_of_in_domain_return_type_is_clean() {
        let diags = check_all(
            "=== function label() ===\n~ return \"a\"\n\
             === main ===\n~ x = int(label())\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn index_valued_argument_fires_when_provably_mistyped() {
        // `xs` is a local `~ temp` bound to a `#[#[..], #[..]]`
        // array-of-arrays literal, so its finalized locals type is
        // `Array<Array<int>>` — indexing it yields `Array<int>`, out of
        // domain.
        let diags = check_all(
            "=== main ===\n\
             ~ temp xs = #[#[1, 2], #[3, 4]]\n~ x = int(xs[0])\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("array"), "{:?}", diags[0].message);
    }

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

    #[test]
    fn index_valued_argument_stays_silent_when_unknown() {
        // `xs` is only ever indexed, never assigned/observed to a concrete
        // type elsewhere, so it stays `Unknown` — no false-flagging.
        let diags = check_all("=== main(xs) ===\n~ x = int(xs[0])\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn stitch_local_variable_valued_argument_fires_when_provably_mistyped() {
        // Every other non-literal-classification test above only ever
        // exercises knot scope (`main`) or file scope — never a stitch
        // body. This drives the `enter_stitch`/`stitch_locals` dispatch
        // path specifically (the exact gap PR #975's own review caught for
        // `structs::check`): `t`'s finalized `BodyTypes::locals` type is a
        // concrete `Array<int>` — out of domain.
        let diags =
            check_all("=== room ===\n= inside\n~ temp t = #[1, 2]\n~ x = int(t)\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("array"), "{:?}", diags[0].message);
    }

    #[test]
    fn variable_valued_argument_inside_var_initializer_uses_global_scope_only() {
        // A call in a file-level VAR/CONST initializer has no enclosing
        // knot/stitch body — only a reference to *another* global is
        // classifiable there (mirrors `structs::check`'s identical file-scope
        // note). `other`'s declared type (`List<Colors>`, one of the two
        // non-scalar shapes `InferredType` represents — see the previous
        // test's comment) is out of domain.
        let diags = check_all("LIST Colors = red, blue\nVAR other = (red)\nVAR x = int(other)\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E078);
        assert!(diags[0].message.contains("list"), "{:?}", diags[0].message);
    }

    #[test]
    fn mistyped_variable_argument_diagnostic_is_order_independent() {
        // #627 discipline (mirrored from `structs::tests::
        // mistyped_variable_field_diagnostic_is_order_independent`): `v`'s
        // out-of-domain classification (and the resulting E078) must not
        // depend on whether its `int(v)` call comes before or after another,
        // unrelated `int()` call in the same body.
        let forward = "=== knot ===\nHello.\n-> DONE\nVAR v = -> knot\n\
             === main ===\n~ x = int(v)\n~ y = int(2.9)\n-> DONE\n";
        let reversed = "=== knot ===\nHello.\n-> DONE\nVAR v = -> knot\n\
             === main ===\n~ y = int(2.9)\n~ x = int(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::E078);
        assert!(
            diags_f[0].message.contains("divert"),
            "{:?}",
            diags_f[0].message
        );

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