1 use super::{SeqSep, Parser, TokenType, PathStyle};
2 use rustc_errors::PResult;
5 use syntax::util::comments;
6 use syntax::token::{self, Nonterminal};
7 use syntax_pos::{Span, Symbol};
12 enum InnerAttributeParsePolicy<'a> {
14 NotPermitted { reason: &'a str, saw_doc_comment: bool, prev_attr_sp: Option<Span> },
17 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
18 permitted in this context";
21 /// Parses attributes that appear before an item.
22 pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
23 let mut attrs: Vec<ast::Attribute> = Vec::new();
24 let mut just_parsed_doc_comment = false;
26 debug!("parse_outer_attributes: self.token={:?}", self.token);
27 match self.token.kind {
29 let inner_error_reason = if just_parsed_doc_comment {
30 "an inner attribute is not permitted following an outer doc comment"
31 } else if !attrs.is_empty() {
32 "an inner attribute is not permitted following an outer attribute"
34 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
36 let inner_parse_policy =
37 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");
50 err.note("inner doc comments like this (starting with \
51 `//!` or `/*!`) can only appear before items");
56 just_parsed_doc_comment = true;
64 fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
65 let style = comments::doc_comment_style(&s.as_str());
66 attr::mk_doc_comment(style, s, self.token.span)
69 /// Matches `attribute = # ! [ meta_item ]`.
71 /// If `permit_inner` is `true`, then a leading `!` indicates an inner
73 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
74 debug!("parse_attribute: 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> {
95 debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
98 let (span, item, style) = match self.token.kind {
100 let lo = self.token.span;
103 if let InnerAttributeParsePolicy::Permitted = inner_parse_policy {
104 self.expected_tokens.push(TokenType::Token(token::Not));
107 let style = if self.token == token::Not {
109 ast::AttrStyle::Inner
111 ast::AttrStyle::Outer
114 self.expect(&token::OpenDelim(token::Bracket))?;
115 let item = self.parse_attr_item()?;
116 self.expect(&token::CloseDelim(token::Bracket))?;
117 let hi = self.prev_span;
119 let attr_sp = lo.to(hi);
121 // Emit error if inner attribute is encountered and not permitted
122 if style == ast::AttrStyle::Inner {
123 if let InnerAttributeParsePolicy::NotPermitted { reason,
124 saw_doc_comment, prev_attr_sp } = inner_parse_policy {
125 let prev_attr_note = if saw_doc_comment {
126 "previous doc comment"
128 "previous outer attribute"
131 let mut diagnostic = self
133 .struct_span_err(attr_sp, reason);
135 if let Some(prev_attr_sp) = prev_attr_sp {
137 .span_label(attr_sp, "not permitted following an outer attibute")
138 .span_label(prev_attr_sp, prev_attr_note);
142 .note("inner attributes, like `#![no_std]`, annotate the item \
143 enclosing them, and are usually found at the beginning of \
144 source files. Outer attributes, like `#[test]`, annotate the \
145 item following them.")
150 (attr_sp, item, style)
153 let token_str = self.this_token_to_string();
154 return Err(self.fatal(&format!("expected `#`, found `{}`", token_str)));
158 Ok(attr::mk_attr_from_item(style, item, span))
161 /// Parses an inner part of an attribute (the path and following tokens).
162 /// The tokens must be either a delimited token stream, or empty token stream,
163 /// or the "legacy" key-value form.
164 /// PATH `(` TOKEN_STREAM `)`
165 /// PATH `[` TOKEN_STREAM `]`
166 /// PATH `{` TOKEN_STREAM `}`
168 /// PATH `=` UNSUFFIXED_LIT
169 /// The delimiters or `=` are still put into the resulting token stream.
170 pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> {
171 let item = match self.token.kind {
172 token::Interpolated(ref nt) => match **nt {
173 Nonterminal::NtMeta(ref item) => Some(item.clone()),
178 Ok(if let Some(item) = item {
182 let path = self.parse_path(PathStyle::Mod)?;
183 let args = self.parse_attr_args()?;
184 ast::AttrItem { path, args }
188 /// Parses attributes that appear after the opening of an item. These should
189 /// be preceded by an exclamation mark, but we accept and warn about one
190 /// terminated by a semicolon.
192 /// Matches `inner_attrs*`.
193 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
194 let mut attrs: Vec<ast::Attribute> = vec![];
196 match self.token.kind {
198 // Don't even try to parse if it's not an inner attribute.
199 if !self.look_ahead(1, |t| t == &token::Not) {
203 let attr = self.parse_attribute(true)?;
204 assert_eq!(attr.style, ast::AttrStyle::Inner);
207 token::DocComment(s) => {
208 // We need to get the position of this token before we bump.
209 let attr = self.mk_doc_comment(s);
210 if attr.style == ast::AttrStyle::Inner {
223 pub(super) fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
224 let lit = self.parse_lit()?;
225 debug!("checking if {:?} is unusuffixed", lit);
227 if !lit.kind.is_unsuffixed() {
228 let msg = "suffixed literals are not allowed in attributes";
229 self.diagnostic().struct_span_err(lit.span, msg)
230 .help("instead of using a suffixed literal \
231 (1u8, 1.0f32, etc.), use an unsuffixed version \
239 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
240 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
241 self.expect(&token::OpenDelim(token::Paren))?;
243 let cfg_predicate = self.parse_meta_item()?;
244 self.expect(&token::Comma)?;
246 // Presumably, the majority of the time there will only be one attr.
247 let mut expanded_attrs = Vec::with_capacity(1);
249 while !self.check(&token::CloseDelim(token::Paren)) {
250 let lo = self.token.span.lo();
251 let item = self.parse_attr_item()?;
252 expanded_attrs.push((item, self.prev_span.with_lo(lo)));
253 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Paren)])?;
256 self.expect(&token::CloseDelim(token::Paren))?;
257 Ok((cfg_predicate, expanded_attrs))
260 /// Matches the following grammar (per RFC 1559).
262 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
263 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
264 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
265 let nt_meta = match self.token.kind {
266 token::Interpolated(ref nt) => match **nt {
267 token::NtMeta(ref e) => Some(e.clone()),
273 if let Some(item) = nt_meta {
274 return match item.meta(item.path.span) {
279 None => self.unexpected(),
283 let lo = self.token.span;
284 let path = self.parse_path(PathStyle::Mod)?;
285 let kind = self.parse_meta_item_kind()?;
286 let span = lo.to(self.prev_span);
287 Ok(ast::MetaItem { path, kind, span })
290 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
291 Ok(if self.eat(&token::Eq) {
292 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
293 } else if self.eat(&token::OpenDelim(token::Paren)) {
294 ast::MetaItemKind::List(self.parse_meta_seq()?)
296 ast::MetaItemKind::Word
300 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
301 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
302 match self.parse_unsuffixed_lit() {
304 return Ok(ast::NestedMetaItem::Literal(lit))
306 Err(ref mut err) => err.cancel(),
309 match self.parse_meta_item() {
311 return Ok(ast::NestedMetaItem::MetaItem(mi))
313 Err(ref mut err) => err.cancel(),
316 let found = self.this_token_to_string();
317 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
318 Err(self.diagnostic().struct_span_err(self.token.span, &msg))
321 /// Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
322 fn parse_meta_seq(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
323 self.parse_seq_to_end(&token::CloseDelim(token::Paren),
324 SeqSep::trailing_allowed(token::Comma),
325 |p: &mut Parser<'a>| p.parse_meta_item_inner())