2018-06-14 07:57:27 +00:00
|
|
|
use rustc::hir::*;
|
|
|
|
use rustc::lint::*;
|
2018-07-19 07:53:23 +00:00
|
|
|
use rustc::{declare_lint, lint_array};
|
2018-06-17 21:58:08 +00:00
|
|
|
use rustc::ty::TypeVariants;
|
2018-06-14 07:57:27 +00:00
|
|
|
|
2018-06-17 21:58:08 +00:00
|
|
|
use crate::utils::{any_parent_is_automatically_derived, match_def_path, opt_def_id, paths, span_lint_and_sugg};
|
2018-06-14 07:57:27 +00:00
|
|
|
|
|
|
|
|
|
|
|
/// **What it does:** Checks for literal calls to `Default::default()`.
|
|
|
|
///
|
|
|
|
/// **Why is this bad?** It's more clear to the reader to use the name of the type whose default is
|
|
|
|
/// being gotten than the generic `Default`.
|
|
|
|
///
|
|
|
|
/// **Known problems:** None.
|
|
|
|
///
|
|
|
|
/// **Example:**
|
|
|
|
/// ```rust
|
|
|
|
/// // Bad
|
|
|
|
/// let s: String = Default::default();
|
|
|
|
///
|
|
|
|
/// // Good
|
|
|
|
/// let s = String::default();
|
|
|
|
/// ```
|
|
|
|
declare_clippy_lint! {
|
|
|
|
pub DEFAULT_TRAIT_ACCESS,
|
2018-06-25 18:39:48 +00:00
|
|
|
pedantic,
|
2018-06-14 07:57:27 +00:00
|
|
|
"checks for literal calls to Default::default()"
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Copy, Clone)]
|
|
|
|
pub struct DefaultTraitAccess;
|
|
|
|
|
|
|
|
impl LintPass for DefaultTraitAccess {
|
|
|
|
fn get_lints(&self) -> LintArray {
|
|
|
|
lint_array!(DEFAULT_TRAIT_ACCESS)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for DefaultTraitAccess {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) {
|
|
|
|
if_chain! {
|
2018-07-12 07:30:57 +00:00
|
|
|
if let ExprKind::Call(ref path, ..) = expr.node;
|
2018-06-17 21:58:08 +00:00
|
|
|
if !any_parent_is_automatically_derived(cx.tcx, expr.id);
|
2018-07-12 07:30:57 +00:00
|
|
|
if let ExprKind::Path(ref qpath) = path.node;
|
2018-06-14 07:57:27 +00:00
|
|
|
if let Some(def_id) = opt_def_id(cx.tables.qpath_def(qpath, path.hir_id));
|
|
|
|
if match_def_path(cx.tcx, def_id, &paths::DEFAULT_TRAIT_METHOD);
|
|
|
|
then {
|
|
|
|
match qpath {
|
|
|
|
QPath::Resolved(..) => {
|
|
|
|
// TODO: Work out a way to put "whatever the imported way of referencing
|
|
|
|
// this type in this file" rather than a fully-qualified type.
|
2018-06-17 21:58:08 +00:00
|
|
|
let expr_ty = cx.tables.expr_ty(expr);
|
|
|
|
if let TypeVariants::TyAdt(..) = expr_ty.sty {
|
|
|
|
let replacement = format!("{}::default()", expr_ty);
|
|
|
|
span_lint_and_sugg(
|
|
|
|
cx,
|
|
|
|
DEFAULT_TRAIT_ACCESS,
|
|
|
|
expr.span,
|
|
|
|
&format!("Calling {} is more clear than this expression", replacement),
|
|
|
|
"try",
|
|
|
|
replacement);
|
|
|
|
}
|
2018-06-14 07:57:27 +00:00
|
|
|
},
|
|
|
|
QPath::TypeRelative(..) => {},
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|