Unnamed repository; edit this file 'description' to name the repository.
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
use std::fmt;

use hir::{DisplayTarget, Field, HirDisplay, Layout, Semantics, Type};
use ide_db::{
    RootDatabase,
    defs::Definition,
    helpers::{get_definition, pick_best_token},
};
use syntax::{AstNode, SyntaxKind};

use crate::FilePosition;

pub struct MemoryLayoutNode {
    pub item_name: String,
    pub typename: String,
    pub size: u64,
    pub alignment: u64,
    pub offset: u64,
    pub parent_idx: i64,
    pub children_start: i64,
    pub children_len: u64,
}

pub struct RecursiveMemoryLayout {
    pub nodes: Vec<MemoryLayoutNode>,
}

// NOTE: this is currently strictly for testing and so isn't super useful as a visualization tool, however it could be adapted to become one?
impl fmt::Display for RecursiveMemoryLayout {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fn process(
            fmt: &mut fmt::Formatter<'_>,
            nodes: &Vec<MemoryLayoutNode>,
            idx: usize,
            depth: usize,
        ) -> fmt::Result {
            let mut out = "\t".repeat(depth);
            let node = &nodes[idx];
            out += &format!(
                "{}: {} (size: {}, align: {}, field offset: {})\n",
                node.item_name, node.typename, node.size, node.alignment, node.offset
            );
            write!(fmt, "{out}")?;
            if node.children_start != -1 {
                for j in nodes[idx].children_start
                    ..(nodes[idx].children_start + nodes[idx].children_len as i64)
                {
                    process(fmt, nodes, j as usize, depth + 1)?;
                }
            }
            Ok(())
        }

        process(fmt, &self.nodes, 0, 0)
    }
}

#[derive(Copy, Clone)]
enum FieldOrTupleIdx {
    Field(Field),
    TupleIdx(usize),
}

impl FieldOrTupleIdx {
    fn name(&self, db: &RootDatabase) -> String {
        match *self {
            FieldOrTupleIdx::Field(f) => f.name(db).as_str().to_owned(),
            FieldOrTupleIdx::TupleIdx(i) => format!(".{i}"),
        }
    }
}

// Feature: View Memory Layout
//
// Displays the recursive memory layout of a datatype.
//
// | Editor  | Action Name |
// |---------|-------------|
// | VS Code | **rust-analyzer: View Memory Layout** |
pub(crate) fn view_memory_layout(
    db: &RootDatabase,
    position: FilePosition,
) -> Option<RecursiveMemoryLayout> {
    let sema = Semantics::new(db);
    let file = sema.parse_guess_edition(position.file_id);
    let display_target = sema.first_crate(position.file_id)?.to_display_target(db);
    let token =
        pick_best_token(file.syntax().token_at_offset(position.offset), |kind| match kind {
            SyntaxKind::IDENT => 3,
            _ => 0,
        })?;

    let def = get_definition(&sema, token)?;

    let ty = match def {
        Definition::Adt(it) => it.ty(db),
        Definition::TypeAlias(it) => it.ty(db),
        Definition::BuiltinType(it) => it.ty(db),
        Definition::SelfType(it) => it.self_ty(db),
        Definition::Local(it) => it.ty(db),
        Definition::Field(it) => it.ty(db).to_type(db),
        Definition::Const(it) => it.ty(db),
        Definition::Static(it) => it.ty(db),
        _ => return None,
    };

    fn read_layout(
        nodes: &mut Vec<MemoryLayoutNode>,
        db: &RootDatabase,
        ty: &Type<'_>,
        layout: &Layout,
        parent_idx: usize,
        display_target: DisplayTarget,
    ) {
        let mut fields = ty
            .fields(db)
            .into_iter()
            .map(|(f, ty)| (FieldOrTupleIdx::Field(f), ty))
            .chain(
                ty.tuple_fields(db)
                    .into_iter()
                    .enumerate()
                    .map(|(i, ty)| (FieldOrTupleIdx::TupleIdx(i), ty)),
            )
            .collect::<Vec<_>>();

        if fields.is_empty() {
            return;
        }

        fields.sort_by_key(|&(f, _)| match f {
            FieldOrTupleIdx::Field(f) => layout.field_offset(f).unwrap_or(0),
            FieldOrTupleIdx::TupleIdx(f) => layout.tuple_field_offset(f).unwrap_or(0),
        });

        let children_start = nodes.len();
        nodes[parent_idx].children_start = children_start as i64;
        nodes[parent_idx].children_len = fields.len() as u64;

        for (field, child_ty) in fields.iter() {
            if let Ok(child_layout) = child_ty.layout(db) {
                nodes.push(MemoryLayoutNode {
                    item_name: field.name(db),
                    typename: { child_ty.display(db, display_target).to_string() },
                    size: child_layout.size(),
                    alignment: child_layout.align(),
                    offset: match *field {
                        FieldOrTupleIdx::Field(f) => layout.field_offset(f).unwrap_or(0),
                        FieldOrTupleIdx::TupleIdx(f) => layout.tuple_field_offset(f).unwrap_or(0),
                    },
                    parent_idx: parent_idx as i64,
                    children_start: -1,
                    children_len: 0,
                });
            } else {
                nodes.push(MemoryLayoutNode {
                    item_name: field.name(db)
                        + format!("(no layout data: {:?})", child_ty.layout(db).unwrap_err())
                            .as_ref(),
                    typename: child_ty.display(db, display_target).to_string(),
                    size: 0,
                    offset: 0,
                    alignment: 0,
                    parent_idx: parent_idx as i64,
                    children_start: -1,
                    children_len: 0,
                });
            }
        }

        for (i, (_, child_ty)) in fields.iter().enumerate() {
            if let Ok(child_layout) = child_ty.layout(db) {
                read_layout(nodes, db, child_ty, &child_layout, children_start + i, display_target);
            }
        }
    }

    ty.layout(db)
        .map(|layout| {
            let item_name = match def {
                // def is a datatype
                Definition::Adt(_)
                | Definition::TypeAlias(_)
                | Definition::BuiltinType(_)
                | Definition::SelfType(_) => "[ROOT]".to_owned(),

                // def is an item
                def => def.name(db).map(|n| n.as_str().to_owned()).unwrap_or("[ROOT]".to_owned()),
            };

            let typename = ty.display(db, display_target).to_string();

            let mut nodes = vec![MemoryLayoutNode {
                item_name,
                typename,
                size: layout.size(),
                offset: 0,
                alignment: layout.align(),
                parent_idx: -1,
                children_start: -1,
                children_len: 0,
            }];
            read_layout(&mut nodes, db, &ty, &layout, 0, display_target);

            RecursiveMemoryLayout { nodes }
        })
        .ok()
}

#[cfg(test)]
mod tests {
    use super::*;

    use crate::fixture;
    use expect_test::expect;

    fn make_memory_layout(
        #[rust_analyzer::rust_fixture] ra_fixture: &str,
    ) -> Option<RecursiveMemoryLayout> {
        let (analysis, position, _) = fixture::annotations(ra_fixture);

        hir::attach_db(&analysis.db, || view_memory_layout(&analysis.db, position))
    }

    #[test]
    fn view_memory_layout_none() {
        assert!(make_memory_layout(r#"$0"#).is_none());
        assert!(make_memory_layout(r#"stru$0ct Blah {}"#).is_none());
    }

    #[test]
    fn view_memory_layout_primitive() {
        expect![[r#"
            foo: i32 (size: 4, align: 4, field offset: 0)
        "#]]
        .assert_eq(
            &make_memory_layout(
                r#"
fn main() {
    let foo$0 = 109; // default i32
}
"#,
            )
            .unwrap()
            .to_string(),
        );
    }

    #[test]
    fn view_memory_layout_constant() {
        expect![[r#"
            BLAH: bool (size: 1, align: 1, field offset: 0)
        "#]]
        .assert_eq(
            &make_memory_layout(
                r#"
const BLAH$0: bool = 0;
"#,
            )
            .unwrap()
            .to_string(),
        );
    }

    #[test]
    fn view_memory_layout_static() {
        expect![[r#"
            BLAH: bool (size: 1, align: 1, field offset: 0)
        "#]]
        .assert_eq(
            &make_memory_layout(
                r#"
static BLAH$0: bool = 0;
"#,
            )
            .unwrap()
            .to_string(),
        );
    }

    #[test]
    fn view_memory_layout_tuple() {
        expect![[r#"
            x: (f64, u8, i64) (size: 24, align: 8, field offset: 0)
            	.0: f64 (size: 8, align: 8, field offset: 0)
            	.1: u8 (size: 1, align: 1, field offset: 8)
            	.2: i64 (size: 8, align: 8, field offset: 16)
        "#]]
        .assert_eq(
            &make_memory_layout(
                r#"
fn main() {
    let x$0 = (101.0, 111u8, 119i64);
}
"#,
            )
            .unwrap()
            .to_string(),
        );
    }

    #[test]
    fn view_memory_layout_c_struct() {
        expect![[r#"
            [ROOT]: Blah (size: 16, align: 4, field offset: 0)
            	a: u32 (size: 4, align: 4, field offset: 0)
            	b: (i32, u8) (size: 8, align: 4, field offset: 4)
            		.0: i32 (size: 4, align: 4, field offset: 0)
            		.1: u8 (size: 1, align: 1, field offset: 4)
            	c: i8 (size: 1, align: 1, field offset: 12)
        "#]]
        .assert_eq(
            &make_memory_layout(
                r#"
#[repr(C)]
struct Blah$0 {
    a: u32,
    b: (i32, u8),
    c: i8,
}
"#,
            )
            .unwrap()
            .to_string(),
        );
    }

    #[test]
    fn view_memory_layout_struct() {
        expect![[r#"
            [ROOT]: Blah (size: 16, align: 4, field offset: 0)
            	b: (i32, u8) (size: 8, align: 4, field offset: 0)
            		.0: i32 (size: 4, align: 4, field offset: 0)
            		.1: u8 (size: 1, align: 1, field offset: 4)
            	a: u32 (size: 4, align: 4, field offset: 8)
            	c: i8 (size: 1, align: 1, field offset: 12)
        "#]]
        .assert_eq(
            &make_memory_layout(
                r#"
struct Blah$0 {
    a: u32,
    b: (i32, u8),
    c: i8,
}
"#,
            )
            .unwrap()
            .to_string(),
        );
    }

    #[test]
    fn view_memory_layout_member() {
        expect![[r#"
            a: bool (size: 1, align: 1, field offset: 0)
        "#]]
        .assert_eq(
            &make_memory_layout(
                r#"
#[repr(C)]
struct Oof {
    a$0: bool,
}
"#,
            )
            .unwrap()
            .to_string(),
        );
    }

    #[test]
    fn view_memory_layout_alias() {
        let ml_a = make_memory_layout(
            r#"
struct X {
    a: u32,
    b: i8,
    c: (f32, f32),
}

type Foo$0 = X;
"#,
        )
        .unwrap();

        let ml_b = make_memory_layout(
            r#"
struct X$0 {
    a: u32,
    b: i8,
    c: (f32, f32),
}
"#,
        )
        .unwrap();

        assert_eq!(ml_a.to_string(), ml_b.to_string());
    }
}
.iter() .position(|&child| child == focus) .unwrap(); // replace focus on parent with split container.children[pos] = split; } // focus the new node self.focus = node; // recalculate all the sizes self.recalculate(); node } pub fn remove(&mut self, index: ViewId) { let mut stack = Vec::new(); if self.focus == index { // focus on something else self.focus_next(); } stack.push(index); while let Some(index) = stack.pop() { let parent_id = self.nodes[index].parent; if let Node { content: Content::Container(container), .. } = &mut self.nodes[parent_id] { if let Some(pos) = container.children.iter().position(|&child| child == index) { container.children.remove(pos); // TODO: if container now only has one child, remove it and place child in parent if container.children.is_empty() && parent_id != self.root { // if container now empty, remove it stack.push(parent_id); } } } self.nodes.remove(index); } self.recalculate() } pub fn views(&self) -> impl Iterator<Item = (&View, bool)> { let focus = self.focus; self.nodes.iter().filter_map(move |(key, node)| match node { Node { content: Content::View(view), .. } => Some((view.as_ref(), focus == key)), _ => None, }) } pub fn views_mut(&mut self) -> impl Iterator<Item = (&mut View, bool)> { let focus = self.focus; self.nodes .iter_mut() .filter_map(move |(key, node)| match node { Node { content: Content::View(view), .. } => Some((view.as_mut(), focus == key)), _ => None, }) } pub fn get(&self, index: ViewId) -> &View { match &self.nodes[index] { Node { content: Content::View(view), .. } => view, _ => unreachable!(), } } pub fn get_mut(&mut self, index: ViewId) -> &mut View { match &mut self.nodes[index] { Node { content: Content::View(view), .. } => view, _ => unreachable!(), } } pub fn is_empty(&self) -> bool { match &self.nodes[self.root] { Node { content: Content::Container(container), .. } => container.children.is_empty(), _ => unreachable!(), } } pub fn resize(&mut self, area: Rect) -> bool { if self.area != area { self.area = area; self.recalculate(); return true; } false } pub fn recalculate(&mut self) { if self.is_empty() { // There are no more views, so the tree should focus itself again. self.focus = self.root; return; } self.stack.push((self.root, self.area)); // take the area // fetch the node // a) node is view, give it whole area // b) node is container, calculate areas for each child and push them on the stack while let Some((key, area)) = self.stack.pop() { let node = &mut self.nodes[key]; match &mut node.content { Content::View(view) => { // debug!!("setting view area {:?}", area); view.area = area; } // TODO: call f() Content::Container(container) => { // debug!!("setting container area {:?}", area); container.area = area; match container.layout { Layout::Horizontal => { let len = container.children.len(); let height = area.height / len as u16; let mut child_y = area.y; for (i, child) in container.children.iter().enumerate() { let mut area = Rect::new( container.area.x, child_y, container.area.width, height, ); child_y += height; // last child takes the remaining width because we can get uneven // space from rounding if i == len - 1 { area.height = container.area.y + container.area.height - area.y; } self.stack.push((*child, area)); } } Layout::Vertical => { let len = container.children.len(); let width = area.width / len as u16; let inner_gap = 1u16; // let total_gap = inner_gap * (len as u16 - 1); let mut child_x = area.x; for (i, child) in container.children.iter().enumerate() { let mut area = Rect::new( child_x, container.area.y, width, container.area.height, ); child_x += width + inner_gap; // last child takes the remaining width because we can get uneven // space from rounding if i == len - 1 { area.width = container.area.x + container.area.width - area.x; } self.stack.push((*child, area)); } } } } } } } pub fn traverse(&self) -> Traverse { Traverse::new(self) } // Finds the split in the given direction if it exists pub fn find_split_in_direction(&self, id: ViewId, direction: Direction) -> Option<ViewId> { let parent = self.nodes[id].parent; // Base case, we found the root of the tree if parent == id { return None; } // Parent must always be a container let parent_container = match &self.nodes[parent].content { Content::Container(container) => container, Content::View(_) => unreachable!(), }; match (direction, parent_container.layout) { (Direction::Up, Layout::Vertical) | (Direction::Left, Layout::Horizontal) | (Direction::Right, Layout::Horizontal) | (Direction::Down, Layout::Vertical) => { // The desired direction of movement is not possible within // the parent container so the search must continue closer to // the root of the split tree. self.find_split_in_direction(parent, direction) } (Direction::Up, Layout::Horizontal) | (Direction::Down, Layout::Horizontal) | (Direction::Left, Layout::Vertical) | (Direction::Right, Layout::Vertical) => { // It's possible to move in the desired direction within // the parent container so an attempt is made to find the // correct child. match self.find_child(id, &parent_container.children, direction) { // Child is found, search is ended Some(id) => Some(id), // A child is not found. This could be because of either two scenarios // 1. Its not possible to move in the desired direction, and search should end // 2. A layout like the following with focus at X and desired direction Right // | _ | x | | // | _ _ _ | | // | _ _ _ | | // The container containing X ends at X so no rightward movement is possible // however there still exists another view/container to the right that hasn't // been explored. Thus another search is done here in the parent container // before concluding it's not possible to move in the desired direction. None => self.find_split_in_direction(parent, direction), } } } } fn find_child(&self, id: ViewId, children: &[ViewId], direction: Direction) -> Option<ViewId> { let mut child_id = match direction { // index wise in the child list the Up and Left represents a -1 // thus reversed iterator. Direction::Up | Direction::Left => children .iter() .rev() .skip_while(|i| **i != id) .copied() .nth(1)?, // Down and Right => +1 index wise in the child list Direction::Down | Direction::Right => { children.iter().skip_while(|i| **i != id).copied().nth(1)? } }; let (current_x, current_y) = match &self.nodes[self.focus].content { Content::View(current_view) => (current_view.area.left(), current_view.area.top()), Content::Container(_) => unreachable!(), }; // If the child is a container the search finds the closest container child // visually based on screen location. while let Content::Container(container) = &self.nodes[child_id].content { match (direction, container.layout) { (_, Layout::Vertical) => { // find closest split based on x because y is irrelevant // in a vertical container (and already correct based on previous search) child_id = *container.children.iter().min_by_key(|id| { let x = match &self.nodes[**id].content { Content::View(view) => view.inner_area().left(), Content::Container(container) => container.area.left(), }; (current_x as i16 - x as i16).abs() })?; } (_, Layout::Horizontal) => { // find closest split based on y because x is irrelevant // in a horizontal container (and already correct based on previous search) child_id = *container.children.iter().min_by_key(|id| { let y = match &self.nodes[**id].content { Content::View(view) => view.inner_area().top(), Content::Container(container) => container.area.top(), }; (current_y as i16 - y as i16).abs() })?; } } } Some(child_id) } pub fn focus_direction(&mut self, direction: Direction) { if let Some(id) = self.find_split_in_direction(self.focus, direction) { self.focus = id; } } pub fn focus_next(&mut self) { // This function is very dumb, but that's because we don't store any parent links. // (we'd be able to go parent.next_sibling() recursively until we find something) // For now that's okay though, since it's unlikely you'll be able to open a large enough // number of splits to notice. let mut views = self .traverse() .skip_while(|&(id, _view)| id != self.focus) .skip(1); // Skip focused value if let Some((id, _)) = views.next() { self.focus = id; } else { // extremely crude, take the first item again let (key, _) = self.traverse().next().unwrap(); self.focus = key; } } pub fn area(&self) -> Rect { self.area } } #[derive(Debug)] pub struct Traverse<'a> { tree: &'a Tree, stack: Vec<ViewId>, // TODO: reuse the one we use on update } impl<'a> Traverse<'a> { fn new(tree: &'a Tree) -> Self { Self { tree, stack: vec![tree.root], } } } impl<'a> Iterator for Traverse<'a> { type Item = (ViewId, &'a View); fn next(&mut self) -> Option<Self::Item> { loop { let key = self.stack.pop()?; let node = &self.tree.nodes[key]; match &node.content { Content::View(view) => return Some((key, view)), Content::Container(container) => { self.stack.extend(container.children.iter().rev()); } } } } } #[cfg(test)] mod test { use super::*; use crate::DocumentId; #[test] fn find_split_in_direction() { let mut tree = Tree::new(Rect { x: 0, y: 0, width: 180, height: 80, }); let mut view = View::new(DocumentId::default()); view.area = Rect::new(0, 0, 180, 80); tree.insert(view); let l0 = tree.focus; let view = View::new(DocumentId::default()); tree.split(view, Layout::Vertical); let r0 = tree.focus; tree.focus = l0; let view = View::new(DocumentId::default()); tree.split(view, Layout::Horizontal); let l1 = tree.focus; tree.focus = l0; let view = View::new(DocumentId::default()); tree.split(view, Layout::Vertical); let l2 = tree.focus; // Tree in test // | L0 | L2 | | // | L1 | R0 | tree.focus = l2; assert_eq!(Some(l0), tree.find_split_in_direction(l2, Direction::Left)); assert_eq!(Some(l1), tree.find_split_in_direction(l2, Direction::Down)); assert_eq!(Some(r0), tree.find_split_in_direction(l2, Direction::Right)); assert_eq!(None, tree.find_split_in_direction(l2, Direction::Up)); tree.focus = l1; assert_eq!(None, tree.find_split_in_direction(l1, Direction::Left)); assert_eq!(None, tree.find_split_in_direction(l1, Direction::Down)); assert_eq!(Some(r0), tree.find_split_in_direction(l1, Direction::Right)); assert_eq!(Some(l0), tree.find_split_in_direction(l1, Direction::Up)); tree.focus = l0; assert_eq!(None, tree.find_split_in_direction(l0, Direction::Left)); assert_eq!(Some(l1), tree.find_split_in_direction(l0, Direction::Down)); assert_eq!(Some(l2), tree.find_split_in_direction(l0, Direction::Right)); assert_eq!(None, tree.find_split_in_direction(l0, Direction::Up)); tree.focus = r0; assert_eq!(Some(l2), tree.find_split_in_direction(r0, Direction::Left)); assert_eq!(None, tree.find_split_in_direction(r0, Direction::Down)); assert_eq!(None, tree.find_split_in_direction(r0, Direction::Right)); assert_eq!(None, tree.find_split_in_direction(r0, Direction::Up)); } }