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::fcw;
8use rustc_session::{declare_lint, declare_lint_pass};
9use rustc_span::{InnerSpan, Span, Symbol, hygiene, sym};
10use rustc_trait_selection::infer::InferCtxtExt;
11
12use crate::lints::{NonFmtPanicBraces, NonFmtPanicUnused};
13use crate::{LateContext, LateLintPass, LintContext, fluent_generated as fluent};
14
15#[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! {
16 NON_FMT_PANICS,
37 Warn,
38 "detect single-argument panic!() invocations in which the argument is not a format string",
39 @future_incompatible = FutureIncompatibleInfo {
40 reason: fcw!(EditionSemanticsChange 2021 "panic-macro-consistency"),
41 explain_reason: false,
42 };
43 report_in_external_macro
44}
45
46pub 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 {
<[_]>::into_vec(::alloc::boxed::box_new([NON_FMT_PANICS]))
}
}
impl NonPanicFmt {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
<[_]>::into_vec(::alloc::boxed::box_new([NON_FMT_PANICS]))
}
}declare_lint_pass!(NonPanicFmt => [NON_FMT_PANICS]);
47
48impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
49 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
50 if let hir::ExprKind::Call(f, [arg]) = &expr.kind
51 && let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind()
52 {
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 #[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!(
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 && cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id)
70 {
71 check_panic(
72 cx,
73 f,
74 match &arg.kind {
77 hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg,
79 _ => ::rustc_middle::util::bug::bug_fmt(format_args!("call to unreachable_display without borrow"))bug!("call to unreachable_display without borrow"),
80 },
81 );
82 }
83 }
84 }
85 }
86}
87
88fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
89 if let hir::ExprKind::Lit(lit) = &arg.kind {
90 if let ast::LitKind::Str(sym, _) = lit.node {
91 check_panic_str(cx, f, arg, sym.as_str());
93 return;
94 }
95 }
96
97 let (span, panic, symbol) = panic_call(cx, f);
100
101 if span.in_external_macro(cx.sess().source_map()) {
102 return;
104 }
105
106 let mut arg_span = arg.span;
112 let mut arg_macro = None;
113 while !span.contains(arg_span) {
114 let ctxt = arg_span.ctxt();
115 if ctxt.is_root() {
116 break;
117 }
118 let expn = ctxt.outer_expn_data();
119 arg_macro = expn.macro_def_id;
120 arg_span = expn.call_site;
121 }
122
123 cx.span_lint(NON_FMT_PANICS, arg_span, |lint| {
124 lint.primary_message(fluent::lint_non_fmt_panic);
125 lint.arg("name", symbol);
126 lint.note(fluent::lint_note);
127 lint.note(fluent::lint_more_info_note);
128 if !is_arg_inside_call(arg_span, span) {
129 return;
131 }
132 if arg_macro.is_some_and(|id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
133 lint.note(fluent::lint_supports_fmt_note);
135 if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
136 lint.multipart_suggestion(
137 fluent::lint_supports_fmt_suggestion,
138 <[_]>::into_vec(::alloc::boxed::box_new([(arg_span.until(open.shrink_to_hi()),
"".into()),
(close.until(arg_span.shrink_to_hi()), "".into())]))vec![
139 (arg_span.until(open.shrink_to_hi()), "".into()),
140 (close.until(arg_span.shrink_to_hi()), "".into()),
141 ],
142 Applicability::MachineApplicable,
143 );
144 }
145 } else {
146 let ty = cx.typeck_results().expr_ty(arg);
147 let is_str = #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Ref(_, r, _) if r.is_str() => true,
_ => false,
}matches!(
149 ty.kind(),
150 ty::Ref(_, r, _) if r.is_str(),
151 ) || #[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!(
152 ty.ty_adt_def(),
153 Some(ty_def) if cx.tcx.is_lang_item(ty_def.did(), LangItem::String),
154 );
155
156 let (infcx, param_env) = cx.tcx.infer_ctxt().build_with_typing_env(cx.typing_env());
157 let suggest_display = is_str
158 || cx
159 .tcx
160 .get_diagnostic_item(sym::Display)
161 .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
162 let suggest_debug = !suggest_display
163 && cx
164 .tcx
165 .get_diagnostic_item(sym::Debug)
166 .is_some_and(|t| infcx.type_implements_trait(t, [ty], param_env).may_apply());
167
168 let suggest_panic_any = !is_str && panic == Some(sym::std_panic_macro);
169
170 let fmt_applicability = if suggest_panic_any {
171 Applicability::MaybeIncorrect
173 } else {
174 Applicability::MachineApplicable
176 };
177
178 if suggest_display {
179 lint.span_suggestion_verbose(
180 arg_span.shrink_to_lo(),
181 fluent::lint_display_suggestion,
182 "\"{}\", ",
183 fmt_applicability,
184 );
185 } else if suggest_debug {
186 lint.arg("ty", ty);
187 lint.span_suggestion_verbose(
188 arg_span.shrink_to_lo(),
189 fluent::lint_debug_suggestion,
190 "\"{:?}\", ",
191 fmt_applicability,
192 );
193 }
194
195 if suggest_panic_any {
196 if let Some((open, close, del)) = find_delimiters(cx, span) {
197 lint.arg("already_suggested", suggest_display || suggest_debug);
198 lint.multipart_suggestion(
199 fluent::lint_panic_suggestion,
200 if del == '(' {
201 <[_]>::into_vec(::alloc::boxed::box_new([(span.until(open),
"std::panic::panic_any".into())]))vec![(span.until(open), "std::panic::panic_any".into())]
202 } else {
203 <[_]>::into_vec(::alloc::boxed::box_new([(span.until(open.shrink_to_hi()),
"std::panic::panic_any(".into()), (close, ")".into())]))vec![
204 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
205 (close, ")".into()),
206 ]
207 },
208 Applicability::MachineApplicable,
209 );
210 }
211 }
212 }
213 });
214}
215
216fn check_panic_str<'tcx>(
217 cx: &LateContext<'tcx>,
218 f: &'tcx hir::Expr<'tcx>,
219 arg: &'tcx hir::Expr<'tcx>,
220 fmt: &str,
221) {
222 if !fmt.contains(&['{', '}']) {
223 return;
225 }
226
227 let (span, _, _) = panic_call(cx, f);
228
229 let sm = cx.sess().source_map();
230 if span.in_external_macro(sm) && arg.span.in_external_macro(sm) {
231 return;
233 }
234
235 let fmt_span = arg.span.source_callsite();
236
237 let (snippet, style) = match sm.span_to_snippet(fmt_span) {
238 Ok(snippet) => {
239 let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
241 (Some(snippet), style)
242 }
243 Err(_) => (None, None),
244 };
245
246 let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
247 let n_arguments = (&mut fmt_parser).filter(|a| #[allow(non_exhaustive_omitted_patterns)] match a {
Piece::NextArgument(_) => true,
_ => false,
}matches!(a, Piece::NextArgument(_))).count();
248
249 if n_arguments > 0 && fmt_parser.errors.is_empty() {
250 let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
251 [] => <[_]>::into_vec(::alloc::boxed::box_new([fmt_span]))vec![fmt_span],
252 v => v
253 .iter()
254 .map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
255 .collect(),
256 };
257 cx.emit_span_lint(
258 NON_FMT_PANICS,
259 arg_spans,
260 NonFmtPanicUnused {
261 count: n_arguments,
262 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span),
263 },
264 );
265 } else {
266 let brace_spans: Option<Vec<_>> =
267 snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
268 s.char_indices()
269 .filter(|&(_, c)| c == '{' || c == '}')
270 .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
271 .collect()
272 });
273 let count = brace_spans.as_ref().map(|v| v.len()).unwrap_or(2);
274 cx.emit_span_lint(
275 NON_FMT_PANICS,
276 brace_spans.unwrap_or_else(|| <[_]>::into_vec(::alloc::boxed::box_new([span]))vec![span]),
277 NonFmtPanicBraces {
278 count,
279 suggestion: is_arg_inside_call(arg.span, span).then_some(arg.span.shrink_to_lo()),
280 },
281 );
282 }
283}
284
285fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> {
288 let snippet = cx.sess().source_map().span_to_snippet(span).ok()?;
289 let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
290 let close = snippet.rfind(|c| ")]}".contains(c))?;
291 Some((
292 span.from_inner(InnerSpan { start: open, end: open + 1 }),
293 span.from_inner(InnerSpan { start: close, end: close + 1 }),
294 open_ch,
295 ))
296}
297
298fn panic_call<'tcx>(
299 cx: &LateContext<'tcx>,
300 f: &'tcx hir::Expr<'tcx>,
301) -> (Span, Option<Symbol>, Symbol) {
302 let mut expn = f.span.ctxt().outer_expn_data();
303
304 let mut panic_macro = None;
305
306 loop {
310 let parent = expn.call_site.ctxt().outer_expn_data();
311 let Some(id) = parent.macro_def_id else { break };
312 let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
313 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!(
314 name,
315 sym::core_panic_macro
316 | sym::std_panic_macro
317 | sym::assert_macro
318 | sym::debug_assert_macro
319 | sym::unreachable_macro
320 ) {
321 break;
322 }
323 expn = parent;
324 panic_macro = Some(name);
325 }
326
327 let macro_symbol =
328 if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
329 (expn.call_site, panic_macro, macro_symbol)
330}
331
332fn is_arg_inside_call(arg: Span, call: Span) -> bool {
333 call.contains(arg) && !call.source_equal(arg)
338}