-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Rollup merge of #5226 - ThibsG:DerefExplicit1566, r=flip1995
Add lint for explicit deref and deref_mut method calls This PR adds the lint `explicit_deref_method` that suggests replacing `deref()` and `deref_mut()` with `&*a` and `&mut *a`. It doesn't lint inside macros. This PR is the continuation of #3258. changelog: Add lint `explicit_deref_method`. Fixes: #1566
- Loading branch information
Showing
7 changed files
with
381 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,113 @@ | ||
use crate::utils::{get_parent_expr, implements_trait, snippet, span_lint_and_sugg}; | ||
use if_chain::if_chain; | ||
use rustc_ast::util::parser::{ExprPrecedence, PREC_POSTFIX, PREC_PREFIX}; | ||
use rustc_errors::Applicability; | ||
use rustc_hir::{Expr, ExprKind}; | ||
use rustc_lint::{LateContext, LateLintPass}; | ||
use rustc_session::{declare_lint_pass, declare_tool_lint}; | ||
use rustc_span::source_map::Span; | ||
|
||
declare_clippy_lint! { | ||
/// **What it does:** Checks for explicit `deref()` or `deref_mut()` method calls. | ||
/// | ||
/// **Why is this bad?** Derefencing by `&*x` or `&mut *x` is clearer and more concise, | ||
/// when not part of a method chain. | ||
/// | ||
/// **Example:** | ||
/// ```rust | ||
/// use std::ops::Deref; | ||
/// let a: &mut String = &mut String::from("foo"); | ||
/// let b: &str = a.deref(); | ||
/// ``` | ||
/// Could be written as: | ||
/// ```rust | ||
/// let a: &mut String = &mut String::from("foo"); | ||
/// let b = &*a; | ||
/// ``` | ||
/// | ||
/// This lint excludes | ||
/// ```rust,ignore | ||
/// let _ = d.unwrap().deref(); | ||
/// ``` | ||
pub EXPLICIT_DEREF_METHODS, | ||
pedantic, | ||
"Explicit use of deref or deref_mut method while not in a method chain." | ||
} | ||
|
||
declare_lint_pass!(Dereferencing => [ | ||
EXPLICIT_DEREF_METHODS | ||
]); | ||
|
||
impl<'a, 'tcx> LateLintPass<'a, 'tcx> for Dereferencing { | ||
fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) { | ||
if_chain! { | ||
if !expr.span.from_expansion(); | ||
if let ExprKind::MethodCall(ref method_name, _, ref args) = &expr.kind; | ||
if args.len() == 1; | ||
|
||
then { | ||
if let Some(parent_expr) = get_parent_expr(cx, expr) { | ||
// Check if we have the whole call chain here | ||
if let ExprKind::MethodCall(..) = parent_expr.kind { | ||
return; | ||
} | ||
// Check for Expr that we don't want to be linted | ||
let precedence = parent_expr.precedence(); | ||
match precedence { | ||
// Lint a Call is ok though | ||
ExprPrecedence::Call | ExprPrecedence::AddrOf => (), | ||
_ => { | ||
if precedence.order() >= PREC_PREFIX && precedence.order() <= PREC_POSTFIX { | ||
return; | ||
} | ||
} | ||
} | ||
} | ||
let name = method_name.ident.as_str(); | ||
lint_deref(cx, &*name, &args[0], args[0].span, expr.span); | ||
} | ||
} | ||
} | ||
} | ||
|
||
fn lint_deref(cx: &LateContext<'_, '_>, method_name: &str, call_expr: &Expr<'_>, var_span: Span, expr_span: Span) { | ||
match method_name { | ||
"deref" => { | ||
if cx | ||
.tcx | ||
.lang_items() | ||
.deref_trait() | ||
.map_or(false, |id| implements_trait(cx, cx.tables.expr_ty(&call_expr), id, &[])) | ||
{ | ||
span_lint_and_sugg( | ||
cx, | ||
EXPLICIT_DEREF_METHODS, | ||
expr_span, | ||
"explicit deref method call", | ||
"try this", | ||
format!("&*{}", &snippet(cx, var_span, "..")), | ||
Applicability::MachineApplicable, | ||
); | ||
} | ||
}, | ||
"deref_mut" => { | ||
if cx | ||
.tcx | ||
.lang_items() | ||
.deref_mut_trait() | ||
.map_or(false, |id| implements_trait(cx, cx.tables.expr_ty(&call_expr), id, &[])) | ||
{ | ||
span_lint_and_sugg( | ||
cx, | ||
EXPLICIT_DEREF_METHODS, | ||
expr_span, | ||
"explicit deref_mut method call", | ||
"try this", | ||
format!("&mut *{}", &snippet(cx, var_span, "..")), | ||
Applicability::MachineApplicable, | ||
); | ||
} | ||
}, | ||
_ => (), | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
// run-rustfix | ||
|
||
#![allow(unused_variables, clippy::many_single_char_names, clippy::clone_double_ref)] | ||
#![warn(clippy::explicit_deref_methods)] | ||
|
||
use std::ops::{Deref, DerefMut}; | ||
|
||
fn concat(deref_str: &str) -> String { | ||
format!("{}bar", deref_str) | ||
} | ||
|
||
fn just_return(deref_str: &str) -> &str { | ||
deref_str | ||
} | ||
|
||
struct CustomVec(Vec<u8>); | ||
impl Deref for CustomVec { | ||
type Target = Vec<u8>; | ||
|
||
fn deref(&self) -> &Vec<u8> { | ||
&self.0 | ||
} | ||
} | ||
|
||
fn main() { | ||
let a: &mut String = &mut String::from("foo"); | ||
|
||
// these should require linting | ||
|
||
let b: &str = &*a; | ||
|
||
let b: &mut str = &mut *a; | ||
|
||
// both derefs should get linted here | ||
let b: String = format!("{}, {}", &*a, &*a); | ||
|
||
println!("{}", &*a); | ||
|
||
#[allow(clippy::match_single_binding)] | ||
match &*a { | ||
_ => (), | ||
} | ||
|
||
let b: String = concat(&*a); | ||
|
||
let b = &*just_return(a); | ||
|
||
let b: String = concat(&*just_return(a)); | ||
|
||
let b: &str = &*a.deref(); | ||
|
||
let opt_a = Some(a.clone()); | ||
let b = &*opt_a.unwrap(); | ||
|
||
// following should not require linting | ||
|
||
let cv = CustomVec(vec![0, 42]); | ||
let c = cv.deref()[0]; | ||
|
||
let b: &str = &*a.deref(); | ||
|
||
let b: String = a.deref().clone(); | ||
|
||
let b: usize = a.deref_mut().len(); | ||
|
||
let b: &usize = &a.deref().len(); | ||
|
||
let b: &str = &*a; | ||
|
||
let b: &mut str = &mut *a; | ||
|
||
macro_rules! expr_deref { | ||
($body:expr) => { | ||
$body.deref() | ||
}; | ||
} | ||
let b: &str = expr_deref!(a); | ||
|
||
// The struct does not implement Deref trait | ||
#[derive(Copy, Clone)] | ||
struct NoLint(u32); | ||
impl NoLint { | ||
pub fn deref(self) -> u32 { | ||
self.0 | ||
} | ||
pub fn deref_mut(self) -> u32 { | ||
self.0 | ||
} | ||
} | ||
let no_lint = NoLint(42); | ||
let b = no_lint.deref(); | ||
let b = no_lint.deref_mut(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
// run-rustfix | ||
|
||
#![allow(unused_variables, clippy::many_single_char_names, clippy::clone_double_ref)] | ||
#![warn(clippy::explicit_deref_methods)] | ||
|
||
use std::ops::{Deref, DerefMut}; | ||
|
||
fn concat(deref_str: &str) -> String { | ||
format!("{}bar", deref_str) | ||
} | ||
|
||
fn just_return(deref_str: &str) -> &str { | ||
deref_str | ||
} | ||
|
||
struct CustomVec(Vec<u8>); | ||
impl Deref for CustomVec { | ||
type Target = Vec<u8>; | ||
|
||
fn deref(&self) -> &Vec<u8> { | ||
&self.0 | ||
} | ||
} | ||
|
||
fn main() { | ||
let a: &mut String = &mut String::from("foo"); | ||
|
||
// these should require linting | ||
|
||
let b: &str = a.deref(); | ||
|
||
let b: &mut str = a.deref_mut(); | ||
|
||
// both derefs should get linted here | ||
let b: String = format!("{}, {}", a.deref(), a.deref()); | ||
|
||
println!("{}", a.deref()); | ||
|
||
#[allow(clippy::match_single_binding)] | ||
match a.deref() { | ||
_ => (), | ||
} | ||
|
||
let b: String = concat(a.deref()); | ||
|
||
let b = just_return(a).deref(); | ||
|
||
let b: String = concat(just_return(a).deref()); | ||
|
||
let b: &str = a.deref().deref(); | ||
|
||
let opt_a = Some(a.clone()); | ||
let b = opt_a.unwrap().deref(); | ||
|
||
// following should not require linting | ||
|
||
let cv = CustomVec(vec![0, 42]); | ||
let c = cv.deref()[0]; | ||
|
||
let b: &str = &*a.deref(); | ||
|
||
let b: String = a.deref().clone(); | ||
|
||
let b: usize = a.deref_mut().len(); | ||
|
||
let b: &usize = &a.deref().len(); | ||
|
||
let b: &str = &*a; | ||
|
||
let b: &mut str = &mut *a; | ||
|
||
macro_rules! expr_deref { | ||
($body:expr) => { | ||
$body.deref() | ||
}; | ||
} | ||
let b: &str = expr_deref!(a); | ||
|
||
// The struct does not implement Deref trait | ||
#[derive(Copy, Clone)] | ||
struct NoLint(u32); | ||
impl NoLint { | ||
pub fn deref(self) -> u32 { | ||
self.0 | ||
} | ||
pub fn deref_mut(self) -> u32 { | ||
self.0 | ||
} | ||
} | ||
let no_lint = NoLint(42); | ||
let b = no_lint.deref(); | ||
let b = no_lint.deref_mut(); | ||
} |
Oops, something went wrong.