diff options
| author | Laurenz <laurmaedje@gmail.com> | 2023-08-19 19:44:08 +0200 |
|---|---|---|
| committer | Laurenz <laurmaedje@gmail.com> | 2023-08-19 19:44:08 +0200 |
| commit | 5fb5854ed80c48660b51ee163b3ff77f7e44ab94 (patch) | |
| tree | ecf71b837a52c4d6ecded46efe0d029dec5f55ba /crates/typst-syntax/src/node.rs | |
| parent | 16855121b666df46c897017dd065f9f3ce567f3b (diff) | |
Make AST borrowed
Diffstat (limited to 'crates/typst-syntax/src/node.rs')
| -rw-r--r-- | crates/typst-syntax/src/node.rs | 23 |
1 files changed, 18 insertions, 5 deletions
diff --git a/crates/typst-syntax/src/node.rs b/crates/typst-syntax/src/node.rs index f949b4dd..8e4e056e 100644 --- a/crates/typst-syntax/src/node.rs +++ b/crates/typst-syntax/src/node.rs @@ -105,22 +105,22 @@ impl SyntaxNode { } /// Whether the node can be cast to the given AST node. - pub fn is<T: AstNode>(&self) -> bool { + pub fn is<'a, T: AstNode<'a>>(&'a self) -> bool { self.cast::<T>().is_some() } /// Try to convert the node to a typed AST node. - pub fn cast<T: AstNode>(&self) -> Option<T> { + pub fn cast<'a, T: AstNode<'a>>(&'a self) -> Option<T> { T::from_untyped(self) } /// Cast the first child that can cast to the AST type `T`. - pub fn cast_first_match<T: AstNode>(&self) -> Option<T> { + pub fn cast_first_match<'a, T: AstNode<'a>>(&'a self) -> Option<T> { self.children().find_map(Self::cast) } /// Cast the last child that can cast to the AST type `T`. - pub fn cast_last_match<T: AstNode>(&self) -> Option<T> { + pub fn cast_last_match<'a, T: AstNode<'a>>(&'a self) -> Option<T> { self.children().rev().find_map(Self::cast) } @@ -273,6 +273,17 @@ impl SyntaxNode { Repr::Error(node) => node.error.span.number() + 1, } } + + /// An arbitrary node just for filling a slot in memory. + /// + /// In contrast to `default()`, this is a const fn. + pub(super) const fn arbitrary() -> Self { + Self(Repr::Leaf(LeafNode { + kind: SyntaxKind::Eof, + text: EcoString::new(), + span: Span::detached(), + })) + } } impl Debug for SyntaxNode { @@ -287,7 +298,7 @@ impl Debug for SyntaxNode { impl Default for SyntaxNode { fn default() -> Self { - Self::error("", "") + Self::arbitrary() } } @@ -802,6 +813,8 @@ impl<'a> LinkedNode<'a> { impl Deref for LinkedNode<'_> { type Target = SyntaxNode; + /// Dereference to a syntax node. Note that this shortens the lifetime, so + /// you may need to use [`get()`](Self::get) instead in some situations. fn deref(&self) -> &Self::Target { self.get() } |
