rs-runec 0.5.0

Compiler, linter, and language server for RuneScript, ClientScript, and GlobalScript, with ClientScript decompilation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
//! Static lint passes complementary to the pointer checker.
//!
//! Each lint:
//!   - consumes the fully-compiled `CompiledScript` objects (read-only),
//!   - emits `Diagnostic`s at `Severity::Warning`,
//!   - never feeds back into codegen or the script writer.
//!
//! Currently included:
//!   1. `check_unused_locals` — any local variable (including parameters)
//!      that is declared/written but never read.
//!   2. `check_unreachable_code` — any source statement whose emitted
//!      instructions are unreachable from node 0 of the CFG.
//!
//! Both lints attach help/suggestion blocks where the fix is mechanical
//! enough to print a before/after diff; otherwise they fall back to a
//! prose message.

use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;

use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
use crate::diagnostics::{
    Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
};
use crate::symbol::LocalEntry;
use crate::types::BaseVarType;

pub fn run_lints(
    scripts: &[CompiledScript],
    source_cache: Option<crate::SourceProvider<'_>>,
) -> DiagnosticsCollector {
    // Each script's two lint passes are independent and their per-script output
    // is deterministic, so fan the scripts out across threads exactly like the
    // other analysis phases (type-check, codegen, pointer-check). `SourceProvider`
    // is `Copy` + `Sync` (it only borrows the source maps), so workers share it
    // freely. `parallel_chunks` hands each worker a contiguous range and joins in
    // input order, so the merged diagnostic stream is byte-identical to the old
    // sequential `for script in scripts` loop.
    let chunk_diags = crate::parallel_chunks(scripts, move |chunk| {
        let mut diags = DiagnosticsCollector::new();
        for script in chunk {
            check_unused_locals(script, source_cache, &mut diags);
            check_unreachable_code(script, source_cache, &mut diags);
        }
        diags
    });
    let mut diags = DiagnosticsCollector::new();
    for d in chunk_diags {
        diags.merge(d);
    }
    diags
}

// ---------------------------------------------------------------------------
// Unused locals
// ---------------------------------------------------------------------------

/// Walk a script's instruction stream, collect per-type read sets for all
/// local opcodes, then cross-reference against `local_table` to find
/// locals that are written or declared but never read. Each unused local
/// gets a warning at its declaration/first-write line.
fn check_unused_locals(
    script: &CompiledScript,
    source_cache: Option<crate::SourceProvider<'_>>,
    diagnostics: &mut DiagnosticsCollector,
) {
    // Per-type slot id -> read? (PushXxxLocal / PushArrayInt).
    let mut int_reads: HashSet<i32> = HashSet::new();
    let mut string_reads: HashSet<i32> = HashSet::new();
    let mut long_reads: HashSet<i32> = HashSet::new();
    // Arrays share one id space; both reads AND writes count as "used".
    let mut array_touched: HashSet<i32> = HashSet::new();

    // Per-type slot id -> source line of the first write (for reporting).
    let mut int_first_write_line: HashMap<i32, usize> = HashMap::new();
    let mut string_first_write_line: HashMap<i32, usize> = HashMap::new();
    let mut long_first_write_line: HashMap<i32, usize> = HashMap::new();
    let mut array_first_def_line: HashMap<i32, usize> = HashMap::new();

    for (i, instr) in script.instructions.iter().enumerate() {
        let id = match &instr.operand {
            Operand::Int(v) => *v,
            _ => continue,
        };
        let line = resolve_line(&script.instructions, i);
        match instr.opcode {
            Opcode::PushIntLocal => {
                int_reads.insert(id);
            }
            Opcode::PopIntLocal => {
                int_first_write_line.entry(id).or_insert(line);
            }
            Opcode::PushStringLocal => {
                string_reads.insert(id);
            }
            Opcode::PopStringLocal => {
                string_first_write_line.entry(id).or_insert(line);
            }
            Opcode::PushLongLocal => {
                long_reads.insert(id);
            }
            Opcode::PopLongLocal => {
                long_first_write_line.entry(id).or_insert(line);
            }
            Opcode::PushArrayInt | Opcode::PopArrayInt => {
                array_touched.insert(id);
            }
            Opcode::DefineArray => {
                array_first_def_line.entry(id).or_insert(line);
            }
            _ => {}
        }
    }

    // The reporting line for an unused *parameter* is its `[trigger,name]`
    // header, which needs an O(file) source scan to locate. Only unused params
    // with no in-body write actually consume it, and those are rare across the
    // corpus, so compute it lazily and memoize per script (`compute_header_line`)
    // rather than scanning every script's source up front. Locals that ARE
    // written report their write line and never touch this.
    let mut header_line_cache: Option<usize> = None;

    // Walk the LocalTable, computing per-type slot ids on the fly using
    // the same counting strategy as `LocalTable::get_variable_id`.
    let mut int_slot_counter: i32 = 0;
    let mut string_slot_counter: i32 = 0;
    let mut long_slot_counter: i32 = 0;
    let mut array_slot_counter: i32 = 0;

    for entry in script.local_table.entries() {
        let LocalEntry {
            name,
            var_type,
            is_param,
            is_array,
        } = entry;
        let is_param = *is_param;
        let is_array = *is_array;
        let suppress = name.starts_with('_');

        if is_array {
            let slot = array_slot_counter;
            array_slot_counter += 1;
            if suppress || array_touched.contains(&slot) {
                continue;
            }
            let line = array_first_def_line.get(&slot).copied().unwrap_or_else(|| {
                *header_line_cache.get_or_insert_with(|| compute_header_line(script, source_cache))
            });
            emit_unused_local(
                script,
                source_cache,
                diagnostics,
                name,
                "array",
                is_param,
                line,
            );
            continue;
        }

        // Parameters claim a slot per base type; locals too. Arrays of a
        // given type also occupy a type slot when they are parameters
        // (matches LocalTable::get_variable_id's `!e.is_array || e.is_param`
        // rule).
        match var_type.base_type() {
            BaseVarType::Integer => {
                let slot = int_slot_counter;
                int_slot_counter += 1;
                if suppress || int_reads.contains(&slot) {
                    continue;
                }
                let line = int_first_write_line.get(&slot).copied().unwrap_or_else(|| {
                    *header_line_cache
                        .get_or_insert_with(|| compute_header_line(script, source_cache))
                });
                emit_unused_local(
                    script,
                    source_cache,
                    diagnostics,
                    name,
                    "int",
                    is_param,
                    line,
                );
            }
            BaseVarType::String => {
                let slot = string_slot_counter;
                string_slot_counter += 1;
                if suppress || string_reads.contains(&slot) {
                    continue;
                }
                let line = string_first_write_line
                    .get(&slot)
                    .copied()
                    .unwrap_or_else(|| {
                        *header_line_cache
                            .get_or_insert_with(|| compute_header_line(script, source_cache))
                    });
                emit_unused_local(
                    script,
                    source_cache,
                    diagnostics,
                    name,
                    "string",
                    is_param,
                    line,
                );
            }
            BaseVarType::Long => {
                let slot = long_slot_counter;
                long_slot_counter += 1;
                if suppress || long_reads.contains(&slot) {
                    continue;
                }
                let line = long_first_write_line
                    .get(&slot)
                    .copied()
                    .unwrap_or_else(|| {
                        *header_line_cache
                            .get_or_insert_with(|| compute_header_line(script, source_cache))
                    });
                emit_unused_local(
                    script,
                    source_cache,
                    diagnostics,
                    name,
                    "long",
                    is_param,
                    line,
                );
            }
        }
    }
}

fn emit_unused_local(
    script: &CompiledScript,
    source_cache: Option<crate::SourceProvider<'_>>,
    diagnostics: &mut DiagnosticsCollector,
    raw_name: &str,
    ty: &str,
    is_param: bool,
    line: usize,
) {
    // `$`-prefixed display name, formatted here (only when a local is actually
    // unused) rather than for every local in the hot walk above.
    let name = format!("${}", raw_name);
    let (message, help_text) = if is_param {
        (
            format!(
                "Parameter `{}` ({}) is declared but never read in this script body.",
                name, ty
            ),
            format!(
                "If `{0}` is intentionally part of the signature (e.g. to \
                 match a label family), prefix its name with an underscore \
                 or remove it from the header if no caller relies on the \
                 position.",
                name
            ),
        )
    } else {
        (
            format!("Local `{}` ({}) is assigned but never read.", name, ty),
            format!(
                "Remove the `def_{}` / assignment, or use `{}` before it \
                 gets overwritten.",
                ty, name
            ),
        )
    };

    // Prose-only help: deleting a local/param without understanding the
    // surrounding intent is rarely safe (callers may depend on
    // parameter position, adjacent statements may have side effects
    // captured through the var). The prose tells the reader what to do;
    // we deliberately don't auto-generate a diff.
    let _ = source_cache;
    let help = Help {
        message: help_text,
        suggestions: Vec::new(),
        applicability: Applicability::MaybeIncorrect,
    };

    let mut diag = Diagnostic {
        file: PathBuf::from(&script.source_path),
        line,
        column: 0,
        message,
        severity: Severity::Warning,
        phase: Phase::PointerCheck, // reused — see main.rs note on Phase
        help: Vec::new(),
    };
    diag.help.push(help);
    diagnostics.add(diag);
}

// ---------------------------------------------------------------------------
// Unreachable code
// ---------------------------------------------------------------------------

/// Build a minimal CFG (reachability-only) and flag any LineNumber whose
/// following instruction is not reachable from the script entry. Compiler-
/// emitted fallthroughs (e.g. the always-emitted `Branch(end)` after a
/// Jump-terminated if body) have no preceding LineNumber and so never
/// trigger a false positive.
fn check_unreachable_code(
    script: &CompiledScript,
    source_cache: Option<crate::SourceProvider<'_>>,
    diagnostics: &mut DiagnosticsCollector,
) {
    let instrs = &script.instructions;
    if instrs.is_empty() {
        return;
    }

    // Skip LineNumbers when assigning node ids — they are diagnostic
    // markers, not control-flow points. `instr_to_node` is indexed directly by
    // instruction position (dense, 0..len) with `u32::MAX` as the "not a node"
    // sentinel — a flat Vec rather than a HashMap, since the keys are dense and
    // this is the hot lookup in `resolve_target`.
    let mut instr_to_node: Vec<u32> = vec![u32::MAX; instrs.len()];
    let mut node_instr: Vec<usize> = Vec::new();
    for (i, instr) in instrs.iter().enumerate() {
        if instr.opcode == Opcode::LineNumber {
            continue;
        }
        instr_to_node[i] = node_instr.len() as u32;
        node_instr.push(i);
    }
    if node_instr.is_empty() {
        return;
    }

    // Forward reachability BFS from node 0. Successors are computed on the fly
    // from each node's instruction (fallthrough by default; branch/switch add
    // target edges; unconditional terminals suppress fallthrough) instead of
    // being materialized into a `Vec<Vec<usize>>` adjacency. That adjacency
    // allocated one heap Vec per node — hundreds of thousands across the corpus —
    // for a graph traversed exactly once; the reachable set is identical without
    // it. Nodes are marked reachable at discovery (push) time, so each is popped
    // and expanded at most once, matching the original two-phase build+BFS.
    let mut reachable = vec![false; node_instr.len()];
    reachable[0] = true;
    let mut queue: VecDeque<usize> = VecDeque::from([0]);
    while let Some(order_idx) = queue.pop_front() {
        let instr = &instrs[node_instr[order_idx]];

        let is_terminal = matches!(
            instr.opcode,
            Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
        );

        // Branch / switch target edges.
        match instr.opcode {
            Opcode::Branch
            | Opcode::BranchNot
            | Opcode::BranchEquals
            | Opcode::BranchLessThan
            | Opcode::BranchGreaterThan
            | Opcode::BranchLessThanOrEquals
            | Opcode::BranchGreaterThanOrEquals
            | Opcode::LongBranchNot
            | Opcode::LongBranchEquals
            | Opcode::LongBranchLessThan
            | Opcode::LongBranchGreaterThan
            | Opcode::LongBranchLessThanOrEquals
            | Opcode::LongBranchGreaterThanOrEquals
            | Opcode::ObjBranchEquals
            | Opcode::ObjBranchNot
            | Opcode::BranchIfTrue
            | Opcode::BranchIfFalse => {
                if let Operand::JumpTarget(target) = &instr.operand
                    && let Some(tnode) = resolve_target(*target, instrs, &instr_to_node)
                    && !reachable[tnode]
                {
                    reachable[tnode] = true;
                    queue.push_back(tnode);
                }
            }
            Opcode::Switch => {
                if let Operand::SwitchTable(tbl_idx) = &instr.operand {
                    let cases = &script.switch_tables[*tbl_idx as usize];
                    for &(_, target) in cases.iter() {
                        if let Some(tnode) = resolve_target(target, instrs, &instr_to_node)
                            && !reachable[tnode]
                        {
                            reachable[tnode] = true;
                            queue.push_back(tnode);
                        }
                    }
                }
            }
            _ => {}
        }

        // Fallthrough edge for non-terminals.
        if !is_terminal && order_idx + 1 < node_instr.len() {
            let m = order_idx + 1;
            if !reachable[m] {
                reachable[m] = true;
                queue.push_back(m);
            }
        }
    }

    // Walk LineNumbers; for each, find the first following non-LineNumber
    // instruction and check reachability. Dedupe by source line.
    let mut reported_lines: HashSet<usize> = HashSet::new();
    for (i, instr) in instrs.iter().enumerate() {
        let line = match (instr.opcode, &instr.operand) {
            (Opcode::LineNumber, Operand::Int(n)) => *n as usize,
            _ => continue,
        };
        let mut j = i + 1;
        let tnode = loop {
            if j >= instrs.len() {
                break None;
            }
            if instrs[j].opcode != Opcode::LineNumber {
                let n = instr_to_node[j];
                break if n == u32::MAX {
                    None
                } else {
                    Some(n as usize)
                };
            }
            j += 1;
        };
        let tnode = match tnode {
            Some(n) => n,
            None => continue,
        };
        if reachable[tnode] {
            continue;
        }
        if !reported_lines.insert(line) {
            continue;
        }
        emit_unreachable(script, source_cache, diagnostics, line);
    }
}

fn emit_unreachable(
    script: &CompiledScript,
    source_cache: Option<crate::SourceProvider<'_>>,
    diagnostics: &mut DiagnosticsCollector,
    line: usize,
) {
    let message = "Unreachable code: this line cannot be executed because control \
         flow never reaches it (a preceding `return`, `@jump`, or \
         unconditional branch prevents fallthrough)."
        .to_string();

    let mut suggestions: Vec<Suggestion> = Vec::new();
    if let Some(cache) = source_cache
        && let Some(src) = cache.get(&script.source_path)
        && nth_source_line(&src, line).is_some()
    {
        suggestions.push(Suggestion {
            file: PathBuf::from(&script.source_path),
            line_range: (line, line),
            replacement: String::new(), // recommend removal
            label: Some("remove the unreachable statement".to_string()),
        });
    }

    let help = Help {
        message: "Remove the dead statement, or move it before the \
                  preceding terminal instruction if it was meant to run."
            .to_string(),
        suggestions,
        applicability: Applicability::MaybeIncorrect,
    };

    let mut diag = Diagnostic {
        file: PathBuf::from(&script.source_path),
        line,
        column: 0,
        message,
        severity: Severity::Warning,
        phase: Phase::PointerCheck,
        help: Vec::new(),
    };
    diag.help.push(help);
    diagnostics.add(diag);
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
    for i in (0..=instr_idx).rev() {
        if instructions[i].opcode == Opcode::LineNumber
            && let Operand::Int(line) = instructions[i].operand
        {
            return line as usize;
        }
    }
    0
}

fn nth_source_line(src: &str, line_no: usize) -> Option<&str> {
    if line_no == 0 {
        return None;
    }
    src.lines().nth(line_no - 1)
}

fn resolve_target(
    mut target: usize,
    instrs: &[Instruction],
    instr_to_node: &[u32],
) -> Option<usize> {
    while target < instrs.len() && instrs[target].opcode == Opcode::LineNumber {
        target += 1;
    }
    if target < instrs.len() {
        let n = instr_to_node[target];
        if n != u32::MAX {
            return Some(n as usize);
        }
    }
    None
}

/// The 1-indexed source line an unused *parameter* is reported at: the script's
/// `[trigger,name]` header, falling back to the line just before the first body
/// statement when the source can't be read. Invoked lazily by
/// `check_unused_locals` — only when a script actually has an unused parameter —
/// because the `find_header_line` scan is O(file) and almost never needed.
fn compute_header_line(
    script: &CompiledScript,
    source_cache: Option<crate::SourceProvider<'_>>,
) -> usize {
    let short_name = script
        .name
        .trim_start_matches('[')
        .trim_end_matches(']')
        .split_once(',')
        .map(|(_, n)| n)
        .unwrap_or(script.name.as_str());
    let first_body_line = script
        .instructions
        .iter()
        .find_map(|i| match (i.opcode, &i.operand) {
            (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
            _ => None,
        })
        .unwrap_or(1);
    source_cache
        .and_then(|c| c.get(&script.source_path))
        .and_then(|src| find_header_line(&src, &script.trigger, short_name))
        .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1))
}

/// Locate the 1-indexed line that declares `[<trigger>,<name>]` in `src`.
/// Mirrors the pointer_checker helper so this module stays self-contained.
fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
    let prefix = format!("[{},{}]", trigger, name);
    let prefix_with_params = format!("[{},{}](", trigger, name);
    for (i, line) in src.lines().enumerate() {
        let trimmed = line.trim_start();
        if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
            return Some(i + 1);
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bytecode::{Instruction, Opcode, Operand};
    use crate::symbol::LocalEntry;
    use crate::types::Type;

    fn empty_script(name: &str) -> CompiledScript {
        let mut s = CompiledScript::new(format!("[label,{}]", name), 0);
        s.trigger = "label".to_string();
        s.source_path = "/virt/test.rs2".to_string();
        s
    }

    fn push_local_entry(
        s: &mut CompiledScript,
        name: &str,
        var_type: Type,
        is_param: bool,
        is_array: bool,
    ) {
        s.local_table.all.push(LocalEntry {
            name: name.to_string(),
            var_type,
            is_param,
            is_array,
        });
    }

    // -----------------------------------------------------------------------
    // Unused locals
    // -----------------------------------------------------------------------

    #[test]
    fn unused_int_local_is_reported() {
        // Body: def_int $x = 5;   (written, never read)
        let mut script = empty_script("foo");
        push_local_entry(&mut script, "x", Type::Int, false, false);
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
            Instruction::push_int(5),
            Instruction::pop_int_local(0),
            Instruction::simple(Opcode::Return),
        ];

        let scripts = [script];
        let mut diags = DiagnosticsCollector::new();
        check_unused_locals(&scripts[0], None, &mut diags);

        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 1, "expected one unused-local warning");
        assert!(
            warnings[0].message.contains("$x"),
            "message should name $x: {}",
            warnings[0].message
        );
        assert_eq!(warnings[0].line, 2);
    }

    #[test]
    fn read_then_written_int_local_is_ok() {
        // def_int $x = 5; def_int $y = $x;   (x is read, y is not — y warns)
        let mut script = empty_script("foo");
        push_local_entry(&mut script, "x", Type::Int, false, false);
        push_local_entry(&mut script, "y", Type::Int, false, false);
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
            Instruction::push_int(5),
            Instruction::pop_int_local(0),
            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
            Instruction::push_int_local(0), // read of $x
            Instruction::pop_int_local(1),  // write to $y
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unused_locals(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 1, "only $y should warn");
        assert!(warnings[0].message.contains("$y"));
    }

    #[test]
    fn unused_parameter_is_reported_with_param_wording() {
        let mut script = empty_script("foo");
        script.trigger = "label".to_string();
        push_local_entry(&mut script, "unused", Type::Int, true, false);
        script.int_arg_count = 1;
        script.int_local_count = 1;
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unused_locals(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 1);
        assert!(
            warnings[0].message.contains("Parameter"),
            "message should use parameter wording: {}",
            warnings[0].message
        );
    }

    #[test]
    fn string_and_long_locals_tracked_independently() {
        let mut script = empty_script("foo");
        push_local_entry(&mut script, "s", Type::String, false, false);
        push_local_entry(&mut script, "l", Type::Long, false, false);
        let hi = script.intern_str("hi".to_string());
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
            Instruction::new(Opcode::PushConstantString, Operand::Str(hi)),
            Instruction::pop_string_local(0),
            Instruction::push_long(42),
            Instruction::pop_long_local(0),
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unused_locals(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 2, "both $s and $l should warn");
        let names: Vec<&str> = warnings.iter().map(|d| d.message.as_str()).collect();
        assert!(names.iter().any(|m| m.contains("$s")));
        assert!(names.iter().any(|m| m.contains("$l")));
    }

    #[test]
    fn unused_array_is_reported() {
        let mut script = empty_script("foo");
        push_local_entry(&mut script, "arr", Type::Int, false, true);
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
            Instruction::push_int(5),
            Instruction::new(Opcode::DefineArray, Operand::Int(0)),
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unused_locals(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].message.contains("$arr"));
        assert!(warnings[0].message.contains("array"));
    }

    #[test]
    fn touched_array_does_not_warn() {
        // def_int $arr(3); $arr(0) = 1; read $arr(0) — array IS used.
        let mut script = empty_script("foo");
        push_local_entry(&mut script, "arr", Type::Int, false, true);
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
            Instruction::push_int(3),
            Instruction::new(Opcode::DefineArray, Operand::Int(0)),
            Instruction::push_int(1),
            Instruction::push_int(0),
            Instruction::new(Opcode::PopArrayInt, Operand::Int(0)),
            Instruction::push_int(0),
            Instruction::new(Opcode::PushArrayInt, Operand::Int(0)),
            Instruction::new(Opcode::PopIntDiscard, Operand::Int(0)),
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unused_locals(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 0, "touched array should not warn");
    }

    // -----------------------------------------------------------------------
    // Unreachable code
    // -----------------------------------------------------------------------

    #[test]
    fn dead_code_after_return_is_reported() {
        // mes("hi"); return; mes("bye");  <-- line 4 unreachable
        let mut script = empty_script("foo");
        let hi = script.intern_str("hi".to_string());
        let bye = script.intern_str("bye".to_string());
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
            Instruction::new(Opcode::PushConstantString, Operand::Str(hi)),
            Instruction::new(Opcode::Command, Operand::Int(0)), // mes
            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
            Instruction::simple(Opcode::Return),
            Instruction::new(Opcode::LineNumber, Operand::Int(4)),
            Instruction::new(Opcode::PushConstantString, Operand::Str(bye)),
            Instruction::new(Opcode::Command, Operand::Int(0)),
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unreachable_code(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].line, 4);
        assert!(warnings[0].message.contains("Unreachable"));
    }

    #[test]
    fn dead_code_after_jump_is_reported() {
        // @some_label; mes("never");
        let mut script = empty_script("foo");
        let never = script.intern_str("never".to_string());
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
            Instruction::new(Opcode::JumpWithParams, Operand::Int(999)),
            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
            Instruction::new(Opcode::PushConstantString, Operand::Str(never)),
            Instruction::new(Opcode::Command, Operand::Int(0)),
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unreachable_code(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0].line, 3);
    }

    #[test]
    fn reachable_code_after_conditional_branch_is_ok() {
        // if (cond) { body } — body IS reachable via BranchEquals target.
        let mut script = empty_script("foo");
        let yes = script.intern_str("yes".to_string());
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
            Instruction::push_int(1),
            Instruction::push_int(1),
            Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(6)),
            Instruction::new(Opcode::Branch, Operand::JumpTarget(9)),
            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
            Instruction::new(Opcode::PushConstantString, Operand::Str(yes)),
            Instruction::new(Opcode::Command, Operand::Int(0)),
            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unreachable_code(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(
            warnings.len(),
            0,
            "conditional-branch body is reachable; got: {:?}",
            warnings.iter().map(|d| &d.message).collect::<Vec<_>>()
        );
    }

    #[test]
    fn compiler_emitted_branch_without_linenumber_does_not_warn() {
        // Simulates compile_if's always-emitted Branch(end) after a body
        // that ends in Return. The Branch has NO leading LineNumber, so
        // our lint should skip it.
        let mut script = empty_script("foo");
        script.instructions = vec![
            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
            Instruction::push_int(1),
            Instruction::push_int(1),
            Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(5)),
            Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
            Instruction::simple(Opcode::Return),
            Instruction::new(Opcode::Branch, Operand::JumpTarget(8)), // compiler-emitted, unreachable
            Instruction::simple(Opcode::Return),
        ];

        let mut diags = DiagnosticsCollector::new();
        check_unreachable_code(&script, None, &mut diags);
        let warnings: Vec<_> = diags
            .diagnostics()
            .iter()
            .filter(|d| d.severity == Severity::Warning)
            .collect();
        assert_eq!(
            warnings.len(),
            0,
            "compiler-emitted unreachable Branch must not warn; got: {:?}",
            warnings.iter().map(|d| &d.message).collect::<Vec<_>>()
        );
    }
}