rustc_lint/
non_fmt_panic.rs

1use rustc_ast as ast;
2use rustc_errors::Applicability;
3use rustc_hir::{self as hir, LangItem};
4use rustc_infer::infer::TyCtxtInferExt;
5use rustc_middle::{bug, ty};
6use rustc_parse_format::{ParseMode, Parser, Piece};
7use rustc_session::lint::FutureIncompatibilityReason;
8use rustc_session::{declare_lint, declare_lint_pass};
9use rustc_span::edition::Edition;
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, fluent_generated as fluent};
15
16declare_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: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2021),
42        explain_reason: false,
43    };
44    report_in_external_macro
45}
46
47declare_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            if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
53                let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id);
54
55                if cx.tcx.is_lang_item(def_id, LangItem::BeginPanic)
56                    || cx.tcx.is_lang_item(def_id, LangItem::Panic)
57                    || f_diagnostic_name == Some(sym::panic_str_2015)
58                {
59                    if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
60                        if matches!(
61                            cx.tcx.get_diagnostic_name(id),
62                            Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro)
63                        ) {
64                            check_panic(cx, f, arg);
65                        }
66                    }
67                } else if f_diagnostic_name == Some(sym::unreachable_display) {
68                    if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
69                        if cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id) {
70                            check_panic(
71                                cx,
72                                f,
73                                // This is safe because we checked above that the callee is indeed
74                                // unreachable_display
75                                match &arg.kind {
76                                    // Get the borrowed arg not the borrow
77                                    hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg,
78                                    _ => bug!("call to unreachable_display without borrow"),
79                                },
80                            );
81                        }
82                    }
83                }
84            }
85        }
86    }
87}
88
89fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
90    if let hir::ExprKind::Lit(lit) = &arg.kind {
91        if let ast::LitKind::Str(sym, _) = lit.node {
92            // The argument is a string literal.
93            check_panic_str(cx, f, arg, sym.as_str());
94            return;
95        }
96    }
97
98    // The argument is *not* a string literal.
99
100    let (span, panic, symbol) = panic_call(cx, f);
101
102    if span.in_external_macro(cx.sess().source_map()) {
103        // Nothing that can be done about it in the current crate.
104        return;
105    }
106
107    // Find the span of the argument to `panic!()` or `unreachable!`, before expansion in the
108    // case of `panic!(some_macro!())` or `unreachable!(some_macro!())`.
109    // We don't use source_callsite(), because this `panic!(..)` might itself
110    // be expanded from another macro, in which case we want to stop at that
111    // expansion.
112    let mut arg_span = arg.span;
113    let mut arg_macro = None;
114    while !span.contains(arg_span) {
115        let ctxt = arg_span.ctxt();
116        if ctxt.is_root() {
117            break;
118        }
119        let expn = ctxt.outer_expn_data();
120        arg_macro = expn.macro_def_id;
121        arg_span = expn.call_site;
122    }
123
124    #[allow(rustc::diagnostic_outside_of_impl)]
125    cx.span_lint(NON_FMT_PANICS, arg_span, |lint| {
126        lint.primary_message(fluent::lint_non_fmt_panic);
127        lint.arg("name", symbol);
128        lint.note(fluent::lint_note);
129        lint.note(fluent::lint_more_info_note);
130        if !is_arg_inside_call(arg_span, span) {
131            // No clue where this argument is coming from.
132            return;
133        }
134        if arg_macro.is_some_and(|id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
135            // A case of `panic!(format!(..))`.
136            lint.note(fluent::lint_supports_fmt_note);
137            if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
138                lint.multipart_suggestion(
139                    fluent::lint_supports_fmt_suggestion,
140                    vec![
141                        (arg_span.until(open.shrink_to_hi()), "".into()),
142                        (close.until(arg_span.shrink_to_hi()), "".into()),
143                    ],
144                    Applicability::MachineApplicable,
145                );
146            }
147        } else {
148            let ty = cx.typeck_results().expr_ty(arg);
149            // If this is a &str or String, we can confidently give the `"{}", ` suggestion.
150            let is_str = matches!(
151                ty.kind(),
152                ty::Ref(_, r, _) if r.is_str(),
153            ) || matches!(
154                ty.ty_adt_def(),
155                Some(ty_def) if cx.tcx.is_lang_item(ty_def.did(), LangItem::String),
156            );
157
158            let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env());
159            let suggest_display = is_str
160                || cx
161                    .tcx
162                    .get_diagnostic_item(sym::Display)
163                    .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
164            let suggest_debug = !suggest_display
165                && cx
166                    .tcx
167                    .get_diagnostic_item(sym::Debug)
168                    .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
169
170            let suggest_panic_any = !is_str && panic == Some(sym::std_panic_macro);
171
172            let fmt_applicability = if suggest_panic_any {
173                // If we can use panic_any, use that as the MachineApplicable suggestion.
174                Applicability::MaybeIncorrect
175            } else {
176                // If we don't suggest panic_any, using a format string is our best bet.
177                Applicability::MachineApplicable
178            };
179
180            if suggest_display {
181                lint.span_suggestion_verbose(
182                    arg_span.shrink_to_lo(),
183                    fluent::lint_display_suggestion,
184                    "\"{}\", ",
185                    fmt_applicability,
186                );
187            } else if suggest_debug {
188                lint.arg("ty", ty);
189                lint.span_suggestion_verbose(
190                    arg_span.shrink_to_lo(),
191                    fluent::lint_debug_suggestion,
192                    "\"{:?}\", ",
193                    fmt_applicability,
194                );
195            }
196
197            if suggest_panic_any {
198                if let Some((open, close, del)) = find_delimiters(cx, span) {
199                    lint.arg("already_suggested", suggest_display || suggest_debug);
200                    lint.multipart_suggestion(
201                        fluent::lint_panic_suggestion,
202                        if del == '(' {
203                            vec![(span.until(open), "std::panic::panic_any".into())]
204                        } else {
205                            vec![
206                                (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
207                                (close, ")".into()),
208                            ]
209                        },
210                        Applicability::MachineApplicable,
211                    );
212                }
213            }
214        }
215    });
216}
217
218fn check_panic_str<'tcx>(
219    cx: &LateContext<'tcx>,
220    f: &'tcx hir::Expr<'tcx>,
221    arg: &'tcx hir::Expr<'tcx>,
222    fmt: &str,
223) {
224    if !fmt.contains(&['{', '}']) {
225        // No brace, no problem.
226        return;
227    }
228
229    let (span, _, _) = panic_call(cx, f);
230
231    let sm = cx.sess().source_map();
232    if span.in_external_macro(sm) && arg.span.in_external_macro(sm) {
233        // Nothing that can be done about it in the current crate.
234        return;
235    }
236
237    let fmt_span = arg.span.source_callsite();
238
239    let (snippet, style) = match sm.span_to_snippet(fmt_span) {
240        Ok(snippet) => {
241            // Count the number of `#`s between the `r` and `"`.
242            let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
243            (Some(snippet), style)
244        }
245        Err(_) => (None, None),
246    };
247
248    let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
249    let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
250
251    if n_arguments > 0 && fmt_parser.errors.is_empty() {
252        let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
253            [] => vec![fmt_span],
254            v => v
255                .iter()
256                .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
257                .collect(),
258        };
259        cx.emit_span_lint(
260            NON_FMT_PANICS,
261            arg_spans,
262            NonFmtPanicUnused {
263                count: n_arguments,
264                suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span),
265            },
266        );
267    } else {
268        let brace_spans: Option<Vec<_>> =
269            snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
270                s.char_indices()
271                    .filter(|&(_, c)| c == '{' || c == '}')
272                    .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
273                    .collect()
274            });
275        let count = brace_spans.as_ref().map(|v| v.len()).unwrap_or(/* any number >1 */ 2);
276        cx.emit_span_lint(
277            NON_FMT_PANICS,
278            brace_spans.unwrap_or_else(|| vec![span]),
279            NonFmtPanicBraces {
280                count,
281                suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span.shrink_to_lo()),
282            },
283        );
284    }
285}
286
287/// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
288/// and the type of (opening) delimiter used.
289fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> {
290    let snippet = cx.sess().source_map().span_to_snippet(span).ok()?;
291    let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
292    let close = snippet.rfind(|c| ")]}".contains(c))?;
293    Some((
294        span.from_inner(InnerSpan { start: open, end: open + 1 }),
295        span.from_inner(InnerSpan { start: close, end: close + 1 }),
296        open_ch,
297    ))
298}
299
300fn panic_call<'tcx>(
301    cx: &LateContext<'tcx>,
302    f: &'tcx hir::Expr<'tcx>,
303) -> (Span, Option<Symbol>, Symbol) {
304    let mut expn = f.span.ctxt().outer_expn_data();
305
306    let mut panic_macro = None;
307
308    // Unwrap more levels of macro expansion, as panic_2015!()
309    // was likely expanded from panic!() and possibly from
310    // [debug_]assert!().
311    loop {
312        let parent = expn.call_site.ctxt().outer_expn_data();
313        let Some(id) = parent.macro_def_id else { break };
314        let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
315        if !matches!(
316            name,
317            sym::core_panic_macro
318                | sym::std_panic_macro
319                | sym::assert_macro
320                | sym::debug_assert_macro
321                | sym::unreachable_macro
322        ) {
323            break;
324        }
325        expn = parent;
326        panic_macro = Some(name);
327    }
328
329    let macro_symbol =
330        if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
331    (expn.call_site, panic_macro, macro_symbol)
332}
333
334fn is_arg_inside_call(arg: Span, call: Span) -> bool {
335    // We only add suggestions if the argument we're looking at appears inside the
336    // panic call in the source file, to avoid invalid suggestions when macros are involved.
337    // We specifically check for the spans to not be identical, as that happens sometimes when
338    // proc_macros lie about spans and apply the same span to all the tokens they produce.
339    call.contains(arg) && !call.source_equal(arg)
340}