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 /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation
23 /// with a single argument does not use `format_args!()`.
24 /// A future edition of Rust will interpret this string as format string,
25 /// which would break this.
28 "detect braces in single-argument panic!() invocations",
29 report_in_external_macro
32 declare_lint_pass!(PanicFmt => [PANIC_FMT]);
34 impl<'tcx> LateLintPass<'tcx> for PanicFmt {
35 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
36 if let hir::ExprKind::Call(f, [arg]) = &expr.kind {
37 if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
38 if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
39 || Some(def_id) == cx.tcx.lang_items().panic_fn()
41 check_panic(cx, f, arg);
48 fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
49 if let hir::ExprKind::Lit(lit) = &arg.kind {
50 if let ast::LitKind::Str(sym, _) = lit.node {
51 let mut 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)
56 let fmt = sym.as_str();
57 if !fmt.contains(&['{', '}'][..]) {
61 let fmt_span = arg.span.source_callsite();
63 let (snippet, style) =
64 match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
66 // Count the number of `#`s between the `r` and `"`.
67 let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
68 (Some(snippet), style)
70 Err(_) => (None, None),
74 Parser::new(fmt.as_ref(), style, snippet.clone(), false, ParseMode::Format);
76 (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
78 // Unwrap another level of macro expansion if this panic!()
79 // was expanded from assert!() or debug_assert!().
80 for &assert in &[sym::assert_macro, sym::debug_assert_macro] {
81 let parent = expn.call_site.ctxt().outer_expn_data();
84 .map_or(false, |id| cx.tcx.is_diagnostic_item(assert, id))
90 if n_arguments > 0 && fmt_parser.errors.is_empty() {
91 let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
93 v => v.iter().map(|span| fmt_span.from_inner(*span)).collect(),
95 cx.struct_span_lint(PANIC_FMT, arg_spans, |lint| {
96 let mut l = lint.build(match n_arguments {
97 1 => "panic message contains an unused formatting placeholder",
98 _ => "panic message contains unused formatting placeholders",
100 l.note("this message is not used as a format string when given without arguments, but will be in a future Rust edition");
101 if expn.call_site.contains(arg.span) {
103 arg.span.shrink_to_hi(),
104 &format!("add the missing argument{}", pluralize!(n_arguments)),
106 Applicability::HasPlaceholders,
109 arg.span.shrink_to_lo(),
110 "or add a \"{}\" format string to use the message literally",
112 Applicability::MachineApplicable,
118 let brace_spans: Option<Vec<_>> = snippet
119 .filter(|s| s.starts_with('"') || s.starts_with("r#"))
122 .filter(|&(_, c)| c == '{' || c == '}')
124 fmt_span.from_inner(InnerSpan { start: i, end: i + 1 })
128 let msg = match &brace_spans {
129 Some(v) if v.len() == 1 => "panic message contains a brace",
130 _ => "panic message contains braces",
132 cx.struct_span_lint(PANIC_FMT, brace_spans.unwrap_or(vec![expn.call_site]), |lint| {
133 let mut l = lint.build(msg);
134 l.note("this message is not used as a format string, but will be in a future Rust edition");
135 if expn.call_site.contains(arg.span) {
137 arg.span.shrink_to_lo(),
138 "add a \"{}\" format string to use the message literally",
140 Applicability::MachineApplicable,