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