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.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 doc_resolution_scope(&self) -> Option<AttrStyle> {
210        match &self.kind {
211            AttrKind::DocComment(..) => Some(self.style),
212            AttrKind::Normal(normal)
213                if normal.item.path == sym::doc && normal.item.value_str().is_some() =>
214            {
215                Some(self.style)
216            }
217            _ => None,
218        }
219    }
220}
221
222impl Attribute {
223    pub fn style(&self) -> AttrStyle {
224        self.style
225    }
226
227    pub fn may_have_doc_links(&self) -> bool {
228        self.doc_str().is_some_and(|s| comments::may_have_doc_links(s.as_str()))
229    }
230
231    /// Extracts the MetaItem from inside this Attribute.
232    pub fn meta(&self) -> Option<MetaItem> {
233        match &self.kind {
234            AttrKind::Normal(normal) => normal.item.meta(self.span),
235            AttrKind::DocComment(..) => None,
236        }
237    }
238
239    pub fn meta_kind(&self) -> Option<MetaItemKind> {
240        match &self.kind {
241            AttrKind::Normal(normal) => normal.item.meta_kind(),
242            AttrKind::DocComment(..) => None,
243        }
244    }
245
246    pub fn token_trees(&self) -> Vec<TokenTree> {
247        match self.kind {
248            AttrKind::Normal(ref normal) => normal
249                .tokens
250                .as_ref()
251                .unwrap_or_else(|| panic!("attribute is missing tokens: {self:?}"))
252                .to_attr_token_stream()
253                .to_token_trees(),
254            AttrKind::DocComment(comment_kind, data) => vec![TokenTree::token_alone(
255                token::DocComment(comment_kind, self.style, data),
256                self.span,
257            )],
258        }
259    }
260}
261
262impl AttrItem {
263    pub fn span(&self) -> Span {
264        self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
265    }
266
267    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
268        match &self.args {
269            AttrArgs::Delimited(args) if args.delim == Delimiter::Parenthesis => {
270                MetaItemKind::list_from_tokens(args.tokens.clone())
271            }
272            AttrArgs::Delimited(_) | AttrArgs::Eq { .. } | AttrArgs::Empty => None,
273        }
274    }
275
276    /// Returns the string value in:
277    ///
278    /// ```text
279    /// #[attribute = "value"]
280    ///               ^^^^^^^
281    /// ```
282    ///
283    /// It returns `None` in any other cases like:
284    ///
285    /// ```text
286    /// #[attr("value")]
287    /// ```
288    fn value_str(&self) -> Option<Symbol> {
289        match &self.args {
290            AttrArgs::Eq { expr, .. } => match expr.kind {
291                ExprKind::Lit(token_lit) => {
292                    LitKind::from_token_lit(token_lit).ok().and_then(|lit| lit.str())
293                }
294                _ => None,
295            },
296            AttrArgs::Delimited(_) | AttrArgs::Empty => None,
297        }
298    }
299
300    pub fn meta(&self, span: Span) -> Option<MetaItem> {
301        Some(MetaItem {
302            unsafety: Safety::Default,
303            path: self.path.clone(),
304            kind: self.meta_kind()?,
305            span,
306        })
307    }
308
309    pub fn meta_kind(&self) -> Option<MetaItemKind> {
310        MetaItemKind::from_attr_args(&self.args)
311    }
312}
313
314impl MetaItem {
315    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
316    pub fn ident(&self) -> Option<Ident> {
317        if let [PathSegment { ident, .. }] = self.path.segments[..] { Some(ident) } else { None }
318    }
319
320    pub fn name(&self) -> Option<Symbol> {
321        self.ident().map(|ident| ident.name)
322    }
323
324    pub fn has_name(&self, name: Symbol) -> bool {
325        self.path == name
326    }
327
328    pub fn is_word(&self) -> bool {
329        matches!(self.kind, MetaItemKind::Word)
330    }
331
332    pub fn meta_item_list(&self) -> Option<&[MetaItemInner]> {
333        match &self.kind {
334            MetaItemKind::List(l) => Some(&**l),
335            _ => None,
336        }
337    }
338
339    /// ```text
340    /// Example:
341    ///     #[attribute(name = "value")]
342    ///                 ^^^^^^^^^^^^^^
343    /// ```
344    pub fn name_value_literal(&self) -> Option<&MetaItemLit> {
345        match &self.kind {
346            MetaItemKind::NameValue(v) => Some(v),
347            _ => None,
348        }
349    }
350
351    /// This is used in case you want the value span instead of the whole attribute. Example:
352    ///
353    /// ```text
354    /// #[doc(alias = "foo")]
355    /// ```
356    ///
357    /// In here, it'll return a span for `"foo"`.
358    pub fn name_value_literal_span(&self) -> Option<Span> {
359        Some(self.name_value_literal()?.span)
360    }
361
362    /// Returns the string value in:
363    ///
364    /// ```text
365    /// #[attribute = "value"]
366    ///               ^^^^^^^
367    /// ```
368    ///
369    /// It returns `None` in any other cases like:
370    ///
371    /// ```text
372    /// #[attr("value")]
373    /// ```
374    pub fn value_str(&self) -> Option<Symbol> {
375        match &self.kind {
376            MetaItemKind::NameValue(v) => v.kind.str(),
377            _ => None,
378        }
379    }
380
381    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItem> {
382        // FIXME: Share code with `parse_path`.
383        let tt = iter.next().map(|tt| TokenTree::uninterpolate(tt));
384        let path = match tt.as_deref() {
385            Some(&TokenTree::Token(
386                Token { kind: ref kind @ (token::Ident(..) | token::PathSep), span },
387                _,
388            )) => 'arm: {
389                let mut segments = if let &token::Ident(name, _) = kind {
390                    if let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) =
391                        iter.peek()
392                    {
393                        iter.next();
394                        thin_vec![PathSegment::from_ident(Ident::new(name, span))]
395                    } else {
396                        break 'arm Path::from_ident(Ident::new(name, span));
397                    }
398                } else {
399                    thin_vec![PathSegment::path_root(span)]
400                };
401                loop {
402                    if let Some(&TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
403                        iter.next().map(|tt| TokenTree::uninterpolate(tt)).as_deref()
404                    {
405                        segments.push(PathSegment::from_ident(Ident::new(name, span)));
406                    } else {
407                        return None;
408                    }
409                    if let Some(TokenTree::Token(Token { kind: token::PathSep, .. }, _)) =
410                        iter.peek()
411                    {
412                        iter.next();
413                    } else {
414                        break;
415                    }
416                }
417                let span = span.with_hi(segments.last().unwrap().ident.span.hi());
418                Path { span, segments, tokens: None }
419            }
420            Some(TokenTree::Delimited(
421                _span,
422                _spacing,
423                Delimiter::Invisible(InvisibleOrigin::MetaVar(
424                    MetaVarKind::Meta { .. } | MetaVarKind::Path,
425                )),
426                _stream,
427            )) => {
428                // This path is currently unreachable in the test suite.
429                unreachable!()
430            }
431            Some(TokenTree::Token(Token { kind, .. }, _)) if kind.is_delim() => {
432                panic!("Should be `AttrTokenTree::Delimited`, not delim tokens: {:?}", tt);
433            }
434            _ => return None,
435        };
436        let list_closing_paren_pos = iter.peek().map(|tt| tt.span().hi());
437        let kind = MetaItemKind::from_tokens(iter)?;
438        let hi = match &kind {
439            MetaItemKind::NameValue(lit) => lit.span.hi(),
440            MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
441            _ => path.span.hi(),
442        };
443        let span = path.span.with_hi(hi);
444        // FIXME: This parses `unsafe()` not as unsafe attribute syntax in `MetaItem`,
445        // but as a parenthesized list. This (and likely `MetaItem`) should be changed in
446        // such a way that builtin macros don't accept extraneous `unsafe()`.
447        Some(MetaItem { unsafety: Safety::Default, path, kind, span })
448    }
449}
450
451impl MetaItemKind {
452    // public because it can be called in the hir
453    pub fn list_from_tokens(tokens: TokenStream) -> Option<ThinVec<MetaItemInner>> {
454        let mut iter = tokens.iter();
455        let mut result = ThinVec::new();
456        while iter.peek().is_some() {
457            let item = MetaItemInner::from_tokens(&mut iter)?;
458            result.push(item);
459            match iter.next() {
460                None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
461                _ => return None,
462            }
463        }
464        Some(result)
465    }
466
467    fn name_value_from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemKind> {
468        match iter.next() {
469            Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => {
470                MetaItemKind::name_value_from_tokens(&mut inner_tokens.iter())
471            }
472            Some(TokenTree::Token(token, _)) => {
473                MetaItemLit::from_token(token).map(MetaItemKind::NameValue)
474            }
475            _ => None,
476        }
477    }
478
479    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemKind> {
480        match iter.peek() {
481            Some(TokenTree::Delimited(.., Delimiter::Parenthesis, inner_tokens)) => {
482                let inner_tokens = inner_tokens.clone();
483                iter.next();
484                MetaItemKind::list_from_tokens(inner_tokens).map(MetaItemKind::List)
485            }
486            Some(TokenTree::Delimited(..)) => None,
487            Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
488                iter.next();
489                MetaItemKind::name_value_from_tokens(iter)
490            }
491            _ => Some(MetaItemKind::Word),
492        }
493    }
494
495    fn from_attr_args(args: &AttrArgs) -> Option<MetaItemKind> {
496        match args {
497            AttrArgs::Empty => Some(MetaItemKind::Word),
498            AttrArgs::Delimited(DelimArgs { dspan: _, delim: Delimiter::Parenthesis, tokens }) => {
499                MetaItemKind::list_from_tokens(tokens.clone()).map(MetaItemKind::List)
500            }
501            AttrArgs::Delimited(..) => None,
502            AttrArgs::Eq { expr, .. } => match expr.kind {
503                ExprKind::Lit(token_lit) => {
504                    // Turn failures to `None`, we'll get parse errors elsewhere.
505                    MetaItemLit::from_token_lit(token_lit, expr.span)
506                        .ok()
507                        .map(|lit| MetaItemKind::NameValue(lit))
508                }
509                _ => None,
510            },
511        }
512    }
513}
514
515impl MetaItemInner {
516    pub fn span(&self) -> Span {
517        match self {
518            MetaItemInner::MetaItem(item) => item.span,
519            MetaItemInner::Lit(lit) => lit.span,
520        }
521    }
522
523    /// For a single-segment meta item, returns its identifier; otherwise, returns `None`.
524    pub fn ident(&self) -> Option<Ident> {
525        self.meta_item().and_then(|meta_item| meta_item.ident())
526    }
527
528    /// For a single-segment meta item, returns its name; otherwise, returns `None`.
529    pub fn name(&self) -> Option<Symbol> {
530        self.ident().map(|ident| ident.name)
531    }
532
533    /// Returns `true` if this list item is a MetaItem with a name of `name`.
534    pub fn has_name(&self, name: Symbol) -> bool {
535        self.meta_item().is_some_and(|meta_item| meta_item.has_name(name))
536    }
537
538    /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
539    pub fn is_word(&self) -> bool {
540        self.meta_item().is_some_and(|meta_item| meta_item.is_word())
541    }
542
543    /// Gets a list of inner meta items from a list `MetaItem` type.
544    pub fn meta_item_list(&self) -> Option<&[MetaItemInner]> {
545        self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
546    }
547
548    /// If it's a singleton list of the form `foo(lit)`, returns the `foo` and
549    /// the `lit`.
550    pub fn singleton_lit_list(&self) -> Option<(Symbol, &MetaItemLit)> {
551        self.meta_item().and_then(|meta_item| {
552            meta_item.meta_item_list().and_then(|meta_item_list| {
553                if meta_item_list.len() == 1
554                    && let Some(ident) = meta_item.ident()
555                    && let Some(lit) = meta_item_list[0].lit()
556                {
557                    return Some((ident.name, lit));
558                }
559                None
560            })
561        })
562    }
563
564    /// See [`MetaItem::name_value_literal_span`].
565    pub fn name_value_literal_span(&self) -> Option<Span> {
566        self.meta_item()?.name_value_literal_span()
567    }
568
569    /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
570    /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
571    pub fn value_str(&self) -> Option<Symbol> {
572        self.meta_item().and_then(|meta_item| meta_item.value_str())
573    }
574
575    /// Returns the `MetaItemLit` if `self` is a `MetaItemInner::Literal`s.
576    pub fn lit(&self) -> Option<&MetaItemLit> {
577        match self {
578            MetaItemInner::Lit(lit) => Some(lit),
579            _ => None,
580        }
581    }
582
583    /// Returns the bool if `self` is a boolean `MetaItemInner::Literal`.
584    pub fn boolean_literal(&self) -> Option<bool> {
585        match self {
586            MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(b), .. }) => Some(*b),
587            _ => None,
588        }
589    }
590
591    /// Returns the `MetaItem` if `self` is a `MetaItemInner::MetaItem` or if it's
592    /// `MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(_), .. })`.
593    pub fn meta_item_or_bool(&self) -> Option<&MetaItemInner> {
594        match self {
595            MetaItemInner::MetaItem(_item) => Some(self),
596            MetaItemInner::Lit(MetaItemLit { kind: LitKind::Bool(_), .. }) => Some(self),
597            _ => None,
598        }
599    }
600
601    /// Returns the `MetaItem` if `self` is a `MetaItemInner::MetaItem`.
602    pub fn meta_item(&self) -> Option<&MetaItem> {
603        match self {
604            MetaItemInner::MetaItem(item) => Some(item),
605            _ => None,
606        }
607    }
608
609    /// Returns `true` if the variant is `MetaItem`.
610    pub fn is_meta_item(&self) -> bool {
611        self.meta_item().is_some()
612    }
613
614    fn from_tokens(iter: &mut TokenStreamIter<'_>) -> Option<MetaItemInner> {
615        match iter.peek() {
616            Some(TokenTree::Token(token, _)) if let Some(lit) = MetaItemLit::from_token(token) => {
617                iter.next();
618                return Some(MetaItemInner::Lit(lit));
619            }
620            Some(TokenTree::Delimited(.., Delimiter::Invisible(_), inner_tokens)) => {
621                iter.next();
622                return MetaItemInner::from_tokens(&mut inner_tokens.iter());
623            }
624            _ => {}
625        }
626        MetaItem::from_tokens(iter).map(MetaItemInner::MetaItem)
627    }
628}
629
630pub fn mk_doc_comment(
631    g: &AttrIdGenerator,
632    comment_kind: CommentKind,
633    style: AttrStyle,
634    data: Symbol,
635    span: Span,
636) -> Attribute {
637    Attribute { kind: AttrKind::DocComment(comment_kind, data), id: g.mk_attr_id(), style, span }
638}
639
640fn mk_attr(
641    g: &AttrIdGenerator,
642    style: AttrStyle,
643    unsafety: Safety,
644    path: Path,
645    args: AttrArgs,
646    span: Span,
647) -> Attribute {
648    mk_attr_from_item(g, AttrItem { unsafety, path, args, tokens: None }, None, style, span)
649}
650
651pub fn mk_attr_from_item(
652    g: &AttrIdGenerator,
653    item: AttrItem,
654    tokens: Option<LazyAttrTokenStream>,
655    style: AttrStyle,
656    span: Span,
657) -> Attribute {
658    Attribute {
659        kind: AttrKind::Normal(P(NormalAttr { item, tokens })),
660        id: g.mk_attr_id(),
661        style,
662        span,
663    }
664}
665
666pub fn mk_attr_word(
667    g: &AttrIdGenerator,
668    style: AttrStyle,
669    unsafety: Safety,
670    name: Symbol,
671    span: Span,
672) -> Attribute {
673    let path = Path::from_ident(Ident::new(name, span));
674    let args = AttrArgs::Empty;
675    mk_attr(g, style, unsafety, path, args, span)
676}
677
678pub fn mk_attr_nested_word(
679    g: &AttrIdGenerator,
680    style: AttrStyle,
681    unsafety: Safety,
682    outer: Symbol,
683    inner: Symbol,
684    span: Span,
685) -> Attribute {
686    let inner_tokens = TokenStream::new(vec![TokenTree::Token(
687        Token::from_ast_ident(Ident::new(inner, span)),
688        Spacing::Alone,
689    )]);
690    let outer_ident = Ident::new(outer, span);
691    let path = Path::from_ident(outer_ident);
692    let attr_args = AttrArgs::Delimited(DelimArgs {
693        dspan: DelimSpan::from_single(span),
694        delim: Delimiter::Parenthesis,
695        tokens: inner_tokens,
696    });
697    mk_attr(g, style, unsafety, path, attr_args, span)
698}
699
700pub fn mk_attr_name_value_str(
701    g: &AttrIdGenerator,
702    style: AttrStyle,
703    unsafety: Safety,
704    name: Symbol,
705    val: Symbol,
706    span: Span,
707) -> Attribute {
708    let lit = token::Lit::new(token::Str, escape_string_symbol(val), None);
709    let expr = P(Expr {
710        id: DUMMY_NODE_ID,
711        kind: ExprKind::Lit(lit),
712        span,
713        attrs: AttrVec::new(),
714        tokens: None,
715    });
716    let path = Path::from_ident(Ident::new(name, span));
717    let args = AttrArgs::Eq { eq_span: span, expr };
718    mk_attr(g, style, unsafety, path, args, span)
719}
720
721pub fn filter_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> impl Iterator<Item = &A> {
722    attrs.iter().filter(move |attr| attr.has_name(name))
723}
724
725pub fn find_by_name<A: AttributeExt>(attrs: &[A], name: Symbol) -> Option<&A> {
726    filter_by_name(attrs, name).next()
727}
728
729pub fn first_attr_value_str_by_name(attrs: &[impl AttributeExt], name: Symbol) -> Option<Symbol> {
730    find_by_name(attrs, name).and_then(|attr| attr.value_str())
731}
732
733pub fn contains_name(attrs: &[impl AttributeExt], name: Symbol) -> bool {
734    find_by_name(attrs, name).is_some()
735}
736
737pub fn list_contains_name(items: &[MetaItemInner], name: Symbol) -> bool {
738    items.iter().any(|item| item.has_name(name))
739}
740
741impl MetaItemLit {
742    pub fn value_str(&self) -> Option<Symbol> {
743        LitKind::from_token_lit(self.as_token_lit()).ok().and_then(|lit| lit.str())
744    }
745}
746
747pub trait AttributeExt: Debug {
748    fn id(&self) -> AttrId;
749
750    /// For a single-segment attribute (i.e., `#[attr]` and not `#[path::atrr]`),
751    /// return the name of the attribute; otherwise, returns `None`.
752    fn name(&self) -> Option<Symbol> {
753        self.ident().map(|ident| ident.name)
754    }
755
756    /// Get the meta item list, `#[attr(meta item list)]`
757    fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>>;
758
759    /// Gets the value literal, as string, when using `#[attr = value]`
760    fn value_str(&self) -> Option<Symbol>;
761
762    /// Gets the span of the value literal, as string, when using `#[attr = value]`
763    fn value_span(&self) -> Option<Span>;
764
765    /// For a single-segment attribute, returns its ident; otherwise, returns `None`.
766    fn ident(&self) -> Option<Ident>;
767
768    /// Checks whether the path of this attribute matches the name.
769    ///
770    /// Matches one segment of the path to each element in `name`
771    fn path_matches(&self, name: &[Symbol]) -> bool;
772
773    /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
774    /// So `#[doc = "doc"]` (which is a doc comment) and `#[doc(...)]` (which is not
775    /// a doc comment) will return `false`.
776    fn is_doc_comment(&self) -> bool;
777
778    #[inline]
779    fn has_name(&self, name: Symbol) -> bool {
780        self.ident().map(|x| x.name == name).unwrap_or(false)
781    }
782
783    #[inline]
784    fn has_any_name(&self, names: &[Symbol]) -> bool {
785        names.iter().any(|&name| self.has_name(name))
786    }
787
788    /// get the span of the entire attribute
789    fn span(&self) -> Span;
790
791    fn is_word(&self) -> bool;
792
793    fn path(&self) -> SmallVec<[Symbol; 1]> {
794        self.ident_path()
795            .map(|i| i.into_iter().map(|i| i.name).collect())
796            .unwrap_or(smallvec![sym::doc])
797    }
798
799    /// Returns None for doc comments
800    fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>>;
801
802    /// Returns the documentation if this is a doc comment or a sugared doc comment.
803    /// * `///doc` returns `Some("doc")`.
804    /// * `#[doc = "doc"]` returns `Some("doc")`.
805    /// * `#[doc(...)]` returns `None`.
806    fn doc_str(&self) -> Option<Symbol>;
807
808    fn is_proc_macro_attr(&self) -> bool {
809        [sym::proc_macro, sym::proc_macro_attribute, sym::proc_macro_derive]
810            .iter()
811            .any(|kind| self.has_name(*kind))
812    }
813
814    /// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
815    /// * `///doc` returns `Some(("doc", CommentKind::Line))`.
816    /// * `/** doc */` returns `Some(("doc", CommentKind::Block))`.
817    /// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`.
818    /// * `#[doc(...)]` returns `None`.
819    fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)>;
820
821    /// Returns outer or inner if this is a doc attribute or a sugared doc
822    /// comment, otherwise None.
823    ///
824    /// This is used in the case of doc comments on modules, to decide whether
825    /// to resolve intra-doc links against the symbols in scope within the
826    /// commented module (for inner doc) vs within its parent module (for outer
827    /// doc).
828    fn doc_resolution_scope(&self) -> Option<AttrStyle>;
829}
830
831// FIXME(fn_delegation): use function delegation instead of manually forwarding
832
833impl Attribute {
834    pub fn id(&self) -> AttrId {
835        AttributeExt::id(self)
836    }
837
838    pub fn name(&self) -> Option<Symbol> {
839        AttributeExt::name(self)
840    }
841
842    pub fn meta_item_list(&self) -> Option<ThinVec<MetaItemInner>> {
843        AttributeExt::meta_item_list(self)
844    }
845
846    pub fn value_str(&self) -> Option<Symbol> {
847        AttributeExt::value_str(self)
848    }
849
850    pub fn value_span(&self) -> Option<Span> {
851        AttributeExt::value_span(self)
852    }
853
854    pub fn ident(&self) -> Option<Ident> {
855        AttributeExt::ident(self)
856    }
857
858    pub fn path_matches(&self, name: &[Symbol]) -> bool {
859        AttributeExt::path_matches(self, name)
860    }
861
862    pub fn is_doc_comment(&self) -> bool {
863        AttributeExt::is_doc_comment(self)
864    }
865
866    #[inline]
867    pub fn has_name(&self, name: Symbol) -> bool {
868        AttributeExt::has_name(self, name)
869    }
870
871    #[inline]
872    pub fn has_any_name(&self, names: &[Symbol]) -> bool {
873        AttributeExt::has_any_name(self, names)
874    }
875
876    pub fn span(&self) -> Span {
877        AttributeExt::span(self)
878    }
879
880    pub fn is_word(&self) -> bool {
881        AttributeExt::is_word(self)
882    }
883
884    pub fn path(&self) -> SmallVec<[Symbol; 1]> {
885        AttributeExt::path(self)
886    }
887
888    pub fn ident_path(&self) -> Option<SmallVec<[Ident; 1]>> {
889        AttributeExt::ident_path(self)
890    }
891
892    pub fn doc_str(&self) -> Option<Symbol> {
893        AttributeExt::doc_str(self)
894    }
895
896    pub fn is_proc_macro_attr(&self) -> bool {
897        AttributeExt::is_proc_macro_attr(self)
898    }
899
900    pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
901        AttributeExt::doc_str_and_comment_kind(self)
902    }
903}