use std::collections::{HashMap, HashSet, VecDeque};
use std::path::PathBuf;
use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
use crate::clientscript;
use crate::diagnostic_messages as msg;
use crate::diagnostics::{
Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
};
use crate::pointer::{PointerHolder, PointerSet, PointerType, command_pointers, trigger_pointers};
use crate::symbol::{SymbolKind, SymbolRegistry};
#[cfg(feature = "memprof")]
static CFG_TRACE: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
#[cfg(feature = "memprof")]
fn cfg_trace_push(source_path: &str) {
if std::env::var_os("RUNEC_TRACE_CFG").is_some() {
CFG_TRACE.lock().unwrap().push(source_path.to_string());
}
}
#[cfg(feature = "memprof")]
pub(crate) fn cfg_trace_report() {
use tracing::info;
let trace = CFG_TRACE.lock().unwrap();
if trace.is_empty() {
return;
}
let distinct: HashSet<&str> = trace.iter().map(|s| s.as_str()).collect();
let nfiles = distinct.len().max(1);
info!(
"[trace] build_cfg calls: {}, distinct files: {}",
trace.len(),
nfiles
);
for &cap in &[16usize, 64, 256, 1024, nfiles] {
let mut lru: Vec<&str> = Vec::with_capacity(cap + 1);
let mut misses = 0usize;
for f in trace.iter() {
let f = f.as_str();
if let Some(pos) = lru.iter().position(|x| *x == f) {
lru.remove(pos);
} else {
misses += 1;
}
lru.insert(0, f);
if lru.len() > cap {
lru.pop();
}
}
info!(
"[trace] LRU cap {:>5}: {:>7} re-parses ({:.2}x of {} files)",
cap,
misses,
misses as f64 / nfiles as f64,
nfiles
);
}
}
pub(crate) enum ScriptRef<'a> {
Borrowed(&'a CompiledScript),
Owned(std::rc::Rc<CompiledScript>),
}
impl std::ops::Deref for ScriptRef<'_> {
type Target = CompiledScript;
fn deref(&self) -> &CompiledScript {
match self {
ScriptRef::Borrowed(s) => s,
ScriptRef::Owned(rc) => rc,
}
}
}
pub(crate) enum ScriptSource<'a> {
Resident(&'a [CompiledScript]),
Recompile {
len: usize,
get: std::cell::RefCell<Box<dyn FnMut(usize) -> std::rc::Rc<CompiledScript> + 'a>>,
},
}
impl<'a> ScriptSource<'a> {
fn len(&self) -> usize {
match self {
ScriptSource::Resident(s) => s.len(),
ScriptSource::Recompile { len, .. } => *len,
}
}
fn get(&self, idx: usize) -> ScriptRef<'a> {
match self {
ScriptSource::Resident(s) => ScriptRef::Borrowed(&(*s)[idx]),
ScriptSource::Recompile { get, .. } => ScriptRef::Owned((get.borrow_mut())(idx)),
}
}
}
#[derive(Debug)]
struct CfgNode {
instruction_index: Option<usize>,
pointer_set: PointerSet,
next: Vec<usize>,
previous: Vec<usize>,
}
impl CfgNode {
fn new(instruction_index: Option<usize>) -> Self {
CfgNode {
instruction_index,
pointer_set: PointerSet::new(),
next: Vec::new(),
previous: Vec::new(),
}
}
fn pointer_node(pointer_set: PointerSet) -> Self {
CfgNode {
instruction_index: None,
pointer_set,
next: Vec::new(),
previous: Vec::new(),
}
}
}
struct ScriptAnalysis {
nodes: Vec<CfgNode>,
required: Vec<Vec<usize>>,
set_list: Vec<Vec<usize>>,
corrupted_list: Vec<Vec<usize>>,
returns: Vec<usize>,
}
impl ScriptAnalysis {
fn new() -> Self {
let n = PointerType::COUNT;
ScriptAnalysis {
nodes: Vec::new(),
required: vec![Vec::new(); n],
set_list: vec![Vec::new(); n],
corrupted_list: vec![Vec::new(); n],
returns: Vec::new(),
}
}
}
pub(crate) struct SharedMaps {
client: bool,
cmd_pointers: HashMap<String, PointerHolder>,
opcode_to_name: HashMap<i32, String>,
script_id_to_index: HashMap<i32, usize>,
script_name_to_index: HashMap<String, usize>,
overlay_interfaces: HashSet<String>,
}
pub struct PointerChecker<'a> {
scripts: ScriptSource<'a>,
#[allow(dead_code)]
registry: &'a SymbolRegistry,
shared: std::sync::Arc<SharedMaps>,
source_cache: Option<crate::SourceProvider<'a>>,
script_analyses: HashMap<String, ScriptAnalysis>,
script_pointers: HashMap<String, PointerHolder>,
pending_analyses: HashSet<String>,
pending_scripts: HashSet<String>,
}
impl SharedMaps {
fn build<'b>(
idents: impl Iterator<Item = (i32, &'b str)>,
registry: &SymbolRegistry,
client: bool,
) -> Self {
let mut opcode_to_name = HashMap::new();
for (name, sym) in ®istry.commands {
if let SymbolKind::Command { opcode, .. } = &sym.kind {
opcode_to_name.insert(*opcode, name.to_lowercase());
}
}
let mut script_id_to_index = HashMap::new();
let mut script_name_to_index = HashMap::new();
for (i, (id, name)) in idents.enumerate() {
script_id_to_index.insert(id, i);
script_name_to_index.entry(name.to_string()).or_insert(i);
}
let mut overlay_interfaces = HashSet::new();
for (name, entry) in ®istry.entity_ids {
if let Some(e) = entry.primary
&& e.const_type == crate::types::Type::OverlayInterface
{
overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
}
}
SharedMaps {
client,
cmd_pointers: registry.profile.as_ref().map_or_else(
|| {
if client {
clientscript::command_pointers(registry)
} else {
command_pointers()
}
},
|profile| profile.command_pointers.clone(),
),
opcode_to_name,
script_id_to_index,
script_name_to_index,
overlay_interfaces,
}
}
}
impl<'a> PointerChecker<'a> {
pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
let shared = std::sync::Arc::new(SharedMaps::build(
scripts.iter().map(|s| (s.id, s.name.as_str())),
registry,
false,
));
Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
}
pub fn new_client(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
let shared = std::sync::Arc::new(SharedMaps::build(
scripts.iter().map(|s| (s.id, s.name.as_str())),
registry,
true,
));
Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
}
pub(crate) fn build_shared(
scripts: &[CompiledScript],
registry: &SymbolRegistry,
) -> std::sync::Arc<SharedMaps> {
std::sync::Arc::new(SharedMaps::build(
scripts.iter().map(|s| (s.id, s.name.as_str())),
registry,
false,
))
}
pub(crate) fn build_shared_idents(
idents: &[(i32, String)],
registry: &SymbolRegistry,
) -> std::sync::Arc<SharedMaps> {
std::sync::Arc::new(SharedMaps::build(
idents.iter().map(|(id, name)| (*id, name.as_str())),
registry,
false,
))
}
pub(crate) fn with_shared(
scripts: ScriptSource<'a>,
registry: &'a SymbolRegistry,
shared: std::sync::Arc<SharedMaps>,
) -> Self {
PointerChecker {
scripts,
registry,
shared,
source_cache: None,
script_analyses: HashMap::new(),
script_pointers: HashMap::new(),
pending_analyses: HashSet::new(),
pending_scripts: HashSet::new(),
}
}
pub fn set_source_cache(&mut self, provider: crate::SourceProvider<'a>) {
self.source_cache = Some(provider);
}
fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
if !self
.registry
.trigger(trigger)
.is_some_and(|trigger| trigger.is_button)
{
return false;
}
let subject = script_name
.trim_start_matches('[')
.trim_end_matches(']')
.split_once(',')
.map(|(_, rest)| rest)
.unwrap_or("");
let iface_name = subject
.split(':')
.next()
.unwrap_or("")
.to_lowercase()
.replace(' ', "_");
if iface_name.is_empty() {
return false;
}
!self.shared.overlay_interfaces.contains(&iface_name)
}
pub fn run(&mut self) -> DiagnosticsCollector {
let names = self.script_names();
self.validate_names(&names)
}
pub fn script_names(&self) -> Vec<String> {
(0..self.scripts.len())
.map(|i| self.scripts.get(i).name.clone())
.collect()
}
pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
let mut diagnostics = DiagnosticsCollector::new();
for script_name in names {
self.validate_script(script_name, &mut diagnostics);
self.script_analyses.clear();
}
diagnostics
}
fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
let script_idx = match self.shared.script_name_to_index.get(script_name) {
Some(&i) => i,
None => return,
};
let trigger = self.scripts.get(script_idx).trigger.clone();
let source_path = self.scripts.get(script_idx).source_path.clone();
let trigger_set = if let Some(profile) = &self.registry.profile {
profile
.trigger_pointers
.get(&trigger)
.copied()
.unwrap_or_default()
} else if self.shared.client {
match trigger.as_str() {
"proc" => [PointerType::ActiveComponent, PointerType::ActiveComponent2]
.into_iter()
.collect(),
_ => PointerSet::new(),
}
} else {
trigger_pointers(&trigger)
};
self.ensure_analysis(script_name);
for &ptr in &PointerType::ALL {
let ptr_idx = ptr.index();
let analysis = match self.script_analyses.get(script_name) {
Some(a) => a,
None => continue,
};
let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
if required_nodes.is_empty() {
continue;
}
let mut corrupted: HashSet<usize> =
analysis.corrupted_list[ptr_idx].iter().copied().collect();
let trigger_provides = if trigger_set.contains(ptr) {
true
} else if ptr == PointerType::PActivePlayer {
self.interface_trigger_grants_protected(&trigger, script_name)
} else {
false
};
if !trigger_provides {
corrupted.insert(0);
}
if corrupted.is_empty() {
continue;
}
let set_blocked: HashSet<usize> = analysis.set_list[ptr_idx].iter().copied().collect();
let path = self.find_edge_path(
script_name,
&required_nodes,
|node_idx| corrupted.contains(&node_idx),
&set_blocked,
);
let mut reported_via_main_bfs = false;
if let Some(path) = path {
if path.is_empty() {
continue;
}
reported_via_main_bfs = true;
let end_node_idx = path[path.len() - 1];
let start_node_idx = path[0];
let is_start_node = end_node_idx == 0;
let repr = ptr.representation();
let static_only = is_static_only_pointer(ptr);
let error_msg = if is_start_node {
if static_only {
msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
} else {
msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
}
} else if static_only {
msg::fmt(msg::POINTER_STALE, &[repr])
} else {
msg::fmt(msg::POINTER_CORRUPTED, &[repr])
};
let analysis = self.script_analyses.get(script_name).unwrap();
let script_ref = self.scripts.get(script_idx);
let instructions = &script_ref.instructions;
let req_line = analysis.nodes[start_node_idx]
.instruction_index
.map(|idx| resolve_line(instructions, idx))
.unwrap_or(0);
diagnostics.add(Diagnostic {
file: PathBuf::from(&source_path),
line: req_line,
column: 0,
message: error_msg,
severity: Severity::Warning,
phase: Phase::PointerCheck,
help: Vec::new(),
});
let read_hint = if static_only {
msg::fmt(msg::POINTER_READ_HERE, &[repr])
} else {
msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
};
diagnostics.add(Diagnostic {
file: PathBuf::from(&source_path),
line: req_line,
column: 0,
message: read_hint,
severity: Severity::Info,
phase: Phase::PointerCheck,
help: Vec::new(),
});
if !is_start_node {
let corrupt_line = analysis.nodes[end_node_idx]
.instruction_index
.map(|idx| resolve_line(instructions, idx))
.unwrap_or(0);
let cause_hint = if static_only {
msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
} else {
msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
};
diagnostics.add(Diagnostic {
file: PathBuf::from(&source_path),
line: corrupt_line,
column: 0,
message: cause_hint,
severity: Severity::Info,
phase: Phase::PointerCheck,
help: Vec::new(),
});
}
}
if !reported_via_main_bfs && is_static_only_pointer(ptr) {
let targets: Vec<(usize, usize)> = {
let analysis = self.script_analyses.get(script_name).unwrap();
let script_ref = self.scripts.get(script_idx);
let instructions = &script_ref.instructions;
let corrupted_nodes: HashSet<usize> =
analysis.corrupted_list[ptr_idx].iter().copied().collect();
required_nodes
.iter()
.filter(|&&node_idx| corrupted_nodes.contains(&node_idx))
.map(|&node_idx| {
let line = analysis.nodes[node_idx]
.instruction_index
.map(|idx| resolve_line(instructions, idx))
.unwrap_or(0);
(node_idx, line)
})
.collect()
};
let mut seen_lines: HashSet<usize> = HashSet::new();
let repr = ptr.representation();
for (node_idx, line) in targets {
if !seen_lines.insert(line) {
continue;
}
let help =
self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
let mut diag = Diagnostic {
file: PathBuf::from(&source_path),
line,
column: 0,
message: msg::fmt(msg::POINTER_STALE, &[repr]),
severity: Severity::Warning,
phase: Phase::PointerCheck,
help: Vec::new(),
};
if let Some(h) = help {
diag.help.push(h);
}
diagnostics.add(diag);
}
}
}
}
fn find_edge_path(
&self,
script_name: &str,
starts: &[usize],
end_pred: impl Fn(usize) -> bool,
blocked: &HashSet<usize>,
) -> Option<Vec<usize>> {
let analysis = self.script_analyses.get(script_name)?;
let mut queue: VecDeque<usize> = VecDeque::new();
let mut visited: HashSet<usize> = HashSet::new();
let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
for &start in starts {
for &prev in &analysis.nodes[start].previous {
if blocked.contains(&prev) || visited.contains(&prev) {
continue;
}
visited.insert(prev);
queue.push_back(prev);
sources.insert(prev, (start, start));
}
}
while let Some(current) = queue.pop_front() {
if end_pred(current) {
let mut path = vec![current];
let mut node = current;
while let Some(&(from, start)) = sources.get(&node) {
if from == start && starts.contains(&from) {
path.push(from);
break;
}
path.push(from);
node = from;
}
path.reverse();
return Some(path);
}
let (_, start_node) = sources[¤t];
for &prev in &analysis.nodes[current].previous {
if blocked.contains(&prev) || visited.contains(&prev) {
continue;
}
visited.insert(prev);
queue.push_back(prev);
sources.insert(prev, (current, start_node));
}
}
None
}
fn find_edge_path_static(
nodes: &[CfgNode],
starts: &[usize],
end_pred: impl Fn(usize) -> bool,
blocked: &HashSet<usize>,
) -> Option<Vec<usize>> {
let mut queue: VecDeque<usize> = VecDeque::new();
let mut visited: HashSet<usize> = HashSet::new();
let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
for &start in starts {
for &prev in &nodes[start].previous {
if blocked.contains(&prev) || visited.contains(&prev) {
continue;
}
visited.insert(prev);
queue.push_back(prev);
sources.insert(prev, (start, start));
}
}
while let Some(current) = queue.pop_front() {
if end_pred(current) {
let mut path = vec![current];
let mut node = current;
while let Some(&(from, start)) = sources.get(&node) {
if from == start && starts.contains(&from) {
path.push(from);
break;
}
path.push(from);
node = from;
}
path.reverse();
return Some(path);
}
for &prev in &nodes[current].previous {
if blocked.contains(&prev) || visited.contains(&prev) {
continue;
}
visited.insert(prev);
queue.push_back(prev);
sources.insert(prev, (current, sources[¤t].1));
}
}
None
}
fn ensure_analysis(&mut self, script_name: &str) {
if self.script_analyses.contains_key(script_name) {
return;
}
if self.pending_analyses.contains(script_name) {
return; }
self.pending_analyses.insert(script_name.to_string());
let script_idx = match self.shared.script_name_to_index.get(script_name) {
Some(&i) => i,
None => return,
};
let mut analysis = self.build_cfg(script_idx);
self.categorize_nodes(script_idx, &mut analysis);
self.script_analyses
.insert(script_name.to_string(), analysis);
self.pending_analyses.remove(script_name);
}
fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
let script = self.scripts.get(script_idx);
#[cfg(feature = "memprof")]
cfg_trace_push(&script.source_path);
let instructions = &script.instructions;
let mut analysis = ScriptAnalysis::new();
analysis.nodes.push(CfgNode::new(None));
let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
let mut node_order: Vec<usize> = Vec::new();
for (i, instr) in instructions.iter().enumerate() {
if instr.opcode == Opcode::LineNumber {
continue;
}
let node_idx = analysis.nodes.len();
instr_to_node.insert(i, node_idx);
node_order.push(i);
analysis.nodes.push(CfgNode::new(Some(i)));
}
if node_order.is_empty() {
return analysis;
}
let first_node = instr_to_node[&node_order[0]];
add_edge(&mut analysis.nodes, 0, first_node);
for (order_idx, &instr_idx) in node_order.iter().enumerate() {
let node_idx = instr_to_node[&instr_idx];
let instr = &instructions[instr_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_idx) = &instr.operand
&& let Some(target_node) =
resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
{
add_edge(&mut analysis.nodes, node_idx, target_node);
}
}
Opcode::Switch => {
if let Operand::SwitchTable(tbl_idx) = &instr.operand {
let cases = &script.switch_tables[*tbl_idx as usize];
for &(_, target_instr_idx) in cases.iter() {
if let Some(target_node) =
resolve_target_node(target_instr_idx, instructions, &instr_to_node)
{
add_edge(&mut analysis.nodes, node_idx, target_node);
}
}
}
}
_ => {}
}
if !is_terminal
&& let Some(next_order_idx) = order_idx.checked_add(1)
&& next_order_idx < node_order.len()
{
let next_node = instr_to_node[&node_order[next_order_idx]];
add_edge(&mut analysis.nodes, node_idx, next_node);
}
if instr.opcode == Opcode::Return {
analysis.returns.push(node_idx);
}
}
self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
analysis
}
fn insert_pointer_nodes(
&self,
script_idx: usize,
analysis: &mut ScriptAnalysis,
instr_to_node: &HashMap<usize, usize>,
node_order: &[usize],
) {
let script_ref = self.scripts.get(script_idx);
let instructions = &script_ref.instructions;
for window_end in 1..node_order.len() {
let branch_instr_idx = node_order[window_end];
let branch_instr = &instructions[branch_instr_idx];
let (push_value, scan_end) = match branch_instr.opcode {
Opcode::BranchIfTrue => (1, window_end),
Opcode::BranchIfFalse => (0, window_end),
Opcode::BranchEquals | Opcode::BranchNot => {
let push_instr = &instructions[node_order[window_end - 1]];
match (push_instr.opcode, &push_instr.operand) {
(Opcode::PushConstantInt, Operand::Int(value @ (0 | 1))) => (
if branch_instr.opcode == Opcode::BranchNot {
1 - value
} else {
*value
},
window_end - 1,
),
_ => continue,
}
}
_ => continue,
};
let mut cmd_instr_idx = None;
for scan in (0..scan_end).rev() {
let idx = node_order[scan];
if instructions[idx].opcode == Opcode::Command {
cmd_instr_idx = Some(idx);
break;
}
if matches!(
instructions[idx].opcode,
Opcode::Branch
| Opcode::Return
| Opcode::Switch
| Opcode::BranchEquals
| Opcode::BranchNot
| Opcode::BranchLessThan
| Opcode::BranchGreaterThan
| Opcode::BranchLessThanOrEquals
| Opcode::BranchGreaterThanOrEquals
| Opcode::BranchIfTrue
| Opcode::BranchIfFalse
) {
break;
}
}
let cmd_instr_idx = match cmd_instr_idx {
Some(idx) => idx,
None => continue,
};
if self.shared.client && (scan_end == 0 || node_order[scan_end - 1] != cmd_instr_idx) {
continue;
}
let cmd_instr = &instructions[cmd_instr_idx];
let cmd_name = self.resolve_command_name(cmd_instr, &script_ref.strings);
let cmd_name = match cmd_name {
Some(n) => n,
None => continue,
};
let holder = match self.shared.cmd_pointers.get(&cmd_name) {
Some(h) => h,
None => continue,
};
if !holder.conditional_set {
continue;
}
if holder.set.is_empty() {
continue;
}
let branch_node_idx = instr_to_node[&branch_instr_idx];
let ptr_node_idx = analysis.nodes.len();
analysis.nodes.push(CfgNode::pointer_node(holder.set));
if push_value == 0 {
let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
.next
.iter()
.copied()
.filter(|&n| {
if let Operand::JumpTarget(target) = &branch_instr.operand
&& let Some(jump_node) =
resolve_target_node(*target, instructions, instr_to_node)
{
return n != jump_node;
}
true
})
.collect();
for ft_target in fallthrough_targets {
remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
}
} else {
if let Operand::JumpTarget(target) = &branch_instr.operand
&& let Some(jump_target_node) =
resolve_target_node(*target, instructions, instr_to_node)
{
remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
}
}
}
}
fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
let script_ref = self.scripts.get(script_idx);
let instructions = &script_ref.instructions;
for node_idx in 0..analysis.nodes.len() {
let instr_idx = match analysis.nodes[node_idx].instruction_index {
Some(i) => i,
None => {
let ptr_set = analysis.nodes[node_idx].pointer_set;
if !ptr_set.is_empty() {
for ptr in ptr_set.iter() {
let pi = ptr.index();
analysis.set_list[pi].push(node_idx);
}
}
continue;
}
};
let instr = &instructions[instr_idx];
match instr.opcode {
Opcode::Command => {
let cmd_name = self.resolve_command_name(instr, &script_ref.strings);
if let Some(name) = cmd_name
&& let Some(holder) = self.shared.cmd_pointers.get(&name).cloned()
{
self.apply_holder(analysis, node_idx, &holder);
}
}
Opcode::Gosub | Opcode::GosubWithParams => {
if let Operand::Int(script_id) = &instr.operand {
let callee_holder = self.get_script_pointers(*script_id);
self.apply_holder(analysis, node_idx, &callee_holder);
}
}
Opcode::Jump | Opcode::JumpWithParams => {
if let Operand::Int(script_id) = &instr.operand {
let callee_holder = self.get_script_pointers(*script_id);
self.apply_holder(analysis, node_idx, &callee_holder);
}
}
Opcode::PushVarp | Opcode::PushVarbit if !self.shared.client => {
let pi = if is_secondary_var_operand(&instr.operand) {
PointerType::ActivePlayer2.index()
} else {
PointerType::ActivePlayer.index()
};
analysis.required[pi].push(node_idx);
}
Opcode::PopVarp | Opcode::PopVarbit if !self.shared.client => {
let pi = if is_secondary_var_operand(&instr.operand) {
PointerType::ActivePlayer2.index()
} else {
PointerType::ActivePlayer.index()
};
analysis.required[pi].push(node_idx);
}
Opcode::PushVarn | Opcode::PopVarn if !self.shared.client => {
let pi = if is_secondary_var_operand(&instr.operand) {
PointerType::ActiveNpc2.index()
} else {
PointerType::ActiveNpc.index()
};
analysis.required[pi].push(node_idx);
}
_ => {}
}
}
}
fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
for ptr in holder.required.iter() {
let pi = ptr.index();
analysis.required[pi].push(node_idx);
}
for ptr in holder.set.iter().filter(|_| !holder.conditional_set) {
let pi = ptr.index();
analysis.set_list[pi].push(node_idx);
}
for ptr in holder.corrupted.iter() {
let pi = ptr.index();
analysis.corrupted_list[pi].push(node_idx);
}
}
fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
let script_idx = match self.shared.script_id_to_index.get(&script_id) {
Some(&i) => i,
None => {
return PointerHolder::default();
}
};
let script_name = self.scripts.get(script_idx).name.clone();
if let Some(holder) = self.script_pointers.get(&script_name) {
return holder.clone();
}
if self.pending_scripts.contains(&script_name) {
return PointerHolder::default();
}
self.pending_scripts.insert(script_name.clone());
self.ensure_analysis(&script_name);
let mut holder = PointerHolder::default();
if let Some(analysis) = self.script_analyses.get(&script_name) {
for &ptr in &PointerType::ALL {
let pi = ptr.index();
let requires = !analysis.required[pi].is_empty();
let has_returns = !analysis.returns.is_empty();
if !requires && !has_returns {
continue;
}
let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
if requires {
let path = Self::find_edge_path_static(
&analysis.nodes,
&analysis.required[pi],
|node_idx| node_idx == 0,
&set_blocked,
);
if path.is_some() {
holder.required.insert(ptr);
}
}
if has_returns {
let corrupted_nodes: HashSet<usize> =
analysis.corrupted_list[pi].iter().copied().collect();
let path = Self::find_edge_path_static(
&analysis.nodes,
&analysis.returns,
|node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
&set_blocked,
);
if path.is_none() {
holder.set.insert(ptr);
}
if !corrupted_nodes.is_empty() {
let path = Self::find_edge_path_static(
&analysis.nodes,
&analysis.returns,
|node_idx| corrupted_nodes.contains(&node_idx),
&set_blocked,
);
if path.is_some() {
holder.corrupted.insert(ptr);
}
}
}
}
}
self.pending_scripts.remove(&script_name);
self.script_pointers
.insert(script_name.clone(), holder.clone());
holder
}
fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
let callee = self.scripts.get(callee_idx);
let analysis = match self.script_analyses.get(&callee.name) {
Some(a) => a,
None => return Vec::new(),
};
let ptr_idx = ptr.index();
let mut seen: HashSet<(String, usize)> = HashSet::new();
let mut result: Vec<(String, usize)> = Vec::new();
for &node_idx in &analysis.corrupted_list[ptr_idx] {
let instr_idx = match analysis.nodes[node_idx].instruction_index {
Some(i) => i,
None => continue,
};
let instr = &callee.instructions[instr_idx];
let line = resolve_line(&callee.instructions, instr_idx);
let name = match instr.opcode {
Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
Some(n) => n,
None => continue,
},
Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
.map(|s| format!("~{}", s))
.unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
None => continue,
},
_ => continue,
},
_ => continue,
};
let key = (name.clone(), line);
if seen.insert(key) {
result.push((name, line));
}
}
result
}
fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
match &instr.operand {
Operand::Int(encoded) => {
let opcode = encoded & 0xFFFF;
let secondary = (encoded >> 16) & 1;
let base_name = self.shared.opcode_to_name.get(&opcode)?;
if secondary == 1 {
Some(format!(".{}", base_name))
} else {
Some(base_name.clone())
}
}
Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
_ => None,
}
}
fn build_rule_a_help(
&mut self,
ptr: PointerType,
caller_source_path: &str,
caller_line: usize,
node_idx: usize,
caller_script_idx: usize,
) -> Option<Help> {
let (is_gosub, script_id) = {
let caller = self.scripts.get(caller_script_idx);
let analysis = self.script_analyses.get(&caller.name)?;
let instr_idx = analysis.nodes[node_idx].instruction_index?;
let instr = &caller.instructions[instr_idx];
match instr.opcode {
Opcode::Jump | Opcode::JumpWithParams => (
false,
match &instr.operand {
Operand::Int(id) => *id,
_ => return None,
},
),
Opcode::Gosub | Opcode::GosubWithParams => (
true,
match &instr.operand {
Operand::Int(id) => *id,
_ => return None,
},
),
_ => return None,
}
};
let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
let callee_name = self.scripts.get(callee_idx).name.clone();
self.ensure_analysis(&callee_name);
let callee = self.scripts.get(callee_idx);
let callee_source = callee.source_path.clone();
let first_body_line = callee
.instructions
.iter()
.find_map(|i| match (i.opcode, &i.operand) {
(Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
_ => None,
})
.unwrap_or(1);
let callee_trigger = callee.trigger.clone();
let callee_short_early = callee
.name
.trim_start_matches('[')
.trim_end_matches(']')
.split_once(',')
.map(|(_, n)| n.to_string())
.unwrap_or_else(|| callee.name.clone());
let callee_header_line = self
.source_cache
.and_then(|c| c.get(&callee_source))
.and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
.unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
let param_name = format!("${}", ptr_cmd);
let callee_short = callee
.name
.trim_start_matches('[')
.trim_end_matches(']')
.split_once(',')
.map(|(_, n)| n.to_string())
.unwrap_or_else(|| callee.name.clone());
let arrow = if is_gosub { "~" } else { "@" };
let corruptors = self.corruptors_in_callee(callee_idx, ptr);
let corruptor_phrase = format_corruptors(&corruptors);
let message = format!(
"`{callee}` reads `{ptr}` then {phrase}; the script still \
compiles and runs, but the reference is brittle to reorder. \
Consider capturing `{ptr}` at the call site and threading it \
through `{callee}` as an `{ty} {pname}` parameter so the \
value is explicit and stable.",
callee = callee_short,
ptr = ptr_cmd,
phrase = corruptor_phrase,
ty = param_type,
pname = param_name,
);
let cache = match self.source_cache {
Some(c) => c,
None => {
return Some(Help {
message,
suggestions: Vec::new(),
applicability: Applicability::Unspecified,
});
}
};
let mut suggestions = Vec::new();
if let Some(src) = cache.get(caller_source_path)
&& let Some(line_text) = nth_source_line(&src, caller_line)
&& let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
{
suggestions.push(Suggestion {
file: PathBuf::from(caller_source_path),
line_range: (caller_line, caller_line),
replacement: rewritten,
label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
});
}
if let Some(src) = cache.get(&callee_source)
&& let Some(header_text) = nth_source_line(&src, callee_header_line)
&& let Some(rewritten) =
rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
{
suggestions.push(Suggestion {
file: PathBuf::from(&callee_source),
line_range: (callee_header_line, callee_header_line),
replacement: rewritten,
label: Some(format!(
"at the `{}` header (add `{} {}`)",
callee_short, param_type, param_name
)),
});
}
Some(Help {
message,
suggestions,
applicability: Applicability::MaybeIncorrect,
})
}
}
fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
if !nodes[from].next.contains(&to) {
nodes[from].next.push(to);
}
if !nodes[to].previous.contains(&from) {
nodes[to].previous.push(from);
}
}
fn is_static_only_pointer(ptr: PointerType) -> bool {
use PointerType::*;
matches!(
ptr,
FindPlayer
| FindNpc
| FindLoc
| FindObj
| FindDb
| LastCom
| LastInt
| LastItem
| LastSlot
| LastTargetslot
| LastUseitem
| LastUseslot
)
}
fn short_script_name(full_name: &str) -> Option<String> {
full_name
.trim_start_matches('[')
.trim_end_matches(']')
.split_once(',')
.map(|(_, n)| n.to_string())
}
fn format_corruptors(corruptors: &[(String, usize)]) -> String {
if corruptors.is_empty() {
return "calls a delay or subroutine that may supersede it".to_string();
}
const MAX: usize = 3;
let shown: Vec<String> = corruptors
.iter()
.take(MAX)
.map(|(name, line)| {
if *line > 0 {
format!("`{}` at line {}", name, line)
} else {
format!("`{}`", name)
}
})
.collect();
let suffix = if corruptors.len() > MAX {
format!(" (and {} more)", corruptors.len() - MAX)
} else {
String::new()
};
let joined = match shown.len() {
1 => shown[0].clone(),
2 => format!("{} and {}", shown[0], shown[1]),
_ => {
let head = shown[..shown.len() - 1].join(", ");
format!("{}, and {}", head, shown[shown.len() - 1])
}
};
format!("calls {}{} which may supersede it", joined, suffix)
}
fn pointer_param_type(ptr: PointerType) -> &'static str {
use PointerType::*;
match ptr {
LastUseitem | LastItem => "obj",
LastCom => "component",
_ => "int",
}
}
fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
if line_no == 0 {
return None;
}
text.lines().nth(line_no - 1)
}
fn rewrite_call_site_arg(
line: &str,
arrow: &str,
callee_short: &str,
ptr_cmd: &str,
) -> Option<String> {
let needle = format!("{}{}", arrow, callee_short);
let start = line.find(&needle)?;
let after_name = start + needle.len();
let tail = &line[after_name..];
let first_non_ws = tail.chars().next();
if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
|| tail.trim_start().is_empty()
{
let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
out.push_str(&line[..after_name]);
out.push('(');
out.push_str(ptr_cmd);
out.push(')');
out.push_str(tail);
return Some(out);
}
if tail.trim_start().starts_with('(') {
let open_rel = tail.find('(')?;
let abs_open = after_name + open_rel;
let close_rel = find_matching_close_paren(&line[abs_open..])?;
let abs_close = abs_open + close_rel;
let inside = line[abs_open + 1..abs_close].trim();
let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
out.push_str(&line[..abs_close]);
if inside.is_empty() {
out.push_str(ptr_cmd);
} else {
out.push_str(", ");
out.push_str(ptr_cmd);
}
out.push_str(&line[abs_close..]);
return Some(out);
}
None
}
fn rewrite_header_add_param(
line: &str,
callee_short: &str,
param_type: &str,
param_name: &str,
) -> Option<String> {
let needle = format!(",{}]", callee_short);
let subject_end = line.find(&needle)?;
let after_bracket = subject_end + needle.len();
let remainder = &line[after_bracket..];
let added = format!("{} {}", param_type, param_name);
if !remainder.trim_start().starts_with('(') {
let mut out = String::with_capacity(line.len() + added.len() + 2);
out.push_str(&line[..after_bracket]);
out.push('(');
out.push_str(&added);
out.push(')');
out.push_str(remainder);
return Some(out);
}
let open_rel = remainder.find('(')?;
let abs_open = after_bracket + open_rel;
let close_rel = find_matching_close_paren(&line[abs_open..])?;
let abs_close = abs_open + close_rel;
let inside = line[abs_open + 1..abs_close].trim();
let mut out = String::with_capacity(line.len() + added.len() + 2);
out.push_str(&line[..abs_close]);
if inside.is_empty() {
out.push_str(&added);
} else {
out.push_str(", ");
out.push_str(&added);
}
out.push_str(&line[abs_close..]);
Some(out)
}
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
}
fn find_matching_close_paren(s: &str) -> Option<usize> {
let bytes = s.as_bytes();
if bytes.first().copied() != Some(b'(') {
return None;
}
let mut depth = 0i32;
for (i, &b) in bytes.iter().enumerate() {
match b {
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
return Some(i);
}
}
_ => {}
}
}
None
}
fn is_secondary_var_operand(operand: &Operand) -> bool {
match operand {
Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
_ => false,
}
}
fn resolve_target_node(
mut target_idx: usize,
instructions: &[Instruction],
instr_to_node: &HashMap<usize, usize>,
) -> Option<usize> {
while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
target_idx += 1;
}
instr_to_node.get(&target_idx).copied()
}
fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
nodes[from].next.retain(|&n| n != to);
nodes[to].previous.retain(|&n| n != from);
}
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
}
#[cfg(test)]
mod tests {
use super::*;
use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
use crate::symbol::SymbolRegistry;
fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
let mut reg = SymbolRegistry::new();
for &(name, opcode) in commands {
reg.register_command(name.to_string(), opcode, vec![], vec![]);
}
reg
}
fn make_script(
name: &str,
trigger: &str,
id: i32,
instructions: Vec<Instruction>,
) -> CompiledScript {
let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
script.trigger = trigger.to_string();
script.source_path = "test.rs2".to_string();
script.instructions = instructions;
script
}
fn cmd(opcode: i32) -> Instruction {
Instruction::new(Opcode::Command, Operand::Int(opcode))
}
fn line(n: i32) -> Instruction {
Instruction::new(Opcode::LineNumber, Operand::Int(n))
}
fn push_int(v: i32) -> Instruction {
Instruction::push_int(v)
}
fn branch_eq(target: usize) -> Instruction {
Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
}
fn branch(target: usize) -> Instruction {
Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
}
fn ret() -> Instruction {
Instruction::simple(Opcode::Return)
}
fn gosub(script_id: i32) -> Instruction {
Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
}
#[test]
fn conditional_setter_with_arg_push() {
let p_finduid_op = 4267;
let p_stopaction_op = 4268;
let registry = registry_with_commands(&[
("p_finduid", p_finduid_op),
("p_stopaction", p_stopaction_op),
]);
let instructions = vec![
line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
let script = make_script("test", "ai_timer", 0, instructions);
let scripts = vec![script];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
assert_eq!(
diags.warning_count(),
0,
"conditional setter should provide p_active_player on true branch, got {} warnings",
diags.warning_count()
);
}
#[test]
fn boolean_branches_preserve_conditional_pointer_analysis() {
let registry = registry_with_commands(&[("p_finduid", 4267), ("p_delay", 4268)]);
for (opcode, target, skip) in [(Opcode::BranchIfTrue, 5, 6), (Opcode::BranchIfFalse, 6, 5)]
{
let script = make_script(
"test",
"ai_timer",
0,
vec![
line(1),
push_int(0),
cmd(4267),
Instruction::new(opcode, Operand::JumpTarget(target)),
branch(skip),
cmd(4268),
ret(),
],
);
assert_eq!(
PointerChecker::new(&[script], ®istry)
.run()
.warning_count(),
0
);
}
let script = make_script(
"test",
"ai_timer",
0,
vec![
line(1),
push_int(0),
cmd(4267),
Instruction::new(Opcode::BranchIfFalse, Operand::JumpTarget(5)),
branch(6),
cmd(4268),
ret(),
],
);
assert!(
PointerChecker::new(&[script], ®istry)
.run()
.warning_count()
> 0
);
}
#[test]
fn gosub_requires_then_corrupts_same_pointer() {
let p_delay_op = 5001;
let npc_delay_op = 5002;
let registry =
registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
let proc_script = make_script(
"tackle_success",
"proc",
100,
vec![
line(1),
push_int(0),
cmd(p_delay_op), line(2),
push_int(0),
cmd(npc_delay_op), ret(),
],
);
let label_script = make_script(
"do_tackle",
"label",
200,
vec![
line(10),
gosub(100), ret(),
],
);
let scripts = vec![proc_script, label_script];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
assert_eq!(
diags.warning_count(),
0,
"gosub that requires-then-corrupts p_active_player should not \
be flagged (engine-tracked pointer), got {} warnings",
diags.warning_count()
);
}
#[test]
fn corruption_before_requirement_is_caught() {
let npc_delay_op = 5002;
let p_delay_op = 5001;
let registry =
registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
let script = make_script(
"bad_order",
"label",
0,
vec![
line(1),
push_int(0),
cmd(npc_delay_op), line(2),
push_int(0),
cmd(p_delay_op), ret(),
],
);
let scripts = vec![script];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
assert!(
diags.warning_count() > 0,
"corruption before requirement should be caught as a warning"
);
}
#[test]
fn uninitialized_pointer_caught() {
let p_delay_op = 5001;
let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
let script = make_script(
"bad_access",
"ai_timer",
0,
vec![
line(1),
push_int(0),
cmd(p_delay_op), ret(),
],
);
let scripts = vec![script];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
assert!(
diags.warning_count() > 0,
"uninitialized pointer access should be caught"
);
}
#[test]
fn branch_target_on_line_number_still_connects() {
let p_delay_op = 5001;
let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
let script = make_script(
"target_on_line_number",
"ai_timer",
0,
vec![
line(1),
push_int(1),
push_int(1),
branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
line(2),
push_int(0),
cmd(p_delay_op),
ret(),
],
);
let scripts = vec![script];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
assert!(
diags.warning_count() > 0,
"jump target on LineNumber must still flag uninitialized pointer \
access (got {} warnings)",
diags.warning_count()
);
}
#[test]
fn secondary_requires_and_corrupts_warns_for_static_pointer() {
let last_useitem_op = 4270;
let p_delay_op = 5001;
let registry =
registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
let callee = make_script(
"consume_useitem",
"label",
100,
vec![
line(1),
cmd(last_useitem_op), line(2),
push_int(0),
cmd(p_delay_op), ret(),
],
);
let caller = make_script(
"use_on_loc",
"oplocu",
200,
vec![
line(10),
Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
],
);
let scripts = vec![callee, caller];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
let last_useitem_warnings = diags
.diagnostics()
.iter()
.filter(|d| d.severity == Severity::Warning)
.filter(|d| d.message.contains("last_useitem"))
.count();
assert!(
last_useitem_warnings > 0,
"static-only pointer (last_useitem) should trigger the \
require+corrupt warning at the jump site; got diags: {:?}",
diags
.diagnostics()
.iter()
.map(|d| &d.message)
.collect::<Vec<_>>()
);
assert_eq!(
diags.error_count(),
0,
"pointer-check diagnostics must never raise error severity; got {} errors",
diags.error_count()
);
}
#[test]
fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
let p_delay_op = 5001;
let npc_delay_op = 5002;
let registry =
registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
let callee = make_script(
"consume_protected",
"proc",
100,
vec![
line(1),
push_int(0),
cmd(p_delay_op), line(2),
push_int(0),
cmd(npc_delay_op), ret(),
],
);
let caller = make_script(
"do_opnpc",
"opnpc1",
200,
vec![
line(10),
Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
ret(),
],
);
let scripts = vec![callee, caller];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
let p_active_player_warnings = diags
.diagnostics()
.iter()
.filter(|d| d.severity == Severity::Warning)
.filter(|d| d.message.contains("p_active_player"))
.count();
assert_eq!(
p_active_player_warnings, 0,
"engine-tracked pointer (p_active_player) must not trigger the \
require+corrupt warning; got {} such warnings",
p_active_player_warnings
);
}
#[test]
fn secondary_varn_requires_active_npc2_not_primary() {
let secondary_varn = Instruction::new(
Opcode::PushVarn,
Operand::Int(1 << 16), );
let proc_script = make_script(
"reads_secondary_varn",
"proc",
100,
vec![
line(1),
secondary_varn,
Instruction::simple(Opcode::PopIntDiscard),
ret(),
],
);
let caller = make_script(
"gosub_into_proc",
"opplayer1",
200,
vec![line(10), gosub(100), ret()],
);
let scripts = vec![proc_script, caller];
let registry = registry_with_commands(&[]);
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
let active_npc_primary_warnings = diags
.diagnostics()
.iter()
.filter(|d| d.severity == Severity::Warning)
.filter(|d| d.message.contains("pointer active_npc."))
.count();
assert_eq!(
active_npc_primary_warnings,
0,
"secondary .%var read must not flag primary active_npc at the \
caller; got diags: {:?}",
diags
.diagnostics()
.iter()
.filter(|d| d.severity == Severity::Warning)
.map(|d| &d.message)
.collect::<Vec<_>>()
);
let active_npc2_warnings = diags
.diagnostics()
.iter()
.filter(|d| d.severity == Severity::Warning)
.filter(|d| d.message.contains("pointer .active_npc."))
.count();
assert!(
active_npc2_warnings > 0,
"secondary .%var should route the requirement to active_npc2; \
got no such warning"
);
}
#[test]
fn rewrite_call_site_no_args() {
let got = rewrite_call_site_arg(
"[opnpcu,wantcat1] @civilian_give_runes;",
"@",
"civilian_give_runes",
"last_useitem",
)
.unwrap();
assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
}
#[test]
fn rewrite_call_site_with_args() {
let got = rewrite_call_site_arg(
"[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
"@",
"amulet_of_glory_interface",
"last_item",
)
.unwrap();
assert_eq!(
got,
"[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
);
}
#[test]
fn rewrite_call_site_gosub_no_args() {
let got =
rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
assert_eq!(got, " ~some_proc(last_useitem);");
}
#[test]
fn rewrite_call_site_empty_arg_list() {
let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
assert_eq!(got, "@foo(last_useitem);");
}
#[test]
fn rewrite_header_no_params() {
let got = rewrite_header_add_param(
"[label,civilian_give_runes]",
"civilian_give_runes",
"obj",
"$last_useitem",
)
.unwrap();
assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
}
#[test]
fn rewrite_header_with_existing_params() {
let got = rewrite_header_add_param(
"[label,amulet_of_glory_interface](string $message)",
"amulet_of_glory_interface",
"obj",
"$last_item",
)
.unwrap();
assert_eq!(
got,
"[label,amulet_of_glory_interface](string $message, obj $last_item)"
);
}
#[test]
fn rewrite_header_proc_with_return_type() {
let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
assert_eq!(got, "[proc,foo](obj $x)(int)");
}
#[test]
fn find_header_line_matches_trigger_and_name() {
let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
assert_eq!(find_header_line(src, "label", "foo"), Some(2));
assert_eq!(find_header_line(src, "label", "bar"), Some(4));
assert_eq!(find_header_line(src, "label", "missing"), None);
}
#[test]
fn format_corruptors_shapes() {
assert_eq!(
format_corruptors(&[]),
"calls a delay or subroutine that may supersede it"
);
assert_eq!(
format_corruptors(&[("p_delay".to_string(), 21)]),
"calls `p_delay` at line 21 which may supersede it"
);
assert_eq!(
format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
"calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
);
assert_eq!(
format_corruptors(&[
("p_delay".to_string(), 21),
("~chatnpc".to_string(), 11),
("~objbox".to_string(), 14),
]),
"calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
);
assert_eq!(
format_corruptors(&[
("p_delay".to_string(), 1),
("~a".to_string(), 2),
("~b".to_string(), 3),
("~c".to_string(), 4),
("~d".to_string(), 5),
]),
"calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
);
assert_eq!(
format_corruptors(&[("p_delay".to_string(), 0)]),
"calls `p_delay` which may supersede it"
);
}
#[test]
fn find_matching_close_paren_nested() {
assert_eq!(find_matching_close_paren("()"), Some(1));
assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
assert_eq!(find_matching_close_paren("("), None);
assert_eq!(find_matching_close_paren("abc"), None);
}
#[test]
fn secondary_warning_attaches_help_with_rewrite_suggestions() {
use std::collections::HashMap;
use std::sync::Arc;
let last_useitem_op = 4270;
let p_delay_op = 5001;
let registry =
registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
let mut callee = make_script(
"consume_useitem",
"label",
100,
vec![
line(2), cmd(last_useitem_op),
line(3),
push_int(0),
cmd(p_delay_op),
ret(),
],
);
callee.source_path = "/virt/consume.rs2".to_string();
let mut caller = make_script(
"use_on_loc",
"oplocu",
200,
vec![
line(1),
Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
],
);
caller.source_path = "/virt/caller.rs2".to_string();
let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
source_cache.insert(
"/virt/caller.rs2".to_string(),
Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
);
source_cache.insert(
"/virt/consume.rs2".to_string(),
Arc::new(
"[label,consume_useitem]\n\
last_useitem;\n\
p_delay(0);\n"
.to_string(),
),
);
let scripts = vec![callee, caller];
let mut checker = PointerChecker::new(&scripts, ®istry);
checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
let diags = checker.run();
let warning = diags
.diagnostics()
.iter()
.find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
.expect("expected a stale-last_useitem warning");
assert_eq!(
warning.help.len(),
1,
"warning should have exactly one Help block, got {}",
warning.help.len()
);
let help = &warning.help[0];
assert!(
help.message.contains("consume_useitem"),
"help message should name the callee, got: {}",
help.message
);
assert!(
help.message.contains("last_useitem"),
"help message should name the pointer, got: {}",
help.message
);
assert_eq!(
help.suggestions.len(),
2,
"help should include both call-site and header suggestions, \
got {}: {:?}",
help.suggestions.len(),
help.suggestions
.iter()
.map(|s| &s.label)
.collect::<Vec<_>>()
);
let caller_sug = help
.suggestions
.iter()
.find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
.expect("expected a call-site suggestion on the caller file");
assert!(
caller_sug
.replacement
.contains("@consume_useitem(last_useitem)"),
"call-site replacement must pass last_useitem as an arg, got: {}",
caller_sug.replacement
);
let header_sug = help
.suggestions
.iter()
.find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
.expect("expected a header suggestion on the callee file");
assert!(
header_sug.replacement.contains("(obj $last_useitem)"),
"header replacement must add `obj $last_useitem` param, got: {}",
header_sug.replacement
);
assert_eq!(help.applicability, Applicability::MaybeIncorrect);
}
#[test]
fn secondary_warning_falls_back_to_prose_help_without_source() {
let last_useitem_op = 4270;
let p_delay_op = 5001;
let registry =
registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
let callee = make_script(
"consume_useitem",
"label",
100,
vec![
line(1),
cmd(last_useitem_op),
line(2),
push_int(0),
cmd(p_delay_op),
ret(),
],
);
let caller = make_script(
"use_on_loc",
"oplocu",
200,
vec![
line(1),
Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
],
);
let scripts = vec![callee, caller];
let mut checker = PointerChecker::new(&scripts, ®istry);
let diags = checker.run();
let warning = diags
.diagnostics()
.iter()
.find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
.expect("warning still fires without source cache");
assert_eq!(warning.help.len(), 1);
let help = &warning.help[0];
assert_eq!(
help.suggestions.len(),
0,
"prose-only help should have no concrete suggestions"
);
assert_eq!(help.applicability, Applicability::Unspecified);
}
}