Skip to main content

runec/
symbol.rs

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