Skip to main content

rustc_parse/parser/
attr.rs

1use rustc_ast as ast;
2use rustc_ast::token::{self, MetaVarKind};
3use rustc_ast::tokenstream::{ParserRange, WithTokens};
4use rustc_ast::{AttrItemKind, Attribute, attr};
5use rustc_errors::codes::*;
6use rustc_errors::{Diag, PResult, msg};
7use rustc_span::{BytePos, Span};
8use thin_vec::ThinVec;
9use tracing::debug;
10
11use super::{
12    AllowConstBlockItems, AttrWrapper, Capturing, FnParseMode, ForceCollect, Parser, PathStyle,
13    Trailing, UsePreAttrPos,
14};
15use crate::parser::FnContext;
16use crate::{diagnostics, exp};
17
18// Public for rustfmt usage
19#[derive(#[automatically_derived]
impl ::core::fmt::Debug for InnerAttrPolicy {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            InnerAttrPolicy::Permitted =>
                ::core::fmt::Formatter::write_str(f, "Permitted"),
            InnerAttrPolicy::Forbidden(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "Forbidden", &__self_0),
        }
    }
}Debug)]
20pub enum InnerAttrPolicy {
21    Permitted,
22    Forbidden(Option<InnerAttrForbiddenReason>),
23}
24
25#[derive(#[automatically_derived]
impl ::core::clone::Clone for InnerAttrForbiddenReason {
    #[inline]
    fn clone(&self) -> InnerAttrForbiddenReason {
        let _: ::core::clone::AssertParamIsClone<Span>;
        *self
    }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for InnerAttrForbiddenReason { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for InnerAttrForbiddenReason {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            InnerAttrForbiddenReason::InCodeBlock =>
                ::core::fmt::Formatter::write_str(f, "InCodeBlock"),
            InnerAttrForbiddenReason::AfterOuterDocComment {
                prev_doc_comment_span: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "AfterOuterDocComment", "prev_doc_comment_span", &__self_0),
            InnerAttrForbiddenReason::AfterOuterAttribute {
                prev_outer_attr_sp: __self_0 } =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "AfterOuterAttribute", "prev_outer_attr_sp", &__self_0),
        }
    }
}Debug)]
26pub enum InnerAttrForbiddenReason {
27    InCodeBlock,
28    AfterOuterDocComment { prev_doc_comment_span: Span },
29    AfterOuterAttribute { prev_outer_attr_sp: Span },
30}
31
32enum OuterAttributeType {
33    DocComment,
34    DocBlockComment,
35    Attribute,
36}
37
38#[derive(#[automatically_derived]
impl ::core::clone::Clone for AllowLeadingUnsafe {
    #[inline]
    fn clone(&self) -> AllowLeadingUnsafe { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AllowLeadingUnsafe { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for AllowLeadingUnsafe {
    #[inline]
    fn eq(&self, other: &AllowLeadingUnsafe) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AllowLeadingUnsafe {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {}
}Eq)]
39pub enum AllowLeadingUnsafe {
40    Yes,
41    No,
42}
43
44impl<'a> Parser<'a> {
45    /// Parses attributes that appear before an item.
46    pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> {
47        let mut outer_attrs = ast::AttrVec::new();
48        let mut just_parsed_doc_comment = false;
49        let start_pos = self.num_bump_calls;
50        loop {
51            let attr = if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Pound,
    token_type: crate::parser::token_type::TokenType::Pound,
}exp!(Pound)) {
52                let prev_outer_attr_sp = outer_attrs.last().map(|attr: &Attribute| attr.span);
53
54                let inner_error_reason = if just_parsed_doc_comment {
55                    Some(InnerAttrForbiddenReason::AfterOuterDocComment {
56                        prev_doc_comment_span: prev_outer_attr_sp.unwrap(),
57                    })
58                } else {
59                    prev_outer_attr_sp.map(|prev_outer_attr_sp| {
60                        InnerAttrForbiddenReason::AfterOuterAttribute { prev_outer_attr_sp }
61                    })
62                };
63                let inner_parse_policy = InnerAttrPolicy::Forbidden(inner_error_reason);
64                just_parsed_doc_comment = false;
65                Some(self.parse_attribute(inner_parse_policy)?)
66            } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
67                if attr_style != ast::AttrStyle::Outer {
68                    let span = self.token.span;
69                    let mut err =
70                        self.dcx().struct_span_err(span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("expected outer doc comment"))msg!("expected outer doc comment"));
71                    err.code(E0753);
72                    if let Some(replacement_span) = self.annotate_following_item_if_applicable(
73                        &mut err,
74                        span,
75                        match comment_kind {
76                            token::CommentKind::Line => OuterAttributeType::DocComment,
77                            token::CommentKind::Block => OuterAttributeType::DocBlockComment,
78                        },
79                        true,
80                    ) {
81                        err.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("inner doc comments like this (starting with `//!` or `/*!`) can only appear before items"))msg!(
82                            "inner doc comments like this (starting with `//!` or `/*!`) can only appear before items"
83                        ));
84                        err.span_suggestion_verbose(
85                            replacement_span,
86                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("you might have meant to write a regular comment"))msg!("you might have meant to write a regular comment"),
87                            "",
88                            rustc_errors::Applicability::MachineApplicable,
89                        );
90                    }
91                    err.emit();
92                }
93                self.bump();
94                just_parsed_doc_comment = true;
95                // Always make an outer attribute - this allows us to recover from a misplaced
96                // inner attribute.
97                Some(attr::mk_doc_comment(
98                    &self.psess.attr_id_generator,
99                    comment_kind,
100                    ast::AttrStyle::Outer,
101                    data,
102                    self.prev_token.span,
103                ))
104            } else {
105                None
106            };
107
108            if let Some(attr) = attr {
109                if attr.style == ast::AttrStyle::Outer {
110                    outer_attrs.push(attr);
111                }
112            } else {
113                break;
114            }
115        }
116        Ok(AttrWrapper::new(outer_attrs, start_pos))
117    }
118
119    /// Matches `attribute = # ! [ meta_item ]`.
120    /// `inner_parse_policy` prescribes how to handle inner attributes.
121    // Public for rustfmt usage.
122    pub fn parse_attribute(
123        &mut self,
124        inner_parse_policy: InnerAttrPolicy,
125    ) -> PResult<'a, ast::Attribute> {
126        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/attr.rs:126",
                        "rustc_parse::parser::attr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/attr.rs"),
                        ::tracing_core::__macro_support::Option::Some(126u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::attr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("parse_attribute: inner_parse_policy={0:?} self.token={1:?}",
                                                    inner_parse_policy, self.token) as &dyn Value))])
            });
    } else { ; }
};debug!(
127            "parse_attribute: inner_parse_policy={:?} self.token={:?}",
128            inner_parse_policy, self.token
129        );
130        let lo = self.token.span;
131        // Attributes can't have attributes of their own [Editor's note: not with that attitude]
132        self.collect_tokens_no_attrs(|this| {
133            let pound_hi = this.token.span.hi();
134            if !this.eat(crate::parser::token_type::ExpTokenPair {
                tok: rustc_ast::token::Pound,
                token_type: crate::parser::token_type::TokenType::Pound,
            }) {
    {
        ::core::panicking::panic_fmt(format_args!("parse_attribute called in non-attribute position"));
    }
};assert!(this.eat(exp!(Pound)), "parse_attribute called in non-attribute position");
135
136            let not_lo = this.token.span.lo();
137            let style =
138                if this.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Bang,
    token_type: crate::parser::token_type::TokenType::Bang,
}exp!(Bang)) { ast::AttrStyle::Inner } else { ast::AttrStyle::Outer };
139
140            let mut bracket_res = this.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenBracket,
    token_type: crate::parser::token_type::TokenType::OpenBracket,
}exp!(OpenBracket));
141            // If `#!` is not followed by `[`
142            if let Err(err) = &mut bracket_res
143                && style == ast::AttrStyle::Inner
144                && pound_hi == not_lo
145            {
146                err.note(
147                    "the token sequence `#!` here looks like the start of \
148                    a shebang interpreter directive but it is not",
149                );
150                err.help(
151                    "if you meant this to be a shebang interpreter directive, \
152                    move it to the very start of the file",
153                );
154            }
155            bracket_res?;
156
157            let attr_item = this.parse_attr_item(ForceCollect::No)?;
158            // `attr_item` will never have tokens: within `parse_attr_item`, `collect_tokens`
159            // attaches tokens only if:
160            // - `ForceCollect::Yes` is passed (not true), or
161            // - attributes on the parsed node require tokens (not true, because attr items can't
162            //   have attributes of their own, hence the empty `HasAttrs` impl for `AttrItem`).
163            if !attr_item.tokens.is_none() {
    ::core::panicking::panic("assertion failed: attr_item.tokens.is_none()")
};assert!(attr_item.tokens.is_none());
164
165            this.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseBracket,
    token_type: crate::parser::token_type::TokenType::CloseBracket,
}exp!(CloseBracket))?;
166            let attr_sp = lo.to(this.prev_token.span);
167
168            // Emit error if inner attribute is encountered and forbidden.
169            if style == ast::AttrStyle::Inner {
170                this.error_on_forbidden_inner_attr(
171                    attr_sp,
172                    inner_parse_policy,
173                    attr_item.node.is_valid_for_outer_style(),
174                );
175            }
176
177            Ok(attr::mk_attr_from_item(
178                &self.psess.attr_id_generator,
179                attr_item.node,
180                None,
181                style,
182                attr_sp,
183            ))
184        })
185    }
186
187    fn annotate_following_item_if_applicable(
188        &self,
189        err: &mut Diag<'_>,
190        span: Span,
191        attr_type: OuterAttributeType,
192        suggest_to_outer: bool,
193    ) -> Option<Span> {
194        let mut snapshot = self.create_snapshot_for_diagnostic();
195        let lo = span.lo()
196            + BytePos(match attr_type {
197                OuterAttributeType::Attribute => 1,
198                _ => 2,
199            });
200        let hi = lo + BytePos(1);
201        let replacement_span = span.with_lo(lo).with_hi(hi);
202        if let OuterAttributeType::DocBlockComment | OuterAttributeType::DocComment = attr_type {
203            snapshot.bump();
204        }
205        loop {
206            // skip any other attributes, we want the item
207            if snapshot.token == token::Pound {
208                if let Err(err) = snapshot.parse_attribute(InnerAttrPolicy::Permitted) {
209                    err.cancel();
210                    return Some(replacement_span);
211                }
212            } else {
213                break;
214            }
215        }
216        match snapshot.parse_item_common(
217            AttrWrapper::empty(),
218            true,
219            false,
220            FnParseMode { req_name: |_, _| true, context: FnContext::Free, req_body: true },
221            ForceCollect::No,
222            AllowConstBlockItems::Yes,
223        ) {
224            Ok(Some(item)) => {
225                err.arg("item", item.kind.descr());
226                err.span_label(
227                    item.span,
228                    match attr_type {
229                        OuterAttributeType::Attribute => {
230                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the inner attribute doesn't annotate this {$item}"))msg!("the inner attribute doesn't annotate this {$item}")
231                        }
232                        OuterAttributeType::DocComment | OuterAttributeType::DocBlockComment => {
233                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the inner doc comment doesn't annotate this {$item}"))msg!("the inner doc comment doesn't annotate this {$item}")
234                        }
235                    },
236                );
237                if suggest_to_outer {
238                    err.span_suggestion_verbose(
239                        replacement_span,
240                        match attr_type {
241                            OuterAttributeType::Attribute =>  rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("to annotate the {$item}, change the attribute from inner to outer style"))msg!("to annotate the {$item}, change the attribute from inner to outer style"),
242                            OuterAttributeType::DocComment | OuterAttributeType::DocBlockComment =>  rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("to annotate the {$item}, change the doc comment from inner to outer style"))msg!("to annotate the {$item}, change the doc comment from inner to outer style"),
243                        },
244                        match attr_type {
245                            OuterAttributeType::Attribute => "",
246                            OuterAttributeType::DocBlockComment => "*",
247                            OuterAttributeType::DocComment => "/",
248                        },
249                        rustc_errors::Applicability::MachineApplicable,
250                    );
251                }
252                return None;
253            }
254            Err(item_err) => {
255                item_err.cancel();
256            }
257            Ok(None) => {}
258        }
259        Some(replacement_span)
260    }
261
262    pub(super) fn error_on_forbidden_inner_attr(
263        &self,
264        attr_sp: Span,
265        policy: InnerAttrPolicy,
266        suggest_to_outer: bool,
267    ) {
268        if let InnerAttrPolicy::Forbidden(reason) = policy {
269            let mut diag = match reason.as_ref().copied() {
270                Some(InnerAttrForbiddenReason::AfterOuterDocComment { prev_doc_comment_span }) => {
271                    self.dcx()
272                        .struct_span_err(
273                            attr_sp,
274                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("an inner attribute is not permitted following an outer doc comment"))msg!(
275                                "an inner attribute is not permitted following an outer doc comment"
276                            ),
277                        )
278                        .with_span_label(
279                            attr_sp,
280                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("not permitted following an outer doc comment"))msg!("not permitted following an outer doc comment"),
281                        )
282                        .with_span_label(prev_doc_comment_span, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("previous doc comment"))msg!("previous doc comment"))
283                }
284                Some(InnerAttrForbiddenReason::AfterOuterAttribute { prev_outer_attr_sp }) => self
285                    .dcx()
286                    .struct_span_err(
287                        attr_sp,
288                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("an inner attribute is not permitted following an outer attribute"))msg!("an inner attribute is not permitted following an outer attribute"),
289                    )
290                    .with_span_label(attr_sp, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("not permitted following an outer attribute"))msg!("not permitted following an outer attribute"))
291                    .with_span_label(prev_outer_attr_sp, rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("previous outer attribute"))msg!("previous outer attribute")),
292                Some(InnerAttrForbiddenReason::InCodeBlock) | None => self.dcx().struct_span_err(
293                    attr_sp,
294                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("an inner attribute is not permitted in this context"))msg!("an inner attribute is not permitted in this context"),
295                ),
296            };
297
298            diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files"))msg!("inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files"));
299            if self
300                .annotate_following_item_if_applicable(
301                    &mut diag,
302                    attr_sp,
303                    OuterAttributeType::Attribute,
304                    suggest_to_outer,
305                )
306                .is_some()
307            {
308                diag.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("outer attributes, like `#[test]`, annotate the item following them"))msg!(
309                    "outer attributes, like `#[test]`, annotate the item following them"
310                ));
311            };
312            diag.emit();
313        }
314    }
315
316    /// Parses an inner part of an attribute (the path and following tokens).
317    /// The tokens must be either a delimited token stream, or empty token stream,
318    /// or the "legacy" key-value form.
319    ///     PATH `(` TOKEN_STREAM `)`
320    ///     PATH `[` TOKEN_STREAM `]`
321    ///     PATH `{` TOKEN_STREAM `}`
322    ///     PATH
323    ///     PATH `=` UNSUFFIXED_LIT
324    /// The delimiters or `=` are still put into the resulting token stream.
325    pub fn parse_attr_item(
326        &mut self,
327        force_collect: ForceCollect,
328    ) -> PResult<'a, WithTokens<ast::AttrItem>> {
329        if let Some(item) = self.eat_metavar_seq_with_matcher(
330            |mv_kind| #[allow(non_exhaustive_omitted_patterns)] match mv_kind {
    MetaVarKind::Meta { .. } => true,
    _ => false,
}matches!(mv_kind, MetaVarKind::Meta { .. }),
331            |this| this.parse_attr_item(force_collect),
332        ) {
333            return Ok(item);
334        }
335
336        // Attr items don't have attributes.
337        self.collect_tokens(None, AttrWrapper::empty(), force_collect, |this, _empty_attrs| {
338            let is_unsafe = this.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe));
339            let unsafety = if is_unsafe {
340                let unsafe_span = this.prev_token.span;
341                this.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
342                ast::Safety::Unsafe(unsafe_span)
343            } else {
344                ast::Safety::Default
345            };
346
347            let path = this.parse_path(PathStyle::Mod)?;
348            let args = this.parse_attr_args()?;
349            if is_unsafe {
350                this.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
351            }
352            Ok((
353                WithTokens::new(ast::AttrItem {
354                    unsafety,
355                    path,
356                    args: AttrItemKind::Unparsed(args),
357                }),
358                Trailing::No,
359                UsePreAttrPos::No,
360            ))
361        })
362    }
363
364    /// Parses attributes that appear after the opening of an item. These should
365    /// be preceded by an exclamation mark, but we accept and warn about one
366    /// terminated by a semicolon.
367    ///
368    /// Matches `inner_attrs*`.
369    pub fn parse_inner_attributes(&mut self) -> PResult<'a, ast::AttrVec> {
370        let mut attrs = ast::AttrVec::new();
371        loop {
372            let start_pos = self.num_bump_calls;
373            // Only try to parse if it is an inner attribute (has `!`).
374            let attr = if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Pound,
    token_type: crate::parser::token_type::TokenType::Pound,
}exp!(Pound)) && self.look_ahead(1, |t| t == &token::Bang) {
375                Some(self.parse_attribute(InnerAttrPolicy::Permitted)?)
376            } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind {
377                if attr_style == ast::AttrStyle::Inner {
378                    self.bump();
379                    Some(attr::mk_doc_comment(
380                        &self.psess.attr_id_generator,
381                        comment_kind,
382                        attr_style,
383                        data,
384                        self.prev_token.span,
385                    ))
386                } else {
387                    None
388                }
389            } else {
390                None
391            };
392            if let Some(attr) = attr {
393                // If we are currently capturing tokens (i.e. we are within a call to
394                // `Parser::collect_tokens`) record the token positions of this inner attribute,
395                // for possible later processing in a `LazyAttrTokenStream`.
396                if let Capturing::Yes = self.capture_state.capturing {
397                    let end_pos = self.num_bump_calls;
398                    let parser_range = ParserRange(start_pos..end_pos);
399                    self.capture_state.inner_attr_parser_ranges.insert(attr.id, parser_range);
400                }
401                attrs.push(attr);
402            } else {
403                break;
404            }
405        }
406        Ok(attrs)
407    }
408
409    // Note: must be unsuffixed.
410    pub(crate) fn parse_unsuffixed_meta_item_lit(&mut self) -> PResult<'a, ast::MetaItemLit> {
411        let lit = self.parse_meta_item_lit()?;
412        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_parse/src/parser/attr.rs:412",
                        "rustc_parse::parser::attr", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_parse/src/parser/attr.rs"),
                        ::tracing_core::__macro_support::Option::Some(412u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_parse::parser::attr"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("checking if {0:?} is unsuffixed",
                                                    lit) as &dyn Value))])
            });
    } else { ; }
};debug!("checking if {:?} is unsuffixed", lit);
413
414        if !lit.kind.is_unsuffixed() {
415            self.dcx().emit_err(diagnostics::SuffixedLiteralInAttribute { span: lit.span });
416        }
417
418        Ok(lit)
419    }
420
421    /// Matches `COMMASEP(meta_item_inner)`.
422    pub fn parse_meta_seq_top(&mut self) -> PResult<'a, ThinVec<ast::MetaItemInner>> {
423        // Presumably, the majority of the time there will only be one attr.
424        let mut nmis = ThinVec::with_capacity(1);
425        while self.token != token::Eof {
426            nmis.push(self.parse_meta_item_inner()?);
427            if !self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Comma,
    token_type: crate::parser::token_type::TokenType::Comma,
}exp!(Comma)) {
428                break;
429            }
430        }
431        Ok(nmis)
432    }
433
434    /// Parse a meta item per RFC 1559.
435    ///
436    /// ```ebnf
437    /// MetaItem = SimplePath ( '=' UNSUFFIXED_LIT | '(' MetaSeq? ')' )? ;
438    /// MetaSeq = MetaItemInner (',' MetaItemInner)* ','? ;
439    /// ```
440    pub fn parse_meta_item(
441        &mut self,
442        unsafe_allowed: AllowLeadingUnsafe,
443    ) -> PResult<'a, ast::MetaItem> {
444        if let Some(MetaVarKind::Meta { has_meta_form }) = self.token.is_metavar_seq() {
445            return if has_meta_form {
446                let attr_item = self
447                    .eat_metavar_seq(MetaVarKind::Meta { has_meta_form: true }, |this| {
448                        this.parse_attr_item(ForceCollect::No)
449                    })
450                    .unwrap()
451                    .node;
452                Ok(attr_item.meta(attr_item.path.span).unwrap())
453            } else {
454                self.unexpected_any()
455            };
456        }
457
458        let lo = self.token.span;
459        let is_unsafe = if unsafe_allowed == AllowLeadingUnsafe::Yes {
460            self.eat_keyword(crate::parser::token_type::ExpKeywordPair {
    kw: rustc_span::symbol::kw::Unsafe,
    token_type: crate::parser::token_type::TokenType::KwUnsafe,
}exp!(Unsafe))
461        } else {
462            false
463        };
464        let unsafety = if is_unsafe {
465            let unsafe_span = self.prev_token.span;
466            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen))?;
467
468            ast::Safety::Unsafe(unsafe_span)
469        } else {
470            ast::Safety::Default
471        };
472
473        let path = self.parse_path(PathStyle::Mod)?;
474        let kind = self.parse_meta_item_kind()?;
475        if is_unsafe {
476            self.expect(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::CloseParen,
    token_type: crate::parser::token_type::TokenType::CloseParen,
}exp!(CloseParen))?;
477        }
478        let span = lo.to(self.prev_token.span);
479
480        Ok(ast::MetaItem { unsafety, path, kind, span })
481    }
482
483    pub(crate) fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
484        Ok(if self.eat(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::Eq,
    token_type: crate::parser::token_type::TokenType::Eq,
}exp!(Eq)) {
485            ast::MetaItemKind::NameValue(self.parse_unsuffixed_meta_item_lit()?)
486        } else if self.check(crate::parser::token_type::ExpTokenPair {
    tok: rustc_ast::token::OpenParen,
    token_type: crate::parser::token_type::TokenType::OpenParen,
}exp!(OpenParen)) {
487            let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
488            ast::MetaItemKind::List(list)
489        } else {
490            ast::MetaItemKind::Word
491        })
492    }
493
494    /// Parse an inner meta item per RFC 1559.
495    ///
496    /// ```ebnf
497    /// MetaItemInner = UNSUFFIXED_LIT | MetaItem ;
498    /// ```
499    pub fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::MetaItemInner> {
500        match self.parse_unsuffixed_meta_item_lit() {
501            Ok(lit) => return Ok(ast::MetaItemInner::Lit(lit)),
502            Err(err) => err.cancel(), // we provide a better error below
503        }
504
505        match self.parse_meta_item(AllowLeadingUnsafe::No) {
506            Ok(mi) => return Ok(ast::MetaItemInner::MetaItem(mi)),
507            Err(err) => err.cancel(), // we provide a better error below
508        }
509
510        let mut err = diagnostics::InvalidMetaItem {
511            span: self.token.span,
512            descr: super::token_descr(&self.token),
513            quote_ident_sugg: None,
514        };
515
516        // Suggest quoting idents, e.g. in `#[cfg(key = value)]`. We don't use `Token::ident` and
517        // don't `uninterpolate` the token to avoid suggesting anything butchered or questionable
518        // when macro metavariables are involved.
519        if self.prev_token == token::Eq
520            && let token::Ident(..) = self.token.kind
521        {
522            let before = self.token.span.shrink_to_lo();
523            while let token::Ident(..) = self.token.kind {
524                self.bump();
525            }
526            err.quote_ident_sugg = Some(diagnostics::InvalidMetaItemQuoteIdentSugg {
527                before,
528                after: self.prev_token.span.shrink_to_hi(),
529            });
530        }
531
532        Err(self.dcx().create_err(err))
533    }
534}