]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/attr.rs
Merge commit '40dd3e2b7089b5e96714e064b731f6dbf17c61a9' into sync_cg_clif-2021-05-27
[rust.git] / compiler / rustc_parse / src / parser / attr.rs
1 use super::{AttrWrapper, Capturing, Parser, PathStyle};
2 use rustc_ast as ast;
3 use rustc_ast::attr;
4 use rustc_ast::token::{self, Nonterminal};
5 use rustc_ast_pretty::pprust;
6 use rustc_errors::{error_code, PResult};
7 use rustc_span::{sym, Span};
8 use std::convert::TryInto;
9
10 use tracing::debug;
11
12 // Public for rustfmt usage
13 #[derive(Debug)]
14 pub enum InnerAttrPolicy<'a> {
15     Permitted,
16     Forbidden { reason: &'a str, saw_doc_comment: bool, prev_attr_sp: Option<Span> },
17 }
18
19 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
20                                                      permitted in this context";
21
22 pub(super) const DEFAULT_INNER_ATTR_FORBIDDEN: InnerAttrPolicy<'_> = InnerAttrPolicy::Forbidden {
23     reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG,
24     saw_doc_comment: false,
25     prev_attr_sp: None,
26 };
27
28 impl<'a> Parser<'a> {
29     /// Parses attributes that appear before an item.
30     pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> {
31         let mut attrs: Vec<ast::Attribute> = Vec::new();
32         let mut just_parsed_doc_comment = false;
33         let start_pos = self.token_cursor.num_next_calls;
34         loop {
35             debug!("parse_outer_attributes: self.token={:?}", self.token);
36             let attr = if self.check(&token::Pound) {
37                 let inner_error_reason = if just_parsed_doc_comment {
38                     "an inner attribute is not permitted following an outer doc comment"
39                 } else if !attrs.is_empty() {
40                     "an inner attribute is not permitted following an outer attribute"
41                 } else {
42                     DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
43                 };
44                 let inner_parse_policy = InnerAttrPolicy::Forbidden {
45                     reason: inner_error_reason,
46                     saw_doc_comment: just_parsed_doc_comment,
47                     prev_attr_sp: attrs.last().map(|a| a.span),
48                 };
49                 just_parsed_doc_comment = false;
50                 Some(self.parse_attribute(inner_parse_policy)?)
51             } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
52                 if attr_style != ast::AttrStyle::Outer {
53                     self.sess
54                         .span_diagnostic
55                         .struct_span_err_with_code(
56                             self.token.span,
57                             "expected outer doc comment",
58                             error_code!(E0753),
59                         )
60                         .note(
61                             "inner doc comments like this (starting with \
62                          `//!` or `/*!`) can only appear before items",
63                         )
64                         .emit();
65                 }
66                 self.bump();
67                 just_parsed_doc_comment = true;
68                 Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
69             } else {
70                 None
71             };
72
73             if let Some(attr) = attr {
74                 attrs.push(attr);
75             } else {
76                 break;
77             }
78         }
79         Ok(AttrWrapper::new(attrs.into(), start_pos))
80     }
81
82     /// Matches `attribute = # ! [ meta_item ]`.
83     /// `inner_parse_policy` prescribes how to handle inner attributes.
84     // Public for rustfmt usage.
85     pub fn parse_attribute(
86         &mut self,
87         inner_parse_policy: InnerAttrPolicy<'_>,
88     ) -> PResult<'a, ast::Attribute> {
89         debug!(
90             "parse_attribute: inner_parse_policy={:?} self.token={:?}",
91             inner_parse_policy, self.token
92         );
93         let lo = self.token.span;
94         // Attributse can't have attributes of their own
95         self.collect_tokens_no_attrs(|this| {
96             if this.eat(&token::Pound) {
97                 let style = if this.eat(&token::Not) {
98                     ast::AttrStyle::Inner
99                 } else {
100                     ast::AttrStyle::Outer
101                 };
102
103                 this.expect(&token::OpenDelim(token::Bracket))?;
104                 let item = this.parse_attr_item(false)?;
105                 this.expect(&token::CloseDelim(token::Bracket))?;
106                 let attr_sp = lo.to(this.prev_token.span);
107
108                 // Emit error if inner attribute is encountered and forbidden.
109                 if style == ast::AttrStyle::Inner {
110                     this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy);
111                 }
112
113                 Ok(attr::mk_attr_from_item(item, None, style, attr_sp))
114             } else {
115                 let token_str = pprust::token_to_string(&this.token);
116                 let msg = &format!("expected `#`, found `{}`", token_str);
117                 Err(this.struct_span_err(this.token.span, msg))
118             }
119         })
120     }
121
122     pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
123         if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_attr_sp } = policy {
124             let prev_attr_note =
125                 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
126
127             let mut diag = self.struct_span_err(attr_sp, reason);
128
129             if let Some(prev_attr_sp) = prev_attr_sp {
130                 diag.span_label(attr_sp, "not permitted following an outer attribute")
131                     .span_label(prev_attr_sp, prev_attr_note);
132             }
133
134             diag.note(
135                 "inner attributes, like `#![no_std]`, annotate the item enclosing them, \
136                 and are usually found at the beginning of source files. \
137                 Outer attributes, like `#[test]`, annotate the item following them.",
138             )
139             .emit();
140         }
141     }
142
143     /// Parses an inner part of an attribute (the path and following tokens).
144     /// The tokens must be either a delimited token stream, or empty token stream,
145     /// or the "legacy" key-value form.
146     ///     PATH `(` TOKEN_STREAM `)`
147     ///     PATH `[` TOKEN_STREAM `]`
148     ///     PATH `{` TOKEN_STREAM `}`
149     ///     PATH
150     ///     PATH `=` UNSUFFIXED_LIT
151     /// The delimiters or `=` are still put into the resulting token stream.
152     pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> {
153         let item = match self.token.kind {
154             token::Interpolated(ref nt) => match **nt {
155                 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
156                 _ => None,
157             },
158             _ => None,
159         };
160         Ok(if let Some(item) = item {
161             self.bump();
162             item
163         } else {
164             let do_parse = |this: &mut Self| {
165                 let path = this.parse_path(PathStyle::Mod)?;
166                 let args = this.parse_attr_args()?;
167                 Ok(ast::AttrItem { path, args, tokens: None })
168             };
169             // Attr items don't have attributes
170             if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }?
171         })
172     }
173
174     /// Parses attributes that appear after the opening of an item. These should
175     /// be preceded by an exclamation mark, but we accept and warn about one
176     /// terminated by a semicolon.
177     ///
178     /// Matches `inner_attrs*`.
179     crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
180         let mut attrs: Vec<ast::Attribute> = vec![];
181         loop {
182             let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
183             // Only try to parse if it is an inner attribute (has `!`).
184             let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
185                 Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
186             } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
187                 if attr_style == ast::AttrStyle::Inner {
188                     self.bump();
189                     Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
190                 } else {
191                     None
192                 }
193             } else {
194                 None
195             };
196             if let Some(attr) = attr {
197                 let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
198                 // If we are currently capturing tokens, mark the location of this inner attribute.
199                 // If capturing ends up creating a `LazyTokenStream`, we will include
200                 // this replace range with it, removing the inner attribute from the final
201                 // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note.
202                 // During macro expansion, they are selectively inserted back into the
203                 // token stream (the first inner attribute is remoevd each time we invoke the
204                 // corresponding macro).
205                 let range = start_pos..end_pos;
206                 if let Capturing::Yes = self.capture_state.capturing {
207                     self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![]));
208                 }
209                 attrs.push(attr);
210             } else {
211                 break;
212             }
213         }
214         Ok(attrs)
215     }
216
217     crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
218         let lit = self.parse_lit()?;
219         debug!("checking if {:?} is unusuffixed", lit);
220
221         if !lit.kind.is_unsuffixed() {
222             self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
223                 .help(
224                     "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
225                     use an unsuffixed version (`1`, `1.0`, etc.)",
226                 )
227                 .emit();
228         }
229
230         Ok(lit)
231     }
232
233     /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
234     pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
235         let cfg_predicate = self.parse_meta_item()?;
236         self.expect(&token::Comma)?;
237
238         // Presumably, the majority of the time there will only be one attr.
239         let mut expanded_attrs = Vec::with_capacity(1);
240         while self.token.kind != token::Eof {
241             let lo = self.token.span;
242             let item = self.parse_attr_item(true)?;
243             expanded_attrs.push((item, lo.to(self.prev_token.span)));
244             if !self.eat(&token::Comma) {
245                 break;
246             }
247         }
248
249         Ok((cfg_predicate, expanded_attrs))
250     }
251
252     /// Matches `COMMASEP(meta_item_inner)`.
253     crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
254         // Presumably, the majority of the time there will only be one attr.
255         let mut nmis = Vec::with_capacity(1);
256         while self.token.kind != token::Eof {
257             nmis.push(self.parse_meta_item_inner()?);
258             if !self.eat(&token::Comma) {
259                 break;
260             }
261         }
262         Ok(nmis)
263     }
264
265     /// Matches the following grammar (per RFC 1559).
266     ///
267     ///     meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
268     ///     meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
269     pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
270         let nt_meta = match self.token.kind {
271             token::Interpolated(ref nt) => match **nt {
272                 token::NtMeta(ref e) => Some(e.clone()),
273                 _ => None,
274             },
275             _ => None,
276         };
277
278         if let Some(item) = nt_meta {
279             return match item.meta(item.path.span) {
280                 Some(meta) => {
281                     self.bump();
282                     Ok(meta)
283                 }
284                 None => self.unexpected(),
285             };
286         }
287
288         let lo = self.token.span;
289         let path = self.parse_path(PathStyle::Mod)?;
290         let kind = self.parse_meta_item_kind()?;
291         let span = lo.to(self.prev_token.span);
292         Ok(ast::MetaItem { path, kind, span })
293     }
294
295     crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
296         Ok(if self.eat(&token::Eq) {
297             ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
298         } else if self.check(&token::OpenDelim(token::Paren)) {
299             // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
300             let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
301             ast::MetaItemKind::List(list)
302         } else {
303             ast::MetaItemKind::Word
304         })
305     }
306
307     /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
308     fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
309         match self.parse_unsuffixed_lit() {
310             Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
311             Err(ref mut err) => err.cancel(),
312         }
313
314         match self.parse_meta_item() {
315             Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
316             Err(ref mut err) => err.cancel(),
317         }
318
319         let found = pprust::token_to_string(&self.token);
320         let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
321         Err(self.struct_span_err(self.token.span, &msg))
322     }
323 }
324
325 pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool {
326     // One of the attributes may either itself be a macro,
327     // or expand to macro attributes (`cfg_attr`).
328     attrs.iter().any(|attr| {
329         if attr.is_doc_comment() {
330             return false;
331         }
332         attr.ident().map_or(true, |ident| {
333             ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name)
334         })
335     })
336 }