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 instruction(&self, opcode: Opcode) -> Result<(u16, Width)> {
105 self.instructions
106 .get(&opcode)
107 .copied()
108 .ok_or_else(|| invalid(format!("Missing operation {opcode:?} in opcode pack")))
109 }
110
111 pub fn width(&self, code: u16) -> Width {
112 self.decoding
113 .get(&code)
114 .map_or(Width::Byte, |&(_, width)| width)
115 }
116
117 pub fn define(&mut self, operation: Opcode, code: u16, width: Width) -> Result<()> {
119 let compatible = match operation {
120 Opcode::PushConstantString => width == Width::String,
121 Opcode::PushConstantLong => width == Width::Long,
122 _ => matches!(width, Width::Byte | Width::Int),
123 };
124 if !compatible {
125 return Err(invalid(format!(
126 "Operand width {width:?} is incompatible with {operation:?}"
127 )));
128 }
129 if self.decoding.contains_key(&code) || self.instructions.contains_key(&operation) {
130 return Err(invalid(format!(
131 "Duplicate operation {operation:?} or opcode {code}"
132 )));
133 }
134 self.instructions.insert(operation, (code, width));
135 self.decoding.insert(code, (operation, width));
136 Ok(())
137 }
138
139 pub fn define_command(&mut self, name: String, code: u16, width: Width) -> Result<()> {
140 if name.is_empty() || !matches!(width, Width::Byte | Width::Int) {
141 return Err(invalid(
142 "Commands require a name and a byte or integer operand",
143 ));
144 }
145 if self.decoding.contains_key(&code)
146 || self.commands.values().any(|existing| *existing == name)
147 {
148 return Err(invalid(format!(
149 "Duplicate command {name} or opcode {code}"
150 )));
151 }
152 self.commands.insert(code, name);
153 self.decoding.insert(code, (Opcode::Command, width));
154 Ok(())
155 }
156
157 pub fn decode(&self, code: u16) -> Result<(Opcode, Width)> {
158 self.decoding
159 .get(&code)
160 .copied()
161 .ok_or_else(|| invalid(format!("Undefined opcode {code}")))
162 }
163}