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