1use crate::types::{BaseVarType, Type};
2use std::collections::{HashMap, HashSet};
3use std::sync::Arc;
4
5pub(crate) fn normalize_entity_name(name: &str) -> std::borrow::Cow<'_, str> {
6 if name.is_ascii()
7 && !name
8 .bytes()
9 .any(|byte| byte.is_ascii_uppercase() || byte == b' ')
10 {
11 std::borrow::Cow::Borrowed(name)
12 } else {
13 std::borrow::Cow::Owned(name.to_lowercase().replace(' ', "_"))
14 }
15}
16
17#[derive(Debug, Clone)]
23pub struct LocalEntry {
24 pub name: String,
25 pub var_type: Type,
26 pub is_param: bool,
27 pub is_array: bool,
28}
29
30#[derive(Debug, Clone, Default)]
37pub struct LocalTable {
38 pub(crate) all: Vec<LocalEntry>,
39}
40
41impl LocalTable {
42 pub fn new() -> Self {
43 LocalTable { all: Vec::new() }
44 }
45
46 pub fn entries(&self) -> &[LocalEntry] {
48 &self.all
49 }
50
51 pub fn shrink_to_fit(&mut self) {
53 self.all.shrink_to_fit();
54 }
55
56 pub fn push_param(&mut self, name: String, param_type: Type) -> i32 {
57 let id = self.get_variable_id_for_next(param_type, false);
58 self.all.push(LocalEntry {
59 name,
60 var_type: param_type,
61 is_param: true,
62 is_array: false,
63 });
64 id
65 }
66
67 pub fn push_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
68 let id = self.get_variable_id_for_next(var_type, is_array);
69 self.all.push(LocalEntry {
70 name,
71 var_type,
72 is_param: false,
73 is_array,
74 });
75 id
76 }
77
78 fn get_variable_id_for_next(&self, var_type: Type, is_array: bool) -> i32 {
80 if is_array {
81 self.all.iter().filter(|e| e.is_array).count() as i32
82 } else {
83 self.all
84 .iter()
85 .filter(|e| {
86 e.var_type.base_type() == var_type.base_type() && (!e.is_array || e.is_param)
87 })
88 .count() as i32
89 }
90 }
91
92 pub fn get_variable_id(&self, index: usize) -> i32 {
94 let entry = &self.all[index];
95 if entry.is_array {
96 self.all[..index].iter().filter(|e| e.is_array).count() as i32
97 } else {
98 self.all[..index]
99 .iter()
100 .filter(|e| {
101 e.var_type.base_type() == entry.var_type.base_type()
102 && (!e.is_array || e.is_param)
103 })
104 .count() as i32
105 }
106 }
107
108 pub fn get_local_count(&self, base: BaseVarType) -> u16 {
110 self.all
111 .iter()
112 .filter(|e| e.var_type.base_type() == base && (!e.is_array || e.is_param))
113 .count() as u16
114 }
115
116 pub fn get_param_count(&self, base: BaseVarType) -> u16 {
118 self.all
119 .iter()
120 .filter(|e| e.is_param && e.var_type.base_type() == base)
121 .count() as u16
122 }
123}
124
125#[derive(Debug, Clone)]
129pub enum SymbolKind {
130 LocalVar {
132 var_type: Type,
133 slot: i32,
135 is_array: bool,
136 },
137 ScriptParam { param_type: Type, slot: i32 },
139 Script {
141 id: i32,
142 trigger: String,
143 param_types: Vec<Type>,
144 return_types: Vec<Type>,
145 },
146 GameVar {
148 var_type: Type,
149 var_id: i32,
150 category: String,
152 },
153 Constant {
155 const_type: Type,
156 int_value: Option<i32>,
157 string_value: Option<String>,
158 },
159 Command {
161 opcode: i32,
162 param_types: Vec<Type>,
163 return_types: Vec<Type>,
164 },
165}
166
167impl SymbolKind {
168 pub fn kind_name(&self) -> &'static str {
169 match self {
170 SymbolKind::LocalVar { .. } => "LocalVar",
171 SymbolKind::ScriptParam { .. } => "ScriptParam",
172 SymbolKind::Script { .. } => "Script",
173 SymbolKind::GameVar { .. } => "GameVar",
174 SymbolKind::Constant { .. } => "Constant",
175 SymbolKind::Command { .. } => "Command",
176 }
177 }
178}
179
180#[derive(Debug, Clone)]
182pub struct Symbol {
183 pub name: String,
184 pub kind: SymbolKind,
185}
186
187#[derive(Debug, Clone, Copy)]
193pub struct EntityRef {
194 pub const_type: Type,
195 pub id: i32,
196}
197
198#[derive(Debug, Clone, Default)]
203pub(crate) struct EntityEntry {
204 pub(crate) primary: Option<EntityRef>,
207 pub(crate) variants: Vec<(Type, i32)>,
210}
211
212impl EntityEntry {
213 fn set_variant(&mut self, entity_type: Type, id: i32) {
215 if let Some(slot) = self.variants.iter_mut().find(|(t, _)| *t == entity_type) {
216 slot.1 = id;
217 } else {
218 self.variants.push((entity_type, id));
219 }
220 }
221}
222
223#[derive(Debug, Clone)]
225pub struct SymbolTable {
226 symbols: HashMap<String, Symbol>,
228 parent: Option<Box<SymbolTable>>,
230 next_int_local: i32,
232 next_string_local: i32,
233 next_long_local: i32,
234 total_int_decls: i32,
237 total_string_decls: i32,
238 total_long_decls: i32,
239}
240
241impl Default for SymbolTable {
242 fn default() -> Self {
243 Self::new()
244 }
245}
246
247impl SymbolTable {
248 pub fn new() -> Self {
249 SymbolTable {
250 symbols: HashMap::new(),
251 parent: None,
252 next_int_local: 0,
253 next_string_local: 0,
254 next_long_local: 0,
255 total_int_decls: 0,
256 total_string_decls: 0,
257 total_long_decls: 0,
258 }
259 }
260
261 pub fn child(parent: SymbolTable) -> Self {
263 let int_local = parent.next_int_local;
264 let string_local = parent.next_string_local;
265 let long_local = parent.next_long_local;
266 let int_decls = parent.total_int_decls;
267 let string_decls = parent.total_string_decls;
268 let long_decls = parent.total_long_decls;
269 SymbolTable {
270 symbols: HashMap::new(),
271 parent: Some(Box::new(parent)),
272 next_int_local: int_local,
273 next_string_local: string_local,
274 next_long_local: long_local,
275 total_int_decls: int_decls,
276 total_string_decls: string_decls,
277 total_long_decls: long_decls,
278 }
279 }
280
281 pub fn new_child(&self) -> Self {
283 SymbolTable {
284 symbols: HashMap::new(),
285 parent: Some(Box::new(self.clone())),
286 next_int_local: self.next_int_local,
287 next_string_local: self.next_string_local,
288 next_long_local: self.next_long_local,
289 total_int_decls: self.total_int_decls,
290 total_string_decls: self.total_string_decls,
291 total_long_decls: self.total_long_decls,
292 }
293 }
294
295 pub fn define(&mut self, name: String, kind: SymbolKind) {
297 self.symbols.insert(name.clone(), Symbol { name, kind });
298 }
299
300 pub fn define_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
304 if !is_array {
306 match var_type.base_type() {
307 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
308 crate::types::BaseVarType::String => self.total_string_decls += 1,
309 crate::types::BaseVarType::Long => self.total_long_decls += 1,
310 }
311 }
312 let new_slot = self.allocate_slot(&var_type);
318 let slot = if let Some(existing) = self.symbols.get(&name) {
319 match &existing.kind {
320 SymbolKind::LocalVar { slot, .. } => *slot,
321 _ => new_slot,
322 }
323 } else {
324 new_slot
325 };
326 self.define(
327 name,
328 SymbolKind::LocalVar {
329 var_type,
330 slot,
331 is_array,
332 },
333 );
334 slot
335 }
336
337 pub fn define_param(&mut self, name: String, param_type: Type) -> i32 {
339 match param_type.base_type() {
340 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
341 crate::types::BaseVarType::String => self.total_string_decls += 1,
342 crate::types::BaseVarType::Long => self.total_long_decls += 1,
343 }
344 let slot = self.allocate_slot(¶m_type);
345 self.define(name, SymbolKind::ScriptParam { param_type, slot });
346 slot
347 }
348
349 fn allocate_slot(&mut self, var_type: &Type) -> i32 {
351 match var_type.base_type() {
352 crate::types::BaseVarType::Integer => {
353 let slot = self.next_int_local;
354 self.next_int_local += 1;
355 slot
356 }
357 crate::types::BaseVarType::String => {
358 let slot = self.next_string_local;
359 self.next_string_local += 1;
360 slot
361 }
362 crate::types::BaseVarType::Long => {
363 let slot = self.next_long_local;
364 self.next_long_local += 1;
365 slot
366 }
367 }
368 }
369
370 pub fn lookup(&self, name: &str) -> Option<&Symbol> {
372 if let Some(sym) = self.symbols.get(name) {
373 return Some(sym);
374 }
375 if let Some(parent) = &self.parent {
376 return parent.lookup(name);
377 }
378 None
379 }
380
381 pub fn lookup_local(&self, name: &str) -> Option<&Symbol> {
383 self.symbols.get(name)
384 }
385
386 pub fn contains(&self, name: &str) -> bool {
388 self.lookup(name).is_some()
389 }
390
391 pub fn save_slots(&self) -> (i32, i32, i32) {
393 (
394 self.next_int_local,
395 self.next_string_local,
396 self.next_long_local,
397 )
398 }
399
400 pub fn restore_slots(&mut self, saved: (i32, i32, i32)) {
404 self.next_int_local = saved.0;
405 self.next_string_local = saved.1;
406 self.next_long_local = saved.2;
407 }
408
409 pub fn merge_slots(&mut self, other: (i32, i32, i32)) {
412 self.next_int_local = self.next_int_local.max(other.0);
413 self.next_string_local = self.next_string_local.max(other.1);
414 self.next_long_local = self.next_long_local.max(other.2);
415 }
416
417 pub fn merge_decls(&mut self, child: &SymbolTable) {
419 self.total_int_decls = child.total_int_decls;
420 self.total_string_decls = child.total_string_decls;
421 self.total_long_decls = child.total_long_decls;
422 }
423
424 pub fn int_local_count(&self) -> u16 {
426 self.total_int_decls as u16
427 }
428
429 pub fn string_local_count(&self) -> u16 {
431 self.total_string_decls as u16
432 }
433
434 pub fn long_local_count(&self) -> u16 {
436 self.total_long_decls as u16
437 }
438
439 pub fn reset_locals(&mut self) {
441 self.next_int_local = 0;
442 self.next_string_local = 0;
443 self.next_long_local = 0;
444 }
445
446 pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
448 self.symbols.iter()
449 }
450}
451
452#[derive(Debug, Clone)]
460pub struct SymbolRegistry {
461 pub(crate) profile: Option<Arc<crate::environment::EngineProfile>>,
462 pub(crate) visibility: Arc<crate::sources::Visibility>,
463 pub(crate) dynamic_returns: HashMap<String, ReturnType>,
464 pub(crate) param_types: HashMap<i32, Type>,
465 pub(crate) stack_commands: HashSet<String>,
466 pub(crate) stack_scripts: HashSet<String>,
467 pub(crate) hook_commands: HashMap<String, bool>,
468 pub(crate) scripts: HashMap<String, Arc<Symbol>>,
472 pub(crate) commands: HashMap<String, Symbol>,
474 pub(crate) game_vars: HashMap<String, Symbol>,
476 pub(crate) constants: HashMap<String, Symbol>,
478 pub(crate) entity_ids: HashMap<String, EntityEntry>,
484 pub(crate) command_param_types: HashMap<String, Vec<Type>>,
487 pub(crate) type_chars: HashMap<String, i32>,
490 pub(crate) script_ids: HashMap<String, i32>,
492 pub(crate) proc_script_ids: HashMap<String, i32>,
494 pub(crate) label_script_ids: HashMap<String, i32>,
496 pub(crate) trigger_script_ids: HashMap<String, i32>,
499 pub(crate) scripts_by_trigger: HashMap<String, Arc<Symbol>>,
504 pub(crate) preloaded_script_ids: HashMap<String, i32>,
507 pub(crate) dbcolumn_types: HashMap<String, Type>,
510 pub(crate) components: HashMap<String, i32>,
512 pub(crate) interface_ids: HashMap<String, i32>,
514 pub(crate) test_scripts: HashSet<String>,
516 pub(crate) client_script_params: HashMap<String, Vec<Type>>,
518 next_script_id: i32,
519}
520
521impl Default for SymbolRegistry {
522 fn default() -> Self {
523 Self::new()
524 }
525}
526
527#[derive(Debug, Clone, Copy)]
528pub enum ReturnType {
529 TypeArgument(usize),
530 ParamArgument(usize),
531}
532
533impl SymbolRegistry {
534 pub fn set_engine_profile(&mut self, profile: crate::environment::EngineProfile) {
535 self.profile = Some(Arc::new(profile));
536 }
537
538 pub fn trigger(&self, name: &str) -> Option<crate::environment::Trigger> {
539 if let Some(profile) = &self.profile {
540 return profile.triggers.get(name).cloned();
541 }
542 crate::trigger_table::is_valid_trigger(name).then(|| crate::environment::Trigger {
543 byte: crate::trigger_table::byte(name),
544 subject_type: crate::trigger_table::subject_type(name),
545 validates_subject: crate::trigger_table::validates_subject(name),
546 is_button: crate::trigger_table::is_button(name),
547 allows_returns: crate::trigger_table::allows_returns(name),
548 })
549 }
550
551 pub fn set_visibility(&mut self, mut visibility: crate::sources::Visibility) {
552 visibility.index_registry(self);
553 self.visibility = Arc::new(visibility);
554 }
555
556 pub fn set_script_id(&mut self, trigger: &str, name: &str, id: i32) {
558 self.preloaded_script_ids
559 .insert(format!("{trigger}:{name}"), id);
560 }
561
562 pub fn set_stack_script(&mut self, trigger: &str, name: &str) {
564 self.stack_scripts.insert(format!("{trigger}:{name}"));
565 }
566
567 pub fn set_command_behavior(
568 &mut self,
569 name: &str,
570 stack: bool,
571 hook: Option<bool>,
572 returns: Option<ReturnType>,
573 ) {
574 if stack {
575 self.stack_commands.insert(name.to_owned());
576 } else {
577 self.stack_commands.remove(name);
578 }
579 if let Some(explicit_component) = hook {
580 self.hook_commands
581 .insert(name.to_owned(), explicit_component);
582 } else {
583 self.hook_commands.remove(name);
584 }
585 if let Some(returns) = returns {
586 self.dynamic_returns.insert(name.to_owned(), returns);
587 } else {
588 self.dynamic_returns.remove(name);
589 }
590 }
591
592 pub fn commands(&self) -> impl Iterator<Item = (&str, &Symbol)> {
593 self.commands
594 .iter()
595 .map(|(name, symbol)| (name.as_str(), symbol))
596 }
597
598 pub fn constants(&self) -> impl Iterator<Item = (&str, &Symbol)> {
599 self.constants
600 .iter()
601 .map(|(name, symbol)| (name.as_str(), symbol))
602 }
603
604 pub(crate) fn remove_script(&mut self, trigger: &str, name: &str) {
605 self.scripts_by_trigger.remove(&format!("{trigger}:{name}"));
606 self.scripts.remove(name);
607 self.stack_scripts.remove(&format!("{trigger}:{name}"));
608 self.test_scripts.remove(&format!("{trigger}:{name}"));
609 if trigger == "proc" {
610 self.proc_script_ids.remove(name);
611 }
612 if trigger == "label" {
613 self.label_script_ids.remove(name);
614 }
615 }
616
617 pub fn load_visibility(&mut self, source_dir: &std::path::Path) {
619 self.visibility = Arc::new(crate::sources::Visibility::load(source_dir, self));
620 }
621
622 pub fn game_variables(&self) -> impl Iterator<Item = (&str, &Symbol)> {
623 self.game_vars
624 .iter()
625 .map(|(name, symbol)| (name.as_str(), symbol))
626 }
627
628 pub fn new() -> Self {
629 SymbolRegistry {
630 profile: None,
631 visibility: Arc::default(),
632 dynamic_returns: HashMap::new(),
633 param_types: HashMap::new(),
634 stack_commands: HashSet::new(),
635 stack_scripts: HashSet::new(),
636 hook_commands: HashMap::new(),
637 scripts: HashMap::new(),
638 commands: HashMap::new(),
639 game_vars: HashMap::new(),
640 constants: HashMap::new(),
641 entity_ids: HashMap::new(),
642 command_param_types: HashMap::new(),
643 type_chars: HashMap::new(),
644 script_ids: HashMap::new(),
645 proc_script_ids: HashMap::new(),
646 label_script_ids: HashMap::new(),
647 trigger_script_ids: HashMap::new(),
648 scripts_by_trigger: HashMap::new(),
649 preloaded_script_ids: HashMap::new(),
650 dbcolumn_types: HashMap::new(),
651 components: HashMap::new(),
652 interface_ids: HashMap::new(),
653 test_scripts: HashSet::new(),
654 client_script_params: HashMap::new(),
655 next_script_id: 0,
656 }
657 }
658
659 pub fn register_clientscript(&mut self, name: String, id: i32, params: Vec<Type>) {
660 self.trigger_script_ids
661 .insert(format!("clientscript:{name}"), id);
662 self.client_script_params.insert(name, params);
663 }
664
665 pub fn register_script(
667 &mut self,
668 name: String,
669 trigger: String,
670 param_types: Vec<Type>,
671 return_types: Vec<Type>,
672 ) -> i32 {
673 let key = format!("{}:{}", trigger, name);
674 let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
675 preloaded
676 } else {
677 let id = self.next_script_id;
678 self.next_script_id += 1;
679 id
680 };
681
682 if trigger == "proc" {
686 self.proc_script_ids.insert(name.clone(), id);
687 } else if trigger == "label" {
688 self.label_script_ids.insert(name.clone(), id);
689 }
690 let symbol = Arc::new(Symbol {
694 name: name.clone(),
695 kind: SymbolKind::Script {
696 id,
697 trigger,
698 param_types,
699 return_types,
700 },
701 });
702 self.scripts_by_trigger.insert(key, Arc::clone(&symbol));
703 self.scripts.insert(name, symbol);
704
705 id
706 }
707
708 pub fn register_command(
710 &mut self,
711 name: String,
712 opcode: i32,
713 param_types: Vec<Type>,
714 return_types: Vec<Type>,
715 ) {
716 self.command_param_types
717 .insert(name.clone(), param_types.clone());
718 self.commands.insert(
719 name.clone(),
720 Symbol {
721 name,
722 kind: SymbolKind::Command {
723 opcode,
724 param_types,
725 return_types,
726 },
727 },
728 );
729 }
730
731 pub fn register_param_type(&mut self, id: i32, ty: Type) {
732 self.param_types.insert(id, ty);
733 }
734
735 pub fn register_game_var(
737 &mut self,
738 name: String,
739 var_type: Type,
740 var_id: i32,
741 category: String,
742 ) {
743 self.game_vars.insert(
744 name.clone(),
745 Symbol {
746 name,
747 kind: SymbolKind::GameVar {
748 var_type,
749 var_id,
750 category,
751 },
752 },
753 );
754 }
755
756 pub fn register_constant(
758 &mut self,
759 name: String,
760 const_type: Type,
761 int_value: Option<i32>,
762 string_value: Option<String>,
763 ) {
764 self.constants.insert(
765 name.clone(),
766 Symbol {
767 name,
768 kind: SymbolKind::Constant {
769 const_type,
770 int_value,
771 string_value,
772 },
773 },
774 );
775 }
776
777 pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
781 let entry = self.entity_ids.entry(name).or_default();
782 entry.primary = Some(EntityRef {
784 const_type: entity_type,
785 id,
786 });
787 entry.set_variant(entity_type, id);
788 }
789
790 pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
800 self.entity_ids
801 .entry(name)
802 .or_default()
803 .set_variant(entity_type, id);
804 }
805
806 pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
810 let normalized = normalize_entity_name(name);
811 self.entity_ids
812 .get(normalized.as_ref())
813 .and_then(|e| e.variants.iter().find(|(t, _)| *t == expected))
814 .map(|(_, id)| *id)
815 }
816
817 pub fn lookup_reference(&self, name: &str, expected: Type) -> Option<i32> {
818 match expected {
819 Type::Component => name
820 .split_once(':')
821 .and_then(|(iface, com)| self.lookup_component(iface, com))
822 .or_else(|| self.lookup_entity_id_typed(name, expected)),
823 Type::ClientScript => self
824 .script_id_for_trigger("clientscript", name)
825 .or_else(|| self.script_id_for_trigger("proc", name)),
826 Type::Proc => self.proc_script_id(name),
827 Type::Model | Type::Texture | Type::Category => {
829 self.lookup_entity_id_typed(name, expected).or_else(|| {
830 name.strip_prefix(expected.name())?
831 .strip_prefix('_')?
832 .parse::<i32>()
833 .ok()
834 .filter(|id| *id >= 0)
835 })
836 }
837 Type::Varp
838 | Type::Varn
839 | Type::Vars
840 | Type::Varbit
841 | Type::Varc
842 | Type::VarClanSetting => self.lookup_game_var(name).and_then(|symbol| {
843 if let SymbolKind::GameVar {
844 var_id, category, ..
845 } = &symbol.kind
846 && match expected {
847 Type::Varc => matches!(category.as_str(), "varc" | "varcs"),
848 Type::VarClanSetting => category.starts_with("clansetting_"),
849 _ => category == expected.name(),
850 }
851 {
852 Some(*var_id)
853 } else {
854 None
855 }
856 }),
857 _ => self.lookup_entity_id_typed(name, expected),
858 }
859 }
860
861 pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
863 self.scripts.get(name).map(|s| s.as_ref())
864 }
865
866 pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
868 if let Some(symbol) = self.scripts.get(name)
869 && matches!(&symbol.kind, SymbolKind::Script { trigger: found, .. } if found == trigger)
870 {
871 return Some(symbol);
872 }
873 self.scripts_by_trigger
874 .get(&format!("{}:{}", trigger, name))
875 .map(|s| s.as_ref())
876 }
877
878 pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
880 self.commands.get(name)
881 }
882
883 pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
885 self.game_vars.get(name)
886 }
887
888 pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
890 self.constants.get(name)
891 }
892
893 pub fn integer_constant_name(&self, value: i32, prefix: &str) -> Option<&str> {
894 self.constants.values().filter(|symbol| symbol.name.starts_with(prefix)).filter_map(|symbol| {
895 matches!(&symbol.kind, SymbolKind::Constant { int_value: Some(id), .. } if *id == value)
896 .then_some(symbol.name.as_str())
897 }).min()
898 }
899
900 pub fn lookup_entity_id(&self, name: &str) -> Option<EntityRef> {
903 let normalized = normalize_entity_name(name);
904 self.entity_ids
905 .get(normalized.as_ref())
906 .and_then(|e| e.primary)
907 }
908
909 pub(crate) fn drop_registration_scratch(&mut self) {
914 self.preloaded_script_ids = HashMap::new();
915 }
916
917 pub fn script_id(&self, name: &str) -> Option<i32> {
923 if let Some(s) = self.scripts.get(name)
924 && let SymbolKind::Script { id, .. } = &s.kind
925 {
926 return Some(*id);
927 }
928 self.script_ids.get(name).copied()
929 }
930
931 pub fn proc_script_id(&self, name: &str) -> Option<i32> {
933 self.proc_script_ids.get(name).copied()
934 }
935
936 pub fn label_script_id(&self, name: &str) -> Option<i32> {
938 self.label_script_ids.get(name).copied()
939 }
940
941 pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
942 let key = format!("{}:{}", trigger, name);
943 if let Some(s) = self.scripts_by_trigger.get(&key)
944 && let SymbolKind::Script { id, .. } = &s.kind
945 {
946 return Some(*id);
947 }
948 self.trigger_script_ids
951 .get(&key)
952 .or_else(|| self.preloaded_script_ids.get(&key))
953 .copied()
954 }
955
956 pub fn command_opcode(&self, name: &str) -> Option<i32> {
957 self.commands.get(name).and_then(|sym| {
958 if let SymbolKind::Command { opcode, .. } = &sym.kind {
959 Some(*opcode)
960 } else {
961 None
962 }
963 })
964 }
965
966 pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
967 self.test_scripts.insert(format!("{}:{}", trigger, name));
968 }
969
970 pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
971 self.test_scripts.contains(&format!("{}:{}", trigger, name))
972 }
973
974 pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
979 let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
980 self.components.get(&key).copied()
981 }
982}
983
984pub(crate) fn normalize_comp_name(name: &str) -> String {
987 let bytes = name.as_bytes();
988 let mut out = Vec::with_capacity(bytes.len());
989 let mut i = 0;
990 while i < bytes.len() {
991 if bytes[i] == b'_'
992 && i > 0
993 && bytes[i - 1].is_ascii_alphabetic()
994 && i + 1 < bytes.len()
995 && bytes[i + 1].is_ascii_digit()
996 {
997 i += 1;
998 continue;
999 }
1000 out.push(bytes[i]);
1001 i += 1;
1002 }
1003 unsafe { String::from_utf8_unchecked(out) }
1004}
1005
1006#[cfg(test)]
1007mod tests {
1008 use super::*;
1009
1010 #[test]
1013 fn normalize_strips_underscore_before_digits() {
1014 assert_eq!(normalize_comp_name("com_2"), "com2");
1015 assert_eq!(normalize_comp_name("com_10"), "com10");
1016 assert_eq!(normalize_comp_name("com_0"), "com0");
1017 }
1018
1019 #[test]
1020 fn normalize_preserves_already_compact_names() {
1021 assert_eq!(normalize_comp_name("com2"), "com2");
1022 assert_eq!(normalize_comp_name("com10"), "com10");
1023 assert_eq!(normalize_comp_name("com0"), "com0");
1024 }
1025
1026 #[test]
1027 fn normalize_preserves_non_digit_underscores() {
1028 assert_eq!(normalize_comp_name("close_button"), "close_button");
1029 assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
1030 assert_eq!(normalize_comp_name("title"), "title");
1031 }
1032
1033 #[test]
1034 fn normalize_only_strips_alpha_digit_boundary() {
1035 assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
1037 assert_eq!(normalize_comp_name("3_panel"), "3_panel");
1039 }
1040
1041 fn registry_647_style() -> SymbolRegistry {
1044 let mut r = SymbolRegistry::new();
1045 r.interface_ids.insert("multi2".into(), 228);
1046 for i in 0..10 {
1048 let key = format!("multi2:com{}", i);
1049 r.components.insert(key, (228 << 16) | i);
1050 }
1051 r
1052 }
1053
1054 #[test]
1055 fn lookup_647_pack_with_647_reference() {
1056 let r = registry_647_style();
1057 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1059 assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
1060 }
1061
1062 #[test]
1063 fn lookup_647_pack_with_225_reference() {
1064 let r = registry_647_style();
1065 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1067 assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
1068 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1069 }
1070
1071 fn registry_225_style() -> SymbolRegistry {
1074 let mut r = SymbolRegistry::new();
1075 r.interface_ids.insert("multi2".into(), 228);
1076 for i in 0..10 {
1079 let key = format!("multi2:com{}", i);
1080 r.components.insert(key, 2459 + i);
1081 }
1082 r
1083 }
1084
1085 #[test]
1086 fn lookup_225_pack_with_225_reference() {
1087 let r = registry_225_style();
1088 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
1089 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1090 }
1091
1092 #[test]
1093 fn lookup_225_pack_with_647_reference() {
1094 let r = registry_225_style();
1095 assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
1096 assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
1097 }
1098
1099 #[test]
1102 fn lookup_returns_none_for_unknown_component() {
1103 let r = registry_647_style();
1104 assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
1105 assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
1106 }
1107}