|
| 1 | +use clippy_utils::diagnostics::span_lint_and_sugg; |
| 2 | +use clippy_utils::sugg::Sugg; |
| 3 | +use clippy_utils::{expr_or_init, is_path_diagnostic_item, path_res}; |
| 4 | +use rustc_errors::Applicability; |
| 5 | +use rustc_hir::def::{CtorKind, DefKind, Res}; |
| 6 | +use rustc_hir::{Expr, ExprKind, QPath}; |
| 7 | +use rustc_infer::infer::InferCtxt; |
| 8 | +use rustc_infer::traits::{Obligation, ObligationCause}; |
| 9 | +use rustc_lint::{LateContext, LateLintPass}; |
| 10 | +use rustc_middle::ty::{self, GenericPredicates, ParamTy, PredicatePolarity, Ty}; |
| 11 | +use rustc_session::declare_lint_pass; |
| 12 | +use rustc_span::sym; |
| 13 | +use rustc_trait_selection::infer::TyCtxtInferExt; |
| 14 | +use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; |
| 15 | +use std::iter; |
| 16 | + |
| 17 | +declare_clippy_lint! { |
| 18 | + /// ### What it does |
| 19 | + /// Detects expressions being enclosed in `Path::new` when passed to a function which would |
| 20 | + /// accept the enclosed expression directly. |
| 21 | + /// |
| 22 | + /// ### Why is this bad? |
| 23 | + /// It is unnecessarily verbose |
| 24 | + /// |
| 25 | + /// ### Example |
| 26 | + /// ```no_run |
| 27 | + /// # use std::{fs, path::Path}; |
| 28 | + /// fs::write(Path::new("foo.txt"), "foo"); |
| 29 | + /// ``` |
| 30 | + /// Use instead: |
| 31 | + /// ```no_run |
| 32 | + /// # use std::{fs, path::Path}; |
| 33 | + /// fs::write("foo.txt", "foo"); |
| 34 | + /// ``` |
| 35 | + #[clippy::version = "1.92.0"] |
| 36 | + pub NEEDLESS_PATH_NEW, |
| 37 | + nursery, |
| 38 | + "`Path::new(x)` passed as an argument where `x` would suffice" |
| 39 | +} |
| 40 | + |
| 41 | +declare_lint_pass!(NeedlessPathNew => [NEEDLESS_PATH_NEW]); |
| 42 | + |
| 43 | +impl<'tcx> LateLintPass<'tcx> for NeedlessPathNew { |
| 44 | + fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx Expr<'tcx>) { |
| 45 | + let tcx = cx.tcx; |
| 46 | + |
| 47 | + let (fn_did, args) = match e.kind { |
| 48 | + ExprKind::Call(callee, args) |
| 49 | + if let Res::Def(DefKind::Fn | DefKind::AssocFn | DefKind::Ctor(_, CtorKind::Fn), did) = |
| 50 | + // re: `expr_or_init`: `callee` might be a variable storing a fn ptr, for example, |
| 51 | + // so we need to get to the actual initializer |
| 52 | + path_res(cx, expr_or_init(cx, callee)) => |
| 53 | + { |
| 54 | + (did, args) |
| 55 | + }, |
| 56 | + ExprKind::MethodCall(_, _, args, _) |
| 57 | + if let Some(did) = cx.typeck_results().type_dependent_def_id(e.hir_id) => |
| 58 | + { |
| 59 | + (did, args) |
| 60 | + }, |
| 61 | + _ => return, |
| 62 | + }; |
| 63 | + |
| 64 | + let sig = tcx.fn_sig(fn_did).skip_binder().skip_binder(); |
| 65 | + |
| 66 | + let infcx = cx.tcx.infer_ctxt().build(cx.typing_mode()); |
| 67 | + |
| 68 | + // `ExprKind::MethodCall` doesn't include the receiver in `args`, but does in `sig.inputs()` |
| 69 | + // -- so we iterate over both in `rev`erse in order to line them up starting from the _end_ |
| 70 | + // |
| 71 | + // and for `ExprKind::Call` this is basically a no-op |
| 72 | + iter::zip(sig.inputs().iter().rev(), args.iter().rev()) |
| 73 | + .enumerate() |
| 74 | + .for_each(|(arg_idx, (arg_ty, arg))| { |
| 75 | + // we want `arg` to be `Path::new(x)` |
| 76 | + if let ExprKind::Call(path_new, [x]) = arg.kind |
| 77 | + && let ExprKind::Path(QPath::TypeRelative(path, new)) = path_new.kind |
| 78 | + && is_path_diagnostic_item(cx, path, sym::Path) |
| 79 | + && new.ident.name == sym::new |
| 80 | + && let ty::Param(arg_param_ty) = arg_ty.kind() |
| 81 | + && !is_used_anywhere_else( |
| 82 | + *arg_param_ty, |
| 83 | + sig.inputs() |
| 84 | + .iter() |
| 85 | + // `arg_idx` is based on the reversed order, so we need to reverse as well for the |
| 86 | + // `enumerate` indices to work |
| 87 | + .rev() |
| 88 | + .enumerate() |
| 89 | + .filter_map(|(i, input)| (i != arg_idx).then_some(*input)), |
| 90 | + ) |
| 91 | + && let x_ty = cx.typeck_results().expr_ty(x) |
| 92 | + && has_required_preds(cx, &infcx, *arg_ty, x_ty, cx.tcx.predicates_of(fn_did)) |
| 93 | + { |
| 94 | + let mut applicability = Applicability::MachineApplicable; |
| 95 | + let sugg = Sugg::hir_with_applicability(cx, x, "_", &mut applicability); |
| 96 | + span_lint_and_sugg( |
| 97 | + cx, |
| 98 | + NEEDLESS_PATH_NEW, |
| 99 | + arg.span, |
| 100 | + "the expression enclosed in `Path::new` can be passed directly", |
| 101 | + "try", |
| 102 | + sugg.to_string(), |
| 103 | + applicability, |
| 104 | + ); |
| 105 | + } |
| 106 | + }); |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +fn is_used_anywhere_else<'tcx>(param_ty: ParamTy, mut other_sig_tys: impl Iterator<Item = Ty<'tcx>>) -> bool { |
| 111 | + other_sig_tys.any(|sig_ty| { |
| 112 | + sig_ty.walk().any(|generic_arg| { |
| 113 | + if let Some(ty) = generic_arg.as_type() |
| 114 | + && let ty::Param(pt) = ty.kind() |
| 115 | + && *pt == param_ty |
| 116 | + { |
| 117 | + true |
| 118 | + } else { |
| 119 | + false |
| 120 | + } |
| 121 | + }) |
| 122 | + }) |
| 123 | +} |
| 124 | + |
| 125 | +fn has_required_preds<'tcx>( |
| 126 | + cx: &LateContext<'tcx>, |
| 127 | + infcx: &InferCtxt<'tcx>, |
| 128 | + param_ty: Ty<'tcx>, |
| 129 | + x_ty: Ty<'tcx>, |
| 130 | + preds: GenericPredicates<'tcx>, |
| 131 | +) -> bool { |
| 132 | + let mut has_preds = false; |
| 133 | + |
| 134 | + let has_required_preds = preds |
| 135 | + .predicates |
| 136 | + .iter() |
| 137 | + .filter_map(|(clause, _)| clause.as_trait_clause()) |
| 138 | + .map(|pred| pred.skip_binder()) |
| 139 | + .filter(|pred| { |
| 140 | + // dbg!(pred.self_ty(), param_ty); |
| 141 | + pred.self_ty() == param_ty |
| 142 | + }) |
| 143 | + .all(|pred| { |
| 144 | + has_preds = true; |
| 145 | + |
| 146 | + if pred.polarity != PredicatePolarity::Positive { |
| 147 | + return false; |
| 148 | + } |
| 149 | + |
| 150 | + let new_pred = pred.with_replaced_self_ty(cx.tcx, x_ty); |
| 151 | + let obligation = Obligation::new(cx.tcx, ObligationCause::dummy(), cx.param_env, new_pred); |
| 152 | + infcx.predicate_must_hold_modulo_regions(&obligation) |
| 153 | + // match cx.tcx.get_diagnostic_name(pred.def_id()) { |
| 154 | + // Some(sym::AsRef) => { |
| 155 | + // // TODO: check if it's `AsRef<Path>` in paricular |
| 156 | + // }, |
| 157 | + // Some(sym::Sized) => todo!(), |
| 158 | + // _ => return false, |
| 159 | + // }; |
| 160 | + }); |
| 161 | + |
| 162 | + if !has_preds { |
| 163 | + // There were no trait clauses -- this means that the type just needs to be `Path`, so the |
| 164 | + // lint is not applicable |
| 165 | + return false; |
| 166 | + } |
| 167 | + |
| 168 | + has_required_preds |
| 169 | +} |
0 commit comments