1 use super::{Parser, PathStyle, TokenType};
2 use rustc_errors::PResult;
5 use syntax::print::pprust;
6 use syntax::token::{self, Nonterminal};
7 use syntax::util::comments;
8 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 = InnerAttributeParsePolicy::NotPermitted {
38 reason: inner_error_reason,
39 saw_doc_comment: just_parsed_doc_comment,
40 prev_attr_sp: attrs.last().and_then(|a| Some(a.span)),
42 let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?;
44 just_parsed_doc_comment = false;
46 token::DocComment(s) => {
47 let attr = self.mk_doc_comment(s);
48 if attr.style != ast::AttrStyle::Outer {
49 let mut err = self.fatal("expected outer doc comment");
51 "inner doc comments like this (starting with \
52 `//!` or `/*!`) can only appear before items",
58 just_parsed_doc_comment = true;
66 fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
67 let style = comments::doc_comment_style(&s.as_str());
68 attr::mk_doc_comment(style, s, self.token.span)
71 /// Matches `attribute = # ! [ meta_item ]`.
73 /// If `permit_inner` is `true`, then a leading `!` indicates an inner
75 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
76 debug!("parse_attribute: permit_inner={:?} self.token={:?}", permit_inner, self.token);
77 let inner_parse_policy = if permit_inner {
78 InnerAttributeParsePolicy::Permitted
80 InnerAttributeParsePolicy::NotPermitted {
81 reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG,
82 saw_doc_comment: false,
86 self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
89 /// The same as `parse_attribute`, except it takes in an `InnerAttributeParsePolicy`
90 /// that prescribes how to handle inner attributes.
91 fn parse_attribute_with_inner_parse_policy(
93 inner_parse_policy: InnerAttributeParsePolicy<'_>,
94 ) -> PResult<'a, ast::Attribute> {
96 "parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
97 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 {
128 } = inner_parse_policy
130 let prev_attr_note = if saw_doc_comment {
131 "previous doc comment"
133 "previous outer attribute"
136 let mut diagnostic = self.struct_span_err(attr_sp, reason);
138 if let Some(prev_attr_sp) = prev_attr_sp {
140 .span_label(attr_sp, "not permitted following an outer attibute")
141 .span_label(prev_attr_sp, prev_attr_note);
146 "inner attributes, like `#![no_std]`, annotate the item \
147 enclosing them, and are usually found at the beginning of \
148 source files. Outer attributes, like `#[test]`, annotate the \
149 item following them.",
155 (attr_sp, item, style)
158 let token_str = pprust::token_to_string(&self.token);
159 return Err(self.fatal(&format!("expected `#`, found `{}`", token_str)));
163 Ok(attr::mk_attr_from_item(style, item, span))
166 /// Parses an inner part of an attribute (the path and following tokens).
167 /// The tokens must be either a delimited token stream, or empty token stream,
168 /// or the "legacy" key-value form.
169 /// PATH `(` TOKEN_STREAM `)`
170 /// PATH `[` TOKEN_STREAM `]`
171 /// PATH `{` TOKEN_STREAM `}`
173 /// PATH `=` UNSUFFIXED_LIT
174 /// The delimiters or `=` are still put into the resulting token stream.
175 pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> {
176 let item = match self.token.kind {
177 token::Interpolated(ref nt) => match **nt {
178 Nonterminal::NtMeta(ref item) => Some(item.clone()),
183 Ok(if let Some(item) = item {
187 let path = self.parse_path(PathStyle::Mod)?;
188 let args = self.parse_attr_args()?;
189 ast::AttrItem { path, args }
193 /// Parses attributes that appear after the opening of an item. These should
194 /// be preceded by an exclamation mark, but we accept and warn about one
195 /// terminated by a semicolon.
197 /// Matches `inner_attrs*`.
198 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
199 let mut attrs: Vec<ast::Attribute> = vec![];
201 match self.token.kind {
203 // Don't even try to parse if it's not an inner attribute.
204 if !self.look_ahead(1, |t| t == &token::Not) {
208 let attr = self.parse_attribute(true)?;
209 assert_eq!(attr.style, ast::AttrStyle::Inner);
212 token::DocComment(s) => {
213 // We need to get the position of this token before we bump.
214 let attr = self.mk_doc_comment(s);
215 if attr.style == ast::AttrStyle::Inner {
228 crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
229 let lit = self.parse_lit()?;
230 debug!("checking if {:?} is unusuffixed", lit);
232 if !lit.kind.is_unsuffixed() {
233 let msg = "suffixed literals are not allowed in attributes";
234 self.struct_span_err(lit.span, msg)
236 "instead of using a suffixed literal \
237 (1u8, 1.0f32, etc.), use an unsuffixed version \
246 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
247 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
248 let cfg_predicate = self.parse_meta_item()?;
249 self.expect(&token::Comma)?;
251 // Presumably, the majority of the time there will only be one attr.
252 let mut expanded_attrs = Vec::with_capacity(1);
253 while self.token.kind != token::Eof {
254 let lo = self.token.span;
255 let item = self.parse_attr_item()?;
256 expanded_attrs.push((item, lo.to(self.prev_span)));
257 if !self.eat(&token::Comma) {
262 Ok((cfg_predicate, expanded_attrs))
265 /// Matches `COMMASEP(meta_item_inner)`.
266 crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
267 // Presumably, the majority of the time there will only be one attr.
268 let mut nmis = Vec::with_capacity(1);
269 while self.token.kind != token::Eof {
270 nmis.push(self.parse_meta_item_inner()?);
271 if !self.eat(&token::Comma) {
278 /// Matches the following grammar (per RFC 1559).
280 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
281 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
282 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
283 let nt_meta = match self.token.kind {
284 token::Interpolated(ref nt) => match **nt {
285 token::NtMeta(ref e) => Some(e.clone()),
291 if let Some(item) = nt_meta {
292 return match item.meta(item.path.span) {
297 None => self.unexpected(),
301 let lo = self.token.span;
302 let path = self.parse_path(PathStyle::Mod)?;
303 let kind = self.parse_meta_item_kind()?;
304 let span = lo.to(self.prev_span);
305 Ok(ast::MetaItem { path, kind, span })
308 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
309 Ok(if self.eat(&token::Eq) {
310 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
311 } else if self.check(&token::OpenDelim(token::Paren)) {
312 // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
313 let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
314 ast::MetaItemKind::List(list)
316 ast::MetaItemKind::Word
320 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
321 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
322 match self.parse_unsuffixed_lit() {
323 Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
324 Err(ref mut err) => err.cancel(),
327 match self.parse_meta_item() {
328 Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
329 Err(ref mut err) => err.cancel(),
332 let found = pprust::token_to_string(&self.token);
333 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
334 Err(self.struct_span_err(self.token.span, &msg))