aboutsummaryrefslogtreecommitdiff
path: root/crates/libsyntax2/src/yellow/syntax.rs
blob: 1d99cab4a94520a034e15bfd40db8a9274ac932b (plain)
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
use std::{
    fmt, sync::Arc,
    hash::{Hasher, Hash},
    ops::Range,
};

use smol_str::SmolStr;

use {
    yellow::{GreenNode, RedNode, TreeRoot, SyntaxRoot, RedPtr, RefRoot, OwnedRoot, SyntaxText},
    SyntaxKind::{self, *},
    TextRange, TextUnit,
};


#[derive(Clone, Copy)]
pub struct SyntaxNode<R: TreeRoot = OwnedRoot> {
    pub(crate) root: R,
    // Guaranteed to not dangle, because `root` holds a
    // strong reference to red's ancestor
    red: RedPtr,
}

unsafe impl<R: TreeRoot> Send for SyntaxNode<R> {}
unsafe impl<R: TreeRoot> Sync for SyntaxNode<R> {}

impl<R1: TreeRoot, R2: TreeRoot> PartialEq<SyntaxNode<R1>> for SyntaxNode<R2> {
    fn eq(&self, other: &SyntaxNode<R1>) -> bool {
        self.red == other.red
    }
}

impl<R: TreeRoot> Eq for SyntaxNode<R> {}
impl<R: TreeRoot> Hash for SyntaxNode<R> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.red.hash(state)
    }
}

pub type SyntaxNodeRef<'a> = SyntaxNode<RefRoot<'a>>;

#[test]
fn syntax_node_ref_is_copy() {
    fn assert_copy<T: Copy>(){}
    assert_copy::<SyntaxNodeRef>()
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct SyntaxError {
    pub msg: String,
    pub offset: TextUnit,
}

impl SyntaxNode<OwnedRoot> {
    pub(crate) fn new_owned(root: SyntaxRoot) -> Self {
        let root = OwnedRoot(Arc::new(root));
        let red = RedPtr::new(&root.syntax_root().red);
        SyntaxNode { root, red }
    }
}

impl<'a> SyntaxNode<RefRoot<'a>> {
    pub(crate) fn leaf_text_ref(self) -> Option<&'a SmolStr> {
        let red = unsafe { self.red.get(self.root.syntax_root()) };
        red.green().leaf_text_ref()
    }
}

impl<R: TreeRoot> SyntaxNode<R> {
    pub fn borrowed<'a>(&'a self) -> SyntaxNodeRef<'a> {
        SyntaxNode {
            root: self.root.borrowed(),
            red: self.red,
        }
    }

    pub fn owned(&self) -> SyntaxNode {
        SyntaxNode {
            root: self.root.owned(),
            red: self.red,
        }
    }

    pub fn kind(&self) -> SyntaxKind {
        self.red().green().kind()
    }

    pub fn range(&self) -> TextRange {
        let red = self.red();
        TextRange::offset_len(red.start_offset(), red.green().text_len())
    }

    pub fn text(&self) -> SyntaxText {
        SyntaxText::new(self.borrowed())
    }

    pub fn children(&self) -> SyntaxNodeChildren<R> {
        SyntaxNodeChildren {
            parent: self.clone(),
            iter: (0..self.red().n_children())
        }
    }

    pub fn parent(&self) -> Option<SyntaxNode<R>> {
        let parent = self.red().parent()?;
        Some(SyntaxNode {
            root: self.root.clone(),
            red: parent,
        })
    }

    pub fn first_child(&self) -> Option<SyntaxNode<R>> {
        let red = self.red().get_child(0)?;
        Some(SyntaxNode { root: self.root.clone(), red })
    }

    pub fn last_child(&self) -> Option<SyntaxNode<R>> {
        let n = self.red().n_children();
        let n = n.checked_sub(1)?;
        let red = self.red().get_child(n)?;
        Some(SyntaxNode { root: self.root.clone(), red })
    }

    pub fn next_sibling(&self) -> Option<SyntaxNode<R>> {
        let red = self.red();
        let parent = self.parent()?;
        let next_sibling_idx = red.index_in_parent()? + 1;
        let sibling_red = parent.red().get_child(next_sibling_idx)?;
        Some(SyntaxNode {
            root: self.root.clone(),
            red: sibling_red,
        })
    }

    pub fn prev_sibling(&self) -> Option<SyntaxNode<R>> {
        let red = self.red();
        let parent = self.parent()?;
        let prev_sibling_idx = red.index_in_parent()?.checked_sub(1)?;
        let sibling_red = parent.red().get_child(prev_sibling_idx)?;
        Some(SyntaxNode {
            root: self.root.clone(),
            red: sibling_red,
        })
    }

    pub fn is_leaf(&self) -> bool {
        self.first_child().is_none()
    }

    pub fn leaf_text(&self) -> Option<SmolStr> {
        self.borrowed().leaf_text_ref().map(|it| it.clone())
    }

    pub(crate) fn replace_with(&self, green: GreenNode) -> GreenNode {
        assert_eq!(self.kind(), green.kind());
        match self.parent() {
            None => green,
            Some(parent) => {
                let children: Vec<_> = parent.children().map(|child| {
                    if child == *self {
                        green.clone()
                    } else {
                        child.red().green().clone()
                    }
                }).collect();
                let new_parent = GreenNode::new_branch(
                    parent.kind(),
                    children.into_boxed_slice(),
                );
                parent.replace_with(new_parent)
            },
        }
    }

    fn red(&self) -> &RedNode {
        unsafe { self.red.get(self.root.syntax_root()) }
    }
}

impl<R: TreeRoot> fmt::Debug for SyntaxNode<R> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{:?}@{:?}", self.kind(), self.range())?;
        if has_short_text(self.kind()) {
            write!(fmt, " \"{}\"", self.text())?;
        }
        Ok(())
    }
}

#[derive(Debug)]
pub struct SyntaxNodeChildren<R: TreeRoot> {
    parent: SyntaxNode<R>,
    iter: Range<usize>,
}

impl<R: TreeRoot> Iterator for SyntaxNodeChildren<R> {
    type Item = SyntaxNode<R>;

    fn next(&mut self) -> Option<SyntaxNode<R>> {
        self.iter.next().map(|i| {
            let red = self.parent.red();
            SyntaxNode {
                root: self.parent.root.clone(),
                red: red.get_child(i).unwrap(),
            }
        })
    }
}

fn has_short_text(kind: SyntaxKind) -> bool {
    match kind {
        IDENT | LIFETIME | INT_NUMBER | FLOAT_NUMBER => true,
        _ => false,
    }
}