]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_parse/src/parser/attr.rs
Auto merge of #97235 - nbdd0121:unwind, r=Amanieu
[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, Delimiter, 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                             "",
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(Delimiter::Bracket))?;
134                 let item = this.parse_attr_item(false)?;
135                 this.expect(&token::CloseDelim(Delimiter::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                     rustc_errors::Applicability::MachineApplicable,
209                 );
210                 return None;
211             }
212             Err(item_err) => {
213                 item_err.cancel();
214             }
215             Ok(None) => {}
216         }
217         Some(replacement_span)
218     }
219
220     pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
221         if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_outer_attr_sp } = policy {
222             let prev_outer_attr_note =
223                 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
224
225             let mut diag = self.struct_span_err(attr_sp, reason);
226
227             if let Some(prev_outer_attr_sp) = prev_outer_attr_sp {
228                 diag.span_label(attr_sp, "not permitted following an outer attribute")
229                     .span_label(prev_outer_attr_sp, prev_outer_attr_note);
230             }
231
232             diag.note(
233                 "inner attributes, like `#![no_std]`, annotate the item enclosing them, and \
234                 are usually found at the beginning of source files",
235             );
236             if self
237                 .annotate_following_item_if_applicable(
238                     &mut diag,
239                     attr_sp,
240                     OuterAttributeType::Attribute,
241                 )
242                 .is_some()
243             {
244                 diag.note("outer attributes, like `#[test]`, annotate the item following them");
245             };
246             diag.emit();
247         }
248     }
249
250     /// Parses an inner part of an attribute (the path and following tokens).
251     /// The tokens must be either a delimited token stream, or empty token stream,
252     /// or the "legacy" key-value form.
253     ///     PATH `(` TOKEN_STREAM `)`
254     ///     PATH `[` TOKEN_STREAM `]`
255     ///     PATH `{` TOKEN_STREAM `}`
256     ///     PATH
257     ///     PATH `=` UNSUFFIXED_LIT
258     /// The delimiters or `=` are still put into the resulting token stream.
259     pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> {
260         let item = match self.token.kind {
261             token::Interpolated(ref nt) => match **nt {
262                 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
263                 _ => None,
264             },
265             _ => None,
266         };
267         Ok(if let Some(item) = item {
268             self.bump();
269             item
270         } else {
271             let do_parse = |this: &mut Self| {
272                 let path = this.parse_path(PathStyle::Mod)?;
273                 let args = this.parse_attr_args()?;
274                 Ok(ast::AttrItem { path, args, tokens: None })
275             };
276             // Attr items don't have attributes
277             if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }?
278         })
279     }
280
281     /// Parses attributes that appear after the opening of an item. These should
282     /// be preceded by an exclamation mark, but we accept and warn about one
283     /// terminated by a semicolon.
284     ///
285     /// Matches `inner_attrs*`.
286     pub(crate) fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
287         let mut attrs: Vec<ast::Attribute> = vec![];
288         loop {
289             let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
290             // Only try to parse if it is an inner attribute (has `!`).
291             let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
292                 Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
293             } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
294                 if attr_style == ast::AttrStyle::Inner {
295                     self.bump();
296                     Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
297                 } else {
298                     None
299                 }
300             } else {
301                 None
302             };
303             if let Some(attr) = attr {
304                 let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
305                 // If we are currently capturing tokens, mark the location of this inner attribute.
306                 // If capturing ends up creating a `LazyTokenStream`, we will include
307                 // this replace range with it, removing the inner attribute from the final
308                 // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note.
309                 // During macro expansion, they are selectively inserted back into the
310                 // token stream (the first inner attribute is removed each time we invoke the
311                 // corresponding macro).
312                 let range = start_pos..end_pos;
313                 if let Capturing::Yes = self.capture_state.capturing {
314                     self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![]));
315                 }
316                 attrs.push(attr);
317             } else {
318                 break;
319             }
320         }
321         Ok(attrs)
322     }
323
324     pub(crate) fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
325         let lit = self.parse_lit()?;
326         debug!("checking if {:?} is unusuffixed", lit);
327
328         if !lit.kind.is_unsuffixed() {
329             self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
330                 .help(
331                     "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
332                     use an unsuffixed version (`1`, `1.0`, etc.)",
333                 )
334                 .emit();
335         }
336
337         Ok(lit)
338     }
339
340     /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
341     pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
342         let cfg_predicate = self.parse_meta_item()?;
343         self.expect(&token::Comma)?;
344
345         // Presumably, the majority of the time there will only be one attr.
346         let mut expanded_attrs = Vec::with_capacity(1);
347         while self.token.kind != token::Eof {
348             let lo = self.token.span;
349             let item = self.parse_attr_item(true)?;
350             expanded_attrs.push((item, lo.to(self.prev_token.span)));
351             if !self.eat(&token::Comma) {
352                 break;
353             }
354         }
355
356         Ok((cfg_predicate, expanded_attrs))
357     }
358
359     /// Matches `COMMASEP(meta_item_inner)`.
360     pub(crate) fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
361         // Presumably, the majority of the time there will only be one attr.
362         let mut nmis = Vec::with_capacity(1);
363         while self.token.kind != token::Eof {
364             nmis.push(self.parse_meta_item_inner()?);
365             if !self.eat(&token::Comma) {
366                 break;
367             }
368         }
369         Ok(nmis)
370     }
371
372     /// Matches the following grammar (per RFC 1559).
373     /// ```ebnf
374     /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
375     /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
376     /// ```
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     pub(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(Delimiter::Parenthesis)) {
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 }