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 script_name_to_index: HashMap<String, usize>,
100 overlay_interfaces: HashSet<String>,
103 source_cache: Option<&'a HashMap<String, std::sync::Arc<String>>>,
108 script_analyses: HashMap<String, ScriptAnalysis>,
110 script_pointers: HashMap<String, PointerHolder>,
111 pending_analyses: HashSet<String>,
112 pending_scripts: HashSet<String>,
113}
114
115impl<'a> PointerChecker<'a> {
116 pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
117 let mut opcode_to_name = HashMap::new();
119 for (name, sym) in ®istry.commands {
120 if let SymbolKind::Command { opcode, .. } = &sym.kind {
121 opcode_to_name.insert(*opcode, name.to_lowercase());
122 }
123 }
124
125 let mut script_id_to_index = HashMap::new();
127 for (i, script) in scripts.iter().enumerate() {
128 script_id_to_index.insert(script.id, i);
129 }
130
131 let mut script_name_to_index = HashMap::new();
135 for (i, script) in scripts.iter().enumerate() {
136 script_name_to_index.entry(script.name.clone()).or_insert(i);
137 }
138
139 let mut overlay_interfaces = HashSet::new();
143 for (name, sym) in ®istry.entity_ids {
144 if let SymbolKind::Constant { const_type, .. } = &sym.kind
145 && *const_type == crate::types::Type::OverlayInterface
146 {
147 overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
148 }
149 }
150
151 PointerChecker {
152 scripts,
153 cmd_pointers: command_pointers(),
154 registry,
155 opcode_to_name,
156 script_id_to_index,
157 script_name_to_index,
158 overlay_interfaces,
159 source_cache: None,
160 script_analyses: HashMap::new(),
161 script_pointers: HashMap::new(),
162 pending_analyses: HashSet::new(),
163 pending_scripts: HashSet::new(),
164 }
165 }
166
167 pub fn set_source_cache(&mut self, cache: &'a HashMap<String, std::sync::Arc<String>>) {
171 self.source_cache = Some(cache);
172 }
173
174 fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
177 if !crate::trigger_table::is_button(trigger) {
178 return false;
179 }
180 let subject = script_name
182 .trim_start_matches('[')
183 .trim_end_matches(']')
184 .split_once(',')
185 .map(|(_, rest)| rest)
186 .unwrap_or("");
187 let iface_name = subject
188 .split(':')
189 .next()
190 .unwrap_or("")
191 .to_lowercase()
192 .replace(' ', "_");
193 if iface_name.is_empty() {
194 return false;
195 }
196 !self.overlay_interfaces.contains(&iface_name)
198 }
199
200 pub fn run(&mut self) -> DiagnosticsCollector {
202 let names = self.script_names();
203 self.validate_names(&names)
204 }
205
206 pub fn script_names(&self) -> Vec<String> {
208 self.scripts.iter().map(|s| s.name.clone()).collect()
209 }
210
211 pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
219 let mut diagnostics = DiagnosticsCollector::new();
220 for script_name in names {
221 self.validate_script(script_name, &mut diagnostics);
222 }
223 diagnostics
224 }
225
226 fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
227 let script_idx = match self.script_name_to_index.get(script_name) {
229 Some(&i) => i,
230 None => return,
231 };
232 let trigger = self.scripts[script_idx].trigger.clone();
233 let source_path = self.scripts[script_idx].source_path.clone();
234 let trigger_set = trigger_pointers(&trigger);
235
236 self.ensure_analysis(script_name);
238
239 for &ptr in &PointerType::ALL {
240 let ptr_idx = ptr.index();
241
242 let analysis = match self.script_analyses.get(script_name) {
244 Some(a) => a,
245 None => continue,
246 };
247
248 let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
249 if required_nodes.is_empty() {
250 continue;
251 }
252
253 let mut corrupted: HashSet<usize> = analysis.corrupted_nodes[ptr_idx].clone();
255
256 let trigger_provides = if trigger_set.contains(ptr) {
260 true
261 } else if ptr == PointerType::PActivePlayer {
262 self.interface_trigger_grants_protected(&trigger, script_name)
263 } else {
264 false
265 };
266 if !trigger_provides {
267 corrupted.insert(0);
268 }
269
270 if corrupted.is_empty() {
271 continue;
272 }
273
274 let set_blocked: HashSet<usize> = analysis.set_nodes[ptr_idx].clone();
275
276 let path = self.find_edge_path(
278 script_name,
279 &required_nodes,
280 |node_idx| corrupted.contains(&node_idx),
281 &set_blocked,
282 );
283
284 let mut reported_via_main_bfs = false;
285 if let Some(path) = path {
286 if path.is_empty() {
287 continue;
288 }
289 reported_via_main_bfs = true;
290
291 let end_node_idx = path[path.len() - 1];
292 let start_node_idx = path[0];
293
294 let is_start_node = end_node_idx == 0;
295 let repr = ptr.representation();
296 let static_only = is_static_only_pointer(ptr);
297
298 let error_msg = if is_start_node {
304 if static_only {
305 msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
306 } else {
307 msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
308 }
309 } else if static_only {
310 msg::fmt(msg::POINTER_STALE, &[repr])
311 } else {
312 msg::fmt(msg::POINTER_CORRUPTED, &[repr])
313 };
314
315 let analysis = self.script_analyses.get(script_name).unwrap();
316 let instructions = &self.scripts[script_idx].instructions;
317 let req_line = analysis.nodes[start_node_idx]
318 .instruction_index
319 .map(|idx| resolve_line(instructions, idx))
320 .unwrap_or(0);
321
322 diagnostics.add(Diagnostic {
327 file: PathBuf::from(&source_path),
328 line: req_line,
329 column: 0,
330 message: error_msg,
331 severity: Severity::Warning,
332 phase: Phase::PointerCheck,
333 help: Vec::new(),
334 });
335
336 let read_hint = if static_only {
337 msg::fmt(msg::POINTER_READ_HERE, &[repr])
338 } else {
339 msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
340 };
341 diagnostics.add(Diagnostic {
342 file: PathBuf::from(&source_path),
343 line: req_line,
344 column: 0,
345 message: read_hint,
346 severity: Severity::Info,
347 phase: Phase::PointerCheck,
348 help: Vec::new(),
349 });
350
351 if !is_start_node {
352 let corrupt_line = analysis.nodes[end_node_idx]
353 .instruction_index
354 .map(|idx| resolve_line(instructions, idx))
355 .unwrap_or(0);
356
357 let cause_hint = if static_only {
358 msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
359 } else {
360 msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
361 };
362 diagnostics.add(Diagnostic {
363 file: PathBuf::from(&source_path),
364 line: corrupt_line,
365 column: 0,
366 message: cause_hint,
367 severity: Severity::Info,
368 phase: Phase::PointerCheck,
369 help: Vec::new(),
370 });
371 }
372 }
373
374 if !reported_via_main_bfs && is_static_only_pointer(ptr) {
387 let analysis = self.script_analyses.get(script_name).unwrap();
388 let instructions = &self.scripts[script_idx].instructions;
389 let corrupted_nodes = &analysis.corrupted_nodes[ptr_idx];
390 let mut seen_lines: HashSet<usize> = HashSet::new();
391 let repr = ptr.representation();
392 for &node_idx in &required_nodes {
393 if !corrupted_nodes.contains(&node_idx) {
394 continue;
395 }
396 let line = analysis.nodes[node_idx]
397 .instruction_index
398 .map(|idx| resolve_line(instructions, idx))
399 .unwrap_or(0);
400 if !seen_lines.insert(line) {
401 continue;
402 }
403
404 let help =
409 self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
410
411 let mut diag = Diagnostic {
419 file: PathBuf::from(&source_path),
420 line,
421 column: 0,
422 message: msg::fmt(msg::POINTER_STALE, &[repr]),
423 severity: Severity::Warning,
424 phase: Phase::PointerCheck,
425 help: Vec::new(),
426 };
427 if let Some(h) = help {
428 diag.help.push(h);
429 }
430 diagnostics.add(diag);
431 }
432 }
433 }
434 }
435
436 fn find_edge_path(
445 &self,
446 script_name: &str,
447 starts: &[usize],
448 end_pred: impl Fn(usize) -> bool,
449 blocked: &HashSet<usize>,
450 ) -> Option<Vec<usize>> {
451 let analysis = self.script_analyses.get(script_name)?;
452
453 let mut queue: VecDeque<usize> = VecDeque::new();
454 let mut visited: HashSet<usize> = HashSet::new();
455 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); for &start in starts {
463 for &prev in &analysis.nodes[start].previous {
464 if blocked.contains(&prev) || visited.contains(&prev) {
465 continue;
466 }
467 visited.insert(prev);
468 queue.push_back(prev);
469 sources.insert(prev, (start, start));
470 }
471 }
472
473 while let Some(current) = queue.pop_front() {
474 if end_pred(current) {
475 let mut path = vec![current];
477 let mut node = current;
478 while let Some(&(from, start)) = sources.get(&node) {
479 if from == start && starts.contains(&from) {
480 path.push(from);
481 break;
482 }
483 path.push(from);
484 node = from;
485 }
486 path.reverse();
487 return Some(path);
488 }
489
490 let (_, start_node) = sources[¤t];
491
492 for &prev in &analysis.nodes[current].previous {
493 if blocked.contains(&prev) || visited.contains(&prev) {
494 continue;
495 }
496 visited.insert(prev);
497 queue.push_back(prev);
498 sources.insert(prev, (current, start_node));
499 }
500 }
501
502 None
503 }
504
505 fn find_edge_path_static(
508 nodes: &[CfgNode],
509 starts: &[usize],
510 end_pred: impl Fn(usize) -> bool,
511 blocked: &HashSet<usize>,
512 ) -> Option<Vec<usize>> {
513 let mut queue: VecDeque<usize> = VecDeque::new();
514 let mut visited: HashSet<usize> = HashSet::new();
515 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
516
517 for &start in starts {
518 for &prev in &nodes[start].previous {
519 if blocked.contains(&prev) || visited.contains(&prev) {
520 continue;
521 }
522 visited.insert(prev);
523 queue.push_back(prev);
524 sources.insert(prev, (start, start));
525 }
526 }
527
528 while let Some(current) = queue.pop_front() {
529 if end_pred(current) {
530 let mut path = vec![current];
531 let mut node = current;
532 while let Some(&(from, start)) = sources.get(&node) {
533 if from == start && starts.contains(&from) {
534 path.push(from);
535 break;
536 }
537 path.push(from);
538 node = from;
539 }
540 path.reverse();
541 return Some(path);
542 }
543
544 for &prev in &nodes[current].previous {
545 if blocked.contains(&prev) || visited.contains(&prev) {
546 continue;
547 }
548 visited.insert(prev);
549 queue.push_back(prev);
550 sources.insert(prev, (current, sources[¤t].1));
551 }
552 }
553
554 None
555 }
556
557 fn ensure_analysis(&mut self, script_name: &str) {
562 if self.script_analyses.contains_key(script_name) {
563 return;
564 }
565 if self.pending_analyses.contains(script_name) {
566 return; }
568 self.pending_analyses.insert(script_name.to_string());
569
570 let script_idx = match self.script_name_to_index.get(script_name) {
571 Some(&i) => i,
572 None => return,
573 };
574
575 let mut analysis = self.build_cfg(script_idx);
576 self.categorize_nodes(script_idx, &mut analysis);
577
578 self.script_analyses
579 .insert(script_name.to_string(), analysis);
580 self.pending_analyses.remove(script_name);
581 }
582
583 fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
588 let script = &self.scripts[script_idx];
589 let instructions = &script.instructions;
590 let mut analysis = ScriptAnalysis::new();
591
592 analysis.nodes.push(CfgNode::new(None));
594
595 let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
597 let mut node_order: Vec<usize> = Vec::new(); for (i, instr) in instructions.iter().enumerate() {
600 if instr.opcode == Opcode::LineNumber {
601 continue;
602 }
603 let node_idx = analysis.nodes.len();
604 instr_to_node.insert(i, node_idx);
605 node_order.push(i);
606 analysis.nodes.push(CfgNode::new(Some(i)));
607 }
608
609 if node_order.is_empty() {
610 return analysis;
611 }
612
613 let first_node = instr_to_node[&node_order[0]];
615 add_edge(&mut analysis.nodes, 0, first_node);
616
617 for (order_idx, &instr_idx) in node_order.iter().enumerate() {
619 let node_idx = instr_to_node[&instr_idx];
620 let instr = &instructions[instr_idx];
621
622 let is_terminal = matches!(
623 instr.opcode,
624 Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
625 );
626
627 match instr.opcode {
632 Opcode::Branch
633 | Opcode::BranchNot
634 | Opcode::BranchEquals
635 | Opcode::BranchLessThan
636 | Opcode::BranchGreaterThan
637 | Opcode::BranchLessThanOrEquals
638 | Opcode::BranchGreaterThanOrEquals
639 | Opcode::LongBranchNot
640 | Opcode::LongBranchEquals
641 | Opcode::LongBranchLessThan
642 | Opcode::LongBranchGreaterThan
643 | Opcode::LongBranchLessThanOrEquals
644 | Opcode::LongBranchGreaterThanOrEquals
645 | Opcode::ObjBranchEquals
646 | Opcode::ObjBranchNot => {
647 if let Operand::JumpTarget(target_instr_idx) = &instr.operand
648 && let Some(target_node) =
649 resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
650 {
651 add_edge(&mut analysis.nodes, node_idx, target_node);
652 }
653 }
654
655 Opcode::Switch => {
656 if let Operand::SwitchTable(cases) = &instr.operand {
657 for &(_, target_instr_idx) in cases {
658 if let Some(target_node) =
659 resolve_target_node(target_instr_idx, instructions, &instr_to_node)
660 {
661 add_edge(&mut analysis.nodes, node_idx, target_node);
662 }
663 }
664 }
665 }
666
667 _ => {}
668 }
669
670 if !is_terminal
672 && let Some(next_order_idx) = order_idx.checked_add(1)
673 && next_order_idx < node_order.len()
674 {
675 let next_node = instr_to_node[&node_order[next_order_idx]];
676 add_edge(&mut analysis.nodes, node_idx, next_node);
677 }
678
679 if instr.opcode == Opcode::Return {
684 analysis.returns.push(node_idx);
685 }
686 }
687
688 self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
690
691 analysis
692 }
693
694 fn insert_pointer_nodes(
697 &self,
698 script_idx: usize,
699 analysis: &mut ScriptAnalysis,
700 instr_to_node: &HashMap<usize, usize>,
701 node_order: &[usize],
702 ) {
703 let instructions = &self.scripts[script_idx].instructions;
704
705 for window_end in 2..node_order.len() {
710 let push_instr_idx = node_order[window_end - 1];
711 let branch_instr_idx = node_order[window_end];
712
713 let push_instr = &instructions[push_instr_idx];
714 let branch_instr = &instructions[branch_instr_idx];
715
716 let push_value = match &push_instr.operand {
718 Operand::Int(v) if *v == 0 || *v == 1 => *v,
719 _ => continue,
720 };
721 if push_instr.opcode != Opcode::PushConstantInt {
722 continue;
723 }
724 if branch_instr.opcode != Opcode::BranchEquals {
725 continue;
726 }
727
728 let mut cmd_instr_idx = None;
730 for scan in (0..window_end - 1).rev() {
731 let idx = node_order[scan];
732 if instructions[idx].opcode == Opcode::Command {
733 cmd_instr_idx = Some(idx);
734 break;
735 }
736 if matches!(
738 instructions[idx].opcode,
739 Opcode::Branch
740 | Opcode::Return
741 | Opcode::Switch
742 | Opcode::BranchEquals
743 | Opcode::BranchNot
744 | Opcode::BranchLessThan
745 | Opcode::BranchGreaterThan
746 | Opcode::BranchLessThanOrEquals
747 | Opcode::BranchGreaterThanOrEquals
748 ) {
749 break;
750 }
751 }
752 let cmd_instr_idx = match cmd_instr_idx {
753 Some(idx) => idx,
754 None => continue,
755 };
756 let cmd_instr = &instructions[cmd_instr_idx];
757
758 let cmd_name = self.resolve_command_name(cmd_instr);
760 let cmd_name = match cmd_name {
761 Some(n) => n,
762 None => continue,
763 };
764
765 let holder = match self.cmd_pointers.get(&cmd_name) {
766 Some(h) => h,
767 None => continue,
768 };
769
770 if !holder.conditional_set {
771 continue;
772 }
773
774 if holder.set.is_empty() {
775 continue;
776 }
777
778 let branch_node_idx = instr_to_node[&branch_instr_idx];
779
780 let ptr_node_idx = analysis.nodes.len();
782 analysis.nodes.push(CfgNode::pointer_node(holder.set));
783
784 if push_value == 0 {
785 let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
793 .next
794 .iter()
795 .copied()
796 .filter(|&n| {
797 if let Operand::JumpTarget(target) = &branch_instr.operand
799 && let Some(jump_node) =
800 resolve_target_node(*target, instructions, instr_to_node)
801 {
802 return n != jump_node;
803 }
804 true
805 })
806 .collect();
807
808 for ft_target in fallthrough_targets {
809 remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
811 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
813 add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
814 }
815 } else {
816 if let Operand::JumpTarget(target) = &branch_instr.operand
820 && let Some(jump_target_node) =
821 resolve_target_node(*target, instructions, instr_to_node)
822 {
823 remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
825 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
827 add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
828 }
829 }
830 }
831 }
832
833 fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
838 let instructions = &self.scripts[script_idx].instructions;
839
840 for node_idx in 0..analysis.nodes.len() {
841 let instr_idx = match analysis.nodes[node_idx].instruction_index {
842 Some(i) => i,
843 None => {
844 let ptr_set = analysis.nodes[node_idx].pointer_set;
846 if !ptr_set.is_empty() {
847 for ptr in ptr_set.iter() {
848 let pi = ptr.index();
849 analysis.set_list[pi].push(node_idx);
850 analysis.set_nodes[pi].insert(node_idx);
851 }
852 }
853 continue;
854 }
855 };
856
857 let instr = &instructions[instr_idx];
858
859 match instr.opcode {
860 Opcode::Command => {
861 let cmd_name = self.resolve_command_name(instr);
862 if let Some(name) = cmd_name
863 && let Some(holder) = self.cmd_pointers.get(&name).cloned()
864 {
865 self.apply_holder(analysis, node_idx, &holder);
866 }
867 }
868
869 Opcode::Gosub | Opcode::GosubWithParams => {
870 if let Operand::Int(script_id) = &instr.operand {
871 let callee_holder = self.get_script_pointers(*script_id);
872 self.apply_holder(analysis, node_idx, &callee_holder);
873 }
874 }
875
876 Opcode::Jump | Opcode::JumpWithParams => {
877 if let Operand::Int(script_id) = &instr.operand {
878 let callee_holder = self.get_script_pointers(*script_id);
879 self.apply_holder(analysis, node_idx, &callee_holder);
880 }
881 }
882
883 Opcode::PushVarp | Opcode::PushVarbit => {
890 let pi = if is_secondary_var_operand(&instr.operand) {
891 PointerType::ActivePlayer2.index()
892 } else {
893 PointerType::ActivePlayer.index()
894 };
895 analysis.required[pi].push(node_idx);
896 }
897
898 Opcode::PopVarp | Opcode::PopVarbit => {
899 let pi = if is_secondary_var_operand(&instr.operand) {
900 PointerType::ActivePlayer2.index()
901 } else {
902 PointerType::ActivePlayer.index()
903 };
904 analysis.required[pi].push(node_idx);
905 }
906
907 Opcode::PushVarn | Opcode::PopVarn => {
908 let pi = if is_secondary_var_operand(&instr.operand) {
909 PointerType::ActiveNpc2.index()
910 } else {
911 PointerType::ActiveNpc.index()
912 };
913 analysis.required[pi].push(node_idx);
914 }
915
916 _ => {}
918 }
919 }
920 }
921
922 fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
923 for ptr in holder.required.iter() {
924 let pi = ptr.index();
925 analysis.required[pi].push(node_idx);
926 }
927 for ptr in holder.set.iter() {
928 let pi = ptr.index();
929 analysis.set_list[pi].push(node_idx);
930 analysis.set_nodes[pi].insert(node_idx);
931 }
932 for ptr in holder.corrupted.iter() {
933 let pi = ptr.index();
934 analysis.corrupted_list[pi].push(node_idx);
935 analysis.corrupted_nodes[pi].insert(node_idx);
936 }
937 }
938
939 fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
955 let script_idx = match self.script_id_to_index.get(&script_id) {
957 Some(&i) => i,
958 None => {
959 return PointerHolder::default();
960 }
961 };
962 let script_name = self.scripts[script_idx].name.clone();
963
964 if let Some(holder) = self.script_pointers.get(&script_name) {
966 return holder.clone();
967 }
968
969 if self.pending_scripts.contains(&script_name) {
971 return PointerHolder::default();
972 }
973 self.pending_scripts.insert(script_name.clone());
974
975 self.ensure_analysis(&script_name);
977
978 let mut holder = PointerHolder::default();
979
980 if let Some(analysis) = self.script_analyses.get(&script_name) {
981 for &ptr in &PointerType::ALL {
982 let pi = ptr.index();
983
984 if !analysis.required[pi].is_empty() {
986 let path = Self::find_edge_path_static(
987 &analysis.nodes,
988 &analysis.required[pi],
989 |node_idx| node_idx == 0,
990 &analysis.set_nodes[pi],
991 );
992 if path.is_some() {
993 holder.required.insert(ptr);
994 }
995 }
996
997 if !analysis.returns.is_empty() {
1000 let corrupted_nodes = &analysis.corrupted_nodes[pi];
1001 let path = Self::find_edge_path_static(
1002 &analysis.nodes,
1003 &analysis.returns,
1004 |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1005 &analysis.set_nodes[pi],
1006 );
1007 if path.is_none() {
1008 holder.set.insert(ptr);
1009 }
1010 }
1011
1012 if !analysis.returns.is_empty() && !analysis.corrupted_nodes[pi].is_empty() {
1014 let corrupted_nodes = &analysis.corrupted_nodes[pi];
1015 let path = Self::find_edge_path_static(
1016 &analysis.nodes,
1017 &analysis.returns,
1018 |node_idx| corrupted_nodes.contains(&node_idx),
1019 &analysis.set_nodes[pi],
1020 );
1021 if path.is_some() {
1022 holder.corrupted.insert(ptr);
1023 }
1024 }
1025 }
1026 }
1027
1028 self.pending_scripts.remove(&script_name);
1029
1030 self.script_pointers
1031 .insert(script_name.clone(), holder.clone());
1032 holder
1033 }
1034
1035 fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1045 let callee = &self.scripts[callee_idx];
1046 let analysis = match self.script_analyses.get(&callee.name) {
1047 Some(a) => a,
1048 None => return Vec::new(),
1049 };
1050 let ptr_idx = ptr.index();
1051 let mut seen: HashSet<(String, usize)> = HashSet::new();
1052 let mut result: Vec<(String, usize)> = Vec::new();
1053
1054 for &node_idx in &analysis.corrupted_list[ptr_idx] {
1055 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1056 Some(i) => i,
1057 None => continue,
1058 };
1059 let instr = &callee.instructions[instr_idx];
1060 let line = resolve_line(&callee.instructions, instr_idx);
1061
1062 let name = match instr.opcode {
1063 Opcode::Command => match self.resolve_command_name(instr) {
1064 Some(n) => n,
1065 None => continue,
1066 },
1067 Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1068 Operand::Int(id) => match self.script_id_to_index.get(id) {
1069 Some(&target_idx) => short_script_name(&self.scripts[target_idx].name)
1070 .map(|s| format!("~{}", s))
1071 .unwrap_or_else(|| self.scripts[target_idx].name.clone()),
1072 None => continue,
1073 },
1074 _ => continue,
1075 },
1076 _ => continue,
1080 };
1081
1082 let key = (name.clone(), line);
1083 if seen.insert(key) {
1084 result.push((name, line));
1085 }
1086 }
1087
1088 result
1089 }
1090
1091 fn resolve_command_name(&self, instr: &Instruction) -> Option<String> {
1092 match &instr.operand {
1093 Operand::Int(encoded) => {
1094 let opcode = encoded & 0xFFFF;
1095 let secondary = (encoded >> 16) & 1;
1096 let base_name = self.opcode_to_name.get(&opcode)?;
1097 if secondary == 1 {
1098 Some(format!(".{}", base_name))
1099 } else {
1100 Some(base_name.clone())
1101 }
1102 }
1103 Operand::Str(name) => Some(name.to_lowercase()),
1104 _ => None,
1105 }
1106 }
1107
1108 fn build_rule_a_help(
1120 &self,
1121 ptr: PointerType,
1122 caller_source_path: &str,
1123 caller_line: usize,
1124 node_idx: usize,
1125 caller_script_idx: usize,
1126 ) -> Option<Help> {
1127 let analysis = self
1128 .script_analyses
1129 .get(&self.scripts[caller_script_idx].name)?;
1130 let caller_instructions = &self.scripts[caller_script_idx].instructions;
1131 let instr_idx = analysis.nodes[node_idx].instruction_index?;
1132 let instr = &caller_instructions[instr_idx];
1133
1134 let (is_gosub, script_id) = match instr.opcode {
1136 Opcode::Jump | Opcode::JumpWithParams => (
1137 false,
1138 match &instr.operand {
1139 Operand::Int(id) => *id,
1140 _ => return None,
1141 },
1142 ),
1143 Opcode::Gosub | Opcode::GosubWithParams => (
1144 true,
1145 match &instr.operand {
1146 Operand::Int(id) => *id,
1147 _ => return None,
1148 },
1149 ),
1150 _ => return None,
1151 };
1152
1153 let callee_idx = *self.script_id_to_index.get(&script_id)?;
1154 let callee = &self.scripts[callee_idx];
1155 let callee_source = callee.source_path.clone();
1156
1157 let first_body_line = callee
1165 .instructions
1166 .iter()
1167 .find_map(|i| match (i.opcode, &i.operand) {
1168 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1169 _ => None,
1170 })
1171 .unwrap_or(1);
1172 let callee_trigger = callee.trigger.clone();
1173 let callee_short_early = callee
1174 .name
1175 .trim_start_matches('[')
1176 .trim_end_matches(']')
1177 .split_once(',')
1178 .map(|(_, n)| n.to_string())
1179 .unwrap_or_else(|| callee.name.clone());
1180 let callee_header_line = self
1181 .source_cache
1182 .and_then(|c| c.get(&callee_source))
1183 .and_then(|src| find_header_line(src, &callee_trigger, &callee_short_early))
1184 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1185
1186 let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
1188 let param_name = format!("${}", ptr_cmd);
1189
1190 let callee_short = callee
1191 .name
1192 .trim_start_matches('[')
1193 .trim_end_matches(']')
1194 .split_once(',')
1195 .map(|(_, n)| n.to_string())
1196 .unwrap_or_else(|| callee.name.clone());
1197
1198 let arrow = if is_gosub { "~" } else { "@" };
1199
1200 let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1205 let corruptor_phrase = format_corruptors(&corruptors);
1206
1207 let message = format!(
1208 "`{callee}` reads `{ptr}` then {phrase}; the script still \
1209 compiles and runs, but the reference is brittle to reorder. \
1210 Consider capturing `{ptr}` at the call site and threading it \
1211 through `{callee}` as an `{ty} {pname}` parameter so the \
1212 value is explicit and stable.",
1213 callee = callee_short,
1214 ptr = ptr_cmd,
1215 phrase = corruptor_phrase,
1216 ty = param_type,
1217 pname = param_name,
1218 );
1219
1220 let cache = match self.source_cache {
1221 Some(c) => c,
1222 None => {
1223 return Some(Help {
1225 message,
1226 suggestions: Vec::new(),
1227 applicability: Applicability::Unspecified,
1228 });
1229 }
1230 };
1231
1232 let mut suggestions = Vec::new();
1233
1234 if let Some(src) = cache.get(caller_source_path)
1237 && let Some(line_text) = nth_source_line(src, caller_line)
1238 && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1239 {
1240 suggestions.push(Suggestion {
1241 file: PathBuf::from(caller_source_path),
1242 line_range: (caller_line, caller_line),
1243 replacement: rewritten,
1244 label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1245 });
1246 }
1247
1248 if let Some(src) = cache.get(&callee_source)
1250 && let Some(header_text) = nth_source_line(src, callee_header_line)
1251 && let Some(rewritten) =
1252 rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
1253 {
1254 suggestions.push(Suggestion {
1255 file: PathBuf::from(&callee_source),
1256 line_range: (callee_header_line, callee_header_line),
1257 replacement: rewritten,
1258 label: Some(format!(
1259 "at the `{}` header (add `{} {}`)",
1260 callee_short, param_type, param_name
1261 )),
1262 });
1263 }
1264
1265 Some(Help {
1266 message,
1267 suggestions,
1268 applicability: Applicability::MaybeIncorrect,
1272 })
1273 }
1274}
1275
1276fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1281 if !nodes[from].next.contains(&to) {
1282 nodes[from].next.push(to);
1283 }
1284 if !nodes[to].previous.contains(&from) {
1285 nodes[to].previous.push(from);
1286 }
1287}
1288
1289fn is_static_only_pointer(ptr: PointerType) -> bool {
1302 use PointerType::*;
1303 matches!(
1304 ptr,
1305 FindPlayer
1306 | FindNpc
1307 | FindLoc
1308 | FindObj
1309 | FindDb
1310 | LastCom
1311 | LastInt
1312 | LastItem
1313 | LastSlot
1314 | LastTargetslot
1315 | LastUseitem
1316 | LastUseslot
1317 )
1318}
1319
1320fn short_script_name(full_name: &str) -> Option<String> {
1323 full_name
1324 .trim_start_matches('[')
1325 .trim_end_matches(']')
1326 .split_once(',')
1327 .map(|(_, n)| n.to_string())
1328}
1329
1330fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1335 if corruptors.is_empty() {
1336 return "calls a delay or subroutine that may supersede it".to_string();
1337 }
1338
1339 const MAX: usize = 3;
1340 let shown: Vec<String> = corruptors
1341 .iter()
1342 .take(MAX)
1343 .map(|(name, line)| {
1344 if *line > 0 {
1345 format!("`{}` at line {}", name, line)
1346 } else {
1347 format!("`{}`", name)
1348 }
1349 })
1350 .collect();
1351
1352 let suffix = if corruptors.len() > MAX {
1353 format!(" (and {} more)", corruptors.len() - MAX)
1354 } else {
1355 String::new()
1356 };
1357
1358 let joined = match shown.len() {
1359 1 => shown[0].clone(),
1360 2 => format!("{} and {}", shown[0], shown[1]),
1361 _ => {
1362 let head = shown[..shown.len() - 1].join(", ");
1363 format!("{}, and {}", head, shown[shown.len() - 1])
1364 }
1365 };
1366
1367 format!("calls {}{} which may supersede it", joined, suffix)
1368}
1369
1370fn pointer_param_type(ptr: PointerType) -> &'static str {
1379 use PointerType::*;
1380 match ptr {
1381 LastUseitem | LastItem => "obj",
1382 LastCom => "component",
1383 _ => "int",
1384 }
1385}
1386
1387fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1389 if line_no == 0 {
1390 return None;
1391 }
1392 text.lines().nth(line_no - 1)
1393}
1394
1395fn rewrite_call_site_arg(
1404 line: &str,
1405 arrow: &str,
1406 callee_short: &str,
1407 ptr_cmd: &str,
1408) -> Option<String> {
1409 let needle = format!("{}{}", arrow, callee_short);
1412 let start = line.find(&needle)?;
1413 let after_name = start + needle.len();
1414 let tail = &line[after_name..];
1415
1416 let first_non_ws = tail.chars().next();
1418 if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1419 || tail.trim_start().is_empty()
1420 {
1421 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1422 out.push_str(&line[..after_name]);
1423 out.push('(');
1424 out.push_str(ptr_cmd);
1425 out.push(')');
1426 out.push_str(tail);
1427 return Some(out);
1428 }
1429
1430 if tail.trim_start().starts_with('(') {
1433 let open_rel = tail.find('(')?;
1434 let abs_open = after_name + open_rel;
1435 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1436 let abs_close = abs_open + close_rel;
1437
1438 let inside = line[abs_open + 1..abs_close].trim();
1440 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1441 out.push_str(&line[..abs_close]);
1442 if inside.is_empty() {
1443 out.push_str(ptr_cmd);
1444 } else {
1445 out.push_str(", ");
1446 out.push_str(ptr_cmd);
1447 }
1448 out.push_str(&line[abs_close..]);
1449 return Some(out);
1450 }
1451
1452 None
1453}
1454
1455fn rewrite_header_add_param(
1461 line: &str,
1462 callee_short: &str,
1463 param_type: &str,
1464 param_name: &str,
1465) -> Option<String> {
1466 let needle = format!(",{}]", callee_short);
1469 let subject_end = line.find(&needle)?;
1470 let after_bracket = subject_end + needle.len();
1471
1472 let remainder = &line[after_bracket..];
1473 let added = format!("{} {}", param_type, param_name);
1474
1475 if !remainder.trim_start().starts_with('(') {
1477 let mut out = String::with_capacity(line.len() + added.len() + 2);
1478 out.push_str(&line[..after_bracket]);
1479 out.push('(');
1480 out.push_str(&added);
1481 out.push(')');
1482 out.push_str(remainder);
1483 return Some(out);
1484 }
1485
1486 let open_rel = remainder.find('(')?;
1488 let abs_open = after_bracket + open_rel;
1489 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1490 let abs_close = abs_open + close_rel;
1491 let inside = line[abs_open + 1..abs_close].trim();
1492
1493 let mut out = String::with_capacity(line.len() + added.len() + 2);
1494 out.push_str(&line[..abs_close]);
1495 if inside.is_empty() {
1496 out.push_str(&added);
1497 } else {
1498 out.push_str(", ");
1499 out.push_str(&added);
1500 }
1501 out.push_str(&line[abs_close..]);
1502 Some(out)
1503}
1504
1505fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1509 let prefix = format!("[{},{}]", trigger, name);
1510 let prefix_with_params = format!("[{},{}](", trigger, name);
1511 for (i, line) in src.lines().enumerate() {
1512 let trimmed = line.trim_start();
1513 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1514 return Some(i + 1);
1515 }
1516 }
1517 None
1518}
1519
1520fn find_matching_close_paren(s: &str) -> Option<usize> {
1524 let bytes = s.as_bytes();
1525 if bytes.first().copied() != Some(b'(') {
1526 return None;
1527 }
1528 let mut depth = 0i32;
1529 for (i, &b) in bytes.iter().enumerate() {
1530 match b {
1531 b'(' => depth += 1,
1532 b')' => {
1533 depth -= 1;
1534 if depth == 0 {
1535 return Some(i);
1536 }
1537 }
1538 _ => {}
1539 }
1540 }
1541 None
1542}
1543
1544fn is_secondary_var_operand(operand: &Operand) -> bool {
1550 match operand {
1551 Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1552 _ => false,
1553 }
1554}
1555
1556fn resolve_target_node(
1562 mut target_idx: usize,
1563 instructions: &[Instruction],
1564 instr_to_node: &HashMap<usize, usize>,
1565) -> Option<usize> {
1566 while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1567 target_idx += 1;
1568 }
1569 instr_to_node.get(&target_idx).copied()
1570}
1571
1572fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1573 nodes[from].next.retain(|&n| n != to);
1574 nodes[to].previous.retain(|&n| n != from);
1575}
1576
1577fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1580 for i in (0..=instr_idx).rev() {
1581 if instructions[i].opcode == Opcode::LineNumber
1582 && let Operand::Int(line) = instructions[i].operand
1583 {
1584 return line as usize;
1585 }
1586 }
1587 0
1588}
1589
1590#[cfg(test)]
1591mod tests {
1592 use super::*;
1593 use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1594 use crate::symbol::SymbolRegistry;
1595
1596 fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1598 let mut reg = SymbolRegistry::new();
1599 for &(name, opcode) in commands {
1600 reg.register_command(name.to_string(), opcode, vec![], vec![]);
1601 }
1602 reg
1603 }
1604
1605 fn make_script(
1607 name: &str,
1608 trigger: &str,
1609 id: i32,
1610 instructions: Vec<Instruction>,
1611 ) -> CompiledScript {
1612 let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1613 script.trigger = trigger.to_string();
1614 script.source_path = "test.rs2".to_string();
1615 script.instructions = instructions;
1616 script
1617 }
1618
1619 fn cmd(opcode: i32) -> Instruction {
1621 Instruction::new(Opcode::Command, Operand::Int(opcode))
1622 }
1623
1624 fn line(n: i32) -> Instruction {
1625 Instruction::new(Opcode::LineNumber, Operand::Int(n))
1626 }
1627
1628 fn push_int(v: i32) -> Instruction {
1629 Instruction::push_int(v)
1630 }
1631
1632 fn branch_eq(target: usize) -> Instruction {
1633 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1634 }
1635
1636 fn branch(target: usize) -> Instruction {
1637 Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1638 }
1639
1640 fn ret() -> Instruction {
1641 Instruction::simple(Opcode::Return)
1642 }
1643
1644 fn gosub(script_id: i32) -> Instruction {
1645 Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1646 }
1647
1648 #[test]
1655 fn conditional_setter_with_arg_push() {
1656 let p_finduid_op = 4267;
1659 let p_stopaction_op = 4268;
1660
1661 let registry = registry_with_commands(&[
1662 ("p_finduid", p_finduid_op),
1663 ("p_stopaction", p_stopaction_op),
1664 ]);
1665
1666 let instructions = vec![
1667 line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
1677
1678 let script = make_script("test", "ai_timer", 0, instructions);
1682 let scripts = vec![script];
1683
1684 let mut checker = PointerChecker::new(&scripts, ®istry);
1685 let diags = checker.run();
1686
1687 assert_eq!(
1691 diags.warning_count(),
1692 0,
1693 "conditional setter should provide p_active_player on true branch, got {} warnings",
1694 diags.warning_count()
1695 );
1696 }
1697
1698 #[test]
1707 fn gosub_requires_then_corrupts_same_pointer() {
1708 let p_delay_op = 5001;
1709 let npc_delay_op = 5002;
1710
1711 let registry =
1712 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
1713
1714 let proc_script = make_script(
1717 "tackle_success",
1718 "proc",
1719 100,
1720 vec![
1721 line(1),
1722 push_int(0),
1723 cmd(p_delay_op), line(2),
1725 push_int(0),
1726 cmd(npc_delay_op), ret(),
1728 ],
1729 );
1730
1731 let label_script = make_script(
1734 "do_tackle",
1735 "label",
1736 200,
1737 vec![
1738 line(10),
1739 gosub(100), ret(),
1741 ],
1742 );
1743
1744 let scripts = vec![proc_script, label_script];
1745 let mut checker = PointerChecker::new(&scripts, ®istry);
1746 let diags = checker.run();
1747
1748 assert_eq!(
1754 diags.warning_count(),
1755 0,
1756 "gosub that requires-then-corrupts p_active_player should not \
1757 be flagged (engine-tracked pointer), got {} warnings",
1758 diags.warning_count()
1759 );
1760 }
1761
1762 #[test]
1768 fn corruption_before_requirement_is_caught() {
1769 let npc_delay_op = 5002;
1770 let p_delay_op = 5001;
1771
1772 let registry =
1773 registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
1774
1775 let script = make_script(
1778 "bad_order",
1779 "label",
1780 0,
1781 vec![
1782 line(1),
1783 push_int(0),
1784 cmd(npc_delay_op), line(2),
1786 push_int(0),
1787 cmd(p_delay_op), ret(),
1789 ],
1790 );
1791
1792 let scripts = vec![script];
1793 let mut checker = PointerChecker::new(&scripts, ®istry);
1794 let diags = checker.run();
1795
1796 assert!(
1797 diags.warning_count() > 0,
1798 "corruption before requirement should be caught as a warning"
1799 );
1800 }
1801
1802 #[test]
1807 fn uninitialized_pointer_caught() {
1808 let p_delay_op = 5001;
1809
1810 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
1811
1812 let script = make_script(
1814 "bad_access",
1815 "ai_timer",
1816 0,
1817 vec![
1818 line(1),
1819 push_int(0),
1820 cmd(p_delay_op), ret(),
1822 ],
1823 );
1824
1825 let scripts = vec![script];
1826 let mut checker = PointerChecker::new(&scripts, ®istry);
1827 let diags = checker.run();
1828
1829 assert!(
1830 diags.warning_count() > 0,
1831 "uninitialized pointer access should be caught"
1832 );
1833 }
1834
1835 #[test]
1845 fn branch_target_on_line_number_still_connects() {
1846 let p_delay_op = 5001;
1847 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
1848
1849 let script = make_script(
1865 "target_on_line_number",
1866 "ai_timer",
1867 0,
1868 vec![
1869 line(1),
1870 push_int(1),
1871 push_int(1),
1872 branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
1874 line(2),
1875 push_int(0),
1876 cmd(p_delay_op),
1877 ret(),
1878 ],
1879 );
1880
1881 let scripts = vec![script];
1882 let mut checker = PointerChecker::new(&scripts, ®istry);
1883 let diags = checker.run();
1884
1885 assert!(
1886 diags.warning_count() > 0,
1887 "jump target on LineNumber must still flag uninitialized pointer \
1888 access (got {} warnings)",
1889 diags.warning_count()
1890 );
1891 }
1892
1893 #[test]
1903 fn secondary_requires_and_corrupts_warns_for_static_pointer() {
1904 let last_useitem_op = 4270;
1907 let p_delay_op = 5001;
1908 let registry =
1909 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
1910
1911 let callee = make_script(
1913 "consume_useitem",
1914 "label",
1915 100,
1916 vec![
1917 line(1),
1918 cmd(last_useitem_op), line(2),
1920 push_int(0),
1921 cmd(p_delay_op), ret(),
1923 ],
1924 );
1925
1926 let caller = make_script(
1933 "use_on_loc",
1934 "oplocu",
1935 200,
1936 vec![
1937 line(10),
1938 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
1939 ],
1940 );
1941
1942 let scripts = vec![callee, caller];
1943 let mut checker = PointerChecker::new(&scripts, ®istry);
1944 let diags = checker.run();
1945
1946 let last_useitem_warnings = diags
1947 .diagnostics()
1948 .iter()
1949 .filter(|d| d.severity == Severity::Warning)
1950 .filter(|d| d.message.contains("last_useitem"))
1951 .count();
1952 assert!(
1953 last_useitem_warnings > 0,
1954 "static-only pointer (last_useitem) should trigger the \
1955 require+corrupt warning at the jump site; got diags: {:?}",
1956 diags
1957 .diagnostics()
1958 .iter()
1959 .map(|d| &d.message)
1960 .collect::<Vec<_>>()
1961 );
1962
1963 assert_eq!(
1964 diags.error_count(),
1965 0,
1966 "pointer-check diagnostics must never raise error severity; got {} errors",
1967 diags.error_count()
1968 );
1969 }
1970
1971 #[test]
1980 fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
1981 let p_delay_op = 5001;
1982 let npc_delay_op = 5002;
1983 let registry =
1984 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
1985
1986 let callee = make_script(
1987 "consume_protected",
1988 "proc",
1989 100,
1990 vec![
1991 line(1),
1992 push_int(0),
1993 cmd(p_delay_op), line(2),
1995 push_int(0),
1996 cmd(npc_delay_op), ret(),
1998 ],
1999 );
2000
2001 let caller = make_script(
2003 "do_opnpc",
2004 "opnpc1",
2005 200,
2006 vec![
2007 line(10),
2008 Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2009 ret(),
2010 ],
2011 );
2012
2013 let scripts = vec![callee, caller];
2014 let mut checker = PointerChecker::new(&scripts, ®istry);
2015 let diags = checker.run();
2016
2017 let p_active_player_warnings = diags
2018 .diagnostics()
2019 .iter()
2020 .filter(|d| d.severity == Severity::Warning)
2021 .filter(|d| d.message.contains("p_active_player"))
2022 .count();
2023 assert_eq!(
2024 p_active_player_warnings, 0,
2025 "engine-tracked pointer (p_active_player) must not trigger the \
2026 require+corrupt warning; got {} such warnings",
2027 p_active_player_warnings
2028 );
2029 }
2030
2031 #[test]
2044 fn secondary_varn_requires_active_npc2_not_primary() {
2045 let secondary_varn = Instruction::new(
2050 Opcode::PushVarn,
2051 Operand::Int(1 << 16), );
2053
2054 let proc_script = make_script(
2056 "reads_secondary_varn",
2057 "proc",
2058 100,
2059 vec![
2060 line(1),
2061 secondary_varn,
2062 Instruction::simple(Opcode::PopIntDiscard),
2063 ret(),
2064 ],
2065 );
2066
2067 let caller = make_script(
2074 "gosub_into_proc",
2075 "opplayer1",
2076 200,
2077 vec![line(10), gosub(100), ret()],
2078 );
2079
2080 let scripts = vec![proc_script, caller];
2081 let registry = registry_with_commands(&[]);
2082 let mut checker = PointerChecker::new(&scripts, ®istry);
2083 let diags = checker.run();
2084
2085 let active_npc_primary_warnings = diags
2091 .diagnostics()
2092 .iter()
2093 .filter(|d| d.severity == Severity::Warning)
2094 .filter(|d| d.message.contains("pointer active_npc."))
2095 .count();
2096 assert_eq!(
2097 active_npc_primary_warnings,
2098 0,
2099 "secondary .%var read must not flag primary active_npc at the \
2100 caller; got diags: {:?}",
2101 diags
2102 .diagnostics()
2103 .iter()
2104 .filter(|d| d.severity == Severity::Warning)
2105 .map(|d| &d.message)
2106 .collect::<Vec<_>>()
2107 );
2108
2109 let active_npc2_warnings = diags
2113 .diagnostics()
2114 .iter()
2115 .filter(|d| d.severity == Severity::Warning)
2116 .filter(|d| d.message.contains("pointer .active_npc."))
2117 .count();
2118 assert!(
2119 active_npc2_warnings > 0,
2120 "secondary .%var should route the requirement to active_npc2; \
2121 got no such warning"
2122 );
2123 }
2124
2125 #[test]
2130 fn rewrite_call_site_no_args() {
2131 let got = rewrite_call_site_arg(
2132 "[opnpcu,wantcat1] @civilian_give_runes;",
2133 "@",
2134 "civilian_give_runes",
2135 "last_useitem",
2136 )
2137 .unwrap();
2138 assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2139 }
2140
2141 #[test]
2142 fn rewrite_call_site_with_args() {
2143 let got = rewrite_call_site_arg(
2144 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2145 "@",
2146 "amulet_of_glory_interface",
2147 "last_item",
2148 )
2149 .unwrap();
2150 assert_eq!(
2151 got,
2152 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2153 );
2154 }
2155
2156 #[test]
2157 fn rewrite_call_site_gosub_no_args() {
2158 let got =
2159 rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2160 assert_eq!(got, " ~some_proc(last_useitem);");
2161 }
2162
2163 #[test]
2164 fn rewrite_call_site_empty_arg_list() {
2165 let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2166 assert_eq!(got, "@foo(last_useitem);");
2167 }
2168
2169 #[test]
2170 fn rewrite_header_no_params() {
2171 let got = rewrite_header_add_param(
2172 "[label,civilian_give_runes]",
2173 "civilian_give_runes",
2174 "obj",
2175 "$last_useitem",
2176 )
2177 .unwrap();
2178 assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2179 }
2180
2181 #[test]
2182 fn rewrite_header_with_existing_params() {
2183 let got = rewrite_header_add_param(
2184 "[label,amulet_of_glory_interface](string $message)",
2185 "amulet_of_glory_interface",
2186 "obj",
2187 "$last_item",
2188 )
2189 .unwrap();
2190 assert_eq!(
2191 got,
2192 "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2193 );
2194 }
2195
2196 #[test]
2197 fn rewrite_header_proc_with_return_type() {
2198 let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2201 assert_eq!(got, "[proc,foo](obj $x)(int)");
2202 }
2203
2204 #[test]
2205 fn find_header_line_matches_trigger_and_name() {
2206 let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2207 assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2208 assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2209 assert_eq!(find_header_line(src, "label", "missing"), None);
2210 }
2211
2212 #[test]
2213 fn format_corruptors_shapes() {
2214 assert_eq!(
2215 format_corruptors(&[]),
2216 "calls a delay or subroutine that may supersede it"
2217 );
2218 assert_eq!(
2219 format_corruptors(&[("p_delay".to_string(), 21)]),
2220 "calls `p_delay` at line 21 which may supersede it"
2221 );
2222 assert_eq!(
2223 format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2224 "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2225 );
2226 assert_eq!(
2227 format_corruptors(&[
2228 ("p_delay".to_string(), 21),
2229 ("~chatnpc".to_string(), 11),
2230 ("~objbox".to_string(), 14),
2231 ]),
2232 "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2233 );
2234 assert_eq!(
2236 format_corruptors(&[
2237 ("p_delay".to_string(), 1),
2238 ("~a".to_string(), 2),
2239 ("~b".to_string(), 3),
2240 ("~c".to_string(), 4),
2241 ("~d".to_string(), 5),
2242 ]),
2243 "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2244 );
2245 assert_eq!(
2247 format_corruptors(&[("p_delay".to_string(), 0)]),
2248 "calls `p_delay` which may supersede it"
2249 );
2250 }
2251
2252 #[test]
2253 fn find_matching_close_paren_nested() {
2254 assert_eq!(find_matching_close_paren("()"), Some(1));
2255 assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2256 assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2257 assert_eq!(find_matching_close_paren("("), None);
2258 assert_eq!(find_matching_close_paren("abc"), None);
2259 }
2260
2261 #[test]
2266 fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2267 use std::collections::HashMap;
2268 use std::sync::Arc;
2269
2270 let last_useitem_op = 4270;
2271 let p_delay_op = 5001;
2272 let registry =
2273 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2274
2275 let mut callee = make_script(
2277 "consume_useitem",
2278 "label",
2279 100,
2280 vec![
2281 line(2), cmd(last_useitem_op),
2283 line(3),
2284 push_int(0),
2285 cmd(p_delay_op),
2286 ret(),
2287 ],
2288 );
2289 callee.source_path = "/virt/consume.rs2".to_string();
2290
2291 let mut caller = make_script(
2293 "use_on_loc",
2294 "oplocu",
2295 200,
2296 vec![
2297 line(1),
2298 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2299 ],
2300 );
2301 caller.source_path = "/virt/caller.rs2".to_string();
2302
2303 let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2306 source_cache.insert(
2307 "/virt/caller.rs2".to_string(),
2308 Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2309 );
2310 source_cache.insert(
2311 "/virt/consume.rs2".to_string(),
2312 Arc::new(
2313 "[label,consume_useitem]\n\
2314 last_useitem;\n\
2315 p_delay(0);\n"
2316 .to_string(),
2317 ),
2318 );
2319
2320 let scripts = vec![callee, caller];
2321 let mut checker = PointerChecker::new(&scripts, ®istry);
2322 checker.set_source_cache(&source_cache);
2323 let diags = checker.run();
2324
2325 let warning = diags
2328 .diagnostics()
2329 .iter()
2330 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2331 .expect("expected a stale-last_useitem warning");
2332
2333 assert_eq!(
2334 warning.help.len(),
2335 1,
2336 "warning should have exactly one Help block, got {}",
2337 warning.help.len()
2338 );
2339 let help = &warning.help[0];
2340 assert!(
2341 help.message.contains("consume_useitem"),
2342 "help message should name the callee, got: {}",
2343 help.message
2344 );
2345 assert!(
2346 help.message.contains("last_useitem"),
2347 "help message should name the pointer, got: {}",
2348 help.message
2349 );
2350
2351 assert_eq!(
2353 help.suggestions.len(),
2354 2,
2355 "help should include both call-site and header suggestions, \
2356 got {}: {:?}",
2357 help.suggestions.len(),
2358 help.suggestions
2359 .iter()
2360 .map(|s| &s.label)
2361 .collect::<Vec<_>>()
2362 );
2363
2364 let caller_sug = help
2366 .suggestions
2367 .iter()
2368 .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2369 .expect("expected a call-site suggestion on the caller file");
2370 assert!(
2371 caller_sug
2372 .replacement
2373 .contains("@consume_useitem(last_useitem)"),
2374 "call-site replacement must pass last_useitem as an arg, got: {}",
2375 caller_sug.replacement
2376 );
2377
2378 let header_sug = help
2380 .suggestions
2381 .iter()
2382 .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2383 .expect("expected a header suggestion on the callee file");
2384 assert!(
2385 header_sug.replacement.contains("(obj $last_useitem)"),
2386 "header replacement must add `obj $last_useitem` param, got: {}",
2387 header_sug.replacement
2388 );
2389
2390 assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2391 }
2392
2393 #[test]
2397 fn secondary_warning_falls_back_to_prose_help_without_source() {
2398 let last_useitem_op = 4270;
2399 let p_delay_op = 5001;
2400 let registry =
2401 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2402
2403 let callee = make_script(
2404 "consume_useitem",
2405 "label",
2406 100,
2407 vec![
2408 line(1),
2409 cmd(last_useitem_op),
2410 line(2),
2411 push_int(0),
2412 cmd(p_delay_op),
2413 ret(),
2414 ],
2415 );
2416 let caller = make_script(
2417 "use_on_loc",
2418 "oplocu",
2419 200,
2420 vec![
2421 line(1),
2422 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2423 ],
2424 );
2425
2426 let scripts = vec![callee, caller];
2427 let mut checker = PointerChecker::new(&scripts, ®istry);
2428 let diags = checker.run();
2430
2431 let warning = diags
2432 .diagnostics()
2433 .iter()
2434 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2435 .expect("warning still fires without source cache");
2436
2437 assert_eq!(warning.help.len(), 1);
2438 let help = &warning.help[0];
2439 assert_eq!(
2440 help.suggestions.len(),
2441 0,
2442 "prose-only help should have no concrete suggestions"
2443 );
2444 assert_eq!(help.applicability, Applicability::Unspecified);
2445 }
2446}