]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/panic.rs
Merge pull request #2748 from phansch/explain_how_to_fix_nightly_build_failures
[rust.git] / clippy_lints / src / panic.rs
1 use rustc::hir::*;
2 use rustc::lint::*;
3 use syntax::ast::LitKind;
4 use utils::{is_direct_expn_of, match_def_path, opt_def_id, paths, resolve_node, span_lint};
5
6 /// **What it does:** Checks for missing parameters in `panic!`.
7 ///
8 /// **Why is this bad?** Contrary to the `format!` family of macros, there are
9 /// two forms of `panic!`: if there are no parameters given, the first argument
10 /// is not a format string and used literally. So while `format!("{}")` will
11 /// fail to compile, `panic!("{}")` will not.
12 ///
13 /// **Known problems:** None.
14 ///
15 /// **Example:**
16 /// ```rust
17 /// panic!("This `panic!` is probably missing a parameter there: {}");
18 /// ```
19 declare_clippy_lint! {
20     pub PANIC_PARAMS,
21     style,
22     "missing parameters in `panic!` calls"
23 }
24
25 #[allow(missing_copy_implementations)]
26 pub struct Pass;
27
28 impl LintPass for Pass {
29     fn get_lints(&self) -> LintArray {
30         lint_array!(PANIC_PARAMS)
31     }
32 }
33
34 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Pass {
35     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
36         if_chain! {
37             if let ExprBlock(ref block) = expr.node;
38             if let Some(ref ex) = block.expr;
39             if let ExprCall(ref fun, ref params) = ex.node;
40             if params.len() == 2;
41             if let ExprPath(ref qpath) = fun.node;
42             if let Some(fun_def_id) = opt_def_id(resolve_node(cx, qpath, fun.hir_id));
43             if match_def_path(cx.tcx, fun_def_id, &paths::BEGIN_PANIC);
44             if let ExprLit(ref lit) = params[0].node;
45             if is_direct_expn_of(expr.span, "panic").is_some();
46             if let LitKind::Str(ref string, _) = lit.node;
47             let string = string.as_str().replace("{{", "").replace("}}", "");
48             if let Some(par) = string.find('{');
49             if string[par..].contains('}');
50             if params[0].span.source_callee().is_none();
51             if params[0].span.lo() != params[0].span.hi();
52             then {
53                 span_lint(cx, PANIC_PARAMS, params[0].span,
54                           "you probably are missing some parameter in your format string");
55             }
56         }
57     }
58 }