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