1 use super::{Parser, PathStyle, TokenType};
4 use rustc_ast::token::{self, Nonterminal};
5 use rustc_ast::util::comments;
6 use rustc_ast_pretty::pprust;
7 use rustc_errors::PResult;
8 use rustc_span::{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 span = self.token.span;
50 let mut err = self.struct_span_err(span, "expected outer doc comment");
52 "inner doc comments like this (starting with \
53 `//!` or `/*!`) can only appear before items",
59 just_parsed_doc_comment = true;
67 fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
68 let style = comments::doc_comment_style(&s.as_str());
69 attr::mk_doc_comment(style, s, self.token.span)
72 /// Matches `attribute = # ! [ meta_item ]`.
74 /// If `permit_inner` is `true`, then a leading `!` indicates an inner
76 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
77 debug!("parse_attribute: permit_inner={:?} self.token={:?}", 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> {
97 "parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
98 inner_parse_policy, self.token
100 let (span, item, style) = match self.token.kind {
102 let lo = self.token.span;
105 if let InnerAttributeParsePolicy::Permitted = inner_parse_policy {
106 self.expected_tokens.push(TokenType::Token(token::Not));
109 let style = if self.token == token::Not {
111 ast::AttrStyle::Inner
113 ast::AttrStyle::Outer
116 self.expect(&token::OpenDelim(token::Bracket))?;
117 let item = self.parse_attr_item()?;
118 self.expect(&token::CloseDelim(token::Bracket))?;
119 let hi = self.prev_span;
121 let attr_sp = lo.to(hi);
123 // Emit error if inner attribute is encountered and not permitted
124 if style == ast::AttrStyle::Inner {
125 if let InnerAttributeParsePolicy::NotPermitted {
129 } = inner_parse_policy
131 let prev_attr_note = if saw_doc_comment {
132 "previous doc comment"
134 "previous outer attribute"
137 let mut diagnostic = self.struct_span_err(attr_sp, reason);
139 if let Some(prev_attr_sp) = prev_attr_sp {
141 .span_label(attr_sp, "not permitted following an outer attibute")
142 .span_label(prev_attr_sp, prev_attr_note);
147 "inner attributes, like `#![no_std]`, annotate the item \
148 enclosing them, and are usually found at the beginning of \
149 source files. Outer attributes, like `#[test]`, annotate the \
150 item following them.",
156 (attr_sp, item, style)
159 let token_str = pprust::token_to_string(&self.token);
160 let msg = &format!("expected `#`, found `{}`", token_str);
161 return Err(self.struct_span_err(self.token.span, msg));
165 Ok(attr::mk_attr_from_item(style, item, span))
168 /// Parses an inner part of an attribute (the path and following tokens).
169 /// The tokens must be either a delimited token stream, or empty token stream,
170 /// or the "legacy" key-value form.
171 /// PATH `(` TOKEN_STREAM `)`
172 /// PATH `[` TOKEN_STREAM `]`
173 /// PATH `{` TOKEN_STREAM `}`
175 /// PATH `=` UNSUFFIXED_LIT
176 /// The delimiters or `=` are still put into the resulting token stream.
177 pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> {
178 let item = match self.token.kind {
179 token::Interpolated(ref nt) => match **nt {
180 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
185 Ok(if let Some(item) = item {
189 let path = self.parse_path(PathStyle::Mod)?;
190 let args = self.parse_attr_args()?;
191 ast::AttrItem { path, args }
195 /// Parses attributes that appear after the opening of an item. These should
196 /// be preceded by an exclamation mark, but we accept and warn about one
197 /// terminated by a semicolon.
199 /// Matches `inner_attrs*`.
200 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
201 let mut attrs: Vec<ast::Attribute> = vec![];
203 match self.token.kind {
205 // Don't even try to parse if it's not an inner attribute.
206 if !self.look_ahead(1, |t| t == &token::Not) {
210 let attr = self.parse_attribute(true)?;
211 assert_eq!(attr.style, ast::AttrStyle::Inner);
214 token::DocComment(s) => {
215 // We need to get the position of this token before we bump.
216 let attr = self.mk_doc_comment(s);
217 if attr.style == ast::AttrStyle::Inner {
230 crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
231 let lit = self.parse_lit()?;
232 debug!("checking if {:?} is unusuffixed", lit);
234 if !lit.kind.is_unsuffixed() {
235 let msg = "suffixed literals are not allowed in attributes";
236 self.struct_span_err(lit.span, msg)
238 "instead of using a suffixed literal \
239 (`1u8`, `1.0f32`, etc.), use an unsuffixed version \
248 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
249 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
250 let cfg_predicate = self.parse_meta_item()?;
251 self.expect(&token::Comma)?;
253 // Presumably, the majority of the time there will only be one attr.
254 let mut expanded_attrs = Vec::with_capacity(1);
255 while self.token.kind != token::Eof {
256 let lo = self.token.span;
257 let item = self.parse_attr_item()?;
258 expanded_attrs.push((item, lo.to(self.prev_span)));
259 if !self.eat(&token::Comma) {
264 Ok((cfg_predicate, expanded_attrs))
267 /// Matches `COMMASEP(meta_item_inner)`.
268 crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
269 // Presumably, the majority of the time there will only be one attr.
270 let mut nmis = Vec::with_capacity(1);
271 while self.token.kind != token::Eof {
272 nmis.push(self.parse_meta_item_inner()?);
273 if !self.eat(&token::Comma) {
280 /// Matches the following grammar (per RFC 1559).
282 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
283 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
284 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
285 let nt_meta = match self.token.kind {
286 token::Interpolated(ref nt) => match **nt {
287 token::NtMeta(ref e) => Some(e.clone()),
293 if let Some(item) = nt_meta {
294 return match item.meta(item.path.span) {
299 None => self.unexpected(),
303 let lo = self.token.span;
304 let path = self.parse_path(PathStyle::Mod)?;
305 let kind = self.parse_meta_item_kind()?;
306 let span = lo.to(self.prev_span);
307 Ok(ast::MetaItem { path, kind, span })
310 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
311 Ok(if self.eat(&token::Eq) {
312 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
313 } else if self.check(&token::OpenDelim(token::Paren)) {
314 // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
315 let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
316 ast::MetaItemKind::List(list)
318 ast::MetaItemKind::Word
322 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
323 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
324 match self.parse_unsuffixed_lit() {
325 Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
326 Err(ref mut err) => err.cancel(),
329 match self.parse_meta_item() {
330 Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
331 Err(ref mut err) => err.cancel(),
334 let found = pprust::token_to_string(&self.token);
335 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
336 Err(self.struct_span_err(self.token.span, &msg))