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#[cfg(feature = "memprof")]
19static CFG_TRACE: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
20
21#[cfg(feature = "memprof")]
22fn cfg_trace_push(source_path: &str) {
23 if std::env::var_os("RUNEC_TRACE_CFG").is_some() {
24 CFG_TRACE.lock().unwrap().push(source_path.to_string());
25 }
26}
27
28#[cfg(feature = "memprof")]
31pub(crate) fn cfg_trace_report() {
32 use tracing::info;
33 let trace = CFG_TRACE.lock().unwrap();
34 if trace.is_empty() {
35 return;
36 }
37 let distinct: HashSet<&str> = trace.iter().map(|s| s.as_str()).collect();
38 let nfiles = distinct.len().max(1);
39 info!(
40 "[trace] build_cfg calls: {}, distinct files: {}",
41 trace.len(),
42 nfiles
43 );
44 for &cap in &[16usize, 64, 256, 1024, nfiles] {
45 let mut lru: Vec<&str> = Vec::with_capacity(cap + 1);
46 let mut misses = 0usize;
47 for f in trace.iter() {
48 let f = f.as_str();
49 if let Some(pos) = lru.iter().position(|x| *x == f) {
50 lru.remove(pos);
51 } else {
52 misses += 1;
53 }
54 lru.insert(0, f);
55 if lru.len() > cap {
56 lru.pop();
57 }
58 }
59 info!(
60 "[trace] LRU cap {:>5}: {:>7} re-parses ({:.2}x of {} files)",
61 cap,
62 misses,
63 misses as f64 / nfiles as f64,
64 nfiles
65 );
66 }
67}
68
69pub(crate) enum ScriptRef<'a> {
78 Borrowed(&'a CompiledScript),
79 Owned(std::rc::Rc<CompiledScript>),
80}
81
82impl std::ops::Deref for ScriptRef<'_> {
83 type Target = CompiledScript;
84 fn deref(&self) -> &CompiledScript {
85 match self {
86 ScriptRef::Borrowed(s) => s,
87 ScriptRef::Owned(rc) => rc,
88 }
89 }
90}
91
92pub(crate) enum ScriptSource<'a> {
98 Resident(&'a [CompiledScript]),
99 Recompile {
100 len: usize,
101 get: std::cell::RefCell<Box<dyn FnMut(usize) -> std::rc::Rc<CompiledScript> + 'a>>,
102 },
103}
104
105impl<'a> ScriptSource<'a> {
106 fn len(&self) -> usize {
107 match self {
108 ScriptSource::Resident(s) => s.len(),
109 ScriptSource::Recompile { len, .. } => *len,
110 }
111 }
112
113 fn get(&self, idx: usize) -> ScriptRef<'a> {
117 match self {
118 ScriptSource::Resident(s) => ScriptRef::Borrowed(&(*s)[idx]),
119 ScriptSource::Recompile { get, .. } => ScriptRef::Owned((get.borrow_mut())(idx)),
120 }
121 }
122}
123
124#[derive(Debug)]
129struct CfgNode {
130 instruction_index: Option<usize>,
133 pointer_set: PointerSet,
135 next: Vec<usize>,
137 previous: Vec<usize>,
139}
140
141impl CfgNode {
142 fn new(instruction_index: Option<usize>) -> Self {
143 CfgNode {
144 instruction_index,
145 pointer_set: PointerSet::new(),
146 next: Vec::new(),
147 previous: Vec::new(),
148 }
149 }
150
151 fn pointer_node(pointer_set: PointerSet) -> Self {
152 CfgNode {
153 instruction_index: None,
154 pointer_set,
155 next: Vec::new(),
156 previous: Vec::new(),
157 }
158 }
159}
160
161struct ScriptAnalysis {
166 nodes: Vec<CfgNode>,
167 required: Vec<Vec<usize>>,
169 set_list: Vec<Vec<usize>>,
171 corrupted_list: Vec<Vec<usize>>,
173 returns: Vec<usize>,
175}
176
177impl ScriptAnalysis {
178 fn new() -> Self {
179 let n = PointerType::COUNT;
180 ScriptAnalysis {
181 nodes: Vec::new(),
182 required: vec![Vec::new(); n],
183 set_list: vec![Vec::new(); n],
184 corrupted_list: vec![Vec::new(); n],
185 returns: Vec::new(),
186 }
187 }
188}
189
190pub(crate) struct SharedMaps {
199 cmd_pointers: HashMap<String, PointerHolder>,
200 opcode_to_name: HashMap<i32, String>,
202 script_id_to_index: HashMap<i32, usize>,
204 script_name_to_index: HashMap<String, usize>,
208 overlay_interfaces: HashSet<String>,
211}
212
213pub struct PointerChecker<'a> {
214 scripts: ScriptSource<'a>,
215 #[allow(dead_code)]
216 registry: &'a SymbolRegistry,
217 shared: std::sync::Arc<SharedMaps>,
219 source_cache: Option<crate::SourceProvider<'a>>,
224 script_analyses: HashMap<String, ScriptAnalysis>,
226 script_pointers: HashMap<String, PointerHolder>,
227 pending_analyses: HashSet<String>,
228 pending_scripts: HashSet<String>,
229}
230
231impl SharedMaps {
232 fn build<'b>(idents: impl Iterator<Item = (i32, &'b str)>, registry: &SymbolRegistry) -> Self {
236 let mut opcode_to_name = HashMap::new();
238 for (name, sym) in ®istry.commands {
239 if let SymbolKind::Command { opcode, .. } = &sym.kind {
240 opcode_to_name.insert(*opcode, name.to_lowercase());
241 }
242 }
243
244 let mut script_id_to_index = HashMap::new();
248 let mut script_name_to_index = HashMap::new();
249 for (i, (id, name)) in idents.enumerate() {
250 script_id_to_index.insert(id, i);
251 script_name_to_index.entry(name.to_string()).or_insert(i);
252 }
253
254 let mut overlay_interfaces = HashSet::new();
258 for (name, entry) in ®istry.entity_ids {
259 if let Some(e) = entry.primary
260 && e.const_type == crate::types::Type::OverlayInterface
261 {
262 overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
263 }
264 }
265
266 SharedMaps {
267 cmd_pointers: command_pointers(),
268 opcode_to_name,
269 script_id_to_index,
270 script_name_to_index,
271 overlay_interfaces,
272 }
273 }
274}
275
276impl<'a> PointerChecker<'a> {
277 pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
278 let shared = std::sync::Arc::new(SharedMaps::build(
279 scripts.iter().map(|s| (s.id, s.name.as_str())),
280 registry,
281 ));
282 Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
283 }
284
285 pub(crate) fn build_shared(
289 scripts: &[CompiledScript],
290 registry: &SymbolRegistry,
291 ) -> std::sync::Arc<SharedMaps> {
292 std::sync::Arc::new(SharedMaps::build(
293 scripts.iter().map(|s| (s.id, s.name.as_str())),
294 registry,
295 ))
296 }
297
298 pub(crate) fn build_shared_idents(
301 idents: &[(i32, String)],
302 registry: &SymbolRegistry,
303 ) -> std::sync::Arc<SharedMaps> {
304 std::sync::Arc::new(SharedMaps::build(
305 idents.iter().map(|(id, name)| (*id, name.as_str())),
306 registry,
307 ))
308 }
309
310 pub(crate) fn with_shared(
313 scripts: ScriptSource<'a>,
314 registry: &'a SymbolRegistry,
315 shared: std::sync::Arc<SharedMaps>,
316 ) -> Self {
317 PointerChecker {
318 scripts,
319 registry,
320 shared,
321 source_cache: None,
322 script_analyses: HashMap::new(),
323 script_pointers: HashMap::new(),
324 pending_analyses: HashSet::new(),
325 pending_scripts: HashSet::new(),
326 }
327 }
328
329 pub fn set_source_cache(&mut self, provider: crate::SourceProvider<'a>) {
333 self.source_cache = Some(provider);
334 }
335
336 fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
339 if !crate::trigger_table::is_button(trigger) {
340 return false;
341 }
342 let subject = script_name
344 .trim_start_matches('[')
345 .trim_end_matches(']')
346 .split_once(',')
347 .map(|(_, rest)| rest)
348 .unwrap_or("");
349 let iface_name = subject
350 .split(':')
351 .next()
352 .unwrap_or("")
353 .to_lowercase()
354 .replace(' ', "_");
355 if iface_name.is_empty() {
356 return false;
357 }
358 !self.shared.overlay_interfaces.contains(&iface_name)
360 }
361
362 pub fn run(&mut self) -> DiagnosticsCollector {
364 let names = self.script_names();
365 self.validate_names(&names)
366 }
367
368 pub fn script_names(&self) -> Vec<String> {
370 (0..self.scripts.len())
371 .map(|i| self.scripts.get(i).name.clone())
372 .collect()
373 }
374
375 pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
383 let mut diagnostics = DiagnosticsCollector::new();
384 for script_name in names {
385 self.validate_script(script_name, &mut diagnostics);
386 self.script_analyses.clear();
394 }
395 diagnostics
396 }
397
398 fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
399 let script_idx = match self.shared.script_name_to_index.get(script_name) {
401 Some(&i) => i,
402 None => return,
403 };
404 let trigger = self.scripts.get(script_idx).trigger.clone();
405 let source_path = self.scripts.get(script_idx).source_path.clone();
406 let trigger_set = trigger_pointers(&trigger);
407
408 self.ensure_analysis(script_name);
410
411 for &ptr in &PointerType::ALL {
412 let ptr_idx = ptr.index();
413
414 let analysis = match self.script_analyses.get(script_name) {
416 Some(a) => a,
417 None => continue,
418 };
419
420 let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
421 if required_nodes.is_empty() {
422 continue;
423 }
424
425 let mut corrupted: HashSet<usize> =
430 analysis.corrupted_list[ptr_idx].iter().copied().collect();
431
432 let trigger_provides = if trigger_set.contains(ptr) {
436 true
437 } else if ptr == PointerType::PActivePlayer {
438 self.interface_trigger_grants_protected(&trigger, script_name)
439 } else {
440 false
441 };
442 if !trigger_provides {
443 corrupted.insert(0);
444 }
445
446 if corrupted.is_empty() {
447 continue;
448 }
449
450 let set_blocked: HashSet<usize> = analysis.set_list[ptr_idx].iter().copied().collect();
451
452 let path = self.find_edge_path(
454 script_name,
455 &required_nodes,
456 |node_idx| corrupted.contains(&node_idx),
457 &set_blocked,
458 );
459
460 let mut reported_via_main_bfs = false;
461 if let Some(path) = path {
462 if path.is_empty() {
463 continue;
464 }
465 reported_via_main_bfs = true;
466
467 let end_node_idx = path[path.len() - 1];
468 let start_node_idx = path[0];
469
470 let is_start_node = end_node_idx == 0;
471 let repr = ptr.representation();
472 let static_only = is_static_only_pointer(ptr);
473
474 let error_msg = if is_start_node {
480 if static_only {
481 msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
482 } else {
483 msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
484 }
485 } else if static_only {
486 msg::fmt(msg::POINTER_STALE, &[repr])
487 } else {
488 msg::fmt(msg::POINTER_CORRUPTED, &[repr])
489 };
490
491 let analysis = self.script_analyses.get(script_name).unwrap();
492 let script_ref = self.scripts.get(script_idx);
493 let instructions = &script_ref.instructions;
494 let req_line = analysis.nodes[start_node_idx]
495 .instruction_index
496 .map(|idx| resolve_line(instructions, idx))
497 .unwrap_or(0);
498
499 diagnostics.add(Diagnostic {
504 file: PathBuf::from(&source_path),
505 line: req_line,
506 column: 0,
507 message: error_msg,
508 severity: Severity::Warning,
509 phase: Phase::PointerCheck,
510 help: Vec::new(),
511 });
512
513 let read_hint = if static_only {
514 msg::fmt(msg::POINTER_READ_HERE, &[repr])
515 } else {
516 msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
517 };
518 diagnostics.add(Diagnostic {
519 file: PathBuf::from(&source_path),
520 line: req_line,
521 column: 0,
522 message: read_hint,
523 severity: Severity::Info,
524 phase: Phase::PointerCheck,
525 help: Vec::new(),
526 });
527
528 if !is_start_node {
529 let corrupt_line = analysis.nodes[end_node_idx]
530 .instruction_index
531 .map(|idx| resolve_line(instructions, idx))
532 .unwrap_or(0);
533
534 let cause_hint = if static_only {
535 msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
536 } else {
537 msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
538 };
539 diagnostics.add(Diagnostic {
540 file: PathBuf::from(&source_path),
541 line: corrupt_line,
542 column: 0,
543 message: cause_hint,
544 severity: Severity::Info,
545 phase: Phase::PointerCheck,
546 help: Vec::new(),
547 });
548 }
549 }
550
551 if !reported_via_main_bfs && is_static_only_pointer(ptr) {
564 let targets: Vec<(usize, usize)> = {
568 let analysis = self.script_analyses.get(script_name).unwrap();
569 let script_ref = self.scripts.get(script_idx);
570 let instructions = &script_ref.instructions;
571 let corrupted_nodes: HashSet<usize> =
572 analysis.corrupted_list[ptr_idx].iter().copied().collect();
573 required_nodes
574 .iter()
575 .filter(|&&node_idx| corrupted_nodes.contains(&node_idx))
576 .map(|&node_idx| {
577 let line = analysis.nodes[node_idx]
578 .instruction_index
579 .map(|idx| resolve_line(instructions, idx))
580 .unwrap_or(0);
581 (node_idx, line)
582 })
583 .collect()
584 };
585 let mut seen_lines: HashSet<usize> = HashSet::new();
586 let repr = ptr.representation();
587 for (node_idx, line) in targets {
588 if !seen_lines.insert(line) {
589 continue;
590 }
591
592 let help =
597 self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
598
599 let mut diag = Diagnostic {
607 file: PathBuf::from(&source_path),
608 line,
609 column: 0,
610 message: msg::fmt(msg::POINTER_STALE, &[repr]),
611 severity: Severity::Warning,
612 phase: Phase::PointerCheck,
613 help: Vec::new(),
614 };
615 if let Some(h) = help {
616 diag.help.push(h);
617 }
618 diagnostics.add(diag);
619 }
620 }
621 }
622 }
623
624 fn find_edge_path(
633 &self,
634 script_name: &str,
635 starts: &[usize],
636 end_pred: impl Fn(usize) -> bool,
637 blocked: &HashSet<usize>,
638 ) -> Option<Vec<usize>> {
639 let analysis = self.script_analyses.get(script_name)?;
640
641 let mut queue: VecDeque<usize> = VecDeque::new();
642 let mut visited: HashSet<usize> = HashSet::new();
643 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); for &start in starts {
651 for &prev in &analysis.nodes[start].previous {
652 if blocked.contains(&prev) || visited.contains(&prev) {
653 continue;
654 }
655 visited.insert(prev);
656 queue.push_back(prev);
657 sources.insert(prev, (start, start));
658 }
659 }
660
661 while let Some(current) = queue.pop_front() {
662 if end_pred(current) {
663 let mut path = vec![current];
665 let mut node = current;
666 while let Some(&(from, start)) = sources.get(&node) {
667 if from == start && starts.contains(&from) {
668 path.push(from);
669 break;
670 }
671 path.push(from);
672 node = from;
673 }
674 path.reverse();
675 return Some(path);
676 }
677
678 let (_, start_node) = sources[¤t];
679
680 for &prev in &analysis.nodes[current].previous {
681 if blocked.contains(&prev) || visited.contains(&prev) {
682 continue;
683 }
684 visited.insert(prev);
685 queue.push_back(prev);
686 sources.insert(prev, (current, start_node));
687 }
688 }
689
690 None
691 }
692
693 fn find_edge_path_static(
696 nodes: &[CfgNode],
697 starts: &[usize],
698 end_pred: impl Fn(usize) -> bool,
699 blocked: &HashSet<usize>,
700 ) -> Option<Vec<usize>> {
701 let mut queue: VecDeque<usize> = VecDeque::new();
702 let mut visited: HashSet<usize> = HashSet::new();
703 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
704
705 for &start in starts {
706 for &prev in &nodes[start].previous {
707 if blocked.contains(&prev) || visited.contains(&prev) {
708 continue;
709 }
710 visited.insert(prev);
711 queue.push_back(prev);
712 sources.insert(prev, (start, start));
713 }
714 }
715
716 while let Some(current) = queue.pop_front() {
717 if end_pred(current) {
718 let mut path = vec![current];
719 let mut node = current;
720 while let Some(&(from, start)) = sources.get(&node) {
721 if from == start && starts.contains(&from) {
722 path.push(from);
723 break;
724 }
725 path.push(from);
726 node = from;
727 }
728 path.reverse();
729 return Some(path);
730 }
731
732 for &prev in &nodes[current].previous {
733 if blocked.contains(&prev) || visited.contains(&prev) {
734 continue;
735 }
736 visited.insert(prev);
737 queue.push_back(prev);
738 sources.insert(prev, (current, sources[¤t].1));
739 }
740 }
741
742 None
743 }
744
745 fn ensure_analysis(&mut self, script_name: &str) {
750 if self.script_analyses.contains_key(script_name) {
751 return;
752 }
753 if self.pending_analyses.contains(script_name) {
754 return; }
756 self.pending_analyses.insert(script_name.to_string());
757
758 let script_idx = match self.shared.script_name_to_index.get(script_name) {
759 Some(&i) => i,
760 None => return,
761 };
762
763 let mut analysis = self.build_cfg(script_idx);
764 self.categorize_nodes(script_idx, &mut analysis);
765
766 self.script_analyses
767 .insert(script_name.to_string(), analysis);
768 self.pending_analyses.remove(script_name);
769 }
770
771 fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
776 let script = self.scripts.get(script_idx);
777 #[cfg(feature = "memprof")]
778 cfg_trace_push(&script.source_path);
779 let instructions = &script.instructions;
780 let mut analysis = ScriptAnalysis::new();
781
782 analysis.nodes.push(CfgNode::new(None));
784
785 let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
787 let mut node_order: Vec<usize> = Vec::new(); for (i, instr) in instructions.iter().enumerate() {
790 if instr.opcode == Opcode::LineNumber {
791 continue;
792 }
793 let node_idx = analysis.nodes.len();
794 instr_to_node.insert(i, node_idx);
795 node_order.push(i);
796 analysis.nodes.push(CfgNode::new(Some(i)));
797 }
798
799 if node_order.is_empty() {
800 return analysis;
801 }
802
803 let first_node = instr_to_node[&node_order[0]];
805 add_edge(&mut analysis.nodes, 0, first_node);
806
807 for (order_idx, &instr_idx) in node_order.iter().enumerate() {
809 let node_idx = instr_to_node[&instr_idx];
810 let instr = &instructions[instr_idx];
811
812 let is_terminal = matches!(
813 instr.opcode,
814 Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
815 );
816
817 match instr.opcode {
822 Opcode::Branch
823 | Opcode::BranchNot
824 | Opcode::BranchEquals
825 | Opcode::BranchLessThan
826 | Opcode::BranchGreaterThan
827 | Opcode::BranchLessThanOrEquals
828 | Opcode::BranchGreaterThanOrEquals
829 | Opcode::LongBranchNot
830 | Opcode::LongBranchEquals
831 | Opcode::LongBranchLessThan
832 | Opcode::LongBranchGreaterThan
833 | Opcode::LongBranchLessThanOrEquals
834 | Opcode::LongBranchGreaterThanOrEquals
835 | Opcode::ObjBranchEquals
836 | Opcode::ObjBranchNot => {
837 if let Operand::JumpTarget(target_instr_idx) = &instr.operand
838 && let Some(target_node) =
839 resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
840 {
841 add_edge(&mut analysis.nodes, node_idx, target_node);
842 }
843 }
844
845 Opcode::Switch => {
846 if let Operand::SwitchTable(tbl_idx) = &instr.operand {
847 let cases = &script.switch_tables[*tbl_idx as usize];
848 for &(_, target_instr_idx) in cases.iter() {
849 if let Some(target_node) =
850 resolve_target_node(target_instr_idx, instructions, &instr_to_node)
851 {
852 add_edge(&mut analysis.nodes, node_idx, target_node);
853 }
854 }
855 }
856 }
857
858 _ => {}
859 }
860
861 if !is_terminal
863 && let Some(next_order_idx) = order_idx.checked_add(1)
864 && next_order_idx < node_order.len()
865 {
866 let next_node = instr_to_node[&node_order[next_order_idx]];
867 add_edge(&mut analysis.nodes, node_idx, next_node);
868 }
869
870 if instr.opcode == Opcode::Return {
875 analysis.returns.push(node_idx);
876 }
877 }
878
879 self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
881
882 analysis
883 }
884
885 fn insert_pointer_nodes(
888 &self,
889 script_idx: usize,
890 analysis: &mut ScriptAnalysis,
891 instr_to_node: &HashMap<usize, usize>,
892 node_order: &[usize],
893 ) {
894 let script_ref = self.scripts.get(script_idx);
895 let instructions = &script_ref.instructions;
896
897 for window_end in 2..node_order.len() {
902 let push_instr_idx = node_order[window_end - 1];
903 let branch_instr_idx = node_order[window_end];
904
905 let push_instr = &instructions[push_instr_idx];
906 let branch_instr = &instructions[branch_instr_idx];
907
908 let push_value = match &push_instr.operand {
910 Operand::Int(v) if *v == 0 || *v == 1 => *v,
911 _ => continue,
912 };
913 if push_instr.opcode != Opcode::PushConstantInt {
914 continue;
915 }
916 if branch_instr.opcode != Opcode::BranchEquals {
917 continue;
918 }
919
920 let mut cmd_instr_idx = None;
922 for scan in (0..window_end - 1).rev() {
923 let idx = node_order[scan];
924 if instructions[idx].opcode == Opcode::Command {
925 cmd_instr_idx = Some(idx);
926 break;
927 }
928 if matches!(
930 instructions[idx].opcode,
931 Opcode::Branch
932 | Opcode::Return
933 | Opcode::Switch
934 | Opcode::BranchEquals
935 | Opcode::BranchNot
936 | Opcode::BranchLessThan
937 | Opcode::BranchGreaterThan
938 | Opcode::BranchLessThanOrEquals
939 | Opcode::BranchGreaterThanOrEquals
940 ) {
941 break;
942 }
943 }
944 let cmd_instr_idx = match cmd_instr_idx {
945 Some(idx) => idx,
946 None => continue,
947 };
948 let cmd_instr = &instructions[cmd_instr_idx];
949
950 let cmd_name = self.resolve_command_name(cmd_instr, &script_ref.strings);
952 let cmd_name = match cmd_name {
953 Some(n) => n,
954 None => continue,
955 };
956
957 let holder = match self.shared.cmd_pointers.get(&cmd_name) {
958 Some(h) => h,
959 None => continue,
960 };
961
962 if !holder.conditional_set {
963 continue;
964 }
965
966 if holder.set.is_empty() {
967 continue;
968 }
969
970 let branch_node_idx = instr_to_node[&branch_instr_idx];
971
972 let ptr_node_idx = analysis.nodes.len();
974 analysis.nodes.push(CfgNode::pointer_node(holder.set));
975
976 if push_value == 0 {
977 let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
985 .next
986 .iter()
987 .copied()
988 .filter(|&n| {
989 if let Operand::JumpTarget(target) = &branch_instr.operand
991 && let Some(jump_node) =
992 resolve_target_node(*target, instructions, instr_to_node)
993 {
994 return n != jump_node;
995 }
996 true
997 })
998 .collect();
999
1000 for ft_target in fallthrough_targets {
1001 remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
1003 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1005 add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
1006 }
1007 } else {
1008 if let Operand::JumpTarget(target) = &branch_instr.operand
1012 && let Some(jump_target_node) =
1013 resolve_target_node(*target, instructions, instr_to_node)
1014 {
1015 remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
1017 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1019 add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
1020 }
1021 }
1022 }
1023 }
1024
1025 fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
1030 let script_ref = self.scripts.get(script_idx);
1031 let instructions = &script_ref.instructions;
1032
1033 for node_idx in 0..analysis.nodes.len() {
1034 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1035 Some(i) => i,
1036 None => {
1037 let ptr_set = analysis.nodes[node_idx].pointer_set;
1039 if !ptr_set.is_empty() {
1040 for ptr in ptr_set.iter() {
1041 let pi = ptr.index();
1042 analysis.set_list[pi].push(node_idx);
1043 }
1044 }
1045 continue;
1046 }
1047 };
1048
1049 let instr = &instructions[instr_idx];
1050
1051 match instr.opcode {
1052 Opcode::Command => {
1053 let cmd_name = self.resolve_command_name(instr, &script_ref.strings);
1054 if let Some(name) = cmd_name
1055 && let Some(holder) = self.shared.cmd_pointers.get(&name).cloned()
1056 {
1057 self.apply_holder(analysis, node_idx, &holder);
1058 }
1059 }
1060
1061 Opcode::Gosub | Opcode::GosubWithParams => {
1062 if let Operand::Int(script_id) = &instr.operand {
1063 let callee_holder = self.get_script_pointers(*script_id);
1064 self.apply_holder(analysis, node_idx, &callee_holder);
1065 }
1066 }
1067
1068 Opcode::Jump | Opcode::JumpWithParams => {
1069 if let Operand::Int(script_id) = &instr.operand {
1070 let callee_holder = self.get_script_pointers(*script_id);
1071 self.apply_holder(analysis, node_idx, &callee_holder);
1072 }
1073 }
1074
1075 Opcode::PushVarp | Opcode::PushVarbit => {
1082 let pi = if is_secondary_var_operand(&instr.operand) {
1083 PointerType::ActivePlayer2.index()
1084 } else {
1085 PointerType::ActivePlayer.index()
1086 };
1087 analysis.required[pi].push(node_idx);
1088 }
1089
1090 Opcode::PopVarp | Opcode::PopVarbit => {
1091 let pi = if is_secondary_var_operand(&instr.operand) {
1092 PointerType::ActivePlayer2.index()
1093 } else {
1094 PointerType::ActivePlayer.index()
1095 };
1096 analysis.required[pi].push(node_idx);
1097 }
1098
1099 Opcode::PushVarn | Opcode::PopVarn => {
1100 let pi = if is_secondary_var_operand(&instr.operand) {
1101 PointerType::ActiveNpc2.index()
1102 } else {
1103 PointerType::ActiveNpc.index()
1104 };
1105 analysis.required[pi].push(node_idx);
1106 }
1107
1108 _ => {}
1110 }
1111 }
1112 }
1113
1114 fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
1115 for ptr in holder.required.iter() {
1116 let pi = ptr.index();
1117 analysis.required[pi].push(node_idx);
1118 }
1119 for ptr in holder.set.iter() {
1120 let pi = ptr.index();
1121 analysis.set_list[pi].push(node_idx);
1122 }
1123 for ptr in holder.corrupted.iter() {
1124 let pi = ptr.index();
1125 analysis.corrupted_list[pi].push(node_idx);
1126 }
1127 }
1128
1129 fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
1145 let script_idx = match self.shared.script_id_to_index.get(&script_id) {
1147 Some(&i) => i,
1148 None => {
1149 return PointerHolder::default();
1150 }
1151 };
1152 let script_name = self.scripts.get(script_idx).name.clone();
1153
1154 if let Some(holder) = self.script_pointers.get(&script_name) {
1156 return holder.clone();
1157 }
1158
1159 if self.pending_scripts.contains(&script_name) {
1161 return PointerHolder::default();
1162 }
1163 self.pending_scripts.insert(script_name.clone());
1164
1165 self.ensure_analysis(&script_name);
1167
1168 let mut holder = PointerHolder::default();
1169
1170 if let Some(analysis) = self.script_analyses.get(&script_name) {
1171 for &ptr in &PointerType::ALL {
1172 let pi = ptr.index();
1173
1174 let requires = !analysis.required[pi].is_empty();
1180 let has_returns = !analysis.returns.is_empty();
1181 if !requires && !has_returns {
1182 continue;
1183 }
1184 let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
1185
1186 if requires {
1188 let path = Self::find_edge_path_static(
1189 &analysis.nodes,
1190 &analysis.required[pi],
1191 |node_idx| node_idx == 0,
1192 &set_blocked,
1193 );
1194 if path.is_some() {
1195 holder.required.insert(ptr);
1196 }
1197 }
1198
1199 if has_returns {
1200 let corrupted_nodes: HashSet<usize> =
1201 analysis.corrupted_list[pi].iter().copied().collect();
1202
1203 let path = Self::find_edge_path_static(
1206 &analysis.nodes,
1207 &analysis.returns,
1208 |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1209 &set_blocked,
1210 );
1211 if path.is_none() {
1212 holder.set.insert(ptr);
1213 }
1214
1215 if !corrupted_nodes.is_empty() {
1217 let path = Self::find_edge_path_static(
1218 &analysis.nodes,
1219 &analysis.returns,
1220 |node_idx| corrupted_nodes.contains(&node_idx),
1221 &set_blocked,
1222 );
1223 if path.is_some() {
1224 holder.corrupted.insert(ptr);
1225 }
1226 }
1227 }
1228 }
1229 }
1230
1231 self.pending_scripts.remove(&script_name);
1232
1233 self.script_pointers
1234 .insert(script_name.clone(), holder.clone());
1235 holder
1236 }
1237
1238 fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1248 let callee = self.scripts.get(callee_idx);
1249 let analysis = match self.script_analyses.get(&callee.name) {
1250 Some(a) => a,
1251 None => return Vec::new(),
1252 };
1253 let ptr_idx = ptr.index();
1254 let mut seen: HashSet<(String, usize)> = HashSet::new();
1255 let mut result: Vec<(String, usize)> = Vec::new();
1256
1257 for &node_idx in &analysis.corrupted_list[ptr_idx] {
1258 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1259 Some(i) => i,
1260 None => continue,
1261 };
1262 let instr = &callee.instructions[instr_idx];
1263 let line = resolve_line(&callee.instructions, instr_idx);
1264
1265 let name = match instr.opcode {
1266 Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
1267 Some(n) => n,
1268 None => continue,
1269 },
1270 Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1271 Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
1272 Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
1273 .map(|s| format!("~{}", s))
1274 .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
1275 None => continue,
1276 },
1277 _ => continue,
1278 },
1279 _ => continue,
1283 };
1284
1285 let key = (name.clone(), line);
1286 if seen.insert(key) {
1287 result.push((name, line));
1288 }
1289 }
1290
1291 result
1292 }
1293
1294 fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
1295 match &instr.operand {
1296 Operand::Int(encoded) => {
1297 let opcode = encoded & 0xFFFF;
1298 let secondary = (encoded >> 16) & 1;
1299 let base_name = self.shared.opcode_to_name.get(&opcode)?;
1300 if secondary == 1 {
1301 Some(format!(".{}", base_name))
1302 } else {
1303 Some(base_name.clone())
1304 }
1305 }
1306 Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
1307 _ => None,
1308 }
1309 }
1310
1311 fn build_rule_a_help(
1323 &mut self,
1324 ptr: PointerType,
1325 caller_source_path: &str,
1326 caller_line: usize,
1327 node_idx: usize,
1328 caller_script_idx: usize,
1329 ) -> Option<Help> {
1330 let (is_gosub, script_id) = {
1333 let caller = self.scripts.get(caller_script_idx);
1334 let analysis = self.script_analyses.get(&caller.name)?;
1335 let instr_idx = analysis.nodes[node_idx].instruction_index?;
1336 let instr = &caller.instructions[instr_idx];
1337 match instr.opcode {
1339 Opcode::Jump | Opcode::JumpWithParams => (
1340 false,
1341 match &instr.operand {
1342 Operand::Int(id) => *id,
1343 _ => return None,
1344 },
1345 ),
1346 Opcode::Gosub | Opcode::GosubWithParams => (
1347 true,
1348 match &instr.operand {
1349 Operand::Int(id) => *id,
1350 _ => return None,
1351 },
1352 ),
1353 _ => return None,
1354 }
1355 };
1356
1357 let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
1358 let callee_name = self.scripts.get(callee_idx).name.clone();
1362 self.ensure_analysis(&callee_name);
1363
1364 let callee = self.scripts.get(callee_idx);
1365 let callee_source = callee.source_path.clone();
1366
1367 let first_body_line = callee
1375 .instructions
1376 .iter()
1377 .find_map(|i| match (i.opcode, &i.operand) {
1378 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1379 _ => None,
1380 })
1381 .unwrap_or(1);
1382 let callee_trigger = callee.trigger.clone();
1383 let callee_short_early = callee
1384 .name
1385 .trim_start_matches('[')
1386 .trim_end_matches(']')
1387 .split_once(',')
1388 .map(|(_, n)| n.to_string())
1389 .unwrap_or_else(|| callee.name.clone());
1390 let callee_header_line = self
1391 .source_cache
1392 .and_then(|c| c.get(&callee_source))
1393 .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
1394 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1395
1396 let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
1398 let param_name = format!("${}", ptr_cmd);
1399
1400 let callee_short = callee
1401 .name
1402 .trim_start_matches('[')
1403 .trim_end_matches(']')
1404 .split_once(',')
1405 .map(|(_, n)| n.to_string())
1406 .unwrap_or_else(|| callee.name.clone());
1407
1408 let arrow = if is_gosub { "~" } else { "@" };
1409
1410 let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1415 let corruptor_phrase = format_corruptors(&corruptors);
1416
1417 let message = format!(
1418 "`{callee}` reads `{ptr}` then {phrase}; the script still \
1419 compiles and runs, but the reference is brittle to reorder. \
1420 Consider capturing `{ptr}` at the call site and threading it \
1421 through `{callee}` as an `{ty} {pname}` parameter so the \
1422 value is explicit and stable.",
1423 callee = callee_short,
1424 ptr = ptr_cmd,
1425 phrase = corruptor_phrase,
1426 ty = param_type,
1427 pname = param_name,
1428 );
1429
1430 let cache = match self.source_cache {
1431 Some(c) => c,
1432 None => {
1433 return Some(Help {
1435 message,
1436 suggestions: Vec::new(),
1437 applicability: Applicability::Unspecified,
1438 });
1439 }
1440 };
1441
1442 let mut suggestions = Vec::new();
1443
1444 if let Some(src) = cache.get(caller_source_path)
1447 && let Some(line_text) = nth_source_line(&src, caller_line)
1448 && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1449 {
1450 suggestions.push(Suggestion {
1451 file: PathBuf::from(caller_source_path),
1452 line_range: (caller_line, caller_line),
1453 replacement: rewritten,
1454 label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1455 });
1456 }
1457
1458 if let Some(src) = cache.get(&callee_source)
1460 && let Some(header_text) = nth_source_line(&src, callee_header_line)
1461 && let Some(rewritten) =
1462 rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
1463 {
1464 suggestions.push(Suggestion {
1465 file: PathBuf::from(&callee_source),
1466 line_range: (callee_header_line, callee_header_line),
1467 replacement: rewritten,
1468 label: Some(format!(
1469 "at the `{}` header (add `{} {}`)",
1470 callee_short, param_type, param_name
1471 )),
1472 });
1473 }
1474
1475 Some(Help {
1476 message,
1477 suggestions,
1478 applicability: Applicability::MaybeIncorrect,
1482 })
1483 }
1484}
1485
1486fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1491 if !nodes[from].next.contains(&to) {
1492 nodes[from].next.push(to);
1493 }
1494 if !nodes[to].previous.contains(&from) {
1495 nodes[to].previous.push(from);
1496 }
1497}
1498
1499fn is_static_only_pointer(ptr: PointerType) -> bool {
1512 use PointerType::*;
1513 matches!(
1514 ptr,
1515 FindPlayer
1516 | FindNpc
1517 | FindLoc
1518 | FindObj
1519 | FindDb
1520 | LastCom
1521 | LastInt
1522 | LastItem
1523 | LastSlot
1524 | LastTargetslot
1525 | LastUseitem
1526 | LastUseslot
1527 )
1528}
1529
1530fn short_script_name(full_name: &str) -> Option<String> {
1533 full_name
1534 .trim_start_matches('[')
1535 .trim_end_matches(']')
1536 .split_once(',')
1537 .map(|(_, n)| n.to_string())
1538}
1539
1540fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1545 if corruptors.is_empty() {
1546 return "calls a delay or subroutine that may supersede it".to_string();
1547 }
1548
1549 const MAX: usize = 3;
1550 let shown: Vec<String> = corruptors
1551 .iter()
1552 .take(MAX)
1553 .map(|(name, line)| {
1554 if *line > 0 {
1555 format!("`{}` at line {}", name, line)
1556 } else {
1557 format!("`{}`", name)
1558 }
1559 })
1560 .collect();
1561
1562 let suffix = if corruptors.len() > MAX {
1563 format!(" (and {} more)", corruptors.len() - MAX)
1564 } else {
1565 String::new()
1566 };
1567
1568 let joined = match shown.len() {
1569 1 => shown[0].clone(),
1570 2 => format!("{} and {}", shown[0], shown[1]),
1571 _ => {
1572 let head = shown[..shown.len() - 1].join(", ");
1573 format!("{}, and {}", head, shown[shown.len() - 1])
1574 }
1575 };
1576
1577 format!("calls {}{} which may supersede it", joined, suffix)
1578}
1579
1580fn pointer_param_type(ptr: PointerType) -> &'static str {
1589 use PointerType::*;
1590 match ptr {
1591 LastUseitem | LastItem => "obj",
1592 LastCom => "component",
1593 _ => "int",
1594 }
1595}
1596
1597fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1599 if line_no == 0 {
1600 return None;
1601 }
1602 text.lines().nth(line_no - 1)
1603}
1604
1605fn rewrite_call_site_arg(
1614 line: &str,
1615 arrow: &str,
1616 callee_short: &str,
1617 ptr_cmd: &str,
1618) -> Option<String> {
1619 let needle = format!("{}{}", arrow, callee_short);
1622 let start = line.find(&needle)?;
1623 let after_name = start + needle.len();
1624 let tail = &line[after_name..];
1625
1626 let first_non_ws = tail.chars().next();
1628 if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1629 || tail.trim_start().is_empty()
1630 {
1631 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1632 out.push_str(&line[..after_name]);
1633 out.push('(');
1634 out.push_str(ptr_cmd);
1635 out.push(')');
1636 out.push_str(tail);
1637 return Some(out);
1638 }
1639
1640 if tail.trim_start().starts_with('(') {
1643 let open_rel = tail.find('(')?;
1644 let abs_open = after_name + open_rel;
1645 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1646 let abs_close = abs_open + close_rel;
1647
1648 let inside = line[abs_open + 1..abs_close].trim();
1650 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1651 out.push_str(&line[..abs_close]);
1652 if inside.is_empty() {
1653 out.push_str(ptr_cmd);
1654 } else {
1655 out.push_str(", ");
1656 out.push_str(ptr_cmd);
1657 }
1658 out.push_str(&line[abs_close..]);
1659 return Some(out);
1660 }
1661
1662 None
1663}
1664
1665fn rewrite_header_add_param(
1671 line: &str,
1672 callee_short: &str,
1673 param_type: &str,
1674 param_name: &str,
1675) -> Option<String> {
1676 let needle = format!(",{}]", callee_short);
1679 let subject_end = line.find(&needle)?;
1680 let after_bracket = subject_end + needle.len();
1681
1682 let remainder = &line[after_bracket..];
1683 let added = format!("{} {}", param_type, param_name);
1684
1685 if !remainder.trim_start().starts_with('(') {
1687 let mut out = String::with_capacity(line.len() + added.len() + 2);
1688 out.push_str(&line[..after_bracket]);
1689 out.push('(');
1690 out.push_str(&added);
1691 out.push(')');
1692 out.push_str(remainder);
1693 return Some(out);
1694 }
1695
1696 let open_rel = remainder.find('(')?;
1698 let abs_open = after_bracket + open_rel;
1699 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1700 let abs_close = abs_open + close_rel;
1701 let inside = line[abs_open + 1..abs_close].trim();
1702
1703 let mut out = String::with_capacity(line.len() + added.len() + 2);
1704 out.push_str(&line[..abs_close]);
1705 if inside.is_empty() {
1706 out.push_str(&added);
1707 } else {
1708 out.push_str(", ");
1709 out.push_str(&added);
1710 }
1711 out.push_str(&line[abs_close..]);
1712 Some(out)
1713}
1714
1715fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1719 let prefix = format!("[{},{}]", trigger, name);
1720 let prefix_with_params = format!("[{},{}](", trigger, name);
1721 for (i, line) in src.lines().enumerate() {
1722 let trimmed = line.trim_start();
1723 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1724 return Some(i + 1);
1725 }
1726 }
1727 None
1728}
1729
1730fn find_matching_close_paren(s: &str) -> Option<usize> {
1734 let bytes = s.as_bytes();
1735 if bytes.first().copied() != Some(b'(') {
1736 return None;
1737 }
1738 let mut depth = 0i32;
1739 for (i, &b) in bytes.iter().enumerate() {
1740 match b {
1741 b'(' => depth += 1,
1742 b')' => {
1743 depth -= 1;
1744 if depth == 0 {
1745 return Some(i);
1746 }
1747 }
1748 _ => {}
1749 }
1750 }
1751 None
1752}
1753
1754fn is_secondary_var_operand(operand: &Operand) -> bool {
1760 match operand {
1761 Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1762 _ => false,
1763 }
1764}
1765
1766fn resolve_target_node(
1772 mut target_idx: usize,
1773 instructions: &[Instruction],
1774 instr_to_node: &HashMap<usize, usize>,
1775) -> Option<usize> {
1776 while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1777 target_idx += 1;
1778 }
1779 instr_to_node.get(&target_idx).copied()
1780}
1781
1782fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1783 nodes[from].next.retain(|&n| n != to);
1784 nodes[to].previous.retain(|&n| n != from);
1785}
1786
1787fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1790 for i in (0..=instr_idx).rev() {
1791 if instructions[i].opcode == Opcode::LineNumber
1792 && let Operand::Int(line) = instructions[i].operand
1793 {
1794 return line as usize;
1795 }
1796 }
1797 0
1798}
1799
1800#[cfg(test)]
1801mod tests {
1802 use super::*;
1803 use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1804 use crate::symbol::SymbolRegistry;
1805
1806 fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1808 let mut reg = SymbolRegistry::new();
1809 for &(name, opcode) in commands {
1810 reg.register_command(name.to_string(), opcode, vec![], vec![]);
1811 }
1812 reg
1813 }
1814
1815 fn make_script(
1817 name: &str,
1818 trigger: &str,
1819 id: i32,
1820 instructions: Vec<Instruction>,
1821 ) -> CompiledScript {
1822 let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1823 script.trigger = trigger.to_string();
1824 script.source_path = "test.rs2".to_string();
1825 script.instructions = instructions;
1826 script
1827 }
1828
1829 fn cmd(opcode: i32) -> Instruction {
1831 Instruction::new(Opcode::Command, Operand::Int(opcode))
1832 }
1833
1834 fn line(n: i32) -> Instruction {
1835 Instruction::new(Opcode::LineNumber, Operand::Int(n))
1836 }
1837
1838 fn push_int(v: i32) -> Instruction {
1839 Instruction::push_int(v)
1840 }
1841
1842 fn branch_eq(target: usize) -> Instruction {
1843 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1844 }
1845
1846 fn branch(target: usize) -> Instruction {
1847 Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1848 }
1849
1850 fn ret() -> Instruction {
1851 Instruction::simple(Opcode::Return)
1852 }
1853
1854 fn gosub(script_id: i32) -> Instruction {
1855 Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1856 }
1857
1858 #[test]
1865 fn conditional_setter_with_arg_push() {
1866 let p_finduid_op = 4267;
1869 let p_stopaction_op = 4268;
1870
1871 let registry = registry_with_commands(&[
1872 ("p_finduid", p_finduid_op),
1873 ("p_stopaction", p_stopaction_op),
1874 ]);
1875
1876 let instructions = vec![
1877 line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
1887
1888 let script = make_script("test", "ai_timer", 0, instructions);
1892 let scripts = vec![script];
1893
1894 let mut checker = PointerChecker::new(&scripts, ®istry);
1895 let diags = checker.run();
1896
1897 assert_eq!(
1901 diags.warning_count(),
1902 0,
1903 "conditional setter should provide p_active_player on true branch, got {} warnings",
1904 diags.warning_count()
1905 );
1906 }
1907
1908 #[test]
1917 fn gosub_requires_then_corrupts_same_pointer() {
1918 let p_delay_op = 5001;
1919 let npc_delay_op = 5002;
1920
1921 let registry =
1922 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
1923
1924 let proc_script = make_script(
1927 "tackle_success",
1928 "proc",
1929 100,
1930 vec![
1931 line(1),
1932 push_int(0),
1933 cmd(p_delay_op), line(2),
1935 push_int(0),
1936 cmd(npc_delay_op), ret(),
1938 ],
1939 );
1940
1941 let label_script = make_script(
1944 "do_tackle",
1945 "label",
1946 200,
1947 vec![
1948 line(10),
1949 gosub(100), ret(),
1951 ],
1952 );
1953
1954 let scripts = vec![proc_script, label_script];
1955 let mut checker = PointerChecker::new(&scripts, ®istry);
1956 let diags = checker.run();
1957
1958 assert_eq!(
1964 diags.warning_count(),
1965 0,
1966 "gosub that requires-then-corrupts p_active_player should not \
1967 be flagged (engine-tracked pointer), got {} warnings",
1968 diags.warning_count()
1969 );
1970 }
1971
1972 #[test]
1978 fn corruption_before_requirement_is_caught() {
1979 let npc_delay_op = 5002;
1980 let p_delay_op = 5001;
1981
1982 let registry =
1983 registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
1984
1985 let script = make_script(
1988 "bad_order",
1989 "label",
1990 0,
1991 vec![
1992 line(1),
1993 push_int(0),
1994 cmd(npc_delay_op), line(2),
1996 push_int(0),
1997 cmd(p_delay_op), ret(),
1999 ],
2000 );
2001
2002 let scripts = vec![script];
2003 let mut checker = PointerChecker::new(&scripts, ®istry);
2004 let diags = checker.run();
2005
2006 assert!(
2007 diags.warning_count() > 0,
2008 "corruption before requirement should be caught as a warning"
2009 );
2010 }
2011
2012 #[test]
2017 fn uninitialized_pointer_caught() {
2018 let p_delay_op = 5001;
2019
2020 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2021
2022 let script = make_script(
2024 "bad_access",
2025 "ai_timer",
2026 0,
2027 vec![
2028 line(1),
2029 push_int(0),
2030 cmd(p_delay_op), ret(),
2032 ],
2033 );
2034
2035 let scripts = vec![script];
2036 let mut checker = PointerChecker::new(&scripts, ®istry);
2037 let diags = checker.run();
2038
2039 assert!(
2040 diags.warning_count() > 0,
2041 "uninitialized pointer access should be caught"
2042 );
2043 }
2044
2045 #[test]
2055 fn branch_target_on_line_number_still_connects() {
2056 let p_delay_op = 5001;
2057 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2058
2059 let script = make_script(
2075 "target_on_line_number",
2076 "ai_timer",
2077 0,
2078 vec![
2079 line(1),
2080 push_int(1),
2081 push_int(1),
2082 branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
2084 line(2),
2085 push_int(0),
2086 cmd(p_delay_op),
2087 ret(),
2088 ],
2089 );
2090
2091 let scripts = vec![script];
2092 let mut checker = PointerChecker::new(&scripts, ®istry);
2093 let diags = checker.run();
2094
2095 assert!(
2096 diags.warning_count() > 0,
2097 "jump target on LineNumber must still flag uninitialized pointer \
2098 access (got {} warnings)",
2099 diags.warning_count()
2100 );
2101 }
2102
2103 #[test]
2113 fn secondary_requires_and_corrupts_warns_for_static_pointer() {
2114 let last_useitem_op = 4270;
2117 let p_delay_op = 5001;
2118 let registry =
2119 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2120
2121 let callee = make_script(
2123 "consume_useitem",
2124 "label",
2125 100,
2126 vec![
2127 line(1),
2128 cmd(last_useitem_op), line(2),
2130 push_int(0),
2131 cmd(p_delay_op), ret(),
2133 ],
2134 );
2135
2136 let caller = make_script(
2143 "use_on_loc",
2144 "oplocu",
2145 200,
2146 vec![
2147 line(10),
2148 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2149 ],
2150 );
2151
2152 let scripts = vec![callee, caller];
2153 let mut checker = PointerChecker::new(&scripts, ®istry);
2154 let diags = checker.run();
2155
2156 let last_useitem_warnings = diags
2157 .diagnostics()
2158 .iter()
2159 .filter(|d| d.severity == Severity::Warning)
2160 .filter(|d| d.message.contains("last_useitem"))
2161 .count();
2162 assert!(
2163 last_useitem_warnings > 0,
2164 "static-only pointer (last_useitem) should trigger the \
2165 require+corrupt warning at the jump site; got diags: {:?}",
2166 diags
2167 .diagnostics()
2168 .iter()
2169 .map(|d| &d.message)
2170 .collect::<Vec<_>>()
2171 );
2172
2173 assert_eq!(
2174 diags.error_count(),
2175 0,
2176 "pointer-check diagnostics must never raise error severity; got {} errors",
2177 diags.error_count()
2178 );
2179 }
2180
2181 #[test]
2190 fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
2191 let p_delay_op = 5001;
2192 let npc_delay_op = 5002;
2193 let registry =
2194 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2195
2196 let callee = make_script(
2197 "consume_protected",
2198 "proc",
2199 100,
2200 vec![
2201 line(1),
2202 push_int(0),
2203 cmd(p_delay_op), line(2),
2205 push_int(0),
2206 cmd(npc_delay_op), ret(),
2208 ],
2209 );
2210
2211 let caller = make_script(
2213 "do_opnpc",
2214 "opnpc1",
2215 200,
2216 vec![
2217 line(10),
2218 Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2219 ret(),
2220 ],
2221 );
2222
2223 let scripts = vec![callee, caller];
2224 let mut checker = PointerChecker::new(&scripts, ®istry);
2225 let diags = checker.run();
2226
2227 let p_active_player_warnings = diags
2228 .diagnostics()
2229 .iter()
2230 .filter(|d| d.severity == Severity::Warning)
2231 .filter(|d| d.message.contains("p_active_player"))
2232 .count();
2233 assert_eq!(
2234 p_active_player_warnings, 0,
2235 "engine-tracked pointer (p_active_player) must not trigger the \
2236 require+corrupt warning; got {} such warnings",
2237 p_active_player_warnings
2238 );
2239 }
2240
2241 #[test]
2254 fn secondary_varn_requires_active_npc2_not_primary() {
2255 let secondary_varn = Instruction::new(
2260 Opcode::PushVarn,
2261 Operand::Int(1 << 16), );
2263
2264 let proc_script = make_script(
2266 "reads_secondary_varn",
2267 "proc",
2268 100,
2269 vec![
2270 line(1),
2271 secondary_varn,
2272 Instruction::simple(Opcode::PopIntDiscard),
2273 ret(),
2274 ],
2275 );
2276
2277 let caller = make_script(
2284 "gosub_into_proc",
2285 "opplayer1",
2286 200,
2287 vec![line(10), gosub(100), ret()],
2288 );
2289
2290 let scripts = vec![proc_script, caller];
2291 let registry = registry_with_commands(&[]);
2292 let mut checker = PointerChecker::new(&scripts, ®istry);
2293 let diags = checker.run();
2294
2295 let active_npc_primary_warnings = diags
2301 .diagnostics()
2302 .iter()
2303 .filter(|d| d.severity == Severity::Warning)
2304 .filter(|d| d.message.contains("pointer active_npc."))
2305 .count();
2306 assert_eq!(
2307 active_npc_primary_warnings,
2308 0,
2309 "secondary .%var read must not flag primary active_npc at the \
2310 caller; got diags: {:?}",
2311 diags
2312 .diagnostics()
2313 .iter()
2314 .filter(|d| d.severity == Severity::Warning)
2315 .map(|d| &d.message)
2316 .collect::<Vec<_>>()
2317 );
2318
2319 let active_npc2_warnings = diags
2323 .diagnostics()
2324 .iter()
2325 .filter(|d| d.severity == Severity::Warning)
2326 .filter(|d| d.message.contains("pointer .active_npc."))
2327 .count();
2328 assert!(
2329 active_npc2_warnings > 0,
2330 "secondary .%var should route the requirement to active_npc2; \
2331 got no such warning"
2332 );
2333 }
2334
2335 #[test]
2340 fn rewrite_call_site_no_args() {
2341 let got = rewrite_call_site_arg(
2342 "[opnpcu,wantcat1] @civilian_give_runes;",
2343 "@",
2344 "civilian_give_runes",
2345 "last_useitem",
2346 )
2347 .unwrap();
2348 assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2349 }
2350
2351 #[test]
2352 fn rewrite_call_site_with_args() {
2353 let got = rewrite_call_site_arg(
2354 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2355 "@",
2356 "amulet_of_glory_interface",
2357 "last_item",
2358 )
2359 .unwrap();
2360 assert_eq!(
2361 got,
2362 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2363 );
2364 }
2365
2366 #[test]
2367 fn rewrite_call_site_gosub_no_args() {
2368 let got =
2369 rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2370 assert_eq!(got, " ~some_proc(last_useitem);");
2371 }
2372
2373 #[test]
2374 fn rewrite_call_site_empty_arg_list() {
2375 let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2376 assert_eq!(got, "@foo(last_useitem);");
2377 }
2378
2379 #[test]
2380 fn rewrite_header_no_params() {
2381 let got = rewrite_header_add_param(
2382 "[label,civilian_give_runes]",
2383 "civilian_give_runes",
2384 "obj",
2385 "$last_useitem",
2386 )
2387 .unwrap();
2388 assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2389 }
2390
2391 #[test]
2392 fn rewrite_header_with_existing_params() {
2393 let got = rewrite_header_add_param(
2394 "[label,amulet_of_glory_interface](string $message)",
2395 "amulet_of_glory_interface",
2396 "obj",
2397 "$last_item",
2398 )
2399 .unwrap();
2400 assert_eq!(
2401 got,
2402 "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2403 );
2404 }
2405
2406 #[test]
2407 fn rewrite_header_proc_with_return_type() {
2408 let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2411 assert_eq!(got, "[proc,foo](obj $x)(int)");
2412 }
2413
2414 #[test]
2415 fn find_header_line_matches_trigger_and_name() {
2416 let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2417 assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2418 assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2419 assert_eq!(find_header_line(src, "label", "missing"), None);
2420 }
2421
2422 #[test]
2423 fn format_corruptors_shapes() {
2424 assert_eq!(
2425 format_corruptors(&[]),
2426 "calls a delay or subroutine that may supersede it"
2427 );
2428 assert_eq!(
2429 format_corruptors(&[("p_delay".to_string(), 21)]),
2430 "calls `p_delay` at line 21 which may supersede it"
2431 );
2432 assert_eq!(
2433 format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2434 "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2435 );
2436 assert_eq!(
2437 format_corruptors(&[
2438 ("p_delay".to_string(), 21),
2439 ("~chatnpc".to_string(), 11),
2440 ("~objbox".to_string(), 14),
2441 ]),
2442 "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2443 );
2444 assert_eq!(
2446 format_corruptors(&[
2447 ("p_delay".to_string(), 1),
2448 ("~a".to_string(), 2),
2449 ("~b".to_string(), 3),
2450 ("~c".to_string(), 4),
2451 ("~d".to_string(), 5),
2452 ]),
2453 "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2454 );
2455 assert_eq!(
2457 format_corruptors(&[("p_delay".to_string(), 0)]),
2458 "calls `p_delay` which may supersede it"
2459 );
2460 }
2461
2462 #[test]
2463 fn find_matching_close_paren_nested() {
2464 assert_eq!(find_matching_close_paren("()"), Some(1));
2465 assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2466 assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2467 assert_eq!(find_matching_close_paren("("), None);
2468 assert_eq!(find_matching_close_paren("abc"), None);
2469 }
2470
2471 #[test]
2476 fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2477 use std::collections::HashMap;
2478 use std::sync::Arc;
2479
2480 let last_useitem_op = 4270;
2481 let p_delay_op = 5001;
2482 let registry =
2483 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2484
2485 let mut callee = make_script(
2487 "consume_useitem",
2488 "label",
2489 100,
2490 vec![
2491 line(2), cmd(last_useitem_op),
2493 line(3),
2494 push_int(0),
2495 cmd(p_delay_op),
2496 ret(),
2497 ],
2498 );
2499 callee.source_path = "/virt/consume.rs2".to_string();
2500
2501 let mut caller = make_script(
2503 "use_on_loc",
2504 "oplocu",
2505 200,
2506 vec![
2507 line(1),
2508 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2509 ],
2510 );
2511 caller.source_path = "/virt/caller.rs2".to_string();
2512
2513 let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2516 source_cache.insert(
2517 "/virt/caller.rs2".to_string(),
2518 Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2519 );
2520 source_cache.insert(
2521 "/virt/consume.rs2".to_string(),
2522 Arc::new(
2523 "[label,consume_useitem]\n\
2524 last_useitem;\n\
2525 p_delay(0);\n"
2526 .to_string(),
2527 ),
2528 );
2529
2530 let scripts = vec![callee, caller];
2531 let mut checker = PointerChecker::new(&scripts, ®istry);
2532 checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
2533 let diags = checker.run();
2534
2535 let warning = diags
2538 .diagnostics()
2539 .iter()
2540 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2541 .expect("expected a stale-last_useitem warning");
2542
2543 assert_eq!(
2544 warning.help.len(),
2545 1,
2546 "warning should have exactly one Help block, got {}",
2547 warning.help.len()
2548 );
2549 let help = &warning.help[0];
2550 assert!(
2551 help.message.contains("consume_useitem"),
2552 "help message should name the callee, got: {}",
2553 help.message
2554 );
2555 assert!(
2556 help.message.contains("last_useitem"),
2557 "help message should name the pointer, got: {}",
2558 help.message
2559 );
2560
2561 assert_eq!(
2563 help.suggestions.len(),
2564 2,
2565 "help should include both call-site and header suggestions, \
2566 got {}: {:?}",
2567 help.suggestions.len(),
2568 help.suggestions
2569 .iter()
2570 .map(|s| &s.label)
2571 .collect::<Vec<_>>()
2572 );
2573
2574 let caller_sug = help
2576 .suggestions
2577 .iter()
2578 .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2579 .expect("expected a call-site suggestion on the caller file");
2580 assert!(
2581 caller_sug
2582 .replacement
2583 .contains("@consume_useitem(last_useitem)"),
2584 "call-site replacement must pass last_useitem as an arg, got: {}",
2585 caller_sug.replacement
2586 );
2587
2588 let header_sug = help
2590 .suggestions
2591 .iter()
2592 .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2593 .expect("expected a header suggestion on the callee file");
2594 assert!(
2595 header_sug.replacement.contains("(obj $last_useitem)"),
2596 "header replacement must add `obj $last_useitem` param, got: {}",
2597 header_sug.replacement
2598 );
2599
2600 assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2601 }
2602
2603 #[test]
2607 fn secondary_warning_falls_back_to_prose_help_without_source() {
2608 let last_useitem_op = 4270;
2609 let p_delay_op = 5001;
2610 let registry =
2611 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2612
2613 let callee = make_script(
2614 "consume_useitem",
2615 "label",
2616 100,
2617 vec![
2618 line(1),
2619 cmd(last_useitem_op),
2620 line(2),
2621 push_int(0),
2622 cmd(p_delay_op),
2623 ret(),
2624 ],
2625 );
2626 let caller = make_script(
2627 "use_on_loc",
2628 "oplocu",
2629 200,
2630 vec![
2631 line(1),
2632 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2633 ],
2634 );
2635
2636 let scripts = vec![callee, caller];
2637 let mut checker = PointerChecker::new(&scripts, ®istry);
2638 let diags = checker.run();
2640
2641 let warning = diags
2642 .diagnostics()
2643 .iter()
2644 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2645 .expect("warning still fires without source cache");
2646
2647 assert_eq!(warning.help.len(), 1);
2648 let help = &warning.help[0];
2649 assert_eq!(
2650 help.suggestions.len(),
2651 0,
2652 "prose-only help should have no concrete suggestions"
2653 );
2654 assert_eq!(help.applicability, Applicability::Unspecified);
2655 }
2656}