]> git.lizzy.rs Git - rust.git/blob - src/librustc_parse/parser/attr.rs
Add comment about the lack of `ExpnData` serialization for proc-macro crates
[rust.git] / src / librustc_parse / parser / attr.rs
1 use super::{Parser, PathStyle};
2 use rustc_ast::ast;
3 use rustc_ast::attr;
4 use rustc_ast::token::{self, Nonterminal};
5 use rustc_ast::util::comments;
6 use rustc_ast_pretty::pprust;
7 use rustc_errors::{error_code, PResult};
8 use rustc_span::{Span, Symbol};
9
10 use log::debug;
11
12 #[derive(Debug)]
13 pub(super) 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             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                 let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?;
48                 attrs.push(attr);
49                 just_parsed_doc_comment = false;
50             } else if let token::DocComment(s) = self.token.kind {
51                 let attr = self.mk_doc_comment(s);
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                 attrs.push(attr);
67                 self.bump();
68                 just_parsed_doc_comment = true;
69             } else {
70                 break;
71             }
72         }
73         Ok(attrs)
74     }
75
76     fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
77         attr::mk_doc_comment(comments::doc_comment_style(s), s, self.token.span)
78     }
79
80     /// Matches `attribute = # ! [ meta_item ]`.
81     ///
82     /// If `permit_inner` is `true`, then a leading `!` indicates an inner
83     /// attribute.
84     pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
85         debug!("parse_attribute: permit_inner={:?} self.token={:?}", permit_inner, self.token);
86         let inner_parse_policy =
87             if permit_inner { InnerAttrPolicy::Permitted } else { DEFAULT_INNER_ATTR_FORBIDDEN };
88         self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
89     }
90
91     /// The same as `parse_attribute`, except it takes in an `InnerAttrPolicy`
92     /// that prescribes how to handle inner attributes.
93     fn parse_attribute_with_inner_parse_policy(
94         &mut self,
95         inner_parse_policy: InnerAttrPolicy<'_>,
96     ) -> PResult<'a, ast::Attribute> {
97         debug!(
98             "parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
99             inner_parse_policy, self.token
100         );
101         let lo = self.token.span;
102         let (span, item, style) = if self.eat(&token::Pound) {
103             let style =
104                 if self.eat(&token::Not) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer };
105
106             self.expect(&token::OpenDelim(token::Bracket))?;
107             let item = self.parse_attr_item()?;
108             self.expect(&token::CloseDelim(token::Bracket))?;
109             let attr_sp = lo.to(self.prev_token.span);
110
111             // Emit error if inner attribute is encountered and forbidden.
112             if style == ast::AttrStyle::Inner {
113                 self.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy);
114             }
115
116             (attr_sp, item, style)
117         } else {
118             let token_str = pprust::token_to_string(&self.token);
119             let msg = &format!("expected `#`, found `{}`", token_str);
120             return Err(self.struct_span_err(self.token.span, msg));
121         };
122
123         Ok(attr::mk_attr_from_item(style, item, span))
124     }
125
126     pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
127         if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_attr_sp } = policy {
128             let prev_attr_note =
129                 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
130
131             let mut diag = self.struct_span_err(attr_sp, reason);
132
133             if let Some(prev_attr_sp) = prev_attr_sp {
134                 diag.span_label(attr_sp, "not permitted following an outer attribute")
135                     .span_label(prev_attr_sp, prev_attr_note);
136             }
137
138             diag.note(
139                 "inner attributes, like `#![no_std]`, annotate the item enclosing them, \
140                 and are usually found at the beginning of source files. \
141                 Outer attributes, like `#[test]`, annotate the item following them.",
142             )
143             .emit();
144         }
145     }
146
147     /// Parses an inner part of an attribute (the path and following tokens).
148     /// The tokens must be either a delimited token stream, or empty token stream,
149     /// or the "legacy" key-value form.
150     ///     PATH `(` TOKEN_STREAM `)`
151     ///     PATH `[` TOKEN_STREAM `]`
152     ///     PATH `{` TOKEN_STREAM `}`
153     ///     PATH
154     ///     PATH `=` UNSUFFIXED_LIT
155     /// The delimiters or `=` are still put into the resulting token stream.
156     pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> {
157         let item = match self.token.kind {
158             token::Interpolated(ref nt) => match **nt {
159                 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
160                 _ => None,
161             },
162             _ => None,
163         };
164         Ok(if let Some(item) = item {
165             self.bump();
166             item
167         } else {
168             let path = self.parse_path(PathStyle::Mod)?;
169             let args = self.parse_attr_args()?;
170             ast::AttrItem { path, args }
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             // Only try to parse if it is an inner attribute (has `!`).
183             if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
184                 let attr = self.parse_attribute(true)?;
185                 assert_eq!(attr.style, ast::AttrStyle::Inner);
186                 attrs.push(attr);
187             } else if let token::DocComment(s) = self.token.kind {
188                 // We need to get the position of this token before we bump.
189                 let attr = self.mk_doc_comment(s);
190                 if attr.style == ast::AttrStyle::Inner {
191                     attrs.push(attr);
192                     self.bump();
193                 } else {
194                     break;
195                 }
196             } else {
197                 break;
198             }
199         }
200         Ok(attrs)
201     }
202
203     crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
204         let lit = self.parse_lit()?;
205         debug!("checking if {:?} is unusuffixed", lit);
206
207         if !lit.kind.is_unsuffixed() {
208             self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
209                 .help(
210                     "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
211                     use an unsuffixed version (`1`, `1.0`, etc.)",
212                 )
213                 .emit();
214         }
215
216         Ok(lit)
217     }
218
219     /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
220     pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
221         let cfg_predicate = self.parse_meta_item()?;
222         self.expect(&token::Comma)?;
223
224         // Presumably, the majority of the time there will only be one attr.
225         let mut expanded_attrs = Vec::with_capacity(1);
226         while self.token.kind != token::Eof {
227             let lo = self.token.span;
228             let item = self.parse_attr_item()?;
229             expanded_attrs.push((item, lo.to(self.prev_token.span)));
230             if !self.eat(&token::Comma) {
231                 break;
232             }
233         }
234
235         Ok((cfg_predicate, expanded_attrs))
236     }
237
238     /// Matches `COMMASEP(meta_item_inner)`.
239     crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
240         // Presumably, the majority of the time there will only be one attr.
241         let mut nmis = Vec::with_capacity(1);
242         while self.token.kind != token::Eof {
243             nmis.push(self.parse_meta_item_inner()?);
244             if !self.eat(&token::Comma) {
245                 break;
246             }
247         }
248         Ok(nmis)
249     }
250
251     /// Matches the following grammar (per RFC 1559).
252     ///
253     ///     meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
254     ///     meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
255     pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
256         let nt_meta = match self.token.kind {
257             token::Interpolated(ref nt) => match **nt {
258                 token::NtMeta(ref e) => Some(e.clone()),
259                 _ => None,
260             },
261             _ => None,
262         };
263
264         if let Some(item) = nt_meta {
265             return match item.meta(item.path.span) {
266                 Some(meta) => {
267                     self.bump();
268                     Ok(meta)
269                 }
270                 None => self.unexpected(),
271             };
272         }
273
274         let lo = self.token.span;
275         let path = self.parse_path(PathStyle::Mod)?;
276         let kind = self.parse_meta_item_kind()?;
277         let span = lo.to(self.prev_token.span);
278         Ok(ast::MetaItem { path, kind, span })
279     }
280
281     crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
282         Ok(if self.eat(&token::Eq) {
283             ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
284         } else if self.check(&token::OpenDelim(token::Paren)) {
285             // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
286             let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
287             ast::MetaItemKind::List(list)
288         } else {
289             ast::MetaItemKind::Word
290         })
291     }
292
293     /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
294     fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
295         match self.parse_unsuffixed_lit() {
296             Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
297             Err(ref mut err) => err.cancel(),
298         }
299
300         match self.parse_meta_item() {
301             Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
302             Err(ref mut err) => err.cancel(),
303         }
304
305         let found = pprust::token_to_string(&self.token);
306         let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
307         Err(self.struct_span_err(self.token.span, &msg))
308     }
309 }