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
//! Map-literal key diagnostics: the T1b **key-domain** warning
//! (`docs/t1b-surface-spec.md` §3, issue #598, [`check`]) and the B5
//! **duplicate-key** error (`docs/stdlib-spec.md` §9.6, issue #1464,
//! [`check_duplicate_keys`]). Both walk the same `MapLiteral` set, which is
//! why they live together; their *wiring* differs (see
//! [`check_duplicate_keys`]'s own doc).
//!
//! §3 rules the map-literal key domain to int/string/bool at runtime
//! (enforced by `brink-runtime`'s `MapKey::from_value` /
//! `RuntimeError::InvalidMapKeyType`) and says "the analyzer warns on
//! statically-visible non-key types" — a claim that, until this module,
//! nothing implemented (`MapLiteral` lowering did zero key-domain checking;
//! only the runtime fault enforced the domain at all).
//!
//! Policy-independent, like `structs::check_duplicates`'s `E084`: a
//! non-key-domain literal key is a structural authoring mistake detectable
//! from the literal alone, so this runs under *both* `types` policies
//! (unlike `structs::check`'s missing/extra/mistyped trio, which is
//! strict-only because it needs a resolved shape). Both [`check`] and
//! [`check_duplicate_keys`] are wired in under `dialect = Brink ||
//! is_native` — wider than the brink-only block the rest of
//! `per_file_diagnostics` uses, matching `structs::check_duplicates`'s own
//! `E084` wiring (same module doc reasoning): B5 (issue #1464, #1103
//! cascade ruling (A)) made `TypeName { … }` construction reach
//! `MapLiteral` through the native surface (`Map { k: v }`) as well as the
//! brink dialect's own `#{…}` spelling, so a `.brink` file compiled under
//! the default `strict-ink` dialect must still get both `E106` and `E138`.
//! Under `strict-ink` *ink* map literals don't exist at all — `#{…}` is
//! already rejected whole by `dialect_gate`'s E051, so critiquing the
//! inside of rejected syntax would be noise — and no native surface exists
//! there to reach one either, so nothing new fires.
//!
//! Scoped to **statically classifiable** key expressions — a literal kind
//! is either obviously in the domain (`Expr::Int`/`Expr::Bool`/`Expr::String`)
//! or obviously not (a float/array/nested-map/struct/fn/list/divert-target
//! literal). A dynamic key (a variable, call, index, or any other
//! non-literal expression) is not statically visible at all — "Unknown
//! never disagrees", the same posture `structs::literal_ty` takes — and is
//! silently left to the runtime fault.

use rowan::TextRange;

use brink_ir::hir::visit::{self, HirVisitor};
use brink_ir::{Diagnostic, DiagnosticCode, Expr, FileId, HirFile, MapLiteral};

/// One per-literal check, applied to every map literal the walk below
/// reaches. Both of this module's passes are this shape, so they share one
/// walker.
type LiteralCheck = fn(&MapLiteral, FileId, &mut Vec<Diagnostic>);

/// Map-literal key-domain checks over every `#{...}` literal in the project.
/// Callers wire this in per-file, under `dialect = Brink || is_native` (see
/// module doc) — no `types`-policy gate, no shape/resolution table needed.
#[must_use]
pub fn check(files: &[(FileId, &HirFile)]) -> Vec<Diagnostic> {
    walk_map_literals(files, check_literal)
}

/// Duplicate-key check over every map literal in the project (`E138`; B5,
/// issue #1464, #1103 cascade ruling (A) — "duplicate keys in a map literal
/// are a **compile error**, consistent with struct dup-field").
///
/// Split from [`check`] because it is a distinct rule (key-domain vs.
/// duplicate-key), not because of wiring — both now share the same
/// `dialect = Brink || is_native` gate (see module doc): this rule is about
/// the *construction* protocol, which the native surface reaches through
/// `Map { k: v }` (`brink_ir::hir::construct`) as well as the brink
/// dialect's `#{…}` sigil — both lower to the same [`MapLiteral`], so one
/// pass serves both surfaces.
#[must_use]
pub fn check_duplicate_keys(files: &[(FileId, &HirFile)]) -> Vec<Diagnostic> {
    walk_map_literals(files, check_duplicates_in_literal)
}

/// Apply `check` to every map literal reachable in `files`.
fn walk_map_literals(files: &[(FileId, &HirFile)], check: LiteralCheck) -> Vec<Diagnostic> {
    let mut out = Vec::new();
    for &(file, hir) in files {
        let mut v = MapKeyVisitor {
            file,
            check,
            diagnostics: &mut out,
        };
        // Issue #2098: `MapKeyVisitor::enter_expr` carries no per-position
        // state at all, so the shared entry point covers the block tree and
        // every file-level declaration's own initializer in one drive — the
        // hand-rolled `check_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 MapKeyVisitor<'a> {
    file: FileId,
    check: LiteralCheck,
    diagnostics: &'a mut Vec<Diagnostic>,
}

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

    fn enter_expr(&mut self, expr: &Expr) {
        if let Expr::MapLiteral(m) = expr {
            (self.check)(m, self.file, self.diagnostics);
        }
    }
}

/// Flag every entry in `m` whose key is a statically-classifiable literal
/// outside the ratified int/string/bool key domain.
fn check_literal(m: &MapLiteral, file: FileId, out: &mut Vec<Diagnostic>) {
    for (key, _value) in &m.entries {
        let Some((kind, own_range)) = non_key_domain_kind(key) else {
            continue;
        };
        out.push(Diagnostic {
            file,
            // The bare scalar variants (float/null/list/divert-target) carry
            // no `ptr` of their own at HIR level (only the wrapper-struct
            // variants — array/map/struct/fn literals — do), so this falls
            // back to the enclosing map literal's own range. Same "point at
            // the whole enclosing literal" fallback `structs::check`'s E069
            // (missing-field) diagnostic uses when there's no more specific
            // span available.
            range: own_range.unwrap_or_else(|| m.ptr.text_range()),
            message: format!(
                "{}: `{kind}` key literal is outside the int/string/bool key domain",
                DiagnosticCode::E106.title(),
            ),
            code: DiagnosticCode::E106,
        });
    }
}

/// A map-literal key that is comparable at compile time — the in-domain
/// literal kinds (`int`/`string`/`bool`, §3's ratified key domain). Two
/// entries collide exactly when their [`StaticKey`]s are equal, which is
/// also the runtime's own `MapKey` identity, so this never reports a
/// collision the runtime wouldn't have.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum StaticKey {
    Int(i32),
    Bool(bool),
    Str(String),
}

impl std::fmt::Display for StaticKey {
    /// Renders the key the way it would be spelled as a map-literal key, so
    /// the `E138` message can name the exact key that collided (`1`,
    /// `true`, `"a"`) instead of only pointing at the enclosing literal.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StaticKey::Int(v) => write!(f, "{v}"),
            StaticKey::Bool(b) => write!(f, "{b}"),
            StaticKey::Str(s) => write!(f, "{s:?}"),
        }
    }
}

/// The compile-time identity of a key expression, when it has one.
///
/// Deliberately narrow, the same "Unknown never disagrees" posture the
/// key-domain check takes: a variable, call, or *interpolated* string is
/// not statically comparable (`#{"{a}": 1, "{b}": 2}` may or may not
/// collide at runtime), so it is skipped rather than guessed at. An
/// out-of-domain key (float, array, …) is skipped too — `E106` already
/// owns that mistake, and reporting a second diagnostic for it would just
/// be noise.
fn static_key(expr: &Expr) -> Option<StaticKey> {
    match expr {
        Expr::Int(v) => Some(StaticKey::Int(*v)),
        Expr::Bool(b) => Some(StaticKey::Bool(*b)),
        Expr::String(s) => match s.parts.as_slice() {
            [brink_ir::StringPart::Literal(text)] => Some(StaticKey::Str(text.clone())),
            _ => None,
        },
        _ => None,
    }
}

/// Flag every entry in `m` whose key repeats an earlier entry's key
/// (`E138`). Order-independent by construction: keys are accumulated in
/// source order into a `BTreeSet`, so the *second* occurrence is the one
/// reported and the diagnostic list is deterministic.
fn check_duplicates_in_literal(m: &MapLiteral, file: FileId, out: &mut Vec<Diagnostic>) {
    let mut seen: std::collections::BTreeSet<StaticKey> = std::collections::BTreeSet::new();
    for (key, _value) in &m.entries {
        let Some(k) = static_key(key) else {
            continue;
        };
        if seen.insert(k.clone()) {
            continue;
        }
        out.push(Diagnostic {
            file,
            // In-domain scalar keys carry no `ptr` of their own at HIR
            // level, so this points at the enclosing literal — the same
            // fallback `check_literal`'s `E106` diagnostic documents.
            range: m.ptr.text_range(),
            message: format!(
                "{}: duplicate key `{k}` — an earlier entry already supplies it",
                DiagnosticCode::E138.title(),
            ),
            code: DiagnosticCode::E138,
        });
    }
}

/// Classify a map-literal key expression as a statically-visible
/// non-key-domain literal, if it is one. `Some((kind, range))` — `kind` is a
/// short human-readable name for the message, `range` is the literal's own
/// text range when it carries a `ptr` (`None` for the bare scalar variants
/// that don't, see [`check_literal`]'s fallback). `Int`/`Bool`/`String` are
/// in-domain (never flagged); any other, non-literal expression (a
/// variable, call, index, field access, or other operator expression) is
/// not statically classifiable at all and returns `None` too — the runtime
/// `InvalidMapKeyType` fault remains the backstop for those.
fn non_key_domain_kind(expr: &Expr) -> Option<(&'static str, Option<TextRange>)> {
    match expr {
        Expr::Float(_) => Some(("float", None)),
        // `Expr::Null` deliberately excluded: there is no `null` keyword in
        // ink/brink source syntax (it's only ever an internal default for an
        // uninitialized `VAR`/`CONST`), so it can never actually appear as a
        // map-literal key expression — a defensive branch the grammar
        // already makes unreachable.
        //
        // The ink `LIST` literal (`(item1, item2)`), distinct from the
        // brink `#[...]` array sigil below — matches `brink-runtime`'s own
        // `type_name`'s "list" label for `Value::List`.
        Expr::ListLiteral(_) => Some(("list", None)),
        Expr::DivertTarget(_) => Some(("divert target", None)),
        Expr::ArrayLiteral(a) => Some(("array", Some(a.ptr.text_range()))),
        Expr::MapLiteral(m) => Some(("map", Some(m.ptr.text_range()))),
        Expr::StructLiteral(sl) => Some(("struct", Some(sl.ptr.text_range()))),
        Expr::FnLiteral(fl) => Some(("function", Some(fl.ptr.text_range()))),
        _ => None,
    }
}

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

    fn build(src: &str) -> HirFile {
        let parsed = brink_syntax::parse(src);
        let (hir, _manifest, _diag) = lower(FileId(0), &parsed.tree());
        hir
    }

    fn check_src(src: &str) -> Vec<Diagnostic> {
        let hir = build(src);
        check(&[(FileId(0), &hir)])
    }

    /// Native-lowered HIR — lambdas exist only on the native surface, so the
    /// #1764 fixtures below must go through `lower_native` (the same reason
    /// `coalesce`'s own `build_native` helper exists).
    fn build_native(src: &str) -> HirFile {
        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());
        hir
    }

    #[test]
    fn clean_int_string_bool_keys_produce_no_diagnostics() {
        let diags = check_src("=== main ===\n~ temp m = #{1: \"a\", \"k\": 2, true: 3}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn float_key_is_e106() {
        let diags = check_src("=== main ===\n~ temp m = #{3.5: 1}\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(diags[0].message.contains("float"), "{:?}", diags[0].message);
    }

    #[test]
    fn array_literal_key_is_e106() {
        let diags = check_src("=== main ===\n~ temp m = #{#[1, 2]: 1}\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(diags[0].message.contains("array"), "{:?}", diags[0].message);
    }

    #[test]
    fn nested_map_literal_key_is_e106() {
        let diags = check_src("=== main ===\n~ temp m = #{#{1: 2}: 1}\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(diags[0].message.contains("map"), "{:?}", diags[0].message);
    }

    #[test]
    fn struct_literal_key_is_e106() {
        let diags = check_src(
            "STRUCT Point = #{x: int}\n\
             === main ===\n~ temp m = #{Point#{x: 1}: 1}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(
            diags[0].message.contains("struct"),
            "{:?}",
            diags[0].message
        );
    }

    #[test]
    fn list_literal_key_is_e106() {
        let diags = check_src(
            "LIST Colors = red, green, blue\n\
             === main ===\n~ temp m = #{(red): 1}\n-> DONE\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(diags[0].message.contains("list"), "{:?}", diags[0].message);
    }

    #[test]
    fn divert_target_key_is_e106() {
        let diags =
            check_src("=== main ===\n~ temp m = #{-> other: 1}\n-> DONE\n=== other ===\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(
            diags[0].message.contains("divert target"),
            "{:?}",
            diags[0].message
        );
    }

    #[test]
    fn fn_literal_key_is_e106() {
        let diags = check_src(
            "=== main ===\n~ temp m = #{#fn(score): 1}\n-> DONE\n\
             === score(x) ===\n~ return x\n",
        );
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(
            diags[0].message.contains("function"),
            "{:?}",
            diags[0].message
        );
    }

    #[test]
    fn dynamic_variable_key_does_not_fire() {
        let diags = check_src("=== main ===\n~ temp k = 1.5\n~ temp m = #{k: 1}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn dynamic_call_key_does_not_fire() {
        let diags = check_src(
            "=== main ===\n~ temp m = #{score(1): 1}\n-> DONE\n\
             === score(x) ===\n~ return x\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn value_position_non_key_domain_is_not_flagged() {
        // Non-key-domain literals are perfectly legal as map *values* — only
        // the key position is domain-restricted.
        let diags = check_src("=== main ===\n~ temp m = #{1: 3.5}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    #[test]
    fn var_decl_initializer_map_literal_is_checked() {
        let diags = check_src("VAR m = #{3.5: 1}\n=== main ===\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
    }

    /// Coverage for a lambda's statements in a VAR/CONST initializer comes
    /// from `visit::visit_with_decl_initializers` (which reaches the
    /// initializer at all) composed with `walk_expr`'s `Expr::Lambda` arm
    /// (which already descends a lambda's statements) — there is no
    /// separate hand-rolled recursion for this position (issue #2098). A
    /// block-bodied lambda's `let` is a statement, not the body's value
    /// expression.
    #[test]
    fn a_bad_key_in_a_lambda_statement_of_a_var_initializer_is_reported() {
        let hir = build_native("var f = ||: int {\n  let m = Map { 3.5: 1 };\n  0\n};\n");
        let diags = check(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
        assert!(diags[0].message.contains("float"), "{:?}", diags[0].message);
    }

    /// The same gap for the duplicate-key rule — one walk, two checks.
    #[test]
    fn a_duplicate_key_in_a_lambda_statement_of_a_var_initializer_is_reported() {
        let hir = build_native("var f = ||: int {\n  let m = Map { 1: 2, 1: 3 };\n  0\n};\n");
        let diags = check_duplicate_keys(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E138);
    }

    /// 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_key_in_a_lambda_tail_of_a_var_initializer_is_still_reported() {
        let hir = build_native("var f = ||: int {\n  let a = 1;\n  Map { 3.5: 1 }\n};\n");
        let diags = check(&[(FileId(0), &hir)]);
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E106);
    }

    /// Full-pipeline reachability: `analyze_with_options` (the entry point
    /// `brink-db`'s real diagnostics query drives, per `lib.rs`'s own doc)
    /// wires this through `finish_analysis` -> `per_file_diagnostics` ->
    /// `map_keys::check`, unconditionally under `dialect = Brink` — no
    /// `types`-policy gate (see module doc), so it fires identically under
    /// both `TypePolicy::Gradual` (the default) and `TypePolicy::Strict`.
    #[test]
    fn fires_through_analyze_under_both_gradual_and_strict_type_policy() {
        use crate::{AnalysisOptions, Dialect, TypePolicy, analyze_with_options};

        let src = "=== main ===\n~ temp m = #{3.5: 1}\n-> DONE\n";
        let parsed = brink_syntax::parse(src);
        let (hir, manifest, diag) = lower(FileId(0), &parsed.tree());
        assert!(diag.is_empty(), "{diag:?}");

        for types in [TypePolicy::Gradual, TypePolicy::Strict] {
            let opts = AnalysisOptions {
                dialect: Dialect::Brink,
                types: Some(types),
                ..Default::default()
            };
            let result = analyze_with_options(&[(FileId(0), &hir, &manifest)], &opts);
            assert!(
                result
                    .diagnostics
                    .iter()
                    .any(|d| d.code == DiagnosticCode::E106),
                "types={types:?}: {:?}",
                result.diagnostics
            );
        }
    }

    // ── Duplicate keys (E138, B5 issue #1464) ───────────────────────

    fn dup_src(src: &str) -> Vec<Diagnostic> {
        let hir = build(src);
        check_duplicate_keys(&[(FileId(0), &hir)])
    }

    /// The brink dialect's own `#{…}` spelling reaches the same rule — the
    /// two surfaces share one `MapLiteral`, so one pass serves both.
    #[test]
    fn a_repeated_string_key_is_e138() {
        let diags = dup_src("=== main ===\n~ temp m = #{\"a\": 1, \"a\": 2}\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E138);
    }

    #[test]
    fn repeats_are_caught_in_every_in_domain_key_kind() {
        for src in [
            "=== main ===\n~ temp m = #{1: \"a\", 1: \"b\"}\n-> DONE\n",
            "=== main ===\n~ temp m = #{true: 1, true: 2}\n-> DONE\n",
            "=== main ===\n~ temp m = #{\"k\": 1, \"k\": 2}\n-> DONE\n",
        ] {
            let diags = dup_src(src);
            assert_eq!(diags.len(), 1, "{src}: {diags:?}");
            assert_eq!(diags[0].code, DiagnosticCode::E138, "{src}");
        }
    }

    /// Three occurrences of one key report twice — one per overwrite, so
    /// the count matches the number of entries actually lost.
    #[test]
    fn each_extra_occurrence_reports_once() {
        let diags = dup_src("=== main ===\n~ temp m = #{1: \"a\", 1: \"b\", 1: \"c\"}\n-> DONE\n");
        assert_eq!(diags.len(), 2, "{diags:?}");
    }

    /// The message names the offending key rather than describing the
    /// rejected last-wins behavior — cascade ruling (A) makes this a
    /// compile error precisely so nothing ever overwrites anything.
    #[test]
    fn the_message_names_the_duplicated_key() {
        let diags = dup_src("=== main ===\n~ temp m = #{1: \"a\", 1: \"b\"}\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert!(
            diags[0].message.contains('1'),
            "message should name the key `1`: {:?}",
            diags[0].message
        );

        let diags = dup_src("=== main ===\n~ temp m = #{\"k\": 1, \"k\": 2}\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert!(
            diags[0].message.contains("\"k\""),
            "message should name the key `\"k\"`: {:?}",
            diags[0].message
        );
    }

    /// Three occurrences of one key report twice, and the two diagnostics
    /// are distinguishable — a review finding on an earlier revision of
    /// this pass noted the messages were byte-identical duplicates that
    /// named neither the key nor which occurrence collided.
    #[test]
    fn each_occurrence_reports_the_same_named_key() {
        let diags = dup_src("=== main ===\n~ temp m = #{1: \"a\", 1: \"b\", 1: \"c\"}\n-> DONE\n");
        assert_eq!(diags.len(), 2, "{diags:?}");
        for d in &diags {
            assert!(d.message.contains('1'), "{:?}", d.message);
        }
    }

    #[test]
    fn distinct_keys_do_not_fire() {
        let diags =
            dup_src("=== main ===\n~ temp m = #{1: \"a\", 2: \"b\", true: 3, \"1\": 4}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// `1` (int) and `"1"` (string) are different `MapKey`s at runtime, so
    /// they must not be reported as a collision here either.
    #[test]
    fn keys_of_different_kinds_never_collide() {
        let diags = dup_src("=== main ===\n~ temp m = #{1: \"a\", \"1\": \"b\"}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// "Unknown never disagrees": a key the compiler cannot compare
    /// statically is left to the runtime rather than guessed at.
    #[test]
    fn dynamic_and_interpolated_keys_do_not_fire() {
        let diags = dup_src("=== main ===\n~ temp k = 1\n~ temp m = #{k: 1, k: 2}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");

        let diags = dup_src(
            "=== main ===\n~ temp a = \"x\"\n~ temp m = #{\"{a}\": 1, \"{a}\": 2}\n-> DONE\n",
        );
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// An out-of-domain key is `E106`'s mistake, not this pass's — a
    /// second diagnostic for the same entry would just be noise.
    #[test]
    fn out_of_domain_keys_are_left_to_e106() {
        let diags = dup_src("=== main ===\n~ temp m = #{3.5: 1, 3.5: 2}\n-> DONE\n");
        assert!(diags.is_empty(), "{diags:?}");
    }

    /// Nested literals are reached by the same walk `check` uses.
    #[test]
    fn a_repeat_inside_a_nested_literal_is_reported() {
        let diags = dup_src("=== main ===\n~ temp m = #{1: #{\"a\": 1, \"a\": 2}}\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E138);
    }

    /// Declaration initializers are outside `visit::visit`'s block walk —
    /// the same VAR/CONST gap `check` covers by hand.
    #[test]
    fn a_repeat_in_a_var_initializer_is_reported() {
        let diags = dup_src("VAR m = #{\"a\": 1, \"a\": 2}\n=== main ===\n-> DONE\n");
        assert_eq!(diags.len(), 1, "{diags:?}");
        assert_eq!(diags[0].code, DiagnosticCode::E138);
    }
}