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