]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/default_trait_access.rs
Pass by ref instead of value
[rust.git] / clippy_lints / src / default_trait_access.rs
1 use rustc::hir::*;
2 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
3 use rustc::{declare_tool_lint, lint_array};
4 use if_chain::if_chain;
5 use rustc::ty::TyKind;
6
7 use crate::utils::{any_parent_is_automatically_derived, match_def_path, opt_def_id, paths, span_lint_and_sugg};
8
9
10 /// **What it does:** Checks for literal calls to `Default::default()`.
11 ///
12 /// **Why is this bad?** It's more clear to the reader to use the name of the type whose default is
13 /// being gotten than the generic `Default`.
14 ///
15 /// **Known problems:** None.
16 ///
17 /// **Example:**
18 /// ```rust
19 /// // Bad
20 /// let s: String = Default::default();
21 ///
22 /// // Good
23 /// let s = String::default();
24 /// ```
25 declare_clippy_lint! {
26     pub DEFAULT_TRAIT_ACCESS,
27     pedantic,
28     "checks for literal calls to Default::default()"
29 }
30
31 #[derive(Copy, Clone)]
32 pub struct DefaultTraitAccess;
33
34 impl LintPass for DefaultTraitAccess {
35     fn get_lints(&self) -> LintArray {
36         lint_array!(DEFAULT_TRAIT_ACCESS)
37     }
38 }
39
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess {
41     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
42         if_chain! {
43             if let ExprKind::Call(ref path, ..) = expr.node;
44             if !any_parent_is_automatically_derived(cx.tcx, expr.id);
45             if let ExprKind::Path(ref qpath) = path.node;
46             if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
47             if match_def_path(cx.tcx, def_id, &paths::DEFAULT_TRAIT_METHOD);
48             then {
49                 match qpath {
50                     QPath::Resolved(..) => {
51                         // TODO: Work out a way to put "whatever the imported way of referencing
52                         // this type in this file" rather than a fully-qualified type.
53                         let expr_ty = cx.tables.expr_ty(expr);
54                         if let TyKind::Adt(..) = expr_ty.sty {
55                             let replacement = format!("{}::default()", expr_ty);
56                             span_lint_and_sugg(
57                                 cx,
58                                 DEFAULT_TRAIT_ACCESS,
59                                 expr.span,
60                                 &format!("Calling {} is more clear than this expression", replacement),
61                                 "try",
62                                 replacement);
63                          }
64                     },
65                     QPath::TypeRelative(..) => {},
66                 }
67             }
68          }
69     }
70 }