squawk_syntax/ast/
node_ext.rs

1// via https://github.com/rust-lang/rust-analyzer/blob/d8887c0758bbd2d5f752d5bd405d4491e90e7ed6/crates/syntax/src/ast/node_ext.rs
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27use std::borrow::Cow;
28
29use rowan::{GreenNodeData, GreenTokenData, NodeOrToken};
30
31use crate::ast;
32use crate::ast::AstNode;
33use crate::{SyntaxNode, TokenText};
34
35use super::support;
36
37impl ast::Constraint {
38    #[inline]
39    pub fn name(&self) -> Option<ast::Name> {
40        support::child(self.syntax())
41    }
42}
43
44impl ast::BinExpr {
45    pub fn lhs(&self) -> Option<ast::Expr> {
46        support::children(self.syntax()).next()
47    }
48
49    pub fn rhs(&self) -> Option<ast::Expr> {
50        support::children(self.syntax()).nth(1)
51    }
52}
53
54impl ast::NameRef {
55    #[inline]
56    pub fn text(&self) -> TokenText<'_> {
57        text_of_first_token(self.syntax())
58    }
59}
60
61impl ast::Name {
62    #[inline]
63    pub fn text(&self) -> TokenText<'_> {
64        text_of_first_token(self.syntax())
65    }
66}
67
68impl ast::CharType {
69    #[inline]
70    pub fn text(&self) -> TokenText<'_> {
71        text_of_first_token(self.syntax())
72    }
73}
74
75pub(crate) fn text_of_first_token(node: &SyntaxNode) -> TokenText<'_> {
76    fn first_token(green_ref: &GreenNodeData) -> &GreenTokenData {
77        green_ref
78            .children()
79            .next()
80            .and_then(NodeOrToken::into_token)
81            .unwrap()
82    }
83
84    match node.green() {
85        Cow::Borrowed(green_ref) => TokenText::borrowed(first_token(green_ref).text()),
86        Cow::Owned(green) => TokenText::owned(first_token(&green).to_owned()),
87    }
88}