1 //! Functions dealing with attributes and meta items.
4 use crate::ast::{AttrId, AttrItem, AttrKind, AttrStyle, Attribute};
5 use crate::ast::{Lit, LitKind};
6 use crate::ast::{MacArgs, MacArgsEq, MacDelimiter, MetaItem, MetaItemKind, NestedMetaItem};
7 use crate::ast::{Path, PathSegment};
9 use crate::token::{self, CommentKind, Delimiter, Token};
10 use crate::tokenstream::{AttrAnnotatedTokenStream, AttrAnnotatedTokenTree};
11 use crate::tokenstream::{DelimSpan, Spacing, TokenTree};
12 use crate::tokenstream::{LazyTokenStream, TokenStream};
13 use crate::util::comments;
15 use rustc_index::bit_set::GrowableBitSet;
16 use rustc_span::source_map::BytePos;
17 use rustc_span::symbol::{sym, Ident, Symbol};
22 pub struct MarkedAttrs(GrowableBitSet<AttrId>);
25 // We have no idea how many attributes there will be, so just
26 // initiate the vectors with 0 bits. We'll grow them as necessary.
27 pub fn new() -> Self {
28 MarkedAttrs(GrowableBitSet::new_empty())
31 pub fn mark(&mut self, attr: &Attribute) {
32 self.0.insert(attr.id);
35 pub fn is_marked(&self, attr: &Attribute) -> bool {
36 self.0.contains(attr.id)
41 /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
42 pub fn meta_item(&self) -> Option<&MetaItem> {
44 NestedMetaItem::MetaItem(ref item) => Some(item),
49 /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
50 pub fn literal(&self) -> Option<&Lit> {
52 NestedMetaItem::Literal(ref lit) => Some(lit),
57 /// Returns `true` if this list item is a MetaItem with a name of `name`.
58 pub fn has_name(&self, name: Symbol) -> bool {
59 self.meta_item().map_or(false, |meta_item| meta_item.has_name(name))
62 /// For a single-segment meta item, returns its name; otherwise, returns `None`.
63 pub fn ident(&self) -> Option<Ident> {
64 self.meta_item().and_then(|meta_item| meta_item.ident())
66 pub fn name_or_empty(&self) -> Symbol {
67 self.ident().unwrap_or_else(Ident::empty).name
70 /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
71 /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
72 pub fn value_str(&self) -> Option<Symbol> {
73 self.meta_item().and_then(|meta_item| meta_item.value_str())
76 /// Returns a name and single literal value tuple of the `MetaItem`.
77 pub fn name_value_literal(&self) -> Option<(Symbol, &Lit)> {
78 self.meta_item().and_then(|meta_item| {
79 meta_item.meta_item_list().and_then(|meta_item_list| {
80 if meta_item_list.len() == 1
81 && let Some(ident) = meta_item.ident()
82 && let Some(lit) = meta_item_list[0].literal()
84 return Some((ident.name, lit));
91 /// Gets a list of inner meta items from a list `MetaItem` type.
92 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
93 self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
96 /// Returns `true` if the variant is `MetaItem`.
97 pub fn is_meta_item(&self) -> bool {
98 self.meta_item().is_some()
101 /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
102 pub fn is_word(&self) -> bool {
103 self.meta_item().map_or(false, |meta_item| meta_item.is_word())
106 /// See [`MetaItem::name_value_literal_span`].
107 pub fn name_value_literal_span(&self) -> Option<Span> {
108 self.meta_item()?.name_value_literal_span()
114 pub fn has_name(&self, name: Symbol) -> bool {
116 AttrKind::Normal(ref normal) => normal.item.path == name,
117 AttrKind::DocComment(..) => false,
121 /// For a single-segment attribute, returns its name; otherwise, returns `None`.
122 pub fn ident(&self) -> Option<Ident> {
124 AttrKind::Normal(ref normal) => {
125 if normal.item.path.segments.len() == 1 {
126 Some(normal.item.path.segments[0].ident)
131 AttrKind::DocComment(..) => None,
134 pub fn name_or_empty(&self) -> Symbol {
135 self.ident().unwrap_or_else(Ident::empty).name
138 pub fn value_str(&self) -> Option<Symbol> {
140 AttrKind::Normal(ref normal) => {
141 normal.item.meta_kind().and_then(|kind| kind.value_str())
143 AttrKind::DocComment(..) => None,
147 pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
149 AttrKind::Normal(ref normal) => match normal.item.meta_kind() {
150 Some(MetaItemKind::List(list)) => Some(list),
153 AttrKind::DocComment(..) => None,
157 pub fn is_word(&self) -> bool {
158 if let AttrKind::Normal(normal) = &self.kind {
159 matches!(normal.item.args, MacArgs::Empty)
167 /// For a single-segment meta item, returns its name; otherwise, returns `None`.
168 pub fn ident(&self) -> Option<Ident> {
169 if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
171 pub fn name_or_empty(&self) -> Symbol {
172 self.ident().unwrap_or_else(Ident::empty).name
176 // #[attribute(name = "value")]
178 pub fn name_value_literal(&self) -> Option<&Lit> {
180 MetaItemKind::NameValue(v) => Some(v),
185 pub fn value_str(&self) -> Option<Symbol> {
186 self.kind.value_str()
189 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
191 MetaItemKind::List(ref l) => Some(&l[..]),
196 pub fn is_word(&self) -> bool {
197 matches!(self.kind, MetaItemKind::Word)
200 pub fn has_name(&self, name: Symbol) -> bool {
204 /// This is used in case you want the value span instead of the whole attribute. Example:
207 /// #[doc(alias = "foo")]
210 /// In here, it'll return a span for `"foo"`.
211 pub fn name_value_literal_span(&self) -> Option<Span> {
212 Some(self.name_value_literal()?.span)
217 pub fn span(&self) -> Span {
218 self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
221 pub fn meta(&self, span: Span) -> Option<MetaItem> {
223 path: self.path.clone(),
224 kind: MetaItemKind::from_mac_args(&self.args)?,
229 pub fn meta_kind(&self) -> Option<MetaItemKind> {
230 MetaItemKind::from_mac_args(&self.args)
235 /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
236 /// So `#[doc = "doc"]` will return `false`.
237 pub fn is_doc_comment(&self) -> bool {
239 AttrKind::Normal(..) => false,
240 AttrKind::DocComment(..) => true,
244 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
246 AttrKind::DocComment(kind, data) => Some((data, kind)),
247 AttrKind::Normal(ref normal) if normal.item.path == sym::doc => normal
250 .and_then(|kind| kind.value_str())
251 .map(|data| (data, CommentKind::Line)),
256 pub fn doc_str(&self) -> Option<Symbol> {
258 AttrKind::DocComment(.., data) => Some(data),
259 AttrKind::Normal(ref normal) if normal.item.path == sym::doc => {
260 normal.item.meta_kind().and_then(|kind| kind.value_str())
266 pub fn may_have_doc_links(&self) -> bool {
267 self.doc_str().map_or(false, |s| comments::may_have_doc_links(s.as_str()))
270 pub fn get_normal_item(&self) -> &AttrItem {
272 AttrKind::Normal(ref normal) => &normal.item,
273 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
277 pub fn unwrap_normal_item(self) -> AttrItem {
279 AttrKind::Normal(normal) => normal.into_inner().item,
280 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
284 /// Extracts the MetaItem from inside this Attribute.
285 pub fn meta(&self) -> Option<MetaItem> {
287 AttrKind::Normal(ref normal) => normal.item.meta(self.span),
288 AttrKind::DocComment(..) => None,
292 pub fn meta_kind(&self) -> Option<MetaItemKind> {
294 AttrKind::Normal(ref normal) => normal.item.meta_kind(),
295 AttrKind::DocComment(..) => None,
299 pub fn tokens(&self) -> AttrAnnotatedTokenStream {
301 AttrKind::Normal(ref normal) => normal
304 .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self))
305 .create_token_stream(),
306 AttrKind::DocComment(comment_kind, data) => AttrAnnotatedTokenStream::from((
307 AttrAnnotatedTokenTree::Token(Token::new(
308 token::DocComment(comment_kind, self.style, data),
319 pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> MetaItem {
320 let lit_kind = LitKind::Str(str, ast::StrStyle::Cooked);
321 mk_name_value_item(ident, lit_kind, str_span)
324 pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
325 let lit = Lit::from_lit_kind(lit_kind, lit_span);
326 let span = ident.span.to(lit_span);
327 MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
330 pub fn mk_list_item(ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
331 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) }
334 pub fn mk_word_item(ident: Ident) -> MetaItem {
335 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
338 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
339 NestedMetaItem::MetaItem(mk_word_item(ident))
342 pub(crate) fn mk_attr_id() -> AttrId {
343 use std::sync::atomic::AtomicU32;
344 use std::sync::atomic::Ordering;
346 static NEXT_ATTR_ID: AtomicU32 = AtomicU32::new(0);
348 let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
349 assert!(id != u32::MAX);
353 pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attribute {
354 mk_attr_from_item(AttrItem { path, args, tokens: None }, None, style, span)
357 pub fn mk_attr_from_item(
359 tokens: Option<LazyTokenStream>,
364 kind: AttrKind::Normal(P(ast::NormalAttr { item, tokens })),
371 /// Returns an inner attribute with the given value and span.
372 pub fn mk_attr_inner(item: MetaItem) -> Attribute {
373 mk_attr(AttrStyle::Inner, item.path, item.kind.mac_args(item.span), item.span)
376 /// Returns an outer attribute with the given value and span.
377 pub fn mk_attr_outer(item: MetaItem) -> Attribute {
378 mk_attr(AttrStyle::Outer, item.path, item.kind.mac_args(item.span), item.span)
381 pub fn mk_doc_comment(
382 comment_kind: CommentKind,
387 Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span }
390 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
391 items.iter().any(|item| item.has_name(name))
395 fn token_trees(&self) -> Vec<TokenTree> {
396 let mut idents = vec![];
397 let mut last_pos = BytePos(0_u32);
398 for (i, segment) in self.path.segments.iter().enumerate() {
399 let is_first = i == 0;
402 Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt(), None);
403 idents.push(TokenTree::token_alone(token::ModSep, mod_sep_span));
405 idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
406 last_pos = segment.ident.span.hi();
408 idents.extend(self.kind.token_trees(self.span));
412 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
414 I: Iterator<Item = TokenTree>,
416 // FIXME: Share code with `parse_path`.
417 let path = match tokens.next().map(TokenTree::uninterpolate) {
418 Some(TokenTree::Token(
419 Token { kind: kind @ (token::Ident(..) | token::ModSep), span },
422 let mut segments = if let token::Ident(name, _) = kind {
423 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
427 vec![PathSegment::from_ident(Ident::new(name, span))]
429 break 'arm Path::from_ident(Ident::new(name, span));
432 vec![PathSegment::path_root(span)]
435 if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
436 tokens.next().map(TokenTree::uninterpolate)
438 segments.push(PathSegment::from_ident(Ident::new(name, span)));
442 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
450 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
451 Path { span, segments, tokens: None }
453 Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. }, _)) => match *nt {
454 token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span),
455 token::Nonterminal::NtPath(ref path) => (**path).clone(),
460 let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
461 let kind = MetaItemKind::from_tokens(tokens)?;
462 let hi = match kind {
463 MetaItemKind::NameValue(ref lit) => lit.span.hi(),
464 MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
467 let span = path.span.with_hi(hi);
468 Some(MetaItem { path, kind, span })
473 pub fn value_str(&self) -> Option<Symbol> {
475 MetaItemKind::NameValue(ref v) => match v.kind {
476 LitKind::Str(ref s, _) => Some(*s),
483 pub fn mac_args(&self, span: Span) -> MacArgs {
485 MetaItemKind::Word => MacArgs::Empty,
486 MetaItemKind::NameValue(lit) => {
487 let expr = P(ast::Expr {
488 id: ast::DUMMY_NODE_ID,
489 kind: ast::ExprKind::Lit(lit.clone()),
491 attrs: ast::AttrVec::new(),
494 MacArgs::Eq(span, MacArgsEq::Ast(expr))
496 MetaItemKind::List(list) => {
497 let mut tts = Vec::new();
498 for (i, item) in list.iter().enumerate() {
500 tts.push(TokenTree::token_alone(token::Comma, span));
502 tts.extend(item.token_trees())
505 DelimSpan::from_single(span),
506 MacDelimiter::Parenthesis,
507 TokenStream::new(tts),
513 fn token_trees(&self, span: Span) -> Vec<TokenTree> {
515 MetaItemKind::Word => vec![],
516 MetaItemKind::NameValue(ref lit) => {
518 TokenTree::token_alone(token::Eq, span),
519 TokenTree::Token(lit.to_token(), Spacing::Alone),
522 MetaItemKind::List(ref list) => {
523 let mut tokens = Vec::new();
524 for (i, item) in list.iter().enumerate() {
526 tokens.push(TokenTree::token_alone(token::Comma, span));
528 tokens.extend(item.token_trees())
530 vec![TokenTree::Delimited(
531 DelimSpan::from_single(span),
532 Delimiter::Parenthesis,
533 TokenStream::new(tokens),
539 fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
540 let mut tokens = tokens.into_trees().peekable();
541 let mut result = Vec::new();
542 while tokens.peek().is_some() {
543 let item = NestedMetaItem::from_tokens(&mut tokens)?;
545 match tokens.next() {
546 None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
550 Some(MetaItemKind::List(result))
553 fn name_value_from_tokens(
554 tokens: &mut impl Iterator<Item = TokenTree>,
555 ) -> Option<MetaItemKind> {
556 match tokens.next() {
557 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
558 MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
560 Some(TokenTree::Token(token, _)) => {
561 Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
567 fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
569 MacArgs::Empty => Some(MetaItemKind::Word),
570 MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
571 MetaItemKind::list_from_tokens(tokens.clone())
573 MacArgs::Delimited(..) => None,
574 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => match &expr.kind {
575 ast::ExprKind::Lit(lit) => Some(MetaItemKind::NameValue(lit.clone())),
578 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
583 tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>,
584 ) -> Option<MetaItemKind> {
585 match tokens.peek() {
586 Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => {
587 let inner_tokens = inner_tokens.clone();
589 MetaItemKind::list_from_tokens(inner_tokens)
591 Some(TokenTree::Delimited(..)) => None,
592 Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
594 MetaItemKind::name_value_from_tokens(tokens)
596 _ => Some(MetaItemKind::Word),
601 impl NestedMetaItem {
602 pub fn span(&self) -> Span {
604 NestedMetaItem::MetaItem(ref item) => item.span,
605 NestedMetaItem::Literal(ref lit) => lit.span,
609 fn token_trees(&self) -> Vec<TokenTree> {
611 NestedMetaItem::MetaItem(ref item) => item.token_trees(),
612 NestedMetaItem::Literal(ref lit) => {
613 vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
618 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
620 I: Iterator<Item = TokenTree>,
622 match tokens.peek() {
623 Some(TokenTree::Token(token, _))
624 if let Ok(lit) = Lit::from_token(token) =>
627 return Some(NestedMetaItem::Literal(lit));
629 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
630 let inner_tokens = inner_tokens.clone();
632 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
636 MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)