1 use super::{Parser, PathStyle};
4 use rustc_ast::token::{self, Nonterminal};
5 use rustc_ast_pretty::pprust;
6 use rustc_errors::{error_code, PResult};
7 use rustc_span::{sym, Span};
11 // Public for rustfmt usage
13 pub enum InnerAttrPolicy<'a> {
15 Forbidden { 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";
21 pub(super) const DEFAULT_INNER_ATTR_FORBIDDEN: InnerAttrPolicy<'_> = InnerAttrPolicy::Forbidden {
22 reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG,
23 saw_doc_comment: false,
28 /// Parses attributes that appear before an item.
29 pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
30 let mut attrs: Vec<ast::Attribute> = Vec::new();
31 let mut just_parsed_doc_comment = false;
33 debug!("parse_outer_attributes: self.token={:?}", self.token);
34 let attr = if self.check(&token::Pound) {
35 let inner_error_reason = if just_parsed_doc_comment {
36 "an inner attribute is not permitted following an outer doc comment"
37 } else if !attrs.is_empty() {
38 "an inner attribute is not permitted following an outer attribute"
40 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
42 let inner_parse_policy = InnerAttrPolicy::Forbidden {
43 reason: inner_error_reason,
44 saw_doc_comment: just_parsed_doc_comment,
45 prev_attr_sp: attrs.last().map(|a| a.span),
47 just_parsed_doc_comment = false;
48 Some(self.parse_attribute(inner_parse_policy)?)
49 } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
50 if attr_style != ast::AttrStyle::Outer {
53 .struct_span_err_with_code(
55 "expected outer doc comment",
59 "inner doc comments like this (starting with \
60 `//!` or `/*!`) can only appear before items",
65 just_parsed_doc_comment = true;
66 Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
71 if let Some(attr) = attr {
80 /// Matches `attribute = # ! [ meta_item ]`.
81 /// `inner_parse_policy` prescribes how to handle inner attributes.
82 // Public for rustfmt usage.
83 pub fn parse_attribute(
85 inner_parse_policy: InnerAttrPolicy<'_>,
86 ) -> PResult<'a, ast::Attribute> {
88 "parse_attribute: inner_parse_policy={:?} self.token={:?}",
89 inner_parse_policy, self.token
91 let lo = self.token.span;
92 self.collect_tokens(|this| {
93 if this.eat(&token::Pound) {
94 let style = if this.eat(&token::Not) {
100 this.expect(&token::OpenDelim(token::Bracket))?;
101 let item = this.parse_attr_item(false)?;
102 this.expect(&token::CloseDelim(token::Bracket))?;
103 let attr_sp = lo.to(this.prev_token.span);
105 // Emit error if inner attribute is encountered and forbidden.
106 if style == ast::AttrStyle::Inner {
107 this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy);
110 Ok(attr::mk_attr_from_item(item, None, style, attr_sp))
112 let token_str = pprust::token_to_string(&this.token);
113 let msg = &format!("expected `#`, found `{}`", token_str);
114 Err(this.struct_span_err(this.token.span, msg))
119 pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
120 if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_attr_sp } = policy {
122 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
124 let mut diag = self.struct_span_err(attr_sp, reason);
126 if let Some(prev_attr_sp) = prev_attr_sp {
127 diag.span_label(attr_sp, "not permitted following an outer attribute")
128 .span_label(prev_attr_sp, prev_attr_note);
132 "inner attributes, like `#![no_std]`, annotate the item enclosing them, \
133 and are usually found at the beginning of source files. \
134 Outer attributes, like `#[test]`, annotate the item following them.",
140 /// Parses an inner part of an attribute (the path and following tokens).
141 /// The tokens must be either a delimited token stream, or empty token stream,
142 /// or the "legacy" key-value form.
143 /// PATH `(` TOKEN_STREAM `)`
144 /// PATH `[` TOKEN_STREAM `]`
145 /// PATH `{` TOKEN_STREAM `}`
147 /// PATH `=` UNSUFFIXED_LIT
148 /// The delimiters or `=` are still put into the resulting token stream.
149 pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> {
150 let item = match self.token.kind {
151 token::Interpolated(ref nt) => match **nt {
152 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
157 Ok(if let Some(item) = item {
161 let do_parse = |this: &mut Self| {
162 let path = this.parse_path(PathStyle::Mod)?;
163 let args = this.parse_attr_args()?;
164 Ok(ast::AttrItem { path, args, tokens: None })
166 if capture_tokens { self.collect_tokens(do_parse) } else { do_parse(self) }?
170 /// Parses attributes that appear after the opening of an item. These should
171 /// be preceded by an exclamation mark, but we accept and warn about one
172 /// terminated by a semicolon.
174 /// Matches `inner_attrs*`.
175 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
176 let mut attrs: Vec<ast::Attribute> = vec![];
178 // Only try to parse if it is an inner attribute (has `!`).
179 let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
180 Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
181 } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
182 if attr_style == ast::AttrStyle::Inner {
184 Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
191 if let Some(attr) = attr {
200 crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
201 let lit = self.parse_lit()?;
202 debug!("checking if {:?} is unusuffixed", lit);
204 if !lit.kind.is_unsuffixed() {
205 self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
207 "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
208 use an unsuffixed version (`1`, `1.0`, etc.)",
216 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
217 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
218 let cfg_predicate = self.parse_meta_item()?;
219 self.expect(&token::Comma)?;
221 // Presumably, the majority of the time there will only be one attr.
222 let mut expanded_attrs = Vec::with_capacity(1);
223 while self.token.kind != token::Eof {
224 let lo = self.token.span;
225 let item = self.parse_attr_item(true)?;
226 expanded_attrs.push((item, lo.to(self.prev_token.span)));
227 if !self.eat(&token::Comma) {
232 Ok((cfg_predicate, expanded_attrs))
235 /// Matches `COMMASEP(meta_item_inner)`.
236 crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
237 // Presumably, the majority of the time there will only be one attr.
238 let mut nmis = Vec::with_capacity(1);
239 while self.token.kind != token::Eof {
240 nmis.push(self.parse_meta_item_inner()?);
241 if !self.eat(&token::Comma) {
248 /// Matches the following grammar (per RFC 1559).
250 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
251 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
252 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
253 let nt_meta = match self.token.kind {
254 token::Interpolated(ref nt) => match **nt {
255 token::NtMeta(ref e) => Some(e.clone()),
261 if let Some(item) = nt_meta {
262 return match item.meta(item.path.span) {
267 None => self.unexpected(),
271 let lo = self.token.span;
272 let path = self.parse_path(PathStyle::Mod)?;
273 let kind = self.parse_meta_item_kind()?;
274 let span = lo.to(self.prev_token.span);
275 Ok(ast::MetaItem { path, kind, span })
278 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
279 Ok(if self.eat(&token::Eq) {
280 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
281 } else if self.check(&token::OpenDelim(token::Paren)) {
282 // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
283 let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
284 ast::MetaItemKind::List(list)
286 ast::MetaItemKind::Word
290 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
291 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
292 match self.parse_unsuffixed_lit() {
293 Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
294 Err(ref mut err) => err.cancel(),
297 match self.parse_meta_item() {
298 Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
299 Err(ref mut err) => err.cancel(),
302 let found = pprust::token_to_string(&self.token);
303 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
304 Err(self.struct_span_err(self.token.span, &msg))
308 pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool {
309 // One of the attributes may either itself be a macro, or apply derive macros (`derive`),
310 // or expand to macro attributes (`cfg_attr`).
311 attrs.iter().any(|attr| {
312 attr.ident().map_or(true, |ident| {
313 ident.name == sym::derive
314 || ident.name == sym::cfg_attr
315 || !rustc_feature::is_builtin_attr_name(ident.name)