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, InnerSpan};
10 /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal.
22 /// In Rust 2018 and earlier, `panic!("{}")` panics with the message `"{}"`,
23 /// as a `panic!()` invocation with a single argument does not use `format_args!()`.
24 /// Rust 2021 interprets this string as format string, which breaks this.
27 "detect braces in single-argument panic!() invocations",
28 report_in_external_macro
31 declare_lint_pass!(PanicFmt => [PANIC_FMT]);
33 impl<'tcx> LateLintPass<'tcx> for PanicFmt {
34 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
35 if let hir::ExprKind::Call(f, [arg]) = &expr.kind {
36 if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
37 if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
38 || Some(def_id) == cx.tcx.lang_items().panic_fn()
40 check_panic(cx, f, arg);
47 fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
48 if let hir::ExprKind::Lit(lit) = &arg.kind {
49 if let ast::LitKind::Str(sym, _) = lit.node {
50 let mut expn = f.span.ctxt().outer_expn_data();
51 if let Some(id) = expn.macro_def_id {
52 if cx.tcx.is_diagnostic_item(sym::std_panic_2015_macro, id)
53 || cx.tcx.is_diagnostic_item(sym::core_panic_2015_macro, id)
55 let fmt = sym.as_str();
56 if !fmt.contains(&['{', '}'][..]) {
60 let fmt_span = arg.span.source_callsite();
62 let (snippet, style) =
63 match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
65 // Count the number of `#`s between the `r` and `"`.
66 let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
67 (Some(snippet), style)
69 Err(_) => (None, None),
73 Parser::new(fmt.as_ref(), style, snippet.clone(), false, ParseMode::Format);
75 (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
77 // Unwrap more levels of macro expansion, as panic_2015!()
78 // was likely expanded from panic!() and possibly from
82 sym::core_panic_macro,
84 sym::debug_assert_macro,
86 let parent = expn.call_site.ctxt().outer_expn_data();
89 .map_or(false, |id| cx.tcx.is_diagnostic_item(assert, id))
95 if n_arguments > 0 && fmt_parser.errors.is_empty() {
96 let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
98 v => v.iter().map(|span| fmt_span.from_inner(*span)).collect(),
100 cx.struct_span_lint(PANIC_FMT, arg_spans, |lint| {
101 let mut l = lint.build(match n_arguments {
102 1 => "panic message contains an unused formatting placeholder",
103 _ => "panic message contains unused formatting placeholders",
105 l.note("this message is not used as a format string when given without arguments, but will be in a future Rust edition");
106 if expn.call_site.contains(arg.span) {
108 arg.span.shrink_to_hi(),
109 &format!("add the missing argument{}", pluralize!(n_arguments)),
111 Applicability::HasPlaceholders,
114 arg.span.shrink_to_lo(),
115 "or add a \"{}\" format string to use the message literally",
117 Applicability::MachineApplicable,
123 let brace_spans: Option<Vec<_>> = snippet
124 .filter(|s| s.starts_with('"') || s.starts_with("r#"))
127 .filter(|&(_, c)| c == '{' || c == '}')
129 fmt_span.from_inner(InnerSpan { start: i, end: i + 1 })
133 let msg = match &brace_spans {
134 Some(v) if v.len() == 1 => "panic message contains a brace",
135 _ => "panic message contains braces",
137 cx.struct_span_lint(PANIC_FMT, brace_spans.unwrap_or(vec![expn.call_site]), |lint| {
138 let mut l = lint.build(msg);
139 l.note("this message is not used as a format string, but will be in a future Rust edition");
140 if expn.call_site.contains(arg.span) {
142 arg.span.shrink_to_lo(),
143 "add a \"{}\" format string to use the message literally",
145 Applicability::MachineApplicable,