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