1 use crate::{LateContext, LateLintPass, LintContext};
3 use rustc_errors::{pluralize, Applicability};
5 use rustc_middle::lint::in_external_macro;
7 use rustc_parse_format::{ParseMode, Parser, Piece};
8 use rustc_session::lint::FutureIncompatibilityReason;
9 use rustc_span::edition::Edition;
10 use rustc_span::{hygiene, sym, symbol::kw, symbol::SymbolStr, InnerSpan, Span, Symbol};
13 /// The `non_fmt_panics` lint detects `panic!(..)` invocations where the first
14 /// argument is not a formatting string.
27 /// In Rust 2018 and earlier, `panic!(x)` directly uses `x` as the message.
28 /// That means that `panic!("{}")` panics with the message `"{}"` instead
29 /// of using it as a formatting string, and `panic!(123)` will panic with
30 /// an `i32` as message.
32 /// Rust 2021 always interprets the first argument as format string.
35 "detect single-argument panic!() invocations in which the argument is not a format string",
36 @future_incompatible = FutureIncompatibleInfo {
37 reason: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2021),
38 explain_reason: false,
40 report_in_external_macro
43 declare_lint_pass!(NonPanicFmt => [NON_FMT_PANICS]);
45 impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
46 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
47 if let hir::ExprKind::Call(f, [arg]) = &expr.kind {
48 if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
49 if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
50 || Some(def_id) == cx.tcx.lang_items().panic_fn()
51 || Some(def_id) == cx.tcx.lang_items().panic_str()
53 if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
54 if cx.tcx.is_diagnostic_item(sym::std_panic_2015_macro, id)
55 || cx.tcx.is_diagnostic_item(sym::core_panic_2015_macro, id)
57 check_panic(cx, f, arg);
66 fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
67 if let hir::ExprKind::Lit(lit) = &arg.kind {
68 if let ast::LitKind::Str(sym, _) = lit.node {
69 // The argument is a string literal.
70 check_panic_str(cx, f, arg, &sym.as_str());
75 // The argument is *not* a string literal.
77 let (span, panic, symbol_str) = panic_call(cx, f);
79 if in_external_macro(cx.sess(), span) {
80 // Nothing that can be done about it in the current crate.
84 // Find the span of the argument to `panic!()`, before expansion in the
85 // case of `panic!(some_macro!())`.
86 // We don't use source_callsite(), because this `panic!(..)` might itself
87 // be expanded from another macro, in which case we want to stop at that
89 let mut arg_span = arg.span;
90 let mut arg_macro = None;
91 while !span.contains(arg_span) {
92 let expn = arg_span.ctxt().outer_expn_data();
96 arg_macro = expn.macro_def_id;
97 arg_span = expn.call_site;
100 cx.struct_span_lint(NON_FMT_PANICS, arg_span, |lint| {
101 let mut l = lint.build("panic message is not a string literal");
102 l.note("this usage of panic!() is deprecated; it will be a hard error in Rust 2021");
103 l.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/panic-macro-consistency.html>");
104 if !span.contains(arg_span) {
105 // No clue where this argument is coming from.
109 if arg_macro.map_or(false, |id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
110 // A case of `panic!(format!(..))`.
111 l.note(format!("the {}!() macro supports formatting, so there's no need for the format!() macro here", symbol_str).as_str());
112 if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
113 l.multipart_suggestion(
114 "remove the `format!(..)` macro call",
116 (arg_span.until(open.shrink_to_hi()), "".into()),
117 (close.until(arg_span.shrink_to_hi()), "".into()),
119 Applicability::MachineApplicable,
123 l.span_suggestion_verbose(
124 arg_span.shrink_to_lo(),
125 "add a \"{}\" format string to Display the message",
127 Applicability::MaybeIncorrect,
129 if panic == sym::std_panic_macro {
130 if let Some((open, close, del)) = find_delimiters(cx, span) {
131 l.multipart_suggestion(
132 "or use std::panic::panic_any instead",
134 vec![(span.until(open), "std::panic::panic_any".into())]
137 (span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
141 Applicability::MachineApplicable,
150 fn check_panic_str<'tcx>(
151 cx: &LateContext<'tcx>,
152 f: &'tcx hir::Expr<'tcx>,
153 arg: &'tcx hir::Expr<'tcx>,
156 if !fmt.contains(&['{', '}'][..]) {
157 // No brace, no problem.
161 let (span, _, _) = panic_call(cx, f);
163 if in_external_macro(cx.sess(), span) && in_external_macro(cx.sess(), arg.span) {
164 // Nothing that can be done about it in the current crate.
168 let fmt_span = arg.span.source_callsite();
170 let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
172 // Count the number of `#`s between the `r` and `"`.
173 let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
174 (Some(snippet), style)
176 Err(_) => (None, None),
180 Parser::new(fmt.as_ref(), style, snippet.clone(), false, ParseMode::Format);
181 let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
183 if n_arguments > 0 && fmt_parser.errors.is_empty() {
184 let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
185 [] => vec![fmt_span],
186 v => v.iter().map(|span| fmt_span.from_inner(*span)).collect(),
188 cx.struct_span_lint(NON_FMT_PANICS, arg_spans, |lint| {
189 let mut l = lint.build(match n_arguments {
190 1 => "panic message contains an unused formatting placeholder",
191 _ => "panic message contains unused formatting placeholders",
193 l.note("this message is not used as a format string when given without arguments, but will be in Rust 2021");
194 if span.contains(arg.span) {
196 arg.span.shrink_to_hi(),
197 &format!("add the missing argument{}", pluralize!(n_arguments)),
199 Applicability::HasPlaceholders,
202 arg.span.shrink_to_lo(),
203 "or add a \"{}\" format string to use the message literally",
205 Applicability::MachineApplicable,
211 let brace_spans: Option<Vec<_>> =
212 snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
214 .filter(|&(_, c)| c == '{' || c == '}')
215 .map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
218 let msg = match &brace_spans {
219 Some(v) if v.len() == 1 => "panic message contains a brace",
220 _ => "panic message contains braces",
222 cx.struct_span_lint(NON_FMT_PANICS, brace_spans.unwrap_or_else(|| vec![span]), |lint| {
223 let mut l = lint.build(msg);
224 l.note("this message is not used as a format string, but will be in Rust 2021");
225 if span.contains(arg.span) {
227 arg.span.shrink_to_lo(),
228 "add a \"{}\" format string to use the message literally",
230 Applicability::MachineApplicable,
238 /// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
239 /// and the type of (opening) delimiter used.
240 fn find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Span, char)> {
241 let snippet = cx.sess().parse_sess.source_map().span_to_snippet(span).ok()?;
242 let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
243 let close = snippet.rfind(|c| ")]}".contains(c))?;
245 span.from_inner(InnerSpan { start: open, end: open + 1 }),
246 span.from_inner(InnerSpan { start: close, end: close + 1 }),
251 fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, SymbolStr) {
252 let mut expn = f.span.ctxt().outer_expn_data();
254 let mut panic_macro = kw::Empty;
256 // Unwrap more levels of macro expansion, as panic_2015!()
257 // was likely expanded from panic!() and possibly from
258 // [debug_]assert!().
260 &[sym::std_panic_macro, sym::core_panic_macro, sym::assert_macro, sym::debug_assert_macro]
262 let parent = expn.call_site.ctxt().outer_expn_data();
263 if parent.macro_def_id.map_or(false, |id| cx.tcx.is_diagnostic_item(i, id)) {
270 if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
271 (expn.call_site, panic_macro, macro_symbol.as_str())