1use std::collections::{HashMap, HashSet, VecDeque};
2use std::path::PathBuf;
3
4use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
5use crate::clientscript;
6use crate::diagnostic_messages as msg;
7use crate::diagnostics::{
8 Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
9};
10use crate::pointer::{PointerHolder, PointerSet, PointerType, command_pointers, trigger_pointers};
11use crate::symbol::{SymbolKind, SymbolRegistry};
12
13#[cfg(feature = "memprof")]
20static CFG_TRACE: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
21
22#[cfg(feature = "memprof")]
23fn cfg_trace_push(source_path: &str) {
24 if std::env::var_os("RUNEC_TRACE_CFG").is_some() {
25 CFG_TRACE.lock().unwrap().push(source_path.to_string());
26 }
27}
28
29#[cfg(feature = "memprof")]
32pub(crate) fn cfg_trace_report() {
33 use tracing::info;
34 let trace = CFG_TRACE.lock().unwrap();
35 if trace.is_empty() {
36 return;
37 }
38 let distinct: HashSet<&str> = trace.iter().map(|s| s.as_str()).collect();
39 let nfiles = distinct.len().max(1);
40 info!(
41 "[trace] build_cfg calls: {}, distinct files: {}",
42 trace.len(),
43 nfiles
44 );
45 for &cap in &[16usize, 64, 256, 1024, nfiles] {
46 let mut lru: Vec<&str> = Vec::with_capacity(cap + 1);
47 let mut misses = 0usize;
48 for f in trace.iter() {
49 let f = f.as_str();
50 if let Some(pos) = lru.iter().position(|x| *x == f) {
51 lru.remove(pos);
52 } else {
53 misses += 1;
54 }
55 lru.insert(0, f);
56 if lru.len() > cap {
57 lru.pop();
58 }
59 }
60 info!(
61 "[trace] LRU cap {:>5}: {:>7} re-parses ({:.2}x of {} files)",
62 cap,
63 misses,
64 misses as f64 / nfiles as f64,
65 nfiles
66 );
67 }
68}
69
70pub(crate) enum ScriptRef<'a> {
79 Borrowed(&'a CompiledScript),
80 Owned(std::rc::Rc<CompiledScript>),
81}
82
83impl std::ops::Deref for ScriptRef<'_> {
84 type Target = CompiledScript;
85 fn deref(&self) -> &CompiledScript {
86 match self {
87 ScriptRef::Borrowed(s) => s,
88 ScriptRef::Owned(rc) => rc,
89 }
90 }
91}
92
93pub(crate) enum ScriptSource<'a> {
99 Resident(&'a [CompiledScript]),
100 Recompile {
101 len: usize,
102 get: std::cell::RefCell<Box<dyn FnMut(usize) -> std::rc::Rc<CompiledScript> + 'a>>,
103 },
104}
105
106impl<'a> ScriptSource<'a> {
107 fn len(&self) -> usize {
108 match self {
109 ScriptSource::Resident(s) => s.len(),
110 ScriptSource::Recompile { len, .. } => *len,
111 }
112 }
113
114 fn get(&self, idx: usize) -> ScriptRef<'a> {
118 match self {
119 ScriptSource::Resident(s) => ScriptRef::Borrowed(&(*s)[idx]),
120 ScriptSource::Recompile { get, .. } => ScriptRef::Owned((get.borrow_mut())(idx)),
121 }
122 }
123}
124
125#[derive(Debug)]
130struct CfgNode {
131 instruction_index: Option<usize>,
134 pointer_set: PointerSet,
136 next: Vec<usize>,
138 previous: Vec<usize>,
140}
141
142impl CfgNode {
143 fn new(instruction_index: Option<usize>) -> Self {
144 CfgNode {
145 instruction_index,
146 pointer_set: PointerSet::new(),
147 next: Vec::new(),
148 previous: Vec::new(),
149 }
150 }
151
152 fn pointer_node(pointer_set: PointerSet) -> Self {
153 CfgNode {
154 instruction_index: None,
155 pointer_set,
156 next: Vec::new(),
157 previous: Vec::new(),
158 }
159 }
160}
161
162struct ScriptAnalysis {
167 nodes: Vec<CfgNode>,
168 required: Vec<Vec<usize>>,
170 set_list: Vec<Vec<usize>>,
172 corrupted_list: Vec<Vec<usize>>,
174 returns: Vec<usize>,
176}
177
178impl ScriptAnalysis {
179 fn new() -> Self {
180 let n = PointerType::COUNT;
181 ScriptAnalysis {
182 nodes: Vec::new(),
183 required: vec![Vec::new(); n],
184 set_list: vec![Vec::new(); n],
185 corrupted_list: vec![Vec::new(); n],
186 returns: Vec::new(),
187 }
188 }
189}
190
191pub(crate) struct SharedMaps {
200 client: bool,
201 cmd_pointers: HashMap<String, PointerHolder>,
202 opcode_to_name: HashMap<i32, String>,
204 script_id_to_index: HashMap<i32, usize>,
206 script_name_to_index: HashMap<String, usize>,
210 overlay_interfaces: HashSet<String>,
213}
214
215pub struct PointerChecker<'a> {
216 scripts: ScriptSource<'a>,
217 #[allow(dead_code)]
218 registry: &'a SymbolRegistry,
219 shared: std::sync::Arc<SharedMaps>,
221 source_cache: Option<crate::SourceProvider<'a>>,
226 script_analyses: HashMap<String, ScriptAnalysis>,
228 script_pointers: HashMap<String, PointerHolder>,
229 pending_analyses: HashSet<String>,
230 pending_scripts: HashSet<String>,
231}
232
233impl SharedMaps {
234 fn build<'b>(
238 idents: impl Iterator<Item = (i32, &'b str)>,
239 registry: &SymbolRegistry,
240 client: bool,
241 ) -> Self {
242 let mut opcode_to_name = HashMap::new();
244 for (name, sym) in ®istry.commands {
245 if let SymbolKind::Command { opcode, .. } = &sym.kind {
246 opcode_to_name.insert(*opcode, name.to_lowercase());
247 }
248 }
249
250 let mut script_id_to_index = HashMap::new();
254 let mut script_name_to_index = HashMap::new();
255 for (i, (id, name)) in idents.enumerate() {
256 script_id_to_index.insert(id, i);
257 script_name_to_index.entry(name.to_string()).or_insert(i);
258 }
259
260 let mut overlay_interfaces = HashSet::new();
264 for (name, entry) in ®istry.entity_ids {
265 if let Some(e) = entry.primary
266 && e.const_type == crate::types::Type::OverlayInterface
267 {
268 overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
269 }
270 }
271
272 SharedMaps {
273 client,
274 cmd_pointers: registry.profile.as_ref().map_or_else(
275 || {
276 if client {
277 clientscript::command_pointers(registry)
278 } else {
279 command_pointers()
280 }
281 },
282 |profile| profile.command_pointers.clone(),
283 ),
284 opcode_to_name,
285 script_id_to_index,
286 script_name_to_index,
287 overlay_interfaces,
288 }
289 }
290}
291
292impl<'a> PointerChecker<'a> {
293 pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
294 let shared = std::sync::Arc::new(SharedMaps::build(
295 scripts.iter().map(|s| (s.id, s.name.as_str())),
296 registry,
297 false,
298 ));
299 Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
300 }
301
302 pub fn new_client(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
303 let shared = std::sync::Arc::new(SharedMaps::build(
304 scripts.iter().map(|s| (s.id, s.name.as_str())),
305 registry,
306 true,
307 ));
308 Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
309 }
310
311 pub(crate) fn build_shared(
315 scripts: &[CompiledScript],
316 registry: &SymbolRegistry,
317 ) -> std::sync::Arc<SharedMaps> {
318 std::sync::Arc::new(SharedMaps::build(
319 scripts.iter().map(|s| (s.id, s.name.as_str())),
320 registry,
321 false,
322 ))
323 }
324
325 pub(crate) fn build_shared_idents(
328 idents: &[(i32, String)],
329 registry: &SymbolRegistry,
330 ) -> std::sync::Arc<SharedMaps> {
331 std::sync::Arc::new(SharedMaps::build(
332 idents.iter().map(|(id, name)| (*id, name.as_str())),
333 registry,
334 false,
335 ))
336 }
337
338 pub(crate) fn with_shared(
341 scripts: ScriptSource<'a>,
342 registry: &'a SymbolRegistry,
343 shared: std::sync::Arc<SharedMaps>,
344 ) -> Self {
345 PointerChecker {
346 scripts,
347 registry,
348 shared,
349 source_cache: None,
350 script_analyses: HashMap::new(),
351 script_pointers: HashMap::new(),
352 pending_analyses: HashSet::new(),
353 pending_scripts: HashSet::new(),
354 }
355 }
356
357 pub fn set_source_cache(&mut self, provider: crate::SourceProvider<'a>) {
361 self.source_cache = Some(provider);
362 }
363
364 fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
367 if !self
368 .registry
369 .trigger(trigger)
370 .is_some_and(|trigger| trigger.is_button)
371 {
372 return false;
373 }
374 let subject = script_name
376 .trim_start_matches('[')
377 .trim_end_matches(']')
378 .split_once(',')
379 .map(|(_, rest)| rest)
380 .unwrap_or("");
381 let iface_name = subject
382 .split(':')
383 .next()
384 .unwrap_or("")
385 .to_lowercase()
386 .replace(' ', "_");
387 if iface_name.is_empty() {
388 return false;
389 }
390 !self.shared.overlay_interfaces.contains(&iface_name)
392 }
393
394 pub fn run(&mut self) -> DiagnosticsCollector {
396 let names = self.script_names();
397 self.validate_names(&names)
398 }
399
400 pub fn script_names(&self) -> Vec<String> {
402 (0..self.scripts.len())
403 .map(|i| self.scripts.get(i).name.clone())
404 .collect()
405 }
406
407 pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
415 let mut diagnostics = DiagnosticsCollector::new();
416 for script_name in names {
417 self.validate_script(script_name, &mut diagnostics);
418 self.script_analyses.clear();
426 }
427 diagnostics
428 }
429
430 fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
431 let script_idx = match self.shared.script_name_to_index.get(script_name) {
433 Some(&i) => i,
434 None => return,
435 };
436 let trigger = self.scripts.get(script_idx).trigger.clone();
437 let source_path = self.scripts.get(script_idx).source_path.clone();
438 let trigger_set = if let Some(profile) = &self.registry.profile {
439 profile
440 .trigger_pointers
441 .get(&trigger)
442 .copied()
443 .unwrap_or_default()
444 } else if self.shared.client {
445 match trigger.as_str() {
446 "proc" => [PointerType::ActiveComponent, PointerType::ActiveComponent2]
447 .into_iter()
448 .collect(),
449 _ => PointerSet::new(),
450 }
451 } else {
452 trigger_pointers(&trigger)
453 };
454
455 self.ensure_analysis(script_name);
457
458 for &ptr in &PointerType::ALL {
459 let ptr_idx = ptr.index();
460
461 let analysis = match self.script_analyses.get(script_name) {
463 Some(a) => a,
464 None => continue,
465 };
466
467 let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
468 if required_nodes.is_empty() {
469 continue;
470 }
471
472 let mut corrupted: HashSet<usize> =
477 analysis.corrupted_list[ptr_idx].iter().copied().collect();
478
479 let trigger_provides = if trigger_set.contains(ptr) {
483 true
484 } else if ptr == PointerType::PActivePlayer {
485 self.interface_trigger_grants_protected(&trigger, script_name)
486 } else {
487 false
488 };
489 if !trigger_provides {
490 corrupted.insert(0);
491 }
492
493 if corrupted.is_empty() {
494 continue;
495 }
496
497 let set_blocked: HashSet<usize> = analysis.set_list[ptr_idx].iter().copied().collect();
498
499 let path = self.find_edge_path(
501 script_name,
502 &required_nodes,
503 |node_idx| corrupted.contains(&node_idx),
504 &set_blocked,
505 );
506
507 let mut reported_via_main_bfs = false;
508 if let Some(path) = path {
509 if path.is_empty() {
510 continue;
511 }
512 reported_via_main_bfs = true;
513
514 let end_node_idx = path[path.len() - 1];
515 let start_node_idx = path[0];
516
517 let is_start_node = end_node_idx == 0;
518 let repr = ptr.representation();
519 let static_only = is_static_only_pointer(ptr);
520
521 let error_msg = if is_start_node {
527 if static_only {
528 msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
529 } else {
530 msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
531 }
532 } else if static_only {
533 msg::fmt(msg::POINTER_STALE, &[repr])
534 } else {
535 msg::fmt(msg::POINTER_CORRUPTED, &[repr])
536 };
537
538 let analysis = self.script_analyses.get(script_name).unwrap();
539 let script_ref = self.scripts.get(script_idx);
540 let instructions = &script_ref.instructions;
541 let req_line = analysis.nodes[start_node_idx]
542 .instruction_index
543 .map(|idx| resolve_line(instructions, idx))
544 .unwrap_or(0);
545
546 diagnostics.add(Diagnostic {
551 file: PathBuf::from(&source_path),
552 line: req_line,
553 column: 0,
554 message: error_msg,
555 severity: Severity::Warning,
556 phase: Phase::PointerCheck,
557 help: Vec::new(),
558 });
559
560 let read_hint = if static_only {
561 msg::fmt(msg::POINTER_READ_HERE, &[repr])
562 } else {
563 msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
564 };
565 diagnostics.add(Diagnostic {
566 file: PathBuf::from(&source_path),
567 line: req_line,
568 column: 0,
569 message: read_hint,
570 severity: Severity::Info,
571 phase: Phase::PointerCheck,
572 help: Vec::new(),
573 });
574
575 if !is_start_node {
576 let corrupt_line = analysis.nodes[end_node_idx]
577 .instruction_index
578 .map(|idx| resolve_line(instructions, idx))
579 .unwrap_or(0);
580
581 let cause_hint = if static_only {
582 msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
583 } else {
584 msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
585 };
586 diagnostics.add(Diagnostic {
587 file: PathBuf::from(&source_path),
588 line: corrupt_line,
589 column: 0,
590 message: cause_hint,
591 severity: Severity::Info,
592 phase: Phase::PointerCheck,
593 help: Vec::new(),
594 });
595 }
596 }
597
598 if !reported_via_main_bfs && is_static_only_pointer(ptr) {
611 let targets: Vec<(usize, usize)> = {
615 let analysis = self.script_analyses.get(script_name).unwrap();
616 let script_ref = self.scripts.get(script_idx);
617 let instructions = &script_ref.instructions;
618 let corrupted_nodes: HashSet<usize> =
619 analysis.corrupted_list[ptr_idx].iter().copied().collect();
620 required_nodes
621 .iter()
622 .filter(|&&node_idx| corrupted_nodes.contains(&node_idx))
623 .map(|&node_idx| {
624 let line = analysis.nodes[node_idx]
625 .instruction_index
626 .map(|idx| resolve_line(instructions, idx))
627 .unwrap_or(0);
628 (node_idx, line)
629 })
630 .collect()
631 };
632 let mut seen_lines: HashSet<usize> = HashSet::new();
633 let repr = ptr.representation();
634 for (node_idx, line) in targets {
635 if !seen_lines.insert(line) {
636 continue;
637 }
638
639 let help =
644 self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
645
646 let mut diag = Diagnostic {
654 file: PathBuf::from(&source_path),
655 line,
656 column: 0,
657 message: msg::fmt(msg::POINTER_STALE, &[repr]),
658 severity: Severity::Warning,
659 phase: Phase::PointerCheck,
660 help: Vec::new(),
661 };
662 if let Some(h) = help {
663 diag.help.push(h);
664 }
665 diagnostics.add(diag);
666 }
667 }
668 }
669 }
670
671 fn find_edge_path(
680 &self,
681 script_name: &str,
682 starts: &[usize],
683 end_pred: impl Fn(usize) -> bool,
684 blocked: &HashSet<usize>,
685 ) -> Option<Vec<usize>> {
686 let analysis = self.script_analyses.get(script_name)?;
687
688 let mut queue: VecDeque<usize> = VecDeque::new();
689 let mut visited: HashSet<usize> = HashSet::new();
690 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); for &start in starts {
698 for &prev in &analysis.nodes[start].previous {
699 if blocked.contains(&prev) || visited.contains(&prev) {
700 continue;
701 }
702 visited.insert(prev);
703 queue.push_back(prev);
704 sources.insert(prev, (start, start));
705 }
706 }
707
708 while let Some(current) = queue.pop_front() {
709 if end_pred(current) {
710 let mut path = vec![current];
712 let mut node = current;
713 while let Some(&(from, start)) = sources.get(&node) {
714 if from == start && starts.contains(&from) {
715 path.push(from);
716 break;
717 }
718 path.push(from);
719 node = from;
720 }
721 path.reverse();
722 return Some(path);
723 }
724
725 let (_, start_node) = sources[¤t];
726
727 for &prev in &analysis.nodes[current].previous {
728 if blocked.contains(&prev) || visited.contains(&prev) {
729 continue;
730 }
731 visited.insert(prev);
732 queue.push_back(prev);
733 sources.insert(prev, (current, start_node));
734 }
735 }
736
737 None
738 }
739
740 fn find_edge_path_static(
743 nodes: &[CfgNode],
744 starts: &[usize],
745 end_pred: impl Fn(usize) -> bool,
746 blocked: &HashSet<usize>,
747 ) -> Option<Vec<usize>> {
748 let mut queue: VecDeque<usize> = VecDeque::new();
749 let mut visited: HashSet<usize> = HashSet::new();
750 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
751
752 for &start in starts {
753 for &prev in &nodes[start].previous {
754 if blocked.contains(&prev) || visited.contains(&prev) {
755 continue;
756 }
757 visited.insert(prev);
758 queue.push_back(prev);
759 sources.insert(prev, (start, start));
760 }
761 }
762
763 while let Some(current) = queue.pop_front() {
764 if end_pred(current) {
765 let mut path = vec![current];
766 let mut node = current;
767 while let Some(&(from, start)) = sources.get(&node) {
768 if from == start && starts.contains(&from) {
769 path.push(from);
770 break;
771 }
772 path.push(from);
773 node = from;
774 }
775 path.reverse();
776 return Some(path);
777 }
778
779 for &prev in &nodes[current].previous {
780 if blocked.contains(&prev) || visited.contains(&prev) {
781 continue;
782 }
783 visited.insert(prev);
784 queue.push_back(prev);
785 sources.insert(prev, (current, sources[¤t].1));
786 }
787 }
788
789 None
790 }
791
792 fn ensure_analysis(&mut self, script_name: &str) {
797 if self.script_analyses.contains_key(script_name) {
798 return;
799 }
800 if self.pending_analyses.contains(script_name) {
801 return; }
803 self.pending_analyses.insert(script_name.to_string());
804
805 let script_idx = match self.shared.script_name_to_index.get(script_name) {
806 Some(&i) => i,
807 None => return,
808 };
809
810 let mut analysis = self.build_cfg(script_idx);
811 self.categorize_nodes(script_idx, &mut analysis);
812
813 self.script_analyses
814 .insert(script_name.to_string(), analysis);
815 self.pending_analyses.remove(script_name);
816 }
817
818 fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
823 let script = self.scripts.get(script_idx);
824 #[cfg(feature = "memprof")]
825 cfg_trace_push(&script.source_path);
826 let instructions = &script.instructions;
827 let mut analysis = ScriptAnalysis::new();
828
829 analysis.nodes.push(CfgNode::new(None));
831
832 let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
834 let mut node_order: Vec<usize> = Vec::new(); for (i, instr) in instructions.iter().enumerate() {
837 if instr.opcode == Opcode::LineNumber {
838 continue;
839 }
840 let node_idx = analysis.nodes.len();
841 instr_to_node.insert(i, node_idx);
842 node_order.push(i);
843 analysis.nodes.push(CfgNode::new(Some(i)));
844 }
845
846 if node_order.is_empty() {
847 return analysis;
848 }
849
850 let first_node = instr_to_node[&node_order[0]];
852 add_edge(&mut analysis.nodes, 0, first_node);
853
854 for (order_idx, &instr_idx) in node_order.iter().enumerate() {
856 let node_idx = instr_to_node[&instr_idx];
857 let instr = &instructions[instr_idx];
858
859 let is_terminal = matches!(
860 instr.opcode,
861 Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
862 );
863
864 match instr.opcode {
869 Opcode::Branch
870 | Opcode::BranchNot
871 | Opcode::BranchEquals
872 | Opcode::BranchLessThan
873 | Opcode::BranchGreaterThan
874 | Opcode::BranchLessThanOrEquals
875 | Opcode::BranchGreaterThanOrEquals
876 | Opcode::LongBranchNot
877 | Opcode::LongBranchEquals
878 | Opcode::LongBranchLessThan
879 | Opcode::LongBranchGreaterThan
880 | Opcode::LongBranchLessThanOrEquals
881 | Opcode::LongBranchGreaterThanOrEquals
882 | Opcode::ObjBranchEquals
883 | Opcode::ObjBranchNot
884 | Opcode::BranchIfTrue
885 | Opcode::BranchIfFalse => {
886 if let Operand::JumpTarget(target_instr_idx) = &instr.operand
887 && let Some(target_node) =
888 resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
889 {
890 add_edge(&mut analysis.nodes, node_idx, target_node);
891 }
892 }
893
894 Opcode::Switch => {
895 if let Operand::SwitchTable(tbl_idx) = &instr.operand {
896 let cases = &script.switch_tables[*tbl_idx as usize];
897 for &(_, target_instr_idx) in cases.iter() {
898 if let Some(target_node) =
899 resolve_target_node(target_instr_idx, instructions, &instr_to_node)
900 {
901 add_edge(&mut analysis.nodes, node_idx, target_node);
902 }
903 }
904 }
905 }
906
907 _ => {}
908 }
909
910 if !is_terminal
912 && let Some(next_order_idx) = order_idx.checked_add(1)
913 && next_order_idx < node_order.len()
914 {
915 let next_node = instr_to_node[&node_order[next_order_idx]];
916 add_edge(&mut analysis.nodes, node_idx, next_node);
917 }
918
919 if instr.opcode == Opcode::Return {
924 analysis.returns.push(node_idx);
925 }
926 }
927
928 self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
930
931 analysis
932 }
933
934 fn insert_pointer_nodes(
937 &self,
938 script_idx: usize,
939 analysis: &mut ScriptAnalysis,
940 instr_to_node: &HashMap<usize, usize>,
941 node_order: &[usize],
942 ) {
943 let script_ref = self.scripts.get(script_idx);
944 let instructions = &script_ref.instructions;
945
946 for window_end in 1..node_order.len() {
951 let branch_instr_idx = node_order[window_end];
952 let branch_instr = &instructions[branch_instr_idx];
953 let (push_value, scan_end) = match branch_instr.opcode {
954 Opcode::BranchIfTrue => (1, window_end),
955 Opcode::BranchIfFalse => (0, window_end),
956 Opcode::BranchEquals | Opcode::BranchNot => {
957 let push_instr = &instructions[node_order[window_end - 1]];
958 match (push_instr.opcode, &push_instr.operand) {
959 (Opcode::PushConstantInt, Operand::Int(value @ (0 | 1))) => (
960 if branch_instr.opcode == Opcode::BranchNot {
961 1 - value
962 } else {
963 *value
964 },
965 window_end - 1,
966 ),
967 _ => continue,
968 }
969 }
970 _ => continue,
971 };
972
973 let mut cmd_instr_idx = None;
975 for scan in (0..scan_end).rev() {
976 let idx = node_order[scan];
977 if instructions[idx].opcode == Opcode::Command {
978 cmd_instr_idx = Some(idx);
979 break;
980 }
981 if matches!(
983 instructions[idx].opcode,
984 Opcode::Branch
985 | Opcode::Return
986 | Opcode::Switch
987 | Opcode::BranchEquals
988 | Opcode::BranchNot
989 | Opcode::BranchLessThan
990 | Opcode::BranchGreaterThan
991 | Opcode::BranchLessThanOrEquals
992 | Opcode::BranchGreaterThanOrEquals
993 | Opcode::BranchIfTrue
994 | Opcode::BranchIfFalse
995 ) {
996 break;
997 }
998 }
999 let cmd_instr_idx = match cmd_instr_idx {
1000 Some(idx) => idx,
1001 None => continue,
1002 };
1003 if self.shared.client && (scan_end == 0 || node_order[scan_end - 1] != cmd_instr_idx) {
1004 continue;
1005 }
1006 let cmd_instr = &instructions[cmd_instr_idx];
1007
1008 let cmd_name = self.resolve_command_name(cmd_instr, &script_ref.strings);
1010 let cmd_name = match cmd_name {
1011 Some(n) => n,
1012 None => continue,
1013 };
1014
1015 let holder = match self.shared.cmd_pointers.get(&cmd_name) {
1016 Some(h) => h,
1017 None => continue,
1018 };
1019
1020 if !holder.conditional_set {
1021 continue;
1022 }
1023
1024 if holder.set.is_empty() {
1025 continue;
1026 }
1027
1028 let branch_node_idx = instr_to_node[&branch_instr_idx];
1029
1030 let ptr_node_idx = analysis.nodes.len();
1032 analysis.nodes.push(CfgNode::pointer_node(holder.set));
1033
1034 if push_value == 0 {
1035 let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
1043 .next
1044 .iter()
1045 .copied()
1046 .filter(|&n| {
1047 if let Operand::JumpTarget(target) = &branch_instr.operand
1049 && let Some(jump_node) =
1050 resolve_target_node(*target, instructions, instr_to_node)
1051 {
1052 return n != jump_node;
1053 }
1054 true
1055 })
1056 .collect();
1057
1058 for ft_target in fallthrough_targets {
1059 remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
1061 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1063 add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
1064 }
1065 } else {
1066 if let Operand::JumpTarget(target) = &branch_instr.operand
1070 && let Some(jump_target_node) =
1071 resolve_target_node(*target, instructions, instr_to_node)
1072 {
1073 remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
1075 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1077 add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
1078 }
1079 }
1080 }
1081 }
1082
1083 fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
1088 let script_ref = self.scripts.get(script_idx);
1089 let instructions = &script_ref.instructions;
1090
1091 for node_idx in 0..analysis.nodes.len() {
1092 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1093 Some(i) => i,
1094 None => {
1095 let ptr_set = analysis.nodes[node_idx].pointer_set;
1097 if !ptr_set.is_empty() {
1098 for ptr in ptr_set.iter() {
1099 let pi = ptr.index();
1100 analysis.set_list[pi].push(node_idx);
1101 }
1102 }
1103 continue;
1104 }
1105 };
1106
1107 let instr = &instructions[instr_idx];
1108
1109 match instr.opcode {
1110 Opcode::Command => {
1111 let cmd_name = self.resolve_command_name(instr, &script_ref.strings);
1112 if let Some(name) = cmd_name
1113 && let Some(holder) = self.shared.cmd_pointers.get(&name).cloned()
1114 {
1115 self.apply_holder(analysis, node_idx, &holder);
1116 }
1117 }
1118
1119 Opcode::Gosub | Opcode::GosubWithParams => {
1120 if let Operand::Int(script_id) = &instr.operand {
1121 let callee_holder = self.get_script_pointers(*script_id);
1122 self.apply_holder(analysis, node_idx, &callee_holder);
1123 }
1124 }
1125
1126 Opcode::Jump | Opcode::JumpWithParams => {
1127 if let Operand::Int(script_id) = &instr.operand {
1128 let callee_holder = self.get_script_pointers(*script_id);
1129 self.apply_holder(analysis, node_idx, &callee_holder);
1130 }
1131 }
1132
1133 Opcode::PushVarp
1140 | Opcode::PushVarbit
1141 | Opcode::PushVarcInt
1142 | Opcode::PushVarcString
1143 | Opcode::PushVarClan
1144 | Opcode::PushClanSettingInt
1145 | Opcode::PushClanSettingVarbit
1146 | Opcode::PushClanSettingLong
1147 | Opcode::PushClanSettingString
1148 if !self.shared.client =>
1149 {
1150 let pi = if is_secondary_var_operand(&instr.operand) {
1151 PointerType::ActivePlayer2.index()
1152 } else {
1153 PointerType::ActivePlayer.index()
1154 };
1155 analysis.required[pi].push(node_idx);
1156 }
1157
1158 Opcode::PopVarp
1159 | Opcode::PopVarbit
1160 | Opcode::PopVarcInt
1161 | Opcode::PopVarcString
1162 | Opcode::PopVarClan
1163 | Opcode::PopClanSettingInt
1164 | Opcode::PopClanSettingVarbit
1165 | Opcode::PopClanSettingLong
1166 | Opcode::PopClanSettingString
1167 if !self.shared.client =>
1168 {
1169 let pi = if is_secondary_var_operand(&instr.operand) {
1170 PointerType::ActivePlayer2.index()
1171 } else {
1172 PointerType::ActivePlayer.index()
1173 };
1174 analysis.required[pi].push(node_idx);
1175 }
1176
1177 Opcode::PushVarn | Opcode::PopVarn | Opcode::PushVarnBit | Opcode::PopVarnBit
1178 if !self.shared.client =>
1179 {
1180 let pi = if is_secondary_var_operand(&instr.operand) {
1181 PointerType::ActiveNpc2.index()
1182 } else {
1183 PointerType::ActiveNpc.index()
1184 };
1185 analysis.required[pi].push(node_idx);
1186 }
1187
1188 _ => {}
1190 }
1191 }
1192 }
1193
1194 fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
1195 for ptr in holder.required.iter() {
1196 let pi = ptr.index();
1197 analysis.required[pi].push(node_idx);
1198 }
1199 for ptr in holder.set.iter().filter(|_| !holder.conditional_set) {
1200 let pi = ptr.index();
1201 analysis.set_list[pi].push(node_idx);
1202 }
1203 for ptr in holder.corrupted.iter() {
1204 let pi = ptr.index();
1205 analysis.corrupted_list[pi].push(node_idx);
1206 }
1207 }
1208
1209 fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
1225 let script_idx = match self.shared.script_id_to_index.get(&script_id) {
1227 Some(&i) => i,
1228 None => {
1229 return PointerHolder::default();
1230 }
1231 };
1232 let script_name = self.scripts.get(script_idx).name.clone();
1233
1234 if let Some(holder) = self.script_pointers.get(&script_name) {
1236 return holder.clone();
1237 }
1238
1239 if self.pending_scripts.contains(&script_name) {
1241 return PointerHolder::default();
1242 }
1243 self.pending_scripts.insert(script_name.clone());
1244
1245 self.ensure_analysis(&script_name);
1247
1248 let mut holder = PointerHolder::default();
1249
1250 if let Some(analysis) = self.script_analyses.get(&script_name) {
1251 for &ptr in &PointerType::ALL {
1252 let pi = ptr.index();
1253
1254 let requires = !analysis.required[pi].is_empty();
1260 let has_returns = !analysis.returns.is_empty();
1261 if !requires && !has_returns {
1262 continue;
1263 }
1264 let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
1265
1266 if requires {
1268 let path = Self::find_edge_path_static(
1269 &analysis.nodes,
1270 &analysis.required[pi],
1271 |node_idx| node_idx == 0,
1272 &set_blocked,
1273 );
1274 if path.is_some() {
1275 holder.required.insert(ptr);
1276 }
1277 }
1278
1279 if has_returns {
1280 let corrupted_nodes: HashSet<usize> =
1281 analysis.corrupted_list[pi].iter().copied().collect();
1282
1283 let path = Self::find_edge_path_static(
1286 &analysis.nodes,
1287 &analysis.returns,
1288 |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1289 &set_blocked,
1290 );
1291 if path.is_none() {
1292 holder.set.insert(ptr);
1293 }
1294
1295 if !corrupted_nodes.is_empty() {
1297 let path = Self::find_edge_path_static(
1298 &analysis.nodes,
1299 &analysis.returns,
1300 |node_idx| corrupted_nodes.contains(&node_idx),
1301 &set_blocked,
1302 );
1303 if path.is_some() {
1304 holder.corrupted.insert(ptr);
1305 }
1306 }
1307 }
1308 }
1309 }
1310
1311 self.pending_scripts.remove(&script_name);
1312
1313 self.script_pointers
1314 .insert(script_name.clone(), holder.clone());
1315 holder
1316 }
1317
1318 fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1328 let callee = self.scripts.get(callee_idx);
1329 let analysis = match self.script_analyses.get(&callee.name) {
1330 Some(a) => a,
1331 None => return Vec::new(),
1332 };
1333 let ptr_idx = ptr.index();
1334 let mut seen: HashSet<(String, usize)> = HashSet::new();
1335 let mut result: Vec<(String, usize)> = Vec::new();
1336
1337 for &node_idx in &analysis.corrupted_list[ptr_idx] {
1338 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1339 Some(i) => i,
1340 None => continue,
1341 };
1342 let instr = &callee.instructions[instr_idx];
1343 let line = resolve_line(&callee.instructions, instr_idx);
1344
1345 let name = match instr.opcode {
1346 Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
1347 Some(n) => n,
1348 None => continue,
1349 },
1350 Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1351 Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
1352 Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
1353 .map(|s| format!("~{}", s))
1354 .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
1355 None => continue,
1356 },
1357 _ => continue,
1358 },
1359 _ => continue,
1363 };
1364
1365 let key = (name.clone(), line);
1366 if seen.insert(key) {
1367 result.push((name, line));
1368 }
1369 }
1370
1371 result
1372 }
1373
1374 fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
1375 match &instr.operand {
1376 Operand::Int(encoded) => {
1377 let opcode = encoded & 0xFFFF;
1378 let secondary = (encoded >> 16) & 1;
1379 let base_name = self.shared.opcode_to_name.get(&opcode)?;
1380 if secondary == 1 {
1381 Some(format!(".{}", base_name))
1382 } else {
1383 Some(base_name.clone())
1384 }
1385 }
1386 Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
1387 _ => None,
1388 }
1389 }
1390
1391 fn build_rule_a_help(
1403 &mut self,
1404 ptr: PointerType,
1405 caller_source_path: &str,
1406 caller_line: usize,
1407 node_idx: usize,
1408 caller_script_idx: usize,
1409 ) -> Option<Help> {
1410 let (is_gosub, script_id) = {
1413 let caller = self.scripts.get(caller_script_idx);
1414 let analysis = self.script_analyses.get(&caller.name)?;
1415 let instr_idx = analysis.nodes[node_idx].instruction_index?;
1416 let instr = &caller.instructions[instr_idx];
1417 match instr.opcode {
1419 Opcode::Jump | Opcode::JumpWithParams => (
1420 false,
1421 match &instr.operand {
1422 Operand::Int(id) => *id,
1423 _ => return None,
1424 },
1425 ),
1426 Opcode::Gosub | Opcode::GosubWithParams => (
1427 true,
1428 match &instr.operand {
1429 Operand::Int(id) => *id,
1430 _ => return None,
1431 },
1432 ),
1433 _ => return None,
1434 }
1435 };
1436
1437 let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
1438 let callee_name = self.scripts.get(callee_idx).name.clone();
1442 self.ensure_analysis(&callee_name);
1443
1444 let callee = self.scripts.get(callee_idx);
1445 let callee_source = callee.source_path.clone();
1446
1447 let first_body_line = callee
1455 .instructions
1456 .iter()
1457 .find_map(|i| match (i.opcode, &i.operand) {
1458 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1459 _ => None,
1460 })
1461 .unwrap_or(1);
1462 let callee_trigger = callee.trigger.clone();
1463 let callee_short_early = callee
1464 .name
1465 .trim_start_matches('[')
1466 .trim_end_matches(']')
1467 .split_once(',')
1468 .map(|(_, n)| n.to_string())
1469 .unwrap_or_else(|| callee.name.clone());
1470 let callee_header_line = self
1471 .source_cache
1472 .and_then(|c| c.get(&callee_source))
1473 .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
1474 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1475
1476 let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
1478 let param_name = format!("${}", ptr_cmd);
1479
1480 let callee_short = callee
1481 .name
1482 .trim_start_matches('[')
1483 .trim_end_matches(']')
1484 .split_once(',')
1485 .map(|(_, n)| n.to_string())
1486 .unwrap_or_else(|| callee.name.clone());
1487
1488 let arrow = if is_gosub { "~" } else { "@" };
1489
1490 let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1495 let corruptor_phrase = format_corruptors(&corruptors);
1496
1497 let message = format!(
1498 "`{callee}` reads `{ptr}` then {phrase}; the script still \
1499 compiles and runs, but the reference is brittle to reorder. \
1500 Consider capturing `{ptr}` at the call site and threading it \
1501 through `{callee}` as an `{ty} {pname}` parameter so the \
1502 value is explicit and stable.",
1503 callee = callee_short,
1504 ptr = ptr_cmd,
1505 phrase = corruptor_phrase,
1506 ty = param_type,
1507 pname = param_name,
1508 );
1509
1510 let cache = match self.source_cache {
1511 Some(c) => c,
1512 None => {
1513 return Some(Help {
1515 message,
1516 suggestions: Vec::new(),
1517 applicability: Applicability::Unspecified,
1518 });
1519 }
1520 };
1521
1522 let mut suggestions = Vec::new();
1523
1524 if let Some(src) = cache.get(caller_source_path)
1527 && let Some(line_text) = nth_source_line(&src, caller_line)
1528 && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1529 {
1530 suggestions.push(Suggestion {
1531 file: PathBuf::from(caller_source_path),
1532 line_range: (caller_line, caller_line),
1533 replacement: rewritten,
1534 label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1535 });
1536 }
1537
1538 if let Some(src) = cache.get(&callee_source)
1540 && let Some(header_text) = nth_source_line(&src, callee_header_line)
1541 && let Some(rewritten) =
1542 rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
1543 {
1544 suggestions.push(Suggestion {
1545 file: PathBuf::from(&callee_source),
1546 line_range: (callee_header_line, callee_header_line),
1547 replacement: rewritten,
1548 label: Some(format!(
1549 "at the `{}` header (add `{} {}`)",
1550 callee_short, param_type, param_name
1551 )),
1552 });
1553 }
1554
1555 Some(Help {
1556 message,
1557 suggestions,
1558 applicability: Applicability::MaybeIncorrect,
1562 })
1563 }
1564}
1565
1566fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1571 if !nodes[from].next.contains(&to) {
1572 nodes[from].next.push(to);
1573 }
1574 if !nodes[to].previous.contains(&from) {
1575 nodes[to].previous.push(from);
1576 }
1577}
1578
1579fn is_static_only_pointer(ptr: PointerType) -> bool {
1592 use PointerType::*;
1593 matches!(
1594 ptr,
1595 FindPlayer
1596 | FindNpc
1597 | FindLoc
1598 | FindObj
1599 | FindDb
1600 | LastCom
1601 | LastInt
1602 | LastItem
1603 | LastSlot
1604 | LastTargetslot
1605 | LastUseitem
1606 | LastUseslot
1607 )
1608}
1609
1610fn short_script_name(full_name: &str) -> Option<String> {
1613 full_name
1614 .trim_start_matches('[')
1615 .trim_end_matches(']')
1616 .split_once(',')
1617 .map(|(_, n)| n.to_string())
1618}
1619
1620fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1625 if corruptors.is_empty() {
1626 return "calls a delay or subroutine that may supersede it".to_string();
1627 }
1628
1629 const MAX: usize = 3;
1630 let shown: Vec<String> = corruptors
1631 .iter()
1632 .take(MAX)
1633 .map(|(name, line)| {
1634 if *line > 0 {
1635 format!("`{}` at line {}", name, line)
1636 } else {
1637 format!("`{}`", name)
1638 }
1639 })
1640 .collect();
1641
1642 let suffix = if corruptors.len() > MAX {
1643 format!(" (and {} more)", corruptors.len() - MAX)
1644 } else {
1645 String::new()
1646 };
1647
1648 let joined = match shown.len() {
1649 1 => shown[0].clone(),
1650 2 => format!("{} and {}", shown[0], shown[1]),
1651 _ => {
1652 let head = shown[..shown.len() - 1].join(", ");
1653 format!("{}, and {}", head, shown[shown.len() - 1])
1654 }
1655 };
1656
1657 format!("calls {}{} which may supersede it", joined, suffix)
1658}
1659
1660fn pointer_param_type(ptr: PointerType) -> &'static str {
1669 use PointerType::*;
1670 match ptr {
1671 LastUseitem | LastItem => "obj",
1672 LastCom => "component",
1673 _ => "int",
1674 }
1675}
1676
1677fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1679 if line_no == 0 {
1680 return None;
1681 }
1682 text.lines().nth(line_no - 1)
1683}
1684
1685fn rewrite_call_site_arg(
1694 line: &str,
1695 arrow: &str,
1696 callee_short: &str,
1697 ptr_cmd: &str,
1698) -> Option<String> {
1699 let needle = format!("{}{}", arrow, callee_short);
1702 let start = line.find(&needle)?;
1703 let after_name = start + needle.len();
1704 let tail = &line[after_name..];
1705
1706 let first_non_ws = tail.chars().next();
1708 if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1709 || tail.trim_start().is_empty()
1710 {
1711 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1712 out.push_str(&line[..after_name]);
1713 out.push('(');
1714 out.push_str(ptr_cmd);
1715 out.push(')');
1716 out.push_str(tail);
1717 return Some(out);
1718 }
1719
1720 if tail.trim_start().starts_with('(') {
1723 let open_rel = tail.find('(')?;
1724 let abs_open = after_name + open_rel;
1725 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1726 let abs_close = abs_open + close_rel;
1727
1728 let inside = line[abs_open + 1..abs_close].trim();
1730 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1731 out.push_str(&line[..abs_close]);
1732 if inside.is_empty() {
1733 out.push_str(ptr_cmd);
1734 } else {
1735 out.push_str(", ");
1736 out.push_str(ptr_cmd);
1737 }
1738 out.push_str(&line[abs_close..]);
1739 return Some(out);
1740 }
1741
1742 None
1743}
1744
1745fn rewrite_header_add_param(
1751 line: &str,
1752 callee_short: &str,
1753 param_type: &str,
1754 param_name: &str,
1755) -> Option<String> {
1756 let needle = format!(",{}]", callee_short);
1759 let subject_end = line.find(&needle)?;
1760 let after_bracket = subject_end + needle.len();
1761
1762 let remainder = &line[after_bracket..];
1763 let added = format!("{} {}", param_type, param_name);
1764
1765 if !remainder.trim_start().starts_with('(') {
1767 let mut out = String::with_capacity(line.len() + added.len() + 2);
1768 out.push_str(&line[..after_bracket]);
1769 out.push('(');
1770 out.push_str(&added);
1771 out.push(')');
1772 out.push_str(remainder);
1773 return Some(out);
1774 }
1775
1776 let open_rel = remainder.find('(')?;
1778 let abs_open = after_bracket + open_rel;
1779 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1780 let abs_close = abs_open + close_rel;
1781 let inside = line[abs_open + 1..abs_close].trim();
1782
1783 let mut out = String::with_capacity(line.len() + added.len() + 2);
1784 out.push_str(&line[..abs_close]);
1785 if inside.is_empty() {
1786 out.push_str(&added);
1787 } else {
1788 out.push_str(", ");
1789 out.push_str(&added);
1790 }
1791 out.push_str(&line[abs_close..]);
1792 Some(out)
1793}
1794
1795fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1799 let prefix = format!("[{},{}]", trigger, name);
1800 let prefix_with_params = format!("[{},{}](", trigger, name);
1801 for (i, line) in src.lines().enumerate() {
1802 let trimmed = line.trim_start();
1803 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1804 return Some(i + 1);
1805 }
1806 }
1807 None
1808}
1809
1810fn find_matching_close_paren(s: &str) -> Option<usize> {
1814 let bytes = s.as_bytes();
1815 if bytes.first().copied() != Some(b'(') {
1816 return None;
1817 }
1818 let mut depth = 0i32;
1819 for (i, &b) in bytes.iter().enumerate() {
1820 match b {
1821 b'(' => depth += 1,
1822 b')' => {
1823 depth -= 1;
1824 if depth == 0 {
1825 return Some(i);
1826 }
1827 }
1828 _ => {}
1829 }
1830 }
1831 None
1832}
1833
1834fn is_secondary_var_operand(operand: &Operand) -> bool {
1840 match operand {
1841 Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1842 _ => false,
1843 }
1844}
1845
1846fn resolve_target_node(
1852 mut target_idx: usize,
1853 instructions: &[Instruction],
1854 instr_to_node: &HashMap<usize, usize>,
1855) -> Option<usize> {
1856 while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1857 target_idx += 1;
1858 }
1859 instr_to_node.get(&target_idx).copied()
1860}
1861
1862fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1863 nodes[from].next.retain(|&n| n != to);
1864 nodes[to].previous.retain(|&n| n != from);
1865}
1866
1867fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1870 for i in (0..=instr_idx).rev() {
1871 if instructions[i].opcode == Opcode::LineNumber
1872 && let Operand::Int(line) = instructions[i].operand
1873 {
1874 return line as usize;
1875 }
1876 }
1877 0
1878}
1879
1880#[cfg(test)]
1881mod tests {
1882 use super::*;
1883 use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1884 use crate::symbol::SymbolRegistry;
1885
1886 fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1888 let mut reg = SymbolRegistry::new();
1889 for &(name, opcode) in commands {
1890 reg.register_command(name.to_string(), opcode, vec![], vec![]);
1891 }
1892 reg
1893 }
1894
1895 fn make_script(
1897 name: &str,
1898 trigger: &str,
1899 id: i32,
1900 instructions: Vec<Instruction>,
1901 ) -> CompiledScript {
1902 let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1903 script.trigger = trigger.to_string();
1904 script.source_path = "test.rs2".to_string();
1905 script.instructions = instructions;
1906 script
1907 }
1908
1909 fn cmd(opcode: i32) -> Instruction {
1911 Instruction::new(Opcode::Command, Operand::Int(opcode))
1912 }
1913
1914 fn line(n: i32) -> Instruction {
1915 Instruction::new(Opcode::LineNumber, Operand::Int(n))
1916 }
1917
1918 fn push_int(v: i32) -> Instruction {
1919 Instruction::push_int(v)
1920 }
1921
1922 fn branch_eq(target: usize) -> Instruction {
1923 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1924 }
1925
1926 fn branch(target: usize) -> Instruction {
1927 Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1928 }
1929
1930 fn ret() -> Instruction {
1931 Instruction::simple(Opcode::Return)
1932 }
1933
1934 fn gosub(script_id: i32) -> Instruction {
1935 Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1936 }
1937
1938 #[test]
1945 fn conditional_setter_with_arg_push() {
1946 let p_finduid_op = 4267;
1949 let p_stopaction_op = 4268;
1950
1951 let registry = registry_with_commands(&[
1952 ("p_finduid", p_finduid_op),
1953 ("p_stopaction", p_stopaction_op),
1954 ]);
1955
1956 let instructions = vec![
1957 line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
1967
1968 let script = make_script("test", "ai_timer", 0, instructions);
1972 let scripts = vec![script];
1973
1974 let mut checker = PointerChecker::new(&scripts, ®istry);
1975 let diags = checker.run();
1976
1977 assert_eq!(
1981 diags.warning_count(),
1982 0,
1983 "conditional setter should provide p_active_player on true branch, got {} warnings",
1984 diags.warning_count()
1985 );
1986 }
1987
1988 #[test]
1989 fn boolean_branches_preserve_conditional_pointer_analysis() {
1990 let registry = registry_with_commands(&[("p_finduid", 4267), ("p_delay", 4268)]);
1991 for (opcode, target, skip) in [(Opcode::BranchIfTrue, 5, 6), (Opcode::BranchIfFalse, 6, 5)]
1992 {
1993 let script = make_script(
1994 "test",
1995 "ai_timer",
1996 0,
1997 vec![
1998 line(1),
1999 push_int(0),
2000 cmd(4267),
2001 Instruction::new(opcode, Operand::JumpTarget(target)),
2002 branch(skip),
2003 cmd(4268),
2004 ret(),
2005 ],
2006 );
2007 assert_eq!(
2008 PointerChecker::new(&[script], ®istry)
2009 .run()
2010 .warning_count(),
2011 0
2012 );
2013 }
2014 let script = make_script(
2015 "test",
2016 "ai_timer",
2017 0,
2018 vec![
2019 line(1),
2020 push_int(0),
2021 cmd(4267),
2022 Instruction::new(Opcode::BranchIfFalse, Operand::JumpTarget(5)),
2023 branch(6),
2024 cmd(4268),
2025 ret(),
2026 ],
2027 );
2028 assert!(
2029 PointerChecker::new(&[script], ®istry)
2030 .run()
2031 .warning_count()
2032 > 0
2033 );
2034 }
2035
2036 #[test]
2045 fn gosub_requires_then_corrupts_same_pointer() {
2046 let p_delay_op = 5001;
2047 let npc_delay_op = 5002;
2048
2049 let registry =
2050 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2051
2052 let proc_script = make_script(
2055 "tackle_success",
2056 "proc",
2057 100,
2058 vec![
2059 line(1),
2060 push_int(0),
2061 cmd(p_delay_op), line(2),
2063 push_int(0),
2064 cmd(npc_delay_op), ret(),
2066 ],
2067 );
2068
2069 let label_script = make_script(
2072 "do_tackle",
2073 "label",
2074 200,
2075 vec![
2076 line(10),
2077 gosub(100), ret(),
2079 ],
2080 );
2081
2082 let scripts = vec![proc_script, label_script];
2083 let mut checker = PointerChecker::new(&scripts, ®istry);
2084 let diags = checker.run();
2085
2086 assert_eq!(
2092 diags.warning_count(),
2093 0,
2094 "gosub that requires-then-corrupts p_active_player should not \
2095 be flagged (engine-tracked pointer), got {} warnings",
2096 diags.warning_count()
2097 );
2098 }
2099
2100 #[test]
2106 fn corruption_before_requirement_is_caught() {
2107 let npc_delay_op = 5002;
2108 let p_delay_op = 5001;
2109
2110 let registry =
2111 registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
2112
2113 let script = make_script(
2116 "bad_order",
2117 "label",
2118 0,
2119 vec![
2120 line(1),
2121 push_int(0),
2122 cmd(npc_delay_op), line(2),
2124 push_int(0),
2125 cmd(p_delay_op), ret(),
2127 ],
2128 );
2129
2130 let scripts = vec![script];
2131 let mut checker = PointerChecker::new(&scripts, ®istry);
2132 let diags = checker.run();
2133
2134 assert!(
2135 diags.warning_count() > 0,
2136 "corruption before requirement should be caught as a warning"
2137 );
2138 }
2139
2140 #[test]
2145 fn uninitialized_pointer_caught() {
2146 let p_delay_op = 5001;
2147
2148 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2149
2150 let script = make_script(
2152 "bad_access",
2153 "ai_timer",
2154 0,
2155 vec![
2156 line(1),
2157 push_int(0),
2158 cmd(p_delay_op), ret(),
2160 ],
2161 );
2162
2163 let scripts = vec![script];
2164 let mut checker = PointerChecker::new(&scripts, ®istry);
2165 let diags = checker.run();
2166
2167 assert!(
2168 diags.warning_count() > 0,
2169 "uninitialized pointer access should be caught"
2170 );
2171 }
2172
2173 #[test]
2183 fn branch_target_on_line_number_still_connects() {
2184 let p_delay_op = 5001;
2185 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2186
2187 let script = make_script(
2203 "target_on_line_number",
2204 "ai_timer",
2205 0,
2206 vec![
2207 line(1),
2208 push_int(1),
2209 push_int(1),
2210 branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
2212 line(2),
2213 push_int(0),
2214 cmd(p_delay_op),
2215 ret(),
2216 ],
2217 );
2218
2219 let scripts = vec![script];
2220 let mut checker = PointerChecker::new(&scripts, ®istry);
2221 let diags = checker.run();
2222
2223 assert!(
2224 diags.warning_count() > 0,
2225 "jump target on LineNumber must still flag uninitialized pointer \
2226 access (got {} warnings)",
2227 diags.warning_count()
2228 );
2229 }
2230
2231 #[test]
2241 fn secondary_requires_and_corrupts_warns_for_static_pointer() {
2242 let last_useitem_op = 4270;
2245 let p_delay_op = 5001;
2246 let registry =
2247 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2248
2249 let callee = make_script(
2251 "consume_useitem",
2252 "label",
2253 100,
2254 vec![
2255 line(1),
2256 cmd(last_useitem_op), line(2),
2258 push_int(0),
2259 cmd(p_delay_op), ret(),
2261 ],
2262 );
2263
2264 let caller = make_script(
2271 "use_on_loc",
2272 "oplocu",
2273 200,
2274 vec![
2275 line(10),
2276 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2277 ],
2278 );
2279
2280 let scripts = vec![callee, caller];
2281 let mut checker = PointerChecker::new(&scripts, ®istry);
2282 let diags = checker.run();
2283
2284 let last_useitem_warnings = diags
2285 .diagnostics()
2286 .iter()
2287 .filter(|d| d.severity == Severity::Warning)
2288 .filter(|d| d.message.contains("last_useitem"))
2289 .count();
2290 assert!(
2291 last_useitem_warnings > 0,
2292 "static-only pointer (last_useitem) should trigger the \
2293 require+corrupt warning at the jump site; got diags: {:?}",
2294 diags
2295 .diagnostics()
2296 .iter()
2297 .map(|d| &d.message)
2298 .collect::<Vec<_>>()
2299 );
2300
2301 assert_eq!(
2302 diags.error_count(),
2303 0,
2304 "pointer-check diagnostics must never raise error severity; got {} errors",
2305 diags.error_count()
2306 );
2307 }
2308
2309 #[test]
2318 fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
2319 let p_delay_op = 5001;
2320 let npc_delay_op = 5002;
2321 let registry =
2322 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2323
2324 let callee = make_script(
2325 "consume_protected",
2326 "proc",
2327 100,
2328 vec![
2329 line(1),
2330 push_int(0),
2331 cmd(p_delay_op), line(2),
2333 push_int(0),
2334 cmd(npc_delay_op), ret(),
2336 ],
2337 );
2338
2339 let caller = make_script(
2341 "do_opnpc",
2342 "opnpc1",
2343 200,
2344 vec![
2345 line(10),
2346 Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2347 ret(),
2348 ],
2349 );
2350
2351 let scripts = vec![callee, caller];
2352 let mut checker = PointerChecker::new(&scripts, ®istry);
2353 let diags = checker.run();
2354
2355 let p_active_player_warnings = diags
2356 .diagnostics()
2357 .iter()
2358 .filter(|d| d.severity == Severity::Warning)
2359 .filter(|d| d.message.contains("p_active_player"))
2360 .count();
2361 assert_eq!(
2362 p_active_player_warnings, 0,
2363 "engine-tracked pointer (p_active_player) must not trigger the \
2364 require+corrupt warning; got {} such warnings",
2365 p_active_player_warnings
2366 );
2367 }
2368
2369 #[test]
2382 fn secondary_varn_requires_active_npc2_not_primary() {
2383 let secondary_varn = Instruction::new(
2388 Opcode::PushVarn,
2389 Operand::Int(1 << 16), );
2391
2392 let proc_script = make_script(
2394 "reads_secondary_varn",
2395 "proc",
2396 100,
2397 vec![
2398 line(1),
2399 secondary_varn,
2400 Instruction::simple(Opcode::PopIntDiscard),
2401 ret(),
2402 ],
2403 );
2404
2405 let caller = make_script(
2412 "gosub_into_proc",
2413 "opplayer1",
2414 200,
2415 vec![line(10), gosub(100), ret()],
2416 );
2417
2418 let scripts = vec![proc_script, caller];
2419 let registry = registry_with_commands(&[]);
2420 let mut checker = PointerChecker::new(&scripts, ®istry);
2421 let diags = checker.run();
2422
2423 let active_npc_primary_warnings = diags
2429 .diagnostics()
2430 .iter()
2431 .filter(|d| d.severity == Severity::Warning)
2432 .filter(|d| d.message.contains("pointer active_npc."))
2433 .count();
2434 assert_eq!(
2435 active_npc_primary_warnings,
2436 0,
2437 "secondary .%var read must not flag primary active_npc at the \
2438 caller; got diags: {:?}",
2439 diags
2440 .diagnostics()
2441 .iter()
2442 .filter(|d| d.severity == Severity::Warning)
2443 .map(|d| &d.message)
2444 .collect::<Vec<_>>()
2445 );
2446
2447 let active_npc2_warnings = diags
2451 .diagnostics()
2452 .iter()
2453 .filter(|d| d.severity == Severity::Warning)
2454 .filter(|d| d.message.contains("pointer .active_npc."))
2455 .count();
2456 assert!(
2457 active_npc2_warnings > 0,
2458 "secondary .%var should route the requirement to active_npc2; \
2459 got no such warning"
2460 );
2461 }
2462
2463 #[test]
2468 fn rewrite_call_site_no_args() {
2469 let got = rewrite_call_site_arg(
2470 "[opnpcu,wantcat1] @civilian_give_runes;",
2471 "@",
2472 "civilian_give_runes",
2473 "last_useitem",
2474 )
2475 .unwrap();
2476 assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2477 }
2478
2479 #[test]
2480 fn rewrite_call_site_with_args() {
2481 let got = rewrite_call_site_arg(
2482 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2483 "@",
2484 "amulet_of_glory_interface",
2485 "last_item",
2486 )
2487 .unwrap();
2488 assert_eq!(
2489 got,
2490 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2491 );
2492 }
2493
2494 #[test]
2495 fn rewrite_call_site_gosub_no_args() {
2496 let got =
2497 rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2498 assert_eq!(got, " ~some_proc(last_useitem);");
2499 }
2500
2501 #[test]
2502 fn rewrite_call_site_empty_arg_list() {
2503 let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2504 assert_eq!(got, "@foo(last_useitem);");
2505 }
2506
2507 #[test]
2508 fn rewrite_header_no_params() {
2509 let got = rewrite_header_add_param(
2510 "[label,civilian_give_runes]",
2511 "civilian_give_runes",
2512 "obj",
2513 "$last_useitem",
2514 )
2515 .unwrap();
2516 assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2517 }
2518
2519 #[test]
2520 fn rewrite_header_with_existing_params() {
2521 let got = rewrite_header_add_param(
2522 "[label,amulet_of_glory_interface](string $message)",
2523 "amulet_of_glory_interface",
2524 "obj",
2525 "$last_item",
2526 )
2527 .unwrap();
2528 assert_eq!(
2529 got,
2530 "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2531 );
2532 }
2533
2534 #[test]
2535 fn rewrite_header_proc_with_return_type() {
2536 let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2539 assert_eq!(got, "[proc,foo](obj $x)(int)");
2540 }
2541
2542 #[test]
2543 fn find_header_line_matches_trigger_and_name() {
2544 let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2545 assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2546 assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2547 assert_eq!(find_header_line(src, "label", "missing"), None);
2548 }
2549
2550 #[test]
2551 fn format_corruptors_shapes() {
2552 assert_eq!(
2553 format_corruptors(&[]),
2554 "calls a delay or subroutine that may supersede it"
2555 );
2556 assert_eq!(
2557 format_corruptors(&[("p_delay".to_string(), 21)]),
2558 "calls `p_delay` at line 21 which may supersede it"
2559 );
2560 assert_eq!(
2561 format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2562 "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2563 );
2564 assert_eq!(
2565 format_corruptors(&[
2566 ("p_delay".to_string(), 21),
2567 ("~chatnpc".to_string(), 11),
2568 ("~objbox".to_string(), 14),
2569 ]),
2570 "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2571 );
2572 assert_eq!(
2574 format_corruptors(&[
2575 ("p_delay".to_string(), 1),
2576 ("~a".to_string(), 2),
2577 ("~b".to_string(), 3),
2578 ("~c".to_string(), 4),
2579 ("~d".to_string(), 5),
2580 ]),
2581 "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2582 );
2583 assert_eq!(
2585 format_corruptors(&[("p_delay".to_string(), 0)]),
2586 "calls `p_delay` which may supersede it"
2587 );
2588 }
2589
2590 #[test]
2591 fn find_matching_close_paren_nested() {
2592 assert_eq!(find_matching_close_paren("()"), Some(1));
2593 assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2594 assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2595 assert_eq!(find_matching_close_paren("("), None);
2596 assert_eq!(find_matching_close_paren("abc"), None);
2597 }
2598
2599 #[test]
2604 fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2605 use std::collections::HashMap;
2606 use std::sync::Arc;
2607
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 mut callee = make_script(
2615 "consume_useitem",
2616 "label",
2617 100,
2618 vec![
2619 line(2), cmd(last_useitem_op),
2621 line(3),
2622 push_int(0),
2623 cmd(p_delay_op),
2624 ret(),
2625 ],
2626 );
2627 callee.source_path = "/virt/consume.rs2".to_string();
2628
2629 let mut caller = make_script(
2631 "use_on_loc",
2632 "oplocu",
2633 200,
2634 vec![
2635 line(1),
2636 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2637 ],
2638 );
2639 caller.source_path = "/virt/caller.rs2".to_string();
2640
2641 let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2644 source_cache.insert(
2645 "/virt/caller.rs2".to_string(),
2646 Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2647 );
2648 source_cache.insert(
2649 "/virt/consume.rs2".to_string(),
2650 Arc::new(
2651 "[label,consume_useitem]\n\
2652 last_useitem;\n\
2653 p_delay(0);\n"
2654 .to_string(),
2655 ),
2656 );
2657
2658 let scripts = vec![callee, caller];
2659 let mut checker = PointerChecker::new(&scripts, ®istry);
2660 checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
2661 let diags = checker.run();
2662
2663 let warning = diags
2666 .diagnostics()
2667 .iter()
2668 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2669 .expect("expected a stale-last_useitem warning");
2670
2671 assert_eq!(
2672 warning.help.len(),
2673 1,
2674 "warning should have exactly one Help block, got {}",
2675 warning.help.len()
2676 );
2677 let help = &warning.help[0];
2678 assert!(
2679 help.message.contains("consume_useitem"),
2680 "help message should name the callee, got: {}",
2681 help.message
2682 );
2683 assert!(
2684 help.message.contains("last_useitem"),
2685 "help message should name the pointer, got: {}",
2686 help.message
2687 );
2688
2689 assert_eq!(
2691 help.suggestions.len(),
2692 2,
2693 "help should include both call-site and header suggestions, \
2694 got {}: {:?}",
2695 help.suggestions.len(),
2696 help.suggestions
2697 .iter()
2698 .map(|s| &s.label)
2699 .collect::<Vec<_>>()
2700 );
2701
2702 let caller_sug = help
2704 .suggestions
2705 .iter()
2706 .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2707 .expect("expected a call-site suggestion on the caller file");
2708 assert!(
2709 caller_sug
2710 .replacement
2711 .contains("@consume_useitem(last_useitem)"),
2712 "call-site replacement must pass last_useitem as an arg, got: {}",
2713 caller_sug.replacement
2714 );
2715
2716 let header_sug = help
2718 .suggestions
2719 .iter()
2720 .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2721 .expect("expected a header suggestion on the callee file");
2722 assert!(
2723 header_sug.replacement.contains("(obj $last_useitem)"),
2724 "header replacement must add `obj $last_useitem` param, got: {}",
2725 header_sug.replacement
2726 );
2727
2728 assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2729 }
2730
2731 #[test]
2735 fn secondary_warning_falls_back_to_prose_help_without_source() {
2736 let last_useitem_op = 4270;
2737 let p_delay_op = 5001;
2738 let registry =
2739 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2740
2741 let callee = make_script(
2742 "consume_useitem",
2743 "label",
2744 100,
2745 vec![
2746 line(1),
2747 cmd(last_useitem_op),
2748 line(2),
2749 push_int(0),
2750 cmd(p_delay_op),
2751 ret(),
2752 ],
2753 );
2754 let caller = make_script(
2755 "use_on_loc",
2756 "oplocu",
2757 200,
2758 vec![
2759 line(1),
2760 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2761 ],
2762 );
2763
2764 let scripts = vec![callee, caller];
2765 let mut checker = PointerChecker::new(&scripts, ®istry);
2766 let diags = checker.run();
2768
2769 let warning = diags
2770 .diagnostics()
2771 .iter()
2772 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2773 .expect("warning still fires without source cache");
2774
2775 assert_eq!(warning.help.len(), 1);
2776 let help = &warning.help[0];
2777 assert_eq!(
2778 help.suggestions.len(),
2779 0,
2780 "prose-only help should have no concrete suggestions"
2781 );
2782 assert_eq!(help.applicability, Applicability::Unspecified);
2783 }
2784}