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