1use crate::types::{BaseVarType, Type};
2use std::collections::{HashMap, HashSet};
3use std::sync::Arc;
4
5#[derive(Debug, Clone)]
11pub struct LocalEntry {
12 pub name: String,
13 pub var_type: Type,
14 pub is_param: bool,
15 pub is_array: bool,
16}
17
18#[derive(Debug, Clone, Default)]
25pub struct LocalTable {
26 pub(crate) all: Vec<LocalEntry>,
27}
28
29impl LocalTable {
30 pub fn new() -> Self {
31 LocalTable { all: Vec::new() }
32 }
33
34 pub fn entries(&self) -> &[LocalEntry] {
36 &self.all
37 }
38
39 pub fn shrink_to_fit(&mut self) {
41 self.all.shrink_to_fit();
42 }
43
44 pub fn push_param(&mut self, name: String, param_type: Type) -> i32 {
45 let id = self.get_variable_id_for_next(param_type, false);
46 self.all.push(LocalEntry {
47 name,
48 var_type: param_type,
49 is_param: true,
50 is_array: false,
51 });
52 id
53 }
54
55 pub fn push_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
56 let id = self.get_variable_id_for_next(var_type, is_array);
57 self.all.push(LocalEntry {
58 name,
59 var_type,
60 is_param: false,
61 is_array,
62 });
63 id
64 }
65
66 fn get_variable_id_for_next(&self, var_type: Type, is_array: bool) -> i32 {
68 if is_array {
69 self.all.iter().filter(|e| e.is_array).count() as i32
70 } else {
71 self.all
72 .iter()
73 .filter(|e| {
74 e.var_type.base_type() == var_type.base_type() && (!e.is_array || e.is_param)
75 })
76 .count() as i32
77 }
78 }
79
80 pub fn get_variable_id(&self, index: usize) -> i32 {
82 let entry = &self.all[index];
83 if entry.is_array {
84 self.all[..index].iter().filter(|e| e.is_array).count() as i32
85 } else {
86 self.all[..index]
87 .iter()
88 .filter(|e| {
89 e.var_type.base_type() == entry.var_type.base_type()
90 && (!e.is_array || e.is_param)
91 })
92 .count() as i32
93 }
94 }
95
96 pub fn get_local_count(&self, base: BaseVarType) -> u16 {
98 self.all
99 .iter()
100 .filter(|e| e.var_type.base_type() == base && (!e.is_array || e.is_param))
101 .count() as u16
102 }
103
104 pub fn get_param_count(&self, base: BaseVarType) -> u16 {
106 self.all
107 .iter()
108 .filter(|e| e.is_param && e.var_type.base_type() == base)
109 .count() as u16
110 }
111}
112
113#[derive(Debug, Clone)]
117pub enum SymbolKind {
118 LocalVar {
120 var_type: Type,
121 slot: i32,
123 is_array: bool,
124 },
125 ScriptParam { param_type: Type, slot: i32 },
127 Script {
129 id: i32,
130 trigger: String,
131 param_types: Vec<Type>,
132 return_types: Vec<Type>,
133 },
134 GameVar {
136 var_type: Type,
137 var_id: i32,
138 category: String,
140 },
141 Constant {
143 const_type: Type,
144 int_value: Option<i32>,
145 string_value: Option<String>,
146 },
147 Command {
149 opcode: i32,
150 param_types: Vec<Type>,
151 return_types: Vec<Type>,
152 },
153}
154
155impl SymbolKind {
156 pub fn kind_name(&self) -> &'static str {
157 match self {
158 SymbolKind::LocalVar { .. } => "LocalVar",
159 SymbolKind::ScriptParam { .. } => "ScriptParam",
160 SymbolKind::Script { .. } => "Script",
161 SymbolKind::GameVar { .. } => "GameVar",
162 SymbolKind::Constant { .. } => "Constant",
163 SymbolKind::Command { .. } => "Command",
164 }
165 }
166}
167
168#[derive(Debug, Clone)]
170pub struct Symbol {
171 pub name: String,
172 pub kind: SymbolKind,
173}
174
175#[derive(Debug, Clone, Copy)]
181pub struct EntityRef {
182 pub const_type: Type,
183 pub id: i32,
184}
185
186#[derive(Debug, Clone, Default)]
191pub(crate) struct EntityEntry {
192 pub(crate) primary: Option<EntityRef>,
195 pub(crate) variants: Vec<(Type, i32)>,
198}
199
200impl EntityEntry {
201 fn set_variant(&mut self, entity_type: Type, id: i32) {
203 if let Some(slot) = self.variants.iter_mut().find(|(t, _)| *t == entity_type) {
204 slot.1 = id;
205 } else {
206 self.variants.push((entity_type, id));
207 }
208 }
209}
210
211#[derive(Debug, Clone)]
213pub struct SymbolTable {
214 symbols: HashMap<String, Symbol>,
216 parent: Option<Box<SymbolTable>>,
218 next_int_local: i32,
220 next_string_local: i32,
221 next_long_local: i32,
222 total_int_decls: i32,
225 total_string_decls: i32,
226 total_long_decls: i32,
227}
228
229impl Default for SymbolTable {
230 fn default() -> Self {
231 Self::new()
232 }
233}
234
235impl SymbolTable {
236 pub fn new() -> Self {
237 SymbolTable {
238 symbols: HashMap::new(),
239 parent: None,
240 next_int_local: 0,
241 next_string_local: 0,
242 next_long_local: 0,
243 total_int_decls: 0,
244 total_string_decls: 0,
245 total_long_decls: 0,
246 }
247 }
248
249 pub fn child(parent: SymbolTable) -> Self {
251 let int_local = parent.next_int_local;
252 let string_local = parent.next_string_local;
253 let long_local = parent.next_long_local;
254 let int_decls = parent.total_int_decls;
255 let string_decls = parent.total_string_decls;
256 let long_decls = parent.total_long_decls;
257 SymbolTable {
258 symbols: HashMap::new(),
259 parent: Some(Box::new(parent)),
260 next_int_local: int_local,
261 next_string_local: string_local,
262 next_long_local: long_local,
263 total_int_decls: int_decls,
264 total_string_decls: string_decls,
265 total_long_decls: long_decls,
266 }
267 }
268
269 pub fn new_child(&self) -> Self {
271 SymbolTable {
272 symbols: HashMap::new(),
273 parent: Some(Box::new(self.clone())),
274 next_int_local: self.next_int_local,
275 next_string_local: self.next_string_local,
276 next_long_local: self.next_long_local,
277 total_int_decls: self.total_int_decls,
278 total_string_decls: self.total_string_decls,
279 total_long_decls: self.total_long_decls,
280 }
281 }
282
283 pub fn define(&mut self, name: String, kind: SymbolKind) {
285 self.symbols.insert(name.clone(), Symbol { name, kind });
286 }
287
288 pub fn define_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
292 if !is_array {
294 match var_type.base_type() {
295 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
296 crate::types::BaseVarType::String => self.total_string_decls += 1,
297 crate::types::BaseVarType::Long => self.total_long_decls += 1,
298 }
299 }
300 let new_slot = self.allocate_slot(&var_type);
306 let slot = if let Some(existing) = self.symbols.get(&name) {
307 match &existing.kind {
308 SymbolKind::LocalVar { slot, .. } => *slot,
309 _ => new_slot,
310 }
311 } else {
312 new_slot
313 };
314 self.define(
315 name,
316 SymbolKind::LocalVar {
317 var_type,
318 slot,
319 is_array,
320 },
321 );
322 slot
323 }
324
325 pub fn define_param(&mut self, name: String, param_type: Type) -> i32 {
327 match param_type.base_type() {
328 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
329 crate::types::BaseVarType::String => self.total_string_decls += 1,
330 crate::types::BaseVarType::Long => self.total_long_decls += 1,
331 }
332 let slot = self.allocate_slot(¶m_type);
333 self.define(name, SymbolKind::ScriptParam { param_type, slot });
334 slot
335 }
336
337 fn allocate_slot(&mut self, var_type: &Type) -> i32 {
339 match var_type.base_type() {
340 crate::types::BaseVarType::Integer => {
341 let slot = self.next_int_local;
342 self.next_int_local += 1;
343 slot
344 }
345 crate::types::BaseVarType::String => {
346 let slot = self.next_string_local;
347 self.next_string_local += 1;
348 slot
349 }
350 crate::types::BaseVarType::Long => {
351 let slot = self.next_long_local;
352 self.next_long_local += 1;
353 slot
354 }
355 }
356 }
357
358 pub fn lookup(&self, name: &str) -> Option<&Symbol> {
360 if let Some(sym) = self.symbols.get(name) {
361 return Some(sym);
362 }
363 if let Some(parent) = &self.parent {
364 return parent.lookup(name);
365 }
366 None
367 }
368
369 pub fn lookup_local(&self, name: &str) -> Option<&Symbol> {
371 self.symbols.get(name)
372 }
373
374 pub fn contains(&self, name: &str) -> bool {
376 self.lookup(name).is_some()
377 }
378
379 pub fn save_slots(&self) -> (i32, i32, i32) {
381 (
382 self.next_int_local,
383 self.next_string_local,
384 self.next_long_local,
385 )
386 }
387
388 pub fn restore_slots(&mut self, saved: (i32, i32, i32)) {
392 self.next_int_local = saved.0;
393 self.next_string_local = saved.1;
394 self.next_long_local = saved.2;
395 }
396
397 pub fn merge_slots(&mut self, other: (i32, i32, i32)) {
400 self.next_int_local = self.next_int_local.max(other.0);
401 self.next_string_local = self.next_string_local.max(other.1);
402 self.next_long_local = self.next_long_local.max(other.2);
403 }
404
405 pub fn merge_decls(&mut self, child: &SymbolTable) {
407 self.total_int_decls = child.total_int_decls;
408 self.total_string_decls = child.total_string_decls;
409 self.total_long_decls = child.total_long_decls;
410 }
411
412 pub fn int_local_count(&self) -> u16 {
414 self.total_int_decls as u16
415 }
416
417 pub fn string_local_count(&self) -> u16 {
419 self.total_string_decls as u16
420 }
421
422 pub fn long_local_count(&self) -> u16 {
424 self.total_long_decls as u16
425 }
426
427 pub fn reset_locals(&mut self) {
429 self.next_int_local = 0;
430 self.next_string_local = 0;
431 self.next_long_local = 0;
432 }
433
434 pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
436 self.symbols.iter()
437 }
438}
439
440#[derive(Debug, Clone)]
448pub struct SymbolRegistry {
449 pub(crate) scripts: HashMap<String, Arc<Symbol>>,
453 pub(crate) commands: HashMap<String, Symbol>,
455 pub(crate) game_vars: HashMap<String, Symbol>,
457 pub(crate) constants: HashMap<String, Symbol>,
459 pub(crate) entity_ids: HashMap<String, EntityEntry>,
465 pub(crate) command_param_types: HashMap<String, Vec<Type>>,
468 pub(crate) type_chars: HashMap<String, i32>,
471 pub(crate) script_ids: HashMap<String, i32>,
473 pub(crate) proc_script_ids: HashMap<String, i32>,
475 pub(crate) label_script_ids: HashMap<String, i32>,
477 pub(crate) trigger_script_ids: HashMap<String, i32>,
480 pub(crate) scripts_by_trigger: HashMap<String, Arc<Symbol>>,
485 pub(crate) preloaded_script_ids: HashMap<String, i32>,
488 pub(crate) dbcolumn_types: HashMap<String, Type>,
491 pub(crate) components: HashMap<String, i32>,
493 pub(crate) interface_ids: HashMap<String, i32>,
495 pub(crate) test_scripts: HashSet<String>,
497 next_script_id: i32,
499}
500
501impl Default for SymbolRegistry {
502 fn default() -> Self {
503 Self::new()
504 }
505}
506
507impl SymbolRegistry {
508 pub fn new() -> Self {
509 SymbolRegistry {
510 scripts: HashMap::new(),
511 commands: HashMap::new(),
512 game_vars: HashMap::new(),
513 constants: HashMap::new(),
514 entity_ids: HashMap::new(),
515 command_param_types: HashMap::new(),
516 type_chars: HashMap::new(),
517 script_ids: HashMap::new(),
518 proc_script_ids: HashMap::new(),
519 label_script_ids: HashMap::new(),
520 trigger_script_ids: HashMap::new(),
521 scripts_by_trigger: HashMap::new(),
522 preloaded_script_ids: HashMap::new(),
523 dbcolumn_types: HashMap::new(),
524 components: HashMap::new(),
525 interface_ids: HashMap::new(),
526 test_scripts: HashSet::new(),
527 next_script_id: 0,
528 }
529 }
530
531 pub fn register_script(
533 &mut self,
534 name: String,
535 trigger: String,
536 param_types: Vec<Type>,
537 return_types: Vec<Type>,
538 ) -> i32 {
539 let key = format!("{}:{}", trigger, name);
540 let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
541 preloaded
542 } else {
543 let id = self.next_script_id;
544 self.next_script_id += 1;
545 id
546 };
547
548 if trigger == "proc" {
552 self.proc_script_ids.insert(name.clone(), id);
553 } else if trigger == "label" {
554 self.label_script_ids.insert(name.clone(), id);
555 }
556 let symbol = Arc::new(Symbol {
560 name: name.clone(),
561 kind: SymbolKind::Script {
562 id,
563 trigger,
564 param_types,
565 return_types,
566 },
567 });
568 self.scripts_by_trigger.insert(key, Arc::clone(&symbol));
569 self.scripts.insert(name, symbol);
570
571 id
572 }
573
574 pub fn register_command(
576 &mut self,
577 name: String,
578 opcode: i32,
579 param_types: Vec<Type>,
580 return_types: Vec<Type>,
581 ) {
582 self.command_param_types
583 .insert(name.clone(), param_types.clone());
584 self.commands.insert(
585 name.clone(),
586 Symbol {
587 name,
588 kind: SymbolKind::Command {
589 opcode,
590 param_types,
591 return_types,
592 },
593 },
594 );
595 }
596
597 pub fn register_game_var(
599 &mut self,
600 name: String,
601 var_type: Type,
602 var_id: i32,
603 category: String,
604 ) {
605 self.game_vars.insert(
606 name.clone(),
607 Symbol {
608 name,
609 kind: SymbolKind::GameVar {
610 var_type,
611 var_id,
612 category,
613 },
614 },
615 );
616 }
617
618 pub fn register_constant(
620 &mut self,
621 name: String,
622 const_type: Type,
623 int_value: Option<i32>,
624 string_value: Option<String>,
625 ) {
626 self.constants.insert(
627 name.clone(),
628 Symbol {
629 name,
630 kind: SymbolKind::Constant {
631 const_type,
632 int_value,
633 string_value,
634 },
635 },
636 );
637 }
638
639 pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
643 let entry = self.entity_ids.entry(name).or_default();
644 entry.primary = Some(EntityRef {
646 const_type: entity_type,
647 id,
648 });
649 entry.set_variant(entity_type, id);
650 }
651
652 pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
662 self.entity_ids
663 .entry(name)
664 .or_default()
665 .set_variant(entity_type, id);
666 }
667
668 pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
672 let normalized = name.to_lowercase().replace(' ', "_");
673 self.entity_ids
674 .get(&normalized)
675 .and_then(|e| e.variants.iter().find(|(t, _)| *t == expected))
676 .map(|(_, id)| *id)
677 }
678
679 pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
681 self.scripts.get(name).map(|s| s.as_ref())
682 }
683
684 pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
686 self.scripts_by_trigger
687 .get(&format!("{}:{}", trigger, name))
688 .map(|s| s.as_ref())
689 }
690
691 pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
693 self.commands.get(name)
694 }
695
696 pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
698 self.game_vars.get(name)
699 }
700
701 pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
703 self.constants.get(name)
704 }
705
706 pub fn lookup_entity_id(&self, name: &str) -> Option<EntityRef> {
709 let normalized = name.to_lowercase().replace(' ', "_");
710 self.entity_ids.get(&normalized).and_then(|e| e.primary)
711 }
712
713 pub(crate) fn drop_registration_scratch(&mut self) {
718 self.preloaded_script_ids = HashMap::new();
719 }
720
721 pub fn script_id(&self, name: &str) -> Option<i32> {
727 if let Some(s) = self.scripts.get(name)
728 && let SymbolKind::Script { id, .. } = &s.kind
729 {
730 return Some(*id);
731 }
732 self.script_ids.get(name).copied()
733 }
734
735 pub fn proc_script_id(&self, name: &str) -> Option<i32> {
737 self.proc_script_ids.get(name).copied()
738 }
739
740 pub fn label_script_id(&self, name: &str) -> Option<i32> {
742 self.label_script_ids.get(name).copied()
743 }
744
745 pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
746 let key = format!("{}:{}", trigger, name);
747 if let Some(s) = self.scripts_by_trigger.get(&key)
748 && let SymbolKind::Script { id, .. } = &s.kind
749 {
750 return Some(*id);
751 }
752 self.trigger_script_ids.get(&key).copied()
755 }
756
757 pub fn command_opcode(&self, name: &str) -> Option<i32> {
758 self.commands.get(name).and_then(|sym| {
759 if let SymbolKind::Command { opcode, .. } = &sym.kind {
760 Some(*opcode)
761 } else {
762 None
763 }
764 })
765 }
766
767 pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
768 self.test_scripts.insert(format!("{}:{}", trigger, name));
769 }
770
771 pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
772 self.test_scripts.contains(&format!("{}:{}", trigger, name))
773 }
774
775 pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
780 let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
781 self.components.get(&key).copied()
782 }
783}
784
785pub(crate) fn normalize_comp_name(name: &str) -> String {
788 let bytes = name.as_bytes();
789 let mut out = Vec::with_capacity(bytes.len());
790 let mut i = 0;
791 while i < bytes.len() {
792 if bytes[i] == b'_'
793 && i > 0
794 && bytes[i - 1].is_ascii_alphabetic()
795 && i + 1 < bytes.len()
796 && bytes[i + 1].is_ascii_digit()
797 {
798 i += 1;
799 continue;
800 }
801 out.push(bytes[i]);
802 i += 1;
803 }
804 unsafe { String::from_utf8_unchecked(out) }
805}
806
807#[cfg(test)]
808mod tests {
809 use super::*;
810
811 #[test]
814 fn normalize_strips_underscore_before_digits() {
815 assert_eq!(normalize_comp_name("com_2"), "com2");
816 assert_eq!(normalize_comp_name("com_10"), "com10");
817 assert_eq!(normalize_comp_name("com_0"), "com0");
818 }
819
820 #[test]
821 fn normalize_preserves_already_compact_names() {
822 assert_eq!(normalize_comp_name("com2"), "com2");
823 assert_eq!(normalize_comp_name("com10"), "com10");
824 assert_eq!(normalize_comp_name("com0"), "com0");
825 }
826
827 #[test]
828 fn normalize_preserves_non_digit_underscores() {
829 assert_eq!(normalize_comp_name("close_button"), "close_button");
830 assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
831 assert_eq!(normalize_comp_name("title"), "title");
832 }
833
834 #[test]
835 fn normalize_only_strips_alpha_digit_boundary() {
836 assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
838 assert_eq!(normalize_comp_name("3_panel"), "3_panel");
840 }
841
842 fn registry_647_style() -> SymbolRegistry {
845 let mut r = SymbolRegistry::new();
846 r.interface_ids.insert("multi2".into(), 228);
847 for i in 0..10 {
849 let key = format!("multi2:com{}", i);
850 r.components.insert(key, (228 << 16) | i);
851 }
852 r
853 }
854
855 #[test]
856 fn lookup_647_pack_with_647_reference() {
857 let r = registry_647_style();
858 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
860 assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
861 }
862
863 #[test]
864 fn lookup_647_pack_with_225_reference() {
865 let r = registry_647_style();
866 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
868 assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
869 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
870 }
871
872 fn registry_225_style() -> SymbolRegistry {
875 let mut r = SymbolRegistry::new();
876 r.interface_ids.insert("multi2".into(), 228);
877 for i in 0..10 {
880 let key = format!("multi2:com{}", i);
881 r.components.insert(key, 2459 + i);
882 }
883 r
884 }
885
886 #[test]
887 fn lookup_225_pack_with_225_reference() {
888 let r = registry_225_style();
889 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
890 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
891 }
892
893 #[test]
894 fn lookup_225_pack_with_647_reference() {
895 let r = registry_225_style();
896 assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
897 assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
898 }
899
900 #[test]
903 fn lookup_returns_none_for_unknown_component() {
904 let r = registry_647_style();
905 assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
906 assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
907 }
908}