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::{DelimSpan, Spacing, TokenTree};
11 use crate::tokenstream::{LazyAttrTokenStream, TokenStream};
12 use crate::util::comments;
14 use rustc_index::bit_set::GrowableBitSet;
15 use rustc_span::source_map::BytePos;
16 use rustc_span::symbol::{sym, Ident, Symbol};
21 pub struct MarkedAttrs(GrowableBitSet<AttrId>);
24 // We have no idea how many attributes there will be, so just
25 // initiate the vectors with 0 bits. We'll grow them as necessary.
26 pub fn new() -> Self {
27 MarkedAttrs(GrowableBitSet::new_empty())
30 pub fn mark(&mut self, attr: &Attribute) {
31 self.0.insert(attr.id);
34 pub fn is_marked(&self, attr: &Attribute) -> bool {
35 self.0.contains(attr.id)
40 /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
41 pub fn meta_item(&self) -> Option<&MetaItem> {
43 NestedMetaItem::MetaItem(ref item) => Some(item),
48 /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
49 pub fn literal(&self) -> Option<&Lit> {
51 NestedMetaItem::Literal(ref lit) => Some(lit),
56 /// Returns `true` if this list item is a MetaItem with a name of `name`.
57 pub fn has_name(&self, name: Symbol) -> bool {
58 self.meta_item().map_or(false, |meta_item| meta_item.has_name(name))
61 /// For a single-segment meta item, returns its name; otherwise, returns `None`.
62 pub fn ident(&self) -> Option<Ident> {
63 self.meta_item().and_then(|meta_item| meta_item.ident())
65 pub fn name_or_empty(&self) -> Symbol {
66 self.ident().unwrap_or_else(Ident::empty).name
69 /// Gets the string value if `self` is a `MetaItem` and the `MetaItem` is a
70 /// `MetaItemKind::NameValue` variant containing a string, otherwise `None`.
71 pub fn value_str(&self) -> Option<Symbol> {
72 self.meta_item().and_then(|meta_item| meta_item.value_str())
75 /// Returns a name and single literal value tuple of the `MetaItem`.
76 pub fn name_value_literal(&self) -> Option<(Symbol, &Lit)> {
77 self.meta_item().and_then(|meta_item| {
78 meta_item.meta_item_list().and_then(|meta_item_list| {
79 if meta_item_list.len() == 1
80 && let Some(ident) = meta_item.ident()
81 && let Some(lit) = meta_item_list[0].literal()
83 return Some((ident.name, lit));
90 /// Gets a list of inner meta items from a list `MetaItem` type.
91 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
92 self.meta_item().and_then(|meta_item| meta_item.meta_item_list())
95 /// Returns `true` if the variant is `MetaItem`.
96 pub fn is_meta_item(&self) -> bool {
97 self.meta_item().is_some()
100 /// Returns `true` if `self` is a `MetaItem` and the meta item is a word.
101 pub fn is_word(&self) -> bool {
102 self.meta_item().map_or(false, |meta_item| meta_item.is_word())
105 /// See [`MetaItem::name_value_literal_span`].
106 pub fn name_value_literal_span(&self) -> Option<Span> {
107 self.meta_item()?.name_value_literal_span()
113 pub fn has_name(&self, name: Symbol) -> bool {
115 AttrKind::Normal(ref normal) => normal.item.path == name,
116 AttrKind::DocComment(..) => false,
120 /// For a single-segment attribute, returns its name; otherwise, returns `None`.
121 pub fn ident(&self) -> Option<Ident> {
123 AttrKind::Normal(ref normal) => {
124 if normal.item.path.segments.len() == 1 {
125 Some(normal.item.path.segments[0].ident)
130 AttrKind::DocComment(..) => None,
133 pub fn name_or_empty(&self) -> Symbol {
134 self.ident().unwrap_or_else(Ident::empty).name
137 pub fn value_str(&self) -> Option<Symbol> {
139 AttrKind::Normal(ref normal) => {
140 normal.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 normal) => match normal.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(normal) = &self.kind {
158 matches!(normal.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> {
185 self.kind.value_str()
188 pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
190 MetaItemKind::List(ref l) => Some(&l[..]),
195 pub fn is_word(&self) -> bool {
196 matches!(self.kind, MetaItemKind::Word)
199 pub fn has_name(&self, name: Symbol) -> bool {
203 /// This is used in case you want the value span instead of the whole attribute. Example:
206 /// #[doc(alias = "foo")]
209 /// In here, it'll return a span for `"foo"`.
210 pub fn name_value_literal_span(&self) -> Option<Span> {
211 Some(self.name_value_literal()?.span)
216 pub fn span(&self) -> Span {
217 self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
220 pub fn meta(&self, span: Span) -> Option<MetaItem> {
222 path: self.path.clone(),
223 kind: MetaItemKind::from_mac_args(&self.args)?,
228 pub fn meta_kind(&self) -> Option<MetaItemKind> {
229 MetaItemKind::from_mac_args(&self.args)
234 /// Returns `true` if it is a sugared doc comment (`///` or `//!` for example).
235 /// So `#[doc = "doc"]` (which is a doc comment) and `#[doc(...)]` (which is not
236 /// a doc comment) will return `false`.
237 pub fn is_doc_comment(&self) -> bool {
239 AttrKind::Normal(..) => false,
240 AttrKind::DocComment(..) => true,
244 /// Returns the documentation and its kind if this is a doc comment or a sugared doc comment.
245 /// * `///doc` returns `Some(("doc", CommentKind::Line))`.
246 /// * `/** doc */` returns `Some(("doc", CommentKind::Block))`.
247 /// * `#[doc = "doc"]` returns `Some(("doc", CommentKind::Line))`.
248 /// * `#[doc(...)]` returns `None`.
249 pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
251 AttrKind::DocComment(kind, data) => Some((data, kind)),
252 AttrKind::Normal(ref normal) if normal.item.path == sym::doc => normal
255 .and_then(|kind| kind.value_str())
256 .map(|data| (data, CommentKind::Line)),
261 /// Returns the documentation if this is a doc comment or a sugared doc comment.
262 /// * `///doc` returns `Some("doc")`.
263 /// * `#[doc = "doc"]` returns `Some("doc")`.
264 /// * `#[doc(...)]` returns `None`.
265 pub fn doc_str(&self) -> Option<Symbol> {
267 AttrKind::DocComment(.., data) => Some(data),
268 AttrKind::Normal(ref normal) if normal.item.path == sym::doc => {
269 normal.item.meta_kind().and_then(|kind| kind.value_str())
275 pub fn may_have_doc_links(&self) -> bool {
276 self.doc_str().map_or(false, |s| comments::may_have_doc_links(s.as_str()))
279 pub fn get_normal_item(&self) -> &AttrItem {
281 AttrKind::Normal(ref normal) => &normal.item,
282 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
286 pub fn unwrap_normal_item(self) -> AttrItem {
288 AttrKind::Normal(normal) => normal.into_inner().item,
289 AttrKind::DocComment(..) => panic!("unexpected doc comment"),
293 /// Extracts the MetaItem from inside this Attribute.
294 pub fn meta(&self) -> Option<MetaItem> {
296 AttrKind::Normal(ref normal) => normal.item.meta(self.span),
297 AttrKind::DocComment(..) => None,
301 pub fn meta_kind(&self) -> Option<MetaItemKind> {
303 AttrKind::Normal(ref normal) => normal.item.meta_kind(),
304 AttrKind::DocComment(..) => None,
308 pub fn tokens(&self) -> TokenStream {
310 AttrKind::Normal(ref normal) => normal
313 .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self))
314 .to_attr_token_stream()
316 AttrKind::DocComment(comment_kind, data) => TokenStream::new(vec![TokenTree::Token(
317 Token::new(token::DocComment(comment_kind, self.style, data), self.span),
326 pub fn mk_name_value_item_str(ident: Ident, str: Symbol, str_span: Span) -> MetaItem {
327 let lit_kind = LitKind::Str(str, ast::StrStyle::Cooked);
328 mk_name_value_item(ident, lit_kind, str_span)
331 pub fn mk_name_value_item(ident: Ident, lit_kind: LitKind, lit_span: Span) -> MetaItem {
332 let lit = Lit::from_lit_kind(lit_kind, lit_span);
333 let span = ident.span.to(lit_span);
334 MetaItem { path: Path::from_ident(ident), span, kind: MetaItemKind::NameValue(lit) }
337 pub fn mk_list_item(ident: Ident, items: Vec<NestedMetaItem>) -> MetaItem {
338 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::List(items) }
341 pub fn mk_word_item(ident: Ident) -> MetaItem {
342 MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
345 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
346 NestedMetaItem::MetaItem(mk_word_item(ident))
349 pub(crate) fn mk_attr_id() -> AttrId {
350 use std::sync::atomic::AtomicU32;
351 use std::sync::atomic::Ordering;
353 static NEXT_ATTR_ID: AtomicU32 = AtomicU32::new(0);
355 let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
356 assert!(id != u32::MAX);
360 pub fn mk_attr(style: AttrStyle, path: Path, args: MacArgs, span: Span) -> Attribute {
361 mk_attr_from_item(AttrItem { path, args, tokens: None }, None, style, span)
364 pub fn mk_attr_from_item(
366 tokens: Option<LazyAttrTokenStream>,
371 kind: AttrKind::Normal(P(ast::NormalAttr { item, tokens })),
378 /// Returns an inner attribute with the given value and span.
379 pub fn mk_attr_inner(item: MetaItem) -> Attribute {
380 mk_attr(AttrStyle::Inner, item.path, item.kind.mac_args(item.span), item.span)
383 /// Returns an outer attribute with the given value and span.
384 pub fn mk_attr_outer(item: MetaItem) -> Attribute {
385 mk_attr(AttrStyle::Outer, item.path, item.kind.mac_args(item.span), item.span)
388 pub fn mk_doc_comment(
389 comment_kind: CommentKind,
394 Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span }
397 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
398 items.iter().any(|item| item.has_name(name))
402 fn token_trees(&self) -> Vec<TokenTree> {
403 let mut idents = vec![];
404 let mut last_pos = BytePos(0_u32);
405 for (i, segment) in self.path.segments.iter().enumerate() {
406 let is_first = i == 0;
409 Span::new(last_pos, segment.ident.span.lo(), segment.ident.span.ctxt(), None);
410 idents.push(TokenTree::token_alone(token::ModSep, mod_sep_span));
412 idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
413 last_pos = segment.ident.span.hi();
415 idents.extend(self.kind.token_trees(self.span));
419 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
421 I: Iterator<Item = TokenTree>,
423 // FIXME: Share code with `parse_path`.
424 let path = match tokens.next().map(TokenTree::uninterpolate) {
425 Some(TokenTree::Token(
426 Token { kind: kind @ (token::Ident(..) | token::ModSep), span },
429 let mut segments = if let token::Ident(name, _) = kind {
430 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
434 vec![PathSegment::from_ident(Ident::new(name, span))]
436 break 'arm Path::from_ident(Ident::new(name, span));
439 vec![PathSegment::path_root(span)]
442 if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
443 tokens.next().map(TokenTree::uninterpolate)
445 segments.push(PathSegment::from_ident(Ident::new(name, span)));
449 if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
457 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
458 Path { span, segments, tokens: None }
460 Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. }, _)) => match *nt {
461 token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span),
462 token::Nonterminal::NtPath(ref path) => (**path).clone(),
467 let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
468 let kind = MetaItemKind::from_tokens(tokens)?;
469 let hi = match kind {
470 MetaItemKind::NameValue(ref lit) => lit.span.hi(),
471 MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
474 let span = path.span.with_hi(hi);
475 Some(MetaItem { path, kind, span })
480 pub fn value_str(&self) -> Option<Symbol> {
482 MetaItemKind::NameValue(ref v) => match v.kind {
483 LitKind::Str(ref s, _) => Some(*s),
490 pub fn mac_args(&self, span: Span) -> MacArgs {
492 MetaItemKind::Word => MacArgs::Empty,
493 MetaItemKind::NameValue(lit) => {
494 let expr = P(ast::Expr {
495 id: ast::DUMMY_NODE_ID,
496 kind: ast::ExprKind::Lit(lit.clone()),
498 attrs: ast::AttrVec::new(),
501 MacArgs::Eq(span, MacArgsEq::Ast(expr))
503 MetaItemKind::List(list) => {
504 let mut tts = Vec::new();
505 for (i, item) in list.iter().enumerate() {
507 tts.push(TokenTree::token_alone(token::Comma, span));
509 tts.extend(item.token_trees())
512 DelimSpan::from_single(span),
513 MacDelimiter::Parenthesis,
514 TokenStream::new(tts),
520 fn token_trees(&self, span: Span) -> Vec<TokenTree> {
522 MetaItemKind::Word => vec![],
523 MetaItemKind::NameValue(ref lit) => {
525 TokenTree::token_alone(token::Eq, span),
526 TokenTree::Token(lit.to_token(), Spacing::Alone),
529 MetaItemKind::List(ref list) => {
530 let mut tokens = Vec::new();
531 for (i, item) in list.iter().enumerate() {
533 tokens.push(TokenTree::token_alone(token::Comma, span));
535 tokens.extend(item.token_trees())
537 vec![TokenTree::Delimited(
538 DelimSpan::from_single(span),
539 Delimiter::Parenthesis,
540 TokenStream::new(tokens),
546 fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
547 let mut tokens = tokens.into_trees().peekable();
548 let mut result = Vec::new();
549 while tokens.peek().is_some() {
550 let item = NestedMetaItem::from_tokens(&mut tokens)?;
552 match tokens.next() {
553 None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
557 Some(MetaItemKind::List(result))
560 fn name_value_from_tokens(
561 tokens: &mut impl Iterator<Item = TokenTree>,
562 ) -> Option<MetaItemKind> {
563 match tokens.next() {
564 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
565 MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
567 Some(TokenTree::Token(token, _)) => {
568 Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
574 fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
576 MacArgs::Empty => Some(MetaItemKind::Word),
577 MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
578 MetaItemKind::list_from_tokens(tokens.clone())
580 MacArgs::Delimited(..) => None,
581 MacArgs::Eq(_, MacArgsEq::Ast(expr)) => match &expr.kind {
582 ast::ExprKind::Lit(lit) => Some(MetaItemKind::NameValue(lit.clone())),
585 MacArgs::Eq(_, MacArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
590 tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>,
591 ) -> Option<MetaItemKind> {
592 match tokens.peek() {
593 Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => {
594 let inner_tokens = inner_tokens.clone();
596 MetaItemKind::list_from_tokens(inner_tokens)
598 Some(TokenTree::Delimited(..)) => None,
599 Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
601 MetaItemKind::name_value_from_tokens(tokens)
603 _ => Some(MetaItemKind::Word),
608 impl NestedMetaItem {
609 pub fn span(&self) -> Span {
611 NestedMetaItem::MetaItem(ref item) => item.span,
612 NestedMetaItem::Literal(ref lit) => lit.span,
616 fn token_trees(&self) -> Vec<TokenTree> {
618 NestedMetaItem::MetaItem(ref item) => item.token_trees(),
619 NestedMetaItem::Literal(ref lit) => {
620 vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
625 fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
627 I: Iterator<Item = TokenTree>,
629 match tokens.peek() {
630 Some(TokenTree::Token(token, _))
631 if let Ok(lit) = Lit::from_token(token) =>
634 return Some(NestedMetaItem::Literal(lit));
636 Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
637 let inner_tokens = inner_tokens.clone();
639 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
643 MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)