Skip to main content

rustc_attr_parsing/attributes/diagnostic/
mod.rs

1use std::ops::Range;
2
3use rustc_errors::E0232;
4use rustc_hir::AttrPath;
5use rustc_hir::attrs::diagnostic::{
6    Directive, Filter, FilterFormatString, Flag, FormatArg, FormatString, LitOrArg, Name,
7    NameValue, Piece, Predicate,
8};
9use rustc_macros::Diagnostic;
10use rustc_parse_format::{
11    Argument, FormatSpec, ParseError, ParseMode, Parser, Piece as RpfPiece, Position,
12};
13use rustc_session::lint::builtin::{
14    MALFORMED_DIAGNOSTIC_ATTRIBUTES, MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
15};
16use rustc_span::{Ident, InnerSpan, Span, Symbol, kw, sym};
17use thin_vec::{ThinVec, thin_vec};
18
19use crate::context::AcceptContext;
20use crate::errors::{
21    FormatWarning, IgnoredDiagnosticOption, MalFormedDiagnosticAttributeLint,
22    MissingOptionsForDiagnosticAttribute, NonMetaItemDiagnosticAttribute, WrappedParserError,
23};
24use crate::parser::{ArgParser, MetaItemListParser, MetaItemOrLitParser, MetaItemParser};
25
26pub(crate) mod check_cfg;
27pub(crate) mod do_not_recommend;
28pub(crate) mod on_const;
29pub(crate) mod on_move;
30pub(crate) mod on_unimplemented;
31pub(crate) mod on_unknown;
32pub(crate) mod on_unmatch_args;
33
34#[derive(#[automatically_derived]
impl ::core::marker::Copy for Mode { }Copy, #[automatically_derived]
impl ::core::clone::Clone for Mode {
    #[inline]
    fn clone(&self) -> Mode { *self }
}Clone)]
35pub(crate) enum Mode {
36    /// `#[rustc_on_unimplemented]`
37    RustcOnUnimplemented,
38    /// `#[diagnostic::on_unimplemented]`
39    DiagnosticOnUnimplemented,
40    /// `#[diagnostic::on_const]`
41    DiagnosticOnConst,
42    /// `#[diagnostic::on_move]`
43    DiagnosticOnMove,
44    /// `#[diagnostic::on_unknown]`
45    DiagnosticOnUnknown,
46    /// `#[diagnostic::on_unmatch_args]`
47    DiagnosticOnUnmatchArgs,
48}
49
50impl Mode {
51    fn as_str(&self) -> &'static str {
52        match self {
53            Self::RustcOnUnimplemented => "rustc_on_unimplemented",
54            Self::DiagnosticOnUnimplemented => "diagnostic::on_unimplemented",
55            Self::DiagnosticOnConst => "diagnostic::on_const",
56            Self::DiagnosticOnMove => "diagnostic::on_move",
57            Self::DiagnosticOnUnknown => "diagnostic::on_unknown",
58            Self::DiagnosticOnUnmatchArgs => "diagnostic::on_unmatch_args",
59        }
60    }
61
62    fn expected_options(&self) -> &'static str {
63        const DEFAULT: &str =
64            "at least one of the `message`, `note` and `label` options are expected";
65        match self {
66            Self::RustcOnUnimplemented => {
67                "see <https://rustc-dev-guide.rust-lang.org/diagnostics.html#rustc_on_unimplemented>"
68            }
69            Self::DiagnosticOnUnimplemented => DEFAULT,
70            Self::DiagnosticOnConst => DEFAULT,
71            Self::DiagnosticOnMove => DEFAULT,
72            Self::DiagnosticOnUnknown => DEFAULT,
73            Self::DiagnosticOnUnmatchArgs => DEFAULT,
74        }
75    }
76
77    fn allowed_options(&self) -> &'static str {
78        const DEFAULT: &str = "only `message`, `note` and `label` are allowed as options";
79        match self {
80            Self::RustcOnUnimplemented => {
81                "see <https://rustc-dev-guide.rust-lang.org/diagnostics.html#rustc_on_unimplemented>"
82            }
83            Self::DiagnosticOnUnimplemented => DEFAULT,
84            Self::DiagnosticOnConst => DEFAULT,
85            Self::DiagnosticOnMove => DEFAULT,
86            Self::DiagnosticOnUnknown => DEFAULT,
87            Self::DiagnosticOnUnmatchArgs => DEFAULT,
88        }
89    }
90
91    fn allowed_format_arguments(&self) -> &'static str {
92        match self {
93            Self::RustcOnUnimplemented => {
94                "see <https://rustc-dev-guide.rust-lang.org/diagnostics.html#rustc_on_unimplemented> for allowed format arguments"
95            }
96            Self::DiagnosticOnUnimplemented => {
97                "only `Self` and generics of the trait are allowed as a format argument"
98            }
99            Self::DiagnosticOnConst => {
100                "only `Self` and generics of the implementation are allowed as a format argument"
101            }
102            Self::DiagnosticOnMove => {
103                "only `This`, `Self` and generics of the type are allowed as a format argument"
104            }
105            Self::DiagnosticOnUnknown => {
106                "only `This` is allowed as a format argument, referring to the failed import"
107            }
108            Self::DiagnosticOnUnmatchArgs => {
109                "only `This` is allowed as a format argument, referring to the macro's name"
110            }
111        }
112    }
113}
114
115fn merge_directives(
116    cx: &mut AcceptContext<'_, '_>,
117    first: &mut Option<(Span, Directive)>,
118    later: (Span, Directive),
119) {
120    if let Some((_, first)) = first {
121        if first.is_rustc_attr || later.1.is_rustc_attr {
122            cx.emit_err(DupesNotAllowed);
123        }
124
125        merge(cx, &mut first.message, later.1.message, sym::message);
126        merge(cx, &mut first.label, later.1.label, sym::label);
127        first.notes.extend(later.1.notes);
128    } else {
129        *first = Some(later);
130    }
131}
132
133fn merge<T>(
134    cx: &mut AcceptContext<'_, '_>,
135    first: &mut Option<(Span, T)>,
136    later: Option<(Span, T)>,
137    option_name: Symbol,
138) {
139    match (first, later) {
140        (Some(_) | None, None) => {}
141        (Some((first_span, _)), Some((later_span, _))) => {
142            let first_span = *first_span;
143            cx.emit_lint(
144                MALFORMED_DIAGNOSTIC_ATTRIBUTES,
145                IgnoredDiagnosticOption { first_span, later_span, option_name },
146                later_span,
147            );
148        }
149        (first @ None, Some(later)) => {
150            first.get_or_insert(later);
151        }
152    }
153}
154
155fn parse_list<'p>(
156    cx: &mut AcceptContext<'_, '_>,
157    args: &'p ArgParser,
158    mode: Mode,
159) -> Option<&'p MetaItemListParser> {
160    let span = cx.attr_span;
161    match args {
162        ArgParser::List(items) if items.len() != 0 => return Some(items),
163        ArgParser::List(list) => {
164            // We're dealing with `#[diagnostic::attr()]`.
165            // This can be because that is what the user typed, but that's also what we'd see
166            // if the user used non-metaitem syntax. See `ArgParser::from_attr_args`.
167            cx.emit_lint(
168                MALFORMED_DIAGNOSTIC_ATTRIBUTES,
169                NonMetaItemDiagnosticAttribute,
170                list.span,
171            );
172        }
173        ArgParser::NoArgs => {
174            cx.emit_lint(
175                MALFORMED_DIAGNOSTIC_ATTRIBUTES,
176                MissingOptionsForDiagnosticAttribute {
177                    attribute: mode.as_str(),
178                    options: mode.expected_options(),
179                },
180                span,
181            );
182        }
183        ArgParser::NameValue(_) => {
184            cx.emit_lint(
185                MALFORMED_DIAGNOSTIC_ATTRIBUTES,
186                MalFormedDiagnosticAttributeLint {
187                    attribute: mode.as_str(),
188                    options: mode.allowed_options(),
189                    span,
190                },
191                span,
192            );
193        }
194    }
195    None
196}
197
198fn parse_directive_items<'p>(
199    cx: &mut AcceptContext<'_, '_>,
200    mode: Mode,
201    items: impl Iterator<Item = &'p MetaItemOrLitParser>,
202    is_root: bool,
203) -> Option<Directive> {
204    let mut message: Option<(Span, _)> = None;
205    let mut label: Option<(Span, _)> = None;
206    let mut notes = ThinVec::new();
207    let mut parent_label = None;
208    let mut filters = ThinVec::new();
209
210    for item in items {
211        let span = item.span();
212
213        macro malformed() {{
214            cx.emit_lint(
215                MALFORMED_DIAGNOSTIC_ATTRIBUTES,
216                MalFormedDiagnosticAttributeLint {
217                    attribute: mode.as_str(),
218                    options: mode.allowed_options(),
219                    span,
220                },
221                span,
222            );
223            continue;
224        }}
225
226        macro or_malformed($($code:tt)*) {{
227            let Some(ret) = (
228                try {
229                    $($code)*
230                }
231            ) else {
232                malformed!()
233            };
234            ret
235        }}
236
237        macro duplicate($name: ident, $($first_span:tt)*) {{
238            let first_span = $($first_span)*;
239            cx.emit_lint(
240                MALFORMED_DIAGNOSTIC_ATTRIBUTES,
241                IgnoredDiagnosticOption {
242                    first_span,
243                    later_span: span,
244                    option_name: $name,
245                },
246                span,
247            );
248        }}
249
250        let item: &MetaItemParser = {
    let Some(ret) =
        (try {
                item.meta_item()?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(item.meta_item()?);
251        let name = {
    let Some(ret) =
        (try {
                item.ident()?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(item.ident()?).name;
252
253        // Currently, as of April 2026, all arguments of all diagnostic attrs
254        // must have a value, like `message = "message"`. Thus in a well-formed
255        // diagnostic attribute this is never `None`.
256        //
257        // But we don't assert its presence yet because we don't want to mention it
258        // if someone does something like `#[diagnostic::on_unimplemented(doesnt_exist)]`.
259        // That happens in the big `match` below.
260        let value: Option<Ident> = match item.args().as_name_value() {
261            Some(nv) => Some({
    let Some(ret) =
        (try {
                nv.value_as_ident()?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(nv.value_as_ident()?)),
262            None => None,
263        };
264
265        let mut parse_format = |input: Ident| {
266            let snippet = cx.sess.source_map().span_to_snippet(input.span).ok();
267            let is_snippet = snippet.is_some();
268            match parse_format_string(input.name, snippet, input.span, mode) {
269                Ok((f, warnings)) => {
270                    for warning in warnings {
271                        let (FormatWarning::InvalidSpecifier { span }
272                        | FormatWarning::PositionalArgument { span }
273                        | FormatWarning::IndexedArgument { span }
274                        | FormatWarning::DisallowedPlaceholder { span, .. }) = warning;
275                        cx.emit_lint(MALFORMED_DIAGNOSTIC_FORMAT_LITERALS, warning, span);
276                    }
277
278                    f
279                }
280                Err(e) => {
281                    cx.emit_lint(
282                        MALFORMED_DIAGNOSTIC_FORMAT_LITERALS,
283                        WrappedParserError {
284                            description: e.description,
285                            label: e.label,
286                            span: slice_span(input.span, e.span.clone(), is_snippet),
287                        },
288                        input.span,
289                    );
290                    // We could not parse the input, just use it as-is.
291                    FormatString {
292                        input: input.name,
293                        span: input.span,
294                        pieces: {
    let len = [()].len();
    let mut vec = ::thin_vec::ThinVec::with_capacity(len);
    vec.push(Piece::Lit(input.name));
    vec
}thin_vec![Piece::Lit(input.name)],
295                    }
296                }
297            }
298        };
299        match (mode, name) {
300            (_, sym::message) => {
301                let value = {
    let Some(ret) =
        (try {
                value?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(value?);
302                if let Some(message) = &message {
303                    {
    let first_span = message.0;
    cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
        IgnoredDiagnosticOption {
            first_span,
            later_span: span,
            option_name: name,
        }, span);
}duplicate!(name, message.0)
304                } else {
305                    message = Some((item.span(), parse_format(value)));
306                }
307            }
308            (_, sym::label) => {
309                let value = {
    let Some(ret) =
        (try {
                value?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(value?);
310                if let Some(label) = &label {
311                    {
    let first_span = label.0;
    cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
        IgnoredDiagnosticOption {
            first_span,
            later_span: span,
            option_name: name,
        }, span);
}duplicate!(name, label.0)
312                } else {
313                    label = Some((item.span(), parse_format(value)));
314                }
315            }
316            (_, sym::note) => {
317                let value = {
    let Some(ret) =
        (try {
                value?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(value?);
318                notes.push(parse_format(value))
319            }
320            (Mode::RustcOnUnimplemented, sym::parent_label) => {
321                let value = {
    let Some(ret) =
        (try {
                value?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(value?);
322                if parent_label.is_none() {
323                    parent_label = Some(parse_format(value));
324                } else {
325                    {
    let first_span = span;
    cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
        IgnoredDiagnosticOption {
            first_span,
            later_span: span,
            option_name: name,
        }, span);
}duplicate!(name, span)
326                }
327            }
328            (Mode::RustcOnUnimplemented, sym::on) => {
329                if is_root {
330                    let items = {
    let Some(ret) =
        (try {
                item.args().as_list()?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(item.args().as_list()?);
331                    let mut iter = items.mixed();
332                    let filter: &MetaItemOrLitParser = match iter.next() {
333                        Some(c) => c,
334                        None => {
335                            cx.emit_err(InvalidOnClause::Empty { span });
336                            continue;
337                        }
338                    };
339
340                    let filter = parse_filter(filter);
341
342                    if items.len() < 2 {
343                        // Something like `#[rustc_on_unimplemented(on(.., /* nothing */))]`
344                        // There's a filter but no directive behind it, this is a mistake.
345                        {
    cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
        MalFormedDiagnosticAttributeLint {
            attribute: mode.as_str(),
            options: mode.allowed_options(),
            span,
        }, span);
    continue;
};malformed!();
346                    }
347
348                    match filter {
349                        Ok(filter) => {
350                            let directive =
351                                {
    let Some(ret) =
        (try {
                parse_directive_items(cx, mode, iter, false)?
            }) else {
            {
                cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
                    MalFormedDiagnosticAttributeLint {
                        attribute: mode.as_str(),
                        options: mode.allowed_options(),
                        span,
                    }, span);
                continue;
            }
        };
    ret
}or_malformed!(parse_directive_items(cx, mode, iter, false)?);
352                            filters.push((filter, directive));
353                        }
354                        Err(e) => {
355                            cx.emit_err(e);
356                        }
357                    }
358                } else {
359                    {
    cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
        MalFormedDiagnosticAttributeLint {
            attribute: mode.as_str(),
            options: mode.allowed_options(),
            span,
        }, span);
    continue;
};malformed!();
360                }
361            }
362
363            _other => {
364                {
    cx.emit_lint(MALFORMED_DIAGNOSTIC_ATTRIBUTES,
        MalFormedDiagnosticAttributeLint {
            attribute: mode.as_str(),
            options: mode.allowed_options(),
            span,
        }, span);
    continue;
};malformed!();
365            }
366        }
367    }
368
369    Some(Directive {
370        is_rustc_attr: #[allow(non_exhaustive_omitted_patterns)] match mode {
    Mode::RustcOnUnimplemented => true,
    _ => false,
}matches!(mode, Mode::RustcOnUnimplemented),
371        filters,
372        message,
373        label,
374        notes,
375        parent_label,
376    })
377}
378
379pub(crate) fn parse_format_string(
380    input: Symbol,
381    snippet: Option<String>,
382    span: Span,
383    mode: Mode,
384) -> Result<(FormatString, Vec<FormatWarning>), ParseError> {
385    let s = input.as_str();
386    let mut parser = Parser::new(s, None, snippet, false, ParseMode::Diagnostic);
387    let pieces: Vec<_> = parser.by_ref().collect();
388
389    if let Some(err) = parser.errors.into_iter().next() {
390        return Err(err);
391    }
392    let mut warnings = Vec::new();
393
394    let pieces = pieces
395        .into_iter()
396        .map(|piece| match piece {
397            RpfPiece::Lit(lit) => Piece::Lit(Symbol::intern(lit)),
398            RpfPiece::NextArgument(arg) => {
399                warn_on_format_spec(&arg.format, &mut warnings, span, parser.is_source_literal);
400                let arg = parse_arg(&arg, mode, &mut warnings, span, parser.is_source_literal);
401                Piece::Arg(arg)
402            }
403        })
404        .collect();
405
406    Ok((FormatString { input, pieces, span }, warnings))
407}
408
409fn parse_arg(
410    arg: &Argument<'_>,
411    mode: Mode,
412    warnings: &mut Vec<FormatWarning>,
413    input_span: Span,
414    is_source_literal: bool,
415) -> FormatArg {
416    let span = slice_span(input_span, arg.position_span.clone(), is_source_literal);
417
418    match arg.position {
419        // Something like "hello {name}"
420        Position::ArgumentNamed(name) => match (mode, Symbol::intern(name)) {
421            (Mode::RustcOnUnimplemented, sym::ItemContext) => FormatArg::ItemContext,
422
423            // Like `{This}`, but sugared.
424            // FIXME(mejrs) maybe rename/rework this or something
425            // if we want to apply this to other attrs?
426            (Mode::RustcOnUnimplemented, sym::Trait) => FormatArg::Trait,
427
428            // Some diagnostic attributes can use `{This}` to refer to the annotated item.
429            // For those that don't, we continue and maybe use it as a generic parameter.
430            //
431            // FIXME(mejrs) `DiagnosticOnUnimplemented` is intentionally not here;
432            // that requires lang approval which is best kept for a standalone PR.
433            (
434                Mode::RustcOnUnimplemented
435                | Mode::DiagnosticOnUnknown
436                | Mode::DiagnosticOnMove
437                | Mode::DiagnosticOnUnmatchArgs,
438                sym::This,
439            ) => FormatArg::This,
440
441            // `{Self}`; the self type.
442            // - For trait declaration attributes that's the type that does not implement it.
443            // - for trait impl attributes, the implemented for type.
444            // - For ADT attributes, that's the type (which will be identical to `{This}`)
445            // - For everything else it doesn't make sense.
446            (
447                Mode::RustcOnUnimplemented
448                | Mode::DiagnosticOnUnimplemented
449                | Mode::DiagnosticOnMove
450                | Mode::DiagnosticOnConst,
451                kw::SelfUpper,
452            ) => FormatArg::SelfUpper,
453
454            // Generic parameters.
455            // FIXME(mejrs) unfortunately, all the "special" symbols above might fall through,
456            // but at this time we are not aware of what generic parameters the trait actually has.
457            // If we find `ItemContext` or something we have to assume that's a generic parameter.
458            // We lint against that in `check_attr.rs` though.
459            (
460                Mode::RustcOnUnimplemented
461                | Mode::DiagnosticOnUnimplemented
462                | Mode::DiagnosticOnMove
463                | Mode::DiagnosticOnConst,
464                generic_param,
465            ) => FormatArg::GenericParam { generic_param, span },
466
467            // Generics are explicitly not allowed, we print those back as is.
468            (Mode::DiagnosticOnUnknown | Mode::DiagnosticOnUnmatchArgs, as_is) => {
469                warnings.push(FormatWarning::DisallowedPlaceholder {
470                    span,
471                    attr: mode.as_str(),
472                    allowed: mode.allowed_format_arguments(),
473                });
474                return FormatArg::AsIs(Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}}}", as_is))
    })format!("{{{as_is}}}")));
475            }
476        },
477
478        // `{:1}` and `{}` are ignored
479        Position::ArgumentIs(idx) => {
480            warnings.push(FormatWarning::IndexedArgument { span });
481            FormatArg::AsIs(Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}}}", idx))
    })format!("{{{idx}}}")))
482        }
483        Position::ArgumentImplicitlyIs(_) => {
484            warnings.push(FormatWarning::PositionalArgument { span });
485            FormatArg::AsIs(sym::empty_braces)
486        }
487    }
488}
489
490/// `#[rustc_on_unimplemented]` and `#[diagnostic::...]` don't actually do anything
491/// with specifiers, so emit a warning if they are used.
492fn warn_on_format_spec(
493    spec: &FormatSpec<'_>,
494    warnings: &mut Vec<FormatWarning>,
495    input_span: Span,
496    is_source_literal: bool,
497) {
498    if spec.ty != "" {
499        let span = spec
500            .ty_span
501            .as_ref()
502            .map(|inner| slice_span(input_span, inner.clone(), is_source_literal))
503            .unwrap_or(input_span);
504        warnings.push(FormatWarning::InvalidSpecifier { span })
505    }
506}
507
508fn slice_span(input: Span, Range { start, end }: Range<usize>, is_source_literal: bool) -> Span {
509    if is_source_literal { input.from_inner(InnerSpan { start, end }) } else { input }
510}
511
512pub(crate) fn parse_filter(input: &MetaItemOrLitParser) -> Result<Filter, InvalidOnClause> {
513    let span = input.span();
514    let pred = parse_predicate(input)?;
515    Ok(Filter { span, pred })
516}
517
518fn parse_predicate(input: &MetaItemOrLitParser) -> Result<Predicate, InvalidOnClause> {
519    let Some(meta_item) = input.meta_item() else {
520        return Err(InvalidOnClause::UnsupportedLiteral { span: input.span() });
521    };
522
523    let Some(predicate) = meta_item.ident() else {
524        return Err(InvalidOnClause::ExpectedIdentifier {
525            span: meta_item.path().span(),
526            path: meta_item.path().get_attribute_path(),
527        });
528    };
529
530    match meta_item.args() {
531        ArgParser::List(mis) => match predicate.name {
532            sym::any => Ok(Predicate::Any(parse_predicate_sequence(mis)?)),
533            sym::all => Ok(Predicate::All(parse_predicate_sequence(mis)?)),
534            sym::not => {
535                if let Some(single) = mis.as_single() {
536                    Ok(Predicate::Not(Box::new(parse_predicate(single)?)))
537                } else {
538                    Err(InvalidOnClause::ExpectedOnePredInNot { span: mis.span })
539                }
540            }
541            invalid_pred => {
542                Err(InvalidOnClause::InvalidPredicate { span: predicate.span, invalid_pred })
543            }
544        },
545        ArgParser::NameValue(p) => {
546            let Some(value) = p.value_as_ident() else {
547                return Err(InvalidOnClause::UnsupportedLiteral { span: p.args_span() });
548            };
549            let name = parse_name(predicate.name);
550            let value = parse_filter_format(value.name);
551            let kv = NameValue { name, value };
552            Ok(Predicate::Match(kv))
553        }
554        ArgParser::NoArgs => {
555            let flag = parse_flag(predicate)?;
556            Ok(Predicate::Flag(flag))
557        }
558    }
559}
560
561fn parse_predicate_sequence(
562    sequence: &MetaItemListParser,
563) -> Result<ThinVec<Predicate>, InvalidOnClause> {
564    sequence.mixed().map(parse_predicate).collect()
565}
566
567fn parse_flag(Ident { name, span }: Ident) -> Result<Flag, InvalidOnClause> {
568    match name {
569        sym::crate_local => Ok(Flag::CrateLocal),
570        sym::direct => Ok(Flag::Direct),
571        sym::from_desugaring => Ok(Flag::FromDesugaring),
572        invalid_flag => Err(InvalidOnClause::InvalidFlag { invalid_flag, span }),
573    }
574}
575
576fn parse_name(name: Symbol) -> Name {
577    match name {
578        kw::SelfUpper => Name::SelfUpper,
579        sym::from_desugaring => Name::FromDesugaring,
580        sym::cause => Name::Cause,
581        generic => Name::GenericArg(generic),
582    }
583}
584
585fn parse_filter_format(input: Symbol) -> FilterFormatString {
586    let pieces = Parser::new(input.as_str(), None, None, false, ParseMode::Diagnostic)
587        .map(|p| match p {
588            RpfPiece::Lit(s) => LitOrArg::Lit(Symbol::intern(s)),
589            // We just ignore formatspecs here
590            RpfPiece::NextArgument(a) => match a.position {
591                // In `TypeErrCtxt::on_unimplemented_note` we substitute `"{integral}"` even
592                // if the integer type has been resolved, to allow targeting all integers.
593                // `"{integer}"` and `"{float}"` come from numerics that haven't been inferred yet,
594                // from the `Display` impl of `InferTy` to be precise.
595                // `"{union|enum|struct}"` is used as a special selector for ADTs.
596                //
597                // Don't try to format these later!
598                Position::ArgumentNamed(
599                    arg @ ("integer" | "integral" | "float" | "union" | "enum" | "struct"),
600                ) => LitOrArg::Lit(Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}}}", arg))
    })format!("{{{arg}}}"))),
601
602                Position::ArgumentNamed(arg) => LitOrArg::Arg(Symbol::intern(arg)),
603                Position::ArgumentImplicitlyIs(_) => LitOrArg::Lit(sym::empty_braces),
604                Position::ArgumentIs(idx) => LitOrArg::Lit(Symbol::intern(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}}}", idx))
    })format!("{{{idx}}}"))),
605            },
606        })
607        .collect();
608    FilterFormatString { pieces }
609}
610
611#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            InvalidOnClause where G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    InvalidOnClause::Empty { span: __binding_0 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("empty `on`-clause in `#[rustc_on_unimplemented]`")));
                        diag.code(E0232);
                        ;
                        diag.span(__binding_0);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("empty `on`-clause here")));
                        diag
                    }
                    InvalidOnClause::ExpectedOnePredInNot { span: __binding_0 }
                        => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("expected a single predicate in `not(..)`")));
                        diag.code(E0232);
                        ;
                        diag.span(__binding_0);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unexpected quantity of predicates here")));
                        diag
                    }
                    InvalidOnClause::UnsupportedLiteral { span: __binding_0 } =>
                        {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("literals inside `on`-clauses are not supported")));
                        diag.code(E0232);
                        ;
                        diag.span(__binding_0);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("unexpected literal here")));
                        diag
                    }
                    InvalidOnClause::ExpectedIdentifier {
                        span: __binding_0, path: __binding_1 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("expected an identifier inside this `on`-clause")));
                        diag.code(E0232);
                        ;
                        diag.arg("path", __binding_1);
                        diag.span(__binding_0);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("expected an identifier here, not `{$path}`")));
                        diag
                    }
                    InvalidOnClause::InvalidPredicate {
                        span: __binding_0, invalid_pred: __binding_1 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this predicate is invalid")));
                        diag.code(E0232);
                        ;
                        diag.arg("invalid_pred", __binding_1);
                        diag.span(__binding_0);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("expected one of `any`, `all` or `not` here, not `{$invalid_pred}`")));
                        diag
                    }
                    InvalidOnClause::InvalidFlag {
                        span: __binding_0, invalid_flag: __binding_1 } => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("invalid flag in `on`-clause")));
                        diag.code(E0232);
                        ;
                        diag.arg("invalid_flag", __binding_1);
                        diag.span(__binding_0);
                        diag.span_label(__binding_0,
                            rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("expected one of the `crate_local`, `direct` or `from_desugaring` flags, not `{$invalid_flag}`")));
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
612pub(crate) enum InvalidOnClause {
613    #[diag("empty `on`-clause in `#[rustc_on_unimplemented]`", code = E0232)]
614    Empty {
615        #[primary_span]
616        #[label("empty `on`-clause here")]
617        span: Span,
618    },
619    #[diag("expected a single predicate in `not(..)`", code = E0232)]
620    ExpectedOnePredInNot {
621        #[primary_span]
622        #[label("unexpected quantity of predicates here")]
623        span: Span,
624    },
625    #[diag("literals inside `on`-clauses are not supported", code = E0232)]
626    UnsupportedLiteral {
627        #[primary_span]
628        #[label("unexpected literal here")]
629        span: Span,
630    },
631    #[diag("expected an identifier inside this `on`-clause", code = E0232)]
632    ExpectedIdentifier {
633        #[primary_span]
634        #[label("expected an identifier here, not `{$path}`")]
635        span: Span,
636        path: AttrPath,
637    },
638    #[diag("this predicate is invalid", code = E0232)]
639    InvalidPredicate {
640        #[primary_span]
641        #[label("expected one of `any`, `all` or `not` here, not `{$invalid_pred}`")]
642        span: Span,
643        invalid_pred: Symbol,
644    },
645    #[diag("invalid flag in `on`-clause", code = E0232)]
646    InvalidFlag {
647        #[primary_span]
648        #[label(
649            "expected one of the `crate_local`, `direct` or `from_desugaring` flags, not `{$invalid_flag}`"
650        )]
651        span: Span,
652        invalid_flag: Symbol,
653    },
654}
655
656#[derive(const _: () =
    {
        impl<'_sess, G> rustc_errors::Diagnostic<'_sess, G> for
            DupesNotAllowed where G: rustc_errors::EmissionGuarantee {
            #[track_caller]
            fn into_diag(self, dcx: rustc_errors::DiagCtxtHandle<'_sess>,
                level: rustc_errors::Level) -> rustc_errors::Diag<'_sess, G> {
                match self {
                    DupesNotAllowed => {
                        let mut diag =
                            rustc_errors::Diag::new(dcx, level,
                                rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("using multiple `rustc_on_unimplemented` (or mixing it with `diagnostic::on_unimplemented`) is not supported")));
                        ;
                        diag
                    }
                }
            }
        }
    };Diagnostic)]
657#[diag(
658    "using multiple `rustc_on_unimplemented` (or mixing it with `diagnostic::on_unimplemented`) is not supported"
659)]
660pub(crate) struct DupesNotAllowed;