Skip to main content

runec/
pointer_checker.rs

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