1 //! FIXME: write short doc here
9 use crate::{AstNode, SyntaxKind, SyntaxNode, TextRange};
11 /// A pointer to a syntax node inside a file. It can be used to remember a
12 /// specific node across reparses of the same file.
13 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
14 pub struct SyntaxNodePtr {
15 // Don't expose this field further. At some point, we might want to replace
16 // range with node id.
17 pub(crate) range: TextRange,
22 pub fn new(node: &SyntaxNode) -> SyntaxNodePtr {
23 SyntaxNodePtr { range: node.text_range(), kind: node.kind() }
26 pub fn to_node(&self, root: &SyntaxNode) -> SyntaxNode {
27 assert!(root.parent().is_none());
28 successors(Some(root.clone()), |node| {
29 node.children().find(|it| it.text_range().contains_range(self.range))
31 .find(|it| it.text_range() == self.range && it.kind() == self.kind)
32 .unwrap_or_else(|| panic!("can't resolve local ptr to SyntaxNode: {:?}", self))
35 pub fn cast<N: AstNode>(self) -> Option<AstPtr<N>> {
36 if !N::can_cast(self.kind) {
39 Some(AstPtr { raw: self, _ty: PhantomData })
43 /// Like `SyntaxNodePtr`, but remembers the type of node
45 pub struct AstPtr<N: AstNode> {
47 _ty: PhantomData<fn() -> N>,
50 impl<N: AstNode> Clone for AstPtr<N> {
51 fn clone(&self) -> AstPtr<N> {
52 AstPtr { raw: self.raw.clone(), _ty: PhantomData }
56 impl<N: AstNode> Eq for AstPtr<N> {}
58 impl<N: AstNode> PartialEq for AstPtr<N> {
59 fn eq(&self, other: &AstPtr<N>) -> bool {
64 impl<N: AstNode> Hash for AstPtr<N> {
65 fn hash<H: Hasher>(&self, state: &mut H) {
70 impl<N: AstNode> AstPtr<N> {
71 pub fn new(node: &N) -> AstPtr<N> {
72 AstPtr { raw: SyntaxNodePtr::new(node.syntax()), _ty: PhantomData }
75 pub fn to_node(&self, root: &SyntaxNode) -> N {
76 let syntax_node = self.raw.to_node(root);
77 N::cast(syntax_node).unwrap()
80 pub fn syntax_node_ptr(&self) -> SyntaxNodePtr {
84 pub fn cast<U: AstNode>(self) -> Option<AstPtr<U>> {
85 if !U::can_cast(self.raw.kind) {
88 Some(AstPtr { raw: self.raw, _ty: PhantomData })
92 impl<N: AstNode> From<AstPtr<N>> for SyntaxNodePtr {
93 fn from(ptr: AstPtr<N>) -> SyntaxNodePtr {
99 fn test_local_syntax_ptr() {
100 use crate::{ast, AstNode, SourceFile};
102 let file = SourceFile::parse("struct Foo { f: u32, }").ok().unwrap();
103 let field = file.syntax().descendants().find_map(ast::RecordField::cast).unwrap();
104 let ptr = SyntaxNodePtr::new(field.syntax());
105 let field_syntax = ptr.to_node(file.syntax());
106 assert_eq!(field.syntax(), &field_syntax);