1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

#![forbid(unsafe_code)]
use crate::interfaces::LeftScreen;
use bytecode_source_map::{mapping::SourceMapping, source_map::SourceMap};
use disassembler::disassembler::{Disassembler, DisassemblerOptions};
use move_binary_format::{
    binary_views::BinaryIndexedView,
    file_format::{CodeOffset, CompiledModule, FunctionDefinitionIndex},
};
use regex::Regex;
use std::collections::HashMap;

#[derive(Clone, Debug)]
pub struct BytecodeInfo {
    pub function_name: String,
    pub function_index: FunctionDefinitionIndex,
    pub code_offset: CodeOffset,
}

#[derive(Clone, Debug)]
pub struct BytecodeViewer<'a> {
    pub lines: Vec<String>,
    pub view: BinaryIndexedView<'a>,
    pub line_map: HashMap<usize, BytecodeInfo>,
}

impl<'a> BytecodeViewer<'a> {
    pub fn new(source_map: SourceMap, module: &'a CompiledModule) -> Self {
        let view = BinaryIndexedView::Module(module);
        let source_mapping = SourceMapping::new(source_map, view);
        let options = DisassemblerOptions {
            print_code: true,
            print_basic_blocks: true,
            ..Default::default()
        };
        let disassembled_string = Disassembler::new(source_mapping, options)
            .disassemble()
            .unwrap();

        let mut base_viewer = Self {
            lines: disassembled_string.lines().map(|x| x.to_string()).collect(),
            line_map: HashMap::new(),
            view,
        };
        base_viewer.build_mapping();
        base_viewer
    }

    fn build_mapping(&mut self) {
        let regex = Regex::new(r"^(\d+):.*").unwrap();
        let fun_regex = Regex::new(r"^public\s+([a-zA-Z_]+)\(").unwrap();
        let mut current_fun = None;
        let mut current_fdef_idx = None;
        let mut line_map = HashMap::new();

        let function_def_for_name: HashMap<String, u16> = self
            .view
            .function_defs()
            .into_iter()
            .flatten()
            .enumerate()
            .map(|(index, fdef)| {
                (
                    self.view
                        .identifier_at(self.view.function_handle_at(fdef.function).name)
                        .to_string(),
                    index as u16,
                )
            })
            .collect();

        for (i, line) in self.lines.iter().enumerate() {
            let line = line.trim();
            if let Some(cap) = fun_regex.captures(line) {
                let fn_name = cap.get(1).unwrap().as_str();
                let function_definition_index = function_def_for_name[fn_name];
                current_fun = Some(fn_name);
                current_fdef_idx = Some(FunctionDefinitionIndex(function_definition_index));
            }

            if let Some(cap) = regex.captures(line) {
                current_fun.map(|fname| {
                    let d = cap.get(1).unwrap().as_str().parse::<u16>().unwrap();
                    line_map.insert(
                        i,
                        BytecodeInfo {
                            function_name: fname.to_string(),
                            function_index: current_fdef_idx.unwrap(),
                            code_offset: d,
                        },
                    )
                });
            }
        }
        self.line_map = line_map;
    }
}

impl LeftScreen for BytecodeViewer<'_> {
    type SourceIndex = BytecodeInfo;

    fn get_source_index_for_line(&self, line: usize, _column: usize) -> Option<&Self::SourceIndex> {
        self.line_map.get(&line)
    }

    fn backing_string(&self) -> String {
        self.lines.join("\n").replace('\t', "    ")
    }
}