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