]> git.lizzy.rs Git - rust.git/blob - crates/syntax/src/ptr.rs
internal: cleanup adt parsing
[rust.git] / crates / syntax / src / ptr.rs
1 //! In rust-analyzer, syntax trees are transient objects.
2 //!
3 //! That means that we create trees when we need them, and tear them down to
4 //! save memory. In this architecture, hanging on to a particular syntax node
5 //! for a long time is ill-advisable, as that keeps the whole tree resident.
6 //!
7 //! Instead, we provide a [`SyntaxNodePtr`] type, which stores information about
8 //! *location* of a particular syntax node in a tree. Its a small type which can
9 //! be cheaply stored, and which can be resolved to a real [`SyntaxNode`] when
10 //! necessary.
11
12 use std::{
13     hash::{Hash, Hasher},
14     iter::successors,
15     marker::PhantomData,
16 };
17
18 use crate::{AstNode, SyntaxKind, SyntaxNode, TextRange};
19
20 /// A pointer to a syntax node inside a file. It can be used to remember a
21 /// specific node across reparses of the same file.
22 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
23 pub struct SyntaxNodePtr {
24     // Don't expose this field further. At some point, we might want to replace
25     // range with node id.
26     pub(crate) range: TextRange,
27     kind: SyntaxKind,
28 }
29
30 impl SyntaxNodePtr {
31     pub fn new(node: &SyntaxNode) -> SyntaxNodePtr {
32         SyntaxNodePtr { range: node.text_range(), kind: node.kind() }
33     }
34
35     /// "Dereference" the pointer to get the node it points to.
36     ///
37     /// Panics if node is not found, so make sure that `root` syntax tree is
38     /// equivalent (is build from the same text) to the tree which was
39     /// originally used to get this [`SyntaxNodePtr`].
40     ///
41     /// The complexity is linear in the depth of the tree and logarithmic in
42     /// tree width. As most trees are shallow, thinking about this as
43     /// `O(log(N))` in the size of the tree is not too wrong!
44     pub fn to_node(&self, root: &SyntaxNode) -> SyntaxNode {
45         assert!(root.parent().is_none());
46         successors(Some(root.clone()), |node| {
47             node.child_or_token_at_range(self.range).and_then(|it| it.into_node())
48         })
49         .find(|it| it.text_range() == self.range && it.kind() == self.kind)
50         .unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self))
51     }
52
53     pub fn cast<N: AstNode>(self) -> Option<AstPtr<N>> {
54         if !N::can_cast(self.kind) {
55             return None;
56         }
57         Some(AstPtr { raw: self, _ty: PhantomData })
58     }
59 }
60
61 /// Like `SyntaxNodePtr`, but remembers the type of node
62 #[derive(Debug)]
63 pub struct AstPtr<N: AstNode> {
64     raw: SyntaxNodePtr,
65     _ty: PhantomData<fn() -> N>,
66 }
67
68 impl<N: AstNode> Clone for AstPtr<N> {
69     fn clone(&self) -> AstPtr<N> {
70         AstPtr { raw: self.raw.clone(), _ty: PhantomData }
71     }
72 }
73
74 impl<N: AstNode> Eq for AstPtr<N> {}
75
76 impl<N: AstNode> PartialEq for AstPtr<N> {
77     fn eq(&self, other: &AstPtr<N>) -> bool {
78         self.raw == other.raw
79     }
80 }
81
82 impl<N: AstNode> Hash for AstPtr<N> {
83     fn hash<H: Hasher>(&self, state: &mut H) {
84         self.raw.hash(state)
85     }
86 }
87
88 impl<N: AstNode> AstPtr<N> {
89     pub fn new(node: &N) -> AstPtr<N> {
90         AstPtr { raw: SyntaxNodePtr::new(node.syntax()), _ty: PhantomData }
91     }
92
93     pub fn to_node(&self, root: &SyntaxNode) -> N {
94         let syntax_node = self.raw.to_node(root);
95         N::cast(syntax_node).unwrap()
96     }
97
98     pub fn syntax_node_ptr(&self) -> SyntaxNodePtr {
99         self.raw.clone()
100     }
101
102     pub fn cast<U: AstNode>(self) -> Option<AstPtr<U>> {
103         if !U::can_cast(self.raw.kind) {
104             return None;
105         }
106         Some(AstPtr { raw: self.raw, _ty: PhantomData })
107     }
108 }
109
110 impl<N: AstNode> From<AstPtr<N>> for SyntaxNodePtr {
111     fn from(ptr: AstPtr<N>) -> SyntaxNodePtr {
112         ptr.raw
113     }
114 }
115
116 #[test]
117 fn test_local_syntax_ptr() {
118     use crate::{ast, AstNode, SourceFile};
119
120     let file = SourceFile::parse("struct Foo { f: u32, }").ok().unwrap();
121     let field = file.syntax().descendants().find_map(ast::RecordField::cast).unwrap();
122     let ptr = SyntaxNodePtr::new(field.syntax());
123     let field_syntax = ptr.to_node(file.syntax());
124     assert_eq!(field.syntax(), &field_syntax);
125 }