rowan/
api.rs

1use std::{borrow::Cow, fmt, iter, marker::PhantomData, ops::Range};
2
3use crate::{
4    cursor, green::GreenTokenData, Direction, GreenNode, GreenNodeData, GreenToken, NodeOrToken,
5    SyntaxKind, SyntaxText, TextRange, TextSize, TokenAtOffset, WalkEvent,
6};
7
8pub trait Language: Sized + Copy + fmt::Debug + Eq + Ord + std::hash::Hash {
9    type Kind: Sized + Copy + fmt::Debug + Eq + Ord + std::hash::Hash;
10
11    fn kind_from_raw(raw: SyntaxKind) -> Self::Kind;
12    fn kind_to_raw(kind: Self::Kind) -> SyntaxKind;
13}
14
15#[derive(Clone, PartialEq, Eq, Hash)]
16pub struct SyntaxNode<L: Language> {
17    raw: cursor::SyntaxNode,
18    _p: PhantomData<L>,
19}
20
21#[derive(Clone, PartialEq, Eq, Hash)]
22pub struct SyntaxToken<L: Language> {
23    raw: cursor::SyntaxToken,
24    _p: PhantomData<L>,
25}
26
27pub type SyntaxElement<L> = NodeOrToken<SyntaxNode<L>, SyntaxToken<L>>;
28
29impl<L: Language> fmt::Debug for SyntaxNode<L> {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        if f.alternate() {
32            let mut level = 0;
33            for event in self.preorder_with_tokens() {
34                match event {
35                    WalkEvent::Enter(element) => {
36                        for _ in 0..level {
37                            write!(f, "  ")?;
38                        }
39                        match element {
40                            NodeOrToken::Node(node) => writeln!(f, "{:?}", node)?,
41                            NodeOrToken::Token(token) => writeln!(f, "{:?}", token)?,
42                        }
43                        level += 1;
44                    }
45                    WalkEvent::Leave(_) => level -= 1,
46                }
47            }
48            assert_eq!(level, 0);
49            Ok(())
50        } else {
51            write!(f, "{:?}@{:?}", self.kind(), self.text_range())
52        }
53    }
54}
55
56impl<L: Language> fmt::Display for SyntaxNode<L> {
57    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        fmt::Display::fmt(&self.raw, f)
59    }
60}
61
62impl<L: Language> fmt::Debug for SyntaxToken<L> {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        write!(f, "{:?}@{:?}", self.kind(), self.text_range())?;
65        if self.text().len() < 25 {
66            return write!(f, " {:?}", self.text());
67        }
68        let text = self.text();
69        for idx in 21..25 {
70            if text.is_char_boundary(idx) {
71                let text = format!("{} ...", &text[..idx]);
72                return write!(f, " {:?}", text);
73            }
74        }
75        unreachable!()
76    }
77}
78
79impl<L: Language> fmt::Display for SyntaxToken<L> {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        fmt::Display::fmt(&self.raw, f)
82    }
83}
84
85impl<L: Language> From<SyntaxNode<L>> for SyntaxElement<L> {
86    fn from(node: SyntaxNode<L>) -> SyntaxElement<L> {
87        NodeOrToken::Node(node)
88    }
89}
90
91impl<L: Language> From<SyntaxToken<L>> for SyntaxElement<L> {
92    fn from(token: SyntaxToken<L>) -> SyntaxElement<L> {
93        NodeOrToken::Token(token)
94    }
95}
96
97impl<L: Language> SyntaxNode<L> {
98    pub fn new_root(green: GreenNode) -> SyntaxNode<L> {
99        SyntaxNode::from(cursor::SyntaxNode::new_root(green))
100    }
101    pub fn new_root_mut(green: GreenNode) -> SyntaxNode<L> {
102        SyntaxNode::from(cursor::SyntaxNode::new_root_mut(green))
103    }
104
105    /// Returns a green tree, equal to the green tree this node
106    /// belongs to, except with this node substituted. The complexity
107    /// of the operation is proportional to the depth of the tree.
108    pub fn replace_with(&self, replacement: GreenNode) -> GreenNode {
109        self.raw.replace_with(replacement)
110    }
111
112    pub fn kind(&self) -> L::Kind {
113        L::kind_from_raw(self.raw.kind())
114    }
115
116    pub fn text_range(&self) -> TextRange {
117        self.raw.text_range()
118    }
119
120    pub fn index(&self) -> usize {
121        self.raw.index()
122    }
123
124    pub fn text(&self) -> SyntaxText {
125        self.raw.text()
126    }
127
128    pub fn green(&self) -> Cow<'_, GreenNodeData> {
129        self.raw.green()
130    }
131
132    pub fn parent(&self) -> Option<SyntaxNode<L>> {
133        self.raw.parent().map(Self::from)
134    }
135
136    pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode<L>> {
137        self.raw.ancestors().map(SyntaxNode::from)
138    }
139
140    pub fn children(&self) -> SyntaxNodeChildren<L> {
141        SyntaxNodeChildren { raw: self.raw.children(), _p: PhantomData }
142    }
143
144    pub fn children_with_tokens(&self) -> SyntaxElementChildren<L> {
145        SyntaxElementChildren { raw: self.raw.children_with_tokens(), _p: PhantomData }
146    }
147
148    pub fn first_child(&self) -> Option<SyntaxNode<L>> {
149        self.raw.first_child().map(Self::from)
150    }
151    pub fn last_child(&self) -> Option<SyntaxNode<L>> {
152        self.raw.last_child().map(Self::from)
153    }
154
155    pub fn first_child_or_token(&self) -> Option<SyntaxElement<L>> {
156        self.raw.first_child_or_token().map(NodeOrToken::from)
157    }
158    pub fn last_child_or_token(&self) -> Option<SyntaxElement<L>> {
159        self.raw.last_child_or_token().map(NodeOrToken::from)
160    }
161
162    pub fn next_sibling(&self) -> Option<SyntaxNode<L>> {
163        self.raw.next_sibling().map(Self::from)
164    }
165    pub fn prev_sibling(&self) -> Option<SyntaxNode<L>> {
166        self.raw.prev_sibling().map(Self::from)
167    }
168
169    pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
170        self.raw.next_sibling_or_token().map(NodeOrToken::from)
171    }
172    pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
173        self.raw.prev_sibling_or_token().map(NodeOrToken::from)
174    }
175
176    /// Return the leftmost token in the subtree of this node.
177    pub fn first_token(&self) -> Option<SyntaxToken<L>> {
178        self.raw.first_token().map(SyntaxToken::from)
179    }
180    /// Return the rightmost token in the subtree of this node.
181    pub fn last_token(&self) -> Option<SyntaxToken<L>> {
182        self.raw.last_token().map(SyntaxToken::from)
183    }
184
185    pub fn siblings(&self, direction: Direction) -> impl Iterator<Item = SyntaxNode<L>> {
186        self.raw.siblings(direction).map(SyntaxNode::from)
187    }
188
189    pub fn siblings_with_tokens(
190        &self,
191        direction: Direction,
192    ) -> impl Iterator<Item = SyntaxElement<L>> {
193        self.raw.siblings_with_tokens(direction).map(SyntaxElement::from)
194    }
195
196    pub fn descendants(&self) -> impl Iterator<Item = SyntaxNode<L>> {
197        self.raw.descendants().map(SyntaxNode::from)
198    }
199
200    pub fn descendants_with_tokens(&self) -> impl Iterator<Item = SyntaxElement<L>> {
201        self.raw.descendants_with_tokens().map(NodeOrToken::from)
202    }
203
204    /// Traverse the subtree rooted at the current node (including the current
205    /// node) in preorder, excluding tokens.
206    pub fn preorder(&self) -> Preorder<L> {
207        Preorder { raw: self.raw.preorder(), _p: PhantomData }
208    }
209
210    /// Traverse the subtree rooted at the current node (including the current
211    /// node) in preorder, including tokens.
212    pub fn preorder_with_tokens(&self) -> PreorderWithTokens<L> {
213        PreorderWithTokens { raw: self.raw.preorder_with_tokens(), _p: PhantomData }
214    }
215
216    /// Find a token in the subtree corresponding to this node, which covers the offset.
217    /// Precondition: offset must be withing node's range.
218    pub fn token_at_offset(&self, offset: TextSize) -> TokenAtOffset<SyntaxToken<L>> {
219        self.raw.token_at_offset(offset).map(SyntaxToken::from)
220    }
221
222    /// Return the deepest node or token in the current subtree that fully
223    /// contains the range. If the range is empty and is contained in two leaf
224    /// nodes, either one can be returned. Precondition: range must be contained
225    /// withing the current node
226    pub fn covering_element(&self, range: TextRange) -> SyntaxElement<L> {
227        NodeOrToken::from(self.raw.covering_element(range))
228    }
229
230    /// Finds a [`SyntaxElement`] which intersects with a given `range`. If
231    /// there are several intersecting elements, any one can be returned.
232    ///
233    /// The method uses binary search internally, so it's complexity is
234    /// `O(log(N))` where `N = self.children_with_tokens().count()`.
235    pub fn child_or_token_at_range(&self, range: TextRange) -> Option<SyntaxElement<L>> {
236        self.raw.child_or_token_at_range(range).map(SyntaxElement::from)
237    }
238
239    /// Returns an independent copy of the subtree rooted at this node.
240    ///
241    /// The parent of the returned node will be `None`, the start offset will be
242    /// zero, but, otherwise, it'll be equivalent to the source node.
243    pub fn clone_subtree(&self) -> SyntaxNode<L> {
244        SyntaxNode::from(self.raw.clone_subtree())
245    }
246
247    pub fn clone_for_update(&self) -> SyntaxNode<L> {
248        SyntaxNode::from(self.raw.clone_for_update())
249    }
250
251    pub fn is_mutable(&self) -> bool {
252        self.raw.is_mutable()
253    }
254
255    pub fn detach(&self) {
256        self.raw.detach()
257    }
258
259    pub fn splice_children(&self, to_delete: Range<usize>, to_insert: Vec<SyntaxElement<L>>) {
260        let to_insert = to_insert.into_iter().map(cursor::SyntaxElement::from).collect::<Vec<_>>();
261        self.raw.splice_children(to_delete, to_insert)
262    }
263}
264
265impl<L: Language> SyntaxToken<L> {
266    /// Returns a green tree, equal to the green tree this token
267    /// belongs to, except with this token substituted. The complexity
268    /// of the operation is proportional to the depth of the tree.
269    pub fn replace_with(&self, new_token: GreenToken) -> GreenNode {
270        self.raw.replace_with(new_token)
271    }
272
273    pub fn kind(&self) -> L::Kind {
274        L::kind_from_raw(self.raw.kind())
275    }
276
277    pub fn text_range(&self) -> TextRange {
278        self.raw.text_range()
279    }
280
281    pub fn index(&self) -> usize {
282        self.raw.index()
283    }
284
285    pub fn text(&self) -> &str {
286        self.raw.text()
287    }
288
289    pub fn green(&self) -> &GreenTokenData {
290        self.raw.green()
291    }
292
293    pub fn parent(&self) -> Option<SyntaxNode<L>> {
294        self.raw.parent().map(SyntaxNode::from)
295    }
296
297    /// Iterator over all the ancestors of this token excluding itself.
298    #[deprecated = "use `SyntaxToken::parent_ancestors` instead"]
299    pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode<L>> {
300        self.parent_ancestors()
301    }
302
303    /// Iterator over all the ancestors of this token excluding itself.
304    pub fn parent_ancestors(&self) -> impl Iterator<Item = SyntaxNode<L>> {
305        self.raw.ancestors().map(SyntaxNode::from)
306    }
307
308    pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
309        self.raw.next_sibling_or_token().map(NodeOrToken::from)
310    }
311    pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
312        self.raw.prev_sibling_or_token().map(NodeOrToken::from)
313    }
314
315    pub fn siblings_with_tokens(
316        &self,
317        direction: Direction,
318    ) -> impl Iterator<Item = SyntaxElement<L>> {
319        self.raw.siblings_with_tokens(direction).map(SyntaxElement::from)
320    }
321
322    /// Next token in the tree (i.e, not necessary a sibling).
323    pub fn next_token(&self) -> Option<SyntaxToken<L>> {
324        self.raw.next_token().map(SyntaxToken::from)
325    }
326    /// Previous token in the tree (i.e, not necessary a sibling).
327    pub fn prev_token(&self) -> Option<SyntaxToken<L>> {
328        self.raw.prev_token().map(SyntaxToken::from)
329    }
330
331    pub fn detach(&self) {
332        self.raw.detach()
333    }
334}
335
336impl<L: Language> SyntaxElement<L> {
337    pub fn text_range(&self) -> TextRange {
338        match self {
339            NodeOrToken::Node(it) => it.text_range(),
340            NodeOrToken::Token(it) => it.text_range(),
341        }
342    }
343
344    pub fn index(&self) -> usize {
345        match self {
346            NodeOrToken::Node(it) => it.index(),
347            NodeOrToken::Token(it) => it.index(),
348        }
349    }
350
351    pub fn kind(&self) -> L::Kind {
352        match self {
353            NodeOrToken::Node(it) => it.kind(),
354            NodeOrToken::Token(it) => it.kind(),
355        }
356    }
357
358    pub fn parent(&self) -> Option<SyntaxNode<L>> {
359        match self {
360            NodeOrToken::Node(it) => it.parent(),
361            NodeOrToken::Token(it) => it.parent(),
362        }
363    }
364
365    pub fn ancestors(&self) -> impl Iterator<Item = SyntaxNode<L>> {
366        let first = match self {
367            NodeOrToken::Node(it) => Some(it.clone()),
368            NodeOrToken::Token(it) => it.parent(),
369        };
370        iter::successors(first, SyntaxNode::parent)
371    }
372
373    pub fn next_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
374        match self {
375            NodeOrToken::Node(it) => it.next_sibling_or_token(),
376            NodeOrToken::Token(it) => it.next_sibling_or_token(),
377        }
378    }
379    pub fn prev_sibling_or_token(&self) -> Option<SyntaxElement<L>> {
380        match self {
381            NodeOrToken::Node(it) => it.prev_sibling_or_token(),
382            NodeOrToken::Token(it) => it.prev_sibling_or_token(),
383        }
384    }
385    pub fn detach(&self) {
386        match self {
387            NodeOrToken::Node(it) => it.detach(),
388            NodeOrToken::Token(it) => it.detach(),
389        }
390    }
391}
392
393#[derive(Debug, Clone)]
394pub struct SyntaxNodeChildren<L: Language> {
395    raw: cursor::SyntaxNodeChildren,
396    _p: PhantomData<L>,
397}
398
399impl<L: Language> Iterator for SyntaxNodeChildren<L> {
400    type Item = SyntaxNode<L>;
401    fn next(&mut self) -> Option<Self::Item> {
402        self.raw.next().map(SyntaxNode::from)
403    }
404}
405
406#[derive(Debug, Clone)]
407pub struct SyntaxElementChildren<L: Language> {
408    raw: cursor::SyntaxElementChildren,
409    _p: PhantomData<L>,
410}
411
412impl<L: Language> Iterator for SyntaxElementChildren<L> {
413    type Item = SyntaxElement<L>;
414    fn next(&mut self) -> Option<Self::Item> {
415        self.raw.next().map(NodeOrToken::from)
416    }
417}
418
419pub struct Preorder<L: Language> {
420    raw: cursor::Preorder,
421    _p: PhantomData<L>,
422}
423
424impl<L: Language> Preorder<L> {
425    pub fn skip_subtree(&mut self) {
426        self.raw.skip_subtree()
427    }
428}
429
430impl<L: Language> Iterator for Preorder<L> {
431    type Item = WalkEvent<SyntaxNode<L>>;
432    fn next(&mut self) -> Option<Self::Item> {
433        self.raw.next().map(|it| it.map(SyntaxNode::from))
434    }
435}
436
437pub struct PreorderWithTokens<L: Language> {
438    raw: cursor::PreorderWithTokens,
439    _p: PhantomData<L>,
440}
441
442impl<L: Language> PreorderWithTokens<L> {
443    pub fn skip_subtree(&mut self) {
444        self.raw.skip_subtree()
445    }
446}
447
448impl<L: Language> Iterator for PreorderWithTokens<L> {
449    type Item = WalkEvent<SyntaxElement<L>>;
450    fn next(&mut self) -> Option<Self::Item> {
451        self.raw.next().map(|it| it.map(SyntaxElement::from))
452    }
453}
454
455impl<L: Language> From<cursor::SyntaxNode> for SyntaxNode<L> {
456    fn from(raw: cursor::SyntaxNode) -> SyntaxNode<L> {
457        SyntaxNode { raw, _p: PhantomData }
458    }
459}
460
461impl<L: Language> From<SyntaxNode<L>> for cursor::SyntaxNode {
462    fn from(node: SyntaxNode<L>) -> cursor::SyntaxNode {
463        node.raw
464    }
465}
466
467impl<L: Language> From<cursor::SyntaxToken> for SyntaxToken<L> {
468    fn from(raw: cursor::SyntaxToken) -> SyntaxToken<L> {
469        SyntaxToken { raw, _p: PhantomData }
470    }
471}
472
473impl<L: Language> From<SyntaxToken<L>> for cursor::SyntaxToken {
474    fn from(token: SyntaxToken<L>) -> cursor::SyntaxToken {
475        token.raw
476    }
477}
478
479impl<L: Language> From<cursor::SyntaxElement> for SyntaxElement<L> {
480    fn from(raw: cursor::SyntaxElement) -> SyntaxElement<L> {
481        match raw {
482            NodeOrToken::Node(it) => NodeOrToken::Node(it.into()),
483            NodeOrToken::Token(it) => NodeOrToken::Token(it.into()),
484        }
485    }
486}
487
488impl<L: Language> From<SyntaxElement<L>> for cursor::SyntaxElement {
489    fn from(element: SyntaxElement<L>) -> cursor::SyntaxElement {
490        match element {
491            NodeOrToken::Node(it) => NodeOrToken::Node(it.into()),
492            NodeOrToken::Token(it) => NodeOrToken::Token(it.into()),
493        }
494    }
495}