1use crate::types::{BaseVarType, Type};
2use std::collections::{HashMap, HashSet};
3
4#[derive(Debug, Clone)]
10pub struct LocalEntry {
11 pub name: String,
12 pub var_type: Type,
13 pub is_param: bool,
14 pub is_array: bool,
15}
16
17#[derive(Debug, Clone, Default)]
24pub struct LocalTable {
25 pub(crate) all: Vec<LocalEntry>,
26}
27
28impl LocalTable {
29 pub fn new() -> Self {
30 LocalTable { all: Vec::new() }
31 }
32
33 pub fn entries(&self) -> &[LocalEntry] {
35 &self.all
36 }
37
38 pub fn push_param(&mut self, name: String, param_type: Type) -> i32 {
39 let id = self.get_variable_id_for_next(param_type, false);
40 self.all.push(LocalEntry {
41 name,
42 var_type: param_type,
43 is_param: true,
44 is_array: false,
45 });
46 id
47 }
48
49 pub fn push_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
50 let id = self.get_variable_id_for_next(var_type, is_array);
51 self.all.push(LocalEntry {
52 name,
53 var_type,
54 is_param: false,
55 is_array,
56 });
57 id
58 }
59
60 fn get_variable_id_for_next(&self, var_type: Type, is_array: bool) -> i32 {
62 if is_array {
63 self.all.iter().filter(|e| e.is_array).count() as i32
64 } else {
65 self.all
66 .iter()
67 .filter(|e| {
68 e.var_type.base_type() == var_type.base_type() && (!e.is_array || e.is_param)
69 })
70 .count() as i32
71 }
72 }
73
74 pub fn get_variable_id(&self, index: usize) -> i32 {
76 let entry = &self.all[index];
77 if entry.is_array {
78 self.all[..index].iter().filter(|e| e.is_array).count() as i32
79 } else {
80 self.all[..index]
81 .iter()
82 .filter(|e| {
83 e.var_type.base_type() == entry.var_type.base_type()
84 && (!e.is_array || e.is_param)
85 })
86 .count() as i32
87 }
88 }
89
90 pub fn get_local_count(&self, base: BaseVarType) -> u16 {
92 self.all
93 .iter()
94 .filter(|e| e.var_type.base_type() == base && (!e.is_array || e.is_param))
95 .count() as u16
96 }
97
98 pub fn get_param_count(&self, base: BaseVarType) -> u16 {
100 self.all
101 .iter()
102 .filter(|e| e.is_param && e.var_type.base_type() == base)
103 .count() as u16
104 }
105}
106
107#[derive(Debug, Clone)]
111pub enum SymbolKind {
112 LocalVar {
114 var_type: Type,
115 slot: i32,
117 is_array: bool,
118 },
119 ScriptParam { param_type: Type, slot: i32 },
121 Script {
123 id: i32,
124 trigger: String,
125 param_types: Vec<Type>,
126 return_types: Vec<Type>,
127 },
128 GameVar {
130 var_type: Type,
131 var_id: i32,
132 category: String,
134 },
135 Constant {
137 const_type: Type,
138 int_value: Option<i32>,
139 string_value: Option<String>,
140 },
141 Command {
143 opcode: i32,
144 param_types: Vec<Type>,
145 return_types: Vec<Type>,
146 },
147}
148
149impl SymbolKind {
150 pub fn kind_name(&self) -> &'static str {
151 match self {
152 SymbolKind::LocalVar { .. } => "LocalVar",
153 SymbolKind::ScriptParam { .. } => "ScriptParam",
154 SymbolKind::Script { .. } => "Script",
155 SymbolKind::GameVar { .. } => "GameVar",
156 SymbolKind::Constant { .. } => "Constant",
157 SymbolKind::Command { .. } => "Command",
158 }
159 }
160}
161
162#[derive(Debug, Clone)]
164pub struct Symbol {
165 pub name: String,
166 pub kind: SymbolKind,
167}
168
169#[derive(Debug, Clone)]
171pub struct SymbolTable {
172 symbols: HashMap<String, Symbol>,
174 parent: Option<Box<SymbolTable>>,
176 next_int_local: i32,
178 next_string_local: i32,
179 next_long_local: i32,
180 total_int_decls: i32,
183 total_string_decls: i32,
184 total_long_decls: i32,
185}
186
187impl Default for SymbolTable {
188 fn default() -> Self {
189 Self::new()
190 }
191}
192
193impl SymbolTable {
194 pub fn new() -> Self {
195 SymbolTable {
196 symbols: HashMap::new(),
197 parent: None,
198 next_int_local: 0,
199 next_string_local: 0,
200 next_long_local: 0,
201 total_int_decls: 0,
202 total_string_decls: 0,
203 total_long_decls: 0,
204 }
205 }
206
207 pub fn child(parent: SymbolTable) -> Self {
209 let int_local = parent.next_int_local;
210 let string_local = parent.next_string_local;
211 let long_local = parent.next_long_local;
212 let int_decls = parent.total_int_decls;
213 let string_decls = parent.total_string_decls;
214 let long_decls = parent.total_long_decls;
215 SymbolTable {
216 symbols: HashMap::new(),
217 parent: Some(Box::new(parent)),
218 next_int_local: int_local,
219 next_string_local: string_local,
220 next_long_local: long_local,
221 total_int_decls: int_decls,
222 total_string_decls: string_decls,
223 total_long_decls: long_decls,
224 }
225 }
226
227 pub fn new_child(&self) -> Self {
229 SymbolTable {
230 symbols: HashMap::new(),
231 parent: Some(Box::new(self.clone())),
232 next_int_local: self.next_int_local,
233 next_string_local: self.next_string_local,
234 next_long_local: self.next_long_local,
235 total_int_decls: self.total_int_decls,
236 total_string_decls: self.total_string_decls,
237 total_long_decls: self.total_long_decls,
238 }
239 }
240
241 pub fn define(&mut self, name: String, kind: SymbolKind) {
243 self.symbols.insert(name.clone(), Symbol { name, kind });
244 }
245
246 pub fn define_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
250 if !is_array {
252 match var_type.base_type() {
253 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
254 crate::types::BaseVarType::String => self.total_string_decls += 1,
255 crate::types::BaseVarType::Long => self.total_long_decls += 1,
256 }
257 }
258 let new_slot = self.allocate_slot(&var_type);
264 let slot = if let Some(existing) = self.symbols.get(&name) {
265 match &existing.kind {
266 SymbolKind::LocalVar { slot, .. } => *slot,
267 _ => new_slot,
268 }
269 } else {
270 new_slot
271 };
272 self.define(
273 name,
274 SymbolKind::LocalVar {
275 var_type,
276 slot,
277 is_array,
278 },
279 );
280 slot
281 }
282
283 pub fn define_param(&mut self, name: String, param_type: Type) -> i32 {
285 match param_type.base_type() {
286 crate::types::BaseVarType::Integer => self.total_int_decls += 1,
287 crate::types::BaseVarType::String => self.total_string_decls += 1,
288 crate::types::BaseVarType::Long => self.total_long_decls += 1,
289 }
290 let slot = self.allocate_slot(¶m_type);
291 self.define(name, SymbolKind::ScriptParam { param_type, slot });
292 slot
293 }
294
295 fn allocate_slot(&mut self, var_type: &Type) -> i32 {
297 match var_type.base_type() {
298 crate::types::BaseVarType::Integer => {
299 let slot = self.next_int_local;
300 self.next_int_local += 1;
301 slot
302 }
303 crate::types::BaseVarType::String => {
304 let slot = self.next_string_local;
305 self.next_string_local += 1;
306 slot
307 }
308 crate::types::BaseVarType::Long => {
309 let slot = self.next_long_local;
310 self.next_long_local += 1;
311 slot
312 }
313 }
314 }
315
316 pub fn lookup(&self, name: &str) -> Option<&Symbol> {
318 if let Some(sym) = self.symbols.get(name) {
319 return Some(sym);
320 }
321 if let Some(parent) = &self.parent {
322 return parent.lookup(name);
323 }
324 None
325 }
326
327 pub fn lookup_local(&self, name: &str) -> Option<&Symbol> {
329 self.symbols.get(name)
330 }
331
332 pub fn contains(&self, name: &str) -> bool {
334 self.lookup(name).is_some()
335 }
336
337 pub fn save_slots(&self) -> (i32, i32, i32) {
339 (
340 self.next_int_local,
341 self.next_string_local,
342 self.next_long_local,
343 )
344 }
345
346 pub fn restore_slots(&mut self, saved: (i32, i32, i32)) {
350 self.next_int_local = saved.0;
351 self.next_string_local = saved.1;
352 self.next_long_local = saved.2;
353 }
354
355 pub fn merge_slots(&mut self, other: (i32, i32, i32)) {
358 self.next_int_local = self.next_int_local.max(other.0);
359 self.next_string_local = self.next_string_local.max(other.1);
360 self.next_long_local = self.next_long_local.max(other.2);
361 }
362
363 pub fn merge_decls(&mut self, child: &SymbolTable) {
365 self.total_int_decls = child.total_int_decls;
366 self.total_string_decls = child.total_string_decls;
367 self.total_long_decls = child.total_long_decls;
368 }
369
370 pub fn int_local_count(&self) -> u16 {
372 self.total_int_decls as u16
373 }
374
375 pub fn string_local_count(&self) -> u16 {
377 self.total_string_decls as u16
378 }
379
380 pub fn long_local_count(&self) -> u16 {
382 self.total_long_decls as u16
383 }
384
385 pub fn reset_locals(&mut self) {
387 self.next_int_local = 0;
388 self.next_string_local = 0;
389 self.next_long_local = 0;
390 }
391
392 pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
394 self.symbols.iter()
395 }
396}
397
398#[derive(Debug, Clone)]
406pub struct SymbolRegistry {
407 pub(crate) scripts: HashMap<String, Symbol>,
409 pub(crate) commands: HashMap<String, Symbol>,
411 pub(crate) game_vars: HashMap<String, Symbol>,
413 pub(crate) constants: HashMap<String, Symbol>,
415 pub(crate) entity_ids: HashMap<String, Symbol>,
418 pub(crate) entity_ids_typed: HashMap<String, HashMap<Type, i32>>,
422 pub(crate) command_param_types: HashMap<String, Vec<Type>>,
425 pub(crate) type_chars: HashMap<String, i32>,
428 pub(crate) script_ids: HashMap<String, i32>,
430 pub(crate) proc_script_ids: HashMap<String, i32>,
432 pub(crate) label_script_ids: HashMap<String, i32>,
434 pub(crate) trigger_script_ids: HashMap<String, i32>,
437 pub(crate) scripts_by_trigger: HashMap<String, Symbol>,
441 pub(crate) preloaded_script_ids: HashMap<String, i32>,
444 pub(crate) dbcolumn_types: HashMap<String, Type>,
447 pub(crate) components: HashMap<String, i32>,
449 pub(crate) interface_ids: HashMap<String, i32>,
451 pub(crate) test_scripts: HashSet<String>,
453 next_script_id: i32,
455}
456
457impl Default for SymbolRegistry {
458 fn default() -> Self {
459 Self::new()
460 }
461}
462
463impl SymbolRegistry {
464 pub fn new() -> Self {
465 SymbolRegistry {
466 scripts: HashMap::new(),
467 commands: HashMap::new(),
468 game_vars: HashMap::new(),
469 constants: HashMap::new(),
470 entity_ids: HashMap::new(),
471 entity_ids_typed: HashMap::new(),
472 command_param_types: HashMap::new(),
473 type_chars: HashMap::new(),
474 script_ids: HashMap::new(),
475 proc_script_ids: HashMap::new(),
476 label_script_ids: HashMap::new(),
477 trigger_script_ids: HashMap::new(),
478 scripts_by_trigger: HashMap::new(),
479 preloaded_script_ids: HashMap::new(),
480 dbcolumn_types: HashMap::new(),
481 components: HashMap::new(),
482 interface_ids: HashMap::new(),
483 test_scripts: HashSet::new(),
484 next_script_id: 0,
485 }
486 }
487
488 pub fn register_script(
490 &mut self,
491 name: String,
492 trigger: String,
493 param_types: Vec<Type>,
494 return_types: Vec<Type>,
495 ) -> i32 {
496 let key = format!("{}:{}", trigger, name);
497 let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
498 preloaded
499 } else {
500 let id = self.next_script_id;
501 self.next_script_id += 1;
502 id
503 };
504
505 self.script_ids.insert(name.clone(), id);
506 self.trigger_script_ids
508 .insert(format!("{}:{}", trigger, name), id);
509 if trigger == "proc" {
510 self.proc_script_ids.insert(name.clone(), id);
511 } else if trigger == "label" {
512 self.label_script_ids.insert(name.clone(), id);
513 }
514 let symbol = Symbol {
515 name: name.clone(),
516 kind: SymbolKind::Script {
517 id,
518 trigger: trigger.clone(),
519 param_types,
520 return_types,
521 },
522 };
523 self.scripts_by_trigger
524 .insert(format!("{}:{}", trigger, name), symbol.clone());
525 self.scripts.insert(name, symbol);
526
527 id
528 }
529
530 pub fn register_command(
532 &mut self,
533 name: String,
534 opcode: i32,
535 param_types: Vec<Type>,
536 return_types: Vec<Type>,
537 ) {
538 self.command_param_types
539 .insert(name.clone(), param_types.clone());
540 self.commands.insert(
541 name.clone(),
542 Symbol {
543 name,
544 kind: SymbolKind::Command {
545 opcode,
546 param_types,
547 return_types,
548 },
549 },
550 );
551 }
552
553 pub fn register_game_var(
555 &mut self,
556 name: String,
557 var_type: Type,
558 var_id: i32,
559 category: String,
560 ) {
561 self.game_vars.insert(
562 name.clone(),
563 Symbol {
564 name,
565 kind: SymbolKind::GameVar {
566 var_type,
567 var_id,
568 category,
569 },
570 },
571 );
572 }
573
574 pub fn register_constant(
576 &mut self,
577 name: String,
578 const_type: Type,
579 int_value: Option<i32>,
580 string_value: Option<String>,
581 ) {
582 self.constants.insert(
583 name.clone(),
584 Symbol {
585 name,
586 kind: SymbolKind::Constant {
587 const_type,
588 int_value,
589 string_value,
590 },
591 },
592 );
593 }
594
595 pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
599 self.entity_ids_typed
601 .entry(name.clone())
602 .or_default()
603 .insert(entity_type, id);
604
605 self.entity_ids.insert(
607 name.clone(),
608 Symbol {
609 name,
610 kind: SymbolKind::Constant {
611 const_type: entity_type,
612 int_value: Some(id),
613 string_value: None,
614 },
615 },
616 );
617 }
618
619 pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
629 self.entity_ids_typed
630 .entry(name)
631 .or_default()
632 .insert(entity_type, id);
633 }
634
635 pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
639 let normalized = name.to_lowercase().replace(' ', "_");
640 self.entity_ids_typed
641 .get(&normalized)
642 .and_then(|m| m.get(&expected))
643 .copied()
644 }
645
646 pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
648 self.scripts.get(name)
649 }
650
651 pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
653 self.scripts_by_trigger
654 .get(&format!("{}:{}", trigger, name))
655 }
656
657 pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
659 self.commands.get(name)
660 }
661
662 pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
664 self.game_vars.get(name)
665 }
666
667 pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
669 self.constants.get(name)
670 }
671
672 pub fn lookup_entity_id(&self, name: &str) -> Option<&Symbol> {
675 let normalized = name.to_lowercase().replace(' ', "_");
676 self.entity_ids.get(&normalized)
677 }
678
679 pub fn script_id(&self, name: &str) -> Option<i32> {
681 self.script_ids.get(name).copied()
682 }
683
684 pub fn proc_script_id(&self, name: &str) -> Option<i32> {
686 self.proc_script_ids.get(name).copied()
687 }
688
689 pub fn label_script_id(&self, name: &str) -> Option<i32> {
691 self.label_script_ids.get(name).copied()
692 }
693
694 pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
695 self.trigger_script_ids
696 .get(&format!("{}:{}", trigger, name))
697 .copied()
698 }
699
700 pub fn command_opcode(&self, name: &str) -> Option<i32> {
701 self.commands.get(name).and_then(|sym| {
702 if let SymbolKind::Command { opcode, .. } = &sym.kind {
703 Some(*opcode)
704 } else {
705 None
706 }
707 })
708 }
709
710 pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
711 self.test_scripts.insert(format!("{}:{}", trigger, name));
712 }
713
714 pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
715 self.test_scripts.contains(&format!("{}:{}", trigger, name))
716 }
717
718 pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
723 let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
724 self.components.get(&key).copied()
725 }
726}
727
728pub(crate) fn normalize_comp_name(name: &str) -> String {
731 let bytes = name.as_bytes();
732 let mut out = Vec::with_capacity(bytes.len());
733 let mut i = 0;
734 while i < bytes.len() {
735 if bytes[i] == b'_'
736 && i > 0
737 && bytes[i - 1].is_ascii_alphabetic()
738 && i + 1 < bytes.len()
739 && bytes[i + 1].is_ascii_digit()
740 {
741 i += 1;
742 continue;
743 }
744 out.push(bytes[i]);
745 i += 1;
746 }
747 unsafe { String::from_utf8_unchecked(out) }
748}
749
750#[cfg(test)]
751mod tests {
752 use super::*;
753
754 #[test]
757 fn normalize_strips_underscore_before_digits() {
758 assert_eq!(normalize_comp_name("com_2"), "com2");
759 assert_eq!(normalize_comp_name("com_10"), "com10");
760 assert_eq!(normalize_comp_name("com_0"), "com0");
761 }
762
763 #[test]
764 fn normalize_preserves_already_compact_names() {
765 assert_eq!(normalize_comp_name("com2"), "com2");
766 assert_eq!(normalize_comp_name("com10"), "com10");
767 assert_eq!(normalize_comp_name("com0"), "com0");
768 }
769
770 #[test]
771 fn normalize_preserves_non_digit_underscores() {
772 assert_eq!(normalize_comp_name("close_button"), "close_button");
773 assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
774 assert_eq!(normalize_comp_name("title"), "title");
775 }
776
777 #[test]
778 fn normalize_only_strips_alpha_digit_boundary() {
779 assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
781 assert_eq!(normalize_comp_name("3_panel"), "3_panel");
783 }
784
785 fn registry_647_style() -> SymbolRegistry {
788 let mut r = SymbolRegistry::new();
789 r.interface_ids.insert("multi2".into(), 228);
790 for i in 0..10 {
792 let key = format!("multi2:com{}", i);
793 r.components.insert(key, (228 << 16) | i);
794 }
795 r
796 }
797
798 #[test]
799 fn lookup_647_pack_with_647_reference() {
800 let r = registry_647_style();
801 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
803 assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
804 }
805
806 #[test]
807 fn lookup_647_pack_with_225_reference() {
808 let r = registry_647_style();
809 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
811 assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
812 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
813 }
814
815 fn registry_225_style() -> SymbolRegistry {
818 let mut r = SymbolRegistry::new();
819 r.interface_ids.insert("multi2".into(), 228);
820 for i in 0..10 {
823 let key = format!("multi2:com{}", i);
824 r.components.insert(key, 2459 + i);
825 }
826 r
827 }
828
829 #[test]
830 fn lookup_225_pack_with_225_reference() {
831 let r = registry_225_style();
832 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
833 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
834 }
835
836 #[test]
837 fn lookup_225_pack_with_647_reference() {
838 let r = registry_225_style();
839 assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
840 assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
841 }
842
843 #[test]
846 fn lookup_returns_none_for_unknown_component() {
847 let r = registry_647_style();
848 assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
849 assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
850 }
851}