1 use super::{AttrWrapper, Capturing, FnParseMode, ForceCollect, Parser, PathStyle};
4 use rustc_ast::token::{self, Nonterminal};
5 use rustc_ast_pretty::pprust;
6 use rustc_errors::{error_code, Diagnostic, PResult};
7 use rustc_span::{sym, BytePos, Span};
8 use std::convert::TryInto;
12 // Public for rustfmt usage
14 pub enum InnerAttrPolicy<'a> {
16 Forbidden { reason: &'a str, saw_doc_comment: bool, prev_attr_sp: Option<Span> },
19 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
20 permitted in this context";
22 pub(super) const DEFAULT_INNER_ATTR_FORBIDDEN: InnerAttrPolicy<'_> = InnerAttrPolicy::Forbidden {
23 reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG,
24 saw_doc_comment: false,
28 enum OuterAttributeType {
35 /// Parses attributes that appear before an item.
36 pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> {
37 let mut attrs: Vec<ast::Attribute> = Vec::new();
38 let mut just_parsed_doc_comment = false;
39 let start_pos = self.token_cursor.num_next_calls;
41 let attr = if self.check(&token::Pound) {
42 let inner_error_reason = if just_parsed_doc_comment {
43 "an inner attribute is not permitted following an outer doc comment"
44 } else if !attrs.is_empty() {
45 "an inner attribute is not permitted following an outer attribute"
47 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
49 let inner_parse_policy = InnerAttrPolicy::Forbidden {
50 reason: inner_error_reason,
51 saw_doc_comment: just_parsed_doc_comment,
52 prev_attr_sp: attrs.last().map(|a| a.span),
54 just_parsed_doc_comment = false;
55 Some(self.parse_attribute(inner_parse_policy)?)
56 } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
57 if attr_style != ast::AttrStyle::Outer {
58 let span = self.token.span;
59 let mut err = self.sess.span_diagnostic.struct_span_err_with_code(
61 "expected outer doc comment",
64 if let Some(replacement_span) = self.annotate_following_item_if_applicable(
68 token::CommentKind::Line => OuterAttributeType::DocComment,
69 token::CommentKind::Block => OuterAttributeType::DocBlockComment,
73 "inner doc comments like this (starting with `//!` or `/*!`) can \
74 only appear before items",
76 err.span_suggestion_verbose(
78 "you might have meant to write a regular comment",
80 rustc_errors::Applicability::MachineApplicable,
86 just_parsed_doc_comment = true;
87 // Always make an outer attribute - this allows us to recover from a misplaced
89 Some(attr::mk_doc_comment(
91 ast::AttrStyle::Outer,
99 if let Some(attr) = attr {
105 Ok(AttrWrapper::new(attrs.into(), start_pos))
108 /// Matches `attribute = # ! [ meta_item ]`.
109 /// `inner_parse_policy` prescribes how to handle inner attributes.
110 // Public for rustfmt usage.
111 pub fn parse_attribute(
113 inner_parse_policy: InnerAttrPolicy<'_>,
114 ) -> PResult<'a, ast::Attribute> {
116 "parse_attribute: inner_parse_policy={:?} self.token={:?}",
117 inner_parse_policy, self.token
119 let lo = self.token.span;
120 // Attributes can't have attributes of their own [Editor's note: not with that attitude]
121 self.collect_tokens_no_attrs(|this| {
122 if this.eat(&token::Pound) {
123 let style = if this.eat(&token::Not) {
124 ast::AttrStyle::Inner
126 ast::AttrStyle::Outer
129 this.expect(&token::OpenDelim(token::Bracket))?;
130 let item = this.parse_attr_item(false)?;
131 this.expect(&token::CloseDelim(token::Bracket))?;
132 let attr_sp = lo.to(this.prev_token.span);
134 // Emit error if inner attribute is encountered and forbidden.
135 if style == ast::AttrStyle::Inner {
136 this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy);
139 Ok(attr::mk_attr_from_item(item, None, style, attr_sp))
141 let token_str = pprust::token_to_string(&this.token);
142 let msg = &format!("expected `#`, found `{token_str}`");
143 Err(this.struct_span_err(this.token.span, msg))
148 fn annotate_following_item_if_applicable(
150 err: &mut Diagnostic,
152 attr_type: OuterAttributeType,
154 let mut snapshot = self.create_snapshot_for_diagnostic();
156 + BytePos(match attr_type {
157 OuterAttributeType::Attribute => 1,
160 let hi = lo + BytePos(1);
161 let replacement_span = span.with_lo(lo).with_hi(hi);
162 if let OuterAttributeType::DocBlockComment | OuterAttributeType::DocComment = attr_type {
166 // skip any other attributes, we want the item
167 if snapshot.token.kind == token::Pound {
168 if let Err(err) = snapshot.parse_attribute(InnerAttrPolicy::Permitted) {
170 return Some(replacement_span);
176 match snapshot.parse_item_common(
177 AttrWrapper::empty(),
180 FnParseMode { req_name: |_| true, req_body: true },
184 let attr_name = match attr_type {
185 OuterAttributeType::Attribute => "attribute",
190 &format!("the inner {} doesn't annotate this {}", attr_name, item.kind.descr()),
192 err.span_suggestion_verbose(
195 "to annotate the {}, change the {} from inner to outer style",
200 OuterAttributeType::Attribute => "",
201 OuterAttributeType::DocBlockComment => "*",
202 OuterAttributeType::DocComment => "/",
205 rustc_errors::Applicability::MachineApplicable,
214 Some(replacement_span)
217 pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
218 if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_attr_sp } = policy {
220 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
222 let mut diag = self.struct_span_err(attr_sp, reason);
224 if let Some(prev_attr_sp) = prev_attr_sp {
225 diag.span_label(attr_sp, "not permitted following an outer attribute")
226 .span_label(prev_attr_sp, prev_attr_note);
230 "inner attributes, like `#![no_std]`, annotate the item enclosing them, and \
231 are usually found at the beginning of source files",
234 .annotate_following_item_if_applicable(
237 OuterAttributeType::Attribute,
241 diag.note("outer attributes, like `#[test]`, annotate the item following them");
247 /// Parses an inner part of an attribute (the path and following tokens).
248 /// The tokens must be either a delimited token stream, or empty token stream,
249 /// or the "legacy" key-value form.
250 /// PATH `(` TOKEN_STREAM `)`
251 /// PATH `[` TOKEN_STREAM `]`
252 /// PATH `{` TOKEN_STREAM `}`
254 /// PATH `=` UNSUFFIXED_LIT
255 /// The delimiters or `=` are still put into the resulting token stream.
256 pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> {
257 let item = match self.token.kind {
258 token::Interpolated(ref nt) => match **nt {
259 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
264 Ok(if let Some(item) = item {
268 let do_parse = |this: &mut Self| {
269 let path = this.parse_path(PathStyle::Mod)?;
270 let args = this.parse_attr_args()?;
271 Ok(ast::AttrItem { path, args, tokens: None })
273 // Attr items don't have attributes
274 if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }?
278 /// Parses attributes that appear after the opening of an item. These should
279 /// be preceded by an exclamation mark, but we accept and warn about one
280 /// terminated by a semicolon.
282 /// Matches `inner_attrs*`.
283 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
284 let mut attrs: Vec<ast::Attribute> = vec![];
286 let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
287 // Only try to parse if it is an inner attribute (has `!`).
288 let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
289 Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
290 } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
291 if attr_style == ast::AttrStyle::Inner {
293 Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
300 if let Some(attr) = attr {
301 let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
302 // If we are currently capturing tokens, mark the location of this inner attribute.
303 // If capturing ends up creating a `LazyTokenStream`, we will include
304 // this replace range with it, removing the inner attribute from the final
305 // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note.
306 // During macro expansion, they are selectively inserted back into the
307 // token stream (the first inner attribute is remoevd each time we invoke the
308 // corresponding macro).
309 let range = start_pos..end_pos;
310 if let Capturing::Yes = self.capture_state.capturing {
311 self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![]));
321 crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
322 let lit = self.parse_lit()?;
323 debug!("checking if {:?} is unusuffixed", lit);
325 if !lit.kind.is_unsuffixed() {
326 self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
328 "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
329 use an unsuffixed version (`1`, `1.0`, etc.)",
337 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
338 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
339 let cfg_predicate = self.parse_meta_item()?;
340 self.expect(&token::Comma)?;
342 // Presumably, the majority of the time there will only be one attr.
343 let mut expanded_attrs = Vec::with_capacity(1);
344 while self.token.kind != token::Eof {
345 let lo = self.token.span;
346 let item = self.parse_attr_item(true)?;
347 expanded_attrs.push((item, lo.to(self.prev_token.span)));
348 if !self.eat(&token::Comma) {
353 Ok((cfg_predicate, expanded_attrs))
356 /// Matches `COMMASEP(meta_item_inner)`.
357 crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
358 // Presumably, the majority of the time there will only be one attr.
359 let mut nmis = Vec::with_capacity(1);
360 while self.token.kind != token::Eof {
361 nmis.push(self.parse_meta_item_inner()?);
362 if !self.eat(&token::Comma) {
369 /// Matches the following grammar (per RFC 1559).
371 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
372 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
373 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
374 let nt_meta = match self.token.kind {
375 token::Interpolated(ref nt) => match **nt {
376 token::NtMeta(ref e) => Some(e.clone()),
382 if let Some(item) = nt_meta {
383 return match item.meta(item.path.span) {
388 None => self.unexpected(),
392 let lo = self.token.span;
393 let path = self.parse_path(PathStyle::Mod)?;
394 let kind = self.parse_meta_item_kind()?;
395 let span = lo.to(self.prev_token.span);
396 Ok(ast::MetaItem { path, kind, span })
399 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
400 Ok(if self.eat(&token::Eq) {
401 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
402 } else if self.check(&token::OpenDelim(token::Paren)) {
403 // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
404 let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
405 ast::MetaItemKind::List(list)
407 ast::MetaItemKind::Word
411 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
412 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
413 match self.parse_unsuffixed_lit() {
414 Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
415 Err(err) => err.cancel(),
418 match self.parse_meta_item() {
419 Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
420 Err(err) => err.cancel(),
423 let found = pprust::token_to_string(&self.token);
424 let msg = format!("expected unsuffixed literal or identifier, found `{found}`");
425 Err(self.struct_span_err(self.token.span, &msg))
429 pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool {
430 // One of the attributes may either itself be a macro,
431 // or expand to macro attributes (`cfg_attr`).
432 attrs.iter().any(|attr| {
433 if attr.is_doc_comment() {
436 attr.ident().map_or(true, |ident| {
437 ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name)