Skip to main content

runec/
symloader.rs

1//! Loads pack files and populates the SymbolRegistry.
2//!
3//! Pack files use 2004scape's `id=name` format (matching CompilerTypeInfo.load).
4//! Constants are loaded from `.constant` files in the scripts directory.
5
6use std::fs;
7use std::path::Path;
8
9use tracing::{info, warn};
10
11use crate::symbol::{SymbolKind, SymbolRegistry};
12use crate::types::Type;
13
14/// Parse the parameter types declared in an `engine.rs2` file and populate
15/// `registry.command_param_types`. Lines like:
16///   `[command,sound_synth](synth $sound, int $loops, int $delay)`
17/// are parsed to extract the ordered list of parameter types per command.
18pub fn load_engine_command_params(registry: &mut SymbolRegistry, engine_rs2: &Path) {
19    let text = match fs::read_to_string(engine_rs2) {
20        Ok(t) => t,
21        Err(_) => return,
22    };
23    for line in text.lines() {
24        let line = line.trim();
25        // Match lines starting with `[command,<name>]`
26        if !line.starts_with("[command,") {
27            continue;
28        }
29        // Extract command name (between the comma and closing bracket)
30        let rest = &line["[command,".len()..];
31        let name_end = match rest.find(']') {
32            Some(i) => i,
33            None => continue,
34        };
35        let name = rest[..name_end].trim().to_string();
36
37        // Extract parameter list between first `(` and matching `)`
38        let after_bracket = &rest[name_end + 1..];
39        let params_start = match after_bracket.find('(') {
40            Some(i) => i + 1,
41            None => {
42                // No params at all
43                registry.command_param_types.insert(name, Vec::new());
44                continue;
45            }
46        };
47        let params_end = match after_bracket[params_start..].find(')') {
48            Some(i) => params_start + i,
49            None => continue,
50        };
51        let params_str = &after_bracket[params_start..params_end];
52
53        let mut param_types: Vec<Type> = Vec::new();
54        for param in params_str.split(',') {
55            let param = param.trim();
56            if param.is_empty() {
57                continue;
58            }
59            // Each param is like `synth $sound` or `int $loops` or just `int`
60            let type_name = param.split_whitespace().next().unwrap_or(param);
61            if let Some(t) = Type::from_name(type_name) {
62                param_types.push(t);
63            } else {
64                // Unknown type — push Int as placeholder so arg count stays correct
65                param_types.push(Type::Int);
66            }
67        }
68        registry
69            .command_param_types
70            .insert(name.clone(), param_types.clone());
71
72        if let Some(sym) = registry.commands.get_mut(&name)
73            && let SymbolKind::Command {
74                param_types: ref mut pt,
75                ..
76            } = sym.kind
77        {
78            *pt = param_types;
79        }
80
81        // Parse return types from the second parenthesized group: `(param_types)(return_types)`
82        let after_params = &after_bracket[params_end + 1..];
83        if let Some(ret_start) = after_params.find('(')
84            && let Some(ret_end) = after_params[ret_start + 1..].find(')')
85        {
86            let ret_str = &after_params[ret_start + 1..ret_start + 1 + ret_end];
87            let mut return_types: Vec<Type> = Vec::new();
88            for ret in ret_str.split(',') {
89                let ret = ret.trim();
90                if ret.is_empty() {
91                    continue;
92                }
93                if let Some(t) = Type::from_name(ret) {
94                    return_types.push(t);
95                }
96            }
97            if !return_types.is_empty() {
98                // Update the command's return types in the registry
99                if let Some(sym) = registry.commands.get_mut(&name)
100                    && let SymbolKind::Command {
101                        return_types: ref mut rt,
102                        ..
103                    } = sym.kind
104                {
105                    *rt = return_types;
106                }
107            }
108        }
109    }
110}
111
112/// Patch return types for commands whose signatures are not in engine.rs2 but are
113/// known to return values in the Neptune compiler. Without this, statement-level
114/// calls to these commands will be missing POP_INT_DISCARD / POP_STRING_DISCARD.
115pub fn patch_command_return_types(registry: &mut SymbolRegistry) {
116    let patches: &[(&str, Vec<Type>)] = &[
117        ("db_find_with_count", vec![Type::Int]),
118        ("db_find_refine_with_count", vec![Type::Int]),
119        ("db_listall_with_count", vec![Type::Int]),
120    ];
121    for (name, ret_types) in patches {
122        if let Some(sym) = registry.commands.get_mut(*name)
123            && let SymbolKind::Command { return_types, .. } = &mut sym.kind
124            && return_types.is_empty()
125        {
126            *return_types = ret_types.clone();
127        }
128    }
129}
130
131/// Load script.pack: `id=[trigger,name]` — pre-assigns script IDs so the
132/// Rust compiler uses the same IDs as the Java compiler.
133fn load_script_pack(registry: &mut SymbolRegistry, path: &Path) {
134    let text = match fs::read_to_string(path) {
135        Ok(t) => t,
136        Err(_) => return,
137    };
138    for line in text.lines() {
139        let line = line.trim();
140        if line.is_empty() {
141            continue;
142        }
143        let (id_str, rest) = match line.split_once('=') {
144            Some(pair) => pair,
145            None => continue,
146        };
147        let id: i32 = match id_str.parse() {
148            Ok(v) => v,
149            Err(_) => continue,
150        };
151        let rest = rest.trim();
152        // Expected format: [trigger,name]
153        if !rest.starts_with('[') || !rest.ends_with(']') {
154            continue;
155        }
156        let inner = &rest[1..rest.len() - 1];
157        let comma = match inner.find(',') {
158            Some(i) => i,
159            None => continue,
160        };
161        let trigger = &inner[..comma];
162        let name = &inner[comma + 1..];
163        if trigger.is_empty() || name.is_empty() {
164            continue;
165        }
166        let key = format!("{}:{}", trigger, name);
167        registry.preloaded_script_ids.insert(key, id);
168    }
169}
170
171/// Generate/update script.pack from .rs2 files, matching 2004scape's regenScriptPack().
172/// Scans all [trigger,name] declarations, preserves existing IDs, assigns new ones.
173pub fn generate_script_pack(scripts_dir: &Path, pack_dir: &Path) {
174    use std::collections::BTreeMap;
175
176    let pack_path = pack_dir.join("script.pack");
177
178    // Load existing entries
179    let mut id_to_name: BTreeMap<i32, String> = BTreeMap::new();
180    let mut name_to_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
181    let mut max_id: i32 = 0;
182
183    if let Ok(text) = fs::read_to_string(&pack_path) {
184        for line in text.lines() {
185            let line = line.trim();
186            if line.is_empty() {
187                continue;
188            }
189            if let Some((id_str, name)) = line.split_once('=')
190                && let Ok(id) = id_str.parse::<i32>()
191            {
192                let name = name.trim().to_string();
193                name_to_id.insert(name.clone(), id);
194                id_to_name.insert(id, name);
195                if id >= max_id {
196                    max_id = id + 1;
197                }
198            }
199        }
200    }
201
202    // Scan .rs2 files for [trigger,name] declarations
203    let mut rs2_files = Vec::new();
204    collect_rs2_files(scripts_dir, &mut rs2_files);
205    rs2_files.sort();
206
207    for path in &rs2_files {
208        // Skip engine.rs2 (command signatures, not compiled scripts)
209        if path.file_name().and_then(|n| n.to_str()) == Some("engine.rs2") {
210            continue;
211        }
212        let Ok(text) = fs::read_to_string(path) else {
213            continue;
214        };
215        for line in text.lines() {
216            let line = line.split("//").next().unwrap_or("").trim();
217            if !line.starts_with('[') {
218                continue;
219            }
220            let bracket_end = match line.find(']') {
221                Some(i) => i,
222                None => continue,
223            };
224            let full_name = &line[..bracket_end + 1]; // e.g. "[proc,foo]"
225            let inner = &line[1..bracket_end];
226            let comma = match inner.find(',') {
227                Some(i) => i,
228                None => continue,
229            };
230            let trigger = &inner[..comma];
231            // Skip command declarations
232            if trigger == "command" {
233                continue;
234            }
235
236            if !name_to_id.contains_key(full_name) {
237                name_to_id.insert(full_name.to_string(), max_id);
238                id_to_name.insert(max_id, full_name.to_string());
239                max_id += 1;
240            }
241        }
242    }
243
244    // Save
245    if let Err(e) = std::fs::create_dir_all(pack_dir) {
246        warn!(target: "runec", "Failed to create pack dir: {}", e);
247        return;
248    }
249    let mut out = String::new();
250    for (id, name) in &id_to_name {
251        out.push_str(&format!("{}={}\n", id, name));
252    }
253    if let Err(e) = fs::write(&pack_path, &out) {
254        warn!(target: "runec", "Failed to write script.pack: {}", e);
255    } else {
256        info!(target: "runec", "script.pack: {} entries", id_to_name.len());
257    }
258}
259
260fn collect_rs2_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
261    let Ok(entries) = fs::read_dir(dir) else {
262        return;
263    };
264    let mut sorted: Vec<std::path::PathBuf> = entries.flatten().map(|e| e.path()).collect();
265    sorted.sort();
266    for path in sorted {
267        if path.is_dir() {
268            collect_rs2_files(&path, out);
269        } else if path.extension().and_then(|e| e.to_str()) == Some("rs2") {
270            out.push(path);
271        }
272    }
273}
274
275/// Load all .pack files from `pack_dir` into `registry`.
276///
277/// Pack files use 2004scape format: `id=name` (one per line).
278/// This matches how 2004scape's Compiler.ts loads CompilerTypeInfo from pack files.
279pub fn load_packs(registry: &mut SymbolRegistry, pack_dir: &Path) {
280    if !pack_dir.exists() {
281        return;
282    }
283
284    // Register engine constants FIRST (baseline defaults).
285    // Pack files loaded below may overwrite these with content-specific values.
286    register_engine_constants(registry);
287
288    load_commands(registry, &pack_dir.join("command.pack"));
289
290    load_game_vars(registry, &pack_dir.join("varp.pack"), "varp");
291    load_game_vars(registry, &pack_dir.join("varn.pack"), "varn");
292    load_game_vars(registry, &pack_dir.join("vars.pack"), "vars");
293    load_game_vars(registry, &pack_dir.join("varbit.pack"), "varbit");
294
295    // Load entity IDs.
296    // Load in ascending priority order: later entries overwrite earlier ones
297    // when the same name exists in multiple tables.
298    //
299    // Priority (highest wins for plain identifier resolution):
300    //   Low:    UI types (interface, overlayinterface, component, idk),
301    //           abstract types (struct, dbrow, dbtable, dbcolumn, param)
302    //   Medium: audio/animation types (synth, seq, spotanim, mesanim, fontmetrics)
303    //   High:   core game entity types (stat, obj, npc, loc, inv, category, enum, ...)
304    //
305    // e.g. "prayer" is in interface.pack (id=5608) AND stat.pack (id=5);
306    //      stat.pack wins so stat_sub(prayer,...) resolves to 5.
307    // e.g. "stafforb" is in struct.pack (id=45) AND obj.pack (id=567);
308    //      obj.pack wins so inv_add(..., stafforb, ...) resolves to 567.
309    for (file, type_hint) in &[
310        // Lowest priority — category overridden by UI types, synth, and all above
311        ("category.pack", Type::Category),
312        // UI types (override category)
313        ("idk.pack", Type::IdKit),
314        ("interface.pack", Type::Interface), // Combined: interfaces + components
315        ("overlayinterface.pack", Type::OverlayInterface),
316        // Abstract / structural types
317        ("struct.pack", Type::Struct),
318        ("dbrow.pack", Type::DbRow),
319        ("dbtable.pack", Type::DbTable),
320        ("dbcolumn.pack", Type::DbColumn),
321        ("param.pack", Type::Param),
322        // Audio / animation / model types (medium priority)
323        ("model.pack", Type::Model),
324        ("fontmetrics.pack", Type::FontMetrics),
325        ("mesanim.pack", Type::MesAnim),
326        ("jingle.pack", Type::Jingle),
327        ("midi.pack", Type::Midi),
328        ("synth.pack", Type::Synth),
329        ("spotanim.pack", Type::Spotanim),
330        ("seq.pack", Type::Seq),
331        // Core game entity types (highest priority — overwrite everything above)
332        ("locshape.pack", Type::LocShape),
333        ("hunt.pack", Type::Hunt),
334        ("npc_mode.pack", Type::NpcMode),
335        ("enum.pack", Type::Enum),
336        ("writeinv.pack", Type::WriteinvObj),
337        ("inv.pack", Type::Inv),
338        ("loc.pack", Type::Loc),
339        ("npc_stat.pack", Type::NpcStat),
340        ("stat.pack", Type::Stat),
341        ("npc.pack", Type::Npc),
342        ("obj.pack", Type::Obj),
343        ("controller.pack", Type::Controller),
344    ] {
345        load_entity_ids(registry, &pack_dir.join(file), *type_hint);
346    }
347
348    // obj.pack entities are also valid as namedobj (an object referenced by
349    // name at compile time). Register them under NamedObj in the typed map
350    // so hint-driven resolution works for commands like inv_add(inv, namedobj, int).
351    load_entity_ids_typed_only(registry, &pack_dir.join("obj.pack"), Type::NamedObj);
352
353    // Register type-name identifiers so they resolve to their CS2 type chars.
354    register_type_chars(registry);
355
356    // Load pre-assigned script IDs LAST so they are available before script registration.
357    load_script_pack(registry, &pack_dir.join("script.pack"));
358
359    // Load clientscript.pack: CS2 scripts the server references by name via
360    // runclientscript(). They are never compiled as RS2, so register them
361    // directly into the resolution maps. Safe no-op if file doesn't exist.
362    load_clientscript_pack(registry, &pack_dir.join("clientscript.pack"));
363}
364
365/// Load clientscript.pack: `id=[clientscript,name]` — registers CS2 script IDs
366/// directly so server-side RS2 can reference them by name
367/// (e.g. `runclientscript(playerdesign4_open_name_entry)` resolves to 3943).
368fn load_clientscript_pack(registry: &mut SymbolRegistry, path: &Path) {
369    let text = match fs::read_to_string(path) {
370        Ok(t) => t,
371        Err(_) => return,
372    };
373    for line in text.lines() {
374        let line = line.trim();
375        if line.is_empty() {
376            continue;
377        }
378        let (id_str, rest) = match line.split_once('=') {
379            Some(pair) => pair,
380            None => continue,
381        };
382        let id: i32 = match id_str.parse() {
383            Ok(v) => v,
384            Err(_) => continue,
385        };
386        let rest = rest.trim();
387        if !rest.starts_with('[') || !rest.ends_with(']') {
388            continue;
389        }
390        let inner = &rest[1..rest.len() - 1];
391        let (_trigger, name) = match inner.split_once(',') {
392            Some(pair) => pair,
393            None => continue,
394        };
395        if name.is_empty() {
396            continue;
397        }
398        registry.script_ids.insert(name.to_string(), id);
399        registry
400            .trigger_script_ids
401            .insert(format!("clientscript:{}", name), id);
402    }
403}
404
405/// Load a game var pack file: `id=name`
406/// Type defaults to Int (matching 2004scape — var types come from config definitions).
407/// Load command.pack: `opcode=name`
408/// Game commands are provided by the engine, not hardcoded in the compiler.
409/// This matches the RuneScriptTS architecture where the consuming engine
410/// passes its `ScriptOpcodeMap` as the `symbols['command']` CompilerTypeInfo.
411fn load_commands(registry: &mut SymbolRegistry, path: &Path) {
412    let text = match fs::read_to_string(path) {
413        Ok(t) => t,
414        Err(_) => return,
415    };
416    for line in text.lines() {
417        let line = line.trim();
418        if line.is_empty() {
419            continue;
420        }
421        let (id_str, name) = match line.split_once('=') {
422            Some(pair) => pair,
423            None => continue,
424        };
425        let opcode: i32 = match id_str.parse() {
426            Ok(v) => v,
427            Err(_) => continue,
428        };
429        let name = name.trim().to_string();
430        if name.is_empty() {
431            continue;
432        }
433        registry.register_command(name, opcode, Vec::new(), Vec::new());
434    }
435}
436
437fn load_game_vars(registry: &mut SymbolRegistry, path: &Path, category: &str) {
438    let text = match fs::read_to_string(path) {
439        Ok(t) => t,
440        Err(_) => return,
441    };
442    for line in text.lines() {
443        let line = line.trim();
444        if line.is_empty() {
445            continue;
446        }
447        let (id_str, name) = match line.split_once('=') {
448            Some(pair) => pair,
449            None => continue,
450        };
451        let idx: i32 = match id_str.parse() {
452            Ok(v) => v,
453            Err(_) => continue,
454        };
455        let name = name.trim().to_string();
456        if name.is_empty() {
457            continue;
458        }
459        // The parser prefixes names with '.' for secondary entity scope
460        // (e.g., .%npc_attacking_uid for varn, .%aggressive_npc for varp on
461        // another player). Register the dot-prefixed version for all categories.
462        registry.register_game_var(format!(".{}", name), Type::Int, idx, category.to_string());
463        registry.register_game_var(name, Type::Int, idx, category.to_string());
464    }
465}
466
467/// Scan `.dbtable` files under `scripts_dir` and register each column as a
468/// compound entity ID `table:column` → packed int, mirroring 2004scape's
469/// runescript lookup.
470///
471/// Packed format: `(tableId << 12) | (colIdx << 4) | tupleNibble`
472/// where `tupleNibble` is 0 for the whole tuple and `N+1` for slot N.
473///
474/// Also populates `registry.dbcolumn_types` so `db_find(music:playbutton, ...)`
475/// emits the correct BaseVarType ordinal.
476///
477/// `dbtable_ids` is the pre-loaded name→id mapping from `dbtable.pack` — the
478/// same IDs the runtime uses when indexing rows.
479pub fn load_dbtable_configs(
480    registry: &mut SymbolRegistry,
481    scripts_dir: &Path,
482    dbtable_ids: &std::collections::HashMap<String, u16>,
483) {
484    let mut dbtable_files: Vec<std::path::PathBuf> = Vec::new();
485    collect_files_by_ext(scripts_dir, "dbtable", &mut dbtable_files);
486    dbtable_files.sort();
487
488    for path in &dbtable_files {
489        let Ok(text) = fs::read_to_string(path) else {
490            continue;
491        };
492        let lines = strip_comments(&text);
493
494        let mut current_table: Option<String> = None;
495        let mut col_idx: u16 = 0;
496        for line in &lines {
497            // Section header: [tablename]
498            if line.starts_with('[') && line.ends_with(']') {
499                let name = line[1..line.len() - 1].trim().to_string();
500                current_table = Some(name);
501                col_idx = 0;
502                continue;
503            }
504            // column=name,type1[,type2...][,INDEXED][,REQUIRED]
505            let Some(rest) = line.strip_prefix("column=") else {
506                continue;
507            };
508            let Some(table_name) = current_table.as_deref() else {
509                continue;
510            };
511            let Some(&table_id) = dbtable_ids.get(table_name) else {
512                continue;
513            };
514
515            let parts: Vec<&str> = rest.split(',').map(str::trim).collect();
516            if parts.is_empty() {
517                continue;
518            }
519            let col_name = parts[0];
520            if col_name.is_empty() {
521                continue;
522            }
523
524            // Collect types, skipping INDEXED/REQUIRED flags.
525            let types: Vec<Type> = parts[1..]
526                .iter()
527                .filter(|s| !matches!(**s, "INDEXED" | "REQUIRED"))
528                .filter_map(|s| Type::from_name(s))
529                .collect();
530
531            let compound = format!("{}:{}", table_name, col_name);
532            let packed = ((table_id as i32) << 12) | ((col_idx as i32) << 4);
533
534            // Register whole-tuple form
535            registry.register_entity_id(compound.clone(), Type::DbColumn, packed);
536
537            // Register per-slot tuple indexes for multi-field columns
538            if types.len() > 1 {
539                for (i, _) in types.iter().enumerate() {
540                    let slot_compound = format!("{}:{}:{}", table_name, col_name, i);
541                    let slot_packed = packed | (((i as i32) + 1) & 0xF);
542                    registry.register_entity_id(slot_compound, Type::DbColumn, slot_packed);
543                }
544            }
545
546            // First-field type drives db_find's BaseVarType ordinal.
547            if let Some(first_type) = types.first().copied() {
548                registry.dbcolumn_types.insert(compound, first_type);
549            }
550
551            col_idx += 1;
552        }
553    }
554}
555
556/// Load dbtable.pack as a `name → id` map. Used by `load_dbtable_configs`.
557pub fn load_dbtable_pack(path: &Path) -> std::collections::HashMap<String, u16> {
558    let mut out = std::collections::HashMap::new();
559    let Ok(text) = fs::read_to_string(path) else {
560        return out;
561    };
562    for line in text.lines() {
563        let line = line.trim();
564        if line.is_empty() {
565            continue;
566        }
567        let Some((id_str, name)) = line.split_once('=') else {
568            continue;
569        };
570        let Ok(id) = id_str.parse::<u16>() else {
571            continue;
572        };
573        let name = name.trim();
574        if name.is_empty() {
575            continue;
576        }
577        out.insert(name.to_string(), id);
578    }
579    out
580}
581
582/// Load all `.constant` files from the scripts directory, matching 2004scape's
583/// `loadDirExtFull(scripts_dir, '.constant', ...)` behavior.
584///
585/// Format: `^name = value` per line, with `//` and `/* */` comment stripping.
586pub fn load_constant_files(registry: &mut SymbolRegistry, scripts_dir: &Path) {
587    let mut constant_files: Vec<std::path::PathBuf> = Vec::new();
588    collect_files_by_ext(scripts_dir, "constant", &mut constant_files);
589    constant_files.sort();
590
591    for path in &constant_files {
592        let text = match fs::read_to_string(path) {
593            Ok(t) => t,
594            Err(_) => continue,
595        };
596        let lines = strip_comments(&text);
597        for line in &lines {
598            // Split on '=' into name and value
599            let eq_pos = match line.find('=') {
600                Some(i) => i,
601                None => continue,
602            };
603            let mut name = line[..eq_pos].trim();
604            let value = line[eq_pos + 1..].trim();
605
606            // Strip leading ^ from name
607            if let Some(stripped) = name.strip_prefix('^') {
608                name = stripped;
609            }
610
611            if name.is_empty() {
612                continue;
613            }
614
615            // Strip surrounding quotes from string values
616            let val_str = if value.starts_with('"') && value.ends_with('"') && value.len() >= 2 {
617                &value[1..value.len() - 1]
618            } else {
619                value
620            };
621
622            register_constant_value(registry, name.to_string(), val_str);
623        }
624    }
625}
626
627/// Register a constant value, auto-detecting its type (int, hex, coord, or string).
628fn register_constant_value(registry: &mut SymbolRegistry, name: String, val_str: &str) {
629    if let Ok(i) = val_str.parse::<i32>() {
630        registry.register_constant(name, Type::Int, Some(i), None);
631    } else if let Some(hex_str) = val_str
632        .strip_prefix("0x")
633        .or_else(|| val_str.strip_prefix("0X"))
634    {
635        let v = u32::from_str_radix(hex_str, 16).unwrap_or(0) as i32;
636        registry.register_constant(name, Type::Int, Some(v), None);
637    } else if let Some(packed) = parse_coord_string(val_str) {
638        registry.register_constant(name, Type::Coord, Some(packed), None);
639    } else {
640        registry.register_constant(name, Type::String, None, Some(val_str.to_string()));
641    }
642}
643
644/// Strip `//` single-line and `/* */` multi-line comments from source text,
645/// matching 2004scape's `loadFileFull()` behavior.
646fn strip_comments(text: &str) -> Vec<String> {
647    let mut result = Vec::new();
648    let mut multi_depth: usize = 0;
649
650    for line in text.lines() {
651        let mut line = line.trim().to_string();
652
653        // Handle continuation of multi-line comments
654        if multi_depth > 0 {
655            while let Some(start) = line.find("/*") {
656                line = line[start + 2..].trim_start().to_string();
657                multi_depth += 1;
658            }
659            while let Some(end) = line.find("*/") {
660                line = line[end + 2..].trim_start().to_string();
661                multi_depth -= 1;
662                if multi_depth == 0 {
663                    break;
664                }
665            }
666            if multi_depth > 0 {
667                continue;
668            }
669        }
670
671        if line.is_empty() {
672            continue;
673        }
674
675        // Strip single-line comments
676        if let Some(idx) = line.find("//") {
677            line = line[..idx].trim_end().to_string();
678            if line.is_empty() {
679                continue;
680            }
681        }
682
683        // Strip inline multi-line comments
684        if let Some(start) = line.find("/*") {
685            if let Some(end) = line.find("*/") {
686                line = format!("{}{}", &line[..start], &line[end + 2..]);
687            } else {
688                line = line[..start].to_string();
689                multi_depth += 1;
690            }
691            if line.is_empty() {
692                continue;
693            }
694        }
695
696        result.push(line);
697    }
698
699    result
700}
701
702/// Scan `.varp`/`.varn`/`.vars`/`.varbit` configs and refine the type
703/// of each matching game-var. `load_game_vars` defaults everything to
704/// `Type::Int`; the real type comes from the `type=<typename>` line
705/// in the config block.
706pub fn load_game_var_types(registry: &mut SymbolRegistry, scripts_dir: &Path) {
707    // Track the next auto-assigned ID per category for vars only found in config files.
708    let mut next_auto_id: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
709    for ext in &["varp", "varn", "vars", "varbit"] {
710        // Compute the next available ID (one past the highest existing).
711        let max_id = registry
712            .game_vars
713            .values()
714            .filter_map(|sym| {
715                if let crate::symbol::SymbolKind::GameVar {
716                    var_id, category, ..
717                } = &sym.kind
718                {
719                    if category == *ext {
720                        Some(*var_id)
721                    } else {
722                        None
723                    }
724                } else {
725                    None
726                }
727            })
728            .max()
729            .unwrap_or(-1);
730        next_auto_id.insert(ext.to_string(), max_id + 1);
731    }
732
733    for ext in &["varp", "varn", "vars", "varbit"] {
734        let mut files = Vec::new();
735        collect_files_by_ext(scripts_dir, ext, &mut files);
736        for path in &files {
737            let Ok(text) = fs::read_to_string(path) else {
738                continue;
739            };
740            let mut current_name: Option<String> = None;
741            for line in text.lines() {
742                let line = line.trim();
743                if line.is_empty() || line.starts_with("//") {
744                    continue;
745                }
746                if let Some(inner) = line.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
747                    let name = inner.trim().to_string();
748                    // Register the var if it doesn't exist yet (config-only var)
749                    if !registry.game_vars.contains_key(&name) {
750                        let id = next_auto_id.get_mut(*ext).unwrap();
751                        let auto_id = *id;
752                        *id += 1;
753                        registry.register_game_var(
754                            name.clone(),
755                            Type::Int,
756                            auto_id,
757                            ext.to_string(),
758                        );
759                        registry.register_game_var(
760                            format!(".{}", name),
761                            Type::Int,
762                            auto_id,
763                            ext.to_string(),
764                        );
765                    }
766                    current_name = Some(name);
767                    continue;
768                }
769                let Some(name) = current_name.as_ref() else {
770                    continue;
771                };
772                if let Some((k, v)) = line.split_once('=')
773                    && k.trim() == "type"
774                {
775                    let type_name = v.trim();
776                    if let Some(ty) = Type::from_name(type_name) {
777                        if let Some(sym) = registry.game_vars.get_mut(name)
778                            && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
779                                &mut sym.kind
780                        {
781                            *var_type = ty;
782                        }
783                        let dot_name = format!(".{}", name);
784                        if let Some(sym) = registry.game_vars.get_mut(&dot_name)
785                            && let crate::symbol::SymbolKind::GameVar { var_type, .. } =
786                                &mut sym.kind
787                        {
788                            *var_type = ty;
789                        }
790                    }
791                }
792            }
793        }
794    }
795}
796
797/// Recursively collect files with a given extension.
798fn collect_files_by_ext(dir: &Path, ext: &str, out: &mut Vec<std::path::PathBuf>) {
799    let entries = match fs::read_dir(dir) {
800        Ok(e) => e,
801        Err(_) => return,
802    };
803    for entry in entries.flatten() {
804        let path = entry.path();
805        if path.is_dir() {
806            collect_files_by_ext(&path, ext, out);
807        } else if path.extension().and_then(|e| e.to_str()) == Some(ext) {
808            out.push(path);
809        }
810    }
811}
812
813/// Parse a coord string in `z_bx_bz_lx_lz` format and return the packed integer.
814/// Packing: x = bx*64 + lx, z = bz*64 + lz, packed = (level << 28) | (x << 14) | z
815fn parse_coord_string(s: &str) -> Option<i32> {
816    let parts: Vec<&str> = s.split('_').collect();
817    if parts.len() != 5 {
818        return None;
819    }
820    let y: i32 = parts[0].parse().ok()?;
821    let bx: i32 = parts[1].parse().ok()?;
822    let bz: i32 = parts[2].parse().ok()?;
823    let lx: i32 = parts[3].parse().ok()?;
824    let lz: i32 = parts[4].parse().ok()?;
825    let x = bx * 64 + lx;
826    let z = bz * 64 + lz;
827    Some((y << 28) | (x << 14) | z)
828}
829
830/// Load an entity pack file. Two `interface.pack` dialects are accepted:
831///
832/// 1. **if3** (rev 647 / 2004scape): key encodes the IDs, value is the short name.
833///    - `<iface_id>=<iface_name>`            → root interface
834///    - `<iface_id>:<comp_id>=<comp_name>`   → component, packed idx = (iface<<16)|comp
835///
836/// 2. **if1** (rev 225 era): key is a flat global index, value carries the full path.
837///    - `<flat_id>=<iface_name>`             → root interface
838///    - `<flat_id>=<iface_name>:<comp_name>` → component, idx = flat_id
839///
840/// Detection is per-line, so a pack written entirely in either dialect parses cleanly,
841/// and neither produces a misleading "subject did not resolve" for entries that are
842/// actually present.
843fn load_entity_ids(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
844    let text = match fs::read_to_string(path) {
845        Ok(t) => t,
846        Err(_) => return,
847    };
848
849    let is_interface_pack = entity_type == Type::Interface;
850
851    // First pass: collect interface name→ID for component resolution.
852    // Both dialects agree on the root form: `<id>=<name>` with no `:` on either side.
853    let mut iface_id_to_name: std::collections::HashMap<i32, String> =
854        std::collections::HashMap::new();
855
856    for line in text.lines() {
857        let line = line.trim();
858        if line.is_empty() {
859            continue;
860        }
861        let (id_str, name) = match line.split_once('=') {
862            Some(pair) => pair,
863            None => continue,
864        };
865        let name = name.trim();
866        if name.is_empty() || name == "null" {
867            continue;
868        }
869
870        if is_interface_pack
871            && !id_str.contains(':')
872            && !name.contains(':')
873            && let Ok(id) = id_str.parse::<i32>()
874        {
875            registry.interface_ids.insert(name.to_string(), id);
876            iface_id_to_name.insert(id, name.to_string());
877        }
878    }
879
880    // Second pass: register entities + components
881    for line in text.lines() {
882        let line = line.trim();
883        if line.is_empty() {
884            continue;
885        }
886        let (id_str, name) = match line.split_once('=') {
887            Some(pair) => pair,
888            None => continue,
889        };
890        let name = name.trim();
891        if name.is_empty() || name == "null" {
892            continue;
893        }
894
895        // Decide shape: native component (LHS has `:`), Jordan component
896        // (RHS has `:` on an interface pack), or plain root.
897        let (idx, component_key, register_name): (i32, Option<String>, String) =
898            if let Some((iface_str, comp_str)) = id_str.split_once(':') {
899                // Native component: `<iface_id>:<comp_id>=<comp_name>`
900                let iface: i32 = match iface_str.parse() {
901                    Ok(v) => v,
902                    Err(_) => continue,
903                };
904                let comp: i32 = match comp_str.parse() {
905                    Ok(v) => v,
906                    Err(_) => continue,
907                };
908                let packed = (iface << 16) | comp;
909                let key = iface_id_to_name
910                    .get(&iface)
911                    .map(|iface_name| format!("{}:{}", iface_name, name));
912                (packed, key, name.to_string())
913            } else if is_interface_pack {
914                let flat_id: i32 = match id_str.parse() {
915                    Ok(v) => v,
916                    Err(_) => continue,
917                };
918                if name.contains(':') {
919                    // Jordan component: `<flat_id>=<iface_name>:<comp_name>`
920                    (flat_id, Some(name.to_string()), name.to_string())
921                } else {
922                    // Root interface in either dialect
923                    (flat_id, None, name.to_string())
924                }
925            } else {
926                // Non-interface pack
927                let id: i32 = match id_str.parse() {
928                    Ok(v) => v,
929                    Err(_) => continue,
930                };
931                (id, None, name.to_string())
932            };
933
934        // In combined interface.pack: component entries register as Type::Component,
935        // interface roots register as Type::Interface.
936        let actual_type = if is_interface_pack && component_key.is_some() {
937            Type::Component
938        } else {
939            entity_type
940        };
941
942        // Normalize name matching TS SymbolTable.normalizeName for Basic symbols:
943        // name.toLowerCase().replace(/\s+/g, '_')
944        let normalized = register_name.to_lowercase().replace(' ', "_");
945        registry.register_entity_id(normalized, actual_type, idx);
946
947        if is_interface_pack && let Some(key) = component_key {
948            let normalized_key = if let Some((iface_part, comp_part)) = key.split_once(':') {
949                format!(
950                    "{}:{}",
951                    iface_part,
952                    crate::symbol::normalize_comp_name(comp_part)
953                )
954            } else {
955                key
956            };
957            registry.components.insert(normalized_key, idx);
958        }
959    }
960}
961
962/// Like `load_entity_ids` but only populates the typed entity map
963/// (no flat/untyped registration). Used to register obj.pack entries
964/// under a secondary type like `NamedObj`.
965fn load_entity_ids_typed_only(registry: &mut SymbolRegistry, path: &Path, entity_type: Type) {
966    let text = match fs::read_to_string(path) {
967        Ok(t) => t,
968        Err(_) => return,
969    };
970    for line in text.lines() {
971        let line = line.trim();
972        if line.is_empty() {
973            continue;
974        }
975        let (id_str, name) = match line.split_once('=') {
976            Some(pair) => pair,
977            None => continue,
978        };
979        let name = name.trim();
980        if name.is_empty() || name == "null" {
981            continue;
982        }
983        let id: i32 = match id_str.parse() {
984            Ok(v) => v,
985            Err(_) => continue,
986        };
987        let normalized = name.to_lowercase().replace(' ', "_");
988        registry.register_entity_id_typed_only(normalized, entity_type, id);
989    }
990}
991
992/// Register type-name identifiers as type-char constants.
993/// These are stored in a separate map (registry.type_chars) checked LAST in identifier
994/// resolution, so commands like `coord` take priority over the type name `coord`.
995fn register_type_chars(registry: &mut SymbolRegistry) {
996    let type_chars: &[(&str, i32)] = &[
997        ("int", b'i' as i32),     // 105
998        ("string", b's' as i32),  // 115
999        ("boolean", b'1' as i32), // 49
1000        ("bool", b'1' as i32),
1001        ("coord", b'c' as i32),     // 99
1002        ("loc", b'l' as i32),       // 108
1003        ("npc", b'n' as i32),       // 110
1004        ("obj", b'o' as i32),       // 111
1005        ("namedobj", b'O' as i32),  // 79
1006        ("playeruid", b'p' as i32), // 112
1007        ("player_uid", b'p' as i32),
1008        ("npcuid", b'u' as i32), // 117
1009        ("npc_uid", b'u' as i32),
1010        ("seq", b'A' as i32),       // 65
1011        ("spotanim", b't' as i32),  // 116
1012        ("synth", b'P' as i32),     // 80
1013        ("stat", b'S' as i32),      // 83
1014        ("component", b'I' as i32), // 73
1015        ("interface", b'a' as i32), // 97
1016        ("toplevelinterface", b'a' as i32),
1017        ("overlayinterface", b'a' as i32),
1018        ("inv", b'v' as i32),     // 118
1019        ("enum", b'g' as i32),    // 103
1020        ("struct", b'J' as i32),  // 74
1021        ("dbrow", 0xD0),          // 208
1022        ("dbtable", b'i' as i32), // treat as int
1023        ("dbcolumn", b'i' as i32),
1024        ("category", b'y' as i32), // 121
1025        ("varp", b'V' as i32),     // 86
1026        ("npc_stat", 0xFE),        // 254
1027        ("npcstat", 0xFE),
1028        ("idkit", b'K' as i32), // 75
1029        ("idk", b'K' as i32),
1030    ];
1031    for (name, val) in type_chars {
1032        registry.type_chars.insert(name.to_string(), *val);
1033    }
1034}
1035
1036/// Register engine-provided constants that the TS compiler passes via
1037/// CompilerTypeInfo objects built from engine enums/maps. These are
1038/// identical across all supported revisions (225-274+).
1039fn register_engine_constants(registry: &mut SymbolRegistry) {
1040    // NpcMode (from NpcModeMap in engine/src/engine/entity/NpcMode.ts)
1041    let npc_modes: &[(&str, i32)] = &[
1042        ("null", -1),
1043        ("none", 0),
1044        ("wander", 1),
1045        ("patrol", 2),
1046        ("playerescape", 3),
1047        ("playerfollow", 4),
1048        ("playerface", 5),
1049        ("playerfaceclose", 6),
1050        ("opplayer1", 7),
1051        ("opplayer2", 8),
1052        ("opplayer3", 9),
1053        ("opplayer4", 10),
1054        ("opplayer5", 11),
1055        ("applayer1", 12),
1056        ("applayer2", 13),
1057        ("applayer3", 14),
1058        ("applayer4", 15),
1059        ("applayer5", 16),
1060        ("oploc1", 17),
1061        ("oploc2", 18),
1062        ("oploc3", 19),
1063        ("oploc4", 20),
1064        ("oploc5", 21),
1065        ("aploc1", 22),
1066        ("aploc2", 23),
1067        ("aploc3", 24),
1068        ("aploc4", 25),
1069        ("aploc5", 26),
1070        ("opobj1", 27),
1071        ("opobj2", 28),
1072        ("opobj3", 29),
1073        ("opobj4", 30),
1074        ("opobj5", 31),
1075        ("apobj1", 32),
1076        ("apobj2", 33),
1077        ("apobj3", 34),
1078        ("apobj4", 35),
1079        ("apobj5", 36),
1080        ("opnpc1", 37),
1081        ("opnpc2", 38),
1082        ("opnpc3", 39),
1083        ("opnpc4", 40),
1084        ("opnpc5", 41),
1085        ("apnpc1", 42),
1086        ("apnpc2", 43),
1087        ("apnpc3", 44),
1088        ("apnpc4", 45),
1089        ("apnpc5", 46),
1090        ("queue1", 47),
1091        ("queue2", 48),
1092        ("queue3", 49),
1093        ("queue4", 50),
1094        ("queue5", 51),
1095        ("queue6", 52),
1096        ("queue7", 53),
1097        ("queue8", 54),
1098        ("queue9", 55),
1099        ("queue10", 56),
1100        ("queue11", 57),
1101        ("queue12", 58),
1102        ("queue13", 59),
1103        ("queue14", 60),
1104        ("queue15", 61),
1105        ("queue16", 62),
1106        ("queue17", 63),
1107        ("queue18", 64),
1108        ("queue19", 65),
1109        ("queue20", 66),
1110    ];
1111    // Many NpcMode names (oploc1-5, aploc1-5, opnpc1-5, apnpc1-5, opobj1-5,
1112    // apobj1-5, opplayer1-5, applayer1-5, queue1-20) collide with names in
1113    // the trigger table. Registering them as flat entity IDs would shadow
1114    // those trigger names whenever they appear in an untyped or Int-typed
1115    // expression context (e.g. `test_op(oploc1, ...)` — the compiler would
1116    // resolve `oploc1` to NpcMode 17 instead of the trigger byte 66).
1117    //
1118    // The non-colliding ones (null, none, wander, patrol, playerescape,
1119    // playerfollow, playerface, playerfaceclose) are registered into both
1120    // maps as before so bare-identifier resolution keeps working for them.
1121    fn is_trigger_collision(name: &str) -> bool {
1122        matches!(
1123            name,
1124            "oploc1"
1125                | "oploc2"
1126                | "oploc3"
1127                | "oploc4"
1128                | "oploc5"
1129                | "aploc1"
1130                | "aploc2"
1131                | "aploc3"
1132                | "aploc4"
1133                | "aploc5"
1134                | "opnpc1"
1135                | "opnpc2"
1136                | "opnpc3"
1137                | "opnpc4"
1138                | "opnpc5"
1139                | "apnpc1"
1140                | "apnpc2"
1141                | "apnpc3"
1142                | "apnpc4"
1143                | "apnpc5"
1144                | "opobj1"
1145                | "opobj2"
1146                | "opobj3"
1147                | "opobj4"
1148                | "opobj5"
1149                | "apobj1"
1150                | "apobj2"
1151                | "apobj3"
1152                | "apobj4"
1153                | "apobj5"
1154                | "opplayer1"
1155                | "opplayer2"
1156                | "opplayer3"
1157                | "opplayer4"
1158                | "opplayer5"
1159                | "applayer1"
1160                | "applayer2"
1161                | "applayer3"
1162                | "applayer4"
1163                | "applayer5"
1164                | "queue1"
1165                | "queue2"
1166                | "queue3"
1167                | "queue4"
1168                | "queue5"
1169                | "queue6"
1170                | "queue7"
1171                | "queue8"
1172                | "queue9"
1173                | "queue10"
1174                | "queue11"
1175                | "queue12"
1176                | "queue13"
1177                | "queue14"
1178                | "queue15"
1179                | "queue16"
1180                | "queue17"
1181                | "queue18"
1182                | "queue19"
1183                | "queue20"
1184        )
1185    }
1186    for &(name, id) in npc_modes {
1187        if is_trigger_collision(name) {
1188            registry.register_entity_id_typed_only(name.to_string(), Type::NpcMode, id);
1189        } else {
1190            registry.register_entity_id(name.to_string(), Type::NpcMode, id);
1191        }
1192    }
1193
1194    // NpcStat FIRST (lower priority — overlapping names will be overwritten by PlayerStat)
1195    let npc_stats: &[(&str, i32)] = &[
1196        ("attack", 0),
1197        ("defence", 1),
1198        ("strength", 2),
1199        ("hitpoints", 3),
1200        ("ranged", 4),
1201        ("magic", 5),
1202    ];
1203    for &(name, id) in npc_stats {
1204        registry.register_entity_id(name.to_string(), Type::NpcStat, id);
1205    }
1206
1207    // PlayerStat SECOND (higher priority — "magic"=6 overwrites npc_stat "magic"=5
1208    // in the flat entity_ids map, matching load_packs ordering)
1209    let stats: &[(&str, i32)] = &[
1210        ("attack", 0),
1211        ("defence", 1),
1212        ("strength", 2),
1213        ("hitpoints", 3),
1214        ("ranged", 4),
1215        ("prayer", 5),
1216        ("magic", 6),
1217        ("cooking", 7),
1218        ("woodcutting", 8),
1219        ("fletching", 9),
1220        ("fishing", 10),
1221        ("firemaking", 11),
1222        ("crafting", 12),
1223        ("smithing", 13),
1224        ("mining", 14),
1225        ("herblore", 15),
1226        ("agility", 16),
1227        ("thieving", 17),
1228        ("slayer", 18),
1229        ("stat18", 18),
1230        ("farming", 19),
1231        ("stat19", 19),
1232        ("runecraft", 20),
1233        ("hunter", 21),
1234        ("construction", 22),
1235        ("summoning", 23),
1236        ("dungeoneering", 24),
1237    ];
1238    for &(name, id) in stats {
1239        registry.register_entity_id(name.to_string(), Type::Stat, id);
1240    }
1241
1242    // Fontmetrics (both naming conventions: 225 uses short, 274 uses _full suffix)
1243    let fontmetrics: &[(&str, i32)] = &[
1244        ("p11", 0),
1245        ("p12", 1),
1246        ("b12", 2),
1247        ("q8", 3),
1248        ("p11_full", 0),
1249        ("p12_full", 1),
1250        ("b12_full", 2),
1251        ("q8_full", 3),
1252    ];
1253    for &(name, id) in fontmetrics {
1254        registry.register_entity_id(name.to_string(), Type::FontMetrics, id);
1255    }
1256
1257    // LocShape (from locshapeInfo in engine/tools/pack/Compiler.ts)
1258    let locshapes: &[(&str, i32)] = &[
1259        ("wall_straight", 0),
1260        ("wall_diagonalcorner", 1),
1261        ("wall_l", 2),
1262        ("wall_squarecorner", 3),
1263        ("walldecor_straight_nooffset", 4),
1264        ("walldecor_straight_offset", 5),
1265        ("walldecor_diagonal_offset", 6),
1266        ("walldecor_diagonal_nooffset", 7),
1267        ("walldecor_diagonal_both", 8),
1268        ("wall_diagonal", 9),
1269        ("centrepiece_straight", 10),
1270        ("centrepiece_diagonal", 11),
1271        ("roof_straight", 12),
1272        ("roof_diagonal_with_roofedge", 13),
1273        ("roof_diagonal", 14),
1274        ("roof_l_concave", 15),
1275        ("roof_l_convex", 16),
1276        ("roof_flat", 17),
1277        ("roofedge_straight", 18),
1278        ("roofedge_diagonalcorner", 19),
1279        ("roofedge_l", 20),
1280        ("roofedge_squarecorner", 21),
1281        ("grounddecor", 22),
1282    ];
1283    for &(name, id) in locshapes {
1284        registry.register_entity_id(name.to_string(), Type::LocShape, id);
1285    }
1286}
1287
1288#[cfg(test)]
1289mod tests {
1290    use super::*;
1291    use crate::symbol::SymbolRegistry;
1292    use crate::types::Type;
1293    use std::io::Write;
1294    use std::path::PathBuf;
1295
1296    fn write_temp_pack(name: &str, content: &str) -> PathBuf {
1297        let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1298            .join("target")
1299            .join("test-symloader");
1300        fs::create_dir_all(&dir).unwrap();
1301        let path = dir.join(name);
1302        let mut f = fs::File::create(&path).unwrap();
1303        f.write_all(content.as_bytes()).unwrap();
1304        path
1305    }
1306
1307    // ── 647-style pack ─────────────────────────────────────────────────
1308    // Format: `<iface_id>=<name>` for roots, `<iface_id>:<comp_id>=<comp_name>`
1309
1310    #[test]
1311    fn load_647_style_registers_components() {
1312        let pack = write_temp_pack(
1313            "interface_647.pack",
1314            "\
1315228=multi2\n\
1316228:0=com0\n\
1317228:1=com1\n\
1318228:2=com2\n\
1319228:3=com3\n\
1320228:6=thin_swords\n\
1321228:9=wide_swords\n",
1322        );
1323        let mut r = SymbolRegistry::new();
1324        load_entity_ids(&mut r, &pack, Type::Interface);
1325
1326        // Root interface registered
1327        assert_eq!(r.interface_ids.get("multi2"), Some(&228));
1328
1329        // Components use normalized keys (com0, not com_0)
1330        assert_eq!(r.lookup_component("multi2", "com0"), Some(228 << 16));
1331        assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1332        assert_eq!(r.lookup_component("multi2", "com3"), Some((228 << 16) | 3));
1333
1334        // Named components (no digits) are unaffected by normalization
1335        assert_eq!(
1336            r.lookup_component("multi2", "thin_swords"),
1337            Some((228 << 16) | 6)
1338        );
1339        assert_eq!(
1340            r.lookup_component("multi2", "wide_swords"),
1341            Some((228 << 16) | 9)
1342        );
1343    }
1344
1345    #[test]
1346    fn load_647_style_resolves_225_references() {
1347        let pack = write_temp_pack(
1348            "interface_647_cross.pack",
1349            "\
1350228=multi2\n\
1351228:0=com0\n\
1352228:1=com1\n\
1353228:2=com2\n",
1354        );
1355        let mut r = SymbolRegistry::new();
1356        load_entity_ids(&mut r, &pack, Type::Interface);
1357
1358        // 225-style references (com_0, com_1, com_2) resolve against 647 pack
1359        assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1360        assert_eq!(r.lookup_component("multi2", "com_1"), Some((228 << 16) | 1));
1361        assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1362    }
1363
1364    // ── 225-style pack ─────────────────────────────────────────────────
1365    // Format: `<flat_id>=<iface_name>` for roots, `<flat_id>=<iface_name>:<comp_name>`
1366
1367    #[test]
1368    fn load_225_style_registers_components() {
1369        let pack = write_temp_pack(
1370            "interface_225.pack",
1371            "\
13722459=multi2\n\
13732460=multi2:com_0\n\
13742461=multi2:com_1\n\
13752462=multi2:com_2\n\
13762463=multi2:com_4\n\
13772464=multi2:com_5\n",
1378        );
1379        let mut r = SymbolRegistry::new();
1380        load_entity_ids(&mut r, &pack, Type::Interface);
1381
1382        // Root interface registered
1383        assert_eq!(r.interface_ids.get("multi2"), Some(&2459));
1384
1385        // 225 references resolve (com_0 normalized to com0 at registration)
1386        assert_eq!(r.lookup_component("multi2", "com_0"), Some(2460));
1387        assert_eq!(r.lookup_component("multi2", "com_2"), Some(2462));
1388        assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1389    }
1390
1391    #[test]
1392    fn load_225_style_resolves_647_references() {
1393        let pack = write_temp_pack(
1394            "interface_225_cross.pack",
1395            "\
13962459=multi2\n\
13972460=multi2:com_0\n\
13982461=multi2:com_1\n\
13992462=multi2:com_2\n",
1400        );
1401        let mut r = SymbolRegistry::new();
1402        load_entity_ids(&mut r, &pack, Type::Interface);
1403
1404        // 647-style references (com0, com1, com2) resolve against 225 pack
1405        assert_eq!(r.lookup_component("multi2", "com0"), Some(2460));
1406        assert_eq!(r.lookup_component("multi2", "com1"), Some(2461));
1407        assert_eq!(r.lookup_component("multi2", "com2"), Some(2462));
1408    }
1409
1410    // ── Entity type correctness ────────────────────────────────────────
1411
1412    #[test]
1413    fn components_register_as_component_type() {
1414        let pack = write_temp_pack(
1415            "interface_types.pack",
1416            "\
1417228=multi2\n\
1418228:0=com0\n",
1419        );
1420        let mut r = SymbolRegistry::new();
1421        load_entity_ids(&mut r, &pack, Type::Interface);
1422
1423        // Root → Interface type, component → Component type
1424        assert!(
1425            r.lookup_entity_id_typed("multi2", Type::Interface)
1426                .is_some()
1427        );
1428        assert!(r.lookup_entity_id_typed("com0", Type::Component).is_some());
1429        assert!(r.lookup_entity_id_typed("com0", Type::Interface).is_none());
1430    }
1431}