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.
7 use itertools::Itertools;
8 use parser::SyntaxKind;
11 ast::{self, support, AstNode, AstToken, NameOwner, SyntaxNode},
12 SmolStr, SyntaxElement, SyntaxToken, T,
16 pub fn text(&self) -> &SmolStr {
17 text_of_first_token(self.syntax())
22 pub fn text(&self) -> &SmolStr {
23 text_of_first_token(self.syntax())
28 pub fn text(&self) -> &SmolStr {
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) -> &SmolStr {
38 node.green().children().next().and_then(|it| it.into_token()).unwrap().text()
42 MacroRules(ast::MacroRules),
43 MacroDef(ast::MacroDef),
46 impl From<ast::MacroRules> for Macro {
47 fn from(it: ast::MacroRules) -> Self {
52 impl From<ast::MacroDef> for Macro {
53 fn from(it: ast::MacroDef) -> Self {
58 impl AstNode for Macro {
59 fn can_cast(kind: SyntaxKind) -> bool {
61 SyntaxKind::MACRO_RULES | SyntaxKind::MACRO_DEF => true,
65 fn cast(syntax: SyntaxNode) -> Option<Self> {
66 let res = match syntax.kind() {
67 SyntaxKind::MACRO_RULES => Macro::MacroRules(ast::MacroRules { syntax }),
68 SyntaxKind::MACRO_DEF => Macro::MacroDef(ast::MacroDef { syntax }),
73 fn syntax(&self) -> &SyntaxNode {
75 Macro::MacroRules(it) => it.syntax(),
76 Macro::MacroDef(it) => it.syntax(),
81 impl NameOwner for Macro {
82 fn name(&self) -> Option<ast::Name> {
84 Macro::MacroRules(mac) => mac.name(),
85 Macro::MacroDef(mac) => mac.name(),
90 impl AttrsOwner for Macro {}
92 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub fn as_simple_atom(&self) -> Option<SmolStr> {
100 if self.eq_token().is_some() || self.token_tree().is_some() {
106 pub fn as_simple_call(&self) -> Option<(SmolStr, ast::TokenTree)> {
107 let tt = self.token_tree()?;
108 Some((self.simple_name()?, tt))
111 pub fn as_simple_key_value(&self) -> Option<(SmolStr, SmolStr)> {
112 let lit = self.literal()?;
113 let key = self.simple_name()?;
114 let value_token = lit.syntax().first_token()?;
116 let value: SmolStr = ast::String::cast(value_token)?.value()?.into();
121 pub fn simple_name(&self) -> Option<SmolStr> {
122 let path = self.path()?;
123 match (path.segment(), path.qualifier()) {
124 (Some(segment), None) => Some(segment.syntax().first_token()?.text().clone()),
129 pub fn kind(&self) -> AttrKind {
130 let first_token = self.syntax().first_token();
131 let first_token_kind = first_token.as_ref().map(SyntaxToken::kind);
132 let second_token_kind =
133 first_token.and_then(|token| token.next_token()).as_ref().map(SyntaxToken::kind);
135 match (first_token_kind, second_token_kind) {
136 (Some(SyntaxKind::POUND), Some(T![!])) => AttrKind::Inner,
137 _ => AttrKind::Outer,
142 #[derive(Debug, Clone, PartialEq, Eq)]
143 pub enum PathSegmentKind {
145 Type { type_ref: Option<ast::Type>, trait_ref: Option<ast::PathType> },
151 impl ast::PathSegment {
152 pub fn parent_path(&self) -> ast::Path {
155 .and_then(ast::Path::cast)
156 .expect("segments are always nested in paths")
159 pub fn kind(&self) -> Option<PathSegmentKind> {
160 let res = if let Some(name_ref) = self.name_ref() {
161 PathSegmentKind::Name(name_ref)
163 match self.syntax().first_child_or_token()?.kind() {
164 T![self] => PathSegmentKind::SelfKw,
165 T![super] => PathSegmentKind::SuperKw,
166 T![crate] => PathSegmentKind::CrateKw,
168 // <T> or <T as Trait>
169 // T is any TypeRef, Trait has to be a PathType
171 self.syntax().children().filter(|node| ast::Type::can_cast(node.kind()));
172 let type_ref = type_refs.next().and_then(ast::Type::cast);
173 let trait_ref = type_refs.next().and_then(ast::PathType::cast);
174 PathSegmentKind::Type { type_ref, trait_ref }
184 pub fn parent_path(&self) -> Option<ast::Path> {
185 self.syntax().parent().and_then(ast::Path::cast)
189 impl ast::UseTreeList {
190 pub fn parent_use_tree(&self) -> ast::UseTree {
193 .and_then(ast::UseTree::cast)
194 .expect("UseTreeLists are always nested in UseTrees")
197 pub fn has_inner_comment(&self) -> bool {
199 .children_with_tokens()
200 .filter_map(|it| it.into_token())
201 .find_map(ast::Comment::cast)
207 pub fn self_ty(&self) -> Option<ast::Type> {
208 match self.target() {
209 (Some(t), None) | (_, Some(t)) => Some(t),
214 pub fn trait_(&self) -> Option<ast::Type> {
215 match self.target() {
216 (Some(t), Some(_)) => Some(t),
221 fn target(&self) -> (Option<ast::Type>, Option<ast::Type>) {
222 let mut types = support::children(self.syntax());
223 let first = types.next();
224 let second = types.next();
229 #[derive(Debug, Clone, PartialEq, Eq)]
230 pub enum StructKind {
231 Record(ast::RecordFieldList),
232 Tuple(ast::TupleFieldList),
237 fn from_node<N: AstNode>(node: &N) -> StructKind {
238 if let Some(nfdl) = support::child::<ast::RecordFieldList>(node.syntax()) {
239 StructKind::Record(nfdl)
240 } else if let Some(pfl) = support::child::<ast::TupleFieldList>(node.syntax()) {
241 StructKind::Tuple(pfl)
249 pub fn kind(&self) -> StructKind {
250 StructKind::from_node(self)
254 impl ast::RecordExprField {
255 pub fn for_field_name(field_name: &ast::NameRef) -> Option<ast::RecordExprField> {
257 field_name.syntax().parent().and_then(ast::RecordExprField::cast).or_else(|| {
258 field_name.syntax().ancestors().nth(4).and_then(ast::RecordExprField::cast)
260 if candidate.field_name().as_ref() == Some(field_name) {
267 /// Deals with field init shorthand
268 pub fn field_name(&self) -> Option<ast::NameRef> {
269 if let Some(name_ref) = self.name_ref() {
270 return Some(name_ref);
272 self.expr()?.name_ref()
276 pub enum NameOrNameRef {
278 NameRef(ast::NameRef),
281 impl fmt::Display for NameOrNameRef {
282 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284 NameOrNameRef::Name(it) => fmt::Display::fmt(it, f),
285 NameOrNameRef::NameRef(it) => fmt::Display::fmt(it, f),
290 impl ast::RecordPatField {
291 /// Deals with field init shorthand
292 pub fn field_name(&self) -> Option<NameOrNameRef> {
293 if let Some(name_ref) = self.name_ref() {
294 return Some(NameOrNameRef::NameRef(name_ref));
296 if let Some(ast::Pat::IdentPat(pat)) = self.pat() {
297 let name = pat.name()?;
298 return Some(NameOrNameRef::Name(name));
305 pub fn parent_enum(&self) -> ast::Enum {
308 .and_then(|it| it.parent())
309 .and_then(ast::Enum::cast)
310 .expect("EnumVariants are always nested in Enums")
312 pub fn kind(&self) -> StructKind {
313 StructKind::from_node(self)
317 #[derive(Debug, Clone, PartialEq, Eq)]
323 impl ast::FieldExpr {
324 pub fn index_token(&self) -> Option<SyntaxToken> {
326 .children_with_tokens()
327 // FIXME: Accepting floats here to reject them in validation later
328 .find(|c| c.kind() == SyntaxKind::INT_NUMBER || c.kind() == SyntaxKind::FLOAT_NUMBER)
330 .and_then(SyntaxElement::as_token)
334 pub fn field_access(&self) -> Option<FieldKind> {
335 if let Some(nr) = self.name_ref() {
336 Some(FieldKind::Name(nr))
337 } else if let Some(tok) = self.index_token() {
338 Some(FieldKind::Index(tok))
345 pub struct SlicePatComponents {
346 pub prefix: Vec<ast::Pat>,
347 pub slice: Option<ast::Pat>,
348 pub suffix: Vec<ast::Pat>,
352 pub fn components(&self) -> SlicePatComponents {
353 let mut args = self.pats().peekable();
355 .peeking_take_while(|p| match p {
356 ast::Pat::RestPat(_) => false,
357 ast::Pat::IdentPat(bp) => match bp.pat() {
358 Some(ast::Pat::RestPat(_)) => false,
361 ast::Pat::RefPat(rp) => match rp.pat() {
362 Some(ast::Pat::RestPat(_)) => false,
363 Some(ast::Pat::IdentPat(bp)) => match bp.pat() {
364 Some(ast::Pat::RestPat(_)) => false,
372 let slice = args.next();
373 let suffix = args.collect();
375 SlicePatComponents { prefix, slice, suffix }
379 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
380 pub enum SelfParamKind {
389 impl ast::SelfParam {
390 pub fn kind(&self) -> SelfParamKind {
391 if self.amp_token().is_some() {
392 if self.mut_token().is_some() {
393 SelfParamKind::MutRef
403 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
404 pub enum TypeBoundKind {
406 PathType(ast::PathType),
408 ForType(ast::ForType),
410 Lifetime(ast::Lifetime),
413 impl ast::TypeBound {
414 pub fn kind(&self) -> TypeBoundKind {
415 if let Some(path_type) = support::children(self.syntax()).next() {
416 TypeBoundKind::PathType(path_type)
417 } else if let Some(for_type) = support::children(self.syntax()).next() {
418 TypeBoundKind::ForType(for_type)
419 } else if let Some(lifetime) = self.lifetime() {
420 TypeBoundKind::Lifetime(lifetime)
427 pub enum VisibilityKind {
435 impl ast::Visibility {
436 pub fn kind(&self) -> VisibilityKind {
437 if let Some(path) = support::children(self.syntax()).next() {
438 VisibilityKind::In(path)
439 } else if self.crate_token().is_some() {
440 VisibilityKind::PubCrate
441 } else if self.super_token().is_some() {
442 VisibilityKind::PubSuper
443 } else if self.self_token().is_some() {
444 VisibilityKind::PubSelf
451 impl ast::LifetimeParam {
452 pub fn lifetime_bounds(&self) -> impl Iterator<Item = SyntaxToken> {
454 .children_with_tokens()
455 .filter_map(|it| it.into_token())
456 .skip_while(|x| x.kind() != T![:])
457 .filter(|it| it.kind() == T![lifetime_ident])
462 pub fn start(&self) -> Option<ast::Pat> {
464 .children_with_tokens()
465 .take_while(|it| !(it.kind() == T![..] || it.kind() == T![..=]))
466 .filter_map(|it| it.into_node())
467 .find_map(ast::Pat::cast)
470 pub fn end(&self) -> Option<ast::Pat> {
472 .children_with_tokens()
473 .skip_while(|it| !(it.kind() == T![..] || it.kind() == T![..=]))
474 .filter_map(|it| it.into_node())
475 .find_map(ast::Pat::cast)
479 impl ast::TokenTree {
480 pub fn left_delimiter_token(&self) -> Option<SyntaxToken> {
482 .first_child_or_token()?
484 .filter(|it| matches!(it.kind(), T!['{'] | T!['('] | T!['[']))
487 pub fn right_delimiter_token(&self) -> Option<SyntaxToken> {
489 .last_child_or_token()?
491 .filter(|it| matches!(it.kind(), T!['}'] | T![')'] | T![']']))
495 impl ast::GenericParamList {
496 pub fn lifetime_params(&self) -> impl Iterator<Item = ast::LifetimeParam> {
497 self.generic_params().filter_map(|param| match param {
498 ast::GenericParam::LifetimeParam(it) => Some(it),
499 ast::GenericParam::TypeParam(_) | ast::GenericParam::ConstParam(_) => None,
502 pub fn type_params(&self) -> impl Iterator<Item = ast::TypeParam> {
503 self.generic_params().filter_map(|param| match param {
504 ast::GenericParam::TypeParam(it) => Some(it),
505 ast::GenericParam::LifetimeParam(_) | ast::GenericParam::ConstParam(_) => None,
508 pub fn const_params(&self) -> impl Iterator<Item = ast::ConstParam> {
509 self.generic_params().filter_map(|param| match param {
510 ast::GenericParam::ConstParam(it) => Some(it),
511 ast::GenericParam::TypeParam(_) | ast::GenericParam::LifetimeParam(_) => None,
516 impl ast::DocCommentsOwner for ast::SourceFile {}
517 impl ast::DocCommentsOwner for ast::Fn {}
518 impl ast::DocCommentsOwner for ast::Struct {}
519 impl ast::DocCommentsOwner for ast::Union {}
520 impl ast::DocCommentsOwner for ast::RecordField {}
521 impl ast::DocCommentsOwner for ast::TupleField {}
522 impl ast::DocCommentsOwner for ast::Enum {}
523 impl ast::DocCommentsOwner for ast::Variant {}
524 impl ast::DocCommentsOwner for ast::Trait {}
525 impl ast::DocCommentsOwner for ast::Module {}
526 impl ast::DocCommentsOwner for ast::Static {}
527 impl ast::DocCommentsOwner for ast::Const {}
528 impl ast::DocCommentsOwner for ast::TypeAlias {}
529 impl ast::DocCommentsOwner for ast::Impl {}
530 impl ast::DocCommentsOwner for ast::MacroRules {}
531 impl ast::DocCommentsOwner for ast::MacroDef {}
532 impl ast::DocCommentsOwner for ast::Macro {}
533 impl ast::DocCommentsOwner for ast::Use {}