1use rustc_ast as ast;
2use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level, msg};
3use rustc_hir as hir;
4use rustc_hir::attrs::lang_items::LangItem;
5use rustc_hir::def_id::DefId;
6use rustc_infer::infer::TyCtxtInferExt;
7use rustc_middle::{bug, ty};
8use rustc_parse_format::{ParseMode, Parser, Piece};
9use rustc_session::lint::fcw;
10use rustc_session::{declare_lint, declare_lint_pass};
11use rustc_span::{InnerSpan, Span, Symbol, hygiene, sym};
12use rustc_trait_selection::infer::InferCtxtExt;
13
14use crate::diagnostics::{NonFmtPanicBraces, NonFmtPanicUnused};
15use crate::{LateContext, LateLintPass, LintContext};
16
17#[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! {
18 NON_FMT_PANICS,
39 Warn,
40 "detect single-argument panic!() invocations in which the argument is not a format string",
41 @future_incompatible = FutureIncompatibleInfo {
42 reason: fcw!(EditionSemanticsChange 2021 "panic-macro-consistency"),
43 explain_reason: false,
44 };
45 report_in_external_macro
46}
47
48pub 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]);
49
50impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
51 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
52 if let hir::ExprKind::Call(f, [arg]) = &expr.kind
53 && let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind()
54 {
55 let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id);
56
57 if cx.tcx.is_lang_item(def_id, LangItem::BeginPanic)
58 || cx.tcx.is_lang_item(def_id, LangItem::Panic)
59 || f_diagnostic_name == Some(sym::panic_str_2015)
60 {
61 if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
62 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!(
63 cx.tcx.get_diagnostic_name(id),
64 Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro)
65 ) {
66 check_panic(cx, f, arg);
67 }
68 }
69 } else if f_diagnostic_name == Some(sym::unreachable_display) {
70 if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id
71 && cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id)
72 {
73 check_panic(
74 cx,
75 f,
76 match &arg.kind {
79 hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg,
81 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("call to unreachable_display without borrow"))bug!("call to unreachable_display without borrow"),
82 },
83 );
84 }
85 }
86 }
87 }
88}
89
90struct PanicMessageNotLiteral<'a, 'tcx> {
91 arg_span: Span,
92 symbol: Symbol,
93 span: Span,
94 arg_macro: Option<DefId>,
95 cx: &'a LateContext<'tcx>,
96 arg: &'tcx hir::Expr<'tcx>,
97 panic: Option<Symbol>,
98}
99
100impl<'a, 'b, 'tcx> Diagnostic<'a, ()> for PanicMessageNotLiteral<'b, 'tcx> {
101 fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
102 let Self { arg_span, symbol, span, arg_macro, cx, arg, panic } = self;
103 let mut lint = Diag::new(dcx, level, "panic message is not a string literal")
104 .with_arg("name", symbol)
105 .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"))
106 .with_note("for more information, see <https://doc.rust-lang.org/edition-guide/rust-2021/panic-macro-consistency.html>");
107 if !is_arg_inside_call(arg_span, span) {
108 return lint;
110 }
111 if arg_macro.is_some_and(|id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
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"));
114 if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
115 lint.multipart_suggestion(
116 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("remove the `format!(..)` macro call"))msg!("remove the `format!(..)` macro call"),
117 ::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![
118 (arg_span.until(open.shrink_to_hi()), "".into()),
119 (close.until(arg_span.shrink_to_hi()), "".into()),
120 ],
121 Applicability::MachineApplicable,
122 );
123 }
124 } else {
125 let ty = cx.typeck_results().expr_ty(arg);
126 let is_str = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Ref(_, r, _) if r.is_str() => true,
_ => false,
}matches!(
128 ty.kind(),
129 ty::Ref(_, r, _) if r.is_str(),
130 ) || #[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!(
131 ty.ty_adt_def(),
132 Some(ty_def) if cx.tcx.is_lang_item(ty_def.did(), LangItem::String),
133 );
134
135 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env());
136 let suggest_display = is_str
137 || cx
138 .tcx
139 .get_diagnostic_item(sym::Display)
140 .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
141 let suggest_debug = !suggest_display
142 && cx
143 .tcx
144 .get_diagnostic_item(sym::Debug)
145 .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
146
147 let suggest_panic_any = !is_str && panic == Some(sym::std_panic_macro);
148
149 let fmt_applicability = if suggest_panic_any {
150 Applicability::MaybeIncorrect
152 } else {
153 Applicability::MachineApplicable
155 };
156
157 if suggest_display {
158 lint.span_suggestion_verbose(
159 arg_span.shrink_to_lo(),
160 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"#),
161 "\"{}\", ",
162 fmt_applicability,
163 );
164 } else if suggest_debug {
165 lint.arg("ty", ty);
166 lint.span_suggestion_verbose(
167 arg_span.shrink_to_lo(),
168 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}`"#),
169 "\"{:?}\", ",
170 fmt_applicability,
171 );
172 }
173
174 if suggest_panic_any {
175 if let Some((open, close, del)) = find_delimiters(cx, span) {
176 lint.arg("already_suggested", suggest_display || suggest_debug);
177 lint.multipart_suggestion(
178 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$already_suggested ->\n [true] or use\n *[false] use\n } std::panic::panic_any instead"))msg!(
179 "{$already_suggested ->
180 [true] or use
181 *[false] use
182 } std::panic::panic_any instead"
183 ),
184 if del == '(' {
185 ::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())]
186 } else {
187 ::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![
188 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
189 (close, ")".into()),
190 ]
191 },
192 Applicability::MachineApplicable,
193 );
194 }
195 }
196 }
197 lint
198 }
199}
200
201fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
202 if let hir::ExprKind::Lit(lit) = &arg.kind {
203 if let ast::LitKind::Str(sym, _) = lit.node {
204 check_panic_str(cx, f, arg, sym.as_str());
206 return;
207 }
208 }
209
210 let (span, panic, symbol) = panic_call(cx, f);
213
214 if span.in_external_macro(cx.sess().source_map()) {
215 return;
217 }
218
219 let mut arg_span = arg.span;
225 let mut arg_macro = None;
226 while !span.contains(arg_span) {
227 let ctxt = arg_span.ctxt();
228 if ctxt.is_root() {
229 break;
230 }
231 let expn = ctxt.outer_expn_data();
232 arg_macro = expn.macro_def_id;
233 arg_span = expn.call_site;
234 }
235
236 cx.emit_span_lint(
237 NON_FMT_PANICS,
238 arg_span,
239 PanicMessageNotLiteral { arg_span, symbol, span, arg_macro, cx, arg, panic },
240 );
241}
242
243fn check_panic_str<'tcx>(
244 cx: &LateContext<'tcx>,
245 f: &'tcx hir::Expr<'tcx>,
246 arg: &'tcx hir::Expr<'tcx>,
247 fmt: &str,
248) {
249 if !fmt.contains(&['{', '}']) {
250 return;
252 }
253
254 let (span, _, _) = panic_call(cx, f);
255
256 let sm = cx.sess().source_map();
257 if span.in_external_macro(sm) && arg.span.in_external_macro(sm) {
258 return;
260 }
261
262 let fmt_span = arg.span.source_callsite();
263
264 let (snippet, style) = match sm.span_to_snippet(fmt_span) {
265 Ok(snippet) => {
266 let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
268 (Some(snippet), style)
269 }
270 Err(_) => (None, None),
271 };
272
273 let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
274 let n_arguments = (&mut fmt_parser).filter(|a| #[allow(non_exhaustive_omitted_patterns)] match a {
Piece::NextArgument(_) => true,
_ => false,
}matches!(a, Piece::NextArgument(_))).count();
275
276 if n_arguments > 0 && fmt_parser.errors.is_empty() {
277 let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
278 [] => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[fmt_span]))vec![fmt_span],
279 v => v
280 .iter()
281 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
282 .collect(),
283 };
284 cx.emit_span_lint(
285 NON_FMT_PANICS,
286 arg_spans,
287 NonFmtPanicUnused {
288 count: n_arguments,
289 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span),
290 },
291 );
292 } else {
293 let brace_spans: Option<Vec<_>> =
294 snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
295 s.char_indices()
296 .filter(|&(_, c)| c == '{' || c == '}')
297 .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
298 .collect()
299 });
300 let count = brace_spans.as_ref().map(|v| v.len()).unwrap_or(2);
301 cx.emit_span_lint(
302 NON_FMT_PANICS,
303 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]),
304 NonFmtPanicBraces {
305 count,
306 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span.shrink_to_lo()),
307 },
308 );
309 }
310}
311
312fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> {
315 let snippet = cx.sess().source_map().span_to_snippet(span).ok()?;
316 let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
317 let close = snippet.rfind(|c| ")]}".contains(c))?;
318 Some((
319 span.from_inner(InnerSpan { start: open, end: open + 1 }),
320 span.from_inner(InnerSpan { start: close, end: close + 1 }),
321 open_ch,
322 ))
323}
324
325fn panic_call<'tcx>(
326 cx: &LateContext<'tcx>,
327 f: &'tcx hir::Expr<'tcx>,
328) -> (Span, Option<Symbol>, Symbol) {
329 let mut expn = f.span.ctxt().outer_expn_data();
330
331 let mut panic_macro = None;
332
333 loop {
337 let parent = expn.call_site.ctxt().outer_expn_data();
338 let Some(id) = parent.macro_def_id else { break };
339 let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
340 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!(
341 name,
342 sym::core_panic_macro
343 | sym::std_panic_macro
344 | sym::assert_macro
345 | sym::debug_assert_macro
346 | sym::unreachable_macro
347 ) {
348 break;
349 }
350 expn = parent;
351 panic_macro = Some(name);
352 }
353
354 let macro_symbol =
355 if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
356 (expn.call_site, panic_macro, macro_symbol)
357}
358
359fn is_arg_inside_call(arg: Span, call: Span) -> bool {
360 call.contains(arg) && !call.source_equal(arg)
365}