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 {
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
}
fn check_unused_locals(
script: &CompiledScript,
source_cache: Option<crate::SourceProvider<'_>>,
diagnostics: &mut DiagnosticsCollector,
) {
let mut int_reads: HashSet<i32> = HashSet::new();
let mut string_reads: HashSet<i32> = HashSet::new();
let mut long_reads: HashSet<i32> = HashSet::new();
let mut array_touched: HashSet<i32> = HashSet::new();
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);
}
_ => {}
}
}
let mut header_line_cache: Option<usize> = None;
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;
}
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,
) {
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
),
)
};
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, help: Vec::new(),
};
diag.help.push(help);
diagnostics.add(diag);
}
fn check_unreachable_code(
script: &CompiledScript,
source_cache: Option<crate::SourceProvider<'_>>,
diagnostics: &mut DiagnosticsCollector,
) {
let instrs = &script.instructions;
if instrs.is_empty() {
return;
}
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;
}
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
);
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);
}
}
}
}
_ => {}
}
if !is_terminal && order_idx + 1 < node_instr.len() {
let m = order_idx + 1;
if !reachable[m] {
reachable[m] = true;
queue.push_back(m);
}
}
}
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(), 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);
}
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
}
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))
}
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
}
#[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,
});
}
#[test]
fn unused_int_local_is_reported() {
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() {
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), Instruction::pop_int_local(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, "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() {
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");
}
#[test]
fn dead_code_after_return_is_reported() {
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)), 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() {
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() {
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() {
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)), 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<_>>()
);
}
}