1use source_map_cache::SourceMapWrapper;
6use source_map_node::FileId;
7use std::fmt;
8use std::fmt::Write;
9use swamp_vm_debug_info::DebugInfo;
10use swamp_vm_disasm::disasm_instructions_color;
11use swamp_vm_types::types::{VariableRegister, VmType, show_frame_memory, write_basic_type};
12use swamp_vm_types::{BinaryInstruction, FrameMemoryAddress, InstructionPositionOffset};
13
14#[must_use]
15pub const fn is_valid_file_id(file_id: FileId) -> bool {
16 file_id != 0 && file_id != 0xffff
17}
18pub fn show_parameters_and_variables(
19 return_type: &VmType,
20 variables: &[VariableRegister],
21 f: &mut dyn Write,
22) -> Result<(), fmt::Error> {
23 if !return_type.is_scalar() {
24 writeln!(f, "{}: {}", tinter::blue("r0"), &return_type,)?;
25 write_basic_type(&return_type.basic_type, FrameMemoryAddress(0), f, 0)?;
26 writeln!(f)?;
27 }
28
29 for variable_register in variables {
30 writeln!(
31 f,
32 "{}: ({}): {} {}",
33 tinter::yellow(format!("{}", variable_register.unique_id_in_function)),
34 tinter::magenta(variable_register),
35 variable_register.register.ty,
36 variable_register.register.comment
37 )?;
38 }
39
40 Ok(())
41}
42
43#[must_use]
46pub fn disasm_function(
47 return_type: &VmType,
48 instructions: &[BinaryInstruction],
49 ip_offset: &InstructionPositionOffset,
50 debug_info: &DebugInfo,
51 source_map_wrapper: &SourceMapWrapper,
52) -> String {
53 let mut header_output = String::new();
54
55 let info = debug_info.fetch(ip_offset.0 as usize).unwrap();
56
57 show_frame_memory(&info.function_debug_info.frame_memory, &mut header_output).unwrap();
58
59 show_parameters_and_variables(
60 return_type,
61 &info.function_debug_info.frame_memory.variable_registers,
62 &mut header_output,
63 )
64 .expect("should work");
65
66 format!(
67 "{}\n{}",
68 header_output,
69 disasm_instructions_color(instructions, ip_offset, debug_info, source_map_wrapper,)
70 )
71}
72
73pub fn disasm_whole_program(
74 debug_info: &DebugInfo,
75 source_map_wrapper: &SourceMapWrapper,
76 instructions: &[BinaryInstruction],
77) {
78 let mut current_ip: u32 = 0;
79
80 while current_ip < (instructions.len() - 1) as u32 {
81 if let Some(debug_info_for_pc) = debug_info.fetch(current_ip as usize) {
82 println!(
84 "{} ==========================================================================",
85 debug_info_for_pc.function_debug_info.name
86 );
87 let end_ip = current_ip + debug_info_for_pc.function_debug_info.ip_range.count.0;
88 let instructions_slice = &instructions[current_ip as usize..end_ip as usize];
89
90 let output_string = disasm_function(
91 &debug_info_for_pc.function_debug_info.return_type,
92 instructions_slice,
93 &InstructionPositionOffset(current_ip),
94 debug_info,
95 source_map_wrapper,
96 );
97 println!("{output_string}"); current_ip = end_ip;
99 } else {
100 panic!("instruction pointer that is not covered")
101 }
102 }
103}