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