]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/attr/mod.rs
Auto merge of #95295 - CAD97:layout-isize, r=scottmcm
[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, TreeAndSpacing};
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_and_spacings(&self) -> Vec<TreeAndSpacing> {
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(token::ModSep, mod_sep_span).into());
400             }
401             idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident)).into());
402             last_pos = segment.ident.span.hi();
403         }
404         idents.extend(self.kind.token_trees_and_spacings(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(Token {
415                 kind: kind @ (token::Ident(..) | token::ModSep),
416                 span,
417             })) => 'arm: {
418                 let mut segments = if let token::Ident(name, _) = kind {
419                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek()
420                     {
421                         tokens.next();
422                         vec![PathSegment::from_ident(Ident::new(name, span))]
423                     } else {
424                         break 'arm Path::from_ident(Ident::new(name, span));
425                     }
426                 } else {
427                     vec![PathSegment::path_root(span)]
428                 };
429                 loop {
430                     if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span })) =
431                         tokens.next().map(TokenTree::uninterpolate)
432                     {
433                         segments.push(PathSegment::from_ident(Ident::new(name, span)));
434                     } else {
435                         return None;
436                     }
437                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. })) = tokens.peek()
438                     {
439                         tokens.next();
440                     } else {
441                         break;
442                     }
443                 }
444                 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
445                 Path { span, segments, tokens: None }
446             }
447             Some(TokenTree::Token(Token { kind: token::Interpolated(nt), .. })) => match *nt {
448                 token::Nonterminal::NtMeta(ref item) => return item.meta(item.path.span),
449                 token::Nonterminal::NtPath(ref path) => (**path).clone(),
450                 _ => return None,
451             },
452             _ => return None,
453         };
454         let list_closing_paren_pos = tokens.peek().map(|tt| tt.span().hi());
455         let kind = MetaItemKind::from_tokens(tokens)?;
456         let hi = match kind {
457             MetaItemKind::NameValue(ref lit) => lit.span.hi(),
458             MetaItemKind::List(..) => list_closing_paren_pos.unwrap_or(path.span.hi()),
459             _ => path.span.hi(),
460         };
461         let span = path.span.with_hi(hi);
462         Some(MetaItem { path, kind, span })
463     }
464 }
465
466 impl MetaItemKind {
467     pub fn value_str(&self) -> Option<Symbol> {
468         match self {
469             MetaItemKind::NameValue(ref v) => match v.kind {
470                 LitKind::Str(ref s, _) => Some(*s),
471                 _ => None,
472             },
473             _ => None,
474         }
475     }
476
477     pub fn mac_args(&self, span: Span) -> MacArgs {
478         match self {
479             MetaItemKind::Word => MacArgs::Empty,
480             MetaItemKind::NameValue(lit) => {
481                 let expr = P(ast::Expr {
482                     id: ast::DUMMY_NODE_ID,
483                     kind: ast::ExprKind::Lit(lit.clone()),
484                     span: lit.span,
485                     attrs: ThinVec::new(),
486                     tokens: None,
487                 });
488                 MacArgs::Eq(span, MacArgsEq::Ast(expr))
489             }
490             MetaItemKind::List(list) => {
491                 let mut tts = Vec::new();
492                 for (i, item) in list.iter().enumerate() {
493                     if i > 0 {
494                         tts.push(TokenTree::token(token::Comma, span).into());
495                     }
496                     tts.extend(item.token_trees_and_spacings())
497                 }
498                 MacArgs::Delimited(
499                     DelimSpan::from_single(span),
500                     MacDelimiter::Parenthesis,
501                     TokenStream::new(tts),
502                 )
503             }
504         }
505     }
506
507     fn token_trees_and_spacings(&self, span: Span) -> Vec<TreeAndSpacing> {
508         match *self {
509             MetaItemKind::Word => vec![],
510             MetaItemKind::NameValue(ref lit) => {
511                 vec![
512                     TokenTree::token(token::Eq, span).into(),
513                     TokenTree::Token(lit.to_token()).into(),
514                 ]
515             }
516             MetaItemKind::List(ref list) => {
517                 let mut tokens = Vec::new();
518                 for (i, item) in list.iter().enumerate() {
519                     if i > 0 {
520                         tokens.push(TokenTree::token(token::Comma, span).into());
521                     }
522                     tokens.extend(item.token_trees_and_spacings())
523                 }
524                 vec![
525                     TokenTree::Delimited(
526                         DelimSpan::from_single(span),
527                         Delimiter::Parenthesis,
528                         TokenStream::new(tokens),
529                     )
530                     .into(),
531                 ]
532             }
533         }
534     }
535
536     fn list_from_tokens(tokens: TokenStream) -> Option<MetaItemKind> {
537         let mut tokens = tokens.into_trees().peekable();
538         let mut result = Vec::new();
539         while tokens.peek().is_some() {
540             let item = NestedMetaItem::from_tokens(&mut tokens)?;
541             result.push(item);
542             match tokens.next() {
543                 None | Some(TokenTree::Token(Token { kind: token::Comma, .. })) => {}
544                 _ => return None,
545             }
546         }
547         Some(MetaItemKind::List(result))
548     }
549
550     fn name_value_from_tokens(
551         tokens: &mut impl Iterator<Item = TokenTree>,
552     ) -> Option<MetaItemKind> {
553         match tokens.next() {
554             Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
555                 MetaItemKind::name_value_from_tokens(&mut inner_tokens.into_trees())
556             }
557             Some(TokenTree::Token(token)) => {
558                 Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
559             }
560             _ => None,
561         }
562     }
563
564     fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
565         match args {
566             MacArgs::Empty => Some(MetaItemKind::Word),
567             MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
568                 MetaItemKind::list_from_tokens(tokens.clone())
569             }
570             MacArgs::Delimited(..) => None,
571             MacArgs::Eq(_, MacArgsEq::Ast(expr)) => match &expr.kind {
572                 ast::ExprKind::Lit(lit) => Some(MetaItemKind::NameValue(lit.clone())),
573                 _ => None,
574             },
575             MacArgs::Eq(_, MacArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
576         }
577     }
578
579     fn from_tokens(
580         tokens: &mut iter::Peekable<impl Iterator<Item = TokenTree>>,
581     ) -> Option<MetaItemKind> {
582         match tokens.peek() {
583             Some(TokenTree::Delimited(_, Delimiter::Parenthesis, inner_tokens)) => {
584                 let inner_tokens = inner_tokens.clone();
585                 tokens.next();
586                 MetaItemKind::list_from_tokens(inner_tokens)
587             }
588             Some(TokenTree::Delimited(..)) => None,
589             Some(TokenTree::Token(Token { kind: token::Eq, .. })) => {
590                 tokens.next();
591                 MetaItemKind::name_value_from_tokens(tokens)
592             }
593             _ => Some(MetaItemKind::Word),
594         }
595     }
596 }
597
598 impl NestedMetaItem {
599     pub fn span(&self) -> Span {
600         match *self {
601             NestedMetaItem::MetaItem(ref item) => item.span,
602             NestedMetaItem::Literal(ref lit) => lit.span,
603         }
604     }
605
606     fn token_trees_and_spacings(&self) -> Vec<TreeAndSpacing> {
607         match *self {
608             NestedMetaItem::MetaItem(ref item) => item.token_trees_and_spacings(),
609             NestedMetaItem::Literal(ref lit) => vec![TokenTree::Token(lit.to_token()).into()],
610         }
611     }
612
613     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
614     where
615         I: Iterator<Item = TokenTree>,
616     {
617         match tokens.peek() {
618             Some(TokenTree::Token(token))
619                 if let Ok(lit) = Lit::from_token(token) =>
620             {
621                 tokens.next();
622                 return Some(NestedMetaItem::Literal(lit));
623             }
624             Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
625                 let inner_tokens = inner_tokens.clone();
626                 tokens.next();
627                 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
628             }
629             _ => {}
630         }
631         MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
632     }
633 }