1use std::cell::{Cell, OnceCell};
2use std::fmt::{self, Write};
3use std::rc::Rc;
4
5use rhue_common::{SourceFile, Span};
6
7use crate::{Instr, Op, format_number};
8
9#[derive(Clone, Debug, PartialEq)]
11pub enum Constant {
12 Number(f64),
13 String(Rc<str>),
14}
15
16#[derive(Clone, Debug, PartialEq)]
18pub struct LocalVar {
19 pub name: Rc<str>,
20 pub reg: u8,
21 pub start_pc: u32,
23 pub end_pc: u32,
24}
25
26#[derive(Clone, Debug, PartialEq)]
28pub struct UpvalDesc {
29 pub in_stack: bool,
32 pub index: u8,
33 pub name: Rc<str>,
35}
36
37#[derive(Default)]
45pub struct InlineCache(OnceCell<Box<[Cell<u32>]>>);
46
47impl InlineCache {
48 #[inline]
50 pub fn slot(&self, pc: usize, len: usize) -> &Cell<u32> {
51 &self
52 .0
53 .get_or_init(|| (0..len).map(|_| Cell::new(0)).collect())[pc]
54 }
55}
56
57impl Clone for InlineCache {
58 fn clone(&self) -> Self {
59 InlineCache::default()
60 }
61}
62
63impl PartialEq for InlineCache {
64 fn eq(&self, _: &Self) -> bool {
65 true
66 }
67}
68
69impl fmt::Debug for InlineCache {
70 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71 f.write_str("InlineCache")
72 }
73}
74
75#[derive(Default)]
79pub struct Verified(Cell<bool>);
80
81impl Verified {
82 pub fn get(&self) -> bool {
83 self.0.get()
84 }
85
86 pub fn set(&self) {
87 self.0.set(true);
88 }
89}
90
91impl Clone for Verified {
92 fn clone(&self) -> Self {
93 Verified::default()
94 }
95}
96
97impl PartialEq for Verified {
98 fn eq(&self, _: &Self) -> bool {
99 true
100 }
101}
102
103impl fmt::Debug for Verified {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 write!(f, "Verified({})", self.0.get())
106 }
107}
108
109#[derive(Clone, Debug, Default, PartialEq)]
115pub struct TableTemplate {
116 pub array: u32,
118 pub hash: u32,
120 pub keys: Vec<u32>,
122}
123
124#[derive(Clone, Debug, Default, PartialEq)]
126pub struct Proto {
127 pub name: Option<Rc<str>>,
129 pub code: Vec<Instr>,
130 pub constants: Vec<Constant>,
131 pub spans: Vec<Span>,
133 pub max_stack: u8,
135 pub num_params: u8,
136 pub is_vararg: bool,
137 pub protos: Vec<Rc<Proto>>,
140 pub upvalues: Vec<UpvalDesc>,
141 pub locals: Vec<LocalVar>,
143 pub span: Span,
145 pub source: Rc<SourceFile>,
147 pub templates: Vec<TableTemplate>,
149 pub cache: InlineCache,
151 pub verified: Verified,
153}
154
155impl Proto {
156 pub fn display_name(&self) -> &str {
158 self.name.as_deref().unwrap_or("<anonymous>")
159 }
160
161 pub fn disassemble(&self) -> String {
164 let mut out = String::new();
165 self.disassemble_into(&mut out, true);
166 out
167 }
168
169 fn disassemble_into(&self, out: &mut String, is_main: bool) {
170 let name = if is_main {
171 "<main>"
172 } else {
173 self.display_name()
174 };
175 let _ = write!(
176 out,
177 "function {name} ({} instructions, {} constants, {} registers",
178 self.code.len(),
179 self.constants.len(),
180 self.max_stack
181 );
182 if !is_main {
183 let _ = write!(
184 out,
185 ", {} params{}",
186 self.num_params,
187 if self.is_vararg { " + ..." } else { "" }
188 );
189 }
190 if !self.upvalues.is_empty() {
191 let names: Vec<&str> = self.upvalues.iter().map(|u| &*u.name).collect();
192 let _ = write!(out, ", upvalues: {}", names.join(", "));
193 }
194 let _ = writeln!(out, ")");
195 for (pc, ins) in self.code.iter().enumerate() {
196 let Some(op) = ins.op() else {
197 let _ = writeln!(out, " {pc:>4} <bad opcode {:#04x}>", ins.0 as u8);
198 continue;
199 };
200 let (a, b, c) = (ins.a(), ins.b(), ins.c());
201 let target = |offset: i32| pc as i64 + 1 + offset as i64;
202 let operands = match op {
203 Op::LoadNil | Op::Close => format!("R{a}"),
204 Op::LoadB if c != 0 => format!("R{a} {} skip", b != 0),
205 Op::LoadB => format!("R{a} {}", b != 0),
206 Op::LoadN => format!("R{a} {}", ins.sbx()),
207 Op::LoadK | Op::GetGlobal | Op::SetGlobal => format!("R{a} K{}", ins.bx()),
208 Op::Move | Op::Unm | Op::Not | Op::Len => format!("R{a} R{b}"),
209 Op::Add
210 | Op::Sub
211 | Op::Mul
212 | Op::Div
213 | Op::IDiv
214 | Op::Mod
215 | Op::Pow
216 | Op::Concat => {
217 format!("R{a} R{b} R{c}")
218 }
219 Op::AddK | Op::SubK | Op::MulK | Op::DivK | Op::IDivK | Op::ModK | Op::PowK => {
220 format!("R{a} R{b} K{c}")
221 }
222 Op::Eq | Op::Lt | Op::Le => format!("{} R{b} R{c}", a != 0),
223 Op::EqK | Op::LtK | Op::LeK | Op::GtK | Op::GeK => {
224 format!("{} R{b} K{c}", a != 0)
225 }
226 Op::Jmp => format!("-> {}", target(ins.sax())),
227 Op::JmpIf | Op::JmpIfNot | Op::ForPrep | Op::ForLoop => {
228 format!("R{a} -> {}", target(ins.sbx() as i32))
229 }
230 Op::GetUpval | Op::SetUpval => format!("R{a} U{b}"),
231 Op::Closure => format!("R{a} P{}", ins.bx()),
232 Op::Interp => format!("R{a} R{b} {c}"),
233 Op::TailCall => {
234 let args = if b == 0 {
235 "...".to_string()
236 } else {
237 (b - 1).to_string()
238 };
239 format!("R{a} {args}")
240 }
241 Op::Call => {
242 let args = if b == 0 {
243 "...".to_string()
244 } else {
245 (b - 1).to_string()
246 };
247 let results = if c == 0 {
248 "...".to_string()
249 } else {
250 (c - 1).to_string()
251 };
252 format!("R{a} {args} -> {results}")
253 }
254 Op::Vararg => {
255 if b == 0 {
256 format!("R{a} ...")
257 } else {
258 format!("R{a} {}", b - 1)
259 }
260 }
261 Op::NewTable => format!("R{a} {b} {c}"),
262 Op::DupTable => format!("R{a} T{}", ins.bx()),
263 Op::GetTable | Op::SetTable => format!("R{a} R{b} R{c}"),
264 Op::GetField | Op::SelfOp => format!("R{a} R{b} K{c}"),
265 Op::SetField => format!("R{a} K{b} R{c}"),
266 Op::SetList if b == 0 => format!("R{a} ..."),
267 Op::SetList => format!("R{a} {b}"),
268 Op::Data => format!("{}", ins.sax()),
269 Op::TForCall => format!("R{a} {c}"),
270 Op::TForLoop => format!("R{a} -> {}", target(ins.sbx() as i32)),
271 Op::Return if c != 0 => format!("R{a} ..."),
272 Op::Return => format!("R{a} {b}"),
273 };
274 let comment = match op {
275 Op::LoadK | Op::GetGlobal | Op::SetGlobal => {
276 self.constant_comment(ins.bx() as usize)
277 }
278 Op::AddK
279 | Op::SubK
280 | Op::MulK
281 | Op::DivK
282 | Op::IDivK
283 | Op::ModK
284 | Op::PowK
285 | Op::EqK
286 | Op::LtK
287 | Op::LeK
288 | Op::GtK
289 | Op::GeK => self.constant_comment(c as usize),
290 Op::GetField | Op::SelfOp => self.constant_comment(c as usize),
291 Op::SetField => self.constant_comment(b as usize),
292 Op::GetUpval | Op::SetUpval => self
293 .upvalues
294 .get(b as usize)
295 .map_or_else(String::new, |u| u.name.to_string()),
296 Op::DupTable => self.template_comment(ins.bx() as usize),
297 Op::Closure => self
298 .protos
299 .get(ins.bx() as usize)
300 .map_or_else(String::new, |p| p.display_name().to_string()),
301 _ => String::new(),
302 };
303 let line = format!(" {pc:>4} {:<10}{operands}", op.mnemonic());
304 if comment.is_empty() {
305 let _ = writeln!(out, "{line}");
306 } else {
307 let _ = writeln!(out, "{line:<34}; {comment}");
308 }
309 }
310 for child in &self.protos {
311 let _ = writeln!(out);
312 child.disassemble_into(out, false);
313 }
314 }
315
316 fn template_comment(&self, t: usize) -> String {
318 let Some(t) = self.templates.get(t) else {
319 return "<missing template>".into();
320 };
321 let keys: Vec<String> = t
322 .keys
323 .iter()
324 .map(|&k| match self.constants.get(k as usize) {
325 Some(Constant::String(s)) => s.to_string(),
326 _ => "?".into(),
327 })
328 .collect();
329 format!("{{{}}}", keys.join(", "))
330 }
331
332 fn constant_comment(&self, k: usize) -> String {
333 match self.constants.get(k) {
334 Some(Constant::Number(n)) => format_number(*n),
335 Some(Constant::String(s)) => format!("{s:?}"),
336 None => "<missing constant>".into(),
337 }
338 }
339}