1use crate::pointer::{PointerHolder, default_command_pointers};
2use crate::types::{BaseVarType, Type};
3use std::collections::{BTreeMap, HashMap, HashSet};
4use std::sync::Arc;
5
6pub(crate) fn normalize_entity_name(name: &str) -> std::borrow::Cow<'_, str> {
7 if name.is_ascii()
8 && !name
9 .bytes()
10 .any(|byte| byte.is_ascii_uppercase() || byte == b' ')
11 {
12 std::borrow::Cow::Borrowed(name)
13 } else {
14 std::borrow::Cow::Owned(name.to_lowercase().replace(' ', "_"))
15 }
16}
17
18#[derive(Debug, Clone)]
24pub struct LocalEntry {
25 pub name: String,
26 pub var_type: Type,
27 pub is_param: bool,
28 pub is_array: bool,
29}
30
31#[derive(Debug, Clone, Default)]
38pub struct LocalTable {
39 pub(crate) all: Vec<LocalEntry>,
40}
41
42impl LocalTable {
43 pub fn new() -> Self {
44 LocalTable { all: Vec::new() }
45 }
46
47 pub fn entries(&self) -> &[LocalEntry] {
49 &self.all
50 }
51
52 pub fn shrink_to_fit(&mut self) {
54 self.all.shrink_to_fit();
55 }
56
57 pub fn push_param(&mut self, name: String, param_type: Type) -> i32 {
58 let id = self.get_variable_id_for_next(param_type, false);
59 self.all.push(LocalEntry {
60 name,
61 var_type: param_type,
62 is_param: true,
63 is_array: false,
64 });
65 id
66 }
67
68 pub fn push_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
69 let id = self.get_variable_id_for_next(var_type, is_array);
70 self.all.push(LocalEntry {
71 name,
72 var_type,
73 is_param: false,
74 is_array,
75 });
76 id
77 }
78
79 fn get_variable_id_for_next(&self, var_type: Type, is_array: bool) -> i32 {
81 if is_array {
82 self.all.iter().filter(|e| e.is_array).count() as i32
83 } else {
84 self.all
85 .iter()
86 .filter(|e| {
87 e.var_type.base_type() == var_type.base_type() && (!e.is_array || e.is_param)
88 })
89 .count() as i32
90 }
91 }
92
93 pub fn get_variable_id(&self, index: usize) -> i32 {
95 let entry = &self.all[index];
96 if entry.is_array {
97 self.all[..index].iter().filter(|e| e.is_array).count() as i32
98 } else {
99 self.all[..index]
100 .iter()
101 .filter(|e| {
102 e.var_type.base_type() == entry.var_type.base_type()
103 && (!e.is_array || e.is_param)
104 })
105 .count() as i32
106 }
107 }
108
109 pub fn get_local_count(&self, base: BaseVarType) -> u16 {
111 self.all
112 .iter()
113 .filter(|e| e.var_type.base_type() == base && (!e.is_array || e.is_param))
114 .count() as u16
115 }
116
117 pub fn get_param_count(&self, base: BaseVarType) -> u16 {
119 self.all
120 .iter()
121 .filter(|e| e.is_param && e.var_type.base_type() == base)
122 .count() as u16
123 }
124}
125
126#[derive(Debug, Clone)]
130pub enum SymbolKind {
131 LocalVar {
133 var_type: Type,
134 slot: i32,
136 is_array: bool,
137 },
138 ScriptParam { param_type: Type, slot: i32 },
140 Script {
142 id: i32,
143 trigger: String,
144 param_types: Vec<Type>,
145 return_types: Vec<Type>,
146 },
147 GameVar {
149 var_type: Type,
150 var_id: i32,
151 category: String,
153 },
154 Constant {
156 const_type: Type,
157 int_value: Option<i32>,
158 string_value: Option<String>,
159 },
160 Command {
162 opcode: i32,
163 param_types: Vec<Type>,
164 return_types: Vec<Type>,
165 },
166}
167
168impl SymbolKind {
169 pub fn kind_name(&self) -> &'static str {
170 match self {
171 SymbolKind::LocalVar { .. } => "LocalVar",
172 SymbolKind::ScriptParam { .. } => "ScriptParam",
173 SymbolKind::Script { .. } => "Script",
174 SymbolKind::GameVar { .. } => "GameVar",
175 SymbolKind::Constant { .. } => "Constant",
176 SymbolKind::Command { .. } => "Command",
177 }
178 }
179}
180
181#[derive(Debug, Clone)]
183pub struct Symbol {
184 pub name: String,
185 pub kind: SymbolKind,
186}
187
188#[derive(Debug, Clone, Copy)]
194pub struct EntityRef {
195 pub const_type: Type,
196 pub id: i32,
197}
198
199#[derive(Debug, Clone, Default)]
204pub(crate) struct EntityEntry {
205 pub(crate) primary: Option<EntityRef>,
208 pub(crate) variants: Vec<(Type, i32)>,
211}
212
213impl EntityEntry {
214 fn set_variant(&mut self, entity_type: Type, id: i32) {
216 if let Some(slot) = self.variants.iter_mut().find(|(t, _)| *t == entity_type) {
217 slot.1 = id;
218 } else {
219 self.variants.push((entity_type, id));
220 }
221 }
222}
223
224#[derive(Debug, Clone)]
226pub struct SymbolTable {
227 symbols: HashMap<String, Symbol>,
229 parent: Option<Box<SymbolTable>>,
231 next_int_local: i32,
233 next_string_local: i32,
234 next_long_local: i32,
235 total_int_decls: i32,
238 total_string_decls: i32,
239 total_long_decls: i32,
240}
241
242impl Default for SymbolTable {
243 fn default() -> Self {
244 Self::new()
245 }
246}
247
248impl SymbolTable {
249 pub fn new() -> Self {
250 SymbolTable {
251 symbols: HashMap::new(),
252 parent: None,
253 next_int_local: 0,
254 next_string_local: 0,
255 next_long_local: 0,
256 total_int_decls: 0,
257 total_string_decls: 0,
258 total_long_decls: 0,
259 }
260 }
261
262 pub fn child(parent: SymbolTable) -> Self {
264 let int_local = parent.next_int_local;
265 let string_local = parent.next_string_local;
266 let long_local = parent.next_long_local;
267 let int_decls = parent.total_int_decls;
268 let string_decls = parent.total_string_decls;
269 let long_decls = parent.total_long_decls;
270 SymbolTable {
271 symbols: HashMap::new(),
272 parent: Some(Box::new(parent)),
273 next_int_local: int_local,
274 next_string_local: string_local,
275 next_long_local: long_local,
276 total_int_decls: int_decls,
277 total_string_decls: string_decls,
278 total_long_decls: long_decls,
279 }
280 }
281
282 pub fn new_child(&self) -> Self {
284 SymbolTable {
285 symbols: HashMap::new(),
286 parent: Some(Box::new(self.clone())),
287 next_int_local: self.next_int_local,
288 next_string_local: self.next_string_local,
289 next_long_local: self.next_long_local,
290 total_int_decls: self.total_int_decls,
291 total_string_decls: self.total_string_decls,
292 total_long_decls: self.total_long_decls,
293 }
294 }
295
296 pub fn define(&mut self, name: String, kind: SymbolKind) {
298 self.symbols.insert(name.clone(), Symbol { name, kind });
299 }
300
301 pub fn define_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
305 if !is_array {
307 match var_type.base_type() {
308 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
309 crate::types::BaseVarType::String => self.total_string_decls += 1,
310 crate::types::BaseVarType::Long => self.total_long_decls += 1,
311 }
312 }
313 let new_slot = self.allocate_slot(&var_type);
319 let slot = if let Some(existing) = self.symbols.get(&name) {
320 match &existing.kind {
321 SymbolKind::LocalVar { slot, .. } => *slot,
322 _ => new_slot,
323 }
324 } else {
325 new_slot
326 };
327 self.define(
328 name,
329 SymbolKind::LocalVar {
330 var_type,
331 slot,
332 is_array,
333 },
334 );
335 slot
336 }
337
338 pub fn define_param(&mut self, name: String, param_type: Type) -> i32 {
340 match param_type.base_type() {
341 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
342 crate::types::BaseVarType::String => self.total_string_decls += 1,
343 crate::types::BaseVarType::Long => self.total_long_decls += 1,
344 }
345 let slot = self.allocate_slot(¶m_type);
346 self.define(name, SymbolKind::ScriptParam { param_type, slot });
347 slot
348 }
349
350 fn allocate_slot(&mut self, var_type: &Type) -> i32 {
352 match var_type.base_type() {
353 crate::types::BaseVarType::Integer => {
354 let slot = self.next_int_local;
355 self.next_int_local += 1;
356 slot
357 }
358 crate::types::BaseVarType::String => {
359 let slot = self.next_string_local;
360 self.next_string_local += 1;
361 slot
362 }
363 crate::types::BaseVarType::Long => {
364 let slot = self.next_long_local;
365 self.next_long_local += 1;
366 slot
367 }
368 }
369 }
370
371 pub fn lookup(&self, name: &str) -> Option<&Symbol> {
373 if let Some(sym) = self.symbols.get(name) {
374 return Some(sym);
375 }
376 if let Some(parent) = &self.parent {
377 return parent.lookup(name);
378 }
379 None
380 }
381
382 pub fn lookup_local(&self, name: &str) -> Option<&Symbol> {
384 self.symbols.get(name)
385 }
386
387 pub fn contains(&self, name: &str) -> bool {
389 self.lookup(name).is_some()
390 }
391
392 pub fn save_slots(&self) -> (i32, i32, i32) {
394 (
395 self.next_int_local,
396 self.next_string_local,
397 self.next_long_local,
398 )
399 }
400
401 pub fn restore_slots(&mut self, saved: (i32, i32, i32)) {
405 self.next_int_local = saved.0;
406 self.next_string_local = saved.1;
407 self.next_long_local = saved.2;
408 }
409
410 pub fn merge_slots(&mut self, other: (i32, i32, i32)) {
413 self.next_int_local = self.next_int_local.max(other.0);
414 self.next_string_local = self.next_string_local.max(other.1);
415 self.next_long_local = self.next_long_local.max(other.2);
416 }
417
418 pub fn merge_decls(&mut self, child: &SymbolTable) {
420 self.total_int_decls = child.total_int_decls;
421 self.total_string_decls = child.total_string_decls;
422 self.total_long_decls = child.total_long_decls;
423 }
424
425 pub fn int_local_count(&self) -> u16 {
427 self.total_int_decls as u16
428 }
429
430 pub fn string_local_count(&self) -> u16 {
432 self.total_string_decls as u16
433 }
434
435 pub fn long_local_count(&self) -> u16 {
437 self.total_long_decls as u16
438 }
439
440 pub fn reset_locals(&mut self) {
442 self.next_int_local = 0;
443 self.next_string_local = 0;
444 self.next_long_local = 0;
445 }
446
447 pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
449 self.symbols.iter()
450 }
451}
452
453#[derive(Debug, Clone)]
461pub struct SymbolRegistry {
462 pub(crate) profile: Option<Arc<crate::environment::EngineProfile>>,
463 pub(crate) visibility: Arc<crate::sources::Visibility>,
464 pub(crate) dynamic_returns: HashMap<String, ReturnType>,
465 pub(crate) param_types: HashMap<i32, Type>,
466 pub(crate) stack_commands: HashSet<String>,
467 component_first_commands: HashSet<String>,
468 command_pointer_overrides: HashMap<String, PointerHolder>,
469 switch_domains: HashMap<Type, BTreeMap<i32, String>>,
470 pub(crate) stack_scripts: HashSet<String>,
471 pub(crate) hook_commands: HashMap<String, bool>,
472 pub(crate) scripts: HashMap<String, Arc<Symbol>>,
476 pub(crate) commands: HashMap<String, Symbol>,
478 pub(crate) game_vars: HashMap<String, Symbol>,
480 pub(crate) constants: HashMap<String, Symbol>,
482 pub(crate) entity_ids: HashMap<String, EntityEntry>,
488 pub(crate) command_param_types: HashMap<String, Vec<Type>>,
491 pub(crate) type_chars: HashMap<String, i32>,
494 pub(crate) script_ids: HashMap<String, i32>,
496 pub(crate) proc_script_ids: HashMap<String, i32>,
498 pub(crate) label_script_ids: HashMap<String, i32>,
500 pub(crate) trigger_script_ids: HashMap<String, i32>,
503 pub(crate) scripts_by_trigger: HashMap<String, Arc<Symbol>>,
508 pub(crate) preloaded_script_ids: HashMap<String, i32>,
510 pub(crate) dbcolumn_types: HashMap<String, Vec<Type>>,
513 pub(crate) components: HashMap<String, i32>,
515 pub(crate) interface_ids: HashMap<String, i32>,
517 pub(crate) test_scripts: HashSet<String>,
519 pub(crate) client_script_params: HashMap<String, Vec<Type>>,
521 pub(crate) next_script_id: i32,
522}
523
524impl Default for SymbolRegistry {
525 fn default() -> Self {
526 Self::new()
527 }
528}
529
530#[derive(Debug, Clone, Copy)]
531pub enum ReturnType {
532 TypeArgument(usize),
533 ParamArgument(usize),
534}
535
536impl SymbolRegistry {
537 pub fn set_engine_profile(&mut self, profile: crate::environment::EngineProfile) {
538 self.command_pointer_overrides.clear();
539 self.profile = Some(Arc::new(profile));
540 }
541
542 pub fn trigger(&self, name: &str) -> Option<crate::environment::Trigger> {
543 if let Some(profile) = &self.profile {
544 return profile.triggers.get(name).cloned();
545 }
546 crate::trigger_table::is_valid_trigger(name).then(|| crate::environment::Trigger {
547 byte: crate::trigger_table::byte(name),
548 subject_type: crate::trigger_table::subject_type(name),
549 validates_subject: crate::trigger_table::validates_subject(name),
550 is_button: crate::trigger_table::is_button(name),
551 allows_returns: crate::trigger_table::allows_returns(name),
552 })
553 }
554
555 pub fn set_visibility(&mut self, mut visibility: crate::sources::Visibility) {
556 visibility.index_registry(self);
557 self.visibility = Arc::new(visibility);
558 }
559
560 pub fn set_script_id(&mut self, trigger: &str, name: &str, id: i32) {
562 self.preloaded_script_ids
563 .insert(format!("{trigger}:{name}"), id);
564 self.next_script_id = self.next_script_id.max(id + 1);
565 }
566
567 pub fn set_stack_script(&mut self, trigger: &str, name: &str) {
569 self.stack_scripts.insert(format!("{trigger}:{name}"));
570 }
571
572 pub fn component_first_command(&self, name: &str) -> bool {
573 let name = name.trim_start_matches('.');
574 self.stack_commands.contains(name) && self.component_first_commands.contains(name)
575 }
576
577 pub fn set_command_suspends(&mut self, name: &str, suspends: bool) {
578 if let Some(profile) = &mut self.profile {
579 Arc::make_mut(profile)
580 .command_pointers
581 .entry(name.to_owned())
582 .or_default()
583 .may_suspend = suspends;
584 } else {
585 self.command_pointer_overrides
586 .entry(name.to_owned())
587 .or_insert_with(|| {
588 default_command_pointers()
589 .get(name)
590 .cloned()
591 .unwrap_or_default()
592 })
593 .may_suspend = suspends;
594 }
595 }
596
597 pub fn command_suspends(&self, name: &str) -> bool {
598 self.command_suspends_for(name, true)
599 }
600
601 pub(crate) fn command_suspends_for(&self, name: &str, server: bool) -> bool {
602 let primary = name.trim_start_matches('.');
603 let lookup = |pointers: &HashMap<String, PointerHolder>| {
604 pointers
605 .get(name)
606 .or_else(|| pointers.get(primary))
607 .map(|holder| holder.may_suspend)
608 };
609 if let Some(profile) = &self.profile {
610 lookup(&profile.command_pointers).unwrap_or(false)
611 } else {
612 lookup(&self.command_pointer_overrides)
613 .or_else(|| server.then(|| lookup(default_command_pointers())).flatten())
614 .unwrap_or(false)
615 }
616 }
617
618 pub fn set_switch_values(&mut self, ty: Type, values: impl IntoIterator<Item = (i32, String)>) {
620 self.switch_domains.insert(ty, values.into_iter().collect());
621 }
622
623 pub fn switch_values(&self, ty: Type) -> Option<&BTreeMap<i32, String>> {
624 self.switch_domains
625 .get(&ty)
626 .filter(|values| !values.is_empty())
627 }
628
629 pub fn set_component_first_command(&mut self, name: &str, component_first: bool) {
630 let name = name.trim_start_matches('.');
631 if component_first {
632 self.component_first_commands.insert(name.to_owned());
633 } else {
634 self.component_first_commands.remove(name);
635 }
636 }
637
638 pub(crate) fn clear_commands(&mut self) {
639 self.commands.clear();
640 self.command_param_types.clear();
641 self.stack_commands.clear();
642 self.component_first_commands.clear();
643 self.command_pointer_overrides.clear();
644 self.hook_commands.clear();
645 self.dynamic_returns.clear();
646 }
647
648 pub fn set_command_behavior(
649 &mut self,
650 name: &str,
651 stack: bool,
652 hook: Option<bool>,
653 returns: Option<ReturnType>,
654 ) {
655 if stack {
656 self.stack_commands.insert(name.to_owned());
657 } else {
658 self.stack_commands.remove(name);
659 self.component_first_commands.remove(name);
660 }
661 if let Some(explicit_component) = hook {
662 self.hook_commands
663 .insert(name.to_owned(), explicit_component);
664 } else {
665 self.hook_commands.remove(name);
666 }
667 if let Some(returns) = returns {
668 self.dynamic_returns.insert(name.to_owned(), returns);
669 } else {
670 self.dynamic_returns.remove(name);
671 }
672 }
673
674 pub fn commands(&self) -> impl Iterator<Item = (&str, &Symbol)> {
675 self.commands
676 .iter()
677 .map(|(name, symbol)| (name.as_str(), symbol))
678 }
679
680 pub fn constants(&self) -> impl Iterator<Item = (&str, &Symbol)> {
681 self.constants
682 .iter()
683 .map(|(name, symbol)| (name.as_str(), symbol))
684 }
685
686 pub(crate) fn remove_script(&mut self, trigger: &str, name: &str) {
687 self.scripts_by_trigger.remove(&format!("{trigger}:{name}"));
688 self.scripts.remove(name);
689 self.stack_scripts.remove(&format!("{trigger}:{name}"));
690 self.test_scripts.remove(&format!("{trigger}:{name}"));
691 if trigger == "proc" {
692 self.proc_script_ids.remove(name);
693 }
694 if trigger == "label" {
695 self.label_script_ids.remove(name);
696 }
697 }
698
699 pub fn load_visibility(&mut self, source_dir: &std::path::Path) {
701 self.visibility = Arc::new(crate::sources::Visibility::load(source_dir, self));
702 }
703
704 pub fn game_variables(&self) -> impl Iterator<Item = (&str, &Symbol)> {
705 self.game_vars
706 .iter()
707 .map(|(name, symbol)| (name.as_str(), symbol))
708 }
709
710 pub fn new() -> Self {
711 SymbolRegistry {
712 profile: None,
713 visibility: Arc::default(),
714 dynamic_returns: HashMap::new(),
715 param_types: HashMap::new(),
716 stack_commands: HashSet::new(),
717 component_first_commands: HashSet::new(),
718 command_pointer_overrides: HashMap::new(),
719 switch_domains: HashMap::from([
720 (
721 Type::Boolean,
722 [(0, "false".into()), (1, "true".into())].into(),
723 ),
724 (Type::IntBool, [(0, "0".into()), (1, "1".into())].into()),
725 ]),
726 stack_scripts: HashSet::new(),
727 hook_commands: HashMap::new(),
728 scripts: HashMap::new(),
729 commands: HashMap::new(),
730 game_vars: HashMap::new(),
731 constants: HashMap::new(),
732 entity_ids: HashMap::new(),
733 command_param_types: HashMap::new(),
734 type_chars: HashMap::new(),
735 script_ids: HashMap::new(),
736 proc_script_ids: HashMap::new(),
737 label_script_ids: HashMap::new(),
738 trigger_script_ids: HashMap::new(),
739 scripts_by_trigger: HashMap::new(),
740 preloaded_script_ids: HashMap::new(),
741 dbcolumn_types: HashMap::new(),
742 components: HashMap::new(),
743 interface_ids: HashMap::new(),
744 test_scripts: HashSet::new(),
745 client_script_params: HashMap::new(),
746 next_script_id: 0,
747 }
748 }
749
750 pub fn register_clientscript(&mut self, name: String, id: i32, params: Vec<Type>) {
751 self.trigger_script_ids
752 .insert(format!("clientscript:{name}"), id);
753 self.client_script_params.insert(name, params);
754 }
755
756 pub fn register_script(
758 &mut self,
759 name: String,
760 trigger: String,
761 param_types: Vec<Type>,
762 return_types: Vec<Type>,
763 ) -> i32 {
764 let key = format!("{}:{}", trigger, name);
765 let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
766 preloaded
767 } else {
768 let id = self.next_script_id;
769 self.next_script_id += 1;
770 id
771 };
772
773 if trigger == "proc" {
777 self.proc_script_ids.insert(name.clone(), id);
778 } else if trigger == "label" {
779 self.label_script_ids.insert(name.clone(), id);
780 }
781 let symbol = Arc::new(Symbol {
785 name: name.clone(),
786 kind: SymbolKind::Script {
787 id,
788 trigger,
789 param_types,
790 return_types,
791 },
792 });
793 self.scripts_by_trigger.insert(key, Arc::clone(&symbol));
794 self.scripts.insert(name, symbol);
795
796 id
797 }
798
799 pub fn register_command(
801 &mut self,
802 name: String,
803 opcode: i32,
804 param_types: Vec<Type>,
805 return_types: Vec<Type>,
806 ) {
807 self.component_first_commands.remove(&name);
808 self.command_pointer_overrides.remove(&name);
809 self.command_param_types
810 .insert(name.clone(), param_types.clone());
811 self.commands.insert(
812 name.clone(),
813 Symbol {
814 name,
815 kind: SymbolKind::Command {
816 opcode,
817 param_types,
818 return_types,
819 },
820 },
821 );
822 }
823
824 pub fn register_param_type(&mut self, id: i32, ty: Type) {
825 self.param_types.insert(id, ty);
826 }
827
828 pub fn register_game_var(
830 &mut self,
831 name: String,
832 var_type: Type,
833 var_id: i32,
834 category: String,
835 ) {
836 self.game_vars.insert(
837 name.clone(),
838 Symbol {
839 name,
840 kind: SymbolKind::GameVar {
841 var_type,
842 var_id,
843 category,
844 },
845 },
846 );
847 }
848
849 pub fn register_constant(
851 &mut self,
852 name: String,
853 const_type: Type,
854 int_value: Option<i32>,
855 string_value: Option<String>,
856 ) {
857 self.constants.insert(
858 name.clone(),
859 Symbol {
860 name,
861 kind: SymbolKind::Constant {
862 const_type,
863 int_value,
864 string_value,
865 },
866 },
867 );
868 }
869
870 pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
874 let entry = self.entity_ids.entry(name).or_default();
875 entry.primary = Some(EntityRef {
877 const_type: entity_type,
878 id,
879 });
880 entry.set_variant(entity_type, id);
881 }
882
883 pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
893 self.entity_ids
894 .entry(name)
895 .or_default()
896 .set_variant(entity_type, id);
897 }
898
899 pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
903 let normalized = normalize_entity_name(name);
904 self.entity_ids
905 .get(normalized.as_ref())
906 .and_then(|e| e.variants.iter().find(|(t, _)| *t == expected))
907 .map(|(_, id)| *id)
908 }
909
910 pub fn lookup_reference(&self, name: &str, expected: Type) -> Option<i32> {
911 match expected {
912 Type::Component => name
913 .split_once(':')
914 .and_then(|(iface, com)| self.lookup_component(iface, com))
915 .or_else(|| self.lookup_entity_id_typed(name, expected)),
916 Type::ClientScript => self
917 .script_id_for_trigger("clientscript", name)
918 .or_else(|| self.script_id_for_trigger("proc", name)),
919 Type::Proc => self.proc_script_id(name),
920 Type::Model | Type::Texture | Type::Category => {
922 self.lookup_entity_id_typed(name, expected).or_else(|| {
923 name.strip_prefix(expected.name())?
924 .strip_prefix('_')?
925 .parse::<i32>()
926 .ok()
927 .filter(|id| *id >= 0)
928 })
929 }
930 Type::Varp
931 | Type::Varn
932 | Type::Vars
933 | Type::Varbit
934 | Type::Varc
935 | Type::VarCon
936 | Type::VarConBit
937 | Type::VarClanSetting => self.lookup_game_var(name).and_then(|symbol| {
938 if let SymbolKind::GameVar {
939 var_id, category, ..
940 } = &symbol.kind
941 && match expected {
942 Type::Varc => matches!(category.as_str(), "varc" | "varcstr"),
943 Type::VarClanSetting => category.starts_with("clansetting_"),
944 _ => category == expected.name(),
945 }
946 {
947 Some(*var_id)
948 } else {
949 None
950 }
951 }),
952 _ => self.lookup_entity_id_typed(name, expected),
953 }
954 }
955
956 pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
958 self.scripts.get(name).map(|s| s.as_ref())
959 }
960
961 pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
963 if let Some(symbol) = self.scripts.get(name)
964 && matches!(&symbol.kind, SymbolKind::Script { trigger: found, .. } if found == trigger)
965 {
966 return Some(symbol);
967 }
968 self.scripts_by_trigger
969 .get(&format!("{}:{}", trigger, name))
970 .map(|s| s.as_ref())
971 }
972
973 pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
975 self.commands.get(name)
976 }
977
978 pub(crate) fn command_fills(&self, name: &str, hint: Option<Type>) -> bool {
981 hint.is_some_and(|h| h.base_type() != BaseVarType::Integer)
982 && self.commands.contains_key(name)
983 }
984
985 pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
987 self.game_vars.get(name)
988 }
989
990 pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
992 self.constants.get(name)
993 }
994
995 pub fn integer_constant_name(&self, value: i32, prefix: &str) -> Option<&str> {
996 self.constants.values().filter(|symbol| symbol.name.starts_with(prefix)).filter_map(|symbol| {
997 matches!(&symbol.kind, SymbolKind::Constant { int_value: Some(id), .. } if *id == value)
998 .then_some(symbol.name.as_str())
999 }).min()
1000 }
1001
1002 pub fn lookup_entity_id(&self, name: &str) -> Option<EntityRef> {
1005 let normalized = normalize_entity_name(name);
1006 self.entity_ids
1007 .get(normalized.as_ref())
1008 .and_then(|e| e.primary)
1009 }
1010
1011 pub(crate) fn drop_registration_scratch(&mut self) {
1016 self.preloaded_script_ids = HashMap::new();
1017 }
1018
1019 pub fn script_id(&self, name: &str) -> Option<i32> {
1025 if let Some(s) = self.scripts.get(name)
1026 && let SymbolKind::Script { id, .. } = &s.kind
1027 {
1028 return Some(*id);
1029 }
1030 self.script_ids.get(name).copied()
1031 }
1032
1033 pub fn proc_script_id(&self, name: &str) -> Option<i32> {
1035 self.proc_script_ids.get(name).copied()
1036 }
1037
1038 pub fn label_script_id(&self, name: &str) -> Option<i32> {
1040 self.label_script_ids.get(name).copied()
1041 }
1042
1043 pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
1044 let key = format!("{}:{}", trigger, name);
1045 if let Some(s) = self.scripts_by_trigger.get(&key)
1046 && let SymbolKind::Script { id, .. } = &s.kind
1047 {
1048 return Some(*id);
1049 }
1050 self.trigger_script_ids
1053 .get(&key)
1054 .or_else(|| self.preloaded_script_ids.get(&key))
1055 .copied()
1056 }
1057
1058 pub fn command_opcode(&self, name: &str) -> Option<i32> {
1059 self.commands.get(name).and_then(|sym| {
1060 if let SymbolKind::Command { opcode, .. } = &sym.kind {
1061 Some(*opcode)
1062 } else {
1063 None
1064 }
1065 })
1066 }
1067
1068 pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
1069 self.test_scripts.insert(format!("{}:{}", trigger, name));
1070 }
1071
1072 pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
1073 self.test_scripts.contains(&format!("{}:{}", trigger, name))
1074 }
1075
1076 pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
1081 let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
1082 self.components.get(&key).copied()
1083 }
1084}
1085
1086pub fn identifier_form(name: &str) -> String {
1090 name.trim()
1091 .chars()
1092 .map(|c| {
1093 if c.is_ascii_alphanumeric() || c == '_' {
1094 c
1095 } else {
1096 '_'
1097 }
1098 })
1099 .collect()
1100}
1101
1102pub(crate) fn normalize_comp_name(name: &str) -> String {
1105 let bytes = name.as_bytes();
1106 let mut out = Vec::with_capacity(bytes.len());
1107 let mut i = 0;
1108 while i < bytes.len() {
1109 if bytes[i] == b'_'
1110 && i > 0
1111 && bytes[i - 1].is_ascii_alphabetic()
1112 && i + 1 < bytes.len()
1113 && bytes[i + 1].is_ascii_digit()
1114 {
1115 i += 1;
1116 continue;
1117 }
1118 out.push(bytes[i]);
1119 i += 1;
1120 }
1121 unsafe { String::from_utf8_unchecked(out) }
1122}
1123
1124#[cfg(test)]
1125mod tests {
1126 use super::*;
1127
1128 #[test]
1131 fn normalize_strips_underscore_before_digits() {
1132 assert_eq!(normalize_comp_name("com_2"), "com2");
1133 assert_eq!(normalize_comp_name("com_10"), "com10");
1134 assert_eq!(normalize_comp_name("com_0"), "com0");
1135 }
1136
1137 #[test]
1138 fn normalize_preserves_already_compact_names() {
1139 assert_eq!(normalize_comp_name("com2"), "com2");
1140 assert_eq!(normalize_comp_name("com10"), "com10");
1141 assert_eq!(normalize_comp_name("com0"), "com0");
1142 }
1143
1144 #[test]
1145 fn normalize_preserves_non_digit_underscores() {
1146 assert_eq!(normalize_comp_name("close_button"), "close_button");
1147 assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
1148 assert_eq!(normalize_comp_name("title"), "title");
1149 }
1150
1151 #[test]
1152 fn normalize_only_strips_alpha_digit_boundary() {
1153 assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
1155 assert_eq!(normalize_comp_name("3_panel"), "3_panel");
1157 }
1158
1159 fn registry_647_style() -> SymbolRegistry {
1162 let mut r = SymbolRegistry::new();
1163 r.interface_ids.insert("multi2".into(), 228);
1164 for i in 0..10 {
1166 let key = format!("multi2:com{}", i);
1167 r.components.insert(key, (228 << 16) | i);
1168 }
1169 r
1170 }
1171
1172 #[test]
1173 fn lookup_647_pack_with_647_reference() {
1174 let r = registry_647_style();
1175 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1177 assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
1178 }
1179
1180 #[test]
1181 fn lookup_647_pack_with_225_reference() {
1182 let r = registry_647_style();
1183 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1185 assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
1186 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1187 }
1188
1189 fn registry_225_style() -> SymbolRegistry {
1192 let mut r = SymbolRegistry::new();
1193 r.interface_ids.insert("multi2".into(), 228);
1194 for i in 0..10 {
1197 let key = format!("multi2:com{}", i);
1198 r.components.insert(key, 2459 + i);
1199 }
1200 r
1201 }
1202
1203 #[test]
1204 fn lookup_225_pack_with_225_reference() {
1205 let r = registry_225_style();
1206 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
1207 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1208 }
1209
1210 #[test]
1211 fn lookup_225_pack_with_647_reference() {
1212 let r = registry_225_style();
1213 assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
1214 assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
1215 }
1216
1217 #[test]
1220 fn lookup_returns_none_for_unknown_component() {
1221 let r = registry_647_style();
1222 assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
1223 assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
1224 }
1225}