1 use if_chain::if_chain;
3 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
5 use rustc::{declare_tool_lint, lint_array};
6 use rustc_errors::Applicability;
8 use crate::utils::{any_parent_is_automatically_derived, paths, span_lint_and_sugg};
10 declare_clippy_lint! {
11 /// **What it does:** Checks for literal calls to `Default::default()`.
13 /// **Why is this bad?** It's more clear to the reader to use the name of the type whose default is
14 /// being gotten than the generic `Default`.
16 /// **Known problems:** None.
21 /// let s: String = Default::default();
24 /// let s = String::default();
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)
39 fn name(&self) -> &'static str {
44 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess {
45 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
47 if let ExprKind::Call(ref path, ..) = expr.node;
48 if !any_parent_is_automatically_derived(cx.tcx, expr.hir_id);
49 if let ExprKind::Path(ref qpath) = path.node;
50 if let Some(def_id) = cx.tables.qpath_def(qpath, path.hir_id).opt_def_id();
51 if cx.match_def_path(def_id, &paths::DEFAULT_TRAIT_METHOD);
54 QPath::Resolved(..) => {
56 // Detect and ignore <Foo as Default>::default() because these calls do
57 // explicitly name the type.
58 if let ExprKind::Call(ref method, ref _args) = expr.node;
59 if let ExprKind::Path(ref p) = method.node;
60 if let QPath::Resolved(Some(_ty), _path) = p;
66 // TODO: Work out a way to put "whatever the imported way of referencing
67 // this type in this file" rather than a fully-qualified type.
68 let expr_ty = cx.tables.expr_ty(expr);
69 if let ty::Adt(..) = expr_ty.sty {
70 let replacement = format!("{}::default()", expr_ty);
75 &format!("Calling {} is more clear than this expression", replacement),
78 Applicability::Unspecified, // First resolve the TODO above
82 QPath::TypeRelative(..) => {},