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