1 //! Functions dealing with attributes and meta items.
4 use crate::ast::{AttrArgs, AttrArgsEq, AttrId, AttrItem, AttrKind, AttrStyle, Attribute};
5 use crate::ast::{DelimArgs, Lit, LitKind};
6 use crate::ast::{MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem};
7 use crate::ast::{Path, PathSegment};
9 use crate::token::{self, CommentKind, Delimiter, Token};
10 use crate::tokenstream::{DelimSpan, Spacing, TokenTree};
11 use crate::tokenstream::{LazyAttrTokenStream, TokenStream};
12 use crate::util::comments;
13 use rustc_data_structures::sync::WorkerLocal;
14 use rustc_index::bit_set::GrowableBitSet;
15 use rustc_span::source_map::BytePos;
16 use rustc_span::symbol::{sym, Ident, Symbol};
20 #[cfg(debug_assertions)]
22 #[cfg(debug_assertions)]
23 use std::sync::atomic::{AtomicU32, Ordering};
24 use thin_vec::thin_vec;
26 pub struct MarkedAttrs(GrowableBitSet<AttrId>);
29 // We have no idea how many attributes there will be, so just
30 // initiate the vectors with 0 bits. We'll grow them as necessary.
31 pub fn new() -> Self {
32 MarkedAttrs(GrowableBitSet::new_empty())
35 pub fn mark(&mut self, attr: &Attribute) {
36 self.0.insert(attr.id);
39 pub fn is_marked(&self, attr: &Attribute) -> bool {
40 self.0.contains(attr.id)
45 /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
46 pub fn meta_item(&self) -> Option<&MetaItem> {
48 NestedMetaItem::MetaItem(item) => Some(item),
53 /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
54 pub fn literal(&self) -> Option<&Lit> {
56 NestedMetaItem::Literal(lit) => Some(lit),
61 /// Returns `true` if this list item is a MetaItem with a name of `name`.
62 pub fn has_name(&self, name: Symbol) -> bool {
63 self.meta_item().map_or(false, |meta_item| meta_item.has_name(name))
66 /// For a single-segment meta item, returns its name; otherwise, returns `None`.
67 pub fn ident(&self) -> Option<Ident> {
68 self.meta_item().and_then(|meta_item| meta_item.ident())
70 pub fn name_or_empty(&self) -> Symbol {
71 self.ident().unwrap_or_else(Ident::empty).name
74 /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
75 /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
76 pub fn value_str(&self) -> Option<Symbol> {
77 self.meta_item().and_then(|meta_item| meta_item.value_str())
80 /// Returns a name and single literal value tuple of the `MetaItem`.
81 pub fn name_value_literal(&self) -> Option<(Symbol, &Lit)> {
82 self.meta_item().and_then(|meta_item| {
83 meta_item.meta_item_list().and_then(|meta_item_list| {
84 if meta_item_list.len() == 1
85 && let Some(ident) = meta_item.ident()
86 && let Some(lit) = meta_item_list[0].literal()
88 return Some((ident.name, lit));
95 /// Gets a list of inner meta items from a list `MetaItem` type.
96 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
97 self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
100 /// Returns `true` if the variant is `MetaItem`.
101 pub fn is_meta_item(&self) -> bool {
102 self.meta_item().is_some()
105 /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
106 pub fn is_word(&self) -> bool {
107 self.meta_item().map_or(false, |meta_item| meta_item.is_word())
110 /// See [`MetaItem::name_value_literal_span`].
111 pub fn name_value_literal_span(&self) -> Option<Span> {
112 self.meta_item()?.name_value_literal_span()
118 pub fn has_name(&self, name: Symbol) -> bool {
120 AttrKind::Normal(normal) => normal.item.path == name,
121 AttrKind::DocComment(..) => false,
125 /// For a single-segment attribute, returns its name; otherwise, returns `None`.
126 pub fn ident(&self) -> Option<Ident> {
128 AttrKind::Normal(normal) => {
129 if let [ident] = &*normal.item.path.segments {
135 AttrKind::DocComment(..) => None,
138 pub fn name_or_empty(&self) -> Symbol {
139 self.ident().unwrap_or_else(Ident::empty).name
142 pub fn value_str(&self) -> Option<Symbol> {
144 AttrKind::Normal(normal) => normal.item.meta_kind().and_then(|kind| kind.value_str()),
145 AttrKind::DocComment(..) => None,
149 pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
151 AttrKind::Normal(normal) => match normal.item.meta_kind() {
152 Some(MetaItemKind::List(list)) => Some(list),
155 AttrKind::DocComment(..) => None,
159 pub fn is_word(&self) -> bool {
160 if let AttrKind::Normal(normal) = &self.kind {
161 matches!(normal.item.args, AttrArgs::Empty)
169 /// For a single-segment meta item, returns its name; otherwise, returns `None`.
170 pub fn ident(&self) -> Option<Ident> {
171 if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
173 pub fn name_or_empty(&self) -> Symbol {
174 self.ident().unwrap_or_else(Ident::empty).name
178 // #[attribute(name = "value")]
180 pub fn name_value_literal(&self) -> Option<&Lit> {
182 MetaItemKind::NameValue(v) => Some(v),
187 pub fn value_str(&self) -> Option<Symbol> {
188 self.kind.value_str()
191 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
193 MetaItemKind::List(l) => Some(&**l),
198 pub fn is_word(&self) -> bool {
199 matches!(self.kind, MetaItemKind::Word)
202 pub fn has_name(&self, name: Symbol) -> bool {
206 /// This is used in case you want the value span instead of the whole attribute. Example:
209 /// #[doc(alias = "foo")]
212 /// In here, it'll return a span for `"foo"`.
213 pub fn name_value_literal_span(&self) -> Option<Span> {
214 Some(self.name_value_literal()?.span)
219 pub fn span(&self) -> Span {
220 self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
223 pub fn meta(&self, span: Span) -> Option<MetaItem> {
225 path: self.path.clone(),
226 kind: MetaItemKind::from_attr_args(&self.args)?,
231 pub fn meta_kind(&self) -> Option<MetaItemKind> {
232 MetaItemKind::from_attr_args(&self.args)
237 /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
238 /// So `#[doc = "doc"]` (which is a doc comment) and `#[doc(...)]` (which is not
239 /// a doc comment) will return `false`.
240 pub fn is_doc_comment(&self) -> bool {
242 AttrKind::Normal(..) => false,
243 AttrKind::DocComment(..) => true,
247 /// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
248 /// * `///doc` returns `Some(("doc", CommentKind::Line))`.
249 /// * `/** doc */` returns `Some(("doc", CommentKind::Block))`.
250 /// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`.
251 /// * `#[doc(...)]` returns `None`.
252 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
254 AttrKind::DocComment(kind, data) => Some((data, kind)),
255 AttrKind::Normal(ref normal) if normal.item.path == sym::doc => normal
258 .and_then(|kind| kind.value_str())
259 .map(|data| (data, CommentKind::Line)),
264 /// Returns the documentation if this is a doc comment or a sugared doc comment.
265 /// * `///doc` returns `Some("doc")`.
266 /// * `#[doc = "doc"]` returns `Some("doc")`.
267 /// * `#[doc(...)]` returns `None`.
268 pub fn doc_str(&self) -> Option<Symbol> {
270 AttrKind::DocComment(.., data) => Some(*data),
271 AttrKind::Normal(normal) if normal.item.path == sym::doc => {
272 normal.item.meta_kind().and_then(|kind| kind.value_str())
278 pub fn may_have_doc_links(&self) -> bool {
279 self.doc_str().map_or(false, |s| comments::may_have_doc_links(s.as_str()))
282 pub fn get_normal_item(&self) -> &AttrItem {
284 AttrKind::Normal(normal) => &normal.item,
285 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
289 pub fn unwrap_normal_item(self) -> AttrItem {
291 AttrKind::Normal(normal) => normal.into_inner().item,
292 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
296 /// Extracts the MetaItem from inside this Attribute.
297 pub fn meta(&self) -> Option<MetaItem> {
299 AttrKind::Normal(normal) => normal.item.meta(self.span),
300 AttrKind::DocComment(..) => None,
304 pub fn meta_kind(&self) -> Option<MetaItemKind> {
306 AttrKind::Normal(normal) => normal.item.meta_kind(),
307 AttrKind::DocComment(..) => None,
311 pub fn tokens(&self) -> TokenStream {
313 AttrKind::Normal(normal) => normal
316 .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self))
317 .to_attr_token_stream()
319 &AttrKind::DocComment(comment_kind, data) => TokenStream::new(vec![TokenTree::Token(
320 Token::new(token::DocComment(comment_kind, self.style, data), self.span),
329 pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> MetaItem {
330 let lit_kind = LitKind::Str(str, ast::StrStyle::Cooked);
331 mk_name_value_item(ident, lit_kind, str_span)
334 pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
335 let lit = Lit::from_lit_kind(lit_kind, lit_span);
336 let span = ident.span.to(lit_span);
337 MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
340 pub fn mk_list_item(ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
341 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) }
344 pub fn mk_word_item(ident: Ident) -> MetaItem {
345 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
348 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
349 NestedMetaItem::MetaItem(mk_word_item(ident))
352 pub struct AttrIdGenerator(WorkerLocal<Cell<u32>>);
354 #[cfg(debug_assertions)]
355 static MAX_ATTR_ID: AtomicU32 = AtomicU32::new(u32::MAX);
357 impl AttrIdGenerator {
358 pub fn new() -> Self {
359 // We use `(index as u32).reverse_bits()` to initialize the
360 // starting value of AttrId in each worker thread.
361 // The `index` is the index of the worker thread.
362 // This ensures that the AttrId generated in each thread is unique.
363 AttrIdGenerator(WorkerLocal::new(|index| {
364 let index: u32 = index.try_into().unwrap();
366 #[cfg(debug_assertions)]
368 let max_id = ((index + 1).next_power_of_two() - 1).bitxor(u32::MAX).reverse_bits();
369 MAX_ATTR_ID.fetch_min(max_id, Ordering::Release);
372 Cell::new(index.reverse_bits())
376 pub fn mk_attr_id(&self) -> AttrId {
377 let id = self.0.get();
379 // Ensure the assigned attr_id does not overlap the bits
380 // representing the number of threads.
381 #[cfg(debug_assertions)]
382 assert!(id <= MAX_ATTR_ID.load(Ordering::Acquire));
396 mk_attr_from_item(g, AttrItem { path, args, tokens: None }, None, style, span)
399 pub fn mk_attr_from_item(
402 tokens: Option<LazyAttrTokenStream>,
407 kind: AttrKind::Normal(P(ast::NormalAttr { item, tokens })),
414 /// Returns an inner attribute with the given value and span.
415 pub fn mk_attr_inner(g: &AttrIdGenerator, item: MetaItem) -> Attribute {
416 mk_attr(g, AttrStyle::Inner, item.path, item.kind.attr_args(item.span), item.span)
419 /// Returns an outer attribute with the given value and span.
420 pub fn mk_attr_outer(g: &AttrIdGenerator, item: MetaItem) -> Attribute {
421 mk_attr(g, AttrStyle::Outer, item.path, item.kind.attr_args(item.span), item.span)
424 pub fn mk_doc_comment(
426 comment_kind: CommentKind,
431 Attribute { kind: AttrKind::DocComment(comment_kind, data), id: g.mk_attr_id(), style, span }
434 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
435 items.iter().any(|item| item.has_name(name))
439 fn token_trees(&self) -> Vec<TokenTree> {
440 let mut idents = vec![];
441 let mut last_pos = BytePos(0_u32);
442 for (i, segment) in self.path.segments.iter().enumerate() {
443 let is_first = i == 0;
446 Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt(), None);
447 idents.push(TokenTree::token_alone(token::ModSep, mod_sep_span));
449 idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
450 last_pos = segment.ident.span.hi();
452 idents.extend(self.kind.token_trees(self.span));
456 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
458 I: Iterator<Item = TokenTree>,
460 // FIXME: Share code with `parse_path`.
461 let path = match tokens.next().map(TokenTree::uninterpolate) {
462 Some(TokenTree::Token(
463 Token { kind: kind @ (token::Ident(..) | token::ModSep), span },
466 let mut segments = if let token::Ident(name, _) = kind {
467 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
471 thin_vec![PathSegment::from_ident(Ident::new(name, span))]
473 break 'arm Path::from_ident(Ident::new(name, span));
476 thin_vec![PathSegment::path_root(span)]
479 if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
480 tokens.next().map(TokenTree::uninterpolate)
482 segments.push(PathSegment::from_ident(Ident::new(name, span)));
486 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
494 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
495 Path { span, segments, tokens: None }
497 Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. }, _)) => match &*nt {
498 token::Nonterminal::NtMeta(item) => return item.meta(item.path.span),
499 token::Nonterminal::NtPath(path) => (**path).clone(),
504 let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
505 let kind = MetaItemKind::from_tokens(tokens)?;
506 let hi = match &kind {
507 MetaItemKind::NameValue(lit) => lit.span.hi(),
508 MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
511 let span = path.span.with_hi(hi);
512 Some(MetaItem { path, kind, span })
517 pub fn value_str(&self) -> Option<Symbol> {
519 MetaItemKind::NameValue(v) => match v.kind {
520 LitKind::Str(s, _) => Some(s),
527 pub fn attr_args(&self, span: Span) -> AttrArgs {
529 MetaItemKind::Word => AttrArgs::Empty,
530 MetaItemKind::NameValue(lit) => {
531 let expr = P(ast::Expr {
532 id: ast::DUMMY_NODE_ID,
533 kind: ast::ExprKind::Lit(lit.token_lit.clone()),
535 attrs: ast::AttrVec::new(),
538 AttrArgs::Eq(span, AttrArgsEq::Ast(expr))
540 MetaItemKind::List(list) => {
541 let mut tts = Vec::new();
542 for (i, item) in list.iter().enumerate() {
544 tts.push(TokenTree::token_alone(token::Comma, span));
546 tts.extend(item.token_trees())
548 AttrArgs::Delimited(DelimArgs {
549 dspan: DelimSpan::from_single(span),
550 delim: MacDelimiter::Parenthesis,
551 tokens: TokenStream::new(tts),
557 fn token_trees(&self, span: Span) -> Vec<TokenTree> {
559 MetaItemKind::Word => vec![],
560 MetaItemKind::NameValue(lit) => {
562 TokenTree::token_alone(token::Eq, span),
563 TokenTree::Token(lit.to_token(), Spacing::Alone),
566 MetaItemKind::List(list) => {
567 let mut tokens = Vec::new();
568 for (i, item) in list.iter().enumerate() {
570 tokens.push(TokenTree::token_alone(token::Comma, span));
572 tokens.extend(item.token_trees())
574 vec![TokenTree::Delimited(
575 DelimSpan::from_single(span),
576 Delimiter::Parenthesis,
577 TokenStream::new(tokens),
583 fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
584 let mut tokens = tokens.into_trees().peekable();
585 let mut result = Vec::new();
586 while tokens.peek().is_some() {
587 let item = NestedMetaItem::from_tokens(&mut tokens)?;
589 match tokens.next() {
590 None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
594 Some(MetaItemKind::List(result))
597 fn name_value_from_tokens(
598 tokens: &mut impl Iterator<Item = TokenTree>,
599 ) -> Option<MetaItemKind> {
600 match tokens.next() {
601 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
602 MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
604 Some(TokenTree::Token(token, _)) => {
605 Lit::from_token(&token).map(MetaItemKind::NameValue)
611 fn from_attr_args(args: &AttrArgs) -> Option<MetaItemKind> {
613 AttrArgs::Empty => Some(MetaItemKind::Word),
614 AttrArgs::Delimited(DelimArgs {
616 delim: MacDelimiter::Parenthesis,
618 }) => MetaItemKind::list_from_tokens(tokens.clone()),
619 AttrArgs::Delimited(..) => None,
620 AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => match expr.kind {
621 ast::ExprKind::Lit(token_lit) => {
622 // Turn failures to `None`, we'll get parse errors elsewhere.
623 Lit::from_token_lit(token_lit, expr.span)
625 .map(|lit| MetaItemKind::NameValue(lit))
629 AttrArgs::Eq(_, AttrArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
634 tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>,
635 ) -> Option<MetaItemKind> {
636 match tokens.peek() {
637 Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => {
638 let inner_tokens = inner_tokens.clone();
640 MetaItemKind::list_from_tokens(inner_tokens)
642 Some(TokenTree::Delimited(..)) => None,
643 Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
645 MetaItemKind::name_value_from_tokens(tokens)
647 _ => Some(MetaItemKind::Word),
652 impl NestedMetaItem {
653 pub fn span(&self) -> Span {
655 NestedMetaItem::MetaItem(item) => item.span,
656 NestedMetaItem::Literal(lit) => lit.span,
660 fn token_trees(&self) -> Vec<TokenTree> {
662 NestedMetaItem::MetaItem(item) => item.token_trees(),
663 NestedMetaItem::Literal(lit) => {
664 vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
669 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
671 I: Iterator<Item = TokenTree>,
673 match tokens.peek() {
674 Some(TokenTree::Token(token, _))
675 if let Some(lit) = Lit::from_token(token) =>
678 return Some(NestedMetaItem::Literal(lit));
680 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
681 let inner_tokens = inner_tokens.clone();
683 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
687 MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)