Skip to main content

runec/
symbol.rs

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