rs-runec 0.7.0

Compiler, linter, and language server for RuneScript, ClientScript, and GlobalScript, with ClientScript decompilation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
use crate::pointer::{PointerHolder, default_command_pointers};
use crate::types::{BaseVarType, Type};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;

pub(crate) fn normalize_entity_name(name: &str) -> std::borrow::Cow<'_, str> {
    if name.is_ascii()
        && !name
            .bytes()
            .any(|byte| byte.is_ascii_uppercase() || byte == b' ')
    {
        std::borrow::Cow::Borrowed(name)
    } else {
        std::borrow::Cow::Owned(name.to_lowercase().replace(' ', "_"))
    }
}

// ── LocalTable ─────────────────────────────────────────────────────────────
// Matches RuneScriptTS `LocalTable` (RuneScript.ts): a flat ordered list of
// all variable declarations within a script, used for slot assignment via
// `getVariableId` (indexOf in type-filtered sublist).

#[derive(Debug, Clone)]
pub struct LocalEntry {
    pub name: String,
    pub var_type: Type,
    pub is_param: bool,
    pub is_array: bool,
}

/// Flat ordered list of all variable declarations within a script.
///
/// `entries` is `pub(crate)` rather than `pub` so the storage shape
/// (currently a `Vec<LocalEntry>`) can change without breaking external
/// consumers. Read access from inside the crate goes through
/// `entries()`; mutations go through `push_param` / `push_local`.
#[derive(Debug, Clone, Default)]
pub struct LocalTable {
    pub(crate) all: Vec<LocalEntry>,
}

impl LocalTable {
    pub fn new() -> Self {
        LocalTable { all: Vec::new() }
    }

    /// Read-only view of the ordered local entries. Use this for iteration.
    pub fn entries(&self) -> &[LocalEntry] {
        &self.all
    }

    /// Release spare capacity once the table is final (post-codegen).
    pub fn shrink_to_fit(&mut self) {
        self.all.shrink_to_fit();
    }

    pub fn push_param(&mut self, name: String, param_type: Type) -> i32 {
        let id = self.get_variable_id_for_next(param_type, false);
        self.all.push(LocalEntry {
            name,
            var_type: param_type,
            is_param: true,
            is_array: false,
        });
        id
    }

    pub fn push_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
        let id = self.get_variable_id_for_next(var_type, is_array);
        self.all.push(LocalEntry {
            name,
            var_type,
            is_param: false,
            is_array,
        });
        id
    }

    /// Matches TS `getVariableId`: indexOf in filtered list.
    fn get_variable_id_for_next(&self, var_type: Type, is_array: bool) -> i32 {
        if is_array {
            self.all.iter().filter(|e| e.is_array).count() as i32
        } else {
            self.all
                .iter()
                .filter(|e| {
                    e.var_type.base_type() == var_type.base_type() && (!e.is_array || e.is_param)
                })
                .count() as i32
        }
    }

    /// Matches TS `getVariableId` for an existing entry by index.
    pub fn get_variable_id(&self, index: usize) -> i32 {
        let entry = &self.all[index];
        if entry.is_array {
            self.all[..index].iter().filter(|e| e.is_array).count() as i32
        } else {
            self.all[..index]
                .iter()
                .filter(|e| {
                    e.var_type.base_type() == entry.var_type.base_type()
                        && (!e.is_array || e.is_param)
                })
                .count() as i32
        }
    }

    /// Matches TS `getLocalCount`.
    pub fn get_local_count(&self, base: BaseVarType) -> u16 {
        self.all
            .iter()
            .filter(|e| e.var_type.base_type() == base && (!e.is_array || e.is_param))
            .count() as u16
    }

    /// Matches TS `getParameterCount`.
    pub fn get_param_count(&self, base: BaseVarType) -> u16 {
        self.all
            .iter()
            .filter(|e| e.is_param && e.var_type.base_type() == base)
            .count() as u16
    }
}

// ── SymbolKind ─────────────────────────────────────────────────────────────

/// The kind of symbol stored in the symbol table.
#[derive(Debug, Clone)]
pub enum SymbolKind {
    /// A local variable within a script.
    LocalVar {
        var_type: Type,
        /// The local variable slot index.
        slot: i32,
        is_array: bool,
    },
    /// A script parameter (like a local var but set from call args).
    ScriptParam { param_type: Type, slot: i32 },
    /// A compiled script (or script reference).
    Script {
        id: i32,
        trigger: String,
        param_types: Vec<Type>,
        return_types: Vec<Type>,
    },
    /// A game variable (varp, varn, vars, varpbit).
    GameVar {
        var_type: Type,
        var_id: i32,
        /// Which game var type: "varp", "varn", "vars", "varpbit"
        category: String,
    },
    /// A constant value.
    Constant {
        const_type: Type,
        int_value: Option<i32>,
        string_value: Option<String>,
    },
    /// An engine command.
    Command {
        opcode: i32,
        param_types: Vec<Type>,
        return_types: Vec<Type>,
    },
}

impl SymbolKind {
    pub fn kind_name(&self) -> &'static str {
        match self {
            SymbolKind::LocalVar { .. } => "LocalVar",
            SymbolKind::ScriptParam { .. } => "ScriptParam",
            SymbolKind::Script { .. } => "Script",
            SymbolKind::GameVar { .. } => "GameVar",
            SymbolKind::Constant { .. } => "Constant",
            SymbolKind::Command { .. } => "Command",
        }
    }
}

/// A single symbol entry in the table.
#[derive(Debug, Clone)]
pub struct Symbol {
    pub name: String,
    pub kind: SymbolKind,
}

/// A resolved entity id (from loc.pack/npc.pack/stat.pack/etc.) and its type.
///
/// Entity IDs hugely outnumber every other symbol (~22k for a full corpus), so
/// they get this 8-byte `Copy` record instead of a 104-byte `Symbol` — entity
/// lookups only ever need the type and the id.
#[derive(Debug, Clone, Copy)]
pub struct EntityRef {
    pub const_type: Type,
    pub id: i32,
}

/// All ids registered under one entity name. Replaces the former
/// `entity_ids: HashMap<String, Symbol>` + `entity_ids_typed:
/// HashMap<String, HashMap<Type, i32>>` pair (same data, ~6 MB smaller on a full
/// corpus: no 104-byte `Symbol`s and no ~22k nested HashMaps).
#[derive(Debug, Clone, Default)]
pub(crate) struct EntityEntry {
    /// Priority winner for untyped lookup (last `register_entity_id` wins);
    /// `None` for typed-only names (registered via `register_entity_id_typed_only`).
    pub(crate) primary: Option<EntityRef>,
    /// Every `(type, id)` variant under this name, for type-aware lookup.
    /// Tiny (usually one entry); includes the primary's `(type, id)`.
    pub(crate) variants: Vec<(Type, i32)>,
}

impl EntityEntry {
    /// Insert or replace the id for `entity_type` (last write wins per type).
    fn set_variant(&mut self, entity_type: Type, id: i32) {
        if let Some(slot) = self.variants.iter_mut().find(|(t, _)| *t == entity_type) {
            slot.1 = id;
        } else {
            self.variants.push((entity_type, id));
        }
    }
}

/// A hierarchical symbol table supporting scoped lookup.
#[derive(Debug, Clone)]
pub struct SymbolTable {
    /// Symbols in this scope.
    symbols: HashMap<String, Symbol>,
    /// Parent scope for hierarchical lookup.
    parent: Option<Box<SymbolTable>>,
    /// Counters for allocating local variable slots.
    next_int_local: i32,
    next_string_local: i32,
    next_long_local: i32,
    /// Total number of local variable declarations (including redeclarations of same name).
    /// The Java compiler counts each def_X statement, even if the slot is reused.
    total_int_decls: i32,
    total_string_decls: i32,
    total_long_decls: i32,
}

impl Default for SymbolTable {
    fn default() -> Self {
        Self::new()
    }
}

impl SymbolTable {
    pub fn new() -> Self {
        SymbolTable {
            symbols: HashMap::new(),
            parent: None,
            next_int_local: 0,
            next_string_local: 0,
            next_long_local: 0,
            total_int_decls: 0,
            total_string_decls: 0,
            total_long_decls: 0,
        }
    }

    /// Create a child scope that inherits from this table.
    pub fn child(parent: SymbolTable) -> Self {
        let int_local = parent.next_int_local;
        let string_local = parent.next_string_local;
        let long_local = parent.next_long_local;
        let int_decls = parent.total_int_decls;
        let string_decls = parent.total_string_decls;
        let long_decls = parent.total_long_decls;
        SymbolTable {
            symbols: HashMap::new(),
            parent: Some(Box::new(parent)),
            next_int_local: int_local,
            next_string_local: string_local,
            next_long_local: long_local,
            total_int_decls: int_decls,
            total_string_decls: string_decls,
            total_long_decls: long_decls,
        }
    }

    /// Create a child scope without consuming the parent (cloning).
    pub fn new_child(&self) -> Self {
        SymbolTable {
            symbols: HashMap::new(),
            parent: Some(Box::new(self.clone())),
            next_int_local: self.next_int_local,
            next_string_local: self.next_string_local,
            next_long_local: self.next_long_local,
            total_int_decls: self.total_int_decls,
            total_string_decls: self.total_string_decls,
            total_long_decls: self.total_long_decls,
        }
    }

    /// Define a symbol in this scope.
    pub fn define(&mut self, name: String, kind: SymbolKind) {
        self.symbols.insert(name.clone(), Symbol { name, kind });
    }

    /// Define a local variable and auto-assign a slot.
    /// `is_array` should be true for array declarations — arrays are excluded from
    /// the local count in the trailer (matching the reference compiler).
    pub fn define_local(&mut self, name: String, var_type: Type, is_array: bool) -> i32 {
        // Count the declaration (Java compiler counts each def_X), but NOT arrays.
        if !is_array {
            match var_type.base_type() {
                crate::types::BaseVarType::Integer => self.total_int_decls += 1,
                crate::types::BaseVarType::String => self.total_string_decls += 1,
                crate::types::BaseVarType::Long => self.total_long_decls += 1,
            }
        }
        // Always advance the slot counter for each declaration, but if the
        // name already exists in this scope, reuse its slot (the new slot
        // becomes a phantom counted in totals but not referenced).
        // This matches the Neptune compiler behavior where redeclaration
        // within the SAME scope reuses the existing slot.
        let new_slot = self.allocate_slot(&var_type);
        let slot = if let Some(existing) = self.symbols.get(&name) {
            match &existing.kind {
                SymbolKind::LocalVar { slot, .. } => *slot,
                _ => new_slot,
            }
        } else {
            new_slot
        };
        self.define(
            name,
            SymbolKind::LocalVar {
                var_type,
                slot,
                is_array,
            },
        );
        slot
    }

    /// Define a script parameter and auto-assign a slot.
    pub fn define_param(&mut self, name: String, param_type: Type) -> i32 {
        match param_type.base_type() {
            crate::types::BaseVarType::Integer => self.total_int_decls += 1,
            crate::types::BaseVarType::String => self.total_string_decls += 1,
            crate::types::BaseVarType::Long => self.total_long_decls += 1,
        }
        let slot = self.allocate_slot(&param_type);
        self.define(name, SymbolKind::ScriptParam { param_type, slot });
        slot
    }

    /// Allocate a slot for a given type.
    fn allocate_slot(&mut self, var_type: &Type) -> i32 {
        match var_type.base_type() {
            crate::types::BaseVarType::Integer => {
                let slot = self.next_int_local;
                self.next_int_local += 1;
                slot
            }
            crate::types::BaseVarType::String => {
                let slot = self.next_string_local;
                self.next_string_local += 1;
                slot
            }
            crate::types::BaseVarType::Long => {
                let slot = self.next_long_local;
                self.next_long_local += 1;
                slot
            }
        }
    }

    /// Look up a symbol by name, searching up through parent scopes.
    pub fn lookup(&self, name: &str) -> Option<&Symbol> {
        if let Some(sym) = self.symbols.get(name) {
            return Some(sym);
        }
        if let Some(parent) = &self.parent {
            return parent.lookup(name);
        }
        None
    }

    /// Look up a symbol only in this scope (not parents).
    pub fn lookup_local(&self, name: &str) -> Option<&Symbol> {
        self.symbols.get(name)
    }

    /// Check if a symbol exists in this scope or parent scopes.
    pub fn contains(&self, name: &str) -> bool {
        self.lookup(name).is_some()
    }

    /// Save the current slot counters. Used before entering a block scope.
    pub fn save_slots(&self) -> (i32, i32, i32) {
        (
            self.next_int_local,
            self.next_string_local,
            self.next_long_local,
        )
    }

    /// Restore slot counters to a saved state, but only if higher counters haven't
    /// been set by a sibling scope. This is used between sibling blocks (if/else)
    /// so each branch starts from the same slot baseline.
    pub fn restore_slots(&mut self, saved: (i32, i32, i32)) {
        self.next_int_local = saved.0;
        self.next_string_local = saved.1;
        self.next_long_local = saved.2;
    }

    /// Advance slot counters to be at least as high as the given values.
    /// Used after a block scope to ensure the next sibling doesn't reuse slots.
    pub fn merge_slots(&mut self, other: (i32, i32, i32)) {
        self.next_int_local = self.next_int_local.max(other.0);
        self.next_string_local = self.next_string_local.max(other.1);
        self.next_long_local = self.next_long_local.max(other.2);
    }

    /// Merge total declaration counts from a child scope.
    pub fn merge_decls(&mut self, child: &SymbolTable) {
        self.total_int_decls = child.total_int_decls;
        self.total_string_decls = child.total_string_decls;
        self.total_long_decls = child.total_long_decls;
    }

    /// Get the total int local count (includes redeclarations, matching Java compiler).
    pub fn int_local_count(&self) -> u16 {
        self.total_int_decls as u16
    }

    /// Get the total string local count.
    pub fn string_local_count(&self) -> u16 {
        self.total_string_decls as u16
    }

    /// Get the total long local count.
    pub fn long_local_count(&self) -> u16 {
        self.total_long_decls as u16
    }

    /// Reset local variable counters (for starting a new script).
    pub fn reset_locals(&mut self) {
        self.next_int_local = 0;
        self.next_string_local = 0;
        self.next_long_local = 0;
    }

    /// Iterate over all symbols in this scope.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &Symbol)> {
        self.symbols.iter()
    }
}

/// The root symbol table manager that holds all global symbols.
///
/// Field visibility is `pub(crate)` rather than `pub` so external consumers
/// only touch the registry through accessor methods (`lookup_command`,
/// `lookup_entity_id`, `register_script`, etc.). This lets internal storage
/// change — e.g. swapping `HashMap<String, _>` for an interned-string map —
/// without breaking the lib's public surface.
#[derive(Debug, Clone)]
pub struct SymbolRegistry {
    pub(crate) profile: Option<Arc<crate::environment::EngineProfile>>,
    pub(crate) visibility: Arc<crate::sources::Visibility>,
    pub(crate) dynamic_returns: HashMap<String, ReturnType>,
    /// Leading arguments that name types (`enum(int, obj, ...)`), by command.
    pub(crate) type_arguments: HashMap<String, usize>,
    pub(crate) param_types: HashMap<i32, Type>,
    pub(crate) stack_commands: HashSet<String>,
    component_first_commands: HashSet<String>,
    command_pointer_overrides: HashMap<String, PointerHolder>,
    switch_domains: HashMap<Type, BTreeMap<i32, String>>,
    pub(crate) stack_scripts: HashSet<String>,
    pub(crate) hook_commands: HashMap<String, bool>,
    /// All registered scripts by name (last registration wins). The `Symbol` is
    /// shared (`Arc`) with `scripts_by_trigger` so each script's symbol — and its
    /// param/return type vectors — is stored once, not once per map.
    pub(crate) scripts: HashMap<String, Arc<Symbol>>,
    /// All registered commands by name.
    pub(crate) commands: HashMap<String, Symbol>,
    /// All registered game variables by name.
    pub(crate) game_vars: HashMap<String, Symbol>,
    /// All registered constants by name (from .constant files).
    pub(crate) constants: HashMap<String, Symbol>,
    /// Entity IDs from pack files (loc.pack, npc.pack, stat.pack, etc.), keyed by
    /// name. Each entry carries a priority winner for plain-identifier lookup
    /// plus all per-type variants for type-aware lookup (so `smokepuff` resolves
    /// to synth=164 in sound_synth() but spotanim=86 in spotanim_map(), matching
    /// the Java compiler). Constants override only `^name` refs.
    pub(crate) entity_ids: HashMap<String, EntityEntry>,
    /// Parameter types for engine commands, parsed from engine.rs2.
    /// Maps command name → ordered list of parameter types.
    pub(crate) command_param_types: HashMap<String, Vec<Type>>,
    /// Type-char values for RS2 type names (int, string, coord, stat, etc.).
    /// Checked last in identifier resolution so commands take priority over type names.
    pub(crate) type_chars: HashMap<String, i32>,
    /// Script name to ID mapping (by name, last registration wins).
    pub(crate) script_ids: HashMap<String, i32>,
    /// Proc script IDs: name → ID for trigger="proc" scripts.
    pub(crate) proc_script_ids: HashMap<String, i32>,
    /// Label script IDs: name → ID for trigger="label" scripts.
    pub(crate) label_script_ids: HashMap<String, i32>,
    /// Trigger-specific script IDs: "trigger:name" → ID.
    /// Used so queue(foo) resolves to the [queue,foo] script, not [proc,foo].
    pub(crate) trigger_script_ids: HashMap<String, i32>,
    /// Full script symbols keyed by "trigger:name".
    /// Unlike `scripts` (name-only key, last-write-wins), this preserves
    /// all trigger variants so `[proc,fib]` isn't overwritten by `[debugproc,fib]`.
    /// Shares each `Symbol` (`Arc`) with `scripts`.
    pub(crate) scripts_by_trigger: HashMap<String, Arc<Symbol>>,
    /// Script IDs supplied by the caller: "trigger:name" → ID.
    pub(crate) preloaded_script_ids: HashMap<String, i32>,
    /// DB column field types: "table:column" → each field's Type. db_find takes
    /// the first field's BaseVarType; db_getfield returns them all.
    pub(crate) dbcolumn_types: HashMap<String, Vec<Type>>,
    /// Component lookup: "interface_name:component_name" → packed (iface_id << 16 | comp_id).
    pub(crate) components: HashMap<String, i32>,
    /// Interface name → ID mapping (for component resolution).
    pub(crate) interface_ids: HashMap<String, i32>,
    /// Scripts defined below `#testscript` — keyed by "trigger:name".
    pub(crate) test_scripts: HashSet<String>,
    /// Next available script ID.
    pub(crate) client_script_params: HashMap<String, Vec<Type>>,
    pub(crate) next_script_id: i32,
}

impl Default for SymbolRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone, Copy)]
pub enum ReturnType {
    TypeArgument(usize),
    ParamArgument(usize),
}

impl SymbolRegistry {
    pub fn set_engine_profile(&mut self, profile: crate::environment::EngineProfile) {
        self.command_pointer_overrides.clear();
        self.profile = Some(Arc::new(profile));
    }

    pub fn trigger(&self, name: &str) -> Option<crate::environment::Trigger> {
        if let Some(profile) = &self.profile {
            return profile.triggers.get(name).cloned();
        }
        crate::trigger_table::is_valid_trigger(name).then(|| crate::environment::Trigger {
            byte: crate::trigger_table::byte(name),
            subject_type: crate::trigger_table::subject_type(name),
            validates_subject: crate::trigger_table::validates_subject(name),
            is_button: crate::trigger_table::is_button(name),
            allows_returns: crate::trigger_table::allows_returns(name),
        })
    }

    pub fn set_visibility(&mut self, mut visibility: crate::sources::Visibility) {
        visibility.index_registry(self);
        self.visibility = Arc::new(visibility);
    }

    /// Supply stable IDs without reading or updating a pack file.
    pub fn set_script_id(&mut self, trigger: &str, name: &str, id: i32) {
        self.preloaded_script_ids
            .insert(format!("{trigger}:{name}"), id);
        self.next_script_id = self.next_script_id.max(id + 1);
    }

    /// Stack argument order is shared by client scripts and their global procs.
    pub fn set_stack_script(&mut self, trigger: &str, name: &str) {
        self.stack_scripts.insert(format!("{trigger}:{name}"));
    }

    pub fn component_first_command(&self, name: &str) -> bool {
        let name = name.trim_start_matches('.');
        self.stack_commands.contains(name) && self.component_first_commands.contains(name)
    }

    pub fn set_command_suspends(&mut self, name: &str, suspends: bool) {
        if let Some(profile) = &mut self.profile {
            Arc::make_mut(profile)
                .command_pointers
                .entry(name.to_owned())
                .or_default()
                .may_suspend = suspends;
        } else {
            self.command_pointer_overrides
                .entry(name.to_owned())
                .or_insert_with(|| {
                    default_command_pointers()
                        .get(name)
                        .cloned()
                        .unwrap_or_default()
                })
                .may_suspend = suspends;
        }
    }

    pub fn command_suspends(&self, name: &str) -> bool {
        self.command_suspends_for(name, true)
    }

    pub(crate) fn command_suspends_for(&self, name: &str, server: bool) -> bool {
        let primary = name.trim_start_matches('.');
        let lookup = |pointers: &HashMap<String, PointerHolder>| {
            pointers
                .get(name)
                .or_else(|| pointers.get(primary))
                .map(|holder| holder.may_suspend)
        };
        if let Some(profile) = &self.profile {
            lookup(&profile.command_pointers).unwrap_or(false)
        } else {
            lookup(&self.command_pointer_overrides)
                .or_else(|| server.then(|| lookup(default_command_pointers())).flatten())
                .unwrap_or(false)
        }
    }

    /// Explicit closed value domains; ordinary integer and asset IDs stay open.
    pub fn set_switch_values(&mut self, ty: Type, values: impl IntoIterator<Item = (i32, String)>) {
        self.switch_domains.insert(ty, values.into_iter().collect());
    }

    pub fn switch_values(&self, ty: Type) -> Option<&BTreeMap<i32, String>> {
        self.switch_domains
            .get(&ty)
            .filter(|values| !values.is_empty())
    }

    pub fn set_component_first_command(&mut self, name: &str, component_first: bool) {
        let name = name.trim_start_matches('.');
        if component_first {
            self.component_first_commands.insert(name.to_owned());
        } else {
            self.component_first_commands.remove(name);
        }
    }

    pub(crate) fn clear_commands(&mut self) {
        self.commands.clear();
        self.command_param_types.clear();
        self.stack_commands.clear();
        self.component_first_commands.clear();
        self.command_pointer_overrides.clear();
        self.hook_commands.clear();
        self.dynamic_returns.clear();
        self.type_arguments.clear();
    }

    pub fn set_command_behavior(
        &mut self,
        name: &str,
        stack: bool,
        hook: Option<bool>,
        returns: Option<ReturnType>,
    ) {
        if stack {
            self.stack_commands.insert(name.to_owned());
        } else {
            self.stack_commands.remove(name);
            self.component_first_commands.remove(name);
        }
        if let Some(explicit_component) = hook {
            self.hook_commands
                .insert(name.to_owned(), explicit_component);
        } else {
            self.hook_commands.remove(name);
        }
        if let Some(returns) = returns {
            self.dynamic_returns.insert(name.to_owned(), returns);
        } else {
            self.dynamic_returns.remove(name);
        }
    }

    pub fn commands(&self) -> impl Iterator<Item = (&str, &Symbol)> {
        self.commands
            .iter()
            .map(|(name, symbol)| (name.as_str(), symbol))
    }

    pub fn constants(&self) -> impl Iterator<Item = (&str, &Symbol)> {
        self.constants
            .iter()
            .map(|(name, symbol)| (name.as_str(), symbol))
    }

    pub(crate) fn remove_script(&mut self, trigger: &str, name: &str) {
        self.scripts_by_trigger.remove(&format!("{trigger}:{name}"));
        self.scripts.remove(name);
        self.stack_scripts.remove(&format!("{trigger}:{name}"));
        self.test_scripts.remove(&format!("{trigger}:{name}"));
        if trigger == "proc" {
            self.proc_script_ids.remove(name);
        }
        if trigger == "label" {
            self.label_script_ids.remove(name);
        }
    }

    /// Re-index source ownership after an importer has written config files.
    pub fn load_visibility(&mut self, source_dir: &std::path::Path) {
        self.visibility = Arc::new(crate::sources::Visibility::load(source_dir, self));
    }

    pub fn game_variables(&self) -> impl Iterator<Item = (&str, &Symbol)> {
        self.game_vars
            .iter()
            .map(|(name, symbol)| (name.as_str(), symbol))
    }

    pub fn new() -> Self {
        SymbolRegistry {
            profile: None,
            visibility: Arc::default(),
            dynamic_returns: HashMap::new(),
            type_arguments: HashMap::new(),
            param_types: HashMap::new(),
            stack_commands: HashSet::new(),
            component_first_commands: HashSet::new(),
            command_pointer_overrides: HashMap::new(),
            switch_domains: HashMap::from([
                (
                    Type::Boolean,
                    [(0, "false".into()), (1, "true".into())].into(),
                ),
                (Type::IntBool, [(0, "0".into()), (1, "1".into())].into()),
            ]),
            stack_scripts: HashSet::new(),
            hook_commands: HashMap::new(),
            scripts: HashMap::new(),
            commands: HashMap::new(),
            game_vars: HashMap::new(),
            constants: HashMap::new(),
            entity_ids: HashMap::new(),
            command_param_types: HashMap::new(),
            type_chars: HashMap::new(),
            script_ids: HashMap::new(),
            proc_script_ids: HashMap::new(),
            label_script_ids: HashMap::new(),
            trigger_script_ids: HashMap::new(),
            scripts_by_trigger: HashMap::new(),
            preloaded_script_ids: HashMap::new(),
            dbcolumn_types: HashMap::new(),
            components: HashMap::new(),
            interface_ids: HashMap::new(),
            test_scripts: HashSet::new(),
            client_script_params: HashMap::new(),
            next_script_id: 0,
        }
    }

    pub fn register_clientscript(&mut self, name: String, id: i32, params: Vec<Type>) {
        self.trigger_script_ids
            .insert(format!("clientscript:{name}"), id);
        self.client_script_params.insert(name, params);
    }

    /// Register a script by name with its type information.
    pub fn register_script(
        &mut self,
        name: String,
        trigger: String,
        param_types: Vec<Type>,
        return_types: Vec<Type>,
    ) -> i32 {
        let key = format!("{}:{}", trigger, name);
        let id = if let Some(&preloaded) = self.preloaded_script_ids.get(&key) {
            preloaded
        } else {
            let id = self.next_script_id;
            self.next_script_id += 1;
            id
        };

        // proc/label ids are keyed by bare name (not `trigger:name`), so they
        // can't be derived from the trigger-keyed map without a per-lookup
        // concat — keep these small dedicated maps.
        if trigger == "proc" {
            self.proc_script_ids.insert(name.clone(), id);
        } else if trigger == "label" {
            self.label_script_ids.insert(name.clone(), id);
        }
        // The id lives in the `Symbol`; `script_id` / `script_id_for_trigger`
        // read it from `scripts` / `scripts_by_trigger` (the `*_script_ids` maps
        // are now only the clientscript-pack fallback), so we don't duplicate it.
        let symbol = Arc::new(Symbol {
            name: name.clone(),
            kind: SymbolKind::Script {
                id,
                trigger,
                param_types,
                return_types,
            },
        });
        self.scripts_by_trigger.insert(key, Arc::clone(&symbol));
        self.scripts.insert(name, symbol);

        id
    }

    /// Register a command (engine function).
    pub fn register_command(
        &mut self,
        name: String,
        opcode: i32,
        param_types: Vec<Type>,
        return_types: Vec<Type>,
    ) {
        self.component_first_commands.remove(&name);
        self.command_pointer_overrides.remove(&name);
        self.command_param_types
            .insert(name.clone(), param_types.clone());
        self.commands.insert(
            name.clone(),
            Symbol {
                name,
                kind: SymbolKind::Command {
                    opcode,
                    param_types,
                    return_types,
                },
            },
        );
    }

    pub fn register_param_type(&mut self, id: i32, ty: Type) {
        self.param_types.insert(id, ty);
    }

    /// Register a game variable.
    pub fn register_game_var(
        &mut self,
        name: String,
        var_type: Type,
        var_id: i32,
        category: String,
    ) {
        self.game_vars.insert(
            name.clone(),
            Symbol {
                name,
                kind: SymbolKind::GameVar {
                    var_type,
                    var_id,
                    category,
                },
            },
        );
    }

    /// Register a constant value (from .constant files).
    pub fn register_constant(
        &mut self,
        name: String,
        const_type: Type,
        int_value: Option<i32>,
        string_value: Option<String>,
    ) {
        self.constants.insert(
            name.clone(),
            Symbol {
                name,
                kind: SymbolKind::Constant {
                    const_type,
                    int_value,
                    string_value,
                },
            },
        );
    }

    /// Register an entity ID (from stat.pack, npc.pack, loc.pack, etc.).
    /// These are stored separately from .constant files values so plain
    /// identifier resolution uses entity IDs, while ^name uses .constant files.
    pub fn register_entity_id(&mut self, name: String, entity_type: Type, id: i32) {
        let entry = self.entity_ids.entry(name).or_default();
        // Priority winner for untyped lookup (last write wins).
        entry.primary = Some(EntityRef {
            const_type: entity_type,
            id,
        });
        entry.set_variant(entity_type, id);
    }

    /// Register an entity ID that should only be resolvable via a typed
    /// (hint-driven) lookup. Skips the flat `entity_ids` map so the name
    /// does not shadow trigger names or other higher-priority resolutions
    /// when used in untyped expression contexts.
    ///
    /// Used for NpcMode names like `oploc1`/`apnpc2` that share their
    /// spelling with `ServerTriggerType` byte names — `npc_setmode(oploc1)`
    /// still works (typed lookup hits `Type::NpcMode`), but bare `oploc1`
    /// in e.g. `test_op(oploc1, …)` falls through to `trigger_table::byte`.
    pub fn register_entity_id_typed_only(&mut self, name: String, entity_type: Type, id: i32) {
        self.entity_ids
            .entry(name)
            .or_default()
            .set_variant(entity_type, id);
    }

    /// Look up an entity ID for a specific expected type. Returns `None` if the
    /// name is not registered for that type.
    /// Normalizes the name (lowercase + spaces→underscores) matching TS normalizeName for Basic symbols.
    pub fn lookup_entity_id_typed(&self, name: &str, expected: Type) -> Option<i32> {
        let normalized = normalize_entity_name(name);
        self.entity_ids
            .get(normalized.as_ref())
            .and_then(|e| e.variants.iter().find(|(t, _)| *t == expected))
            .map(|(_, id)| *id)
    }

    pub fn lookup_reference(&self, name: &str, expected: Type) -> Option<i32> {
        match expected {
            Type::Component => name
                .split_once(':')
                .and_then(|(iface, com)| self.lookup_component(iface, com))
                .or_else(|| self.lookup_entity_id_typed(name, expected)),
            Type::ClientScript => self
                .script_id_for_trigger("clientscript", name)
                .or_else(|| self.script_id_for_trigger("proc", name)),
            Type::Proc => self.proc_script_id(name),
            // These go by number without a name of their own.
            Type::Model | Type::Texture | Type::Category => {
                self.lookup_entity_id_typed(name, expected).or_else(|| {
                    name.strip_prefix(expected.name())?
                        .strip_prefix('_')?
                        .parse::<i32>()
                        .ok()
                        .filter(|id| *id >= 0)
                })
            }
            Type::Varp
            | Type::Varn
            | Type::Vars
            | Type::VarpBit
            | Type::Varc
            | Type::VarCon
            | Type::VarConBit
            | Type::VarClanSetting => self.lookup_game_var(name).and_then(|symbol| {
                if let SymbolKind::GameVar {
                    var_id, category, ..
                } = &symbol.kind
                    && match expected {
                        Type::Varc => matches!(category.as_str(), "varc" | "varcstr"),
                        Type::VarClanSetting => category.starts_with("clansetting_"),
                        _ => category == expected.name(),
                    }
                {
                    Some(*var_id)
                } else {
                    None
                }
            }),
            _ => self.lookup_entity_id_typed(name, expected),
        }
    }

    /// Look up a script by name (last registration wins if multiple triggers share the name).
    pub fn lookup_script(&self, name: &str) -> Option<&Symbol> {
        self.scripts.get(name).map(|s| s.as_ref())
    }

    /// Look up a script by trigger and name (avoids name collisions between triggers).
    pub fn lookup_script_by_trigger(&self, trigger: &str, name: &str) -> Option<&Symbol> {
        if let Some(symbol) = self.scripts.get(name)
            && matches!(&symbol.kind, SymbolKind::Script { trigger: found, .. } if found == trigger)
        {
            return Some(symbol);
        }
        self.scripts_by_trigger
            .get(&format!("{}:{}", trigger, name))
            .map(|s| s.as_ref())
    }

    /// Look up a command by name.
    pub fn lookup_command(&self, name: &str) -> Option<&Symbol> {
        self.commands.get(name)
    }

    /// Whether a bare `name` in a `hint` slot is the command rather than an
    /// entity: entity ids are ints, so a string or long slot takes the command.
    pub(crate) fn command_fills(&self, name: &str, hint: Option<Type>) -> bool {
        hint.is_some_and(|h| h.base_type() != BaseVarType::Integer)
            && self.commands.contains_key(name)
    }

    /// Look up a game variable by name.
    pub fn lookup_game_var(&self, name: &str) -> Option<&Symbol> {
        self.game_vars.get(name)
    }

    /// Look up a constant by name (from .constant files).
    pub fn lookup_constant(&self, name: &str) -> Option<&Symbol> {
        self.constants.get(name)
    }

    pub fn integer_constant_name(&self, value: i32, prefix: &str) -> Option<&str> {
        self.constants.values().filter(|symbol| symbol.name.starts_with(prefix)).filter_map(|symbol| {
            matches!(&symbol.kind, SymbolKind::Constant { int_value: Some(id), .. } if *id == value)
                .then_some(symbol.name.as_str())
        }).min()
    }

    /// Look up an entity ID by name (from stat.pack, npc.pack, etc.).
    /// Normalizes the name matching TS normalizeName for Basic symbols.
    pub fn lookup_entity_id(&self, name: &str) -> Option<EntityRef> {
        let normalized = normalize_entity_name(name);
        self.entity_ids
            .get(normalized.as_ref())
            .and_then(|e| e.primary)
    }

    /// Free registration-only scratch once every script is registered. The
    /// pre-assigned IDs are consulted only while assigning
    /// ids in `register_script`; codegen and pointer-checking never read them.
    /// Replacing (not `clear`-ing) the map returns its buckets to the allocator.
    pub(crate) fn drop_registration_scratch(&mut self) {
        self.preloaded_script_ids = HashMap::new();
    }

    /// Get the script ID for a given name. Reads the id from the registered
    /// script's `Symbol`; falls back to `script_ids` (clientscript-pack entries,
    /// which are never registered as RS2). Registered scripts take precedence,
    /// matching the old insert order (clientscripts loaded, then `register_script`
    /// overwrote by name).
    pub fn script_id(&self, name: &str) -> Option<i32> {
        if let Some(s) = self.scripts.get(name)
            && let SymbolKind::Script { id, .. } = &s.kind
        {
            return Some(*id);
        }
        self.script_ids.get(name).copied()
    }

    /// Get the proc script ID for a given name.
    pub fn proc_script_id(&self, name: &str) -> Option<i32> {
        self.proc_script_ids.get(name).copied()
    }

    /// Get the label script ID for a given name.
    pub fn label_script_id(&self, name: &str) -> Option<i32> {
        self.label_script_ids.get(name).copied()
    }

    pub fn script_id_for_trigger(&self, trigger: &str, name: &str) -> Option<i32> {
        let key = format!("{}:{}", trigger, name);
        if let Some(s) = self.scripts_by_trigger.get(&key)
            && let SymbolKind::Script { id, .. } = &s.kind
        {
            return Some(*id);
        }
        // Fallback: clientscript-pack ids (keyed `clientscript:name`), never
        // registered as RS2 scripts.
        self.trigger_script_ids
            .get(&key)
            .or_else(|| self.preloaded_script_ids.get(&key))
            .copied()
    }

    pub fn command_opcode(&self, name: &str) -> Option<i32> {
        self.commands.get(name).and_then(|sym| {
            if let SymbolKind::Command { opcode, .. } = &sym.kind {
                Some(*opcode)
            } else {
                None
            }
        })
    }

    pub fn mark_test_script(&mut self, trigger: &str, name: &str) {
        self.test_scripts.insert(format!("{}:{}", trigger, name));
    }

    pub fn is_test_script(&self, trigger: &str, name: &str) -> bool {
        self.test_scripts.contains(&format!("{}:{}", trigger, name))
    }

    /// Look up a component by interface_name:component_name.
    /// Returns the packed (iface_id << 16 | comp_id) value.
    /// Normalizes the component name so 647-style `com2` and 225-style `com_2`
    /// both resolve against whichever form the pack was written in.
    pub fn lookup_component(&self, iface_name: &str, comp_name: &str) -> Option<i32> {
        let key = format!("{}:{}", iface_name, normalize_comp_name(comp_name));
        self.components.get(&key).copied()
    }
}

/// A pack name as scripts write it: trimmed, with each character an
/// identifier can't hold (a space, a hyphen) as `_`. Packs keep Jagex's real
/// names, so `cove lid` is `cove_lid` in source.
pub fn identifier_form(name: &str) -> String {
    name.trim()
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// Strip underscores at alpha→digit boundaries to unify 647-style `com2`
/// with 225-style `com_2`. Both normalize to `com2`.
pub(crate) fn normalize_comp_name(name: &str) -> String {
    let bytes = name.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'_'
            && i > 0
            && bytes[i - 1].is_ascii_alphabetic()
            && i + 1 < bytes.len()
            && bytes[i + 1].is_ascii_digit()
        {
            i += 1;
            continue;
        }
        out.push(bytes[i]);
        i += 1;
    }
    unsafe { String::from_utf8_unchecked(out) }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── normalize_comp_name ────────────────────────────────────────────

    #[test]
    fn normalize_strips_underscore_before_digits() {
        assert_eq!(normalize_comp_name("com_2"), "com2");
        assert_eq!(normalize_comp_name("com_10"), "com10");
        assert_eq!(normalize_comp_name("com_0"), "com0");
    }

    #[test]
    fn normalize_preserves_already_compact_names() {
        assert_eq!(normalize_comp_name("com2"), "com2");
        assert_eq!(normalize_comp_name("com10"), "com10");
        assert_eq!(normalize_comp_name("com0"), "com0");
    }

    #[test]
    fn normalize_preserves_non_digit_underscores() {
        assert_eq!(normalize_comp_name("close_button"), "close_button");
        assert_eq!(normalize_comp_name("thin_swords"), "thin_swords");
        assert_eq!(normalize_comp_name("title"), "title");
    }

    #[test]
    fn normalize_only_strips_alpha_digit_boundary() {
        // underscore between two digits — not stripped
        assert_eq!(normalize_comp_name("layer_2_3"), "layer2_3");
        // underscore between digit and alpha — not stripped
        assert_eq!(normalize_comp_name("3_panel"), "3_panel");
    }

    // ── lookup_component (647 pack style) ──────────────────────────────

    fn registry_647_style() -> SymbolRegistry {
        let mut r = SymbolRegistry::new();
        r.interface_ids.insert("multi2".into(), 228);
        // 647 pack registers `com0`..`com9` (no underscore)
        for i in 0..10 {
            let key = format!("multi2:com{}", i);
            r.components.insert(key, (228 << 16) | i);
        }
        r
    }

    #[test]
    fn lookup_647_pack_with_647_reference() {
        let r = registry_647_style();
        // Script uses the same 647 naming: `multi2:com2`
        assert_eq!(r.lookup_component("multi2", "com2"), Some((228 << 16) | 2));
        assert_eq!(r.lookup_component("multi2", "com9"), Some((228 << 16) | 9));
    }

    #[test]
    fn lookup_647_pack_with_225_reference() {
        let r = registry_647_style();
        // Script uses 225 naming: `multi2:com_2` — must still resolve
        assert_eq!(r.lookup_component("multi2", "com_2"), Some((228 << 16) | 2));
        assert_eq!(r.lookup_component("multi2", "com_9"), Some((228 << 16) | 9));
        assert_eq!(r.lookup_component("multi2", "com_0"), Some(228 << 16));
    }

    // ── lookup_component (225 pack style) ──────────────────────────────

    fn registry_225_style() -> SymbolRegistry {
        let mut r = SymbolRegistry::new();
        r.interface_ids.insert("multi2".into(), 228);
        // 225 pack registers `multi2:com_0`..`com_9` — but through
        // symloader normalization these become `com0`..`com9`.
        for i in 0..10 {
            let key = format!("multi2:com{}", i);
            r.components.insert(key, 2459 + i);
        }
        r
    }

    #[test]
    fn lookup_225_pack_with_225_reference() {
        let r = registry_225_style();
        assert_eq!(r.lookup_component("multi2", "com_0"), Some(2459));
        assert_eq!(r.lookup_component("multi2", "com_5"), Some(2464));
    }

    #[test]
    fn lookup_225_pack_with_647_reference() {
        let r = registry_225_style();
        assert_eq!(r.lookup_component("multi2", "com0"), Some(2459));
        assert_eq!(r.lookup_component("multi2", "com5"), Some(2464));
    }

    // ── lookup_component (miss) ────────────────────────────────────────

    #[test]
    fn lookup_returns_none_for_unknown_component() {
        let r = registry_647_style();
        assert_eq!(r.lookup_component("multi2", "nonexistent"), None);
        assert_eq!(r.lookup_component("unknown_iface", "com0"), None);
    }
}