Skip to main content

runec/
pointer_checker.rs

1use std::collections::{HashMap, HashSet, VecDeque};
2use std::path::PathBuf;
3
4use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
5use crate::diagnostic_messages as msg;
6use crate::diagnostics::{
7    Applicability, Diagnostic, DiagnosticsCollector, Help, Phase, Severity, Suggestion,
8};
9use crate::pointer::{PointerHolder, PointerSet, PointerType, command_pointers, trigger_pointers};
10use crate::symbol::{SymbolKind, SymbolRegistry};
11
12// ---------------------------------------------------------------------------
13// CFG re-compile access trace (profiling only). Records the file whose CFG is
14// built, so an LRU simulation can estimate the re-parse multiplier a streaming
15// "re-compile on demand" pointer check would pay — measured before committing
16// to that rearchitecture. Enabled by `RUNEC_TRACE_CFG`; built only with memprof.
17// ---------------------------------------------------------------------------
18#[cfg(feature = "memprof")]
19static CFG_TRACE: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
20
21#[cfg(feature = "memprof")]
22fn cfg_trace_push(source_path: &str) {
23    if std::env::var_os("RUNEC_TRACE_CFG").is_some() {
24        CFG_TRACE.lock().unwrap().push(source_path.to_string());
25    }
26}
27
28/// Simulate an LRU file cache over the recorded CFG-build sequence and report
29/// re-parse counts for several cache sizes (1.0x = each file parsed once).
30#[cfg(feature = "memprof")]
31pub(crate) fn cfg_trace_report() {
32    use tracing::info;
33    let trace = CFG_TRACE.lock().unwrap();
34    if trace.is_empty() {
35        return;
36    }
37    let distinct: HashSet<&str> = trace.iter().map(|s| s.as_str()).collect();
38    let nfiles = distinct.len().max(1);
39    info!(
40        "[trace] build_cfg calls: {}, distinct files: {}",
41        trace.len(),
42        nfiles
43    );
44    for &cap in &[16usize, 64, 256, 1024, nfiles] {
45        let mut lru: Vec<&str> = Vec::with_capacity(cap + 1);
46        let mut misses = 0usize;
47        for f in trace.iter() {
48            let f = f.as_str();
49            if let Some(pos) = lru.iter().position(|x| *x == f) {
50                lru.remove(pos);
51            } else {
52                misses += 1;
53            }
54            lru.insert(0, f);
55            if lru.len() > cap {
56                lru.pop();
57            }
58        }
59        info!(
60            "[trace] LRU cap {:>5}: {:>7} re-parses ({:.2}x of {} files)",
61            cap,
62            misses,
63            misses as f64 / nfiles as f64,
64            nfiles
65        );
66    }
67}
68
69// ---------------------------------------------------------------------------
70// Script source: resident slice (batch/stream) or recompile-on-demand (the
71// `RUNEC_RECOMPILE` memory mode, which never holds all compiled scripts).
72// ---------------------------------------------------------------------------
73
74/// A script handle that is either borrowed from the resident slice (zero-cost)
75/// or owned via an `Rc` from the recompile store. Derefs to `CompiledScript`, so
76/// call sites read fields the same way regardless of mode.
77pub(crate) enum ScriptRef<'a> {
78    Borrowed(&'a CompiledScript),
79    Owned(std::rc::Rc<CompiledScript>),
80}
81
82impl std::ops::Deref for ScriptRef<'_> {
83    type Target = CompiledScript;
84    fn deref(&self) -> &CompiledScript {
85        match self {
86            ScriptRef::Borrowed(s) => s,
87            ScriptRef::Owned(rc) => rc,
88        }
89    }
90}
91
92/// Where the pointer checker gets a script's compiled form. `Resident` borrows
93/// the already-compiled slice. `Recompile` calls back into a store that re-parses
94/// and compiles the script on demand (bounded LRU), so the 13 MB of compiled
95/// scripts need not be resident. The recompile getter is `FnMut` (mutates its
96/// cache) and not `Sync`, so that mode runs the checker single-threaded.
97pub(crate) enum ScriptSource<'a> {
98    Resident(&'a [CompiledScript]),
99    Recompile {
100        len: usize,
101        get: std::cell::RefCell<Box<dyn FnMut(usize) -> std::rc::Rc<CompiledScript> + 'a>>,
102    },
103}
104
105impl<'a> ScriptSource<'a> {
106    fn len(&self) -> usize {
107        match self {
108            ScriptSource::Resident(s) => s.len(),
109            ScriptSource::Recompile { len, .. } => *len,
110        }
111    }
112
113    /// Fetch script `idx`. Borrowed (resident) carries the slice lifetime, not
114    /// `&self`'s, so it doesn't pin a whole-`self` borrow — preserving the
115    /// checker's disjoint field borrows (scripts vs the mutable caches).
116    fn get(&self, idx: usize) -> ScriptRef<'a> {
117        match self {
118            ScriptSource::Resident(s) => ScriptRef::Borrowed(&(*s)[idx]),
119            ScriptSource::Recompile { get, .. } => ScriptRef::Owned((get.borrow_mut())(idx)),
120        }
121    }
122}
123
124// ---------------------------------------------------------------------------
125// Control flow graph node
126// ---------------------------------------------------------------------------
127
128#[derive(Debug)]
129struct CfgNode {
130    /// Index into `CompiledScript::instructions`, or `None` for synthetic nodes
131    /// (start node, pointer-instruction nodes).
132    instruction_index: Option<usize>,
133    /// For pointer-instruction nodes: the set of pointers this node establishes.
134    pointer_set: PointerSet,
135    /// Successor node indices.
136    next: Vec<usize>,
137    /// Predecessor node indices.
138    previous: Vec<usize>,
139}
140
141impl CfgNode {
142    fn new(instruction_index: Option<usize>) -> Self {
143        CfgNode {
144            instruction_index,
145            pointer_set: PointerSet::new(),
146            next: Vec::new(),
147            previous: Vec::new(),
148        }
149    }
150
151    fn pointer_node(pointer_set: PointerSet) -> Self {
152        CfgNode {
153            instruction_index: None,
154            pointer_set,
155            next: Vec::new(),
156            previous: Vec::new(),
157        }
158    }
159}
160
161// ---------------------------------------------------------------------------
162// Per-script analysis result
163// ---------------------------------------------------------------------------
164
165struct ScriptAnalysis {
166    nodes: Vec<CfgNode>,
167    /// `required[ptr_index]` = list of node indices whose instruction requires this pointer.
168    required: Vec<Vec<usize>>,
169    /// `set_list[ptr_index]` = list of node indices that establish this pointer.
170    set_list: Vec<Vec<usize>>,
171    /// `corrupted_list[ptr_index]` = list of node indices that corrupt this pointer.
172    corrupted_list: Vec<Vec<usize>>,
173    /// Node indices of Return instructions.
174    returns: Vec<usize>,
175}
176
177impl ScriptAnalysis {
178    fn new() -> Self {
179        let n = PointerType::COUNT;
180        ScriptAnalysis {
181            nodes: Vec::new(),
182            required: vec![Vec::new(); n],
183            set_list: vec![Vec::new(); n],
184            corrupted_list: vec![Vec::new(); n],
185            returns: Vec::new(),
186        }
187    }
188}
189
190// ---------------------------------------------------------------------------
191// PointerChecker
192// ---------------------------------------------------------------------------
193
194/// Read-only lookup tables derived once from the compiled scripts + registry.
195/// Shared via `Arc` across the per-chunk checkers that run on worker threads,
196/// so this (command-table-sized) data is built once per compile instead of once
197/// per thread — the pointer-check pass otherwise rebuilt all of it ~N-cores times.
198pub(crate) struct SharedMaps {
199    cmd_pointers: HashMap<String, PointerHolder>,
200    /// Reverse map: command opcode -> command name (lowercase).
201    opcode_to_name: HashMap<i32, String>,
202    /// Reverse map: script id -> index into `scripts`.
203    script_id_to_index: HashMap<i32, usize>,
204    /// Reverse map: script name -> index into `scripts` (first occurrence wins,
205    /// matching a linear `position(|s| s.name == name)` scan). Avoids an O(n)
206    /// scan per `validate_script`/`ensure_analysis` call (O(n²) overall).
207    script_name_to_index: HashMap<String, usize>,
208    /// Overlay interface names (normalized lowercase). If_button/inv_button triggers
209    /// for non-overlay interfaces grant p_active_player, matching ServerPointerChecker.
210    overlay_interfaces: HashSet<String>,
211}
212
213pub struct PointerChecker<'a> {
214    scripts: ScriptSource<'a>,
215    #[allow(dead_code)]
216    registry: &'a SymbolRegistry,
217    /// Read-only lookup tables, shared (`Arc`) across worker threads.
218    shared: std::sync::Arc<SharedMaps>,
219    /// Optional source-text cache, keyed by `CompiledScript::source_path`.
220    /// When present, the checker attaches rustc-style Help/Suggestion
221    /// blocks to its warnings. When `None`, warnings still fire but carry
222    /// no concrete fix text. Read-only; never feeds codegen.
223    source_cache: Option<crate::SourceProvider<'a>>,
224    // Caches
225    script_analyses: HashMap<String, ScriptAnalysis>,
226    script_pointers: HashMap<String, PointerHolder>,
227    pending_analyses: HashSet<String>,
228    pending_scripts: HashSet<String>,
229}
230
231impl SharedMaps {
232    /// Build the read-only lookup tables from the script identities (id, name) +
233    /// registry. Taking `(id, name)` idents rather than the compiled slice lets
234    /// the recompile mode build these from lightweight metas (no held bytecode).
235    fn build<'b>(idents: impl Iterator<Item = (i32, &'b str)>, registry: &SymbolRegistry) -> Self {
236        // Build reverse opcode -> name map from registry.commands
237        let mut opcode_to_name = HashMap::new();
238        for (name, sym) in &registry.commands {
239            if let SymbolKind::Command { opcode, .. } = &sym.kind {
240                opcode_to_name.insert(*opcode, name.to_lowercase());
241            }
242        }
243
244        // Build reverse id->index and name->index maps. Insert only the first
245        // name occurrence so lookups match a `position(|s| s.name == name)` scan
246        // when multiple triggers share a name.
247        let mut script_id_to_index = HashMap::new();
248        let mut script_name_to_index = HashMap::new();
249        for (i, (id, name)) in idents.enumerate() {
250            script_id_to_index.insert(id, i);
251            script_name_to_index.entry(name.to_string()).or_insert(i);
252        }
253
254        // Build overlay interface set from entity_ids (OverlayInterface type).
255        // Any if_button/inv_button trigger whose interface is NOT in this set
256        // gets p_active_player granted, matching ServerPointerChecker.
257        let mut overlay_interfaces = HashSet::new();
258        for (name, entry) in &registry.entity_ids {
259            if let Some(e) = entry.primary
260                && e.const_type == crate::types::Type::OverlayInterface
261            {
262                overlay_interfaces.insert(name.to_lowercase().replace(' ', "_"));
263            }
264        }
265
266        SharedMaps {
267            cmd_pointers: command_pointers(),
268            opcode_to_name,
269            script_id_to_index,
270            script_name_to_index,
271            overlay_interfaces,
272        }
273    }
274}
275
276impl<'a> PointerChecker<'a> {
277    pub fn new(scripts: &'a [CompiledScript], registry: &'a SymbolRegistry) -> Self {
278        let shared = std::sync::Arc::new(SharedMaps::build(
279            scripts.iter().map(|s| (s.id, s.name.as_str())),
280            registry,
281        ));
282        Self::with_shared(ScriptSource::Resident(scripts), registry, shared)
283    }
284
285    /// Build the read-only lookup tables once, so a fleet of per-chunk checkers
286    /// can share them across threads (`Arc::clone`) instead of each rebuilding
287    /// the full command/script tables.
288    pub(crate) fn build_shared(
289        scripts: &[CompiledScript],
290        registry: &SymbolRegistry,
291    ) -> std::sync::Arc<SharedMaps> {
292        std::sync::Arc::new(SharedMaps::build(
293            scripts.iter().map(|s| (s.id, s.name.as_str())),
294            registry,
295        ))
296    }
297
298    /// Build the shared maps for the recompile mode from lightweight `(id, name)`
299    /// idents, so no compiled bytecode need be resident to construct them.
300    pub(crate) fn build_shared_idents(
301        idents: &[(i32, String)],
302        registry: &SymbolRegistry,
303    ) -> std::sync::Arc<SharedMaps> {
304        std::sync::Arc::new(SharedMaps::build(
305            idents.iter().map(|(id, name)| (*id, name.as_str())),
306            registry,
307        ))
308    }
309
310    /// Construct a checker over pre-built shared maps. Each worker thread gets
311    /// its own checker (own memoization caches) but shares the read-only maps.
312    pub(crate) fn with_shared(
313        scripts: ScriptSource<'a>,
314        registry: &'a SymbolRegistry,
315        shared: std::sync::Arc<SharedMaps>,
316    ) -> Self {
317        PointerChecker {
318            scripts,
319            registry,
320            shared,
321            source_cache: None,
322            script_analyses: HashMap::new(),
323            script_pointers: HashMap::new(),
324            pending_analyses: HashSet::new(),
325            pending_scripts: HashSet::new(),
326        }
327    }
328
329    /// Attach a source-text cache so emitted warnings can carry concrete
330    /// before/after suggestion text. Purely diagnostic — never touches
331    /// bytecode, script metadata, or output ordering.
332    pub fn set_source_cache(&mut self, provider: crate::SourceProvider<'a>) {
333        self.source_cache = Some(provider);
334    }
335
336    /// Check if an if_button/inv_button trigger on a non-overlay interface
337    /// grants p_active_player. Matches ServerPointerChecker.setsPointerTrigger().
338    fn interface_trigger_grants_protected(&self, trigger: &str, script_name: &str) -> bool {
339        if !crate::trigger_table::is_button(trigger) {
340            return false;
341        }
342        // Extract interface name from script name: "[trigger,interface_name:component]"
343        let subject = script_name
344            .trim_start_matches('[')
345            .trim_end_matches(']')
346            .split_once(',')
347            .map(|(_, rest)| rest)
348            .unwrap_or("");
349        let iface_name = subject
350            .split(':')
351            .next()
352            .unwrap_or("")
353            .to_lowercase()
354            .replace(' ', "_");
355        if iface_name.is_empty() {
356            return false;
357        }
358        // Non-overlay interfaces grant p_active_player
359        !self.shared.overlay_interfaces.contains(&iface_name)
360    }
361
362    /// Run pointer checking on all scripts and return collected diagnostics.
363    pub fn run(&mut self) -> DiagnosticsCollector {
364        let names = self.script_names();
365        self.validate_names(&names)
366    }
367
368    /// Script names in validation order (the order of `scripts`).
369    pub fn script_names(&self) -> Vec<String> {
370        (0..self.scripts.len())
371            .map(|i| self.scripts.get(i).name.clone())
372            .collect()
373    }
374
375    /// Validate the given scripts, returning their diagnostics in `names` order.
376    ///
377    /// The per-script caches are pure memoization (a script's analysis is a
378    /// function of the read-only scripts + registry), so splitting
379    /// `script_names()` into chunks and giving each chunk its own
380    /// `PointerChecker` produces byte-identical diagnostics to validating
381    /// everything in a single checker — which lets the pass run across threads.
382    pub fn validate_names(&mut self, names: &[String]) -> DiagnosticsCollector {
383        let mut diagnostics = DiagnosticsCollector::new();
384        for script_name in names {
385            self.validate_script(script_name, &mut diagnostics);
386            // A script's CFG (and any callee CFGs built to derive summaries) is
387            // only needed during its own validation; the cross-script pointer
388            // summaries persist in `script_pointers`. Free the CFGs now so peak
389            // scratch is ~one script's CFG instead of the whole chunk's — the
390            // checker otherwise memoizes every analyzed CFG for the chunk's life.
391            // (`build_rule_a_help` rebuilds a callee's CFG on demand if a later
392            // warning needs it, so diagnostics are unchanged.)
393            self.script_analyses.clear();
394        }
395        diagnostics
396    }
397
398    fn validate_script(&mut self, script_name: &str, diagnostics: &mut DiagnosticsCollector) {
399        // Find the script
400        let script_idx = match self.shared.script_name_to_index.get(script_name) {
401            Some(&i) => i,
402            None => return,
403        };
404        let trigger = self.scripts.get(script_idx).trigger.clone();
405        let source_path = self.scripts.get(script_idx).source_path.clone();
406        let trigger_set = trigger_pointers(&trigger);
407
408        // Ensure analysis exists
409        self.ensure_analysis(script_name);
410
411        for &ptr in &PointerType::ALL {
412            let ptr_idx = ptr.index();
413
414            // Get analysis data — we need to work with references carefully
415            let analysis = match self.script_analyses.get(script_name) {
416                Some(a) => a,
417                None => continue,
418            };
419
420            let required_nodes: Vec<usize> = analysis.required[ptr_idx].clone();
421            if required_nodes.is_empty() {
422                continue;
423            }
424
425            // Build corrupted set: start with the analysis corrupted nodes. The
426            // CFG stores only the compact `corrupted_list` Vec; the BFS needs an
427            // O(1) lookup set, so materialize one here (transient, dropped after
428            // this pointer's check) rather than retaining a duplicate per CFG.
429            let mut corrupted: HashSet<usize> =
430                analysis.corrupted_list[ptr_idx].iter().copied().collect();
431
432            // If the trigger doesn't set this pointer, add the start node (node 0) as corrupted.
433            // Special case: if_button/inv_button triggers on non-overlay interfaces
434            // grant p_active_player, matching ServerPointerChecker.
435            let trigger_provides = if trigger_set.contains(ptr) {
436                true
437            } else if ptr == PointerType::PActivePlayer {
438                self.interface_trigger_grants_protected(&trigger, script_name)
439            } else {
440                false
441            };
442            if !trigger_provides {
443                corrupted.insert(0);
444            }
445
446            if corrupted.is_empty() {
447                continue;
448            }
449
450            let set_blocked: HashSet<usize> = analysis.set_list[ptr_idx].iter().copied().collect();
451
452            // Try to find a path from a required node backwards to a corrupted node
453            let path = self.find_edge_path(
454                script_name,
455                &required_nodes,
456                |node_idx| corrupted.contains(&node_idx),
457                &set_blocked,
458            );
459
460            let mut reported_via_main_bfs = false;
461            if let Some(path) = path {
462                if path.is_empty() {
463                    continue;
464                }
465                reported_via_main_bfs = true;
466
467                let end_node_idx = path[path.len() - 1];
468                let start_node_idx = path[0];
469
470                let is_start_node = end_node_idx == 0;
471                let repr = ptr.representation();
472                let static_only = is_static_only_pointer(ptr);
473
474                // Use softer "stale reference" wording for last_* / find_*
475                // pointers — those are not tracked by the runtime and the
476                // scripts compile and run; "corrupted" overstates it. The
477                // engine-tracked family keeps the strong wording because a
478                // missing pointer there is a real pointerCheck crash.
479                let error_msg = if is_start_node {
480                    if static_only {
481                        msg::fmt(msg::POINTER_STALE_UNINIT, &[repr])
482                    } else {
483                        msg::fmt(msg::POINTER_UNINITIALIZED, &[repr])
484                    }
485                } else if static_only {
486                    msg::fmt(msg::POINTER_STALE, &[repr])
487                } else {
488                    msg::fmt(msg::POINTER_CORRUPTED, &[repr])
489                };
490
491                let analysis = self.script_analyses.get(script_name).unwrap();
492                let script_ref = self.scripts.get(script_idx);
493                let instructions = &script_ref.instructions;
494                let req_line = analysis.nodes[start_node_idx]
495                    .instruction_index
496                    .map(|idx| resolve_line(instructions, idx))
497                    .unwrap_or(0);
498
499                // Pointer diagnostics are reported as warnings: they flag
500                // real static-analysis findings but should not fail the
501                // compile. Runtime pointer enforcement (via engine
502                // `pointerCheck`) still catches genuine misuse.
503                diagnostics.add(Diagnostic {
504                    file: PathBuf::from(&source_path),
505                    line: req_line,
506                    column: 0,
507                    message: error_msg,
508                    severity: Severity::Warning,
509                    phase: Phase::PointerCheck,
510                    help: Vec::new(),
511                });
512
513                let read_hint = if static_only {
514                    msg::fmt(msg::POINTER_READ_HERE, &[repr])
515                } else {
516                    msg::fmt(msg::POINTER_REQUIRED_LOC, &[repr])
517                };
518                diagnostics.add(Diagnostic {
519                    file: PathBuf::from(&source_path),
520                    line: req_line,
521                    column: 0,
522                    message: read_hint,
523                    severity: Severity::Info,
524                    phase: Phase::PointerCheck,
525                    help: Vec::new(),
526                });
527
528                if !is_start_node {
529                    let corrupt_line = analysis.nodes[end_node_idx]
530                        .instruction_index
531                        .map(|idx| resolve_line(instructions, idx))
532                        .unwrap_or(0);
533
534                    let cause_hint = if static_only {
535                        msg::fmt(msg::POINTER_SUPERSEDED_HERE, &[repr])
536                    } else {
537                        msg::fmt(msg::POINTER_CORRUPTED_LOC, &[repr])
538                    };
539                    diagnostics.add(Diagnostic {
540                        file: PathBuf::from(&source_path),
541                        line: corrupt_line,
542                        column: 0,
543                        message: cause_hint,
544                        severity: Severity::Info,
545                        phase: Phase::PointerCheck,
546                        help: Vec::new(),
547                    });
548                }
549            }
550
551            // Secondary check: flag nodes that simultaneously require AND
552            // corrupt this pointer. The 2004scape TS PointerChecker does not
553            // catch these (its BFS only inspects predecessors of required
554            // nodes, never the required node itself), but they correspond to
555            // real "@jump to a label that consumes then invalidates the
556            // pointer" patterns that are worth surfacing.
557            //
558            // Only emit for static-only pointers (last_*, find_*). The
559            // active_player / p_active_player / active_npc / active_loc /
560            // active_obj family is runtime-tracked by the engine and, in
561            // practice, the callers in these patterns do not access the
562            // pointer again after the gosub, so flagging them is noise.
563            if !reported_via_main_bfs && is_static_only_pointer(ptr) {
564                // Collect the (node, line) pairs that both require and corrupt
565                // this pointer, then drop the analysis borrow so help generation
566                // can take `&mut self` (it may rebuild a cleared callee's CFG).
567                let targets: Vec<(usize, usize)> = {
568                    let analysis = self.script_analyses.get(script_name).unwrap();
569                    let script_ref = self.scripts.get(script_idx);
570                    let instructions = &script_ref.instructions;
571                    let corrupted_nodes: HashSet<usize> =
572                        analysis.corrupted_list[ptr_idx].iter().copied().collect();
573                    required_nodes
574                        .iter()
575                        .filter(|&&node_idx| corrupted_nodes.contains(&node_idx))
576                        .map(|&node_idx| {
577                            let line = analysis.nodes[node_idx]
578                                .instruction_index
579                                .map(|idx| resolve_line(instructions, idx))
580                                .unwrap_or(0);
581                            (node_idx, line)
582                        })
583                        .collect()
584                };
585                let mut seen_lines: HashSet<usize> = HashSet::new();
586                let repr = ptr.representation();
587                for (node_idx, line) in targets {
588                    if !seen_lines.insert(line) {
589                        continue;
590                    }
591
592                    // Build a rustc-style Help pointing at the concrete fix:
593                    // thread the pointer through the callee as a parameter.
594                    // Falls back to prose-only if source cache is absent or
595                    // the callee can't be identified.
596                    let help =
597                        self.build_rule_a_help(ptr, &source_path, line, node_idx, script_idx);
598
599                    // Secondary-heuristic warning: both "read here" and
600                    // "superseded here" collapse to the same Jump/Gosub
601                    // node, so the info hints from the main-BFS path would
602                    // just triple-print the same source line. The Help
603                    // block already pinpoints the call site and the label
604                    // header with a concrete fix — skip the duplicate
605                    // hints and use the softer stale wording.
606                    let mut diag = Diagnostic {
607                        file: PathBuf::from(&source_path),
608                        line,
609                        column: 0,
610                        message: msg::fmt(msg::POINTER_STALE, &[repr]),
611                        severity: Severity::Warning,
612                        phase: Phase::PointerCheck,
613                        help: Vec::new(),
614                    };
615                    if let Some(h) = help {
616                        diag.help.push(h);
617                    }
618                    diagnostics.add(diag);
619                }
620            }
621        }
622    }
623
624    // -----------------------------------------------------------------------
625    // BFS path finding
626    // -----------------------------------------------------------------------
627
628    /// Find a path from any start node backwards through predecessor edges to
629    /// a node satisfying `end_pred`, avoiding nodes in `blocked`.
630    ///
631    /// Returns the path from start to end (inclusive) if found.
632    fn find_edge_path(
633        &self,
634        script_name: &str,
635        starts: &[usize],
636        end_pred: impl Fn(usize) -> bool,
637        blocked: &HashSet<usize>,
638    ) -> Option<Vec<usize>> {
639        let analysis = self.script_analyses.get(script_name)?;
640
641        let mut queue: VecDeque<usize> = VecDeque::new();
642        let mut visited: HashSet<usize> = HashSet::new();
643        // Track which node led us to each node, plus which start node originated this path
644        let mut sources: HashMap<usize, (usize, usize)> = HashMap::new(); // node -> (from_node, start_node)
645
646        // Seed BFS: for each start node, add its predecessors.
647        // Matches TS: we do NOT check start nodes themselves against the end predicate.
648        // This prevents false positives when a Gosub node is both required and corrupted
649        // for the same pointer (the requirement is satisfied first within the proc).
650        for &start in starts {
651            for &prev in &analysis.nodes[start].previous {
652                if blocked.contains(&prev) || visited.contains(&prev) {
653                    continue;
654                }
655                visited.insert(prev);
656                queue.push_back(prev);
657                sources.insert(prev, (start, start));
658            }
659        }
660
661        while let Some(current) = queue.pop_front() {
662            if end_pred(current) {
663                // Reconstruct path from current back to start
664                let mut path = vec![current];
665                let mut node = current;
666                while let Some(&(from, start)) = sources.get(&node) {
667                    if from == start && starts.contains(&from) {
668                        path.push(from);
669                        break;
670                    }
671                    path.push(from);
672                    node = from;
673                }
674                path.reverse();
675                return Some(path);
676            }
677
678            let (_, start_node) = sources[&current];
679
680            for &prev in &analysis.nodes[current].previous {
681                if blocked.contains(&prev) || visited.contains(&prev) {
682                    continue;
683                }
684                visited.insert(prev);
685                queue.push_back(prev);
686                sources.insert(prev, (current, start_node));
687            }
688        }
689
690        None
691    }
692
693    /// Static version of find_edge_path that operates on nodes directly,
694    /// used by get_script_pointers where we can't borrow &self.
695    fn find_edge_path_static(
696        nodes: &[CfgNode],
697        starts: &[usize],
698        end_pred: impl Fn(usize) -> bool,
699        blocked: &HashSet<usize>,
700    ) -> Option<Vec<usize>> {
701        let mut queue: VecDeque<usize> = VecDeque::new();
702        let mut visited: HashSet<usize> = HashSet::new();
703        let mut sources: HashMap<usize, (usize, usize)> = HashMap::new();
704
705        for &start in starts {
706            for &prev in &nodes[start].previous {
707                if blocked.contains(&prev) || visited.contains(&prev) {
708                    continue;
709                }
710                visited.insert(prev);
711                queue.push_back(prev);
712                sources.insert(prev, (start, start));
713            }
714        }
715
716        while let Some(current) = queue.pop_front() {
717            if end_pred(current) {
718                let mut path = vec![current];
719                let mut node = current;
720                while let Some(&(from, start)) = sources.get(&node) {
721                    if from == start && starts.contains(&from) {
722                        path.push(from);
723                        break;
724                    }
725                    path.push(from);
726                    node = from;
727                }
728                path.reverse();
729                return Some(path);
730            }
731
732            for &prev in &nodes[current].previous {
733                if blocked.contains(&prev) || visited.contains(&prev) {
734                    continue;
735                }
736                visited.insert(prev);
737                queue.push_back(prev);
738                sources.insert(prev, (current, sources[&current].1));
739            }
740        }
741
742        None
743    }
744
745    // -----------------------------------------------------------------------
746    // Analysis
747    // -----------------------------------------------------------------------
748
749    fn ensure_analysis(&mut self, script_name: &str) {
750        if self.script_analyses.contains_key(script_name) {
751            return;
752        }
753        if self.pending_analyses.contains(script_name) {
754            return; // cycle detection
755        }
756        self.pending_analyses.insert(script_name.to_string());
757
758        let script_idx = match self.shared.script_name_to_index.get(script_name) {
759            Some(&i) => i,
760            None => return,
761        };
762
763        let mut analysis = self.build_cfg(script_idx);
764        self.categorize_nodes(script_idx, &mut analysis);
765
766        self.script_analyses
767            .insert(script_name.to_string(), analysis);
768        self.pending_analyses.remove(script_name);
769    }
770
771    // -----------------------------------------------------------------------
772    // CFG construction
773    // -----------------------------------------------------------------------
774
775    fn build_cfg(&self, script_idx: usize) -> ScriptAnalysis {
776        let script = self.scripts.get(script_idx);
777        #[cfg(feature = "memprof")]
778        cfg_trace_push(&script.source_path);
779        let instructions = &script.instructions;
780        let mut analysis = ScriptAnalysis::new();
781
782        // Node 0 = start node (no instruction)
783        analysis.nodes.push(CfgNode::new(None));
784
785        // Map instruction index -> CFG node index (skipping LineNumber instructions)
786        let mut instr_to_node: HashMap<usize, usize> = HashMap::new();
787        let mut node_order: Vec<usize> = Vec::new(); // instruction indices in order
788
789        for (i, instr) in instructions.iter().enumerate() {
790            if instr.opcode == Opcode::LineNumber {
791                continue;
792            }
793            let node_idx = analysis.nodes.len();
794            instr_to_node.insert(i, node_idx);
795            node_order.push(i);
796            analysis.nodes.push(CfgNode::new(Some(i)));
797        }
798
799        if node_order.is_empty() {
800            return analysis;
801        }
802
803        // Connect start node to first instruction node
804        let first_node = instr_to_node[&node_order[0]];
805        add_edge(&mut analysis.nodes, 0, first_node);
806
807        // Build edges based on instruction semantics
808        for (order_idx, &instr_idx) in node_order.iter().enumerate() {
809            let node_idx = instr_to_node[&instr_idx];
810            let instr = &instructions[instr_idx];
811
812            let is_terminal = matches!(
813                instr.opcode,
814                Opcode::Branch | Opcode::Return | Opcode::Jump | Opcode::JumpWithParams
815            );
816
817            // Handle jump targets for branches (conditional and unconditional).
818            // Jump targets often land on a LineNumber instruction (emitted for the
819            // body's first source line); LineNumbers are not in `instr_to_node`, so
820            // walk forward to the first real instruction before resolving.
821            match instr.opcode {
822                Opcode::Branch
823                | Opcode::BranchNot
824                | Opcode::BranchEquals
825                | Opcode::BranchLessThan
826                | Opcode::BranchGreaterThan
827                | Opcode::BranchLessThanOrEquals
828                | Opcode::BranchGreaterThanOrEquals
829                | Opcode::LongBranchNot
830                | Opcode::LongBranchEquals
831                | Opcode::LongBranchLessThan
832                | Opcode::LongBranchGreaterThan
833                | Opcode::LongBranchLessThanOrEquals
834                | Opcode::LongBranchGreaterThanOrEquals
835                | Opcode::ObjBranchEquals
836                | Opcode::ObjBranchNot => {
837                    if let Operand::JumpTarget(target_instr_idx) = &instr.operand
838                        && let Some(target_node) =
839                            resolve_target_node(*target_instr_idx, instructions, &instr_to_node)
840                    {
841                        add_edge(&mut analysis.nodes, node_idx, target_node);
842                    }
843                }
844
845                Opcode::Switch => {
846                    if let Operand::SwitchTable(tbl_idx) = &instr.operand {
847                        let cases = &script.switch_tables[*tbl_idx as usize];
848                        for &(_, target_instr_idx) in cases.iter() {
849                            if let Some(target_node) =
850                                resolve_target_node(target_instr_idx, instructions, &instr_to_node)
851                            {
852                                add_edge(&mut analysis.nodes, node_idx, target_node);
853                            }
854                        }
855                    }
856                }
857
858                _ => {}
859            }
860
861            // Add fallthrough edge (next non-LineNumber instruction) for non-terminal instructions
862            if !is_terminal
863                && let Some(next_order_idx) = order_idx.checked_add(1)
864                && next_order_idx < node_order.len()
865            {
866                let next_node = instr_to_node[&node_order[next_order_idx]];
867                add_edge(&mut analysis.nodes, node_idx, next_node);
868            }
869
870            // For conditional branches: also add fallthrough
871            // (already handled above since conditional branches are not terminal)
872
873            // Track Return nodes
874            if instr.opcode == Opcode::Return {
875                analysis.returns.push(node_idx);
876            }
877        }
878
879        // Pointer inversion: detect Command -> PushConstantInt(0/1) -> BranchEquals patterns
880        self.insert_pointer_nodes(script_idx, &mut analysis, &instr_to_node, &node_order);
881
882        analysis
883    }
884
885    /// Detect conditional pointer setting patterns and insert synthetic
886    /// PointerInstructionNode nodes.
887    fn insert_pointer_nodes(
888        &self,
889        script_idx: usize,
890        analysis: &mut ScriptAnalysis,
891        instr_to_node: &HashMap<usize, usize>,
892        node_order: &[usize],
893    ) {
894        let script_ref = self.scripts.get(script_idx);
895        let instructions = &script_ref.instructions;
896
897        // Look for the pattern: [Command with conditional_set] ... [PushConstantInt(0 or 1)] [BranchEquals]
898        // The Command may not be immediately before PushConstantInt because argument
899        // pushes sit between them. So we scan backwards from PushConstantInt+BranchEquals
900        // to find the nearest Command.
901        for window_end in 2..node_order.len() {
902            let push_instr_idx = node_order[window_end - 1];
903            let branch_instr_idx = node_order[window_end];
904
905            let push_instr = &instructions[push_instr_idx];
906            let branch_instr = &instructions[branch_instr_idx];
907
908            // Check: PushConstantInt(0 or 1) followed by BranchEquals
909            let push_value = match &push_instr.operand {
910                Operand::Int(v) if *v == 0 || *v == 1 => *v,
911                _ => continue,
912            };
913            if push_instr.opcode != Opcode::PushConstantInt {
914                continue;
915            }
916            if branch_instr.opcode != Opcode::BranchEquals {
917                continue;
918            }
919
920            // Scan backwards to find the nearest Command instruction
921            let mut cmd_instr_idx = None;
922            for scan in (0..window_end - 1).rev() {
923                let idx = node_order[scan];
924                if instructions[idx].opcode == Opcode::Command {
925                    cmd_instr_idx = Some(idx);
926                    break;
927                }
928                // Stop scanning if we hit a branch/return/switch (control flow boundary)
929                if matches!(
930                    instructions[idx].opcode,
931                    Opcode::Branch
932                        | Opcode::Return
933                        | Opcode::Switch
934                        | Opcode::BranchEquals
935                        | Opcode::BranchNot
936                        | Opcode::BranchLessThan
937                        | Opcode::BranchGreaterThan
938                        | Opcode::BranchLessThanOrEquals
939                        | Opcode::BranchGreaterThanOrEquals
940                ) {
941                    break;
942                }
943            }
944            let cmd_instr_idx = match cmd_instr_idx {
945                Some(idx) => idx,
946                None => continue,
947            };
948            let cmd_instr = &instructions[cmd_instr_idx];
949
950            // Look up command pointer info
951            let cmd_name = self.resolve_command_name(cmd_instr, &script_ref.strings);
952            let cmd_name = match cmd_name {
953                Some(n) => n,
954                None => continue,
955            };
956
957            let holder = match self.shared.cmd_pointers.get(&cmd_name) {
958                Some(h) => h,
959                None => continue,
960            };
961
962            if !holder.conditional_set {
963                continue;
964            }
965
966            if holder.set.is_empty() {
967                continue;
968            }
969
970            let branch_node_idx = instr_to_node[&branch_instr_idx];
971
972            // Create a synthetic pointer node with the command's set pointers
973            let ptr_node_idx = analysis.nodes.len();
974            analysis.nodes.push(CfgNode::pointer_node(holder.set));
975
976            if push_value == 0 {
977                // Inverted conditional: pointer is set when the branch is NOT taken
978                // (i.e., the fallthrough path after BranchEquals).
979                // The BranchEquals jumps when equal (value == 0 means "not found"),
980                // so the fallthrough means "found" -> pointer is set.
981                //
982                // Insert pointer node between BranchEquals and its fallthrough target.
983                // BranchEquals fallthrough = the next node in sequence after BranchEquals.
984                let fallthrough_targets: Vec<usize> = analysis.nodes[branch_node_idx]
985                    .next
986                    .iter()
987                    .copied()
988                    .filter(|&n| {
989                        // fallthrough target = not the jump target
990                        if let Operand::JumpTarget(target) = &branch_instr.operand
991                            && let Some(jump_node) =
992                                resolve_target_node(*target, instructions, instr_to_node)
993                        {
994                            return n != jump_node;
995                        }
996                        true
997                    })
998                    .collect();
999
1000                for ft_target in fallthrough_targets {
1001                    // Remove edge: branch -> fallthrough
1002                    remove_edge(&mut analysis.nodes, branch_node_idx, ft_target);
1003                    // Add: branch -> ptr_node -> fallthrough
1004                    add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1005                    add_edge(&mut analysis.nodes, ptr_node_idx, ft_target);
1006                }
1007            } else {
1008                // push_value == 1: pointer is set when the branch IS taken
1009                // BranchEquals jumps when equal (value == 1 means "found"),
1010                // so the jump target means "found" -> pointer is set.
1011                if let Operand::JumpTarget(target) = &branch_instr.operand
1012                    && let Some(jump_target_node) =
1013                        resolve_target_node(*target, instructions, instr_to_node)
1014                {
1015                    // Remove edge: branch -> jump_target
1016                    remove_edge(&mut analysis.nodes, branch_node_idx, jump_target_node);
1017                    // Add: branch -> ptr_node -> jump_target
1018                    add_edge(&mut analysis.nodes, branch_node_idx, ptr_node_idx);
1019                    add_edge(&mut analysis.nodes, ptr_node_idx, jump_target_node);
1020                }
1021            }
1022        }
1023    }
1024
1025    // -----------------------------------------------------------------------
1026    // Node categorization
1027    // -----------------------------------------------------------------------
1028
1029    fn categorize_nodes(&mut self, script_idx: usize, analysis: &mut ScriptAnalysis) {
1030        let script_ref = self.scripts.get(script_idx);
1031        let instructions = &script_ref.instructions;
1032
1033        for node_idx in 0..analysis.nodes.len() {
1034            let instr_idx = match analysis.nodes[node_idx].instruction_index {
1035                Some(i) => i,
1036                None => {
1037                    // Synthetic pointer node — categorize its set pointers
1038                    let ptr_set = analysis.nodes[node_idx].pointer_set;
1039                    if !ptr_set.is_empty() {
1040                        for ptr in ptr_set.iter() {
1041                            let pi = ptr.index();
1042                            analysis.set_list[pi].push(node_idx);
1043                        }
1044                    }
1045                    continue;
1046                }
1047            };
1048
1049            let instr = &instructions[instr_idx];
1050
1051            match instr.opcode {
1052                Opcode::Command => {
1053                    let cmd_name = self.resolve_command_name(instr, &script_ref.strings);
1054                    if let Some(name) = cmd_name
1055                        && let Some(holder) = self.shared.cmd_pointers.get(&name).cloned()
1056                    {
1057                        self.apply_holder(analysis, node_idx, &holder);
1058                    }
1059                }
1060
1061                Opcode::Gosub | Opcode::GosubWithParams => {
1062                    if let Operand::Int(script_id) = &instr.operand {
1063                        let callee_holder = self.get_script_pointers(*script_id);
1064                        self.apply_holder(analysis, node_idx, &callee_holder);
1065                    }
1066                }
1067
1068                Opcode::Jump | Opcode::JumpWithParams => {
1069                    if let Operand::Int(script_id) = &instr.operand {
1070                        let callee_holder = self.get_script_pointers(*script_id);
1071                        self.apply_holder(analysis, node_idx, &callee_holder);
1072                    }
1073                }
1074
1075                // Var reads/writes: dot-prefixed sources (`.%v`) route to the
1076                // secondary active_* pointer. The compiler encodes this by
1077                // setting bit 16 of the operand (see compiler.rs, where
1078                // secondary game vars emit `(1 << 16) | var_id`). TS emits
1079                // distinct opcodes (PushVar/PushVar2); we flatten that into a
1080                // single opcode + operand flag and recover it here.
1081                Opcode::PushVarp | Opcode::PushVarbit => {
1082                    let pi = if is_secondary_var_operand(&instr.operand) {
1083                        PointerType::ActivePlayer2.index()
1084                    } else {
1085                        PointerType::ActivePlayer.index()
1086                    };
1087                    analysis.required[pi].push(node_idx);
1088                }
1089
1090                Opcode::PopVarp | Opcode::PopVarbit => {
1091                    let pi = if is_secondary_var_operand(&instr.operand) {
1092                        PointerType::ActivePlayer2.index()
1093                    } else {
1094                        PointerType::ActivePlayer.index()
1095                    };
1096                    analysis.required[pi].push(node_idx);
1097                }
1098
1099                Opcode::PushVarn | Opcode::PopVarn => {
1100                    let pi = if is_secondary_var_operand(&instr.operand) {
1101                        PointerType::ActiveNpc2.index()
1102                    } else {
1103                        PointerType::ActiveNpc.index()
1104                    };
1105                    analysis.required[pi].push(node_idx);
1106                }
1107
1108                // PushVars/PopVars are global server vars — no pointer requirements
1109                _ => {}
1110            }
1111        }
1112    }
1113
1114    fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
1115        for ptr in holder.required.iter() {
1116            let pi = ptr.index();
1117            analysis.required[pi].push(node_idx);
1118        }
1119        for ptr in holder.set.iter() {
1120            let pi = ptr.index();
1121            analysis.set_list[pi].push(node_idx);
1122        }
1123        for ptr in holder.corrupted.iter() {
1124            let pi = ptr.index();
1125            analysis.corrupted_list[pi].push(node_idx);
1126        }
1127    }
1128
1129    // -----------------------------------------------------------------------
1130    // Callee pointer resolution
1131    // -----------------------------------------------------------------------
1132
1133    /// Get the merged pointer requirements/effects of a called script.
1134    ///
1135    /// Uses graph reachability (matching the TS `calculatePointers`):
1136    /// - **requires**: is there a path from a required-node backwards to graph[0]
1137    ///   without passing through a setter? If yes, the script needs this pointer
1138    ///   from its caller.
1139    /// - **sets**: is there any return-path that reaches graph[0] or a corruptor
1140    ///   without passing through a setter? If NO such path, the script guarantees
1141    ///   the pointer is set on all exit paths.
1142    /// - **corrupts**: is there a return-path that reaches a corruptor without
1143    ///   passing through a setter? If yes, the script may corrupt this pointer.
1144    fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
1145        // Find script by ID
1146        let script_idx = match self.shared.script_id_to_index.get(&script_id) {
1147            Some(&i) => i,
1148            None => {
1149                return PointerHolder::default();
1150            }
1151        };
1152        let script_name = self.scripts.get(script_idx).name.clone();
1153
1154        // Check cache
1155        if let Some(holder) = self.script_pointers.get(&script_name) {
1156            return holder.clone();
1157        }
1158
1159        // Cycle detection
1160        if self.pending_scripts.contains(&script_name) {
1161            return PointerHolder::default();
1162        }
1163        self.pending_scripts.insert(script_name.clone());
1164
1165        // Ensure analysis exists
1166        self.ensure_analysis(&script_name);
1167
1168        let mut holder = PointerHolder::default();
1169
1170        if let Some(analysis) = self.script_analyses.get(&script_name) {
1171            for &ptr in &PointerType::ALL {
1172                let pi = ptr.index();
1173
1174                // Both BFS walks below treat setter nodes as blocking. The CFG
1175                // stores only the compact `set_list`/`corrupted_list` Vecs, so
1176                // build the O(1) lookup sets on demand here (transient, freed at
1177                // the end of this iteration) instead of caching a duplicate
1178                // HashSet per pointer type in every memoized CFG.
1179                let requires = !analysis.required[pi].is_empty();
1180                let has_returns = !analysis.returns.is_empty();
1181                if !requires && !has_returns {
1182                    continue;
1183                }
1184                let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
1185
1186                // requiresPointerScript: BFS from required → graph[0], blocked by setters
1187                if requires {
1188                    let path = Self::find_edge_path_static(
1189                        &analysis.nodes,
1190                        &analysis.required[pi],
1191                        |node_idx| node_idx == 0,
1192                        &set_blocked,
1193                    );
1194                    if path.is_some() {
1195                        holder.required.insert(ptr);
1196                    }
1197                }
1198
1199                if has_returns {
1200                    let corrupted_nodes: HashSet<usize> =
1201                        analysis.corrupted_list[pi].iter().copied().collect();
1202
1203                    // setsPointerScript: BFS from returns → (graph[0] OR corruptor),
1204                    // blocked by setters. If NO path found, the script guarantees set.
1205                    let path = Self::find_edge_path_static(
1206                        &analysis.nodes,
1207                        &analysis.returns,
1208                        |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1209                        &set_blocked,
1210                    );
1211                    if path.is_none() {
1212                        holder.set.insert(ptr);
1213                    }
1214
1215                    // corruptsPointerScript: BFS from returns → corruptor, blocked by setters
1216                    if !corrupted_nodes.is_empty() {
1217                        let path = Self::find_edge_path_static(
1218                            &analysis.nodes,
1219                            &analysis.returns,
1220                            |node_idx| corrupted_nodes.contains(&node_idx),
1221                            &set_blocked,
1222                        );
1223                        if path.is_some() {
1224                            holder.corrupted.insert(ptr);
1225                        }
1226                    }
1227                }
1228            }
1229        }
1230
1231        self.pending_scripts.remove(&script_name);
1232
1233        self.script_pointers
1234            .insert(script_name.clone(), holder.clone());
1235        holder
1236    }
1237
1238    // -----------------------------------------------------------------------
1239    // Command name resolution
1240    // -----------------------------------------------------------------------
1241
1242    /// Walk the callee's analyzed CFG and return every instruction that
1243    /// put `ptr` into `corrupted_list` — a direct `Command(p_delay)`,
1244    /// a `Gosub(~chatnpc)` whose callee transitively corrupts the
1245    /// pointer, etc. Each entry is `(display_name, source_line)`.
1246    /// Results are deduplicated by `(name, line)`.
1247    fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1248        let callee = self.scripts.get(callee_idx);
1249        let analysis = match self.script_analyses.get(&callee.name) {
1250            Some(a) => a,
1251            None => return Vec::new(),
1252        };
1253        let ptr_idx = ptr.index();
1254        let mut seen: HashSet<(String, usize)> = HashSet::new();
1255        let mut result: Vec<(String, usize)> = Vec::new();
1256
1257        for &node_idx in &analysis.corrupted_list[ptr_idx] {
1258            let instr_idx = match analysis.nodes[node_idx].instruction_index {
1259                Some(i) => i,
1260                None => continue,
1261            };
1262            let instr = &callee.instructions[instr_idx];
1263            let line = resolve_line(&callee.instructions, instr_idx);
1264
1265            let name = match instr.opcode {
1266                Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
1267                    Some(n) => n,
1268                    None => continue,
1269                },
1270                Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1271                    Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
1272                        Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
1273                            .map(|s| format!("~{}", s))
1274                            .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
1275                        None => continue,
1276                    },
1277                    _ => continue,
1278                },
1279                // Jumps are terminal — they don't contribute to a
1280                // return-path corruption (the proc/label that @jumps out
1281                // is flagged via its own gosub/jump inheritance).
1282                _ => continue,
1283            };
1284
1285            let key = (name.clone(), line);
1286            if seen.insert(key) {
1287                result.push((name, line));
1288            }
1289        }
1290
1291        result
1292    }
1293
1294    fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
1295        match &instr.operand {
1296            Operand::Int(encoded) => {
1297                let opcode = encoded & 0xFFFF;
1298                let secondary = (encoded >> 16) & 1;
1299                let base_name = self.shared.opcode_to_name.get(&opcode)?;
1300                if secondary == 1 {
1301                    Some(format!(".{}", base_name))
1302                } else {
1303                    Some(base_name.clone())
1304                }
1305            }
1306            Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
1307            _ => None,
1308        }
1309    }
1310
1311    // -----------------------------------------------------------------------
1312    // Suggestion builder: Rule A — thread `last_*` through the callee
1313    // -----------------------------------------------------------------------
1314    //
1315    // Given a jump/gosub node that secondary-flagged for a static-only
1316    // pointer, produce a rustc-style Help with two Suggestions:
1317    //   1. rewrite the caller line to pass the captured pointer as an arg
1318    //   2. append a matching parameter to the callee's label/proc header
1319    //
1320    // Falls back to `None` when the source cache is absent or the callee
1321    // cannot be identified — the warning itself still fires.
1322    fn build_rule_a_help(
1323        &mut self,
1324        ptr: PointerType,
1325        caller_source_path: &str,
1326        caller_line: usize,
1327        node_idx: usize,
1328        caller_script_idx: usize,
1329    ) -> Option<Help> {
1330        // Resolve the jump/gosub target from the caller's CFG node, then drop
1331        // the borrow so the callee's analysis can be (re)built below.
1332        let (is_gosub, script_id) = {
1333            let caller = self.scripts.get(caller_script_idx);
1334            let analysis = self.script_analyses.get(&caller.name)?;
1335            let instr_idx = analysis.nodes[node_idx].instruction_index?;
1336            let instr = &caller.instructions[instr_idx];
1337            // Only Jump/Gosub nodes drive Rule A.
1338            match instr.opcode {
1339                Opcode::Jump | Opcode::JumpWithParams => (
1340                    false,
1341                    match &instr.operand {
1342                        Operand::Int(id) => *id,
1343                        _ => return None,
1344                    },
1345                ),
1346                Opcode::Gosub | Opcode::GosubWithParams => (
1347                    true,
1348                    match &instr.operand {
1349                        Operand::Int(id) => *id,
1350                        _ => return None,
1351                    },
1352                ),
1353                _ => return None,
1354            }
1355        };
1356
1357        let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
1358        // The callee's CFG may have been freed (CFG caches are cleared between
1359        // top-level scripts to bound memory); rebuild it — a no-op if cached —
1360        // so `corruptors_in_callee` can name the specific superseding command.
1361        let callee_name = self.scripts.get(callee_idx).name.clone();
1362        self.ensure_analysis(&callee_name);
1363
1364        let callee = self.scripts.get(callee_idx);
1365        let callee_source = callee.source_path.clone();
1366
1367        // Derive the callee's `[trigger,name]` header line. The first
1368        // LineNumber instruction points at the *body's* first statement,
1369        // which is usually one line below the header — but not always
1370        // (blank lines, doc comments can shift it). Instead, scan the
1371        // source directly for the unambiguous `[<trigger>,<short>]`
1372        // pattern and fall back to the LineNumber estimate if the source
1373        // cache isn't attached.
1374        let first_body_line = callee
1375            .instructions
1376            .iter()
1377            .find_map(|i| match (i.opcode, &i.operand) {
1378                (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1379                _ => None,
1380            })
1381            .unwrap_or(1);
1382        let callee_trigger = callee.trigger.clone();
1383        let callee_short_early = callee
1384            .name
1385            .trim_start_matches('[')
1386            .trim_end_matches(']')
1387            .split_once(',')
1388            .map(|(_, n)| n.to_string())
1389            .unwrap_or_else(|| callee.name.clone());
1390        let callee_header_line = self
1391            .source_cache
1392            .and_then(|c| c.get(&callee_source))
1393            .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
1394            .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1395
1396        let ptr_cmd = ptr.representation(); // "last_useitem", "last_item", …
1397        let param_type = pointer_param_type(ptr);
1398        let param_name = format!("${}", ptr_cmd);
1399
1400        let callee_short = callee
1401            .name
1402            .trim_start_matches('[')
1403            .trim_end_matches(']')
1404            .split_once(',')
1405            .map(|(_, n)| n.to_string())
1406            .unwrap_or_else(|| callee.name.clone());
1407
1408        let arrow = if is_gosub { "~" } else { "@" };
1409
1410        // Pull the specific corruptor(s) from the callee's own analysis
1411        // so the help message names what actually supersedes the pointer
1412        // (e.g. `p_delay` at line 21, or `~chatnpc` at line 11) rather
1413        // than saying "a delay or subroutine" generically.
1414        let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1415        let corruptor_phrase = format_corruptors(&corruptors);
1416
1417        let message = format!(
1418            "`{callee}` reads `{ptr}` then {phrase}; the script still \
1419             compiles and runs, but the reference is brittle to reorder. \
1420             Consider capturing `{ptr}` at the call site and threading it \
1421             through `{callee}` as an `{ty} {pname}` parameter so the \
1422             value is explicit and stable.",
1423            callee = callee_short,
1424            ptr = ptr_cmd,
1425            phrase = corruptor_phrase,
1426            ty = param_type,
1427            pname = param_name,
1428        );
1429
1430        let cache = match self.source_cache {
1431            Some(c) => c,
1432            None => {
1433                // Prose-only fallback — still useful even without source text.
1434                return Some(Help {
1435                    message,
1436                    suggestions: Vec::new(),
1437                    applicability: Applicability::Unspecified,
1438                });
1439            }
1440        };
1441
1442        let mut suggestions = Vec::new();
1443
1444        // (1) Caller rewrite: insert the captured pointer as an argument
1445        // to the @label/~proc call on `caller_line`.
1446        if let Some(src) = cache.get(caller_source_path)
1447            && let Some(line_text) = nth_source_line(&src, caller_line)
1448            && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1449        {
1450            suggestions.push(Suggestion {
1451                file: PathBuf::from(caller_source_path),
1452                line_range: (caller_line, caller_line),
1453                replacement: rewritten,
1454                label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1455            });
1456        }
1457
1458        // (2) Callee rewrite: append `<ty> <name>` to the header's param list.
1459        if let Some(src) = cache.get(&callee_source)
1460            && let Some(header_text) = nth_source_line(&src, callee_header_line)
1461            && let Some(rewritten) =
1462                rewrite_header_add_param(header_text, &callee_short, param_type, &param_name)
1463        {
1464            suggestions.push(Suggestion {
1465                file: PathBuf::from(&callee_source),
1466                line_range: (callee_header_line, callee_header_line),
1467                replacement: rewritten,
1468                label: Some(format!(
1469                    "at the `{}` header (add `{} {}`)",
1470                    callee_short, param_type, param_name
1471                )),
1472            });
1473        }
1474
1475        Some(Help {
1476            message,
1477            suggestions,
1478            // The rewrite may collide with an existing local named after the
1479            // pointer, or with an existing param list that already contains
1480            // the value under a different name — human review recommended.
1481            applicability: Applicability::MaybeIncorrect,
1482        })
1483    }
1484}
1485
1486// ---------------------------------------------------------------------------
1487// Graph edge helpers
1488// ---------------------------------------------------------------------------
1489
1490fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1491    if !nodes[from].next.contains(&to) {
1492        nodes[from].next.push(to);
1493    }
1494    if !nodes[to].previous.contains(&from) {
1495        nodes[to].previous.push(from);
1496    }
1497}
1498
1499/// The 2004scape engine tracks `active_player`, `active_npc`, `active_loc`,
1500/// `active_obj`, their `.`-prefixed secondary variants, and
1501/// `p_active_player`/`p_active_player2` via `ScriptState.pointerCheck` at
1502/// runtime. `last_*` and `find_*` pointers are *not* tracked at runtime —
1503/// they are a compile-time discipline only (see the `last_useitem` handler
1504/// in PlayerOps.ts, which gates on `state.trigger`, not a runtime pointer).
1505///
1506/// The "requires AND corrupts at the same node" heuristic (a Jump/Gosub
1507/// inheriting `required | corrupted` from its callee) produces real
1508/// findings for the static-only set but is typically noise for the
1509/// engine-tracked set — callers in that pattern rarely touch the pointer
1510/// after the jump, so the engine's runtime check never fires.
1511fn is_static_only_pointer(ptr: PointerType) -> bool {
1512    use PointerType::*;
1513    matches!(
1514        ptr,
1515        FindPlayer
1516            | FindNpc
1517            | FindLoc
1518            | FindObj
1519            | FindDb
1520            | LastCom
1521            | LastInt
1522            | LastItem
1523            | LastSlot
1524            | LastTargetslot
1525            | LastUseitem
1526            | LastUseslot
1527    )
1528}
1529
1530/// Strip the `[trigger,name]` brackets from a script's full name and
1531/// return just the `name` half, for display in help messages.
1532fn short_script_name(full_name: &str) -> Option<String> {
1533    full_name
1534        .trim_start_matches('[')
1535        .trim_end_matches(']')
1536        .split_once(',')
1537        .map(|(_, n)| n.to_string())
1538}
1539
1540/// Render a list of `(name, line)` corruptors into the clause slot
1541/// in the help message. Empty → generic fallback; 1 → `calls `X` at line N`;
1542/// 2 → `calls `X` at line N and `Y` at line M`; 3+ → list with commas
1543/// and a trailing "and", truncated after 3 with "…".
1544fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1545    if corruptors.is_empty() {
1546        return "calls a delay or subroutine that may supersede it".to_string();
1547    }
1548
1549    const MAX: usize = 3;
1550    let shown: Vec<String> = corruptors
1551        .iter()
1552        .take(MAX)
1553        .map(|(name, line)| {
1554            if *line > 0 {
1555                format!("`{}` at line {}", name, line)
1556            } else {
1557                format!("`{}`", name)
1558            }
1559        })
1560        .collect();
1561
1562    let suffix = if corruptors.len() > MAX {
1563        format!(" (and {} more)", corruptors.len() - MAX)
1564    } else {
1565        String::new()
1566    };
1567
1568    let joined = match shown.len() {
1569        1 => shown[0].clone(),
1570        2 => format!("{} and {}", shown[0], shown[1]),
1571        _ => {
1572            let head = shown[..shown.len() - 1].join(", ");
1573            format!("{}, and {}", head, shown[shown.len() - 1])
1574        }
1575    };
1576
1577    format!("calls {}{} which may supersede it", joined, suffix)
1578}
1579
1580/// The RuneScript parameter type to use when threading a `last_*` pointer
1581/// through as a label argument. Mirrors the return types declared on the
1582/// corresponding engine commands in `content/scripts/engine.rs2`:
1583///   last_useitem/last_item -> obj
1584///   last_com               -> component
1585///   last_useslot/last_slot/last_targetslot/last_int -> int
1586/// Every other static-only pointer falls back to `int` (safe default —
1587/// the suggestion lands in `Applicability::MaybeIncorrect` anyway).
1588fn pointer_param_type(ptr: PointerType) -> &'static str {
1589    use PointerType::*;
1590    match ptr {
1591        LastUseitem | LastItem => "obj",
1592        LastCom => "component",
1593        _ => "int",
1594    }
1595}
1596
1597/// Extract 1-indexed line `line_no` from `text`. `None` if out of range.
1598fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1599    if line_no == 0 {
1600        return None;
1601    }
1602    text.lines().nth(line_no - 1)
1603}
1604
1605/// Rewrite a caller line like `[oplocu,...] @label;` or
1606/// `@label(1);` to pass `last_useitem` (or whichever pointer) as an
1607/// additional argument. Returns `None` if the pattern isn't recognized.
1608///
1609/// Handles:
1610///   `@name;`                -> `@name(last_useitem);`
1611///   `@name(a, b);`          -> `@name(a, b, last_useitem);`
1612///   `~name;` / `~name(...)` (gosub) — same shape with `~`.
1613fn rewrite_call_site_arg(
1614    line: &str,
1615    arrow: &str,
1616    callee_short: &str,
1617    ptr_cmd: &str,
1618) -> Option<String> {
1619    // Locate `<arrow><callee_short>` as a call reference. The label may
1620    // appear multiple times on one line (rare) — we rewrite the first.
1621    let needle = format!("{}{}", arrow, callee_short);
1622    let start = line.find(&needle)?;
1623    let after_name = start + needle.len();
1624    let tail = &line[after_name..];
1625
1626    // Case A: immediately followed by `;` or end-of-line — no existing args.
1627    let first_non_ws = tail.chars().next();
1628    if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1629        || tail.trim_start().is_empty()
1630    {
1631        let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1632        out.push_str(&line[..after_name]);
1633        out.push('(');
1634        out.push_str(ptr_cmd);
1635        out.push(')');
1636        out.push_str(tail);
1637        return Some(out);
1638    }
1639
1640    // Case B: followed by `(` — locate the matching `)` and insert the arg
1641    // just before it.
1642    if tail.trim_start().starts_with('(') {
1643        let open_rel = tail.find('(')?;
1644        let abs_open = after_name + open_rel;
1645        let close_rel = find_matching_close_paren(&line[abs_open..])?;
1646        let abs_close = abs_open + close_rel;
1647
1648        // Empty arg list: `@name()` -> `@name(last_useitem)`.
1649        let inside = line[abs_open + 1..abs_close].trim();
1650        let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1651        out.push_str(&line[..abs_close]);
1652        if inside.is_empty() {
1653            out.push_str(ptr_cmd);
1654        } else {
1655            out.push_str(", ");
1656            out.push_str(ptr_cmd);
1657        }
1658        out.push_str(&line[abs_close..]);
1659        return Some(out);
1660    }
1661
1662    None
1663}
1664
1665/// Rewrite a label/proc header line to append `<ty> <name>` to its
1666/// parameter list. Handles all three forms:
1667///   `[label,foo]`              -> `[label,foo](obj $used)`
1668///   `[label,foo](int $x)`      -> `[label,foo](int $x, obj $used)`
1669///   `[proc,foo]()(int)`        -> `[proc,foo](obj $used)(int)`
1670fn rewrite_header_add_param(
1671    line: &str,
1672    callee_short: &str,
1673    param_type: &str,
1674    param_name: &str,
1675) -> Option<String> {
1676    // Locate the `,<callee_short>]` subject closer so we know where the
1677    // header ends and any parameter list begins.
1678    let needle = format!(",{}]", callee_short);
1679    let subject_end = line.find(&needle)?;
1680    let after_bracket = subject_end + needle.len();
1681
1682    let remainder = &line[after_bracket..];
1683    let added = format!("{} {}", param_type, param_name);
1684
1685    // No param list at all — append `(<ty> <name>)`.
1686    if !remainder.trim_start().starts_with('(') {
1687        let mut out = String::with_capacity(line.len() + added.len() + 2);
1688        out.push_str(&line[..after_bracket]);
1689        out.push('(');
1690        out.push_str(&added);
1691        out.push(')');
1692        out.push_str(remainder);
1693        return Some(out);
1694    }
1695
1696    // Has at least one `(...)` — find its close and insert before it.
1697    let open_rel = remainder.find('(')?;
1698    let abs_open = after_bracket + open_rel;
1699    let close_rel = find_matching_close_paren(&line[abs_open..])?;
1700    let abs_close = abs_open + close_rel;
1701    let inside = line[abs_open + 1..abs_close].trim();
1702
1703    let mut out = String::with_capacity(line.len() + added.len() + 2);
1704    out.push_str(&line[..abs_close]);
1705    if inside.is_empty() {
1706        out.push_str(&added);
1707    } else {
1708        out.push_str(", ");
1709        out.push_str(&added);
1710    }
1711    out.push_str(&line[abs_close..]);
1712    Some(out)
1713}
1714
1715/// Locate the 1-indexed line that declares `[<trigger>,<name>]` in `src`.
1716/// Ignores leading whitespace; matches on the exact `[trigger,name]`
1717/// prefix (before any `(...)` parameter list).
1718fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1719    let prefix = format!("[{},{}]", trigger, name);
1720    let prefix_with_params = format!("[{},{}](", trigger, name);
1721    for (i, line) in src.lines().enumerate() {
1722        let trimmed = line.trim_start();
1723        if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1724            return Some(i + 1);
1725        }
1726    }
1727    None
1728}
1729
1730/// Given a string whose first char is `(`, return the byte offset of the
1731/// matching `)`. Respects nesting but is deliberately naive about strings
1732/// (RuneScript headers don't contain string literals).
1733fn find_matching_close_paren(s: &str) -> Option<usize> {
1734    let bytes = s.as_bytes();
1735    if bytes.first().copied() != Some(b'(') {
1736        return None;
1737    }
1738    let mut depth = 0i32;
1739    for (i, &b) in bytes.iter().enumerate() {
1740        match b {
1741            b'(' => depth += 1,
1742            b')' => {
1743                depth -= 1;
1744                if depth == 0 {
1745                    return Some(i);
1746                }
1747            }
1748            _ => {}
1749        }
1750    }
1751    None
1752}
1753
1754/// Game-var Push/Pop instructions encode the secondary (dot-prefixed,
1755/// `.%v`) vs primary (`%v`) distinction in bit 16 of the integer operand
1756/// (see `compiler.rs` Expr::GameVar handling: `(1 << 16) | var_id`).
1757/// TS uses distinct opcodes for this; we collapse to a single opcode and
1758/// recover the flag here when attributing the pointer requirement.
1759fn is_secondary_var_operand(operand: &Operand) -> bool {
1760    match operand {
1761        Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1762        _ => false,
1763    }
1764}
1765
1766/// Resolve a jump target (an instruction index) to the CFG node index, walking
1767/// past any `LineNumber` instructions that are stripped from the CFG. Without
1768/// this, an `if` body's BranchEquals target — which usually lands on the body's
1769/// leading LineNumber — would fail the `instr_to_node.get()` lookup and the
1770/// edge would silently drop, disconnecting the body from its predecessors.
1771fn resolve_target_node(
1772    mut target_idx: usize,
1773    instructions: &[Instruction],
1774    instr_to_node: &HashMap<usize, usize>,
1775) -> Option<usize> {
1776    while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1777        target_idx += 1;
1778    }
1779    instr_to_node.get(&target_idx).copied()
1780}
1781
1782fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1783    nodes[from].next.retain(|&n| n != to);
1784    nodes[to].previous.retain(|&n| n != from);
1785}
1786
1787/// Find the source line number for an instruction by scanning backwards for
1788/// the nearest `LineNumber` instruction. Returns 0 if none found.
1789fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1790    for i in (0..=instr_idx).rev() {
1791        if instructions[i].opcode == Opcode::LineNumber
1792            && let Operand::Int(line) = instructions[i].operand
1793        {
1794            return line as usize;
1795        }
1796    }
1797    0
1798}
1799
1800#[cfg(test)]
1801mod tests {
1802    use super::*;
1803    use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1804    use crate::symbol::SymbolRegistry;
1805
1806    /// Build a minimal registry with a command registered at a given opcode.
1807    fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1808        let mut reg = SymbolRegistry::new();
1809        for &(name, opcode) in commands {
1810            reg.register_command(name.to_string(), opcode, vec![], vec![]);
1811        }
1812        reg
1813    }
1814
1815    /// Build a compiled script with the given trigger, name, and instructions.
1816    fn make_script(
1817        name: &str,
1818        trigger: &str,
1819        id: i32,
1820        instructions: Vec<Instruction>,
1821    ) -> CompiledScript {
1822        let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1823        script.trigger = trigger.to_string();
1824        script.source_path = "test.rs2".to_string();
1825        script.instructions = instructions;
1826        script
1827    }
1828
1829    /// Helper: Command instruction with encoded opcode (no secondary entity).
1830    fn cmd(opcode: i32) -> Instruction {
1831        Instruction::new(Opcode::Command, Operand::Int(opcode))
1832    }
1833
1834    fn line(n: i32) -> Instruction {
1835        Instruction::new(Opcode::LineNumber, Operand::Int(n))
1836    }
1837
1838    fn push_int(v: i32) -> Instruction {
1839        Instruction::push_int(v)
1840    }
1841
1842    fn branch_eq(target: usize) -> Instruction {
1843        Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1844    }
1845
1846    fn branch(target: usize) -> Instruction {
1847        Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1848    }
1849
1850    fn ret() -> Instruction {
1851        Instruction::simple(Opcode::Return)
1852    }
1853
1854    fn gosub(script_id: i32) -> Instruction {
1855        Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1856    }
1857
1858    // -----------------------------------------------------------------------
1859    // Test: conditional setter with argument push between Command and Branch
1860    // -----------------------------------------------------------------------
1861    // Simulates: if (p_finduid(uid) = true) { p_stopaction; }
1862    // Bytecode: PushVar, Command(p_finduid), PushConstantInt(1), BranchEquals, Branch, ...
1863    // The conditional setter should be detected despite the PushVar before Command.
1864    #[test]
1865    fn conditional_setter_with_arg_push() {
1866        // p_finduid opcode = 4267 (arbitrary, just needs to be in command_pointers)
1867        // p_stopaction opcode = 4268
1868        let p_finduid_op = 4267;
1869        let p_stopaction_op = 4268;
1870
1871        let registry = registry_with_commands(&[
1872            ("p_finduid", p_finduid_op),
1873            ("p_stopaction", p_stopaction_op),
1874        ]);
1875
1876        let instructions = vec![
1877            line(1),              // 0: LineNumber
1878            push_int(0),          // 1: PushVar(uid) - simulated as push_int
1879            cmd(p_finduid_op),    // 2: Command(p_finduid)
1880            push_int(1),          // 3: PushConstantInt(1) = true
1881            branch_eq(7),         // 4: BranchEquals -> body
1882            branch(8),            // 5: Branch -> end
1883            line(2),              // 6: LineNumber
1884            cmd(p_stopaction_op), // 7: Command(p_stopaction) - requires p_active_player
1885            ret(),                // 8: Return
1886        ];
1887
1888        // Script with "label" trigger (gets all pointers initially? No - we want
1889        // to test that the conditional setter provides the pointer)
1890        // Use "ai_timer" which only provides active_npc — no p_active_player.
1891        let script = make_script("test", "ai_timer", 0, instructions);
1892        let scripts = vec![script];
1893
1894        let mut checker = PointerChecker::new(&scripts, &registry);
1895        let diags = checker.run();
1896
1897        // p_finduid conditionally sets p_active_player on the true branch.
1898        // p_stopaction requires p_active_player and is only on the true branch.
1899        // So this should produce NO diagnostics.
1900        assert_eq!(
1901            diags.warning_count(),
1902            0,
1903            "conditional setter should provide p_active_player on true branch, got {} warnings",
1904            diags.warning_count()
1905        );
1906    }
1907
1908    // -----------------------------------------------------------------------
1909    // Test: proc that requires AND corrupts the same pointer (gnomeball pattern)
1910    // -----------------------------------------------------------------------
1911    // Simulates a label calling a proc that:
1912    //   - requires p_active_player (via p_delay)
1913    //   - then corrupts p_active_player (via npc_delay)
1914    // The Gosub node is simultaneously in required and corrupted lists.
1915    // This should NOT be flagged — the requirement is satisfied before corruption.
1916    #[test]
1917    fn gosub_requires_then_corrupts_same_pointer() {
1918        let p_delay_op = 5001;
1919        let npc_delay_op = 5002;
1920
1921        let registry =
1922            registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
1923
1924        // Proc: p_delay(0); npc_delay(0); return;
1925        // This proc requires p_active_player (p_delay) then corrupts it (npc_delay).
1926        let proc_script = make_script(
1927            "tackle_success",
1928            "proc",
1929            100,
1930            vec![
1931                line(1),
1932                push_int(0),
1933                cmd(p_delay_op), // requires p_active_player, does NOT corrupt it
1934                line(2),
1935                push_int(0),
1936                cmd(npc_delay_op), // corrupts p_active_player
1937                ret(),
1938            ],
1939        );
1940
1941        // Label: calls the proc via gosub
1942        // The label trigger provides all pointers including p_active_player.
1943        let label_script = make_script(
1944            "do_tackle",
1945            "label",
1946            200,
1947            vec![
1948                line(10),
1949                gosub(100), // Gosub to proc — requires AND corrupts p_active_player
1950                ret(),
1951            ],
1952        );
1953
1954        let scripts = vec![proc_script, label_script];
1955        let mut checker = PointerChecker::new(&scripts, &registry);
1956        let diags = checker.run();
1957
1958        // The label has p_active_player from trigger.
1959        // The gosub requires it (satisfied) then corrupts it.
1960        // No diagnostic — the main BFS starts from predecessors of the
1961        // required node (not the node itself), and the secondary require+
1962        // corrupt heuristic skips engine-tracked pointers like PActivePlayer.
1963        assert_eq!(
1964            diags.warning_count(),
1965            0,
1966            "gosub that requires-then-corrupts p_active_player should not \
1967             be flagged (engine-tracked pointer), got {} warnings",
1968            diags.warning_count()
1969        );
1970    }
1971
1972    // -----------------------------------------------------------------------
1973    // Test: legitimate corruption SHOULD be caught
1974    // -----------------------------------------------------------------------
1975    // A command corrupts p_active_player, then a later command requires it.
1976    // This should produce an error.
1977    #[test]
1978    fn corruption_before_requirement_is_caught() {
1979        let npc_delay_op = 5002;
1980        let p_delay_op = 5001;
1981
1982        let registry =
1983            registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
1984
1985        // Label: npc_delay(0); p_delay(0);
1986        // npc_delay corrupts p_active_player, then p_delay requires it.
1987        let script = make_script(
1988            "bad_order",
1989            "label",
1990            0,
1991            vec![
1992                line(1),
1993                push_int(0),
1994                cmd(npc_delay_op), // corrupts p_active_player
1995                line(2),
1996                push_int(0),
1997                cmd(p_delay_op), // requires p_active_player — should fail!
1998                ret(),
1999            ],
2000        );
2001
2002        let scripts = vec![script];
2003        let mut checker = PointerChecker::new(&scripts, &registry);
2004        let diags = checker.run();
2005
2006        assert!(
2007            diags.warning_count() > 0,
2008            "corruption before requirement should be caught as a warning"
2009        );
2010    }
2011
2012    // -----------------------------------------------------------------------
2013    // Test: uninitialized pointer access
2014    // -----------------------------------------------------------------------
2015    // A script with a trigger that doesn't provide p_active_player uses p_delay.
2016    #[test]
2017    fn uninitialized_pointer_caught() {
2018        let p_delay_op = 5001;
2019
2020        let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2021
2022        // ai_timer trigger only provides active_npc, not p_active_player.
2023        let script = make_script(
2024            "bad_access",
2025            "ai_timer",
2026            0,
2027            vec![
2028                line(1),
2029                push_int(0),
2030                cmd(p_delay_op), // requires p_active_player — not provided by trigger
2031                ret(),
2032            ],
2033        );
2034
2035        let scripts = vec![script];
2036        let mut checker = PointerChecker::new(&scripts, &registry);
2037        let diags = checker.run();
2038
2039        assert!(
2040            diags.warning_count() > 0,
2041            "uninitialized pointer access should be caught"
2042        );
2043    }
2044
2045    // -----------------------------------------------------------------------
2046    // Test: jump target landing on a LineNumber instruction
2047    // -----------------------------------------------------------------------
2048    // Regression: BranchEquals/Branch targets patched to body_start often
2049    // land on a LineNumber instruction (emitted for the body's first source
2050    // line). LineNumbers are stripped from the CFG, so without
2051    // resolve_target_node() the edge would be silently dropped and the body
2052    // node would have no predecessors — hiding genuine uninitialized-pointer
2053    // errors for callers that wrap the @jump in an `if` block.
2054    #[test]
2055    fn branch_target_on_line_number_still_connects() {
2056        let p_delay_op = 5001;
2057        let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2058
2059        // ai_timer trigger provides active_npc but NOT p_active_player.
2060        // Layout: `if (1 = 1) { p_delay(0); }` — BranchEquals jumps to the
2061        // body's leading LineNumber. If the CFG drops that edge the body
2062        // node is disconnected and the uninitialized p_active_player read
2063        // is never flagged.
2064        //
2065        //   0 LineNumber(1)
2066        //   1 PushConstantInt(1)
2067        //   2 PushConstantInt(1)
2068        //   3 BranchEquals -> 5 (LineNumber at body start)
2069        //   4 Branch       -> 8 (end-of-if marker; here, Return)
2070        //   5 LineNumber(2)
2071        //   6 PushConstantInt(0)
2072        //   7 Command(p_delay)
2073        //   8 Return
2074        let script = make_script(
2075            "target_on_line_number",
2076            "ai_timer",
2077            0,
2078            vec![
2079                line(1),
2080                push_int(1),
2081                push_int(1),
2082                branch_eq(5), // jump target is the LineNumber at index 5
2083                Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
2084                line(2),
2085                push_int(0),
2086                cmd(p_delay_op),
2087                ret(),
2088            ],
2089        );
2090
2091        let scripts = vec![script];
2092        let mut checker = PointerChecker::new(&scripts, &registry);
2093        let diags = checker.run();
2094
2095        assert!(
2096            diags.warning_count() > 0,
2097            "jump target on LineNumber must still flag uninitialized pointer \
2098             access (got {} warnings)",
2099            diags.warning_count()
2100        );
2101    }
2102
2103    // -----------------------------------------------------------------------
2104    // Test: secondary require+corrupt warning for static-only pointers
2105    // -----------------------------------------------------------------------
2106    // A label that requires AND corrupts LastUseitem (via last_useitem then
2107    // p_delay) is called via @jump from an oplocu trigger that provides
2108    // LastUseitem. The main BFS correctly finds no error (predecessors are
2109    // clean), but the secondary heuristic flags the Jump as "requires and
2110    // corrupts last_useitem on the same node" — this is the 23-warning
2111    // pattern from the legacy lost-city 225 output.
2112    #[test]
2113    fn secondary_requires_and_corrupts_warns_for_static_pointer() {
2114        // last_useitem and p_delay opcodes (arbitrary, just need to be in
2115        // command_pointers()).
2116        let last_useitem_op = 4270;
2117        let p_delay_op = 5001;
2118        let registry =
2119            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2120
2121        // Callee label: reads last_useitem, then corrupts it via p_delay.
2122        let callee = make_script(
2123            "consume_useitem",
2124            "label",
2125            100,
2126            vec![
2127                line(1),
2128                cmd(last_useitem_op), // requires LastUseitem
2129                line(2),
2130                push_int(0),
2131                cmd(p_delay_op), // corrupts LastUseitem
2132                ret(),
2133            ],
2134        );
2135
2136        // Caller: oplocu trigger provides LastUseitem. Jumps to the label.
2137        // The Jump node inherits BOTH required[LastUseitem] AND
2138        // corrupted[LastUseitem]. Main BFS: predecessors of Jump trace back
2139        // to node 0, which is NOT corrupted (trigger provides) — no main
2140        // diagnostic. Secondary heuristic: Jump appears in both sets, emit
2141        // a warning.
2142        let caller = make_script(
2143            "use_on_loc",
2144            "oplocu",
2145            200,
2146            vec![
2147                line(10),
2148                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2149            ],
2150        );
2151
2152        let scripts = vec![callee, caller];
2153        let mut checker = PointerChecker::new(&scripts, &registry);
2154        let diags = checker.run();
2155
2156        let last_useitem_warnings = diags
2157            .diagnostics()
2158            .iter()
2159            .filter(|d| d.severity == Severity::Warning)
2160            .filter(|d| d.message.contains("last_useitem"))
2161            .count();
2162        assert!(
2163            last_useitem_warnings > 0,
2164            "static-only pointer (last_useitem) should trigger the \
2165             require+corrupt warning at the jump site; got diags: {:?}",
2166            diags
2167                .diagnostics()
2168                .iter()
2169                .map(|d| &d.message)
2170                .collect::<Vec<_>>()
2171        );
2172
2173        assert_eq!(
2174            diags.error_count(),
2175            0,
2176            "pointer-check diagnostics must never raise error severity; got {} errors",
2177            diags.error_count()
2178        );
2179    }
2180
2181    // -----------------------------------------------------------------------
2182    // Test: secondary heuristic SUPPRESSES warnings for engine-tracked pointers
2183    // -----------------------------------------------------------------------
2184    // Same pattern as above, but the pointer is PActivePlayer (engine-
2185    // tracked). The secondary heuristic must NOT emit — the user's legacy
2186    // 23-warning output specifically excludes the gnome_baller
2187    // p_active_player findings because the 2004scape engine manages that
2188    // pointer at runtime.
2189    #[test]
2190    fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
2191        let p_delay_op = 5001;
2192        let npc_delay_op = 5002;
2193        let registry =
2194            registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2195
2196        let callee = make_script(
2197            "consume_protected",
2198            "proc",
2199            100,
2200            vec![
2201                line(1),
2202                push_int(0),
2203                cmd(p_delay_op), // requires PActivePlayer
2204                line(2),
2205                push_int(0),
2206                cmd(npc_delay_op), // corrupts PActivePlayer
2207                ret(),
2208            ],
2209        );
2210
2211        // opnpc1 provides ActivePlayer, PActivePlayer, ActiveNpc.
2212        let caller = make_script(
2213            "do_opnpc",
2214            "opnpc1",
2215            200,
2216            vec![
2217                line(10),
2218                Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2219                ret(),
2220            ],
2221        );
2222
2223        let scripts = vec![callee, caller];
2224        let mut checker = PointerChecker::new(&scripts, &registry);
2225        let diags = checker.run();
2226
2227        let p_active_player_warnings = diags
2228            .diagnostics()
2229            .iter()
2230            .filter(|d| d.severity == Severity::Warning)
2231            .filter(|d| d.message.contains("p_active_player"))
2232            .count();
2233        assert_eq!(
2234            p_active_player_warnings, 0,
2235            "engine-tracked pointer (p_active_player) must not trigger the \
2236             require+corrupt warning; got {} such warnings",
2237            p_active_player_warnings
2238        );
2239    }
2240
2241    // -----------------------------------------------------------------------
2242    // Test: secondary (dot-prefixed) var reads require the `*2` pointer
2243    // -----------------------------------------------------------------------
2244    // Regression: categorize_nodes used to map every PushVarn/PopVarn (and
2245    // PushVarp/PopVarp/PushVarbit/PopVarbit) to the primary active_npc /
2246    // active_player pointer, ignoring the bit-16 "secondary" flag that
2247    // compiler.rs sets on `.%var` operands. That miscategorization caused
2248    // the 4 spurious `uninitialized active_npc` warnings at
2249    // gnomeball_pass.rs2:1,2 and duel_arena.rs2:3,10.
2250    //
2251    // A proc reading `.%npc_var` should only require active_npc2 — no
2252    // active_npc warning should propagate to its callers.
2253    #[test]
2254    fn secondary_varn_requires_active_npc2_not_primary() {
2255        // PushVarn is Opcode::PushVarn (=4). Operand encodes var_id in low
2256        // 16 bits; bit 16 marks secondary. We bypass the varn registry by
2257        // emitting the raw opcode — the pointer checker only inspects the
2258        // opcode + operand.
2259        let secondary_varn = Instruction::new(
2260            Opcode::PushVarn,
2261            Operand::Int(1 << 16), // .%var_id 0, secondary
2262        );
2263
2264        // Proc reads a secondary NPC var and returns.
2265        let proc_script = make_script(
2266            "reads_secondary_varn",
2267            "proc",
2268            100,
2269            vec![
2270                line(1),
2271                secondary_varn,
2272                Instruction::simple(Opcode::PopIntDiscard),
2273                ret(),
2274            ],
2275        );
2276
2277        // Caller: opplayer1 trigger provides active_player/p_active_player/
2278        // active_player2, but does NOT provide active_npc or active_npc2.
2279        // Before the fix, the gosub inherited active_npc (primary) from the
2280        // proc and the caller would be flagged "uninitialized active_npc".
2281        // After the fix, the proc only requires active_npc2, which also
2282        // isn't provided — but crucially, `active_npc` is not flagged.
2283        let caller = make_script(
2284            "gosub_into_proc",
2285            "opplayer1",
2286            200,
2287            vec![line(10), gosub(100), ret()],
2288        );
2289
2290        let scripts = vec![proc_script, caller];
2291        let registry = registry_with_commands(&[]);
2292        let mut checker = PointerChecker::new(&scripts, &registry);
2293        let diags = checker.run();
2294
2295        // Diagnostic messages use the pointer's `representation()`:
2296        //   PointerType::ActiveNpc  -> "active_npc"
2297        //   PointerType::ActiveNpc2 -> ".active_npc"
2298        // Match "pointer active_npc." to count ONLY primary hits — the
2299        // secondary form appears as "pointer .active_npc.".
2300        let active_npc_primary_warnings = diags
2301            .diagnostics()
2302            .iter()
2303            .filter(|d| d.severity == Severity::Warning)
2304            .filter(|d| d.message.contains("pointer active_npc."))
2305            .count();
2306        assert_eq!(
2307            active_npc_primary_warnings,
2308            0,
2309            "secondary .%var read must not flag primary active_npc at the \
2310             caller; got diags: {:?}",
2311            diags
2312                .diagnostics()
2313                .iter()
2314                .filter(|d| d.severity == Severity::Warning)
2315                .map(|d| &d.message)
2316                .collect::<Vec<_>>()
2317        );
2318
2319        // Sanity: the secondary requirement DID propagate — opplayer1 doesn't
2320        // provide active_npc2 either, so `.active_npc` should be flagged.
2321        // This proves the attribution went to the `*2` pointer as intended.
2322        let active_npc2_warnings = diags
2323            .diagnostics()
2324            .iter()
2325            .filter(|d| d.severity == Severity::Warning)
2326            .filter(|d| d.message.contains("pointer .active_npc."))
2327            .count();
2328        assert!(
2329            active_npc2_warnings > 0,
2330            "secondary .%var should route the requirement to active_npc2; \
2331             got no such warning"
2332        );
2333    }
2334
2335    // -----------------------------------------------------------------------
2336    // Unit tests for the Rule A text rewriters
2337    // -----------------------------------------------------------------------
2338
2339    #[test]
2340    fn rewrite_call_site_no_args() {
2341        let got = rewrite_call_site_arg(
2342            "[opnpcu,wantcat1] @civilian_give_runes;",
2343            "@",
2344            "civilian_give_runes",
2345            "last_useitem",
2346        )
2347        .unwrap();
2348        assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2349    }
2350
2351    #[test]
2352    fn rewrite_call_site_with_args() {
2353        let got = rewrite_call_site_arg(
2354            "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2355            "@",
2356            "amulet_of_glory_interface",
2357            "last_item",
2358        )
2359        .unwrap();
2360        assert_eq!(
2361            got,
2362            "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2363        );
2364    }
2365
2366    #[test]
2367    fn rewrite_call_site_gosub_no_args() {
2368        let got =
2369            rewrite_call_site_arg("    ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2370        assert_eq!(got, "    ~some_proc(last_useitem);");
2371    }
2372
2373    #[test]
2374    fn rewrite_call_site_empty_arg_list() {
2375        let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2376        assert_eq!(got, "@foo(last_useitem);");
2377    }
2378
2379    #[test]
2380    fn rewrite_header_no_params() {
2381        let got = rewrite_header_add_param(
2382            "[label,civilian_give_runes]",
2383            "civilian_give_runes",
2384            "obj",
2385            "$last_useitem",
2386        )
2387        .unwrap();
2388        assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2389    }
2390
2391    #[test]
2392    fn rewrite_header_with_existing_params() {
2393        let got = rewrite_header_add_param(
2394            "[label,amulet_of_glory_interface](string $message)",
2395            "amulet_of_glory_interface",
2396            "obj",
2397            "$last_item",
2398        )
2399        .unwrap();
2400        assert_eq!(
2401            got,
2402            "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2403        );
2404    }
2405
2406    #[test]
2407    fn rewrite_header_proc_with_return_type() {
2408        // `[proc,foo]()(int)` — parameter list comes before the return
2409        // list. We must insert into the FIRST `(...)` group.
2410        let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2411        assert_eq!(got, "[proc,foo](obj $x)(int)");
2412    }
2413
2414    #[test]
2415    fn find_header_line_matches_trigger_and_name() {
2416        let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2417        assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2418        assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2419        assert_eq!(find_header_line(src, "label", "missing"), None);
2420    }
2421
2422    #[test]
2423    fn format_corruptors_shapes() {
2424        assert_eq!(
2425            format_corruptors(&[]),
2426            "calls a delay or subroutine that may supersede it"
2427        );
2428        assert_eq!(
2429            format_corruptors(&[("p_delay".to_string(), 21)]),
2430            "calls `p_delay` at line 21 which may supersede it"
2431        );
2432        assert_eq!(
2433            format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2434            "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2435        );
2436        assert_eq!(
2437            format_corruptors(&[
2438                ("p_delay".to_string(), 21),
2439                ("~chatnpc".to_string(), 11),
2440                ("~objbox".to_string(), 14),
2441            ]),
2442            "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2443        );
2444        // Truncates after 3 with a summary suffix.
2445        assert_eq!(
2446            format_corruptors(&[
2447                ("p_delay".to_string(), 1),
2448                ("~a".to_string(), 2),
2449                ("~b".to_string(), 3),
2450                ("~c".to_string(), 4),
2451                ("~d".to_string(), 5),
2452            ]),
2453            "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2454        );
2455        // Unknown line falls back to bare name.
2456        assert_eq!(
2457            format_corruptors(&[("p_delay".to_string(), 0)]),
2458            "calls `p_delay` which may supersede it"
2459        );
2460    }
2461
2462    #[test]
2463    fn find_matching_close_paren_nested() {
2464        assert_eq!(find_matching_close_paren("()"), Some(1));
2465        assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2466        assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2467        assert_eq!(find_matching_close_paren("("), None);
2468        assert_eq!(find_matching_close_paren("abc"), None);
2469    }
2470
2471    // -----------------------------------------------------------------------
2472    // Test: secondary require+corrupt warning carries a populated Help
2473    //       with concrete before/after suggestions when source is available
2474    // -----------------------------------------------------------------------
2475    #[test]
2476    fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2477        use std::collections::HashMap;
2478        use std::sync::Arc;
2479
2480        let last_useitem_op = 4270;
2481        let p_delay_op = 5001;
2482        let registry =
2483            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2484
2485        // Callee label — reads last_useitem, then p_delay corrupts it.
2486        let mut callee = make_script(
2487            "consume_useitem",
2488            "label",
2489            100,
2490            vec![
2491                line(2), // body starts on source line 2
2492                cmd(last_useitem_op),
2493                line(3),
2494                push_int(0),
2495                cmd(p_delay_op),
2496                ret(),
2497            ],
2498        );
2499        callee.source_path = "/virt/consume.rs2".to_string();
2500
2501        // Caller — oplocu provides last_useitem; @jumps into callee.
2502        let mut caller = make_script(
2503            "use_on_loc",
2504            "oplocu",
2505            200,
2506            vec![
2507                line(1),
2508                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2509            ],
2510        );
2511        caller.source_path = "/virt/caller.rs2".to_string();
2512
2513        // Virtual source text. Caller on line 1, callee header on line 1
2514        // of its own file.
2515        let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2516        source_cache.insert(
2517            "/virt/caller.rs2".to_string(),
2518            Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2519        );
2520        source_cache.insert(
2521            "/virt/consume.rs2".to_string(),
2522            Arc::new(
2523                "[label,consume_useitem]\n\
2524                 last_useitem;\n\
2525                 p_delay(0);\n"
2526                    .to_string(),
2527            ),
2528        );
2529
2530        let scripts = vec![callee, caller];
2531        let mut checker = PointerChecker::new(&scripts, &registry);
2532        checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
2533        let diags = checker.run();
2534
2535        // Find the corrupted-last_useitem warning and verify help is
2536        // attached with both call-site and header rewrites.
2537        let warning = diags
2538            .diagnostics()
2539            .iter()
2540            .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2541            .expect("expected a stale-last_useitem warning");
2542
2543        assert_eq!(
2544            warning.help.len(),
2545            1,
2546            "warning should have exactly one Help block, got {}",
2547            warning.help.len()
2548        );
2549        let help = &warning.help[0];
2550        assert!(
2551            help.message.contains("consume_useitem"),
2552            "help message should name the callee, got: {}",
2553            help.message
2554        );
2555        assert!(
2556            help.message.contains("last_useitem"),
2557            "help message should name the pointer, got: {}",
2558            help.message
2559        );
2560
2561        // Two suggestions: (1) call site, (2) label header.
2562        assert_eq!(
2563            help.suggestions.len(),
2564            2,
2565            "help should include both call-site and header suggestions, \
2566             got {}: {:?}",
2567            help.suggestions.len(),
2568            help.suggestions
2569                .iter()
2570                .map(|s| &s.label)
2571                .collect::<Vec<_>>()
2572        );
2573
2574        // Caller rewrite lands on the call file.
2575        let caller_sug = help
2576            .suggestions
2577            .iter()
2578            .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2579            .expect("expected a call-site suggestion on the caller file");
2580        assert!(
2581            caller_sug
2582                .replacement
2583                .contains("@consume_useitem(last_useitem)"),
2584            "call-site replacement must pass last_useitem as an arg, got: {}",
2585            caller_sug.replacement
2586        );
2587
2588        // Header rewrite lands on the callee file.
2589        let header_sug = help
2590            .suggestions
2591            .iter()
2592            .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2593            .expect("expected a header suggestion on the callee file");
2594        assert!(
2595            header_sug.replacement.contains("(obj $last_useitem)"),
2596            "header replacement must add `obj $last_useitem` param, got: {}",
2597            header_sug.replacement
2598        );
2599
2600        assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2601    }
2602
2603    // -----------------------------------------------------------------------
2604    // Test: help falls back to prose-only when source cache is absent
2605    // -----------------------------------------------------------------------
2606    #[test]
2607    fn secondary_warning_falls_back_to_prose_help_without_source() {
2608        let last_useitem_op = 4270;
2609        let p_delay_op = 5001;
2610        let registry =
2611            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2612
2613        let callee = make_script(
2614            "consume_useitem",
2615            "label",
2616            100,
2617            vec![
2618                line(1),
2619                cmd(last_useitem_op),
2620                line(2),
2621                push_int(0),
2622                cmd(p_delay_op),
2623                ret(),
2624            ],
2625        );
2626        let caller = make_script(
2627            "use_on_loc",
2628            "oplocu",
2629            200,
2630            vec![
2631                line(1),
2632                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2633            ],
2634        );
2635
2636        let scripts = vec![callee, caller];
2637        let mut checker = PointerChecker::new(&scripts, &registry);
2638        // Deliberately NO set_source_cache call.
2639        let diags = checker.run();
2640
2641        let warning = diags
2642            .diagnostics()
2643            .iter()
2644            .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2645            .expect("warning still fires without source cache");
2646
2647        assert_eq!(warning.help.len(), 1);
2648        let help = &warning.help[0];
2649        assert_eq!(
2650            help.suggestions.len(),
2651            0,
2652            "prose-only help should have no concrete suggestions"
2653        );
2654        assert_eq!(help.applicability, Applicability::Unspecified);
2655    }
2656}