1 use super::{SeqSep, Parser, TokenType, PathStyle};
4 use syntax::util::comments;
5 use syntax::token::{self, Nonterminal, DelimToken};
6 use syntax::tokenstream::{TokenStream, TokenTree};
7 use syntax_pos::{Span, Symbol};
13 enum InnerAttributeParsePolicy<'a> {
15 NotPermitted { reason: &'a str, saw_doc_comment: bool, prev_attr_sp: Option<Span> },
18 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
19 permitted in this context";
22 /// Parses attributes that appear before an item.
23 pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
24 let mut attrs: Vec<ast::Attribute> = Vec::new();
25 let mut just_parsed_doc_comment = false;
27 debug!("parse_outer_attributes: self.token={:?}", self.token);
28 match self.token.kind {
30 let inner_error_reason = if just_parsed_doc_comment {
31 "an inner attribute is not permitted following an outer doc comment"
32 } else if !attrs.is_empty() {
33 "an inner attribute is not permitted following an outer attribute"
35 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
37 let inner_parse_policy =
38 InnerAttributeParsePolicy::NotPermitted {
39 reason: inner_error_reason,
40 saw_doc_comment: just_parsed_doc_comment,
41 prev_attr_sp: attrs.last().and_then(|a| Some(a.span))
43 let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?;
45 just_parsed_doc_comment = false;
47 token::DocComment(s) => {
48 let attr = self.mk_doc_comment(s);
49 if attr.style != ast::AttrStyle::Outer {
50 let mut err = self.fatal("expected outer doc comment");
51 err.note("inner doc comments like this (starting with \
52 `//!` or `/*!`) can only appear before items");
57 just_parsed_doc_comment = true;
65 fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
66 let style = comments::doc_comment_style(&s.as_str());
67 attr::mk_doc_comment(style, s, self.token.span)
70 /// Matches `attribute = # ! [ meta_item ]`.
72 /// If `permit_inner` is `true`, then a leading `!` indicates an inner
74 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
75 debug!("parse_attribute: permit_inner={:?} self.token={:?}",
78 let inner_parse_policy = if permit_inner {
79 InnerAttributeParsePolicy::Permitted
81 InnerAttributeParsePolicy::NotPermitted {
82 reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG,
83 saw_doc_comment: false,
87 self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
90 /// The same as `parse_attribute`, except it takes in an `InnerAttributeParsePolicy`
91 /// that prescribes how to handle inner attributes.
92 fn parse_attribute_with_inner_parse_policy(
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, item, style) = match self.token.kind {
101 let lo = self.token.span;
104 if let InnerAttributeParsePolicy::Permitted = inner_parse_policy {
105 self.expected_tokens.push(TokenType::Token(token::Not));
108 let style = if self.token == token::Not {
110 ast::AttrStyle::Inner
112 ast::AttrStyle::Outer
115 self.expect(&token::OpenDelim(token::Bracket))?;
116 let item = self.parse_attr_item()?;
117 self.expect(&token::CloseDelim(token::Bracket))?;
118 let hi = self.prev_span;
120 let attr_sp = lo.to(hi);
122 // Emit error if inner attribute is encountered and not permitted
123 if style == ast::AttrStyle::Inner {
124 if let InnerAttributeParsePolicy::NotPermitted { reason,
125 saw_doc_comment, prev_attr_sp } = inner_parse_policy {
126 let prev_attr_note = if saw_doc_comment {
127 "previous doc comment"
129 "previous outer attribute"
132 let mut diagnostic = self
134 .struct_span_err(attr_sp, reason);
136 if let Some(prev_attr_sp) = prev_attr_sp {
138 .span_label(attr_sp, "not permitted following an outer attibute")
139 .span_label(prev_attr_sp, prev_attr_note);
143 .note("inner attributes, like `#![no_std]`, annotate the item \
144 enclosing them, and are usually found at the beginning of \
145 source files. Outer attributes, like `#[test]`, annotate the \
146 item following them.")
151 (attr_sp, item, style)
154 let token_str = self.this_token_to_string();
155 return Err(self.fatal(&format!("expected `#`, found `{}`", token_str)));
159 Ok(attr::mk_attr_from_item(style, item, span))
162 /// Parses an inner part of an attribute (the path and following tokens).
163 /// The tokens must be either a delimited token stream, or empty token stream,
164 /// or the "legacy" key-value form.
165 /// PATH `(` TOKEN_STREAM `)`
166 /// PATH `[` TOKEN_STREAM `]`
167 /// PATH `{` TOKEN_STREAM `}`
169 /// PATH `=` UNSUFFIXED_LIT
170 /// The delimiters or `=` are still put into the resulting token stream.
171 pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> {
172 let item = match self.token.kind {
173 token::Interpolated(ref nt) => match **nt {
174 Nonterminal::NtMeta(ref item) => Some(item.clone()),
179 Ok(if let Some(item) = item {
183 let path = self.parse_path(PathStyle::Mod)?;
184 let tokens = if self.check(&token::OpenDelim(DelimToken::Paren)) ||
185 self.check(&token::OpenDelim(DelimToken::Bracket)) ||
186 self.check(&token::OpenDelim(DelimToken::Brace)) {
187 self.parse_token_tree().into()
188 } else if self.eat(&token::Eq) {
189 let eq = TokenTree::token(token::Eq, self.prev_span);
190 let mut is_interpolated_expr = false;
191 if let token::Interpolated(nt) = &self.token.kind {
192 if let token::NtExpr(..) = **nt {
193 is_interpolated_expr = true;
196 let token_tree = if is_interpolated_expr {
197 // We need to accept arbitrary interpolated expressions to continue
198 // supporting things like `doc = $expr` that work on stable.
199 // Non-literal interpolated expressions are rejected after expansion.
200 self.parse_token_tree()
202 self.parse_unsuffixed_lit()?.token_tree()
204 TokenStream::new(vec![eq.into(), token_tree.into()])
206 TokenStream::default()
208 ast::AttrItem { path, tokens }
212 /// Parses attributes that appear after the opening of an item. These should
213 /// be preceded by an exclamation mark, but we accept and warn about one
214 /// terminated by a semicolon.
216 /// Matches `inner_attrs*`.
217 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
218 let mut attrs: Vec<ast::Attribute> = vec![];
220 match self.token.kind {
222 // Don't even try to parse if it's not an inner attribute.
223 if !self.look_ahead(1, |t| t == &token::Not) {
227 let attr = self.parse_attribute(true)?;
228 assert_eq!(attr.style, ast::AttrStyle::Inner);
231 token::DocComment(s) => {
232 // We need to get the position of this token before we bump.
233 let attr = self.mk_doc_comment(s);
234 if attr.style == ast::AttrStyle::Inner {
247 pub(super) fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
248 let lit = self.parse_lit()?;
249 debug!("checking if {:?} is unusuffixed", lit);
251 if !lit.kind.is_unsuffixed() {
252 let msg = "suffixed literals are not allowed in attributes";
253 self.diagnostic().struct_span_err(lit.span, msg)
254 .help("instead of using a suffixed literal \
255 (1u8, 1.0f32, etc.), use an unsuffixed version \
263 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
264 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
265 self.expect(&token::OpenDelim(token::Paren))?;
267 let cfg_predicate = self.parse_meta_item()?;
268 self.expect(&token::Comma)?;
270 // Presumably, the majority of the time there will only be one attr.
271 let mut expanded_attrs = Vec::with_capacity(1);
273 while !self.check(&token::CloseDelim(token::Paren)) {
274 let lo = self.token.span.lo();
275 let item = self.parse_attr_item()?;
276 expanded_attrs.push((item, self.prev_span.with_lo(lo)));
277 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Paren)])?;
280 self.expect(&token::CloseDelim(token::Paren))?;
281 Ok((cfg_predicate, expanded_attrs))
284 /// Matches the following grammar (per RFC 1559).
286 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
287 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
288 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
289 let nt_meta = match self.token.kind {
290 token::Interpolated(ref nt) => match **nt {
291 token::NtMeta(ref e) => Some(e.clone()),
297 if let Some(item) = nt_meta {
298 return match item.meta(item.path.span) {
303 None => self.unexpected(),
307 let lo = self.token.span;
308 let path = self.parse_path(PathStyle::Mod)?;
309 let kind = self.parse_meta_item_kind()?;
310 let span = lo.to(self.prev_span);
311 Ok(ast::MetaItem { path, kind, span })
314 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
315 Ok(if self.eat(&token::Eq) {
316 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
317 } else if self.eat(&token::OpenDelim(token::Paren)) {
318 ast::MetaItemKind::List(self.parse_meta_seq()?)
320 ast::MetaItemKind::Word
324 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
325 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
326 match self.parse_unsuffixed_lit() {
328 return Ok(ast::NestedMetaItem::Literal(lit))
330 Err(ref mut err) => err.cancel(),
333 match self.parse_meta_item() {
335 return Ok(ast::NestedMetaItem::MetaItem(mi))
337 Err(ref mut err) => err.cancel(),
340 let found = self.this_token_to_string();
341 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
342 Err(self.diagnostic().struct_span_err(self.token.span, &msg))
345 /// Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
346 fn parse_meta_seq(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
347 self.parse_seq_to_end(&token::CloseDelim(token::Paren),
348 SeqSep::trailing_allowed(token::Comma),
349 |p: &mut Parser<'a>| p.parse_meta_item_inner())