Skip to content

Commit da66a50

Browse files
committed
Specialize panic_fmt lint for the {core,std}::panic!() macros.
It now only reacts to expansion of those macros, and suggests inserting `"{}", ` in the right place.
1 parent 462ee9c commit da66a50

File tree

2 files changed

+24
-5
lines changed

2 files changed

+24
-5
lines changed

compiler/rustc_lint/src/panic_fmt.rs

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
use crate::{LateContext, LateLintPass, LintContext};
22
use rustc_ast as ast;
3+
use rustc_errors::Applicability;
34
use rustc_hir as hir;
45
use rustc_middle::ty;
6+
use rustc_span::sym;
57

68
declare_lint! {
79
/// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.
@@ -46,11 +48,26 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
4648
if let hir::ExprKind::Lit(lit) = &arg.kind {
4749
if let ast::LitKind::Str(sym, _) = lit.node {
4850
if sym.as_str().contains(&['{', '}'][..]) {
49-
cx.struct_span_lint(PANIC_FMT, f.span, |lint| {
50-
lint.build("Panic message contains a brace")
51-
.note("This message is not used as a format string, but will be in a future Rust version")
52-
.emit();
53-
});
51+
let expn = f.span.ctxt().outer_expn_data();
52+
if let Some(id) = expn.macro_def_id {
53+
if cx.tcx.is_diagnostic_item(sym::std_panic_macro, id)
54+
|| cx.tcx.is_diagnostic_item(sym::core_panic_macro, id)
55+
{
56+
cx.struct_span_lint(PANIC_FMT, expn.call_site, |lint| {
57+
let mut l = lint.build("Panic message contains a brace");
58+
l.note("This message is not used as a format string, but will be in a future Rust version");
59+
if expn.call_site.contains(arg.span) {
60+
l.span_suggestion(
61+
arg.span.shrink_to_lo(),
62+
"add a \"{}\" format string to use the message literally",
63+
"\"{}\", ".into(),
64+
Applicability::MachineApplicable,
65+
);
66+
}
67+
l.emit();
68+
});
69+
}
70+
}
5471
}
5572
}
5673
}

compiler/rustc_span/src/symbol.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,7 @@ symbols! {
393393
copysignf64,
394394
core,
395395
core_intrinsics,
396+
core_panic_macro,
396397
cosf32,
397398
cosf64,
398399
crate_id,
@@ -1064,6 +1065,7 @@ symbols! {
10641065
staticlib,
10651066
std,
10661067
std_inject,
1068+
std_panic_macro,
10671069
stmt,
10681070
stmt_expr_attributes,
10691071
stop_after_dataflow,

0 commit comments

Comments
 (0)