Skip to main content

syntax/ast/
traits.rs

1//! Various traits that are implemented by ast nodes.
2//!
3//! The implementations are usually trivial, and live in generated.rs
4use either::Either;
5
6use crate::{
7    SyntaxNode, SyntaxToken, T,
8    ast::{self, AstChildren, AstNode, support},
9    match_ast,
10};
11
12pub trait HasName: AstNode {
13    fn name(&self) -> Option<ast::Name> {
14        support::child(self.syntax())
15    }
16}
17
18pub trait HasVisibility: AstNode {
19    fn visibility(&self) -> Option<ast::Visibility> {
20        support::child(self.syntax())
21    }
22}
23
24pub trait HasLoopBody: AstNode {
25    fn loop_body(&self) -> Option<ast::BlockExpr> {
26        support::child(self.syntax())
27    }
28
29    fn label(&self) -> Option<ast::Label> {
30        support::child(self.syntax())
31    }
32}
33
34pub trait HasArgList: AstNode {
35    fn arg_list(&self) -> Option<ast::ArgList> {
36        support::child(self.syntax())
37    }
38}
39
40pub trait HasModuleItem: AstNode {
41    fn items(&self) -> AstChildren<ast::Item> {
42        support::children(self.syntax())
43    }
44}
45
46pub trait HasGenericParams: AstNode {
47    fn generic_param_list(&self) -> Option<ast::GenericParamList> {
48        support::child(self.syntax())
49    }
50
51    fn where_clause(&self) -> Option<ast::WhereClause> {
52        support::child(self.syntax())
53    }
54}
55pub trait HasGenericArgs: AstNode {
56    fn generic_arg_list(&self) -> Option<ast::GenericArgList> {
57        support::child(self.syntax())
58    }
59}
60
61pub trait HasTypeBounds: AstNode {
62    fn type_bound_list(&self) -> Option<ast::TypeBoundList> {
63        support::child(self.syntax())
64    }
65
66    fn colon_token(&self) -> Option<SyntaxToken> {
67        support::token(self.syntax(), T![:])
68    }
69}
70
71pub trait HasAttrs: AstNode {
72    fn attrs(&self) -> AstChildren<ast::Attr> {
73        support::children(self.syntax())
74    }
75
76    fn doc_comments(&self) -> AstChildren<ast::DocComment> {
77        support::children(self.syntax())
78    }
79
80    fn attrs_with_doc(&self) -> AstChildren<ast::AnyAttr> {
81        support::children(self.syntax())
82    }
83
84    /// This may return the same node as called with (with `SourceFile`). The caller has the responsibility
85    /// to avoid duplicate attributes.
86    fn inner_attributes_node(&self) -> Option<SyntaxNode> {
87        let syntax = self.syntax();
88        Some(match_ast! {
89            match syntax {
90                // A `SourceFile` contains the inner attributes of itself.
91                ast::SourceFile(_) => syntax.clone(),
92                ast::ExternBlock(it) => it.extern_item_list()?.syntax().clone(),
93                ast::Fn(it) => it.body()?.stmt_list()?.syntax().clone(),
94                ast::MatchExpr(it) => it.match_arm_list()?.syntax().clone(),
95                ast::Impl(it) => it.assoc_item_list()?.syntax().clone(),
96                ast::Trait(it) => it.assoc_item_list()?.syntax().clone(),
97                ast::Module(it) => it.item_list()?.syntax().clone(),
98                ast::BlockExpr(it) => {
99                    if !it.may_carry_attributes() {
100                        return None;
101                    }
102                    syntax.clone()
103                },
104                _ => return None,
105            }
106        })
107    }
108}
109
110/// Returns all attributes of this node, including inner attributes that may not be directly under this node
111/// but under a child.
112pub fn attrs_with_doc_including_inner(
113    owner: &dyn HasAttrs,
114) -> impl Iterator<Item = ast::AnyAttr> + Clone {
115    owner.attrs_with_doc().filter(|attr| attr.kind().is_outer()).chain(
116        owner
117            .inner_attributes_node()
118            .into_iter()
119            .flat_map(|node| support::children::<ast::AnyAttr>(&node))
120            .filter(|attr| attr.kind().is_inner()),
121    )
122}
123
124pub fn attrs_including_inner(owner: &dyn HasAttrs) -> impl Iterator<Item = ast::Attr> + Clone {
125    AttrsIter::new(attrs_with_doc_including_inner(owner))
126}
127
128#[derive(Clone)]
129pub struct AttrsIter<I> {
130    inner: I,
131}
132
133impl<I: Iterator<Item = ast::AnyAttr>> AttrsIter<I> {
134    #[inline]
135    pub fn new(inner: I) -> Self {
136        Self { inner }
137    }
138}
139
140impl<I: Iterator<Item = ast::AnyAttr>> Iterator for AttrsIter<I> {
141    type Item = ast::Attr;
142
143    #[inline]
144    fn next(&mut self) -> Option<Self::Item> {
145        self.inner.find_map(|attr| match attr {
146            ast::AnyAttr::Attr(it) => Some(it),
147            ast::AnyAttr::DocComment(_) => None,
148        })
149    }
150}
151
152impl<A: HasName, B: HasName> HasName for Either<A, B> {}