Skip to main content

syntax/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//! These methods should only do simple, shallow tasks related to the syntax of the node itself.
5
6use std::{fmt, iter::successors};
7
8use itertools::Itertools;
9use parser::SyntaxKind;
10use rowan::{GreenNodeData, GreenTokenData, TextSize};
11use smallvec::{SmallVec, smallvec};
12
13use crate::{
14    NodeOrToken, SmolStr, SyntaxElement, SyntaxElementChildren, SyntaxToken, T,
15    ast::{
16        self, AnyComment, AstNode, AstToken, CommentShape, HasAttrs, HasGenericArgs,
17        HasGenericParams, HasName, HasTypeBounds, SyntaxNode, support,
18    },
19    syntax_editor::SyntaxEditor,
20};
21
22use super::{GenericParam, RangeItem, RangeOp};
23
24impl ast::Lifetime {
25    pub fn text(&self) -> &str {
26        text_of_first_token(self.syntax())
27    }
28}
29
30impl ast::Name {
31    pub fn text(&self) -> &str {
32        text_of_first_token(self.syntax())
33    }
34}
35
36impl ast::NameRef {
37    pub fn text(&self) -> &str {
38        text_of_first_token(self.syntax())
39    }
40
41    pub fn as_tuple_field(&self) -> Option<usize> {
42        self.text().parse().ok()
43    }
44
45    pub fn token_kind(&self) -> SyntaxKind {
46        self.syntax().first_token().map_or(SyntaxKind::ERROR, |it| it.kind())
47    }
48}
49
50fn text_of_first_token(node: &SyntaxNode) -> &str {
51    fn first_token(green_ref: &GreenNodeData) -> &GreenTokenData {
52        green_ref.children().next().and_then(NodeOrToken::into_token).unwrap()
53    }
54
55    first_token(node.green()).text()
56}
57
58fn into_comma(it: NodeOrToken<SyntaxNode, SyntaxToken>) -> Option<SyntaxToken> {
59    let token = match it {
60        NodeOrToken::Token(it) => it,
61        NodeOrToken::Node(node) if node.kind() == SyntaxKind::ERROR => node.first_token()?,
62        NodeOrToken::Node(_) => return None,
63    };
64    (token.kind() == T![,]).then_some(token)
65}
66
67impl ast::Abi {
68    pub fn abi_string(&self) -> Option<ast::String> {
69        support::token(&self.syntax, SyntaxKind::STRING).and_then(ast::String::cast)
70    }
71}
72
73impl ast::HasModuleItem for ast::StmtList {}
74
75impl ast::BlockExpr {
76    // FIXME: remove all these methods, they belong to ast::StmtList
77    pub fn statements(&self) -> impl Iterator<Item = ast::Stmt> {
78        self.stmt_list().into_iter().flat_map(|it| it.statements())
79    }
80    pub fn tail_expr(&self) -> Option<ast::Expr> {
81        self.stmt_list()?.tail_expr()
82    }
83    /// Block expressions accept outer and inner attributes, but only when they are the outer
84    /// expression of an expression statement or the final expression of another block expression.
85    pub fn may_carry_attributes(&self) -> bool {
86        matches!(
87            self.syntax().parent().map(|it| it.kind()),
88            Some(SyntaxKind::BLOCK_EXPR | SyntaxKind::EXPR_STMT)
89        )
90    }
91}
92
93#[derive(Debug, PartialEq, Eq, Clone)]
94pub enum Macro {
95    MacroRules(ast::MacroRules),
96    MacroDef(ast::MacroDef),
97}
98
99impl From<ast::MacroRules> for Macro {
100    fn from(it: ast::MacroRules) -> Self {
101        Macro::MacroRules(it)
102    }
103}
104
105impl From<ast::MacroDef> for Macro {
106    fn from(it: ast::MacroDef) -> Self {
107        Macro::MacroDef(it)
108    }
109}
110
111impl AstNode for Macro {
112    fn can_cast(kind: SyntaxKind) -> bool {
113        matches!(kind, SyntaxKind::MACRO_RULES | SyntaxKind::MACRO_DEF)
114    }
115    fn cast(syntax: SyntaxNode) -> Option<Self> {
116        let res = match syntax.kind() {
117            SyntaxKind::MACRO_RULES => Macro::MacroRules(ast::MacroRules { syntax }),
118            SyntaxKind::MACRO_DEF => Macro::MacroDef(ast::MacroDef { syntax }),
119            _ => return None,
120        };
121        Some(res)
122    }
123    fn syntax(&self) -> &SyntaxNode {
124        match self {
125            Macro::MacroRules(it) => it.syntax(),
126            Macro::MacroDef(it) => it.syntax(),
127        }
128    }
129}
130
131impl HasName for Macro {
132    fn name(&self) -> Option<ast::Name> {
133        match self {
134            Macro::MacroRules(mac) => mac.name(),
135            Macro::MacroDef(mac) => mac.name(),
136        }
137    }
138}
139
140impl HasAttrs for Macro {}
141
142impl From<ast::AssocItem> for ast::Item {
143    fn from(assoc: ast::AssocItem) -> Self {
144        match assoc {
145            ast::AssocItem::Const(it) => ast::Item::Const(it),
146            ast::AssocItem::Fn(it) => ast::Item::Fn(it),
147            ast::AssocItem::MacroCall(it) => ast::Item::MacroCall(it),
148            ast::AssocItem::TypeAlias(it) => ast::Item::TypeAlias(it),
149        }
150    }
151}
152
153impl From<ast::ExternItem> for ast::Item {
154    fn from(extern_item: ast::ExternItem) -> Self {
155        match extern_item {
156            ast::ExternItem::Static(it) => ast::Item::Static(it),
157            ast::ExternItem::Fn(it) => ast::Item::Fn(it),
158            ast::ExternItem::MacroCall(it) => ast::Item::MacroCall(it),
159            ast::ExternItem::TypeAlias(it) => ast::Item::TypeAlias(it),
160        }
161    }
162}
163
164#[derive(Debug, Copy, Clone, PartialEq, Eq)]
165pub enum AttrKind {
166    Inner,
167    Outer,
168}
169
170impl AttrKind {
171    /// Returns `true` if the attr_kind is [`Inner`](Self::Inner).
172    pub fn is_inner(&self) -> bool {
173        matches!(self, Self::Inner)
174    }
175
176    /// Returns `true` if the attr_kind is [`Outer`](Self::Outer).
177    pub fn is_outer(&self) -> bool {
178        matches!(self, Self::Outer)
179    }
180}
181
182impl ast::Meta {
183    pub fn as_simple_atom(&self) -> Option<SmolStr> {
184        Some(self.as_simple_path()?.as_single_name_ref()?.text().into())
185    }
186
187    pub fn as_simple_call(&self) -> Option<(SmolStr, ast::TokenTree)> {
188        let ast::Meta::TokenTreeMeta(meta) = self else { return None };
189        Some((meta.path()?.as_single_name_ref()?.text().into(), meta.token_tree()?))
190    }
191
192    pub fn as_simple_path(&self) -> Option<ast::Path> {
193        let ast::Meta::PathMeta(meta) = self else { return None };
194        meta.path()
195    }
196
197    pub fn simple_name(&self) -> Option<SmolStr> {
198        match self {
199            ast::Meta::CfgAttrMeta(_) => Some(SmolStr::new_static("cfg_attr")),
200            ast::Meta::CfgMeta(_) => Some(SmolStr::new_static("cfg")),
201            _ => {
202                let path = self.path()?;
203                match (path.segment(), path.qualifier()) {
204                    (Some(segment), None) => Some(segment.syntax().first_token()?.text().into()),
205                    _ => None,
206                }
207            }
208        }
209    }
210
211    pub fn path(&self) -> Option<ast::Path> {
212        match self {
213            ast::Meta::CfgAttrMeta(_) | ast::Meta::CfgMeta(_) => None,
214            ast::Meta::KeyValueMeta(it) => it.path(),
215            ast::Meta::PathMeta(it) => it.path(),
216            ast::Meta::TokenTreeMeta(it) => it.path(),
217            ast::Meta::UnsafeMeta(it) => it.meta()?.path(),
218        }
219    }
220
221    /// Includes `cfg_attr()` inner metas (without considering the predicate).
222    pub fn skip_cfg_attrs(self) -> SmallVec<[ast::Meta; 1]> {
223        match self {
224            ast::Meta::CfgAttrMeta(meta) => {
225                meta.metas().flat_map(|meta| meta.skip_cfg_attrs()).collect()
226            }
227            _ => smallvec![self],
228        }
229    }
230
231    /// FIXME: Calling this is almost always incorrect, as `cfg_attr` can contains multiple `Meta`s.
232    pub fn parent_attr(&self) -> Option<ast::Attr> {
233        self.syntax().ancestors().find_map(ast::Attr::cast)
234    }
235}
236
237impl ast::Attr {
238    pub fn as_simple_atom(&self) -> Option<SmolStr> {
239        self.meta().and_then(|meta| meta.as_simple_atom())
240    }
241
242    pub fn as_simple_call(&self) -> Option<(SmolStr, ast::TokenTree)> {
243        self.meta().and_then(|meta| meta.as_simple_call())
244    }
245
246    pub fn as_simple_path(&self) -> Option<ast::Path> {
247        self.meta().and_then(|meta| meta.as_simple_path())
248    }
249
250    pub fn simple_name(&self) -> Option<SmolStr> {
251        self.meta().and_then(|meta| meta.simple_name())
252    }
253
254    pub fn path(&self) -> Option<ast::Path> {
255        self.meta().and_then(|meta| meta.path())
256    }
257
258    pub fn kind(&self) -> AttrKind {
259        match self.excl_token() {
260            Some(_) => AttrKind::Inner,
261            None => AttrKind::Outer,
262        }
263    }
264
265    /// Includes `cfg_attr()` inner metas (without considering the predicate).
266    pub fn skip_cfg_attrs(&self) -> SmallVec<[ast::Meta; 1]> {
267        match self.meta() {
268            Some(meta) => meta.skip_cfg_attrs(),
269            None => SmallVec::new(),
270        }
271    }
272}
273
274impl ast::DocComment {
275    // `///` or `/**` or `//!` or `/*!`, all are 3 chars.
276    pub const PREFIX_LEN: TextSize = TextSize::new(3);
277
278    pub fn kind(&self) -> AttrKind {
279        match self.inner_doc_comment_token() {
280            Some(_) => AttrKind::Inner,
281            None => AttrKind::Outer,
282        }
283    }
284
285    pub fn token(&self) -> AnyComment {
286        self.syntax
287            .first_token()
288            .and_then(ast::AnyComment::cast)
289            .expect("`ast::DocComment` must have a comment token")
290    }
291
292    pub fn shape(&self) -> CommentShape {
293        CommentShape::from_text(self.text_with_markers())
294    }
295
296    /// Returns the text with the `/**...*/` or `/*!...*/` or `///...` or `//!...` markers.
297    pub fn text_with_markers(&self) -> &str {
298        text_of_first_token(&self.syntax)
299    }
300
301    /// Returns the textual content of a doc comment node as a single string with prefix and suffix removed.
302    pub fn text(&self) -> &str {
303        let shape = self.shape();
304        let text = &self.text_with_markers()[Self::PREFIX_LEN.into()..];
305        if shape == CommentShape::Block {
306            // The `*/` may not exist because of recovery.
307            text.strip_suffix("*/").unwrap_or(text)
308        } else {
309            text
310        }
311    }
312}
313
314impl ast::AnyAttr {
315    pub fn kind(&self) -> AttrKind {
316        match self {
317            ast::AnyAttr::Attr(it) => it.kind(),
318            ast::AnyAttr::DocComment(it) => it.kind(),
319        }
320    }
321}
322
323#[derive(Debug, Clone, PartialEq, Eq)]
324pub enum PathSegmentKind {
325    Name(ast::NameRef),
326    Type { type_ref: Option<ast::Type>, trait_ref: Option<ast::PathType> },
327    SelfTypeKw,
328    SelfKw,
329    SuperKw,
330    CrateKw,
331}
332
333impl ast::PathSegment {
334    pub fn parent_path(&self) -> ast::Path {
335        self.syntax()
336            .parent()
337            .and_then(ast::Path::cast)
338            .expect("segments are always nested in paths")
339    }
340
341    pub fn crate_token(&self) -> Option<SyntaxToken> {
342        self.name_ref().and_then(|it| it.crate_token())
343    }
344
345    pub fn self_token(&self) -> Option<SyntaxToken> {
346        self.name_ref().and_then(|it| it.self_token())
347    }
348
349    pub fn self_type_token(&self) -> Option<SyntaxToken> {
350        self.name_ref().and_then(|it| it.Self_token())
351    }
352
353    pub fn super_token(&self) -> Option<SyntaxToken> {
354        self.name_ref().and_then(|it| it.super_token())
355    }
356
357    pub fn kind(&self) -> Option<PathSegmentKind> {
358        let res = if let Some(name_ref) = self.name_ref() {
359            match name_ref.token_kind() {
360                T![Self] => PathSegmentKind::SelfTypeKw,
361                T![self] => PathSegmentKind::SelfKw,
362                T![super] => PathSegmentKind::SuperKw,
363                T![crate] => PathSegmentKind::CrateKw,
364                _ => PathSegmentKind::Name(name_ref),
365            }
366        } else {
367            let (type_ref, trait_ref) = self.type_anchor()?.target();
368            PathSegmentKind::Type { type_ref, trait_ref }
369        };
370        Some(res)
371    }
372}
373
374impl ast::Path {
375    pub fn parent_path(&self) -> Option<ast::Path> {
376        self.syntax().parent().and_then(ast::Path::cast)
377    }
378
379    pub fn as_single_segment(&self) -> Option<ast::PathSegment> {
380        match self.qualifier() {
381            Some(_) => None,
382            None => self.segment(),
383        }
384    }
385
386    pub fn as_single_name_ref(&self) -> Option<ast::NameRef> {
387        match self.qualifier() {
388            Some(_) => None,
389            None => self.segment()?.name_ref(),
390        }
391    }
392
393    pub fn first_qualifier_or_self(&self) -> ast::Path {
394        successors(Some(self.clone()), ast::Path::qualifier).last().unwrap()
395    }
396
397    pub fn first_qualifier(&self) -> Option<ast::Path> {
398        successors(self.qualifier(), ast::Path::qualifier).last()
399    }
400
401    pub fn first_segment(&self) -> Option<ast::PathSegment> {
402        self.first_qualifier_or_self().segment()
403    }
404
405    pub fn segments(&self) -> impl Iterator<Item = ast::PathSegment> + Clone {
406        let path_range = self.syntax().text_range();
407        successors(self.first_segment(), move |p| {
408            p.parent_path().parent_path().and_then(|p| {
409                if path_range.contains_range(p.syntax().text_range()) { p.segment() } else { None }
410            })
411        })
412    }
413
414    pub fn qualifiers(&self) -> impl Iterator<Item = ast::Path> + Clone {
415        successors(self.qualifier(), |p| p.qualifier())
416    }
417
418    pub fn top_path(&self) -> ast::Path {
419        let mut this = self.clone();
420        while let Some(path) = this.parent_path() {
421            this = path;
422        }
423        this
424    }
425}
426
427impl ast::Use {
428    pub fn is_simple_glob(&self) -> bool {
429        self.use_tree().is_some_and(|use_tree| {
430            use_tree.use_tree_list().is_none() && use_tree.star_token().is_some()
431        })
432    }
433}
434
435impl ast::UseTree {
436    pub fn is_simple_path(&self) -> bool {
437        self.use_tree_list().is_none() && self.star_token().is_none()
438    }
439
440    pub fn parent_use_tree_list(&self) -> Option<ast::UseTreeList> {
441        self.syntax().parent().and_then(ast::UseTreeList::cast)
442    }
443
444    pub fn top_use_tree(&self) -> ast::UseTree {
445        let mut this = self.clone();
446        while let Some(use_tree_list) = this.parent_use_tree_list() {
447            this = use_tree_list.parent_use_tree();
448        }
449        this
450    }
451}
452
453impl ast::UseTreeList {
454    pub fn parent_use_tree(&self) -> ast::UseTree {
455        self.syntax()
456            .parent()
457            .and_then(ast::UseTree::cast)
458            .expect("UseTreeLists are always nested in UseTrees")
459    }
460
461    pub fn has_inner_comment(&self) -> bool {
462        self.syntax()
463            .children_with_tokens()
464            .filter_map(|it| it.into_token())
465            .find_map(ast::Comment::cast)
466            .is_some()
467    }
468
469    pub fn comma(&self) -> impl Iterator<Item = SyntaxToken> {
470        self.syntax()
471            .children_with_tokens()
472            .filter_map(|it| it.into_token().filter(|it| it.kind() == T![,]))
473    }
474
475    /// Remove the unnecessary braces in current `UseTreeList`
476    pub fn remove_unnecessary_braces(mut self, editor: &SyntaxEditor) {
477        // Returns true iff there is a single subtree and it is not the self keyword. The braces in
478        // `use x::{self};` are necessary and so we should not remove them.
479        let has_single_subtree_that_is_not_self = |u: &ast::UseTreeList| {
480            let use_trees = u.use_trees().filter(|use_tree| !editor.deleted(use_tree.syntax()));
481            if let Some((single_subtree,)) = use_trees.collect_tuple() {
482                // We have a single subtree, check whether it is self.
483
484                let is_self = single_subtree.path().as_ref().is_some_and(|path| {
485                    path.segment().and_then(|seg| seg.self_token()).is_some()
486                        && path.qualifier().is_none()
487                });
488
489                !is_self
490            } else {
491                // Not a single subtree
492                false
493            }
494        };
495
496        let remove_brace_in_use_tree_list = |u: &ast::UseTreeList| {
497            if has_single_subtree_that_is_not_self(u) {
498                if let Some(a) = u.l_curly_token() {
499                    editor.delete(a)
500                }
501                if let Some(a) = u.r_curly_token() {
502                    editor.delete(a)
503                }
504                u.comma().for_each(|u| editor.delete(u));
505            }
506        };
507
508        // take `use crate::{{{{A}}}}` for example
509        // the below remove the innermost {}, got `use crate::{{{A}}}`
510        remove_brace_in_use_tree_list(&self);
511
512        // the below remove other unnecessary {}, got `use crate::A`
513        while let Some(parent_use_tree_list) = self.parent_use_tree().parent_use_tree_list() {
514            remove_brace_in_use_tree_list(&parent_use_tree_list);
515            self = parent_use_tree_list;
516        }
517    }
518}
519
520impl ast::Impl {
521    pub fn self_ty(&self) -> Option<ast::Type> {
522        self.target().1
523    }
524
525    pub fn trait_(&self) -> Option<ast::Type> {
526        self.target().0
527    }
528
529    fn target(&self) -> (Option<ast::Type>, Option<ast::Type>) {
530        let mut types = support::children(self.syntax()).peekable();
531        let for_kw = self.for_token();
532        let trait_ = types.next_if(|trait_: &ast::Type| {
533            for_kw.is_some_and(|for_kw| {
534                trait_.syntax().text_range().start() < for_kw.text_range().start()
535            })
536        });
537        let self_ty = types.next();
538        (trait_, self_ty)
539    }
540
541    pub fn for_trait_name_ref(name_ref: &ast::NameRef) -> Option<ast::Impl> {
542        let this = name_ref.syntax().ancestors().find_map(ast::Impl::cast)?;
543        if this.trait_()?.syntax().text_range().start() == name_ref.syntax().text_range().start() {
544            Some(this)
545        } else {
546            None
547        }
548    }
549}
550
551impl ast::TypeAnchor {
552    pub fn self_ty(&self) -> Option<ast::Type> {
553        self.target().0
554    }
555
556    pub fn trait_(&self) -> Option<ast::PathType> {
557        self.target().1
558    }
559
560    fn target(&self) -> (Option<ast::Type>, Option<ast::PathType>) {
561        let mut types = support::children(self.syntax()).peekable();
562        let as_kw = self.as_token();
563        let self_ty = types.next_if(|self_ty: &ast::Type| {
564            as_kw.is_none_or(|as_kw| {
565                self_ty.syntax().text_range().start() < as_kw.text_range().start()
566            })
567        });
568        let trait_ = types.next().and_then(|it| match it {
569            ast::Type::PathType(it) => Some(it),
570            _ => None,
571        });
572        (self_ty, trait_)
573    }
574}
575
576#[derive(Debug, Clone, PartialEq, Eq)]
577pub enum StructKind {
578    Record(ast::RecordFieldList),
579    Tuple(ast::TupleFieldList),
580    Unit,
581}
582
583impl StructKind {
584    fn from_node<N: AstNode>(node: &N) -> StructKind {
585        if let Some(nfdl) = support::child::<ast::RecordFieldList>(node.syntax()) {
586            StructKind::Record(nfdl)
587        } else if let Some(pfl) = support::child::<ast::TupleFieldList>(node.syntax()) {
588            StructKind::Tuple(pfl)
589        } else {
590            StructKind::Unit
591        }
592    }
593}
594
595impl ast::Struct {
596    pub fn kind(&self) -> StructKind {
597        StructKind::from_node(self)
598    }
599}
600
601impl ast::Union {
602    pub fn kind(&self) -> StructKind {
603        StructKind::from_node(self)
604    }
605}
606
607impl ast::RecordExprField {
608    pub fn for_field_name(field_name: &ast::NameRef) -> Option<ast::RecordExprField> {
609        let candidate = Self::for_name_ref(field_name)?;
610        if candidate.field_name().as_ref() == Some(field_name) { Some(candidate) } else { None }
611    }
612
613    pub fn for_name_ref(name_ref: &ast::NameRef) -> Option<ast::RecordExprField> {
614        let syn = name_ref.syntax();
615        syn.parent()
616            .and_then(ast::RecordExprField::cast)
617            .or_else(|| syn.ancestors().nth(4).and_then(ast::RecordExprField::cast))
618    }
619
620    /// Deals with field init shorthand
621    pub fn field_name(&self) -> Option<ast::NameRef> {
622        if let Some(name_ref) = self.name_ref() {
623            return Some(name_ref);
624        }
625        if let ast::Expr::PathExpr(expr) = self.expr()? {
626            let path = expr.path()?;
627            let segment = path.segment()?;
628            let name_ref = segment.name_ref()?;
629            if path.qualifier().is_none() {
630                return Some(name_ref);
631            }
632        }
633        None
634    }
635}
636
637#[derive(Debug, Clone)]
638pub enum NameLike {
639    NameRef(ast::NameRef),
640    Name(ast::Name),
641    Lifetime(ast::Lifetime),
642}
643
644impl NameLike {
645    pub fn as_name_ref(&self) -> Option<&ast::NameRef> {
646        match self {
647            NameLike::NameRef(name_ref) => Some(name_ref),
648            _ => None,
649        }
650    }
651    pub fn as_lifetime(&self) -> Option<&ast::Lifetime> {
652        match self {
653            NameLike::Lifetime(lifetime) => Some(lifetime),
654            _ => None,
655        }
656    }
657    pub fn text(&self) -> &str {
658        match self {
659            NameLike::NameRef(name_ref) => name_ref.text(),
660            NameLike::Name(name) => name.text(),
661            NameLike::Lifetime(lifetime) => lifetime.text(),
662        }
663    }
664}
665
666impl ast::AstNode for NameLike {
667    fn can_cast(kind: SyntaxKind) -> bool {
668        matches!(kind, SyntaxKind::NAME | SyntaxKind::NAME_REF | SyntaxKind::LIFETIME)
669    }
670    fn cast(syntax: SyntaxNode) -> Option<Self> {
671        let res = match syntax.kind() {
672            SyntaxKind::NAME => NameLike::Name(ast::Name { syntax }),
673            SyntaxKind::NAME_REF => NameLike::NameRef(ast::NameRef { syntax }),
674            SyntaxKind::LIFETIME => NameLike::Lifetime(ast::Lifetime { syntax }),
675            _ => return None,
676        };
677        Some(res)
678    }
679    fn syntax(&self) -> &SyntaxNode {
680        match self {
681            NameLike::NameRef(it) => it.syntax(),
682            NameLike::Name(it) => it.syntax(),
683            NameLike::Lifetime(it) => it.syntax(),
684        }
685    }
686}
687
688const _: () = {
689    use ast::{Lifetime, Name, NameRef};
690    stdx::impl_from!(NameRef, Name, Lifetime for NameLike);
691};
692
693#[derive(Debug, Clone, PartialEq)]
694pub enum NameOrNameRef {
695    Name(ast::Name),
696    NameRef(ast::NameRef),
697}
698
699impl fmt::Display for NameOrNameRef {
700    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
701        match self {
702            NameOrNameRef::Name(it) => fmt::Display::fmt(it, f),
703            NameOrNameRef::NameRef(it) => fmt::Display::fmt(it, f),
704        }
705    }
706}
707
708impl ast::AstNode for NameOrNameRef {
709    fn can_cast(kind: SyntaxKind) -> bool {
710        matches!(kind, SyntaxKind::NAME | SyntaxKind::NAME_REF)
711    }
712    fn cast(syntax: SyntaxNode) -> Option<Self> {
713        let res = match syntax.kind() {
714            SyntaxKind::NAME => NameOrNameRef::Name(ast::Name { syntax }),
715            SyntaxKind::NAME_REF => NameOrNameRef::NameRef(ast::NameRef { syntax }),
716            _ => return None,
717        };
718        Some(res)
719    }
720    fn syntax(&self) -> &SyntaxNode {
721        match self {
722            NameOrNameRef::NameRef(it) => it.syntax(),
723            NameOrNameRef::Name(it) => it.syntax(),
724        }
725    }
726}
727
728impl NameOrNameRef {
729    pub fn text(&self) -> &str {
730        match self {
731            NameOrNameRef::Name(name) => name.text(),
732            NameOrNameRef::NameRef(name_ref) => name_ref.text(),
733        }
734    }
735}
736
737impl ast::RecordPatField {
738    pub fn for_field_name_ref(field_name: &ast::NameRef) -> Option<ast::RecordPatField> {
739        let candidate = field_name.syntax().parent().and_then(ast::RecordPatField::cast)?;
740        match candidate.field_name()? {
741            NameOrNameRef::NameRef(name_ref) if name_ref == *field_name => Some(candidate),
742            _ => None,
743        }
744    }
745
746    pub fn for_field_name(field_name: &ast::Name) -> Option<ast::RecordPatField> {
747        let candidate =
748            field_name.syntax().ancestors().nth(2).and_then(ast::RecordPatField::cast)?;
749        match candidate.field_name()? {
750            NameOrNameRef::Name(name) if name == *field_name => Some(candidate),
751            _ => None,
752        }
753    }
754
755    pub fn parent_record_pat(&self) -> ast::RecordPat {
756        self.syntax().ancestors().find_map(ast::RecordPat::cast).unwrap()
757    }
758
759    /// Deals with field init shorthand
760    pub fn field_name(&self) -> Option<NameOrNameRef> {
761        if let Some(name_ref) = self.name_ref() {
762            return Some(NameOrNameRef::NameRef(name_ref));
763        }
764        match self.pat() {
765            Some(ast::Pat::IdentPat(pat)) => {
766                let name = pat.name()?;
767                Some(NameOrNameRef::Name(name))
768            }
769            Some(ast::Pat::BoxPat(pat)) => match pat.pat() {
770                Some(ast::Pat::IdentPat(pat)) => {
771                    let name = pat.name()?;
772                    Some(NameOrNameRef::Name(name))
773                }
774                _ => None,
775            },
776            _ => None,
777        }
778    }
779}
780
781impl ast::Variant {
782    pub fn parent_enum(&self) -> ast::Enum {
783        self.syntax()
784            .parent()
785            .and_then(|it| it.parent())
786            .and_then(ast::Enum::cast)
787            .expect("EnumVariants are always nested in Enums")
788    }
789    pub fn kind(&self) -> StructKind {
790        StructKind::from_node(self)
791    }
792}
793
794impl ast::Item {
795    pub fn generic_param_list(&self) -> Option<ast::GenericParamList> {
796        ast::AnyHasGenericParams::cast(self.syntax().clone())?.generic_param_list()
797    }
798}
799
800impl ast::Type {
801    pub fn generic_arg_list(&self) -> Option<ast::GenericArgList> {
802        if let ast::Type::PathType(path_type) = self {
803            path_type.path()?.segment()?.generic_arg_list()
804        } else {
805            None
806        }
807    }
808
809    pub fn needs_angles_in_path(&self) -> bool {
810        !matches!(self, ast::Type::PathType(_)) || self.generic_arg_list().is_some()
811    }
812}
813
814#[derive(Debug, Clone, PartialEq, Eq)]
815pub enum FieldKind {
816    Name(ast::NameRef),
817    Index(SyntaxToken),
818}
819
820impl ast::FieldExpr {
821    pub fn index_token(&self) -> Option<SyntaxToken> {
822        self.syntax
823            .children_with_tokens()
824            // FIXME: Accepting floats here to reject them in validation later
825            .find(|c| c.kind() == SyntaxKind::INT_NUMBER || c.kind() == SyntaxKind::FLOAT_NUMBER)
826            .as_ref()
827            .and_then(SyntaxElement::as_token)
828            .cloned()
829    }
830
831    pub fn field_access(&self) -> Option<FieldKind> {
832        match self.name_ref() {
833            Some(nr) => Some(FieldKind::Name(nr)),
834            None => self.index_token().map(FieldKind::Index),
835        }
836    }
837}
838
839pub struct SlicePatComponents {
840    pub prefix: Vec<ast::Pat>,
841    pub slice: Option<ast::Pat>,
842    pub suffix: Vec<ast::Pat>,
843}
844
845impl ast::SlicePat {
846    pub fn components(&self) -> SlicePatComponents {
847        let mut args = self.pats().peekable();
848        let prefix = args
849            .peeking_take_while(|p| match p {
850                ast::Pat::RestPat(_) => false,
851                ast::Pat::IdentPat(bp) => !matches!(bp.pat(), Some(ast::Pat::RestPat(_))),
852                ast::Pat::RefPat(rp) => match rp.pat() {
853                    Some(ast::Pat::RestPat(_)) => false,
854                    Some(ast::Pat::IdentPat(bp)) => !matches!(bp.pat(), Some(ast::Pat::RestPat(_))),
855                    _ => true,
856                },
857                _ => true,
858            })
859            .collect();
860        let slice = args.next();
861        let suffix = args.collect();
862
863        SlicePatComponents { prefix, slice, suffix }
864    }
865}
866
867impl ast::IdentPat {
868    pub fn is_simple_ident(&self) -> bool {
869        self.at_token().is_none()
870            && self.mut_token().is_none()
871            && self.ref_token().is_none()
872            && self.pat().is_none()
873    }
874}
875
876#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
877pub enum SelfParamKind {
878    /// self
879    Owned,
880    /// &self
881    Ref,
882    /// &mut self
883    MutRef,
884}
885
886impl ast::SelfParam {
887    pub fn kind(&self) -> SelfParamKind {
888        if self.amp_token().is_some() {
889            if self.mut_token().is_some() { SelfParamKind::MutRef } else { SelfParamKind::Ref }
890        } else {
891            SelfParamKind::Owned
892        }
893    }
894}
895
896#[derive(Clone, Debug, PartialEq, Eq, Hash)]
897pub enum TypeBoundKind {
898    /// Trait
899    PathType(Option<ast::ForBinder>, ast::PathType),
900    /// use
901    Use(ast::UseBoundGenericArgs),
902    /// 'a
903    Lifetime(ast::Lifetime),
904}
905
906impl ast::TypeBound {
907    pub fn kind(&self) -> Option<TypeBoundKind> {
908        if let Some(path_type) = support::children(self.syntax()).next() {
909            Some(TypeBoundKind::PathType(self.for_binder(), path_type))
910        } else if let Some(for_binder) = support::children::<ast::ForType>(&self.syntax).next() {
911            let Some(ast::Type::PathType(path_type)) = for_binder.ty() else { return None };
912            Some(TypeBoundKind::PathType(for_binder.for_binder(), path_type))
913        } else if let Some(args) = self.use_bound_generic_args() {
914            Some(TypeBoundKind::Use(args))
915        } else if let Some(lifetime) = self.lifetime() {
916            Some(TypeBoundKind::Lifetime(lifetime))
917        } else {
918            unreachable!()
919        }
920    }
921}
922
923#[derive(Debug, Clone)]
924pub enum TypeOrConstParam {
925    Type(ast::TypeParam),
926    Const(ast::ConstParam),
927}
928
929impl From<TypeOrConstParam> for GenericParam {
930    fn from(value: TypeOrConstParam) -> Self {
931        match value {
932            TypeOrConstParam::Type(it) => GenericParam::TypeParam(it),
933            TypeOrConstParam::Const(it) => GenericParam::ConstParam(it),
934        }
935    }
936}
937
938impl TypeOrConstParam {
939    pub fn name(&self) -> Option<ast::Name> {
940        match self {
941            TypeOrConstParam::Type(x) => x.name(),
942            TypeOrConstParam::Const(x) => x.name(),
943        }
944    }
945}
946
947impl AstNode for TypeOrConstParam {
948    fn can_cast(kind: SyntaxKind) -> bool
949    where
950        Self: Sized,
951    {
952        matches!(kind, SyntaxKind::TYPE_PARAM | SyntaxKind::CONST_PARAM)
953    }
954
955    fn cast(syntax: SyntaxNode) -> Option<Self>
956    where
957        Self: Sized,
958    {
959        let res = match syntax.kind() {
960            SyntaxKind::TYPE_PARAM => TypeOrConstParam::Type(ast::TypeParam { syntax }),
961            SyntaxKind::CONST_PARAM => TypeOrConstParam::Const(ast::ConstParam { syntax }),
962            _ => return None,
963        };
964        Some(res)
965    }
966
967    fn syntax(&self) -> &SyntaxNode {
968        match self {
969            TypeOrConstParam::Type(it) => it.syntax(),
970            TypeOrConstParam::Const(it) => it.syntax(),
971        }
972    }
973}
974
975impl HasAttrs for TypeOrConstParam {}
976
977pub enum VisibilityKind {
978    In(ast::Path),
979    PubCrate,
980    PubSuper,
981    PubSelf,
982    Pub,
983}
984
985impl ast::Visibility {
986    pub fn kind(&self) -> VisibilityKind {
987        match self.visibility_inner() {
988            Some(inner) => inner.kind(),
989            None => VisibilityKind::Pub,
990        }
991    }
992}
993
994impl ast::VisibilityInner {
995    pub fn kind(&self) -> VisibilityKind {
996        match self.path() {
997            Some(path) => {
998                if let Some(segment) =
999                    path.as_single_segment().filter(|it| it.coloncolon_token().is_none())
1000                {
1001                    if segment.crate_token().is_some() {
1002                        return VisibilityKind::PubCrate;
1003                    } else if segment.super_token().is_some() {
1004                        return VisibilityKind::PubSuper;
1005                    } else if segment.self_token().is_some() {
1006                        return VisibilityKind::PubSelf;
1007                    }
1008                }
1009                VisibilityKind::In(path)
1010            }
1011            None => VisibilityKind::Pub,
1012        }
1013    }
1014}
1015
1016impl ast::LifetimeParam {
1017    pub fn lifetime_bounds(&self) -> impl Iterator<Item = SyntaxToken> {
1018        self.type_bound_list()
1019            .into_iter()
1020            .flat_map(|it| it.bounds())
1021            .filter_map(|it| it.lifetime()?.lifetime_ident_token())
1022    }
1023}
1024
1025impl ast::Module {
1026    /// Returns the parent ast::Module, this is different than the semantic parent in that this only
1027    /// considers parent declarations in the AST
1028    pub fn parent(&self) -> Option<ast::Module> {
1029        self.syntax().ancestors().nth(2).and_then(ast::Module::cast)
1030    }
1031}
1032
1033impl RangeItem for ast::RangePat {
1034    type Bound = ast::Pat;
1035
1036    fn start(&self) -> Option<ast::Pat> {
1037        self.syntax()
1038            .children_with_tokens()
1039            .take_while(|it| !(it.kind() == T![..] || it.kind() == T![..=]))
1040            .filter_map(|it| it.into_node())
1041            .find_map(ast::Pat::cast)
1042    }
1043
1044    fn end(&self) -> Option<ast::Pat> {
1045        self.syntax()
1046            .children_with_tokens()
1047            .skip_while(|it| !(it.kind() == T![..] || it.kind() == T![..=]))
1048            .filter_map(|it| it.into_node())
1049            .find_map(ast::Pat::cast)
1050    }
1051
1052    fn op_token(&self) -> Option<SyntaxToken> {
1053        self.syntax().children_with_tokens().find_map(|it| {
1054            let token = it.into_token()?;
1055
1056            match token.kind() {
1057                T![..] => Some(token),
1058                T![..=] => Some(token),
1059                _ => None,
1060            }
1061        })
1062    }
1063
1064    fn op_kind(&self) -> Option<RangeOp> {
1065        self.syntax().children_with_tokens().find_map(|it| {
1066            let token = it.into_token()?;
1067
1068            match token.kind() {
1069                T![..] => Some(RangeOp::Exclusive),
1070                T![..=] => Some(RangeOp::Inclusive),
1071                _ => None,
1072            }
1073        })
1074    }
1075}
1076
1077impl ast::TokenTree {
1078    pub fn token_trees_and_tokens(
1079        &self,
1080    ) -> impl Iterator<Item = NodeOrToken<ast::TokenTree, SyntaxToken>> {
1081        self.syntax().children_with_tokens().filter_map(|not| match not {
1082            NodeOrToken::Node(node) => ast::TokenTree::cast(node).map(NodeOrToken::Node),
1083            NodeOrToken::Token(t) => Some(NodeOrToken::Token(t)),
1084        })
1085    }
1086
1087    pub fn left_delimiter_token(&self) -> Option<SyntaxToken> {
1088        self.syntax()
1089            .first_child_or_token()?
1090            .into_token()
1091            .filter(|it| matches!(it.kind(), T!['{'] | T!['('] | T!['[']))
1092    }
1093
1094    pub fn right_delimiter_token(&self) -> Option<SyntaxToken> {
1095        self.syntax()
1096            .last_child_or_token()?
1097            .into_token()
1098            .filter(|it| matches!(it.kind(), T!['}'] | T![')'] | T![']']))
1099    }
1100
1101    pub fn parent_meta(&self) -> Option<ast::Meta> {
1102        self.syntax().parent().and_then(ast::Meta::cast)
1103    }
1104}
1105
1106impl ast::GenericArgList {
1107    pub fn lifetime_args(&self) -> impl Iterator<Item = ast::LifetimeArg> {
1108        self.generic_args().filter_map(|arg| match arg {
1109            ast::GenericArg::LifetimeArg(it) => Some(it),
1110            _ => None,
1111        })
1112    }
1113}
1114
1115impl ast::GenericParamList {
1116    pub fn lifetime_params(&self) -> impl Iterator<Item = ast::LifetimeParam> {
1117        self.generic_params().filter_map(|param| match param {
1118            ast::GenericParam::LifetimeParam(it) => Some(it),
1119            ast::GenericParam::TypeParam(_) | ast::GenericParam::ConstParam(_) => None,
1120        })
1121    }
1122    pub fn type_or_const_params(&self) -> impl Iterator<Item = ast::TypeOrConstParam> + use<> {
1123        self.generic_params().filter_map(|param| match param {
1124            ast::GenericParam::TypeParam(it) => Some(ast::TypeOrConstParam::Type(it)),
1125            ast::GenericParam::LifetimeParam(_) => None,
1126            ast::GenericParam::ConstParam(it) => Some(ast::TypeOrConstParam::Const(it)),
1127        })
1128    }
1129}
1130
1131impl ast::ArgList {
1132    /// Comma separated args, argument may be empty
1133    pub fn args_maybe_empty(&self) -> impl Iterator<Item = Option<ast::Expr>> {
1134        // (Expr? ','?)*
1135        let mut after_arg = false;
1136        self.syntax().children_with_tokens().filter_map(move |it| {
1137            if into_comma(it.clone()).is_some() {
1138                if std::mem::take(&mut after_arg) { None } else { Some(None) }
1139            } else {
1140                Some(ast::Expr::cast(it.into_node()?).inspect(|_| after_arg = true))
1141            }
1142        })
1143    }
1144}
1145
1146impl ast::ForExpr {
1147    pub fn iterable(&self) -> Option<ast::Expr> {
1148        // If the iterable is a BlockExpr, check if the body is missing.
1149        // If it is assume the iterable is the expression that is missing instead.
1150        let mut exprs = support::children(self.syntax());
1151        let first = exprs.next();
1152        match first {
1153            Some(ast::Expr::BlockExpr(_)) => exprs.next().and(first),
1154            first => first,
1155        }
1156    }
1157}
1158
1159impl ast::HasLoopBody for ast::ForExpr {
1160    fn loop_body(&self) -> Option<ast::BlockExpr> {
1161        let mut exprs = support::children(self.syntax());
1162        let first = exprs.next();
1163        let second = exprs.next();
1164        second.or(first)
1165    }
1166}
1167
1168impl ast::WhileExpr {
1169    pub fn condition(&self) -> Option<ast::Expr> {
1170        // If the condition is a BlockExpr, check if the body is missing.
1171        // If it is assume the condition is the expression that is missing instead.
1172        let mut exprs = support::children(self.syntax());
1173        let first = exprs.next();
1174        match first {
1175            Some(ast::Expr::BlockExpr(_)) => exprs.next().and(first),
1176            first => first,
1177        }
1178    }
1179}
1180
1181impl ast::HasLoopBody for ast::WhileExpr {
1182    fn loop_body(&self) -> Option<ast::BlockExpr> {
1183        let mut exprs = support::children(self.syntax());
1184        let first = exprs.next();
1185        let second = exprs.next();
1186        second.or(first)
1187    }
1188}
1189
1190impl From<ast::Adt> for ast::Item {
1191    fn from(it: ast::Adt) -> Self {
1192        match it {
1193            ast::Adt::Enum(it) => ast::Item::Enum(it),
1194            ast::Adt::Struct(it) => ast::Item::Struct(it),
1195            ast::Adt::Union(it) => ast::Item::Union(it),
1196        }
1197    }
1198}
1199
1200impl ast::MatchGuard {
1201    pub fn condition(&self) -> Option<ast::Expr> {
1202        support::child(&self.syntax)
1203    }
1204}
1205
1206impl ast::MatchArm {
1207    pub fn parent_match(&self) -> ast::MatchExpr {
1208        self.syntax()
1209            .parent()
1210            .and_then(|it| it.parent())
1211            .and_then(ast::MatchExpr::cast)
1212            .expect("MatchArms are always nested in MatchExprs")
1213    }
1214}
1215
1216impl From<ast::Item> for ast::AnyHasAttrs {
1217    fn from(node: ast::Item) -> Self {
1218        Self::new(node)
1219    }
1220}
1221
1222impl From<ast::AssocItem> for ast::AnyHasAttrs {
1223    fn from(node: ast::AssocItem) -> Self {
1224        Self::new(node)
1225    }
1226}
1227
1228impl ast::OrPat {
1229    pub fn leading_pipe(&self) -> Option<SyntaxToken> {
1230        self.syntax
1231            .children_with_tokens()
1232            .find(|it| !it.kind().is_trivia())
1233            .and_then(NodeOrToken::into_token)
1234            .filter(|it| it.kind() == T![|])
1235    }
1236}
1237
1238#[derive(Debug, Clone)]
1239pub enum CfgAtomKey {
1240    True,
1241    False,
1242    Ident(SyntaxToken),
1243}
1244
1245impl ast::CfgAtom {
1246    pub fn key(&self) -> Option<CfgAtomKey> {
1247        if self.true_token().is_some() {
1248            Some(CfgAtomKey::True)
1249        } else if self.false_token().is_some() {
1250            Some(CfgAtomKey::False)
1251        } else {
1252            self.ident_token().map(CfgAtomKey::Ident)
1253        }
1254    }
1255}
1256
1257/// An iterator over the elements in an [`ast::TokenTree`].
1258///
1259/// Does not yield trivia or the delimiters.
1260#[derive(Clone)]
1261pub struct TokenTreeChildren {
1262    iter: SyntaxElementChildren,
1263}
1264
1265impl TokenTreeChildren {
1266    #[inline]
1267    pub fn new(tt: &ast::TokenTree) -> Self {
1268        let mut iter = tt.syntax.children_with_tokens();
1269        iter.next(); // Bump the opening delimiter.
1270        Self { iter }
1271    }
1272}
1273
1274impl Iterator for TokenTreeChildren {
1275    type Item = NodeOrToken<ast::TokenTree, SyntaxToken>;
1276
1277    #[inline]
1278    fn next(&mut self) -> Option<Self::Item> {
1279        self.iter.find_map(|item| match item {
1280            NodeOrToken::Node(node) => ast::TokenTree::cast(node).map(NodeOrToken::Node),
1281            NodeOrToken::Token(token) => {
1282                let kind = token.kind();
1283                (!matches!(
1284                    kind,
1285                    SyntaxKind::WHITESPACE | SyntaxKind::COMMENT | T![')'] | T![']'] | T!['}']
1286                ))
1287                .then_some(NodeOrToken::Token(token))
1288            }
1289        })
1290    }
1291}