Skip to main content

runec/
types.rs

1/// Base variable types in the RS2 type system.
2/// Every ScriptVarType maps to one of these for stack operations.
3#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
4pub enum BaseVarType {
5    Integer,
6    String,
7    Long,
8}
9
10/// All script variable types supported by RuneScript.
11/// These correspond to the types used in the 2004Scape/RS2 engine.
12#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
13pub enum Type {
14    // Primitive types
15    Int,
16    Boolean,
17    String,
18    Long,
19    Char,
20    Colour,
21    Coord,
22
23    // Game entity types
24    Loc,
25    Npc,
26    Obj,
27    NamedObj,
28    PlayerUid,
29    NpcUid,
30
31    // Visual/audio types
32    Seq,
33    Spotanim,
34    Synth,
35    Vorbis,
36    Midi,
37    Jingle,
38    Graphic,
39    FontMetrics,
40    ChatCat,
41    ChatPhrase,
42    Model,
43    Texture,
44    IdKit,
45    MesAnim,
46    Hitmark,
47
48    // UI types
49    Stat,
50    Component,
51    IfType,
52    SetPosH,
53    SetPosV,
54    SetSize,
55    SetTextAlignH,
56    SetTextAlignV,
57    ClanForumQfc,
58    /// A parameter holding the number of one of the caller's arrays.
59    IntArray,
60    Key,
61    ChatType,
62    ChatFilter,
63    WindowMode,
64    PlatformType,
65    IntBool,
66    Interface,
67    TopLevelInterface,
68    OverlayInterface,
69    Inv,
70
71    // Data types
72    Enum,
73    Struct,
74    Param,
75    DbTable,
76    DbRow,
77    DbColumn,
78    Category,
79
80    // Variable types
81    Varp,
82    Varn,
83    Vars,
84    VarpBit,
85    Varc,
86    VarClan,
87    VarClanSetting,
88    VarCon,
89    VarConBit,
90    VarnBit,
91    VarObj,
92
93    // Map types
94    MapZone,
95    MapArea,
96    MapElement,
97
98    // Misc types
99    LocShape,
100    NpcMode,
101    NpcStat,
102    Area,
103    Hunt,
104    MoveSpeed,
105    EntityOverlay,
106    StringVector,
107    WriteInv,
108
109    // Config tables
110    Bas,
111    Billboard,
112    ParticleEffector,
113    ParticleEmitter,
114    Cursor,
115    Flo,
116    Flu,
117    ItemCode,
118    Light,
119    Msi,
120    Quest,
121
122    // Controller type (instanced area manager)
123    Controller,
124    RegionCoord,
125    /// A region (instance), as `region_uid` gives it and
126    /// `region_findbyuid` takes it.
127    RegionUid,
128
129    // Script reference types (for parameters that hold script IDs)
130    Proc,
131    ClientScript,
132    Label,
133    Queue,
134    SoftTimer,
135    Timer,
136    Walktrigger,
137    ControllerQueue,
138    NpcQueue,
139
140    // Meta types (used internally by the compiler)
141    Any,
142    Error,
143    Void,
144}
145
146impl Type {
147    pub fn to_char(self) -> char {
148        // A clan forum link is a long to the client.
149        if self == Self::ClanForumQfc {
150            return '§';
151        }
152        Self::CHARS
153            .chars()
154            .find(|&ch| Self::from_char(ch) == Some(self))
155            .unwrap_or('i')
156    }
157
158    /// Every character a script names a type by.
159    pub const CHARS: &'static str = "is§1clnoOpNAtPMjdmxKSIavgJyVÐþ`µzf«ke@\u{80}";
160
161    pub fn from_char(ch: char) -> Option<Self> {
162        Some(match ch {
163            'i' => Self::Int,
164            's' => Self::String,
165            '§' => Self::Long,
166            'z' => Self::Char,
167            'f' => Self::FontMetrics,
168            '«' => Self::Vorbis,
169            'k' => Self::ChatCat,
170            'e' => Self::ChatPhrase,
171            '1' => Self::Boolean,
172            'c' => Self::Coord,
173            'l' => Self::Loc,
174            'n' => Self::Npc,
175            'o' => Self::Obj,
176            'O' => Self::NamedObj,
177            'p' => Self::PlayerUid,
178            'N' => Self::NpcUid,
179            'A' => Self::Seq,
180            't' => Self::Spotanim,
181            'P' => Self::Synth,
182            'M' => Self::Midi,
183            'j' => Self::Jingle,
184            'd' => Self::Graphic,
185            'm' => Self::Model,
186            'x' => Self::Texture,
187            'K' => Self::IdKit,
188            'S' => Self::Stat,
189            'I' => Self::Component,
190            'a' => Self::Interface,
191            'v' => Self::Inv,
192            'g' => Self::Enum,
193            'J' => Self::Struct,
194            'y' => Self::Category,
195            'V' => Self::Varp,
196            'Ð' => Self::DbRow,
197            'þ' => Self::NpcStat,
198            '`' => Self::MapArea,
199            'µ' => Self::MapElement,
200            '@' => Self::Cursor,
201            '\u{80}' => Self::Bas,
202            _ => return None,
203        })
204    }
205
206    /// Returns the base var type (determines which stack to use).
207    pub fn base_type(&self) -> BaseVarType {
208        match self {
209            Type::String => BaseVarType::String,
210            Type::Long | Type::ClanForumQfc => BaseVarType::Long,
211            _ => BaseVarType::Integer,
212        }
213    }
214
215    /// Default value for uninitialised local variable declarations.
216    /// Boolean and Int default to 0; all other int-based types default to -1 (null).
217    pub fn default_int_value(&self) -> i32 {
218        match self {
219            Type::Int | Type::Boolean => 0,
220            ty if ty.is_int_kind() => 0,
221            _ => -1,
222        }
223    }
224
225    /// Default value for implicit return values at end of scripts.
226    /// Only Int pushes 0; everything else (including Boolean) pushes -1.
227    pub fn default_return_value(&self) -> i32 {
228        match self {
229            Type::Int => 0,
230            ty if ty.is_int_kind() => 0,
231            _ => -1,
232        }
233    }
234
235    /// Parse a type name from a def_ prefix (e.g., "def_int" -> Int).
236    pub fn from_def_str(s: &str) -> Option<Type> {
237        let type_name = s.strip_prefix("def_")?;
238        Self::from_name(type_name)
239    }
240
241    /// Parse a type from its bare name (e.g., "int" -> Int).
242    pub fn from_name(s: &str) -> Option<Type> {
243        match s {
244            "int" => Some(Type::Int),
245            "boolean" | "bool" => Some(Type::Boolean),
246            "string" => Some(Type::String),
247            "long" => Some(Type::Long),
248            "char" => Some(Type::Char),
249            "colour" | "color" | "rgb" => Some(Type::Colour),
250            "clanforumqfc" => Some(Type::ClanForumQfc),
251            "intarray" => Some(Type::IntArray),
252            "key" => Some(Type::Key),
253            "chattype" => Some(Type::ChatType),
254            "chatfilter" => Some(Type::ChatFilter),
255            "windowmode" => Some(Type::WindowMode),
256            "platformtype" => Some(Type::PlatformType),
257            "intbool" => Some(Type::IntBool),
258            "iftype" => Some(Type::IfType),
259            "setposh" => Some(Type::SetPosH),
260            "setposv" => Some(Type::SetPosV),
261            "setsize" => Some(Type::SetSize),
262            "settextalignh" => Some(Type::SetTextAlignH),
263            "settextalignv" => Some(Type::SetTextAlignV),
264            "coord" => Some(Type::Coord),
265            "loc" => Some(Type::Loc),
266            "npc" => Some(Type::Npc),
267            "obj" => Some(Type::Obj),
268            "namedobj" => Some(Type::NamedObj),
269            "playeruid" | "player_uid" => Some(Type::PlayerUid),
270            "npcuid" | "npc_uid" => Some(Type::NpcUid),
271            "seq" => Some(Type::Seq),
272            "spotanim" => Some(Type::Spotanim),
273            "synth" => Some(Type::Synth),
274            "vorbis" => Some(Type::Vorbis),
275            "midi" => Some(Type::Midi),
276            "jingle" => Some(Type::Jingle),
277            "graphic" => Some(Type::Graphic),
278            "fontmetrics" => Some(Type::FontMetrics),
279            "chatcat" | "quickchatcat" => Some(Type::ChatCat),
280            "chatphrase" | "quickchatphrase" => Some(Type::ChatPhrase),
281            "model" => Some(Type::Model),
282            "texture" => Some(Type::Texture),
283            "idk" | "idkit" => Some(Type::IdKit),
284            "mesanim" => Some(Type::MesAnim),
285            "hitmark" => Some(Type::Hitmark),
286            "stat" => Some(Type::Stat),
287            "component" => Some(Type::Component),
288            "interface" => Some(Type::Interface),
289            "toplevelinterface" => Some(Type::TopLevelInterface),
290            "overlayinterface" => Some(Type::OverlayInterface),
291            "inv" => Some(Type::Inv),
292            "enum" => Some(Type::Enum),
293            "struct" => Some(Type::Struct),
294            "param" => Some(Type::Param),
295            "dbtable" => Some(Type::DbTable),
296            "dbrow" => Some(Type::DbRow),
297            "dbcolumn" => Some(Type::DbColumn),
298            "category" => Some(Type::Category),
299            "varp" => Some(Type::Varp),
300            "varn" => Some(Type::Varn),
301            "vars" => Some(Type::Vars),
302            "varpbit" => Some(Type::VarpBit),
303            "varc" => Some(Type::Varc),
304            "varclan" => Some(Type::VarClan),
305            "varclansetting" => Some(Type::VarClanSetting),
306            "varcon" => Some(Type::VarCon),
307            "varconbit" => Some(Type::VarConBit),
308            "varnbit" => Some(Type::VarnBit),
309            "varobj" => Some(Type::VarObj),
310            "mapzone" => Some(Type::MapZone),
311            "wma" | "maparea" => Some(Type::MapArea),
312            "mapelement" | "mel" => Some(Type::MapElement),
313            "locshape" | "loc_shape" => Some(Type::LocShape),
314            "npc_mode" | "npcmode" => Some(Type::NpcMode),
315            "npc_stat" | "npcstat" => Some(Type::NpcStat),
316            "area" => Some(Type::Area),
317            "hunt" => Some(Type::Hunt),
318            "movespeed" => Some(Type::MoveSpeed),
319            "entityoverlay" => Some(Type::EntityOverlay),
320            "stringvector" => Some(Type::StringVector),
321            "writeinv" | "writeinvobj" => Some(Type::WriteInv),
322            "controller" => Some(Type::Controller),
323            "bas" => Some(Type::Bas),
324            "billboard" => Some(Type::Billboard),
325            "particleeffector" => Some(Type::ParticleEffector),
326            "particleemitter" => Some(Type::ParticleEmitter),
327            "cursor" => Some(Type::Cursor),
328            "flo" => Some(Type::Flo),
329            "flu" => Some(Type::Flu),
330            "itemcode" => Some(Type::ItemCode),
331            "light" => Some(Type::Light),
332            "msi" => Some(Type::Msi),
333            "quest" => Some(Type::Quest),
334            "regioncoord" => Some(Type::RegionCoord),
335            "regionuid" | "region_uid" => Some(Type::RegionUid),
336            // Script reference types (used when passing proc/label/queue references as params)
337            "label" => Some(Type::Label),
338            "proc" => Some(Type::Proc),
339            "clientscript" => Some(Type::ClientScript),
340            "command" => Some(Type::Int),
341            "queue" => Some(Type::Queue),
342            "softtimer" => Some(Type::SoftTimer),
343            "timer" => Some(Type::Timer),
344            "controller_queue" => Some(Type::ControllerQueue),
345            "npc_queue" => Some(Type::NpcQueue),
346            "walktrigger" => Some(Type::Walktrigger),
347            "any" => Some(Type::Any),
348            "intparam" | "stringparam" => Some(Type::Param),
349            "type" => Some(Type::Int),
350            _ => None,
351        }
352    }
353
354    /// An int that only differs in how its values print: declarations say `int`.
355    pub fn is_int_kind(&self) -> bool {
356        matches!(
357            self,
358            Type::Colour
359                | Type::Key
360                | Type::ChatType
361                | Type::ChatFilter
362                | Type::WindowMode
363                | Type::PlatformType
364                | Type::IntBool
365                | Type::IfType
366                | Type::SetPosH
367                | Type::SetPosV
368                | Type::SetSize
369                | Type::SetTextAlignH
370                | Type::SetTextAlignV
371        )
372    }
373
374    /// The name a declaration of this type gives.
375    pub fn declared_name(&self) -> &'static str {
376        if self.is_int_kind() {
377            "int"
378        } else {
379            self.name()
380        }
381    }
382
383    /// Get the name of this type as used in RuneScript source.
384    pub fn name(&self) -> &'static str {
385        match self {
386            Type::Int => "int",
387            Type::Boolean => "boolean",
388            Type::String => "string",
389            Type::Long => "long",
390            Type::Char => "char",
391            Type::Colour => "colour",
392            Type::ClanForumQfc => "clanforumqfc",
393            Type::IntArray => "intarray",
394            Type::Key => "key",
395            Type::ChatType => "chattype",
396            Type::ChatFilter => "chatfilter",
397            Type::WindowMode => "windowmode",
398            Type::PlatformType => "platformtype",
399            Type::IntBool => "intbool",
400            Type::Coord => "coord",
401            Type::Loc => "loc",
402            Type::Npc => "npc",
403            Type::Obj => "obj",
404            Type::NamedObj => "namedobj",
405            Type::PlayerUid => "playeruid",
406            Type::NpcUid => "npcuid",
407            Type::Seq => "seq",
408            Type::Spotanim => "spotanim",
409            Type::Synth => "synth",
410            Type::Vorbis => "vorbis",
411            Type::Midi => "midi",
412            Type::Jingle => "jingle",
413            Type::Graphic => "graphic",
414            Type::FontMetrics => "fontmetrics",
415            Type::ChatCat => "chatcat",
416            Type::ChatPhrase => "chatphrase",
417            Type::Model => "model",
418            Type::Texture => "texture",
419            Type::IdKit => "idkit",
420            Type::MesAnim => "mesanim",
421            Type::Hitmark => "hitmark",
422            Type::Stat => "stat",
423            Type::Component => "component",
424            Type::IfType => "iftype",
425            Type::SetPosH => "setposh",
426            Type::SetPosV => "setposv",
427            Type::SetSize => "setsize",
428            Type::SetTextAlignH => "settextalignh",
429            Type::SetTextAlignV => "settextalignv",
430            Type::Interface => "interface",
431            Type::TopLevelInterface => "toplevelinterface",
432            Type::OverlayInterface => "overlayinterface",
433            Type::Inv => "inv",
434            Type::Enum => "enum",
435            Type::Struct => "struct",
436            Type::Param => "param",
437            Type::DbTable => "dbtable",
438            Type::DbRow => "dbrow",
439            Type::DbColumn => "dbcolumn",
440            Type::Category => "category",
441            Type::Varp => "varp",
442            Type::Varn => "varn",
443            Type::Vars => "vars",
444            Type::VarpBit => "varpbit",
445            Type::Varc => "varc",
446            Type::VarClan => "varclan",
447            Type::VarClanSetting => "varclansetting",
448            Type::VarCon => "varcon",
449            Type::VarConBit => "varconbit",
450            Type::VarnBit => "varnbit",
451            Type::VarObj => "varobj",
452            Type::MapZone => "mapzone",
453            Type::MapArea => "maparea",
454            Type::MapElement => "mapelement",
455            Type::LocShape => "loc_shape",
456            Type::NpcMode => "npc_mode",
457            Type::NpcStat => "npc_stat",
458            Type::Area => "area",
459            Type::Hunt => "hunt",
460            Type::MoveSpeed => "movespeed",
461            Type::EntityOverlay => "entityoverlay",
462            Type::StringVector => "stringvector",
463            Type::WriteInv => "writeinv",
464            Type::Controller => "controller",
465            Type::Bas => "bas",
466            Type::Billboard => "billboard",
467            Type::ParticleEffector => "particleeffector",
468            Type::ParticleEmitter => "particleemitter",
469            Type::Cursor => "cursor",
470            Type::Flo => "flo",
471            Type::Flu => "flu",
472            Type::ItemCode => "itemcode",
473            Type::Light => "light",
474            Type::Msi => "msi",
475            Type::Quest => "quest",
476            Type::RegionCoord => "regioncoord",
477            Type::RegionUid => "regionuid",
478            Type::Proc => "proc",
479            Type::ClientScript => "clientscript",
480            Type::Label => "label",
481            Type::Queue => "queue",
482            Type::SoftTimer => "softtimer",
483            Type::Timer => "timer",
484            Type::ControllerQueue => "controller_queue",
485            Type::NpcQueue => "npc_queue",
486            Type::Walktrigger => "walktrigger",
487            Type::Any => "any",
488            Type::Error => "error",
489            Type::Void => "void",
490        }
491    }
492
493    pub fn allow_switch(&self) -> bool {
494        self.base_type() == BaseVarType::Integer
495    }
496
497    /// Returns true if this is a numeric type that supports arithmetic.
498    pub fn is_numeric(&self) -> bool {
499        matches!(self, Type::Int | Type::Long)
500    }
501
502    /// Returns true if this is a type that uses object-style comparison (string equality).
503    pub fn is_obj_type(&self) -> bool {
504        matches!(self, Type::String)
505    }
506
507    /// Returns all known def_ type names.
508    pub fn all_def_keywords() -> Vec<&'static str> {
509        vec![
510            "def_int",
511            "def_boolean",
512            "def_string",
513            "def_long",
514            "def_char",
515            "def_coord",
516            "def_loc",
517            "def_npc",
518            "def_obj",
519            "def_namedobj",
520            "def_playeruid",
521            "def_npcuid",
522            "def_seq",
523            "def_spotanim",
524            "def_synth",
525            "def_midi",
526            "def_jingle",
527            "def_graphic",
528            "def_fontmetrics",
529            "def_model",
530            "def_texture",
531            "def_idkit",
532            "def_mesanim",
533            "def_hitmark",
534            "def_stat",
535            "def_component",
536            "def_interface",
537            "def_toplevelinterface",
538            "def_overlayinterface",
539            "def_inv",
540            "def_enum",
541            "def_struct",
542            "def_param",
543            "def_dbtable",
544            "def_dbrow",
545            "def_dbcolumn",
546            "def_category",
547            "def_varp",
548            "def_varn",
549            "def_vars",
550            "def_varpbit",
551            "def_varc",
552            "def_varclan",
553            "def_varclansetting",
554            "def_varcon",
555            "def_varconbit",
556            "def_varnbit",
557            "def_varobj",
558            "def_mapzone",
559            "def_maparea",
560            "def_mapelement",
561            "def_loc_shape",
562            "def_npc_mode",
563            "def_npc_stat",
564            "def_area",
565            "def_hunt",
566            "def_movespeed",
567            "def_entityoverlay",
568            "def_stringvector",
569            "def_writeinv",
570            "def_controller",
571            "def_regionuid",
572            "def_bas",
573            "def_billboard",
574            "def_particleeffector",
575            "def_particleemitter",
576            "def_cursor",
577            "def_flo",
578            "def_flu",
579            "def_itemcode",
580            "def_light",
581            "def_msi",
582            "def_quest",
583        ]
584    }
585}
586
587impl std::fmt::Display for Type {
588    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
589        write!(f, "{}", self.name())
590    }
591}