brink-analyzer 0.0.10

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
//! Structural validation passes over the HIR.
//!
//! These passes walk the HIR statement tree and emit diagnostics for
//! structurally invalid patterns that the parser accepts but the language
//! semantics forbid.

use brink_ir::hir::{Block, Choice, ChoiceSet, HirVisitor, Knot, Stmt};
use brink_ir::{Diagnostic, DiagnosticCode, FileId, HirFile};

/// Run all structural validation passes on the given files.
pub fn validate(files: &[(FileId, &HirFile)]) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();
    for &(file_id, hir) in files {
        // E029 is positional — it depends on the statements *after* a
        // conditional/sequence in the enclosing block — so it keeps its own
        // contextual walk. The remaining checks are node-local or per-block and
        // share a single traversal via the shared HIR visitor.
        check_choices_in_inline_context(file_id, hir, &mut diagnostics);

        let mut v = StructuralChecks::new(file_id);
        brink_ir::hir::visit::visit(hir, &mut v);
        // Append per-check buckets in the original pass order; each bucket is
        // already in DFS order, so overall diagnostic ordering is unchanged.
        diagnostics.extend(v.returns);
        diagnostics.extend(v.unreachable);
        diagnostics.extend(v.fallbacks);
    }
    diagnostics
}

// ─── Choice-in-conditional/sequence validation ──────────────────────

/// Inklecate rejects choices nested inside conditionals or sequences when
/// the choice has no continuation path — no explicit divert on the choice
/// AND no statements after the conditional/sequence in the enclosing block
/// to fall through to.
///
/// Invalid: `{ true: * choice }` — dead end, no continuation.
/// Valid:   `{ true: * choice -> target }` — explicit divert.
/// Valid:   `{ true: + [Burn] \n Hello } \n - -> label` — gather after
///          the conditional provides a continuation path.
fn check_choices_in_inline_context(
    file_id: FileId,
    hir: &HirFile,
    diagnostics: &mut Vec<Diagnostic>,
) {
    walk_block(&hir.root_content, false, file_id, diagnostics);
    for knot in &hir.knots {
        walk_block(&knot.body, false, file_id, diagnostics);
        for stitch in &knot.stitches {
            walk_block(&stitch.body, false, file_id, diagnostics);
        }
    }
}

/// Walk a block's statements. `dead_end` is true when we're inside a
/// conditional/sequence that has no continuation after it — meaning
/// inline choices without diverts would be dead ends.
fn walk_block(block: &Block, dead_end: bool, file_id: FileId, diagnostics: &mut Vec<Diagnostic>) {
    for (i, stmt) in block.stmts.iter().enumerate() {
        match stmt {
            Stmt::ChoiceSet(cs) => {
                if dead_end {
                    check_choice_set_diverts(cs, file_id, diagnostics);
                }
                // Always recurse into choice bodies + continuation.
                walk_choice_set(cs, file_id, diagnostics);
            }
            Stmt::Conditional(cond) => {
                let has_continuation = has_meaningful_stmts_after(&block.stmts, i);
                for branch in &cond.branches {
                    walk_block(&branch.body, !has_continuation, file_id, diagnostics);
                }
            }
            Stmt::Sequence(seq) => {
                let has_continuation = has_meaningful_stmts_after(&block.stmts, i);
                for branch in &seq.branches {
                    walk_block(branch, !has_continuation, file_id, diagnostics);
                }
            }
            Stmt::LabeledBlock(inner) => {
                walk_block(inner, dead_end, file_id, diagnostics);
            }
            _ => {}
        }
    }
}

/// Check if there are meaningful (non-EOL) statements after position `i`.
fn has_meaningful_stmts_after(stmts: &[Stmt], i: usize) -> bool {
    stmts[i + 1..].iter().any(|s| !matches!(s, Stmt::EndOfLine))
}

/// Walk into a choice set's choices and continuation.
fn walk_choice_set(cs: &ChoiceSet, file_id: FileId, diagnostics: &mut Vec<Diagnostic>) {
    for choice in &cs.choices {
        walk_block(&choice.body, false, file_id, diagnostics);
    }
    walk_block(&cs.continuation, false, file_id, diagnostics);
}

/// Check that every choice in the set has an explicit divert in its body.
/// Emit E029 for any choice that doesn't.
fn check_choice_set_diverts(cs: &ChoiceSet, file_id: FileId, diagnostics: &mut Vec<Diagnostic>) {
    for choice in &cs.choices {
        if !choice_has_explicit_divert(choice) {
            diagnostics.push(Diagnostic {
                file: file_id,
                range: choice.ptr.text_range(),
                message: "choice in conditional or sequence must explicitly divert".into(),
                code: DiagnosticCode::E029,
            });
        }
    }
}

/// A choice has an explicit divert if its body contains a `Divert`,
/// `TunnelCall`, or `ThreadStart` statement (at any depth — the divert
/// could be inside nested content).
fn choice_has_explicit_divert(choice: &Choice) -> bool {
    block_has_divert(&choice.body)
}

fn block_has_divert(block: &Block) -> bool {
    block.stmts.iter().any(|stmt| match stmt {
        Stmt::Divert(_) | Stmt::TunnelCall(_) | Stmt::ThreadStart(_) => true,
        Stmt::Conditional(cond) => cond.branches.iter().all(|b| block_has_divert(&b.body)),
        Stmt::LabeledBlock(inner) => block_has_divert(inner),
        _ => false,
    })
}

// ─── Combined node-local / per-block checks (E032, E033, E034) ───────
//
// One shared-visitor traversal drives three checks that the old code ran as
// three separate full walks:
//   - E032: an explicit `~ return` outside a function knot.
//   - E033: the first statement after a terminal (`Divert`/`Return`) in a block.
//   - E034: a choice set consisting entirely of fallback choices.
// Diagnostics are bucketed per check so `validate` can append them in the
// original pass order.

/// Per-block state for the E033 unreachable-after-terminal check. Pushed on
/// `enter_block`, popped on `exit_block`, so nested blocks don't interfere.
#[derive(Default)]
struct UnreachableState {
    saw_terminal: bool,
    flagged: bool,
}

struct StructuralChecks {
    file_id: FileId,
    /// True while inside a function knot's body/stitches — suppresses E032.
    in_function: bool,
    /// Per-block E033 state, one frame per enclosing block.
    unreachable_stack: Vec<UnreachableState>,
    returns: Vec<Diagnostic>,
    unreachable: Vec<Diagnostic>,
    fallbacks: Vec<Diagnostic>,
}

impl StructuralChecks {
    fn new(file_id: FileId) -> Self {
        Self {
            file_id,
            in_function: false,
            unreachable_stack: Vec::new(),
            returns: Vec::new(),
            unreachable: Vec::new(),
            fallbacks: Vec::new(),
        }
    }
}

impl HirVisitor for StructuralChecks {
    fn enter_knot(&mut self, knot: &Knot) {
        // E032 is suppressed inside function knots (bodies and stitches). Knots
        // don't nest, so a single flag reset in exit_knot suffices.
        self.in_function = knot.is_function;
    }

    fn exit_knot(&mut self, _knot: &Knot) {
        self.in_function = false;
    }

    fn enter_block(&mut self, _block: &Block) {
        self.unreachable_stack.push(UnreachableState::default());
    }

    fn exit_block(&mut self, _block: &Block) {
        self.unreachable_stack.pop();
    }

    fn enter_stmt(&mut self, stmt: &Stmt) {
        // E033: the first non-EOL statement after a terminal, per block. Check
        // against the current block's state before updating it, mirroring the
        // old per-block walk order.
        let flag_unreachable = self
            .unreachable_stack
            .last()
            .is_some_and(|s| s.saw_terminal && !s.flagged)
            && !matches!(stmt, Stmt::EndOfLine);
        if flag_unreachable && let Some(range) = stmt_range(stmt) {
            self.unreachable.push(Diagnostic {
                file: self.file_id,
                range,
                message: DiagnosticCode::E033.title().to_string(),
                code: DiagnosticCode::E033,
            });
            if let Some(s) = self.unreachable_stack.last_mut() {
                s.flagged = true;
            }
        }
        // `Divert`/`Return` are terminal; `TunnelCall`/`ThreadStart` are not.
        if matches!(stmt, Stmt::Divert(_) | Stmt::Return(_))
            && let Some(s) = self.unreachable_stack.last_mut()
        {
            s.saw_terminal = true;
        }

        // E032: explicit return (has a syntax ptr — tunnel returns are None)
        // outside a function.
        if let Stmt::Return(ret) = stmt
            && ret.ptr.is_some()
            && !self.in_function
        {
            let range = ret
                .ptr
                .map_or(rowan::TextRange::default(), |p| p.text_range());
            self.returns.push(Diagnostic {
                file: self.file_id,
                range,
                message: DiagnosticCode::E032.title().to_string(),
                code: DiagnosticCode::E032,
            });
        }

        // E034: a choice set that is entirely fallback choices.
        if let Stmt::ChoiceSet(cs) = stmt
            && !cs.choices.is_empty()
            && cs.choices.iter().all(|c| c.is_fallback)
        {
            self.fallbacks.push(Diagnostic {
                file: self.file_id,
                range: cs.choices[0].ptr.text_range(),
                message: DiagnosticCode::E034.title().to_string(),
                code: DiagnosticCode::E034,
            });
        }
    }
}

/// Extract a source range from a statement, if available.
fn stmt_range(stmt: &Stmt) -> Option<rowan::TextRange> {
    match stmt {
        Stmt::Content(c) => c
            .ptr
            .as_ref()
            .map(brink_syntax::ast::SyntaxNodePtr::text_range),
        Stmt::Divert(d) => d
            .ptr
            .as_ref()
            .map(brink_syntax::ast::SyntaxNodePtr::text_range),
        Stmt::TunnelCall(t) => Some(t.ptr.text_range()),
        Stmt::ThreadStart(t) => Some(t.ptr.text_range()),
        Stmt::TempDecl(t) => Some(t.ptr.text_range()),
        Stmt::Assignment(a) => Some(a.ptr.text_range()),
        Stmt::Return(r) => r.ptr.as_ref().map(brink_syntax::ast::AstPtr::text_range),
        Stmt::ChoiceSet(cs) => cs.choices.first().map(|c| c.ptr.text_range()),
        Stmt::Conditional(c) => Some(c.ptr.text_range()),
        Stmt::Sequence(s) => Some(s.ptr.text_range()),
        Stmt::LabeledBlock(b) => b.label.as_ref().map(|l| l.range),
        Stmt::ExprStmt(_) | Stmt::EndOfLine => None,
    }
}

#[cfg(test)]
mod tests {
    use brink_ir::hir::*;
    use brink_ir::{DiagnosticCode, FileId, HirFile};
    use brink_syntax::ast::{self, AstPtr, SyntaxNodePtr};
    use rowan::{TextRange, TextSize};

    use super::*;

    /// Guards the combined `StructuralChecks` pass against the one real risk of
    /// sharing a walker: the shared walk descends inline conditional/sequence
    /// branches inside content (which the old per-check walks never did). By
    /// grammar those branches can hold a divert (always last) but never a
    /// return, a choice set, or a terminal-then-statement — so no new
    /// `E032`/`E033`/`E034` may fire. (Verified: HIR lowering puts the divert
    /// last, e.g. `{cond: -> a text}` lowers to `[Content, Divert]`.)
    #[test]
    fn inline_branch_diverts_produce_no_spurious_structural_diagnostics() {
        let cases = [
            "A {cond: -> away} B\n=== away ===\n-> END\n",
            "{cond: -> a | -> b}\n=== a ===\n-> END\n=== b ===\n-> END\n",
            "{shuffle: -> a | -> b}\n=== a ===\n-> END\n=== b ===\n-> END\n",
            "{cond: -> a text after divert}\n=== a ===\n-> END\n",
            "Line {cond: -> a} {other: -> b}\n=== a ===\n-> END\n=== b ===\n-> END\n",
        ];
        for src in cases {
            let parsed = brink_syntax::parse(src);
            let tree = parsed.tree();
            let (hir, _, _) = brink_ir::hir::lower(FileId(0), &tree);
            let diags = validate(&[(FileId(0), &hir)]);
            let structural: Vec<_> = diags
                .iter()
                .map(|d| d.code)
                .filter(|c| {
                    matches!(
                        c,
                        DiagnosticCode::E032 | DiagnosticCode::E033 | DiagnosticCode::E034
                    )
                })
                .collect();
            assert!(
                structural.is_empty(),
                "inline-branch diverts must not produce structural diagnostics: {src:?} -> {structural:?}"
            );
        }
    }

    fn empty_hir() -> HirFile {
        HirFile {
            root_content: Block::default(),
            knots: Vec::new(),
            variables: Vec::new(),
            constants: Vec::new(),
            lists: Vec::new(),
            externals: Vec::new(),
            includes: Vec::new(),
        }
    }

    fn dummy_range() -> TextRange {
        TextRange::new(TextSize::new(0), TextSize::new(1))
    }

    fn dummy_knot_ptr() -> ContainerPtr {
        ContainerPtr::Knot(AstPtr::from_range(dummy_range()))
    }

    fn dummy_choice_ptr() -> AstPtr<ast::Choice> {
        AstPtr::from_range(dummy_range())
    }

    fn dummy_return_ptr() -> AstPtr<ast::ReturnStmt> {
        AstPtr::from_range(dummy_range())
    }

    // ── E032: return outside function ────────────────────────────

    #[test]
    fn return_in_non_function_emits_e032() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "my_knot".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![Stmt::Return(Return {
                    ptr: Some(dummy_return_ptr()),
                    value: None,
                    onwards_args: Vec::new(),
                })],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        assert_eq!(diags.len(), 1);
        assert_eq!(diags[0].code, DiagnosticCode::E032);
    }

    #[test]
    fn return_in_function_no_error() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "my_func".into(),
                range: dummy_range(),
            },
            is_function: true,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![Stmt::Return(Return {
                    ptr: Some(dummy_return_ptr()),
                    value: Some(Expr::Int(42)),
                    onwards_args: Vec::new(),
                })],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        assert!(
            diags.is_empty(),
            "return in function should not trigger E032: {diags:?}"
        );
    }

    #[test]
    fn tunnel_return_in_non_function_no_error() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "my_knot".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![Stmt::Return(Return {
                    ptr: None, // tunnel return
                    value: None,
                    onwards_args: Vec::new(),
                })],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        assert!(
            diags.is_empty(),
            "tunnel return (ptr=None) should not trigger E032: {diags:?}"
        );
    }

    // ── E033: unreachable code after divert ──────────────────────

    #[test]
    fn content_after_divert_emits_e033() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "test".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![
                    Stmt::Divert(Divert {
                        ptr: None,
                        target: DivertTarget {
                            path: DivertPath::Done,
                            args: Vec::new(),
                        },
                    }),
                    Stmt::Content(Content {
                        ptr: Some(SyntaxNodePtr::from_range(dummy_range())),
                        parts: vec![ContentPart::Text("unreachable".into())],
                        tags: Vec::new(),
                    }),
                ],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        let e033s: Vec<_> = diags
            .iter()
            .filter(|d| d.code == DiagnosticCode::E033)
            .collect();
        assert_eq!(e033s.len(), 1);
    }

    #[test]
    fn eol_after_divert_no_warning() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "test".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![
                    Stmt::Divert(Divert {
                        ptr: None,
                        target: DivertTarget {
                            path: DivertPath::Done,
                            args: Vec::new(),
                        },
                    }),
                    Stmt::EndOfLine,
                ],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        let e033s: Vec<_> = diags
            .iter()
            .filter(|d| d.code == DiagnosticCode::E033)
            .collect();
        assert!(
            e033s.is_empty(),
            "EndOfLine after divert should not trigger E033"
        );
    }

    #[test]
    fn content_after_thread_start_no_warning() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "test".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![
                    Stmt::ThreadStart(ThreadStart {
                        ptr: AstPtr::from_range(dummy_range()),
                        target: DivertTarget {
                            path: DivertPath::Path(Path {
                                segments: vec![Name {
                                    text: "other".into(),
                                    range: dummy_range(),
                                }],
                                range: dummy_range(),
                            }),
                            args: Vec::new(),
                        },
                    }),
                    Stmt::Content(Content {
                        ptr: Some(SyntaxNodePtr::from_range(dummy_range())),
                        parts: vec![ContentPart::Text("still reachable".into())],
                        tags: Vec::new(),
                    }),
                ],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        let e033s: Vec<_> = diags
            .iter()
            .filter(|d| d.code == DiagnosticCode::E033)
            .collect();
        assert!(
            e033s.is_empty(),
            "ThreadStart is not terminal — content after it is reachable"
        );
    }

    #[test]
    fn content_after_tunnel_call_no_warning() {
        // `-> wave ->` returns control to the next statement, so content
        // following a tunnel call is reachable and must not trigger E033.
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "greet".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![
                    Stmt::TunnelCall(TunnelCall {
                        ptr: AstPtr::from_range(dummy_range()),
                        targets: vec![DivertTarget {
                            path: DivertPath::Path(Path {
                                segments: vec![Name {
                                    text: "wave".into(),
                                    range: dummy_range(),
                                }],
                                range: dummy_range(),
                            }),
                            args: Vec::new(),
                        }],
                    }),
                    Stmt::Content(Content {
                        ptr: Some(SyntaxNodePtr::from_range(dummy_range())),
                        parts: vec![ContentPart::Text("and we're off".into())],
                        tags: Vec::new(),
                    }),
                ],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        let e033s: Vec<_> = diags
            .iter()
            .filter(|d| d.code == DiagnosticCode::E033)
            .collect();
        assert!(
            e033s.is_empty(),
            "TunnelCall is not terminal — content after it is reachable: {e033s:?}"
        );
    }

    // ── E034: all-fallback choice set ────────────────────────────

    #[test]
    fn all_fallback_choice_set_emits_e034() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "test".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![Stmt::ChoiceSet(Box::new(ChoiceSet {
                    choices: vec![Choice {
                        ptr: dummy_choice_ptr(),
                        is_sticky: false,
                        is_fallback: true,
                        label: None,
                        condition: None,
                        start_content: None,
                        bracket_content: None,
                        inner_content: None,
                        tags: Vec::new(),
                        body: Block::default(),
                        container_id: None,
                    }],
                    continuation: Block::default(),
                    context: ChoiceSetContext::Weave,
                    depth: 1,
                    gather_id: None,
                }))],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        let e034s: Vec<_> = diags
            .iter()
            .filter(|d| d.code == DiagnosticCode::E034)
            .collect();
        assert_eq!(e034s.len(), 1);
    }

    #[test]
    fn mixed_fallback_and_normal_no_warning() {
        let mut hir = empty_hir();
        hir.knots.push(Knot {
            ptr: dummy_knot_ptr(),
            name: Name {
                text: "test".into(),
                range: dummy_range(),
            },
            is_function: false,
            params: Vec::new(),
            body: Block {
                label: None,
                stmts: vec![Stmt::ChoiceSet(Box::new(ChoiceSet {
                    choices: vec![
                        Choice {
                            ptr: dummy_choice_ptr(),
                            is_sticky: false,
                            is_fallback: true,
                            label: None,
                            condition: None,
                            start_content: None,
                            bracket_content: None,
                            inner_content: None,
                            tags: Vec::new(),
                            body: Block::default(),
                            container_id: None,
                        },
                        Choice {
                            ptr: dummy_choice_ptr(),
                            is_sticky: false,
                            is_fallback: false,
                            label: None,
                            condition: None,
                            start_content: None,
                            bracket_content: None,
                            inner_content: None,
                            tags: Vec::new(),
                            body: Block::default(),
                            container_id: None,
                        },
                    ],
                    continuation: Block::default(),
                    context: ChoiceSetContext::Weave,
                    depth: 1,
                    gather_id: None,
                }))],
                container_id: None,
            },
            stitches: Vec::new(),
        });

        let files = vec![(FileId(0), &hir)];
        let diags = validate(&files);
        let e034s: Vec<_> = diags
            .iter()
            .filter(|d| d.code == DiagnosticCode::E034)
            .collect();
        assert!(e034s.is_empty(), "mixed set should not trigger E034");
    }
}