]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/default_trait_access.rs
Run rustfmt on clippy_lints
[rust.git] / clippy_lints / src / default_trait_access.rs
1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use crate::rustc::hir::*;
11 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
12 use crate::rustc::ty::TyKind;
13 use crate::rustc::{declare_tool_lint, lint_array};
14 use crate::rustc_errors::Applicability;
15 use if_chain::if_chain;
16
17 use crate::utils::{any_parent_is_automatically_derived, match_def_path, opt_def_id, paths, span_lint_and_sugg};
18
19 /// **What it does:** Checks for literal calls to `Default::default()`.
20 ///
21 /// **Why is this bad?** It's more clear to the reader to use the name of the type whose default is
22 /// being gotten than the generic `Default`.
23 ///
24 /// **Known problems:** None.
25 ///
26 /// **Example:**
27 /// ```rust
28 /// // Bad
29 /// let s: String = Default::default();
30 ///
31 /// // Good
32 /// let s = String::default();
33 /// ```
34 declare_clippy_lint! {
35     pub DEFAULT_TRAIT_ACCESS,
36     pedantic,
37     "checks for literal calls to Default::default()"
38 }
39
40 #[derive(Copy, Clone)]
41 pub struct DefaultTraitAccess;
42
43 impl LintPass for DefaultTraitAccess {
44     fn get_lints(&self) -> LintArray {
45         lint_array!(DEFAULT_TRAIT_ACCESS)
46     }
47 }
48
49 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess {
50     fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
51         if_chain! {
52            if let ExprKind::Call(ref path, ..) = expr.node;
53            if !any_parent_is_automatically_derived(cx.tcx, expr.id);
54            if let ExprKind::Path(ref qpath) = path.node;
55            if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
56            if match_def_path(cx.tcx, def_id, &paths::DEFAULT_TRAIT_METHOD);
57            then {
58                match qpath {
59                    QPath::Resolved(..) => {
60                        if_chain! {
61                            // Detect and ignore <Foo as Default>::default() because these calls do
62                            // explicitly name the type.
63                            if let ExprKind::Call(ref method, ref _args) = expr.node;
64                            if let ExprKind::Path(ref p) = method.node;
65                            if let QPath::Resolved(Some(_ty), _path) = p;
66                            then {
67                                return;
68                            }
69                        }
70
71                        // TODO: Work out a way to put "whatever the imported way of referencing
72                        // this type in this file" rather than a fully-qualified type.
73                        let expr_ty = cx.tables.expr_ty(expr);
74                        if let TyKind::Adt(..) = expr_ty.sty {
75                            let replacement = format!("{}::default()", expr_ty);
76                            span_lint_and_sugg(
77                                cx,
78                                DEFAULT_TRAIT_ACCESS,
79                                expr.span,
80                                &format!("Calling {} is more clear than this expression", replacement),
81                                "try",
82                                replacement,
83                                Applicability::Unspecified, // First resolve the TODO above
84                            );
85                         }
86                    },
87                    QPath::TypeRelative(..) => {},
88                }
89            }
90         }
91     }
92 }