Skip to main content

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