Skip to main content

runec/
symbol.rs

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