]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast/src/attr/mod.rs
Rollup merge of #101759 - lnicola:rust-analyzer-2022-09-13, r=lnicola
[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::{DelimSpan, Spacing, TokenTree};
11 use crate::tokenstream::{LazyAttrTokenStream, TokenStream};
12 use crate::util::comments;
13
14 use rustc_index::bit_set::GrowableBitSet;
15 use rustc_span::source_map::BytePos;
16 use rustc_span::symbol::{sym, Ident, Symbol};
17 use rustc_span::Span;
18
19 use std::iter;
20
21 pub struct MarkedAttrs(GrowableBitSet<AttrId>);
22
23 impl MarkedAttrs {
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())
28     }
29
30     pub fn mark(&mut self, attr: &Attribute) {
31         self.0.insert(attr.id);
32     }
33
34     pub fn is_marked(&self, attr: &Attribute) -> bool {
35         self.0.contains(attr.id)
36     }
37 }
38
39 impl NestedMetaItem {
40     /// Returns the `MetaItem` if `self` is a `NestedMetaItem::MetaItem`.
41     pub fn meta_item(&self) -> Option<&MetaItem> {
42         match *self {
43             NestedMetaItem::MetaItem(ref item) => Some(item),
44             _ => None,
45         }
46     }
47
48     /// Returns the `Lit` if `self` is a `NestedMetaItem::Literal`s.
49     pub fn literal(&self) -> Option<&Lit> {
50         match *self {
51             NestedMetaItem::Literal(ref lit) => Some(lit),
52             _ => None,
53         }
54     }
55
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))
59     }
60
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())
64     }
65     pub fn name_or_empty(&self) -> Symbol {
66         self.ident().unwrap_or_else(Ident::empty).name
67     }
68
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())
73     }
74
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()
82                 {
83                     return Some((ident.name, lit));
84                 }
85                 None
86             })
87         })
88     }
89
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())
93     }
94
95     /// Returns `true` if the variant is `MetaItem`.
96     pub fn is_meta_item(&self) -> bool {
97         self.meta_item().is_some()
98     }
99
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())
103     }
104
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()
108     }
109 }
110
111 impl Attribute {
112     #[inline]
113     pub fn has_name(&self, name: Symbol) -> bool {
114         match self.kind {
115             AttrKind::Normal(ref normal) => normal.item.path == name,
116             AttrKind::DocComment(..) => false,
117         }
118     }
119
120     /// For a single-segment attribute, returns its name; otherwise, returns `None`.
121     pub fn ident(&self) -> Option<Ident> {
122         match self.kind {
123             AttrKind::Normal(ref normal) => {
124                 if normal.item.path.segments.len() == 1 {
125                     Some(normal.item.path.segments[0].ident)
126                 } else {
127                     None
128                 }
129             }
130             AttrKind::DocComment(..) => None,
131         }
132     }
133     pub fn name_or_empty(&self) -> Symbol {
134         self.ident().unwrap_or_else(Ident::empty).name
135     }
136
137     pub fn value_str(&self) -> Option<Symbol> {
138         match self.kind {
139             AttrKind::Normal(ref normal) => {
140                 normal.item.meta_kind().and_then(|kind| kind.value_str())
141             }
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 normal) => match normal.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(normal) = &self.kind {
158             matches!(normal.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         self.kind.value_str()
186     }
187
188     pub fn meta_item_list(&self) -> Option<&[NestedMetaItem]> {
189         match self.kind {
190             MetaItemKind::List(ref l) => Some(&l[..]),
191             _ => None,
192         }
193     }
194
195     pub fn is_word(&self) -> bool {
196         matches!(self.kind, MetaItemKind::Word)
197     }
198
199     pub fn has_name(&self, name: Symbol) -> bool {
200         self.path == name
201     }
202
203     /// This is used in case you want the value span instead of the whole attribute. Example:
204     ///
205     /// ```text
206     /// #[doc(alias = "foo")]
207     /// ```
208     ///
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)
212     }
213 }
214
215 impl AttrItem {
216     pub fn span(&self) -> Span {
217         self.args.span().map_or(self.path.span, |args_span| self.path.span.to(args_span))
218     }
219
220     pub fn meta(&self, span: Span) -> Option<MetaItem> {
221         Some(MetaItem {
222             path: self.path.clone(),
223             kind: MetaItemKind::from_mac_args(&self.args)?,
224             span,
225         })
226     }
227
228     pub fn meta_kind(&self) -> Option<MetaItemKind> {
229         MetaItemKind::from_mac_args(&self.args)
230     }
231 }
232
233 impl Attribute {
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 {
238         match self.kind {
239             AttrKind::Normal(..) => false,
240             AttrKind::DocComment(..) => true,
241         }
242     }
243
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)> {
250         match self.kind {
251             AttrKind::DocComment(kind, data) => Some((data, kind)),
252             AttrKind::Normal(ref normal) if normal.item.path == sym::doc => normal
253                 .item
254                 .meta_kind()
255                 .and_then(|kind| kind.value_str())
256                 .map(|data| (data, CommentKind::Line)),
257             _ => None,
258         }
259     }
260
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> {
266         match self.kind {
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())
270             }
271             _ => None,
272         }
273     }
274
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()))
277     }
278
279     pub fn get_normal_item(&self) -> &AttrItem {
280         match self.kind {
281             AttrKind::Normal(ref normal) => &normal.item,
282             AttrKind::DocComment(..) => panic!("unexpected doc comment"),
283         }
284     }
285
286     pub fn unwrap_normal_item(self) -> AttrItem {
287         match self.kind {
288             AttrKind::Normal(normal) => normal.into_inner().item,
289             AttrKind::DocComment(..) => panic!("unexpected doc comment"),
290         }
291     }
292
293     /// Extracts the MetaItem from inside this Attribute.
294     pub fn meta(&self) -> Option<MetaItem> {
295         match self.kind {
296             AttrKind::Normal(ref normal) => normal.item.meta(self.span),
297             AttrKind::DocComment(..) => None,
298         }
299     }
300
301     pub fn meta_kind(&self) -> Option<MetaItemKind> {
302         match self.kind {
303             AttrKind::Normal(ref normal) => normal.item.meta_kind(),
304             AttrKind::DocComment(..) => None,
305         }
306     }
307
308     pub fn tokens(&self) -> TokenStream {
309         match self.kind {
310             AttrKind::Normal(ref normal) => normal
311                 .tokens
312                 .as_ref()
313                 .unwrap_or_else(|| panic!("attribute is missing tokens: {:?}", self))
314                 .to_attr_token_stream()
315                 .to_tokenstream(),
316             AttrKind::DocComment(comment_kind, data) => TokenStream::new(vec![TokenTree::Token(
317                 Token::new(token::DocComment(comment_kind, self.style, data), self.span),
318                 Spacing::Alone,
319             )]),
320         }
321     }
322 }
323
324 /* Constructors */
325
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)
329 }
330
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) }
335 }
336
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) }
339 }
340
341 pub fn mk_word_item(ident: Ident) -> MetaItem {
342     MetaItem { path: Path::from_ident(ident), span: ident.span, kind: MetaItemKind::Word }
343 }
344
345 pub fn mk_nested_word_item(ident: Ident) -> NestedMetaItem {
346     NestedMetaItem::MetaItem(mk_word_item(ident))
347 }
348
349 pub(crate) fn mk_attr_id() -> AttrId {
350     use std::sync::atomic::AtomicU32;
351     use std::sync::atomic::Ordering;
352
353     static NEXT_ATTR_ID: AtomicU32 = AtomicU32::new(0);
354
355     let id = NEXT_ATTR_ID.fetch_add(1, Ordering::SeqCst);
356     assert!(id != u32::MAX);
357     AttrId::from_u32(id)
358 }
359
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)
362 }
363
364 pub fn mk_attr_from_item(
365     item: AttrItem,
366     tokens: Option<LazyAttrTokenStream>,
367     style: AttrStyle,
368     span: Span,
369 ) -> Attribute {
370     Attribute {
371         kind: AttrKind::Normal(P(ast::NormalAttr { item, tokens })),
372         id: mk_attr_id(),
373         style,
374         span,
375     }
376 }
377
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)
381 }
382
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)
386 }
387
388 pub fn mk_doc_comment(
389     comment_kind: CommentKind,
390     style: AttrStyle,
391     data: Symbol,
392     span: Span,
393 ) -> Attribute {
394     Attribute { kind: AttrKind::DocComment(comment_kind, data), id: mk_attr_id(), style, span }
395 }
396
397 pub fn list_contains_name(items: &[NestedMetaItem], name: Symbol) -> bool {
398     items.iter().any(|item| item.has_name(name))
399 }
400
401 impl MetaItem {
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;
407             if !is_first {
408                 let mod_sep_span =
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));
411             }
412             idents.push(TokenTree::Token(Token::from_ast_ident(segment.ident), Spacing::Alone));
413             last_pos = segment.ident.span.hi();
414         }
415         idents.extend(self.kind.token_trees(self.span));
416         idents
417     }
418
419     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<MetaItem>
420     where
421         I: Iterator<Item = TokenTree>,
422     {
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 },
427                 _,
428             )) => 'arm: {
429                 let mut segments = if let token::Ident(name, _) = kind {
430                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
431                         tokens.peek()
432                     {
433                         tokens.next();
434                         vec![PathSegment::from_ident(Ident::new(name, span))]
435                     } else {
436                         break 'arm Path::from_ident(Ident::new(name, span));
437                     }
438                 } else {
439                     vec![PathSegment::path_root(span)]
440                 };
441                 loop {
442                     if let Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }, _)) =
443                         tokens.next().map(TokenTree::uninterpolate)
444                     {
445                         segments.push(PathSegment::from_ident(Ident::new(name, span)));
446                     } else {
447                         return None;
448                     }
449                     if let Some(TokenTree::Token(Token { kind: token::ModSep, .. }, _)) =
450                         tokens.peek()
451                     {
452                         tokens.next();
453                     } else {
454                         break;
455                     }
456                 }
457                 let span = span.with_hi(segments.last().unwrap().ident.span.hi());
458                 Path { span, segments, tokens: None }
459             }
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(),
463                 _ => return None,
464             },
465             _ => return None,
466         };
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()),
472             _ => path.span.hi(),
473         };
474         let span = path.span.with_hi(hi);
475         Some(MetaItem { path, kind, span })
476     }
477 }
478
479 impl MetaItemKind {
480     pub fn value_str(&self) -> Option<Symbol> {
481         match self {
482             MetaItemKind::NameValue(ref v) => match v.kind {
483                 LitKind::Str(ref s, _) => Some(*s),
484                 _ => None,
485             },
486             _ => None,
487         }
488     }
489
490     pub fn mac_args(&self, span: Span) -> MacArgs {
491         match self {
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()),
497                     span: lit.span,
498                     attrs: ast::AttrVec::new(),
499                     tokens: None,
500                 });
501                 MacArgs::Eq(span, MacArgsEq::Ast(expr))
502             }
503             MetaItemKind::List(list) => {
504                 let mut tts = Vec::new();
505                 for (i, item) in list.iter().enumerate() {
506                     if i > 0 {
507                         tts.push(TokenTree::token_alone(token::Comma, span));
508                     }
509                     tts.extend(item.token_trees())
510                 }
511                 MacArgs::Delimited(
512                     DelimSpan::from_single(span),
513                     MacDelimiter::Parenthesis,
514                     TokenStream::new(tts),
515                 )
516             }
517         }
518     }
519
520     fn token_trees(&self, span: Span) -> Vec<TokenTree> {
521         match *self {
522             MetaItemKind::Word => vec![],
523             MetaItemKind::NameValue(ref lit) => {
524                 vec![
525                     TokenTree::token_alone(token::Eq, span),
526                     TokenTree::Token(lit.to_token(), Spacing::Alone),
527                 ]
528             }
529             MetaItemKind::List(ref list) => {
530                 let mut tokens = Vec::new();
531                 for (i, item) in list.iter().enumerate() {
532                     if i > 0 {
533                         tokens.push(TokenTree::token_alone(token::Comma, span));
534                     }
535                     tokens.extend(item.token_trees())
536                 }
537                 vec![TokenTree::Delimited(
538                     DelimSpan::from_single(span),
539                     Delimiter::Parenthesis,
540                     TokenStream::new(tokens),
541                 )]
542             }
543         }
544     }
545
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)?;
551             result.push(item);
552             match tokens.next() {
553                 None | Some(TokenTree::Token(Token { kind: token::Comma, .. }, _)) => {}
554                 _ => return None,
555             }
556         }
557         Some(MetaItemKind::List(result))
558     }
559
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())
566             }
567             Some(TokenTree::Token(token, _)) => {
568                 Lit::from_token(&token).ok().map(MetaItemKind::NameValue)
569             }
570             _ => None,
571         }
572     }
573
574     fn from_mac_args(args: &MacArgs) -> Option<MetaItemKind> {
575         match args {
576             MacArgs::Empty => Some(MetaItemKind::Word),
577             MacArgs::Delimited(_, MacDelimiter::Parenthesis, tokens) => {
578                 MetaItemKind::list_from_tokens(tokens.clone())
579             }
580             MacArgs::Delimited(..) => None,
581             MacArgs::Eq(_, MacArgsEq::Ast(expr)) => match &expr.kind {
582                 ast::ExprKind::Lit(lit) => Some(MetaItemKind::NameValue(lit.clone())),
583                 _ => None,
584             },
585             MacArgs::Eq(_, MacArgsEq::Hir(lit)) => Some(MetaItemKind::NameValue(lit.clone())),
586         }
587     }
588
589     fn from_tokens(
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();
595                 tokens.next();
596                 MetaItemKind::list_from_tokens(inner_tokens)
597             }
598             Some(TokenTree::Delimited(..)) => None,
599             Some(TokenTree::Token(Token { kind: token::Eq, .. }, _)) => {
600                 tokens.next();
601                 MetaItemKind::name_value_from_tokens(tokens)
602             }
603             _ => Some(MetaItemKind::Word),
604         }
605     }
606 }
607
608 impl NestedMetaItem {
609     pub fn span(&self) -> Span {
610         match *self {
611             NestedMetaItem::MetaItem(ref item) => item.span,
612             NestedMetaItem::Literal(ref lit) => lit.span,
613         }
614     }
615
616     fn token_trees(&self) -> Vec<TokenTree> {
617         match *self {
618             NestedMetaItem::MetaItem(ref item) => item.token_trees(),
619             NestedMetaItem::Literal(ref lit) => {
620                 vec![TokenTree::Token(lit.to_token(), Spacing::Alone)]
621             }
622         }
623     }
624
625     fn from_tokens<I>(tokens: &mut iter::Peekable<I>) -> Option<NestedMetaItem>
626     where
627         I: Iterator<Item = TokenTree>,
628     {
629         match tokens.peek() {
630             Some(TokenTree::Token(token, _))
631                 if let Ok(lit) = Lit::from_token(token) =>
632             {
633                 tokens.next();
634                 return Some(NestedMetaItem::Literal(lit));
635             }
636             Some(TokenTree::Delimited(_, Delimiter::Invisible, inner_tokens)) => {
637                 let inner_tokens = inner_tokens.clone();
638                 tokens.next();
639                 return NestedMetaItem::from_tokens(&mut inner_tokens.into_trees().peekable());
640             }
641             _ => {}
642         }
643         MetaItem::from_tokens(tokens).map(NestedMetaItem::MetaItem)
644     }
645 }