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.
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.
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};
20 enum InnerAttributeParsePolicy<'a> {
22 NotPermitted { reason: &'a str },
25 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
26 permitted in this context";
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;
34 debug!("parse_outer_attributes: self.token={:?}", self.token);
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"
42 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
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;
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");
59 just_parsed_doc_comment = true;
67 /// Matches `attribute = # ! [ meta_item ]`
69 /// If permit_inner is true, then a leading `!` indicates an inner
71 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
72 debug!("parse_attribute: permit_inner={:?} self.token={:?}",
75 let inner_parse_policy = if permit_inner {
76 InnerAttributeParsePolicy::Permitted
78 InnerAttributeParsePolicy::NotPermitted
79 { reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG }
81 self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
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={:?}",
92 let (span, path, tokens, style) = match self.token {
97 if let InnerAttributeParsePolicy::Permitted = inner_parse_policy {
98 self.expected_tokens.push(TokenType::Token(token::Not));
100 let style = if self.token == token::Not {
102 if let InnerAttributeParsePolicy::NotPermitted { reason } = inner_parse_policy
104 let span = self.span;
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.")
113 ast::AttrStyle::Inner
115 ast::AttrStyle::Outer
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;
123 (lo.to(hi), path, tokens, style)
126 let token_str = self.this_token_to_string();
127 return Err(self.fatal(&format!("expected `#`, found `{}`", token_str)));
132 id: attr::mk_attr_id(),
136 is_sugared_doc: false,
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 `}`
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()),
158 Ok(if let Some(meta) = meta {
160 (meta.ident, meta.node.tokens(meta.span))
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(),
173 TokenStream::concat(vec![eq.into(), tree.into()])
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.
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![];
191 // Don't even try to parse if it's not an inner attribute.
192 if !self.look_ahead(1, |t| t == &token::Not) {
196 let attr = self.parse_attribute(true)?;
197 assert_eq!(attr.style, ast::AttrStyle::Inner);
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 {
216 fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
217 let lit = self.parse_lit()?;
218 debug!("Checking if {:?} is unusuffixed.", lit);
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 \
232 /// Per RFC#1559, matches the following grammar:
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()),
245 if let Some(meta) = nt_meta {
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 })
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()?)
263 ast::MetaItemKind::Word
267 /// matches meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;
268 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
271 match self.parse_unsuffixed_lit() {
273 return Ok(respan(lo.to(self.prev_span), ast::NestedMetaItemKind::Literal(lit)))
275 Err(ref mut err) => self.diagnostic().cancel(err)
278 match self.parse_meta_item() {
280 return Ok(respan(lo.to(self.prev_span), ast::NestedMetaItemKind::MetaItem(mi)))
282 Err(ref mut err) => self.diagnostic().cancel(err)
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))
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())