runec/clientscript/
format.rs1use super::invalid;
2use crate::bytecode::Opcode;
3use crate::types::BaseVarType;
4use std::collections::{BTreeMap, HashMap, HashSet};
5use std::fs;
6use std::io::Result;
7use std::path::Path;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum Width {
11 Byte,
12 Int,
13 Long,
14 String,
15}
16
17impl Width {
18 fn instruction(opcode: Opcode) -> Self {
19 match opcode {
20 Opcode::PushConstantString => Self::String,
21 Opcode::PushConstantLong => Self::Long,
22 Opcode::Return | Opcode::PopIntDiscard | Opcode::PopStringDiscard => Self::Byte,
23 _ => Self::Int,
24 }
25 }
26
27 pub(super) fn integer(self, out: &mut Vec<u8>, value: i64) -> Result<()> {
28 match self {
29 Self::Byte => out.push(u8::try_from(value).map_err(invalid)?),
30 Self::Int => {
31 out.extend_from_slice(&i32::try_from(value).map_err(invalid)?.to_be_bytes())
32 }
33 Self::Long => out.extend_from_slice(&value.to_be_bytes()),
34 Self::String => return Err(invalid("Expected string operand")),
35 }
36 Ok(())
37 }
38}
39
40#[derive(Clone, Debug)]
41pub struct Format {
42 instructions: HashMap<Opcode, (u16, Width)>,
43 decoding: HashMap<u16, (Opcode, Width)>,
44 pub commands: BTreeMap<u16, String>,
45 pub local_types: Vec<BaseVarType>,
46 pub switches: bool,
47}
48
49impl Format {
50 pub fn load(path: &Path) -> Result<Self> {
51 Self::parse(&fs::read_to_string(path)?)
52 }
53
54 pub fn parse(text: &str) -> Result<Self> {
55 let mut instructions = HashMap::new();
56 let mut commands = BTreeMap::new();
57 let mut codes = HashSet::new();
58 let mut names = HashSet::new();
59 for (index, line) in text.lines().map(str::trim).enumerate() {
60 if line.is_empty() || line.starts_with('#') {
61 continue;
62 }
63 let (code, name) = line
64 .split_once('=')
65 .ok_or_else(|| invalid(format!("Line {}: expected opcode=name", index + 1)))?;
66 let (code, name) = (code.trim().parse::<u16>().map_err(invalid)?, name.trim());
67 if name.is_empty() {
68 return Err(invalid(format!("Missing operation name for opcode {code}")));
69 }
70 if !codes.insert(code) || !names.insert(name) {
71 return Err(invalid(format!(
72 "Duplicate operation {name} or opcode {code}"
73 )));
74 }
75 if let Some(opcode) = Opcode::core(name) {
76 instructions.insert(opcode, (code, Width::instruction(opcode)));
77 } else {
78 commands.insert(code, name.to_owned());
79 }
80 }
81 let mut local_types = vec![BaseVarType::Integer, BaseVarType::String];
82 if instructions.contains_key(&Opcode::PushConstantLong) {
83 local_types.push(BaseVarType::Long);
84 }
85 let switches = instructions.contains_key(&Opcode::Switch);
86 let mut decoding = instructions
87 .iter()
88 .map(|(&opcode, &(code, width))| (code, (opcode, width)))
89 .collect::<HashMap<_, _>>();
90 decoding.extend(
91 commands
92 .keys()
93 .map(|&code| (code, (Opcode::Command, Width::Byte))),
94 );
95 Ok(Self {
96 instructions,
97 decoding,
98 commands,
99 local_types,
100 switches,
101 })
102 }
103
104 pub fn has(&self, opcode: Opcode) -> bool {
105 self.instructions.contains_key(&opcode)
106 }
107
108 pub fn instruction(&self, opcode: Opcode) -> Result<(u16, Width)> {
109 self.instructions
110 .get(&opcode)
111 .copied()
112 .ok_or_else(|| invalid(format!("Missing operation {opcode:?} in opcode pack")))
113 }
114
115 pub fn width(&self, code: u16) -> Width {
116 self.decoding
117 .get(&code)
118 .map_or(Width::Byte, |&(_, width)| width)
119 }
120
121 pub fn define(&mut self, operation: Opcode, code: u16, width: Width) -> Result<()> {
123 let compatible = match operation {
124 Opcode::PushConstantString => width == Width::String,
125 Opcode::PushConstantLong => width == Width::Long,
126 _ => matches!(width, Width::Byte | Width::Int),
127 };
128 if !compatible {
129 return Err(invalid(format!(
130 "Operand width {width:?} is incompatible with {operation:?}"
131 )));
132 }
133 if self.decoding.contains_key(&code) || self.instructions.contains_key(&operation) {
134 return Err(invalid(format!(
135 "Duplicate operation {operation:?} or opcode {code}"
136 )));
137 }
138 self.instructions.insert(operation, (code, width));
139 self.decoding.insert(code, (operation, width));
140 Ok(())
141 }
142
143 pub fn define_command(&mut self, name: String, code: u16, width: Width) -> Result<()> {
144 if name.is_empty() || !matches!(width, Width::Byte | Width::Int) {
145 return Err(invalid(
146 "Commands require a name and a byte or integer operand",
147 ));
148 }
149 if self.decoding.contains_key(&code)
150 || self.commands.values().any(|existing| *existing == name)
151 {
152 return Err(invalid(format!(
153 "Duplicate command {name} or opcode {code}"
154 )));
155 }
156 self.commands.insert(code, name);
157 self.decoding.insert(code, (Opcode::Command, width));
158 Ok(())
159 }
160
161 pub fn decode(&self, code: u16) -> Result<(Opcode, Width)> {
162 self.decoding
163 .get(&code)
164 .copied()
165 .ok_or_else(|| invalid(format!("Undefined opcode {code}")))
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 #[test]
174 fn client_var_instructions_take_an_int_operand() {
175 let format =
176 Format::parse("643=PushVarClan\n274=PushVarClanBit\n47=PushVarPlayer\n").unwrap();
177 assert_eq!(
178 format.decode(643).unwrap(),
179 (Opcode::PushVarClan, Width::Int)
180 );
181 assert_eq!(
182 format.decode(274).unwrap(),
183 (Opcode::PushVarClanBit, Width::Int)
184 );
185 assert_eq!(
186 format.decode(47).unwrap(),
187 (Opcode::PushVarPlayer, Width::Int)
188 );
189 }
190}