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