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