Skip to main content

datex_core/disassembler/
disassembler.rs

1use crate::{
2    disassembler::options::DisassemblerOptions,
3    dxb_parser::body::{
4        DXBParserError, InstructionWithSpan, iterate_instructions,
5    },
6    instruction::{
7        CountOrUnbounded, Instruction, NestedInstructionResolutionStrategy,
8        regular_instruction::RegularInstruction,
9        type_instruction::TypeInstruction,
10    },
11    prelude::*,
12    utils::ansi_colors::{AnsiColor, AnsiWrite},
13};
14use alloc::{rc::Rc, vec::IntoIter};
15use core::{
16    cell::RefCell,
17    fmt::{Debug, Write},
18};
19use serde::Serialize;
20
21/// A generic tree structure for instructions with child instructions.
22#[derive(Debug, Clone, PartialEq, Serialize)]
23pub struct InstructionTree<T>
24where
25    T: Debug + Clone,
26{
27    instruction: Box<T>,
28    #[serde(skip_serializing_if = "Vec::is_empty")]
29    children: Vec<InstructionTree<T>>,
30}
31impl Default for InstructionTree<Instruction> {
32    fn default() -> Self {
33        InstructionTree::new(Instruction::Regular(
34            RegularInstruction::UnboundedStatements,
35        ))
36    }
37}
38
39impl<T> From<T> for InstructionTree<T>
40where
41    T: Debug + Clone,
42{
43    fn from(instruction: T) -> Self {
44        InstructionTree::new(instruction)
45    }
46}
47
48impl From<RegularInstruction> for InstructionTree<Instruction> {
49    fn from(instruction: RegularInstruction) -> Self {
50        InstructionTree::new(Instruction::Regular(instruction))
51    }
52}
53
54impl From<TypeInstruction> for InstructionTree<Instruction> {
55    fn from(instruction: TypeInstruction) -> Self {
56        InstructionTree::new(Instruction::Type(instruction))
57    }
58}
59
60impl From<RegularInstruction> for InstructionTree<InstructionWithSpan> {
61    fn from(instruction: RegularInstruction) -> Self {
62        InstructionTree::new(InstructionWithSpan::from(Instruction::Regular(
63            instruction,
64        )))
65    }
66}
67
68impl From<TypeInstruction> for InstructionTree<InstructionWithSpan> {
69    fn from(instruction: TypeInstruction) -> Self {
70        InstructionTree::new(InstructionWithSpan::from(Instruction::Type(
71            instruction,
72        )))
73    }
74}
75
76impl From<Instruction> for InstructionTree<InstructionWithSpan> {
77    fn from(instruction: Instruction) -> Self {
78        InstructionTree::new(InstructionWithSpan::from(instruction))
79    }
80}
81
82impl From<Vec<InstructionTree<Instruction>>> for InstructionTree<Instruction> {
83    fn from(mut instruction_trees: Vec<InstructionTree<Instruction>>) -> Self {
84        if instruction_trees.len() == 1 {
85            instruction_trees.remove(0)
86        } else {
87            fn visit_next_child(
88                parent: &mut InstructionTree<Instruction>,
89                iterator: &mut IntoIter<InstructionTree<Instruction>>,
90            ) -> bool {
91                let mut current = match iterator.next() {
92                    Some(next) => next,
93                    None => return false,
94                };
95
96                // if instruction with next expected instructions, skip the next n instructions
97                if current.children().is_empty()
98                    && let Some(child_count) = current
99                        .instruction()
100                        .get_next_expected_instructions()
101                        .total_count()
102                    && let CountOrUnbounded::Count(child_count) = child_count
103                {
104                    for _ in 0..child_count {
105                        if !visit_next_child(&mut current, iterator) {
106                            panic!(
107                                "Expected {} children for instruction {:?}, but got fewer",
108                                child_count,
109                                current.instruction()
110                            );
111                        }
112                    }
113                }
114
115                parent.children.push(current);
116
117                true
118            }
119
120            let mut iterator = instruction_trees.into_iter();
121
122            let mut root: InstructionTree<Instruction> =
123                iterator.next().unwrap();
124            if !root.children().is_empty() {
125                panic!("Multiple root nodes found in instruction tree.");
126            }
127
128            while visit_next_child(&mut root, &mut iterator) {}
129
130            root
131        }
132    }
133}
134
135impl InstructionTree<InstructionWithSpan> {
136    /// Flattens the tree into a list of instructions,
137    /// also recursively flattens instructions like [RegularInstruction::_RemoteExecutionDebugTree]
138    /// into [RegularInstruction::_RemoteExecutionDebugFlat]
139    pub fn flatten_instructions(self) -> Vec<InstructionWithSpan> {
140        let mut result = if let Instruction::Regular(instruction) =
141            &self.instruction.instruction
142            && let Some(flattened) = instruction.clone().flatten_instruction()
143        {
144            vec![InstructionWithSpan {
145                instruction: Instruction::Regular(flattened),
146                span: self.instruction.span,
147            }]
148        } else {
149            vec![*self.instruction]
150        };
151
152        for child in self.children {
153            result.extend(child.flatten_instructions());
154        }
155        result
156    }
157}
158
159impl InstructionTree<Instruction> {
160    /// Flattens the tree into a list of instructions,
161    pub fn flatten_instructions(self) -> Vec<Instruction> {
162        InstructionTree::<InstructionWithSpan>::from(self)
163            .flatten_instructions()
164            .into_iter()
165            .map(Instruction::from)
166            .collect()
167    }
168}
169
170impl<T> InstructionTree<T>
171where
172    T: Debug + Clone,
173{
174    /// Create a new tree with a root instruction
175    pub fn new(instruction: T) -> Self {
176        Self {
177            instruction: Box::new(instruction),
178            children: Vec::new(),
179        }
180    }
181
182    /// Create a new tree with a root instruction and children
183    pub fn new_with_children(
184        instruction: T,
185        children: Vec<InstructionTree<T>>,
186    ) -> Self {
187        Self {
188            instruction: Box::new(instruction),
189            children,
190        }
191    }
192
193    /// Flattens the tree into a list of instructions
194    pub fn flatten(&self) -> Vec<T> {
195        let mut result = vec![*self.instruction.clone()];
196        for child in &self.children {
197            result.extend(child.flatten());
198        }
199        result
200    }
201
202    /// Maps a tree to an instruction tree with a different generic type with a mapping function, preserving the structure
203    pub fn map<N: Debug + Clone>(
204        self,
205        f: impl Fn(T) -> N + Clone,
206    ) -> InstructionTree<N> {
207        InstructionTree {
208            instruction: Box::new(f(*self.instruction)),
209            children: self
210                .children
211                .into_iter()
212                .map(|child| child.map(f.clone()))
213                .collect(),
214        }
215    }
216
217    pub fn children(&self) -> &Vec<InstructionTree<T>> {
218        &self.children
219    }
220
221    pub fn instruction(&self) -> &T {
222        &self.instruction
223    }
224}
225
226/// An instruction tree containing an optional detailed instruction tree inside each node
227#[derive(Debug, Clone)]
228struct DetailedInstructionTree(
229    pub  InstructionTree<(
230        InstructionWithSpan,
231        Option<Box<DetailedInstructionTree>>,
232    )>,
233);
234
235#[derive(Default, Clone, Debug, PartialEq)]
236pub enum InnerInstructions<'a> {
237    #[default]
238    None,
239    Flat(&'a Vec<InstructionWithSpan>),
240    Tree(&'a InstructionTree<InstructionWithSpan>),
241}
242
243impl From<InstructionTree<InstructionWithSpan>>
244    for InstructionTree<Instruction>
245{
246    fn from(value: InstructionTree<InstructionWithSpan>) -> Self {
247        value.map(|i| i.instruction)
248    }
249}
250
251impl From<InstructionTree<Instruction>>
252    for InstructionTree<InstructionWithSpan>
253{
254    fn from(value: InstructionTree<Instruction>) -> Self {
255        value.map(InstructionWithSpan::from)
256    }
257}
258
259/// Converts a raw DXB body in to human-readable disassembled instructions string
260pub(super) fn disassemble_body_to_string(
261    body: &[u8],
262    options: DisassemblerOptions,
263) -> String {
264    let (instructions, err) = disassemble_body(
265        body,
266        options.nested_instructions_resolution_strategy(),
267    );
268    disassemble_instruction_tree_to_string(instructions, err, options)
269}
270
271/// Converts an instruction tree in to human-readable disassembled instructions string
272pub fn disassemble_instruction_tree_to_string(
273    instruction_tree: InstructionTree<InstructionWithSpan>,
274    error: Option<DXBParserError>,
275    options: DisassemblerOptions,
276) -> String {
277    let instructions = instruction_tree_to_detailed_tree(instruction_tree);
278
279    let mut output = String::new();
280
281    if options.tree {
282        disassemble_body_to_string_inner(
283            &mut output,
284            instructions,
285            0,
286            true,
287            true,
288            false,
289            options.colorized,
290            0,
291        );
292    } else {
293        write_flat_instructions(
294            &mut output,
295            instructions,
296            options.colorized,
297            0,
298        );
299    }
300
301    if let Some(err) = error {
302        if options.colorized {
303            write!(
304                &mut output,
305                "\x1b[38;2;245;39;60m\n[!] Parser Error: {}\x1b[0m",
306                err
307            )
308            .unwrap();
309        } else {
310            write!(&mut output, "[!] Parser Error: {}", err).unwrap();
311        }
312    }
313
314    output
315}
316
317/// Converts a raw DXB body into a list of disassembled Instruction values
318pub fn disassemble_body(
319    body: &[u8],
320    nested_instruction_resolution_strategy: NestedInstructionResolutionStrategy,
321) -> (InstructionTree<InstructionWithSpan>, Option<DXBParserError>) {
322    let mut iterator = iterate_instructions(
323        Rc::new(RefCell::new(body.to_vec())),
324        nested_instruction_resolution_strategy,
325    );
326    get_instruction_tree(&mut iterator)
327}
328
329/// Converts a list of Instruction values into an instruction tree
330pub fn get_instruction_tree_from_list(
331    instructions: Vec<InstructionWithSpan>,
332) -> (InstructionTree<InstructionWithSpan>, Option<DXBParserError>) {
333    let mut iterator = instructions.into_iter().map(Ok);
334    get_instruction_tree(&mut iterator)
335}
336
337/// Converts an instruction iterator into a list of disassembled Instruction values
338pub fn get_instruction_tree(
339    instructions: impl Iterator<Item = Result<InstructionWithSpan, DXBParserError>>,
340) -> (InstructionTree<InstructionWithSpan>, Option<DXBParserError>) {
341    let mut tree = InstructionTree::new(
342        Instruction::Regular(RegularInstruction::UnboundedStatements).into(),
343    ); // initial tree root, gets overridden
344    let err = disassemble_body_inner(
345        &mut instructions.into_iter(),
346        &mut tree,
347        CountOrUnbounded::UnboundedStart,
348        true,
349    );
350    (tree, err)
351}
352
353/// Writes a detailed instruction tree to an output string recursively with optional colorization and indentation
354fn write_flat_instructions(
355    output: &mut String,
356    instructions: DetailedInstructionTree,
357    colorized: bool,
358    level: u32,
359) {
360    for (instruction, inner_instructions) in instructions.0.flatten() {
361        write!(output, "{}", " ".repeat(level as usize * 2),).unwrap();
362        write_instruction(output, &instruction, level, colorized);
363        if let Some(inner_instructions) = inner_instructions {
364            write_flat_instructions(
365                output,
366                *inner_instructions,
367                colorized,
368                level + 1,
369            );
370        }
371    }
372}
373
374/// Writes a single instruction to an output string with optional colorization and indentation
375fn write_instruction(
376    output: &mut String,
377    instruction: &Instruction,
378    level: u32,
379    colorized: bool,
380) {
381    if colorized {
382        let color = color_for_level(level);
383        output.write_fg(color);
384    }
385
386    write!(
387        output,
388        "{}",
389        match instruction {
390            Instruction::Regular(instr) => instr.instruction_code_string(),
391            Instruction::Type(instr) => format!("TYPE.{}", instr.as_ref()),
392        }
393    )
394    .unwrap();
395
396    if colorized {
397        output.write_reset();
398    }
399
400    if let Some(metadata_string) = instruction.metadata_string() {
401        write!(output, " {}", metadata_string).unwrap();
402    }
403
404    writeln!(output).unwrap();
405}
406
407/// Returns an instruction text color for a given level
408fn color_for_level(level: u32) -> AnsiColor {
409    match level % 10 {
410        0 => AnsiColor::Rgb(0, 153, 204), // deep sky blue
411        1 => AnsiColor::Rgb(0, 204, 153), // teal
412        2 => AnsiColor::Rgb(51, 204, 102), // green
413        3 => AnsiColor::Rgb(153, 255, 51), // lime green
414        4 => AnsiColor::Rgb(255, 221, 51), // golden yellow
415        5 => AnsiColor::Rgb(204, 204, 255), // light periwinkle
416        6 => AnsiColor::Rgb(153, 153, 255), // soft purple
417        7 => AnsiColor::Rgb(153, 102, 204), // medium purple
418        8 => AnsiColor::Rgb(255, 153, 204), // pink
419        9 => AnsiColor::Rgb(255, 204, 229), // soft pink / rose
420        _ => AnsiColor::Rgb(200, 200, 200), // neutral fallback
421    }
422}
423
424fn disassemble_body_to_string_inner(
425    output: &mut String,
426    instructions: DetailedInstructionTree,
427    indent_width: usize,
428    is_root_child: bool,
429    is_last_child: bool,
430    is_inner: bool,
431    colorized: bool,
432    level: u32,
433) {
434    let indent = " ".repeat(indent_width * 3);
435    let children_len = instructions.0.children.len();
436
437    let (main, inner) = *instructions.0.instruction;
438
439    write!(
440        output,
441        "{}{}",
442        indent,
443        if is_root_child {
444            ""
445        } else if is_inner {
446            "↳  "
447        } else if is_last_child || children_len > 0 {
448            "└─ "
449        } else {
450            "├─ "
451        },
452    )
453    .unwrap();
454
455    write_instruction(output, &main, level, colorized);
456
457    if let Some(inner) = inner {
458        disassemble_body_to_string_inner(
459            output,
460            *inner,
461            if is_root_child { 0 } else { indent_width + 1 },
462            false,
463            false,
464            true,
465            colorized,
466            level + 1,
467        );
468    }
469
470    for (i, child) in instructions.0.children.into_iter().enumerate() {
471        disassemble_body_to_string_inner(
472            output,
473            DetailedInstructionTree(child),
474            if is_root_child { 0 } else { indent_width + 1 },
475            false,
476            i == children_len - 1,
477            false,
478            colorized,
479            level,
480        );
481    }
482}
483
484fn instruction_tree_to_detailed_tree(
485    instructions: InstructionTree<InstructionWithSpan>,
486) -> DetailedInstructionTree {
487    DetailedInstructionTree(instructions.map(|i| {
488        let inner = get_inner_instructions_as_detailed_tree(&i).map(Box::new);
489        (i, inner)
490    }))
491}
492
493fn get_inner_instructions_as_detailed_tree(
494    instruction: &InstructionWithSpan,
495) -> Option<DetailedInstructionTree> {
496    match &instruction.instruction {
497        Instruction::Regular(instruction) => match instruction
498            .inner_instructions_from_debug_instruction()
499        {
500            InnerInstructions::Tree(tree) => {
501                Some(instruction_tree_to_detailed_tree(tree.clone()))
502            }
503            InnerInstructions::Flat(flat) => {
504                let (tree, err) = get_instruction_tree_from_list(flat.clone());
505                if let Some(err) = err {
506                    panic!("{}", err);
507                }
508                Some(instruction_tree_to_detailed_tree(tree))
509            }
510            InnerInstructions::None => None,
511        },
512        _ => None,
513    }
514}
515fn disassemble_body_inner(
516    iterator: &mut impl Iterator<Item = Result<InstructionWithSpan, DXBParserError>>,
517    parent: &mut InstructionTree<InstructionWithSpan>,
518    count_or_unbounded: CountOrUnbounded,
519    is_root: bool,
520) -> Option<DXBParserError> {
521    loop {
522        let next = iterator.next();
523        match next {
524            Some(instruction) => {
525                match instruction {
526                    Err(e) => {
527                        return Some(e);
528                    }
529                    Ok(instruction) => {
530                        // get next expected children
531                        let next_expected_count = instruction
532                            .get_next_expected_instructions()
533                            .total_count();
534                        let mut tree = InstructionTree::new(instruction);
535
536                        let err = match next_expected_count {
537                            Some(next_expected_count) => {
538                                match next_expected_count {
539                                    CountOrUnbounded::UnboundedEnd => {
540                                        parent.children.push(tree);
541                                        return None;
542                                    }
543                                    _ => disassemble_body_inner(
544                                        iterator,
545                                        &mut tree,
546                                        next_expected_count,
547                                        false,
548                                    ),
549                                }
550                            }
551                            None => None,
552                        };
553
554                        // if root node, replace parent with first instruction
555                        if is_root {
556                            *parent = tree;
557                        } else {
558                            parent.children.push(tree);
559                        }
560
561                        if let Some(err) = err {
562                            return Some(err);
563                        }
564
565                        // all expected children collected
566                        if let CountOrUnbounded::Count(expected_count) =
567                            count_or_unbounded
568                            && parent.children.len() as u32 >= expected_count
569                        {
570                            break;
571                        }
572                    }
573                }
574            }
575            None => break,
576        }
577    }
578
579    None
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585    use crate::{
586        disassembler::assertions::instructions_with_span,
587        dxb_parser::next_instructions_stack::{
588            NextInstructionsStack, NextScopeInstruction,
589        },
590        global::protocol_structures::serializable::Serializable,
591        instruction::{
592            instruction_codes::InstructionCode,
593            instruction_data::{
594                InstructionBlockData, InstructionBlockDataDebugFlat,
595                InstructionBlockDataDebugTree, StatementsData, UInt8Data,
596                UnboundedStatementsData,
597            },
598            regular_instruction::RegularInstruction,
599        },
600    };
601    use test_case::test_case;
602
603    #[test_case(
604        &[],
605        InstructionTree::new(Instruction::Regular(RegularInstruction::UnboundedStatements)),
606        Some(DXBParserError::ExpectingMoreInstructions(NextInstructionsStack(vec![NextScopeInstruction::Regular(1)])))
607         ; "empty dxb")]
608    #[test_case(
609        &[
610            Instruction::Regular(RegularInstruction::True),
611            Instruction::Regular(RegularInstruction::False),
612        ],
613        InstructionTree::new(Instruction::Regular(RegularInstruction::True)),
614        Some(DXBParserError::UnexpectedBytesAfterEndOfInstructions)
615         ; "multiple root nodes")]
616    #[test_case(
617        &[
618            Instruction::Regular(RegularInstruction::Statements(StatementsData {statements_count: 2, terminated: true})),
619            Instruction::Regular(RegularInstruction::True),
620            Instruction::Regular(RegularInstruction::False),
621        ],
622        InstructionTree {
623            instruction: Box::new(Instruction::Regular(RegularInstruction::Statements(StatementsData {statements_count: 2, terminated: true}))),
624            children: vec![
625                InstructionTree::new(Instruction::Regular(RegularInstruction::True)),
626                InstructionTree::new(Instruction::Regular(RegularInstruction::False)),
627            ]
628        },
629        None
630         ; "simple statements"
631    )]
632    #[test_case(
633        &[
634            Instruction::Regular(RegularInstruction::UnboundedStatements),
635            Instruction::Regular(RegularInstruction::True),
636            Instruction::Regular(RegularInstruction::False),
637            Instruction::Regular(RegularInstruction::UnboundedStatementsEnd(UnboundedStatementsData {terminated: false})),
638        ],
639        InstructionTree {
640            instruction: Box::new(Instruction::Regular(RegularInstruction::UnboundedStatements)),
641            children: vec![
642                InstructionTree::new(Instruction::Regular(RegularInstruction::True)),
643                InstructionTree::new(Instruction::Regular(RegularInstruction::False)),
644                InstructionTree::new(Instruction::Regular(RegularInstruction::UnboundedStatementsEnd(UnboundedStatementsData {terminated: false})))
645            ]
646        },
647        None
648         ; "unbounded statements"
649    )]
650    #[test_case(
651        &[
652            Instruction::Regular(RegularInstruction::Statements(StatementsData {statements_count: 2, terminated: true})),
653            Instruction::Regular(RegularInstruction::UnboundedStatements),
654            Instruction::Regular(RegularInstruction::True),
655            Instruction::Regular(RegularInstruction::False),
656            Instruction::Regular(RegularInstruction::UnboundedStatementsEnd(UnboundedStatementsData {terminated: false})),
657            Instruction::Regular(RegularInstruction::Null),
658        ],
659        InstructionTree {
660            instruction: Box::new(Instruction::Regular(RegularInstruction::Statements(StatementsData {statements_count: 2, terminated: true}))),
661            children: vec![
662                InstructionTree {
663                    instruction: Box::new(Instruction::Regular(RegularInstruction::UnboundedStatements)),
664                    children: vec![
665                        InstructionTree::new(Instruction::Regular(RegularInstruction::True)),
666                        InstructionTree::new(Instruction::Regular(RegularInstruction::False)),
667                        InstructionTree::new(Instruction::Regular(RegularInstruction::UnboundedStatementsEnd(UnboundedStatementsData {terminated: false})))
668                    ]
669                },
670                InstructionTree::new(Instruction::Regular(RegularInstruction::Null)),
671            ]
672        },
673        None
674        ; "normal and unbounded statements"
675    )]
676    #[test_case(
677        &[
678            Instruction::Regular(RegularInstruction::True),
679        ],
680        InstructionTree::new(Instruction::Regular(RegularInstruction::True)),
681        None
682        ; "single instruction"
683    )]
684    #[test_case(
685        &[
686            Instruction::Regular(RegularInstruction::Statements(StatementsData {statements_count: 2, terminated: true})),
687            Instruction::Regular(RegularInstruction::True),
688        ],
689        InstructionTree {
690            instruction: Box::new(Instruction::Regular(RegularInstruction::Statements(StatementsData {statements_count: 2, terminated: true}))),
691            children: vec![
692                InstructionTree::new(Instruction::Regular(RegularInstruction::True)),
693            ]
694        },
695        Some(DXBParserError::ExpectingMoreInstructions(NextInstructionsStack(vec![NextScopeInstruction::Regular(1)])))
696        ; "statements with missing instructions"
697    )]
698    #[test_case(
699        &[
700            Instruction::Regular(RegularInstruction::RemoteExecution(InstructionBlockData {
701                length: 2,
702                injected_value_count: 0,
703                injected_values: vec![],
704                body: vec![
705                    InstructionCode::UINT_8 as u8,
706                    42,
707                ]
708            })),
709            Instruction::Regular(RegularInstruction::True)
710        ],
711        InstructionTree {
712            instruction: Box::new(Instruction::Regular(RegularInstruction::RemoteExecution(InstructionBlockData {
713                length: 2,
714                injected_value_count: 0,
715                injected_values: vec![],
716                body: vec![
717                    InstructionCode::UINT_8 as u8,
718                    42,
719                ]
720            }))),
721            children: vec![
722                InstructionTree::new(Instruction::Regular(RegularInstruction::True)),
723            ]
724        },
725        None
726        ; "remote execution"
727    )]
728
729    fn disassemble_statements(
730        instructions: &[Instruction],
731        expected_tree: InstructionTree<Instruction>,
732        expected_err: Option<DXBParserError>,
733    ) {
734        let dxb = instructions.to_bytes();
735        let (tree, err) = disassemble_body(
736            &dxb,
737            NestedInstructionResolutionStrategy::default(),
738        );
739
740        assert_eq!(err, expected_err);
741        assert_eq!(tree, expected_tree.into())
742    }
743
744    #[test]
745    fn disassemble_nested_flat() {
746        let instructions = vec![
747            Instruction::Regular(RegularInstruction::RemoteExecution(
748                InstructionBlockData {
749                    length: 5,
750                    injected_value_count: 0,
751                    injected_values: vec![],
752                    body: vec![
753                        InstructionCode::ADD as u8,
754                        InstructionCode::UINT_8 as u8,
755                        42,
756                        InstructionCode::UINT_8 as u8,
757                        43,
758                    ],
759                },
760            )),
761            Instruction::Regular(RegularInstruction::True),
762        ];
763        let dxb = instructions.to_bytes();
764        let (tree, err) = disassemble_body(
765            &dxb,
766            NestedInstructionResolutionStrategy::ResolveNestedScopesFlat,
767        );
768
769        assert_eq!(err, None);
770        assert_eq!(
771            InstructionTree::<Instruction>::from(tree),
772            InstructionTree {
773                instruction: Box::new(Instruction::Regular(
774                    RegularInstruction::_RemoteExecutionDebugFlat(
775                        InstructionBlockDataDebugFlat {
776                            length: 5,
777                            injected_variable_count: 0,
778                            injected_values: vec![],
779                            body: instructions_with_span!(
780                                Instruction::Regular(RegularInstruction::Add),
781                                Instruction::Regular(
782                                    RegularInstruction::UInt8(UInt8Data(42))
783                                ),
784                                Instruction::Regular(
785                                    RegularInstruction::UInt8(UInt8Data(43))
786                                ),
787                            )
788                        }
789                    )
790                )),
791                children: vec![InstructionTree::new(Instruction::Regular(
792                    RegularInstruction::True
793                )),]
794            }
795        );
796    }
797
798    #[test]
799    fn disassemble_nested_tree() {
800        let instructions = vec![
801            Instruction::Regular(RegularInstruction::RemoteExecution(
802                InstructionBlockData {
803                    length: 5,
804                    injected_value_count: 0,
805                    injected_values: vec![],
806                    body: vec![
807                        InstructionCode::ADD as u8,
808                        InstructionCode::UINT_8 as u8,
809                        42,
810                        InstructionCode::UINT_8 as u8,
811                        43,
812                    ],
813                },
814            )),
815            Instruction::Regular(RegularInstruction::True),
816        ];
817        let dxb = instructions.to_bytes();
818        let (tree, err) = disassemble_body(
819            &dxb,
820            NestedInstructionResolutionStrategy::ResolveNestedScopesTree,
821        );
822
823        assert_eq!(err, None);
824        assert_eq!(
825            InstructionTree::<Instruction>::from(tree),
826            InstructionTree {
827                instruction: Box::new(Instruction::Regular(
828                    RegularInstruction::_RemoteExecutionDebugTree(
829                        InstructionBlockDataDebugTree {
830                            length: 5,
831                            injected_variable_count: 0,
832                            injected_values: vec![],
833                            body: InstructionTree {
834                                instruction: Box::new(Instruction::Regular(
835                                    RegularInstruction::Add
836                                )),
837                                children: vec![
838                                    InstructionTree::new(Instruction::Regular(
839                                        RegularInstruction::UInt8(UInt8Data(
840                                            42
841                                        ))
842                                    )),
843                                    InstructionTree::new(Instruction::Regular(
844                                        RegularInstruction::UInt8(UInt8Data(
845                                            43
846                                        ))
847                                    )),
848                                ]
849                            }
850                            .into()
851                        }
852                    )
853                )),
854                children: vec![InstructionTree::new(Instruction::Regular(
855                    RegularInstruction::True
856                )),]
857            }
858        );
859    }
860
861    #[ignore]
862    #[cfg(all(feature = "std", feature = "compiler"))]
863    #[test]
864    fn disassemble_string_test() {
865        use crate::{
866            compiler::{CompileOptions, compile_script},
867            runtime::Runtime,
868        };
869
870        let script = r#"
871            var x = 5;
872            var y = 42;
873            @example :: (
874                1;2;3;
875                @test :: (1 + 2);
876            )
877        "#;
878        let dxb =
879            compile_script(script, CompileOptions::default(), Runtime::stub())
880                .unwrap()
881                .0;
882        println!(
883            "{}",
884            disassemble_body_to_string(
885                &dxb,
886                DisassemblerOptions {
887                    tree: true,
888                    colorized: true,
889                    recursive: true,
890                }
891            )
892        );
893
894        println!(
895            "{}",
896            disassemble_body_to_string(
897                &dxb,
898                DisassemblerOptions {
899                    tree: false,
900                    colorized: true,
901                    recursive: true,
902                }
903            )
904        );
905
906        println!(
907            "{}",
908            disassemble_body_to_string(
909                &dxb,
910                DisassemblerOptions {
911                    tree: true,
912                    colorized: true,
913                    recursive: false,
914                }
915            )
916        );
917    }
918}