1use crate::types::{BaseVarType, Type};
2use std::collections::HashMap;
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 next_script_id: i32,
453}
454
455impl Default for SymbolRegistry {
456 fn default() -> Self {
457 Self::new()
458 }
459}
460
461impl SymbolRegistry {
462 pub fn new() -> Self {
463 SymbolRegistry {
464 scripts: HashMap::new(),
465 commands: HashMap::new(),
466 game_vars: HashMap::new(),
467 constants: HashMap::new(),
468 entity_ids: HashMap::new(),
469 entity_ids_typed: HashMap::new(),
470 command_param_types: HashMap::new(),
471 type_chars: HashMap::new(),
472 script_ids: HashMap::new(),
473 proc_script_ids: HashMap::new(),
474 label_script_ids: HashMap::new(),
475 trigger_script_ids: HashMap::new(),
476 scripts_by_trigger: HashMap::new(),
477 preloaded_script_ids: HashMap::new(),
478 dbcolumn_types: HashMap::new(),
479 components: HashMap::new(),
480 interface_ids: HashMap::new(),
481 next_script_id: 0,
482 }
483 }
484
485 pub fn register_script(
487 &mut self,
488 name: String,
489 trigger: String,
490 param_types: Vec<Type>,
491 return_types: Vec<Type>,
492 ) -> i32 {
493 let key = format!("{}:{}", trigger, name);
494 let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
495 preloaded
496 } else {
497 let id = self.next_script_id;
498 self.next_script_id += 1;
499 id
500 };
501
502 self.script_ids.insert(name.clone(), id);
503 self.trigger_script_ids
505 .insert(format!("{}:{}", trigger, name), id);
506 if trigger == "proc" {
507 self.proc_script_ids.insert(name.clone(), id);
508 } else if trigger == "label" {
509 self.label_script_ids.insert(name.clone(), id);
510 }
511 let symbol = Symbol {
512 name: name.clone(),
513 kind: SymbolKind::Script {
514 id,
515 trigger: trigger.clone(),
516 param_types,
517 return_types,
518 },
519 };
520 self.scripts_by_trigger
521 .insert(format!("{}:{}", trigger, name), symbol.clone());
522 self.scripts.insert(name, symbol);
523
524 id
525 }
526
527 pub fn register_command(
529 &mut self,
530 name: String,
531 opcode: i32,
532 param_types: Vec<Type>,
533 return_types: Vec<Type>,
534 ) {
535 self.commands.insert(
536 name.clone(),
537 Symbol {
538 name,
539 kind: SymbolKind::Command {
540 opcode,
541 param_types,
542 return_types,
543 },
544 },
545 );
546 }
547
548 pub fn register_game_var(
550 &mut self,
551 name: String,
552 var_type: Type,
553 var_id: i32,
554 category: String,
555 ) {
556 self.game_vars.insert(
557 name.clone(),
558 Symbol {
559 name,
560 kind: SymbolKind::GameVar {
561 var_type,
562 var_id,
563 category,
564 },
565 },
566 );
567 }
568
569 pub fn register_constant(
571 &mut self,
572 name: String,
573 const_type: Type,
574 int_value: Option<i32>,
575 string_value: Option<String>,
576 ) {
577 self.constants.insert(
578 name.clone(),
579 Symbol {
580 name,
581 kind: SymbolKind::Constant {
582 const_type,
583 int_value,
584 string_value,
585 },
586 },
587 );
588 }
589
590 pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
594 self.entity_ids_typed
596 .entry(name.clone())
597 .or_default()
598 .insert(entity_type, id);
599
600 self.entity_ids.insert(
602 name.clone(),
603 Symbol {
604 name,
605 kind: SymbolKind::Constant {
606 const_type: entity_type,
607 int_value: Some(id),
608 string_value: None,
609 },
610 },
611 );
612 }
613
614 pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
618 let normalized = name.to_lowercase().replace(' ', "_");
619 self.entity_ids_typed
620 .get(&normalized)
621 .and_then(|m| m.get(&expected))
622 .copied()
623 }
624
625 pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
627 self.scripts.get(name)
628 }
629
630 pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
632 self.scripts_by_trigger
633 .get(&format!("{}:{}", trigger, name))
634 }
635
636 pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
638 self.commands.get(name)
639 }
640
641 pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
643 self.game_vars.get(name)
644 }
645
646 pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
648 self.constants.get(name)
649 }
650
651 pub fn lookup_entity_id(&self, name: &str) -> Option<&Symbol> {
654 let normalized = name.to_lowercase().replace(' ', "_");
655 self.entity_ids.get(&normalized)
656 }
657
658 pub fn script_id(&self, name: &str) -> Option<i32> {
660 self.script_ids.get(name).copied()
661 }
662
663 pub fn proc_script_id(&self, name: &str) -> Option<i32> {
665 self.proc_script_ids.get(name).copied()
666 }
667
668 pub fn label_script_id(&self, name: &str) -> Option<i32> {
670 self.label_script_ids.get(name).copied()
671 }
672
673 pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
674 self.trigger_script_ids
675 .get(&format!("{}:{}", trigger, name))
676 .copied()
677 }
678
679 pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
684 let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
685 self.components.get(&key).copied()
686 }
687}
688
689pub(crate) fn normalize_comp_name(name: &str) -> String {
692 let bytes = name.as_bytes();
693 let mut out = Vec::with_capacity(bytes.len());
694 let mut i = 0;
695 while i < bytes.len() {
696 if bytes[i] == b'_'
697 && i > 0
698 && bytes[i - 1].is_ascii_alphabetic()
699 && i + 1 < bytes.len()
700 && bytes[i + 1].is_ascii_digit()
701 {
702 i += 1;
703 continue;
704 }
705 out.push(bytes[i]);
706 i += 1;
707 }
708 unsafe { String::from_utf8_unchecked(out) }
709}
710
711#[cfg(test)]
712mod tests {
713 use super::*;
714
715 #[test]
718 fn normalize_strips_underscore_before_digits() {
719 assert_eq!(normalize_comp_name("com_2"), "com2");
720 assert_eq!(normalize_comp_name("com_10"), "com10");
721 assert_eq!(normalize_comp_name("com_0"), "com0");
722 }
723
724 #[test]
725 fn normalize_preserves_already_compact_names() {
726 assert_eq!(normalize_comp_name("com2"), "com2");
727 assert_eq!(normalize_comp_name("com10"), "com10");
728 assert_eq!(normalize_comp_name("com0"), "com0");
729 }
730
731 #[test]
732 fn normalize_preserves_non_digit_underscores() {
733 assert_eq!(normalize_comp_name("close_button"), "close_button");
734 assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
735 assert_eq!(normalize_comp_name("title"), "title");
736 }
737
738 #[test]
739 fn normalize_only_strips_alpha_digit_boundary() {
740 assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
742 assert_eq!(normalize_comp_name("3_panel"), "3_panel");
744 }
745
746 fn registry_647_style() -> SymbolRegistry {
749 let mut r = SymbolRegistry::new();
750 r.interface_ids.insert("multi2".into(), 228);
751 for i in 0..10 {
753 let key = format!("multi2:com{}", i);
754 r.components.insert(key, (228 << 16) | i);
755 }
756 r
757 }
758
759 #[test]
760 fn lookup_647_pack_with_647_reference() {
761 let r = registry_647_style();
762 assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
764 assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
765 }
766
767 #[test]
768 fn lookup_647_pack_with_225_reference() {
769 let r = registry_647_style();
770 assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
772 assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
773 assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
774 }
775
776 fn registry_225_style() -> SymbolRegistry {
779 let mut r = SymbolRegistry::new();
780 r.interface_ids.insert("multi2".into(), 228);
781 for i in 0..10 {
784 let key = format!("multi2:com{}", i);
785 r.components.insert(key, 2459 + i);
786 }
787 r
788 }
789
790 #[test]
791 fn lookup_225_pack_with_225_reference() {
792 let r = registry_225_style();
793 assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
794 assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
795 }
796
797 #[test]
798 fn lookup_225_pack_with_647_reference() {
799 let r = registry_225_style();
800 assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
801 assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
802 }
803
804 #[test]
807 fn lookup_returns_none_for_unknown_component() {
808 let r = registry_647_style();
809 assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
810 assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
811 }
812}