|
| 1 | +// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution. |
| 3 | +// |
| 4 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 5 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 6 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 7 | +// option. This file may not be copied, modified, or distributed |
| 8 | +// except according to those terms. |
| 9 | + |
| 10 | +use crate::rustc::hir::Expr; |
| 11 | +use crate::rustc::infer::InferCtxt; |
| 12 | +use crate::rustc::lint::{LateContext, LateLintPass, LintArray, LintPass}; |
| 13 | +use crate::rustc::traits; |
| 14 | +use crate::rustc::ty::adjustment::Adjust; |
| 15 | +use crate::rustc::ty::{self, ToPolyTraitRef, Ty}; |
| 16 | +use crate::rustc::{declare_tool_lint, lint_array}; |
| 17 | +use crate::syntax_pos::symbol::Ident; |
| 18 | +use crate::utils::{match_def_path, paths, span_lint_and_then}; |
| 19 | +use if_chain::if_chain; |
| 20 | +use std::collections::VecDeque; |
| 21 | + |
| 22 | +/// **What it does:** Checks for coercing something that already contains a |
| 23 | +/// `dyn Any` to `dyn Any` itself. |
| 24 | +/// |
| 25 | +/// **Why is this bad?** It's probably a mistake. |
| 26 | +/// |
| 27 | +/// **Known problems:** None. |
| 28 | +/// |
| 29 | +/// **Example:** |
| 30 | +/// ```rust |
| 31 | +/// let box_foo: Box<Foo> = Box::new(Foo); |
| 32 | +/// let mut box_any: Box<dyn Any> = box_foo; |
| 33 | +/// let bad: &mut dyn Any = &mut box_any; |
| 34 | +/// // you probably meant |
| 35 | +/// let ok: &mut dyn Any = &mut *box_any; |
| 36 | +/// ``` |
| 37 | +declare_clippy_lint! { |
| 38 | + pub WRONG_ANY_COERCE, |
| 39 | + correctness, |
| 40 | + "coercing a type already containing `dyn Any` to `dyn Any` itself" |
| 41 | +} |
| 42 | + |
| 43 | +#[derive(Default)] |
| 44 | +pub struct WrongAnyCoerce; |
| 45 | + |
| 46 | +impl LintPass for WrongAnyCoerce { |
| 47 | + fn get_lints(&self) -> LintArray { |
| 48 | + lint_array!(WRONG_ANY_COERCE) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +struct LintData<'tcx> { |
| 53 | + coerced_to_any: Ty<'tcx>, |
| 54 | +} |
| 55 | + |
| 56 | +impl<'a, 'tcx> LateLintPass<'a, 'tcx> for WrongAnyCoerce { |
| 57 | + fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr) { |
| 58 | + let adjustments = cx.tables.expr_adjustments(expr); |
| 59 | + for (i, adj) in adjustments.iter().enumerate() { |
| 60 | + if let Adjust::Unsize = adj.kind { |
| 61 | + let src_ty = if i == 0 { |
| 62 | + cx.tables.expr_ty(expr) |
| 63 | + } else { |
| 64 | + adjustments[i - 1].target |
| 65 | + }; |
| 66 | + cx.tcx.infer_ctxt().enter(|infcx| { |
| 67 | + let opt_lint_data = check_unsize_coercion(infcx, cx.param_env, src_ty, adj.target); |
| 68 | + if let Some(lint_data) = opt_lint_data { |
| 69 | + // TODO: we might be able to suggest dereferencing in some cases |
| 70 | + let cta_str = lint_data.coerced_to_any.to_string(); |
| 71 | + span_lint_and_then( |
| 72 | + cx, |
| 73 | + WRONG_ANY_COERCE, |
| 74 | + expr.span, |
| 75 | + &format!("coercing `{}` to `dyn Any`", cta_str), |
| 76 | + |db| { |
| 77 | + if !cta_str.contains("Any") { |
| 78 | + db.note(&format!("`{}` dereferences to `dyn Any`", cta_str)); |
| 79 | + } |
| 80 | + }, |
| 81 | + ) |
| 82 | + } |
| 83 | + }); |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +/// Returns whether or not this coercion should be linted |
| 90 | +fn check_unsize_coercion<'tcx>( |
| 91 | + infcx: InferCtxt<'_, '_, 'tcx>, |
| 92 | + param_env: ty::ParamEnv<'tcx>, |
| 93 | + src_ty: Ty<'tcx>, |
| 94 | + tgt_ty: Ty<'tcx>, |
| 95 | +) -> Option<LintData<'tcx>> { |
| 96 | + // redo the typechecking for this coercion to see if it required unsizing something to `dyn Any` |
| 97 | + // see https://github.com/rust-lang/rust/blob/cae6efc37d70ab7d353e6ab9ce229d59a65ed643/src/librustc_typeck/check/coercion.rs#L454-L611 |
| 98 | + let tcx = infcx.tcx; |
| 99 | + // don't report overflow errors |
| 100 | + let mut selcx = traits::SelectionContext::with_query_mode(&infcx, traits::TraitQueryMode::Canonical); |
| 101 | + let mut queue = VecDeque::new(); |
| 102 | + queue.push_back( |
| 103 | + ty::TraitRef::new( |
| 104 | + tcx.lang_items().coerce_unsized_trait().unwrap(), |
| 105 | + tcx.mk_substs_trait(src_ty, &[tgt_ty.into()]), |
| 106 | + ) |
| 107 | + .to_poly_trait_ref(), |
| 108 | + ); |
| 109 | + while let Some(trait_ref) = queue.pop_front() { |
| 110 | + if match_def_path(tcx, trait_ref.def_id(), &paths::ANY_TRAIT) { |
| 111 | + // found something unsizing to `dyn Any` |
| 112 | + let coerced_to_any = trait_ref.self_ty(); |
| 113 | + if type_contains_any(&mut selcx, param_env, coerced_to_any) { |
| 114 | + return Some(LintData { coerced_to_any }); |
| 115 | + } |
| 116 | + } |
| 117 | + let select_result = selcx.select(&traits::Obligation::new( |
| 118 | + traits::ObligationCause::dummy(), |
| 119 | + param_env, |
| 120 | + trait_ref.to_poly_trait_predicate(), |
| 121 | + )); |
| 122 | + if let Ok(Some(vtable)) = select_result { |
| 123 | + // we only care about trait predicates |
| 124 | + queue.extend( |
| 125 | + vtable |
| 126 | + .nested_obligations() |
| 127 | + .into_iter() |
| 128 | + .filter_map(|oblig| oblig.predicate.to_opt_poly_trait_ref()), |
| 129 | + ); |
| 130 | + } |
| 131 | + } |
| 132 | + None |
| 133 | +} |
| 134 | + |
| 135 | +fn type_contains_any<'tcx>( |
| 136 | + selcx: &mut traits::SelectionContext<'_, '_, 'tcx>, |
| 137 | + param_env: ty::ParamEnv<'tcx>, |
| 138 | + ty: Ty<'tcx>, |
| 139 | +) -> bool { |
| 140 | + // check if it derefs to `dyn Any` |
| 141 | + if_chain! { |
| 142 | + if let Some((any_src_deref_ty, _deref_count)) = fully_deref_type(selcx, param_env, ty); |
| 143 | + if let ty::TyKind::Dynamic(trait_list, _) = any_src_deref_ty.sty; |
| 144 | + if match_def_path(selcx.tcx(), trait_list.skip_binder().principal().def_id, &paths::ANY_TRAIT); |
| 145 | + then { |
| 146 | + // TODO: use deref_count to make a suggestion |
| 147 | + return true; |
| 148 | + } |
| 149 | + } |
| 150 | + // TODO: check for `RefCell<dyn Any>`? |
| 151 | + false |
| 152 | +} |
| 153 | + |
| 154 | +/// Calls [deref_type] repeatedly |
| 155 | +fn fully_deref_type<'tcx>( |
| 156 | + selcx: &mut traits::SelectionContext<'_, '_, 'tcx>, |
| 157 | + param_env: ty::ParamEnv<'tcx>, |
| 158 | + src_ty: Ty<'tcx>, |
| 159 | +) -> Option<(Ty<'tcx>, usize)> { |
| 160 | + if let Some(deref_1) = deref_type(selcx, param_env, src_ty) { |
| 161 | + let mut deref_count = 1; |
| 162 | + let mut cur_ty = deref_1; |
| 163 | + while let Some(deref_n) = deref_type(selcx, param_env, cur_ty) { |
| 164 | + deref_count += 1; |
| 165 | + cur_ty = deref_n; |
| 166 | + } |
| 167 | + Some((cur_ty, deref_count)) |
| 168 | + } else { |
| 169 | + None |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +/// Returns the type of `*expr`, where `expr` has type `src_ty`. |
| 174 | +/// This will go through `Deref` `impl`s if necessary. |
| 175 | +/// Returns `None` if `*expr` would not typecheck. |
| 176 | +fn deref_type<'tcx>( |
| 177 | + selcx: &mut traits::SelectionContext<'_, '_, 'tcx>, |
| 178 | + param_env: ty::ParamEnv<'tcx>, |
| 179 | + src_ty: Ty<'tcx>, |
| 180 | +) -> Option<Ty<'tcx>> { |
| 181 | + if let Some(ty::TypeAndMut { ty, .. }) = src_ty.builtin_deref(true) { |
| 182 | + Some(ty) |
| 183 | + } else { |
| 184 | + // compute `<T as Deref>::Target` |
| 185 | + let infcx = selcx.infcx(); |
| 186 | + let tcx = selcx.tcx(); |
| 187 | + let src_deref = ty::TraitRef::new( |
| 188 | + tcx.lang_items().deref_trait().unwrap(), |
| 189 | + tcx.mk_substs_trait(src_ty, &[]), |
| 190 | + ); |
| 191 | + let mut obligations = Vec::new(); |
| 192 | + let src_deref_ty = traits::normalize_projection_type( |
| 193 | + selcx, |
| 194 | + param_env, |
| 195 | + ty::ProjectionTy::from_ref_and_name(tcx, src_deref, Ident::from_str("Target")), |
| 196 | + traits::ObligationCause::dummy(), |
| 197 | + 0, |
| 198 | + &mut obligations, |
| 199 | + ); |
| 200 | + // only return something if all the obligations definitely hold |
| 201 | + let obligations_ok = obligations.iter().all(|oblig| infcx.predicate_must_hold(oblig)); |
| 202 | + if obligations_ok { |
| 203 | + Some(infcx.resolve_type_vars_if_possible(&src_deref_ty)) |
| 204 | + } else { |
| 205 | + None |
| 206 | + } |
| 207 | + } |
| 208 | +} |
0 commit comments