Skip to main content

runec/
symbol.rs

1use crate::types::{BaseVarType, Type};
2use std::collections::HashMap;
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    /// Next available script ID.
452    next_script_id: i32,
453}
454
455impl Default for SymbolRegistry {
456    fn default() -> Self {
457        Self::new()
458    }
459}
460
461impl SymbolRegistry {
462    pub fn new() -> Self {
463        SymbolRegistry {
464            scripts: HashMap::new(),
465            commands: HashMap::new(),
466            game_vars: HashMap::new(),
467            constants: HashMap::new(),
468            entity_ids: HashMap::new(),
469            entity_ids_typed: HashMap::new(),
470            command_param_types: HashMap::new(),
471            type_chars: HashMap::new(),
472            script_ids: HashMap::new(),
473            proc_script_ids: HashMap::new(),
474            label_script_ids: HashMap::new(),
475            trigger_script_ids: HashMap::new(),
476            scripts_by_trigger: HashMap::new(),
477            preloaded_script_ids: HashMap::new(),
478            dbcolumn_types: HashMap::new(),
479            components: HashMap::new(),
480            interface_ids: HashMap::new(),
481            next_script_id: 0,
482        }
483    }
484
485    /// Register a script by name with its type information.
486    pub fn register_script(
487        &mut self,
488        name: String,
489        trigger: String,
490        param_types: Vec<Type>,
491        return_types: Vec<Type>,
492    ) -> i32 {
493        let key = format!("{}:{}", trigger, name);
494        let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
495            preloaded
496        } else {
497            let id = self.next_script_id;
498            self.next_script_id += 1;
499            id
500        };
501
502        self.script_ids.insert(name.clone(), id);
503        // Register in trigger-specific maps
504        self.trigger_script_ids
505            .insert(format!("{}:{}", trigger, name), id);
506        if trigger == "proc" {
507            self.proc_script_ids.insert(name.clone(), id);
508        } else if trigger == "label" {
509            self.label_script_ids.insert(name.clone(), id);
510        }
511        let symbol = Symbol {
512            name: name.clone(),
513            kind: SymbolKind::Script {
514                id,
515                trigger: trigger.clone(),
516                param_types,
517                return_types,
518            },
519        };
520        self.scripts_by_trigger
521            .insert(format!("{}:{}", trigger, name), symbol.clone());
522        self.scripts.insert(name, symbol);
523
524        id
525    }
526
527    /// Register a command (engine function).
528    pub fn register_command(
529        &mut self,
530        name: String,
531        opcode: i32,
532        param_types: Vec<Type>,
533        return_types: Vec<Type>,
534    ) {
535        self.commands.insert(
536            name.clone(),
537            Symbol {
538                name,
539                kind: SymbolKind::Command {
540                    opcode,
541                    param_types,
542                    return_types,
543                },
544            },
545        );
546    }
547
548    /// Register a game variable.
549    pub fn register_game_var(
550        &mut self,
551        name: String,
552        var_type: Type,
553        var_id: i32,
554        category: String,
555    ) {
556        self.game_vars.insert(
557            name.clone(),
558            Symbol {
559                name,
560                kind: SymbolKind::GameVar {
561                    var_type,
562                    var_id,
563                    category,
564                },
565            },
566        );
567    }
568
569    /// Register a constant value (from .constant files).
570    pub fn register_constant(
571        &mut self,
572        name: String,
573        const_type: Type,
574        int_value: Option<i32>,
575        string_value: Option<String>,
576    ) {
577        self.constants.insert(
578            name.clone(),
579            Symbol {
580                name,
581                kind: SymbolKind::Constant {
582                    const_type,
583                    int_value,
584                    string_value,
585                },
586            },
587        );
588    }
589
590    /// Register an entity ID (from stat.pack, npc.pack, loc.pack, etc.).
591    /// These are stored separately from .constant files values so plain
592    /// identifier resolution uses entity IDs, while ^name uses .constant files.
593    pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
594        // Store in the typed map (for type-aware lookup).
595        self.entity_ids_typed
596            .entry(name.clone())
597            .or_default()
598            .insert(entity_type, id);
599
600        // Also store in the flat map (priority-ordered; last write wins).
601        self.entity_ids.insert(
602            name.clone(),
603            Symbol {
604                name,
605                kind: SymbolKind::Constant {
606                    const_type: entity_type,
607                    int_value: Some(id),
608                    string_value: None,
609                },
610            },
611        );
612    }
613
614    /// Look up an entity ID for a specific expected type. Returns `None` if the
615    /// name is not registered for that type.
616    /// Normalizes the name (lowercase + spaces→underscores) matching TS normalizeName for Basic symbols.
617    pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
618        let normalized = name.to_lowercase().replace(' ', "_");
619        self.entity_ids_typed
620            .get(&normalized)
621            .and_then(|m| m.get(&expected))
622            .copied()
623    }
624
625    /// Look up a script by name (last registration wins if multiple triggers share the name).
626    pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
627        self.scripts.get(name)
628    }
629
630    /// Look up a script by trigger and name (avoids name collisions between triggers).
631    pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
632        self.scripts_by_trigger
633            .get(&format!("{}:{}", trigger, name))
634    }
635
636    /// Look up a command by name.
637    pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
638        self.commands.get(name)
639    }
640
641    /// Look up a game variable by name.
642    pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
643        self.game_vars.get(name)
644    }
645
646    /// Look up a constant by name (from .constant files).
647    pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
648        self.constants.get(name)
649    }
650
651    /// Look up an entity ID by name (from stat.pack, npc.pack, etc.).
652    /// Normalizes the name matching TS normalizeName for Basic symbols.
653    pub fn lookup_entity_id(&self, name: &str) -> Option<&Symbol> {
654        let normalized = name.to_lowercase().replace(' ', "_");
655        self.entity_ids.get(&normalized)
656    }
657
658    /// Get the script ID for a given name.
659    pub fn script_id(&self, name: &str) -> Option<i32> {
660        self.script_ids.get(name).copied()
661    }
662
663    /// Get the proc script ID for a given name.
664    pub fn proc_script_id(&self, name: &str) -> Option<i32> {
665        self.proc_script_ids.get(name).copied()
666    }
667
668    /// Get the label script ID for a given name.
669    pub fn label_script_id(&self, name: &str) -> Option<i32> {
670        self.label_script_ids.get(name).copied()
671    }
672
673    pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
674        self.trigger_script_ids
675            .get(&format!("{}:{}", trigger, name))
676            .copied()
677    }
678
679    /// Look up a component by interface_name:component_name.
680    /// Returns the packed (iface_id << 16 | comp_id) value.
681    /// Normalizes the component name so 647-style `com2` and 225-style `com_2`
682    /// both resolve against whichever form the pack was written in.
683    pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
684        let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
685        self.components.get(&key).copied()
686    }
687}
688
689/// Strip underscores at alpha→digit boundaries to unify 647-style `com2`
690/// with 225-style `com_2`. Both normalize to `com2`.
691pub(crate) fn normalize_comp_name(name: &str) -> String {
692    let bytes = name.as_bytes();
693    let mut out = Vec::with_capacity(bytes.len());
694    let mut i = 0;
695    while i < bytes.len() {
696        if bytes[i] == b'_'
697            && i > 0
698            && bytes[i - 1].is_ascii_alphabetic()
699            && i + 1 < bytes.len()
700            && bytes[i + 1].is_ascii_digit()
701        {
702            i += 1;
703            continue;
704        }
705        out.push(bytes[i]);
706        i += 1;
707    }
708    unsafe { String::from_utf8_unchecked(out) }
709}
710
711#[cfg(test)]
712mod tests {
713    use super::*;
714
715    // ── normalize_comp_name ────────────────────────────────────────────
716
717    #[test]
718    fn normalize_strips_underscore_before_digits() {
719        assert_eq!(normalize_comp_name("com_2"), "com2");
720        assert_eq!(normalize_comp_name("com_10"), "com10");
721        assert_eq!(normalize_comp_name("com_0"), "com0");
722    }
723
724    #[test]
725    fn normalize_preserves_already_compact_names() {
726        assert_eq!(normalize_comp_name("com2"), "com2");
727        assert_eq!(normalize_comp_name("com10"), "com10");
728        assert_eq!(normalize_comp_name("com0"), "com0");
729    }
730
731    #[test]
732    fn normalize_preserves_non_digit_underscores() {
733        assert_eq!(normalize_comp_name("close_button"), "close_button");
734        assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
735        assert_eq!(normalize_comp_name("title"), "title");
736    }
737
738    #[test]
739    fn normalize_only_strips_alpha_digit_boundary() {
740        // underscore between two digits — not stripped
741        assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
742        // underscore between digit and alpha — not stripped
743        assert_eq!(normalize_comp_name("3_panel"), "3_panel");
744    }
745
746    // ── lookup_component (647 pack style) ──────────────────────────────
747
748    fn registry_647_style() -> SymbolRegistry {
749        let mut r = SymbolRegistry::new();
750        r.interface_ids.insert("multi2".into(), 228);
751        // 647 pack registers `com0`..`com9` (no underscore)
752        for i in 0..10 {
753            let key = format!("multi2:com{}", i);
754            r.components.insert(key, (228 << 16) | i);
755        }
756        r
757    }
758
759    #[test]
760    fn lookup_647_pack_with_647_reference() {
761        let r = registry_647_style();
762        // Script uses the same 647 naming: `multi2:com2`
763        assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
764        assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
765    }
766
767    #[test]
768    fn lookup_647_pack_with_225_reference() {
769        let r = registry_647_style();
770        // Script uses 225 naming: `multi2:com_2` — must still resolve
771        assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
772        assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
773        assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
774    }
775
776    // ── lookup_component (225 pack style) ──────────────────────────────
777
778    fn registry_225_style() -> SymbolRegistry {
779        let mut r = SymbolRegistry::new();
780        r.interface_ids.insert("multi2".into(), 228);
781        // 225 pack registers `multi2:com_0`..`com_9` — but through
782        // symloader normalization these become `com0`..`com9`.
783        for i in 0..10 {
784            let key = format!("multi2:com{}", i);
785            r.components.insert(key, 2459 + i);
786        }
787        r
788    }
789
790    #[test]
791    fn lookup_225_pack_with_225_reference() {
792        let r = registry_225_style();
793        assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
794        assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
795    }
796
797    #[test]
798    fn lookup_225_pack_with_647_reference() {
799        let r = registry_225_style();
800        assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
801        assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
802    }
803
804    // ── lookup_component (miss) ────────────────────────────────────────
805
806    #[test]
807    fn lookup_returns_none_for_unknown_component() {
808        let r = registry_647_style();
809        assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
810        assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
811    }
812}