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 | Opcode::PushVarbit if !self.shared.client => {
1140 let pi = if is_secondary_var_operand(&instr.operand) {
1141 PointerType::ActivePlayer2.index()
1142 } else {
1143 PointerType::ActivePlayer.index()
1144 };
1145 analysis.required[pi].push(node_idx);
1146 }
1147
1148 Opcode::PopVarp | Opcode::PopVarbit if !self.shared.client => {
1149 let pi = if is_secondary_var_operand(&instr.operand) {
1150 PointerType::ActivePlayer2.index()
1151 } else {
1152 PointerType::ActivePlayer.index()
1153 };
1154 analysis.required[pi].push(node_idx);
1155 }
1156
1157 Opcode::PushVarn | Opcode::PopVarn if !self.shared.client => {
1158 let pi = if is_secondary_var_operand(&instr.operand) {
1159 PointerType::ActiveNpc2.index()
1160 } else {
1161 PointerType::ActiveNpc.index()
1162 };
1163 analysis.required[pi].push(node_idx);
1164 }
1165
1166 _ => {}
1168 }
1169 }
1170 }
1171
1172 fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
1173 for ptr in holder.required.iter() {
1174 let pi = ptr.index();
1175 analysis.required[pi].push(node_idx);
1176 }
1177 for ptr in holder.set.iter().filter(|_| !holder.conditional_set) {
1178 let pi = ptr.index();
1179 analysis.set_list[pi].push(node_idx);
1180 }
1181 for ptr in holder.corrupted.iter() {
1182 let pi = ptr.index();
1183 analysis.corrupted_list[pi].push(node_idx);
1184 }
1185 }
1186
1187 fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
1203 let script_idx = match self.shared.script_id_to_index.get(&script_id) {
1205 Some(&i) => i,
1206 None => {
1207 return PointerHolder::default();
1208 }
1209 };
1210 let script_name = self.scripts.get(script_idx).name.clone();
1211
1212 if let Some(holder) = self.script_pointers.get(&script_name) {
1214 return holder.clone();
1215 }
1216
1217 if self.pending_scripts.contains(&script_name) {
1219 return PointerHolder::default();
1220 }
1221 self.pending_scripts.insert(script_name.clone());
1222
1223 self.ensure_analysis(&script_name);
1225
1226 let mut holder = PointerHolder::default();
1227
1228 if let Some(analysis) = self.script_analyses.get(&script_name) {
1229 for &ptr in &PointerType::ALL {
1230 let pi = ptr.index();
1231
1232 let requires = !analysis.required[pi].is_empty();
1238 let has_returns = !analysis.returns.is_empty();
1239 if !requires && !has_returns {
1240 continue;
1241 }
1242 let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
1243
1244 if requires {
1246 let path = Self::find_edge_path_static(
1247 &analysis.nodes,
1248 &analysis.required[pi],
1249 |node_idx| node_idx == 0,
1250 &set_blocked,
1251 );
1252 if path.is_some() {
1253 holder.required.insert(ptr);
1254 }
1255 }
1256
1257 if has_returns {
1258 let corrupted_nodes: HashSet<usize> =
1259 analysis.corrupted_list[pi].iter().copied().collect();
1260
1261 let path = Self::find_edge_path_static(
1264 &analysis.nodes,
1265 &analysis.returns,
1266 |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1267 &set_blocked,
1268 );
1269 if path.is_none() {
1270 holder.set.insert(ptr);
1271 }
1272
1273 if !corrupted_nodes.is_empty() {
1275 let path = Self::find_edge_path_static(
1276 &analysis.nodes,
1277 &analysis.returns,
1278 |node_idx| corrupted_nodes.contains(&node_idx),
1279 &set_blocked,
1280 );
1281 if path.is_some() {
1282 holder.corrupted.insert(ptr);
1283 }
1284 }
1285 }
1286 }
1287 }
1288
1289 self.pending_scripts.remove(&script_name);
1290
1291 self.script_pointers
1292 .insert(script_name.clone(), holder.clone());
1293 holder
1294 }
1295
1296 fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1306 let callee = self.scripts.get(callee_idx);
1307 let analysis = match self.script_analyses.get(&callee.name) {
1308 Some(a) => a,
1309 None => return Vec::new(),
1310 };
1311 let ptr_idx = ptr.index();
1312 let mut seen: HashSet<(String, usize)> = HashSet::new();
1313 let mut result: Vec<(String, usize)> = Vec::new();
1314
1315 for &node_idx in &analysis.corrupted_list[ptr_idx] {
1316 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1317 Some(i) => i,
1318 None => continue,
1319 };
1320 let instr = &callee.instructions[instr_idx];
1321 let line = resolve_line(&callee.instructions, instr_idx);
1322
1323 let name = match instr.opcode {
1324 Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
1325 Some(n) => n,
1326 None => continue,
1327 },
1328 Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1329 Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
1330 Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
1331 .map(|s| format!("~{}", s))
1332 .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
1333 None => continue,
1334 },
1335 _ => continue,
1336 },
1337 _ => continue,
1341 };
1342
1343 let key = (name.clone(), line);
1344 if seen.insert(key) {
1345 result.push((name, line));
1346 }
1347 }
1348
1349 result
1350 }
1351
1352 fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
1353 match &instr.operand {
1354 Operand::Int(encoded) => {
1355 let opcode = encoded & 0xFFFF;
1356 let secondary = (encoded >> 16) & 1;
1357 let base_name = self.shared.opcode_to_name.get(&opcode)?;
1358 if secondary == 1 {
1359 Some(format!(".{}", base_name))
1360 } else {
1361 Some(base_name.clone())
1362 }
1363 }
1364 Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
1365 _ => None,
1366 }
1367 }
1368
1369 fn build_rule_a_help(
1381 &mut self,
1382 ptr: PointerType,
1383 caller_source_path: &str,
1384 caller_line: usize,
1385 node_idx: usize,
1386 caller_script_idx: usize,
1387 ) -> Option<Help> {
1388 let (is_gosub, script_id) = {
1391 let caller = self.scripts.get(caller_script_idx);
1392 let analysis = self.script_analyses.get(&caller.name)?;
1393 let instr_idx = analysis.nodes[node_idx].instruction_index?;
1394 let instr = &caller.instructions[instr_idx];
1395 match instr.opcode {
1397 Opcode::Jump | Opcode::JumpWithParams => (
1398 false,
1399 match &instr.operand {
1400 Operand::Int(id) => *id,
1401 _ => return None,
1402 },
1403 ),
1404 Opcode::Gosub | Opcode::GosubWithParams => (
1405 true,
1406 match &instr.operand {
1407 Operand::Int(id) => *id,
1408 _ => return None,
1409 },
1410 ),
1411 _ => return None,
1412 }
1413 };
1414
1415 let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
1416 let callee_name = self.scripts.get(callee_idx).name.clone();
1420 self.ensure_analysis(&callee_name);
1421
1422 let callee = self.scripts.get(callee_idx);
1423 let callee_source = callee.source_path.clone();
1424
1425 let first_body_line = callee
1433 .instructions
1434 .iter()
1435 .find_map(|i| match (i.opcode, &i.operand) {
1436 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1437 _ => None,
1438 })
1439 .unwrap_or(1);
1440 let callee_trigger = callee.trigger.clone();
1441 let callee_short_early = callee
1442 .name
1443 .trim_start_matches('[')
1444 .trim_end_matches(']')
1445 .split_once(',')
1446 .map(|(_, n)| n.to_string())
1447 .unwrap_or_else(|| callee.name.clone());
1448 let callee_header_line = self
1449 .source_cache
1450 .and_then(|c| c.get(&callee_source))
1451 .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
1452 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1453
1454 let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
1456 let param_name = format!("${}", ptr_cmd);
1457
1458 let callee_short = callee
1459 .name
1460 .trim_start_matches('[')
1461 .trim_end_matches(']')
1462 .split_once(',')
1463 .map(|(_, n)| n.to_string())
1464 .unwrap_or_else(|| callee.name.clone());
1465
1466 let arrow = if is_gosub { "~" } else { "@" };
1467
1468 let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1473 let corruptor_phrase = format_corruptors(&corruptors);
1474
1475 let message = format!(
1476 "`{callee}` reads `{ptr}` then {phrase}; the script still \
1477 compiles and runs, but the reference is brittle to reorder. \
1478 Consider capturing `{ptr}` at the call site and threading it \
1479 through `{callee}` as an `{ty} {pname}` parameter so the \
1480 value is explicit and stable.",
1481 callee = callee_short,
1482 ptr = ptr_cmd,
1483 phrase = corruptor_phrase,
1484 ty = param_type,
1485 pname = param_name,
1486 );
1487
1488 let cache = match self.source_cache {
1489 Some(c) => c,
1490 None => {
1491 return Some(Help {
1493 message,
1494 suggestions: Vec::new(),
1495 applicability: Applicability::Unspecified,
1496 });
1497 }
1498 };
1499
1500 let mut suggestions = Vec::new();
1501
1502 if let Some(src) = cache.get(caller_source_path)
1505 && let Some(line_text) = nth_source_line(&src, caller_line)
1506 && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1507 {
1508 suggestions.push(Suggestion {
1509 file: PathBuf::from(caller_source_path),
1510 line_range: (caller_line, caller_line),
1511 replacement: rewritten,
1512 label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1513 });
1514 }
1515
1516 if let Some(src) = cache.get(&callee_source)
1518 && let Some(header_text) = nth_source_line(&src, callee_header_line)
1519 && let Some(rewritten) =
1520 rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
1521 {
1522 suggestions.push(Suggestion {
1523 file: PathBuf::from(&callee_source),
1524 line_range: (callee_header_line, callee_header_line),
1525 replacement: rewritten,
1526 label: Some(format!(
1527 "at the `{}` header (add `{} {}`)",
1528 callee_short, param_type, param_name
1529 )),
1530 });
1531 }
1532
1533 Some(Help {
1534 message,
1535 suggestions,
1536 applicability: Applicability::MaybeIncorrect,
1540 })
1541 }
1542}
1543
1544fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1549 if !nodes[from].next.contains(&to) {
1550 nodes[from].next.push(to);
1551 }
1552 if !nodes[to].previous.contains(&from) {
1553 nodes[to].previous.push(from);
1554 }
1555}
1556
1557fn is_static_only_pointer(ptr: PointerType) -> bool {
1570 use PointerType::*;
1571 matches!(
1572 ptr,
1573 FindPlayer
1574 | FindNpc
1575 | FindLoc
1576 | FindObj
1577 | FindDb
1578 | LastCom
1579 | LastInt
1580 | LastItem
1581 | LastSlot
1582 | LastTargetslot
1583 | LastUseitem
1584 | LastUseslot
1585 )
1586}
1587
1588fn short_script_name(full_name: &str) -> Option<String> {
1591 full_name
1592 .trim_start_matches('[')
1593 .trim_end_matches(']')
1594 .split_once(',')
1595 .map(|(_, n)| n.to_string())
1596}
1597
1598fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1603 if corruptors.is_empty() {
1604 return "calls a delay or subroutine that may supersede it".to_string();
1605 }
1606
1607 const MAX: usize = 3;
1608 let shown: Vec<String> = corruptors
1609 .iter()
1610 .take(MAX)
1611 .map(|(name, line)| {
1612 if *line > 0 {
1613 format!("`{}` at line {}", name, line)
1614 } else {
1615 format!("`{}`", name)
1616 }
1617 })
1618 .collect();
1619
1620 let suffix = if corruptors.len() > MAX {
1621 format!(" (and {} more)", corruptors.len() - MAX)
1622 } else {
1623 String::new()
1624 };
1625
1626 let joined = match shown.len() {
1627 1 => shown[0].clone(),
1628 2 => format!("{} and {}", shown[0], shown[1]),
1629 _ => {
1630 let head = shown[..shown.len() - 1].join(", ");
1631 format!("{}, and {}", head, shown[shown.len() - 1])
1632 }
1633 };
1634
1635 format!("calls {}{} which may supersede it", joined, suffix)
1636}
1637
1638fn pointer_param_type(ptr: PointerType) -> &'static str {
1647 use PointerType::*;
1648 match ptr {
1649 LastUseitem | LastItem => "obj",
1650 LastCom => "component",
1651 _ => "int",
1652 }
1653}
1654
1655fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1657 if line_no == 0 {
1658 return None;
1659 }
1660 text.lines().nth(line_no - 1)
1661}
1662
1663fn rewrite_call_site_arg(
1672 line: &str,
1673 arrow: &str,
1674 callee_short: &str,
1675 ptr_cmd: &str,
1676) -> Option<String> {
1677 let needle = format!("{}{}", arrow, callee_short);
1680 let start = line.find(&needle)?;
1681 let after_name = start + needle.len();
1682 let tail = &line[after_name..];
1683
1684 let first_non_ws = tail.chars().next();
1686 if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1687 || tail.trim_start().is_empty()
1688 {
1689 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1690 out.push_str(&line[..after_name]);
1691 out.push('(');
1692 out.push_str(ptr_cmd);
1693 out.push(')');
1694 out.push_str(tail);
1695 return Some(out);
1696 }
1697
1698 if tail.trim_start().starts_with('(') {
1701 let open_rel = tail.find('(')?;
1702 let abs_open = after_name + open_rel;
1703 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1704 let abs_close = abs_open + close_rel;
1705
1706 let inside = line[abs_open + 1..abs_close].trim();
1708 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1709 out.push_str(&line[..abs_close]);
1710 if inside.is_empty() {
1711 out.push_str(ptr_cmd);
1712 } else {
1713 out.push_str(", ");
1714 out.push_str(ptr_cmd);
1715 }
1716 out.push_str(&line[abs_close..]);
1717 return Some(out);
1718 }
1719
1720 None
1721}
1722
1723fn rewrite_header_add_param(
1729 line: &str,
1730 callee_short: &str,
1731 param_type: &str,
1732 param_name: &str,
1733) -> Option<String> {
1734 let needle = format!(",{}]", callee_short);
1737 let subject_end = line.find(&needle)?;
1738 let after_bracket = subject_end + needle.len();
1739
1740 let remainder = &line[after_bracket..];
1741 let added = format!("{} {}", param_type, param_name);
1742
1743 if !remainder.trim_start().starts_with('(') {
1745 let mut out = String::with_capacity(line.len() + added.len() + 2);
1746 out.push_str(&line[..after_bracket]);
1747 out.push('(');
1748 out.push_str(&added);
1749 out.push(')');
1750 out.push_str(remainder);
1751 return Some(out);
1752 }
1753
1754 let open_rel = remainder.find('(')?;
1756 let abs_open = after_bracket + open_rel;
1757 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1758 let abs_close = abs_open + close_rel;
1759 let inside = line[abs_open + 1..abs_close].trim();
1760
1761 let mut out = String::with_capacity(line.len() + added.len() + 2);
1762 out.push_str(&line[..abs_close]);
1763 if inside.is_empty() {
1764 out.push_str(&added);
1765 } else {
1766 out.push_str(", ");
1767 out.push_str(&added);
1768 }
1769 out.push_str(&line[abs_close..]);
1770 Some(out)
1771}
1772
1773fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1777 let prefix = format!("[{},{}]", trigger, name);
1778 let prefix_with_params = format!("[{},{}](", trigger, name);
1779 for (i, line) in src.lines().enumerate() {
1780 let trimmed = line.trim_start();
1781 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1782 return Some(i + 1);
1783 }
1784 }
1785 None
1786}
1787
1788fn find_matching_close_paren(s: &str) -> Option<usize> {
1792 let bytes = s.as_bytes();
1793 if bytes.first().copied() != Some(b'(') {
1794 return None;
1795 }
1796 let mut depth = 0i32;
1797 for (i, &b) in bytes.iter().enumerate() {
1798 match b {
1799 b'(' => depth += 1,
1800 b')' => {
1801 depth -= 1;
1802 if depth == 0 {
1803 return Some(i);
1804 }
1805 }
1806 _ => {}
1807 }
1808 }
1809 None
1810}
1811
1812fn is_secondary_var_operand(operand: &Operand) -> bool {
1818 match operand {
1819 Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1820 _ => false,
1821 }
1822}
1823
1824fn resolve_target_node(
1830 mut target_idx: usize,
1831 instructions: &[Instruction],
1832 instr_to_node: &HashMap<usize, usize>,
1833) -> Option<usize> {
1834 while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1835 target_idx += 1;
1836 }
1837 instr_to_node.get(&target_idx).copied()
1838}
1839
1840fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1841 nodes[from].next.retain(|&n| n != to);
1842 nodes[to].previous.retain(|&n| n != from);
1843}
1844
1845fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1848 for i in (0..=instr_idx).rev() {
1849 if instructions[i].opcode == Opcode::LineNumber
1850 && let Operand::Int(line) = instructions[i].operand
1851 {
1852 return line as usize;
1853 }
1854 }
1855 0
1856}
1857
1858#[cfg(test)]
1859mod tests {
1860 use super::*;
1861 use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1862 use crate::symbol::SymbolRegistry;
1863
1864 fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1866 let mut reg = SymbolRegistry::new();
1867 for &(name, opcode) in commands {
1868 reg.register_command(name.to_string(), opcode, vec![], vec![]);
1869 }
1870 reg
1871 }
1872
1873 fn make_script(
1875 name: &str,
1876 trigger: &str,
1877 id: i32,
1878 instructions: Vec<Instruction>,
1879 ) -> CompiledScript {
1880 let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1881 script.trigger = trigger.to_string();
1882 script.source_path = "test.rs2".to_string();
1883 script.instructions = instructions;
1884 script
1885 }
1886
1887 fn cmd(opcode: i32) -> Instruction {
1889 Instruction::new(Opcode::Command, Operand::Int(opcode))
1890 }
1891
1892 fn line(n: i32) -> Instruction {
1893 Instruction::new(Opcode::LineNumber, Operand::Int(n))
1894 }
1895
1896 fn push_int(v: i32) -> Instruction {
1897 Instruction::push_int(v)
1898 }
1899
1900 fn branch_eq(target: usize) -> Instruction {
1901 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1902 }
1903
1904 fn branch(target: usize) -> Instruction {
1905 Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1906 }
1907
1908 fn ret() -> Instruction {
1909 Instruction::simple(Opcode::Return)
1910 }
1911
1912 fn gosub(script_id: i32) -> Instruction {
1913 Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1914 }
1915
1916 #[test]
1923 fn conditional_setter_with_arg_push() {
1924 let p_finduid_op = 4267;
1927 let p_stopaction_op = 4268;
1928
1929 let registry = registry_with_commands(&[
1930 ("p_finduid", p_finduid_op),
1931 ("p_stopaction", p_stopaction_op),
1932 ]);
1933
1934 let instructions = vec![
1935 line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
1945
1946 let script = make_script("test", "ai_timer", 0, instructions);
1950 let scripts = vec![script];
1951
1952 let mut checker = PointerChecker::new(&scripts, ®istry);
1953 let diags = checker.run();
1954
1955 assert_eq!(
1959 diags.warning_count(),
1960 0,
1961 "conditional setter should provide p_active_player on true branch, got {} warnings",
1962 diags.warning_count()
1963 );
1964 }
1965
1966 #[test]
1967 fn boolean_branches_preserve_conditional_pointer_analysis() {
1968 let registry = registry_with_commands(&[("p_finduid", 4267), ("p_delay", 4268)]);
1969 for (opcode, target, skip) in [(Opcode::BranchIfTrue, 5, 6), (Opcode::BranchIfFalse, 6, 5)]
1970 {
1971 let script = make_script(
1972 "test",
1973 "ai_timer",
1974 0,
1975 vec![
1976 line(1),
1977 push_int(0),
1978 cmd(4267),
1979 Instruction::new(opcode, Operand::JumpTarget(target)),
1980 branch(skip),
1981 cmd(4268),
1982 ret(),
1983 ],
1984 );
1985 assert_eq!(
1986 PointerChecker::new(&[script], ®istry)
1987 .run()
1988 .warning_count(),
1989 0
1990 );
1991 }
1992 let script = make_script(
1993 "test",
1994 "ai_timer",
1995 0,
1996 vec![
1997 line(1),
1998 push_int(0),
1999 cmd(4267),
2000 Instruction::new(Opcode::BranchIfFalse, Operand::JumpTarget(5)),
2001 branch(6),
2002 cmd(4268),
2003 ret(),
2004 ],
2005 );
2006 assert!(
2007 PointerChecker::new(&[script], ®istry)
2008 .run()
2009 .warning_count()
2010 > 0
2011 );
2012 }
2013
2014 #[test]
2023 fn gosub_requires_then_corrupts_same_pointer() {
2024 let p_delay_op = 5001;
2025 let npc_delay_op = 5002;
2026
2027 let registry =
2028 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2029
2030 let proc_script = make_script(
2033 "tackle_success",
2034 "proc",
2035 100,
2036 vec![
2037 line(1),
2038 push_int(0),
2039 cmd(p_delay_op), line(2),
2041 push_int(0),
2042 cmd(npc_delay_op), ret(),
2044 ],
2045 );
2046
2047 let label_script = make_script(
2050 "do_tackle",
2051 "label",
2052 200,
2053 vec![
2054 line(10),
2055 gosub(100), ret(),
2057 ],
2058 );
2059
2060 let scripts = vec![proc_script, label_script];
2061 let mut checker = PointerChecker::new(&scripts, ®istry);
2062 let diags = checker.run();
2063
2064 assert_eq!(
2070 diags.warning_count(),
2071 0,
2072 "gosub that requires-then-corrupts p_active_player should not \
2073 be flagged (engine-tracked pointer), got {} warnings",
2074 diags.warning_count()
2075 );
2076 }
2077
2078 #[test]
2084 fn corruption_before_requirement_is_caught() {
2085 let npc_delay_op = 5002;
2086 let p_delay_op = 5001;
2087
2088 let registry =
2089 registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
2090
2091 let script = make_script(
2094 "bad_order",
2095 "label",
2096 0,
2097 vec![
2098 line(1),
2099 push_int(0),
2100 cmd(npc_delay_op), line(2),
2102 push_int(0),
2103 cmd(p_delay_op), ret(),
2105 ],
2106 );
2107
2108 let scripts = vec![script];
2109 let mut checker = PointerChecker::new(&scripts, ®istry);
2110 let diags = checker.run();
2111
2112 assert!(
2113 diags.warning_count() > 0,
2114 "corruption before requirement should be caught as a warning"
2115 );
2116 }
2117
2118 #[test]
2123 fn uninitialized_pointer_caught() {
2124 let p_delay_op = 5001;
2125
2126 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2127
2128 let script = make_script(
2130 "bad_access",
2131 "ai_timer",
2132 0,
2133 vec![
2134 line(1),
2135 push_int(0),
2136 cmd(p_delay_op), ret(),
2138 ],
2139 );
2140
2141 let scripts = vec![script];
2142 let mut checker = PointerChecker::new(&scripts, ®istry);
2143 let diags = checker.run();
2144
2145 assert!(
2146 diags.warning_count() > 0,
2147 "uninitialized pointer access should be caught"
2148 );
2149 }
2150
2151 #[test]
2161 fn branch_target_on_line_number_still_connects() {
2162 let p_delay_op = 5001;
2163 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2164
2165 let script = make_script(
2181 "target_on_line_number",
2182 "ai_timer",
2183 0,
2184 vec![
2185 line(1),
2186 push_int(1),
2187 push_int(1),
2188 branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
2190 line(2),
2191 push_int(0),
2192 cmd(p_delay_op),
2193 ret(),
2194 ],
2195 );
2196
2197 let scripts = vec![script];
2198 let mut checker = PointerChecker::new(&scripts, ®istry);
2199 let diags = checker.run();
2200
2201 assert!(
2202 diags.warning_count() > 0,
2203 "jump target on LineNumber must still flag uninitialized pointer \
2204 access (got {} warnings)",
2205 diags.warning_count()
2206 );
2207 }
2208
2209 #[test]
2219 fn secondary_requires_and_corrupts_warns_for_static_pointer() {
2220 let last_useitem_op = 4270;
2223 let p_delay_op = 5001;
2224 let registry =
2225 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2226
2227 let callee = make_script(
2229 "consume_useitem",
2230 "label",
2231 100,
2232 vec![
2233 line(1),
2234 cmd(last_useitem_op), line(2),
2236 push_int(0),
2237 cmd(p_delay_op), ret(),
2239 ],
2240 );
2241
2242 let caller = make_script(
2249 "use_on_loc",
2250 "oplocu",
2251 200,
2252 vec![
2253 line(10),
2254 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2255 ],
2256 );
2257
2258 let scripts = vec![callee, caller];
2259 let mut checker = PointerChecker::new(&scripts, ®istry);
2260 let diags = checker.run();
2261
2262 let last_useitem_warnings = diags
2263 .diagnostics()
2264 .iter()
2265 .filter(|d| d.severity == Severity::Warning)
2266 .filter(|d| d.message.contains("last_useitem"))
2267 .count();
2268 assert!(
2269 last_useitem_warnings > 0,
2270 "static-only pointer (last_useitem) should trigger the \
2271 require+corrupt warning at the jump site; got diags: {:?}",
2272 diags
2273 .diagnostics()
2274 .iter()
2275 .map(|d| &d.message)
2276 .collect::<Vec<_>>()
2277 );
2278
2279 assert_eq!(
2280 diags.error_count(),
2281 0,
2282 "pointer-check diagnostics must never raise error severity; got {} errors",
2283 diags.error_count()
2284 );
2285 }
2286
2287 #[test]
2296 fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
2297 let p_delay_op = 5001;
2298 let npc_delay_op = 5002;
2299 let registry =
2300 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2301
2302 let callee = make_script(
2303 "consume_protected",
2304 "proc",
2305 100,
2306 vec![
2307 line(1),
2308 push_int(0),
2309 cmd(p_delay_op), line(2),
2311 push_int(0),
2312 cmd(npc_delay_op), ret(),
2314 ],
2315 );
2316
2317 let caller = make_script(
2319 "do_opnpc",
2320 "opnpc1",
2321 200,
2322 vec![
2323 line(10),
2324 Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2325 ret(),
2326 ],
2327 );
2328
2329 let scripts = vec![callee, caller];
2330 let mut checker = PointerChecker::new(&scripts, ®istry);
2331 let diags = checker.run();
2332
2333 let p_active_player_warnings = diags
2334 .diagnostics()
2335 .iter()
2336 .filter(|d| d.severity == Severity::Warning)
2337 .filter(|d| d.message.contains("p_active_player"))
2338 .count();
2339 assert_eq!(
2340 p_active_player_warnings, 0,
2341 "engine-tracked pointer (p_active_player) must not trigger the \
2342 require+corrupt warning; got {} such warnings",
2343 p_active_player_warnings
2344 );
2345 }
2346
2347 #[test]
2360 fn secondary_varn_requires_active_npc2_not_primary() {
2361 let secondary_varn = Instruction::new(
2366 Opcode::PushVarn,
2367 Operand::Int(1 << 16), );
2369
2370 let proc_script = make_script(
2372 "reads_secondary_varn",
2373 "proc",
2374 100,
2375 vec![
2376 line(1),
2377 secondary_varn,
2378 Instruction::simple(Opcode::PopIntDiscard),
2379 ret(),
2380 ],
2381 );
2382
2383 let caller = make_script(
2390 "gosub_into_proc",
2391 "opplayer1",
2392 200,
2393 vec![line(10), gosub(100), ret()],
2394 );
2395
2396 let scripts = vec![proc_script, caller];
2397 let registry = registry_with_commands(&[]);
2398 let mut checker = PointerChecker::new(&scripts, ®istry);
2399 let diags = checker.run();
2400
2401 let active_npc_primary_warnings = diags
2407 .diagnostics()
2408 .iter()
2409 .filter(|d| d.severity == Severity::Warning)
2410 .filter(|d| d.message.contains("pointer active_npc."))
2411 .count();
2412 assert_eq!(
2413 active_npc_primary_warnings,
2414 0,
2415 "secondary .%var read must not flag primary active_npc at the \
2416 caller; got diags: {:?}",
2417 diags
2418 .diagnostics()
2419 .iter()
2420 .filter(|d| d.severity == Severity::Warning)
2421 .map(|d| &d.message)
2422 .collect::<Vec<_>>()
2423 );
2424
2425 let active_npc2_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!(
2435 active_npc2_warnings > 0,
2436 "secondary .%var should route the requirement to active_npc2; \
2437 got no such warning"
2438 );
2439 }
2440
2441 #[test]
2446 fn rewrite_call_site_no_args() {
2447 let got = rewrite_call_site_arg(
2448 "[opnpcu,wantcat1] @civilian_give_runes;",
2449 "@",
2450 "civilian_give_runes",
2451 "last_useitem",
2452 )
2453 .unwrap();
2454 assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2455 }
2456
2457 #[test]
2458 fn rewrite_call_site_with_args() {
2459 let got = rewrite_call_site_arg(
2460 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2461 "@",
2462 "amulet_of_glory_interface",
2463 "last_item",
2464 )
2465 .unwrap();
2466 assert_eq!(
2467 got,
2468 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2469 );
2470 }
2471
2472 #[test]
2473 fn rewrite_call_site_gosub_no_args() {
2474 let got =
2475 rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2476 assert_eq!(got, " ~some_proc(last_useitem);");
2477 }
2478
2479 #[test]
2480 fn rewrite_call_site_empty_arg_list() {
2481 let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2482 assert_eq!(got, "@foo(last_useitem);");
2483 }
2484
2485 #[test]
2486 fn rewrite_header_no_params() {
2487 let got = rewrite_header_add_param(
2488 "[label,civilian_give_runes]",
2489 "civilian_give_runes",
2490 "obj",
2491 "$last_useitem",
2492 )
2493 .unwrap();
2494 assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2495 }
2496
2497 #[test]
2498 fn rewrite_header_with_existing_params() {
2499 let got = rewrite_header_add_param(
2500 "[label,amulet_of_glory_interface](string $message)",
2501 "amulet_of_glory_interface",
2502 "obj",
2503 "$last_item",
2504 )
2505 .unwrap();
2506 assert_eq!(
2507 got,
2508 "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2509 );
2510 }
2511
2512 #[test]
2513 fn rewrite_header_proc_with_return_type() {
2514 let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2517 assert_eq!(got, "[proc,foo](obj $x)(int)");
2518 }
2519
2520 #[test]
2521 fn find_header_line_matches_trigger_and_name() {
2522 let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2523 assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2524 assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2525 assert_eq!(find_header_line(src, "label", "missing"), None);
2526 }
2527
2528 #[test]
2529 fn format_corruptors_shapes() {
2530 assert_eq!(
2531 format_corruptors(&[]),
2532 "calls a delay or subroutine that may supersede it"
2533 );
2534 assert_eq!(
2535 format_corruptors(&[("p_delay".to_string(), 21)]),
2536 "calls `p_delay` at line 21 which may supersede it"
2537 );
2538 assert_eq!(
2539 format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2540 "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2541 );
2542 assert_eq!(
2543 format_corruptors(&[
2544 ("p_delay".to_string(), 21),
2545 ("~chatnpc".to_string(), 11),
2546 ("~objbox".to_string(), 14),
2547 ]),
2548 "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2549 );
2550 assert_eq!(
2552 format_corruptors(&[
2553 ("p_delay".to_string(), 1),
2554 ("~a".to_string(), 2),
2555 ("~b".to_string(), 3),
2556 ("~c".to_string(), 4),
2557 ("~d".to_string(), 5),
2558 ]),
2559 "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2560 );
2561 assert_eq!(
2563 format_corruptors(&[("p_delay".to_string(), 0)]),
2564 "calls `p_delay` which may supersede it"
2565 );
2566 }
2567
2568 #[test]
2569 fn find_matching_close_paren_nested() {
2570 assert_eq!(find_matching_close_paren("()"), Some(1));
2571 assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2572 assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2573 assert_eq!(find_matching_close_paren("("), None);
2574 assert_eq!(find_matching_close_paren("abc"), None);
2575 }
2576
2577 #[test]
2582 fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2583 use std::collections::HashMap;
2584 use std::sync::Arc;
2585
2586 let last_useitem_op = 4270;
2587 let p_delay_op = 5001;
2588 let registry =
2589 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2590
2591 let mut callee = make_script(
2593 "consume_useitem",
2594 "label",
2595 100,
2596 vec![
2597 line(2), cmd(last_useitem_op),
2599 line(3),
2600 push_int(0),
2601 cmd(p_delay_op),
2602 ret(),
2603 ],
2604 );
2605 callee.source_path = "/virt/consume.rs2".to_string();
2606
2607 let mut caller = make_script(
2609 "use_on_loc",
2610 "oplocu",
2611 200,
2612 vec![
2613 line(1),
2614 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2615 ],
2616 );
2617 caller.source_path = "/virt/caller.rs2".to_string();
2618
2619 let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2622 source_cache.insert(
2623 "/virt/caller.rs2".to_string(),
2624 Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2625 );
2626 source_cache.insert(
2627 "/virt/consume.rs2".to_string(),
2628 Arc::new(
2629 "[label,consume_useitem]\n\
2630 last_useitem;\n\
2631 p_delay(0);\n"
2632 .to_string(),
2633 ),
2634 );
2635
2636 let scripts = vec![callee, caller];
2637 let mut checker = PointerChecker::new(&scripts, ®istry);
2638 checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
2639 let diags = checker.run();
2640
2641 let warning = diags
2644 .diagnostics()
2645 .iter()
2646 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2647 .expect("expected a stale-last_useitem warning");
2648
2649 assert_eq!(
2650 warning.help.len(),
2651 1,
2652 "warning should have exactly one Help block, got {}",
2653 warning.help.len()
2654 );
2655 let help = &warning.help[0];
2656 assert!(
2657 help.message.contains("consume_useitem"),
2658 "help message should name the callee, got: {}",
2659 help.message
2660 );
2661 assert!(
2662 help.message.contains("last_useitem"),
2663 "help message should name the pointer, got: {}",
2664 help.message
2665 );
2666
2667 assert_eq!(
2669 help.suggestions.len(),
2670 2,
2671 "help should include both call-site and header suggestions, \
2672 got {}: {:?}",
2673 help.suggestions.len(),
2674 help.suggestions
2675 .iter()
2676 .map(|s| &s.label)
2677 .collect::<Vec<_>>()
2678 );
2679
2680 let caller_sug = help
2682 .suggestions
2683 .iter()
2684 .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2685 .expect("expected a call-site suggestion on the caller file");
2686 assert!(
2687 caller_sug
2688 .replacement
2689 .contains("@consume_useitem(last_useitem)"),
2690 "call-site replacement must pass last_useitem as an arg, got: {}",
2691 caller_sug.replacement
2692 );
2693
2694 let header_sug = help
2696 .suggestions
2697 .iter()
2698 .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2699 .expect("expected a header suggestion on the callee file");
2700 assert!(
2701 header_sug.replacement.contains("(obj $last_useitem)"),
2702 "header replacement must add `obj $last_useitem` param, got: {}",
2703 header_sug.replacement
2704 );
2705
2706 assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2707 }
2708
2709 #[test]
2713 fn secondary_warning_falls_back_to_prose_help_without_source() {
2714 let last_useitem_op = 4270;
2715 let p_delay_op = 5001;
2716 let registry =
2717 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2718
2719 let callee = make_script(
2720 "consume_useitem",
2721 "label",
2722 100,
2723 vec![
2724 line(1),
2725 cmd(last_useitem_op),
2726 line(2),
2727 push_int(0),
2728 cmd(p_delay_op),
2729 ret(),
2730 ],
2731 );
2732 let caller = make_script(
2733 "use_on_loc",
2734 "oplocu",
2735 200,
2736 vec![
2737 line(1),
2738 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2739 ],
2740 );
2741
2742 let scripts = vec![callee, caller];
2743 let mut checker = PointerChecker::new(&scripts, ®istry);
2744 let diags = checker.run();
2746
2747 let warning = diags
2748 .diagnostics()
2749 .iter()
2750 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2751 .expect("warning still fires without source cache");
2752
2753 assert_eq!(warning.help.len(), 1);
2754 let help = &warning.help[0];
2755 assert_eq!(
2756 help.suggestions.len(),
2757 0,
2758 "prose-only help should have no concrete suggestions"
2759 );
2760 assert_eq!(help.applicability, Applicability::Unspecified);
2761 }
2762}