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) type_arguments: HashMap<String, usize>,
467 pub(crate) param_types: HashMap<i32, Type>,
468 pub(crate) stack_commands: HashSet<String>,
469 component_first_commands: HashSet<String>,
470 command_pointer_overrides: HashMap<String, PointerHolder>,
471 switch_domains: HashMap<Type, BTreeMap<i32, String>>,
472 pub(crate) stack_scripts: HashSet<String>,
473 pub(crate) hook_commands: HashMap<String, bool>,
474 pub(crate) scripts: HashMap<String, Arc<Symbol>>,
478 pub(crate) commands: HashMap<String, Symbol>,
480 pub(crate) game_vars: HashMap<String, Symbol>,
482 pub(crate) constants: HashMap<String, Symbol>,
484 pub(crate) entity_ids: HashMap<String, EntityEntry>,
490 pub(crate) command_param_types: HashMap<String, Vec<Type>>,
493 pub(crate) type_chars: HashMap<String, i32>,
496 pub(crate) script_ids: HashMap<String, i32>,
498 pub(crate) proc_script_ids: HashMap<String, i32>,
500 pub(crate) label_script_ids: HashMap<String, i32>,
502 pub(crate) trigger_script_ids: HashMap<String, i32>,
505 pub(crate) scripts_by_trigger: HashMap<String, Arc<Symbol>>,
510 pub(crate) preloaded_script_ids: HashMap<String, i32>,
512 pub(crate) dbcolumn_types: HashMap<String, Vec<Type>>,
515 pub(crate) components: HashMap<String, i32>,
517 pub(crate) interface_ids: HashMap<String, i32>,
519 pub(crate) test_scripts: HashSet<String>,
521 pub(crate) client_script_params: HashMap<String, Vec<Type>>,
523 pub(crate) next_script_id: i32,
524}
525
526impl Default for SymbolRegistry {
527 fn default() -> Self {
528 Self::new()
529 }
530}
531
532#[derive(Debug, Clone, Copy)]
533pub enum ReturnType {
534 TypeArgument(usize),
535 ParamArgument(usize),
536}
537
538impl SymbolRegistry {
539 pub fn set_engine_profile(&mut self, profile: crate::environment::EngineProfile) {
540 self.command_pointer_overrides.clear();
541 self.profile = Some(Arc::new(profile));
542 }
543
544 pub fn trigger(&self, name: &str) -> Option<crate::environment::Trigger> {
545 if let Some(profile) = &self.profile {
546 return profile.triggers.get(name).cloned();
547 }
548 crate::trigger_table::is_valid_trigger(name).then(|| crate::environment::Trigger {
549 byte: crate::trigger_table::byte(name),
550 subject_type: crate::trigger_table::subject_type(name),
551 validates_subject: crate::trigger_table::validates_subject(name),
552 is_button: crate::trigger_table::is_button(name),
553 allows_returns: crate::trigger_table::allows_returns(name),
554 })
555 }
556
557 pub fn set_visibility(&mut self, mut visibility: crate::sources::Visibility) {
558 visibility.index_registry(self);
559 self.visibility = Arc::new(visibility);
560 }
561
562 pub fn set_script_id(&mut self, trigger: &str, name: &str, id: i32) {
564 self.preloaded_script_ids
565 .insert(format!("{trigger}:{name}"), id);
566 self.next_script_id = self.next_script_id.max(id + 1);
567 }
568
569 pub fn set_stack_script(&mut self, trigger: &str, name: &str) {
571 self.stack_scripts.insert(format!("{trigger}:{name}"));
572 }
573
574 pub fn component_first_command(&self, name: &str) -> bool {
575 let name = name.trim_start_matches('.');
576 self.stack_commands.contains(name) && self.component_first_commands.contains(name)
577 }
578
579 pub fn set_command_suspends(&mut self, name: &str, suspends: bool) {
580 if let Some(profile) = &mut self.profile {
581 Arc::make_mut(profile)
582 .command_pointers
583 .entry(name.to_owned())
584 .or_default()
585 .may_suspend = suspends;
586 } else {
587 self.command_pointer_overrides
588 .entry(name.to_owned())
589 .or_insert_with(|| {
590 default_command_pointers()
591 .get(name)
592 .cloned()
593 .unwrap_or_default()
594 })
595 .may_suspend = suspends;
596 }
597 }
598
599 pub fn command_suspends(&self, name: &str) -> bool {
600 self.command_suspends_for(name, true)
601 }
602
603 pub(crate) fn command_suspends_for(&self, name: &str, server: bool) -> bool {
604 let primary = name.trim_start_matches('.');
605 let lookup = |pointers: &HashMap<String, PointerHolder>| {
606 pointers
607 .get(name)
608 .or_else(|| pointers.get(primary))
609 .map(|holder| holder.may_suspend)
610 };
611 if let Some(profile) = &self.profile {
612 lookup(&profile.command_pointers).unwrap_or(false)
613 } else {
614 lookup(&self.command_pointer_overrides)
615 .or_else(|| server.then(|| lookup(default_command_pointers())).flatten())
616 .unwrap_or(false)
617 }
618 }
619
620 pub fn set_switch_values(&mut self, ty: Type, values: impl IntoIterator<Item = (i32, String)>) {
622 self.switch_domains.insert(ty, values.into_iter().collect());
623 }
624
625 pub fn switch_values(&self, ty: Type) -> Option<&BTreeMap<i32, String>> {
626 self.switch_domains
627 .get(&ty)
628 .filter(|values| !values.is_empty())
629 }
630
631 pub fn set_component_first_command(&mut self, name: &str, component_first: bool) {
632 let name = name.trim_start_matches('.');
633 if component_first {
634 self.component_first_commands.insert(name.to_owned());
635 } else {
636 self.component_first_commands.remove(name);
637 }
638 }
639
640 pub(crate) fn clear_commands(&mut self) {
641 self.commands.clear();
642 self.command_param_types.clear();
643 self.stack_commands.clear();
644 self.component_first_commands.clear();
645 self.command_pointer_overrides.clear();
646 self.hook_commands.clear();
647 self.dynamic_returns.clear();
648 self.type_arguments.clear();
649 }
650
651 pub fn set_command_behavior(
652 &mut self,
653 name: &str,
654 stack: bool,
655 hook: Option<bool>,
656 returns: Option<ReturnType>,
657 ) {
658 if stack {
659 self.stack_commands.insert(name.to_owned());
660 } else {
661 self.stack_commands.remove(name);
662 self.component_first_commands.remove(name);
663 }
664 if let Some(explicit_component) = hook {
665 self.hook_commands
666 .insert(name.to_owned(), explicit_component);
667 } else {
668 self.hook_commands.remove(name);
669 }
670 if let Some(returns) = returns {
671 self.dynamic_returns.insert(name.to_owned(), returns);
672 } else {
673 self.dynamic_returns.remove(name);
674 }
675 }
676
677 pub fn commands(&self) -> impl Iterator<Item = (&str, &Symbol)> {
678 self.commands
679 .iter()
680 .map(|(name, symbol)| (name.as_str(), symbol))
681 }
682
683 pub fn constants(&self) -> impl Iterator<Item = (&str, &Symbol)> {
684 self.constants
685 .iter()
686 .map(|(name, symbol)| (name.as_str(), symbol))
687 }
688
689 pub(crate) fn remove_script(&mut self, trigger: &str, name: &str) {
690 self.scripts_by_trigger.remove(&format!("{trigger}:{name}"));
691 self.scripts.remove(name);
692 self.stack_scripts.remove(&format!("{trigger}:{name}"));
693 self.test_scripts.remove(&format!("{trigger}:{name}"));
694 if trigger == "proc" {
695 self.proc_script_ids.remove(name);
696 }
697 if trigger == "label" {
698 self.label_script_ids.remove(name);
699 }
700 }
701
702 pub fn load_visibility(&mut self, source_dir: &std::path::Path) {
704 self.visibility = Arc::new(crate::sources::Visibility::load(source_dir, self));
705 }
706
707 pub fn game_variables(&self) -> impl Iterator<Item = (&str, &Symbol)> {
708 self.game_vars
709 .iter()
710 .map(|(name, symbol)| (name.as_str(), symbol))
711 }
712
713 pub fn new() -> Self {
714 SymbolRegistry {
715 profile: None,
716 visibility: Arc::default(),
717 dynamic_returns: HashMap::new(),
718 type_arguments: HashMap::new(),
719 param_types: HashMap::new(),
720 stack_commands: HashSet::new(),
721 component_first_commands: HashSet::new(),
722 command_pointer_overrides: HashMap::new(),
723 switch_domains: HashMap::from([
724 (
725 Type::Boolean,
726 [(0, "false".into()), (1, "true".into())].into(),
727 ),
728 (Type::IntBool, [(0, "0".into()), (1, "1".into())].into()),
729 ]),
730 stack_scripts: HashSet::new(),
731 hook_commands: HashMap::new(),
732 scripts: HashMap::new(),
733 commands: HashMap::new(),
734 game_vars: HashMap::new(),
735 constants: HashMap::new(),
736 entity_ids: HashMap::new(),
737 command_param_types: HashMap::new(),
738 type_chars: HashMap::new(),
739 script_ids: HashMap::new(),
740 proc_script_ids: HashMap::new(),
741 label_script_ids: HashMap::new(),
742 trigger_script_ids: HashMap::new(),
743 scripts_by_trigger: HashMap::new(),
744 preloaded_script_ids: HashMap::new(),
745 dbcolumn_types: HashMap::new(),
746 components: HashMap::new(),
747 interface_ids: HashMap::new(),
748 test_scripts: HashSet::new(),
749 client_script_params: HashMap::new(),
750 next_script_id: 0,
751 }
752 }
753
754 pub fn register_clientscript(&mut self, name: String, id: i32, params: Vec<Type>) {
755 self.trigger_script_ids
756 .insert(format!("clientscript:{name}"), id);
757 self.client_script_params.insert(name, params);
758 }
759
760 pub fn register_script(
762 &mut self,
763 name: String,
764 trigger: String,
765 param_types: Vec<Type>,
766 return_types: Vec<Type>,
767 ) -> i32 {
768 let key = format!("{}:{}", trigger, name);
769 let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
770 preloaded
771 } else {
772 let id = self.next_script_id;
773 self.next_script_id += 1;
774 id
775 };
776
777 if trigger == "proc" {
781 self.proc_script_ids.insert(name.clone(), id);
782 } else if trigger == "label" {
783 self.label_script_ids.insert(name.clone(), id);
784 }
785 let symbol = Arc::new(Symbol {
789 name: name.clone(),
790 kind: SymbolKind::Script {
791 id,
792 trigger,
793 param_types,
794 return_types,
795 },
796 });
797 self.scripts_by_trigger.insert(key, Arc::clone(&symbol));
798 self.scripts.insert(name, symbol);
799
800 id
801 }
802
803 pub fn register_command(
805 &mut self,
806 name: String,
807 opcode: i32,
808 param_types: Vec<Type>,
809 return_types: Vec<Type>,
810 ) {
811 self.component_first_commands.remove(&name);
812 self.command_pointer_overrides.remove(&name);
813 self.command_param_types
814 .insert(name.clone(), param_types.clone());
815 self.commands.insert(
816 name.clone(),
817 Symbol {
818 name,
819 kind: SymbolKind::Command {
820 opcode,
821 param_types,
822 return_types,
823 },
824 },
825 );
826 }
827
828 pub fn register_param_type(&mut self, id: i32, ty: Type) {
829 self.param_types.insert(id, ty);
830 }
831
832 pub fn register_game_var(
834 &mut self,
835 name: String,
836 var_type: Type,
837 var_id: i32,
838 category: String,
839 ) {
840 self.game_vars.insert(
841 name.clone(),
842 Symbol {
843 name,
844 kind: SymbolKind::GameVar {
845 var_type,
846 var_id,
847 category,
848 },
849 },
850 );
851 }
852
853 pub fn register_constant(
855 &mut self,
856 name: String,
857 const_type: Type,
858 int_value: Option<i32>,
859 string_value: Option<String>,
860 ) {
861 self.constants.insert(
862 name.clone(),
863 Symbol {
864 name,
865 kind: SymbolKind::Constant {
866 const_type,
867 int_value,
868 string_value,
869 },
870 },
871 );
872 }
873
874 pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
878 let entry = self.entity_ids.entry(name).or_default();
879 entry.primary = Some(EntityRef {
881 const_type: entity_type,
882 id,
883 });
884 entry.set_variant(entity_type, id);
885 }
886
887 pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
897 self.entity_ids
898 .entry(name)
899 .or_default()
900 .set_variant(entity_type, id);
901 }
902
903 pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
907 let normalized = normalize_entity_name(name);
908 self.entity_ids
909 .get(normalized.as_ref())
910 .and_then(|e| e.variants.iter().find(|(t, _)| *t == expected))
911 .map(|(_, id)| *id)
912 }
913
914 pub fn lookup_reference(&self, name: &str, expected: Type) -> Option<i32> {
915 match expected {
916 Type::Component => name
917 .split_once(':')
918 .and_then(|(iface, com)| self.lookup_component(iface, com))
919 .or_else(|| self.lookup_entity_id_typed(name, expected)),
920 Type::ClientScript => self
921 .script_id_for_trigger("clientscript", name)
922 .or_else(|| self.script_id_for_trigger("proc", name)),
923 Type::Proc => self.proc_script_id(name),
924 Type::Model | Type::Texture | Type::Category => {
926 self.lookup_entity_id_typed(name, expected).or_else(|| {
927 name.strip_prefix(expected.name())?
928 .strip_prefix('_')?
929 .parse::<i32>()
930 .ok()
931 .filter(|id| *id >= 0)
932 })
933 }
934 Type::Varp
935 | Type::Varn
936 | Type::Vars
937 | Type::VarpBit
938 | Type::Varc
939 | Type::VarCon
940 | Type::VarConBit
941 | Type::VarClanSetting => self.lookup_game_var(name).and_then(|symbol| {
942 if let SymbolKind::GameVar {
943 var_id, category, ..
944 } = &symbol.kind
945 && match expected {
946 Type::Varc => matches!(category.as_str(), "varc" | "varcstr"),
947 Type::VarClanSetting => category.starts_with("clansetting_"),
948 _ => category == expected.name(),
949 }
950 {
951 Some(*var_id)
952 } else {
953 None
954 }
955 }),
956 _ => self.lookup_entity_id_typed(name, expected),
957 }
958 }
959
960 pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
962 self.scripts.get(name).map(|s| s.as_ref())
963 }
964
965 pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
967 if let Some(symbol) = self.scripts.get(name)
968 && matches!(&symbol.kind, SymbolKind::Script { trigger: found, .. } if found == trigger)
969 {
970 return Some(symbol);
971 }
972 self.scripts_by_trigger
973 .get(&format!("{}:{}", trigger, name))
974 .map(|s| s.as_ref())
975 }
976
977 pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
979 self.commands.get(name)
980 }
981
982 pub(crate) fn command_fills(&self, name: &str, hint: Option<Type>) -> bool {
985 hint.is_some_and(|h| h.base_type() != BaseVarType::Integer)
986 && self.commands.contains_key(name)
987 }
988
989 pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
991 self.game_vars.get(name)
992 }
993
994 pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
996 self.constants.get(name)
997 }
998
999 pub fn integer_constant_name(&self, value: i32, prefix: &str) -> Option<&str> {
1000 self.constants.values().filter(|symbol| symbol.name.starts_with(prefix)).filter_map(|symbol| {
1001 matches!(&symbol.kind, SymbolKind::Constant { int_value: Some(id), .. } if *id == value)
1002 .then_some(symbol.name.as_str())
1003 }).min()
1004 }
1005
1006 pub fn lookup_entity_id(&self, name: &str) -> Option<EntityRef> {
1009 let normalized = normalize_entity_name(name);
1010 self.entity_ids
1011 .get(normalized.as_ref())
1012 .and_then(|e| e.primary)
1013 }
1014
1015 pub(crate) fn drop_registration_scratch(&mut self) {
1020 self.preloaded_script_ids = HashMap::new();
1021 }
1022
1023 pub fn script_id(&self, name: &str) -> Option<i32> {
1029 if let Some(s) = self.scripts.get(name)
1030 && let SymbolKind::Script { id, .. } = &s.kind
1031 {
1032 return Some(*id);
1033 }
1034 self.script_ids.get(name).copied()
1035 }
1036
1037 pub fn proc_script_id(&self, name: &str) -> Option<i32> {
1039 self.proc_script_ids.get(name).copied()
1040 }
1041
1042 pub fn label_script_id(&self, name: &str) -> Option<i32> {
1044 self.label_script_ids.get(name).copied()
1045 }
1046
1047 pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
1048 let key = format!("{}:{}", trigger, name);
1049 if let Some(s) = self.scripts_by_trigger.get(&key)
1050 && let SymbolKind::Script { id, .. } = &s.kind
1051 {
1052 return Some(*id);
1053 }
1054 self.trigger_script_ids
1057 .get(&key)
1058 .or_else(|| self.preloaded_script_ids.get(&key))
1059 .copied()
1060 }
1061
1062 pub fn command_opcode(&self, name: &str) -> Option<i32> {
1063 self.commands.get(name).and_then(|sym| {
1064 if let SymbolKind::Command { opcode, .. } = &sym.kind {
1065 Some(*opcode)
1066 } else {
1067 None
1068 }
1069 })
1070 }
1071
1072 pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
1073 self.test_scripts.insert(format!("{}:{}", trigger, name));
1074 }
1075
1076 pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
1077 self.test_scripts.contains(&format!("{}:{}", trigger, name))
1078 }
1079
1080 pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
1085 let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
1086 self.components.get(&key).copied()
1087 }
1088}
1089
1090pub fn identifier_form(name: &str) -> String {
1094 name.trim()
1095 .chars()
1096 .map(|c| {
1097 if c.is_ascii_alphanumeric() || c == '_' {
1098 c
1099 } else {
1100 '_'
1101 }
1102 })
1103 .collect()
1104}
1105
1106pub(crate) fn normalize_comp_name(name: &str) -> String {
1109 let bytes = name.as_bytes();
1110 let mut out = Vec::with_capacity(bytes.len());
1111 let mut i = 0;
1112 while i < bytes.len() {
1113 if bytes[i] == b'_'
1114 && i > 0
1115 && bytes[i - 1].is_ascii_alphabetic()
1116 && i + 1 < bytes.len()
1117 && bytes[i + 1].is_ascii_digit()
1118 {
1119 i += 1;
1120 continue;
1121 }
1122 out.push(bytes[i]);
1123 i += 1;
1124 }
1125 unsafe { String::from_utf8_unchecked(out) }
1126}
1127
1128#[cfg(test)]
1129mod tests {
1130 use super::*;
1131
1132 #[test]
1135 fn normalize_strips_underscore_before_digits() {
1136 assert_eq!(normalize_comp_name("com_2"), "com2");
1137 assert_eq!(normalize_comp_name("com_10"), "com10");
1138 assert_eq!(normalize_comp_name("com_0"), "com0");
1139 }
1140
1141 #[test]
1142 fn normalize_preserves_already_compact_names() {
1143 assert_eq!(normalize_comp_name("com2"), "com2");
1144 assert_eq!(normalize_comp_name("com10"), "com10");
1145 assert_eq!(normalize_comp_name("com0"), "com0");
1146 }
1147
1148 #[test]
1149 fn normalize_preserves_non_digit_underscores() {
1150 assert_eq!(normalize_comp_name("close_button"), "close_button");
1151 assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
1152 assert_eq!(normalize_comp_name("title"), "title");
1153 }
1154
1155 #[test]
1156 fn normalize_only_strips_alpha_digit_boundary() {
1157 assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
1159 assert_eq!(normalize_comp_name("3_panel"), "3_panel");
1161 }
1162
1163 fn registry_647_style() -> SymbolRegistry {
1166 let mut r = SymbolRegistry::new();
1167 r.interface_ids.insert("multi2".into(), 228);
1168 for i in 0..10 {
1170 let key = format!("multi2:com{}", i);
1171 r.components.insert(key, (228 << 16) | i);
1172 }
1173 r
1174 }
1175
1176 #[test]
1177 fn lookup_647_pack_with_647_reference() {
1178 let r = registry_647_style();
1179 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
1181 assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
1182 }
1183
1184 #[test]
1185 fn lookup_647_pack_with_225_reference() {
1186 let r = registry_647_style();
1187 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
1189 assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
1190 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
1191 }
1192
1193 fn registry_225_style() -> SymbolRegistry {
1196 let mut r = SymbolRegistry::new();
1197 r.interface_ids.insert("multi2".into(), 228);
1198 for i in 0..10 {
1201 let key = format!("multi2:com{}", i);
1202 r.components.insert(key, 2459 + i);
1203 }
1204 r
1205 }
1206
1207 #[test]
1208 fn lookup_225_pack_with_225_reference() {
1209 let r = registry_225_style();
1210 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
1211 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
1212 }
1213
1214 #[test]
1215 fn lookup_225_pack_with_647_reference() {
1216 let r = registry_225_style();
1217 assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
1218 assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
1219 }
1220
1221 #[test]
1224 fn lookup_returns_none_for_unknown_component() {
1225 let r = registry_647_style();
1226 assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
1227 assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
1228 }
1229}