1 use super::{Parser, PathStyle};
4 use rustc_ast::token::{self, Nonterminal};
5 use rustc_ast::util::comments;
6 use rustc_ast_pretty::pprust;
7 use rustc_errors::{error_code, PResult};
8 use rustc_span::{Span, Symbol};
13 pub(super) 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 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 let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?;
49 just_parsed_doc_comment = false;
50 } else if let token::DocComment(s) = self.token.kind {
51 let attr = self.mk_doc_comment(s);
52 if attr.style != ast::AttrStyle::Outer {
55 .struct_span_err_with_code(
57 "expected outer doc comment",
61 "inner doc comments like this (starting with \
62 `//!` or `/*!`) can only appear before items",
68 just_parsed_doc_comment = true;
76 fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
77 attr::mk_doc_comment(comments::doc_comment_style(s), s, self.token.span)
80 /// Matches `attribute = # ! [ meta_item ]`.
82 /// If `permit_inner` is `true`, then a leading `!` indicates an inner
84 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
85 debug!("parse_attribute: permit_inner={:?} self.token={:?}", permit_inner, self.token);
86 let inner_parse_policy =
87 if permit_inner { InnerAttrPolicy::Permitted } else { DEFAULT_INNER_ATTR_FORBIDDEN };
88 self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
91 /// The same as `parse_attribute`, except it takes in an `InnerAttrPolicy`
92 /// that prescribes how to handle inner attributes.
93 fn parse_attribute_with_inner_parse_policy(
95 inner_parse_policy: InnerAttrPolicy<'_>,
96 ) -> PResult<'a, ast::Attribute> {
98 "parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
99 inner_parse_policy, self.token
101 let lo = self.token.span;
102 let (span, item, style) = if self.eat(&token::Pound) {
104 if self.eat(&token::Not) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer };
106 self.expect(&token::OpenDelim(token::Bracket))?;
107 let item = self.parse_attr_item()?;
108 self.expect(&token::CloseDelim(token::Bracket))?;
109 let attr_sp = lo.to(self.prev_token.span);
111 // Emit error if inner attribute is encountered and forbidden.
112 if style == ast::AttrStyle::Inner {
113 self.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy);
116 (attr_sp, item, style)
118 let token_str = pprust::token_to_string(&self.token);
119 let msg = &format!("expected `#`, found `{}`", token_str);
120 return Err(self.struct_span_err(self.token.span, msg));
123 Ok(attr::mk_attr_from_item(style, item, span))
126 pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
127 if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_attr_sp } = policy {
129 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
131 let mut diag = self.struct_span_err(attr_sp, reason);
133 if let Some(prev_attr_sp) = prev_attr_sp {
134 diag.span_label(attr_sp, "not permitted following an outer attribute")
135 .span_label(prev_attr_sp, prev_attr_note);
139 "inner attributes, like `#![no_std]`, annotate the item enclosing them, \
140 and are usually found at the beginning of source files. \
141 Outer attributes, like `#[test]`, annotate the item following them.",
147 /// Parses an inner part of an attribute (the path and following tokens).
148 /// The tokens must be either a delimited token stream, or empty token stream,
149 /// or the "legacy" key-value form.
150 /// PATH `(` TOKEN_STREAM `)`
151 /// PATH `[` TOKEN_STREAM `]`
152 /// PATH `{` TOKEN_STREAM `}`
154 /// PATH `=` UNSUFFIXED_LIT
155 /// The delimiters or `=` are still put into the resulting token stream.
156 pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> {
157 let item = match self.token.kind {
158 token::Interpolated(ref nt) => match **nt {
159 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
164 Ok(if let Some(item) = item {
168 let path = self.parse_path(PathStyle::Mod)?;
169 let args = self.parse_attr_args()?;
170 ast::AttrItem { path, args }
174 /// Parses attributes that appear after the opening of an item. These should
175 /// be preceded by an exclamation mark, but we accept and warn about one
176 /// terminated by a semicolon.
178 /// Matches `inner_attrs*`.
179 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
180 let mut attrs: Vec<ast::Attribute> = vec![];
182 // Only try to parse if it is an inner attribute (has `!`).
183 if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
184 let attr = self.parse_attribute(true)?;
185 assert_eq!(attr.style, ast::AttrStyle::Inner);
187 } else if let token::DocComment(s) = self.token.kind {
188 // We need to get the position of this token before we bump.
189 let attr = self.mk_doc_comment(s);
190 if attr.style == ast::AttrStyle::Inner {
203 crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
204 let lit = self.parse_lit()?;
205 debug!("checking if {:?} is unusuffixed", lit);
207 if !lit.kind.is_unsuffixed() {
208 self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
210 "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
211 use an unsuffixed version (`1`, `1.0`, etc.)",
219 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
220 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
221 let cfg_predicate = self.parse_meta_item()?;
222 self.expect(&token::Comma)?;
224 // Presumably, the majority of the time there will only be one attr.
225 let mut expanded_attrs = Vec::with_capacity(1);
226 while self.token.kind != token::Eof {
227 let lo = self.token.span;
228 let item = self.parse_attr_item()?;
229 expanded_attrs.push((item, lo.to(self.prev_token.span)));
230 if !self.eat(&token::Comma) {
235 Ok((cfg_predicate, expanded_attrs))
238 /// Matches `COMMASEP(meta_item_inner)`.
239 crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
240 // Presumably, the majority of the time there will only be one attr.
241 let mut nmis = Vec::with_capacity(1);
242 while self.token.kind != token::Eof {
243 nmis.push(self.parse_meta_item_inner()?);
244 if !self.eat(&token::Comma) {
251 /// Matches the following grammar (per RFC 1559).
253 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
254 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
255 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
256 let nt_meta = match self.token.kind {
257 token::Interpolated(ref nt) => match **nt {
258 token::NtMeta(ref e) => Some(e.clone()),
264 if let Some(item) = nt_meta {
265 return match item.meta(item.path.span) {
270 None => self.unexpected(),
274 let lo = self.token.span;
275 let path = self.parse_path(PathStyle::Mod)?;
276 let kind = self.parse_meta_item_kind()?;
277 let span = lo.to(self.prev_token.span);
278 Ok(ast::MetaItem { path, kind, span })
281 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
282 Ok(if self.eat(&token::Eq) {
283 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
284 } else if self.check(&token::OpenDelim(token::Paren)) {
285 // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
286 let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
287 ast::MetaItemKind::List(list)
289 ast::MetaItemKind::Word
293 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
294 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
295 match self.parse_unsuffixed_lit() {
296 Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
297 Err(ref mut err) => err.cancel(),
300 match self.parse_meta_item() {
301 Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
302 Err(ref mut err) => err.cancel(),
305 let found = pprust::token_to_string(&self.token);
306 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
307 Err(self.struct_span_err(self.token.span, &msg))