Skip to main content

rustc_lint/
non_fmt_panic.rs

1use rustc_ast as ast;
2use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level, msg};
3use rustc_hir::def_id::DefId;
4use rustc_hir::{self as hir, LangItem};
5use rustc_infer::infer::TyCtxtInferExt;
6use rustc_middle::{bug, ty};
7use rustc_parse_format::{ParseMode, Parser, Piece};
8use rustc_session::lint::fcw;
9use rustc_session::{declare_lint, declare_lint_pass};
10use rustc_span::{InnerSpan, Span, Symbol, hygiene, sym};
11use rustc_trait_selection::infer::InferCtxtExt;
12
13use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused};
14use crate::{LateContext, LateLintPass, LintContext};
15
16#[doc =
r" The `non_fmt_panics` lint detects `panic!(..)` invocations where the first"]
#[doc = r" argument is not a formatting string."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run,edition2018"]
#[doc = r#" panic!("{}");"#]
#[doc = r" panic!(123);"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" In Rust 2018 and earlier, `panic!(x)` directly uses `x` as the message."]
#[doc =
r#" That means that `panic!("{}")` panics with the message `"{}"` instead"#]
#[doc =
r" of using it as a formatting string, and `panic!(123)` will panic with"]
#[doc = r" an `i32` as message."]
#[doc = r""]
#[doc = r" Rust 2021 always interprets the first argument as format string."]
static NON_FMT_PANICS: &::rustc_lint_defs::Lint =
    &::rustc_lint_defs::Lint {
            name: "NON_FMT_PANICS",
            default_level: ::rustc_lint_defs::Warn,
            desc: "detect single-argument panic!() invocations in which the argument is not a format string",
            is_externally_loaded: false,
            report_in_external_macro: true,
            future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
                    reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionSemanticsChange(::rustc_lint_defs::EditionFcw {
                            edition: rustc_span::edition::Edition::Edition2021,
                            page_slug: "panic-macro-consistency",
                        }),
                    explain_reason: false,
                    ..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
                }),
            ..::rustc_lint_defs::Lint::default_fields_for_macro()
        };declare_lint! {
17    /// The `non_fmt_panics` lint detects `panic!(..)` invocations where the first
18    /// argument is not a formatting string.
19    ///
20    /// ### Example
21    ///
22    /// ```rust,no_run,edition2018
23    /// panic!("{}");
24    /// panic!(123);
25    /// ```
26    ///
27    /// {{produces}}
28    ///
29    /// ### Explanation
30    ///
31    /// In Rust 2018 and earlier, `panic!(x)` directly uses `x` as the message.
32    /// That means that `panic!("{}")` panics with the message `"{}"` instead
33    /// of using it as a formatting string, and `panic!(123)` will panic with
34    /// an `i32` as message.
35    ///
36    /// Rust 2021 always interprets the first argument as format string.
37    NON_FMT_PANICS,
38    Warn,
39    "detect single-argument panic!() invocations in which the argument is not a format string",
40    @future_incompatible = FutureIncompatibleInfo {
41        reason: fcw!(EditionSemanticsChange 2021 "panic-macro-consistency"),
42        explain_reason: false,
43    };
44    report_in_external_macro
45}
46
47pub struct NonPanicFmt;
#[automatically_derived]
impl ::core::marker::Copy for NonPanicFmt { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NonPanicFmt { }
#[automatically_derived]
impl ::core::clone::Clone for NonPanicFmt {
    #[inline]
    fn clone(&self) -> NonPanicFmt { *self }
}
impl ::rustc_lint_defs::LintPass for NonPanicFmt {
    fn name(&self) -> &'static str { "NonPanicFmt" }
    fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_FMT_PANICS]))
    }
}
impl NonPanicFmt {
    #[allow(unused)]
    pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                [NON_FMT_PANICS]))
    }
}declare_lint_pass!(NonPanicFmt => [NON_FMT_PANICS]);
48
49impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
50    fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
51        if let hir::ExprKind::Call(f, [arg]) = &expr.kind
52            && let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind()
53        {
54            let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id);
55
56            if cx.tcx.is_lang_item(def_id, LangItem::BeginPanic)
57                || cx.tcx.is_lang_item(def_id, LangItem::Panic)
58                || f_diagnostic_name == Some(sym::panic_str_2015)
59            {
60                if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
61                    if #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(id)
    {
    Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro) => true,
    _ => false,
}matches!(
62                        cx.tcx.get_diagnostic_name(id),
63                        Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro)
64                    ) {
65                        check_panic(cx, f, arg);
66                    }
67                }
68            } else if f_diagnostic_name == Some(sym::unreachable_display) {
69                if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id
70                    && cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id)
71                {
72                    check_panic(
73                        cx,
74                        f,
75                        // This is safe because we checked above that the callee is indeed
76                        // unreachable_display
77                        match &arg.kind {
78                            // Get the borrowed arg not the borrow
79                            hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg,
80                            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("call to unreachable_display without borrow"))bug!("call to unreachable_display without borrow"),
81                        },
82                    );
83                }
84            }
85        }
86    }
87}
88
89struct PanicMessageNotLiteral<'a, 'tcx> {
90    arg_span: Span,
91    symbol: Symbol,
92    span: Span,
93    arg_macro: Option<DefId>,
94    cx: &'a LateContext<'tcx>,
95    arg: &'tcx hir::Expr<'tcx>,
96    panic: Option<Symbol>,
97}
98
99impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for PanicMessageNotLiteral<'b, 'tcx> {
100    fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
101        let Self { arg_span, symbol, span, arg_macro, cx, arg, panic } = self;
102        let mut lint = Diag::new(dcx, level, "panic message is not a string literal")
103            .with_arg("name", symbol)
104            .with_note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this usage of `{$name}!()` is deprecated; it will be a hard error in Rust 2021"))msg!("this usage of `{$name}!()` is deprecated; it will be a hard error in Rust 2021"))
105            .with_note("for more information, see <https://doc.rust-lang.org/edition-guide/rust-2021/panic-macro-consistency.html>");
106        if !is_arg_inside_call(arg_span, span) {
107            // No clue where this argument is coming from.
108            return lint;
109        }
110        if arg_macro.is_some_and(|id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
111            // A case of `panic!(format!(..))`.
112            lint.note(rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the `{$name}!()` macro supports formatting, so there's no need for the `format!()` macro here"))msg!("the `{$name}!()` macro supports formatting, so there's no need for the `format!()` macro here"));
113            if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
114                lint.multipart_suggestion(
115                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("remove the `format!(..)` macro call"))msg!("remove the `format!(..)` macro call"),
116                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(arg_span.until(open.shrink_to_hi()), "".into()),
                (close.until(arg_span.shrink_to_hi()), "".into())]))vec![
117                        (arg_span.until(open.shrink_to_hi()), "".into()),
118                        (close.until(arg_span.shrink_to_hi()), "".into()),
119                    ],
120                    Applicability::MachineApplicable,
121                );
122            }
123        } else {
124            let ty = cx.typeck_results().expr_ty(arg);
125            // If this is a &str or String, we can confidently give the `"{}", ` suggestion.
126            let is_str = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
    ty::Ref(_, r, _) if r.is_str() => true,
    _ => false,
}matches!(
127                ty.kind(),
128                ty::Ref(_, r, _) if r.is_str(),
129            ) || #[allow(non_exhaustive_omitted_patterns)] match ty.ty_adt_def() {
    Some(ty_def) if cx.tcx.is_lang_item(ty_def.did(), LangItem::String) =>
        true,
    _ => false,
}matches!(
130                ty.ty_adt_def(),
131                Some(ty_def) if cx.tcx.is_lang_item(ty_def.did(), LangItem::String),
132            );
133
134            let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env());
135            let suggest_display = is_str
136                || cx
137                    .tcx
138                    .get_diagnostic_item(sym::Display)
139                    .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
140            let suggest_debug = !suggest_display
141                && cx
142                    .tcx
143                    .get_diagnostic_item(sym::Debug)
144                    .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
145
146            let suggest_panic_any = !is_str && panic == Some(sym::std_panic_macro);
147
148            let fmt_applicability = if suggest_panic_any {
149                // If we can use panic_any, use that as the MachineApplicable suggestion.
150                Applicability::MaybeIncorrect
151            } else {
152                // If we don't suggest panic_any, using a format string is our best bet.
153                Applicability::MachineApplicable
154            };
155
156            if suggest_display {
157                lint.span_suggestion_verbose(
158                    arg_span.shrink_to_lo(),
159                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("add a \"{\"{\"}{\"}\"}\" format string to `Display` the message"))msg!(r#"add a "{"{"}{"}"}" format string to `Display` the message"#),
160                    "\"{}\", ",
161                    fmt_applicability,
162                );
163            } else if suggest_debug {
164                lint.arg("ty", ty);
165                lint.span_suggestion_verbose(
166                    arg_span.shrink_to_lo(),
167                    rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("add a \"{\"{\"}:?{\"}\"}\" format string to use the `Debug` implementation of `{$ty}`"))msg!(r#"add a "{"{"}:?{"}"}" format string to use the `Debug` implementation of `{$ty}`"#),
168                    "\"{:?}\", ",
169                    fmt_applicability,
170                );
171            }
172
173            if suggest_panic_any {
174                if let Some((open, close, del)) = find_delimiters(cx, span) {
175                    lint.arg("already_suggested", suggest_display || suggest_debug);
176                    lint.multipart_suggestion(
177                        rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$already_suggested ->\n                                [true] or use\n                                *[false] use\n                            } std::panic::panic_any instead"))msg!(
178                            "{$already_suggested ->
179                                [true] or use
180                                *[false] use
181                            } std::panic::panic_any instead"
182                        ),
183                        if del == '(' {
184                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.until(open), "std::panic::panic_any".into())]))vec![(span.until(open), "std::panic::panic_any".into())]
185                        } else {
186                            ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [(span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
                (close, ")".into())]))vec![
187                                (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
188                                (close, ")".into()),
189                            ]
190                        },
191                        Applicability::MachineApplicable,
192                    );
193                }
194            }
195        }
196        lint
197    }
198}
199
200fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
201    if let hir::ExprKind::Lit(lit) = &arg.kind {
202        if let ast::LitKind::Str(sym, _) = lit.node {
203            // The argument is a string literal.
204            check_panic_str(cx, f, arg, sym.as_str());
205            return;
206        }
207    }
208
209    // The argument is *not* a string literal.
210
211    let (span, panic, symbol) = panic_call(cx, f);
212
213    if span.in_external_macro(cx.sess().source_map()) {
214        // Nothing that can be done about it in the current crate.
215        return;
216    }
217
218    // Find the span of the argument to `panic!()` or `unreachable!`, before expansion in the
219    // case of `panic!(some_macro!())` or `unreachable!(some_macro!())`.
220    // We don't use source_callsite(), because this `panic!(..)` might itself
221    // be expanded from another macro, in which case we want to stop at that
222    // expansion.
223    let mut arg_span = arg.span;
224    let mut arg_macro = None;
225    while !span.contains(arg_span) {
226        let ctxt = arg_span.ctxt();
227        if ctxt.is_root() {
228            break;
229        }
230        let expn = ctxt.outer_expn_data();
231        arg_macro = expn.macro_def_id;
232        arg_span = expn.call_site;
233    }
234
235    cx.emit_span_lint(
236        NON_FMT_PANICS,
237        arg_span,
238        PanicMessageNotLiteral { arg_span, symbol, span, arg_macro, cx, arg, panic },
239    );
240}
241
242fn check_panic_str<'tcx>(
243    cx: &LateContext<'tcx>,
244    f: &'tcx hir::Expr<'tcx>,
245    arg: &'tcx hir::Expr<'tcx>,
246    fmt: &str,
247) {
248    if !fmt.contains(&['{', '}']) {
249        // No brace, no problem.
250        return;
251    }
252
253    let (span, _, _) = panic_call(cx, f);
254
255    let sm = cx.sess().source_map();
256    if span.in_external_macro(sm) && arg.span.in_external_macro(sm) {
257        // Nothing that can be done about it in the current crate.
258        return;
259    }
260
261    let fmt_span = arg.span.source_callsite();
262
263    let (snippet, style) = match sm.span_to_snippet(fmt_span) {
264        Ok(snippet) => {
265            // Count the number of `#`s between the `r` and `"`.
266            let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
267            (Some(snippet), style)
268        }
269        Err(_) => (None, None),
270    };
271
272    let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
273    let n_arguments = (&mut fmt_parser).filter(|a| #[allow(non_exhaustive_omitted_patterns)] match a {
    Piece::NextArgument(_) => true,
    _ => false,
}matches!(a, Piece::NextArgument(_))).count();
274
275    if n_arguments > 0 && fmt_parser.errors.is_empty() {
276        let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
277            [] => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [fmt_span]))vec![fmt_span],
278            v => v
279                .iter()
280                .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
281                .collect(),
282        };
283        cx.emit_span_lint(
284            NON_FMT_PANICS,
285            arg_spans,
286            NonFmtPanicUnused {
287                count: n_arguments,
288                suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span),
289            },
290        );
291    } else {
292        let brace_spans: Option<Vec<_>> =
293            snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
294                s.char_indices()
295                    .filter(|&(_, c)| c == '{' || c == '}')
296                    .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
297                    .collect()
298            });
299        let count = brace_spans.as_ref().map(|v| v.len()).unwrap_or(/* any number >1 */ 2);
300        cx.emit_span_lint(
301            NON_FMT_PANICS,
302            brace_spans.unwrap_or_else(|| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [span]))vec![span]),
303            NonFmtPanicBraces {
304                count,
305                suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span.shrink_to_lo()),
306            },
307        );
308    }
309}
310
311/// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
312/// and the type of (opening) delimiter used.
313fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> {
314    let snippet = cx.sess().source_map().span_to_snippet(span).ok()?;
315    let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
316    let close = snippet.rfind(|c| ")]}".contains(c))?;
317    Some((
318        span.from_inner(InnerSpan { start: open, end: open + 1 }),
319        span.from_inner(InnerSpan { start: close, end: close + 1 }),
320        open_ch,
321    ))
322}
323
324fn panic_call<'tcx>(
325    cx: &LateContext<'tcx>,
326    f: &'tcx hir::Expr<'tcx>,
327) -> (Span, Option<Symbol>, Symbol) {
328    let mut expn = f.span.ctxt().outer_expn_data();
329
330    let mut panic_macro = None;
331
332    // Unwrap more levels of macro expansion, as panic_2015!()
333    // was likely expanded from panic!() and possibly from
334    // [debug_]assert!().
335    loop {
336        let parent = expn.call_site.ctxt().outer_expn_data();
337        let Some(id) = parent.macro_def_id else { break };
338        let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
339        if !#[allow(non_exhaustive_omitted_patterns)] match name {
    sym::core_panic_macro | sym::std_panic_macro | sym::assert_macro |
        sym::debug_assert_macro | sym::unreachable_macro => true,
    _ => false,
}matches!(
340            name,
341            sym::core_panic_macro
342                | sym::std_panic_macro
343                | sym::assert_macro
344                | sym::debug_assert_macro
345                | sym::unreachable_macro
346        ) {
347            break;
348        }
349        expn = parent;
350        panic_macro = Some(name);
351    }
352
353    let macro_symbol =
354        if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
355    (expn.call_site, panic_macro, macro_symbol)
356}
357
358fn is_arg_inside_call(arg: Span, call: Span) -> bool {
359    // We only add suggestions if the argument we're looking at appears inside the
360    // panic call in the source file, to avoid invalid suggestions when macros are involved.
361    // We specifically check for the spans to not be identical, as that happens sometimes when
362    // proc_macros lie about spans and apply the same span to all the tokens they produce.
363    call.contains(arg) && !call.source_equal(arg)
364}