Skip to main content

runec/
lints.rs

1//! Static lint passes complementary to the pointer checker.
2//!
3//! Each lint:
4//!   - consumes the fully-compiled `CompiledScript` objects (read-only),
5//!   - emits `Diagnostic`s at `Severity::Warning`,
6//!   - never feeds back into codegen or the script writer.
7//!
8//! Currently included:
9//!   1. `check_unused_locals` — any local variable (including parameters)
10//!      that is declared/written but never read.
11//!   2. `check_unreachable_code` — any source statement whose emitted
12//!      instructions are unreachable from node 0 of the CFG.
13//!
14//! Both lints attach help/suggestion blocks where the fix is mechanical
15//! enough to print a before/after diff; otherwise they fall back to a
16//! prose message.
17
18use std::collections::{HashMap, HashSet, VecDeque};
19use std::path::PathBuf;
20
21use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
22use crate::diagnostics::{
23    Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
24};
25use crate::symbol::LocalEntry;
26use crate::types::BaseVarType;
27
28pub fn run_lints(
29    scripts: &[CompiledScript],
30    source_cache: Option<crate::SourceProvider<'_>>,
31) -> DiagnosticsCollector {
32    // Each script's two lint passes are independent and their per-script output
33    // is deterministic, so fan the scripts out across threads exactly like the
34    // other analysis phases (type-check, codegen, pointer-check). `SourceProvider`
35    // is `Copy` + `Sync` (it only borrows the source maps), so workers share it
36    // freely. `parallel_chunks` hands each worker a contiguous range and joins in
37    // input order, so the merged diagnostic stream is byte-identical to the old
38    // sequential `for script in scripts` loop.
39    let chunk_diags = crate::parallel_chunks(scripts, move |chunk| {
40        let mut diags = DiagnosticsCollector::new();
41        for script in chunk {
42            check_unused_locals(script, source_cache, &mut diags);
43            check_unreachable_code(script, source_cache, &mut diags);
44        }
45        diags
46    });
47    let mut diags = DiagnosticsCollector::new();
48    for d in chunk_diags {
49        diags.merge(d);
50    }
51    diags
52}
53
54// ---------------------------------------------------------------------------
55// Unused locals
56// ---------------------------------------------------------------------------
57
58/// Walk a script's instruction stream, collect per-type read sets for all
59/// local opcodes, then cross-reference against `local_table` to find
60/// locals that are written or declared but never read. Each unused local
61/// gets a warning at its declaration/first-write line.
62fn check_unused_locals(
63    script: &CompiledScript,
64    source_cache: Option<crate::SourceProvider<'_>>,
65    diagnostics: &mut DiagnosticsCollector,
66) {
67    // Per-type slot id -> read? (PushXxxLocal / PushArrayInt).
68    let mut int_reads: HashSet<i32> = HashSet::new();
69    let mut string_reads: HashSet<i32> = HashSet::new();
70    let mut long_reads: HashSet<i32> = HashSet::new();
71    // Arrays share one id space; both reads AND writes count as "used".
72    let mut array_touched: HashSet<i32> = HashSet::new();
73
74    // Per-type slot id -> source line of the first write (for reporting).
75    let mut int_first_write_line: HashMap<i32, usize> = HashMap::new();
76    let mut string_first_write_line: HashMap<i32, usize> = HashMap::new();
77    let mut long_first_write_line: HashMap<i32, usize> = HashMap::new();
78    let mut array_first_def_line: HashMap<i32, usize> = HashMap::new();
79
80    for (i, instr) in script.instructions.iter().enumerate() {
81        let id = match &instr.operand {
82            Operand::Int(v) => *v,
83            _ => continue,
84        };
85        let line = resolve_line(&script.instructions, i);
86        match instr.opcode {
87            Opcode::PushIntLocal => {
88                int_reads.insert(id);
89            }
90            Opcode::PopIntLocal => {
91                int_first_write_line.entry(id).or_insert(line);
92            }
93            Opcode::PushStringLocal => {
94                string_reads.insert(id);
95            }
96            Opcode::PopStringLocal => {
97                string_first_write_line.entry(id).or_insert(line);
98            }
99            Opcode::PushLongLocal => {
100                long_reads.insert(id);
101            }
102            Opcode::PopLongLocal => {
103                long_first_write_line.entry(id).or_insert(line);
104            }
105            Opcode::PushArrayInt | Opcode::PopArrayInt => {
106                array_touched.insert(id);
107            }
108            Opcode::DefineArray => {
109                array_first_def_line.entry(id).or_insert(line);
110            }
111            _ => {}
112        }
113    }
114
115    // The reporting line for an unused *parameter* is its `[trigger,name]`
116    // header, which needs an O(file) source scan to locate. Only unused params
117    // with no in-body write actually consume it, and those are rare across the
118    // corpus, so compute it lazily and memoize per script (`compute_header_line`)
119    // rather than scanning every script's source up front. Locals that ARE
120    // written report their write line and never touch this.
121    let mut header_line_cache: Option<usize> = None;
122
123    // Walk the LocalTable, computing per-type slot ids on the fly using
124    // the same counting strategy as `LocalTable::get_variable_id`.
125    let mut int_slot_counter: i32 = 0;
126    let mut string_slot_counter: i32 = 0;
127    let mut long_slot_counter: i32 = 0;
128    let mut array_slot_counter: i32 = 0;
129
130    for entry in script.local_table.entries() {
131        let LocalEntry {
132            name,
133            var_type,
134            is_param,
135            is_array,
136        } = entry;
137        let is_param = *is_param;
138        let is_array = *is_array;
139        let suppress = name.starts_with('_');
140
141        if is_array {
142            let slot = array_slot_counter;
143            array_slot_counter += 1;
144            if suppress || array_touched.contains(&slot) {
145                continue;
146            }
147            let line = array_first_def_line.get(&slot).copied().unwrap_or_else(|| {
148                *header_line_cache.get_or_insert_with(|| compute_header_line(script, source_cache))
149            });
150            emit_unused_local(
151                script,
152                source_cache,
153                diagnostics,
154                name,
155                "array",
156                is_param,
157                line,
158            );
159            continue;
160        }
161
162        // Parameters claim a slot per base type; locals too. Arrays of a
163        // given type also occupy a type slot when they are parameters
164        // (matches LocalTable::get_variable_id's `!e.is_array || e.is_param`
165        // rule).
166        match var_type.base_type() {
167            BaseVarType::Integer => {
168                let slot = int_slot_counter;
169                int_slot_counter += 1;
170                if suppress || int_reads.contains(&slot) {
171                    continue;
172                }
173                let line = int_first_write_line.get(&slot).copied().unwrap_or_else(|| {
174                    *header_line_cache
175                        .get_or_insert_with(|| compute_header_line(script, source_cache))
176                });
177                emit_unused_local(
178                    script,
179                    source_cache,
180                    diagnostics,
181                    name,
182                    "int",
183                    is_param,
184                    line,
185                );
186            }
187            BaseVarType::String => {
188                let slot = string_slot_counter;
189                string_slot_counter += 1;
190                if suppress || string_reads.contains(&slot) {
191                    continue;
192                }
193                let line = string_first_write_line
194                    .get(&slot)
195                    .copied()
196                    .unwrap_or_else(|| {
197                        *header_line_cache
198                            .get_or_insert_with(|| compute_header_line(script, source_cache))
199                    });
200                emit_unused_local(
201                    script,
202                    source_cache,
203                    diagnostics,
204                    name,
205                    "string",
206                    is_param,
207                    line,
208                );
209            }
210            BaseVarType::Long => {
211                let slot = long_slot_counter;
212                long_slot_counter += 1;
213                if suppress || long_reads.contains(&slot) {
214                    continue;
215                }
216                let line = long_first_write_line
217                    .get(&slot)
218                    .copied()
219                    .unwrap_or_else(|| {
220                        *header_line_cache
221                            .get_or_insert_with(|| compute_header_line(script, source_cache))
222                    });
223                emit_unused_local(
224                    script,
225                    source_cache,
226                    diagnostics,
227                    name,
228                    "long",
229                    is_param,
230                    line,
231                );
232            }
233        }
234    }
235}
236
237fn emit_unused_local(
238    script: &CompiledScript,
239    source_cache: Option<crate::SourceProvider<'_>>,
240    diagnostics: &mut DiagnosticsCollector,
241    raw_name: &str,
242    ty: &str,
243    is_param: bool,
244    line: usize,
245) {
246    // `$`-prefixed display name, formatted here (only when a local is actually
247    // unused) rather than for every local in the hot walk above.
248    let name = format!("${}", raw_name);
249    let (message, help_text) = if is_param {
250        (
251            format!(
252                "Parameter `{}` ({}) is declared but never read in this script body.",
253                name, ty
254            ),
255            format!(
256                "If `{0}` is intentionally part of the signature (e.g. to \
257                 match a label family), prefix its name with an underscore \
258                 or remove it from the header if no caller relies on the \
259                 position.",
260                name
261            ),
262        )
263    } else {
264        (
265            format!("Local `{}` ({}) is assigned but never read.", name, ty),
266            format!(
267                "Remove the `def_{}` / assignment, or use `{}` before it \
268                 gets overwritten.",
269                ty, name
270            ),
271        )
272    };
273
274    // Prose-only help: deleting a local/param without understanding the
275    // surrounding intent is rarely safe (callers may depend on
276    // parameter position, adjacent statements may have side effects
277    // captured through the var). The prose tells the reader what to do;
278    // we deliberately don't auto-generate a diff.
279    let _ = source_cache;
280    let help = Help {
281        message: help_text,
282        suggestions: Vec::new(),
283        applicability: Applicability::MaybeIncorrect,
284    };
285
286    let mut diag = Diagnostic {
287        file: PathBuf::from(&script.source_path),
288        line,
289        column: 0,
290        message,
291        severity: Severity::Warning,
292        phase: Phase::PointerCheck, // reused — see main.rs note on Phase
293        help: Vec::new(),
294    };
295    diag.help.push(help);
296    diagnostics.add(diag);
297}
298
299// ---------------------------------------------------------------------------
300// Unreachable code
301// ---------------------------------------------------------------------------
302
303/// Build a minimal CFG (reachability-only) and flag any LineNumber whose
304/// following instruction is not reachable from the script entry. Compiler-
305/// emitted fallthroughs (e.g. the always-emitted `Branch(end)` after a
306/// Jump-terminated if body) have no preceding LineNumber and so never
307/// trigger a false positive.
308fn check_unreachable_code(
309    script: &CompiledScript,
310    source_cache: Option<crate::SourceProvider<'_>>,
311    diagnostics: &mut DiagnosticsCollector,
312) {
313    let instrs = &script.instructions;
314    if instrs.is_empty() {
315        return;
316    }
317
318    // Skip LineNumbers when assigning node ids — they are diagnostic
319    // markers, not control-flow points. `instr_to_node` is indexed directly by
320    // instruction position (dense, 0..len) with `u32::MAX` as the "not a node"
321    // sentinel — a flat Vec rather than a HashMap, since the keys are dense and
322    // this is the hot lookup in `resolve_target`.
323    let mut instr_to_node: Vec<u32> = vec![u32::MAX; instrs.len()];
324    let mut node_instr: Vec<usize> = Vec::new();
325    for (i, instr) in instrs.iter().enumerate() {
326        if instr.opcode == Opcode::LineNumber {
327            continue;
328        }
329        instr_to_node[i] = node_instr.len() as u32;
330        node_instr.push(i);
331    }
332    if node_instr.is_empty() {
333        return;
334    }
335
336    // Forward reachability BFS from node 0. Successors are computed on the fly
337    // from each node's instruction (fallthrough by default; branch/switch add
338    // target edges; unconditional terminals suppress fallthrough) instead of
339    // being materialized into a `Vec<Vec<usize>>` adjacency. That adjacency
340    // allocated one heap Vec per node — hundreds of thousands across the corpus —
341    // for a graph traversed exactly once; the reachable set is identical without
342    // it. Nodes are marked reachable at discovery (push) time, so each is popped
343    // and expanded at most once, matching the original two-phase build+BFS.
344    let mut reachable = vec![false; node_instr.len()];
345    reachable[0] = true;
346    let mut queue: VecDeque<usize> = VecDeque::from([0]);
347    while let Some(order_idx) = queue.pop_front() {
348        let instr = &instrs[node_instr[order_idx]];
349
350        let is_terminal = matches!(
351            instr.opcode,
352            Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
353        );
354
355        // Branch / switch target edges.
356        match instr.opcode {
357            Opcode::Branch
358            | Opcode::BranchNot
359            | Opcode::BranchEquals
360            | Opcode::BranchLessThan
361            | Opcode::BranchGreaterThan
362            | Opcode::BranchLessThanOrEquals
363            | Opcode::BranchGreaterThanOrEquals
364            | Opcode::LongBranchNot
365            | Opcode::LongBranchEquals
366            | Opcode::LongBranchLessThan
367            | Opcode::LongBranchGreaterThan
368            | Opcode::LongBranchLessThanOrEquals
369            | Opcode::LongBranchGreaterThanOrEquals
370            | Opcode::ObjBranchEquals
371            | Opcode::ObjBranchNot
372            | Opcode::BranchIfTrue
373            | Opcode::BranchIfFalse => {
374                if let Operand::JumpTarget(target) = &instr.operand
375                    && let Some(tnode) = resolve_target(*target, instrs, &instr_to_node)
376                    && !reachable[tnode]
377                {
378                    reachable[tnode] = true;
379                    queue.push_back(tnode);
380                }
381            }
382            Opcode::Switch => {
383                if let Operand::SwitchTable(tbl_idx) = &instr.operand {
384                    let cases = &script.switch_tables[*tbl_idx as usize];
385                    for &(_, target) in cases.iter() {
386                        if let Some(tnode) = resolve_target(target, instrs, &instr_to_node)
387                            && !reachable[tnode]
388                        {
389                            reachable[tnode] = true;
390                            queue.push_back(tnode);
391                        }
392                    }
393                }
394            }
395            _ => {}
396        }
397
398        // Fallthrough edge for non-terminals.
399        if !is_terminal && order_idx + 1 < node_instr.len() {
400            let m = order_idx + 1;
401            if !reachable[m] {
402                reachable[m] = true;
403                queue.push_back(m);
404            }
405        }
406    }
407
408    // Walk LineNumbers; for each, find the first following non-LineNumber
409    // instruction and check reachability. Dedupe by source line.
410    let mut reported_lines: HashSet<usize> = HashSet::new();
411    for (i, instr) in instrs.iter().enumerate() {
412        let line = match (instr.opcode, &instr.operand) {
413            (Opcode::LineNumber, Operand::Int(n)) => *n as usize,
414            _ => continue,
415        };
416        let mut j = i + 1;
417        let tnode = loop {
418            if j >= instrs.len() {
419                break None;
420            }
421            if instrs[j].opcode != Opcode::LineNumber {
422                let n = instr_to_node[j];
423                break if n == u32::MAX {
424                    None
425                } else {
426                    Some(n as usize)
427                };
428            }
429            j += 1;
430        };
431        let tnode = match tnode {
432            Some(n) => n,
433            None => continue,
434        };
435        if reachable[tnode] {
436            continue;
437        }
438        if !reported_lines.insert(line) {
439            continue;
440        }
441        emit_unreachable(script, source_cache, diagnostics, line);
442    }
443}
444
445fn emit_unreachable(
446    script: &CompiledScript,
447    source_cache: Option<crate::SourceProvider<'_>>,
448    diagnostics: &mut DiagnosticsCollector,
449    line: usize,
450) {
451    let message = "Unreachable code: this line cannot be executed because control \
452         flow never reaches it (a preceding `return`, `@jump`, or \
453         unconditional branch prevents fallthrough)."
454        .to_string();
455
456    let mut suggestions: Vec<Suggestion> = Vec::new();
457    if let Some(cache) = source_cache
458        && let Some(src) = cache.get(&script.source_path)
459        && nth_source_line(&src, line).is_some()
460    {
461        suggestions.push(Suggestion {
462            file: PathBuf::from(&script.source_path),
463            line_range: (line, line),
464            replacement: String::new(), // recommend removal
465            label: Some("remove the unreachable statement".to_string()),
466        });
467    }
468
469    let help = Help {
470        message: "Remove the dead statement, or move it before the \
471                  preceding terminal instruction if it was meant to run."
472            .to_string(),
473        suggestions,
474        applicability: Applicability::MaybeIncorrect,
475    };
476
477    let mut diag = Diagnostic {
478        file: PathBuf::from(&script.source_path),
479        line,
480        column: 0,
481        message,
482        severity: Severity::Warning,
483        phase: Phase::PointerCheck,
484        help: Vec::new(),
485    };
486    diag.help.push(help);
487    diagnostics.add(diag);
488}
489
490// ---------------------------------------------------------------------------
491// Shared helpers
492// ---------------------------------------------------------------------------
493
494fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
495    for i in (0..=instr_idx).rev() {
496        if instructions[i].opcode == Opcode::LineNumber
497            && let Operand::Int(line) = instructions[i].operand
498        {
499            return line as usize;
500        }
501    }
502    0
503}
504
505fn nth_source_line(src: &str, line_no: usize) -> Option<&str> {
506    if line_no == 0 {
507        return None;
508    }
509    src.lines().nth(line_no - 1)
510}
511
512fn resolve_target(
513    mut target: usize,
514    instrs: &[Instruction],
515    instr_to_node: &[u32],
516) -> Option<usize> {
517    while target < instrs.len() && instrs[target].opcode == Opcode::LineNumber {
518        target += 1;
519    }
520    if target < instrs.len() {
521        let n = instr_to_node[target];
522        if n != u32::MAX {
523            return Some(n as usize);
524        }
525    }
526    None
527}
528
529/// The 1-indexed source line an unused *parameter* is reported at: the script's
530/// `[trigger,name]` header, falling back to the line just before the first body
531/// statement when the source can't be read. Invoked lazily by
532/// `check_unused_locals` — only when a script actually has an unused parameter —
533/// because the `find_header_line` scan is O(file) and almost never needed.
534fn compute_header_line(
535    script: &CompiledScript,
536    source_cache: Option<crate::SourceProvider<'_>>,
537) -> usize {
538    let short_name = script
539        .name
540        .trim_start_matches('[')
541        .trim_end_matches(']')
542        .split_once(',')
543        .map(|(_, n)| n)
544        .unwrap_or(script.name.as_str());
545    let first_body_line = script
546        .instructions
547        .iter()
548        .find_map(|i| match (i.opcode, &i.operand) {
549            (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
550            _ => None,
551        })
552        .unwrap_or(1);
553    source_cache
554        .and_then(|c| c.get(&script.source_path))
555        .and_then(|src| find_header_line(&src, &script.trigger, short_name))
556        .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1))
557}
558
559/// Locate the 1-indexed line that declares `[<trigger>,<name>]` in `src`.
560/// Mirrors the pointer_checker helper so this module stays self-contained.
561fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
562    let prefix = format!("[{},{}]", trigger, name);
563    let prefix_with_params = format!("[{},{}](", trigger, name);
564    for (i, line) in src.lines().enumerate() {
565        let trimmed = line.trim_start();
566        if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
567            return Some(i + 1);
568        }
569    }
570    None
571}
572
573// ---------------------------------------------------------------------------
574// Tests
575// ---------------------------------------------------------------------------
576
577#[cfg(test)]
578mod tests {
579    use super::*;
580    use crate::bytecode::{Instruction, Opcode, Operand};
581    use crate::symbol::LocalEntry;
582    use crate::types::Type;
583
584    fn empty_script(name: &str) -> CompiledScript {
585        let mut s = CompiledScript::new(format!("[label,{}]", name), 0);
586        s.trigger = "label".to_string();
587        s.source_path = "/virt/test.rs2".to_string();
588        s
589    }
590
591    fn push_local_entry(
592        s: &mut CompiledScript,
593        name: &str,
594        var_type: Type,
595        is_param: bool,
596        is_array: bool,
597    ) {
598        s.local_table.all.push(LocalEntry {
599            name: name.to_string(),
600            var_type,
601            is_param,
602            is_array,
603        });
604    }
605
606    // -----------------------------------------------------------------------
607    // Unused locals
608    // -----------------------------------------------------------------------
609
610    #[test]
611    fn unused_int_local_is_reported() {
612        // Body: def_int $x = 5;   (written, never read)
613        let mut script = empty_script("foo");
614        push_local_entry(&mut script, "x", Type::Int, false, false);
615        script.instructions = vec![
616            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
617            Instruction::push_int(5),
618            Instruction::pop_int_local(0),
619            Instruction::simple(Opcode::Return),
620        ];
621
622        let scripts = [script];
623        let mut diags = DiagnosticsCollector::new();
624        check_unused_locals(&scripts[0], None, &mut diags);
625
626        let warnings: Vec<_> = diags
627            .diagnostics()
628            .iter()
629            .filter(|d| d.severity == Severity::Warning)
630            .collect();
631        assert_eq!(warnings.len(), 1, "expected one unused-local warning");
632        assert!(
633            warnings[0].message.contains("$x"),
634            "message should name $x: {}",
635            warnings[0].message
636        );
637        assert_eq!(warnings[0].line, 2);
638    }
639
640    #[test]
641    fn read_then_written_int_local_is_ok() {
642        // def_int $x = 5; def_int $y = $x;   (x is read, y is not — y warns)
643        let mut script = empty_script("foo");
644        push_local_entry(&mut script, "x", Type::Int, false, false);
645        push_local_entry(&mut script, "y", Type::Int, false, false);
646        script.instructions = vec![
647            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
648            Instruction::push_int(5),
649            Instruction::pop_int_local(0),
650            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
651            Instruction::push_int_local(0), // read of $x
652            Instruction::pop_int_local(1),  // write to $y
653            Instruction::simple(Opcode::Return),
654        ];
655
656        let mut diags = DiagnosticsCollector::new();
657        check_unused_locals(&script, None, &mut diags);
658        let warnings: Vec<_> = diags
659            .diagnostics()
660            .iter()
661            .filter(|d| d.severity == Severity::Warning)
662            .collect();
663        assert_eq!(warnings.len(), 1, "only $y should warn");
664        assert!(warnings[0].message.contains("$y"));
665    }
666
667    #[test]
668    fn unused_parameter_is_reported_with_param_wording() {
669        let mut script = empty_script("foo");
670        script.trigger = "label".to_string();
671        push_local_entry(&mut script, "unused", Type::Int, true, false);
672        script.int_arg_count = 1;
673        script.int_local_count = 1;
674        script.instructions = vec![
675            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
676            Instruction::simple(Opcode::Return),
677        ];
678
679        let mut diags = DiagnosticsCollector::new();
680        check_unused_locals(&script, None, &mut diags);
681        let warnings: Vec<_> = diags
682            .diagnostics()
683            .iter()
684            .filter(|d| d.severity == Severity::Warning)
685            .collect();
686        assert_eq!(warnings.len(), 1);
687        assert!(
688            warnings[0].message.contains("Parameter"),
689            "message should use parameter wording: {}",
690            warnings[0].message
691        );
692    }
693
694    #[test]
695    fn string_and_long_locals_tracked_independently() {
696        let mut script = empty_script("foo");
697        push_local_entry(&mut script, "s", Type::String, false, false);
698        push_local_entry(&mut script, "l", Type::Long, false, false);
699        let hi = script.intern_str("hi".to_string());
700        script.instructions = vec![
701            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
702            Instruction::new(Opcode::PushConstantString, Operand::Str(hi)),
703            Instruction::pop_string_local(0),
704            Instruction::push_long(42),
705            Instruction::pop_long_local(0),
706            Instruction::simple(Opcode::Return),
707        ];
708
709        let mut diags = DiagnosticsCollector::new();
710        check_unused_locals(&script, None, &mut diags);
711        let warnings: Vec<_> = diags
712            .diagnostics()
713            .iter()
714            .filter(|d| d.severity == Severity::Warning)
715            .collect();
716        assert_eq!(warnings.len(), 2, "both $s and $l should warn");
717        let names: Vec<&str> = warnings.iter().map(|d| d.message.as_str()).collect();
718        assert!(names.iter().any(|m| m.contains("$s")));
719        assert!(names.iter().any(|m| m.contains("$l")));
720    }
721
722    #[test]
723    fn unused_array_is_reported() {
724        let mut script = empty_script("foo");
725        push_local_entry(&mut script, "arr", Type::Int, false, true);
726        script.instructions = vec![
727            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
728            Instruction::push_int(5),
729            Instruction::new(Opcode::DefineArray, Operand::Int(0)),
730            Instruction::simple(Opcode::Return),
731        ];
732
733        let mut diags = DiagnosticsCollector::new();
734        check_unused_locals(&script, None, &mut diags);
735        let warnings: Vec<_> = diags
736            .diagnostics()
737            .iter()
738            .filter(|d| d.severity == Severity::Warning)
739            .collect();
740        assert_eq!(warnings.len(), 1);
741        assert!(warnings[0].message.contains("$arr"));
742        assert!(warnings[0].message.contains("array"));
743    }
744
745    #[test]
746    fn touched_array_does_not_warn() {
747        // def_int $arr(3); $arr(0) = 1; read $arr(0) — array IS used.
748        let mut script = empty_script("foo");
749        push_local_entry(&mut script, "arr", Type::Int, false, true);
750        script.instructions = vec![
751            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
752            Instruction::push_int(3),
753            Instruction::new(Opcode::DefineArray, Operand::Int(0)),
754            Instruction::push_int(1),
755            Instruction::push_int(0),
756            Instruction::new(Opcode::PopArrayInt, Operand::Int(0)),
757            Instruction::push_int(0),
758            Instruction::new(Opcode::PushArrayInt, Operand::Int(0)),
759            Instruction::new(Opcode::PopIntDiscard, Operand::Int(0)),
760            Instruction::simple(Opcode::Return),
761        ];
762
763        let mut diags = DiagnosticsCollector::new();
764        check_unused_locals(&script, None, &mut diags);
765        let warnings: Vec<_> = diags
766            .diagnostics()
767            .iter()
768            .filter(|d| d.severity == Severity::Warning)
769            .collect();
770        assert_eq!(warnings.len(), 0, "touched array should not warn");
771    }
772
773    // -----------------------------------------------------------------------
774    // Unreachable code
775    // -----------------------------------------------------------------------
776
777    #[test]
778    fn dead_code_after_return_is_reported() {
779        // mes("hi"); return; mes("bye");  <-- line 4 unreachable
780        let mut script = empty_script("foo");
781        let hi = script.intern_str("hi".to_string());
782        let bye = script.intern_str("bye".to_string());
783        script.instructions = vec![
784            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
785            Instruction::new(Opcode::PushConstantString, Operand::Str(hi)),
786            Instruction::new(Opcode::Command, Operand::Int(0)), // mes
787            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
788            Instruction::simple(Opcode::Return),
789            Instruction::new(Opcode::LineNumber, Operand::Int(4)),
790            Instruction::new(Opcode::PushConstantString, Operand::Str(bye)),
791            Instruction::new(Opcode::Command, Operand::Int(0)),
792            Instruction::simple(Opcode::Return),
793        ];
794
795        let mut diags = DiagnosticsCollector::new();
796        check_unreachable_code(&script, None, &mut diags);
797        let warnings: Vec<_> = diags
798            .diagnostics()
799            .iter()
800            .filter(|d| d.severity == Severity::Warning)
801            .collect();
802        assert_eq!(warnings.len(), 1);
803        assert_eq!(warnings[0].line, 4);
804        assert!(warnings[0].message.contains("Unreachable"));
805    }
806
807    #[test]
808    fn dead_code_after_jump_is_reported() {
809        // @some_label; mes("never");
810        let mut script = empty_script("foo");
811        let never = script.intern_str("never".to_string());
812        script.instructions = vec![
813            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
814            Instruction::new(Opcode::JumpWithParams, Operand::Int(999)),
815            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
816            Instruction::new(Opcode::PushConstantString, Operand::Str(never)),
817            Instruction::new(Opcode::Command, Operand::Int(0)),
818            Instruction::simple(Opcode::Return),
819        ];
820
821        let mut diags = DiagnosticsCollector::new();
822        check_unreachable_code(&script, None, &mut diags);
823        let warnings: Vec<_> = diags
824            .diagnostics()
825            .iter()
826            .filter(|d| d.severity == Severity::Warning)
827            .collect();
828        assert_eq!(warnings.len(), 1);
829        assert_eq!(warnings[0].line, 3);
830    }
831
832    #[test]
833    fn reachable_code_after_conditional_branch_is_ok() {
834        // if (cond) { body } — body IS reachable via BranchEquals target.
835        let mut script = empty_script("foo");
836        let yes = script.intern_str("yes".to_string());
837        script.instructions = vec![
838            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
839            Instruction::push_int(1),
840            Instruction::push_int(1),
841            Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(6)),
842            Instruction::new(Opcode::Branch, Operand::JumpTarget(9)),
843            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
844            Instruction::new(Opcode::PushConstantString, Operand::Str(yes)),
845            Instruction::new(Opcode::Command, Operand::Int(0)),
846            Instruction::new(Opcode::LineNumber, Operand::Int(3)),
847            Instruction::simple(Opcode::Return),
848        ];
849
850        let mut diags = DiagnosticsCollector::new();
851        check_unreachable_code(&script, None, &mut diags);
852        let warnings: Vec<_> = diags
853            .diagnostics()
854            .iter()
855            .filter(|d| d.severity == Severity::Warning)
856            .collect();
857        assert_eq!(
858            warnings.len(),
859            0,
860            "conditional-branch body is reachable; got: {:?}",
861            warnings.iter().map(|d| &d.message).collect::<Vec<_>>()
862        );
863    }
864
865    #[test]
866    fn compiler_emitted_branch_without_linenumber_does_not_warn() {
867        // Simulates compile_if's always-emitted Branch(end) after a body
868        // that ends in Return. The Branch has NO leading LineNumber, so
869        // our lint should skip it.
870        let mut script = empty_script("foo");
871        script.instructions = vec![
872            Instruction::new(Opcode::LineNumber, Operand::Int(1)),
873            Instruction::push_int(1),
874            Instruction::push_int(1),
875            Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(5)),
876            Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
877            Instruction::new(Opcode::LineNumber, Operand::Int(2)),
878            Instruction::simple(Opcode::Return),
879            Instruction::new(Opcode::Branch, Operand::JumpTarget(8)), // compiler-emitted, unreachable
880            Instruction::simple(Opcode::Return),
881        ];
882
883        let mut diags = DiagnosticsCollector::new();
884        check_unreachable_code(&script, None, &mut diags);
885        let warnings: Vec<_> = diags
886            .diagnostics()
887            .iter()
888            .filter(|d| d.severity == Severity::Warning)
889            .collect();
890        assert_eq!(
891            warnings.len(),
892            0,
893            "compiler-emitted unreachable Branch must not warn; got: {:?}",
894            warnings.iter().map(|d| &d.message).collect::<Vec<_>>()
895        );
896    }
897}