|
| 1 | +use crate::{LateContext, LateLintPass, LintContext}; |
| 2 | +use rustc_ast as ast; |
| 3 | +use rustc_hir as hir; |
| 4 | +use rustc_middle::ty; |
| 5 | + |
| 6 | +declare_lint! { |
| 7 | + /// The `panic_fmt` lint detects `panic!("..")` with `{` or `}` in the string literal. |
| 8 | + /// |
| 9 | + /// ### Example |
| 10 | + /// |
| 11 | + /// ```rust,no_run |
| 12 | + /// panic!("{}"); |
| 13 | + /// ``` |
| 14 | + /// |
| 15 | + /// {{produces}} |
| 16 | + /// |
| 17 | + /// ### Explanation |
| 18 | + /// |
| 19 | + /// `panic!("{}")` panics with the message `"{}"`, as a `panic!()` invocation |
| 20 | + /// with a single argument does not use `format_args!()`. |
| 21 | + /// A future version of Rust will interpret this string as format string, |
| 22 | + /// which would break this. |
| 23 | + PANIC_FMT, |
| 24 | + Warn, |
| 25 | + "detect braces in single-argument panic!() invocations", |
| 26 | + report_in_external_macro |
| 27 | +} |
| 28 | + |
| 29 | +declare_lint_pass!(PanicFmt => [PANIC_FMT]); |
| 30 | + |
| 31 | +impl<'tcx> LateLintPass<'tcx> for PanicFmt { |
| 32 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { |
| 33 | + if let hir::ExprKind::Call(f, [arg]) = &expr.kind { |
| 34 | + if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() { |
| 35 | + if Some(def_id) == cx.tcx.lang_items().begin_panic_fn() |
| 36 | + || Some(def_id) == cx.tcx.lang_items().panic_fn() |
| 37 | + { |
| 38 | + check_panic(cx, f, arg); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) { |
| 46 | + if let hir::ExprKind::Lit(lit) = &arg.kind { |
| 47 | + if let ast::LitKind::Str(sym, _) = lit.node { |
| 48 | + 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 | + }); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments