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