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