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 recursive_scripts: HashSet<String>,
233}
234
235impl SharedMaps {
236 fn build<'b>(
240 idents: impl Iterator<Item = (i32, &'b str)>,
241 registry: &SymbolRegistry,
242 client: bool,
243 ) -> Self {
244 let mut opcode_to_name = HashMap::new();
246 for (name, sym) in ®istry.commands {
247 if let SymbolKind::Command { opcode, .. } = &sym.kind {
248 opcode_to_name.insert(*opcode, name.to_lowercase());
249 }
250 }
251
252 let mut script_id_to_index = HashMap::new();
256 let mut script_name_to_index = HashMap::new();
257 for (i, (id, name)) in idents.enumerate() {
258 script_id_to_index.insert(id, i);
259 script_name_to_index.entry(name.to_string()).or_insert(i);
260 }
261
262 let mut overlay_interfaces = HashSet::new();
266 for (name, entry) in ®istry.entity_ids {
267 if entry
268 .variants
269 .iter()
270 .any(|(t, _)| *t == Type::OverlayInterface)
271 {
272 overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
273 }
274 }
275
276 SharedMaps {
277 client,
278 cmd_pointers: registry.profile.as_ref().map_or_else(
279 || {
280 if client {
281 clientscript::command_pointers(registry)
282 } else {
283 command_pointers()
284 }
285 },
286 |profile| profile.command_pointers.clone(),
287 ),
288 opcode_to_name,
289 script_id_to_index,
290 script_name_to_index,
291 overlay_interfaces,
292 }
293 }
294}
295
296impl<'a> PointerChecker<'a> {
297 pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
298 let shared = std::sync::Arc::new(SharedMaps::build(
299 scripts.iter().map(|s| (s.id, s.name.as_str())),
300 registry,
301 false,
302 ));
303 Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
304 }
305
306 pub fn new_client(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
307 let shared = std::sync::Arc::new(SharedMaps::build(
308 scripts.iter().map(|s| (s.id, s.name.as_str())),
309 registry,
310 true,
311 ));
312 Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
313 }
314
315 pub(crate) fn build_shared(
319 scripts: &[CompiledScript],
320 registry: &SymbolRegistry,
321 client: bool,
322 ) -> std::sync::Arc<SharedMaps> {
323 std::sync::Arc::new(SharedMaps::build(
324 scripts.iter().map(|s| (s.id, s.name.as_str())),
325 registry,
326 client,
327 ))
328 }
329
330 pub(crate) fn build_shared_idents(
333 idents: &[(i32, String)],
334 registry: &SymbolRegistry,
335 ) -> std::sync::Arc<SharedMaps> {
336 std::sync::Arc::new(SharedMaps::build(
337 idents.iter().map(|(id, name)| (*id, name.as_str())),
338 registry,
339 false,
340 ))
341 }
342
343 pub(crate) fn with_shared(
346 scripts: ScriptSource<'a>,
347 registry: &'a SymbolRegistry,
348 shared: std::sync::Arc<SharedMaps>,
349 ) -> Self {
350 PointerChecker {
351 scripts,
352 registry,
353 shared,
354 source_cache: None,
355 script_analyses: HashMap::new(),
356 script_pointers: HashMap::new(),
357 pending_analyses: HashSet::new(),
358 pending_scripts: HashSet::new(),
359 recursive_scripts: HashSet::new(),
360 }
361 }
362
363 pub fn set_source_cache(&mut self, provider: crate::SourceProvider<'a>) {
367 self.source_cache = Some(provider);
368 }
369
370 fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
373 if !self
374 .registry
375 .trigger(trigger)
376 .is_some_and(|trigger| trigger.is_button)
377 {
378 return false;
379 }
380 let subject = script_name
382 .trim_start_matches('[')
383 .trim_end_matches(']')
384 .split_once(',')
385 .map(|(_, rest)| rest)
386 .unwrap_or("");
387 let iface_name = subject
388 .split(':')
389 .next()
390 .unwrap_or("")
391 .to_lowercase()
392 .replace(' ', "_");
393 if iface_name.is_empty() {
394 return false;
395 }
396 !self.shared.overlay_interfaces.contains(&iface_name)
398 }
399
400 pub fn run(&mut self) -> DiagnosticsCollector {
402 let names = self.script_names();
403 self.validate_names(&names)
404 }
405
406 pub fn script_names(&self) -> Vec<String> {
408 (0..self.scripts.len())
409 .map(|i| self.scripts.get(i).name.clone())
410 .collect()
411 }
412
413 pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
421 self.validate_names_until(names, &|| false)
422 }
423
424 pub(crate) fn validate_names_until(
426 &mut self,
427 names: &[String],
428 stop: &dyn Fn() -> bool,
429 ) -> DiagnosticsCollector {
430 self.validate_names_with(names, stop, |_, _| {})
431 }
432
433 pub(crate) fn validate_names_with_requirements_until(
434 &mut self,
435 names: &[String],
436 stop: &dyn Fn() -> bool,
437 ) -> (DiagnosticsCollector, HashMap<String, PointerSet>) {
438 let mut requirements = HashMap::new();
439 let diagnostics = self.validate_names_with(names, stop, |checker, name| {
440 if let Some(analysis) = checker.script_analyses.get(name) {
441 let required = PointerType::ALL
442 .into_iter()
443 .filter(|pointer| {
444 let pi = pointer.index();
445 if analysis.required[pi].is_empty() {
446 return false;
447 }
448 let blocked = analysis.set_list[pi].iter().copied().collect();
449 Self::requires_at_entry(analysis, pi, &blocked)
450 })
451 .collect();
452 requirements.insert(name.to_string(), required);
453 }
454 });
455 (diagnostics, requirements)
456 }
457
458 fn validate_names_with(
459 &mut self,
460 names: &[String],
461 stop: &dyn Fn() -> bool,
462 mut on_script: impl FnMut(&Self, &str),
463 ) -> DiagnosticsCollector {
464 let mut diagnostics = DiagnosticsCollector::new();
465 for script_name in names {
466 if stop() {
467 break;
468 }
469 self.validate_script(script_name, &mut diagnostics);
470 on_script(self, script_name);
471 self.script_analyses.clear();
479 }
480 diagnostics
481 }
482
483 fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
484 let script_idx = match self.shared.script_name_to_index.get(script_name) {
486 Some(&i) => i,
487 None => return,
488 };
489 let trigger = self.scripts.get(script_idx).trigger.clone();
490 let source_path = self.scripts.get(script_idx).source_path.clone();
491 let trigger_set = if let Some(profile) = &self.registry.profile {
492 profile
493 .trigger_pointers
494 .get(&trigger)
495 .copied()
496 .unwrap_or_default()
497 } else if self.shared.client {
498 match trigger.as_str() {
499 "proc" => [PointerType::ActiveComponent, PointerType::ActiveComponent2]
500 .into_iter()
501 .collect(),
502 _ => PointerSet::new(),
503 }
504 } else {
505 trigger_pointers(&trigger)
506 };
507
508 self.ensure_analysis(script_name);
510
511 if !self.shared.client && matches!(trigger.as_str(), "proc" | "label") {
512 self.warn_implicit_context(script_idx, diagnostics);
513 }
514
515 for &ptr in &PointerType::ALL {
516 let ptr_idx = ptr.index();
517
518 let analysis = match self.script_analyses.get(script_name) {
520 Some(a) => a,
521 None => continue,
522 };
523
524 let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
525 if required_nodes.is_empty() {
526 continue;
527 }
528
529 let mut corrupted: HashSet<usize> =
534 analysis.corrupted_list[ptr_idx].iter().copied().collect();
535
536 let trigger_provides = if trigger_set.contains(ptr) {
540 true
541 } else if ptr == PointerType::PActivePlayer {
542 self.interface_trigger_grants_protected(&trigger, script_name)
543 } else {
544 false
545 };
546 if !trigger_provides {
547 corrupted.insert(0);
548 }
549
550 if corrupted.is_empty() {
551 continue;
552 }
553
554 let set_blocked: HashSet<usize> = analysis.set_list[ptr_idx].iter().copied().collect();
555
556 let path = self.find_edge_path(
558 script_name,
559 &required_nodes,
560 |node_idx| corrupted.contains(&node_idx),
561 &set_blocked,
562 );
563
564 let mut reported_via_main_bfs = false;
565 if let Some(path) = path {
566 if path.is_empty() {
567 continue;
568 }
569 reported_via_main_bfs = true;
570
571 let end_node_idx = path[path.len() - 1];
572 let start_node_idx = path[0];
573
574 let is_start_node = end_node_idx == 0;
575 let repr = ptr.representation();
576 let static_only = is_static_only_pointer(ptr);
577
578 let error_msg = if is_start_node {
584 if static_only {
585 msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
586 } else {
587 msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
588 }
589 } else if static_only {
590 msg::fmt(msg::POINTER_STALE, &[repr])
591 } else {
592 msg::fmt(msg::POINTER_CORRUPTED, &[repr])
593 };
594
595 let analysis = self.script_analyses.get(script_name).unwrap();
596 let script_ref = self.scripts.get(script_idx);
597 let instructions = &script_ref.instructions;
598 let req_line = analysis.nodes[start_node_idx]
599 .instruction_index
600 .map(|idx| resolve_line(instructions, idx))
601 .unwrap_or(0);
602
603 diagnostics.add(Diagnostic {
608 file: PathBuf::from(&source_path),
609 line: req_line,
610 column: 0,
611 message: error_msg,
612 severity: Severity::Warning,
613 phase: Phase::PointerCheck,
614 help: Vec::new(),
615 });
616
617 let read_hint = if static_only {
618 msg::fmt(msg::POINTER_READ_HERE, &[repr])
619 } else {
620 msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
621 };
622 diagnostics.add(Diagnostic {
623 file: PathBuf::from(&source_path),
624 line: req_line,
625 column: 0,
626 message: read_hint,
627 severity: Severity::Info,
628 phase: Phase::PointerCheck,
629 help: Vec::new(),
630 });
631
632 if !is_start_node {
633 let corrupt_line = analysis.nodes[end_node_idx]
634 .instruction_index
635 .map(|idx| resolve_line(instructions, idx))
636 .unwrap_or(0);
637
638 let cause_hint = if static_only {
639 msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
640 } else {
641 msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
642 };
643 diagnostics.add(Diagnostic {
644 file: PathBuf::from(&source_path),
645 line: corrupt_line,
646 column: 0,
647 message: cause_hint,
648 severity: Severity::Info,
649 phase: Phase::PointerCheck,
650 help: Vec::new(),
651 });
652 }
653 }
654
655 if !reported_via_main_bfs && is_static_only_pointer(ptr) {
668 let targets: Vec<(usize, usize)> = {
672 let analysis = self.script_analyses.get(script_name).unwrap();
673 let script_ref = self.scripts.get(script_idx);
674 let instructions = &script_ref.instructions;
675 let corrupted_nodes: HashSet<usize> =
676 analysis.corrupted_list[ptr_idx].iter().copied().collect();
677 required_nodes
678 .iter()
679 .filter(|&&node_idx| corrupted_nodes.contains(&node_idx))
680 .map(|&node_idx| {
681 let line = analysis.nodes[node_idx]
682 .instruction_index
683 .map(|idx| resolve_line(instructions, idx))
684 .unwrap_or(0);
685 (node_idx, line)
686 })
687 .collect()
688 };
689 let mut seen_lines: HashSet<usize> = HashSet::new();
690 let repr = ptr.representation();
691 for (node_idx, line) in targets {
692 if !seen_lines.insert(line) {
693 continue;
694 }
695
696 let help =
701 self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
702
703 let mut diag = Diagnostic {
711 file: PathBuf::from(&source_path),
712 line,
713 column: 0,
714 message: msg::fmt(msg::POINTER_STALE, &[repr]),
715 severity: Severity::Warning,
716 phase: Phase::PointerCheck,
717 help: Vec::new(),
718 };
719 if let Some(h) = help {
720 diag.help.push(h);
721 }
722 diagnostics.add(diag);
723 }
724 }
725 }
726 }
727
728 fn warn_implicit_context(&self, script_idx: usize, diagnostics: &mut DiagnosticsCollector) {
729 let script = self.scripts.get(script_idx);
730 let Some(analysis) = self.script_analyses.get(&script.name) else {
731 return;
732 };
733 for ptr in PointerType::ALL
734 .into_iter()
735 .filter(|ptr| is_static_only_pointer(*ptr))
736 {
737 let pi = ptr.index();
738 if !analysis.required[pi].iter().any(|&node| {
739 analysis.nodes[node]
740 .instruction_index
741 .is_some_and(|instruction| {
742 script.instructions[instruction].opcode == Opcode::Command
743 })
744 }) {
745 continue;
746 }
747 let blocked = analysis.set_list[pi]
748 .iter()
749 .chain(&analysis.corrupted_list[pi])
750 .copied()
751 .collect::<HashSet<_>>();
752 let mut inherited = vec![false; analysis.nodes.len()];
753 let mut pending = vec![0];
754 while let Some(node) = pending.pop() {
755 if inherited[node] {
756 continue;
757 }
758 inherited[node] = true;
759 if !blocked.contains(&node) {
760 pending.extend(&analysis.nodes[node].next);
761 }
762 }
763 let mut reported = HashSet::new();
764 for &node in &analysis.required[pi] {
765 let Some(instruction) = analysis.nodes[node].instruction_index else {
766 continue;
767 };
768 if !inherited[node] || script.instructions[instruction].opcode != Opcode::Command {
769 continue;
770 }
771 let line = resolve_line(&script.instructions, instruction);
772 if reported.insert(line) {
773 diagnostics.warning(
774 PathBuf::from(&script.source_path),
775 line,
776 0,
777 msg::fmt(
778 msg::POINTER_IMPLICIT_CONTEXT,
779 &[ptr.representation(), &script.name],
780 ),
781 Phase::PointerCheck,
782 );
783 }
784 }
785 }
786 }
787
788 fn find_edge_path(
797 &self,
798 script_name: &str,
799 starts: &[usize],
800 end_pred: impl Fn(usize) -> bool,
801 blocked: &HashSet<usize>,
802 ) -> Option<Vec<usize>> {
803 let analysis = self.script_analyses.get(script_name)?;
804
805 let mut queue: VecDeque<usize> = VecDeque::new();
806 let mut visited: HashSet<usize> = HashSet::new();
807 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); for &start in starts {
815 for &prev in &analysis.nodes[start].previous {
816 if blocked.contains(&prev) || visited.contains(&prev) {
817 continue;
818 }
819 visited.insert(prev);
820 queue.push_back(prev);
821 sources.insert(prev, (start, start));
822 }
823 }
824
825 while let Some(current) = queue.pop_front() {
826 if end_pred(current) {
827 let mut path = vec![current];
829 let mut node = current;
830 while let Some(&(from, start)) = sources.get(&node) {
831 if from == start && starts.contains(&from) {
832 path.push(from);
833 break;
834 }
835 path.push(from);
836 node = from;
837 }
838 path.reverse();
839 return Some(path);
840 }
841
842 let (_, start_node) = sources[¤t];
843
844 for &prev in &analysis.nodes[current].previous {
845 if blocked.contains(&prev) || visited.contains(&prev) {
846 continue;
847 }
848 visited.insert(prev);
849 queue.push_back(prev);
850 sources.insert(prev, (current, start_node));
851 }
852 }
853
854 None
855 }
856
857 fn find_edge_path_static(
860 nodes: &[CfgNode],
861 starts: &[usize],
862 end_pred: impl Fn(usize) -> bool,
863 blocked: &HashSet<usize>,
864 ) -> Option<Vec<usize>> {
865 let mut queue: VecDeque<usize> = VecDeque::new();
866 let mut visited: HashSet<usize> = HashSet::new();
867 let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
868
869 for &start in starts {
870 for &prev in &nodes[start].previous {
871 if blocked.contains(&prev) || visited.contains(&prev) {
872 continue;
873 }
874 visited.insert(prev);
875 queue.push_back(prev);
876 sources.insert(prev, (start, start));
877 }
878 }
879
880 while let Some(current) = queue.pop_front() {
881 if end_pred(current) {
882 let mut path = vec![current];
883 let mut node = current;
884 while let Some(&(from, start)) = sources.get(&node) {
885 if from == start && starts.contains(&from) {
886 path.push(from);
887 break;
888 }
889 path.push(from);
890 node = from;
891 }
892 path.reverse();
893 return Some(path);
894 }
895
896 for &prev in &nodes[current].previous {
897 if blocked.contains(&prev) || visited.contains(&prev) {
898 continue;
899 }
900 visited.insert(prev);
901 queue.push_back(prev);
902 sources.insert(prev, (current, sources[¤t].1));
903 }
904 }
905
906 None
907 }
908
909 fn ensure_analysis(&mut self, script_name: &str) {
914 if self.script_analyses.contains_key(script_name) {
915 return;
916 }
917 if self.pending_analyses.contains(script_name) {
918 self.mark_recursive_scripts();
919 return;
920 }
921 self.pending_analyses.insert(script_name.to_string());
922
923 let script_idx = match self.shared.script_name_to_index.get(script_name) {
924 Some(&i) => i,
925 None => return,
926 };
927
928 let mut analysis = self.build_cfg(script_idx);
929 self.categorize_nodes(script_idx, &mut analysis);
930
931 self.script_analyses
932 .insert(script_name.to_string(), analysis);
933 if !self.recursive_scripts.is_empty() {
934 self.recursive_scripts.insert(script_name.to_string());
935 }
936 self.pending_analyses.remove(script_name);
937 self.resolve_recursive_scripts();
938 }
939
940 fn mark_recursive_scripts(&mut self) {
941 self.recursive_scripts
942 .extend(self.pending_analyses.iter().cloned());
943 self.recursive_scripts
944 .extend(self.pending_scripts.iter().cloned());
945 }
946
947 fn resolve_recursive_scripts(&mut self) {
948 if self.recursive_scripts.is_empty()
949 || !self.pending_analyses.is_empty()
950 || !self.pending_scripts.is_empty()
951 {
952 return;
953 }
954 let mut names: Vec<_> = self.recursive_scripts.drain().collect();
955 names.sort();
956 for name in &names {
959 self.script_pointers.insert(
960 name.clone(),
961 PointerHolder {
962 set: PointerSet::all(),
963 ..PointerHolder::default()
964 },
965 );
966 }
967 loop {
968 let mut updates = Vec::with_capacity(names.len());
969 for name in &names {
970 let idx = self.shared.script_name_to_index[name];
971 let mut analysis = self.build_cfg(idx);
972 self.categorize_nodes(idx, &mut analysis);
973 let holder = Self::analyzed_pointers(&analysis);
974 updates.push((name.clone(), analysis, holder));
975 }
976 let mut changed = false;
977 for (name, analysis, holder) in updates {
978 changed |= self.script_pointers[&name] != holder;
979 self.script_analyses.insert(name.clone(), analysis);
980 self.script_pointers.insert(name, holder);
981 }
982 if !changed {
983 break;
984 }
985 }
986 }
987
988 fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
993 let script = self.scripts.get(script_idx);
994 #[cfg(feature = "memprof")]
995 cfg_trace_push(&script.source_path);
996 let instructions = &script.instructions;
997 let mut analysis = ScriptAnalysis::new();
998
999 analysis.nodes.push(CfgNode::new(None));
1001
1002 let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
1004 let mut node_order: Vec<usize> = Vec::new(); for (i, instr) in instructions.iter().enumerate() {
1007 if instr.opcode == Opcode::LineNumber {
1008 continue;
1009 }
1010 let node_idx = analysis.nodes.len();
1011 instr_to_node.insert(i, node_idx);
1012 node_order.push(i);
1013 analysis.nodes.push(CfgNode::new(Some(i)));
1014 }
1015
1016 if node_order.is_empty() {
1017 return analysis;
1018 }
1019
1020 let first_node = instr_to_node[&node_order[0]];
1022 add_edge(&mut analysis.nodes, 0, first_node);
1023
1024 for (order_idx, &instr_idx) in node_order.iter().enumerate() {
1026 let node_idx = instr_to_node[&instr_idx];
1027 let instr = &instructions[instr_idx];
1028
1029 let is_terminal = matches!(
1030 instr.opcode,
1031 Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
1032 );
1033
1034 match instr.opcode {
1039 Opcode::Branch
1040 | Opcode::BranchNot
1041 | Opcode::BranchEquals
1042 | Opcode::BranchLessThan
1043 | Opcode::BranchGreaterThan
1044 | Opcode::BranchLessThanOrEquals
1045 | Opcode::BranchGreaterThanOrEquals
1046 | Opcode::LongBranchNot
1047 | Opcode::LongBranchEquals
1048 | Opcode::LongBranchLessThan
1049 | Opcode::LongBranchGreaterThan
1050 | Opcode::LongBranchLessThanOrEquals
1051 | Opcode::LongBranchGreaterThanOrEquals
1052 | Opcode::ObjBranchEquals
1053 | Opcode::ObjBranchNot
1054 | Opcode::BranchIfTrue
1055 | Opcode::BranchIfFalse => {
1056 if let Operand::JumpTarget(target_instr_idx) = &instr.operand
1057 && let Some(target_node) =
1058 resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
1059 {
1060 add_edge(&mut analysis.nodes, node_idx, target_node);
1061 }
1062 }
1063
1064 Opcode::Switch => {
1065 if let Operand::SwitchTable(tbl_idx) = &instr.operand {
1066 let cases = &script.switch_tables[*tbl_idx as usize];
1067 for &(_, target_instr_idx) in cases.iter() {
1068 if let Some(target_node) =
1069 resolve_target_node(target_instr_idx, instructions, &instr_to_node)
1070 {
1071 add_edge(&mut analysis.nodes, node_idx, target_node);
1072 }
1073 }
1074 }
1075 }
1076
1077 _ => {}
1078 }
1079
1080 if !is_terminal
1082 && let Some(next_order_idx) = order_idx.checked_add(1)
1083 && next_order_idx < node_order.len()
1084 {
1085 let next_node = instr_to_node[&node_order[next_order_idx]];
1086 add_edge(&mut analysis.nodes, node_idx, next_node);
1087 }
1088
1089 if instr.opcode == Opcode::Return {
1094 analysis.returns.push(node_idx);
1095 }
1096 }
1097
1098 self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
1100
1101 analysis
1102 }
1103
1104 fn insert_pointer_nodes(
1107 &self,
1108 script_idx: usize,
1109 analysis: &mut ScriptAnalysis,
1110 instr_to_node: &HashMap<usize, usize>,
1111 node_order: &[usize],
1112 ) {
1113 let script_ref = self.scripts.get(script_idx);
1114 let instructions = &script_ref.instructions;
1115
1116 for window_end in 1..node_order.len() {
1119 let branch_instr_idx = node_order[window_end];
1120 let branch_instr = &instructions[branch_instr_idx];
1121 let (push_value, scan_end) = match branch_instr.opcode {
1122 Opcode::BranchIfTrue => (1, window_end),
1123 Opcode::BranchIfFalse => (0, window_end),
1124 Opcode::BranchEquals | Opcode::BranchNot => {
1125 let push_instr = &instructions[node_order[window_end - 1]];
1126 match (push_instr.opcode, &push_instr.operand) {
1127 (Opcode::PushConstantInt, Operand::Int(value @ (0 | 1))) => (
1128 if branch_instr.opcode == Opcode::BranchNot {
1129 1 - value
1130 } else {
1131 *value
1132 },
1133 window_end - 1,
1134 ),
1135 _ => continue,
1136 }
1137 }
1138 _ => continue,
1139 };
1140
1141 let Some(&cmd_instr_idx) = scan_end.checked_sub(1).and_then(|idx| node_order.get(idx))
1142 else {
1143 continue;
1144 };
1145 let cmd_instr = &instructions[cmd_instr_idx];
1146 if cmd_instr.opcode != Opcode::Command {
1147 continue;
1148 }
1149
1150 let cmd_name = self.resolve_command_name(cmd_instr, &script_ref.strings);
1152 let cmd_name = match cmd_name {
1153 Some(n) => n,
1154 None => continue,
1155 };
1156
1157 let holder = match self.shared.cmd_pointers.get(&cmd_name) {
1158 Some(h) => h,
1159 None => continue,
1160 };
1161
1162 if !holder.conditional_set {
1163 continue;
1164 }
1165
1166 if holder.set.is_empty() {
1167 continue;
1168 }
1169
1170 let branch_node_idx = instr_to_node[&branch_instr_idx];
1171
1172 let ptr_node_idx = analysis.nodes.len();
1174 analysis.nodes.push(CfgNode::pointer_node(holder.set));
1175
1176 if push_value == 0 {
1177 let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
1185 .next
1186 .iter()
1187 .copied()
1188 .filter(|&n| {
1189 if let Operand::JumpTarget(target) = &branch_instr.operand
1191 && let Some(jump_node) =
1192 resolve_target_node(*target, instructions, instr_to_node)
1193 {
1194 return n != jump_node;
1195 }
1196 true
1197 })
1198 .collect();
1199
1200 for ft_target in fallthrough_targets {
1201 remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
1203 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1205 add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
1206 }
1207 } else {
1208 if let Operand::JumpTarget(target) = &branch_instr.operand
1212 && let Some(jump_target_node) =
1213 resolve_target_node(*target, instructions, instr_to_node)
1214 {
1215 remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
1217 add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1219 add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
1220 }
1221 }
1222 }
1223 }
1224
1225 fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
1230 let script_ref = self.scripts.get(script_idx);
1231 let instructions = &script_ref.instructions;
1232
1233 for node_idx in 0..analysis.nodes.len() {
1234 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1235 Some(i) => i,
1236 None => {
1237 let ptr_set = analysis.nodes[node_idx].pointer_set;
1239 if !ptr_set.is_empty() {
1240 for ptr in ptr_set.iter() {
1241 let pi = ptr.index();
1242 analysis.set_list[pi].push(node_idx);
1243 }
1244 }
1245 continue;
1246 }
1247 };
1248
1249 let instr = &instructions[instr_idx];
1250
1251 match instr.opcode {
1252 Opcode::Command => {
1253 let cmd_name = self.resolve_command_name(instr, &script_ref.strings);
1254 if let Some(name) = cmd_name
1255 && let Some(holder) = self.shared.cmd_pointers.get(&name).cloned()
1256 {
1257 self.apply_holder(analysis, node_idx, &holder);
1258 }
1259 }
1260
1261 Opcode::Gosub | Opcode::GosubWithParams => {
1262 if let Operand::Int(script_id) = &instr.operand {
1263 let callee_holder = self.get_script_pointers(*script_id);
1264 self.apply_holder(analysis, node_idx, &callee_holder);
1265 }
1266 }
1267
1268 Opcode::Jump | Opcode::JumpWithParams => {
1269 if let Operand::Int(script_id) = &instr.operand {
1270 let callee_holder = self.get_script_pointers(*script_id);
1271 self.apply_holder(analysis, node_idx, &callee_holder);
1272 }
1273 }
1274
1275 Opcode::PushVarp
1282 | Opcode::PushVarpBit
1283 | Opcode::PushVarcInt
1284 | Opcode::PushVarcString
1285 | Opcode::PushVarClan
1286 | Opcode::PushClanSettingInt
1287 | Opcode::PushClanSettingVarbit
1288 | Opcode::PushClanSettingLong
1289 | Opcode::PushClanSettingString
1290 if !self.shared.client =>
1291 {
1292 let pi = if is_secondary_var_operand(&instr.operand) {
1293 PointerType::ActivePlayer2.index()
1294 } else {
1295 PointerType::ActivePlayer.index()
1296 };
1297 analysis.required[pi].push(node_idx);
1298 }
1299
1300 Opcode::PopVarp
1301 | Opcode::PopVarpBit
1302 | Opcode::PopVarcInt
1303 | Opcode::PopVarcString
1304 | Opcode::PopVarClan
1305 | Opcode::PopClanSettingInt
1306 | Opcode::PopClanSettingVarbit
1307 | Opcode::PopClanSettingLong
1308 | Opcode::PopClanSettingString
1309 if !self.shared.client =>
1310 {
1311 let pi = if is_secondary_var_operand(&instr.operand) {
1312 PointerType::ActivePlayer2.index()
1313 } else {
1314 PointerType::ActivePlayer.index()
1315 };
1316 analysis.required[pi].push(node_idx);
1317 }
1318
1319 Opcode::PushVarn | Opcode::PopVarn | Opcode::PushVarnBit | Opcode::PopVarnBit
1320 if !self.shared.client =>
1321 {
1322 let pi = if is_secondary_var_operand(&instr.operand) {
1323 PointerType::ActiveNpc2.index()
1324 } else {
1325 PointerType::ActiveNpc.index()
1326 };
1327 analysis.required[pi].push(node_idx);
1328 }
1329
1330 Opcode::PushVarCon
1331 | Opcode::PopVarCon
1332 | Opcode::PushVarConBit
1333 | Opcode::PopVarConBit
1334 if !self.shared.client =>
1335 {
1336 let pi = if is_secondary_var_operand(&instr.operand) {
1337 PointerType::ActiveController2.index()
1338 } else {
1339 PointerType::ActiveController.index()
1340 };
1341 analysis.required[pi].push(node_idx);
1342 }
1343
1344 _ => {}
1346 }
1347 }
1348 }
1349
1350 fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
1351 for ptr in holder.required.iter() {
1352 let pi = ptr.index();
1353 analysis.required[pi].push(node_idx);
1354 }
1355 for ptr in holder.set.iter().filter(|_| !holder.conditional_set) {
1356 let pi = ptr.index();
1357 analysis.set_list[pi].push(node_idx);
1358 }
1359 for ptr in holder.corrupted.iter() {
1360 let pi = ptr.index();
1361 analysis.corrupted_list[pi].push(node_idx);
1362 }
1363 }
1364
1365 fn requires_at_entry(
1370 analysis: &ScriptAnalysis,
1371 pointer: usize,
1372 setters: &HashSet<usize>,
1373 ) -> bool {
1374 Self::find_edge_path_static(
1375 &analysis.nodes,
1376 &analysis.required[pointer],
1377 |node_idx| node_idx == 0,
1378 setters,
1379 )
1380 .is_some()
1381 }
1382
1383 fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
1395 let script_idx = match self.shared.script_id_to_index.get(&script_id) {
1397 Some(&i) => i,
1398 None => {
1399 return PointerHolder::default();
1400 }
1401 };
1402 let script_name = self.scripts.get(script_idx).name.clone();
1403
1404 if let Some(holder) = self.script_pointers.get(&script_name) {
1406 return holder.clone();
1407 }
1408
1409 if self.pending_scripts.contains(&script_name) {
1411 self.mark_recursive_scripts();
1412 return PointerHolder::default();
1413 }
1414 self.pending_scripts.insert(script_name.clone());
1415
1416 self.ensure_analysis(&script_name);
1418
1419 let holder = self
1420 .script_analyses
1421 .get(&script_name)
1422 .map_or_else(PointerHolder::default, Self::analyzed_pointers);
1423 self.pending_scripts.remove(&script_name);
1424 self.script_pointers.insert(script_name.clone(), holder);
1425 self.resolve_recursive_scripts();
1426 self.script_pointers[&script_name].clone()
1427 }
1428
1429 fn analyzed_pointers(analysis: &ScriptAnalysis) -> PointerHolder {
1430 let mut holder = PointerHolder::default();
1431 for &ptr in &PointerType::ALL {
1432 let pi = ptr.index();
1433
1434 let requires = !analysis.required[pi].is_empty();
1440 let has_returns = !analysis.returns.is_empty();
1441 if !requires && !has_returns {
1442 continue;
1443 }
1444 let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
1445
1446 if requires && Self::requires_at_entry(analysis, pi, &set_blocked) {
1448 holder.required.insert(ptr);
1449 }
1450
1451 if has_returns {
1452 let corrupted_nodes: HashSet<usize> =
1453 analysis.corrupted_list[pi].iter().copied().collect();
1454
1455 let path = Self::find_edge_path_static(
1458 &analysis.nodes,
1459 &analysis.returns,
1460 |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1461 &set_blocked,
1462 );
1463 if path.is_none() {
1464 holder.set.insert(ptr);
1465 }
1466
1467 if !corrupted_nodes.is_empty() {
1469 let path = Self::find_edge_path_static(
1470 &analysis.nodes,
1471 &analysis.returns,
1472 |node_idx| corrupted_nodes.contains(&node_idx),
1473 &set_blocked,
1474 );
1475 if path.is_some() {
1476 holder.corrupted.insert(ptr);
1477 }
1478 }
1479 }
1480 }
1481 holder
1482 }
1483
1484 fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1494 let callee = self.scripts.get(callee_idx);
1495 let analysis = match self.script_analyses.get(&callee.name) {
1496 Some(a) => a,
1497 None => return Vec::new(),
1498 };
1499 let ptr_idx = ptr.index();
1500 let mut seen: HashSet<(String, usize)> = HashSet::new();
1501 let mut result: Vec<(String, usize)> = Vec::new();
1502
1503 for &node_idx in &analysis.corrupted_list[ptr_idx] {
1504 let instr_idx = match analysis.nodes[node_idx].instruction_index {
1505 Some(i) => i,
1506 None => continue,
1507 };
1508 let instr = &callee.instructions[instr_idx];
1509 let line = resolve_line(&callee.instructions, instr_idx);
1510
1511 let name = match instr.opcode {
1512 Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
1513 Some(n) => n,
1514 None => continue,
1515 },
1516 Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1517 Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
1518 Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
1519 .map(|s| format!("~{}", s))
1520 .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
1521 None => continue,
1522 },
1523 _ => continue,
1524 },
1525 _ => continue,
1529 };
1530
1531 let key = (name.clone(), line);
1532 if seen.insert(key) {
1533 result.push((name, line));
1534 }
1535 }
1536
1537 result
1538 }
1539
1540 fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
1541 match &instr.operand {
1542 Operand::Int(encoded) => {
1543 let opcode = encoded & 0xFFFF;
1544 let secondary = (encoded >> 16) & 1;
1545 let base_name = self.shared.opcode_to_name.get(&opcode)?;
1546 if secondary == 1 {
1547 Some(format!(".{}", base_name))
1548 } else {
1549 Some(base_name.clone())
1550 }
1551 }
1552 Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
1553 _ => None,
1554 }
1555 }
1556
1557 fn build_rule_a_help(
1569 &mut self,
1570 ptr: PointerType,
1571 caller_source_path: &str,
1572 caller_line: usize,
1573 node_idx: usize,
1574 caller_script_idx: usize,
1575 ) -> Option<Help> {
1576 let (is_gosub, script_id) = {
1579 let caller = self.scripts.get(caller_script_idx);
1580 let analysis = self.script_analyses.get(&caller.name)?;
1581 let instr_idx = analysis.nodes[node_idx].instruction_index?;
1582 let instr = &caller.instructions[instr_idx];
1583 match instr.opcode {
1585 Opcode::Jump | Opcode::JumpWithParams => (
1586 false,
1587 match &instr.operand {
1588 Operand::Int(id) => *id,
1589 _ => return None,
1590 },
1591 ),
1592 Opcode::Gosub | Opcode::GosubWithParams => (
1593 true,
1594 match &instr.operand {
1595 Operand::Int(id) => *id,
1596 _ => return None,
1597 },
1598 ),
1599 _ => return None,
1600 }
1601 };
1602
1603 let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
1604 let callee_name = self.scripts.get(callee_idx).name.clone();
1608 self.ensure_analysis(&callee_name);
1609
1610 let callee = self.scripts.get(callee_idx);
1611 let callee_source = callee.source_path.clone();
1612
1613 let first_body_line = callee
1621 .instructions
1622 .iter()
1623 .find_map(|i| match (i.opcode, &i.operand) {
1624 (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1625 _ => None,
1626 })
1627 .unwrap_or(1);
1628 let callee_trigger = callee.trigger.clone();
1629 let callee_short_early = callee
1630 .name
1631 .trim_start_matches('[')
1632 .trim_end_matches(']')
1633 .split_once(',')
1634 .map(|(_, n)| n.to_string())
1635 .unwrap_or_else(|| callee.name.clone());
1636 let callee_header_line = self
1637 .source_cache
1638 .and_then(|c| c.get(&callee_source))
1639 .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
1640 .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1641
1642 let ptr_cmd = ptr.representation(); let param_type = pointer_param_type(ptr);
1644 let param_name = format!("${}", ptr_cmd);
1645
1646 let callee_short = callee
1647 .name
1648 .trim_start_matches('[')
1649 .trim_end_matches(']')
1650 .split_once(',')
1651 .map(|(_, n)| n.to_string())
1652 .unwrap_or_else(|| callee.name.clone());
1653
1654 let arrow = if is_gosub { "~" } else { "@" };
1655
1656 let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1661 let corruptor_phrase = format_corruptors(&corruptors);
1662
1663 let message = format!(
1664 "`{callee}` reads `{ptr}` then {phrase}; the script still \
1665 compiles and runs, but the reference is brittle to reorder. \
1666 Consider capturing `{ptr}` at the call site and threading it \
1667 through `{callee}` as an `{ty} {pname}` parameter so the \
1668 value is explicit and stable.",
1669 callee = callee_short,
1670 ptr = ptr_cmd,
1671 phrase = corruptor_phrase,
1672 ty = param_type,
1673 pname = param_name,
1674 );
1675
1676 let cache = match self.source_cache {
1677 Some(c) => c,
1678 None => {
1679 return Some(Help {
1681 message,
1682 suggestions: Vec::new(),
1683 applicability: Applicability::Unspecified,
1684 });
1685 }
1686 };
1687
1688 let mut suggestions = Vec::new();
1689
1690 if let Some(src) = cache.get(caller_source_path)
1693 && let Some(line_text) = nth_source_line(&src, caller_line)
1694 && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1695 {
1696 suggestions.push(Suggestion {
1697 file: PathBuf::from(caller_source_path),
1698 line_range: (caller_line, caller_line),
1699 replacement: rewritten,
1700 label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1701 });
1702 }
1703
1704 if let Some(src) = cache.get(&callee_source)
1706 && let Some(header_text) = nth_source_line(&src, callee_header_line)
1707 && let Some(rewritten) =
1708 rewrite_header_add_param(header_text, &callee_short, param_type, ¶m_name)
1709 {
1710 suggestions.push(Suggestion {
1711 file: PathBuf::from(&callee_source),
1712 line_range: (callee_header_line, callee_header_line),
1713 replacement: rewritten,
1714 label: Some(format!(
1715 "at the `{}` header (add `{} {}`)",
1716 callee_short, param_type, param_name
1717 )),
1718 });
1719 }
1720
1721 Some(Help {
1722 message,
1723 suggestions,
1724 applicability: Applicability::MaybeIncorrect,
1728 })
1729 }
1730}
1731
1732fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1737 if !nodes[from].next.contains(&to) {
1738 nodes[from].next.push(to);
1739 }
1740 if !nodes[to].previous.contains(&from) {
1741 nodes[to].previous.push(from);
1742 }
1743}
1744
1745fn is_static_only_pointer(ptr: PointerType) -> bool {
1758 use PointerType::*;
1759 matches!(
1760 ptr,
1761 FindPlayer
1762 | FindNpc
1763 | FindLoc
1764 | FindObj
1765 | FindDb
1766 | LastCom
1767 | LastInt
1768 | LastItem
1769 | LastSlot
1770 | LastTargetslot
1771 | LastUseitem
1772 | LastUseslot
1773 | LastString
1774 | LastCoord
1775 )
1776}
1777
1778fn short_script_name(full_name: &str) -> Option<String> {
1781 full_name
1782 .trim_start_matches('[')
1783 .trim_end_matches(']')
1784 .split_once(',')
1785 .map(|(_, n)| n.to_string())
1786}
1787
1788fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1793 if corruptors.is_empty() {
1794 return "calls a delay or subroutine that may supersede it".to_string();
1795 }
1796
1797 const MAX: usize = 3;
1798 let shown: Vec<String> = corruptors
1799 .iter()
1800 .take(MAX)
1801 .map(|(name, line)| {
1802 if *line > 0 {
1803 format!("`{}` at line {}", name, line)
1804 } else {
1805 format!("`{}`", name)
1806 }
1807 })
1808 .collect();
1809
1810 let suffix = if corruptors.len() > MAX {
1811 format!(" (and {} more)", corruptors.len() - MAX)
1812 } else {
1813 String::new()
1814 };
1815
1816 let joined = match shown.len() {
1817 1 => shown[0].clone(),
1818 2 => format!("{} and {}", shown[0], shown[1]),
1819 _ => {
1820 let head = shown[..shown.len() - 1].join(", ");
1821 format!("{}, and {}", head, shown[shown.len() - 1])
1822 }
1823 };
1824
1825 format!("calls {}{} which may supersede it", joined, suffix)
1826}
1827
1828fn pointer_param_type(ptr: PointerType) -> &'static str {
1837 use PointerType::*;
1838 match ptr {
1839 LastUseitem | LastItem => "obj",
1840 LastCom => "component",
1841 LastString => "string",
1842 LastCoord => "coord",
1843 _ => "int",
1844 }
1845}
1846
1847fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1849 if line_no == 0 {
1850 return None;
1851 }
1852 text.lines().nth(line_no - 1)
1853}
1854
1855fn rewrite_call_site_arg(
1864 line: &str,
1865 arrow: &str,
1866 callee_short: &str,
1867 ptr_cmd: &str,
1868) -> Option<String> {
1869 let needle = format!("{}{}", arrow, callee_short);
1872 let start = line.find(&needle)?;
1873 let after_name = start + needle.len();
1874 let tail = &line[after_name..];
1875
1876 let first_non_ws = tail.chars().next();
1878 if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1879 || tail.trim_start().is_empty()
1880 {
1881 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1882 out.push_str(&line[..after_name]);
1883 out.push('(');
1884 out.push_str(ptr_cmd);
1885 out.push(')');
1886 out.push_str(tail);
1887 return Some(out);
1888 }
1889
1890 if tail.trim_start().starts_with('(') {
1893 let open_rel = tail.find('(')?;
1894 let abs_open = after_name + open_rel;
1895 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1896 let abs_close = abs_open + close_rel;
1897
1898 let inside = line[abs_open + 1..abs_close].trim();
1900 let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1901 out.push_str(&line[..abs_close]);
1902 if inside.is_empty() {
1903 out.push_str(ptr_cmd);
1904 } else {
1905 out.push_str(", ");
1906 out.push_str(ptr_cmd);
1907 }
1908 out.push_str(&line[abs_close..]);
1909 return Some(out);
1910 }
1911
1912 None
1913}
1914
1915fn rewrite_header_add_param(
1921 line: &str,
1922 callee_short: &str,
1923 param_type: &str,
1924 param_name: &str,
1925) -> Option<String> {
1926 let needle = format!(",{}]", callee_short);
1929 let subject_end = line.find(&needle)?;
1930 let after_bracket = subject_end + needle.len();
1931
1932 let remainder = &line[after_bracket..];
1933 let added = format!("{} {}", param_type, param_name);
1934
1935 if !remainder.trim_start().starts_with('(') {
1937 let mut out = String::with_capacity(line.len() + added.len() + 2);
1938 out.push_str(&line[..after_bracket]);
1939 out.push('(');
1940 out.push_str(&added);
1941 out.push(')');
1942 out.push_str(remainder);
1943 return Some(out);
1944 }
1945
1946 let open_rel = remainder.find('(')?;
1948 let abs_open = after_bracket + open_rel;
1949 let close_rel = find_matching_close_paren(&line[abs_open..])?;
1950 let abs_close = abs_open + close_rel;
1951 let inside = line[abs_open + 1..abs_close].trim();
1952
1953 let mut out = String::with_capacity(line.len() + added.len() + 2);
1954 out.push_str(&line[..abs_close]);
1955 if inside.is_empty() {
1956 out.push_str(&added);
1957 } else {
1958 out.push_str(", ");
1959 out.push_str(&added);
1960 }
1961 out.push_str(&line[abs_close..]);
1962 Some(out)
1963}
1964
1965fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1969 let prefix = format!("[{},{}]", trigger, name);
1970 let prefix_with_params = format!("[{},{}](", trigger, name);
1971 for (i, line) in src.lines().enumerate() {
1972 let trimmed = line.trim_start();
1973 if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1974 return Some(i + 1);
1975 }
1976 }
1977 None
1978}
1979
1980fn find_matching_close_paren(s: &str) -> Option<usize> {
1984 let bytes = s.as_bytes();
1985 if bytes.first().copied() != Some(b'(') {
1986 return None;
1987 }
1988 let mut depth = 0i32;
1989 for (i, &b) in bytes.iter().enumerate() {
1990 match b {
1991 b'(' => depth += 1,
1992 b')' => {
1993 depth -= 1;
1994 if depth == 0 {
1995 return Some(i);
1996 }
1997 }
1998 _ => {}
1999 }
2000 }
2001 None
2002}
2003
2004fn is_secondary_var_operand(operand: &Operand) -> bool {
2010 match operand {
2011 Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
2012 _ => false,
2013 }
2014}
2015
2016fn resolve_target_node(
2022 mut target_idx: usize,
2023 instructions: &[Instruction],
2024 instr_to_node: &HashMap<usize, usize>,
2025) -> Option<usize> {
2026 while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
2027 target_idx += 1;
2028 }
2029 instr_to_node.get(&target_idx).copied()
2030}
2031
2032fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
2033 nodes[from].next.retain(|&n| n != to);
2034 nodes[to].previous.retain(|&n| n != from);
2035}
2036
2037fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
2040 for i in (0..=instr_idx).rev() {
2041 if instructions[i].opcode == Opcode::LineNumber
2042 && let Operand::Int(line) = instructions[i].operand
2043 {
2044 return line as usize;
2045 }
2046 }
2047 0
2048}
2049
2050#[cfg(test)]
2051mod tests {
2052 use super::*;
2053 use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
2054 use crate::symbol::SymbolRegistry;
2055
2056 fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
2058 let mut reg = SymbolRegistry::new();
2059 for &(name, opcode) in commands {
2060 reg.register_command(name.to_string(), opcode, vec![], vec![]);
2061 }
2062 reg
2063 }
2064
2065 fn make_script(
2067 name: &str,
2068 trigger: &str,
2069 id: i32,
2070 instructions: Vec<Instruction>,
2071 ) -> CompiledScript {
2072 let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
2073 script.trigger = trigger.to_string();
2074 script.source_path = "test.rs2".to_string();
2075 script.instructions = instructions;
2076 script
2077 }
2078
2079 fn cmd(opcode: i32) -> Instruction {
2081 Instruction::new(Opcode::Command, Operand::Int(opcode))
2082 }
2083
2084 fn line(n: i32) -> Instruction {
2085 Instruction::new(Opcode::LineNumber, Operand::Int(n))
2086 }
2087
2088 fn push_int(v: i32) -> Instruction {
2089 Instruction::push_int(v)
2090 }
2091
2092 fn branch_eq(target: usize) -> Instruction {
2093 Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
2094 }
2095
2096 fn branch(target: usize) -> Instruction {
2097 Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
2098 }
2099
2100 fn ret() -> Instruction {
2101 Instruction::simple(Opcode::Return)
2102 }
2103
2104 fn gosub(script_id: i32) -> Instruction {
2105 Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
2106 }
2107
2108 #[test]
2115 fn conditional_setter_with_arg_push() {
2116 let p_finduid_op = 4267;
2119 let p_stopaction_op = 4268;
2120
2121 let registry = registry_with_commands(&[
2122 ("p_finduid", p_finduid_op),
2123 ("p_stopaction", p_stopaction_op),
2124 ]);
2125
2126 let instructions = vec![
2127 line(1), push_int(0), cmd(p_finduid_op), push_int(1), branch_eq(7), branch(8), line(2), cmd(p_stopaction_op), ret(), ];
2137
2138 let script = make_script("test", "ai_timer", 0, instructions);
2142 let scripts = vec![script];
2143
2144 let mut checker = PointerChecker::new(&scripts, ®istry);
2145 let diags = checker.run();
2146
2147 assert_eq!(
2151 diags.warning_count(),
2152 0,
2153 "conditional setter should provide p_active_player on true branch, got {} warnings",
2154 diags.warning_count()
2155 );
2156 }
2157
2158 #[test]
2159 fn boolean_branches_preserve_conditional_pointer_analysis() {
2160 let registry = registry_with_commands(&[("p_finduid", 4267), ("p_delay", 4268)]);
2161 for (opcode, target, skip) in [(Opcode::BranchIfTrue, 5, 6), (Opcode::BranchIfFalse, 6, 5)]
2162 {
2163 let script = make_script(
2164 "test",
2165 "ai_timer",
2166 0,
2167 vec![
2168 line(1),
2169 push_int(0),
2170 cmd(4267),
2171 Instruction::new(opcode, Operand::JumpTarget(target)),
2172 branch(skip),
2173 cmd(4268),
2174 ret(),
2175 ],
2176 );
2177 assert_eq!(
2178 PointerChecker::new(&[script], ®istry)
2179 .run()
2180 .warning_count(),
2181 0
2182 );
2183 }
2184 let script = make_script(
2185 "test",
2186 "ai_timer",
2187 0,
2188 vec![
2189 line(1),
2190 push_int(0),
2191 cmd(4267),
2192 Instruction::new(Opcode::BranchIfFalse, Operand::JumpTarget(5)),
2193 branch(6),
2194 cmd(4268),
2195 ret(),
2196 ],
2197 );
2198 assert!(
2199 PointerChecker::new(&[script], ®istry)
2200 .run()
2201 .warning_count()
2202 > 0
2203 );
2204 }
2205
2206 #[test]
2215 fn gosub_requires_then_corrupts_same_pointer() {
2216 let p_delay_op = 5001;
2217 let npc_delay_op = 5002;
2218
2219 let registry =
2220 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2221
2222 let proc_script = make_script(
2225 "tackle_success",
2226 "proc",
2227 100,
2228 vec![
2229 line(1),
2230 push_int(0),
2231 cmd(p_delay_op), line(2),
2233 push_int(0),
2234 cmd(npc_delay_op), ret(),
2236 ],
2237 );
2238
2239 let label_script = make_script(
2242 "do_tackle",
2243 "label",
2244 200,
2245 vec![
2246 line(10),
2247 gosub(100), ret(),
2249 ],
2250 );
2251
2252 let scripts = vec![proc_script, label_script];
2253 let mut checker = PointerChecker::new(&scripts, ®istry);
2254 let diags = checker.run();
2255
2256 assert_eq!(
2262 diags.warning_count(),
2263 0,
2264 "gosub that requires-then-corrupts p_active_player should not \
2265 be flagged (engine-tracked pointer), got {} warnings",
2266 diags.warning_count()
2267 );
2268 }
2269
2270 #[test]
2276 fn corruption_before_requirement_is_caught() {
2277 let npc_delay_op = 5002;
2278 let p_delay_op = 5001;
2279
2280 let registry =
2281 registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
2282
2283 let script = make_script(
2286 "bad_order",
2287 "label",
2288 0,
2289 vec![
2290 line(1),
2291 push_int(0),
2292 cmd(npc_delay_op), line(2),
2294 push_int(0),
2295 cmd(p_delay_op), ret(),
2297 ],
2298 );
2299
2300 let scripts = vec![script];
2301 let mut checker = PointerChecker::new(&scripts, ®istry);
2302 let diags = checker.run();
2303
2304 assert!(
2305 diags.warning_count() > 0,
2306 "corruption before requirement should be caught as a warning"
2307 );
2308 }
2309
2310 #[test]
2315 fn uninitialized_pointer_caught() {
2316 let p_delay_op = 5001;
2317
2318 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2319
2320 let script = make_script(
2322 "bad_access",
2323 "ai_timer",
2324 0,
2325 vec![
2326 line(1),
2327 push_int(0),
2328 cmd(p_delay_op), ret(),
2330 ],
2331 );
2332
2333 let scripts = vec![script];
2334 let mut checker = PointerChecker::new(&scripts, ®istry);
2335 let diags = checker.run();
2336
2337 assert!(
2338 diags.warning_count() > 0,
2339 "uninitialized pointer access should be caught"
2340 );
2341 }
2342
2343 #[test]
2349 fn region_commands_need_their_region() {
2350 let (create, set) = (5202, 5203);
2351 let registry = registry_with_commands(&[("region_create", create), ("region_set", set)]);
2352 let dot = |opcode: i32| opcode | (1 << 16);
2353 let warnings = |instructions: Vec<Instruction>| {
2354 let scripts = vec![make_script("test", "ai_timer", 0, instructions)];
2355 PointerChecker::new(&scripts, ®istry)
2356 .run()
2357 .warning_count()
2358 };
2359 assert_eq!(
2360 warnings(vec![line(1), cmd(create), line(2), cmd(set), ret()]),
2361 0
2362 );
2363 assert!(warnings(vec![line(1), cmd(set), ret()]) > 0);
2364 assert!(warnings(vec![line(1), cmd(create), line(2), cmd(dot(set)), ret()]) > 0);
2365 assert_eq!(
2366 warnings(vec![
2367 line(1),
2368 cmd(dot(create)),
2369 line(2),
2370 cmd(dot(set)),
2371 ret()
2372 ]),
2373 0
2374 );
2375 }
2376
2377 #[test]
2387 fn branch_target_on_line_number_still_connects() {
2388 let p_delay_op = 5001;
2389 let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2390
2391 let script = make_script(
2407 "target_on_line_number",
2408 "ai_timer",
2409 0,
2410 vec![
2411 line(1),
2412 push_int(1),
2413 push_int(1),
2414 branch_eq(5), Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
2416 line(2),
2417 push_int(0),
2418 cmd(p_delay_op),
2419 ret(),
2420 ],
2421 );
2422
2423 let scripts = vec![script];
2424 let mut checker = PointerChecker::new(&scripts, ®istry);
2425 let diags = checker.run();
2426
2427 assert!(
2428 diags.warning_count() > 0,
2429 "jump target on LineNumber must still flag uninitialized pointer \
2430 access (got {} warnings)",
2431 diags.warning_count()
2432 );
2433 }
2434
2435 #[test]
2445 fn secondary_requires_and_corrupts_warns_for_static_pointer() {
2446 let last_useitem_op = 4270;
2449 let p_delay_op = 5001;
2450 let registry =
2451 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2452
2453 let callee = make_script(
2455 "consume_useitem",
2456 "label",
2457 100,
2458 vec![
2459 line(1),
2460 cmd(last_useitem_op), line(2),
2462 push_int(0),
2463 cmd(p_delay_op), ret(),
2465 ],
2466 );
2467
2468 let caller = make_script(
2475 "use_on_loc",
2476 "oplocu",
2477 200,
2478 vec![
2479 line(10),
2480 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2481 ],
2482 );
2483
2484 let scripts = vec![callee, caller];
2485 let mut checker = PointerChecker::new(&scripts, ®istry);
2486 let diags = checker.run();
2487
2488 let last_useitem_warnings = diags
2489 .diagnostics()
2490 .iter()
2491 .filter(|d| d.severity == Severity::Warning)
2492 .filter(|d| d.message.contains("last_useitem"))
2493 .count();
2494 assert!(
2495 last_useitem_warnings > 0,
2496 "static-only pointer (last_useitem) should trigger the \
2497 require+corrupt warning at the jump site; got diags: {:?}",
2498 diags
2499 .diagnostics()
2500 .iter()
2501 .map(|d| &d.message)
2502 .collect::<Vec<_>>()
2503 );
2504
2505 assert_eq!(
2506 diags.error_count(),
2507 0,
2508 "pointer-check diagnostics must never raise error severity; got {} errors",
2509 diags.error_count()
2510 );
2511 }
2512
2513 #[test]
2522 fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
2523 let p_delay_op = 5001;
2524 let npc_delay_op = 5002;
2525 let registry =
2526 registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2527
2528 let callee = make_script(
2529 "consume_protected",
2530 "proc",
2531 100,
2532 vec![
2533 line(1),
2534 push_int(0),
2535 cmd(p_delay_op), line(2),
2537 push_int(0),
2538 cmd(npc_delay_op), ret(),
2540 ],
2541 );
2542
2543 let caller = make_script(
2545 "do_opnpc",
2546 "opnpc1",
2547 200,
2548 vec![
2549 line(10),
2550 Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2551 ret(),
2552 ],
2553 );
2554
2555 let scripts = vec![callee, caller];
2556 let mut checker = PointerChecker::new(&scripts, ®istry);
2557 let diags = checker.run();
2558
2559 let p_active_player_warnings = diags
2560 .diagnostics()
2561 .iter()
2562 .filter(|d| d.severity == Severity::Warning)
2563 .filter(|d| d.message.contains("p_active_player"))
2564 .count();
2565 assert_eq!(
2566 p_active_player_warnings, 0,
2567 "engine-tracked pointer (p_active_player) must not trigger the \
2568 require+corrupt warning; got {} such warnings",
2569 p_active_player_warnings
2570 );
2571 }
2572
2573 #[test]
2586 fn secondary_varn_requires_active_npc2_not_primary() {
2587 let secondary_varn = Instruction::new(
2592 Opcode::PushVarn,
2593 Operand::Int(1 << 16), );
2595
2596 let proc_script = make_script(
2598 "reads_secondary_varn",
2599 "proc",
2600 100,
2601 vec![
2602 line(1),
2603 secondary_varn,
2604 Instruction::simple(Opcode::PopIntDiscard),
2605 ret(),
2606 ],
2607 );
2608
2609 let caller = make_script(
2616 "gosub_into_proc",
2617 "opplayer1",
2618 200,
2619 vec![line(10), gosub(100), ret()],
2620 );
2621
2622 let scripts = vec![proc_script, caller];
2623 let registry = registry_with_commands(&[]);
2624 let mut checker = PointerChecker::new(&scripts, ®istry);
2625 let diags = checker.run();
2626
2627 let active_npc_primary_warnings = diags
2633 .diagnostics()
2634 .iter()
2635 .filter(|d| d.severity == Severity::Warning)
2636 .filter(|d| d.message.contains("pointer active_npc."))
2637 .count();
2638 assert_eq!(
2639 active_npc_primary_warnings,
2640 0,
2641 "secondary .%var read must not flag primary active_npc at the \
2642 caller; got diags: {:?}",
2643 diags
2644 .diagnostics()
2645 .iter()
2646 .filter(|d| d.severity == Severity::Warning)
2647 .map(|d| &d.message)
2648 .collect::<Vec<_>>()
2649 );
2650
2651 let active_npc2_warnings = diags
2655 .diagnostics()
2656 .iter()
2657 .filter(|d| d.severity == Severity::Warning)
2658 .filter(|d| d.message.contains("pointer .active_npc."))
2659 .count();
2660 assert!(
2661 active_npc2_warnings > 0,
2662 "secondary .%var should route the requirement to active_npc2; \
2663 got no such warning"
2664 );
2665 }
2666
2667 #[test]
2672 fn rewrite_call_site_no_args() {
2673 let got = rewrite_call_site_arg(
2674 "[opnpcu,wantcat1] @civilian_give_runes;",
2675 "@",
2676 "civilian_give_runes",
2677 "last_useitem",
2678 )
2679 .unwrap();
2680 assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2681 }
2682
2683 #[test]
2684 fn rewrite_call_site_with_args() {
2685 let got = rewrite_call_site_arg(
2686 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2687 "@",
2688 "amulet_of_glory_interface",
2689 "last_item",
2690 )
2691 .unwrap();
2692 assert_eq!(
2693 got,
2694 "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2695 );
2696 }
2697
2698 #[test]
2699 fn rewrite_call_site_gosub_no_args() {
2700 let got =
2701 rewrite_call_site_arg(" ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2702 assert_eq!(got, " ~some_proc(last_useitem);");
2703 }
2704
2705 #[test]
2706 fn rewrite_call_site_empty_arg_list() {
2707 let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2708 assert_eq!(got, "@foo(last_useitem);");
2709 }
2710
2711 #[test]
2712 fn rewrite_header_no_params() {
2713 let got = rewrite_header_add_param(
2714 "[label,civilian_give_runes]",
2715 "civilian_give_runes",
2716 "obj",
2717 "$last_useitem",
2718 )
2719 .unwrap();
2720 assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2721 }
2722
2723 #[test]
2724 fn rewrite_header_with_existing_params() {
2725 let got = rewrite_header_add_param(
2726 "[label,amulet_of_glory_interface](string $message)",
2727 "amulet_of_glory_interface",
2728 "obj",
2729 "$last_item",
2730 )
2731 .unwrap();
2732 assert_eq!(
2733 got,
2734 "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2735 );
2736 }
2737
2738 #[test]
2739 fn rewrite_header_proc_with_return_type() {
2740 let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2743 assert_eq!(got, "[proc,foo](obj $x)(int)");
2744 }
2745
2746 #[test]
2747 fn find_header_line_matches_trigger_and_name() {
2748 let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2749 assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2750 assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2751 assert_eq!(find_header_line(src, "label", "missing"), None);
2752 }
2753
2754 #[test]
2755 fn format_corruptors_shapes() {
2756 assert_eq!(
2757 format_corruptors(&[]),
2758 "calls a delay or subroutine that may supersede it"
2759 );
2760 assert_eq!(
2761 format_corruptors(&[("p_delay".to_string(), 21)]),
2762 "calls `p_delay` at line 21 which may supersede it"
2763 );
2764 assert_eq!(
2765 format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2766 "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2767 );
2768 assert_eq!(
2769 format_corruptors(&[
2770 ("p_delay".to_string(), 21),
2771 ("~chatnpc".to_string(), 11),
2772 ("~objbox".to_string(), 14),
2773 ]),
2774 "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2775 );
2776 assert_eq!(
2778 format_corruptors(&[
2779 ("p_delay".to_string(), 1),
2780 ("~a".to_string(), 2),
2781 ("~b".to_string(), 3),
2782 ("~c".to_string(), 4),
2783 ("~d".to_string(), 5),
2784 ]),
2785 "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2786 );
2787 assert_eq!(
2789 format_corruptors(&[("p_delay".to_string(), 0)]),
2790 "calls `p_delay` which may supersede it"
2791 );
2792 }
2793
2794 #[test]
2795 fn find_matching_close_paren_nested() {
2796 assert_eq!(find_matching_close_paren("()"), Some(1));
2797 assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2798 assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2799 assert_eq!(find_matching_close_paren("("), None);
2800 assert_eq!(find_matching_close_paren("abc"), None);
2801 }
2802
2803 #[test]
2808 fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2809 use std::collections::HashMap;
2810 use std::sync::Arc;
2811
2812 let last_useitem_op = 4270;
2813 let p_delay_op = 5001;
2814 let registry =
2815 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2816
2817 let mut callee = make_script(
2819 "consume_useitem",
2820 "label",
2821 100,
2822 vec![
2823 line(2), cmd(last_useitem_op),
2825 line(3),
2826 push_int(0),
2827 cmd(p_delay_op),
2828 ret(),
2829 ],
2830 );
2831 callee.source_path = "/virt/consume.rs2".to_string();
2832
2833 let mut caller = make_script(
2835 "use_on_loc",
2836 "oplocu",
2837 200,
2838 vec![
2839 line(1),
2840 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2841 ],
2842 );
2843 caller.source_path = "/virt/caller.rs2".to_string();
2844
2845 let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2848 source_cache.insert(
2849 "/virt/caller.rs2".to_string(),
2850 Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2851 );
2852 source_cache.insert(
2853 "/virt/consume.rs2".to_string(),
2854 Arc::new(
2855 "[label,consume_useitem]\n\
2856 last_useitem;\n\
2857 p_delay(0);\n"
2858 .to_string(),
2859 ),
2860 );
2861
2862 let scripts = vec![callee, caller];
2863 let mut checker = PointerChecker::new(&scripts, ®istry);
2864 checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
2865 let diags = checker.run();
2866
2867 let warning = diags
2870 .diagnostics()
2871 .iter()
2872 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2873 .expect("expected a stale-last_useitem warning");
2874
2875 assert_eq!(
2876 warning.help.len(),
2877 1,
2878 "warning should have exactly one Help block, got {}",
2879 warning.help.len()
2880 );
2881 let help = &warning.help[0];
2882 assert!(
2883 help.message.contains("consume_useitem"),
2884 "help message should name the callee, got: {}",
2885 help.message
2886 );
2887 assert!(
2888 help.message.contains("last_useitem"),
2889 "help message should name the pointer, got: {}",
2890 help.message
2891 );
2892
2893 assert_eq!(
2895 help.suggestions.len(),
2896 2,
2897 "help should include both call-site and header suggestions, \
2898 got {}: {:?}",
2899 help.suggestions.len(),
2900 help.suggestions
2901 .iter()
2902 .map(|s| &s.label)
2903 .collect::<Vec<_>>()
2904 );
2905
2906 let caller_sug = help
2908 .suggestions
2909 .iter()
2910 .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2911 .expect("expected a call-site suggestion on the caller file");
2912 assert!(
2913 caller_sug
2914 .replacement
2915 .contains("@consume_useitem(last_useitem)"),
2916 "call-site replacement must pass last_useitem as an arg, got: {}",
2917 caller_sug.replacement
2918 );
2919
2920 let header_sug = help
2922 .suggestions
2923 .iter()
2924 .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2925 .expect("expected a header suggestion on the callee file");
2926 assert!(
2927 header_sug.replacement.contains("(obj $last_useitem)"),
2928 "header replacement must add `obj $last_useitem` param, got: {}",
2929 header_sug.replacement
2930 );
2931
2932 assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2933 }
2934
2935 #[test]
2939 fn secondary_warning_falls_back_to_prose_help_without_source() {
2940 let last_useitem_op = 4270;
2941 let p_delay_op = 5001;
2942 let registry =
2943 registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2944
2945 let callee = make_script(
2946 "consume_useitem",
2947 "label",
2948 100,
2949 vec![
2950 line(1),
2951 cmd(last_useitem_op),
2952 line(2),
2953 push_int(0),
2954 cmd(p_delay_op),
2955 ret(),
2956 ],
2957 );
2958 let caller = make_script(
2959 "use_on_loc",
2960 "oplocu",
2961 200,
2962 vec![
2963 line(1),
2964 Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2965 ],
2966 );
2967
2968 let scripts = vec![callee, caller];
2969 let mut checker = PointerChecker::new(&scripts, ®istry);
2970 let diags = checker.run();
2972
2973 let warning = diags
2974 .diagnostics()
2975 .iter()
2976 .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2977 .expect("warning still fires without source cache");
2978
2979 assert_eq!(warning.help.len(), 1);
2980 let help = &warning.help[0];
2981 assert_eq!(
2982 help.suggestions.len(),
2983 0,
2984 "prose-only help should have no concrete suggestions"
2985 );
2986 assert_eq!(help.applicability, Applicability::Unspecified);
2987 }
2988}