1 // Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
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.
11 use crate::rustc::hir::*;
12 use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
13 use crate::rustc::ty::TyKind;
14 use crate::rustc::{declare_tool_lint, lint_array};
15 use crate::rustc_errors::Applicability;
16 use if_chain::if_chain;
18 use crate::utils::{any_parent_is_automatically_derived, match_def_path, opt_def_id, paths, span_lint_and_sugg};
21 /// **What it does:** Checks for literal calls to `Default::default()`.
23 /// **Why is this bad?** It's more clear to the reader to use the name of the type whose default is
24 /// being gotten than the generic `Default`.
26 /// **Known problems:** None.
31 /// let s: String = Default::default();
34 /// let s = String::default();
36 declare_clippy_lint! {
37 pub DEFAULT_TRAIT_ACCESS,
39 "checks for literal calls to Default::default()"
42 #[derive(Copy, Clone)]
43 pub struct DefaultTraitAccess;
45 impl LintPass for DefaultTraitAccess {
46 fn get_lints(&self) -> LintArray {
47 lint_array!(DEFAULT_TRAIT_ACCESS)
51 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess {
52 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
54 if let ExprKind::Call(ref path, ..) = expr.node;
55 if !any_parent_is_automatically_derived(cx.tcx, expr.id);
56 if let ExprKind::Path(ref qpath) = path.node;
57 if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
58 if match_def_path(cx.tcx, def_id, &paths::DEFAULT_TRAIT_METHOD);
61 QPath::Resolved(..) => {
63 // Detect and ignore <Foo as Default>::default() because these calls do
64 // explicitly name the type.
65 if let ExprKind::Call(ref method, ref _args) = expr.node;
66 if let ExprKind::Path(ref p) = method.node;
67 if let QPath::Resolved(Some(_ty), _path) = p;
73 // TODO: Work out a way to put "whatever the imported way of referencing
74 // this type in this file" rather than a fully-qualified type.
75 let expr_ty = cx.tables.expr_ty(expr);
76 if let TyKind::Adt(..) = expr_ty.sty {
77 let replacement = format!("{}::default()", expr_ty);
82 &format!("Calling {} is more clear than this expression", replacement),
85 Applicability::Unspecified,
89 QPath::TypeRelative(..) => {},