1use std::collections::{HashMap, HashSet, VecDeque};
2use std::path::PathBuf;
3
4use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
5use crate::diagnostic_messages as msg;
6use crate::diagnostics::{
7 Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
8};
9use crate::pointer::{PointerHolder, PointerSet, PointerType, command_pointers, trigger_pointers};
10use crate::symbol::{SymbolKind, SymbolRegistry};
11
12#[derive(Debug)]
17struct CfgNode {
18 instruction_index: Option<usize>,
21 pointer_set: PointerSet,
23 next: Vec<usize>,
25 previous: Vec<usize>,
27}
28
29impl CfgNode {
30 fn new(instruction_index: Option<usize>) -> Self {
31 CfgNode {
32 instruction_index,
33 pointer_set: PointerSet::new(),
34 next: Vec::new(),
35 previous: Vec::new(),
36 }
37 }
38
39 fn pointer_node(pointer_set: PointerSet) -> Self {
40 CfgNode {
41 instruction_index: None,
42 pointer_set,
43 next: Vec::new(),
44 previous: Vec::new(),
45 }
46 }
47}
48
49struct ScriptAnalysis {
54 nodes: Vec<CfgNode>,
55 required: Vec<Vec<usize>>,
57 set_list: Vec<Vec<usize>>,
59 corrupted_list: Vec<Vec<usize>>,
61 set_nodes: Vec<HashSet<usize>>,
63 corrupted_nodes: Vec<HashSet<usize>>,
64 returns: Vec<usize>,
66}
67
68impl ScriptAnalysis {
69 fn new() -> Self {
70 let n = PointerType::COUNT;
71 ScriptAnalysis {
72 nodes: Vec::new(),
73 required: vec![Vec::new(); n],
74 set_list: vec![Vec::new(); n],
75 corrupted_list: vec![Vec::new(); n],
76 set_nodes: vec![HashSet::new(); n],
77 corrupted_nodes: vec![HashSet::new(); n],
78 returns: Vec::new(),
79 }
80 }
81}
82
83pub struct PointerChecker<'a> {
88 scripts: &'a [CompiledScript],
89 cmd_pointers: HashMap<String, PointerHolder>,
90 #[allow(dead_code)]
91 registry: &'a SymbolRegistry,
92 opcode_to_name: HashMap<i32, String>,
94 script_id_to_index: HashMap<i32, usize>,
96 overlay_interfaces: HashSet<String>,
99 source_cache: Option<&'a HashMap<String, std::rc::Rc<String>>>,
104 script_analyses: HashMap<String, ScriptAnalysis>,
106 script_pointers: HashMap<String, PointerHolder>,
107 pending_analyses: HashSet<String>,
108 pending_scripts: HashSet<String>,
109}
110
111impl<'a> PointerChecker<'a> {
112 pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
113 let mut opcode_to_name = HashMap::new();
115 for (name, sym) in ®istry.commands {
116 if let SymbolKind::Command { opcode, .. } = &sym.kind {
117 opcode_to_name.insert(*opcode, name.to_lowercase());
118 }
119 }
120
121 let mut script_id_to_index = HashMap::new();
123 for (i, script) in scripts.iter().enumerate() {
124 script_id_to_index.insert(script.id, i);
125 }
126
127 let mut overlay_interfaces = HashSet::new();
131 for (name, sym) in ®istry.entity_ids {
132 if let SymbolKind::Constant { const_type, .. } = &sym.kind
133 && *const_type == crate::types::Type::OverlayInterface
134 {
135 overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
136 }
137 }
138
139 PointerChecker {
140 scripts,
141 cmd_pointers: command_pointers(),
142 registry,
143 opcode_to_name,
144 script_id_to_index,
145 overlay_interfaces,
146 source_cache: None,
147 script_analyses: HashMap::new(),
148 script_pointers: HashMap::new(),
149 pending_analyses: HashSet::new(),
150 pending_scripts: HashSet::new(),
151 }
152 }
153
154 pub fn set_source_cache(&mut self, cache: &'a HashMap<String, std::rc::Rc<String>>) {
158 self.source_cache = Some(cache);
159 }
160
161 fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
164 if !crate::trigger_table::is_button(trigger) {
165 return false;
166 }
167 let subject = script_name
169 .trim_start_matches('[')
170 .trim_end_matches(']')
171 .split_once(',')
172 .map(|(_, rest)| rest)
173 .unwrap_or("");
174 let iface_name = subject
175 .split(':')
176 .next()
177 .unwrap_or("")
178 .to_lowercase()
179 .replace(' ', "_");
180 if iface_name.is_empty() {
181 return false;
182 }
183 !self.overlay_interfaces.contains(&iface_name)
185 }
186
187 pub fn run(&mut self) -> DiagnosticsCollector {
189 let mut diagnostics = DiagnosticsCollector::new();
190
191 let script_names: Vec<String> = self.scripts.iter().map(|s| s.name.clone()).collect();
193
194 for script_name in &script_names {
195 self.validate_script(script_name, &mut diagnostics);
196 }
197
198 diagnostics
199 }
200
201 fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
202 let script_idx = match self.scripts.iter().position(|s| s.name == script_name) {
204 Some(i) => i,
205 None => return,
206 };
207 let trigger = self.scripts[script_idx].trigger.clone();
208 let source_path = self.scripts[script_idx].source_path.clone();
209 let trigger_set = trigger_pointers(&trigger);
210
211 self.ensure_analysis(script_name);
213
214 for &ptr in &PointerType::ALL {
215 let ptr_idx = ptr.index();
216
217 let analysis = match self.script_analyses.get(script_name) {
219 Some(a) => a,
220 None => continue,
221 };
222
223 let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
224 if required_nodes.is_empty() {
225 continue;
226 }
227
228 let mut corrupted: HashSet<usize> = analysis.corrupted_nodes[ptr_idx].clone();
230
231 let trigger_provides = if trigger_set.contains(ptr) {
235 true
236 } else if ptr == PointerType::PActivePlayer {
237 self.interface_trigger_grants_protected(&trigger, script_name)
238 } else {
239 false
240 };
241 if !trigger_provides {
242 corrupted.insert(0);
243 }
244
245 if corrupted.is_empty() {
246 continue;
247 }
248
249 let set_blocked: HashSet<usize> = analysis.set_nodes[ptr_idx].clone();
250
251 let path = self.find_edge_path(
253 script_name,
254 &required_nodes,
255 |node_idx| corrupted.contains(&node_idx),
256 &set_blocked,
257 );
258
259 let mut reported_via_main_bfs = false;
260 if let Some(path) = path {
261 if path.is_empty() {
262 continue;
263 }
264 reported_via_main_bfs = true;
265
266 let end_node_idx = path[path.len() - 1];
267 let start_node_idx = path[0];
268
269 let is_start_node = end_node_idx == 0;
270 let repr = ptr.representation();
271 let static_only = is_static_only_pointer(ptr);
272
273 let error_msg = if is_start_node {
279 if static_only {
280 msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
281 } else {
282 msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
283 }
284 } else if static_only {
285 msg::fmt(msg::POINTER_STALE, &[repr])
286 } else {
287 msg::fmt(msg::POINTER_CORRUPTED, &[repr])
288 };
289
290 let analysis = self.script_analyses.get(script_name).unwrap();
291 let instructions = &self.scripts[script_idx].instructions;
292 let req_line = analysis.nodes[start_node_idx]
293 .instruction_index
294 .map(|idx| resolve_line(instructions, idx))
295 .unwrap_or(0);
296
297 diagnostics.add(Diagnostic {
302 file: PathBuf::from(&source_path),
303 line: req_line,
304 column: 0,
305 message: error_msg,
306 severity: Severity::Warning,
307 phase: Phase::PointerCheck,
308 help: Vec::new(),
309 });
310
311 let read_hint = if static_only {
312 msg::fmt(msg::POINTER_READ_HERE, &[repr])
313 } else {
314 msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
315 };
316 diagnostics.add(Diagnostic {
317 file: PathBuf::from(&source_path),
318 line: req_line,
319 column: 0,
320 message: read_hint,
321 severity: Severity::Info,
322 phase: Phase::PointerCheck,
323 help: Vec::new(),
324 });
325
326 if !is_start_node {
327 let corrupt_line = analysis.nodes[end_node_idx]
328 .instruction_index
329 .map(|idx| resolve_line(instructions, idx))
330 .unwrap_or(0);
331
332 let cause_hint = if static_only {
333 msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
334 } else {
335 msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
336 };
337 diagnostics.add(Diagnostic {
338 file: PathBuf::from(&source_path),
339 line: corrupt_line,
340 column: 0,
341 message: cause_hint,
342 severity: Severity::Info,
343 phase: Phase::PointerCheck,
344 help: Vec::new(),
345 });
346 }
347 }
348
349 if !reported_via_main_bfs && is_static_only_pointer(ptr) {
362 let analysis = self.script_analyses.get(script_name).unwrap();
363 let instructions = &self.scripts[script_idx].instructions;
364 let corrupted_nodes = &analysis.corrupted_nodes[ptr_idx];
365 let mut seen_lines: HashSet<usize> = HashSet::new();
366 let repr = ptr.representation();
367 for &node_idx in &required_nodes {
368 if !corrupted_nodes.contains(&node_idx) {
369 continue;
370 }
371 let line = analysis.nodes[node_idx]
372 .instruction_index
373 .map(|idx| resolve_line(instructions, idx))
374 .unwrap_or(0);
375 if !seen_lines.insert(line) {
376 continue;
377 }
378
379 let help =
384 self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
385
386 let mut diag = Diagnostic {
394 file: PathBuf::from(&source_path),
395 line,
396 column: 0,
397 message: msg::fmt(msg::POINTER_STALE, &[repr]),
398 severity: Severity::Warning,
399 phase: Phase::PointerCheck,
400 help: Vec::new(),
401 };
402 if let Some(h) = help {
403 diag.help.push(h);
404 }
405 diagnostics.add(diag);
406 }
407 }
408 }
409 }
410
411 fn find_edge_path(
420 &self,
421 script_name: &str,
422 starts: &[usize],
423 end_pred: impl Fn(usize) -> bool,
424 blocked: &HashSet<usize>,
425 ) -> Option<Vec<usize>> {
426 let analysis = self.script_analyses.get(script_name)?;
427
428 let mut queue: VecDeque<usize> = VecDeque::new();
429 let mut visited: HashSet<usize> = HashSet::new();
430 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); for &start in starts {
438 for &prev in &analysis.nodes[start].previous {
439 if blocked.contains(&prev) || visited.contains(&prev) {
440 continue;
441 }
442 visited.insert(prev);
443 queue.push_back(prev);
444 sources.insert(prev, (start, start));
445 }
446 }
447
448 while let Some(current) = queue.pop_front() {
449 if end_pred(current) {
450 let mut path = vec![current];
452 let mut node = current;
453 while let Some(&(from, start)) = sources.get(&node) {
454 if from == start && starts.contains(&from) {
455 path.push(from);
456 break;
457 }
458 path.push(from);
459 node = from;
460 }
461 path.reverse();
462 return Some(path);
463 }
464
465 let (_, start_node) = sources[¤t];
466
467 for &prev in &analysis.nodes[current].previous {
468 if blocked.contains(&prev) || visited.contains(&prev) {
469 continue;
470 }
471 visited.insert(prev);
472 queue.push_back(prev);
473 sources.insert(prev, (current, start_node));
474 }
475 }
476
477 None
478 }
479
480 fn find_edge_path_static(
483 nodes: &[CfgNode],
484 starts: &[usize],
485 end_pred: impl Fn(usize) -> bool,
486 blocked: &HashSet<usize>,
487 ) -> Option<Vec<usize>> {
488 let mut queue: VecDeque<usize> = VecDeque::new();
489 let mut visited: HashSet<usize> = HashSet::new();
490 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
491
492 for &start in starts {
493 for &prev in &nodes[start].previous {
494 if blocked.contains(&prev) || visited.contains(&prev) {
495 continue;
496 }
497 visited.insert(prev);
498 queue.push_back(prev);
499 sources.insert(prev, (start, start));
500 }
501 }
502
503 while let Some(current) = queue.pop_front() {
504 if end_pred(current) {
505 let mut path = vec![current];
506 let mut node = current;
507 while let Some(&(from, start)) = sources.get(&node) {
508 if from == start && starts.contains(&from) {
509 path.push(from);
510 break;
511 }
512 path.push(from);
513 node = from;
514 }
515 path.reverse();
516 return Some(path);
517 }
518
519 for &prev in &nodes[current].previous {
520 if blocked.contains(&prev) || visited.contains(&prev) {
521 continue;
522 }
523 visited.insert(prev);
524 queue.push_back(prev);
525 sources.insert(prev, (current, sources[¤t].1));
526 }
527 }
528
529 None
530 }
531
532 fn ensure_analysis(&mut self, script_name: &str) {
537 if self.script_analyses.contains_key(script_name) {
538 return;
539 }
540 if self.pending_analyses.contains(script_name) {
541 return; }
543 self.pending_analyses.insert(script_name.to_string());
544
545 let script_idx = match self.scripts.iter().position(|s| s.name == script_name) {
546 Some(i) => i,
547 None => return,
548 };
549
550 let mut analysis = self.build_cfg(script_idx);
551 self.categorize_nodes(script_idx, &mut analysis);
552
553 self.script_analyses
554 .insert(script_name.to_string(), analysis);
555 self.pending_analyses.remove(script_name);
556 }
557
558 fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
563 let script = &self.scripts[script_idx];
564 let instructions = &script.instructions;
565 let mut analysis = ScriptAnalysis::new();
566
567 analysis.nodes.push(CfgNode::new(None));
569
570 let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
572 let mut node_order: Vec<usize> = Vec::new(); for (i, instr) in instructions.iter().enumerate() {
575 if instr.opcode == Opcode::LineNumber {
576 continue;
577 }
578 let node_idx = analysis.nodes.len();
579 instr_to_node.insert(i, node_idx);
580 node_order.push(i);
581 analysis.nodes.push(CfgNode::new(Some(i)));
582 }
583
584 if node_order.is_empty() {
585 return analysis;
586 }
587
588 let first_node = instr_to_node[&node_order[0]];
590 add_edge(&mut analysis.nodes, 0, first_node);
591
592 for (order_idx, &instr_idx) in node_order.iter().enumerate() {
594 let node_idx = instr_to_node[&instr_idx];
595 let instr = &instructions[instr_idx];
596
597 let is_terminal = matches!(
598 instr.opcode,
599 Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
600 );
601
602 match instr.opcode {
607 Opcode::Branch
608 | Opcode::BranchNot
609 | Opcode::BranchEquals
610 | Opcode::BranchLessThan
611 | Opcode::BranchGreaterThan
612 | Opcode::BranchLessThanOrEquals
613 | Opcode::BranchGreaterThanOrEquals
614 | Opcode::LongBranchNot
615 | Opcode::LongBranchEquals
616 | Opcode::LongBranchLessThan
617 | Opcode::LongBranchGreaterThan
618 | Opcode::LongBranchLessThanOrEquals
619 | Opcode::LongBranchGreaterThanOrEquals
620 | Opcode::ObjBranchEquals
621 | Opcode::ObjBranchNot => {
622 if let Operand::JumpTarget(target_instr_idx) = &instr.operand
623 && let Some(target_node) =
624 resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
625 {
626 add_edge(&mut analysis.nodes, node_idx, target_node);
627 }
628 }
629
630 Opcode::Switch => {
631 if let Operand::SwitchTable(cases) = &instr.operand {
632 for &(_, target_instr_idx) in cases {
633 if let Some(target_node) =
634 resolve_target_node(target_instr_idx, instructions, &instr_to_node)
635 {
636 add_edge(&mut analysis.nodes, node_idx, target_node);
637 }
638 }
639 }
640 }
641
642 _ => {}
643 }
644
645 if !is_terminal
647 && let Some(next_order_idx) = order_idx.checked_add(1)
648 && next_order_idx < node_order.len()
649 {
650 let next_node = instr_to_node[&node_order[next_order_idx]];
651 add_edge(&mut analysis.nodes, node_idx, next_node);
652 }
653
654 if instr.opcode == Opcode::Return {
659 analysis.returns.push(node_idx);
660 }
661 }
662
663 self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
665
666 analysis
667 }
668
669 fn insert_pointer_nodes(
672 &self,
673 script_idx: usize,
674 analysis: &mut ScriptAnalysis,
675 instr_to_node: &HashMap<usize, usize>,
676 node_order: &[usize],
677 ) {
678 let instructions = &self.scripts[script_idx].instructions;
679
680 for window_end in 2..node_order.len() {
685 let push_instr_idx = node_order[window_end - 1];
686 let branch_instr_idx = node_order[window_end];
687
688 let push_instr = &instructions[push_instr_idx];
689 let branch_instr = &instructions[branch_instr_idx];
690
691 let push_value = match &push_instr.operand {
693 Operand::Int(v) if *v == 0 || *v == 1 => *v,
694 _ => continue,
695 };
696 if push_instr.opcode != Opcode::PushConstantInt {
697 continue;
698 }
699 if branch_instr.opcode != Opcode::BranchEquals {
700 continue;
701 }
702
703 let mut cmd_instr_idx = None;
705 for scan in (0..window_end - 1).rev() {
706 let idx = node_order[scan];
707 if instructions[idx].opcode == Opcode::Command {
708 cmd_instr_idx = Some(idx);
709 break;
710 }
711 if matches!(
713 instructions[idx].opcode,
714 Opcode::Branch
715 | Opcode::Return
716 | Opcode::Switch
717 | Opcode::BranchEquals
718 | Opcode::BranchNot
719 | Opcode::BranchLessThan
720 | Opcode::BranchGreaterThan
721 | Opcode::BranchLessThanOrEquals
722 | Opcode::BranchGreaterThanOrEquals
723 ) {
724 break;
725 }
726 }
727 let cmd_instr_idx = match cmd_instr_idx {
728 Some(idx) => idx,
729 None => continue,
730 };
731 let cmd_instr = &instructions[cmd_instr_idx];
732
733 let cmd_name = self.resolve_command_name(cmd_instr);
735 let cmd_name = match cmd_name {
736 Some(n) => n,
737 None => continue,
738 };
739
740 let holder = match self.cmd_pointers.get(&cmd_name) {
741 Some(h) => h,
742 None => continue,
743 };
744
745 if !holder.conditional_set {
746 continue;
747 }
748
749 if holder.set.is_empty() {
750 continue;
751 }
752
753 let branch_node_idx = instr_to_node[&branch_instr_idx];
754
755 let ptr_node_idx = analysis.nodes.len();
757 analysis.nodes.push(CfgNode::pointer_node(holder.set));
758
759 if push_value == 0 {
760 let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
768 .next
769 .iter()
770 .copied()
771 .filter(|&n| {
772 if let Operand::JumpTarget(target) = &branch_instr.operand
774 && let Some(jump_node) =
775 resolve_target_node(*target, instructions, instr_to_node)
776 {
777 return n != jump_node;
778 }
779 true
780 })
781 .collect();
782
783 for ft_target in fallthrough_targets {
784 remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
786 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
788 add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
789 }
790 } else {
791 if let Operand::JumpTarget(target) = &branch_instr.operand
795 && let Some(jump_target_node) =
796 resolve_target_node(*target, instructions, instr_to_node)
797 {
798 remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
800 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
802 add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
803 }
804 }
805 }
806 }
807
808 fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
813 let instructions = &self.scripts[script_idx].instructions;
814
815 for node_idx in 0..analysis.nodes.len() {
816 let instr_idx = match analysis.nodes[node_idx].instruction_index {
817 Some(i) => i,
818 None => {
819 let ptr_set = analysis.nodes[node_idx].pointer_set;
821 if !ptr_set.is_empty() {
822 for ptr in ptr_set.iter() {
823 let pi = ptr.index();
824 analysis.set_list[pi].push(node_idx);
825 analysis.set_nodes[pi].insert(node_idx);
826 }
827 }
828 continue;
829 }
830 };
831
832 let instr = &instructions[instr_idx];
833
834 match instr.opcode {
835 Opcode::Command => {
836 let cmd_name = self.resolve_command_name(instr);
837 if let Some(name) = cmd_name
838 && let Some(holder) = self.cmd_pointers.get(&name).cloned()
839 {
840 self.apply_holder(analysis, node_idx, &holder);
841 }
842 }
843
844 Opcode::Gosub | Opcode::GosubWithParams => {
845 if let Operand::Int(script_id) = &instr.operand {
846 let callee_holder = self.get_script_pointers(*script_id);
847 self.apply_holder(analysis, node_idx, &callee_holder);
848 }
849 }
850
851 Opcode::Jump | Opcode::JumpWithParams => {
852 if let Operand::Int(script_id) = &instr.operand {
853 let callee_holder = self.get_script_pointers(*script_id);
854 self.apply_holder(analysis, node_idx, &callee_holder);
855 }
856 }
857
858 Opcode::PushVarp | Opcode::PushVarbit => {
865 let pi = if is_secondary_var_operand(&instr.operand) {
866 PointerType::ActivePlayer2.index()
867 } else {
868 PointerType::ActivePlayer.index()
869 };
870 analysis.required[pi].push(node_idx);
871 }
872
873 Opcode::PopVarp | Opcode::PopVarbit => {
874 let pi = if is_secondary_var_operand(&instr.operand) {
875 PointerType::ActivePlayer2.index()
876 } else {
877 PointerType::ActivePlayer.index()
878 };
879 analysis.required[pi].push(node_idx);
880 }
881
882 Opcode::PushVarn | Opcode::PopVarn => {
883 let pi = if is_secondary_var_operand(&instr.operand) {
884 PointerType::ActiveNpc2.index()
885 } else {
886 PointerType::ActiveNpc.index()
887 };
888 analysis.required[pi].push(node_idx);
889 }
890
891 _ => {}
893 }
894 }
895 }
896
897 fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
898 for ptr in holder.required.iter() {
899 let pi = ptr.index();
900 analysis.required[pi].push(node_idx);
901 }
902 for ptr in holder.set.iter() {
903 let pi = ptr.index();
904 analysis.set_list[pi].push(node_idx);
905 analysis.set_nodes[pi].insert(node_idx);
906 }
907 for ptr in holder.corrupted.iter() {
908 let pi = ptr.index();
909 analysis.corrupted_list[pi].push(node_idx);
910 analysis.corrupted_nodes[pi].insert(node_idx);
911 }
912 }
913
914 fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
930 let script_idx = match self.script_id_to_index.get(&script_id) {
932 Some(&i) => i,
933 None => {
934 return PointerHolder::default();
935 }
936 };
937 let script_name = self.scripts[script_idx].name.clone();
938
939 if let Some(holder) = self.script_pointers.get(&script_name) {
941 return holder.clone();
942 }
943
944 if self.pending_scripts.contains(&script_name) {
946 return PointerHolder::default();
947 }
948 self.pending_scripts.insert(script_name.clone());
949
950 self.ensure_analysis(&script_name);
952
953 let mut holder = PointerHolder::default();
954
955 if let Some(analysis) = self.script_analyses.get(&script_name) {
956 for &ptr in &PointerType::ALL {
957 let pi = ptr.index();
958
959 if !analysis.required[pi].is_empty() {
961 let path = Self::find_edge_path_static(
962 &analysis.nodes,
963 &analysis.required[pi],
964 |node_idx| node_idx == 0,
965 &analysis.set_nodes[pi],
966 );
967 if path.is_some() {
968 holder.required.insert(ptr);
969 }
970 }
971
972 if !analysis.returns.is_empty() {
975 let corrupted_nodes = &analysis.corrupted_nodes[pi];
976 let path = Self::find_edge_path_static(
977 &analysis.nodes,
978 &analysis.returns,
979 |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
980 &analysis.set_nodes[pi],
981 );
982 if path.is_none() {
983 holder.set.insert(ptr);
984 }
985 }
986
987 if !analysis.returns.is_empty() && !analysis.corrupted_nodes[pi].is_empty() {
989 let corrupted_nodes = &analysis.corrupted_nodes[pi];
990 let path = Self::find_edge_path_static(
991 &analysis.nodes,
992 &analysis.returns,
993 |node_idx| corrupted_nodes.contains(&node_idx),
994 &analysis.set_nodes[pi],
995 );
996 if path.is_some() {
997 holder.corrupted.insert(ptr);
998 }
999 }
1000 }
1001 }
1002
1003 self.pending_scripts.remove(&script_name);
1004
1005 self.script_pointers
1006 .insert(script_name.clone(), holder.clone());
1007 holder
1008 }
1009
1010 fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1020 let callee = &self.scripts[callee_idx];
1021 let analysis = match self.script_analyses.get(&callee.name) {
1022 Some(a) => a,
1023 None => return Vec::new(),
1024 };
1025 let ptr_idx = ptr.index();
1026 let mut seen: HashSet<(String, usize)> = HashSet::new();
1027 let mut result: Vec<(String, usize)> = Vec::new();
1028
1029 for &node_idx in &analysis.corrupted_list[ptr_idx] {
1030 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1031 Some(i) => i,
1032 None => continue,
1033 };
1034 let instr = &callee.instructions[instr_idx];
1035 let line = resolve_line(&callee.instructions, instr_idx);
1036
1037 let name = match instr.opcode {
1038 Opcode::Command => match self.resolve_command_name(instr) {
1039 Some(n) => n,
1040 None => continue,
1041 },
1042 Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1043 Operand::Int(id) => match self.script_id_to_index.get(id) {
1044 Some(&target_idx) => short_script_name(&self.scripts[target_idx].name)
1045 .map(|s| format!("~{}", s))
1046 .unwrap_or_else(|| self.scripts[target_idx].name.clone()),
1047 None => continue,
1048 },
1049 _ => continue,
1050 },
1051 _ => continue,
1055 };
1056
1057 let key = (name.clone(), line);
1058 if seen.insert(key) {
1059 result.push((name, line));
1060 }
1061 }
1062
1063 result
1064 }
1065
1066 fn resolve_command_name(&self, instr: &Instruction) -> Option<String> {
1067 match &instr.operand {
1068 Operand::Int(encoded) => {
1069 let opcode = encoded & 0xFFFF;
1070 let secondary = (encoded >> 16) & 1;
1071 let base_name = self.opcode_to_name.get(&opcode)?;
1072 if secondary == 1 {
1073 Some(format!(".{}", base_name))
1074 } else {
1075 Some(base_name.clone())
1076 }
1077 }
1078 Operand::Str(name) => Some(name.to_lowercase()),
1079 _ => None,
1080 }
1081 }
1082
1083 fn build_rule_a_help(
1095 &self,
1096 ptr: PointerType,
1097 caller_source_path: &str,
1098 caller_line: usize,
1099 node_idx: usize,
1100 caller_script_idx: usize,
1101 ) -> Option<Help> {
1102 let analysis = self
1103 .script_analyses
1104 .get(&self.scripts[caller_script_idx].name)?;
1105 let caller_instructions = &self.scripts[caller_script_idx].instructions;
1106 let instr_idx = analysis.nodes[node_idx].instruction_index?;
1107 let instr = &caller_instructions[instr_idx];
1108
1109 let (is_gosub, script_id) = match instr.opcode {
1111 Opcode::Jump | Opcode::JumpWithParams => (
1112 false,
1113 match &instr.operand {
1114 Operand::Int(id) => *id,
1115 _ => return None,
1116 },
1117 ),
1118 Opcode::Gosub | Opcode::GosubWithParams => (
1119 true,
1120 match &instr.operand {
1121 Operand::Int(id) => *id,
1122 _ => return None,
1123 },
1124 ),
1125 _ => return None,
1126 };
1127
1128 let callee_idx = *self.script_id_to_index.get(&script_id)?;
1129 let callee = &self.scripts[callee_idx];
1130 let callee_source = callee.source_path.clone();
1131
1132 let first_body_line = callee
1140 .instructions
1141 .iter()
1142 .find_map(|i| match (i.opcode, &i.operand) {
1143 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1144 _ => None,
1145 })
1146 .unwrap_or(1);
1147 let callee_trigger = callee.trigger.clone();
1148 let callee_short_early = callee
1149 .name
1150 .trim_start_matches('[')
1151 .trim_end_matches(']')
1152 .split_once(',')
1153 .map(|(_, n)| n.to_string())
1154 .unwrap_or_else(|| callee.name.clone());
1155 let callee_header_line = self
1156 .source_cache
1157 .and_then(|c| c.get(&callee_source))
1158 .and_then(|src| find_header_line(src, &callee_trigger, &callee_short_early))
1159 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1160
1161 let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
1163 let param_name = format!("${}", ptr_cmd);
1164
1165 let callee_short = callee
1166 .name
1167 .trim_start_matches('[')
1168 .trim_end_matches(']')
1169 .split_once(',')
1170 .map(|(_, n)| n.to_string())
1171 .unwrap_or_else(|| callee.name.clone());
1172
1173 let arrow = if is_gosub { "~" } else { "@" };
1174
1175 let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1180 let corruptor_phrase = format_corruptors(&corruptors);
1181
1182 let message = format!(
1183 "`{callee}` reads `{ptr}` then {phrase}; the script still \
1184 compiles and runs, but the reference is brittle to reorder. \
1185 Consider capturing `{ptr}` at the call site and threading it \
1186 through `{callee}` as an `{ty} {pname}` parameter so the \
1187 value is explicit and stable.",
1188 callee = callee_short,
1189 ptr = ptr_cmd,
1190 phrase = corruptor_phrase,
1191 ty = param_type,
1192 pname = param_name,
1193 );
1194
1195 let cache = match self.source_cache {
1196 Some(c) => c,
1197 None => {
1198 return Some(Help {
1200 message,
1201 suggestions: Vec::new(),
1202 applicability: Applicability::Unspecified,
1203 });
1204 }
1205 };
1206
1207 let mut suggestions = Vec::new();
1208
1209 if let Some(src) = cache.get(caller_source_path)
1212 && let Some(line_text) = nth_source_line(src, caller_line)
1213 && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1214 {
1215 suggestions.push(Suggestion {
1216 file: PathBuf::from(caller_source_path),
1217 line_range: (caller_line, caller_line),
1218 replacement: rewritten,
1219 label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1220 });
1221 }
1222
1223 if let Some(src) = cache.get(&callee_source)
1225 && let Some(header_text) = nth_source_line(src, callee_header_line)
1226 && let Some(rewritten) =
1227 rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
1228 {
1229 suggestions.push(Suggestion {
1230 file: PathBuf::from(&callee_source),
1231 line_range: (callee_header_line, callee_header_line),
1232 replacement: rewritten,
1233 label: Some(format!(
1234 "at the `{}` header (add `{} {}`)",
1235 callee_short, param_type, param_name
1236 )),
1237 });
1238 }
1239
1240 Some(Help {
1241 message,
1242 suggestions,
1243 applicability: Applicability::MaybeIncorrect,
1247 })
1248 }
1249}
1250
1251fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1256 if !nodes[from].next.contains(&to) {
1257 nodes[from].next.push(to);
1258 }
1259 if !nodes[to].previous.contains(&from) {
1260 nodes[to].previous.push(from);
1261 }
1262}
1263
1264fn is_static_only_pointer(ptr: PointerType) -> bool {
1277 use PointerType::*;
1278 matches!(
1279 ptr,
1280 FindPlayer
1281 | FindNpc
1282 | FindLoc
1283 | FindObj
1284 | FindDb
1285 | LastCom
1286 | LastInt
1287 | LastItem
1288 | LastSlot
1289 | LastTargetslot
1290 | LastUseitem
1291 | LastUseslot
1292 )
1293}
1294
1295fn short_script_name(full_name: &str) -> Option<String> {
1298 full_name
1299 .trim_start_matches('[')
1300 .trim_end_matches(']')
1301 .split_once(',')
1302 .map(|(_, n)| n.to_string())
1303}
1304
1305fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1310 if corruptors.is_empty() {
1311 return "calls a delay or subroutine that may supersede it".to_string();
1312 }
1313
1314 const MAX: usize = 3;
1315 let shown: Vec<String> = corruptors
1316 .iter()
1317 .take(MAX)
1318 .map(|(name, line)| {
1319 if *line > 0 {
1320 format!("`{}` at line {}", name, line)
1321 } else {
1322 format!("`{}`", name)
1323 }
1324 })
1325 .collect();
1326
1327 let suffix = if corruptors.len() > MAX {
1328 format!(" (and {} more)", corruptors.len() - MAX)
1329 } else {
1330 String::new()
1331 };
1332
1333 let joined = match shown.len() {
1334 1 => shown[0].clone(),
1335 2 => format!("{} and {}", shown[0], shown[1]),
1336 _ => {
1337 let head = shown[..shown.len() - 1].join(", ");
1338 format!("{}, and {}", head, shown[shown.len() - 1])
1339 }
1340 };
1341
1342 format!("calls {}{} which may supersede it", joined, suffix)
1343}
1344
1345fn pointer_param_type(ptr: PointerType) -> &'static str {
1354 use PointerType::*;
1355 match ptr {
1356 LastUseitem | LastItem => "obj",
1357 LastCom => "component",
1358 _ => "int",
1359 }
1360}
1361
1362fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1364 if line_no == 0 {
1365 return None;
1366 }
1367 text.lines().nth(line_no - 1)
1368}
1369
1370fn rewrite_call_site_arg(
1379 line: &str,
1380 arrow: &str,
1381 callee_short: &str,
1382 ptr_cmd: &str,
1383) -> Option<String> {
1384 let needle = format!("{}{}", arrow, callee_short);
1387 let start = line.find(&needle)?;
1388 let after_name = start + needle.len();
1389 let tail = &line[after_name..];
1390
1391 let first_non_ws = tail.chars().next();
1393 if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1394 || tail.trim_start().is_empty()
1395 {
1396 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1397 out.push_str(&line[..after_name]);
1398 out.push('(');
1399 out.push_str(ptr_cmd);
1400 out.push(')');
1401 out.push_str(tail);
1402 return Some(out);
1403 }
1404
1405 if tail.trim_start().starts_with('(') {
1408 let open_rel = tail.find('(')?;
1409 let abs_open = after_name + open_rel;
1410 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1411 let abs_close = abs_open + close_rel;
1412
1413 let inside = line[abs_open + 1..abs_close].trim();
1415 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1416 out.push_str(&line[..abs_close]);
1417 if inside.is_empty() {
1418 out.push_str(ptr_cmd);
1419 } else {
1420 out.push_str(", ");
1421 out.push_str(ptr_cmd);
1422 }
1423 out.push_str(&line[abs_close..]);
1424 return Some(out);
1425 }
1426
1427 None
1428}
1429
1430fn rewrite_header_add_param(
1436 line: &str,
1437 callee_short: &str,
1438 param_type: &str,
1439 param_name: &str,
1440) -> Option<String> {
1441 let needle = format!(",{}]", callee_short);
1444 let subject_end = line.find(&needle)?;
1445 let after_bracket = subject_end + needle.len();
1446
1447 let remainder = &line[after_bracket..];
1448 let added = format!("{} {}", param_type, param_name);
1449
1450 if !remainder.trim_start().starts_with('(') {
1452 let mut out = String::with_capacity(line.len() + added.len() + 2);
1453 out.push_str(&line[..after_bracket]);
1454 out.push('(');
1455 out.push_str(&added);
1456 out.push(')');
1457 out.push_str(remainder);
1458 return Some(out);
1459 }
1460
1461 let open_rel = remainder.find('(')?;
1463 let abs_open = after_bracket + open_rel;
1464 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1465 let abs_close = abs_open + close_rel;
1466 let inside = line[abs_open + 1..abs_close].trim();
1467
1468 let mut out = String::with_capacity(line.len() + added.len() + 2);
1469 out.push_str(&line[..abs_close]);
1470 if inside.is_empty() {
1471 out.push_str(&added);
1472 } else {
1473 out.push_str(", ");
1474 out.push_str(&added);
1475 }
1476 out.push_str(&line[abs_close..]);
1477 Some(out)
1478}
1479
1480fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1484 let prefix = format!("[{},{}]", trigger, name);
1485 let prefix_with_params = format!("[{},{}](", trigger, name);
1486 for (i, line) in src.lines().enumerate() {
1487 let trimmed = line.trim_start();
1488 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1489 return Some(i + 1);
1490 }
1491 }
1492 None
1493}
1494
1495fn find_matching_close_paren(s: &str) -> Option<usize> {
1499 let bytes = s.as_bytes();
1500 if bytes.first().copied() != Some(b'(') {
1501 return None;
1502 }
1503 let mut depth = 0i32;
1504 for (i, &b) in bytes.iter().enumerate() {
1505 match b {
1506 b'(' => depth += 1,
1507 b')' => {
1508 depth -= 1;
1509 if depth == 0 {
1510 return Some(i);
1511 }
1512 }
1513 _ => {}
1514 }
1515 }
1516 None
1517}
1518
1519fn is_secondary_var_operand(operand: &Operand) -> bool {
1525 match operand {
1526 Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1527 _ => false,
1528 }
1529}
1530
1531fn resolve_target_node(
1537 mut target_idx: usize,
1538 instructions: &[Instruction],
1539 instr_to_node: &HashMap<usize, usize>,
1540) -> Option<usize> {
1541 while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1542 target_idx += 1;
1543 }
1544 instr_to_node.get(&target_idx).copied()
1545}
1546
1547fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1548 nodes[from].next.retain(|&n| n != to);
1549 nodes[to].previous.retain(|&n| n != from);
1550}
1551
1552fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1555 for i in (0..=instr_idx).rev() {
1556 if instructions[i].opcode == Opcode::LineNumber
1557 && let Operand::Int(line) = instructions[i].operand
1558 {
1559 return line as usize;
1560 }
1561 }
1562 0
1563}
1564
1565#[cfg(test)]
1566mod tests {
1567 use super::*;
1568 use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1569 use crate::symbol::SymbolRegistry;
1570
1571 fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1573 let mut reg = SymbolRegistry::new();
1574 for &(name, opcode) in commands {
1575 reg.register_command(name.to_string(), opcode, vec![], vec![]);
1576 }
1577 reg
1578 }
1579
1580 fn make_script(
1582 name: &str,
1583 trigger: &str,
1584 id: i32,
1585 instructions: Vec<Instruction>,
1586 ) -> CompiledScript {
1587 let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1588 script.trigger = trigger.to_string();
1589 script.source_path = "test.rs2".to_string();
1590 script.instructions = instructions;
1591 script
1592 }
1593
1594 fn cmd(opcode: i32) -> Instruction {
1596 Instruction::new(Opcode::Command, Operand::Int(opcode))
1597 }
1598
1599 fn line(n: i32) -> Instruction {
1600 Instruction::new(Opcode::LineNumber, Operand::Int(n))
1601 }
1602
1603 fn push_int(v: i32) -> Instruction {
1604 Instruction::push_int(v)
1605 }
1606
1607 fn branch_eq(target: usize) -> Instruction {
1608 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1609 }
1610
1611 fn branch(target: usize) -> Instruction {
1612 Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1613 }
1614
1615 fn ret() -> Instruction {
1616 Instruction::simple(Opcode::Return)
1617 }
1618
1619 fn gosub(script_id: i32) -> Instruction {
1620 Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1621 }
1622
1623 #[test]
1630 fn conditional_setter_with_arg_push() {
1631 let p_finduid_op = 4267;
1634 let p_stopaction_op = 4268;
1635
1636 let registry = registry_with_commands(&[
1637 ("p_finduid", p_finduid_op),
1638 ("p_stopaction", p_stopaction_op),
1639 ]);
1640
1641 let instructions = vec![
1642 line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
1652
1653 let script = make_script("test", "ai_timer", 0, instructions);
1657 let scripts = vec![script];
1658
1659 let mut checker = PointerChecker::new(&scripts, ®istry);
1660 let diags = checker.run();
1661
1662 assert_eq!(
1666 diags.warning_count(),
1667 0,
1668 "conditional setter should provide p_active_player on true branch, got {} warnings",
1669 diags.warning_count()
1670 );
1671 }
1672
1673 #[test]
1682 fn gosub_requires_then_corrupts_same_pointer() {
1683 let p_delay_op = 5001;
1684 let npc_delay_op = 5002;
1685
1686 let registry =
1687 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
1688
1689 let proc_script = make_script(
1692 "tackle_success",
1693 "proc",
1694 100,
1695 vec![
1696 line(1),
1697 push_int(0),
1698 cmd(p_delay_op), line(2),
1700 push_int(0),
1701 cmd(npc_delay_op), ret(),
1703 ],
1704 );
1705
1706 let label_script = make_script(
1709 "do_tackle",
1710 "label",
1711 200,
1712 vec![
1713 line(10),
1714 gosub(100), ret(),
1716 ],
1717 );
1718
1719 let scripts = vec![proc_script, label_script];
1720 let mut checker = PointerChecker::new(&scripts, ®istry);
1721 let diags = checker.run();
1722
1723 assert_eq!(
1729 diags.warning_count(),
1730 0,
1731 "gosub that requires-then-corrupts p_active_player should not \
1732 be flagged (engine-tracked pointer), got {} warnings",
1733 diags.warning_count()
1734 );
1735 }
1736
1737 #[test]
1743 fn corruption_before_requirement_is_caught() {
1744 let npc_delay_op = 5002;
1745 let p_delay_op = 5001;
1746
1747 let registry =
1748 registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
1749
1750 let script = make_script(
1753 "bad_order",
1754 "label",
1755 0,
1756 vec![
1757 line(1),
1758 push_int(0),
1759 cmd(npc_delay_op), line(2),
1761 push_int(0),
1762 cmd(p_delay_op), ret(),
1764 ],
1765 );
1766
1767 let scripts = vec![script];
1768 let mut checker = PointerChecker::new(&scripts, ®istry);
1769 let diags = checker.run();
1770
1771 assert!(
1772 diags.warning_count() > 0,
1773 "corruption before requirement should be caught as a warning"
1774 );
1775 }
1776
1777 #[test]
1782 fn uninitialized_pointer_caught() {
1783 let p_delay_op = 5001;
1784
1785 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
1786
1787 let script = make_script(
1789 "bad_access",
1790 "ai_timer",
1791 0,
1792 vec![
1793 line(1),
1794 push_int(0),
1795 cmd(p_delay_op), ret(),
1797 ],
1798 );
1799
1800 let scripts = vec![script];
1801 let mut checker = PointerChecker::new(&scripts, ®istry);
1802 let diags = checker.run();
1803
1804 assert!(
1805 diags.warning_count() > 0,
1806 "uninitialized pointer access should be caught"
1807 );
1808 }
1809
1810 #[test]
1820 fn branch_target_on_line_number_still_connects() {
1821 let p_delay_op = 5001;
1822 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
1823
1824 let script = make_script(
1840 "target_on_line_number",
1841 "ai_timer",
1842 0,
1843 vec![
1844 line(1),
1845 push_int(1),
1846 push_int(1),
1847 branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
1849 line(2),
1850 push_int(0),
1851 cmd(p_delay_op),
1852 ret(),
1853 ],
1854 );
1855
1856 let scripts = vec![script];
1857 let mut checker = PointerChecker::new(&scripts, ®istry);
1858 let diags = checker.run();
1859
1860 assert!(
1861 diags.warning_count() > 0,
1862 "jump target on LineNumber must still flag uninitialized pointer \
1863 access (got {} warnings)",
1864 diags.warning_count()
1865 );
1866 }
1867
1868 #[test]
1878 fn secondary_requires_and_corrupts_warns_for_static_pointer() {
1879 let last_useitem_op = 4270;
1882 let p_delay_op = 5001;
1883 let registry =
1884 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
1885
1886 let callee = make_script(
1888 "consume_useitem",
1889 "label",
1890 100,
1891 vec![
1892 line(1),
1893 cmd(last_useitem_op), line(2),
1895 push_int(0),
1896 cmd(p_delay_op), ret(),
1898 ],
1899 );
1900
1901 let caller = make_script(
1908 "use_on_loc",
1909 "oplocu",
1910 200,
1911 vec![
1912 line(10),
1913 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
1914 ],
1915 );
1916
1917 let scripts = vec![callee, caller];
1918 let mut checker = PointerChecker::new(&scripts, ®istry);
1919 let diags = checker.run();
1920
1921 let last_useitem_warnings = diags
1922 .diagnostics()
1923 .iter()
1924 .filter(|d| d.severity == Severity::Warning)
1925 .filter(|d| d.message.contains("last_useitem"))
1926 .count();
1927 assert!(
1928 last_useitem_warnings > 0,
1929 "static-only pointer (last_useitem) should trigger the \
1930 require+corrupt warning at the jump site; got diags: {:?}",
1931 diags
1932 .diagnostics()
1933 .iter()
1934 .map(|d| &d.message)
1935 .collect::<Vec<_>>()
1936 );
1937
1938 assert_eq!(
1939 diags.error_count(),
1940 0,
1941 "pointer-check diagnostics must never raise error severity; got {} errors",
1942 diags.error_count()
1943 );
1944 }
1945
1946 #[test]
1955 fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
1956 let p_delay_op = 5001;
1957 let npc_delay_op = 5002;
1958 let registry =
1959 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
1960
1961 let callee = make_script(
1962 "consume_protected",
1963 "proc",
1964 100,
1965 vec![
1966 line(1),
1967 push_int(0),
1968 cmd(p_delay_op), line(2),
1970 push_int(0),
1971 cmd(npc_delay_op), ret(),
1973 ],
1974 );
1975
1976 let caller = make_script(
1978 "do_opnpc",
1979 "opnpc1",
1980 200,
1981 vec![
1982 line(10),
1983 Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
1984 ret(),
1985 ],
1986 );
1987
1988 let scripts = vec![callee, caller];
1989 let mut checker = PointerChecker::new(&scripts, ®istry);
1990 let diags = checker.run();
1991
1992 let p_active_player_warnings = diags
1993 .diagnostics()
1994 .iter()
1995 .filter(|d| d.severity == Severity::Warning)
1996 .filter(|d| d.message.contains("p_active_player"))
1997 .count();
1998 assert_eq!(
1999 p_active_player_warnings, 0,
2000 "engine-tracked pointer (p_active_player) must not trigger the \
2001 require+corrupt warning; got {} such warnings",
2002 p_active_player_warnings
2003 );
2004 }
2005
2006 #[test]
2019 fn secondary_varn_requires_active_npc2_not_primary() {
2020 let secondary_varn = Instruction::new(
2025 Opcode::PushVarn,
2026 Operand::Int(1 << 16), );
2028
2029 let proc_script = make_script(
2031 "reads_secondary_varn",
2032 "proc",
2033 100,
2034 vec![
2035 line(1),
2036 secondary_varn,
2037 Instruction::simple(Opcode::PopIntDiscard),
2038 ret(),
2039 ],
2040 );
2041
2042 let caller = make_script(
2049 "gosub_into_proc",
2050 "opplayer1",
2051 200,
2052 vec![line(10), gosub(100), ret()],
2053 );
2054
2055 let scripts = vec![proc_script, caller];
2056 let registry = registry_with_commands(&[]);
2057 let mut checker = PointerChecker::new(&scripts, ®istry);
2058 let diags = checker.run();
2059
2060 let active_npc_primary_warnings = diags
2066 .diagnostics()
2067 .iter()
2068 .filter(|d| d.severity == Severity::Warning)
2069 .filter(|d| d.message.contains("pointer active_npc."))
2070 .count();
2071 assert_eq!(
2072 active_npc_primary_warnings,
2073 0,
2074 "secondary .%var read must not flag primary active_npc at the \
2075 caller; got diags: {:?}",
2076 diags
2077 .diagnostics()
2078 .iter()
2079 .filter(|d| d.severity == Severity::Warning)
2080 .map(|d| &d.message)
2081 .collect::<Vec<_>>()
2082 );
2083
2084 let active_npc2_warnings = diags
2088 .diagnostics()
2089 .iter()
2090 .filter(|d| d.severity == Severity::Warning)
2091 .filter(|d| d.message.contains("pointer .active_npc."))
2092 .count();
2093 assert!(
2094 active_npc2_warnings > 0,
2095 "secondary .%var should route the requirement to active_npc2; \
2096 got no such warning"
2097 );
2098 }
2099
2100 #[test]
2105 fn rewrite_call_site_no_args() {
2106 let got = rewrite_call_site_arg(
2107 "[opnpcu,wantcat1] @civilian_give_runes;",
2108 "@",
2109 "civilian_give_runes",
2110 "last_useitem",
2111 )
2112 .unwrap();
2113 assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2114 }
2115
2116 #[test]
2117 fn rewrite_call_site_with_args() {
2118 let got = rewrite_call_site_arg(
2119 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2120 "@",
2121 "amulet_of_glory_interface",
2122 "last_item",
2123 )
2124 .unwrap();
2125 assert_eq!(
2126 got,
2127 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2128 );
2129 }
2130
2131 #[test]
2132 fn rewrite_call_site_gosub_no_args() {
2133 let got =
2134 rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2135 assert_eq!(got, " ~some_proc(last_useitem);");
2136 }
2137
2138 #[test]
2139 fn rewrite_call_site_empty_arg_list() {
2140 let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2141 assert_eq!(got, "@foo(last_useitem);");
2142 }
2143
2144 #[test]
2145 fn rewrite_header_no_params() {
2146 let got = rewrite_header_add_param(
2147 "[label,civilian_give_runes]",
2148 "civilian_give_runes",
2149 "obj",
2150 "$last_useitem",
2151 )
2152 .unwrap();
2153 assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2154 }
2155
2156 #[test]
2157 fn rewrite_header_with_existing_params() {
2158 let got = rewrite_header_add_param(
2159 "[label,amulet_of_glory_interface](string $message)",
2160 "amulet_of_glory_interface",
2161 "obj",
2162 "$last_item",
2163 )
2164 .unwrap();
2165 assert_eq!(
2166 got,
2167 "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2168 );
2169 }
2170
2171 #[test]
2172 fn rewrite_header_proc_with_return_type() {
2173 let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2176 assert_eq!(got, "[proc,foo](obj $x)(int)");
2177 }
2178
2179 #[test]
2180 fn find_header_line_matches_trigger_and_name() {
2181 let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2182 assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2183 assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2184 assert_eq!(find_header_line(src, "label", "missing"), None);
2185 }
2186
2187 #[test]
2188 fn format_corruptors_shapes() {
2189 assert_eq!(
2190 format_corruptors(&[]),
2191 "calls a delay or subroutine that may supersede it"
2192 );
2193 assert_eq!(
2194 format_corruptors(&[("p_delay".to_string(), 21)]),
2195 "calls `p_delay` at line 21 which may supersede it"
2196 );
2197 assert_eq!(
2198 format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2199 "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2200 );
2201 assert_eq!(
2202 format_corruptors(&[
2203 ("p_delay".to_string(), 21),
2204 ("~chatnpc".to_string(), 11),
2205 ("~objbox".to_string(), 14),
2206 ]),
2207 "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2208 );
2209 assert_eq!(
2211 format_corruptors(&[
2212 ("p_delay".to_string(), 1),
2213 ("~a".to_string(), 2),
2214 ("~b".to_string(), 3),
2215 ("~c".to_string(), 4),
2216 ("~d".to_string(), 5),
2217 ]),
2218 "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2219 );
2220 assert_eq!(
2222 format_corruptors(&[("p_delay".to_string(), 0)]),
2223 "calls `p_delay` which may supersede it"
2224 );
2225 }
2226
2227 #[test]
2228 fn find_matching_close_paren_nested() {
2229 assert_eq!(find_matching_close_paren("()"), Some(1));
2230 assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2231 assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2232 assert_eq!(find_matching_close_paren("("), None);
2233 assert_eq!(find_matching_close_paren("abc"), None);
2234 }
2235
2236 #[test]
2241 fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2242 use std::collections::HashMap;
2243 use std::rc::Rc;
2244
2245 let last_useitem_op = 4270;
2246 let p_delay_op = 5001;
2247 let registry =
2248 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2249
2250 let mut callee = make_script(
2252 "consume_useitem",
2253 "label",
2254 100,
2255 vec![
2256 line(2), cmd(last_useitem_op),
2258 line(3),
2259 push_int(0),
2260 cmd(p_delay_op),
2261 ret(),
2262 ],
2263 );
2264 callee.source_path = "/virt/consume.rs2".to_string();
2265
2266 let mut caller = make_script(
2268 "use_on_loc",
2269 "oplocu",
2270 200,
2271 vec![
2272 line(1),
2273 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2274 ],
2275 );
2276 caller.source_path = "/virt/caller.rs2".to_string();
2277
2278 let mut source_cache: HashMap<String, Rc<String>> = HashMap::new();
2281 source_cache.insert(
2282 "/virt/caller.rs2".to_string(),
2283 Rc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2284 );
2285 source_cache.insert(
2286 "/virt/consume.rs2".to_string(),
2287 Rc::new(
2288 "[label,consume_useitem]\n\
2289 last_useitem;\n\
2290 p_delay(0);\n"
2291 .to_string(),
2292 ),
2293 );
2294
2295 let scripts = vec![callee, caller];
2296 let mut checker = PointerChecker::new(&scripts, ®istry);
2297 checker.set_source_cache(&source_cache);
2298 let diags = checker.run();
2299
2300 let warning = diags
2303 .diagnostics()
2304 .iter()
2305 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2306 .expect("expected a stale-last_useitem warning");
2307
2308 assert_eq!(
2309 warning.help.len(),
2310 1,
2311 "warning should have exactly one Help block, got {}",
2312 warning.help.len()
2313 );
2314 let help = &warning.help[0];
2315 assert!(
2316 help.message.contains("consume_useitem"),
2317 "help message should name the callee, got: {}",
2318 help.message
2319 );
2320 assert!(
2321 help.message.contains("last_useitem"),
2322 "help message should name the pointer, got: {}",
2323 help.message
2324 );
2325
2326 assert_eq!(
2328 help.suggestions.len(),
2329 2,
2330 "help should include both call-site and header suggestions, \
2331 got {}: {:?}",
2332 help.suggestions.len(),
2333 help.suggestions
2334 .iter()
2335 .map(|s| &s.label)
2336 .collect::<Vec<_>>()
2337 );
2338
2339 let caller_sug = help
2341 .suggestions
2342 .iter()
2343 .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2344 .expect("expected a call-site suggestion on the caller file");
2345 assert!(
2346 caller_sug
2347 .replacement
2348 .contains("@consume_useitem(last_useitem)"),
2349 "call-site replacement must pass last_useitem as an arg, got: {}",
2350 caller_sug.replacement
2351 );
2352
2353 let header_sug = help
2355 .suggestions
2356 .iter()
2357 .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2358 .expect("expected a header suggestion on the callee file");
2359 assert!(
2360 header_sug.replacement.contains("(obj $last_useitem)"),
2361 "header replacement must add `obj $last_useitem` param, got: {}",
2362 header_sug.replacement
2363 );
2364
2365 assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2366 }
2367
2368 #[test]
2372 fn secondary_warning_falls_back_to_prose_help_without_source() {
2373 let last_useitem_op = 4270;
2374 let p_delay_op = 5001;
2375 let registry =
2376 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2377
2378 let callee = make_script(
2379 "consume_useitem",
2380 "label",
2381 100,
2382 vec![
2383 line(1),
2384 cmd(last_useitem_op),
2385 line(2),
2386 push_int(0),
2387 cmd(p_delay_op),
2388 ret(),
2389 ],
2390 );
2391 let caller = make_script(
2392 "use_on_loc",
2393 "oplocu",
2394 200,
2395 vec![
2396 line(1),
2397 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2398 ],
2399 );
2400
2401 let scripts = vec![callee, caller];
2402 let mut checker = PointerChecker::new(&scripts, ®istry);
2403 let diags = checker.run();
2405
2406 let warning = diags
2407 .diagnostics()
2408 .iter()
2409 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2410 .expect("warning still fires without source cache");
2411
2412 assert_eq!(warning.help.len(), 1);
2413 let help = &warning.help[0];
2414 assert_eq!(
2415 help.suggestions.len(),
2416 0,
2417 "prose-only help should have no concrete suggestions"
2418 );
2419 assert_eq!(help.applicability, Applicability::Unspecified);
2420 }
2421}