Skip to content

Commit

Permalink
Auto merge of #9279 - tabokie:weight-loss, r=flip1995
Browse files Browse the repository at this point in the history
chore: a few small improvements to code quality

Some improvements:
- Simplify implementation of `is_unit_type`
- Use slice matching to destruct `Call` or `MethodCall` whenever possible

changelog: none

r? `@flip1995`
  • Loading branch information
bors committed Aug 2, 2022
2 parents 367d09f + ac7a91e commit 4914833
Show file tree
Hide file tree
Showing 19 changed files with 60 additions and 91 deletions.
5 changes: 1 addition & 4 deletions clippy_lints/src/checked_conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,7 @@ fn get_types_from_cast<'a>(
let limit_from: Option<(&Expr<'_>, &str)> = call_from_cast.or_else(|| {
if_chain! {
// `from_type::from, to_type::max_value()`
if let ExprKind::Call(from_func, args) = &expr.kind;
// `to_type::max_value()`
if args.len() == 1;
if let limit = &args[0];
if let ExprKind::Call(from_func, [limit]) = &expr.kind;
// `from_type::from`
if let ExprKind::Path(ref path) = &from_func.kind;
if let Some(from_sym) = get_implementing_type(path, INTS, "from");
Expand Down
4 changes: 2 additions & 2 deletions clippy_lints/src/create_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ declare_lint_pass!(CreateDir => [CREATE_DIR]);
impl LateLintPass<'_> for CreateDir {
fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
if_chain! {
if let ExprKind::Call(func, args) = expr.kind;
if let ExprKind::Call(func, [arg, ..]) = expr.kind;
if let ExprKind::Path(ref path) = func.kind;
if let Some(def_id) = cx.qpath_res(path, func.hir_id).opt_def_id();
if match_def_path(cx, def_id, &paths::STD_FS_CREATE_DIR);
Expand All @@ -45,7 +45,7 @@ impl LateLintPass<'_> for CreateDir {
expr.span,
"calling `std::fs::create_dir` where there may be a better way",
"consider calling `std::fs::create_dir_all` instead",
format!("create_dir_all({})", snippet(cx, args[0].span, "..")),
format!("create_dir_all({})", snippet(cx, arg.span, "..")),
Applicability::MaybeIncorrect,
)
}
Expand Down
11 changes: 5 additions & 6 deletions clippy_lints/src/from_str_radix_10.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ declare_lint_pass!(FromStrRadix10 => [FROM_STR_RADIX_10]);
impl<'tcx> LateLintPass<'tcx> for FromStrRadix10 {
fn check_expr(&mut self, cx: &LateContext<'tcx>, exp: &Expr<'tcx>) {
if_chain! {
if let ExprKind::Call(maybe_path, arguments) = &exp.kind;
if let ExprKind::Call(maybe_path, [src, radix]) = &exp.kind;
if let ExprKind::Path(QPath::TypeRelative(ty, pathseg)) = &maybe_path.kind;

// check if the first part of the path is some integer primitive
Expand All @@ -60,20 +60,19 @@ impl<'tcx> LateLintPass<'tcx> for FromStrRadix10 {
if pathseg.ident.name.as_str() == "from_str_radix";

// check if the second argument is a primitive `10`
if arguments.len() == 2;
if let ExprKind::Lit(lit) = &arguments[1].kind;
if let ExprKind::Lit(lit) = &radix.kind;
if let rustc_ast::ast::LitKind::Int(10, _) = lit.node;

then {
let expr = if let ExprKind::AddrOf(_, _, expr) = &arguments[0].kind {
let expr = if let ExprKind::AddrOf(_, _, expr) = &src.kind {
let ty = cx.typeck_results().expr_ty(expr);
if is_ty_stringish(cx, ty) {
expr
} else {
&arguments[0]
&src
}
} else {
&arguments[0]
&src
};

let sugg = Sugg::hir_with_applicability(
Expand Down
10 changes: 3 additions & 7 deletions clippy_lints/src/loops/manual_memcpy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,11 +119,9 @@ fn build_manual_memcpy_suggestion<'tcx>(

let print_limit = |end: &Expr<'_>, end_str: &str, base: &Expr<'_>, sugg: MinifyingSugg<'static>| {
if_chain! {
if let ExprKind::MethodCall(method, len_args, _) = end.kind;
if let ExprKind::MethodCall(method, [recv], _) = end.kind;
if method.ident.name == sym::len;
if len_args.len() == 1;
if let Some(arg) = len_args.get(0);
if path_to_local(arg) == path_to_local(base);
if path_to_local(recv) == path_to_local(base);
then {
if sugg.to_string() == end_str {
sugg::EMPTY.into()
Expand Down Expand Up @@ -343,10 +341,8 @@ fn get_slice_like_element_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Opti

fn fetch_cloned_expr<'tcx>(expr: &'tcx Expr<'tcx>) -> &'tcx Expr<'tcx> {
if_chain! {
if let ExprKind::MethodCall(method, args, _) = expr.kind;
if let ExprKind::MethodCall(method, [arg], _) = expr.kind;
if method.ident.name == sym::clone;
if args.len() == 1;
if let Some(arg) = args.get(0);
then { arg } else { expr }
}
}
Expand Down
5 changes: 2 additions & 3 deletions clippy_lints/src/loops/needless_range_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -188,10 +188,9 @@ pub(super) fn check<'tcx>(

fn is_len_call(expr: &Expr<'_>, var: Symbol) -> bool {
if_chain! {
if let ExprKind::MethodCall(method, len_args, _) = expr.kind;
if len_args.len() == 1;
if let ExprKind::MethodCall(method, [recv], _) = expr.kind;
if method.ident.name == sym::len;
if let ExprKind::Path(QPath::Resolved(_, path)) = len_args[0].kind;
if let ExprKind::Path(QPath::Resolved(_, path)) = recv.kind;
if path.segments.len() == 1;
if path.segments[0].ident.name == var;
then {
Expand Down
11 changes: 4 additions & 7 deletions clippy_lints/src/manual_ok_or.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,14 @@ impl<'tcx> LateLintPass<'tcx> for ManualOkOr {
}

if_chain! {
if let ExprKind::MethodCall(method_segment, args, _) = scrutinee.kind;
if let ExprKind::MethodCall(method_segment, [receiver, or_expr, map_expr], _) = scrutinee.kind;
if method_segment.ident.name == sym!(map_or);
if args.len() == 3;
let method_receiver = &args[0];
let ty = cx.typeck_results().expr_ty(method_receiver);
let ty = cx.typeck_results().expr_ty(receiver);
if is_type_diagnostic_item(cx, ty, sym::Option);
let or_expr = &args[1];
if is_ok_wrapping(cx, &args[2]);
if is_ok_wrapping(cx, map_expr);
if let ExprKind::Call(Expr { kind: ExprKind::Path(err_path), .. }, &[ref err_arg]) = or_expr.kind;
if is_lang_ctor(cx, err_path, ResultErr);
if let Some(method_receiver_snippet) = snippet_opt(cx, method_receiver.span);
if let Some(method_receiver_snippet) = snippet_opt(cx, receiver.span);
if let Some(err_arg_snippet) = snippet_opt(cx, err_arg.span);
if let Some(indent) = indent_of(cx, scrutinee.span);
then {
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/map_err_ignore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -113,18 +113,18 @@ impl<'tcx> LateLintPass<'tcx> for MapErrIgnore {
}

// check if this is a method call (e.g. x.foo())
if let ExprKind::MethodCall(method, args, _) = e.kind {
if let ExprKind::MethodCall(method, [_, arg], _) = e.kind {
// only work if the method name is `map_err` and there are only 2 arguments (e.g. x.map_err(|_|[1]
// Enum::Variant[2]))
if method.ident.as_str() == "map_err" && args.len() == 2 {
if method.ident.name == sym!(map_err) {
// make sure the first argument is a closure, and grab the CaptureRef, BodyId, and fn_decl_span
// fields
if let ExprKind::Closure(&Closure {
capture_clause,
body,
fn_decl_span,
..
}) = args[1].kind
}) = arg.kind
{
// check if this is by Reference (meaning there's no move statement)
if capture_clause == CaptureBy::Ref {
Expand Down
6 changes: 1 addition & 5 deletions clippy_lints/src/map_unit_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,7 @@ declare_clippy_lint! {
declare_lint_pass!(MapUnit => [OPTION_MAP_UNIT_FN, RESULT_MAP_UNIT_FN]);

fn is_unit_type(ty: Ty<'_>) -> bool {
match ty.kind() {
ty::Tuple(slice) => slice.is_empty(),
ty::Never => true,
_ => false,
}
ty.is_unit() || ty.is_never()
}

fn is_unit_function(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
Expand Down
6 changes: 3 additions & 3 deletions clippy_lints/src/matches/match_as_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,10 @@ fn is_ref_some_arm(cx: &LateContext<'_>, arm: &Arm<'_>) -> Option<BindingAnnotat
if is_lang_ctor(cx, qpath, LangItem::OptionSome);
if let PatKind::Binding(rb, .., ident, _) = first_pat.kind;
if rb == BindingAnnotation::Ref || rb == BindingAnnotation::RefMut;
if let ExprKind::Call(e, args) = peel_blocks(arm.body).kind;
if let ExprKind::Call(e, [arg]) = peel_blocks(arm.body).kind;
if let ExprKind::Path(ref some_path) = e.kind;
if is_lang_ctor(cx, some_path, LangItem::OptionSome) && args.len() == 1;
if let ExprKind::Path(QPath::Resolved(_, path2)) = args[0].kind;
if is_lang_ctor(cx, some_path, LangItem::OptionSome);
if let ExprKind::Path(QPath::Resolved(_, path2)) = arg.kind;
if path2.segments.len() == 1 && ident.name == path2.segments[0].ident.name;
then {
return Some(rb)
Expand Down
6 changes: 2 additions & 4 deletions clippy_lints/src/matches/try_err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,10 @@ pub(super) fn check<'tcx>(cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>, scrutine
// val,
// };
if_chain! {
if let ExprKind::Call(match_fun, try_args) = scrutinee.kind;
if let ExprKind::Call(match_fun, [try_arg, ..]) = scrutinee.kind;
if let ExprKind::Path(ref match_fun_path) = match_fun.kind;
if matches!(match_fun_path, QPath::LangItem(LangItem::TryTraitBranch, ..));
if let Some(try_arg) = try_args.get(0);
if let ExprKind::Call(err_fun, err_args) = try_arg.kind;
if let Some(err_arg) = err_args.get(0);
if let ExprKind::Call(err_fun, [err_arg, ..]) = try_arg.kind;
if let ExprKind::Path(ref err_fun_path) = err_fun.kind;
if is_lang_ctor(cx, err_fun_path, ResultErr);
if let Some(return_ty) = find_return_type(cx, &expr.kind);
Expand Down
6 changes: 2 additions & 4 deletions clippy_lints/src/mem_replace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,7 @@ fn check_replace_with_uninit(cx: &LateContext<'_>, src: &Expr<'_>, dest: &Expr<'
}

if_chain! {
if let ExprKind::Call(repl_func, repl_args) = src.kind;
if repl_args.is_empty();
if let ExprKind::Call(repl_func, []) = src.kind;
if let ExprKind::Path(ref repl_func_qpath) = repl_func.kind;
if let Some(repl_def_id) = cx.qpath_res(repl_func_qpath, repl_func.hir_id).opt_def_id();
then {
Expand Down Expand Up @@ -246,11 +245,10 @@ impl<'tcx> LateLintPass<'tcx> for MemReplace {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
// Check that `expr` is a call to `mem::replace()`
if let ExprKind::Call(func, func_args) = expr.kind;
if let ExprKind::Call(func, [dest, src]) = expr.kind;
if let ExprKind::Path(ref func_qpath) = func.kind;
if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id();
if cx.tcx.is_diagnostic_item(sym::mem_replace, def_id);
if let [dest, src] = func_args;
then {
check_replace_option_with_none(cx, src, dest, expr.span);
check_replace_with_uninit(cx, src, dest, expr.span);
Expand Down
6 changes: 2 additions & 4 deletions clippy_lints/src/path_buf_push_overwrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,9 @@ declare_lint_pass!(PathBufPushOverwrite => [PATH_BUF_PUSH_OVERWRITE]);
impl<'tcx> LateLintPass<'tcx> for PathBufPushOverwrite {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
if let ExprKind::MethodCall(path, args, _) = expr.kind;
if let ExprKind::MethodCall(path, [recv, get_index_arg], _) = expr.kind;
if path.ident.name == sym!(push);
if args.len() == 2;
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(&args[0]).peel_refs(), sym::PathBuf);
if let Some(get_index_arg) = args.get(1);
if is_type_diagnostic_item(cx, cx.typeck_results().expr_ty(recv).peel_refs(), sym::PathBuf);
if let ExprKind::Lit(ref lit) = get_index_arg.kind;
if let LitKind::Str(ref path_lit, _) = lit.node;
if let pushed_path = Path::new(path_lit.as_str());
Expand Down
3 changes: 1 addition & 2 deletions clippy_lints/src/question_mark.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,7 @@ fn check_is_none_or_err_and_early_return<'tcx>(cx: &LateContext<'tcx>, expr: &Ex
if_chain! {
if let Some(higher::If { cond, then, r#else }) = higher::If::hir(expr);
if !is_else_clause(cx.tcx, expr);
if let ExprKind::MethodCall(segment, args, _) = &cond.kind;
if let Some(caller) = args.get(0);
if let ExprKind::MethodCall(segment, [caller, ..], _) = &cond.kind;
let caller_ty = cx.typeck_results().expr_ty(caller);
let if_block = IfBlockType::IfIs(caller, caller_ty, segment.ident.name, then, r#else);
if is_early_return(sym::Option, cx, &if_block) || is_early_return(sym::Result, cx, &if_block);
Expand Down
12 changes: 6 additions & 6 deletions clippy_lints/src/ranges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,24 +385,24 @@ fn check_range_zip_with_len(cx: &LateContext<'_>, path: &PathSegment<'_>, args:
if path.ident.as_str() == "zip";
if let [iter, zip_arg] = args;
// `.iter()` call
if let ExprKind::MethodCall(iter_path, iter_args, _) = iter.kind;
if let ExprKind::MethodCall(iter_path, [iter_caller, ..], _) = iter.kind;
if iter_path.ident.name == sym::iter;
// range expression in `.zip()` call: `0..x.len()`
if let Some(higher::Range { start: Some(start), end: Some(end), .. }) = higher::Range::hir(zip_arg);
if is_integer_const(cx, start, 0);
// `.len()` call
if let ExprKind::MethodCall(len_path, len_args, _) = end.kind;
if len_path.ident.name == sym::len && len_args.len() == 1;
if let ExprKind::MethodCall(len_path, [len_caller], _) = end.kind;
if len_path.ident.name == sym::len;
// `.iter()` and `.len()` called on same `Path`
if let ExprKind::Path(QPath::Resolved(_, iter_path)) = iter_args[0].kind;
if let ExprKind::Path(QPath::Resolved(_, len_path)) = len_args[0].kind;
if let ExprKind::Path(QPath::Resolved(_, iter_path)) = iter_caller.kind;
if let ExprKind::Path(QPath::Resolved(_, len_path)) = len_caller.kind;
if SpanlessEq::new(cx).eq_path_segments(iter_path.segments, len_path.segments);
then {
span_lint(cx,
RANGE_ZIP_WITH_LEN,
span,
&format!("it is more idiomatic to use `{}.iter().enumerate()`",
snippet(cx, iter_args[0].span, "_"))
snippet(cx, iter_caller.span, "_"))
);
}
}
Expand Down
11 changes: 5 additions & 6 deletions clippy_lints/src/regex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,21 +57,20 @@ declare_lint_pass!(Regex => [INVALID_REGEX, TRIVIAL_REGEX]);
impl<'tcx> LateLintPass<'tcx> for Regex {
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) {
if_chain! {
if let ExprKind::Call(fun, args) = expr.kind;
if let ExprKind::Call(fun, [arg]) = expr.kind;
if let ExprKind::Path(ref qpath) = fun.kind;
if args.len() == 1;
if let Some(def_id) = cx.qpath_res(qpath, fun.hir_id).opt_def_id();
then {
if match_def_path(cx, def_id, &paths::REGEX_NEW) ||
match_def_path(cx, def_id, &paths::REGEX_BUILDER_NEW) {
check_regex(cx, &args[0], true);
check_regex(cx, arg, true);
} else if match_def_path(cx, def_id, &paths::REGEX_BYTES_NEW) ||
match_def_path(cx, def_id, &paths::REGEX_BYTES_BUILDER_NEW) {
check_regex(cx, &args[0], false);
check_regex(cx, arg, false);
} else if match_def_path(cx, def_id, &paths::REGEX_SET_NEW) {
check_set(cx, &args[0], true);
check_set(cx, arg, true);
} else if match_def_path(cx, def_id, &paths::REGEX_BYTES_SET_NEW) {
check_set(cx, &args[0], false);
check_set(cx, arg, false);
}
}
}
Expand Down
9 changes: 2 additions & 7 deletions clippy_lints/src/slow_vector_initialization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,15 +233,10 @@ impl<'a, 'tcx> VectorInitializationVisitor<'a, 'tcx> {
/// Returns `true` if give expression is `repeat(0).take(...)`
fn is_repeat_take(&self, expr: &Expr<'_>) -> bool {
if_chain! {
if let ExprKind::MethodCall(take_path, take_args, _) = expr.kind;
if let ExprKind::MethodCall(take_path, [recv, len_arg, ..], _) = expr.kind;
if take_path.ident.name == sym!(take);

// Check that take is applied to `repeat(0)`
if let Some(repeat_expr) = take_args.get(0);
if self.is_repeat_zero(repeat_expr);

if let Some(len_arg) = take_args.get(1);

if self.is_repeat_zero(recv);
then {
// Check that len expression is equals to `with_capacity` expression
if SpanlessEq::new(self.cx).eq_expr(len_arg, self.vec_alloc.len_expr) {
Expand Down
5 changes: 2 additions & 3 deletions clippy_lints/src/stable_sort_primitive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,11 @@ struct LintDetection {

fn detect_stable_sort_primitive(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<LintDetection> {
if_chain! {
if let ExprKind::MethodCall(method_name, args, _) = &expr.kind;
if let Some(slice) = &args.get(0);
if let ExprKind::MethodCall(method_name, [slice, args @ ..], _) = &expr.kind;
if let Some(method) = SortingKind::from_stable_name(method_name.ident.name.as_str());
if let Some(slice_type) = is_slice_of_primitives(cx, slice);
then {
let args_str = args.iter().skip(1).map(|arg| Sugg::hir(cx, arg, "..").to_string()).collect::<Vec<String>>().join(", ");
let args_str = args.iter().map(|arg| Sugg::hir(cx, arg, "..").to_string()).collect::<Vec<String>>().join(", ");
Some(LintDetection { slice_name: Sugg::hir(cx, slice, "..").to_string(), method, method_args: args_str, slice_type })
} else {
None
Expand Down
Loading

0 comments on commit 4914833

Please sign in to comment.