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, varpbit).
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    /// Leading arguments that name types (`enum(int, obj, ...)`), by command.
466    pub(crate) type_arguments: HashMap<String, usize>,
467    pub(crate) param_types: HashMap<i32, Type>,
468    pub(crate) stack_commands: HashSet<String>,
469    component_first_commands: HashSet<String>,
470    command_pointer_overrides: HashMap<String, PointerHolder>,
471    switch_domains: HashMap<Type, BTreeMap<i32, String>>,
472    pub(crate) stack_scripts: HashSet<String>,
473    pub(crate) hook_commands: HashMap<String, bool>,
474    /// All registered scripts by name (last registration wins). The `Symbol` is
475    /// shared (`Arc`) with `scripts_by_trigger` so each script's symbol — and its
476    /// param/return type vectors — is stored once, not once per map.
477    pub(crate) scripts: HashMap<String, Arc<Symbol>>,
478    /// All registered commands by name.
479    pub(crate) commands: HashMap<String, Symbol>,
480    /// All registered game variables by name.
481    pub(crate) game_vars: HashMap<String, Symbol>,
482    /// All registered constants by name (from .constant files).
483    pub(crate) constants: HashMap<String, Symbol>,
484    /// Entity IDs from pack files (loc.pack, npc.pack, stat.pack, etc.), keyed by
485    /// name. Each entry carries a priority winner for plain-identifier lookup
486    /// plus all per-type variants for type-aware lookup (so `smokepuff` resolves
487    /// to synth=164 in sound_synth() but spotanim=86 in spotanim_map(), matching
488    /// the Java compiler). Constants override only `^name` refs.
489    pub(crate) entity_ids: HashMap<String, EntityEntry>,
490    /// Parameter types for engine commands, parsed from engine.rs2.
491    /// Maps command name → ordered list of parameter types.
492    pub(crate) command_param_types: HashMap<String, Vec<Type>>,
493    /// Type-char values for RS2 type names (int, string, coord, stat, etc.).
494    /// Checked last in identifier resolution so commands take priority over type names.
495    pub(crate) type_chars: HashMap<String, i32>,
496    /// Script name to ID mapping (by name, last registration wins).
497    pub(crate) script_ids: HashMap<String, i32>,
498    /// Proc script IDs: name → ID for trigger="proc" scripts.
499    pub(crate) proc_script_ids: HashMap<String, i32>,
500    /// Label script IDs: name → ID for trigger="label" scripts.
501    pub(crate) label_script_ids: HashMap<String, i32>,
502    /// Trigger-specific script IDs: "trigger:name" → ID.
503    /// Used so queue(foo) resolves to the [queue,foo] script, not [proc,foo].
504    pub(crate) trigger_script_ids: HashMap<String, i32>,
505    /// Full script symbols keyed by "trigger:name".
506    /// Unlike `scripts` (name-only key, last-write-wins), this preserves
507    /// all trigger variants so `[proc,fib]` isn't overwritten by `[debugproc,fib]`.
508    /// Shares each `Symbol` (`Arc`) with `scripts`.
509    pub(crate) scripts_by_trigger: HashMap<String, Arc<Symbol>>,
510    /// Script IDs supplied by the caller: "trigger:name" → ID.
511    pub(crate) preloaded_script_ids: HashMap<String, i32>,
512    /// DB column field types: "table:column" → each field's Type. db_find takes
513    /// the first field's BaseVarType; db_getfield returns them all.
514    pub(crate) dbcolumn_types: HashMap<String, Vec<Type>>,
515    /// Component lookup: "interface_name:component_name" → packed (iface_id << 16 | comp_id).
516    pub(crate) components: HashMap<String, i32>,
517    /// Interface name → ID mapping (for component resolution).
518    pub(crate) interface_ids: HashMap<String, i32>,
519    /// Scripts defined below `#testscript` — keyed by "trigger:name".
520    pub(crate) test_scripts: HashSet<String>,
521    /// Next available script ID.
522    pub(crate) client_script_params: HashMap<String, Vec<Type>>,
523    pub(crate) next_script_id: i32,
524}
525
526impl Default for SymbolRegistry {
527    fn default() -> Self {
528        Self::new()
529    }
530}
531
532#[derive(Debug, Clone, Copy)]
533pub enum ReturnType {
534    TypeArgument(usize),
535    ParamArgument(usize),
536}
537
538impl SymbolRegistry {
539    pub fn set_engine_profile(&mut self, profile: crate::environment::EngineProfile) {
540        self.command_pointer_overrides.clear();
541        self.profile = Some(Arc::new(profile));
542    }
543
544    pub fn trigger(&self, name: &str) -> Option<crate::environment::Trigger> {
545        if let Some(profile) = &self.profile {
546            return profile.triggers.get(name).cloned();
547        }
548        crate::trigger_table::is_valid_trigger(name).then(|| crate::environment::Trigger {
549            byte: crate::trigger_table::byte(name),
550            subject_type: crate::trigger_table::subject_type(name),
551            validates_subject: crate::trigger_table::validates_subject(name),
552            is_button: crate::trigger_table::is_button(name),
553            allows_returns: crate::trigger_table::allows_returns(name),
554        })
555    }
556
557    pub fn set_visibility(&mut self, mut visibility: crate::sources::Visibility) {
558        visibility.index_registry(self);
559        self.visibility = Arc::new(visibility);
560    }
561
562    /// Supply stable IDs without reading or updating a pack file.
563    pub fn set_script_id(&mut self, trigger: &str, name: &str, id: i32) {
564        self.preloaded_script_ids
565            .insert(format!("{trigger}:{name}"), id);
566        self.next_script_id = self.next_script_id.max(id + 1);
567    }
568
569    /// Stack argument order is shared by client scripts and their global procs.
570    pub fn set_stack_script(&mut self, trigger: &str, name: &str) {
571        self.stack_scripts.insert(format!("{trigger}:{name}"));
572    }
573
574    pub fn component_first_command(&self, name: &str) -> bool {
575        let name = name.trim_start_matches('.');
576        self.stack_commands.contains(name) && self.component_first_commands.contains(name)
577    }
578
579    pub fn set_command_suspends(&mut self, name: &str, suspends: bool) {
580        if let Some(profile) = &mut self.profile {
581            Arc::make_mut(profile)
582                .command_pointers
583                .entry(name.to_owned())
584                .or_default()
585                .may_suspend = suspends;
586        } else {
587            self.command_pointer_overrides
588                .entry(name.to_owned())
589                .or_insert_with(|| {
590                    default_command_pointers()
591                        .get(name)
592                        .cloned()
593                        .unwrap_or_default()
594                })
595                .may_suspend = suspends;
596        }
597    }
598
599    pub fn command_suspends(&self, name: &str) -> bool {
600        self.command_suspends_for(name, true)
601    }
602
603    pub(crate) fn command_suspends_for(&self, name: &str, server: bool) -> bool {
604        let primary = name.trim_start_matches('.');
605        let lookup = |pointers: &HashMap<String, PointerHolder>| {
606            pointers
607                .get(name)
608                .or_else(|| pointers.get(primary))
609                .map(|holder| holder.may_suspend)
610        };
611        if let Some(profile) = &self.profile {
612            lookup(&profile.command_pointers).unwrap_or(false)
613        } else {
614            lookup(&self.command_pointer_overrides)
615                .or_else(|| server.then(|| lookup(default_command_pointers())).flatten())
616                .unwrap_or(false)
617        }
618    }
619
620    /// Explicit closed value domains; ordinary integer and asset IDs stay open.
621    pub fn set_switch_values(&mut self, ty: Type, values: impl IntoIterator<Item = (i32, String)>) {
622        self.switch_domains.insert(ty, values.into_iter().collect());
623    }
624
625    pub fn switch_values(&self, ty: Type) -> Option<&BTreeMap<i32, String>> {
626        self.switch_domains
627            .get(&ty)
628            .filter(|values| !values.is_empty())
629    }
630
631    pub fn set_component_first_command(&mut self, name: &str, component_first: bool) {
632        let name = name.trim_start_matches('.');
633        if component_first {
634            self.component_first_commands.insert(name.to_owned());
635        } else {
636            self.component_first_commands.remove(name);
637        }
638    }
639
640    pub(crate) fn clear_commands(&mut self) {
641        self.commands.clear();
642        self.command_param_types.clear();
643        self.stack_commands.clear();
644        self.component_first_commands.clear();
645        self.command_pointer_overrides.clear();
646        self.hook_commands.clear();
647        self.dynamic_returns.clear();
648        self.type_arguments.clear();
649    }
650
651    pub fn set_command_behavior(
652        &mut self,
653        name: &str,
654        stack: bool,
655        hook: Option<bool>,
656        returns: Option<ReturnType>,
657    ) {
658        if stack {
659            self.stack_commands.insert(name.to_owned());
660        } else {
661            self.stack_commands.remove(name);
662            self.component_first_commands.remove(name);
663        }
664        if let Some(explicit_component) = hook {
665            self.hook_commands
666                .insert(name.to_owned(), explicit_component);
667        } else {
668            self.hook_commands.remove(name);
669        }
670        if let Some(returns) = returns {
671            self.dynamic_returns.insert(name.to_owned(), returns);
672        } else {
673            self.dynamic_returns.remove(name);
674        }
675    }
676
677    pub fn commands(&self) -> impl Iterator<Item = (&str, &Symbol)> {
678        self.commands
679            .iter()
680            .map(|(name, symbol)| (name.as_str(), symbol))
681    }
682
683    pub fn constants(&self) -> impl Iterator<Item = (&str, &Symbol)> {
684        self.constants
685            .iter()
686            .map(|(name, symbol)| (name.as_str(), symbol))
687    }
688
689    pub(crate) fn remove_script(&mut self, trigger: &str, name: &str) {
690        self.scripts_by_trigger.remove(&format!("{trigger}:{name}"));
691        self.scripts.remove(name);
692        self.stack_scripts.remove(&format!("{trigger}:{name}"));
693        self.test_scripts.remove(&format!("{trigger}:{name}"));
694        if trigger == "proc" {
695            self.proc_script_ids.remove(name);
696        }
697        if trigger == "label" {
698            self.label_script_ids.remove(name);
699        }
700    }
701
702    /// Re-index source ownership after an importer has written config files.
703    pub fn load_visibility(&mut self, source_dir: &std::path::Path) {
704        self.visibility = Arc::new(crate::sources::Visibility::load(source_dir, self));
705    }
706
707    pub fn game_variables(&self) -> impl Iterator<Item = (&str, &Symbol)> {
708        self.game_vars
709            .iter()
710            .map(|(name, symbol)| (name.as_str(), symbol))
711    }
712
713    pub fn new() -> Self {
714        SymbolRegistry {
715            profile: None,
716            visibility: Arc::default(),
717            dynamic_returns: HashMap::new(),
718            type_arguments: HashMap::new(),
719            param_types: HashMap::new(),
720            stack_commands: HashSet::new(),
721            component_first_commands: HashSet::new(),
722            command_pointer_overrides: HashMap::new(),
723            switch_domains: HashMap::from([
724                (
725                    Type::Boolean,
726                    [(0, "false".into()), (1, "true".into())].into(),
727                ),
728                (Type::IntBool, [(0, "0".into()), (1, "1".into())].into()),
729            ]),
730            stack_scripts: HashSet::new(),
731            hook_commands: HashMap::new(),
732            scripts: HashMap::new(),
733            commands: HashMap::new(),
734            game_vars: HashMap::new(),
735            constants: HashMap::new(),
736            entity_ids: HashMap::new(),
737            command_param_types: HashMap::new(),
738            type_chars: HashMap::new(),
739            script_ids: HashMap::new(),
740            proc_script_ids: HashMap::new(),
741            label_script_ids: HashMap::new(),
742            trigger_script_ids: HashMap::new(),
743            scripts_by_trigger: HashMap::new(),
744            preloaded_script_ids: HashMap::new(),
745            dbcolumn_types: HashMap::new(),
746            components: HashMap::new(),
747            interface_ids: HashMap::new(),
748            test_scripts: HashSet::new(),
749            client_script_params: HashMap::new(),
750            next_script_id: 0,
751        }
752    }
753
754    pub fn register_clientscript(&mut self, name: String, id: i32, params: Vec<Type>) {
755        self.trigger_script_ids
756            .insert(format!("clientscript:{name}"), id);
757        self.client_script_params.insert(name, params);
758    }
759
760    /// Register a script by name with its type information.
761    pub fn register_script(
762        &mut self,
763        name: String,
764        trigger: String,
765        param_types: Vec<Type>,
766        return_types: Vec<Type>,
767    ) -> i32 {
768        let key = format!("{}:{}", trigger, name);
769        let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
770            preloaded
771        } else {
772            let id = self.next_script_id;
773            self.next_script_id += 1;
774            id
775        };
776
777        // proc/label ids are keyed by bare name (not `trigger:name`), so they
778        // can't be derived from the trigger-keyed map without a per-lookup
779        // concat — keep these small dedicated maps.
780        if trigger == "proc" {
781            self.proc_script_ids.insert(name.clone(), id);
782        } else if trigger == "label" {
783            self.label_script_ids.insert(name.clone(), id);
784        }
785        // The id lives in the `Symbol`; `script_id` / `script_id_for_trigger`
786        // read it from `scripts` / `scripts_by_trigger` (the `*_script_ids` maps
787        // are now only the clientscript-pack fallback), so we don't duplicate it.
788        let symbol = Arc::new(Symbol {
789            name: name.clone(),
790            kind: SymbolKind::Script {
791                id,
792                trigger,
793                param_types,
794                return_types,
795            },
796        });
797        self.scripts_by_trigger.insert(key, Arc::clone(&symbol));
798        self.scripts.insert(name, symbol);
799
800        id
801    }
802
803    /// Register a command (engine function).
804    pub fn register_command(
805        &mut self,
806        name: String,
807        opcode: i32,
808        param_types: Vec<Type>,
809        return_types: Vec<Type>,
810    ) {
811        self.component_first_commands.remove(&name);
812        self.command_pointer_overrides.remove(&name);
813        self.command_param_types
814            .insert(name.clone(), param_types.clone());
815        self.commands.insert(
816            name.clone(),
817            Symbol {
818                name,
819                kind: SymbolKind::Command {
820                    opcode,
821                    param_types,
822                    return_types,
823                },
824            },
825        );
826    }
827
828    pub fn register_param_type(&mut self, id: i32, ty: Type) {
829        self.param_types.insert(id, ty);
830    }
831
832    /// Register a game variable.
833    pub fn register_game_var(
834        &mut self,
835        name: String,
836        var_type: Type,
837        var_id: i32,
838        category: String,
839    ) {
840        self.game_vars.insert(
841            name.clone(),
842            Symbol {
843                name,
844                kind: SymbolKind::GameVar {
845                    var_type,
846                    var_id,
847                    category,
848                },
849            },
850        );
851    }
852
853    /// Register a constant value (from .constant files).
854    pub fn register_constant(
855        &mut self,
856        name: String,
857        const_type: Type,
858        int_value: Option<i32>,
859        string_value: Option<String>,
860    ) {
861        self.constants.insert(
862            name.clone(),
863            Symbol {
864                name,
865                kind: SymbolKind::Constant {
866                    const_type,
867                    int_value,
868                    string_value,
869                },
870            },
871        );
872    }
873
874    /// Register an entity ID (from stat.pack, npc.pack, loc.pack, etc.).
875    /// These are stored separately from .constant files values so plain
876    /// identifier resolution uses entity IDs, while ^name uses .constant files.
877    pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
878        let entry = self.entity_ids.entry(name).or_default();
879        // Priority winner for untyped lookup (last write wins).
880        entry.primary = Some(EntityRef {
881            const_type: entity_type,
882            id,
883        });
884        entry.set_variant(entity_type, id);
885    }
886
887    /// Register an entity ID that should only be resolvable via a typed
888    /// (hint-driven) lookup. Skips the flat `entity_ids` map so the name
889    /// does not shadow trigger names or other higher-priority resolutions
890    /// when used in untyped expression contexts.
891    ///
892    /// Used for NpcMode names like `oploc1`/`apnpc2` that share their
893    /// spelling with `ServerTriggerType` byte names — `npc_setmode(oploc1)`
894    /// still works (typed lookup hits `Type::NpcMode`), but bare `oploc1`
895    /// in e.g. `test_op(oploc1, …)` falls through to `trigger_table::byte`.
896    pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
897        self.entity_ids
898            .entry(name)
899            .or_default()
900            .set_variant(entity_type, id);
901    }
902
903    /// Look up an entity ID for a specific expected type. Returns `None` if the
904    /// name is not registered for that type.
905    /// Normalizes the name (lowercase + spaces→underscores) matching TS normalizeName for Basic symbols.
906    pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
907        let normalized = normalize_entity_name(name);
908        self.entity_ids
909            .get(normalized.as_ref())
910            .and_then(|e| e.variants.iter().find(|(t, _)| *t == expected))
911            .map(|(_, id)| *id)
912    }
913
914    pub fn lookup_reference(&self, name: &str, expected: Type) -> Option<i32> {
915        match expected {
916            Type::Component => name
917                .split_once(':')
918                .and_then(|(iface, com)| self.lookup_component(iface, com))
919                .or_else(|| self.lookup_entity_id_typed(name, expected)),
920            Type::ClientScript => self
921                .script_id_for_trigger("clientscript", name)
922                .or_else(|| self.script_id_for_trigger("proc", name)),
923            Type::Proc => self.proc_script_id(name),
924            // These go by number without a name of their own.
925            Type::Model | Type::Texture | Type::Category => {
926                self.lookup_entity_id_typed(name, expected).or_else(|| {
927                    name.strip_prefix(expected.name())?
928                        .strip_prefix('_')?
929                        .parse::<i32>()
930                        .ok()
931                        .filter(|id| *id >= 0)
932                })
933            }
934            Type::Varp
935            | Type::Varn
936            | Type::Vars
937            | Type::VarpBit
938            | Type::Varc
939            | Type::VarCon
940            | Type::VarConBit
941            | Type::VarClanSetting => self.lookup_game_var(name).and_then(|symbol| {
942                if let SymbolKind::GameVar {
943                    var_id, category, ..
944                } = &symbol.kind
945                    && match expected {
946                        Type::Varc => matches!(category.as_str(), "varc" | "varcstr"),
947                        Type::VarClanSetting => category.starts_with("clansetting_"),
948                        _ => category == expected.name(),
949                    }
950                {
951                    Some(*var_id)
952                } else {
953                    None
954                }
955            }),
956            _ => self.lookup_entity_id_typed(name, expected),
957        }
958    }
959
960    /// Look up a script by name (last registration wins if multiple triggers share the name).
961    pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
962        self.scripts.get(name).map(|s| s.as_ref())
963    }
964
965    /// Look up a script by trigger and name (avoids name collisions between triggers).
966    pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
967        if let Some(symbol) = self.scripts.get(name)
968            && matches!(&symbol.kind, SymbolKind::Script { trigger: found, .. } if found == trigger)
969        {
970            return Some(symbol);
971        }
972        self.scripts_by_trigger
973            .get(&format!("{}:{}", trigger, name))
974            .map(|s| s.as_ref())
975    }
976
977    /// Look up a command by name.
978    pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
979        self.commands.get(name)
980    }
981
982    /// Whether a bare `name` in a `hint` slot is the command rather than an
983    /// entity: entity ids are ints, so a string or long slot takes the command.
984    pub(crate) fn command_fills(&self, name: &str, hint: Option<Type>) -> bool {
985        hint.is_some_and(|h| h.base_type() != BaseVarType::Integer)
986            && self.commands.contains_key(name)
987    }
988
989    /// Look up a game variable by name.
990    pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
991        self.game_vars.get(name)
992    }
993
994    /// Look up a constant by name (from .constant files).
995    pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
996        self.constants.get(name)
997    }
998
999    pub fn integer_constant_name(&self, value: i32, prefix: &str) -> Option<&str> {
1000        self.constants.values().filter(|symbol| symbol.name.starts_with(prefix)).filter_map(|symbol| {
1001            matches!(&symbol.kind, SymbolKind::Constant { int_value: Some(id), .. } if *id == value)
1002                .then_some(symbol.name.as_str())
1003        }).min()
1004    }
1005
1006    /// Look up an entity ID by name (from stat.pack, npc.pack, etc.).
1007    /// Normalizes the name matching TS normalizeName for Basic symbols.
1008    pub fn lookup_entity_id(&self, name: &str) -> Option<EntityRef> {
1009        let normalized = normalize_entity_name(name);
1010        self.entity_ids
1011            .get(normalized.as_ref())
1012            .and_then(|e| e.primary)
1013    }
1014
1015    /// Free registration-only scratch once every script is registered. The
1016    /// pre-assigned IDs are consulted only while assigning
1017    /// ids in `register_script`; codegen and pointer-checking never read them.
1018    /// Replacing (not `clear`-ing) the map returns its buckets to the allocator.
1019    pub(crate) fn drop_registration_scratch(&mut self) {
1020        self.preloaded_script_ids = HashMap::new();
1021    }
1022
1023    /// Get the script ID for a given name. Reads the id from the registered
1024    /// script's `Symbol`; falls back to `script_ids` (clientscript-pack entries,
1025    /// which are never registered as RS2). Registered scripts take precedence,
1026    /// matching the old insert order (clientscripts loaded, then `register_script`
1027    /// overwrote by name).
1028    pub fn script_id(&self, name: &str) -> Option<i32> {
1029        if let Some(s) = self.scripts.get(name)
1030            && let SymbolKind::Script { id, .. } = &s.kind
1031        {
1032            return Some(*id);
1033        }
1034        self.script_ids.get(name).copied()
1035    }
1036
1037    /// Get the proc script ID for a given name.
1038    pub fn proc_script_id(&self, name: &str) -> Option<i32> {
1039        self.proc_script_ids.get(name).copied()
1040    }
1041
1042    /// Get the label script ID for a given name.
1043    pub fn label_script_id(&self, name: &str) -> Option<i32> {
1044        self.label_script_ids.get(name).copied()
1045    }
1046
1047    pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
1048        let key = format!("{}:{}", trigger, name);
1049        if let Some(s) = self.scripts_by_trigger.get(&key)
1050            && let SymbolKind::Script { id, .. } = &s.kind
1051        {
1052            return Some(*id);
1053        }
1054        // Fallback: clientscript-pack ids (keyed `clientscript:name`), never
1055        // registered as RS2 scripts.
1056        self.trigger_script_ids
1057            .get(&key)
1058            .or_else(|| self.preloaded_script_ids.get(&key))
1059            .copied()
1060    }
1061
1062    pub fn command_opcode(&self, name: &str) -> Option<i32> {
1063        self.commands.get(name).and_then(|sym| {
1064            if let SymbolKind::Command { opcode, .. } = &sym.kind {
1065                Some(*opcode)
1066            } else {
1067                None
1068            }
1069        })
1070    }
1071
1072    pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
1073        self.test_scripts.insert(format!("{}:{}", trigger, name));
1074    }
1075
1076    pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
1077        self.test_scripts.contains(&format!("{}:{}", trigger, name))
1078    }
1079
1080    /// Look up a component by interface_name:component_name.
1081    /// Returns the packed (iface_id << 16 | comp_id) value.
1082    /// Normalizes the component name so 647-style `com2` and 225-style `com_2`
1083    /// both resolve against whichever form the pack was written in.
1084    pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
1085        let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
1086        self.components.get(&key).copied()
1087    }
1088}
1089
1090/// A pack name as scripts write it: trimmed, with each character an
1091/// identifier can't hold (a space, a hyphen) as `_`. Packs keep Jagex's real
1092/// names, so `cove lid` is `cove_lid` in source.
1093pub fn identifier_form(name: &str) -> String {
1094    name.trim()
1095        .chars()
1096        .map(|c| {
1097            if c.is_ascii_alphanumeric() || c == '_' {
1098                c
1099            } else {
1100                '_'
1101            }
1102        })
1103        .collect()
1104}
1105
1106/// Strip underscores at alpha→digit boundaries to unify 647-style `com2`
1107/// with 225-style `com_2`. Both normalize to `com2`.
1108pub(crate) fn normalize_comp_name(name: &str) -> String {
1109    let bytes = name.as_bytes();
1110    let mut out = Vec::with_capacity(bytes.len());
1111    let mut i = 0;
1112    while i < bytes.len() {
1113        if bytes[i] == b'_'
1114            && i > 0
1115            && bytes[i - 1].is_ascii_alphabetic()
1116            && i + 1 < bytes.len()
1117            && bytes[i + 1].is_ascii_digit()
1118        {
1119            i += 1;
1120            continue;
1121        }
1122        out.push(bytes[i]);
1123        i += 1;
1124    }
1125    unsafe { String::from_utf8_unchecked(out) }
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130    use super::*;
1131
1132    // ── normalize_comp_name ────────────────────────────────────────────
1133
1134    #[test]
1135    fn normalize_strips_underscore_before_digits() {
1136        assert_eq!(normalize_comp_name("com_2"), "com2");
1137        assert_eq!(normalize_comp_name("com_10"), "com10");
1138        assert_eq!(normalize_comp_name("com_0"), "com0");
1139    }
1140
1141    #[test]
1142    fn normalize_preserves_already_compact_names() {
1143        assert_eq!(normalize_comp_name("com2"), "com2");
1144        assert_eq!(normalize_comp_name("com10"), "com10");
1145        assert_eq!(normalize_comp_name("com0"), "com0");
1146    }
1147
1148    #[test]
1149    fn normalize_preserves_non_digit_underscores() {
1150        assert_eq!(normalize_comp_name("close_button"), "close_button");
1151        assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
1152        assert_eq!(normalize_comp_name("title"), "title");
1153    }
1154
1155    #[test]
1156    fn normalize_only_strips_alpha_digit_boundary() {
1157        // underscore between two digits — not stripped
1158        assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
1159        // underscore between digit and alpha — not stripped
1160        assert_eq!(normalize_comp_name("3_panel"), "3_panel");
1161    }
1162
1163    // ── lookup_component (647 pack style) ──────────────────────────────
1164
1165    fn registry_647_style() -> SymbolRegistry {
1166        let mut r = SymbolRegistry::new();
1167        r.interface_ids.insert("multi2".into(), 228);
1168        // 647 pack registers `com0`..`com9` (no underscore)
1169        for i in 0..10 {
1170            let key = format!("multi2:com{}", i);
1171            r.components.insert(key, (228 << 16) | i);
1172        }
1173        r
1174    }
1175
1176    #[test]
1177    fn lookup_647_pack_with_647_reference() {
1178        let r = registry_647_style();
1179        // Script uses the same 647 naming: `multi2:com2`
1180        assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1181        assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
1182    }
1183
1184    #[test]
1185    fn lookup_647_pack_with_225_reference() {
1186        let r = registry_647_style();
1187        // Script uses 225 naming: `multi2:com_2` — must still resolve
1188        assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1189        assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
1190        assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1191    }
1192
1193    // ── lookup_component (225 pack style) ──────────────────────────────
1194
1195    fn registry_225_style() -> SymbolRegistry {
1196        let mut r = SymbolRegistry::new();
1197        r.interface_ids.insert("multi2".into(), 228);
1198        // 225 pack registers `multi2:com_0`..`com_9` — but through
1199        // symloader normalization these become `com0`..`com9`.
1200        for i in 0..10 {
1201            let key = format!("multi2:com{}", i);
1202            r.components.insert(key, 2459 + i);
1203        }
1204        r
1205    }
1206
1207    #[test]
1208    fn lookup_225_pack_with_225_reference() {
1209        let r = registry_225_style();
1210        assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
1211        assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1212    }
1213
1214    #[test]
1215    fn lookup_225_pack_with_647_reference() {
1216        let r = registry_225_style();
1217        assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
1218        assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
1219    }
1220
1221    // ── lookup_component (miss) ────────────────────────────────────────
1222
1223    #[test]
1224    fn lookup_returns_none_for_unknown_component() {
1225        let r = registry_647_style();
1226        assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
1227        assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
1228    }
1229}