typst_syntax/
node.rs

1use std::fmt::{self, Debug, Display, Formatter};
2use std::ops::{Deref, Range};
3use std::rc::Rc;
4use std::sync::Arc;
5
6use ecow::{EcoString, EcoVec, eco_format, eco_vec};
7
8use crate::{FileId, Span, SyntaxKind};
9
10/// A node in the untyped syntax tree.
11#[derive(Clone, Eq, PartialEq, Hash)]
12pub struct SyntaxNode(Repr);
13
14/// The three internal representations.
15#[derive(Clone, Eq, PartialEq, Hash)]
16enum Repr {
17    /// A leaf node.
18    Leaf(LeafNode),
19    /// A reference-counted inner node.
20    Inner(Arc<InnerNode>),
21    /// An error node.
22    Error(Arc<ErrorNode>),
23}
24
25impl SyntaxNode {
26    /// Create a new leaf node.
27    pub fn leaf(kind: SyntaxKind, text: impl Into<EcoString>) -> Self {
28        Self(Repr::Leaf(LeafNode::new(kind, text)))
29    }
30
31    /// Create a new inner node with children.
32    pub fn inner(kind: SyntaxKind, children: Vec<SyntaxNode>) -> Self {
33        Self(Repr::Inner(Arc::new(InnerNode::new(kind, children))))
34    }
35
36    /// Create a new error node.
37    pub fn error(error: SyntaxError, text: impl Into<EcoString>) -> Self {
38        Self(Repr::Error(Arc::new(ErrorNode::new(error, text))))
39    }
40
41    /// Create a dummy node of the given kind.
42    ///
43    /// Panics if `kind` is `SyntaxKind::Error`.
44    #[track_caller]
45    pub const fn placeholder(kind: SyntaxKind) -> Self {
46        if matches!(kind, SyntaxKind::Error) {
47            panic!("cannot create error placeholder");
48        }
49        Self(Repr::Leaf(LeafNode {
50            kind,
51            text: EcoString::new(),
52            span: Span::detached(),
53        }))
54    }
55
56    /// The type of the node.
57    pub fn kind(&self) -> SyntaxKind {
58        match &self.0 {
59            Repr::Leaf(leaf) => leaf.kind,
60            Repr::Inner(inner) => inner.kind,
61            Repr::Error(_) => SyntaxKind::Error,
62        }
63    }
64
65    /// Return `true` if the length is 0.
66    pub fn is_empty(&self) -> bool {
67        self.len() == 0
68    }
69
70    /// The byte length of the node in the source text.
71    pub fn len(&self) -> usize {
72        match &self.0 {
73            Repr::Leaf(leaf) => leaf.len(),
74            Repr::Inner(inner) => inner.len,
75            Repr::Error(node) => node.len(),
76        }
77    }
78
79    /// The span of the node.
80    pub fn span(&self) -> Span {
81        match &self.0 {
82            Repr::Leaf(leaf) => leaf.span,
83            Repr::Inner(inner) => inner.span,
84            Repr::Error(node) => node.error.span,
85        }
86    }
87
88    /// The text of the node if it is a leaf or error node.
89    ///
90    /// Returns the empty string if this is an inner node.
91    pub fn text(&self) -> &EcoString {
92        static EMPTY: EcoString = EcoString::new();
93        match &self.0 {
94            Repr::Leaf(leaf) => &leaf.text,
95            Repr::Inner(_) => &EMPTY,
96            Repr::Error(node) => &node.text,
97        }
98    }
99
100    /// Extract the text from the node.
101    ///
102    /// Builds the string if this is an inner node.
103    pub fn into_text(self) -> EcoString {
104        match self.0 {
105            Repr::Leaf(leaf) => leaf.text,
106            Repr::Inner(inner) => {
107                inner.children.iter().cloned().map(Self::into_text).collect()
108            }
109            Repr::Error(node) => node.text.clone(),
110        }
111    }
112
113    /// The node's children.
114    pub fn children(&self) -> std::slice::Iter<'_, SyntaxNode> {
115        match &self.0 {
116            Repr::Leaf(_) | Repr::Error(_) => [].iter(),
117            Repr::Inner(inner) => inner.children.iter(),
118        }
119    }
120
121    /// Whether the node or its children contain an error.
122    pub fn erroneous(&self) -> bool {
123        match &self.0 {
124            Repr::Leaf(_) => false,
125            Repr::Inner(inner) => inner.erroneous,
126            Repr::Error(_) => true,
127        }
128    }
129
130    /// The error messages for this node and its descendants.
131    pub fn errors(&self) -> Vec<SyntaxError> {
132        if !self.erroneous() {
133            return vec![];
134        }
135
136        if let Repr::Error(node) = &self.0 {
137            vec![node.error.clone()]
138        } else {
139            self.children()
140                .filter(|node| node.erroneous())
141                .flat_map(|node| node.errors())
142                .collect()
143        }
144    }
145
146    /// Add a user-presentable hint if this is an error node.
147    pub fn hint(&mut self, hint: impl Into<EcoString>) {
148        if let Repr::Error(node) = &mut self.0 {
149            Arc::make_mut(node).hint(hint);
150        }
151    }
152
153    /// Set a synthetic span for the node and all its descendants.
154    pub fn synthesize(&mut self, span: Span) {
155        match &mut self.0 {
156            Repr::Leaf(leaf) => leaf.span = span,
157            Repr::Inner(inner) => Arc::make_mut(inner).synthesize(span),
158            Repr::Error(node) => Arc::make_mut(node).error.span = span,
159        }
160    }
161
162    /// Whether the two syntax nodes are the same apart from spans.
163    pub fn spanless_eq(&self, other: &Self) -> bool {
164        match (&self.0, &other.0) {
165            (Repr::Leaf(a), Repr::Leaf(b)) => a.spanless_eq(b),
166            (Repr::Inner(a), Repr::Inner(b)) => a.spanless_eq(b),
167            (Repr::Error(a), Repr::Error(b)) => a.spanless_eq(b),
168            _ => false,
169        }
170    }
171}
172
173impl SyntaxNode {
174    /// Convert the child to another kind.
175    ///
176    /// Don't use this for converting to an error!
177    #[track_caller]
178    pub(super) fn convert_to_kind(&mut self, kind: SyntaxKind) {
179        debug_assert!(!kind.is_error());
180        match &mut self.0 {
181            Repr::Leaf(leaf) => leaf.kind = kind,
182            Repr::Inner(inner) => Arc::make_mut(inner).kind = kind,
183            Repr::Error(_) => panic!("cannot convert error"),
184        }
185    }
186
187    /// Convert the child to an error, if it isn't already one.
188    pub(super) fn convert_to_error(&mut self, message: impl Into<EcoString>) {
189        if !self.kind().is_error() {
190            let text = std::mem::take(self).into_text();
191            *self = SyntaxNode::error(SyntaxError::new(message), text);
192        }
193    }
194
195    /// Convert the child to an error stating that the given thing was
196    /// expected, but the current kind was found.
197    pub(super) fn expected(&mut self, expected: &str) {
198        let kind = self.kind();
199        self.convert_to_error(eco_format!("expected {expected}, found {}", kind.name()));
200        if kind.is_keyword() && matches!(expected, "identifier" | "pattern") {
201            self.hint(eco_format!(
202                "keyword `{text}` is not allowed as an identifier; try `{text}_` instead",
203                text = self.text(),
204            ));
205        }
206    }
207
208    /// Convert the child to an error stating it was unexpected.
209    pub(super) fn unexpected(&mut self) {
210        self.convert_to_error(eco_format!("unexpected {}", self.kind().name()));
211    }
212
213    /// Assign spans to each node.
214    pub(super) fn numberize(
215        &mut self,
216        id: FileId,
217        within: Range<u64>,
218    ) -> NumberingResult {
219        if within.start >= within.end {
220            return Err(Unnumberable);
221        }
222
223        let mid = Span::from_number(id, (within.start + within.end) / 2).unwrap();
224        match &mut self.0 {
225            Repr::Leaf(leaf) => leaf.span = mid,
226            Repr::Inner(inner) => Arc::make_mut(inner).numberize(id, None, within)?,
227            Repr::Error(node) => Arc::make_mut(node).error.span = mid,
228        }
229
230        Ok(())
231    }
232
233    /// Whether this is a leaf node.
234    pub(super) fn is_leaf(&self) -> bool {
235        matches!(self.0, Repr::Leaf(_))
236    }
237
238    /// The number of descendants, including the node itself.
239    pub(super) fn descendants(&self) -> usize {
240        match &self.0 {
241            Repr::Leaf(_) | Repr::Error(_) => 1,
242            Repr::Inner(inner) => inner.descendants,
243        }
244    }
245
246    /// The node's children, mutably.
247    pub(super) fn children_mut(&mut self) -> &mut [SyntaxNode] {
248        match &mut self.0 {
249            Repr::Leaf(_) | Repr::Error(_) => &mut [],
250            Repr::Inner(inner) => &mut Arc::make_mut(inner).children,
251        }
252    }
253
254    /// Replaces a range of children with a replacement.
255    ///
256    /// May have mutated the children if it returns `Err(_)`.
257    pub(super) fn replace_children(
258        &mut self,
259        range: Range<usize>,
260        replacement: Vec<SyntaxNode>,
261    ) -> NumberingResult {
262        if let Repr::Inner(inner) = &mut self.0 {
263            Arc::make_mut(inner).replace_children(range, replacement)?;
264        }
265        Ok(())
266    }
267
268    /// Update this node after changes were made to one of its children.
269    pub(super) fn update_parent(
270        &mut self,
271        prev_len: usize,
272        new_len: usize,
273        prev_descendants: usize,
274        new_descendants: usize,
275    ) {
276        if let Repr::Inner(inner) = &mut self.0 {
277            Arc::make_mut(inner).update_parent(
278                prev_len,
279                new_len,
280                prev_descendants,
281                new_descendants,
282            );
283        }
284    }
285
286    /// The upper bound of assigned numbers in this subtree.
287    pub(super) fn upper(&self) -> u64 {
288        match &self.0 {
289            Repr::Leaf(leaf) => leaf.span.number() + 1,
290            Repr::Inner(inner) => inner.upper,
291            Repr::Error(node) => node.error.span.number() + 1,
292        }
293    }
294}
295
296impl Debug for SyntaxNode {
297    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
298        match &self.0 {
299            Repr::Leaf(leaf) => leaf.fmt(f),
300            Repr::Inner(inner) => inner.fmt(f),
301            Repr::Error(node) => node.fmt(f),
302        }
303    }
304}
305
306impl Default for SyntaxNode {
307    fn default() -> Self {
308        Self::leaf(SyntaxKind::End, EcoString::new())
309    }
310}
311
312/// A leaf node in the untyped syntax tree.
313#[derive(Clone, Eq, PartialEq, Hash)]
314struct LeafNode {
315    /// What kind of node this is (each kind would have its own struct in a
316    /// strongly typed AST).
317    kind: SyntaxKind,
318    /// The source text of the node.
319    text: EcoString,
320    /// The node's span.
321    span: Span,
322}
323
324impl LeafNode {
325    /// Create a new leaf node.
326    #[track_caller]
327    fn new(kind: SyntaxKind, text: impl Into<EcoString>) -> Self {
328        debug_assert!(!kind.is_error());
329        Self { kind, text: text.into(), span: Span::detached() }
330    }
331
332    /// The byte length of the node in the source text.
333    fn len(&self) -> usize {
334        self.text.len()
335    }
336
337    /// Whether the two leaf nodes are the same apart from spans.
338    fn spanless_eq(&self, other: &Self) -> bool {
339        self.kind == other.kind && self.text == other.text
340    }
341}
342
343impl Debug for LeafNode {
344    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
345        write!(f, "{:?}: {:?}", self.kind, self.text)
346    }
347}
348
349/// An inner node in the untyped syntax tree.
350#[derive(Clone, Eq, PartialEq, Hash)]
351struct InnerNode {
352    /// What kind of node this is (each kind would have its own struct in a
353    /// strongly typed AST).
354    kind: SyntaxKind,
355    /// The byte length of the node in the source.
356    len: usize,
357    /// The node's span.
358    span: Span,
359    /// The number of nodes in the whole subtree, including this node.
360    descendants: usize,
361    /// Whether this node or any of its children are erroneous.
362    erroneous: bool,
363    /// The upper bound of this node's numbering range.
364    upper: u64,
365    /// This node's children, losslessly make up this node.
366    children: Vec<SyntaxNode>,
367}
368
369impl InnerNode {
370    /// Create a new inner node with the given kind and children.
371    #[track_caller]
372    fn new(kind: SyntaxKind, children: Vec<SyntaxNode>) -> Self {
373        debug_assert!(!kind.is_error());
374
375        let mut len = 0;
376        let mut descendants = 1;
377        let mut erroneous = false;
378
379        for child in &children {
380            len += child.len();
381            descendants += child.descendants();
382            erroneous |= child.erroneous();
383        }
384
385        Self {
386            kind,
387            len,
388            span: Span::detached(),
389            descendants,
390            erroneous,
391            upper: 0,
392            children,
393        }
394    }
395
396    /// Set a synthetic span for the node and all its descendants.
397    fn synthesize(&mut self, span: Span) {
398        self.span = span;
399        self.upper = span.number();
400        for child in &mut self.children {
401            child.synthesize(span);
402        }
403    }
404
405    /// Assign span numbers `within` an interval to this node's subtree or just
406    /// a `range` of its children.
407    fn numberize(
408        &mut self,
409        id: FileId,
410        range: Option<Range<usize>>,
411        within: Range<u64>,
412    ) -> NumberingResult {
413        // Determine how many nodes we will number.
414        let descendants = match &range {
415            Some(range) if range.is_empty() => return Ok(()),
416            Some(range) => self.children[range.clone()]
417                .iter()
418                .map(SyntaxNode::descendants)
419                .sum::<usize>(),
420            None => self.descendants,
421        };
422
423        // Determine the distance between two neighbouring assigned numbers. If
424        // possible, we try to fit all numbers into the left half of `within`
425        // so that there is space for future insertions.
426        let space = within.end - within.start;
427        let mut stride = space / (2 * descendants as u64);
428        if stride == 0 {
429            stride = space / self.descendants as u64;
430            if stride == 0 {
431                return Err(Unnumberable);
432            }
433        }
434
435        // Number the node itself.
436        let mut start = within.start;
437        if range.is_none() {
438            let end = start + stride;
439            self.span = Span::from_number(id, (start + end) / 2).unwrap();
440            self.upper = within.end;
441            start = end;
442        }
443
444        // Number the children.
445        let len = self.children.len();
446        for child in &mut self.children[range.unwrap_or(0..len)] {
447            let end = start + child.descendants() as u64 * stride;
448            child.numberize(id, start..end)?;
449            start = end;
450        }
451
452        Ok(())
453    }
454
455    /// Whether the two inner nodes are the same apart from spans.
456    fn spanless_eq(&self, other: &Self) -> bool {
457        self.kind == other.kind
458            && self.len == other.len
459            && self.descendants == other.descendants
460            && self.erroneous == other.erroneous
461            && self.children.len() == other.children.len()
462            && self
463                .children
464                .iter()
465                .zip(&other.children)
466                .all(|(a, b)| a.spanless_eq(b))
467    }
468
469    /// Replaces a range of children with a replacement.
470    ///
471    /// May have mutated the children if it returns `Err(_)`.
472    fn replace_children(
473        &mut self,
474        mut range: Range<usize>,
475        replacement: Vec<SyntaxNode>,
476    ) -> NumberingResult {
477        let Some(id) = self.span.id() else { return Err(Unnumberable) };
478        let mut replacement_range = 0..replacement.len();
479
480        // Trim off common prefix.
481        while range.start < range.end
482            && replacement_range.start < replacement_range.end
483            && self.children[range.start]
484                .spanless_eq(&replacement[replacement_range.start])
485        {
486            range.start += 1;
487            replacement_range.start += 1;
488        }
489
490        // Trim off common suffix.
491        while range.start < range.end
492            && replacement_range.start < replacement_range.end
493            && self.children[range.end - 1]
494                .spanless_eq(&replacement[replacement_range.end - 1])
495        {
496            range.end -= 1;
497            replacement_range.end -= 1;
498        }
499
500        let mut replacement_vec = replacement;
501        let replacement = &replacement_vec[replacement_range.clone()];
502        let superseded = &self.children[range.clone()];
503
504        // Compute the new byte length.
505        self.len = self.len + replacement.iter().map(SyntaxNode::len).sum::<usize>()
506            - superseded.iter().map(SyntaxNode::len).sum::<usize>();
507
508        // Compute the new number of descendants.
509        self.descendants = self.descendants
510            + replacement.iter().map(SyntaxNode::descendants).sum::<usize>()
511            - superseded.iter().map(SyntaxNode::descendants).sum::<usize>();
512
513        // Determine whether we're still erroneous after the replacement. That's
514        // the case if
515        // - any of the new nodes is erroneous,
516        // - or if we were erroneous before due to a non-superseded node.
517        self.erroneous = replacement.iter().any(SyntaxNode::erroneous)
518            || (self.erroneous
519                && (self.children[..range.start].iter().any(SyntaxNode::erroneous))
520                || self.children[range.end..].iter().any(SyntaxNode::erroneous));
521
522        // Perform the replacement.
523        self.children
524            .splice(range.clone(), replacement_vec.drain(replacement_range.clone()));
525        range.end = range.start + replacement_range.len();
526
527        // Renumber the new children. Retries until it works, taking
528        // exponentially more children into account.
529        let mut left = 0;
530        let mut right = 0;
531        let max_left = range.start;
532        let max_right = self.children.len() - range.end;
533        loop {
534            let renumber = range.start - left..range.end + right;
535
536            // The minimum assignable number is either
537            // - the upper bound of the node right before the to-be-renumbered
538            //   children,
539            // - or this inner node's span number plus one if renumbering starts
540            //   at the first child.
541            let start_number = renumber
542                .start
543                .checked_sub(1)
544                .and_then(|i| self.children.get(i))
545                .map_or(self.span.number() + 1, |child| child.upper());
546
547            // The upper bound for renumbering is either
548            // - the span number of the first child after the to-be-renumbered
549            //   children,
550            // - or this node's upper bound if renumbering ends behind the last
551            //   child.
552            let end_number = self
553                .children
554                .get(renumber.end)
555                .map_or(self.upper, |next| next.span().number());
556
557            // Try to renumber.
558            let within = start_number..end_number;
559            if self.numberize(id, Some(renumber), within).is_ok() {
560                return Ok(());
561            }
562
563            // If it didn't even work with all children, we give up.
564            if left == max_left && right == max_right {
565                return Err(Unnumberable);
566            }
567
568            // Exponential expansion to both sides.
569            left = (left + 1).next_power_of_two().min(max_left);
570            right = (right + 1).next_power_of_two().min(max_right);
571        }
572    }
573
574    /// Update this node after changes were made to one of its children.
575    fn update_parent(
576        &mut self,
577        prev_len: usize,
578        new_len: usize,
579        prev_descendants: usize,
580        new_descendants: usize,
581    ) {
582        self.len = self.len + new_len - prev_len;
583        self.descendants = self.descendants + new_descendants - prev_descendants;
584        self.erroneous = self.children.iter().any(SyntaxNode::erroneous);
585    }
586}
587
588impl Debug for InnerNode {
589    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
590        write!(f, "{:?}: {}", self.kind, self.len)?;
591        if !self.children.is_empty() {
592            f.write_str(" ")?;
593            f.debug_list().entries(&self.children).finish()?;
594        }
595        Ok(())
596    }
597}
598
599/// An error node in the untyped syntax tree.
600#[derive(Clone, Eq, PartialEq, Hash)]
601struct ErrorNode {
602    /// The source text of the node.
603    text: EcoString,
604    /// The syntax error.
605    error: SyntaxError,
606}
607
608impl ErrorNode {
609    /// Create new error node.
610    fn new(error: SyntaxError, text: impl Into<EcoString>) -> Self {
611        Self { text: text.into(), error }
612    }
613
614    /// The byte length of the node in the source text.
615    fn len(&self) -> usize {
616        self.text.len()
617    }
618
619    /// Add a user-presentable hint to this error node.
620    fn hint(&mut self, hint: impl Into<EcoString>) {
621        self.error.hints.push(hint.into());
622    }
623
624    /// Whether the two leaf nodes are the same apart from spans.
625    fn spanless_eq(&self, other: &Self) -> bool {
626        self.text == other.text && self.error.spanless_eq(&other.error)
627    }
628}
629
630impl Debug for ErrorNode {
631    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
632        write!(f, "Error: {:?} ({})", self.text, self.error.message)
633    }
634}
635
636/// A syntactical error.
637#[derive(Debug, Clone, Eq, PartialEq, Hash)]
638pub struct SyntaxError {
639    /// The node's span.
640    pub span: Span,
641    /// The error message.
642    pub message: EcoString,
643    /// Additional hints to the user, indicating how this error could be avoided
644    /// or worked around.
645    pub hints: EcoVec<EcoString>,
646}
647
648impl SyntaxError {
649    /// Create a new detached syntax error.
650    pub fn new(message: impl Into<EcoString>) -> Self {
651        Self {
652            span: Span::detached(),
653            message: message.into(),
654            hints: eco_vec![],
655        }
656    }
657
658    /// Whether the two errors are the same apart from spans.
659    fn spanless_eq(&self, other: &Self) -> bool {
660        self.message == other.message && self.hints == other.hints
661    }
662}
663
664/// A syntax node in a context.
665///
666/// Knows its exact offset in the file and provides access to its
667/// children, parent and siblings.
668///
669/// **Note that all sibling and leaf accessors skip over trivia!**
670#[derive(Clone)]
671pub struct LinkedNode<'a> {
672    node: &'a SyntaxNode,
673    parent: Option<Rc<Self>>,
674    index: usize,
675    offset: usize,
676}
677
678impl<'a> LinkedNode<'a> {
679    /// Start a new traversal at a root node.
680    pub fn new(root: &'a SyntaxNode) -> Self {
681        Self { node: root, parent: None, index: 0, offset: 0 }
682    }
683
684    /// Get the contained syntax node.
685    pub fn get(&self) -> &'a SyntaxNode {
686        self.node
687    }
688
689    /// The index of this node in its parent's children list.
690    pub fn index(&self) -> usize {
691        self.index
692    }
693
694    /// The absolute byte offset of this node in the source file.
695    pub fn offset(&self) -> usize {
696        self.offset
697    }
698
699    /// The byte range of this node in the source file.
700    pub fn range(&self) -> Range<usize> {
701        self.offset..self.offset + self.node.len()
702    }
703
704    /// An iterator over this node's children.
705    pub fn children(&self) -> LinkedChildren<'a> {
706        LinkedChildren {
707            parent: Rc::new(self.clone()),
708            iter: self.node.children().enumerate(),
709            front: self.offset,
710            back: self.offset + self.len(),
711        }
712    }
713
714    /// Find a descendant with the given span.
715    pub fn find(&self, span: Span) -> Option<LinkedNode<'a>> {
716        if self.span() == span {
717            return Some(self.clone());
718        }
719
720        if let Repr::Inner(inner) = &self.0 {
721            // The parent of a subtree has a smaller span number than all of its
722            // descendants. Therefore, we can bail out early if the target span's
723            // number is smaller than our number.
724            if span.number() < inner.span.number() {
725                return None;
726            }
727
728            let mut children = self.children().peekable();
729            while let Some(child) = children.next() {
730                // Every node in this child's subtree has a smaller span number than
731                // the next sibling. Therefore we only need to recurse if the next
732                // sibling's span number is larger than the target span's number.
733                if children
734                    .peek()
735                    .is_none_or(|next| next.span().number() > span.number())
736                    && let Some(found) = child.find(span)
737                {
738                    return Some(found);
739                }
740            }
741        }
742
743        None
744    }
745}
746
747/// Access to parents and siblings.
748impl LinkedNode<'_> {
749    /// Get this node's parent.
750    pub fn parent(&self) -> Option<&Self> {
751        self.parent.as_deref()
752    }
753
754    /// Get the first previous non-trivia sibling node.
755    pub fn prev_sibling(&self) -> Option<Self> {
756        let parent = self.parent()?;
757        let index = self.index.checked_sub(1)?;
758        let node = parent.node.children().nth(index)?;
759        let offset = self.offset - node.len();
760        let prev = Self { node, parent: self.parent.clone(), index, offset };
761        if prev.kind().is_trivia() { prev.prev_sibling() } else { Some(prev) }
762    }
763
764    /// Get the next non-trivia sibling node.
765    pub fn next_sibling(&self) -> Option<Self> {
766        let parent = self.parent()?;
767        let index = self.index.checked_add(1)?;
768        let node = parent.node.children().nth(index)?;
769        let offset = self.offset + self.node.len();
770        let next = Self { node, parent: self.parent.clone(), index, offset };
771        if next.kind().is_trivia() { next.next_sibling() } else { Some(next) }
772    }
773
774    /// Get the kind of this node's parent.
775    pub fn parent_kind(&self) -> Option<SyntaxKind> {
776        Some(self.parent()?.node.kind())
777    }
778
779    /// Get the kind of this node's first previous non-trivia sibling.
780    pub fn prev_sibling_kind(&self) -> Option<SyntaxKind> {
781        Some(self.prev_sibling()?.node.kind())
782    }
783
784    /// Get the kind of this node's next non-trivia sibling.
785    pub fn next_sibling_kind(&self) -> Option<SyntaxKind> {
786        Some(self.next_sibling()?.node.kind())
787    }
788}
789
790/// Indicates whether the cursor is before the related byte index, or after.
791#[derive(Debug, Clone)]
792pub enum Side {
793    Before,
794    After,
795}
796
797/// Access to leaves.
798impl LinkedNode<'_> {
799    /// Get the rightmost non-trivia leaf before this node.
800    pub fn prev_leaf(&self) -> Option<Self> {
801        let mut node = self.clone();
802        while let Some(prev) = node.prev_sibling() {
803            if let Some(leaf) = prev.rightmost_leaf() {
804                return Some(leaf);
805            }
806            node = prev;
807        }
808        self.parent()?.prev_leaf()
809    }
810
811    /// Find the leftmost contained non-trivia leaf.
812    pub fn leftmost_leaf(&self) -> Option<Self> {
813        if self.is_leaf() && !self.kind().is_trivia() && !self.kind().is_error() {
814            return Some(self.clone());
815        }
816
817        for child in self.children() {
818            if let Some(leaf) = child.leftmost_leaf() {
819                return Some(leaf);
820            }
821        }
822
823        None
824    }
825
826    /// Get the leaf immediately before the specified byte offset.
827    fn leaf_before(&self, cursor: usize) -> Option<Self> {
828        if self.node.children().len() == 0 && cursor <= self.offset + self.len() {
829            return Some(self.clone());
830        }
831
832        let mut offset = self.offset;
833        let count = self.node.children().len();
834        for (i, child) in self.children().enumerate() {
835            let len = child.len();
836            if (offset < cursor && cursor <= offset + len)
837                || (offset == cursor && i + 1 == count)
838            {
839                return child.leaf_before(cursor);
840            }
841            offset += len;
842        }
843
844        None
845    }
846
847    /// Get the leaf after the specified byte offset.
848    fn leaf_after(&self, cursor: usize) -> Option<Self> {
849        if self.node.children().len() == 0 && cursor < self.offset + self.len() {
850            return Some(self.clone());
851        }
852
853        let mut offset = self.offset;
854        for child in self.children() {
855            let len = child.len();
856            if offset <= cursor && cursor < offset + len {
857                return child.leaf_after(cursor);
858            }
859            offset += len;
860        }
861
862        None
863    }
864
865    /// Get the leaf at the specified byte offset.
866    pub fn leaf_at(&self, cursor: usize, side: Side) -> Option<Self> {
867        match side {
868            Side::Before => self.leaf_before(cursor),
869            Side::After => self.leaf_after(cursor),
870        }
871    }
872
873    /// Find the rightmost contained non-trivia leaf.
874    pub fn rightmost_leaf(&self) -> Option<Self> {
875        if self.is_leaf() && !self.kind().is_trivia() {
876            return Some(self.clone());
877        }
878
879        for child in self.children().rev() {
880            if let Some(leaf) = child.rightmost_leaf() {
881                return Some(leaf);
882            }
883        }
884
885        None
886    }
887
888    /// Get the leftmost non-trivia leaf after this node.
889    pub fn next_leaf(&self) -> Option<Self> {
890        let mut node = self.clone();
891        while let Some(next) = node.next_sibling() {
892            if let Some(leaf) = next.leftmost_leaf() {
893                return Some(leaf);
894            }
895            node = next;
896        }
897        self.parent()?.next_leaf()
898    }
899}
900
901impl Deref for LinkedNode<'_> {
902    type Target = SyntaxNode;
903
904    /// Dereference to a syntax node. Note that this shortens the lifetime, so
905    /// you may need to use [`get()`](Self::get) instead in some situations.
906    fn deref(&self) -> &Self::Target {
907        self.get()
908    }
909}
910
911impl Debug for LinkedNode<'_> {
912    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
913        self.node.fmt(f)
914    }
915}
916
917/// An iterator over the children of a linked node.
918pub struct LinkedChildren<'a> {
919    parent: Rc<LinkedNode<'a>>,
920    iter: std::iter::Enumerate<std::slice::Iter<'a, SyntaxNode>>,
921    front: usize,
922    back: usize,
923}
924
925impl<'a> Iterator for LinkedChildren<'a> {
926    type Item = LinkedNode<'a>;
927
928    fn next(&mut self) -> Option<Self::Item> {
929        self.iter.next().map(|(index, node)| {
930            let offset = self.front;
931            self.front += node.len();
932            LinkedNode {
933                node,
934                parent: Some(self.parent.clone()),
935                index,
936                offset,
937            }
938        })
939    }
940
941    fn size_hint(&self) -> (usize, Option<usize>) {
942        self.iter.size_hint()
943    }
944}
945
946impl DoubleEndedIterator for LinkedChildren<'_> {
947    fn next_back(&mut self) -> Option<Self::Item> {
948        self.iter.next_back().map(|(index, node)| {
949            self.back -= node.len();
950            LinkedNode {
951                node,
952                parent: Some(self.parent.clone()),
953                index,
954                offset: self.back,
955            }
956        })
957    }
958}
959
960impl ExactSizeIterator for LinkedChildren<'_> {}
961
962/// Result of numbering a node within an interval.
963pub(super) type NumberingResult = Result<(), Unnumberable>;
964
965/// Indicates that a node cannot be numbered within a given interval.
966#[derive(Debug, Copy, Clone, Eq, PartialEq)]
967pub(super) struct Unnumberable;
968
969impl Display for Unnumberable {
970    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
971        f.pad("cannot number within this interval")
972    }
973}
974
975impl std::error::Error for Unnumberable {}
976
977#[cfg(test)]
978mod tests {
979    use super::*;
980    use crate::Source;
981
982    #[test]
983    fn test_linked_node() {
984        let source = Source::detached("#set text(12pt, red)");
985
986        // Find "text" with Before.
987        let node = LinkedNode::new(source.root()).leaf_at(7, Side::Before).unwrap();
988        assert_eq!(node.offset(), 5);
989        assert_eq!(node.text(), "text");
990
991        // Find "text" with After.
992        let node = LinkedNode::new(source.root()).leaf_at(7, Side::After).unwrap();
993        assert_eq!(node.offset(), 5);
994        assert_eq!(node.text(), "text");
995
996        // Go back to "#set". Skips the space.
997        let prev = node.prev_sibling().unwrap();
998        assert_eq!(prev.offset(), 1);
999        assert_eq!(prev.text(), "set");
1000    }
1001
1002    #[test]
1003    fn test_linked_node_non_trivia_leaf() {
1004        let source = Source::detached("#set fun(12pt, red)");
1005        let leaf = LinkedNode::new(source.root()).leaf_at(6, Side::Before).unwrap();
1006        let prev = leaf.prev_leaf().unwrap();
1007        assert_eq!(leaf.text(), "fun");
1008        assert_eq!(prev.text(), "set");
1009
1010        // Check position 9 with Before.
1011        let source = Source::detached("#let x = 10");
1012        let leaf = LinkedNode::new(source.root()).leaf_at(9, Side::Before).unwrap();
1013        let prev = leaf.prev_leaf().unwrap();
1014        let next = leaf.next_leaf().unwrap();
1015        assert_eq!(prev.text(), "=");
1016        assert_eq!(leaf.text(), " ");
1017        assert_eq!(next.text(), "10");
1018
1019        // Check position 9 with After.
1020        let source = Source::detached("#let x = 10");
1021        let leaf = LinkedNode::new(source.root()).leaf_at(9, Side::After).unwrap();
1022        let prev = leaf.prev_leaf().unwrap();
1023        assert!(leaf.next_leaf().is_none());
1024        assert_eq!(prev.text(), "=");
1025        assert_eq!(leaf.text(), "10");
1026    }
1027}