diff options
Diffstat (limited to 'compiler/rustc_trait_selection')
5 files changed, 130 insertions, 67 deletions
diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs index 139b2997136..8fe4ffebd86 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/find_anon_type.rs @@ -75,7 +75,7 @@ impl<'tcx> Visitor<'tcx> for FindNestedTypeVisitor<'tcx> { fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx, AmbigArg>) -> Self::Result { match arg.kind { - hir::TyKind::BareFn(_) => { + hir::TyKind::FnPtr(_) => { self.current_index.shift_in(1); let _ = intravisit::walk_ty(self, arg); self.current_index.shift_out(1); diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index 362052e9fdb..e801ec358fa 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -1187,6 +1187,13 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { has_custom_message: bool, ) -> bool { let span = obligation.cause.span; + let param_env = obligation.param_env; + + let mk_result = |trait_pred_and_new_ty| { + let obligation = + self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty); + self.predicate_must_hold_modulo_regions(&obligation) + }; let code = match obligation.cause.code() { ObligationCauseCode::FunctionArg { parent_code, .. } => parent_code, @@ -1195,6 +1202,76 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { c @ ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _) if self.tcx.hir_span(*hir_id).lo() == span.lo() => { + // `hir_id` corresponds to the HIR node that introduced a `where`-clause obligation. + // If that obligation comes from a type in an associated method call, we need + // special handling here. + if let hir::Node::Expr(expr) = self.tcx.parent_hir_node(*hir_id) + && let hir::ExprKind::Call(base, _) = expr.kind + && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, segment)) = base.kind + && let hir::Node::Expr(outer) = self.tcx.parent_hir_node(expr.hir_id) + && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mtbl, _) = outer.kind + && ty.span == span + { + // We've encountered something like `&str::from("")`, where the intended code + // was likely `<&str>::from("")`. The former is interpreted as "call method + // `from` on `str` and borrow the result", while the latter means "call method + // `from` on `&str`". + + let trait_pred_and_imm_ref = poly_trait_pred.map_bound(|p| { + (p, Ty::new_imm_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty())) + }); + let trait_pred_and_mut_ref = poly_trait_pred.map_bound(|p| { + (p, Ty::new_mut_ref(self.tcx, self.tcx.lifetimes.re_static, p.self_ty())) + }); + + let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref); + let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref); + let sugg_msg = |pre: &str| { + format!( + "you likely meant to call the associated function `{FN}` for type \ + `&{pre}{TY}`, but the code as written calls associated function `{FN}` on \ + type `{TY}`", + FN = segment.ident, + TY = poly_trait_pred.self_ty(), + ) + }; + match (imm_ref_self_ty_satisfies_pred, mut_ref_self_ty_satisfies_pred, mtbl) { + (true, _, hir::Mutability::Not) | (_, true, hir::Mutability::Mut) => { + err.multipart_suggestion_verbose( + sugg_msg(mtbl.prefix_str()), + vec![ + (outer.span.shrink_to_lo(), "<".to_string()), + (span.shrink_to_hi(), ">".to_string()), + ], + Applicability::MachineApplicable, + ); + } + (true, _, hir::Mutability::Mut) => { + // There's an associated function found on the immutable borrow of the + err.multipart_suggestion_verbose( + sugg_msg("mut "), + vec![ + (outer.span.shrink_to_lo().until(span), "<&".to_string()), + (span.shrink_to_hi(), ">".to_string()), + ], + Applicability::MachineApplicable, + ); + } + (_, true, hir::Mutability::Not) => { + err.multipart_suggestion_verbose( + sugg_msg(""), + vec![ + (outer.span.shrink_to_lo().until(span), "<&mut ".to_string()), + (span.shrink_to_hi(), ">".to_string()), + ], + Applicability::MachineApplicable, + ); + } + _ => {} + } + // If we didn't return early here, we would instead suggest `&&str::from("")`. + return false; + } c } c if matches!( @@ -1220,8 +1297,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { never_suggest_borrow.push(def_id); } - let param_env = obligation.param_env; - // Try to apply the original trait bound by borrowing. let mut try_borrowing = |old_pred: ty::PolyTraitPredicate<'tcx>, blacklist: &[DefId]| @@ -1243,11 +1318,6 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { ) }); - let mk_result = |trait_pred_and_new_ty| { - let obligation = - self.mk_trait_obligation_with_new_self_ty(param_env, trait_pred_and_new_ty); - self.predicate_must_hold_modulo_regions(&obligation) - }; let imm_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_imm_ref); let mut_ref_self_ty_satisfies_pred = mk_result(trait_pred_and_mut_ref); diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 81ce58a93fa..9af85f5e3f0 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -80,11 +80,11 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } Some(LangItem::DiscriminantKind) => { // `DiscriminantKind` is automatically implemented for every type. - candidates.vec.push(BuiltinCandidate { has_nested: false }); + candidates.vec.push(BuiltinCandidate); } Some(LangItem::PointeeTrait) => { // `Pointee` is automatically implemented for every type. - candidates.vec.push(BuiltinCandidate { has_nested: false }); + candidates.vec.push(BuiltinCandidate); } Some(LangItem::Sized) => { self.assemble_builtin_sized_candidate( @@ -365,7 +365,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { { debug!(?self_ty, ?obligation, "assemble_fused_iterator_candidates",); - candidates.vec.push(BuiltinCandidate { has_nested: false }); + candidates.vec.push(BuiltinCandidate); } } @@ -810,7 +810,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { hir::Movability::Movable => { // Movable coroutines are always `Unpin`, so add an // unconditional builtin candidate. - candidates.vec.push(BuiltinCandidate { has_nested: false }); + candidates.vec.push(BuiltinCandidate); } } } @@ -1122,10 +1122,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { sizedness: SizedTraitKind, ) { match self.sizedness_conditions(obligation, sizedness) { - BuiltinImplConditions::Where(nested) => { - candidates - .vec - .push(SizedCandidate { has_nested: !nested.skip_binder().is_empty() }); + BuiltinImplConditions::Where(_nested) => { + candidates.vec.push(SizedCandidate); } BuiltinImplConditions::None => {} BuiltinImplConditions::Ambiguous => { @@ -1143,10 +1141,8 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { candidates: &mut SelectionCandidateSet<'tcx>, ) { match conditions { - BuiltinImplConditions::Where(nested) => { - candidates - .vec - .push(BuiltinCandidate { has_nested: !nested.skip_binder().is_empty() }); + BuiltinImplConditions::Where(_) => { + candidates.vec.push(BuiltinCandidate); } BuiltinImplConditions::None => {} BuiltinImplConditions::Ambiguous => { @@ -1160,7 +1156,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { _obligation: &PolyTraitObligation<'tcx>, candidates: &mut SelectionCandidateSet<'tcx>, ) { - candidates.vec.push(BuiltinCandidate { has_nested: false }); + candidates.vec.push(BuiltinCandidate); } fn assemble_candidate_for_tuple( @@ -1171,7 +1167,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let self_ty = self.infcx.shallow_resolve(obligation.self_ty().skip_binder()); match self_ty.kind() { ty::Tuple(_) => { - candidates.vec.push(BuiltinCandidate { has_nested: false }); + candidates.vec.push(BuiltinCandidate); } ty::Infer(ty::TyVar(_)) => { candidates.ambiguous = true; @@ -1215,7 +1211,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { let self_ty = self.infcx.resolve_vars_if_possible(obligation.self_ty()); match self_ty.skip_binder().kind() { - ty::FnPtr(..) => candidates.vec.push(BuiltinCandidate { has_nested: false }), + ty::FnPtr(..) => candidates.vec.push(BuiltinCandidate), ty::Bool | ty::Char | ty::Int(_) diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index a6b77583fdc..545531f927a 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -37,13 +37,13 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { candidate: SelectionCandidate<'tcx>, ) -> Result<Selection<'tcx>, SelectionError<'tcx>> { Ok(match candidate { - SizedCandidate { has_nested } => { - let data = self.confirm_builtin_candidate(obligation, has_nested); + SizedCandidate => { + let data = self.confirm_builtin_candidate(obligation); ImplSource::Builtin(BuiltinImplSource::Misc, data) } - BuiltinCandidate { has_nested } => { - let data = self.confirm_builtin_candidate(obligation, has_nested); + BuiltinCandidate => { + let data = self.confirm_builtin_candidate(obligation); ImplSource::Builtin(BuiltinImplSource::Misc, data) } @@ -249,50 +249,47 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { } } + #[instrument(level = "debug", skip(self), ret)] fn confirm_builtin_candidate( &mut self, obligation: &PolyTraitObligation<'tcx>, - has_nested: bool, ) -> PredicateObligations<'tcx> { - debug!(?obligation, ?has_nested, "confirm_builtin_candidate"); - + debug!(?obligation, "confirm_builtin_candidate"); let tcx = self.tcx(); - let obligations = if has_nested { - let trait_def = obligation.predicate.def_id(); - let conditions = match tcx.as_lang_item(trait_def) { - Some(LangItem::Sized) => { - self.sizedness_conditions(obligation, SizedTraitKind::Sized) - } - Some(LangItem::MetaSized) => { - self.sizedness_conditions(obligation, SizedTraitKind::MetaSized) - } - Some(LangItem::PointeeSized) => { - bug!("`PointeeSized` is removing during lowering"); - } - Some(LangItem::Copy | LangItem::Clone) => self.copy_clone_conditions(obligation), - Some(LangItem::FusedIterator) => self.fused_iterator_conditions(obligation), - other => bug!("unexpected builtin trait {trait_def:?} ({other:?})"), - }; - let BuiltinImplConditions::Where(types) = conditions else { - bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation); - }; - let types = self.infcx.enter_forall_and_leak_universe(types); - - let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerived); - self.collect_predicates_for_types( - obligation.param_env, - cause, - obligation.recursion_depth + 1, - trait_def, - types, - ) - } else { - PredicateObligations::new() + let trait_def = obligation.predicate.def_id(); + let conditions = match tcx.as_lang_item(trait_def) { + Some(LangItem::Sized) => self.sizedness_conditions(obligation, SizedTraitKind::Sized), + Some(LangItem::MetaSized) => { + self.sizedness_conditions(obligation, SizedTraitKind::MetaSized) + } + Some(LangItem::PointeeSized) => { + bug!("`PointeeSized` is removing during lowering"); + } + Some(LangItem::Copy | LangItem::Clone) => self.copy_clone_conditions(obligation), + Some(LangItem::FusedIterator) => self.fused_iterator_conditions(obligation), + Some( + LangItem::Destruct + | LangItem::DiscriminantKind + | LangItem::FnPtrTrait + | LangItem::PointeeTrait + | LangItem::Tuple + | LangItem::Unpin, + ) => BuiltinImplConditions::Where(ty::Binder::dummy(vec![])), + other => bug!("unexpected builtin trait {trait_def:?} ({other:?})"), }; + let BuiltinImplConditions::Where(types) = conditions else { + bug!("obligation {:?} had matched a builtin impl but now doesn't", obligation); + }; + let types = self.infcx.enter_forall_and_leak_universe(types); - debug!(?obligations); - - obligations + let cause = obligation.derived_cause(ObligationCauseCode::BuiltinDerived); + self.collect_predicates_for_types( + obligation.param_env, + cause, + obligation.recursion_depth + 1, + trait_def, + types, + ) } #[instrument(level = "debug", skip(self))] diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index af3641c22ed..c9930c69b32 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -1834,7 +1834,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { // We prefer `Sized` candidates over everything. let mut sized_candidates = - candidates.iter().filter(|c| matches!(c.candidate, SizedCandidate { has_nested: _ })); + candidates.iter().filter(|c| matches!(c.candidate, SizedCandidate)); if let Some(sized_candidate) = sized_candidates.next() { // There should only ever be a single sized candidate // as they would otherwise overlap. @@ -1986,8 +1986,8 @@ impl<'tcx> SelectionContext<'_, 'tcx> { // Don't use impl candidates which overlap with other candidates. // This should pretty much only ever happen with malformed impls. if candidates.iter().all(|c| match c.candidate { - SizedCandidate { has_nested: _ } - | BuiltinCandidate { has_nested: _ } + SizedCandidate + | BuiltinCandidate | TransmutabilityCandidate | AutoImplCandidate | ClosureCandidate { .. } |
