]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/attr.rs
Rollup merge of #95857 - ouz-a:mir-opt, r=oli-obk
[rust.git] / compiler / rustc_parse / src / parser / attr.rs
1 use super::{AttrWrapper, Capturing, FnParseMode, ForceCollect, 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, Diagnostic, PResult};
7 use rustc_span::{sym, BytePos, 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_outer_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_outer_attr_sp: None,
26 };
27
28 enum OuterAttributeType {
29     DocComment,
30     DocBlockComment,
31     Attribute,
32 }
33
34 impl<'a> Parser<'a> {
35     /// Parses attributes that appear before an item.
36     pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> {
37         let mut outer_attrs: Vec<ast::Attribute> = Vec::new();
38         let mut just_parsed_doc_comment = false;
39         let start_pos = self.token_cursor.num_next_calls;
40         loop {
41             let attr = if self.check(&token::Pound) {
42                 let prev_outer_attr_sp = outer_attrs.last().map(|attr| attr.span);
43
44                 let inner_error_reason = if just_parsed_doc_comment {
45                     "an inner attribute is not permitted following an outer doc comment"
46                 } else if prev_outer_attr_sp.is_some() {
47                     "an inner attribute is not permitted following an outer attribute"
48                 } else {
49                     DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
50                 };
51                 let inner_parse_policy = InnerAttrPolicy::Forbidden {
52                     reason: inner_error_reason,
53                     saw_doc_comment: just_parsed_doc_comment,
54                     prev_outer_attr_sp,
55                 };
56                 just_parsed_doc_comment = false;
57                 Some(self.parse_attribute(inner_parse_policy)?)
58             } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
59                 if attr_style != ast::AttrStyle::Outer {
60                     let span = self.token.span;
61                     let mut err = self.sess.span_diagnostic.struct_span_err_with_code(
62                         span,
63                         "expected outer doc comment",
64                         error_code!(E0753),
65                     );
66                     if let Some(replacement_span) = self.annotate_following_item_if_applicable(
67                         &mut err,
68                         span,
69                         match comment_kind {
70                             token::CommentKind::Line => OuterAttributeType::DocComment,
71                             token::CommentKind::Block => OuterAttributeType::DocBlockComment,
72                         },
73                     ) {
74                         err.note(
75                             "inner doc comments like this (starting with `//!` or `/*!`) can \
76                             only appear before items",
77                         );
78                         err.span_suggestion_verbose(
79                             replacement_span,
80                             "you might have meant to write a regular comment",
81                             String::new(),
82                             rustc_errors::Applicability::MachineApplicable,
83                         );
84                     }
85                     err.emit();
86                 }
87                 self.bump();
88                 just_parsed_doc_comment = true;
89                 // Always make an outer attribute - this allows us to recover from a misplaced
90                 // inner attribute.
91                 Some(attr::mk_doc_comment(
92                     comment_kind,
93                     ast::AttrStyle::Outer,
94                     data,
95                     self.prev_token.span,
96                 ))
97             } else {
98                 None
99             };
100
101             if let Some(attr) = attr {
102                 if attr.style == ast::AttrStyle::Outer {
103                     outer_attrs.push(attr);
104                 }
105             } else {
106                 break;
107             }
108         }
109         Ok(AttrWrapper::new(outer_attrs.into(), start_pos))
110     }
111
112     /// Matches `attribute = # ! [ meta_item ]`.
113     /// `inner_parse_policy` prescribes how to handle inner attributes.
114     // Public for rustfmt usage.
115     pub fn parse_attribute(
116         &mut self,
117         inner_parse_policy: InnerAttrPolicy<'_>,
118     ) -> PResult<'a, ast::Attribute> {
119         debug!(
120             "parse_attribute: inner_parse_policy={:?} self.token={:?}",
121             inner_parse_policy, self.token
122         );
123         let lo = self.token.span;
124         // Attributes can't have attributes of their own [Editor's note: not with that attitude]
125         self.collect_tokens_no_attrs(|this| {
126             if this.eat(&token::Pound) {
127                 let style = if this.eat(&token::Not) {
128                     ast::AttrStyle::Inner
129                 } else {
130                     ast::AttrStyle::Outer
131                 };
132
133                 this.expect(&token::OpenDelim(token::Bracket))?;
134                 let item = this.parse_attr_item(false)?;
135                 this.expect(&token::CloseDelim(token::Bracket))?;
136                 let attr_sp = lo.to(this.prev_token.span);
137
138                 // Emit error if inner attribute is encountered and forbidden.
139                 if style == ast::AttrStyle::Inner {
140                     this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy);
141                 }
142
143                 Ok(attr::mk_attr_from_item(item, None, style, attr_sp))
144             } else {
145                 let token_str = pprust::token_to_string(&this.token);
146                 let msg = &format!("expected `#`, found `{token_str}`");
147                 Err(this.struct_span_err(this.token.span, msg))
148             }
149         })
150     }
151
152     fn annotate_following_item_if_applicable(
153         &self,
154         err: &mut Diagnostic,
155         span: Span,
156         attr_type: OuterAttributeType,
157     ) -> Option<Span> {
158         let mut snapshot = self.create_snapshot_for_diagnostic();
159         let lo = span.lo()
160             + BytePos(match attr_type {
161                 OuterAttributeType::Attribute => 1,
162                 _ => 2,
163             });
164         let hi = lo + BytePos(1);
165         let replacement_span = span.with_lo(lo).with_hi(hi);
166         if let OuterAttributeType::DocBlockComment | OuterAttributeType::DocComment = attr_type {
167             snapshot.bump();
168         }
169         loop {
170             // skip any other attributes, we want the item
171             if snapshot.token.kind == token::Pound {
172                 if let Err(err) = snapshot.parse_attribute(InnerAttrPolicy::Permitted) {
173                     err.cancel();
174                     return Some(replacement_span);
175                 }
176             } else {
177                 break;
178             }
179         }
180         match snapshot.parse_item_common(
181             AttrWrapper::empty(),
182             true,
183             false,
184             FnParseMode { req_name: |_| true, req_body: true },
185             ForceCollect::No,
186         ) {
187             Ok(Some(item)) => {
188                 let attr_name = match attr_type {
189                     OuterAttributeType::Attribute => "attribute",
190                     _ => "doc comment",
191                 };
192                 err.span_label(
193                     item.span,
194                     &format!("the inner {} doesn't annotate this {}", attr_name, item.kind.descr()),
195                 );
196                 err.span_suggestion_verbose(
197                     replacement_span,
198                     &format!(
199                         "to annotate the {}, change the {} from inner to outer style",
200                         item.kind.descr(),
201                         attr_name
202                     ),
203                     (match attr_type {
204                         OuterAttributeType::Attribute => "",
205                         OuterAttributeType::DocBlockComment => "*",
206                         OuterAttributeType::DocComment => "/",
207                     })
208                     .to_string(),
209                     rustc_errors::Applicability::MachineApplicable,
210                 );
211                 return None;
212             }
213             Err(item_err) => {
214                 item_err.cancel();
215             }
216             Ok(None) => {}
217         }
218         Some(replacement_span)
219     }
220
221     pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
222         if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_outer_attr_sp } = policy {
223             let prev_outer_attr_note =
224                 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
225
226             let mut diag = self.struct_span_err(attr_sp, reason);
227
228             if let Some(prev_outer_attr_sp) = prev_outer_attr_sp {
229                 diag.span_label(attr_sp, "not permitted following an outer attribute")
230                     .span_label(prev_outer_attr_sp, prev_outer_attr_note);
231             }
232
233             diag.note(
234                 "inner attributes, like `#![no_std]`, annotate the item enclosing them, and \
235                 are usually found at the beginning of source files",
236             );
237             if self
238                 .annotate_following_item_if_applicable(
239                     &mut diag,
240                     attr_sp,
241                     OuterAttributeType::Attribute,
242                 )
243                 .is_some()
244             {
245                 diag.note("outer attributes, like `#[test]`, annotate the item following them");
246             };
247             diag.emit();
248         }
249     }
250
251     /// Parses an inner part of an attribute (the path and following tokens).
252     /// The tokens must be either a delimited token stream, or empty token stream,
253     /// or the "legacy" key-value form.
254     ///     PATH `(` TOKEN_STREAM `)`
255     ///     PATH `[` TOKEN_STREAM `]`
256     ///     PATH `{` TOKEN_STREAM `}`
257     ///     PATH
258     ///     PATH `=` UNSUFFIXED_LIT
259     /// The delimiters or `=` are still put into the resulting token stream.
260     pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> {
261         let item = match self.token.kind {
262             token::Interpolated(ref nt) => match **nt {
263                 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
264                 _ => None,
265             },
266             _ => None,
267         };
268         Ok(if let Some(item) = item {
269             self.bump();
270             item
271         } else {
272             let do_parse = |this: &mut Self| {
273                 let path = this.parse_path(PathStyle::Mod)?;
274                 let args = this.parse_attr_args()?;
275                 Ok(ast::AttrItem { path, args, tokens: None })
276             };
277             // Attr items don't have attributes
278             if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }?
279         })
280     }
281
282     /// Parses attributes that appear after the opening of an item. These should
283     /// be preceded by an exclamation mark, but we accept and warn about one
284     /// terminated by a semicolon.
285     ///
286     /// Matches `inner_attrs*`.
287     crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
288         let mut attrs: Vec<ast::Attribute> = vec![];
289         loop {
290             let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
291             // Only try to parse if it is an inner attribute (has `!`).
292             let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
293                 Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
294             } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
295                 if attr_style == ast::AttrStyle::Inner {
296                     self.bump();
297                     Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
298                 } else {
299                     None
300                 }
301             } else {
302                 None
303             };
304             if let Some(attr) = attr {
305                 let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
306                 // If we are currently capturing tokens, mark the location of this inner attribute.
307                 // If capturing ends up creating a `LazyTokenStream`, we will include
308                 // this replace range with it, removing the inner attribute from the final
309                 // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note.
310                 // During macro expansion, they are selectively inserted back into the
311                 // token stream (the first inner attribute is removed each time we invoke the
312                 // corresponding macro).
313                 let range = start_pos..end_pos;
314                 if let Capturing::Yes = self.capture_state.capturing {
315                     self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![]));
316                 }
317                 attrs.push(attr);
318             } else {
319                 break;
320             }
321         }
322         Ok(attrs)
323     }
324
325     crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
326         let lit = self.parse_lit()?;
327         debug!("checking if {:?} is unusuffixed", lit);
328
329         if !lit.kind.is_unsuffixed() {
330             self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
331                 .help(
332                     "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
333                     use an unsuffixed version (`1`, `1.0`, etc.)",
334                 )
335                 .emit();
336         }
337
338         Ok(lit)
339     }
340
341     /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
342     pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
343         let cfg_predicate = self.parse_meta_item()?;
344         self.expect(&token::Comma)?;
345
346         // Presumably, the majority of the time there will only be one attr.
347         let mut expanded_attrs = Vec::with_capacity(1);
348         while self.token.kind != token::Eof {
349             let lo = self.token.span;
350             let item = self.parse_attr_item(true)?;
351             expanded_attrs.push((item, lo.to(self.prev_token.span)));
352             if !self.eat(&token::Comma) {
353                 break;
354             }
355         }
356
357         Ok((cfg_predicate, expanded_attrs))
358     }
359
360     /// Matches `COMMASEP(meta_item_inner)`.
361     crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
362         // Presumably, the majority of the time there will only be one attr.
363         let mut nmis = Vec::with_capacity(1);
364         while self.token.kind != token::Eof {
365             nmis.push(self.parse_meta_item_inner()?);
366             if !self.eat(&token::Comma) {
367                 break;
368             }
369         }
370         Ok(nmis)
371     }
372
373     /// Matches the following grammar (per RFC 1559).
374     ///
375     ///     meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
376     ///     meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
377     pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
378         let nt_meta = match self.token.kind {
379             token::Interpolated(ref nt) => match **nt {
380                 token::NtMeta(ref e) => Some(e.clone()),
381                 _ => None,
382             },
383             _ => None,
384         };
385
386         if let Some(item) = nt_meta {
387             return match item.meta(item.path.span) {
388                 Some(meta) => {
389                     self.bump();
390                     Ok(meta)
391                 }
392                 None => self.unexpected(),
393             };
394         }
395
396         let lo = self.token.span;
397         let path = self.parse_path(PathStyle::Mod)?;
398         let kind = self.parse_meta_item_kind()?;
399         let span = lo.to(self.prev_token.span);
400         Ok(ast::MetaItem { path, kind, span })
401     }
402
403     crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
404         Ok(if self.eat(&token::Eq) {
405             ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
406         } else if self.check(&token::OpenDelim(token::Paren)) {
407             // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
408             let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
409             ast::MetaItemKind::List(list)
410         } else {
411             ast::MetaItemKind::Word
412         })
413     }
414
415     /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
416     fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
417         match self.parse_unsuffixed_lit() {
418             Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
419             Err(err) => err.cancel(),
420         }
421
422         match self.parse_meta_item() {
423             Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
424             Err(err) => err.cancel(),
425         }
426
427         let found = pprust::token_to_string(&self.token);
428         let msg = format!("expected unsuffixed literal or identifier, found `{found}`");
429         Err(self.struct_span_err(self.token.span, &msg))
430     }
431 }
432
433 pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool {
434     // One of the attributes may either itself be a macro,
435     // or expand to macro attributes (`cfg_attr`).
436     attrs.iter().any(|attr| {
437         if attr.is_doc_comment() {
438             return false;
439         }
440         attr.ident().map_or(true, |ident| {
441             ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name)
442         })
443     })
444 }