]> git.lizzy.rs Git - rust.git/blob - crates/syntax/src/ast/node_ext.rs
Don't insert imports outside of cfg attributed items
[rust.git] / crates / syntax / src / ast / node_ext.rs
1 //! Various extension methods to ast Nodes, which are hard to code-generate.
2 //! Extensions for various expressions live in a sibling `expr_extensions` module.
3
4 use std::{borrow::Cow, fmt, iter::successors};
5
6 use itertools::Itertools;
7 use parser::SyntaxKind;
8 use rowan::{GreenNodeData, GreenTokenData};
9
10 use crate::{
11     ast::{self, support, AstChildren, AstNode, AstToken, AttrsOwner, NameOwner, SyntaxNode},
12     NodeOrToken, SmolStr, SyntaxElement, SyntaxToken, TokenText, T,
13 };
14
15 impl ast::Lifetime {
16     pub fn text(&self) -> TokenText<'_> {
17         text_of_first_token(self.syntax())
18     }
19 }
20
21 impl ast::Name {
22     pub fn text(&self) -> TokenText<'_> {
23         text_of_first_token(self.syntax())
24     }
25 }
26
27 impl ast::NameRef {
28     pub fn text(&self) -> TokenText<'_> {
29         text_of_first_token(self.syntax())
30     }
31
32     pub fn as_tuple_field(&self) -> Option<usize> {
33         self.text().parse().ok()
34     }
35 }
36
37 fn text_of_first_token(node: &SyntaxNode) -> TokenText<'_> {
38     fn first_token(green_ref: &GreenNodeData) -> &GreenTokenData {
39         green_ref.children().next().and_then(NodeOrToken::into_token).unwrap()
40     }
41
42     match node.green() {
43         Cow::Borrowed(green_ref) => TokenText::borrowed(first_token(green_ref).text()),
44         Cow::Owned(green) => TokenText::owned(first_token(&green).to_owned()),
45     }
46 }
47
48 impl ast::BlockExpr {
49     pub fn items(&self) -> AstChildren<ast::Item> {
50         support::children(self.syntax())
51     }
52 }
53
54 #[derive(Debug, PartialEq, Eq, Clone)]
55 pub enum Macro {
56     MacroRules(ast::MacroRules),
57     MacroDef(ast::MacroDef),
58 }
59
60 impl From<ast::MacroRules> for Macro {
61     fn from(it: ast::MacroRules) -> Self {
62         Macro::MacroRules(it)
63     }
64 }
65
66 impl From<ast::MacroDef> for Macro {
67     fn from(it: ast::MacroDef) -> Self {
68         Macro::MacroDef(it)
69     }
70 }
71
72 impl AstNode for Macro {
73     fn can_cast(kind: SyntaxKind) -> bool {
74         matches!(kind, SyntaxKind::MACRO_RULES | SyntaxKind::MACRO_DEF)
75     }
76     fn cast(syntax: SyntaxNode) -> Option<Self> {
77         let res = match syntax.kind() {
78             SyntaxKind::MACRO_RULES => Macro::MacroRules(ast::MacroRules { syntax }),
79             SyntaxKind::MACRO_DEF => Macro::MacroDef(ast::MacroDef { syntax }),
80             _ => return None,
81         };
82         Some(res)
83     }
84     fn syntax(&self) -> &SyntaxNode {
85         match self {
86             Macro::MacroRules(it) => it.syntax(),
87             Macro::MacroDef(it) => it.syntax(),
88         }
89     }
90 }
91
92 impl NameOwner for Macro {
93     fn name(&self) -> Option<ast::Name> {
94         match self {
95             Macro::MacroRules(mac) => mac.name(),
96             Macro::MacroDef(mac) => mac.name(),
97         }
98     }
99 }
100
101 impl AttrsOwner for Macro {}
102
103 /// Basically an owned `dyn AttrsOwner` without extra boxing.
104 pub struct AttrsOwnerNode {
105     node: SyntaxNode,
106 }
107
108 impl AttrsOwnerNode {
109     pub fn new<N: AttrsOwner>(node: N) -> Self {
110         AttrsOwnerNode { node: node.syntax().clone() }
111     }
112 }
113
114 impl AttrsOwner for AttrsOwnerNode {}
115 impl AstNode for AttrsOwnerNode {
116     fn can_cast(_: SyntaxKind) -> bool
117     where
118         Self: Sized,
119     {
120         false
121     }
122     fn cast(_: SyntaxNode) -> Option<Self>
123     where
124         Self: Sized,
125     {
126         None
127     }
128     fn syntax(&self) -> &SyntaxNode {
129         &self.node
130     }
131 }
132
133 #[derive(Debug, Clone, PartialEq, Eq)]
134 pub enum AttrKind {
135     Inner,
136     Outer,
137 }
138
139 impl AttrKind {
140     /// Returns `true` if the attr_kind is [`Inner`].
141     pub fn is_inner(&self) -> bool {
142         matches!(self, Self::Inner)
143     }
144
145     /// Returns `true` if the attr_kind is [`Outer`].
146     pub fn is_outer(&self) -> bool {
147         matches!(self, Self::Outer)
148     }
149 }
150
151 impl ast::Attr {
152     pub fn as_simple_atom(&self) -> Option<SmolStr> {
153         let meta = self.meta()?;
154         if meta.eq_token().is_some() || meta.token_tree().is_some() {
155             return None;
156         }
157         self.simple_name()
158     }
159
160     pub fn as_simple_call(&self) -> Option<(SmolStr, ast::TokenTree)> {
161         let tt = self.meta()?.token_tree()?;
162         Some((self.simple_name()?, tt))
163     }
164
165     pub fn simple_name(&self) -> Option<SmolStr> {
166         let path = self.meta()?.path()?;
167         match (path.segment(), path.qualifier()) {
168             (Some(segment), None) => Some(segment.syntax().first_token()?.text().into()),
169             _ => None,
170         }
171     }
172
173     pub fn kind(&self) -> AttrKind {
174         let first_token = self.syntax().first_token();
175         let first_token_kind = first_token.as_ref().map(SyntaxToken::kind);
176         let second_token_kind =
177             first_token.and_then(|token| token.next_token()).as_ref().map(SyntaxToken::kind);
178
179         match (first_token_kind, second_token_kind) {
180             (Some(T![#]), Some(T![!])) => AttrKind::Inner,
181             _ => AttrKind::Outer,
182         }
183     }
184
185     pub fn path(&self) -> Option<ast::Path> {
186         self.meta()?.path()
187     }
188
189     pub fn expr(&self) -> Option<ast::Expr> {
190         self.meta()?.expr()
191     }
192
193     pub fn token_tree(&self) -> Option<ast::TokenTree> {
194         self.meta()?.token_tree()
195     }
196 }
197
198 #[derive(Debug, Clone, PartialEq, Eq)]
199 pub enum PathSegmentKind {
200     Name(ast::NameRef),
201     Type { type_ref: Option<ast::Type>, trait_ref: Option<ast::PathType> },
202     SelfKw,
203     SuperKw,
204     CrateKw,
205 }
206
207 impl ast::PathSegment {
208     pub fn parent_path(&self) -> ast::Path {
209         self.syntax()
210             .parent()
211             .and_then(ast::Path::cast)
212             .expect("segments are always nested in paths")
213     }
214
215     pub fn crate_token(&self) -> Option<SyntaxToken> {
216         self.name_ref().and_then(|it| it.crate_token())
217     }
218
219     pub fn self_token(&self) -> Option<SyntaxToken> {
220         self.name_ref().and_then(|it| it.self_token())
221     }
222
223     pub fn super_token(&self) -> Option<SyntaxToken> {
224         self.name_ref().and_then(|it| it.super_token())
225     }
226
227     pub fn kind(&self) -> Option<PathSegmentKind> {
228         let res = if let Some(name_ref) = self.name_ref() {
229             match name_ref.syntax().first_token().map(|it| it.kind()) {
230                 Some(T![self]) => PathSegmentKind::SelfKw,
231                 Some(T![super]) => PathSegmentKind::SuperKw,
232                 Some(T![crate]) => PathSegmentKind::CrateKw,
233                 _ => PathSegmentKind::Name(name_ref),
234             }
235         } else {
236             match self.syntax().first_child_or_token()?.kind() {
237                 T![<] => {
238                     // <T> or <T as Trait>
239                     // T is any TypeRef, Trait has to be a PathType
240                     let mut type_refs =
241                         self.syntax().children().filter(|node| ast::Type::can_cast(node.kind()));
242                     let type_ref = type_refs.next().and_then(ast::Type::cast);
243                     let trait_ref = type_refs.next().and_then(ast::PathType::cast);
244                     PathSegmentKind::Type { type_ref, trait_ref }
245                 }
246                 _ => return None,
247             }
248         };
249         Some(res)
250     }
251 }
252
253 impl ast::Path {
254     pub fn parent_path(&self) -> Option<ast::Path> {
255         self.syntax().parent().and_then(ast::Path::cast)
256     }
257
258     pub fn as_single_segment(&self) -> Option<ast::PathSegment> {
259         match self.qualifier() {
260             Some(_) => None,
261             None => self.segment(),
262         }
263     }
264
265     pub fn as_single_name_ref(&self) -> Option<ast::NameRef> {
266         match self.qualifier() {
267             Some(_) => None,
268             None => self.segment()?.name_ref(),
269         }
270     }
271
272     pub fn first_qualifier_or_self(&self) -> ast::Path {
273         successors(Some(self.clone()), ast::Path::qualifier).last().unwrap()
274     }
275
276     pub fn first_segment(&self) -> Option<ast::PathSegment> {
277         self.first_qualifier_or_self().segment()
278     }
279
280     pub fn segments(&self) -> impl Iterator<Item = ast::PathSegment> + Clone {
281         successors(self.first_segment(), |p| {
282             p.parent_path().parent_path().and_then(|p| p.segment())
283         })
284     }
285
286     pub fn qualifiers(&self) -> impl Iterator<Item = ast::Path> + Clone {
287         successors(self.qualifier(), |p| p.qualifier())
288     }
289 }
290
291 impl ast::Use {
292     pub fn is_simple_glob(&self) -> bool {
293         self.use_tree()
294             .map(|use_tree| use_tree.use_tree_list().is_none() && use_tree.star_token().is_some())
295             .unwrap_or(false)
296     }
297 }
298
299 impl ast::UseTree {
300     pub fn is_simple_path(&self) -> bool {
301         self.use_tree_list().is_none() && self.star_token().is_none()
302     }
303 }
304
305 impl ast::UseTreeList {
306     pub fn parent_use_tree(&self) -> ast::UseTree {
307         self.syntax()
308             .parent()
309             .and_then(ast::UseTree::cast)
310             .expect("UseTreeLists are always nested in UseTrees")
311     }
312
313     pub fn has_inner_comment(&self) -> bool {
314         self.syntax()
315             .children_with_tokens()
316             .filter_map(|it| it.into_token())
317             .find_map(ast::Comment::cast)
318             .is_some()
319     }
320 }
321
322 impl ast::Impl {
323     pub fn self_ty(&self) -> Option<ast::Type> {
324         match self.target() {
325             (Some(t), None) | (_, Some(t)) => Some(t),
326             _ => None,
327         }
328     }
329
330     pub fn trait_(&self) -> Option<ast::Type> {
331         match self.target() {
332             (Some(t), Some(_)) => Some(t),
333             _ => None,
334         }
335     }
336
337     fn target(&self) -> (Option<ast::Type>, Option<ast::Type>) {
338         let mut types = support::children(self.syntax());
339         let first = types.next();
340         let second = types.next();
341         (first, second)
342     }
343
344     pub fn for_trait_name_ref(name_ref: &ast::NameRef) -> Option<ast::Impl> {
345         let this = name_ref.syntax().ancestors().find_map(ast::Impl::cast)?;
346         if this.trait_()?.syntax().text_range().start() == name_ref.syntax().text_range().start() {
347             Some(this)
348         } else {
349             None
350         }
351     }
352 }
353
354 #[derive(Debug, Clone, PartialEq, Eq)]
355 pub enum StructKind {
356     Record(ast::RecordFieldList),
357     Tuple(ast::TupleFieldList),
358     Unit,
359 }
360
361 impl StructKind {
362     fn from_node<N: AstNode>(node: &N) -> StructKind {
363         if let Some(nfdl) = support::child::<ast::RecordFieldList>(node.syntax()) {
364             StructKind::Record(nfdl)
365         } else if let Some(pfl) = support::child::<ast::TupleFieldList>(node.syntax()) {
366             StructKind::Tuple(pfl)
367         } else {
368             StructKind::Unit
369         }
370     }
371 }
372
373 impl ast::Struct {
374     pub fn kind(&self) -> StructKind {
375         StructKind::from_node(self)
376     }
377 }
378
379 impl ast::RecordExprField {
380     pub fn for_field_name(field_name: &ast::NameRef) -> Option<ast::RecordExprField> {
381         let candidate = Self::for_name_ref(field_name)?;
382         if candidate.field_name().as_ref() == Some(field_name) {
383             Some(candidate)
384         } else {
385             None
386         }
387     }
388
389     pub fn for_name_ref(name_ref: &ast::NameRef) -> Option<ast::RecordExprField> {
390         let syn = name_ref.syntax();
391         syn.parent()
392             .and_then(ast::RecordExprField::cast)
393             .or_else(|| syn.ancestors().nth(4).and_then(ast::RecordExprField::cast))
394     }
395
396     /// Deals with field init shorthand
397     pub fn field_name(&self) -> Option<ast::NameRef> {
398         if let Some(name_ref) = self.name_ref() {
399             return Some(name_ref);
400         }
401         self.expr()?.name_ref()
402     }
403 }
404
405 #[derive(Debug, Clone)]
406 pub enum NameLike {
407     NameRef(ast::NameRef),
408     Name(ast::Name),
409     Lifetime(ast::Lifetime),
410 }
411
412 impl NameLike {
413     pub fn as_name_ref(&self) -> Option<&ast::NameRef> {
414         match self {
415             NameLike::NameRef(name_ref) => Some(name_ref),
416             _ => None,
417         }
418     }
419 }
420
421 impl ast::AstNode for NameLike {
422     fn can_cast(kind: SyntaxKind) -> bool {
423         matches!(kind, SyntaxKind::NAME | SyntaxKind::NAME_REF | SyntaxKind::LIFETIME)
424     }
425     fn cast(syntax: SyntaxNode) -> Option<Self> {
426         let res = match syntax.kind() {
427             SyntaxKind::NAME => NameLike::Name(ast::Name { syntax }),
428             SyntaxKind::NAME_REF => NameLike::NameRef(ast::NameRef { syntax }),
429             SyntaxKind::LIFETIME => NameLike::Lifetime(ast::Lifetime { syntax }),
430             _ => return None,
431         };
432         Some(res)
433     }
434     fn syntax(&self) -> &SyntaxNode {
435         match self {
436             NameLike::NameRef(it) => it.syntax(),
437             NameLike::Name(it) => it.syntax(),
438             NameLike::Lifetime(it) => it.syntax(),
439         }
440     }
441 }
442
443 mod __ {
444     use super::{
445         ast::{Lifetime, Name, NameRef},
446         NameLike,
447     };
448     stdx::impl_from!(NameRef, Name, Lifetime for NameLike);
449 }
450
451 #[derive(Debug, Clone, PartialEq)]
452 pub enum NameOrNameRef {
453     Name(ast::Name),
454     NameRef(ast::NameRef),
455 }
456
457 impl fmt::Display for NameOrNameRef {
458     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
459         match self {
460             NameOrNameRef::Name(it) => fmt::Display::fmt(it, f),
461             NameOrNameRef::NameRef(it) => fmt::Display::fmt(it, f),
462         }
463     }
464 }
465
466 impl NameOrNameRef {
467     pub fn text(&self) -> TokenText<'_> {
468         match self {
469             NameOrNameRef::Name(name) => name.text(),
470             NameOrNameRef::NameRef(name_ref) => name_ref.text(),
471         }
472     }
473 }
474
475 impl ast::RecordPatField {
476     pub fn for_field_name_ref(field_name: &ast::NameRef) -> Option<ast::RecordPatField> {
477         let candidate = field_name.syntax().parent().and_then(ast::RecordPatField::cast)?;
478         match candidate.field_name()? {
479             NameOrNameRef::NameRef(name_ref) if name_ref == *field_name => Some(candidate),
480             _ => None,
481         }
482     }
483
484     pub fn for_field_name(field_name: &ast::Name) -> Option<ast::RecordPatField> {
485         let candidate =
486             field_name.syntax().ancestors().nth(2).and_then(ast::RecordPatField::cast)?;
487         match candidate.field_name()? {
488             NameOrNameRef::Name(name) if name == *field_name => Some(candidate),
489             _ => None,
490         }
491     }
492
493     /// Deals with field init shorthand
494     pub fn field_name(&self) -> Option<NameOrNameRef> {
495         if let Some(name_ref) = self.name_ref() {
496             return Some(NameOrNameRef::NameRef(name_ref));
497         }
498         match self.pat() {
499             Some(ast::Pat::IdentPat(pat)) => {
500                 let name = pat.name()?;
501                 Some(NameOrNameRef::Name(name))
502             }
503             Some(ast::Pat::BoxPat(pat)) => match pat.pat() {
504                 Some(ast::Pat::IdentPat(pat)) => {
505                     let name = pat.name()?;
506                     Some(NameOrNameRef::Name(name))
507                 }
508                 _ => None,
509             },
510             _ => None,
511         }
512     }
513 }
514
515 impl ast::Variant {
516     pub fn parent_enum(&self) -> ast::Enum {
517         self.syntax()
518             .parent()
519             .and_then(|it| it.parent())
520             .and_then(ast::Enum::cast)
521             .expect("EnumVariants are always nested in Enums")
522     }
523     pub fn kind(&self) -> StructKind {
524         StructKind::from_node(self)
525     }
526 }
527
528 #[derive(Debug, Clone, PartialEq, Eq)]
529 pub enum FieldKind {
530     Name(ast::NameRef),
531     Index(SyntaxToken),
532 }
533
534 impl ast::FieldExpr {
535     pub fn index_token(&self) -> Option<SyntaxToken> {
536         self.syntax
537             .children_with_tokens()
538             // FIXME: Accepting floats here to reject them in validation later
539             .find(|c| c.kind() == SyntaxKind::INT_NUMBER || c.kind() == SyntaxKind::FLOAT_NUMBER)
540             .as_ref()
541             .and_then(SyntaxElement::as_token)
542             .cloned()
543     }
544
545     pub fn field_access(&self) -> Option<FieldKind> {
546         if let Some(nr) = self.name_ref() {
547             Some(FieldKind::Name(nr))
548         } else {
549             self.index_token().map(FieldKind::Index)
550         }
551     }
552 }
553
554 pub struct SlicePatComponents {
555     pub prefix: Vec<ast::Pat>,
556     pub slice: Option<ast::Pat>,
557     pub suffix: Vec<ast::Pat>,
558 }
559
560 impl ast::SlicePat {
561     pub fn components(&self) -> SlicePatComponents {
562         let mut args = self.pats().peekable();
563         let prefix = args
564             .peeking_take_while(|p| match p {
565                 ast::Pat::RestPat(_) => false,
566                 ast::Pat::IdentPat(bp) => !matches!(bp.pat(), Some(ast::Pat::RestPat(_))),
567                 ast::Pat::RefPat(rp) => match rp.pat() {
568                     Some(ast::Pat::RestPat(_)) => false,
569                     Some(ast::Pat::IdentPat(bp)) => !matches!(bp.pat(), Some(ast::Pat::RestPat(_))),
570                     _ => true,
571                 },
572                 _ => true,
573             })
574             .collect();
575         let slice = args.next();
576         let suffix = args.collect();
577
578         SlicePatComponents { prefix, slice, suffix }
579     }
580 }
581
582 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
583 pub enum SelfParamKind {
584     /// self
585     Owned,
586     /// &self
587     Ref,
588     /// &mut self
589     MutRef,
590 }
591
592 impl ast::SelfParam {
593     pub fn kind(&self) -> SelfParamKind {
594         if self.amp_token().is_some() {
595             if self.mut_token().is_some() {
596                 SelfParamKind::MutRef
597             } else {
598                 SelfParamKind::Ref
599             }
600         } else {
601             SelfParamKind::Owned
602         }
603     }
604 }
605
606 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
607 pub enum TypeBoundKind {
608     /// Trait
609     PathType(ast::PathType),
610     /// for<'a> ...
611     ForType(ast::ForType),
612     /// 'a
613     Lifetime(ast::Lifetime),
614 }
615
616 impl ast::TypeBound {
617     pub fn kind(&self) -> TypeBoundKind {
618         if let Some(path_type) = support::children(self.syntax()).next() {
619             TypeBoundKind::PathType(path_type)
620         } else if let Some(for_type) = support::children(self.syntax()).next() {
621             TypeBoundKind::ForType(for_type)
622         } else if let Some(lifetime) = self.lifetime() {
623             TypeBoundKind::Lifetime(lifetime)
624         } else {
625             unreachable!()
626         }
627     }
628 }
629
630 pub enum VisibilityKind {
631     In(ast::Path),
632     PubCrate,
633     PubSuper,
634     PubSelf,
635     Pub,
636 }
637
638 impl ast::Visibility {
639     pub fn kind(&self) -> VisibilityKind {
640         match self.path() {
641             Some(path) => {
642                 if let Some(segment) =
643                     path.as_single_segment().filter(|it| it.coloncolon_token().is_none())
644                 {
645                     if segment.crate_token().is_some() {
646                         return VisibilityKind::PubCrate;
647                     } else if segment.super_token().is_some() {
648                         return VisibilityKind::PubSuper;
649                     } else if segment.self_token().is_some() {
650                         return VisibilityKind::PubSelf;
651                     }
652                 }
653                 VisibilityKind::In(path)
654             }
655             None => VisibilityKind::Pub,
656         }
657     }
658
659     pub fn is_eq_to(&self, other: &Self) -> bool {
660         match (self.kind(), other.kind()) {
661             (VisibilityKind::In(this), VisibilityKind::In(other)) => {
662                 stdx::iter_eq_by(this.segments(), other.segments(), |lhs, rhs| {
663                     lhs.kind().zip(rhs.kind()).map_or(false, |it| match it {
664                         (PathSegmentKind::CrateKw, PathSegmentKind::CrateKw)
665                         | (PathSegmentKind::SelfKw, PathSegmentKind::SelfKw)
666                         | (PathSegmentKind::SuperKw, PathSegmentKind::SuperKw) => true,
667                         (PathSegmentKind::Name(lhs), PathSegmentKind::Name(rhs)) => {
668                             lhs.text() == rhs.text()
669                         }
670                         _ => false,
671                     })
672                 })
673             }
674             (VisibilityKind::PubSelf, VisibilityKind::PubSelf)
675             | (VisibilityKind::PubSuper, VisibilityKind::PubSuper)
676             | (VisibilityKind::PubCrate, VisibilityKind::PubCrate)
677             | (VisibilityKind::Pub, VisibilityKind::Pub) => true,
678             _ => false,
679         }
680     }
681 }
682
683 impl ast::LifetimeParam {
684     pub fn lifetime_bounds(&self) -> impl Iterator<Item = SyntaxToken> {
685         self.syntax()
686             .children_with_tokens()
687             .filter_map(|it| it.into_token())
688             .skip_while(|x| x.kind() != T![:])
689             .filter(|it| it.kind() == T![lifetime_ident])
690     }
691 }
692
693 impl ast::Module {
694     /// Returns the parent ast::Module, this is different than the semantic parent in that this only
695     /// considers parent declarations in the AST
696     pub fn parent(&self) -> Option<ast::Module> {
697         self.syntax().ancestors().nth(2).and_then(ast::Module::cast)
698     }
699 }
700
701 impl ast::RangePat {
702     pub fn start(&self) -> Option<ast::Pat> {
703         self.syntax()
704             .children_with_tokens()
705             .take_while(|it| !(it.kind() == T![..] || it.kind() == T![..=]))
706             .filter_map(|it| it.into_node())
707             .find_map(ast::Pat::cast)
708     }
709
710     pub fn end(&self) -> Option<ast::Pat> {
711         self.syntax()
712             .children_with_tokens()
713             .skip_while(|it| !(it.kind() == T![..] || it.kind() == T![..=]))
714             .filter_map(|it| it.into_node())
715             .find_map(ast::Pat::cast)
716     }
717 }
718
719 impl ast::TokenTree {
720     pub fn left_delimiter_token(&self) -> Option<SyntaxToken> {
721         self.syntax()
722             .first_child_or_token()?
723             .into_token()
724             .filter(|it| matches!(it.kind(), T!['{'] | T!['('] | T!['[']))
725     }
726
727     pub fn right_delimiter_token(&self) -> Option<SyntaxToken> {
728         self.syntax()
729             .last_child_or_token()?
730             .into_token()
731             .filter(|it| matches!(it.kind(), T!['}'] | T![')'] | T![']']))
732     }
733 }
734
735 impl ast::GenericParamList {
736     pub fn lifetime_params(&self) -> impl Iterator<Item = ast::LifetimeParam> {
737         self.generic_params().filter_map(|param| match param {
738             ast::GenericParam::LifetimeParam(it) => Some(it),
739             ast::GenericParam::TypeParam(_) | ast::GenericParam::ConstParam(_) => None,
740         })
741     }
742     pub fn type_params(&self) -> impl Iterator<Item = ast::TypeParam> {
743         self.generic_params().filter_map(|param| match param {
744             ast::GenericParam::TypeParam(it) => Some(it),
745             ast::GenericParam::LifetimeParam(_) | ast::GenericParam::ConstParam(_) => None,
746         })
747     }
748     pub fn const_params(&self) -> impl Iterator<Item = ast::ConstParam> {
749         self.generic_params().filter_map(|param| match param {
750             ast::GenericParam::ConstParam(it) => Some(it),
751             ast::GenericParam::TypeParam(_) | ast::GenericParam::LifetimeParam(_) => None,
752         })
753     }
754 }
755
756 impl ast::DocCommentsOwner for ast::SourceFile {}
757 impl ast::DocCommentsOwner for ast::Fn {}
758 impl ast::DocCommentsOwner for ast::Struct {}
759 impl ast::DocCommentsOwner for ast::Union {}
760 impl ast::DocCommentsOwner for ast::RecordField {}
761 impl ast::DocCommentsOwner for ast::TupleField {}
762 impl ast::DocCommentsOwner for ast::Enum {}
763 impl ast::DocCommentsOwner for ast::Variant {}
764 impl ast::DocCommentsOwner for ast::Trait {}
765 impl ast::DocCommentsOwner for ast::Module {}
766 impl ast::DocCommentsOwner for ast::Static {}
767 impl ast::DocCommentsOwner for ast::Const {}
768 impl ast::DocCommentsOwner for ast::TypeAlias {}
769 impl ast::DocCommentsOwner for ast::Impl {}
770 impl ast::DocCommentsOwner for ast::MacroRules {}
771 impl ast::DocCommentsOwner for ast::MacroDef {}
772 impl ast::DocCommentsOwner for ast::Macro {}
773 impl ast::DocCommentsOwner for ast::Use {}