rustc_ast/attr/
mod.rs

1//! Functions dealing with attributes and meta items.
2
3pub mod data_structures;
4pub mod version;
5
6use std::fmt::Debug;
7use std::sync::atomic::{AtomicU32, Ordering};
8
9use rustc_index::bit_set::GrowableBitSet;
10use rustc_span::{Ident, Span, Symbol, sym};
11use smallvec::{SmallVec, smallvec};
12use thin_vec::{ThinVec, thin_vec};
13
14use crate::AttrItemKind;
15use crate::ast::{
16    AttrArgs, AttrId, AttrItem, AttrKind, AttrStyle, AttrVec, Attribute, DUMMY_NODE_ID, DelimArgs,
17    Expr, ExprKind, LitKind, MetaItem, MetaItemInner, MetaItemKind, MetaItemLit, NormalAttr, Path,
18    PathSegment, Safety,
19};
20use crate::token::{
21    self, CommentKind, Delimiter, DocFragmentKind, InvisibleOrigin, MetaVarKind, Token,
22};
23use crate::tokenstream::{
24    DelimSpan, LazyAttrTokenStream, Spacing, TokenStream, TokenStreamIter, TokenTree,
25};
26use crate::util::comments;
27use crate::util::literal::escape_string_symbol;
28
29pub struct MarkedAttrs(GrowableBitSet<AttrId>);
30
31impl MarkedAttrs {
32    pub fn new() -> Self {
33        // We have no idea how many attributes there will be, so just
34        // initiate the vectors with 0 bits. We'll grow them as necessary.
35        MarkedAttrs(GrowableBitSet::new_empty())
36    }
37
38    pub fn mark(&mut self, attr: &Attribute) {
39        self.0.insert(attr.id);
40    }
41
42    pub fn is_marked(&self, attr: &Attribute) -> bool {
43        self.0.contains(attr.id)
44    }
45}
46
47pub struct AttrIdGenerator(AtomicU32);
48
49impl AttrIdGenerator {
50    pub fn new() -> Self {
51        AttrIdGenerator(AtomicU32::new(0))
52    }
53
54    pub fn mk_attr_id(&self) -> AttrId {
55        let id = self.0.fetch_add(1, Ordering::Relaxed);
56        assert!(id != u32::MAX);
57        AttrId::from_u32(id)
58    }
59}
60
61impl Attribute {
62    pub fn get_normal_item(&self) -> &AttrItem {
63        match &self.kind {
64            AttrKind::Normal(normal) => &normal.item,
65            AttrKind::DocComment(..) => panic!("unexpected doc comment"),
66        }
67    }
68
69    /// Replaces the arguments of this attribute with new arguments `AttrItemKind`.
70    /// This is useful for making this attribute into a trace attribute, and should otherwise be avoided.
71    pub fn replace_args(&mut self, new_args: AttrItemKind) {
72        match &mut self.kind {
73            AttrKind::Normal(normal) => normal.item.args = new_args,
74            AttrKind::DocComment(..) => panic!("unexpected doc comment"),
75        }
76    }
77
78    pub fn unwrap_normal_item(self) -> AttrItem {
79        match self.kind {
80            AttrKind::Normal(normal) => normal.item,
81            AttrKind::DocComment(..) => panic!("unexpected doc comment"),
82        }
83    }
84}
85
86impl AttributeExt for Attribute {
87    fn id(&self) -> AttrId {
88        self.id
89    }
90
91    fn value_span(&self) -> Option<Span> {
92        match &self.kind {
93            AttrKind::Normal(normal) => match &normal.item.args.unparsed_ref()? {
94                AttrArgs::Eq { expr, .. } => Some(expr.span),
95                _ => None,
96            },
97            AttrKind::DocComment(..) => None,
98        }
99    }
100
101    /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
102    /// So `#[doc = "doc"]` (which is a doc comment) and `#[doc(...)]` (which is not
103    /// a doc comment) will return `false`.
104    fn is_doc_comment(&self) -> Option<Span> {
105        match self.kind {
106            AttrKind::Normal(..) => None,
107            AttrKind::DocComment(..) => Some(self.span),
108        }
109    }
110
111    /// For a single-segment attribute, returns its name; otherwise, returns `None`.
112    fn name(&self) -> Option<Symbol> {
113        match &self.kind {
114            AttrKind::Normal(normal) => {
115                if let [ident] = &*normal.item.path.segments {
116                    Some(ident.ident.name)
117                } else {
118                    None
119                }
120            }
121            AttrKind::DocComment(..) => None,
122        }
123    }
124
125    fn symbol_path(&self) -> Option<SmallVec<[Symbol; 1]>> {
126        match &self.kind {
127            AttrKind::Normal(p) => {
128                Some(p.item.path.segments.iter().map(|i| i.ident.name).collect())
129            }
130            AttrKind::DocComment(_, _) => None,
131        }
132    }
133
134    fn path_span(&self) -> Option<Span> {
135        match &self.kind {
136            AttrKind::Normal(attr) => Some(attr.item.path.span),
137            AttrKind::DocComment(_, _) => None,
138        }
139    }
140
141    fn path_matches(&self, name: &[Symbol]) -> bool {
142        match &self.kind {
143            AttrKind::Normal(normal) => {
144                normal.item.path.segments.len() == name.len()
145                    && normal
146                        .item
147                        .path
148                        .segments
149                        .iter()
150                        .zip(name)
151                        .all(|(s, n)| s.args.is_none() && s.ident.name == *n)
152            }
153            AttrKind::DocComment(..) => false,
154        }
155    }
156
157    fn span(&self) -> Span {
158        self.span
159    }
160
161    fn is_word(&self) -> bool {
162        if let AttrKind::Normal(normal) = &self.kind {
163            matches!(normal.item.args, AttrItemKind::Unparsed(AttrArgs::Empty))
164        } else {
165            false
166        }
167    }
168
169    /// Returns a list of meta items if the attribute is delimited with parenthesis:
170    ///
171    /// ```text
172    /// #[attr(a, b = "c")] // Returns `Some()`.
173    /// #[attr = ""] // Returns `None`.
174    /// #[attr] // Returns `None`.
175    /// ```
176    fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
177        match &self.kind {
178            AttrKind::Normal(normal) => normal.item.meta_item_list(),
179            AttrKind::DocComment(..) => None,
180        }
181    }
182
183    /// Returns the string value in:
184    ///
185    /// ```text
186    /// #[attribute = "value"]
187    ///               ^^^^^^^
188    /// ```
189    ///
190    /// It returns `None` in any other cases, including doc comments if they
191    /// are not under the form `#[doc = "..."]`.
192    ///
193    /// It also returns `None` for:
194    ///
195    /// ```text
196    /// #[attr("value")]
197    /// ```
198    fn value_str(&self) -> Option<Symbol> {
199        match &self.kind {
200            AttrKind::Normal(normal) => normal.item.value_str(),
201            AttrKind::DocComment(..) => None,
202        }
203    }
204
205    /// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
206    /// * `///doc` returns `Some(("doc", DocFragmentKind::Sugared(CommentKind::Line)))`.
207    /// * `/** doc */` returns `Some(("doc", DocFragmentKind::Sugared(CommentKind::Block)))`.
208    /// * `#[doc = "doc"]` returns `Some(("doc", DocFragmentKind::Raw))`.
209    /// * `#[doc(...)]` returns `None`.
210    fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
211        match &self.kind {
212            AttrKind::DocComment(kind, data) => Some((*data, DocFragmentKind::Sugared(*kind))),
213            AttrKind::Normal(normal) if normal.item.path == sym::doc => {
214                if let Some(value) = normal.item.value_str()
215                    && let Some(value_span) = normal.item.value_span()
216                {
217                    Some((value, DocFragmentKind::Raw(value_span)))
218                } else {
219                    None
220                }
221            }
222            _ => None,
223        }
224    }
225
226    /// Returns the documentation if this is a doc comment or a sugared doc comment.
227    /// * `///doc` returns `Some("doc")`.
228    /// * `#[doc = "doc"]` returns `Some("doc")`.
229    /// * `#[doc(...)]` returns `None`.
230    fn doc_str(&self) -> Option<Symbol> {
231        match &self.kind {
232            AttrKind::DocComment(.., data) => Some(*data),
233            AttrKind::Normal(normal) if normal.item.path == sym::doc => normal.item.value_str(),
234            _ => None,
235        }
236    }
237
238    fn doc_resolution_scope(&self) -> Option<AttrStyle> {
239        match &self.kind {
240            AttrKind::DocComment(..) => Some(self.style),
241            AttrKind::Normal(normal)
242                if normal.item.path == sym::doc && normal.item.value_str().is_some() =>
243            {
244                Some(self.style)
245            }
246            _ => None,
247        }
248    }
249
250    fn is_automatically_derived_attr(&self) -> bool {
251        self.has_name(sym::automatically_derived)
252    }
253
254    fn is_doc_hidden(&self) -> bool {
255        self.has_name(sym::doc)
256            && self.meta_item_list().is_some_and(|l| list_contains_name(&l, sym::hidden))
257    }
258
259    fn is_doc_keyword_or_attribute(&self) -> bool {
260        if self.has_name(sym::doc)
261            && let Some(items) = self.meta_item_list()
262        {
263            for item in items {
264                if item.has_name(sym::keyword) || item.has_name(sym::attribute) {
265                    return true;
266                }
267            }
268        }
269        false
270    }
271}
272
273impl Attribute {
274    pub fn style(&self) -> AttrStyle {
275        self.style
276    }
277
278    pub fn may_have_doc_links(&self) -> bool {
279        self.doc_str().is_some_and(|s| comments::may_have_doc_links(s.as_str()))
280    }
281
282    /// Extracts the MetaItem from inside this Attribute.
283    pub fn meta(&self) -> Option<MetaItem> {
284        match &self.kind {
285            AttrKind::Normal(normal) => normal.item.meta(self.span),
286            AttrKind::DocComment(..) => None,
287        }
288    }
289
290    pub fn meta_kind(&self) -> Option<MetaItemKind> {
291        match &self.kind {
292            AttrKind::Normal(normal) => normal.item.meta_kind(),
293            AttrKind::DocComment(..) => None,
294        }
295    }
296
297    pub fn token_trees(&self) -> Vec<TokenTree> {
298        match self.kind {
299            AttrKind::Normal(ref normal) => normal
300                .tokens
301                .as_ref()
302                .unwrap_or_else(|| panic!("attribute is missing tokens: {self:?}"))
303                .to_attr_token_stream()
304                .to_token_trees(),
305            AttrKind::DocComment(comment_kind, data) => vec![TokenTree::token_alone(
306                token::DocComment(comment_kind, self.style, data),
307                self.span,
308            )],
309        }
310    }
311}
312
313impl AttrItem {
314    pub fn span(&self) -> Span {
315        self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
316    }
317
318    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
319        match &self.args.unparsed_ref()? {
320            AttrArgs::Delimited(args) if args.delim == Delimiter::Parenthesis => {
321                MetaItemKind::list_from_tokens(args.tokens.clone())
322            }
323            AttrArgs::Delimited(_) | AttrArgs::Eq { .. } | AttrArgs::Empty => None,
324        }
325    }
326
327    /// Returns the string value in:
328    ///
329    /// ```text
330    /// #[attribute = "value"]
331    ///               ^^^^^^^
332    /// ```
333    ///
334    /// It returns `None` in any other cases like:
335    ///
336    /// ```text
337    /// #[attr("value")]
338    /// ```
339    fn value_str(&self) -> Option<Symbol> {
340        match &self.args.unparsed_ref()? {
341            AttrArgs::Eq { expr, .. } => match expr.kind {
342                ExprKind::Lit(token_lit) => {
343                    LitKind::from_token_lit(token_lit).ok().and_then(|lit| lit.str())
344                }
345                _ => None,
346            },
347            AttrArgs::Delimited(_) | AttrArgs::Empty => None,
348        }
349    }
350
351    /// Returns the span in:
352    ///
353    /// ```text
354    /// #[attribute = "value"]
355    ///               ^^^^^^^
356    /// ```
357    ///
358    /// It returns `None` in any other cases like:
359    ///
360    /// ```text
361    /// #[attr("value")]
362    /// ```
363    fn value_span(&self) -> Option<Span> {
364        match &self.args.unparsed_ref()? {
365            AttrArgs::Eq { expr, .. } => Some(expr.span),
366            AttrArgs::Delimited(_) | AttrArgs::Empty => None,
367        }
368    }
369
370    pub fn meta(&self, span: Span) -> Option<MetaItem> {
371        Some(MetaItem {
372            unsafety: Safety::Default,
373            path: self.path.clone(),
374            kind: self.meta_kind()?,
375            span,
376        })
377    }
378
379    pub fn meta_kind(&self) -> Option<MetaItemKind> {
380        MetaItemKind::from_attr_args(self.args.unparsed_ref()?)
381    }
382}
383
384impl MetaItem {
385    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
386    pub fn ident(&self) -> Option<Ident> {
387        if let [PathSegment { ident, .. }] = self.path.segments[..] { Some(ident) } else { None }
388    }
389
390    pub fn name(&self) -> Option<Symbol> {
391        self.ident().map(|ident| ident.name)
392    }
393
394    pub fn has_name(&self, name: Symbol) -> bool {
395        self.path == name
396    }
397
398    pub fn is_word(&self) -> bool {
399        matches!(self.kind, MetaItemKind::Word)
400    }
401
402    pub fn meta_item_list(&self) -> Option<&[MetaItemInner]> {
403        match &self.kind {
404            MetaItemKind::List(l) => Some(&**l),
405            _ => None,
406        }
407    }
408
409    /// ```text
410    /// Example:
411    ///     #[attribute(name = "value")]
412    ///                 ^^^^^^^^^^^^^^
413    /// ```
414    pub fn name_value_literal(&self) -> Option<&MetaItemLit> {
415        match &self.kind {
416            MetaItemKind::NameValue(v) => Some(v),
417            _ => None,
418        }
419    }
420
421    /// This is used in case you want the value span instead of the whole attribute. Example:
422    ///
423    /// ```text
424    /// #[doc(alias = "foo")]
425    /// ```
426    ///
427    /// In here, it'll return a span for `"foo"`.
428    pub fn name_value_literal_span(&self) -> Option<Span> {
429        Some(self.name_value_literal()?.span)
430    }
431
432    /// Returns the string value in:
433    ///
434    /// ```text
435    /// #[attribute = "value"]
436    ///               ^^^^^^^
437    /// ```
438    ///
439    /// It returns `None` in any other cases like:
440    ///
441    /// ```text
442    /// #[attr("value")]
443    /// ```
444    pub fn value_str(&self) -> Option<Symbol> {
445        match &self.kind {
446            MetaItemKind::NameValue(v) => v.kind.str(),
447            _ => None,
448        }
449    }
450
451    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItem> {
452        // FIXME: Share code with `parse_path`.
453        let tt = iter.next().map(|tt| TokenTree::uninterpolate(tt));
454        let path = match tt.as_deref() {
455            Some(&TokenTree::Token(
456                Token { kind: ref kind @ (token::Ident(..) | token::PathSep), span },
457                _,
458            )) => 'arm: {
459                let mut segments = if let &token::Ident(name, _) = kind {
460                    if let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) =
461                        iter.peek()
462                    {
463                        iter.next();
464                        thin_vec![PathSegment::from_ident(Ident::new(name, span))]
465                    } else {
466                        break 'arm Path::from_ident(Ident::new(name, span));
467                    }
468                } else {
469                    thin_vec![PathSegment::path_root(span)]
470                };
471                loop {
472                    let Some(&TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
473                        iter.next().map(|tt| TokenTree::uninterpolate(tt)).as_deref()
474                    else {
475                        return None;
476                    };
477                    segments.push(PathSegment::from_ident(Ident::new(name, span)));
478                    let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) = iter.peek()
479                    else {
480                        break;
481                    };
482                    iter.next();
483                }
484                let span = span.with_hi(segments.last().unwrap().ident.span.hi());
485                Path { span, segments, tokens: None }
486            }
487            Some(TokenTree::Delimited(
488                _span,
489                _spacing,
490                Delimiter::Invisible(InvisibleOrigin::MetaVar(
491                    MetaVarKind::Meta { .. } | MetaVarKind::Path,
492                )),
493                _stream,
494            )) => {
495                // This path is currently unreachable in the test suite.
496                unreachable!()
497            }
498            Some(TokenTree::Token(Token { kind, .. }, _)) if kind.is_delim() => {
499                panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tt);
500            }
501            _ => return None,
502        };
503        let list_closing_paren_pos = iter.peek().map(|tt| tt.span().hi());
504        let kind = MetaItemKind::from_tokens(iter)?;
505        let hi = match &kind {
506            MetaItemKind::NameValue(lit) => lit.span.hi(),
507            MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
508            _ => path.span.hi(),
509        };
510        let span = path.span.with_hi(hi);
511        // FIXME: This parses `unsafe()` not as unsafe attribute syntax in `MetaItem`,
512        // but as a parenthesized list. This (and likely `MetaItem`) should be changed in
513        // such a way that builtin macros don't accept extraneous `unsafe()`.
514        Some(MetaItem { unsafety: Safety::Default, path, kind, span })
515    }
516}
517
518impl MetaItemKind {
519    // public because it can be called in the hir
520    pub fn list_from_tokens(tokens: TokenStream) -> Option<ThinVec<MetaItemInner>> {
521        let mut iter = tokens.iter();
522        let mut result = ThinVec::new();
523        while iter.peek().is_some() {
524            let item = MetaItemInner::from_tokens(&mut iter)?;
525            result.push(item);
526            match iter.next() {
527                None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
528                _ => return None,
529            }
530        }
531        Some(result)
532    }
533
534    fn name_value_from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemKind> {
535        match iter.next() {
536            Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => {
537                MetaItemKind::name_value_from_tokens(&mut inner_tokens.iter())
538            }
539            Some(TokenTree::Token(token, _)) => {
540                MetaItemLit::from_token(token).map(MetaItemKind::NameValue)
541            }
542            _ => None,
543        }
544    }
545
546    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemKind> {
547        match iter.peek() {
548            Some(TokenTree::Delimited(.., Delimiter::Parenthesis, inner_tokens)) => {
549                let inner_tokens = inner_tokens.clone();
550                iter.next();
551                MetaItemKind::list_from_tokens(inner_tokens).map(MetaItemKind::List)
552            }
553            Some(TokenTree::Delimited(..)) => None,
554            Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
555                iter.next();
556                MetaItemKind::name_value_from_tokens(iter)
557            }
558            _ => Some(MetaItemKind::Word),
559        }
560    }
561
562    fn from_attr_args(args: &AttrArgs) -> Option<MetaItemKind> {
563        match args {
564            AttrArgs::Empty => Some(MetaItemKind::Word),
565            AttrArgs::Delimited(DelimArgs { dspan: _, delim: Delimiter::Parenthesis, tokens }) => {
566                MetaItemKind::list_from_tokens(tokens.clone()).map(MetaItemKind::List)
567            }
568            AttrArgs::Delimited(..) => None,
569            AttrArgs::Eq { expr, .. } => match expr.kind {
570                ExprKind::Lit(token_lit) => {
571                    // Turn failures to `None`, we'll get parse errors elsewhere.
572                    MetaItemLit::from_token_lit(token_lit, expr.span)
573                        .ok()
574                        .map(|lit| MetaItemKind::NameValue(lit))
575                }
576                _ => None,
577            },
578        }
579    }
580}
581
582impl MetaItemInner {
583    pub fn span(&self) -> Span {
584        match self {
585            MetaItemInner::MetaItem(item) => item.span,
586            MetaItemInner::Lit(lit) => lit.span,
587        }
588    }
589
590    /// For a single-segment meta item, returns its identifier; otherwise, returns `None`.
591    pub fn ident(&self) -> Option<Ident> {
592        self.meta_item().and_then(|meta_item| meta_item.ident())
593    }
594
595    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
596    pub fn name(&self) -> Option<Symbol> {
597        self.ident().map(|ident| ident.name)
598    }
599
600    /// Returns `true` if this list item is a MetaItem with a name of `name`.
601    pub fn has_name(&self, name: Symbol) -> bool {
602        self.meta_item().is_some_and(|meta_item| meta_item.has_name(name))
603    }
604
605    /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
606    pub fn is_word(&self) -> bool {
607        self.meta_item().is_some_and(|meta_item| meta_item.is_word())
608    }
609
610    /// Gets a list of inner meta items from a list `MetaItem` type.
611    pub fn meta_item_list(&self) -> Option<&[MetaItemInner]> {
612        self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
613    }
614
615    /// If it's a singleton list of the form `foo(lit)`, returns the `foo` and
616    /// the `lit`.
617    pub fn singleton_lit_list(&self) -> Option<(Symbol, &MetaItemLit)> {
618        self.meta_item().and_then(|meta_item| {
619            meta_item.meta_item_list().and_then(|meta_item_list| {
620                if meta_item_list.len() == 1
621                    && let Some(ident) = meta_item.ident()
622                    && let Some(lit) = meta_item_list[0].lit()
623                {
624                    return Some((ident.name, lit));
625                }
626                None
627            })
628        })
629    }
630
631    /// See [`MetaItem::name_value_literal_span`].
632    pub fn name_value_literal_span(&self) -> Option<Span> {
633        self.meta_item()?.name_value_literal_span()
634    }
635
636    /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
637    /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
638    pub fn value_str(&self) -> Option<Symbol> {
639        self.meta_item().and_then(|meta_item| meta_item.value_str())
640    }
641
642    /// Returns the `MetaItemLit` if `self` is a `MetaItemInner::Literal`s.
643    pub fn lit(&self) -> Option<&MetaItemLit> {
644        match self {
645            MetaItemInner::Lit(lit) => Some(lit),
646            _ => None,
647        }
648    }
649
650    /// Returns the bool if `self` is a boolean `MetaItemInner::Literal`.
651    pub fn boolean_literal(&self) -> Option<bool> {
652        match self {
653            MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(b), .. }) => Some(*b),
654            _ => None,
655        }
656    }
657
658    /// Returns the `MetaItem` if `self` is a `MetaItemInner::MetaItem` or if it's
659    /// `MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(_), .. })`.
660    pub fn meta_item_or_bool(&self) -> Option<&MetaItemInner> {
661        match self {
662            MetaItemInner::MetaItem(_item) => Some(self),
663            MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(_), .. }) => Some(self),
664            _ => None,
665        }
666    }
667
668    /// Returns the `MetaItem` if `self` is a `MetaItemInner::MetaItem`.
669    pub fn meta_item(&self) -> Option<&MetaItem> {
670        match self {
671            MetaItemInner::MetaItem(item) => Some(item),
672            _ => None,
673        }
674    }
675
676    /// Returns `true` if the variant is `MetaItem`.
677    pub fn is_meta_item(&self) -> bool {
678        self.meta_item().is_some()
679    }
680
681    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemInner> {
682        match iter.peek() {
683            Some(TokenTree::Token(token, _)) if let Some(lit) = MetaItemLit::from_token(token) => {
684                iter.next();
685                return Some(MetaItemInner::Lit(lit));
686            }
687            Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => {
688                iter.next();
689                return MetaItemInner::from_tokens(&mut inner_tokens.iter());
690            }
691            _ => {}
692        }
693        MetaItem::from_tokens(iter).map(MetaItemInner::MetaItem)
694    }
695}
696
697pub fn mk_doc_comment(
698    g: &AttrIdGenerator,
699    comment_kind: CommentKind,
700    style: AttrStyle,
701    data: Symbol,
702    span: Span,
703) -> Attribute {
704    Attribute { kind: AttrKind::DocComment(comment_kind, data), id: g.mk_attr_id(), style, span }
705}
706
707fn mk_attr(
708    g: &AttrIdGenerator,
709    style: AttrStyle,
710    unsafety: Safety,
711    path: Path,
712    args: AttrArgs,
713    span: Span,
714) -> Attribute {
715    mk_attr_from_item(
716        g,
717        AttrItem { unsafety, path, args: AttrItemKind::Unparsed(args), tokens: None },
718        None,
719        style,
720        span,
721    )
722}
723
724pub fn mk_attr_from_item(
725    g: &AttrIdGenerator,
726    item: AttrItem,
727    tokens: Option<LazyAttrTokenStream>,
728    style: AttrStyle,
729    span: Span,
730) -> Attribute {
731    Attribute {
732        kind: AttrKind::Normal(Box::new(NormalAttr { item, tokens })),
733        id: g.mk_attr_id(),
734        style,
735        span,
736    }
737}
738
739pub fn mk_attr_word(
740    g: &AttrIdGenerator,
741    style: AttrStyle,
742    unsafety: Safety,
743    name: Symbol,
744    span: Span,
745) -> Attribute {
746    let path = Path::from_ident(Ident::new(name, span));
747    let args = AttrArgs::Empty;
748    mk_attr(g, style, unsafety, path, args, span)
749}
750
751pub fn mk_attr_nested_word(
752    g: &AttrIdGenerator,
753    style: AttrStyle,
754    unsafety: Safety,
755    outer: Symbol,
756    inner: Symbol,
757    span: Span,
758) -> Attribute {
759    let inner_tokens = TokenStream::new(vec![TokenTree::Token(
760        Token::from_ast_ident(Ident::new(inner, span)),
761        Spacing::Alone,
762    )]);
763    let outer_ident = Ident::new(outer, span);
764    let path = Path::from_ident(outer_ident);
765    let attr_args = AttrArgs::Delimited(DelimArgs {
766        dspan: DelimSpan::from_single(span),
767        delim: Delimiter::Parenthesis,
768        tokens: inner_tokens,
769    });
770    mk_attr(g, style, unsafety, path, attr_args, span)
771}
772
773pub fn mk_attr_name_value_str(
774    g: &AttrIdGenerator,
775    style: AttrStyle,
776    unsafety: Safety,
777    name: Symbol,
778    val: Symbol,
779    span: Span,
780) -> Attribute {
781    let lit = token::Lit::new(token::Str, escape_string_symbol(val), None);
782    let expr = Box::new(Expr {
783        id: DUMMY_NODE_ID,
784        kind: ExprKind::Lit(lit),
785        span,
786        attrs: AttrVec::new(),
787        tokens: None,
788    });
789    let path = Path::from_ident(Ident::new(name, span));
790    let args = AttrArgs::Eq { eq_span: span, expr };
791    mk_attr(g, style, unsafety, path, args, span)
792}
793
794pub fn filter_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> impl Iterator<Item = &A> {
795    attrs.iter().filter(move |attr| attr.has_name(name))
796}
797
798pub fn find_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> Option<&A> {
799    filter_by_name(attrs, name).next()
800}
801
802pub fn first_attr_value_str_by_name(attrs: &[impl AttributeExt], name: Symbol) -> Option<Symbol> {
803    find_by_name(attrs, name).and_then(|attr| attr.value_str())
804}
805
806pub fn contains_name(attrs: &[impl AttributeExt], name: Symbol) -> bool {
807    find_by_name(attrs, name).is_some()
808}
809
810pub fn list_contains_name(items: &[MetaItemInner], name: Symbol) -> bool {
811    items.iter().any(|item| item.has_name(name))
812}
813
814impl MetaItemLit {
815    pub fn value_str(&self) -> Option<Symbol> {
816        LitKind::from_token_lit(self.as_token_lit()).ok().and_then(|lit| lit.str())
817    }
818}
819
820pub trait AttributeExt: Debug {
821    fn id(&self) -> AttrId;
822
823    /// For a single-segment attribute (i.e., `#[attr]` and not `#[path::atrr]`),
824    /// return the name of the attribute; otherwise, returns `None`.
825    fn name(&self) -> Option<Symbol>;
826
827    /// Get the meta item list, `#[attr(meta item list)]`
828    fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>>;
829
830    /// Gets the value literal, as string, when using `#[attr = value]`
831    fn value_str(&self) -> Option<Symbol>;
832
833    /// Gets the span of the value literal, as string, when using `#[attr = value]`
834    fn value_span(&self) -> Option<Span>;
835
836    /// Checks whether the path of this attribute matches the name.
837    ///
838    /// Matches one segment of the path to each element in `name`
839    fn path_matches(&self, name: &[Symbol]) -> bool;
840
841    /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
842    /// So `#[doc = "doc"]` (which is a doc comment) and `#[doc(...)]` (which is not
843    /// a doc comment) will return `false`.
844    fn is_doc_comment(&self) -> Option<Span>;
845
846    #[inline]
847    fn has_name(&self, name: Symbol) -> bool {
848        self.name().map(|x| x == name).unwrap_or(false)
849    }
850
851    #[inline]
852    fn has_any_name(&self, names: &[Symbol]) -> bool {
853        names.iter().any(|&name| self.has_name(name))
854    }
855
856    /// get the span of the entire attribute
857    fn span(&self) -> Span;
858
859    fn is_word(&self) -> bool;
860
861    fn path(&self) -> SmallVec<[Symbol; 1]> {
862        self.symbol_path().unwrap_or(smallvec![sym::doc])
863    }
864
865    fn path_span(&self) -> Option<Span>;
866
867    /// Returns None for doc comments
868    fn symbol_path(&self) -> Option<SmallVec<[Symbol; 1]>>;
869
870    /// Returns the documentation if this is a doc comment or a sugared doc comment.
871    /// * `///doc` returns `Some("doc")`.
872    /// * `#[doc = "doc"]` returns `Some("doc")`.
873    /// * `#[doc(...)]` returns `None`.
874    fn doc_str(&self) -> Option<Symbol>;
875
876    fn is_proc_macro_attr(&self) -> bool {
877        [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
878            .iter()
879            .any(|kind| self.has_name(*kind))
880    }
881    fn is_automatically_derived_attr(&self) -> bool;
882
883    /// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
884    /// * `///doc` returns `Some(("doc", CommentKind::Line))`.
885    /// * `/** doc */` returns `Some(("doc", CommentKind::Block))`.
886    /// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`.
887    /// * `#[doc(...)]` returns `None`.
888    fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)>;
889
890    /// Returns outer or inner if this is a doc attribute or a sugared doc
891    /// comment, otherwise None.
892    ///
893    /// This is used in the case of doc comments on modules, to decide whether
894    /// to resolve intra-doc links against the symbols in scope within the
895    /// commented module (for inner doc) vs within its parent module (for outer
896    /// doc).
897    fn doc_resolution_scope(&self) -> Option<AttrStyle>;
898
899    /// Returns `true` if this attribute contains `doc(hidden)`.
900    fn is_doc_hidden(&self) -> bool;
901
902    /// Returns `true` is this attribute contains `doc(keyword)` or `doc(attribute)`.
903    fn is_doc_keyword_or_attribute(&self) -> bool;
904}
905
906// FIXME(fn_delegation): use function delegation instead of manually forwarding
907
908impl Attribute {
909    pub fn id(&self) -> AttrId {
910        AttributeExt::id(self)
911    }
912
913    pub fn name(&self) -> Option<Symbol> {
914        AttributeExt::name(self)
915    }
916
917    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
918        AttributeExt::meta_item_list(self)
919    }
920
921    pub fn value_str(&self) -> Option<Symbol> {
922        AttributeExt::value_str(self)
923    }
924
925    pub fn value_span(&self) -> Option<Span> {
926        AttributeExt::value_span(self)
927    }
928
929    pub fn path_matches(&self, name: &[Symbol]) -> bool {
930        AttributeExt::path_matches(self, name)
931    }
932
933    // on ast attributes we return a bool since that's what most code already expects
934    pub fn is_doc_comment(&self) -> bool {
935        AttributeExt::is_doc_comment(self).is_some()
936    }
937
938    #[inline]
939    pub fn has_name(&self, name: Symbol) -> bool {
940        AttributeExt::has_name(self, name)
941    }
942
943    #[inline]
944    pub fn has_any_name(&self, names: &[Symbol]) -> bool {
945        AttributeExt::has_any_name(self, names)
946    }
947
948    pub fn span(&self) -> Span {
949        AttributeExt::span(self)
950    }
951
952    pub fn is_word(&self) -> bool {
953        AttributeExt::is_word(self)
954    }
955
956    pub fn path(&self) -> SmallVec<[Symbol; 1]> {
957        AttributeExt::path(self)
958    }
959
960    pub fn doc_str(&self) -> Option<Symbol> {
961        AttributeExt::doc_str(self)
962    }
963
964    pub fn is_proc_macro_attr(&self) -> bool {
965        AttributeExt::is_proc_macro_attr(self)
966    }
967
968    pub fn doc_str_and_fragment_kind(&self) -> Option<(Symbol, DocFragmentKind)> {
969        AttributeExt::doc_str_and_fragment_kind(self)
970    }
971}