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.
4 use std::{borrow::Cow, fmt, iter::successors};
6 use itertools::Itertools;
7 use parser::SyntaxKind;
8 use rowan::{GreenNodeData, GreenTokenData};
11 ast::{self, support, AstChildren, AstNode, AstToken, AttrsOwner, NameOwner, SyntaxNode},
12 NodeOrToken, SmolStr, SyntaxElement, SyntaxToken, TokenText, T,
16 pub fn text(&self) -> TokenText<'_> {
17 text_of_first_token(self.syntax())
22 pub fn text(&self) -> TokenText<'_> {
23 text_of_first_token(self.syntax())
28 pub fn text(&self) -> TokenText<'_> {
29 text_of_first_token(self.syntax())
32 pub fn as_tuple_field(&self) -> Option<usize> {
33 self.text().parse().ok()
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()
43 Cow::Borrowed(green_ref) => TokenText::borrowed(first_token(green_ref).text()),
44 Cow::Owned(green) => TokenText::owned(first_token(&green).to_owned()),
49 pub fn items(&self) -> AstChildren<ast::Item> {
50 support::children(self.syntax())
54 #[derive(Debug, PartialEq, Eq, Clone)]
56 MacroRules(ast::MacroRules),
57 MacroDef(ast::MacroDef),
60 impl From<ast::MacroRules> for Macro {
61 fn from(it: ast::MacroRules) -> Self {
66 impl From<ast::MacroDef> for Macro {
67 fn from(it: ast::MacroDef) -> Self {
72 impl AstNode for Macro {
73 fn can_cast(kind: SyntaxKind) -> bool {
74 matches!(kind, SyntaxKind::MACRO_RULES | SyntaxKind::MACRO_DEF)
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 }),
84 fn syntax(&self) -> &SyntaxNode {
86 Macro::MacroRules(it) => it.syntax(),
87 Macro::MacroDef(it) => it.syntax(),
92 impl NameOwner for Macro {
93 fn name(&self) -> Option<ast::Name> {
95 Macro::MacroRules(mac) => mac.name(),
96 Macro::MacroDef(mac) => mac.name(),
101 impl AttrsOwner for Macro {}
103 /// Basically an owned `dyn AttrsOwner` without extra boxing.
104 pub struct AttrsOwnerNode {
108 impl AttrsOwnerNode {
109 pub fn new<N: AttrsOwner>(node: N) -> Self {
110 AttrsOwnerNode { node: node.syntax().clone() }
114 impl AttrsOwner for AttrsOwnerNode {}
115 impl AstNode for AttrsOwnerNode {
116 fn can_cast(_: SyntaxKind) -> bool
122 fn cast(_: SyntaxNode) -> Option<Self>
128 fn syntax(&self) -> &SyntaxNode {
133 #[derive(Debug, Clone, PartialEq, Eq)]
140 /// Returns `true` if the attr_kind is [`Inner`].
141 pub fn is_inner(&self) -> bool {
142 matches!(self, Self::Inner)
145 /// Returns `true` if the attr_kind is [`Outer`].
146 pub fn is_outer(&self) -> bool {
147 matches!(self, Self::Outer)
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() {
160 pub fn as_simple_call(&self) -> Option<(SmolStr, ast::TokenTree)> {
161 let tt = self.meta()?.token_tree()?;
162 Some((self.simple_name()?, tt))
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()),
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);
179 match (first_token_kind, second_token_kind) {
180 (Some(T![#]), Some(T![!])) => AttrKind::Inner,
181 _ => AttrKind::Outer,
185 pub fn path(&self) -> Option<ast::Path> {
189 pub fn expr(&self) -> Option<ast::Expr> {
193 pub fn token_tree(&self) -> Option<ast::TokenTree> {
194 self.meta()?.token_tree()
198 #[derive(Debug, Clone, PartialEq, Eq)]
199 pub enum PathSegmentKind {
201 Type { type_ref: Option<ast::Type>, trait_ref: Option<ast::PathType> },
207 impl ast::PathSegment {
208 pub fn parent_path(&self) -> ast::Path {
211 .and_then(ast::Path::cast)
212 .expect("segments are always nested in paths")
215 pub fn crate_token(&self) -> Option<SyntaxToken> {
216 self.name_ref().and_then(|it| it.crate_token())
219 pub fn self_token(&self) -> Option<SyntaxToken> {
220 self.name_ref().and_then(|it| it.self_token())
223 pub fn super_token(&self) -> Option<SyntaxToken> {
224 self.name_ref().and_then(|it| it.super_token())
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),
236 match self.syntax().first_child_or_token()?.kind() {
238 // <T> or <T as Trait>
239 // T is any TypeRef, Trait has to be a PathType
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 }
254 pub fn parent_path(&self) -> Option<ast::Path> {
255 self.syntax().parent().and_then(ast::Path::cast)
258 pub fn as_single_segment(&self) -> Option<ast::PathSegment> {
259 match self.qualifier() {
261 None => self.segment(),
265 pub fn as_single_name_ref(&self) -> Option<ast::NameRef> {
266 match self.qualifier() {
268 None => self.segment()?.name_ref(),
272 pub fn first_qualifier_or_self(&self) -> ast::Path {
273 successors(Some(self.clone()), ast::Path::qualifier).last().unwrap()
276 pub fn first_segment(&self) -> Option<ast::PathSegment> {
277 self.first_qualifier_or_self().segment()
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())
286 pub fn qualifiers(&self) -> impl Iterator<Item = ast::Path> + Clone {
287 successors(self.qualifier(), |p| p.qualifier())
292 pub fn is_simple_glob(&self) -> bool {
294 .map(|use_tree| use_tree.use_tree_list().is_none() && use_tree.star_token().is_some())
300 pub fn is_simple_path(&self) -> bool {
301 self.use_tree_list().is_none() && self.star_token().is_none()
305 impl ast::UseTreeList {
306 pub fn parent_use_tree(&self) -> ast::UseTree {
309 .and_then(ast::UseTree::cast)
310 .expect("UseTreeLists are always nested in UseTrees")
313 pub fn has_inner_comment(&self) -> bool {
315 .children_with_tokens()
316 .filter_map(|it| it.into_token())
317 .find_map(ast::Comment::cast)
323 pub fn self_ty(&self) -> Option<ast::Type> {
324 match self.target() {
325 (Some(t), None) | (_, Some(t)) => Some(t),
330 pub fn trait_(&self) -> Option<ast::Type> {
331 match self.target() {
332 (Some(t), Some(_)) => Some(t),
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();
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() {
354 #[derive(Debug, Clone, PartialEq, Eq)]
355 pub enum StructKind {
356 Record(ast::RecordFieldList),
357 Tuple(ast::TupleFieldList),
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)
374 pub fn kind(&self) -> StructKind {
375 StructKind::from_node(self)
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) {
389 pub fn for_name_ref(name_ref: &ast::NameRef) -> Option<ast::RecordExprField> {
390 let syn = name_ref.syntax();
392 .and_then(ast::RecordExprField::cast)
393 .or_else(|| syn.ancestors().nth(4).and_then(ast::RecordExprField::cast))
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);
401 self.expr()?.name_ref()
405 #[derive(Debug, Clone)]
407 NameRef(ast::NameRef),
409 Lifetime(ast::Lifetime),
413 pub fn as_name_ref(&self) -> Option<&ast::NameRef> {
415 NameLike::NameRef(name_ref) => Some(name_ref),
421 impl ast::AstNode for NameLike {
422 fn can_cast(kind: SyntaxKind) -> bool {
423 matches!(kind, SyntaxKind::NAME | SyntaxKind::NAME_REF | SyntaxKind::LIFETIME)
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 }),
434 fn syntax(&self) -> &SyntaxNode {
436 NameLike::NameRef(it) => it.syntax(),
437 NameLike::Name(it) => it.syntax(),
438 NameLike::Lifetime(it) => it.syntax(),
445 ast::{Lifetime, Name, NameRef},
448 stdx::impl_from!(NameRef, Name, Lifetime for NameLike);
451 #[derive(Debug, Clone, PartialEq)]
452 pub enum NameOrNameRef {
454 NameRef(ast::NameRef),
457 impl fmt::Display for NameOrNameRef {
458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
460 NameOrNameRef::Name(it) => fmt::Display::fmt(it, f),
461 NameOrNameRef::NameRef(it) => fmt::Display::fmt(it, f),
467 pub fn text(&self) -> TokenText<'_> {
469 NameOrNameRef::Name(name) => name.text(),
470 NameOrNameRef::NameRef(name_ref) => name_ref.text(),
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),
484 pub fn for_field_name(field_name: &ast::Name) -> Option<ast::RecordPatField> {
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),
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));
499 Some(ast::Pat::IdentPat(pat)) => {
500 let name = pat.name()?;
501 Some(NameOrNameRef::Name(name))
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))
516 pub fn parent_enum(&self) -> ast::Enum {
519 .and_then(|it| it.parent())
520 .and_then(ast::Enum::cast)
521 .expect("EnumVariants are always nested in Enums")
523 pub fn kind(&self) -> StructKind {
524 StructKind::from_node(self)
528 #[derive(Debug, Clone, PartialEq, Eq)]
534 impl ast::FieldExpr {
535 pub fn index_token(&self) -> Option<SyntaxToken> {
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)
541 .and_then(SyntaxElement::as_token)
545 pub fn field_access(&self) -> Option<FieldKind> {
546 if let Some(nr) = self.name_ref() {
547 Some(FieldKind::Name(nr))
549 self.index_token().map(FieldKind::Index)
554 pub struct SlicePatComponents {
555 pub prefix: Vec<ast::Pat>,
556 pub slice: Option<ast::Pat>,
557 pub suffix: Vec<ast::Pat>,
561 pub fn components(&self) -> SlicePatComponents {
562 let mut args = self.pats().peekable();
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(_))),
575 let slice = args.next();
576 let suffix = args.collect();
578 SlicePatComponents { prefix, slice, suffix }
582 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
583 pub enum SelfParamKind {
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
606 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
607 pub enum TypeBoundKind {
609 PathType(ast::PathType),
611 ForType(ast::ForType),
613 Lifetime(ast::Lifetime),
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)
630 pub enum VisibilityKind {
638 impl ast::Visibility {
639 pub fn kind(&self) -> VisibilityKind {
642 if let Some(segment) =
643 path.as_single_segment().filter(|it| it.coloncolon_token().is_none())
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;
653 VisibilityKind::In(path)
655 None => VisibilityKind::Pub,
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()
674 (VisibilityKind::PubSelf, VisibilityKind::PubSelf)
675 | (VisibilityKind::PubSuper, VisibilityKind::PubSuper)
676 | (VisibilityKind::PubCrate, VisibilityKind::PubCrate)
677 | (VisibilityKind::Pub, VisibilityKind::Pub) => true,
683 impl ast::LifetimeParam {
684 pub fn lifetime_bounds(&self) -> impl Iterator<Item = SyntaxToken> {
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])
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)
702 pub fn start(&self) -> Option<ast::Pat> {
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)
710 pub fn end(&self) -> Option<ast::Pat> {
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)
719 impl ast::TokenTree {
720 pub fn left_delimiter_token(&self) -> Option<SyntaxToken> {
722 .first_child_or_token()?
724 .filter(|it| matches!(it.kind(), T!['{'] | T!['('] | T!['[']))
727 pub fn right_delimiter_token(&self) -> Option<SyntaxToken> {
729 .last_child_or_token()?
731 .filter(|it| matches!(it.kind(), T!['}'] | T![')'] | T![']']))
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,
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,
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,
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 {}