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 syntax_pos::{mk_sp, Span};
14 use codemap::{spanned, Spanned};
15 use parse::common::SeqSep;
18 use parse::parser::{Parser, TokenType};
21 #[derive(PartialEq, Eq, Debug)]
22 enum InnerAttributeParsePolicy<'a> {
24 NotPermitted { reason: &'a str },
27 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &'static str = "an inner attribute is not \
28 permitted in this context";
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;
36 debug!("parse_outer_attributes: self.token={:?}", self.token);
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"
44 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
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;
51 token::DocComment(s) => {
52 let attr = ::attr::mk_sugared_doc_attr(
54 self.id_to_interned_str(ast::Ident::with_empty_ctxt(s)),
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");
66 just_parsed_doc_comment = true;
74 /// Matches `attribute = # ! [ meta_item ]`
76 /// If permit_inner is true, then a leading `!` indicates an inner
78 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
79 debug!("parse_attribute: permit_inner={:?} self.token={:?}",
82 let inner_parse_policy = if permit_inner {
83 InnerAttributeParsePolicy::Permitted
85 InnerAttributeParsePolicy::NotPermitted
86 { reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG }
88 self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
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={:?}",
99 let (span, value, mut style) = match self.token {
101 let lo = self.span.lo;
104 if inner_parse_policy == InnerAttributeParsePolicy::Permitted {
105 self.expected_tokens.push(TokenType::Token(token::Not));
107 let style = if self.token == token::Not {
109 if let InnerAttributeParsePolicy::NotPermitted { reason } = inner_parse_policy
111 let span = self.span;
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.")
121 ast::AttrStyle::Inner
123 ast::AttrStyle::Outer
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))?;
131 (mk_sp(lo, hi), meta_item, style)
134 let token_str = self.this_token_to_string();
135 return Err(self.fatal(&format!("expected `#`, found `{}`", token_str)));
139 if inner_parse_policy == InnerAttributeParsePolicy::Permitted &&
140 self.token == token::Semi {
143 "this inner attribute syntax is deprecated. The new syntax is \
144 `#![foo]`, with a bang and no semicolon");
145 style = ast::AttrStyle::Inner;
150 node: ast::Attribute_ {
151 id: attr::mk_attr_id(),
154 is_sugared_doc: false,
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.
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![];
169 // Don't even try to parse if it's not an inner attribute.
170 if !self.look_ahead(1, |t| t == &token::Not) {
174 let attr = self.parse_attribute(true)?;
175 assert!(attr.node.style == ast::AttrStyle::Inner);
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 {
196 fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
197 let lit = self.parse_lit()?;
198 debug!("Checking if {:?} is unusuffixed.", lit);
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 \
212 /// Per RFC#1559, matches the following grammar:
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()),
222 if let Some(meta) = nt_meta {
227 let lo = self.span.lo;
228 let ident = self.parse_ident()?;
229 let name = self.id_to_interned_str(ident);
233 let lit = self.parse_unsuffixed_lit()?;
234 let hi = self.span.hi;
235 Ok(P(spanned(lo, hi, ast::MetaItemKind::NameValue(name, lit))))
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))))
243 let hi = self.last_span.hi;
244 Ok(P(spanned(lo, hi, ast::MetaItemKind::Word(name))))
249 /// matches meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;
250 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
252 let lo = self.span.lo;
254 match self.parse_unsuffixed_lit() {
256 return Ok(spanned(lo, self.span.hi, ast::NestedMetaItemKind::Literal(lit)))
258 Err(ref mut err) => self.diagnostic().cancel(err)
261 match self.parse_meta_item() {
263 return Ok(spanned(lo, self.span.hi, ast::NestedMetaItemKind::MetaItem(mi)))
265 Err(ref mut err) => self.diagnostic().cancel(err)
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))
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())