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_outer_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,
25 prev_outer_attr_sp: None,
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 outer_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 prev_outer_attr_sp = outer_attrs.last().map(|attr| attr.span);
44 let inner_error_reason = if just_parsed_doc_comment {
45 "an inner attribute is not permitted following an outer doc comment"
46 } else if prev_outer_attr_sp.is_some() {
47 "an inner attribute is not permitted following an outer attribute"
49 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
51 let inner_parse_policy = InnerAttrPolicy::Forbidden {
52 reason: inner_error_reason,
53 saw_doc_comment: just_parsed_doc_comment,
56 just_parsed_doc_comment = false;
57 Some(self.parse_attribute(inner_parse_policy)?)
58 } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
59 if attr_style != ast::AttrStyle::Outer {
60 let span = self.token.span;
61 let mut err = self.sess.span_diagnostic.struct_span_err_with_code(
63 "expected outer doc comment",
66 if let Some(replacement_span) = self.annotate_following_item_if_applicable(
70 token::CommentKind::Line => OuterAttributeType::DocComment,
71 token::CommentKind::Block => OuterAttributeType::DocBlockComment,
75 "inner doc comments like this (starting with `//!` or `/*!`) can \
76 only appear before items",
78 err.span_suggestion_verbose(
80 "you might have meant to write a regular comment",
82 rustc_errors::Applicability::MachineApplicable,
88 just_parsed_doc_comment = true;
89 // Always make an outer attribute - this allows us to recover from a misplaced
91 Some(attr::mk_doc_comment(
93 ast::AttrStyle::Outer,
101 if let Some(attr) = attr {
102 if attr.style == ast::AttrStyle::Outer {
103 outer_attrs.push(attr);
109 Ok(AttrWrapper::new(outer_attrs.into(), start_pos))
112 /// Matches `attribute = # ! [ meta_item ]`.
113 /// `inner_parse_policy` prescribes how to handle inner attributes.
114 // Public for rustfmt usage.
115 pub fn parse_attribute(
117 inner_parse_policy: InnerAttrPolicy<'_>,
118 ) -> PResult<'a, ast::Attribute> {
120 "parse_attribute: inner_parse_policy={:?} self.token={:?}",
121 inner_parse_policy, self.token
123 let lo = self.token.span;
124 // Attributes can't have attributes of their own [Editor's note: not with that attitude]
125 self.collect_tokens_no_attrs(|this| {
126 if this.eat(&token::Pound) {
127 let style = if this.eat(&token::Not) {
128 ast::AttrStyle::Inner
130 ast::AttrStyle::Outer
133 this.expect(&token::OpenDelim(token::Bracket))?;
134 let item = this.parse_attr_item(false)?;
135 this.expect(&token::CloseDelim(token::Bracket))?;
136 let attr_sp = lo.to(this.prev_token.span);
138 // Emit error if inner attribute is encountered and forbidden.
139 if style == ast::AttrStyle::Inner {
140 this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy);
143 Ok(attr::mk_attr_from_item(item, None, style, attr_sp))
145 let token_str = pprust::token_to_string(&this.token);
146 let msg = &format!("expected `#`, found `{token_str}`");
147 Err(this.struct_span_err(this.token.span, msg))
152 fn annotate_following_item_if_applicable(
154 err: &mut Diagnostic,
156 attr_type: OuterAttributeType,
158 let mut snapshot = self.create_snapshot_for_diagnostic();
160 + BytePos(match attr_type {
161 OuterAttributeType::Attribute => 1,
164 let hi = lo + BytePos(1);
165 let replacement_span = span.with_lo(lo).with_hi(hi);
166 if let OuterAttributeType::DocBlockComment | OuterAttributeType::DocComment = attr_type {
170 // skip any other attributes, we want the item
171 if snapshot.token.kind == token::Pound {
172 if let Err(err) = snapshot.parse_attribute(InnerAttrPolicy::Permitted) {
174 return Some(replacement_span);
180 match snapshot.parse_item_common(
181 AttrWrapper::empty(),
184 FnParseMode { req_name: |_| true, req_body: true },
188 let attr_name = match attr_type {
189 OuterAttributeType::Attribute => "attribute",
194 &format!("the inner {} doesn't annotate this {}", attr_name, item.kind.descr()),
196 err.span_suggestion_verbose(
199 "to annotate the {}, change the {} from inner to outer style",
204 OuterAttributeType::Attribute => "",
205 OuterAttributeType::DocBlockComment => "*",
206 OuterAttributeType::DocComment => "/",
209 rustc_errors::Applicability::MachineApplicable,
218 Some(replacement_span)
221 pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) {
222 if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_outer_attr_sp } = policy {
223 let prev_outer_attr_note =
224 if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" };
226 let mut diag = self.struct_span_err(attr_sp, reason);
228 if let Some(prev_outer_attr_sp) = prev_outer_attr_sp {
229 diag.span_label(attr_sp, "not permitted following an outer attribute")
230 .span_label(prev_outer_attr_sp, prev_outer_attr_note);
234 "inner attributes, like `#![no_std]`, annotate the item enclosing them, and \
235 are usually found at the beginning of source files",
238 .annotate_following_item_if_applicable(
241 OuterAttributeType::Attribute,
245 diag.note("outer attributes, like `#[test]`, annotate the item following them");
251 /// Parses an inner part of an attribute (the path and following tokens).
252 /// The tokens must be either a delimited token stream, or empty token stream,
253 /// or the "legacy" key-value form.
254 /// PATH `(` TOKEN_STREAM `)`
255 /// PATH `[` TOKEN_STREAM `]`
256 /// PATH `{` TOKEN_STREAM `}`
258 /// PATH `=` UNSUFFIXED_LIT
259 /// The delimiters or `=` are still put into the resulting token stream.
260 pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> {
261 let item = match self.token.kind {
262 token::Interpolated(ref nt) => match **nt {
263 Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
268 Ok(if let Some(item) = item {
272 let do_parse = |this: &mut Self| {
273 let path = this.parse_path(PathStyle::Mod)?;
274 let args = this.parse_attr_args()?;
275 Ok(ast::AttrItem { path, args, tokens: None })
277 // Attr items don't have attributes
278 if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }?
282 /// Parses attributes that appear after the opening of an item. These should
283 /// be preceded by an exclamation mark, but we accept and warn about one
284 /// terminated by a semicolon.
286 /// Matches `inner_attrs*`.
287 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
288 let mut attrs: Vec<ast::Attribute> = vec![];
290 let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
291 // Only try to parse if it is an inner attribute (has `!`).
292 let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) {
293 Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
294 } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
295 if attr_style == ast::AttrStyle::Inner {
297 Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span))
304 if let Some(attr) = attr {
305 let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap();
306 // If we are currently capturing tokens, mark the location of this inner attribute.
307 // If capturing ends up creating a `LazyTokenStream`, we will include
308 // this replace range with it, removing the inner attribute from the final
309 // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note.
310 // During macro expansion, they are selectively inserted back into the
311 // token stream (the first inner attribute is removed each time we invoke the
312 // corresponding macro).
313 let range = start_pos..end_pos;
314 if let Capturing::Yes = self.capture_state.capturing {
315 self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![]));
325 crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
326 let lit = self.parse_lit()?;
327 debug!("checking if {:?} is unusuffixed", lit);
329 if !lit.kind.is_unsuffixed() {
330 self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes")
332 "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \
333 use an unsuffixed version (`1`, `1.0`, etc.)",
341 /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
342 pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
343 let cfg_predicate = self.parse_meta_item()?;
344 self.expect(&token::Comma)?;
346 // Presumably, the majority of the time there will only be one attr.
347 let mut expanded_attrs = Vec::with_capacity(1);
348 while self.token.kind != token::Eof {
349 let lo = self.token.span;
350 let item = self.parse_attr_item(true)?;
351 expanded_attrs.push((item, lo.to(self.prev_token.span)));
352 if !self.eat(&token::Comma) {
357 Ok((cfg_predicate, expanded_attrs))
360 /// Matches `COMMASEP(meta_item_inner)`.
361 crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
362 // Presumably, the majority of the time there will only be one attr.
363 let mut nmis = Vec::with_capacity(1);
364 while self.token.kind != token::Eof {
365 nmis.push(self.parse_meta_item_inner()?);
366 if !self.eat(&token::Comma) {
373 /// Matches the following grammar (per RFC 1559).
375 /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
376 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
377 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
378 let nt_meta = match self.token.kind {
379 token::Interpolated(ref nt) => match **nt {
380 token::NtMeta(ref e) => Some(e.clone()),
386 if let Some(item) = nt_meta {
387 return match item.meta(item.path.span) {
392 None => self.unexpected(),
396 let lo = self.token.span;
397 let path = self.parse_path(PathStyle::Mod)?;
398 let kind = self.parse_meta_item_kind()?;
399 let span = lo.to(self.prev_token.span);
400 Ok(ast::MetaItem { path, kind, span })
403 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
404 Ok(if self.eat(&token::Eq) {
405 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
406 } else if self.check(&token::OpenDelim(token::Paren)) {
407 // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
408 let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
409 ast::MetaItemKind::List(list)
411 ast::MetaItemKind::Word
415 /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
416 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
417 match self.parse_unsuffixed_lit() {
418 Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
419 Err(err) => err.cancel(),
422 match self.parse_meta_item() {
423 Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
424 Err(err) => err.cancel(),
427 let found = pprust::token_to_string(&self.token);
428 let msg = format!("expected unsuffixed literal or identifier, found `{found}`");
429 Err(self.struct_span_err(self.token.span, &msg))
433 pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool {
434 // One of the attributes may either itself be a macro,
435 // or expand to macro attributes (`cfg_attr`).
436 attrs.iter().any(|attr| {
437 if attr.is_doc_comment() {
440 attr.ident().map_or(true, |ident| {
441 ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name)