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};
12use crate::types::Type;
13
14#[cfg(feature = "memprof")]
21static CFG_TRACE: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
22
23#[cfg(feature = "memprof")]
24fn cfg_trace_push(source_path: &str) {
25 if std::env::var_os("RUNEC_TRACE_CFG").is_some() {
26 CFG_TRACE.lock().unwrap().push(source_path.to_string());
27 }
28}
29
30#[cfg(feature = "memprof")]
33pub(crate) fn cfg_trace_report() {
34 use tracing::info;
35 let trace = CFG_TRACE.lock().unwrap();
36 if trace.is_empty() {
37 return;
38 }
39 let distinct: HashSet<&str> = trace.iter().map(|s| s.as_str()).collect();
40 let nfiles = distinct.len().max(1);
41 info!(
42 "[trace] build_cfg calls: {}, distinct files: {}",
43 trace.len(),
44 nfiles
45 );
46 for &cap in &[16usize, 64, 256, 1024, nfiles] {
47 let mut lru: Vec<&str> = Vec::with_capacity(cap + 1);
48 let mut misses = 0usize;
49 for f in trace.iter() {
50 let f = f.as_str();
51 if let Some(pos) = lru.iter().position(|x| *x == f) {
52 lru.remove(pos);
53 } else {
54 misses += 1;
55 }
56 lru.insert(0, f);
57 if lru.len() > cap {
58 lru.pop();
59 }
60 }
61 info!(
62 "[trace] LRU cap {:>5}: {:>7} re-parses ({:.2}x of {} files)",
63 cap,
64 misses,
65 misses as f64 / nfiles as f64,
66 nfiles
67 );
68 }
69}
70
71pub(crate) enum ScriptRef<'a> {
80 Borrowed(&'a CompiledScript),
81 Owned(std::rc::Rc<CompiledScript>),
82}
83
84impl std::ops::Deref for ScriptRef<'_> {
85 type Target = CompiledScript;
86 fn deref(&self) -> &CompiledScript {
87 match self {
88 ScriptRef::Borrowed(s) => s,
89 ScriptRef::Owned(rc) => rc,
90 }
91 }
92}
93
94pub(crate) enum ScriptSource<'a> {
100 Resident(&'a [CompiledScript]),
101 Recompile {
102 len: usize,
103 get: std::cell::RefCell<Box<dyn FnMut(usize) -> std::rc::Rc<CompiledScript> + 'a>>,
104 },
105}
106
107impl<'a> ScriptSource<'a> {
108 fn len(&self) -> usize {
109 match self {
110 ScriptSource::Resident(s) => s.len(),
111 ScriptSource::Recompile { len, .. } => *len,
112 }
113 }
114
115 fn get(&self, idx: usize) -> ScriptRef<'a> {
119 match self {
120 ScriptSource::Resident(s) => ScriptRef::Borrowed(&(*s)[idx]),
121 ScriptSource::Recompile { get, .. } => ScriptRef::Owned((get.borrow_mut())(idx)),
122 }
123 }
124}
125
126#[derive(Debug)]
131struct CfgNode {
132 instruction_index: Option<usize>,
135 pointer_set: PointerSet,
137 next: Vec<usize>,
139 previous: Vec<usize>,
141}
142
143impl CfgNode {
144 fn new(instruction_index: Option<usize>) -> Self {
145 CfgNode {
146 instruction_index,
147 pointer_set: PointerSet::new(),
148 next: Vec::new(),
149 previous: Vec::new(),
150 }
151 }
152
153 fn pointer_node(pointer_set: PointerSet) -> Self {
154 CfgNode {
155 instruction_index: None,
156 pointer_set,
157 next: Vec::new(),
158 previous: Vec::new(),
159 }
160 }
161}
162
163struct ScriptAnalysis {
168 nodes: Vec<CfgNode>,
169 required: Vec<Vec<usize>>,
171 set_list: Vec<Vec<usize>>,
173 corrupted_list: Vec<Vec<usize>>,
175 returns: Vec<usize>,
177}
178
179impl ScriptAnalysis {
180 fn new() -> Self {
181 let n = PointerType::COUNT;
182 ScriptAnalysis {
183 nodes: Vec::new(),
184 required: vec![Vec::new(); n],
185 set_list: vec![Vec::new(); n],
186 corrupted_list: vec![Vec::new(); n],
187 returns: Vec::new(),
188 }
189 }
190}
191
192pub(crate) struct SharedMaps {
201 client: bool,
202 cmd_pointers: HashMap<String, PointerHolder>,
203 opcode_to_name: HashMap<i32, String>,
205 script_id_to_index: HashMap<i32, usize>,
207 script_name_to_index: HashMap<String, usize>,
211 overlay_interfaces: HashSet<String>,
214}
215
216pub struct PointerChecker<'a> {
217 scripts: ScriptSource<'a>,
218 #[allow(dead_code)]
219 registry: &'a SymbolRegistry,
220 shared: std::sync::Arc<SharedMaps>,
222 source_cache: Option<crate::SourceProvider<'a>>,
227 script_analyses: HashMap<String, ScriptAnalysis>,
229 script_pointers: HashMap<String, PointerHolder>,
230 pending_analyses: HashSet<String>,
231 pending_scripts: HashSet<String>,
232}
233
234impl SharedMaps {
235 fn build<'b>(
239 idents: impl Iterator<Item = (i32, &'b str)>,
240 registry: &SymbolRegistry,
241 client: bool,
242 ) -> Self {
243 let mut opcode_to_name = HashMap::new();
245 for (name, sym) in ®istry.commands {
246 if let SymbolKind::Command { opcode, .. } = &sym.kind {
247 opcode_to_name.insert(*opcode, name.to_lowercase());
248 }
249 }
250
251 let mut script_id_to_index = HashMap::new();
255 let mut script_name_to_index = HashMap::new();
256 for (i, (id, name)) in idents.enumerate() {
257 script_id_to_index.insert(id, i);
258 script_name_to_index.entry(name.to_string()).or_insert(i);
259 }
260
261 let mut overlay_interfaces = HashSet::new();
265 for (name, entry) in ®istry.entity_ids {
266 if entry
267 .variants
268 .iter()
269 .any(|(t, _)| *t == Type::OverlayInterface)
270 {
271 overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
272 }
273 }
274
275 SharedMaps {
276 client,
277 cmd_pointers: registry.profile.as_ref().map_or_else(
278 || {
279 if client {
280 clientscript::command_pointers(registry)
281 } else {
282 command_pointers()
283 }
284 },
285 |profile| profile.command_pointers.clone(),
286 ),
287 opcode_to_name,
288 script_id_to_index,
289 script_name_to_index,
290 overlay_interfaces,
291 }
292 }
293}
294
295impl<'a> PointerChecker<'a> {
296 pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
297 let shared = std::sync::Arc::new(SharedMaps::build(
298 scripts.iter().map(|s| (s.id, s.name.as_str())),
299 registry,
300 false,
301 ));
302 Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
303 }
304
305 pub fn new_client(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
306 let shared = std::sync::Arc::new(SharedMaps::build(
307 scripts.iter().map(|s| (s.id, s.name.as_str())),
308 registry,
309 true,
310 ));
311 Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
312 }
313
314 pub(crate) fn build_shared(
318 scripts: &[CompiledScript],
319 registry: &SymbolRegistry,
320 client: bool,
321 ) -> std::sync::Arc<SharedMaps> {
322 std::sync::Arc::new(SharedMaps::build(
323 scripts.iter().map(|s| (s.id, s.name.as_str())),
324 registry,
325 client,
326 ))
327 }
328
329 pub(crate) fn build_shared_idents(
332 idents: &[(i32, String)],
333 registry: &SymbolRegistry,
334 ) -> std::sync::Arc<SharedMaps> {
335 std::sync::Arc::new(SharedMaps::build(
336 idents.iter().map(|(id, name)| (*id, name.as_str())),
337 registry,
338 false,
339 ))
340 }
341
342 pub(crate) fn with_shared(
345 scripts: ScriptSource<'a>,
346 registry: &'a SymbolRegistry,
347 shared: std::sync::Arc<SharedMaps>,
348 ) -> Self {
349 PointerChecker {
350 scripts,
351 registry,
352 shared,
353 source_cache: None,
354 script_analyses: HashMap::new(),
355 script_pointers: HashMap::new(),
356 pending_analyses: HashSet::new(),
357 pending_scripts: HashSet::new(),
358 }
359 }
360
361 pub fn set_source_cache(&mut self, provider: crate::SourceProvider<'a>) {
365 self.source_cache = Some(provider);
366 }
367
368 fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
371 if !self
372 .registry
373 .trigger(trigger)
374 .is_some_and(|trigger| trigger.is_button)
375 {
376 return false;
377 }
378 let subject = script_name
380 .trim_start_matches('[')
381 .trim_end_matches(']')
382 .split_once(',')
383 .map(|(_, rest)| rest)
384 .unwrap_or("");
385 let iface_name = subject
386 .split(':')
387 .next()
388 .unwrap_or("")
389 .to_lowercase()
390 .replace(' ', "_");
391 if iface_name.is_empty() {
392 return false;
393 }
394 !self.shared.overlay_interfaces.contains(&iface_name)
396 }
397
398 pub fn run(&mut self) -> DiagnosticsCollector {
400 let names = self.script_names();
401 self.validate_names(&names)
402 }
403
404 pub fn script_names(&self) -> Vec<String> {
406 (0..self.scripts.len())
407 .map(|i| self.scripts.get(i).name.clone())
408 .collect()
409 }
410
411 pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
419 self.validate_names_until(names, &|| false)
420 }
421
422 pub(crate) fn validate_names_until(
424 &mut self,
425 names: &[String],
426 stop: &dyn Fn() -> bool,
427 ) -> DiagnosticsCollector {
428 let mut diagnostics = DiagnosticsCollector::new();
429 for script_name in names {
430 if stop() {
431 break;
432 }
433 self.validate_script(script_name, &mut diagnostics);
434 self.script_analyses.clear();
442 }
443 diagnostics
444 }
445
446 fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
447 let script_idx = match self.shared.script_name_to_index.get(script_name) {
449 Some(&i) => i,
450 None => return,
451 };
452 let trigger = self.scripts.get(script_idx).trigger.clone();
453 let source_path = self.scripts.get(script_idx).source_path.clone();
454 let trigger_set = if let Some(profile) = &self.registry.profile {
455 profile
456 .trigger_pointers
457 .get(&trigger)
458 .copied()
459 .unwrap_or_default()
460 } else if self.shared.client {
461 match trigger.as_str() {
462 "proc" => [PointerType::ActiveComponent, PointerType::ActiveComponent2]
463 .into_iter()
464 .collect(),
465 _ => PointerSet::new(),
466 }
467 } else {
468 trigger_pointers(&trigger)
469 };
470
471 self.ensure_analysis(script_name);
473
474 for &ptr in &PointerType::ALL {
475 let ptr_idx = ptr.index();
476
477 let analysis = match self.script_analyses.get(script_name) {
479 Some(a) => a,
480 None => continue,
481 };
482
483 let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
484 if required_nodes.is_empty() {
485 continue;
486 }
487
488 let mut corrupted: HashSet<usize> =
493 analysis.corrupted_list[ptr_idx].iter().copied().collect();
494
495 let trigger_provides = if trigger_set.contains(ptr) {
499 true
500 } else if ptr == PointerType::PActivePlayer {
501 self.interface_trigger_grants_protected(&trigger, script_name)
502 } else {
503 false
504 };
505 if !trigger_provides {
506 corrupted.insert(0);
507 }
508
509 if corrupted.is_empty() {
510 continue;
511 }
512
513 let set_blocked: HashSet<usize> = analysis.set_list[ptr_idx].iter().copied().collect();
514
515 let path = self.find_edge_path(
517 script_name,
518 &required_nodes,
519 |node_idx| corrupted.contains(&node_idx),
520 &set_blocked,
521 );
522
523 let mut reported_via_main_bfs = false;
524 if let Some(path) = path {
525 if path.is_empty() {
526 continue;
527 }
528 reported_via_main_bfs = true;
529
530 let end_node_idx = path[path.len() - 1];
531 let start_node_idx = path[0];
532
533 let is_start_node = end_node_idx == 0;
534 let repr = ptr.representation();
535 let static_only = is_static_only_pointer(ptr);
536
537 let error_msg = if is_start_node {
543 if static_only {
544 msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
545 } else {
546 msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
547 }
548 } else if static_only {
549 msg::fmt(msg::POINTER_STALE, &[repr])
550 } else {
551 msg::fmt(msg::POINTER_CORRUPTED, &[repr])
552 };
553
554 let analysis = self.script_analyses.get(script_name).unwrap();
555 let script_ref = self.scripts.get(script_idx);
556 let instructions = &script_ref.instructions;
557 let req_line = analysis.nodes[start_node_idx]
558 .instruction_index
559 .map(|idx| resolve_line(instructions, idx))
560 .unwrap_or(0);
561
562 diagnostics.add(Diagnostic {
567 file: PathBuf::from(&source_path),
568 line: req_line,
569 column: 0,
570 message: error_msg,
571 severity: Severity::Warning,
572 phase: Phase::PointerCheck,
573 help: Vec::new(),
574 });
575
576 let read_hint = if static_only {
577 msg::fmt(msg::POINTER_READ_HERE, &[repr])
578 } else {
579 msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
580 };
581 diagnostics.add(Diagnostic {
582 file: PathBuf::from(&source_path),
583 line: req_line,
584 column: 0,
585 message: read_hint,
586 severity: Severity::Info,
587 phase: Phase::PointerCheck,
588 help: Vec::new(),
589 });
590
591 if !is_start_node {
592 let corrupt_line = analysis.nodes[end_node_idx]
593 .instruction_index
594 .map(|idx| resolve_line(instructions, idx))
595 .unwrap_or(0);
596
597 let cause_hint = if static_only {
598 msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
599 } else {
600 msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
601 };
602 diagnostics.add(Diagnostic {
603 file: PathBuf::from(&source_path),
604 line: corrupt_line,
605 column: 0,
606 message: cause_hint,
607 severity: Severity::Info,
608 phase: Phase::PointerCheck,
609 help: Vec::new(),
610 });
611 }
612 }
613
614 if !reported_via_main_bfs && is_static_only_pointer(ptr) {
627 let targets: Vec<(usize, usize)> = {
631 let analysis = self.script_analyses.get(script_name).unwrap();
632 let script_ref = self.scripts.get(script_idx);
633 let instructions = &script_ref.instructions;
634 let corrupted_nodes: HashSet<usize> =
635 analysis.corrupted_list[ptr_idx].iter().copied().collect();
636 required_nodes
637 .iter()
638 .filter(|&&node_idx| corrupted_nodes.contains(&node_idx))
639 .map(|&node_idx| {
640 let line = analysis.nodes[node_idx]
641 .instruction_index
642 .map(|idx| resolve_line(instructions, idx))
643 .unwrap_or(0);
644 (node_idx, line)
645 })
646 .collect()
647 };
648 let mut seen_lines: HashSet<usize> = HashSet::new();
649 let repr = ptr.representation();
650 for (node_idx, line) in targets {
651 if !seen_lines.insert(line) {
652 continue;
653 }
654
655 let help =
660 self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
661
662 let mut diag = Diagnostic {
670 file: PathBuf::from(&source_path),
671 line,
672 column: 0,
673 message: msg::fmt(msg::POINTER_STALE, &[repr]),
674 severity: Severity::Warning,
675 phase: Phase::PointerCheck,
676 help: Vec::new(),
677 };
678 if let Some(h) = help {
679 diag.help.push(h);
680 }
681 diagnostics.add(diag);
682 }
683 }
684 }
685 }
686
687 fn find_edge_path(
696 &self,
697 script_name: &str,
698 starts: &[usize],
699 end_pred: impl Fn(usize) -> bool,
700 blocked: &HashSet<usize>,
701 ) -> Option<Vec<usize>> {
702 let analysis = self.script_analyses.get(script_name)?;
703
704 let mut queue: VecDeque<usize> = VecDeque::new();
705 let mut visited: HashSet<usize> = HashSet::new();
706 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); for &start in starts {
714 for &prev in &analysis.nodes[start].previous {
715 if blocked.contains(&prev) || visited.contains(&prev) {
716 continue;
717 }
718 visited.insert(prev);
719 queue.push_back(prev);
720 sources.insert(prev, (start, start));
721 }
722 }
723
724 while let Some(current) = queue.pop_front() {
725 if end_pred(current) {
726 let mut path = vec![current];
728 let mut node = current;
729 while let Some(&(from, start)) = sources.get(&node) {
730 if from == start && starts.contains(&from) {
731 path.push(from);
732 break;
733 }
734 path.push(from);
735 node = from;
736 }
737 path.reverse();
738 return Some(path);
739 }
740
741 let (_, start_node) = sources[¤t];
742
743 for &prev in &analysis.nodes[current].previous {
744 if blocked.contains(&prev) || visited.contains(&prev) {
745 continue;
746 }
747 visited.insert(prev);
748 queue.push_back(prev);
749 sources.insert(prev, (current, start_node));
750 }
751 }
752
753 None
754 }
755
756 fn find_edge_path_static(
759 nodes: &[CfgNode],
760 starts: &[usize],
761 end_pred: impl Fn(usize) -> bool,
762 blocked: &HashSet<usize>,
763 ) -> Option<Vec<usize>> {
764 let mut queue: VecDeque<usize> = VecDeque::new();
765 let mut visited: HashSet<usize> = HashSet::new();
766 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
767
768 for &start in starts {
769 for &prev in &nodes[start].previous {
770 if blocked.contains(&prev) || visited.contains(&prev) {
771 continue;
772 }
773 visited.insert(prev);
774 queue.push_back(prev);
775 sources.insert(prev, (start, start));
776 }
777 }
778
779 while let Some(current) = queue.pop_front() {
780 if end_pred(current) {
781 let mut path = vec![current];
782 let mut node = current;
783 while let Some(&(from, start)) = sources.get(&node) {
784 if from == start && starts.contains(&from) {
785 path.push(from);
786 break;
787 }
788 path.push(from);
789 node = from;
790 }
791 path.reverse();
792 return Some(path);
793 }
794
795 for &prev in &nodes[current].previous {
796 if blocked.contains(&prev) || visited.contains(&prev) {
797 continue;
798 }
799 visited.insert(prev);
800 queue.push_back(prev);
801 sources.insert(prev, (current, sources[¤t].1));
802 }
803 }
804
805 None
806 }
807
808 fn ensure_analysis(&mut self, script_name: &str) {
813 if self.script_analyses.contains_key(script_name) {
814 return;
815 }
816 if self.pending_analyses.contains(script_name) {
817 return; }
819 self.pending_analyses.insert(script_name.to_string());
820
821 let script_idx = match self.shared.script_name_to_index.get(script_name) {
822 Some(&i) => i,
823 None => return,
824 };
825
826 let mut analysis = self.build_cfg(script_idx);
827 self.categorize_nodes(script_idx, &mut analysis);
828
829 self.script_analyses
830 .insert(script_name.to_string(), analysis);
831 self.pending_analyses.remove(script_name);
832 }
833
834 fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
839 let script = self.scripts.get(script_idx);
840 #[cfg(feature = "memprof")]
841 cfg_trace_push(&script.source_path);
842 let instructions = &script.instructions;
843 let mut analysis = ScriptAnalysis::new();
844
845 analysis.nodes.push(CfgNode::new(None));
847
848 let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
850 let mut node_order: Vec<usize> = Vec::new(); for (i, instr) in instructions.iter().enumerate() {
853 if instr.opcode == Opcode::LineNumber {
854 continue;
855 }
856 let node_idx = analysis.nodes.len();
857 instr_to_node.insert(i, node_idx);
858 node_order.push(i);
859 analysis.nodes.push(CfgNode::new(Some(i)));
860 }
861
862 if node_order.is_empty() {
863 return analysis;
864 }
865
866 let first_node = instr_to_node[&node_order[0]];
868 add_edge(&mut analysis.nodes, 0, first_node);
869
870 for (order_idx, &instr_idx) in node_order.iter().enumerate() {
872 let node_idx = instr_to_node[&instr_idx];
873 let instr = &instructions[instr_idx];
874
875 let is_terminal = matches!(
876 instr.opcode,
877 Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
878 );
879
880 match instr.opcode {
885 Opcode::Branch
886 | Opcode::BranchNot
887 | Opcode::BranchEquals
888 | Opcode::BranchLessThan
889 | Opcode::BranchGreaterThan
890 | Opcode::BranchLessThanOrEquals
891 | Opcode::BranchGreaterThanOrEquals
892 | Opcode::LongBranchNot
893 | Opcode::LongBranchEquals
894 | Opcode::LongBranchLessThan
895 | Opcode::LongBranchGreaterThan
896 | Opcode::LongBranchLessThanOrEquals
897 | Opcode::LongBranchGreaterThanOrEquals
898 | Opcode::ObjBranchEquals
899 | Opcode::ObjBranchNot
900 | Opcode::BranchIfTrue
901 | Opcode::BranchIfFalse => {
902 if let Operand::JumpTarget(target_instr_idx) = &instr.operand
903 && let Some(target_node) =
904 resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
905 {
906 add_edge(&mut analysis.nodes, node_idx, target_node);
907 }
908 }
909
910 Opcode::Switch => {
911 if let Operand::SwitchTable(tbl_idx) = &instr.operand {
912 let cases = &script.switch_tables[*tbl_idx as usize];
913 for &(_, target_instr_idx) in cases.iter() {
914 if let Some(target_node) =
915 resolve_target_node(target_instr_idx, instructions, &instr_to_node)
916 {
917 add_edge(&mut analysis.nodes, node_idx, target_node);
918 }
919 }
920 }
921 }
922
923 _ => {}
924 }
925
926 if !is_terminal
928 && let Some(next_order_idx) = order_idx.checked_add(1)
929 && next_order_idx < node_order.len()
930 {
931 let next_node = instr_to_node[&node_order[next_order_idx]];
932 add_edge(&mut analysis.nodes, node_idx, next_node);
933 }
934
935 if instr.opcode == Opcode::Return {
940 analysis.returns.push(node_idx);
941 }
942 }
943
944 self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
946
947 analysis
948 }
949
950 fn insert_pointer_nodes(
953 &self,
954 script_idx: usize,
955 analysis: &mut ScriptAnalysis,
956 instr_to_node: &HashMap<usize, usize>,
957 node_order: &[usize],
958 ) {
959 let script_ref = self.scripts.get(script_idx);
960 let instructions = &script_ref.instructions;
961
962 for window_end in 1..node_order.len() {
967 let branch_instr_idx = node_order[window_end];
968 let branch_instr = &instructions[branch_instr_idx];
969 let (push_value, scan_end) = match branch_instr.opcode {
970 Opcode::BranchIfTrue => (1, window_end),
971 Opcode::BranchIfFalse => (0, window_end),
972 Opcode::BranchEquals | Opcode::BranchNot => {
973 let push_instr = &instructions[node_order[window_end - 1]];
974 match (push_instr.opcode, &push_instr.operand) {
975 (Opcode::PushConstantInt, Operand::Int(value @ (0 | 1))) => (
976 if branch_instr.opcode == Opcode::BranchNot {
977 1 - value
978 } else {
979 *value
980 },
981 window_end - 1,
982 ),
983 _ => continue,
984 }
985 }
986 _ => continue,
987 };
988
989 let mut cmd_instr_idx = None;
991 for scan in (0..scan_end).rev() {
992 let idx = node_order[scan];
993 if instructions[idx].opcode == Opcode::Command {
994 cmd_instr_idx = Some(idx);
995 break;
996 }
997 if matches!(
999 instructions[idx].opcode,
1000 Opcode::Branch
1001 | Opcode::Return
1002 | Opcode::Switch
1003 | Opcode::BranchEquals
1004 | Opcode::BranchNot
1005 | Opcode::BranchLessThan
1006 | Opcode::BranchGreaterThan
1007 | Opcode::BranchLessThanOrEquals
1008 | Opcode::BranchGreaterThanOrEquals
1009 | Opcode::BranchIfTrue
1010 | Opcode::BranchIfFalse
1011 ) {
1012 break;
1013 }
1014 }
1015 let cmd_instr_idx = match cmd_instr_idx {
1016 Some(idx) => idx,
1017 None => continue,
1018 };
1019 if self.shared.client && (scan_end == 0 || node_order[scan_end - 1] != cmd_instr_idx) {
1020 continue;
1021 }
1022 let cmd_instr = &instructions[cmd_instr_idx];
1023
1024 let cmd_name = self.resolve_command_name(cmd_instr, &script_ref.strings);
1026 let cmd_name = match cmd_name {
1027 Some(n) => n,
1028 None => continue,
1029 };
1030
1031 let holder = match self.shared.cmd_pointers.get(&cmd_name) {
1032 Some(h) => h,
1033 None => continue,
1034 };
1035
1036 if !holder.conditional_set {
1037 continue;
1038 }
1039
1040 if holder.set.is_empty() {
1041 continue;
1042 }
1043
1044 let branch_node_idx = instr_to_node[&branch_instr_idx];
1045
1046 let ptr_node_idx = analysis.nodes.len();
1048 analysis.nodes.push(CfgNode::pointer_node(holder.set));
1049
1050 if push_value == 0 {
1051 let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
1059 .next
1060 .iter()
1061 .copied()
1062 .filter(|&n| {
1063 if let Operand::JumpTarget(target) = &branch_instr.operand
1065 && let Some(jump_node) =
1066 resolve_target_node(*target, instructions, instr_to_node)
1067 {
1068 return n != jump_node;
1069 }
1070 true
1071 })
1072 .collect();
1073
1074 for ft_target in fallthrough_targets {
1075 remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
1077 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1079 add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
1080 }
1081 } else {
1082 if let Operand::JumpTarget(target) = &branch_instr.operand
1086 && let Some(jump_target_node) =
1087 resolve_target_node(*target, instructions, instr_to_node)
1088 {
1089 remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
1091 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1093 add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
1094 }
1095 }
1096 }
1097 }
1098
1099 fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
1104 let script_ref = self.scripts.get(script_idx);
1105 let instructions = &script_ref.instructions;
1106
1107 for node_idx in 0..analysis.nodes.len() {
1108 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1109 Some(i) => i,
1110 None => {
1111 let ptr_set = analysis.nodes[node_idx].pointer_set;
1113 if !ptr_set.is_empty() {
1114 for ptr in ptr_set.iter() {
1115 let pi = ptr.index();
1116 analysis.set_list[pi].push(node_idx);
1117 }
1118 }
1119 continue;
1120 }
1121 };
1122
1123 let instr = &instructions[instr_idx];
1124
1125 match instr.opcode {
1126 Opcode::Command => {
1127 let cmd_name = self.resolve_command_name(instr, &script_ref.strings);
1128 if let Some(name) = cmd_name
1129 && let Some(holder) = self.shared.cmd_pointers.get(&name).cloned()
1130 {
1131 self.apply_holder(analysis, node_idx, &holder);
1132 }
1133 }
1134
1135 Opcode::Gosub | Opcode::GosubWithParams => {
1136 if let Operand::Int(script_id) = &instr.operand {
1137 let callee_holder = self.get_script_pointers(*script_id);
1138 self.apply_holder(analysis, node_idx, &callee_holder);
1139 }
1140 }
1141
1142 Opcode::Jump | Opcode::JumpWithParams => {
1143 if let Operand::Int(script_id) = &instr.operand {
1144 let callee_holder = self.get_script_pointers(*script_id);
1145 self.apply_holder(analysis, node_idx, &callee_holder);
1146 }
1147 }
1148
1149 Opcode::PushVarp
1156 | Opcode::PushVarbit
1157 | Opcode::PushVarcInt
1158 | Opcode::PushVarcString
1159 | Opcode::PushVarClan
1160 | Opcode::PushClanSettingInt
1161 | Opcode::PushClanSettingVarbit
1162 | Opcode::PushClanSettingLong
1163 | Opcode::PushClanSettingString
1164 if !self.shared.client =>
1165 {
1166 let pi = if is_secondary_var_operand(&instr.operand) {
1167 PointerType::ActivePlayer2.index()
1168 } else {
1169 PointerType::ActivePlayer.index()
1170 };
1171 analysis.required[pi].push(node_idx);
1172 }
1173
1174 Opcode::PopVarp
1175 | Opcode::PopVarbit
1176 | Opcode::PopVarcInt
1177 | Opcode::PopVarcString
1178 | Opcode::PopVarClan
1179 | Opcode::PopClanSettingInt
1180 | Opcode::PopClanSettingVarbit
1181 | Opcode::PopClanSettingLong
1182 | Opcode::PopClanSettingString
1183 if !self.shared.client =>
1184 {
1185 let pi = if is_secondary_var_operand(&instr.operand) {
1186 PointerType::ActivePlayer2.index()
1187 } else {
1188 PointerType::ActivePlayer.index()
1189 };
1190 analysis.required[pi].push(node_idx);
1191 }
1192
1193 Opcode::PushVarn | Opcode::PopVarn | Opcode::PushVarnBit | Opcode::PopVarnBit
1194 if !self.shared.client =>
1195 {
1196 let pi = if is_secondary_var_operand(&instr.operand) {
1197 PointerType::ActiveNpc2.index()
1198 } else {
1199 PointerType::ActiveNpc.index()
1200 };
1201 analysis.required[pi].push(node_idx);
1202 }
1203
1204 _ => {}
1206 }
1207 }
1208 }
1209
1210 fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
1211 for ptr in holder.required.iter() {
1212 let pi = ptr.index();
1213 analysis.required[pi].push(node_idx);
1214 }
1215 for ptr in holder.set.iter().filter(|_| !holder.conditional_set) {
1216 let pi = ptr.index();
1217 analysis.set_list[pi].push(node_idx);
1218 }
1219 for ptr in holder.corrupted.iter() {
1220 let pi = ptr.index();
1221 analysis.corrupted_list[pi].push(node_idx);
1222 }
1223 }
1224
1225 fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
1241 let script_idx = match self.shared.script_id_to_index.get(&script_id) {
1243 Some(&i) => i,
1244 None => {
1245 return PointerHolder::default();
1246 }
1247 };
1248 let script_name = self.scripts.get(script_idx).name.clone();
1249
1250 if let Some(holder) = self.script_pointers.get(&script_name) {
1252 return holder.clone();
1253 }
1254
1255 if self.pending_scripts.contains(&script_name) {
1257 return PointerHolder::default();
1258 }
1259 self.pending_scripts.insert(script_name.clone());
1260
1261 self.ensure_analysis(&script_name);
1263
1264 let mut holder = PointerHolder::default();
1265
1266 if let Some(analysis) = self.script_analyses.get(&script_name) {
1267 for &ptr in &PointerType::ALL {
1268 let pi = ptr.index();
1269
1270 let requires = !analysis.required[pi].is_empty();
1276 let has_returns = !analysis.returns.is_empty();
1277 if !requires && !has_returns {
1278 continue;
1279 }
1280 let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
1281
1282 if requires {
1284 let path = Self::find_edge_path_static(
1285 &analysis.nodes,
1286 &analysis.required[pi],
1287 |node_idx| node_idx == 0,
1288 &set_blocked,
1289 );
1290 if path.is_some() {
1291 holder.required.insert(ptr);
1292 }
1293 }
1294
1295 if has_returns {
1296 let corrupted_nodes: HashSet<usize> =
1297 analysis.corrupted_list[pi].iter().copied().collect();
1298
1299 let path = Self::find_edge_path_static(
1302 &analysis.nodes,
1303 &analysis.returns,
1304 |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1305 &set_blocked,
1306 );
1307 if path.is_none() {
1308 holder.set.insert(ptr);
1309 }
1310
1311 if !corrupted_nodes.is_empty() {
1313 let path = Self::find_edge_path_static(
1314 &analysis.nodes,
1315 &analysis.returns,
1316 |node_idx| corrupted_nodes.contains(&node_idx),
1317 &set_blocked,
1318 );
1319 if path.is_some() {
1320 holder.corrupted.insert(ptr);
1321 }
1322 }
1323 }
1324 }
1325 }
1326
1327 self.pending_scripts.remove(&script_name);
1328
1329 self.script_pointers
1330 .insert(script_name.clone(), holder.clone());
1331 holder
1332 }
1333
1334 fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1344 let callee = self.scripts.get(callee_idx);
1345 let analysis = match self.script_analyses.get(&callee.name) {
1346 Some(a) => a,
1347 None => return Vec::new(),
1348 };
1349 let ptr_idx = ptr.index();
1350 let mut seen: HashSet<(String, usize)> = HashSet::new();
1351 let mut result: Vec<(String, usize)> = Vec::new();
1352
1353 for &node_idx in &analysis.corrupted_list[ptr_idx] {
1354 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1355 Some(i) => i,
1356 None => continue,
1357 };
1358 let instr = &callee.instructions[instr_idx];
1359 let line = resolve_line(&callee.instructions, instr_idx);
1360
1361 let name = match instr.opcode {
1362 Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
1363 Some(n) => n,
1364 None => continue,
1365 },
1366 Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1367 Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
1368 Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
1369 .map(|s| format!("~{}", s))
1370 .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
1371 None => continue,
1372 },
1373 _ => continue,
1374 },
1375 _ => continue,
1379 };
1380
1381 let key = (name.clone(), line);
1382 if seen.insert(key) {
1383 result.push((name, line));
1384 }
1385 }
1386
1387 result
1388 }
1389
1390 fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
1391 match &instr.operand {
1392 Operand::Int(encoded) => {
1393 let opcode = encoded & 0xFFFF;
1394 let secondary = (encoded >> 16) & 1;
1395 let base_name = self.shared.opcode_to_name.get(&opcode)?;
1396 if secondary == 1 {
1397 Some(format!(".{}", base_name))
1398 } else {
1399 Some(base_name.clone())
1400 }
1401 }
1402 Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
1403 _ => None,
1404 }
1405 }
1406
1407 fn build_rule_a_help(
1419 &mut self,
1420 ptr: PointerType,
1421 caller_source_path: &str,
1422 caller_line: usize,
1423 node_idx: usize,
1424 caller_script_idx: usize,
1425 ) -> Option<Help> {
1426 let (is_gosub, script_id) = {
1429 let caller = self.scripts.get(caller_script_idx);
1430 let analysis = self.script_analyses.get(&caller.name)?;
1431 let instr_idx = analysis.nodes[node_idx].instruction_index?;
1432 let instr = &caller.instructions[instr_idx];
1433 match instr.opcode {
1435 Opcode::Jump | Opcode::JumpWithParams => (
1436 false,
1437 match &instr.operand {
1438 Operand::Int(id) => *id,
1439 _ => return None,
1440 },
1441 ),
1442 Opcode::Gosub | Opcode::GosubWithParams => (
1443 true,
1444 match &instr.operand {
1445 Operand::Int(id) => *id,
1446 _ => return None,
1447 },
1448 ),
1449 _ => return None,
1450 }
1451 };
1452
1453 let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
1454 let callee_name = self.scripts.get(callee_idx).name.clone();
1458 self.ensure_analysis(&callee_name);
1459
1460 let callee = self.scripts.get(callee_idx);
1461 let callee_source = callee.source_path.clone();
1462
1463 let first_body_line = callee
1471 .instructions
1472 .iter()
1473 .find_map(|i| match (i.opcode, &i.operand) {
1474 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1475 _ => None,
1476 })
1477 .unwrap_or(1);
1478 let callee_trigger = callee.trigger.clone();
1479 let callee_short_early = callee
1480 .name
1481 .trim_start_matches('[')
1482 .trim_end_matches(']')
1483 .split_once(',')
1484 .map(|(_, n)| n.to_string())
1485 .unwrap_or_else(|| callee.name.clone());
1486 let callee_header_line = self
1487 .source_cache
1488 .and_then(|c| c.get(&callee_source))
1489 .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
1490 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1491
1492 let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
1494 let param_name = format!("${}", ptr_cmd);
1495
1496 let callee_short = callee
1497 .name
1498 .trim_start_matches('[')
1499 .trim_end_matches(']')
1500 .split_once(',')
1501 .map(|(_, n)| n.to_string())
1502 .unwrap_or_else(|| callee.name.clone());
1503
1504 let arrow = if is_gosub { "~" } else { "@" };
1505
1506 let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1511 let corruptor_phrase = format_corruptors(&corruptors);
1512
1513 let message = format!(
1514 "`{callee}` reads `{ptr}` then {phrase}; the script still \
1515 compiles and runs, but the reference is brittle to reorder. \
1516 Consider capturing `{ptr}` at the call site and threading it \
1517 through `{callee}` as an `{ty} {pname}` parameter so the \
1518 value is explicit and stable.",
1519 callee = callee_short,
1520 ptr = ptr_cmd,
1521 phrase = corruptor_phrase,
1522 ty = param_type,
1523 pname = param_name,
1524 );
1525
1526 let cache = match self.source_cache {
1527 Some(c) => c,
1528 None => {
1529 return Some(Help {
1531 message,
1532 suggestions: Vec::new(),
1533 applicability: Applicability::Unspecified,
1534 });
1535 }
1536 };
1537
1538 let mut suggestions = Vec::new();
1539
1540 if let Some(src) = cache.get(caller_source_path)
1543 && let Some(line_text) = nth_source_line(&src, caller_line)
1544 && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1545 {
1546 suggestions.push(Suggestion {
1547 file: PathBuf::from(caller_source_path),
1548 line_range: (caller_line, caller_line),
1549 replacement: rewritten,
1550 label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1551 });
1552 }
1553
1554 if let Some(src) = cache.get(&callee_source)
1556 && let Some(header_text) = nth_source_line(&src, callee_header_line)
1557 && let Some(rewritten) =
1558 rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
1559 {
1560 suggestions.push(Suggestion {
1561 file: PathBuf::from(&callee_source),
1562 line_range: (callee_header_line, callee_header_line),
1563 replacement: rewritten,
1564 label: Some(format!(
1565 "at the `{}` header (add `{} {}`)",
1566 callee_short, param_type, param_name
1567 )),
1568 });
1569 }
1570
1571 Some(Help {
1572 message,
1573 suggestions,
1574 applicability: Applicability::MaybeIncorrect,
1578 })
1579 }
1580}
1581
1582fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1587 if !nodes[from].next.contains(&to) {
1588 nodes[from].next.push(to);
1589 }
1590 if !nodes[to].previous.contains(&from) {
1591 nodes[to].previous.push(from);
1592 }
1593}
1594
1595fn is_static_only_pointer(ptr: PointerType) -> bool {
1608 use PointerType::*;
1609 matches!(
1610 ptr,
1611 FindPlayer
1612 | FindNpc
1613 | FindLoc
1614 | FindObj
1615 | FindDb
1616 | LastCom
1617 | LastInt
1618 | LastItem
1619 | LastSlot
1620 | LastTargetslot
1621 | LastUseitem
1622 | LastUseslot
1623 )
1624}
1625
1626fn short_script_name(full_name: &str) -> Option<String> {
1629 full_name
1630 .trim_start_matches('[')
1631 .trim_end_matches(']')
1632 .split_once(',')
1633 .map(|(_, n)| n.to_string())
1634}
1635
1636fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1641 if corruptors.is_empty() {
1642 return "calls a delay or subroutine that may supersede it".to_string();
1643 }
1644
1645 const MAX: usize = 3;
1646 let shown: Vec<String> = corruptors
1647 .iter()
1648 .take(MAX)
1649 .map(|(name, line)| {
1650 if *line > 0 {
1651 format!("`{}` at line {}", name, line)
1652 } else {
1653 format!("`{}`", name)
1654 }
1655 })
1656 .collect();
1657
1658 let suffix = if corruptors.len() > MAX {
1659 format!(" (and {} more)", corruptors.len() - MAX)
1660 } else {
1661 String::new()
1662 };
1663
1664 let joined = match shown.len() {
1665 1 => shown[0].clone(),
1666 2 => format!("{} and {}", shown[0], shown[1]),
1667 _ => {
1668 let head = shown[..shown.len() - 1].join(", ");
1669 format!("{}, and {}", head, shown[shown.len() - 1])
1670 }
1671 };
1672
1673 format!("calls {}{} which may supersede it", joined, suffix)
1674}
1675
1676fn pointer_param_type(ptr: PointerType) -> &'static str {
1685 use PointerType::*;
1686 match ptr {
1687 LastUseitem | LastItem => "obj",
1688 LastCom => "component",
1689 _ => "int",
1690 }
1691}
1692
1693fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1695 if line_no == 0 {
1696 return None;
1697 }
1698 text.lines().nth(line_no - 1)
1699}
1700
1701fn rewrite_call_site_arg(
1710 line: &str,
1711 arrow: &str,
1712 callee_short: &str,
1713 ptr_cmd: &str,
1714) -> Option<String> {
1715 let needle = format!("{}{}", arrow, callee_short);
1718 let start = line.find(&needle)?;
1719 let after_name = start + needle.len();
1720 let tail = &line[after_name..];
1721
1722 let first_non_ws = tail.chars().next();
1724 if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1725 || tail.trim_start().is_empty()
1726 {
1727 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1728 out.push_str(&line[..after_name]);
1729 out.push('(');
1730 out.push_str(ptr_cmd);
1731 out.push(')');
1732 out.push_str(tail);
1733 return Some(out);
1734 }
1735
1736 if tail.trim_start().starts_with('(') {
1739 let open_rel = tail.find('(')?;
1740 let abs_open = after_name + open_rel;
1741 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1742 let abs_close = abs_open + close_rel;
1743
1744 let inside = line[abs_open + 1..abs_close].trim();
1746 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1747 out.push_str(&line[..abs_close]);
1748 if inside.is_empty() {
1749 out.push_str(ptr_cmd);
1750 } else {
1751 out.push_str(", ");
1752 out.push_str(ptr_cmd);
1753 }
1754 out.push_str(&line[abs_close..]);
1755 return Some(out);
1756 }
1757
1758 None
1759}
1760
1761fn rewrite_header_add_param(
1767 line: &str,
1768 callee_short: &str,
1769 param_type: &str,
1770 param_name: &str,
1771) -> Option<String> {
1772 let needle = format!(",{}]", callee_short);
1775 let subject_end = line.find(&needle)?;
1776 let after_bracket = subject_end + needle.len();
1777
1778 let remainder = &line[after_bracket..];
1779 let added = format!("{} {}", param_type, param_name);
1780
1781 if !remainder.trim_start().starts_with('(') {
1783 let mut out = String::with_capacity(line.len() + added.len() + 2);
1784 out.push_str(&line[..after_bracket]);
1785 out.push('(');
1786 out.push_str(&added);
1787 out.push(')');
1788 out.push_str(remainder);
1789 return Some(out);
1790 }
1791
1792 let open_rel = remainder.find('(')?;
1794 let abs_open = after_bracket + open_rel;
1795 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1796 let abs_close = abs_open + close_rel;
1797 let inside = line[abs_open + 1..abs_close].trim();
1798
1799 let mut out = String::with_capacity(line.len() + added.len() + 2);
1800 out.push_str(&line[..abs_close]);
1801 if inside.is_empty() {
1802 out.push_str(&added);
1803 } else {
1804 out.push_str(", ");
1805 out.push_str(&added);
1806 }
1807 out.push_str(&line[abs_close..]);
1808 Some(out)
1809}
1810
1811fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1815 let prefix = format!("[{},{}]", trigger, name);
1816 let prefix_with_params = format!("[{},{}](", trigger, name);
1817 for (i, line) in src.lines().enumerate() {
1818 let trimmed = line.trim_start();
1819 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1820 return Some(i + 1);
1821 }
1822 }
1823 None
1824}
1825
1826fn find_matching_close_paren(s: &str) -> Option<usize> {
1830 let bytes = s.as_bytes();
1831 if bytes.first().copied() != Some(b'(') {
1832 return None;
1833 }
1834 let mut depth = 0i32;
1835 for (i, &b) in bytes.iter().enumerate() {
1836 match b {
1837 b'(' => depth += 1,
1838 b')' => {
1839 depth -= 1;
1840 if depth == 0 {
1841 return Some(i);
1842 }
1843 }
1844 _ => {}
1845 }
1846 }
1847 None
1848}
1849
1850fn is_secondary_var_operand(operand: &Operand) -> bool {
1856 match operand {
1857 Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1858 _ => false,
1859 }
1860}
1861
1862fn resolve_target_node(
1868 mut target_idx: usize,
1869 instructions: &[Instruction],
1870 instr_to_node: &HashMap<usize, usize>,
1871) -> Option<usize> {
1872 while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1873 target_idx += 1;
1874 }
1875 instr_to_node.get(&target_idx).copied()
1876}
1877
1878fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1879 nodes[from].next.retain(|&n| n != to);
1880 nodes[to].previous.retain(|&n| n != from);
1881}
1882
1883fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1886 for i in (0..=instr_idx).rev() {
1887 if instructions[i].opcode == Opcode::LineNumber
1888 && let Operand::Int(line) = instructions[i].operand
1889 {
1890 return line as usize;
1891 }
1892 }
1893 0
1894}
1895
1896#[cfg(test)]
1897mod tests {
1898 use super::*;
1899 use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1900 use crate::symbol::SymbolRegistry;
1901
1902 fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1904 let mut reg = SymbolRegistry::new();
1905 for &(name, opcode) in commands {
1906 reg.register_command(name.to_string(), opcode, vec![], vec![]);
1907 }
1908 reg
1909 }
1910
1911 fn make_script(
1913 name: &str,
1914 trigger: &str,
1915 id: i32,
1916 instructions: Vec<Instruction>,
1917 ) -> CompiledScript {
1918 let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1919 script.trigger = trigger.to_string();
1920 script.source_path = "test.rs2".to_string();
1921 script.instructions = instructions;
1922 script
1923 }
1924
1925 fn cmd(opcode: i32) -> Instruction {
1927 Instruction::new(Opcode::Command, Operand::Int(opcode))
1928 }
1929
1930 fn line(n: i32) -> Instruction {
1931 Instruction::new(Opcode::LineNumber, Operand::Int(n))
1932 }
1933
1934 fn push_int(v: i32) -> Instruction {
1935 Instruction::push_int(v)
1936 }
1937
1938 fn branch_eq(target: usize) -> Instruction {
1939 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1940 }
1941
1942 fn branch(target: usize) -> Instruction {
1943 Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1944 }
1945
1946 fn ret() -> Instruction {
1947 Instruction::simple(Opcode::Return)
1948 }
1949
1950 fn gosub(script_id: i32) -> Instruction {
1951 Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1952 }
1953
1954 #[test]
1961 fn conditional_setter_with_arg_push() {
1962 let p_finduid_op = 4267;
1965 let p_stopaction_op = 4268;
1966
1967 let registry = registry_with_commands(&[
1968 ("p_finduid", p_finduid_op),
1969 ("p_stopaction", p_stopaction_op),
1970 ]);
1971
1972 let instructions = vec![
1973 line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
1983
1984 let script = make_script("test", "ai_timer", 0, instructions);
1988 let scripts = vec![script];
1989
1990 let mut checker = PointerChecker::new(&scripts, ®istry);
1991 let diags = checker.run();
1992
1993 assert_eq!(
1997 diags.warning_count(),
1998 0,
1999 "conditional setter should provide p_active_player on true branch, got {} warnings",
2000 diags.warning_count()
2001 );
2002 }
2003
2004 #[test]
2005 fn boolean_branches_preserve_conditional_pointer_analysis() {
2006 let registry = registry_with_commands(&[("p_finduid", 4267), ("p_delay", 4268)]);
2007 for (opcode, target, skip) in [(Opcode::BranchIfTrue, 5, 6), (Opcode::BranchIfFalse, 6, 5)]
2008 {
2009 let script = make_script(
2010 "test",
2011 "ai_timer",
2012 0,
2013 vec![
2014 line(1),
2015 push_int(0),
2016 cmd(4267),
2017 Instruction::new(opcode, Operand::JumpTarget(target)),
2018 branch(skip),
2019 cmd(4268),
2020 ret(),
2021 ],
2022 );
2023 assert_eq!(
2024 PointerChecker::new(&[script], ®istry)
2025 .run()
2026 .warning_count(),
2027 0
2028 );
2029 }
2030 let script = make_script(
2031 "test",
2032 "ai_timer",
2033 0,
2034 vec![
2035 line(1),
2036 push_int(0),
2037 cmd(4267),
2038 Instruction::new(Opcode::BranchIfFalse, Operand::JumpTarget(5)),
2039 branch(6),
2040 cmd(4268),
2041 ret(),
2042 ],
2043 );
2044 assert!(
2045 PointerChecker::new(&[script], ®istry)
2046 .run()
2047 .warning_count()
2048 > 0
2049 );
2050 }
2051
2052 #[test]
2061 fn gosub_requires_then_corrupts_same_pointer() {
2062 let p_delay_op = 5001;
2063 let npc_delay_op = 5002;
2064
2065 let registry =
2066 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2067
2068 let proc_script = make_script(
2071 "tackle_success",
2072 "proc",
2073 100,
2074 vec![
2075 line(1),
2076 push_int(0),
2077 cmd(p_delay_op), line(2),
2079 push_int(0),
2080 cmd(npc_delay_op), ret(),
2082 ],
2083 );
2084
2085 let label_script = make_script(
2088 "do_tackle",
2089 "label",
2090 200,
2091 vec![
2092 line(10),
2093 gosub(100), ret(),
2095 ],
2096 );
2097
2098 let scripts = vec![proc_script, label_script];
2099 let mut checker = PointerChecker::new(&scripts, ®istry);
2100 let diags = checker.run();
2101
2102 assert_eq!(
2108 diags.warning_count(),
2109 0,
2110 "gosub that requires-then-corrupts p_active_player should not \
2111 be flagged (engine-tracked pointer), got {} warnings",
2112 diags.warning_count()
2113 );
2114 }
2115
2116 #[test]
2122 fn corruption_before_requirement_is_caught() {
2123 let npc_delay_op = 5002;
2124 let p_delay_op = 5001;
2125
2126 let registry =
2127 registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
2128
2129 let script = make_script(
2132 "bad_order",
2133 "label",
2134 0,
2135 vec![
2136 line(1),
2137 push_int(0),
2138 cmd(npc_delay_op), line(2),
2140 push_int(0),
2141 cmd(p_delay_op), ret(),
2143 ],
2144 );
2145
2146 let scripts = vec![script];
2147 let mut checker = PointerChecker::new(&scripts, ®istry);
2148 let diags = checker.run();
2149
2150 assert!(
2151 diags.warning_count() > 0,
2152 "corruption before requirement should be caught as a warning"
2153 );
2154 }
2155
2156 #[test]
2161 fn uninitialized_pointer_caught() {
2162 let p_delay_op = 5001;
2163
2164 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2165
2166 let script = make_script(
2168 "bad_access",
2169 "ai_timer",
2170 0,
2171 vec![
2172 line(1),
2173 push_int(0),
2174 cmd(p_delay_op), ret(),
2176 ],
2177 );
2178
2179 let scripts = vec![script];
2180 let mut checker = PointerChecker::new(&scripts, ®istry);
2181 let diags = checker.run();
2182
2183 assert!(
2184 diags.warning_count() > 0,
2185 "uninitialized pointer access should be caught"
2186 );
2187 }
2188
2189 #[test]
2199 fn branch_target_on_line_number_still_connects() {
2200 let p_delay_op = 5001;
2201 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2202
2203 let script = make_script(
2219 "target_on_line_number",
2220 "ai_timer",
2221 0,
2222 vec![
2223 line(1),
2224 push_int(1),
2225 push_int(1),
2226 branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
2228 line(2),
2229 push_int(0),
2230 cmd(p_delay_op),
2231 ret(),
2232 ],
2233 );
2234
2235 let scripts = vec![script];
2236 let mut checker = PointerChecker::new(&scripts, ®istry);
2237 let diags = checker.run();
2238
2239 assert!(
2240 diags.warning_count() > 0,
2241 "jump target on LineNumber must still flag uninitialized pointer \
2242 access (got {} warnings)",
2243 diags.warning_count()
2244 );
2245 }
2246
2247 #[test]
2257 fn secondary_requires_and_corrupts_warns_for_static_pointer() {
2258 let last_useitem_op = 4270;
2261 let p_delay_op = 5001;
2262 let registry =
2263 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2264
2265 let callee = make_script(
2267 "consume_useitem",
2268 "label",
2269 100,
2270 vec![
2271 line(1),
2272 cmd(last_useitem_op), line(2),
2274 push_int(0),
2275 cmd(p_delay_op), ret(),
2277 ],
2278 );
2279
2280 let caller = make_script(
2287 "use_on_loc",
2288 "oplocu",
2289 200,
2290 vec![
2291 line(10),
2292 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2293 ],
2294 );
2295
2296 let scripts = vec![callee, caller];
2297 let mut checker = PointerChecker::new(&scripts, ®istry);
2298 let diags = checker.run();
2299
2300 let last_useitem_warnings = diags
2301 .diagnostics()
2302 .iter()
2303 .filter(|d| d.severity == Severity::Warning)
2304 .filter(|d| d.message.contains("last_useitem"))
2305 .count();
2306 assert!(
2307 last_useitem_warnings > 0,
2308 "static-only pointer (last_useitem) should trigger the \
2309 require+corrupt warning at the jump site; got diags: {:?}",
2310 diags
2311 .diagnostics()
2312 .iter()
2313 .map(|d| &d.message)
2314 .collect::<Vec<_>>()
2315 );
2316
2317 assert_eq!(
2318 diags.error_count(),
2319 0,
2320 "pointer-check diagnostics must never raise error severity; got {} errors",
2321 diags.error_count()
2322 );
2323 }
2324
2325 #[test]
2334 fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
2335 let p_delay_op = 5001;
2336 let npc_delay_op = 5002;
2337 let registry =
2338 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2339
2340 let callee = make_script(
2341 "consume_protected",
2342 "proc",
2343 100,
2344 vec![
2345 line(1),
2346 push_int(0),
2347 cmd(p_delay_op), line(2),
2349 push_int(0),
2350 cmd(npc_delay_op), ret(),
2352 ],
2353 );
2354
2355 let caller = make_script(
2357 "do_opnpc",
2358 "opnpc1",
2359 200,
2360 vec![
2361 line(10),
2362 Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2363 ret(),
2364 ],
2365 );
2366
2367 let scripts = vec![callee, caller];
2368 let mut checker = PointerChecker::new(&scripts, ®istry);
2369 let diags = checker.run();
2370
2371 let p_active_player_warnings = diags
2372 .diagnostics()
2373 .iter()
2374 .filter(|d| d.severity == Severity::Warning)
2375 .filter(|d| d.message.contains("p_active_player"))
2376 .count();
2377 assert_eq!(
2378 p_active_player_warnings, 0,
2379 "engine-tracked pointer (p_active_player) must not trigger the \
2380 require+corrupt warning; got {} such warnings",
2381 p_active_player_warnings
2382 );
2383 }
2384
2385 #[test]
2398 fn secondary_varn_requires_active_npc2_not_primary() {
2399 let secondary_varn = Instruction::new(
2404 Opcode::PushVarn,
2405 Operand::Int(1 << 16), );
2407
2408 let proc_script = make_script(
2410 "reads_secondary_varn",
2411 "proc",
2412 100,
2413 vec![
2414 line(1),
2415 secondary_varn,
2416 Instruction::simple(Opcode::PopIntDiscard),
2417 ret(),
2418 ],
2419 );
2420
2421 let caller = make_script(
2428 "gosub_into_proc",
2429 "opplayer1",
2430 200,
2431 vec![line(10), gosub(100), ret()],
2432 );
2433
2434 let scripts = vec![proc_script, caller];
2435 let registry = registry_with_commands(&[]);
2436 let mut checker = PointerChecker::new(&scripts, ®istry);
2437 let diags = checker.run();
2438
2439 let active_npc_primary_warnings = diags
2445 .diagnostics()
2446 .iter()
2447 .filter(|d| d.severity == Severity::Warning)
2448 .filter(|d| d.message.contains("pointer active_npc."))
2449 .count();
2450 assert_eq!(
2451 active_npc_primary_warnings,
2452 0,
2453 "secondary .%var read must not flag primary active_npc at the \
2454 caller; got diags: {:?}",
2455 diags
2456 .diagnostics()
2457 .iter()
2458 .filter(|d| d.severity == Severity::Warning)
2459 .map(|d| &d.message)
2460 .collect::<Vec<_>>()
2461 );
2462
2463 let active_npc2_warnings = diags
2467 .diagnostics()
2468 .iter()
2469 .filter(|d| d.severity == Severity::Warning)
2470 .filter(|d| d.message.contains("pointer .active_npc."))
2471 .count();
2472 assert!(
2473 active_npc2_warnings > 0,
2474 "secondary .%var should route the requirement to active_npc2; \
2475 got no such warning"
2476 );
2477 }
2478
2479 #[test]
2484 fn rewrite_call_site_no_args() {
2485 let got = rewrite_call_site_arg(
2486 "[opnpcu,wantcat1] @civilian_give_runes;",
2487 "@",
2488 "civilian_give_runes",
2489 "last_useitem",
2490 )
2491 .unwrap();
2492 assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2493 }
2494
2495 #[test]
2496 fn rewrite_call_site_with_args() {
2497 let got = rewrite_call_site_arg(
2498 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2499 "@",
2500 "amulet_of_glory_interface",
2501 "last_item",
2502 )
2503 .unwrap();
2504 assert_eq!(
2505 got,
2506 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2507 );
2508 }
2509
2510 #[test]
2511 fn rewrite_call_site_gosub_no_args() {
2512 let got =
2513 rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2514 assert_eq!(got, " ~some_proc(last_useitem);");
2515 }
2516
2517 #[test]
2518 fn rewrite_call_site_empty_arg_list() {
2519 let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2520 assert_eq!(got, "@foo(last_useitem);");
2521 }
2522
2523 #[test]
2524 fn rewrite_header_no_params() {
2525 let got = rewrite_header_add_param(
2526 "[label,civilian_give_runes]",
2527 "civilian_give_runes",
2528 "obj",
2529 "$last_useitem",
2530 )
2531 .unwrap();
2532 assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2533 }
2534
2535 #[test]
2536 fn rewrite_header_with_existing_params() {
2537 let got = rewrite_header_add_param(
2538 "[label,amulet_of_glory_interface](string $message)",
2539 "amulet_of_glory_interface",
2540 "obj",
2541 "$last_item",
2542 )
2543 .unwrap();
2544 assert_eq!(
2545 got,
2546 "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2547 );
2548 }
2549
2550 #[test]
2551 fn rewrite_header_proc_with_return_type() {
2552 let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2555 assert_eq!(got, "[proc,foo](obj $x)(int)");
2556 }
2557
2558 #[test]
2559 fn find_header_line_matches_trigger_and_name() {
2560 let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2561 assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2562 assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2563 assert_eq!(find_header_line(src, "label", "missing"), None);
2564 }
2565
2566 #[test]
2567 fn format_corruptors_shapes() {
2568 assert_eq!(
2569 format_corruptors(&[]),
2570 "calls a delay or subroutine that may supersede it"
2571 );
2572 assert_eq!(
2573 format_corruptors(&[("p_delay".to_string(), 21)]),
2574 "calls `p_delay` at line 21 which may supersede it"
2575 );
2576 assert_eq!(
2577 format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2578 "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2579 );
2580 assert_eq!(
2581 format_corruptors(&[
2582 ("p_delay".to_string(), 21),
2583 ("~chatnpc".to_string(), 11),
2584 ("~objbox".to_string(), 14),
2585 ]),
2586 "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2587 );
2588 assert_eq!(
2590 format_corruptors(&[
2591 ("p_delay".to_string(), 1),
2592 ("~a".to_string(), 2),
2593 ("~b".to_string(), 3),
2594 ("~c".to_string(), 4),
2595 ("~d".to_string(), 5),
2596 ]),
2597 "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2598 );
2599 assert_eq!(
2601 format_corruptors(&[("p_delay".to_string(), 0)]),
2602 "calls `p_delay` which may supersede it"
2603 );
2604 }
2605
2606 #[test]
2607 fn find_matching_close_paren_nested() {
2608 assert_eq!(find_matching_close_paren("()"), Some(1));
2609 assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2610 assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2611 assert_eq!(find_matching_close_paren("("), None);
2612 assert_eq!(find_matching_close_paren("abc"), None);
2613 }
2614
2615 #[test]
2620 fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2621 use std::collections::HashMap;
2622 use std::sync::Arc;
2623
2624 let last_useitem_op = 4270;
2625 let p_delay_op = 5001;
2626 let registry =
2627 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2628
2629 let mut callee = make_script(
2631 "consume_useitem",
2632 "label",
2633 100,
2634 vec![
2635 line(2), cmd(last_useitem_op),
2637 line(3),
2638 push_int(0),
2639 cmd(p_delay_op),
2640 ret(),
2641 ],
2642 );
2643 callee.source_path = "/virt/consume.rs2".to_string();
2644
2645 let mut caller = make_script(
2647 "use_on_loc",
2648 "oplocu",
2649 200,
2650 vec![
2651 line(1),
2652 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2653 ],
2654 );
2655 caller.source_path = "/virt/caller.rs2".to_string();
2656
2657 let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2660 source_cache.insert(
2661 "/virt/caller.rs2".to_string(),
2662 Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2663 );
2664 source_cache.insert(
2665 "/virt/consume.rs2".to_string(),
2666 Arc::new(
2667 "[label,consume_useitem]\n\
2668 last_useitem;\n\
2669 p_delay(0);\n"
2670 .to_string(),
2671 ),
2672 );
2673
2674 let scripts = vec![callee, caller];
2675 let mut checker = PointerChecker::new(&scripts, ®istry);
2676 checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
2677 let diags = checker.run();
2678
2679 let warning = diags
2682 .diagnostics()
2683 .iter()
2684 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2685 .expect("expected a stale-last_useitem warning");
2686
2687 assert_eq!(
2688 warning.help.len(),
2689 1,
2690 "warning should have exactly one Help block, got {}",
2691 warning.help.len()
2692 );
2693 let help = &warning.help[0];
2694 assert!(
2695 help.message.contains("consume_useitem"),
2696 "help message should name the callee, got: {}",
2697 help.message
2698 );
2699 assert!(
2700 help.message.contains("last_useitem"),
2701 "help message should name the pointer, got: {}",
2702 help.message
2703 );
2704
2705 assert_eq!(
2707 help.suggestions.len(),
2708 2,
2709 "help should include both call-site and header suggestions, \
2710 got {}: {:?}",
2711 help.suggestions.len(),
2712 help.suggestions
2713 .iter()
2714 .map(|s| &s.label)
2715 .collect::<Vec<_>>()
2716 );
2717
2718 let caller_sug = help
2720 .suggestions
2721 .iter()
2722 .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2723 .expect("expected a call-site suggestion on the caller file");
2724 assert!(
2725 caller_sug
2726 .replacement
2727 .contains("@consume_useitem(last_useitem)"),
2728 "call-site replacement must pass last_useitem as an arg, got: {}",
2729 caller_sug.replacement
2730 );
2731
2732 let header_sug = help
2734 .suggestions
2735 .iter()
2736 .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2737 .expect("expected a header suggestion on the callee file");
2738 assert!(
2739 header_sug.replacement.contains("(obj $last_useitem)"),
2740 "header replacement must add `obj $last_useitem` param, got: {}",
2741 header_sug.replacement
2742 );
2743
2744 assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2745 }
2746
2747 #[test]
2751 fn secondary_warning_falls_back_to_prose_help_without_source() {
2752 let last_useitem_op = 4270;
2753 let p_delay_op = 5001;
2754 let registry =
2755 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2756
2757 let callee = make_script(
2758 "consume_useitem",
2759 "label",
2760 100,
2761 vec![
2762 line(1),
2763 cmd(last_useitem_op),
2764 line(2),
2765 push_int(0),
2766 cmd(p_delay_op),
2767 ret(),
2768 ],
2769 );
2770 let caller = make_script(
2771 "use_on_loc",
2772 "oplocu",
2773 200,
2774 vec![
2775 line(1),
2776 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2777 ],
2778 );
2779
2780 let scripts = vec![callee, caller];
2781 let mut checker = PointerChecker::new(&scripts, ®istry);
2782 let diags = checker.run();
2784
2785 let warning = diags
2786 .diagnostics()
2787 .iter()
2788 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2789 .expect("warning still fires without source cache");
2790
2791 assert_eq!(warning.help.len(), 1);
2792 let help = &warning.help[0];
2793 assert_eq!(
2794 help.suggestions.len(),
2795 0,
2796 "prose-only help should have no concrete suggestions"
2797 );
2798 assert_eq!(help.applicability, Applicability::Unspecified);
2799 }
2800}