1use rustc_ast as ast;
2use rustc_attr_ir::lang_items::LangItem;
3use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level, msg};
4use rustc_hir as hir;
5use rustc_hir::def_id::DefId;
6use rustc_infer::infer::TyCtxtInferExt;
7use rustc_lint_defs::{declare_lint, declare_lint_pass, fcw};
8use rustc_middle::ty;
9use rustc_parse_format::{ParseMode, Parser, Piece};
10use rustc_span::{InnerSpan, Span, Symbol, bug, hygiene, sym};
11use rustc_trait_selection::infer::InferCtxtExt;
12
13use crate::diagnostics::{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 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) -> Self { *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 match &arg.kind {
78 hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg,
80 _ => ::rustc_span::macros::bug_impl(None,
format_args!("call to unreachable_display without borrow"),
Location::caller())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 return lint;
109 }
110 if arg_macro.is_some_and(|id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
111 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 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
147 && panic == Some(sym::std_panic_macro)
148 && cx
149 .tcx
150 .all_diagnostic_items(())
151 .name_to_id
152 .keys()
153 .any(|name| name.as_str() == "panic_any");
154
155 let fmt_applicability = if suggest_panic_any {
156 Applicability::MaybeIncorrect
158 } else {
159 Applicability::MachineApplicable
161 };
162
163 if suggest_display {
164 lint.span_suggestion_verbose(
165 arg_span.shrink_to_lo(),
166 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"#),
167 "\"{}\", ",
168 fmt_applicability,
169 );
170 } else if suggest_debug {
171 lint.arg("ty", ty);
172 lint.span_suggestion_verbose(
173 arg_span.shrink_to_lo(),
174 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}`"#),
175 "\"{:?}\", ",
176 fmt_applicability,
177 );
178 }
179
180 if suggest_panic_any {
181 if let Some((open, close, del)) = find_delimiters(cx, span) {
182 lint.arg("already_suggested", suggest_display || suggest_debug);
183 lint.multipart_suggestion(
184 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("{$already_suggested ->\n [true] or use\n *[false] use\n } std::panic::panic_any instead"))msg!(
185 "{$already_suggested ->
186 [true] or use
187 *[false] use
188 } std::panic::panic_any instead"
189 ),
190 if del == '(' {
191 ::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())]
192 } else {
193 ::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![
194 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
195 (close, ")".into()),
196 ]
197 },
198 Applicability::MachineApplicable,
199 );
200 }
201 }
202 }
203 lint
204 }
205}
206
207fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
208 if let hir::ExprKind::Lit(lit) = &arg.kind {
209 if let ast::LitKind::Str(sym, _) = lit.node {
210 check_panic_str(cx, f, arg, sym.as_str());
212 return;
213 }
214 }
215
216 let (span, panic, symbol) = panic_call(cx, f);
219
220 if span.in_external_macro(cx.sess().source_map()) {
221 return;
223 }
224
225 let mut arg_span = arg.span;
231 let mut arg_macro = None;
232 while !span.contains(arg_span) {
233 let ctxt = arg_span.ctxt();
234 if ctxt.is_root() {
235 break;
236 }
237 let expn = ctxt.outer_expn_data();
238 arg_macro = expn.macro_def_id;
239 arg_span = expn.call_site;
240 }
241
242 cx.emit_span_lint(
243 NON_FMT_PANICS,
244 arg_span,
245 PanicMessageNotLiteral { arg_span, symbol, span, arg_macro, cx, arg, panic },
246 );
247}
248
249fn check_panic_str<'tcx>(
250 cx: &LateContext<'tcx>,
251 f: &'tcx hir::Expr<'tcx>,
252 arg: &'tcx hir::Expr<'tcx>,
253 fmt: &str,
254) {
255 if !fmt.contains(&['{', '}']) {
256 return;
258 }
259
260 let (span, _, _) = panic_call(cx, f);
261
262 let sm = cx.sess().source_map();
263 if span.in_external_macro(sm) && arg.span.in_external_macro(sm) {
264 return;
266 }
267
268 let fmt_span = arg.span.source_callsite();
269
270 let (snippet, style) = match sm.span_to_snippet(fmt_span) {
271 Ok(snippet) => {
272 let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
274 (Some(snippet), style)
275 }
276 Err(_) => (None, None),
277 };
278
279 let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
280 let n_arguments = (&mut fmt_parser).filter(|a| #[allow(non_exhaustive_omitted_patterns)] match a {
Piece::NextArgument(_) => true,
_ => false,
}matches!(a, Piece::NextArgument(_))).count();
281
282 if n_arguments > 0 && fmt_parser.errors.is_empty() {
283 let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
284 [] => ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[fmt_span]))vec![fmt_span],
285 v => v
286 .iter()
287 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
288 .collect(),
289 };
290 cx.emit_span_lint(
291 NON_FMT_PANICS,
292 arg_spans,
293 NonFmtPanicUnused {
294 count: n_arguments,
295 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span),
296 },
297 );
298 } else {
299 let brace_spans: Option<Vec<_>> =
300 snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
301 s.char_indices()
302 .filter(|&(_, c)| c == '{' || c == '}')
303 .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
304 .collect()
305 });
306 let count = brace_spans.as_ref().map(|v| v.len()).unwrap_or(2);
307 cx.emit_span_lint(
308 NON_FMT_PANICS,
309 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]),
310 NonFmtPanicBraces {
311 count,
312 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span.shrink_to_lo()),
313 },
314 );
315 }
316}
317
318fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> {
321 let snippet = cx.sess().source_map().span_to_snippet(span).ok()?;
322 let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
323 let close = snippet.rfind(|c| ")]}".contains(c))?;
324 Some((
325 span.from_inner(InnerSpan { start: open, end: open + 1 }),
326 span.from_inner(InnerSpan { start: close, end: close + 1 }),
327 open_ch,
328 ))
329}
330
331fn panic_call<'tcx>(
332 cx: &LateContext<'tcx>,
333 f: &'tcx hir::Expr<'tcx>,
334) -> (Span, Option<Symbol>, Symbol) {
335 let mut expn = f.span.ctxt().outer_expn_data();
336
337 let mut panic_macro = None;
338
339 loop {
343 let parent = expn.call_site.ctxt().outer_expn_data();
344 let Some(id) = parent.macro_def_id else { break };
345 let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
346 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!(
347 name,
348 sym::core_panic_macro
349 | sym::std_panic_macro
350 | sym::assert_macro
351 | sym::debug_assert_macro
352 | sym::unreachable_macro
353 ) {
354 break;
355 }
356 expn = parent;
357 panic_macro = Some(name);
358 }
359
360 let macro_symbol =
361 if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
362 (expn.call_site, panic_macro, macro_symbol)
363}
364
365fn is_arg_inside_call(arg: Span, call: Span) -> bool {
366 call.contains(arg) && call.lo_hi() != arg.lo_hi()
371}