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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
use std::borrow::Cow;

use indexmap::IndexMap;
use planus_types::intermediate::{DeclarationIndex, DeclarationKind};

use crate::{
    children::{Byterange, Children},
    object_info::ObjectName,
    ByteIndex, InspectableFlatbuffer, Object, OffsetObject, OffsetObjectKind,
};

pub type ObjectIndex = usize;
pub type LineIndex = usize;

pub struct ObjectMapping<'a> {
    pub root_object: Object<'a>,
    pub root_objects: IndexMap<Object<'a>, (ByteIndex, ByteIndex)>,
    pub root_intervals: rust_lapper::Lapper<ByteIndex, ObjectIndex>,
}

impl<'a> InspectableFlatbuffer<'a> {
    pub fn calculate_object_mapping(
        &self,
        root_table_index: DeclarationIndex,
    ) -> ObjectMapping<'a> {
        assert!(matches!(
            self.declarations.get_declaration(root_table_index).1.kind,
            DeclarationKind::Table(_)
        ));

        let root_offset_object = OffsetObject {
            offset: 0,
            kind: crate::OffsetObjectKind::Table(root_table_index),
        };

        let mut builder = ObjectMappingBuilder::default();

        builder.process_root_object(Object::Offset(root_offset_object), self);

        ObjectMapping {
            root_object: root_offset_object.follow_offset(self).unwrap(),
            root_objects: builder.root_objects,
            root_intervals: rust_lapper::Lapper::new(builder.root_intervals),
        }
    }
}

#[derive(Clone, Debug)]
pub struct Interpretation {
    pub root_object_index: ObjectIndex,
    pub lines: Vec<LineIndex>,
}

#[derive(Debug)]
pub struct LineTree<'a> {
    field_name: Option<Cow<'a, str>>,
    object: Object<'a>,
    start_line_index: LineIndex,
    end_line_index: Option<LineIndex>,
    range: (ByteIndex, ByteIndex),
    children: Vec<LineTree<'a>>,
}

#[derive(Clone, Debug)]
pub struct Line<'a> {
    pub indentation: usize,
    pub start_line_index: LineIndex,
    pub end_line_index: LineIndex,
    pub parent_line_index: LineIndex,
    pub name: String,
    pub line: String,
    pub object_width: usize,
    pub start: ByteIndex,
    pub end: ByteIndex,
    pub object: Object<'a>,
}

impl<'a> LineTree<'a> {
    fn get_interpretations(
        &self,
        root_object_index: ObjectIndex,
        byte_index: ByteIndex,
        lines: &mut Vec<LineIndex>,
        callback: &mut impl FnMut(Interpretation),
    ) -> bool {
        if !(self.range.0..self.range.1).contains(&byte_index) {
            return false;
        }

        lines.push(self.start_line_index);

        let mut found = false;
        for child in &self.children {
            found |= child.get_interpretations(root_object_index, byte_index, lines, callback);
        }
        if !found {
            callback(Interpretation {
                root_object_index,
                lines: lines.clone(),
            });
        }
        lines.pop();
        true
    }

    fn to_strings_helper(
        &self,
        depth: usize,
        parent_line_index: LineIndex,
        buffer: &InspectableFlatbuffer<'a>,
        out: &mut Vec<Line<'a>>,
    ) {
        debug_assert_eq!(out.len(), self.start_line_index);

        let mut line = String::new();
        let name = self.object.print_object(buffer);

        if let Object::Offset(OffsetObject {
            kind: OffsetObjectKind::VTable(_),
            ..
        }) = &self.object
        {
            line.push_str("#vtable");
        } else {
            if let Some(field_name) = &self.field_name {
                line.push_str(field_name);
                line.push_str(": ");
            }

            line.push_str(&name);

            if self.end_line_index.is_some() {
                line.push_str(" {");
            } else if self.object.have_braces() {
                line.push_str(" {}");
            }
        }

        out.push(Line {
            object_width: line.len(),
            line,
            name,
            indentation: 2 * depth,
            start_line_index: self.start_line_index,
            end_line_index: self.end_line_index.unwrap_or(self.start_line_index),
            parent_line_index,
            object: self.object,
            start: self.range.0,
            end: self.range.1,
        });

        for child in &self.children {
            let index = out.len();
            child.to_strings_helper(depth + 1, self.start_line_index, buffer, out);
            out[self.start_line_index].object_width = out[self.start_line_index]
                .object_width
                .max(out[index].object_width + 2);
        }

        if let Some(end_line) = self.end_line_index {
            debug_assert_eq!(out.len(), end_line);
            out.push(Line {
                object_width: out[self.start_line_index].object_width,
                name: String::new(),
                indentation: 2 * depth,
                start_line_index: self.start_line_index,
                end_line_index: self.end_line_index.unwrap_or(self.start_line_index),
                line: "}".to_string(),
                parent_line_index,
                object: self.object,
                start: self.range.0,
                end: self.range.1,
            });
        }
    }

    pub fn flatten(&self, buffer: &InspectableFlatbuffer<'a>) -> Vec<Line<'a>> {
        let mut out = Vec::new();
        self.to_strings_helper(0, 0, buffer, &mut out);
        out
    }

    pub fn last_line(&self) -> usize {
        if let Some(end_line) = self.end_line_index {
            end_line
        } else if let Some(last) = self.children.last() {
            last.last_line()
        } else {
            self.start_line_index
        }
    }
}

impl<'a> ObjectMapping<'a> {
    pub fn get_interpretations(
        &self,
        byte_index: ByteIndex,
        buffer: &InspectableFlatbuffer<'a>,
    ) -> Vec<Interpretation> {
        let mut interpretations = Vec::new();
        self.get_interpretations_cb(byte_index, buffer, |interpretation| {
            interpretations.push(interpretation);
        });
        interpretations
    }

    pub fn get_interpretations_cb(
        &self,
        byte_index: ByteIndex,
        buffer: &InspectableFlatbuffer<'a>,
        mut callback: impl FnMut(Interpretation),
    ) {
        for root_object_index in self.root_intervals.find(byte_index, byte_index + 1) {
            self.line_tree(root_object_index.val, buffer)
                .get_interpretations(
                    root_object_index.val,
                    byte_index,
                    &mut Vec::new(),
                    &mut callback,
                );
        }
    }

    pub fn line_tree(
        &self,
        root_object_index: ObjectIndex,
        buffer: &InspectableFlatbuffer<'a>,
    ) -> LineTree<'a> {
        fn handler<'a>(
            field_name: Option<Cow<'a, str>>,
            current: Object<'a>,
            buffer: &InspectableFlatbuffer<'a>,
            next_line: &mut LineIndex,
        ) -> LineTree<'a> {
            let current_line = *next_line;
            *next_line += 1;
            let mut children = Vec::new();
            let mut range = current.byterange(buffer);
            current.children(buffer, |field_name, child| {
                let child = handler(field_name, child, buffer, next_line);
                range.0 = range.0.min(child.range.0);
                range.1 = range.1.max(child.range.1);
                children.push(child);
            });

            let mut end_line = None;

            if !children.is_empty() {
                end_line = Some(*next_line);
                *next_line += 1;
            }

            LineTree {
                field_name,
                object: current,
                start_line_index: current_line,
                end_line_index: end_line,
                range,
                children,
            }
        }
        handler(
            None,
            *self.root_objects.get_index(root_object_index).unwrap().0,
            buffer,
            &mut 0,
        )
    }
}

#[derive(Default)]
struct ObjectMappingBuilder<'a> {
    root_objects: IndexMap<Object<'a>, (ByteIndex, ByteIndex)>,
    root_intervals: Vec<rust_lapper::Interval<ByteIndex, ObjectIndex>>,
}

impl<'a> ObjectMappingBuilder<'a> {
    fn process_root_object(&mut self, current: Object<'a>, buffer: &InspectableFlatbuffer<'a>) {
        if self.root_objects.contains_key(&current) {
            return;
        }

        if let Object::Offset(offset_object) = current {
            if let Ok(inner) = offset_object.follow_offset(buffer) {
                self.process_root_object(inner, buffer);
            }
        }

        let mut range = current.byterange(buffer);

        current.children(buffer, |child_name, child| {
            std::mem::drop(child_name);
            self.process_child_object(child, &mut range, buffer);
        });
        let (index, old) = self.root_objects.insert_full(current, range);
        assert!(old.is_none());
        self.root_intervals.push(rust_lapper::Interval {
            start: range.0,
            stop: range.1,
            val: index,
        });
    }

    fn process_child_object(
        &mut self,
        current: Object<'a>,
        range: &mut (u32, u32),
        buffer: &InspectableFlatbuffer<'a>,
    ) {
        let crange = current.byterange(buffer);
        range.0 = range.0.min(crange.0);
        range.1 = range.1.max(crange.1);

        if let Object::Offset(offset_object) = current {
            if let Ok(inner) = offset_object.follow_offset(buffer) {
                self.process_root_object(inner, buffer);
            }
        }

        current.children(buffer, |child_name, child| {
            std::mem::drop(child_name);
            self.process_child_object(child, range, buffer);
        });
    }
}