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