Skip to main content

runec/
symbol.rs

1use crate::types::{BaseVarType, Type};
2use std::collections::{HashMap, HashSet};
3use std::sync::Arc;
4
5// ── LocalTable ─────────────────────────────────────────────────────────────
6// Matches RuneScriptTS `LocalTable` (RuneScript.ts): a flat ordered list of
7// all variable declarations within a script, used for slot assignment via
8// `getVariableId` (indexOf in type-filtered sublist).
9
10#[derive(Debug, Clone)]
11pub struct LocalEntry {
12    pub name: String,
13    pub var_type: Type,
14    pub is_param: bool,
15    pub is_array: bool,
16}
17
18/// Flat ordered list of all variable declarations within a script.
19///
20/// `entries` is `pub(crate)` rather than `pub` so the storage shape
21/// (currently a `Vec<LocalEntry>`) can change without breaking external
22/// consumers. Read access from inside the crate goes through
23/// `entries()`; mutations go through `push_param` / `push_local`.
24#[derive(Debug, Clone, Default)]
25pub struct LocalTable {
26    pub(crate) all: Vec<LocalEntry>,
27}
28
29impl LocalTable {
30    pub fn new() -> Self {
31        LocalTable { all: Vec::new() }
32    }
33
34    /// Read-only view of the ordered local entries. Use this for iteration.
35    pub fn entries(&self) -> &[LocalEntry] {
36        &self.all
37    }
38
39    /// Release spare capacity once the table is final (post-codegen).
40    pub fn shrink_to_fit(&mut self) {
41        self.all.shrink_to_fit();
42    }
43
44    pub fn push_param(&mut self, name: String, param_type: Type) -> i32 {
45        let id = self.get_variable_id_for_next(param_type, false);
46        self.all.push(LocalEntry {
47            name,
48            var_type: param_type,
49            is_param: true,
50            is_array: false,
51        });
52        id
53    }
54
55    pub fn push_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
56        let id = self.get_variable_id_for_next(var_type, is_array);
57        self.all.push(LocalEntry {
58            name,
59            var_type,
60            is_param: false,
61            is_array,
62        });
63        id
64    }
65
66    /// Matches TS `getVariableId`: indexOf in filtered list.
67    fn get_variable_id_for_next(&self, var_type: Type, is_array: bool) -> i32 {
68        if is_array {
69            self.all.iter().filter(|e| e.is_array).count() as i32
70        } else {
71            self.all
72                .iter()
73                .filter(|e| {
74                    e.var_type.base_type() == var_type.base_type() && (!e.is_array || e.is_param)
75                })
76                .count() as i32
77        }
78    }
79
80    /// Matches TS `getVariableId` for an existing entry by index.
81    pub fn get_variable_id(&self, index: usize) -> i32 {
82        let entry = &self.all[index];
83        if entry.is_array {
84            self.all[..index].iter().filter(|e| e.is_array).count() as i32
85        } else {
86            self.all[..index]
87                .iter()
88                .filter(|e| {
89                    e.var_type.base_type() == entry.var_type.base_type()
90                        && (!e.is_array || e.is_param)
91                })
92                .count() as i32
93        }
94    }
95
96    /// Matches TS `getLocalCount`.
97    pub fn get_local_count(&self, base: BaseVarType) -> u16 {
98        self.all
99            .iter()
100            .filter(|e| e.var_type.base_type() == base && (!e.is_array || e.is_param))
101            .count() as u16
102    }
103
104    /// Matches TS `getParameterCount`.
105    pub fn get_param_count(&self, base: BaseVarType) -> u16 {
106        self.all
107            .iter()
108            .filter(|e| e.is_param && e.var_type.base_type() == base)
109            .count() as u16
110    }
111}
112
113// ── SymbolKind ─────────────────────────────────────────────────────────────
114
115/// The kind of symbol stored in the symbol table.
116#[derive(Debug, Clone)]
117pub enum SymbolKind {
118    /// A local variable within a script.
119    LocalVar {
120        var_type: Type,
121        /// The local variable slot index.
122        slot: i32,
123        is_array: bool,
124    },
125    /// A script parameter (like a local var but set from call args).
126    ScriptParam { param_type: Type, slot: i32 },
127    /// A compiled script (or script reference).
128    Script {
129        id: i32,
130        trigger: String,
131        param_types: Vec<Type>,
132        return_types: Vec<Type>,
133    },
134    /// A game variable (varp, varn, vars, varbit).
135    GameVar {
136        var_type: Type,
137        var_id: i32,
138        /// Which game var type: "varp", "varn", "vars", "varbit"
139        category: String,
140    },
141    /// A constant value.
142    Constant {
143        const_type: Type,
144        int_value: Option<i32>,
145        string_value: Option<String>,
146    },
147    /// An engine command.
148    Command {
149        opcode: i32,
150        param_types: Vec<Type>,
151        return_types: Vec<Type>,
152    },
153}
154
155impl SymbolKind {
156    pub fn kind_name(&self) -> &'static str {
157        match self {
158            SymbolKind::LocalVar { .. } => "LocalVar",
159            SymbolKind::ScriptParam { .. } => "ScriptParam",
160            SymbolKind::Script { .. } => "Script",
161            SymbolKind::GameVar { .. } => "GameVar",
162            SymbolKind::Constant { .. } => "Constant",
163            SymbolKind::Command { .. } => "Command",
164        }
165    }
166}
167
168/// A single symbol entry in the table.
169#[derive(Debug, Clone)]
170pub struct Symbol {
171    pub name: String,
172    pub kind: SymbolKind,
173}
174
175/// A resolved entity id (from loc.pack/npc.pack/stat.pack/etc.) and its type.
176///
177/// Entity IDs hugely outnumber every other symbol (~22k for a full corpus), so
178/// they get this 8-byte `Copy` record instead of a 104-byte `Symbol` — entity
179/// lookups only ever need the type and the id.
180#[derive(Debug, Clone, Copy)]
181pub struct EntityRef {
182    pub const_type: Type,
183    pub id: i32,
184}
185
186/// All ids registered under one entity name. Replaces the former
187/// `entity_ids: HashMap<String, Symbol>` + `entity_ids_typed:
188/// HashMap<String, HashMap<Type, i32>>` pair (same data, ~6 MB smaller on a full
189/// corpus: no 104-byte `Symbol`s and no ~22k nested HashMaps).
190#[derive(Debug, Clone, Default)]
191pub(crate) struct EntityEntry {
192    /// Priority winner for untyped lookup (last `register_entity_id` wins);
193    /// `None` for typed-only names (registered via `register_entity_id_typed_only`).
194    pub(crate) primary: Option<EntityRef>,
195    /// Every `(type, id)` variant under this name, for type-aware lookup.
196    /// Tiny (usually one entry); includes the primary's `(type, id)`.
197    pub(crate) variants: Vec<(Type, i32)>,
198}
199
200impl EntityEntry {
201    /// Insert or replace the id for `entity_type` (last write wins per type).
202    fn set_variant(&mut self, entity_type: Type, id: i32) {
203        if let Some(slot) = self.variants.iter_mut().find(|(t, _)| *t == entity_type) {
204            slot.1 = id;
205        } else {
206            self.variants.push((entity_type, id));
207        }
208    }
209}
210
211/// A hierarchical symbol table supporting scoped lookup.
212#[derive(Debug, Clone)]
213pub struct SymbolTable {
214    /// Symbols in this scope.
215    symbols: HashMap<String, Symbol>,
216    /// Parent scope for hierarchical lookup.
217    parent: Option<Box<SymbolTable>>,
218    /// Counters for allocating local variable slots.
219    next_int_local: i32,
220    next_string_local: i32,
221    next_long_local: i32,
222    /// Total number of local variable declarations (including redeclarations of same name).
223    /// The Java compiler counts each def_X statement, even if the slot is reused.
224    total_int_decls: i32,
225    total_string_decls: i32,
226    total_long_decls: i32,
227}
228
229impl Default for SymbolTable {
230    fn default() -> Self {
231        Self::new()
232    }
233}
234
235impl SymbolTable {
236    pub fn new() -> Self {
237        SymbolTable {
238            symbols: HashMap::new(),
239            parent: None,
240            next_int_local: 0,
241            next_string_local: 0,
242            next_long_local: 0,
243            total_int_decls: 0,
244            total_string_decls: 0,
245            total_long_decls: 0,
246        }
247    }
248
249    /// Create a child scope that inherits from this table.
250    pub fn child(parent: SymbolTable) -> Self {
251        let int_local = parent.next_int_local;
252        let string_local = parent.next_string_local;
253        let long_local = parent.next_long_local;
254        let int_decls = parent.total_int_decls;
255        let string_decls = parent.total_string_decls;
256        let long_decls = parent.total_long_decls;
257        SymbolTable {
258            symbols: HashMap::new(),
259            parent: Some(Box::new(parent)),
260            next_int_local: int_local,
261            next_string_local: string_local,
262            next_long_local: long_local,
263            total_int_decls: int_decls,
264            total_string_decls: string_decls,
265            total_long_decls: long_decls,
266        }
267    }
268
269    /// Create a child scope without consuming the parent (cloning).
270    pub fn new_child(&self) -> Self {
271        SymbolTable {
272            symbols: HashMap::new(),
273            parent: Some(Box::new(self.clone())),
274            next_int_local: self.next_int_local,
275            next_string_local: self.next_string_local,
276            next_long_local: self.next_long_local,
277            total_int_decls: self.total_int_decls,
278            total_string_decls: self.total_string_decls,
279            total_long_decls: self.total_long_decls,
280        }
281    }
282
283    /// Define a symbol in this scope.
284    pub fn define(&mut self, name: String, kind: SymbolKind) {
285        self.symbols.insert(name.clone(), Symbol { name, kind });
286    }
287
288    /// Define a local variable and auto-assign a slot.
289    /// `is_array` should be true for array declarations — arrays are excluded from
290    /// the local count in the trailer (matching the reference compiler).
291    pub fn define_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
292        // Count the declaration (Java compiler counts each def_X), but NOT arrays.
293        if !is_array {
294            match var_type.base_type() {
295                crate::types::BaseVarType::Integer => self.total_int_decls += 1,
296                crate::types::BaseVarType::String => self.total_string_decls += 1,
297                crate::types::BaseVarType::Long => self.total_long_decls += 1,
298            }
299        }
300        // Always advance the slot counter for each declaration, but if the
301        // name already exists in this scope, reuse its slot (the new slot
302        // becomes a phantom counted in totals but not referenced).
303        // This matches the Neptune compiler behavior where redeclaration
304        // within the SAME scope reuses the existing slot.
305        let new_slot = self.allocate_slot(&var_type);
306        let slot = if let Some(existing) = self.symbols.get(&name) {
307            match &existing.kind {
308                SymbolKind::LocalVar { slot, .. } => *slot,
309                _ => new_slot,
310            }
311        } else {
312            new_slot
313        };
314        self.define(
315            name,
316            SymbolKind::LocalVar {
317                var_type,
318                slot,
319                is_array,
320            },
321        );
322        slot
323    }
324
325    /// Define a script parameter and auto-assign a slot.
326    pub fn define_param(&mut self, name: String, param_type: Type) -> i32 {
327        match param_type.base_type() {
328            crate::types::BaseVarType::Integer => self.total_int_decls += 1,
329            crate::types::BaseVarType::String => self.total_string_decls += 1,
330            crate::types::BaseVarType::Long => self.total_long_decls += 1,
331        }
332        let slot = self.allocate_slot(&param_type);
333        self.define(name, SymbolKind::ScriptParam { param_type, slot });
334        slot
335    }
336
337    /// Allocate a slot for a given type.
338    fn allocate_slot(&mut self, var_type: &Type) -> i32 {
339        match var_type.base_type() {
340            crate::types::BaseVarType::Integer => {
341                let slot = self.next_int_local;
342                self.next_int_local += 1;
343                slot
344            }
345            crate::types::BaseVarType::String => {
346                let slot = self.next_string_local;
347                self.next_string_local += 1;
348                slot
349            }
350            crate::types::BaseVarType::Long => {
351                let slot = self.next_long_local;
352                self.next_long_local += 1;
353                slot
354            }
355        }
356    }
357
358    /// Look up a symbol by name, searching up through parent scopes.
359    pub fn lookup(&self, name: &str) -> Option<&Symbol> {
360        if let Some(sym) = self.symbols.get(name) {
361            return Some(sym);
362        }
363        if let Some(parent) = &self.parent {
364            return parent.lookup(name);
365        }
366        None
367    }
368
369    /// Look up a symbol only in this scope (not parents).
370    pub fn lookup_local(&self, name: &str) -> Option<&Symbol> {
371        self.symbols.get(name)
372    }
373
374    /// Check if a symbol exists in this scope or parent scopes.
375    pub fn contains(&self, name: &str) -> bool {
376        self.lookup(name).is_some()
377    }
378
379    /// Save the current slot counters. Used before entering a block scope.
380    pub fn save_slots(&self) -> (i32, i32, i32) {
381        (
382            self.next_int_local,
383            self.next_string_local,
384            self.next_long_local,
385        )
386    }
387
388    /// Restore slot counters to a saved state, but only if higher counters haven't
389    /// been set by a sibling scope. This is used between sibling blocks (if/else)
390    /// so each branch starts from the same slot baseline.
391    pub fn restore_slots(&mut self, saved: (i32, i32, i32)) {
392        self.next_int_local = saved.0;
393        self.next_string_local = saved.1;
394        self.next_long_local = saved.2;
395    }
396
397    /// Advance slot counters to be at least as high as the given values.
398    /// Used after a block scope to ensure the next sibling doesn't reuse slots.
399    pub fn merge_slots(&mut self, other: (i32, i32, i32)) {
400        self.next_int_local = self.next_int_local.max(other.0);
401        self.next_string_local = self.next_string_local.max(other.1);
402        self.next_long_local = self.next_long_local.max(other.2);
403    }
404
405    /// Merge total declaration counts from a child scope.
406    pub fn merge_decls(&mut self, child: &SymbolTable) {
407        self.total_int_decls = child.total_int_decls;
408        self.total_string_decls = child.total_string_decls;
409        self.total_long_decls = child.total_long_decls;
410    }
411
412    /// Get the total int local count (includes redeclarations, matching Java compiler).
413    pub fn int_local_count(&self) -> u16 {
414        self.total_int_decls as u16
415    }
416
417    /// Get the total string local count.
418    pub fn string_local_count(&self) -> u16 {
419        self.total_string_decls as u16
420    }
421
422    /// Get the total long local count.
423    pub fn long_local_count(&self) -> u16 {
424        self.total_long_decls as u16
425    }
426
427    /// Reset local variable counters (for starting a new script).
428    pub fn reset_locals(&mut self) {
429        self.next_int_local = 0;
430        self.next_string_local = 0;
431        self.next_long_local = 0;
432    }
433
434    /// Iterate over all symbols in this scope.
435    pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
436        self.symbols.iter()
437    }
438}
439
440/// The root symbol table manager that holds all global symbols.
441///
442/// Field visibility is `pub(crate)` rather than `pub` so external consumers
443/// only touch the registry through accessor methods (`lookup_command`,
444/// `lookup_entity_id`, `register_script`, etc.). This lets internal storage
445/// change — e.g. swapping `HashMap<String, _>` for an interned-string map —
446/// without breaking the lib's public surface.
447#[derive(Debug, Clone)]
448pub struct SymbolRegistry {
449    /// All registered scripts by name (last registration wins). The `Symbol` is
450    /// shared (`Arc`) with `scripts_by_trigger` so each script's symbol — and its
451    /// param/return type vectors — is stored once, not once per map.
452    pub(crate) scripts: HashMap<String, Arc<Symbol>>,
453    /// All registered commands by name.
454    pub(crate) commands: HashMap<String, Symbol>,
455    /// All registered game variables by name.
456    pub(crate) game_vars: HashMap<String, Symbol>,
457    /// All registered constants by name (from .constant files).
458    pub(crate) constants: HashMap<String, Symbol>,
459    /// Entity IDs from pack files (loc.pack, npc.pack, stat.pack, etc.), keyed by
460    /// name. Each entry carries a priority winner for plain-identifier lookup
461    /// plus all per-type variants for type-aware lookup (so `smokepuff` resolves
462    /// to synth=164 in sound_synth() but spotanim=86 in spotanim_map(), matching
463    /// the Java compiler). Constants override only `^name` refs.
464    pub(crate) entity_ids: HashMap<String, EntityEntry>,
465    /// Parameter types for engine commands, parsed from engine.rs2.
466    /// Maps command name → ordered list of parameter types.
467    pub(crate) command_param_types: HashMap<String, Vec<Type>>,
468    /// Type-char values for RS2 type names (int, string, coord, stat, etc.).
469    /// Checked last in identifier resolution so commands take priority over type names.
470    pub(crate) type_chars: HashMap<String, i32>,
471    /// Script name to ID mapping (by name, last registration wins).
472    pub(crate) script_ids: HashMap<String, i32>,
473    /// Proc script IDs: name → ID for trigger="proc" scripts.
474    pub(crate) proc_script_ids: HashMap<String, i32>,
475    /// Label script IDs: name → ID for trigger="label" scripts.
476    pub(crate) label_script_ids: HashMap<String, i32>,
477    /// Trigger-specific script IDs: "trigger:name" → ID.
478    /// Used so queue(foo) resolves to the [queue,foo] script, not [proc,foo].
479    pub(crate) trigger_script_ids: HashMap<String, i32>,
480    /// Full script symbols keyed by "trigger:name".
481    /// Unlike `scripts` (name-only key, last-write-wins), this preserves
482    /// all trigger variants so `[proc,fib]` isn't overwritten by `[debugproc,fib]`.
483    /// Shares each `Symbol` (`Arc`) with `scripts`.
484    pub(crate) scripts_by_trigger: HashMap<String, Arc<Symbol>>,
485    /// Pre-assigned script IDs loaded from script.pack: "trigger:name" → ID.
486    /// When present, overrides sequential assignment so IDs match the Java compiler.
487    pub(crate) preloaded_script_ids: HashMap<String, i32>,
488    /// DB column types: "table:column" → first field Type (from dbcolumn.pack).
489    /// Used by db_find to determine the implicit BaseVarType argument.
490    pub(crate) dbcolumn_types: HashMap<String, Type>,
491    /// Component lookup: "interface_name:component_name" → packed (iface_id << 16 | comp_id).
492    pub(crate) components: HashMap<String, i32>,
493    /// Interface name → ID mapping (for component resolution).
494    pub(crate) interface_ids: HashMap<String, i32>,
495    /// Scripts defined below `#testscript` — keyed by "trigger:name".
496    pub(crate) test_scripts: HashSet<String>,
497    /// Next available script ID.
498    next_script_id: i32,
499}
500
501impl Default for SymbolRegistry {
502    fn default() -> Self {
503        Self::new()
504    }
505}
506
507impl SymbolRegistry {
508    pub fn new() -> Self {
509        SymbolRegistry {
510            scripts: HashMap::new(),
511            commands: HashMap::new(),
512            game_vars: HashMap::new(),
513            constants: HashMap::new(),
514            entity_ids: HashMap::new(),
515            command_param_types: HashMap::new(),
516            type_chars: HashMap::new(),
517            script_ids: HashMap::new(),
518            proc_script_ids: HashMap::new(),
519            label_script_ids: HashMap::new(),
520            trigger_script_ids: HashMap::new(),
521            scripts_by_trigger: HashMap::new(),
522            preloaded_script_ids: HashMap::new(),
523            dbcolumn_types: HashMap::new(),
524            components: HashMap::new(),
525            interface_ids: HashMap::new(),
526            test_scripts: HashSet::new(),
527            next_script_id: 0,
528        }
529    }
530
531    /// Register a script by name with its type information.
532    pub fn register_script(
533        &mut self,
534        name: String,
535        trigger: String,
536        param_types: Vec<Type>,
537        return_types: Vec<Type>,
538    ) -> i32 {
539        let key = format!("{}:{}", trigger, name);
540        let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
541            preloaded
542        } else {
543            let id = self.next_script_id;
544            self.next_script_id += 1;
545            id
546        };
547
548        // proc/label ids are keyed by bare name (not `trigger:name`), so they
549        // can't be derived from the trigger-keyed map without a per-lookup
550        // concat — keep these small dedicated maps.
551        if trigger == "proc" {
552            self.proc_script_ids.insert(name.clone(), id);
553        } else if trigger == "label" {
554            self.label_script_ids.insert(name.clone(), id);
555        }
556        // The id lives in the `Symbol`; `script_id` / `script_id_for_trigger`
557        // read it from `scripts` / `scripts_by_trigger` (the `*_script_ids` maps
558        // are now only the clientscript-pack fallback), so we don't duplicate it.
559        let symbol = Arc::new(Symbol {
560            name: name.clone(),
561            kind: SymbolKind::Script {
562                id,
563                trigger,
564                param_types,
565                return_types,
566            },
567        });
568        self.scripts_by_trigger.insert(key, Arc::clone(&symbol));
569        self.scripts.insert(name, symbol);
570
571        id
572    }
573
574    /// Register a command (engine function).
575    pub fn register_command(
576        &mut self,
577        name: String,
578        opcode: i32,
579        param_types: Vec<Type>,
580        return_types: Vec<Type>,
581    ) {
582        self.command_param_types
583            .insert(name.clone(), param_types.clone());
584        self.commands.insert(
585            name.clone(),
586            Symbol {
587                name,
588                kind: SymbolKind::Command {
589                    opcode,
590                    param_types,
591                    return_types,
592                },
593            },
594        );
595    }
596
597    /// Register a game variable.
598    pub fn register_game_var(
599        &mut self,
600        name: String,
601        var_type: Type,
602        var_id: i32,
603        category: String,
604    ) {
605        self.game_vars.insert(
606            name.clone(),
607            Symbol {
608                name,
609                kind: SymbolKind::GameVar {
610                    var_type,
611                    var_id,
612                    category,
613                },
614            },
615        );
616    }
617
618    /// Register a constant value (from .constant files).
619    pub fn register_constant(
620        &mut self,
621        name: String,
622        const_type: Type,
623        int_value: Option<i32>,
624        string_value: Option<String>,
625    ) {
626        self.constants.insert(
627            name.clone(),
628            Symbol {
629                name,
630                kind: SymbolKind::Constant {
631                    const_type,
632                    int_value,
633                    string_value,
634                },
635            },
636        );
637    }
638
639    /// Register an entity ID (from stat.pack, npc.pack, loc.pack, etc.).
640    /// These are stored separately from .constant files values so plain
641    /// identifier resolution uses entity IDs, while ^name uses .constant files.
642    pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
643        let entry = self.entity_ids.entry(name).or_default();
644        // Priority winner for untyped lookup (last write wins).
645        entry.primary = Some(EntityRef {
646            const_type: entity_type,
647            id,
648        });
649        entry.set_variant(entity_type, id);
650    }
651
652    /// Register an entity ID that should only be resolvable via a typed
653    /// (hint-driven) lookup. Skips the flat `entity_ids` map so the name
654    /// does not shadow trigger names or other higher-priority resolutions
655    /// when used in untyped expression contexts.
656    ///
657    /// Used for NpcMode names like `oploc1`/`apnpc2` that share their
658    /// spelling with `ServerTriggerType` byte names — `npc_setmode(oploc1)`
659    /// still works (typed lookup hits `Type::NpcMode`), but bare `oploc1`
660    /// in e.g. `test_op(oploc1, …)` falls through to `trigger_table::byte`.
661    pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
662        self.entity_ids
663            .entry(name)
664            .or_default()
665            .set_variant(entity_type, id);
666    }
667
668    /// Look up an entity ID for a specific expected type. Returns `None` if the
669    /// name is not registered for that type.
670    /// Normalizes the name (lowercase + spaces→underscores) matching TS normalizeName for Basic symbols.
671    pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
672        let normalized = name.to_lowercase().replace(' ', "_");
673        self.entity_ids
674            .get(&normalized)
675            .and_then(|e| e.variants.iter().find(|(t, _)| *t == expected))
676            .map(|(_, id)| *id)
677    }
678
679    /// Look up a script by name (last registration wins if multiple triggers share the name).
680    pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
681        self.scripts.get(name).map(|s| s.as_ref())
682    }
683
684    /// Look up a script by trigger and name (avoids name collisions between triggers).
685    pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
686        self.scripts_by_trigger
687            .get(&format!("{}:{}", trigger, name))
688            .map(|s| s.as_ref())
689    }
690
691    /// Look up a command by name.
692    pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
693        self.commands.get(name)
694    }
695
696    /// Look up a game variable by name.
697    pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
698        self.game_vars.get(name)
699    }
700
701    /// Look up a constant by name (from .constant files).
702    pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
703        self.constants.get(name)
704    }
705
706    /// Look up an entity ID by name (from stat.pack, npc.pack, etc.).
707    /// Normalizes the name matching TS normalizeName for Basic symbols.
708    pub fn lookup_entity_id(&self, name: &str) -> Option<EntityRef> {
709        let normalized = name.to_lowercase().replace(' ', "_");
710        self.entity_ids.get(&normalized).and_then(|e| e.primary)
711    }
712
713    /// Free registration-only scratch once every script is registered. The
714    /// pre-assigned IDs from `script.pack` are consulted only while assigning
715    /// ids in `register_script`; codegen and pointer-checking never read them.
716    /// Replacing (not `clear`-ing) the map returns its buckets to the allocator.
717    pub(crate) fn drop_registration_scratch(&mut self) {
718        self.preloaded_script_ids = HashMap::new();
719    }
720
721    /// Get the script ID for a given name. Reads the id from the registered
722    /// script's `Symbol`; falls back to `script_ids` (clientscript-pack entries,
723    /// which are never registered as RS2). Registered scripts take precedence,
724    /// matching the old insert order (clientscripts loaded, then `register_script`
725    /// overwrote by name).
726    pub fn script_id(&self, name: &str) -> Option<i32> {
727        if let Some(s) = self.scripts.get(name)
728            && let SymbolKind::Script { id, .. } = &s.kind
729        {
730            return Some(*id);
731        }
732        self.script_ids.get(name).copied()
733    }
734
735    /// Get the proc script ID for a given name.
736    pub fn proc_script_id(&self, name: &str) -> Option<i32> {
737        self.proc_script_ids.get(name).copied()
738    }
739
740    /// Get the label script ID for a given name.
741    pub fn label_script_id(&self, name: &str) -> Option<i32> {
742        self.label_script_ids.get(name).copied()
743    }
744
745    pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
746        let key = format!("{}:{}", trigger, name);
747        if let Some(s) = self.scripts_by_trigger.get(&key)
748            && let SymbolKind::Script { id, .. } = &s.kind
749        {
750            return Some(*id);
751        }
752        // Fallback: clientscript-pack ids (keyed `clientscript:name`), never
753        // registered as RS2 scripts.
754        self.trigger_script_ids.get(&key).copied()
755    }
756
757    pub fn command_opcode(&self, name: &str) -> Option<i32> {
758        self.commands.get(name).and_then(|sym| {
759            if let SymbolKind::Command { opcode, .. } = &sym.kind {
760                Some(*opcode)
761            } else {
762                None
763            }
764        })
765    }
766
767    pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
768        self.test_scripts.insert(format!("{}:{}", trigger, name));
769    }
770
771    pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
772        self.test_scripts.contains(&format!("{}:{}", trigger, name))
773    }
774
775    /// Look up a component by interface_name:component_name.
776    /// Returns the packed (iface_id << 16 | comp_id) value.
777    /// Normalizes the component name so 647-style `com2` and 225-style `com_2`
778    /// both resolve against whichever form the pack was written in.
779    pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
780        let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
781        self.components.get(&key).copied()
782    }
783}
784
785/// Strip underscores at alpha→digit boundaries to unify 647-style `com2`
786/// with 225-style `com_2`. Both normalize to `com2`.
787pub(crate) fn normalize_comp_name(name: &str) -> String {
788    let bytes = name.as_bytes();
789    let mut out = Vec::with_capacity(bytes.len());
790    let mut i = 0;
791    while i < bytes.len() {
792        if bytes[i] == b'_'
793            && i > 0
794            && bytes[i - 1].is_ascii_alphabetic()
795            && i + 1 < bytes.len()
796            && bytes[i + 1].is_ascii_digit()
797        {
798            i += 1;
799            continue;
800        }
801        out.push(bytes[i]);
802        i += 1;
803    }
804    unsafe { String::from_utf8_unchecked(out) }
805}
806
807#[cfg(test)]
808mod tests {
809    use super::*;
810
811    // ── normalize_comp_name ────────────────────────────────────────────
812
813    #[test]
814    fn normalize_strips_underscore_before_digits() {
815        assert_eq!(normalize_comp_name("com_2"), "com2");
816        assert_eq!(normalize_comp_name("com_10"), "com10");
817        assert_eq!(normalize_comp_name("com_0"), "com0");
818    }
819
820    #[test]
821    fn normalize_preserves_already_compact_names() {
822        assert_eq!(normalize_comp_name("com2"), "com2");
823        assert_eq!(normalize_comp_name("com10"), "com10");
824        assert_eq!(normalize_comp_name("com0"), "com0");
825    }
826
827    #[test]
828    fn normalize_preserves_non_digit_underscores() {
829        assert_eq!(normalize_comp_name("close_button"), "close_button");
830        assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
831        assert_eq!(normalize_comp_name("title"), "title");
832    }
833
834    #[test]
835    fn normalize_only_strips_alpha_digit_boundary() {
836        // underscore between two digits — not stripped
837        assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
838        // underscore between digit and alpha — not stripped
839        assert_eq!(normalize_comp_name("3_panel"), "3_panel");
840    }
841
842    // ── lookup_component (647 pack style) ──────────────────────────────
843
844    fn registry_647_style() -> SymbolRegistry {
845        let mut r = SymbolRegistry::new();
846        r.interface_ids.insert("multi2".into(), 228);
847        // 647 pack registers `com0`..`com9` (no underscore)
848        for i in 0..10 {
849            let key = format!("multi2:com{}", i);
850            r.components.insert(key, (228 << 16) | i);
851        }
852        r
853    }
854
855    #[test]
856    fn lookup_647_pack_with_647_reference() {
857        let r = registry_647_style();
858        // Script uses the same 647 naming: `multi2:com2`
859        assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
860        assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
861    }
862
863    #[test]
864    fn lookup_647_pack_with_225_reference() {
865        let r = registry_647_style();
866        // Script uses 225 naming: `multi2:com_2` — must still resolve
867        assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
868        assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
869        assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
870    }
871
872    // ── lookup_component (225 pack style) ──────────────────────────────
873
874    fn registry_225_style() -> SymbolRegistry {
875        let mut r = SymbolRegistry::new();
876        r.interface_ids.insert("multi2".into(), 228);
877        // 225 pack registers `multi2:com_0`..`com_9` — but through
878        // symloader normalization these become `com0`..`com9`.
879        for i in 0..10 {
880            let key = format!("multi2:com{}", i);
881            r.components.insert(key, 2459 + i);
882        }
883        r
884    }
885
886    #[test]
887    fn lookup_225_pack_with_225_reference() {
888        let r = registry_225_style();
889        assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
890        assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
891    }
892
893    #[test]
894    fn lookup_225_pack_with_647_reference() {
895        let r = registry_225_style();
896        assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
897        assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
898    }
899
900    // ── lookup_component (miss) ────────────────────────────────────────
901
902    #[test]
903    fn lookup_returns_none_for_unknown_component() {
904        let r = registry_647_style();
905        assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
906        assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
907    }
908}