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