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_data_structures::thin_vec::ThinVec;
16 use rustc_index::bit_set::GrowableBitSet;
17 use rustc_span::source_map::BytePos;
18 use rustc_span::symbol::{sym, Ident, Symbol};
23 pub struct MarkedAttrs(GrowableBitSet<AttrId>);
26 // We have no idea how many attributes there will be, so just
27 // initiate the vectors with 0 bits. We'll grow them as necessary.
28 pub fn new() -> Self {
29 MarkedAttrs(GrowableBitSet::new_empty())
32 pub fn mark(&mut self, attr: &Attribute) {
33 self.0.insert(attr.id);
36 pub fn is_marked(&self, attr: &Attribute) -> bool {
37 self.0.contains(attr.id)
42 /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
43 pub fn meta_item(&self) -> Option<&MetaItem> {
45 NestedMetaItem::MetaItem(ref item) => Some(item),
50 /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
51 pub fn literal(&self) -> Option<&Lit> {
53 NestedMetaItem::Literal(ref lit) => Some(lit),
58 /// Returns `true` if this list item is a MetaItem with a name of `name`.
59 pub fn has_name(&self, name: Symbol) -> bool {
60 self.meta_item().map_or(false, |meta_item| meta_item.has_name(name))
63 /// For a single-segment meta item, returns its name; otherwise, returns `None`.
64 pub fn ident(&self) -> Option<Ident> {
65 self.meta_item().and_then(|meta_item| meta_item.ident())
67 pub fn name_or_empty(&self) -> Symbol {
68 self.ident().unwrap_or_else(Ident::empty).name
71 /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
72 /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
73 pub fn value_str(&self) -> Option<Symbol> {
74 self.meta_item().and_then(|meta_item| meta_item.value_str())
77 /// Returns a name and single literal value tuple of the `MetaItem`.
78 pub fn name_value_literal(&self) -> Option<(Symbol, &Lit)> {
79 self.meta_item().and_then(|meta_item| {
80 meta_item.meta_item_list().and_then(|meta_item_list| {
81 if meta_item_list.len() == 1
82 && let Some(ident) = meta_item.ident()
83 && let Some(lit) = meta_item_list[0].literal()
85 return Some((ident.name, lit));
92 /// Gets a list of inner meta items from a list `MetaItem` type.
93 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
94 self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
97 /// Returns `true` if the variant is `MetaItem`.
98 pub fn is_meta_item(&self) -> bool {
99 self.meta_item().is_some()
102 /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
103 pub fn is_word(&self) -> bool {
104 self.meta_item().map_or(false, |meta_item| meta_item.is_word())
107 /// See [`MetaItem::name_value_literal_span`].
108 pub fn name_value_literal_span(&self) -> Option<Span> {
109 self.meta_item()?.name_value_literal_span()
115 pub fn has_name(&self, name: Symbol) -> bool {
117 AttrKind::Normal(ref item, _) => item.path == name,
118 AttrKind::DocComment(..) => false,
122 /// For a single-segment attribute, returns its name; otherwise, returns `None`.
123 pub fn ident(&self) -> Option<Ident> {
125 AttrKind::Normal(ref item, _) => {
126 if item.path.segments.len() == 1 {
127 Some(item.path.segments[0].ident)
132 AttrKind::DocComment(..) => None,
135 pub fn name_or_empty(&self) -> Symbol {
136 self.ident().unwrap_or_else(Ident::empty).name
139 pub fn value_str(&self) -> Option<Symbol> {
141 AttrKind::Normal(ref item, _) => item.meta_kind().and_then(|kind| kind.value_str()),
142 AttrKind::DocComment(..) => None,
146 pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
148 AttrKind::Normal(ref item, _) => match item.meta_kind() {
149 Some(MetaItemKind::List(list)) => Some(list),
152 AttrKind::DocComment(..) => None,
156 pub fn is_word(&self) -> bool {
157 if let AttrKind::Normal(item, _) = &self.kind {
158 matches!(item.args, MacArgs::Empty)
166 /// For a single-segment meta item, returns its name; otherwise, returns `None`.
167 pub fn ident(&self) -> Option<Ident> {
168 if self.path.segments.len() == 1 { Some(self.path.segments[0].ident) } else { None }
170 pub fn name_or_empty(&self) -> Symbol {
171 self.ident().unwrap_or_else(Ident::empty).name
175 // #[attribute(name = "value")]
177 pub fn name_value_literal(&self) -> Option<&Lit> {
179 MetaItemKind::NameValue(v) => Some(v),
184 pub fn value_str(&self) -> Option<Symbol> {
186 MetaItemKind::NameValue(ref v) => match v.kind {
187 LitKind::Str(ref s, _) => Some(*s),
194 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
196 MetaItemKind::List(ref l) => Some(&l[..]),
201 pub fn is_word(&self) -> bool {
202 matches!(self.kind, MetaItemKind::Word)
205 pub fn has_name(&self, name: Symbol) -> bool {
209 /// This is used in case you want the value span instead of the whole attribute. Example:
212 /// #[doc(alias = "foo")]
215 /// In here, it'll return a span for `"foo"`.
216 pub fn name_value_literal_span(&self) -> Option<Span> {
217 Some(self.name_value_literal()?.span)
222 pub fn span(&self) -> Span {
223 self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
226 pub fn meta(&self, span: Span) -> Option<MetaItem> {
228 path: self.path.clone(),
229 kind: MetaItemKind::from_mac_args(&self.args)?,
234 pub fn meta_kind(&self) -> Option<MetaItemKind> {
235 MetaItemKind::from_mac_args(&self.args)
240 pub fn is_doc_comment(&self) -> bool {
242 AttrKind::Normal(..) => false,
243 AttrKind::DocComment(..) => true,
247 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
249 AttrKind::DocComment(kind, data) => Some((data, kind)),
250 AttrKind::Normal(ref item, _) if item.path == sym::doc => item
252 .and_then(|kind| kind.value_str())
253 .map(|data| (data, CommentKind::Line)),
258 pub fn doc_str(&self) -> Option<Symbol> {
260 AttrKind::DocComment(.., data) => Some(data),
261 AttrKind::Normal(ref item, _) if item.path == sym::doc => {
262 item.meta_kind().and_then(|kind| kind.value_str())
268 pub fn may_have_doc_links(&self) -> bool {
269 self.doc_str().map_or(false, |s| comments::may_have_doc_links(s.as_str()))
272 pub fn get_normal_item(&self) -> &AttrItem {
274 AttrKind::Normal(ref item, _) => item,
275 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
279 pub fn unwrap_normal_item(self) -> AttrItem {
281 AttrKind::Normal(item, _) => item,
282 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
286 /// Extracts the MetaItem from inside this Attribute.
287 pub fn meta(&self) -> Option<MetaItem> {
289 AttrKind::Normal(ref item, _) => item.meta(self.span),
290 AttrKind::DocComment(..) => None,
294 pub fn meta_kind(&self) -> Option<MetaItemKind> {
296 AttrKind::Normal(ref item, _) => item.meta_kind(),
297 AttrKind::DocComment(..) => None,
301 pub fn tokens(&self) -> AttrAnnotatedTokenStream {
303 AttrKind::Normal(_, ref tokens) => tokens
305 .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self))
306 .create_token_stream(),
307 AttrKind::DocComment(comment_kind, data) => AttrAnnotatedTokenStream::from((
308 AttrAnnotatedTokenTree::Token(Token::new(
309 token::DocComment(comment_kind, self.style, data),
320 pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> MetaItem {
321 let lit_kind = LitKind::Str(str, ast::StrStyle::Cooked);
322 mk_name_value_item(ident, lit_kind, str_span)
325 pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
326 let lit = Lit::from_lit_kind(lit_kind, lit_span);
327 let span = ident.span.to(lit_span);
328 MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
331 pub fn mk_list_item(ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
332 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) }
335 pub fn mk_word_item(ident: Ident) -> MetaItem {
336 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
339 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
340 NestedMetaItem::MetaItem(mk_word_item(ident))
343 pub(crate) fn mk_attr_id() -> AttrId {
344 use std::sync::atomic::AtomicU32;
345 use std::sync::atomic::Ordering;
347 static NEXT_ATTR_ID: AtomicU32 = AtomicU32::new(0);
349 let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
350 assert!(id != u32::MAX);
354 pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attribute {
355 mk_attr_from_item(AttrItem { path, args, tokens: None }, None, style, span)
358 pub fn mk_attr_from_item(
360 tokens: Option<LazyTokenStream>,
364 Attribute { kind: AttrKind::Normal(item, tokens), id: mk_attr_id(), style, span }
367 /// Returns an inner attribute with the given value and span.
368 pub fn mk_attr_inner(item: MetaItem) -> Attribute {
369 mk_attr(AttrStyle::Inner, item.path, item.kind.mac_args(item.span), item.span)
372 /// Returns an outer attribute with the given value and span.
373 pub fn mk_attr_outer(item: MetaItem) -> Attribute {
374 mk_attr(AttrStyle::Outer, item.path, item.kind.mac_args(item.span), item.span)
377 pub fn mk_doc_comment(
378 comment_kind: CommentKind,
383 Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span }
386 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
387 items.iter().any(|item| item.has_name(name))
391 fn token_trees(&self) -> Vec<TokenTree> {
392 let mut idents = vec![];
393 let mut last_pos = BytePos(0_u32);
394 for (i, segment) in self.path.segments.iter().enumerate() {
395 let is_first = i == 0;
398 Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt(), None);
399 idents.push(TokenTree::token_alone(token::ModSep, mod_sep_span));
401 idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
402 last_pos = segment.ident.span.hi();
404 idents.extend(self.kind.token_trees(self.span));
408 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
410 I: Iterator<Item = TokenTree>,
412 // FIXME: Share code with `parse_path`.
413 let path = match tokens.next().map(TokenTree::uninterpolate) {
414 Some(TokenTree::Token(
415 Token { kind: kind @ (token::Ident(..) | token::ModSep), span },
418 let mut segments = if let token::Ident(name, _) = kind {
419 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
423 vec![PathSegment::from_ident(Ident::new(name, span))]
425 break 'arm Path::from_ident(Ident::new(name, span));
428 vec![PathSegment::path_root(span)]
431 if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
432 tokens.next().map(TokenTree::uninterpolate)
434 segments.push(PathSegment::from_ident(Ident::new(name, span)));
438 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
446 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
447 Path { span, segments, tokens: None }
449 Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. }, _)) => match *nt {
450 token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span),
451 token::Nonterminal::NtPath(ref path) => (**path).clone(),
456 let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
457 let kind = MetaItemKind::from_tokens(tokens)?;
458 let hi = match kind {
459 MetaItemKind::NameValue(ref lit) => lit.span.hi(),
460 MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
463 let span = path.span.with_hi(hi);
464 Some(MetaItem { path, kind, span })
469 pub fn value_str(&self) -> Option<Symbol> {
471 MetaItemKind::NameValue(ref v) => match v.kind {
472 LitKind::Str(ref s, _) => Some(*s),
479 pub fn mac_args(&self, span: Span) -> MacArgs {
481 MetaItemKind::Word => MacArgs::Empty,
482 MetaItemKind::NameValue(lit) => {
483 let expr = P(ast::Expr {
484 id: ast::DUMMY_NODE_ID,
485 kind: ast::ExprKind::Lit(lit.clone()),
487 attrs: ThinVec::new(),
490 MacArgs::Eq(span, MacArgsEq::Ast(expr))
492 MetaItemKind::List(list) => {
493 let mut tts = Vec::new();
494 for (i, item) in list.iter().enumerate() {
496 tts.push(TokenTree::token_alone(token::Comma, span));
498 tts.extend(item.token_trees())
501 DelimSpan::from_single(span),
502 MacDelimiter::Parenthesis,
503 TokenStream::new(tts),
509 fn token_trees(&self, span: Span) -> Vec<TokenTree> {
511 MetaItemKind::Word => vec![],
512 MetaItemKind::NameValue(ref lit) => {
514 TokenTree::token_alone(token::Eq, span),
515 TokenTree::Token(lit.to_token(), Spacing::Alone),
518 MetaItemKind::List(ref list) => {
519 let mut tokens = Vec::new();
520 for (i, item) in list.iter().enumerate() {
522 tokens.push(TokenTree::token_alone(token::Comma, span));
524 tokens.extend(item.token_trees())
526 vec![TokenTree::Delimited(
527 DelimSpan::from_single(span),
528 Delimiter::Parenthesis,
529 TokenStream::new(tokens),
535 fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
536 let mut tokens = tokens.into_trees().peekable();
537 let mut result = Vec::new();
538 while tokens.peek().is_some() {
539 let item = NestedMetaItem::from_tokens(&mut tokens)?;
541 match tokens.next() {
542 None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
546 Some(MetaItemKind::List(result))
549 fn name_value_from_tokens(
550 tokens: &mut impl Iterator<Item = TokenTree>,
551 ) -> Option<MetaItemKind> {
552 match tokens.next() {
553 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
554 MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
556 Some(TokenTree::Token(token, _)) => {
557 Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
563 fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
565 MacArgs::Empty => Some(MetaItemKind::Word),
566 MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
567 MetaItemKind::list_from_tokens(tokens.clone())
569 MacArgs::Delimited(..) => None,
570 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => match &expr.kind {
571 ast::ExprKind::Lit(lit) => Some(MetaItemKind::NameValue(lit.clone())),
574 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
579 tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>,
580 ) -> Option<MetaItemKind> {
581 match tokens.peek() {
582 Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => {
583 let inner_tokens = inner_tokens.clone();
585 MetaItemKind::list_from_tokens(inner_tokens)
587 Some(TokenTree::Delimited(..)) => None,
588 Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
590 MetaItemKind::name_value_from_tokens(tokens)
592 _ => Some(MetaItemKind::Word),
597 impl NestedMetaItem {
598 pub fn span(&self) -> Span {
600 NestedMetaItem::MetaItem(ref item) => item.span,
601 NestedMetaItem::Literal(ref lit) => lit.span,
605 fn token_trees(&self) -> Vec<TokenTree> {
607 NestedMetaItem::MetaItem(ref item) => item.token_trees(),
608 NestedMetaItem::Literal(ref lit) => {
609 vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
614 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
616 I: Iterator<Item = TokenTree>,
618 match tokens.peek() {
619 Some(TokenTree::Token(token, _))
620 if let Ok(lit) = Lit::from_token(token) =>
623 return Some(NestedMetaItem::Literal(lit));
625 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
626 let inner_tokens = inner_tokens.clone();
628 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
632 MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)