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