1use crate::bytecode::{CompiledScript, Instruction, Opcode, Operand};
3use crate::compiler::Compiler;
4use crate::ide::highlighting::interpolations;
5use crate::lexer::Lexer;
6use crate::parser::{Expr, ScriptDeclaration, ScriptFile, Statement, StringPart};
7use crate::symbol::{SymbolKind, SymbolRegistry};
8use crate::text::LineIndex;
9use crate::token::Kind;
10use crate::typechecker::TypeChecker;
11use crate::types::{BaseVarType, Type};
12use std::collections::HashMap;
13use std::fmt::Write;
14use std::ops::Range;
15use std::path::Path;
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub struct StackEffect {
20 pub pops: [usize; 3],
21 pub pushes: [usize; 3],
22}
23
24impl StackEffect {
25 fn signature(params: &[Type], returns: &[Type]) -> Self {
26 fn counts(types: &[Type]) -> [usize; 3] {
27 let mut counts = [0; 3];
28 for ty in types {
29 counts[match ty.base_type() {
30 BaseVarType::Integer => 0,
31 BaseVarType::String => 1,
32 BaseVarType::Long => 2,
33 }] += 1;
34 }
35 counts
36 }
37 Self {
38 pops: counts(params),
39 pushes: counts(returns),
40 }
41 }
42}
43
44#[derive(Clone, Debug)]
45pub struct InspectedInstruction {
46 pub pc: usize,
47 pub mnemonic: String,
48 pub operand: String,
49 pub effect: Option<StackEffect>,
50}
51
52#[derive(Clone, Debug)]
53pub struct CallInspection {
54 pub range: Range<usize>,
55 pub call: String,
56 pub script: String,
57 pub instructions: Vec<InspectedInstruction>,
58 pub net: Option<[i64; 3]>,
59 pub whole_script: bool,
61}
62
63impl CallInspection {
64 pub fn markdown(&self) -> String {
65 let mut out = format!("# Bytecode: {}\n\nScript: `{}`\n\n", self.call, self.script);
66 if self.whole_script {
67 out.push_str("Showing the entire containing script.\n\n");
68 }
69 out.push_str(
70 "Instruction order includes argument evaluation. Stack columns show pops → pushes.\n\n",
71 );
72 out.push_str("| PC | Instruction | Operand | int | string | long |\n| ---: | --- | --- | ---: | ---: | ---: |\n");
73 for row in &self.instructions {
74 let counts = row
75 .effect
76 .map(|effect| {
77 (0..3)
78 .map(|i| format!("{} → {}", effect.pops[i], effect.pushes[i]))
79 .collect::<Vec<_>>()
80 })
81 .unwrap_or_else(|| vec!["unknown".into(); 3]);
82 let operand = row.operand.replace('|', "\\|").replace('\n', "\\n");
83 let _ = writeln!(
84 out,
85 "| {} | {} | {} | {} | {} | {} |",
86 row.pc, row.mnemonic, operand, counts[0], counts[1], counts[2]
87 );
88 }
89 match self.net {
90 Some(net) => { let _ = writeln!(out, "\nNet stack change: int {:+}, string {:+}, long {:+}.", net[0], net[1], net[2]); }
91 None => out.push_str("\nNet stack change: unknown (an instruction has an unknown effect or the sequence branches).\n"),
92 }
93 if self.instructions.is_empty() {
94 out.push_str("\nThis selection emits no instructions.\n");
95 }
96 out
97 }
98}
99
100pub fn call_range(
102 source: &str,
103 path: &Path,
104 selection: Range<usize>,
105 registry: &SymbolRegistry,
106) -> Result<Option<Range<usize>>, String> {
107 let file = crate::clientscript::parse(source, path).map_err(|error| error.to_string())?;
108 Ok(select(source, path, &file, selection, registry)?.map(|(_, call)| call.range))
109}
110
111pub fn inspect_call(
113 source: &str,
114 path: &Path,
115 selection: Range<usize>,
116 registry: &SymbolRegistry,
117 client: bool,
118) -> Result<Option<CallInspection>, String> {
119 let file = crate::clientscript::parse(source, path).map_err(|error| error.to_string())?;
120 let Some((script, call)) = select(source, path, &file, selection, registry)? else {
121 return Ok(None);
122 };
123 inspect_script(script, path, registry, client, InspectionTarget::Call(call)).map(Some)
124}
125
126pub fn inspect_code(
129 source: &str,
130 path: &Path,
131 selection: Range<usize>,
132 registry: &SymbolRegistry,
133 client: bool,
134) -> Result<Option<CallInspection>, String> {
135 validate_selection(source, &selection)?;
136 let file = crate::clientscript::parse(source, path).map_err(|error| error.to_string())?;
137 let Some((script, range)) = containing_script(source, &file, selection.clone())? else {
138 return Ok(None);
139 };
140 let target = match select(source, path, &file, selection, registry)? {
141 Some((_, call)) => InspectionTarget::Call(call),
142 None => InspectionTarget::Script(range),
143 };
144 inspect_script(script, path, registry, client, target).map(Some)
145}
146
147enum InspectionTarget {
148 Call(CallSite),
149 Script(Range<usize>),
150}
151
152fn inspect_script(
153 script: &ScriptDeclaration,
154 path: &Path,
155 registry: &SymbolRegistry,
156 client: bool,
157 target: InspectionTarget,
158) -> Result<CallInspection, String> {
159 let mut checker = TypeChecker::new(registry);
160 checker.check_file(
161 &ScriptFile {
162 scripts: vec![script.clone()],
163 },
164 path,
165 );
166 if checker.diagnostics.has_errors() {
167 return Err(checker
168 .diagnostics
169 .errors()
170 .iter()
171 .map(ToString::to_string)
172 .collect::<Vec<_>>()
173 .join("\n"));
174 }
175 let mut compiler = Compiler::new(registry);
176 let (compiled, traces) = compiler.compile_traced(script, client);
177 if !compiler.errors.is_empty() {
178 return Err(compiler.errors.join("\n"));
179 }
180 let (range, call, selected_instructions, whole_script) = match target {
181 InspectionTarget::Call(call) => {
182 let trace = traces
183 .iter()
184 .find(|trace| trace.expression == call.expression)
185 .ok_or("The selected expression has no direct call lowering to inspect.")?;
186 (call.range, call.name, trace.instructions.clone(), false)
187 }
188 InspectionTarget::Script(range) => (
189 range,
190 "entire script".to_owned(),
191 0..compiled.instructions.len(),
192 true,
193 ),
194 };
195 let effects: HashMap<_, _> = traces
196 .iter()
197 .filter_map(|trace| {
198 Some((
199 trace.operation?,
200 trace
201 .signature
202 .as_ref()
203 .map(|(params, returns)| StackEffect::signature(params, returns)),
204 ))
205 })
206 .collect();
207 let mut positions = Vec::with_capacity(compiled.instructions.len() + 1);
208 let mut pc = 0;
209 for instruction in &compiled.instructions {
210 positions.push(pc);
211 if instruction.opcode != Opcode::LineNumber {
212 pc += 1;
213 }
214 }
215 positions.push(pc);
216 let mut instructions = Vec::new();
217 let mut net = Some([0i64; 3]);
218 for index in selected_instructions {
219 let instruction = &compiled.instructions[index];
220 if instruction.opcode == Opcode::LineNumber {
221 continue;
222 }
223 let effect = effects
224 .get(&index)
225 .copied()
226 .unwrap_or_else(|| instruction_effect(instruction, registry));
227 if let (Some(total), Some(effect)) = (&mut net, effect) {
228 for (i, total) in total.iter_mut().enumerate() {
229 *total += effect.pushes[i] as i64 - effect.pops[i] as i64;
230 }
231 } else {
232 net = None;
233 }
234 if matches!(
235 instruction.operand,
236 Operand::JumpTarget(_) | Operand::SwitchTable(_)
237 ) || matches!(instruction.opcode, Opcode::Raw | Opcode::Return)
238 {
239 net = None;
240 }
241 let (mnemonic, operand) = display_instruction(&compiled, instruction, &positions, registry);
242 instructions.push(InspectedInstruction {
243 pc: positions[index],
244 mnemonic,
245 operand,
246 effect,
247 });
248 }
249 Ok(CallInspection {
250 range,
251 call,
252 script: compiled.name,
253 instructions,
254 net,
255 whole_script,
256 })
257}
258
259#[derive(Clone, Copy, PartialEq, Eq)]
260enum CallKind {
261 Command,
262 Proc,
263 Jump,
264}
265
266struct CallSite {
267 expression: usize,
268 name: String,
269 range: Range<usize>,
270}
271
272struct Candidate {
273 kind: CallKind,
274 name: String,
275 range: Range<usize>,
276}
277
278fn validate_selection(source: &str, selection: &Range<usize>) -> Result<(), String> {
279 if selection.start > selection.end
280 || selection.end > source.len()
281 || !source.is_char_boundary(selection.start)
282 || !source.is_char_boundary(selection.end)
283 {
284 return Err("Invalid source selection.".into());
285 }
286 Ok(())
287}
288
289fn containing_script<'a>(
290 source: &str,
291 file: &'a ScriptFile,
292 mut selection: Range<usize>,
293) -> Result<Option<(&'a ScriptDeclaration, Range<usize>)>, String> {
294 if !selection.is_empty() {
295 let selected = &source[selection.clone()];
296 if !selected.trim().is_empty() {
297 let leading = selected.len() - selected.trim_start().len();
298 selection.end = selection.start + selected.trim_end().len();
299 selection.start += leading;
300 }
301 }
302 let lines = LineIndex::new(source);
303 let selected_line = lines.line_at(selection.start) + 1;
304 let Some((index, script)) = file
305 .scripts
306 .iter()
307 .enumerate()
308 .rev()
309 .find(|(_, script)| script.line <= selected_line)
310 else {
311 return Ok(None);
312 };
313 if file
314 .scripts
315 .iter()
316 .filter(|other| other.line == script.line)
317 .count()
318 > 1
319 {
320 return Err(
321 "Place script declarations on separate lines before inspecting their bytecode.".into(),
322 );
323 }
324 let start = lines.line(script.line - 1).map_or(0, |line| line.start);
325 let end = file
326 .scripts
327 .get(index + 1)
328 .and_then(|next| lines.line(next.line - 1))
329 .map_or(source.len(), |line| line.start);
330 if selection.end > end {
331 return Err("The selection crosses script declarations. Select code within one script to inspect its bytecode.".into());
332 }
333 if script.trigger == "command" {
334 return Err(
335 "Command declarations have no script bytecode. Select a command call or a script body."
336 .into(),
337 );
338 }
339 Ok(Some((script, start..end)))
340}
341
342fn select<'a>(
343 source: &str,
344 path: &Path,
345 file: &'a ScriptFile,
346 mut selection: Range<usize>,
347 registry: &SymbolRegistry,
348) -> Result<Option<(&'a ScriptDeclaration, CallSite)>, String> {
349 validate_selection(source, &selection)?;
350 if !selection.is_empty() {
351 let selected = &source[selection.clone()];
352 let leading = selected.len() - selected.trim_start().len();
353 let selected = selected.trim_end();
354 let selected = selected.strip_suffix(';').unwrap_or(selected).trim_end();
355 if selected.len() <= leading {
356 return Ok(None);
357 }
358 selection.end = selection.start + selected.len();
359 selection.start += leading;
360 }
361 let lines = LineIndex::new(source);
362 let selected_line = lines.line_at(selection.start) + 1;
363 let Some(script) = file
364 .scripts
365 .iter()
366 .rev()
367 .find(|script| script.line <= selected_line)
368 else {
369 return Ok(None);
370 };
371 if script.trigger == "command" {
372 return Ok(None);
373 }
374 let start = lines.line(script.line - 1).map_or(0, |line| line.start);
375 let end = file
376 .scripts
377 .iter()
378 .find(|next| next.line > script.line)
379 .and_then(|next| lines.line(next.line - 1))
380 .map_or(source.len(), |line| line.start);
381 let candidates = candidates(source, path, start..end, registry)?;
382 let mut expressions = Vec::new();
383 visit_statements(&script.body, &mut |expr| match expr {
384 Expr::CommandCall { name, .. } => expressions.push((expr, CallKind::Command, name)),
385 Expr::ProcCall { name, .. } => expressions.push((expr, CallKind::Proc, name)),
386 Expr::JumpCall { name, .. } => expressions.push((expr, CallKind::Jump, name)),
387 Expr::Identifier(name)
388 if registry
389 .lookup_command(name.trim_start_matches('.'))
390 .is_some() =>
391 {
392 expressions.push((expr, CallKind::Command, name))
393 }
394 _ => {}
395 });
396 let mut cursor = 0;
397 let mut found: Option<CallSite> = None;
398 for (expr, kind, name) in expressions {
399 let Some(relative) = candidates[cursor..]
400 .iter()
401 .position(|candidate| candidate.kind == kind && candidate.name == *name)
402 else {
403 continue;
404 };
405 let candidate = &candidates[cursor + relative];
406 cursor += relative + 1;
407 let contains = candidate.range.start <= selection.start
408 && candidate.range.end >= selection.end
409 && (selection.start < candidate.range.end || selection.start == candidate.range.start);
410 if contains
411 && found
412 .as_ref()
413 .is_none_or(|old| old.range.len() > candidate.range.len())
414 {
415 found = Some(CallSite {
416 expression: expr as *const Expr as usize,
417 name: match kind {
418 CallKind::Proc => format!("~{name}"),
419 CallKind::Jump => format!("@{name}"),
420 CallKind::Command => name.clone(),
421 },
422 range: candidate.range.clone(),
423 });
424 }
425 }
426 Ok(found.map(|call| (script, call)))
427}
428
429fn candidates(
430 source: &str,
431 path: &Path,
432 range: Range<usize>,
433 registry: &SymbolRegistry,
434) -> Result<Vec<Candidate>, String> {
435 fn tokens(
436 source: &str,
437 path: &Path,
438 range: Range<usize>,
439 out: &mut Vec<(Kind, String, Range<usize>)>,
440 depth: usize,
441 ) -> Result<(), String> {
442 if depth > 32 {
443 return Ok(());
444 }
445 let label = path.to_path_buf();
446 let (lexed, spans, errors) = Lexer::new(&source[range.clone()], &label).tokenize_spanned();
447 if !errors.is_empty() {
448 return Err(errors
449 .iter()
450 .map(ToString::to_string)
451 .collect::<Vec<_>>()
452 .join("\n"));
453 }
454 for (token, span) in lexed.into_iter().zip(spans) {
455 let span = span.start + range.start..span.end + range.start;
456 if token.kind == Kind::StringLiteral {
457 for (part, code) in interpolations(&source[span.clone()]) {
458 if code {
459 tokens(
460 source,
461 path,
462 span.start + part.start + 1..span.start + part.end - 1,
463 out,
464 depth + 1,
465 )?;
466 }
467 }
468 }
469 if !matches!(
470 token.kind,
471 Kind::SingleLineComment | Kind::MultiLineComment | Kind::EndOfFile
472 ) {
473 out.push((token.kind, token.value, span));
474 }
475 }
476 Ok(())
477 }
478 let mut lexed = Vec::new();
479 tokens(source, path, range, &mut lexed, 0)?;
480 lexed.sort_by_key(|token| token.2.start);
481 let mut body = lexed
482 .iter()
483 .position(|token| token.0 == Kind::RBracket)
484 .map_or(0, |index| index + 1);
485 while lexed.get(body).is_some_and(|token| token.0 == Kind::LParen) {
486 body = close_parens(&lexed, body).map_or(lexed.len(), |end| end + 1);
487 }
488 let mut result = Vec::new();
489 for i in body..lexed.len() {
490 if !matches!(lexed[i].0, Kind::Identifier | Kind::Command | Kind::Trigger) {
491 continue;
492 }
493 let mut first = i;
494 let mut name = lexed[i].1.clone();
495 if first > 0 && lexed[first - 1].0 == Kind::Dot {
496 first -= 1;
497 name.insert(0, '.');
498 }
499 let kind = match first.checked_sub(1).map(|previous| lexed[previous].0) {
500 Some(Kind::ScriptCall) => {
501 first -= 1;
502 CallKind::Proc
503 }
504 Some(Kind::JumpCall) => {
505 first -= 1;
506 CallKind::Jump
507 }
508 Some(Kind::LocalVar | Kind::GameVar | Kind::ConstantVar | Kind::Colon) => continue,
509 _ => CallKind::Command,
510 };
511 let mut next = i + 1;
512 if lexed
513 .get(next)
514 .is_some_and(|token| token.0 == Kind::BinaryOperator && token.1 == "*")
515 {
516 name.push('*');
517 next += 1;
518 }
519 let parenthesized = lexed.get(next).is_some_and(|token| token.0 == Kind::LParen);
520 if kind == CallKind::Command
521 && !parenthesized
522 && registry
523 .lookup_command(name.trim_start_matches('.'))
524 .is_none()
525 {
526 continue;
527 }
528 let mut end = lexed[i].2.end;
529 while lexed.get(next).is_some_and(|token| token.0 == Kind::LParen) {
530 let Some(close) = close_parens(&lexed, next) else {
531 break;
532 };
533 end = lexed[close].2.end;
534 next = close + 1;
535 }
536 result.push(Candidate {
537 kind,
538 name,
539 range: lexed[first].2.start..end,
540 });
541 }
542 Ok(result)
543}
544
545fn close_parens(tokens: &[(Kind, String, Range<usize>)], start: usize) -> Option<usize> {
546 let mut depth = 0usize;
547 for (i, (kind, _, _)) in tokens.iter().enumerate().skip(start) {
548 match kind {
549 Kind::LParen => depth += 1,
550 Kind::RParen => {
551 depth = depth.checked_sub(1)?;
552 if depth == 0 {
553 return Some(i);
554 }
555 }
556 _ => {}
557 }
558 }
559 None
560}
561
562fn visit_statements<'a>(statements: &'a [Statement], visit: &mut impl FnMut(&'a Expr)) {
563 for statement in statements {
564 match statement {
565 Statement::VarDeclaration { value, .. } => {
566 if let Some(value) = value {
567 visit_expr(value, visit);
568 }
569 }
570 Statement::ArrayDeclaration { size, .. } => visit_expr(size, visit),
571 Statement::Assignment { target, value, .. } => {
572 visit_expr(target, visit);
573 visit_expr(value, visit);
574 }
575 Statement::Expression { expr, .. } => visit_expr(expr, visit),
576 Statement::Return { values, .. } => {
577 for value in values {
578 visit_expr(value, visit);
579 }
580 }
581 Statement::If {
582 condition,
583 body,
584 else_if,
585 else_body,
586 ..
587 } => {
588 visit_expr(condition, visit);
589 visit_statements(body, visit);
590 for (condition, body, _) in else_if {
591 visit_expr(condition, visit);
592 visit_statements(body, visit);
593 }
594 if let Some(body) = else_body {
595 visit_statements(body, visit);
596 }
597 }
598 Statement::While {
599 condition, body, ..
600 } => {
601 visit_expr(condition, visit);
602 visit_statements(body, visit);
603 }
604 Statement::Switch {
605 expr,
606 cases,
607 default,
608 default_index,
609 ..
610 } => {
611 visit_expr(expr, visit);
612 for i in 0..=cases.len() {
613 if i == *default_index
614 && let Some(body) = default
615 {
616 visit_statements(body, visit);
617 }
618 if let Some(case) = cases.get(i) {
619 for value in &case.values {
620 visit_expr(value, visit);
621 }
622 visit_statements(&case.body, visit);
623 }
624 }
625 }
626 Statement::OrphanCase { case, .. } => {
627 for value in &case.values {
628 visit_expr(value, visit);
629 }
630 visit_statements(&case.body, visit);
631 }
632 Statement::Empty => {}
633 }
634 }
635}
636
637fn visit_expr<'a>(expr: &'a Expr, visit: &mut impl FnMut(&'a Expr)) {
638 visit(expr);
639 match expr {
640 Expr::CommandCall { args, .. }
641 | Expr::ProcCall { args, .. }
642 | Expr::JumpCall { args, .. }
643 | Expr::Tuple(args)
644 | Expr::MultiAssign(args, _) => {
645 for arg in args {
646 visit_expr(arg, visit);
647 }
648 }
649 Expr::ArrayAccess { index, .. } | Expr::Calc(index) => visit_expr(index, visit),
650 Expr::BinaryOp { lhs, rhs, .. } | Expr::LogicalOp { lhs, rhs, .. } => {
651 visit_expr(lhs, visit);
652 visit_expr(rhs, visit);
653 }
654 Expr::JoinedString { parts } => {
655 for part in parts {
656 if let StringPart::Expr(expr) = part {
657 visit_expr(expr, visit);
658 }
659 }
660 }
661 _ => {}
662 }
663}
664
665fn instruction_effect(instruction: &Instruction, registry: &SymbolRegistry) -> Option<StackEffect> {
666 use Opcode::*;
667 let effect = |pops, pushes| Some(StackEffect { pops, pushes });
668 if matches!(
669 instruction.opcode,
670 PushVarp
671 | PushVarn
672 | PushVars
673 | PushVarbit
674 | PushVarcInt
675 | PushVarcString
676 | PushVarClan
677 | PushVarObj
678 | PushVarnBit
679 | PushVarCon
680 | PushVarConBit
681 | PushClanSettingInt
682 | PushClanSettingVarbit
683 | PushClanSettingLong
684 | PushClanSettingString
685 | PopVarp
686 | PopVarn
687 | PopVars
688 | PopVarbit
689 | PopVarcInt
690 | PopVarcString
691 | PopVarClan
692 | PopVarObj
693 | PopVarnBit
694 | PopVarCon
695 | PopVarConBit
696 | PopClanSettingInt
697 | PopClanSettingVarbit
698 | PopClanSettingLong
699 | PopClanSettingString
700 ) {
701 let Operand::Int(encoded) = instruction.operand else {
702 return None;
703 };
704 return registry.game_variables().find_map(|(_, symbol)| {
705 let SymbolKind::GameVar {
706 var_id,
707 var_type,
708 category,
709 } = &symbol.kind
710 else {
711 return None;
712 };
713 if *var_id != (encoded & 0xffff) {
714 return None;
715 }
716 if Opcode::push_var(category) == instruction.opcode {
717 Some(StackEffect::signature(&[], &[*var_type]))
718 } else if Opcode::pop_var(category) == instruction.opcode {
719 Some(StackEffect::signature(&[*var_type], &[]))
720 } else {
721 None
722 }
723 });
724 }
725 match instruction.opcode {
726 PushConstantInt | PushIntLocal => effect([0; 3], [1, 0, 0]),
727 PushConstantString | PushStringLocal => effect([0; 3], [0, 1, 0]),
728 PushConstantLong | PushLongLocal => effect([0; 3], [0, 0, 1]),
729 PopIntLocal | PopIntDiscard | DefineArray => effect([1, 0, 0], [0; 3]),
730 PopStringLocal | PopStringDiscard => effect([0, 1, 0], [0; 3]),
731 PopLongLocal | PopLongDiscard => effect([0, 0, 1], [0; 3]),
732 PushArrayInt => effect([1, 0, 0], [1, 0, 0]),
733 PopArrayInt => effect([2, 0, 0], [0; 3]),
734 JoinString => match instruction.operand {
735 Operand::StringCount(count) => effect([0, count as usize, 0], [0, 1, 0]),
736 _ => None,
737 },
738 Branch => effect([0; 3], [0; 3]),
739 BranchIfTrue | BranchIfFalse | Switch => effect([1, 0, 0], [0; 3]),
740 BranchNot
741 | BranchEquals
742 | BranchLessThan
743 | BranchGreaterThan
744 | BranchLessThanOrEquals
745 | BranchGreaterThanOrEquals => effect([2, 0, 0], [0; 3]),
746 LongBranchNot
747 | LongBranchEquals
748 | LongBranchLessThan
749 | LongBranchGreaterThan
750 | LongBranchLessThanOrEquals
751 | LongBranchGreaterThanOrEquals => effect([0, 0, 2], [0; 3]),
752 Add | Sub | Multiply | Divide | Modulo | And | Or | Min | Max | Pow | InvPow | SetBit
753 | ClearBit | TestBit | AddPercent | ToggleBit => effect([2, 0, 0], [1, 0, 0]),
754 Random | RandomInc | BitCount | SinDeg | CosDeg | Abs => effect([1, 0, 0], [1, 0, 0]),
755 Interpolate => effect([5, 0, 0], [1, 0, 0]),
756 Scale | SetBitRange | ClearBitRange | GetBitRange => effect([3, 0, 0], [1, 0, 0]),
757 SetBitRangeToVal => effect([4, 0, 0], [1, 0, 0]),
758 Atan2Deg => effect([2, 0, 0], [1, 0, 0]),
759 Command => {
760 command_symbol(instruction, registry).and_then(|(name, symbol)| match &symbol.kind {
761 SymbolKind::Command {
762 param_types,
763 return_types,
764 ..
765 } if !(param_types.is_empty() && return_types.is_empty())
766 && !param_types
767 .iter()
768 .chain(return_types)
769 .any(|ty| matches!(ty, Type::Any | Type::Error))
770 && !registry.dynamic_returns.contains_key(name)
771 && !registry.hook_commands.contains_key(name)
772 && Compiler::command_variadic_info(name).is_none() =>
773 {
774 Some(StackEffect::signature(param_types, return_types))
775 }
776 _ => None,
777 })
778 }
779 _ => None,
780 }
781}
782
783fn command_symbol<'a>(
784 instruction: &Instruction,
785 registry: &'a SymbolRegistry,
786) -> Option<(&'a str, &'a crate::symbol::Symbol)> {
787 let Operand::Int(encoded) = instruction.operand else {
788 return None;
789 };
790 registry
791 .commands
792 .iter()
793 .find_map(|(name, symbol)| match symbol.kind {
794 SymbolKind::Command { opcode, .. } if opcode == (encoded & 0xffff) => {
795 Some((name.as_str(), symbol))
796 }
797 _ => None,
798 })
799}
800
801fn display_instruction(
802 script: &CompiledScript,
803 instruction: &Instruction,
804 positions: &[usize],
805 registry: &SymbolRegistry,
806) -> (String, String) {
807 if instruction.opcode == Opcode::Raw
808 && let Operand::Long(encoded) = instruction.operand
809 {
810 return (
811 format!("Raw opcode {}", (encoded >> 32) as u16),
812 (encoded as i32).to_string(),
813 );
814 }
815 if instruction.opcode == Opcode::Command
816 && let Some((name, _)) = command_symbol(instruction, registry)
817 {
818 let Operand::Int(encoded) = instruction.operand else {
819 unreachable!()
820 };
821 return (
822 name.to_owned(),
823 format!(
824 "opcode {}, operand {}",
825 encoded & 0xffff,
826 (encoded >> 16) & 255
827 ),
828 );
829 }
830 let operand = match &instruction.operand {
831 Operand::None => String::new(),
832 Operand::Int(value) => value.to_string(),
833 Operand::Long(value) => value.to_string(),
834 Operand::Str(index) => format!(
835 "{:?}",
836 script
837 .strings
838 .get(*index as usize)
839 .map(|s| s.as_ref())
840 .unwrap_or("<missing string>")
841 ),
842 Operand::JumpTarget(target) => positions
843 .get(*target)
844 .map_or_else(|| "unknown target".into(), |pc| format!("→ {pc}")),
845 Operand::SwitchTable(index) => format!("{:?}", script.switch_tables.get(*index as usize)),
846 Operand::StringCount(count) => count.to_string(),
847 Operand::ArrayDef(slot, kind) => format!("array {slot}, type {}", *kind as char),
848 };
849 (format!("{:?}", instruction.opcode), operand)
850}