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
1140                | Opcode::PushVarbit
1141                | Opcode::PushVarcInt
1142                | Opcode::PushVarcString
1143                | Opcode::PushVarClan
1144                | Opcode::PushClanSettingInt
1145                | Opcode::PushClanSettingVarbit
1146                | Opcode::PushClanSettingLong
1147                | Opcode::PushClanSettingString
1148                    if !self.shared.client =>
1149                {
1150                    let pi = if is_secondary_var_operand(&instr.operand) {
1151                        PointerType::ActivePlayer2.index()
1152                    } else {
1153                        PointerType::ActivePlayer.index()
1154                    };
1155                    analysis.required[pi].push(node_idx);
1156                }
1157
1158                Opcode::PopVarp
1159                | Opcode::PopVarbit
1160                | Opcode::PopVarcInt
1161                | Opcode::PopVarcString
1162                | Opcode::PopVarClan
1163                | Opcode::PopClanSettingInt
1164                | Opcode::PopClanSettingVarbit
1165                | Opcode::PopClanSettingLong
1166                | Opcode::PopClanSettingString
1167                    if !self.shared.client =>
1168                {
1169                    let pi = if is_secondary_var_operand(&instr.operand) {
1170                        PointerType::ActivePlayer2.index()
1171                    } else {
1172                        PointerType::ActivePlayer.index()
1173                    };
1174                    analysis.required[pi].push(node_idx);
1175                }
1176
1177                Opcode::PushVarn | Opcode::PopVarn | Opcode::PushVarnBit | Opcode::PopVarnBit
1178                    if !self.shared.client =>
1179                {
1180                    let pi = if is_secondary_var_operand(&instr.operand) {
1181                        PointerType::ActiveNpc2.index()
1182                    } else {
1183                        PointerType::ActiveNpc.index()
1184                    };
1185                    analysis.required[pi].push(node_idx);
1186                }
1187
1188                // PushVars/PopVars are global server vars — no pointer requirements
1189                _ => {}
1190            }
1191        }
1192    }
1193
1194    fn apply_holder(&self, analysis: &mut ScriptAnalysis, node_idx: usize, holder: &PointerHolder) {
1195        for ptr in holder.required.iter() {
1196            let pi = ptr.index();
1197            analysis.required[pi].push(node_idx);
1198        }
1199        for ptr in holder.set.iter().filter(|_| !holder.conditional_set) {
1200            let pi = ptr.index();
1201            analysis.set_list[pi].push(node_idx);
1202        }
1203        for ptr in holder.corrupted.iter() {
1204            let pi = ptr.index();
1205            analysis.corrupted_list[pi].push(node_idx);
1206        }
1207    }
1208
1209    // -----------------------------------------------------------------------
1210    // Callee pointer resolution
1211    // -----------------------------------------------------------------------
1212
1213    /// Get the merged pointer requirements/effects of a called script.
1214    ///
1215    /// Uses graph reachability (matching the TS `calculatePointers`):
1216    /// - **requires**: is there a path from a required-node backwards to graph[0]
1217    ///   without passing through a setter? If yes, the script needs this pointer
1218    ///   from its caller.
1219    /// - **sets**: is there any return-path that reaches graph[0] or a corruptor
1220    ///   without passing through a setter? If NO such path, the script guarantees
1221    ///   the pointer is set on all exit paths.
1222    /// - **corrupts**: is there a return-path that reaches a corruptor without
1223    ///   passing through a setter? If yes, the script may corrupt this pointer.
1224    fn get_script_pointers(&mut self, script_id: i32) -> PointerHolder {
1225        // Find script by ID
1226        let script_idx = match self.shared.script_id_to_index.get(&script_id) {
1227            Some(&i) => i,
1228            None => {
1229                return PointerHolder::default();
1230            }
1231        };
1232        let script_name = self.scripts.get(script_idx).name.clone();
1233
1234        // Check cache
1235        if let Some(holder) = self.script_pointers.get(&script_name) {
1236            return holder.clone();
1237        }
1238
1239        // Cycle detection
1240        if self.pending_scripts.contains(&script_name) {
1241            return PointerHolder::default();
1242        }
1243        self.pending_scripts.insert(script_name.clone());
1244
1245        // Ensure analysis exists
1246        self.ensure_analysis(&script_name);
1247
1248        let mut holder = PointerHolder::default();
1249
1250        if let Some(analysis) = self.script_analyses.get(&script_name) {
1251            for &ptr in &PointerType::ALL {
1252                let pi = ptr.index();
1253
1254                // Both BFS walks below treat setter nodes as blocking. The CFG
1255                // stores only the compact `set_list`/`corrupted_list` Vecs, so
1256                // build the O(1) lookup sets on demand here (transient, freed at
1257                // the end of this iteration) instead of caching a duplicate
1258                // HashSet per pointer type in every memoized CFG.
1259                let requires = !analysis.required[pi].is_empty();
1260                let has_returns = !analysis.returns.is_empty();
1261                if !requires && !has_returns {
1262                    continue;
1263                }
1264                let set_blocked: HashSet<usize> = analysis.set_list[pi].iter().copied().collect();
1265
1266                // requiresPointerScript: BFS from required → graph[0], blocked by setters
1267                if requires {
1268                    let path = Self::find_edge_path_static(
1269                        &analysis.nodes,
1270                        &analysis.required[pi],
1271                        |node_idx| node_idx == 0,
1272                        &set_blocked,
1273                    );
1274                    if path.is_some() {
1275                        holder.required.insert(ptr);
1276                    }
1277                }
1278
1279                if has_returns {
1280                    let corrupted_nodes: HashSet<usize> =
1281                        analysis.corrupted_list[pi].iter().copied().collect();
1282
1283                    // setsPointerScript: BFS from returns → (graph[0] OR corruptor),
1284                    // blocked by setters. If NO path found, the script guarantees set.
1285                    let path = Self::find_edge_path_static(
1286                        &analysis.nodes,
1287                        &analysis.returns,
1288                        |node_idx| node_idx == 0 || corrupted_nodes.contains(&node_idx),
1289                        &set_blocked,
1290                    );
1291                    if path.is_none() {
1292                        holder.set.insert(ptr);
1293                    }
1294
1295                    // corruptsPointerScript: BFS from returns → corruptor, blocked by setters
1296                    if !corrupted_nodes.is_empty() {
1297                        let path = Self::find_edge_path_static(
1298                            &analysis.nodes,
1299                            &analysis.returns,
1300                            |node_idx| corrupted_nodes.contains(&node_idx),
1301                            &set_blocked,
1302                        );
1303                        if path.is_some() {
1304                            holder.corrupted.insert(ptr);
1305                        }
1306                    }
1307                }
1308            }
1309        }
1310
1311        self.pending_scripts.remove(&script_name);
1312
1313        self.script_pointers
1314            .insert(script_name.clone(), holder.clone());
1315        holder
1316    }
1317
1318    // -----------------------------------------------------------------------
1319    // Command name resolution
1320    // -----------------------------------------------------------------------
1321
1322    /// Walk the callee's analyzed CFG and return every instruction that
1323    /// put `ptr` into `corrupted_list` — a direct `Command(p_delay)`,
1324    /// a `Gosub(~chatnpc)` whose callee transitively corrupts the
1325    /// pointer, etc. Each entry is `(display_name, source_line)`.
1326    /// Results are deduplicated by `(name, line)`.
1327    fn corruptors_in_callee(&self, callee_idx: usize, ptr: PointerType) -> Vec<(String, usize)> {
1328        let callee = self.scripts.get(callee_idx);
1329        let analysis = match self.script_analyses.get(&callee.name) {
1330            Some(a) => a,
1331            None => return Vec::new(),
1332        };
1333        let ptr_idx = ptr.index();
1334        let mut seen: HashSet<(String, usize)> = HashSet::new();
1335        let mut result: Vec<(String, usize)> = Vec::new();
1336
1337        for &node_idx in &analysis.corrupted_list[ptr_idx] {
1338            let instr_idx = match analysis.nodes[node_idx].instruction_index {
1339                Some(i) => i,
1340                None => continue,
1341            };
1342            let instr = &callee.instructions[instr_idx];
1343            let line = resolve_line(&callee.instructions, instr_idx);
1344
1345            let name = match instr.opcode {
1346                Opcode::Command => match self.resolve_command_name(instr, &callee.strings) {
1347                    Some(n) => n,
1348                    None => continue,
1349                },
1350                Opcode::Gosub | Opcode::GosubWithParams => match &instr.operand {
1351                    Operand::Int(id) => match self.shared.script_id_to_index.get(id) {
1352                        Some(&target_idx) => short_script_name(&self.scripts.get(target_idx).name)
1353                            .map(|s| format!("~{}", s))
1354                            .unwrap_or_else(|| self.scripts.get(target_idx).name.clone()),
1355                        None => continue,
1356                    },
1357                    _ => continue,
1358                },
1359                // Jumps are terminal — they don't contribute to a
1360                // return-path corruption (the proc/label that @jumps out
1361                // is flagged via its own gosub/jump inheritance).
1362                _ => continue,
1363            };
1364
1365            let key = (name.clone(), line);
1366            if seen.insert(key) {
1367                result.push((name, line));
1368            }
1369        }
1370
1371        result
1372    }
1373
1374    fn resolve_command_name(&self, instr: &Instruction, strings: &[Box<str>]) -> Option<String> {
1375        match &instr.operand {
1376            Operand::Int(encoded) => {
1377                let opcode = encoded & 0xFFFF;
1378                let secondary = (encoded >> 16) & 1;
1379                let base_name = self.shared.opcode_to_name.get(&opcode)?;
1380                if secondary == 1 {
1381                    Some(format!(".{}", base_name))
1382                } else {
1383                    Some(base_name.clone())
1384                }
1385            }
1386            Operand::Str(idx) => Some(strings[*idx as usize].to_lowercase()),
1387            _ => None,
1388        }
1389    }
1390
1391    // -----------------------------------------------------------------------
1392    // Suggestion builder: Rule A — thread `last_*` through the callee
1393    // -----------------------------------------------------------------------
1394    //
1395    // Given a jump/gosub node that secondary-flagged for a static-only
1396    // pointer, produce a rustc-style Help with two Suggestions:
1397    //   1. rewrite the caller line to pass the captured pointer as an arg
1398    //   2. append a matching parameter to the callee's label/proc header
1399    //
1400    // Falls back to `None` when the source cache is absent or the callee
1401    // cannot be identified — the warning itself still fires.
1402    fn build_rule_a_help(
1403        &mut self,
1404        ptr: PointerType,
1405        caller_source_path: &str,
1406        caller_line: usize,
1407        node_idx: usize,
1408        caller_script_idx: usize,
1409    ) -> Option<Help> {
1410        // Resolve the jump/gosub target from the caller's CFG node, then drop
1411        // the borrow so the callee's analysis can be (re)built below.
1412        let (is_gosub, script_id) = {
1413            let caller = self.scripts.get(caller_script_idx);
1414            let analysis = self.script_analyses.get(&caller.name)?;
1415            let instr_idx = analysis.nodes[node_idx].instruction_index?;
1416            let instr = &caller.instructions[instr_idx];
1417            // Only Jump/Gosub nodes drive Rule A.
1418            match instr.opcode {
1419                Opcode::Jump | Opcode::JumpWithParams => (
1420                    false,
1421                    match &instr.operand {
1422                        Operand::Int(id) => *id,
1423                        _ => return None,
1424                    },
1425                ),
1426                Opcode::Gosub | Opcode::GosubWithParams => (
1427                    true,
1428                    match &instr.operand {
1429                        Operand::Int(id) => *id,
1430                        _ => return None,
1431                    },
1432                ),
1433                _ => return None,
1434            }
1435        };
1436
1437        let callee_idx = *self.shared.script_id_to_index.get(&script_id)?;
1438        // The callee's CFG may have been freed (CFG caches are cleared between
1439        // top-level scripts to bound memory); rebuild it — a no-op if cached —
1440        // so `corruptors_in_callee` can name the specific superseding command.
1441        let callee_name = self.scripts.get(callee_idx).name.clone();
1442        self.ensure_analysis(&callee_name);
1443
1444        let callee = self.scripts.get(callee_idx);
1445        let callee_source = callee.source_path.clone();
1446
1447        // Derive the callee's `[trigger,name]` header line. The first
1448        // LineNumber instruction points at the *body's* first statement,
1449        // which is usually one line below the header — but not always
1450        // (blank lines, doc comments can shift it). Instead, scan the
1451        // source directly for the unambiguous `[<trigger>,<short>]`
1452        // pattern and fall back to the LineNumber estimate if the source
1453        // cache isn't attached.
1454        let first_body_line = callee
1455            .instructions
1456            .iter()
1457            .find_map(|i| match (i.opcode, &i.operand) {
1458                (Opcode::LineNumber, Operand::Int(n)) => Some(*n as usize),
1459                _ => None,
1460            })
1461            .unwrap_or(1);
1462        let callee_trigger = callee.trigger.clone();
1463        let callee_short_early = callee
1464            .name
1465            .trim_start_matches('[')
1466            .trim_end_matches(']')
1467            .split_once(',')
1468            .map(|(_, n)| n.to_string())
1469            .unwrap_or_else(|| callee.name.clone());
1470        let callee_header_line = self
1471            .source_cache
1472            .and_then(|c| c.get(&callee_source))
1473            .and_then(|src| find_header_line(&src, &callee_trigger, &callee_short_early))
1474            .unwrap_or_else(|| first_body_line.saturating_sub(1).max(1));
1475
1476        let ptr_cmd = ptr.representation(); // "last_useitem", "last_item", …
1477        let param_type = pointer_param_type(ptr);
1478        let param_name = format!("${}", ptr_cmd);
1479
1480        let callee_short = callee
1481            .name
1482            .trim_start_matches('[')
1483            .trim_end_matches(']')
1484            .split_once(',')
1485            .map(|(_, n)| n.to_string())
1486            .unwrap_or_else(|| callee.name.clone());
1487
1488        let arrow = if is_gosub { "~" } else { "@" };
1489
1490        // Pull the specific corruptor(s) from the callee's own analysis
1491        // so the help message names what actually supersedes the pointer
1492        // (e.g. `p_delay` at line 21, or `~chatnpc` at line 11) rather
1493        // than saying "a delay or subroutine" generically.
1494        let corruptors = self.corruptors_in_callee(callee_idx, ptr);
1495        let corruptor_phrase = format_corruptors(&corruptors);
1496
1497        let message = format!(
1498            "`{callee}` reads `{ptr}` then {phrase}; the script still \
1499             compiles and runs, but the reference is brittle to reorder. \
1500             Consider capturing `{ptr}` at the call site and threading it \
1501             through `{callee}` as an `{ty} {pname}` parameter so the \
1502             value is explicit and stable.",
1503            callee = callee_short,
1504            ptr = ptr_cmd,
1505            phrase = corruptor_phrase,
1506            ty = param_type,
1507            pname = param_name,
1508        );
1509
1510        let cache = match self.source_cache {
1511            Some(c) => c,
1512            None => {
1513                // Prose-only fallback — still useful even without source text.
1514                return Some(Help {
1515                    message,
1516                    suggestions: Vec::new(),
1517                    applicability: Applicability::Unspecified,
1518                });
1519            }
1520        };
1521
1522        let mut suggestions = Vec::new();
1523
1524        // (1) Caller rewrite: insert the captured pointer as an argument
1525        // to the @label/~proc call on `caller_line`.
1526        if let Some(src) = cache.get(caller_source_path)
1527            && let Some(line_text) = nth_source_line(&src, caller_line)
1528            && let Some(rewritten) = rewrite_call_site_arg(line_text, arrow, &callee_short, ptr_cmd)
1529        {
1530            suggestions.push(Suggestion {
1531                file: PathBuf::from(caller_source_path),
1532                line_range: (caller_line, caller_line),
1533                replacement: rewritten,
1534                label: Some(format!("at the call site (pass `{ptr_cmd}` as an arg)")),
1535            });
1536        }
1537
1538        // (2) Callee rewrite: append `<ty> <name>` to the header's param list.
1539        if let Some(src) = cache.get(&callee_source)
1540            && let Some(header_text) = nth_source_line(&src, callee_header_line)
1541            && let Some(rewritten) =
1542                rewrite_header_add_param(header_text, &callee_short, param_type, &param_name)
1543        {
1544            suggestions.push(Suggestion {
1545                file: PathBuf::from(&callee_source),
1546                line_range: (callee_header_line, callee_header_line),
1547                replacement: rewritten,
1548                label: Some(format!(
1549                    "at the `{}` header (add `{} {}`)",
1550                    callee_short, param_type, param_name
1551                )),
1552            });
1553        }
1554
1555        Some(Help {
1556            message,
1557            suggestions,
1558            // The rewrite may collide with an existing local named after the
1559            // pointer, or with an existing param list that already contains
1560            // the value under a different name — human review recommended.
1561            applicability: Applicability::MaybeIncorrect,
1562        })
1563    }
1564}
1565
1566// ---------------------------------------------------------------------------
1567// Graph edge helpers
1568// ---------------------------------------------------------------------------
1569
1570fn add_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1571    if !nodes[from].next.contains(&to) {
1572        nodes[from].next.push(to);
1573    }
1574    if !nodes[to].previous.contains(&from) {
1575        nodes[to].previous.push(from);
1576    }
1577}
1578
1579/// The 2004scape engine tracks `active_player`, `active_npc`, `active_loc`,
1580/// `active_obj`, their `.`-prefixed secondary variants, and
1581/// `p_active_player`/`p_active_player2` via `ScriptState.pointerCheck` at
1582/// runtime. `last_*` and `find_*` pointers are *not* tracked at runtime —
1583/// they are a compile-time discipline only (see the `last_useitem` handler
1584/// in PlayerOps.ts, which gates on `state.trigger`, not a runtime pointer).
1585///
1586/// The "requires AND corrupts at the same node" heuristic (a Jump/Gosub
1587/// inheriting `required | corrupted` from its callee) produces real
1588/// findings for the static-only set but is typically noise for the
1589/// engine-tracked set — callers in that pattern rarely touch the pointer
1590/// after the jump, so the engine's runtime check never fires.
1591fn is_static_only_pointer(ptr: PointerType) -> bool {
1592    use PointerType::*;
1593    matches!(
1594        ptr,
1595        FindPlayer
1596            | FindNpc
1597            | FindLoc
1598            | FindObj
1599            | FindDb
1600            | LastCom
1601            | LastInt
1602            | LastItem
1603            | LastSlot
1604            | LastTargetslot
1605            | LastUseitem
1606            | LastUseslot
1607    )
1608}
1609
1610/// Strip the `[trigger,name]` brackets from a script's full name and
1611/// return just the `name` half, for display in help messages.
1612fn short_script_name(full_name: &str) -> Option<String> {
1613    full_name
1614        .trim_start_matches('[')
1615        .trim_end_matches(']')
1616        .split_once(',')
1617        .map(|(_, n)| n.to_string())
1618}
1619
1620/// Render a list of `(name, line)` corruptors into the clause slot
1621/// in the help message. Empty → generic fallback; 1 → `calls `X` at line N`;
1622/// 2 → `calls `X` at line N and `Y` at line M`; 3+ → list with commas
1623/// and a trailing "and", truncated after 3 with "…".
1624fn format_corruptors(corruptors: &[(String, usize)]) -> String {
1625    if corruptors.is_empty() {
1626        return "calls a delay or subroutine that may supersede it".to_string();
1627    }
1628
1629    const MAX: usize = 3;
1630    let shown: Vec<String> = corruptors
1631        .iter()
1632        .take(MAX)
1633        .map(|(name, line)| {
1634            if *line > 0 {
1635                format!("`{}` at line {}", name, line)
1636            } else {
1637                format!("`{}`", name)
1638            }
1639        })
1640        .collect();
1641
1642    let suffix = if corruptors.len() > MAX {
1643        format!(" (and {} more)", corruptors.len() - MAX)
1644    } else {
1645        String::new()
1646    };
1647
1648    let joined = match shown.len() {
1649        1 => shown[0].clone(),
1650        2 => format!("{} and {}", shown[0], shown[1]),
1651        _ => {
1652            let head = shown[..shown.len() - 1].join(", ");
1653            format!("{}, and {}", head, shown[shown.len() - 1])
1654        }
1655    };
1656
1657    format!("calls {}{} which may supersede it", joined, suffix)
1658}
1659
1660/// The RuneScript parameter type to use when threading a `last_*` pointer
1661/// through as a label argument. Mirrors the return types declared on the
1662/// corresponding engine commands in `content/scripts/engine.rs2`:
1663///   last_useitem/last_item -> obj
1664///   last_com               -> component
1665///   last_useslot/last_slot/last_targetslot/last_int -> int
1666/// Every other static-only pointer falls back to `int` (safe default —
1667/// the suggestion lands in `Applicability::MaybeIncorrect` anyway).
1668fn pointer_param_type(ptr: PointerType) -> &'static str {
1669    use PointerType::*;
1670    match ptr {
1671        LastUseitem | LastItem => "obj",
1672        LastCom => "component",
1673        _ => "int",
1674    }
1675}
1676
1677/// Extract 1-indexed line `line_no` from `text`. `None` if out of range.
1678fn nth_source_line(text: &str, line_no: usize) -> Option<&str> {
1679    if line_no == 0 {
1680        return None;
1681    }
1682    text.lines().nth(line_no - 1)
1683}
1684
1685/// Rewrite a caller line like `[oplocu,...] @label;` or
1686/// `@label(1);` to pass `last_useitem` (or whichever pointer) as an
1687/// additional argument. Returns `None` if the pattern isn't recognized.
1688///
1689/// Handles:
1690///   `@name;`                -> `@name(last_useitem);`
1691///   `@name(a, b);`          -> `@name(a, b, last_useitem);`
1692///   `~name;` / `~name(...)` (gosub) — same shape with `~`.
1693fn rewrite_call_site_arg(
1694    line: &str,
1695    arrow: &str,
1696    callee_short: &str,
1697    ptr_cmd: &str,
1698) -> Option<String> {
1699    // Locate `<arrow><callee_short>` as a call reference. The label may
1700    // appear multiple times on one line (rare) — we rewrite the first.
1701    let needle = format!("{}{}", arrow, callee_short);
1702    let start = line.find(&needle)?;
1703    let after_name = start + needle.len();
1704    let tail = &line[after_name..];
1705
1706    // Case A: immediately followed by `;` or end-of-line — no existing args.
1707    let first_non_ws = tail.chars().next();
1708    if matches!(first_non_ws, None | Some(';') | Some('\r') | Some('\n'))
1709        || tail.trim_start().is_empty()
1710    {
1711        let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1712        out.push_str(&line[..after_name]);
1713        out.push('(');
1714        out.push_str(ptr_cmd);
1715        out.push(')');
1716        out.push_str(tail);
1717        return Some(out);
1718    }
1719
1720    // Case B: followed by `(` — locate the matching `)` and insert the arg
1721    // just before it.
1722    if tail.trim_start().starts_with('(') {
1723        let open_rel = tail.find('(')?;
1724        let abs_open = after_name + open_rel;
1725        let close_rel = find_matching_close_paren(&line[abs_open..])?;
1726        let abs_close = abs_open + close_rel;
1727
1728        // Empty arg list: `@name()` -> `@name(last_useitem)`.
1729        let inside = line[abs_open + 1..abs_close].trim();
1730        let mut out = String::with_capacity(line.len() + ptr_cmd.len() + 2);
1731        out.push_str(&line[..abs_close]);
1732        if inside.is_empty() {
1733            out.push_str(ptr_cmd);
1734        } else {
1735            out.push_str(", ");
1736            out.push_str(ptr_cmd);
1737        }
1738        out.push_str(&line[abs_close..]);
1739        return Some(out);
1740    }
1741
1742    None
1743}
1744
1745/// Rewrite a label/proc header line to append `<ty> <name>` to its
1746/// parameter list. Handles all three forms:
1747///   `[label,foo]`              -> `[label,foo](obj $used)`
1748///   `[label,foo](int $x)`      -> `[label,foo](int $x, obj $used)`
1749///   `[proc,foo]()(int)`        -> `[proc,foo](obj $used)(int)`
1750fn rewrite_header_add_param(
1751    line: &str,
1752    callee_short: &str,
1753    param_type: &str,
1754    param_name: &str,
1755) -> Option<String> {
1756    // Locate the `,<callee_short>]` subject closer so we know where the
1757    // header ends and any parameter list begins.
1758    let needle = format!(",{}]", callee_short);
1759    let subject_end = line.find(&needle)?;
1760    let after_bracket = subject_end + needle.len();
1761
1762    let remainder = &line[after_bracket..];
1763    let added = format!("{} {}", param_type, param_name);
1764
1765    // No param list at all — append `(<ty> <name>)`.
1766    if !remainder.trim_start().starts_with('(') {
1767        let mut out = String::with_capacity(line.len() + added.len() + 2);
1768        out.push_str(&line[..after_bracket]);
1769        out.push('(');
1770        out.push_str(&added);
1771        out.push(')');
1772        out.push_str(remainder);
1773        return Some(out);
1774    }
1775
1776    // Has at least one `(...)` — find its close and insert before it.
1777    let open_rel = remainder.find('(')?;
1778    let abs_open = after_bracket + open_rel;
1779    let close_rel = find_matching_close_paren(&line[abs_open..])?;
1780    let abs_close = abs_open + close_rel;
1781    let inside = line[abs_open + 1..abs_close].trim();
1782
1783    let mut out = String::with_capacity(line.len() + added.len() + 2);
1784    out.push_str(&line[..abs_close]);
1785    if inside.is_empty() {
1786        out.push_str(&added);
1787    } else {
1788        out.push_str(", ");
1789        out.push_str(&added);
1790    }
1791    out.push_str(&line[abs_close..]);
1792    Some(out)
1793}
1794
1795/// Locate the 1-indexed line that declares `[<trigger>,<name>]` in `src`.
1796/// Ignores leading whitespace; matches on the exact `[trigger,name]`
1797/// prefix (before any `(...)` parameter list).
1798fn find_header_line(src: &str, trigger: &str, name: &str) -> Option<usize> {
1799    let prefix = format!("[{},{}]", trigger, name);
1800    let prefix_with_params = format!("[{},{}](", trigger, name);
1801    for (i, line) in src.lines().enumerate() {
1802        let trimmed = line.trim_start();
1803        if trimmed.starts_with(&prefix) || trimmed.starts_with(&prefix_with_params) {
1804            return Some(i + 1);
1805        }
1806    }
1807    None
1808}
1809
1810/// Given a string whose first char is `(`, return the byte offset of the
1811/// matching `)`. Respects nesting but is deliberately naive about strings
1812/// (RuneScript headers don't contain string literals).
1813fn find_matching_close_paren(s: &str) -> Option<usize> {
1814    let bytes = s.as_bytes();
1815    if bytes.first().copied() != Some(b'(') {
1816        return None;
1817    }
1818    let mut depth = 0i32;
1819    for (i, &b) in bytes.iter().enumerate() {
1820        match b {
1821            b'(' => depth += 1,
1822            b')' => {
1823                depth -= 1;
1824                if depth == 0 {
1825                    return Some(i);
1826                }
1827            }
1828            _ => {}
1829        }
1830    }
1831    None
1832}
1833
1834/// Game-var Push/Pop instructions encode the secondary (dot-prefixed,
1835/// `.%v`) vs primary (`%v`) distinction in bit 16 of the integer operand
1836/// (see `compiler.rs` Expr::GameVar handling: `(1 << 16) | var_id`).
1837/// TS uses distinct opcodes for this; we collapse to a single opcode and
1838/// recover the flag here when attributing the pointer requirement.
1839fn is_secondary_var_operand(operand: &Operand) -> bool {
1840    match operand {
1841        Operand::Int(encoded) => ((*encoded >> 16) & 1) == 1,
1842        _ => false,
1843    }
1844}
1845
1846/// Resolve a jump target (an instruction index) to the CFG node index, walking
1847/// past any `LineNumber` instructions that are stripped from the CFG. Without
1848/// this, an `if` body's BranchEquals target — which usually lands on the body's
1849/// leading LineNumber — would fail the `instr_to_node.get()` lookup and the
1850/// edge would silently drop, disconnecting the body from its predecessors.
1851fn resolve_target_node(
1852    mut target_idx: usize,
1853    instructions: &[Instruction],
1854    instr_to_node: &HashMap<usize, usize>,
1855) -> Option<usize> {
1856    while target_idx < instructions.len() && instructions[target_idx].opcode == Opcode::LineNumber {
1857        target_idx += 1;
1858    }
1859    instr_to_node.get(&target_idx).copied()
1860}
1861
1862fn remove_edge(nodes: &mut [CfgNode], from: usize, to: usize) {
1863    nodes[from].next.retain(|&n| n != to);
1864    nodes[to].previous.retain(|&n| n != from);
1865}
1866
1867/// Find the source line number for an instruction by scanning backwards for
1868/// the nearest `LineNumber` instruction. Returns 0 if none found.
1869fn resolve_line(instructions: &[Instruction], instr_idx: usize) -> usize {
1870    for i in (0..=instr_idx).rev() {
1871        if instructions[i].opcode == Opcode::LineNumber
1872            && let Operand::Int(line) = instructions[i].operand
1873        {
1874            return line as usize;
1875        }
1876    }
1877    0
1878}
1879
1880#[cfg(test)]
1881mod tests {
1882    use super::*;
1883    use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
1884    use crate::symbol::SymbolRegistry;
1885
1886    /// Build a minimal registry with a command registered at a given opcode.
1887    fn registry_with_commands(commands: &[(&str, i32)]) -> SymbolRegistry {
1888        let mut reg = SymbolRegistry::new();
1889        for &(name, opcode) in commands {
1890            reg.register_command(name.to_string(), opcode, vec![], vec![]);
1891        }
1892        reg
1893    }
1894
1895    /// Build a compiled script with the given trigger, name, and instructions.
1896    fn make_script(
1897        name: &str,
1898        trigger: &str,
1899        id: i32,
1900        instructions: Vec<Instruction>,
1901    ) -> CompiledScript {
1902        let mut script = CompiledScript::new(format!("[{trigger},{name}]"), id);
1903        script.trigger = trigger.to_string();
1904        script.source_path = "test.rs2".to_string();
1905        script.instructions = instructions;
1906        script
1907    }
1908
1909    /// Helper: Command instruction with encoded opcode (no secondary entity).
1910    fn cmd(opcode: i32) -> Instruction {
1911        Instruction::new(Opcode::Command, Operand::Int(opcode))
1912    }
1913
1914    fn line(n: i32) -> Instruction {
1915        Instruction::new(Opcode::LineNumber, Operand::Int(n))
1916    }
1917
1918    fn push_int(v: i32) -> Instruction {
1919        Instruction::push_int(v)
1920    }
1921
1922    fn branch_eq(target: usize) -> Instruction {
1923        Instruction::new(Opcode::BranchEquals, Operand::JumpTarget(target))
1924    }
1925
1926    fn branch(target: usize) -> Instruction {
1927        Instruction::new(Opcode::Branch, Operand::JumpTarget(target))
1928    }
1929
1930    fn ret() -> Instruction {
1931        Instruction::simple(Opcode::Return)
1932    }
1933
1934    fn gosub(script_id: i32) -> Instruction {
1935        Instruction::new(Opcode::GosubWithParams, Operand::Int(script_id))
1936    }
1937
1938    // -----------------------------------------------------------------------
1939    // Test: conditional setter with argument push between Command and Branch
1940    // -----------------------------------------------------------------------
1941    // Simulates: if (p_finduid(uid) = true) { p_stopaction; }
1942    // Bytecode: PushVar, Command(p_finduid), PushConstantInt(1), BranchEquals, Branch, ...
1943    // The conditional setter should be detected despite the PushVar before Command.
1944    #[test]
1945    fn conditional_setter_with_arg_push() {
1946        // p_finduid opcode = 4267 (arbitrary, just needs to be in command_pointers)
1947        // p_stopaction opcode = 4268
1948        let p_finduid_op = 4267;
1949        let p_stopaction_op = 4268;
1950
1951        let registry = registry_with_commands(&[
1952            ("p_finduid", p_finduid_op),
1953            ("p_stopaction", p_stopaction_op),
1954        ]);
1955
1956        let instructions = vec![
1957            line(1),              // 0: LineNumber
1958            push_int(0),          // 1: PushVar(uid) - simulated as push_int
1959            cmd(p_finduid_op),    // 2: Command(p_finduid)
1960            push_int(1),          // 3: PushConstantInt(1) = true
1961            branch_eq(7),         // 4: BranchEquals -> body
1962            branch(8),            // 5: Branch -> end
1963            line(2),              // 6: LineNumber
1964            cmd(p_stopaction_op), // 7: Command(p_stopaction) - requires p_active_player
1965            ret(),                // 8: Return
1966        ];
1967
1968        // Script with "label" trigger (gets all pointers initially? No - we want
1969        // to test that the conditional setter provides the pointer)
1970        // Use "ai_timer" which only provides active_npc — no p_active_player.
1971        let script = make_script("test", "ai_timer", 0, instructions);
1972        let scripts = vec![script];
1973
1974        let mut checker = PointerChecker::new(&scripts, &registry);
1975        let diags = checker.run();
1976
1977        // p_finduid conditionally sets p_active_player on the true branch.
1978        // p_stopaction requires p_active_player and is only on the true branch.
1979        // So this should produce NO diagnostics.
1980        assert_eq!(
1981            diags.warning_count(),
1982            0,
1983            "conditional setter should provide p_active_player on true branch, got {} warnings",
1984            diags.warning_count()
1985        );
1986    }
1987
1988    #[test]
1989    fn boolean_branches_preserve_conditional_pointer_analysis() {
1990        let registry = registry_with_commands(&[("p_finduid", 4267), ("p_delay", 4268)]);
1991        for (opcode, target, skip) in [(Opcode::BranchIfTrue, 5, 6), (Opcode::BranchIfFalse, 6, 5)]
1992        {
1993            let script = make_script(
1994                "test",
1995                "ai_timer",
1996                0,
1997                vec![
1998                    line(1),
1999                    push_int(0),
2000                    cmd(4267),
2001                    Instruction::new(opcode, Operand::JumpTarget(target)),
2002                    branch(skip),
2003                    cmd(4268),
2004                    ret(),
2005                ],
2006            );
2007            assert_eq!(
2008                PointerChecker::new(&[script], &registry)
2009                    .run()
2010                    .warning_count(),
2011                0
2012            );
2013        }
2014        let script = make_script(
2015            "test",
2016            "ai_timer",
2017            0,
2018            vec![
2019                line(1),
2020                push_int(0),
2021                cmd(4267),
2022                Instruction::new(Opcode::BranchIfFalse, Operand::JumpTarget(5)),
2023                branch(6),
2024                cmd(4268),
2025                ret(),
2026            ],
2027        );
2028        assert!(
2029            PointerChecker::new(&[script], &registry)
2030                .run()
2031                .warning_count()
2032                > 0
2033        );
2034    }
2035
2036    // -----------------------------------------------------------------------
2037    // Test: proc that requires AND corrupts the same pointer (gnomeball pattern)
2038    // -----------------------------------------------------------------------
2039    // Simulates a label calling a proc that:
2040    //   - requires p_active_player (via p_delay)
2041    //   - then corrupts p_active_player (via npc_delay)
2042    // The Gosub node is simultaneously in required and corrupted lists.
2043    // This should NOT be flagged — the requirement is satisfied before corruption.
2044    #[test]
2045    fn gosub_requires_then_corrupts_same_pointer() {
2046        let p_delay_op = 5001;
2047        let npc_delay_op = 5002;
2048
2049        let registry =
2050            registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2051
2052        // Proc: p_delay(0); npc_delay(0); return;
2053        // This proc requires p_active_player (p_delay) then corrupts it (npc_delay).
2054        let proc_script = make_script(
2055            "tackle_success",
2056            "proc",
2057            100,
2058            vec![
2059                line(1),
2060                push_int(0),
2061                cmd(p_delay_op), // requires p_active_player, does NOT corrupt it
2062                line(2),
2063                push_int(0),
2064                cmd(npc_delay_op), // corrupts p_active_player
2065                ret(),
2066            ],
2067        );
2068
2069        // Label: calls the proc via gosub
2070        // The label trigger provides all pointers including p_active_player.
2071        let label_script = make_script(
2072            "do_tackle",
2073            "label",
2074            200,
2075            vec![
2076                line(10),
2077                gosub(100), // Gosub to proc — requires AND corrupts p_active_player
2078                ret(),
2079            ],
2080        );
2081
2082        let scripts = vec![proc_script, label_script];
2083        let mut checker = PointerChecker::new(&scripts, &registry);
2084        let diags = checker.run();
2085
2086        // The label has p_active_player from trigger.
2087        // The gosub requires it (satisfied) then corrupts it.
2088        // No diagnostic — the main BFS starts from predecessors of the
2089        // required node (not the node itself), and the secondary require+
2090        // corrupt heuristic skips engine-tracked pointers like PActivePlayer.
2091        assert_eq!(
2092            diags.warning_count(),
2093            0,
2094            "gosub that requires-then-corrupts p_active_player should not \
2095             be flagged (engine-tracked pointer), got {} warnings",
2096            diags.warning_count()
2097        );
2098    }
2099
2100    // -----------------------------------------------------------------------
2101    // Test: legitimate corruption SHOULD be caught
2102    // -----------------------------------------------------------------------
2103    // A command corrupts p_active_player, then a later command requires it.
2104    // This should produce an error.
2105    #[test]
2106    fn corruption_before_requirement_is_caught() {
2107        let npc_delay_op = 5002;
2108        let p_delay_op = 5001;
2109
2110        let registry =
2111            registry_with_commands(&[("npc_delay", npc_delay_op), ("p_delay", p_delay_op)]);
2112
2113        // Label: npc_delay(0); p_delay(0);
2114        // npc_delay corrupts p_active_player, then p_delay requires it.
2115        let script = make_script(
2116            "bad_order",
2117            "label",
2118            0,
2119            vec![
2120                line(1),
2121                push_int(0),
2122                cmd(npc_delay_op), // corrupts p_active_player
2123                line(2),
2124                push_int(0),
2125                cmd(p_delay_op), // requires p_active_player — should fail!
2126                ret(),
2127            ],
2128        );
2129
2130        let scripts = vec![script];
2131        let mut checker = PointerChecker::new(&scripts, &registry);
2132        let diags = checker.run();
2133
2134        assert!(
2135            diags.warning_count() > 0,
2136            "corruption before requirement should be caught as a warning"
2137        );
2138    }
2139
2140    // -----------------------------------------------------------------------
2141    // Test: uninitialized pointer access
2142    // -----------------------------------------------------------------------
2143    // A script with a trigger that doesn't provide p_active_player uses p_delay.
2144    #[test]
2145    fn uninitialized_pointer_caught() {
2146        let p_delay_op = 5001;
2147
2148        let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2149
2150        // ai_timer trigger only provides active_npc, not p_active_player.
2151        let script = make_script(
2152            "bad_access",
2153            "ai_timer",
2154            0,
2155            vec![
2156                line(1),
2157                push_int(0),
2158                cmd(p_delay_op), // requires p_active_player — not provided by trigger
2159                ret(),
2160            ],
2161        );
2162
2163        let scripts = vec![script];
2164        let mut checker = PointerChecker::new(&scripts, &registry);
2165        let diags = checker.run();
2166
2167        assert!(
2168            diags.warning_count() > 0,
2169            "uninitialized pointer access should be caught"
2170        );
2171    }
2172
2173    // -----------------------------------------------------------------------
2174    // Test: jump target landing on a LineNumber instruction
2175    // -----------------------------------------------------------------------
2176    // Regression: BranchEquals/Branch targets patched to body_start often
2177    // land on a LineNumber instruction (emitted for the body's first source
2178    // line). LineNumbers are stripped from the CFG, so without
2179    // resolve_target_node() the edge would be silently dropped and the body
2180    // node would have no predecessors — hiding genuine uninitialized-pointer
2181    // errors for callers that wrap the @jump in an `if` block.
2182    #[test]
2183    fn branch_target_on_line_number_still_connects() {
2184        let p_delay_op = 5001;
2185        let registry = registry_with_commands(&[("p_delay", p_delay_op)]);
2186
2187        // ai_timer trigger provides active_npc but NOT p_active_player.
2188        // Layout: `if (1 = 1) { p_delay(0); }` — BranchEquals jumps to the
2189        // body's leading LineNumber. If the CFG drops that edge the body
2190        // node is disconnected and the uninitialized p_active_player read
2191        // is never flagged.
2192        //
2193        //   0 LineNumber(1)
2194        //   1 PushConstantInt(1)
2195        //   2 PushConstantInt(1)
2196        //   3 BranchEquals -> 5 (LineNumber at body start)
2197        //   4 Branch       -> 8 (end-of-if marker; here, Return)
2198        //   5 LineNumber(2)
2199        //   6 PushConstantInt(0)
2200        //   7 Command(p_delay)
2201        //   8 Return
2202        let script = make_script(
2203            "target_on_line_number",
2204            "ai_timer",
2205            0,
2206            vec![
2207                line(1),
2208                push_int(1),
2209                push_int(1),
2210                branch_eq(5), // jump target is the LineNumber at index 5
2211                Instruction::new(Opcode::Branch, Operand::JumpTarget(8)),
2212                line(2),
2213                push_int(0),
2214                cmd(p_delay_op),
2215                ret(),
2216            ],
2217        );
2218
2219        let scripts = vec![script];
2220        let mut checker = PointerChecker::new(&scripts, &registry);
2221        let diags = checker.run();
2222
2223        assert!(
2224            diags.warning_count() > 0,
2225            "jump target on LineNumber must still flag uninitialized pointer \
2226             access (got {} warnings)",
2227            diags.warning_count()
2228        );
2229    }
2230
2231    // -----------------------------------------------------------------------
2232    // Test: secondary require+corrupt warning for static-only pointers
2233    // -----------------------------------------------------------------------
2234    // A label that requires AND corrupts LastUseitem (via last_useitem then
2235    // p_delay) is called via @jump from an oplocu trigger that provides
2236    // LastUseitem. The main BFS correctly finds no error (predecessors are
2237    // clean), but the secondary heuristic flags the Jump as "requires and
2238    // corrupts last_useitem on the same node" — this is the 23-warning
2239    // pattern from the legacy lost-city 225 output.
2240    #[test]
2241    fn secondary_requires_and_corrupts_warns_for_static_pointer() {
2242        // last_useitem and p_delay opcodes (arbitrary, just need to be in
2243        // command_pointers()).
2244        let last_useitem_op = 4270;
2245        let p_delay_op = 5001;
2246        let registry =
2247            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2248
2249        // Callee label: reads last_useitem, then corrupts it via p_delay.
2250        let callee = make_script(
2251            "consume_useitem",
2252            "label",
2253            100,
2254            vec![
2255                line(1),
2256                cmd(last_useitem_op), // requires LastUseitem
2257                line(2),
2258                push_int(0),
2259                cmd(p_delay_op), // corrupts LastUseitem
2260                ret(),
2261            ],
2262        );
2263
2264        // Caller: oplocu trigger provides LastUseitem. Jumps to the label.
2265        // The Jump node inherits BOTH required[LastUseitem] AND
2266        // corrupted[LastUseitem]. Main BFS: predecessors of Jump trace back
2267        // to node 0, which is NOT corrupted (trigger provides) — no main
2268        // diagnostic. Secondary heuristic: Jump appears in both sets, emit
2269        // a warning.
2270        let caller = make_script(
2271            "use_on_loc",
2272            "oplocu",
2273            200,
2274            vec![
2275                line(10),
2276                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2277            ],
2278        );
2279
2280        let scripts = vec![callee, caller];
2281        let mut checker = PointerChecker::new(&scripts, &registry);
2282        let diags = checker.run();
2283
2284        let last_useitem_warnings = diags
2285            .diagnostics()
2286            .iter()
2287            .filter(|d| d.severity == Severity::Warning)
2288            .filter(|d| d.message.contains("last_useitem"))
2289            .count();
2290        assert!(
2291            last_useitem_warnings > 0,
2292            "static-only pointer (last_useitem) should trigger the \
2293             require+corrupt warning at the jump site; got diags: {:?}",
2294            diags
2295                .diagnostics()
2296                .iter()
2297                .map(|d| &d.message)
2298                .collect::<Vec<_>>()
2299        );
2300
2301        assert_eq!(
2302            diags.error_count(),
2303            0,
2304            "pointer-check diagnostics must never raise error severity; got {} errors",
2305            diags.error_count()
2306        );
2307    }
2308
2309    // -----------------------------------------------------------------------
2310    // Test: secondary heuristic SUPPRESSES warnings for engine-tracked pointers
2311    // -----------------------------------------------------------------------
2312    // Same pattern as above, but the pointer is PActivePlayer (engine-
2313    // tracked). The secondary heuristic must NOT emit — the user's legacy
2314    // 23-warning output specifically excludes the gnome_baller
2315    // p_active_player findings because the 2004scape engine manages that
2316    // pointer at runtime.
2317    #[test]
2318    fn secondary_requires_and_corrupts_silent_for_engine_pointer() {
2319        let p_delay_op = 5001;
2320        let npc_delay_op = 5002;
2321        let registry =
2322            registry_with_commands(&[("p_delay", p_delay_op), ("npc_delay", npc_delay_op)]);
2323
2324        let callee = make_script(
2325            "consume_protected",
2326            "proc",
2327            100,
2328            vec![
2329                line(1),
2330                push_int(0),
2331                cmd(p_delay_op), // requires PActivePlayer
2332                line(2),
2333                push_int(0),
2334                cmd(npc_delay_op), // corrupts PActivePlayer
2335                ret(),
2336            ],
2337        );
2338
2339        // opnpc1 provides ActivePlayer, PActivePlayer, ActiveNpc.
2340        let caller = make_script(
2341            "do_opnpc",
2342            "opnpc1",
2343            200,
2344            vec![
2345                line(10),
2346                Instruction::new(Opcode::GosubWithParams, Operand::Int(100)),
2347                ret(),
2348            ],
2349        );
2350
2351        let scripts = vec![callee, caller];
2352        let mut checker = PointerChecker::new(&scripts, &registry);
2353        let diags = checker.run();
2354
2355        let p_active_player_warnings = diags
2356            .diagnostics()
2357            .iter()
2358            .filter(|d| d.severity == Severity::Warning)
2359            .filter(|d| d.message.contains("p_active_player"))
2360            .count();
2361        assert_eq!(
2362            p_active_player_warnings, 0,
2363            "engine-tracked pointer (p_active_player) must not trigger the \
2364             require+corrupt warning; got {} such warnings",
2365            p_active_player_warnings
2366        );
2367    }
2368
2369    // -----------------------------------------------------------------------
2370    // Test: secondary (dot-prefixed) var reads require the `*2` pointer
2371    // -----------------------------------------------------------------------
2372    // Regression: categorize_nodes used to map every PushVarn/PopVarn (and
2373    // PushVarp/PopVarp/PushVarbit/PopVarbit) to the primary active_npc /
2374    // active_player pointer, ignoring the bit-16 "secondary" flag that
2375    // compiler.rs sets on `.%var` operands. That miscategorization caused
2376    // the 4 spurious `uninitialized active_npc` warnings at
2377    // gnomeball_pass.rs2:1,2 and duel_arena.rs2:3,10.
2378    //
2379    // A proc reading `.%npc_var` should only require active_npc2 — no
2380    // active_npc warning should propagate to its callers.
2381    #[test]
2382    fn secondary_varn_requires_active_npc2_not_primary() {
2383        // PushVarn is Opcode::PushVarn (=4). Operand encodes var_id in low
2384        // 16 bits; bit 16 marks secondary. We bypass the varn registry by
2385        // emitting the raw opcode — the pointer checker only inspects the
2386        // opcode + operand.
2387        let secondary_varn = Instruction::new(
2388            Opcode::PushVarn,
2389            Operand::Int(1 << 16), // .%var_id 0, secondary
2390        );
2391
2392        // Proc reads a secondary NPC var and returns.
2393        let proc_script = make_script(
2394            "reads_secondary_varn",
2395            "proc",
2396            100,
2397            vec![
2398                line(1),
2399                secondary_varn,
2400                Instruction::simple(Opcode::PopIntDiscard),
2401                ret(),
2402            ],
2403        );
2404
2405        // Caller: opplayer1 trigger provides active_player/p_active_player/
2406        // active_player2, but does NOT provide active_npc or active_npc2.
2407        // Before the fix, the gosub inherited active_npc (primary) from the
2408        // proc and the caller would be flagged "uninitialized active_npc".
2409        // After the fix, the proc only requires active_npc2, which also
2410        // isn't provided — but crucially, `active_npc` is not flagged.
2411        let caller = make_script(
2412            "gosub_into_proc",
2413            "opplayer1",
2414            200,
2415            vec![line(10), gosub(100), ret()],
2416        );
2417
2418        let scripts = vec![proc_script, caller];
2419        let registry = registry_with_commands(&[]);
2420        let mut checker = PointerChecker::new(&scripts, &registry);
2421        let diags = checker.run();
2422
2423        // Diagnostic messages use the pointer's `representation()`:
2424        //   PointerType::ActiveNpc  -> "active_npc"
2425        //   PointerType::ActiveNpc2 -> ".active_npc"
2426        // Match "pointer active_npc." to count ONLY primary hits — the
2427        // secondary form appears as "pointer .active_npc.".
2428        let active_npc_primary_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_eq!(
2435            active_npc_primary_warnings,
2436            0,
2437            "secondary .%var read must not flag primary active_npc at the \
2438             caller; got diags: {:?}",
2439            diags
2440                .diagnostics()
2441                .iter()
2442                .filter(|d| d.severity == Severity::Warning)
2443                .map(|d| &d.message)
2444                .collect::<Vec<_>>()
2445        );
2446
2447        // Sanity: the secondary requirement DID propagate — opplayer1 doesn't
2448        // provide active_npc2 either, so `.active_npc` should be flagged.
2449        // This proves the attribution went to the `*2` pointer as intended.
2450        let active_npc2_warnings = diags
2451            .diagnostics()
2452            .iter()
2453            .filter(|d| d.severity == Severity::Warning)
2454            .filter(|d| d.message.contains("pointer .active_npc."))
2455            .count();
2456        assert!(
2457            active_npc2_warnings > 0,
2458            "secondary .%var should route the requirement to active_npc2; \
2459             got no such warning"
2460        );
2461    }
2462
2463    // -----------------------------------------------------------------------
2464    // Unit tests for the Rule A text rewriters
2465    // -----------------------------------------------------------------------
2466
2467    #[test]
2468    fn rewrite_call_site_no_args() {
2469        let got = rewrite_call_site_arg(
2470            "[opnpcu,wantcat1] @civilian_give_runes;",
2471            "@",
2472            "civilian_give_runes",
2473            "last_useitem",
2474        )
2475        .unwrap();
2476        assert_eq!(got, "[opnpcu,wantcat1] @civilian_give_runes(last_useitem);");
2477    }
2478
2479    #[test]
2480    fn rewrite_call_site_with_args() {
2481        let got = rewrite_call_site_arg(
2482            "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\");",
2483            "@",
2484            "amulet_of_glory_interface",
2485            "last_item",
2486        )
2487        .unwrap();
2488        assert_eq!(
2489            got,
2490            "[opheld4,amulet_of_glory_4] @amulet_of_glory_interface(\"msg\", last_item);"
2491        );
2492    }
2493
2494    #[test]
2495    fn rewrite_call_site_gosub_no_args() {
2496        let got =
2497            rewrite_call_site_arg("    ~some_proc;", "~", "some_proc", "last_useitem").unwrap();
2498        assert_eq!(got, "    ~some_proc(last_useitem);");
2499    }
2500
2501    #[test]
2502    fn rewrite_call_site_empty_arg_list() {
2503        let got = rewrite_call_site_arg("@foo();", "@", "foo", "last_useitem").unwrap();
2504        assert_eq!(got, "@foo(last_useitem);");
2505    }
2506
2507    #[test]
2508    fn rewrite_header_no_params() {
2509        let got = rewrite_header_add_param(
2510            "[label,civilian_give_runes]",
2511            "civilian_give_runes",
2512            "obj",
2513            "$last_useitem",
2514        )
2515        .unwrap();
2516        assert_eq!(got, "[label,civilian_give_runes](obj $last_useitem)");
2517    }
2518
2519    #[test]
2520    fn rewrite_header_with_existing_params() {
2521        let got = rewrite_header_add_param(
2522            "[label,amulet_of_glory_interface](string $message)",
2523            "amulet_of_glory_interface",
2524            "obj",
2525            "$last_item",
2526        )
2527        .unwrap();
2528        assert_eq!(
2529            got,
2530            "[label,amulet_of_glory_interface](string $message, obj $last_item)"
2531        );
2532    }
2533
2534    #[test]
2535    fn rewrite_header_proc_with_return_type() {
2536        // `[proc,foo]()(int)` — parameter list comes before the return
2537        // list. We must insert into the FIRST `(...)` group.
2538        let got = rewrite_header_add_param("[proc,foo]()(int)", "foo", "obj", "$x").unwrap();
2539        assert_eq!(got, "[proc,foo](obj $x)(int)");
2540    }
2541
2542    #[test]
2543    fn find_header_line_matches_trigger_and_name() {
2544        let src = "// comment\n[label,foo]\nbody line\n[label,bar](int $x)\n";
2545        assert_eq!(find_header_line(src, "label", "foo"), Some(2));
2546        assert_eq!(find_header_line(src, "label", "bar"), Some(4));
2547        assert_eq!(find_header_line(src, "label", "missing"), None);
2548    }
2549
2550    #[test]
2551    fn format_corruptors_shapes() {
2552        assert_eq!(
2553            format_corruptors(&[]),
2554            "calls a delay or subroutine that may supersede it"
2555        );
2556        assert_eq!(
2557            format_corruptors(&[("p_delay".to_string(), 21)]),
2558            "calls `p_delay` at line 21 which may supersede it"
2559        );
2560        assert_eq!(
2561            format_corruptors(&[("p_delay".to_string(), 21), ("~chatnpc".to_string(), 11),]),
2562            "calls `p_delay` at line 21 and `~chatnpc` at line 11 which may supersede it"
2563        );
2564        assert_eq!(
2565            format_corruptors(&[
2566                ("p_delay".to_string(), 21),
2567                ("~chatnpc".to_string(), 11),
2568                ("~objbox".to_string(), 14),
2569            ]),
2570            "calls `p_delay` at line 21, `~chatnpc` at line 11, and `~objbox` at line 14 which may supersede it"
2571        );
2572        // Truncates after 3 with a summary suffix.
2573        assert_eq!(
2574            format_corruptors(&[
2575                ("p_delay".to_string(), 1),
2576                ("~a".to_string(), 2),
2577                ("~b".to_string(), 3),
2578                ("~c".to_string(), 4),
2579                ("~d".to_string(), 5),
2580            ]),
2581            "calls `p_delay` at line 1, `~a` at line 2, and `~b` at line 3 (and 2 more) which may supersede it"
2582        );
2583        // Unknown line falls back to bare name.
2584        assert_eq!(
2585            format_corruptors(&[("p_delay".to_string(), 0)]),
2586            "calls `p_delay` which may supersede it"
2587        );
2588    }
2589
2590    #[test]
2591    fn find_matching_close_paren_nested() {
2592        assert_eq!(find_matching_close_paren("()"), Some(1));
2593        assert_eq!(find_matching_close_paren("(a, b)"), Some(5));
2594        assert_eq!(find_matching_close_paren("(f(x), y)"), Some(8));
2595        assert_eq!(find_matching_close_paren("("), None);
2596        assert_eq!(find_matching_close_paren("abc"), None);
2597    }
2598
2599    // -----------------------------------------------------------------------
2600    // Test: secondary require+corrupt warning carries a populated Help
2601    //       with concrete before/after suggestions when source is available
2602    // -----------------------------------------------------------------------
2603    #[test]
2604    fn secondary_warning_attaches_help_with_rewrite_suggestions() {
2605        use std::collections::HashMap;
2606        use std::sync::Arc;
2607
2608        let last_useitem_op = 4270;
2609        let p_delay_op = 5001;
2610        let registry =
2611            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2612
2613        // Callee label — reads last_useitem, then p_delay corrupts it.
2614        let mut callee = make_script(
2615            "consume_useitem",
2616            "label",
2617            100,
2618            vec![
2619                line(2), // body starts on source line 2
2620                cmd(last_useitem_op),
2621                line(3),
2622                push_int(0),
2623                cmd(p_delay_op),
2624                ret(),
2625            ],
2626        );
2627        callee.source_path = "/virt/consume.rs2".to_string();
2628
2629        // Caller — oplocu provides last_useitem; @jumps into callee.
2630        let mut caller = make_script(
2631            "use_on_loc",
2632            "oplocu",
2633            200,
2634            vec![
2635                line(1),
2636                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2637            ],
2638        );
2639        caller.source_path = "/virt/caller.rs2".to_string();
2640
2641        // Virtual source text. Caller on line 1, callee header on line 1
2642        // of its own file.
2643        let mut source_cache: HashMap<String, Arc<String>> = HashMap::new();
2644        source_cache.insert(
2645            "/virt/caller.rs2".to_string(),
2646            Arc::new("[oplocu,target] @consume_useitem;\n".to_string()),
2647        );
2648        source_cache.insert(
2649            "/virt/consume.rs2".to_string(),
2650            Arc::new(
2651                "[label,consume_useitem]\n\
2652                 last_useitem;\n\
2653                 p_delay(0);\n"
2654                    .to_string(),
2655            ),
2656        );
2657
2658        let scripts = vec![callee, caller];
2659        let mut checker = PointerChecker::new(&scripts, &registry);
2660        checker.set_source_cache(crate::SourceProvider::Eager(&source_cache));
2661        let diags = checker.run();
2662
2663        // Find the corrupted-last_useitem warning and verify help is
2664        // attached with both call-site and header rewrites.
2665        let warning = diags
2666            .diagnostics()
2667            .iter()
2668            .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2669            .expect("expected a stale-last_useitem warning");
2670
2671        assert_eq!(
2672            warning.help.len(),
2673            1,
2674            "warning should have exactly one Help block, got {}",
2675            warning.help.len()
2676        );
2677        let help = &warning.help[0];
2678        assert!(
2679            help.message.contains("consume_useitem"),
2680            "help message should name the callee, got: {}",
2681            help.message
2682        );
2683        assert!(
2684            help.message.contains("last_useitem"),
2685            "help message should name the pointer, got: {}",
2686            help.message
2687        );
2688
2689        // Two suggestions: (1) call site, (2) label header.
2690        assert_eq!(
2691            help.suggestions.len(),
2692            2,
2693            "help should include both call-site and header suggestions, \
2694             got {}: {:?}",
2695            help.suggestions.len(),
2696            help.suggestions
2697                .iter()
2698                .map(|s| &s.label)
2699                .collect::<Vec<_>>()
2700        );
2701
2702        // Caller rewrite lands on the call file.
2703        let caller_sug = help
2704            .suggestions
2705            .iter()
2706            .find(|s| s.file.to_string_lossy() == "/virt/caller.rs2")
2707            .expect("expected a call-site suggestion on the caller file");
2708        assert!(
2709            caller_sug
2710                .replacement
2711                .contains("@consume_useitem(last_useitem)"),
2712            "call-site replacement must pass last_useitem as an arg, got: {}",
2713            caller_sug.replacement
2714        );
2715
2716        // Header rewrite lands on the callee file.
2717        let header_sug = help
2718            .suggestions
2719            .iter()
2720            .find(|s| s.file.to_string_lossy() == "/virt/consume.rs2")
2721            .expect("expected a header suggestion on the callee file");
2722        assert!(
2723            header_sug.replacement.contains("(obj $last_useitem)"),
2724            "header replacement must add `obj $last_useitem` param, got: {}",
2725            header_sug.replacement
2726        );
2727
2728        assert_eq!(help.applicability, Applicability::MaybeIncorrect);
2729    }
2730
2731    // -----------------------------------------------------------------------
2732    // Test: help falls back to prose-only when source cache is absent
2733    // -----------------------------------------------------------------------
2734    #[test]
2735    fn secondary_warning_falls_back_to_prose_help_without_source() {
2736        let last_useitem_op = 4270;
2737        let p_delay_op = 5001;
2738        let registry =
2739            registry_with_commands(&[("last_useitem", last_useitem_op), ("p_delay", p_delay_op)]);
2740
2741        let callee = make_script(
2742            "consume_useitem",
2743            "label",
2744            100,
2745            vec![
2746                line(1),
2747                cmd(last_useitem_op),
2748                line(2),
2749                push_int(0),
2750                cmd(p_delay_op),
2751                ret(),
2752            ],
2753        );
2754        let caller = make_script(
2755            "use_on_loc",
2756            "oplocu",
2757            200,
2758            vec![
2759                line(1),
2760                Instruction::new(Opcode::JumpWithParams, Operand::Int(100)),
2761            ],
2762        );
2763
2764        let scripts = vec![callee, caller];
2765        let mut checker = PointerChecker::new(&scripts, &registry);
2766        // Deliberately NO set_source_cache call.
2767        let diags = checker.run();
2768
2769        let warning = diags
2770            .diagnostics()
2771            .iter()
2772            .find(|d| d.severity == Severity::Warning && d.message.contains("stale `last_useitem`"))
2773            .expect("warning still fires without source cache");
2774
2775        assert_eq!(warning.help.len(), 1);
2776        let help = &warning.help[0];
2777        assert_eq!(
2778            help.suggestions.len(),
2779            0,
2780            "prose-only help should have no concrete suggestions"
2781        );
2782        assert_eq!(help.applicability, Applicability::Unspecified);
2783    }
2784}