1 use crate::{LateContext, LateLintPass, LintContext};
3 use rustc_errors::{pluralize, Applicability};
6 use rustc_parse_format::{ParseMode, Parser, Piece};
7 use rustc_span::{sym, symbol::kw, InnerSpan, Span, Symbol};
10 /// The `non_fmt_panic` lint detects `panic!(..)` invocations where the first
11 /// argument is not a formatting string.
24 /// In Rust 2018 and earlier, `panic!(x)` directly uses `x` as the message.
25 /// That means that `panic!("{}")` panics with the message `"{}"` instead
26 /// of using it as a formatting string, and `panic!(123)` will panic with
27 /// an `i32` as message.
29 /// Rust 2021 always interprets the first argument as format string.
32 "detect single-argument panic!() invocations in which the argument is not a format string",
33 report_in_external_macro
36 declare_lint_pass!(NonPanicFmt => [NON_FMT_PANIC]);
38 impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
39 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
40 if let hir::ExprKind::Call(f, [arg]) = &expr.kind {
41 if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
42 if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
43 || Some(def_id) == cx.tcx.lang_items().panic_fn()
44 || Some(def_id) == cx.tcx.lang_items().panic_str()
46 if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
47 if cx.tcx.is_diagnostic_item(sym::std_panic_2015_macro, id)
48 || cx.tcx.is_diagnostic_item(sym::core_panic_2015_macro, id)
50 check_panic(cx, f, arg);
59 fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
60 if let hir::ExprKind::Lit(lit) = &arg.kind {
61 if let ast::LitKind::Str(sym, _) = lit.node {
62 // The argument is a string literal.
63 check_panic_str(cx, f, arg, &sym.as_str());
68 // The argument is *not* a string literal.
70 let (span, panic) = panic_call(cx, f);
72 cx.struct_span_lint(NON_FMT_PANIC, arg.span, |lint| {
73 let mut l = lint.build("panic message is not a string literal");
74 l.note("this is no longer accepted in Rust 2021");
75 if span.contains(arg.span) {
76 l.span_suggestion_verbose(
77 arg.span.shrink_to_lo(),
78 "add a \"{}\" format string to Display the message",
80 Applicability::MaybeIncorrect,
82 if panic == sym::std_panic_macro {
83 l.span_suggestion_verbose(
85 "or use std::panic::panic_any instead",
86 "std::panic::panic_any(".into(),
87 Applicability::MachineApplicable,
95 fn check_panic_str<'tcx>(
96 cx: &LateContext<'tcx>,
97 f: &'tcx hir::Expr<'tcx>,
98 arg: &'tcx hir::Expr<'tcx>,
101 if !fmt.contains(&['{', '}'][..]) {
102 // No brace, no problem.
106 let fmt_span = arg.span.source_callsite();
108 let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
110 // Count the number of `#`s between the `r` and `"`.
111 let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
112 (Some(snippet), style)
114 Err(_) => (None, None),
118 Parser::new(fmt.as_ref(), style, snippet.clone(), false, ParseMode::Format);
119 let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
121 let (span, _) = panic_call(cx, f);
123 if n_arguments > 0 && fmt_parser.errors.is_empty() {
124 let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
125 [] => vec![fmt_span],
126 v => v.iter().map(|span| fmt_span.from_inner(*span)).collect(),
128 cx.struct_span_lint(NON_FMT_PANIC, arg_spans, |lint| {
129 let mut l = lint.build(match n_arguments {
130 1 => "panic message contains an unused formatting placeholder",
131 _ => "panic message contains unused formatting placeholders",
133 l.note("this message is not used as a format string when given without arguments, but will be in Rust 2021");
134 if span.contains(arg.span) {
136 arg.span.shrink_to_hi(),
137 &format!("add the missing argument{}", pluralize!(n_arguments)),
139 Applicability::HasPlaceholders,
142 arg.span.shrink_to_lo(),
143 "or add a \"{}\" format string to use the message literally",
145 Applicability::MachineApplicable,
151 let brace_spans: Option<Vec<_>> =
152 snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
154 .filter(|&(_, c)| c == '{' || c == '}')
155 .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
158 let msg = match &brace_spans {
159 Some(v) if v.len() == 1 => "panic message contains a brace",
160 _ => "panic message contains braces",
162 cx.struct_span_lint(NON_FMT_PANIC, brace_spans.unwrap_or(vec![span]), |lint| {
163 let mut l = lint.build(msg);
164 l.note("this message is not used as a format string, but will be in Rust 2021");
165 if span.contains(arg.span) {
167 arg.span.shrink_to_lo(),
168 "add a \"{}\" format string to use the message literally",
170 Applicability::MachineApplicable,
178 fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol) {
179 let mut expn = f.span.ctxt().outer_expn_data();
181 let mut panic_macro = kw::Empty;
183 // Unwrap more levels of macro expansion, as panic_2015!()
184 // was likely expanded from panic!() and possibly from
185 // [debug_]assert!().
187 &[sym::std_panic_macro, sym::core_panic_macro, sym::assert_macro, sym::debug_assert_macro]
189 let parent = expn.call_site.ctxt().outer_expn_data();
190 if parent.macro_def_id.map_or(false, |id| cx.tcx.is_diagnostic_item(i, id)) {
196 (expn.call_site, panic_macro)