Skip to main content

runec/
symloader.rs

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