3 use rustc::{declare_lint, lint_array};
4 use if_chain::if_chain;
7 use crate::utils::{any_parent_is_automatically_derived, match_def_path, opt_def_id, paths, span_lint_and_sugg};
10 /// **What it does:** Checks for literal calls to `Default::default()`.
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`.
15 /// **Known problems:** None.
20 /// let s: String = Default::default();
23 /// let s = String::default();
25 declare_clippy_lint! {
26 pub DEFAULT_TRAIT_ACCESS,
28 "checks for literal calls to Default::default()"
31 #[derive(Copy, Clone)]
32 pub struct DefaultTraitAccess;
34 impl LintPass for DefaultTraitAccess {
35 fn get_lints(&self) -> LintArray {
36 lint_array!(DEFAULT_TRAIT_ACCESS)
40 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess {
41 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
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);
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);
60 &format!("Calling {} is more clear than this expression", replacement),
65 QPath::TypeRelative(..) => {},