]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/attr/mod.rs
Rollup merge of #101495 - bjorn3:pause-no-sse2, r=Mark-Simulacrum
[rust.git] / compiler / rustc_ast / src / attr / mod.rs
1 //! Functions dealing with attributes and meta items.
2
3 use crate::ast;
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};
8 use crate::ptr::P;
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;
14
15 use rustc_index::bit_set::GrowableBitSet;
16 use rustc_span::source_map::BytePos;
17 use rustc_span::symbol::{sym, Ident, Symbol};
18 use rustc_span::Span;
19
20 use std::iter;
21
22 pub struct MarkedAttrs(GrowableBitSet<AttrId>);
23
24 impl MarkedAttrs {
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())
29     }
30
31     pub fn mark(&mut self, attr: &Attribute) {
32         self.0.insert(attr.id);
33     }
34
35     pub fn is_marked(&self, attr: &Attribute) -> bool {
36         self.0.contains(attr.id)
37     }
38 }
39
40 impl NestedMetaItem {
41     /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
42     pub fn meta_item(&self) -> Option<&MetaItem> {
43         match *self {
44             NestedMetaItem::MetaItem(ref item) => Some(item),
45             _ => None,
46         }
47     }
48
49     /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
50     pub fn literal(&self) -> Option<&Lit> {
51         match *self {
52             NestedMetaItem::Literal(ref lit) => Some(lit),
53             _ => None,
54         }
55     }
56
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))
60     }
61
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())
65     }
66     pub fn name_or_empty(&self) -> Symbol {
67         self.ident().unwrap_or_else(Ident::empty).name
68     }
69
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())
74     }
75
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()
83                 {
84                     return Some((ident.name, lit));
85                 }
86                 None
87             })
88         })
89     }
90
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())
94     }
95
96     /// Returns `true` if the variant is `MetaItem`.
97     pub fn is_meta_item(&self) -> bool {
98         self.meta_item().is_some()
99     }
100
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())
104     }
105
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()
109     }
110 }
111
112 impl Attribute {
113     #[inline]
114     pub fn has_name(&self, name: Symbol) -> bool {
115         match self.kind {
116             AttrKind::Normal(ref normal) => normal.item.path == name,
117             AttrKind::DocComment(..) => false,
118         }
119     }
120
121     /// For a single-segment attribute, returns its name; otherwise, returns `None`.
122     pub fn ident(&self) -> Option<Ident> {
123         match self.kind {
124             AttrKind::Normal(ref normal) => {
125                 if normal.item.path.segments.len() == 1 {
126                     Some(normal.item.path.segments[0].ident)
127                 } else {
128                     None
129                 }
130             }
131             AttrKind::DocComment(..) => None,
132         }
133     }
134     pub fn name_or_empty(&self) -> Symbol {
135         self.ident().unwrap_or_else(Ident::empty).name
136     }
137
138     pub fn value_str(&self) -> Option<Symbol> {
139         match self.kind {
140             AttrKind::Normal(ref normal) => {
141                 normal.item.meta_kind().and_then(|kind| kind.value_str())
142             }
143             AttrKind::DocComment(..) => None,
144         }
145     }
146
147     pub fn meta_item_list(&self) -> Option<Vec<NestedMetaItem>> {
148         match self.kind {
149             AttrKind::Normal(ref normal) => match normal.item.meta_kind() {
150                 Some(MetaItemKind::List(list)) => Some(list),
151                 _ => None,
152             },
153             AttrKind::DocComment(..) => None,
154         }
155     }
156
157     pub fn is_word(&self) -> bool {
158         if let AttrKind::Normal(normal) = &self.kind {
159             matches!(normal.item.args, MacArgs::Empty)
160         } else {
161             false
162         }
163     }
164 }
165
166 impl MetaItem {
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 }
170     }
171     pub fn name_or_empty(&self) -> Symbol {
172         self.ident().unwrap_or_else(Ident::empty).name
173     }
174
175     // Example:
176     //     #[attribute(name = "value")]
177     //                 ^^^^^^^^^^^^^^
178     pub fn name_value_literal(&self) -> Option<&Lit> {
179         match &self.kind {
180             MetaItemKind::NameValue(v) => Some(v),
181             _ => None,
182         }
183     }
184
185     pub fn value_str(&self) -> Option<Symbol> {
186         self.kind.value_str()
187     }
188
189     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
190         match self.kind {
191             MetaItemKind::List(ref l) => Some(&l[..]),
192             _ => None,
193         }
194     }
195
196     pub fn is_word(&self) -> bool {
197         matches!(self.kind, MetaItemKind::Word)
198     }
199
200     pub fn has_name(&self, name: Symbol) -> bool {
201         self.path == name
202     }
203
204     /// This is used in case you want the value span instead of the whole attribute. Example:
205     ///
206     /// ```text
207     /// #[doc(alias = "foo")]
208     /// ```
209     ///
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)
213     }
214 }
215
216 impl AttrItem {
217     pub fn span(&self) -> Span {
218         self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
219     }
220
221     pub fn meta(&self, span: Span) -> Option<MetaItem> {
222         Some(MetaItem {
223             path: self.path.clone(),
224             kind: MetaItemKind::from_mac_args(&self.args)?,
225             span,
226         })
227     }
228
229     pub fn meta_kind(&self) -> Option<MetaItemKind> {
230         MetaItemKind::from_mac_args(&self.args)
231     }
232 }
233
234 impl Attribute {
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 {
238         match self.kind {
239             AttrKind::Normal(..) => false,
240             AttrKind::DocComment(..) => true,
241         }
242     }
243
244     pub fn doc_str_and_comment_kind(&self) -> Option<(Symbol, CommentKind)> {
245         match self.kind {
246             AttrKind::DocComment(kind, data) => Some((data, kind)),
247             AttrKind::Normal(ref normal) if normal.item.path == sym::doc => normal
248                 .item
249                 .meta_kind()
250                 .and_then(|kind| kind.value_str())
251                 .map(|data| (data, CommentKind::Line)),
252             _ => None,
253         }
254     }
255
256     pub fn doc_str(&self) -> Option<Symbol> {
257         match self.kind {
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())
261             }
262             _ => None,
263         }
264     }
265
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()))
268     }
269
270     pub fn get_normal_item(&self) -> &AttrItem {
271         match self.kind {
272             AttrKind::Normal(ref normal) => &normal.item,
273             AttrKind::DocComment(..) => panic!("unexpected doc comment"),
274         }
275     }
276
277     pub fn unwrap_normal_item(self) -> AttrItem {
278         match self.kind {
279             AttrKind::Normal(normal) => normal.into_inner().item,
280             AttrKind::DocComment(..) => panic!("unexpected doc comment"),
281         }
282     }
283
284     /// Extracts the MetaItem from inside this Attribute.
285     pub fn meta(&self) -> Option<MetaItem> {
286         match self.kind {
287             AttrKind::Normal(ref normal) => normal.item.meta(self.span),
288             AttrKind::DocComment(..) => None,
289         }
290     }
291
292     pub fn meta_kind(&self) -> Option<MetaItemKind> {
293         match self.kind {
294             AttrKind::Normal(ref normal) => normal.item.meta_kind(),
295             AttrKind::DocComment(..) => None,
296         }
297     }
298
299     pub fn tokens(&self) -> AttrAnnotatedTokenStream {
300         match self.kind {
301             AttrKind::Normal(ref normal) => normal
302                 .tokens
303                 .as_ref()
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),
309                     self.span,
310                 )),
311                 Spacing::Alone,
312             )),
313         }
314     }
315 }
316
317 /* Constructors */
318
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)
322 }
323
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) }
328 }
329
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) }
332 }
333
334 pub fn mk_word_item(ident: Ident) -> MetaItem {
335     MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
336 }
337
338 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
339     NestedMetaItem::MetaItem(mk_word_item(ident))
340 }
341
342 pub(crate) fn mk_attr_id() -> AttrId {
343     use std::sync::atomic::AtomicU32;
344     use std::sync::atomic::Ordering;
345
346     static NEXT_ATTR_ID: AtomicU32 = AtomicU32::new(0);
347
348     let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
349     assert!(id != u32::MAX);
350     AttrId::from_u32(id)
351 }
352
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)
355 }
356
357 pub fn mk_attr_from_item(
358     item: AttrItem,
359     tokens: Option<LazyTokenStream>,
360     style: AttrStyle,
361     span: Span,
362 ) -> Attribute {
363     Attribute {
364         kind: AttrKind::Normal(P(ast::NormalAttr { item, tokens })),
365         id: mk_attr_id(),
366         style,
367         span,
368     }
369 }
370
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)
374 }
375
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)
379 }
380
381 pub fn mk_doc_comment(
382     comment_kind: CommentKind,
383     style: AttrStyle,
384     data: Symbol,
385     span: Span,
386 ) -> Attribute {
387     Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span }
388 }
389
390 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
391     items.iter().any(|item| item.has_name(name))
392 }
393
394 impl MetaItem {
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;
400             if !is_first {
401                 let mod_sep_span =
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));
404             }
405             idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
406             last_pos = segment.ident.span.hi();
407         }
408         idents.extend(self.kind.token_trees(self.span));
409         idents
410     }
411
412     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
413     where
414         I: Iterator<Item = TokenTree>,
415     {
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 },
420                 _,
421             )) => 'arm: {
422                 let mut segments = if let token::Ident(name, _) = kind {
423                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
424                         tokens.peek()
425                     {
426                         tokens.next();
427                         vec![PathSegment::from_ident(Ident::new(name, span))]
428                     } else {
429                         break 'arm Path::from_ident(Ident::new(name, span));
430                     }
431                 } else {
432                     vec![PathSegment::path_root(span)]
433                 };
434                 loop {
435                     if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
436                         tokens.next().map(TokenTree::uninterpolate)
437                     {
438                         segments.push(PathSegment::from_ident(Ident::new(name, span)));
439                     } else {
440                         return None;
441                     }
442                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
443                         tokens.peek()
444                     {
445                         tokens.next();
446                     } else {
447                         break;
448                     }
449                 }
450                 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
451                 Path { span, segments, tokens: None }
452             }
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(),
456                 _ => return None,
457             },
458             _ => return None,
459         };
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()),
465             _ => path.span.hi(),
466         };
467         let span = path.span.with_hi(hi);
468         Some(MetaItem { path, kind, span })
469     }
470 }
471
472 impl MetaItemKind {
473     pub fn value_str(&self) -> Option<Symbol> {
474         match self {
475             MetaItemKind::NameValue(ref v) => match v.kind {
476                 LitKind::Str(ref s, _) => Some(*s),
477                 _ => None,
478             },
479             _ => None,
480         }
481     }
482
483     pub fn mac_args(&self, span: Span) -> MacArgs {
484         match self {
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()),
490                     span: lit.span,
491                     attrs: ast::AttrVec::new(),
492                     tokens: None,
493                 });
494                 MacArgs::Eq(span, MacArgsEq::Ast(expr))
495             }
496             MetaItemKind::List(list) => {
497                 let mut tts = Vec::new();
498                 for (i, item) in list.iter().enumerate() {
499                     if i > 0 {
500                         tts.push(TokenTree::token_alone(token::Comma, span));
501                     }
502                     tts.extend(item.token_trees())
503                 }
504                 MacArgs::Delimited(
505                     DelimSpan::from_single(span),
506                     MacDelimiter::Parenthesis,
507                     TokenStream::new(tts),
508                 )
509             }
510         }
511     }
512
513     fn token_trees(&self, span: Span) -> Vec<TokenTree> {
514         match *self {
515             MetaItemKind::Word => vec![],
516             MetaItemKind::NameValue(ref lit) => {
517                 vec![
518                     TokenTree::token_alone(token::Eq, span),
519                     TokenTree::Token(lit.to_token(), Spacing::Alone),
520                 ]
521             }
522             MetaItemKind::List(ref list) => {
523                 let mut tokens = Vec::new();
524                 for (i, item) in list.iter().enumerate() {
525                     if i > 0 {
526                         tokens.push(TokenTree::token_alone(token::Comma, span));
527                     }
528                     tokens.extend(item.token_trees())
529                 }
530                 vec![TokenTree::Delimited(
531                     DelimSpan::from_single(span),
532                     Delimiter::Parenthesis,
533                     TokenStream::new(tokens),
534                 )]
535             }
536         }
537     }
538
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)?;
544             result.push(item);
545             match tokens.next() {
546                 None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
547                 _ => return None,
548             }
549         }
550         Some(MetaItemKind::List(result))
551     }
552
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())
559             }
560             Some(TokenTree::Token(token, _)) => {
561                 Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
562             }
563             _ => None,
564         }
565     }
566
567     fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
568         match args {
569             MacArgs::Empty => Some(MetaItemKind::Word),
570             MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
571                 MetaItemKind::list_from_tokens(tokens.clone())
572             }
573             MacArgs::Delimited(..) => None,
574             MacArgs::Eq(_, MacArgsEq::Ast(expr)) => match &expr.kind {
575                 ast::ExprKind::Lit(lit) => Some(MetaItemKind::NameValue(lit.clone())),
576                 _ => None,
577             },
578             MacArgs::Eq(_, MacArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
579         }
580     }
581
582     fn from_tokens(
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();
588                 tokens.next();
589                 MetaItemKind::list_from_tokens(inner_tokens)
590             }
591             Some(TokenTree::Delimited(..)) => None,
592             Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
593                 tokens.next();
594                 MetaItemKind::name_value_from_tokens(tokens)
595             }
596             _ => Some(MetaItemKind::Word),
597         }
598     }
599 }
600
601 impl NestedMetaItem {
602     pub fn span(&self) -> Span {
603         match *self {
604             NestedMetaItem::MetaItem(ref item) => item.span,
605             NestedMetaItem::Literal(ref lit) => lit.span,
606         }
607     }
608
609     fn token_trees(&self) -> Vec<TokenTree> {
610         match *self {
611             NestedMetaItem::MetaItem(ref item) => item.token_trees(),
612             NestedMetaItem::Literal(ref lit) => {
613                 vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
614             }
615         }
616     }
617
618     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
619     where
620         I: Iterator<Item = TokenTree>,
621     {
622         match tokens.peek() {
623             Some(TokenTree::Token(token, _))
624                 if let Ok(lit) = Lit::from_token(token) =>
625             {
626                 tokens.next();
627                 return Some(NestedMetaItem::Literal(lit));
628             }
629             Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
630                 let inner_tokens = inner_tokens.clone();
631                 tokens.next();
632                 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
633             }
634             _ => {}
635         }
636         MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
637     }
638 }