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, InvisibleOrigin, MetaVarKind, 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::Delimited(
409                _span,
410                _spacing,
411                Delimiter::Invisible(InvisibleOrigin::MetaVar(
412                    MetaVarKind::Meta { .. } | MetaVarKind::Path,
413                )),
414                _stream,
415            )) => {
416                // This path is currently unreachable in the test suite.
417                unreachable!()
418            }
419            Some(TokenTree::Token(
420                Token { kind: token::OpenDelim(_) | token::CloseDelim(_), .. },
421                _,
422            )) => {
423                panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tt);
424            }
425            _ => return None,
426        };
427        let list_closing_paren_pos = iter.peek().map(|tt| tt.span().hi());
428        let kind = MetaItemKind::from_tokens(iter)?;
429        let hi = match &kind {
430            MetaItemKind::NameValue(lit) => lit.span.hi(),
431            MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
432            _ => path.span.hi(),
433        };
434        let span = path.span.with_hi(hi);
435        // FIXME: This parses `unsafe()` not as unsafe attribute syntax in `MetaItem`,
436        // but as a parenthesized list. This (and likely `MetaItem`) should be changed in
437        // such a way that builtin macros don't accept extraneous `unsafe()`.
438        Some(MetaItem { unsafety: Safety::Default, path, kind, span })
439    }
440}
441
442impl MetaItemKind {
443    // public because it can be called in the hir
444    pub fn list_from_tokens(tokens: TokenStream) -> Option<ThinVec<MetaItemInner>> {
445        let mut iter = tokens.iter();
446        let mut result = ThinVec::new();
447        while iter.peek().is_some() {
448            let item = MetaItemInner::from_tokens(&mut iter)?;
449            result.push(item);
450            match iter.next() {
451                None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
452                _ => return None,
453            }
454        }
455        Some(result)
456    }
457
458    fn name_value_from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemKind> {
459        match iter.next() {
460            Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => {
461                MetaItemKind::name_value_from_tokens(&mut inner_tokens.iter())
462            }
463            Some(TokenTree::Token(token, _)) => {
464                MetaItemLit::from_token(token).map(MetaItemKind::NameValue)
465            }
466            _ => None,
467        }
468    }
469
470    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemKind> {
471        match iter.peek() {
472            Some(TokenTree::Delimited(.., Delimiter::Parenthesis, inner_tokens)) => {
473                let inner_tokens = inner_tokens.clone();
474                iter.next();
475                MetaItemKind::list_from_tokens(inner_tokens).map(MetaItemKind::List)
476            }
477            Some(TokenTree::Delimited(..)) => None,
478            Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
479                iter.next();
480                MetaItemKind::name_value_from_tokens(iter)
481            }
482            _ => Some(MetaItemKind::Word),
483        }
484    }
485
486    fn from_attr_args(args: &AttrArgs) -> Option<MetaItemKind> {
487        match args {
488            AttrArgs::Empty => Some(MetaItemKind::Word),
489            AttrArgs::Delimited(DelimArgs { dspan: _, delim: Delimiter::Parenthesis, tokens }) => {
490                MetaItemKind::list_from_tokens(tokens.clone()).map(MetaItemKind::List)
491            }
492            AttrArgs::Delimited(..) => None,
493            AttrArgs::Eq { expr, .. } => match expr.kind {
494                ExprKind::Lit(token_lit) => {
495                    // Turn failures to `None`, we'll get parse errors elsewhere.
496                    MetaItemLit::from_token_lit(token_lit, expr.span)
497                        .ok()
498                        .map(|lit| MetaItemKind::NameValue(lit))
499                }
500                _ => None,
501            },
502        }
503    }
504}
505
506impl MetaItemInner {
507    pub fn span(&self) -> Span {
508        match self {
509            MetaItemInner::MetaItem(item) => item.span,
510            MetaItemInner::Lit(lit) => lit.span,
511        }
512    }
513
514    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
515    pub fn ident(&self) -> Option<Ident> {
516        self.meta_item().and_then(|meta_item| meta_item.ident())
517    }
518
519    pub fn name_or_empty(&self) -> Symbol {
520        self.ident().unwrap_or_else(Ident::empty).name
521    }
522
523    /// Returns `true` if this list item is a MetaItem with a name of `name`.
524    pub fn has_name(&self, name: Symbol) -> bool {
525        self.meta_item().is_some_and(|meta_item| meta_item.has_name(name))
526    }
527
528    /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
529    pub fn is_word(&self) -> bool {
530        self.meta_item().is_some_and(|meta_item| meta_item.is_word())
531    }
532
533    /// Gets a list of inner meta items from a list `MetaItem` type.
534    pub fn meta_item_list(&self) -> Option<&[MetaItemInner]> {
535        self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
536    }
537
538    /// If it's a singleton list of the form `foo(lit)`, returns the `foo` and
539    /// the `lit`.
540    pub fn singleton_lit_list(&self) -> Option<(Symbol, &MetaItemLit)> {
541        self.meta_item().and_then(|meta_item| {
542            meta_item.meta_item_list().and_then(|meta_item_list| {
543                if meta_item_list.len() == 1
544                    && let Some(ident) = meta_item.ident()
545                    && let Some(lit) = meta_item_list[0].lit()
546                {
547                    return Some((ident.name, lit));
548                }
549                None
550            })
551        })
552    }
553
554    /// See [`MetaItem::name_value_literal_span`].
555    pub fn name_value_literal_span(&self) -> Option<Span> {
556        self.meta_item()?.name_value_literal_span()
557    }
558
559    /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
560    /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
561    pub fn value_str(&self) -> Option<Symbol> {
562        self.meta_item().and_then(|meta_item| meta_item.value_str())
563    }
564
565    /// Returns the `MetaItemLit` if `self` is a `MetaItemInner::Literal`s.
566    pub fn lit(&self) -> Option<&MetaItemLit> {
567        match self {
568            MetaItemInner::Lit(lit) => Some(lit),
569            _ => None,
570        }
571    }
572
573    /// Returns the `MetaItem` if `self` is a `MetaItemInner::MetaItem` or if it's
574    /// `MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(_), .. })`.
575    pub fn meta_item_or_bool(&self) -> Option<&MetaItemInner> {
576        match self {
577            MetaItemInner::MetaItem(_item) => Some(self),
578            MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(_), .. }) => Some(self),
579            _ => None,
580        }
581    }
582
583    /// Returns the `MetaItem` if `self` is a `MetaItemInner::MetaItem`.
584    pub fn meta_item(&self) -> Option<&MetaItem> {
585        match self {
586            MetaItemInner::MetaItem(item) => Some(item),
587            _ => None,
588        }
589    }
590
591    /// Returns `true` if the variant is `MetaItem`.
592    pub fn is_meta_item(&self) -> bool {
593        self.meta_item().is_some()
594    }
595
596    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemInner> {
597        match iter.peek() {
598            Some(TokenTree::Token(token, _)) if let Some(lit) = MetaItemLit::from_token(token) => {
599                iter.next();
600                return Some(MetaItemInner::Lit(lit));
601            }
602            Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => {
603                iter.next();
604                return MetaItemInner::from_tokens(&mut inner_tokens.iter());
605            }
606            _ => {}
607        }
608        MetaItem::from_tokens(iter).map(MetaItemInner::MetaItem)
609    }
610}
611
612pub fn mk_doc_comment(
613    g: &AttrIdGenerator,
614    comment_kind: CommentKind,
615    style: AttrStyle,
616    data: Symbol,
617    span: Span,
618) -> Attribute {
619    Attribute { kind: AttrKind::DocComment(comment_kind, data), id: g.mk_attr_id(), style, span }
620}
621
622pub fn mk_attr(
623    g: &AttrIdGenerator,
624    style: AttrStyle,
625    unsafety: Safety,
626    path: Path,
627    args: AttrArgs,
628    span: Span,
629) -> Attribute {
630    mk_attr_from_item(g, AttrItem { unsafety, path, args, tokens: None }, None, style, span)
631}
632
633pub fn mk_attr_from_item(
634    g: &AttrIdGenerator,
635    item: AttrItem,
636    tokens: Option<LazyAttrTokenStream>,
637    style: AttrStyle,
638    span: Span,
639) -> Attribute {
640    Attribute {
641        kind: AttrKind::Normal(P(NormalAttr { item, tokens })),
642        id: g.mk_attr_id(),
643        style,
644        span,
645    }
646}
647
648pub fn mk_attr_word(
649    g: &AttrIdGenerator,
650    style: AttrStyle,
651    unsafety: Safety,
652    name: Symbol,
653    span: Span,
654) -> Attribute {
655    let path = Path::from_ident(Ident::new(name, span));
656    let args = AttrArgs::Empty;
657    mk_attr(g, style, unsafety, path, args, span)
658}
659
660pub fn mk_attr_nested_word(
661    g: &AttrIdGenerator,
662    style: AttrStyle,
663    unsafety: Safety,
664    outer: Symbol,
665    inner: Symbol,
666    span: Span,
667) -> Attribute {
668    let inner_tokens = TokenStream::new(vec![TokenTree::Token(
669        Token::from_ast_ident(Ident::new(inner, span)),
670        Spacing::Alone,
671    )]);
672    let outer_ident = Ident::new(outer, span);
673    let path = Path::from_ident(outer_ident);
674    let attr_args = AttrArgs::Delimited(DelimArgs {
675        dspan: DelimSpan::from_single(span),
676        delim: Delimiter::Parenthesis,
677        tokens: inner_tokens,
678    });
679    mk_attr(g, style, unsafety, path, attr_args, span)
680}
681
682pub fn mk_attr_name_value_str(
683    g: &AttrIdGenerator,
684    style: AttrStyle,
685    unsafety: Safety,
686    name: Symbol,
687    val: Symbol,
688    span: Span,
689) -> Attribute {
690    let lit = token::Lit::new(token::Str, escape_string_symbol(val), None);
691    let expr = P(Expr {
692        id: DUMMY_NODE_ID,
693        kind: ExprKind::Lit(lit),
694        span,
695        attrs: AttrVec::new(),
696        tokens: None,
697    });
698    let path = Path::from_ident(Ident::new(name, span));
699    let args = AttrArgs::Eq { eq_span: span, expr };
700    mk_attr(g, style, unsafety, path, args, span)
701}
702
703pub fn filter_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> impl Iterator<Item = &A> {
704    attrs.iter().filter(move |attr| attr.has_name(name))
705}
706
707pub fn find_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> Option<&A> {
708    filter_by_name(attrs, name).next()
709}
710
711pub fn first_attr_value_str_by_name(attrs: &[impl AttributeExt], name: Symbol) -> Option<Symbol> {
712    find_by_name(attrs, name).and_then(|attr| attr.value_str())
713}
714
715pub fn contains_name(attrs: &[impl AttributeExt], name: Symbol) -> bool {
716    find_by_name(attrs, name).is_some()
717}
718
719pub fn list_contains_name(items: &[MetaItemInner], name: Symbol) -> bool {
720    items.iter().any(|item| item.has_name(name))
721}
722
723impl MetaItemLit {
724    pub fn value_str(&self) -> Option<Symbol> {
725        LitKind::from_token_lit(self.as_token_lit()).ok().and_then(|lit| lit.str())
726    }
727}
728
729pub trait AttributeExt: Debug {
730    fn id(&self) -> AttrId;
731
732    /// For a single-segment attribute (i.e., `#[attr]` and not `#[path::atrr]`),
733    /// return the name of the attribute, else return the empty identifier.
734    fn name_or_empty(&self) -> Symbol {
735        self.ident().unwrap_or_else(Ident::empty).name
736    }
737
738    /// Get the meta item list, `#[attr(meta item list)]`
739    fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>>;
740
741    /// Gets the value literal, as string, when using `#[attr = value]`
742    fn value_str(&self) -> Option<Symbol>;
743
744    /// Gets the span of the value literal, as string, when using `#[attr = value]`
745    fn value_span(&self) -> Option<Span>;
746
747    /// For a single-segment attribute, returns its name; otherwise, returns `None`.
748    fn ident(&self) -> Option<Ident>;
749
750    /// Checks whether the path of this attribute matches the name.
751    ///
752    /// Matches one segment of the path to each element in `name`
753    fn path_matches(&self, name: &[Symbol]) -> bool;
754
755    /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
756    /// So `#[doc = "doc"]` (which is a doc comment) and `#[doc(...)]` (which is not
757    /// a doc comment) will return `false`.
758    fn is_doc_comment(&self) -> bool;
759
760    #[inline]
761    fn has_name(&self, name: Symbol) -> bool {
762        self.ident().map(|x| x.name == name).unwrap_or(false)
763    }
764
765    /// get the span of the entire attribute
766    fn span(&self) -> Span;
767
768    fn is_word(&self) -> bool;
769
770    fn path(&self) -> SmallVec<[Symbol; 1]> {
771        self.ident_path()
772            .map(|i| i.into_iter().map(|i| i.name).collect())
773            .unwrap_or(smallvec![sym::doc])
774    }
775
776    /// Returns None for doc comments
777    fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>>;
778
779    /// Returns the documentation if this is a doc comment or a sugared doc comment.
780    /// * `///doc` returns `Some("doc")`.
781    /// * `#[doc = "doc"]` returns `Some("doc")`.
782    /// * `#[doc(...)]` returns `None`.
783    fn doc_str(&self) -> Option<Symbol>;
784
785    fn is_proc_macro_attr(&self) -> bool {
786        [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
787            .iter()
788            .any(|kind| self.has_name(*kind))
789    }
790
791    /// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
792    /// * `///doc` returns `Some(("doc", CommentKind::Line))`.
793    /// * `/** doc */` returns `Some(("doc", CommentKind::Block))`.
794    /// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`.
795    /// * `#[doc(...)]` returns `None`.
796    fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)>;
797
798    fn style(&self) -> AttrStyle;
799}
800
801// FIXME(fn_delegation): use function delegation instead of manually forwarding
802
803impl Attribute {
804    pub fn id(&self) -> AttrId {
805        AttributeExt::id(self)
806    }
807
808    pub fn name_or_empty(&self) -> Symbol {
809        AttributeExt::name_or_empty(self)
810    }
811
812    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
813        AttributeExt::meta_item_list(self)
814    }
815
816    pub fn value_str(&self) -> Option<Symbol> {
817        AttributeExt::value_str(self)
818    }
819
820    pub fn value_span(&self) -> Option<Span> {
821        AttributeExt::value_span(self)
822    }
823
824    pub fn ident(&self) -> Option<Ident> {
825        AttributeExt::ident(self)
826    }
827
828    pub fn path_matches(&self, name: &[Symbol]) -> bool {
829        AttributeExt::path_matches(self, name)
830    }
831
832    pub fn is_doc_comment(&self) -> bool {
833        AttributeExt::is_doc_comment(self)
834    }
835
836    #[inline]
837    pub fn has_name(&self, name: Symbol) -> bool {
838        AttributeExt::has_name(self, name)
839    }
840
841    pub fn span(&self) -> Span {
842        AttributeExt::span(self)
843    }
844
845    pub fn is_word(&self) -> bool {
846        AttributeExt::is_word(self)
847    }
848
849    pub fn path(&self) -> SmallVec<[Symbol; 1]> {
850        AttributeExt::path(self)
851    }
852
853    pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
854        AttributeExt::ident_path(self)
855    }
856
857    pub fn doc_str(&self) -> Option<Symbol> {
858        AttributeExt::doc_str(self)
859    }
860
861    pub fn is_proc_macro_attr(&self) -> bool {
862        AttributeExt::is_proc_macro_attr(self)
863    }
864
865    pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
866        AttributeExt::doc_str_and_comment_kind(self)
867    }
868
869    pub fn style(&self) -> AttrStyle {
870        AttributeExt::style(self)
871    }
872}