rustc_ast/attr/
mod.rs

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