|
| 1 | +use crate::utils::is_type_diagnostic_item; |
| 2 | +use rustc_hir as hir; |
| 3 | +use rustc_lint::LateContext; |
| 4 | +use rustc_middle::ty; |
| 5 | +use rustc_middle::ty::Ty; |
| 6 | +use rustc_span::symbol::sym; |
| 7 | + |
| 8 | +pub fn derefs_to_slice<'tcx>( |
| 9 | + cx: &LateContext<'tcx>, |
| 10 | + expr: &'tcx hir::Expr<'tcx>, |
| 11 | + ty: Ty<'tcx>, |
| 12 | +) -> Option<&'tcx hir::Expr<'tcx>> { |
| 13 | + fn may_slice<'a>(cx: &LateContext<'a>, ty: Ty<'a>) -> bool { |
| 14 | + match ty.kind() { |
| 15 | + ty::Slice(_) => true, |
| 16 | + ty::Adt(def, _) if def.is_box() => may_slice(cx, ty.boxed_ty()), |
| 17 | + ty::Adt(..) => is_type_diagnostic_item(cx, ty, sym::vec_type), |
| 18 | + ty::Array(_, size) => size |
| 19 | + .try_eval_usize(cx.tcx, cx.param_env) |
| 20 | + .map_or(false, |size| size < 32), |
| 21 | + ty::Ref(_, inner, _) => may_slice(cx, inner), |
| 22 | + _ => false, |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + if let hir::ExprKind::MethodCall(ref path, _, ref args, _) = expr.kind { |
| 27 | + if path.ident.name == sym::iter && may_slice(cx, cx.typeck_results().expr_ty(&args[0])) { |
| 28 | + Some(&args[0]) |
| 29 | + } else { |
| 30 | + None |
| 31 | + } |
| 32 | + } else { |
| 33 | + match ty.kind() { |
| 34 | + ty::Slice(_) => Some(expr), |
| 35 | + ty::Adt(def, _) if def.is_box() && may_slice(cx, ty.boxed_ty()) => Some(expr), |
| 36 | + ty::Ref(_, inner, _) => { |
| 37 | + if may_slice(cx, inner) { |
| 38 | + Some(expr) |
| 39 | + } else { |
| 40 | + None |
| 41 | + } |
| 42 | + }, |
| 43 | + _ => None, |
| 44 | + } |
| 45 | + } |
| 46 | +} |
0 commit comments