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