diff options
| author | bors <bors@rust-lang.org> | 2023-05-23 12:47:51 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2023-05-23 12:47:51 +0000 |
| commit | b08148f6a76010ea3d4e91d61245aa7aac59e4b4 (patch) | |
| tree | bb3f063f430b4843502fa17bd691aff6f4cbc056 /compiler | |
| parent | f3d597b31c0f101a02c230798afa31a36bdacbc6 (diff) | |
| parent | c4f2a62182da7d2fce3a961fe12ffb7d72097ca2 (diff) | |
| download | rust-b08148f6a76010ea3d4e91d61245aa7aac59e4b4.tar.gz rust-b08148f6a76010ea3d4e91d61245aa7aac59e4b4.zip | |
Auto merge of #111869 - Dylan-DPC:rollup-9pydw08, r=Dylan-DPC
Rollup of 6 pull requests Successful merges: - #111461 (Fix symbol conflict diagnostic mistakenly being shown instead of missing crate diagnostic) - #111579 (Also assume wrap-around discriminants in `as` MIR building) - #111704 (Remove return type sized check hack from hir typeck) - #111853 (Check opaques for mismatch during writeback) - #111854 (rustdoc: clean up `settings.css`) - #111860 (Don't ICE if method receiver fails to unify with `arbitrary_self_types`) r? `@ghost` `@rustbot` modify labels: rollup
Diffstat (limited to 'compiler')
| -rw-r--r-- | compiler/rustc_borrowck/src/region_infer/opaque_types.rs | 2 | ||||
| -rw-r--r-- | compiler/rustc_errors/src/lib.rs | 1 | ||||
| -rw-r--r-- | compiler/rustc_hir_analysis/src/collect/type_of.rs | 9 | ||||
| -rw-r--r-- | compiler/rustc_hir_typeck/src/check.rs | 20 | ||||
| -rw-r--r-- | compiler/rustc_hir_typeck/src/method/confirm.rs | 25 | ||||
| -rw-r--r-- | compiler/rustc_hir_typeck/src/writeback.rs | 44 | ||||
| -rw-r--r-- | compiler/rustc_metadata/src/creader.rs | 10 | ||||
| -rw-r--r-- | compiler/rustc_metadata/src/locator.rs | 13 | ||||
| -rw-r--r-- | compiler/rustc_middle/src/ty/mod.rs | 18 | ||||
| -rw-r--r-- | compiler/rustc_middle/src/ty/typeck_results.rs | 12 | ||||
| -rw-r--r-- | compiler/rustc_mir_build/src/build/expr/as_rvalue.rs | 101 | ||||
| -rw-r--r-- | compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs | 2 | ||||
| -rw-r--r-- | compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs | 277 |
13 files changed, 208 insertions, 326 deletions
diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs index 309f23d9226..e9b5c47ce23 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types.rs @@ -152,8 +152,10 @@ impl<'tcx> RegionInferenceContext<'tcx> { let guar = ty.error_reported().err().unwrap_or_else(|| { prev.report_mismatch( &OpaqueHiddenType { ty, span: concrete_type.span }, + opaque_type_key.def_id, infcx.tcx, ) + .emit() }); prev.ty = infcx.tcx.ty_error(guar); } diff --git a/compiler/rustc_errors/src/lib.rs b/compiler/rustc_errors/src/lib.rs index 5a80024f19b..074fbb1322c 100644 --- a/compiler/rustc_errors/src/lib.rs +++ b/compiler/rustc_errors/src/lib.rs @@ -478,6 +478,7 @@ pub enum StashKey { MaybeFruTypo, CallAssocMethod, TraitMissingMethod, + OpaqueHiddenTypeMismatch, } fn default_track_diagnostic(d: &mut Diagnostic, f: &mut dyn FnMut(&mut Diagnostic)) { diff --git a/compiler/rustc_hir_analysis/src/collect/type_of.rs b/compiler/rustc_hir_analysis/src/collect/type_of.rs index ca430a5e863..97c6cb491d1 100644 --- a/compiler/rustc_hir_analysis/src/collect/type_of.rs +++ b/compiler/rustc_hir_analysis/src/collect/type_of.rs @@ -584,7 +584,8 @@ fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> T debug!(?concrete_type, "found constraint"); if let Some(prev) = &mut self.found { if concrete_type.ty != prev.ty && !(concrete_type, prev.ty).references_error() { - let guar = prev.report_mismatch(&concrete_type, self.tcx); + let guar = + prev.report_mismatch(&concrete_type, self.def_id, self.tcx).emit(); prev.ty = self.tcx.ty_error(guar); } } else { @@ -678,10 +679,10 @@ fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> T // Only check against typeck if we didn't already error if !hidden.ty.references_error() { for concrete_type in locator.typeck_types { - if tcx.erase_regions(concrete_type.ty) != tcx.erase_regions(hidden.ty) + if concrete_type.ty != tcx.erase_regions(hidden.ty) && !(concrete_type, hidden).references_error() { - hidden.report_mismatch(&concrete_type, tcx); + hidden.report_mismatch(&concrete_type, def_id, tcx).emit(); } } } @@ -722,7 +723,7 @@ fn find_opaque_ty_constraints_for_rpit( if concrete_type.ty != self.found.ty && !(concrete_type, self.found).references_error() { - self.found.report_mismatch(&concrete_type, self.tcx); + self.found.report_mismatch(&concrete_type, self.def_id, self.tcx).emit(); } } } diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index bf8259ff70f..186ac536c6e 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -103,24 +103,8 @@ pub(super) fn check_fn<'a, 'tcx>( fcx.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig); - if let ty::Dynamic(_, _, ty::Dyn) = declared_ret_ty.kind() { - // FIXME: We need to verify that the return type is `Sized` after the return expression has - // been evaluated so that we have types available for all the nodes being returned, but that - // requires the coerced evaluated type to be stored. Moving `check_return_expr` before this - // causes unsized errors caused by the `declared_ret_ty` to point at the return expression, - // while keeping the current ordering we will ignore the tail expression's type because we - // don't know it yet. We can't do `check_expr_kind` while keeping `check_return_expr` - // because we will trigger "unreachable expression" lints unconditionally. - // Because of all of this, we perform a crude check to know whether the simplest `!Sized` - // case that a newcomer might make, returning a bare trait, and in that case we populate - // the tail expression's type so that the suggestion will be correct, but ignore all other - // possible cases. - fcx.check_expr(&body.value); - fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); - } else { - fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); - fcx.check_return_expr(&body.value, false); - } + fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType); + fcx.check_return_expr(&body.value, false); // We insert the deferred_generator_interiors entry after visiting the body. // This ensures that all nested generators appear before the entry of this generator. diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 59bf45f0ed2..98529b66602 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -471,7 +471,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { self_ty, method_self_ty, self.span, pick ); let cause = self.cause( - self.span, + self.self_expr.span, ObligationCauseCode::UnifyReceiver(Box::new(UnifyReceiverContext { assoc_item: pick.item, param_env: self.param_env, @@ -482,13 +482,22 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { Ok(InferOk { obligations, value: () }) => { self.register_predicates(obligations); } - Err(_) => { - span_bug!( - self.span, - "{} was a subtype of {} but now is not?", - self_ty, - method_self_ty - ); + Err(terr) => { + // FIXME(arbitrary_self_types): We probably should limit the + // situations where this can occur by adding additional restrictions + // to the feature, like the self type can't reference method substs. + if self.tcx.features().arbitrary_self_types { + self.err_ctxt() + .report_mismatched_types(&cause, method_self_ty, self_ty, terr) + .emit(); + } else { + span_bug!( + self.span, + "{} was a subtype of {} but now is not?", + self_ty, + method_self_ty + ); + } } } } diff --git a/compiler/rustc_hir_typeck/src/writeback.rs b/compiler/rustc_hir_typeck/src/writeback.rs index 2daec205cfc..0f21fc1e662 100644 --- a/compiler/rustc_hir_typeck/src/writeback.rs +++ b/compiler/rustc_hir_typeck/src/writeback.rs @@ -5,7 +5,7 @@ use crate::FnCtxt; use hir::def_id::LocalDefId; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::ErrorGuaranteed; +use rustc_errors::{ErrorGuaranteed, StashKey}; use rustc_hir as hir; use rustc_hir::intravisit::{self, Visitor}; use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282; @@ -82,10 +82,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { wbcx.typeck_results.treat_byte_string_as_slice = mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice); - if let Some(e) = self.tainted_by_errors() { - wbcx.typeck_results.tainted_by_errors = Some(e); - } - debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results); self.tcx.arena.alloc(wbcx.typeck_results) @@ -118,12 +114,21 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { ) -> WritebackCx<'cx, 'tcx> { let owner = body.id().hir_id.owner; - WritebackCx { + let mut wbcx = WritebackCx { fcx, typeck_results: ty::TypeckResults::new(owner), body, rustc_dump_user_substs, + }; + + // HACK: We specifically don't want the (opaque) error from tainting our + // inference context. That'll prevent us from doing opaque type inference + // later on in borrowck, which affects diagnostic spans pretty negatively. + if let Some(e) = fcx.tainted_by_errors() { + wbcx.typeck_results.tainted_by_errors = Some(e); } + + wbcx } fn tcx(&self) -> TyCtxt<'tcx> { @@ -578,13 +583,26 @@ impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { continue; } - let hidden_type = hidden_type.remap_generic_params_to_declaration_params( - opaque_type_key, - self.fcx.infcx.tcx, - true, - ); - - self.typeck_results.concrete_opaque_types.insert(opaque_type_key.def_id, hidden_type); + let hidden_type = + self.tcx().erase_regions(hidden_type.remap_generic_params_to_declaration_params( + opaque_type_key, + self.tcx(), + true, + )); + + if let Some(last_opaque_ty) = self + .typeck_results + .concrete_opaque_types + .insert(opaque_type_key.def_id, hidden_type) + && last_opaque_ty.ty != hidden_type.ty + { + hidden_type + .report_mismatch(&last_opaque_ty, opaque_type_key.def_id, self.tcx()) + .stash( + self.tcx().def_span(opaque_type_key.def_id), + StashKey::OpaqueHiddenTypeMismatch, + ); + } } } diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index 98ea9dc7501..209bf395624 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -148,11 +148,15 @@ impl CStore { assert_eq!(self.metas.len(), self.stable_crate_ids.len()); let num = CrateNum::new(self.stable_crate_ids.len()); if let Some(&existing) = self.stable_crate_ids.get(&root.stable_crate_id()) { - let crate_name0 = root.name(); - if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name()) { + // Check for (potential) conflicts with the local crate + if existing == LOCAL_CRATE { + Err(CrateError::SymbolConflictsCurrent(root.name())) + } else if let Some(crate_name1) = self.metas[existing].as_ref().map(|data| data.name()) + { + let crate_name0 = root.name(); Err(CrateError::StableCrateIdCollision(crate_name0, crate_name1)) } else { - Err(CrateError::SymbolConflictsCurrent(crate_name0)) + Err(CrateError::NotFound(root.name())) } } else { self.metas.push(None); diff --git a/compiler/rustc_metadata/src/locator.rs b/compiler/rustc_metadata/src/locator.rs index 6ec691f73b7..1aab4adf0b3 100644 --- a/compiler/rustc_metadata/src/locator.rs +++ b/compiler/rustc_metadata/src/locator.rs @@ -961,6 +961,7 @@ pub(crate) enum CrateError { DlSym(String), LocatorCombined(Box<CombinedLocatorError>), NonDylibPlugin(Symbol), + NotFound(Symbol), } enum MetadataError<'a> { @@ -1131,6 +1132,18 @@ impl CrateError { CrateError::NonDylibPlugin(crate_name) => { sess.emit_err(errors::NoDylibPlugin { span, crate_name }); } + CrateError::NotFound(crate_name) => { + sess.emit_err(errors::CannotFindCrate { + span, + crate_name, + add_info: String::new(), + missing_core, + current_crate: sess.opts.crate_name.clone().unwrap_or("<unknown>".to_string()), + is_nightly_build: sess.is_nightly_build(), + profiler_runtime: Symbol::intern(&sess.opts.unstable_opts.profiler_runtime), + locator_triple: sess.opts.target_triple.clone(), + }); + } } } } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index ecb191676c2..c9cd644fab0 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -37,7 +37,7 @@ use rustc_data_structures::intern::Interned; use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; use rustc_data_structures::steal::Steal; use rustc_data_structures::tagged_ptr::CopyTaggedPtr; -use rustc_errors::ErrorGuaranteed; +use rustc_errors::{DiagnosticBuilder, ErrorGuaranteed, StashKey}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res}; use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap}; @@ -1439,14 +1439,26 @@ pub struct OpaqueHiddenType<'tcx> { } impl<'tcx> OpaqueHiddenType<'tcx> { - pub fn report_mismatch(&self, other: &Self, tcx: TyCtxt<'tcx>) -> ErrorGuaranteed { + pub fn report_mismatch( + &self, + other: &Self, + opaque_def_id: LocalDefId, + tcx: TyCtxt<'tcx>, + ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> { + if let Some(diag) = tcx + .sess + .diagnostic() + .steal_diagnostic(tcx.def_span(opaque_def_id), StashKey::OpaqueHiddenTypeMismatch) + { + diag.cancel(); + } // Found different concrete types for the opaque type. let sub_diag = if self.span == other.span { TypeMismatchReason::ConflictType { span: self.span } } else { TypeMismatchReason::PreviousUse { span: self.span } }; - tcx.sess.emit_err(OpaqueHiddenTypeMismatch { + tcx.sess.create_err(OpaqueHiddenTypeMismatch { self_ty: self.ty, other_ty: other.ty, other_span: other.span, diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 5a0571f4bb7..e04dbbff9a7 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -151,10 +151,14 @@ pub struct TypeckResults<'tcx> { /// this field will be set to `Some(ErrorGuaranteed)`. pub tainted_by_errors: Option<ErrorGuaranteed>, - /// All the opaque types that have hidden types set - /// by this function. We also store the - /// type here, so that mir-borrowck can use it as a hint for figuring out hidden types, - /// even if they are only set in dead code (which doesn't show up in MIR). + /// All the opaque types that have hidden types set by this function. + /// We also store the type here, so that the compiler can use it as a hint + /// for figuring out hidden types, even if they are only set in dead code + /// (which doesn't show up in MIR). + /// + /// These types are mapped back to the opaque's identity substitutions + /// (with erased regions), which is why we don't associated substs with any + /// of these usages. pub concrete_opaque_types: FxIndexMap<LocalDefId, ty::OpaqueHiddenType<'tcx>>, /// Tracks the minimum captures required for a closure; diff --git a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs index c385b00692f..bcab4c0d24b 100644 --- a/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs +++ b/compiler/rustc_mir_build/src/build/expr/as_rvalue.rs @@ -15,6 +15,7 @@ use rustc_middle::mir::Place; use rustc_middle::mir::*; use rustc_middle::thir::*; use rustc_middle::ty::cast::{mir_cast_kind, CastTy}; +use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{self, Ty, UpvarSubsts}; use rustc_span::Span; @@ -225,49 +226,63 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { ); let (op,ty) = (Operand::Move(discr), discr_ty); - if let Abi::Scalar(scalar) = layout.unwrap().abi{ - if let Primitive::Int(_, signed) = scalar.primitive() { - let range = scalar.valid_range(&this.tcx); - // FIXME: Handle wraparound cases too. - if range.end >= range.start { - let mut assumer = |range: u128, bin_op: BinOp| { - // We will be overwriting this val if our scalar is signed value - // because sign extension on unsigned types might cause unintended things - let mut range_val = - ConstantKind::from_bits(this.tcx, range, ty::ParamEnv::empty().and(discr_ty)); - let bool_ty = this.tcx.types.bool; - if signed { - let scalar_size_extend = scalar.size(&this.tcx).sign_extend(range); - let discr_layout = this.tcx.layout_of(this.param_env.and(discr_ty)); - let truncated_val = discr_layout.unwrap().size.truncate(scalar_size_extend); - range_val = ConstantKind::from_bits( - this.tcx, - truncated_val, - ty::ParamEnv::empty().and(discr_ty), - ); - } - let lit_op = this.literal_operand(expr.span, range_val); - let is_bin_op = this.temp(bool_ty, expr_span); - this.cfg.push_assign( - block, - source_info, - is_bin_op, - Rvalue::BinaryOp(bin_op, Box::new(((lit_op), (Operand::Copy(discr))))), - ); - this.cfg.push( - block, - Statement { - source_info, - kind: StatementKind::Intrinsic(Box::new(NonDivergingIntrinsic::Assume( - Operand::Copy(is_bin_op), - ))), - }, - ) - }; - assumer(range.end, BinOp::Ge); - assumer(range.start, BinOp::Le); - } - } + if let Abi::Scalar(scalar) = layout.unwrap().abi + && !scalar.is_always_valid(&this.tcx) + && let Primitive::Int(int_width, _signed) = scalar.primitive() + { + let unsigned_ty = int_width.to_ty(this.tcx, false); + let unsigned_place = this.temp(unsigned_ty, expr_span); + this.cfg.push_assign( + block, + source_info, + unsigned_place, + Rvalue::Cast(CastKind::IntToInt, Operand::Copy(discr), unsigned_ty)); + + let bool_ty = this.tcx.types.bool; + let range = scalar.valid_range(&this.tcx); + let merge_op = + if range.start <= range.end { + BinOp::BitAnd + } else { + BinOp::BitOr + }; + + let mut comparer = |range: u128, bin_op: BinOp| -> Place<'tcx> { + let range_val = + ConstantKind::from_bits(this.tcx, range, ty::ParamEnv::empty().and(unsigned_ty)); + let lit_op = this.literal_operand(expr.span, range_val); + let is_bin_op = this.temp(bool_ty, expr_span); + this.cfg.push_assign( + block, + source_info, + is_bin_op, + Rvalue::BinaryOp(bin_op, Box::new((Operand::Copy(unsigned_place), lit_op))), + ); + is_bin_op + }; + let assert_place = if range.start == 0 { + comparer(range.end, BinOp::Le) + } else { + let start_place = comparer(range.start, BinOp::Ge); + let end_place = comparer(range.end, BinOp::Le); + let merge_place = this.temp(bool_ty, expr_span); + this.cfg.push_assign( + block, + source_info, + merge_place, + Rvalue::BinaryOp(merge_op, Box::new((Operand::Move(start_place), Operand::Move(end_place)))), + ); + merge_place + }; + this.cfg.push( + block, + Statement { + source_info, + kind: StatementKind::Intrinsic(Box::new(NonDivergingIntrinsic::Assume( + Operand::Move(assert_place), + ))), + }, + ); } (op,ty) diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs index f5f2fe54217..dc43a3d154a 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs @@ -885,7 +885,7 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { return; } - if self.suggest_impl_trait(&mut err, span, &obligation, trait_predicate) { + if self.suggest_impl_trait(&mut err, &obligation, trait_predicate) { err.emit(); return; } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index ea17f23434b..83511e898f7 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -30,9 +30,9 @@ use rustc_middle::hir::map; use rustc_middle::ty::error::TypeError::{self, Sorts}; use rustc_middle::ty::{ self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, - GeneratorDiagnosticData, GeneratorInteriorTypeCause, Infer, InferTy, InternalSubsts, - IsSuggestable, ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder, - TypeSuperFoldable, TypeVisitableExt, TypeckResults, + GeneratorDiagnosticData, GeneratorInteriorTypeCause, InferTy, InternalSubsts, IsSuggestable, + ToPredicate, Ty, TyCtxt, TypeAndMut, TypeFoldable, TypeFolder, TypeSuperFoldable, + TypeVisitableExt, TypeckResults, }; use rustc_span::def_id::LocalDefId; use rustc_span::symbol::{sym, Ident, Symbol}; @@ -261,7 +261,6 @@ pub trait TypeErrCtxtExt<'tcx> { fn suggest_impl_trait( &self, err: &mut Diagnostic, - span: Span, obligation: &PredicateObligation<'tcx>, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool; @@ -1792,215 +1791,66 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> { fn suggest_impl_trait( &self, err: &mut Diagnostic, - span: Span, obligation: &PredicateObligation<'tcx>, trait_pred: ty::PolyTraitPredicate<'tcx>, ) -> bool { - match obligation.cause.code().peel_derives() { - // Only suggest `impl Trait` if the return type is unsized because it is `dyn Trait`. - ObligationCauseCode::SizedReturnType => {} - _ => return false, - } - - let hir = self.tcx.hir(); - let fn_hir_id = hir.local_def_id_to_hir_id(obligation.cause.body_id); - let node = hir.find_by_def_id(obligation.cause.body_id); - let Some(hir::Node::Item(hir::Item { - kind: hir::ItemKind::Fn(sig, _, body_id), - .. - })) = node - else { + let ObligationCauseCode::SizedReturnType = obligation.cause.code() else { return false; }; - let body = hir.body(*body_id); - let trait_pred = self.resolve_vars_if_possible(trait_pred); - let ty = trait_pred.skip_binder().self_ty(); - let is_object_safe = match ty.kind() { - ty::Dynamic(predicates, _, ty::Dyn) => { - // If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`. - predicates - .principal_def_id() - .map_or(true, |def_id| self.tcx.check_is_object_safe(def_id)) - } - // We only want to suggest `impl Trait` to `dyn Trait`s. - // For example, `fn foo() -> str` needs to be filtered out. - _ => return false, - }; - - let hir::FnRetTy::Return(ret_ty) = sig.decl.output else { + let ty::Dynamic(_, _, ty::Dyn) = trait_pred.self_ty().skip_binder().kind() else { return false; }; - // Use `TypeVisitor` instead of the output type directly to find the span of `ty` for - // cases like `fn foo() -> (dyn Trait, i32) {}`. - // Recursively look for `TraitObject` types and if there's only one, use that span to - // suggest `impl Trait`. - - // Visit to make sure there's a single `return` type to suggest `impl Trait`, - // otherwise suggest using `Box<dyn Trait>` or an enum. - let mut visitor = ReturnsVisitor::default(); - visitor.visit_body(&body); - - let typeck_results = self.typeck_results.as_ref().unwrap(); - let Some(liberated_sig) = typeck_results.liberated_fn_sigs().get(fn_hir_id).copied() else { return false; }; - - let ret_types = visitor - .returns - .iter() - .filter_map(|expr| Some((expr.span, typeck_results.node_type_opt(expr.hir_id)?))) - .map(|(expr_span, ty)| (expr_span, self.resolve_vars_if_possible(ty))); - let (last_ty, all_returns_have_same_type, only_never_return) = ret_types.clone().fold( - (None, true, true), - |(last_ty, mut same, only_never_return): (std::option::Option<Ty<'_>>, bool, bool), - (_, ty)| { - let ty = self.resolve_vars_if_possible(ty); - same &= - !matches!(ty.kind(), ty::Error(_)) - && last_ty.map_or(true, |last_ty| { - // FIXME: ideally we would use `can_coerce` here instead, but `typeck` comes - // *after* in the dependency graph. - match (ty.kind(), last_ty.kind()) { - (Infer(InferTy::IntVar(_)), Infer(InferTy::IntVar(_))) - | (Infer(InferTy::FloatVar(_)), Infer(InferTy::FloatVar(_))) - | (Infer(InferTy::FreshIntTy(_)), Infer(InferTy::FreshIntTy(_))) - | ( - Infer(InferTy::FreshFloatTy(_)), - Infer(InferTy::FreshFloatTy(_)), - ) => true, - _ => ty == last_ty, - } - }); - (Some(ty), same, only_never_return && matches!(ty.kind(), ty::Never)) - }, - ); - let mut spans_and_needs_box = vec![]; - - match liberated_sig.output().kind() { - ty::Dynamic(predicates, _, ty::Dyn) => { - let cause = ObligationCause::misc(ret_ty.span, obligation.cause.body_id); - let param_env = ty::ParamEnv::empty(); - - if !only_never_return { - for (expr_span, return_ty) in ret_types { - let self_ty_satisfies_dyn_predicates = |self_ty| { - predicates.iter().all(|predicate| { - let pred = predicate.with_self_ty(self.tcx, self_ty); - let obl = Obligation::new(self.tcx, cause.clone(), param_env, pred); - self.predicate_may_hold(&obl) - }) - }; - - if let ty::Adt(def, substs) = return_ty.kind() - && def.is_box() - && self_ty_satisfies_dyn_predicates(substs.type_at(0)) - { - spans_and_needs_box.push((expr_span, false)); - } else if self_ty_satisfies_dyn_predicates(return_ty) { - spans_and_needs_box.push((expr_span, true)); - } else { - return false; - } - } - } - } - _ => return false, - }; - - let sm = self.tcx.sess.source_map(); - if !ret_ty.span.overlaps(span) { - return false; - } - let snippet = if let hir::TyKind::TraitObject(..) = ret_ty.kind { - if let Ok(snippet) = sm.span_to_snippet(ret_ty.span) { - snippet - } else { - return false; - } - } else { - // Substitute the type, so we can print a fixup given `type Alias = dyn Trait` - let name = liberated_sig.output().to_string(); - let name = - name.strip_prefix('(').and_then(|name| name.strip_suffix(')')).unwrap_or(&name); - if !name.starts_with("dyn ") { - return false; - } - name.to_owned() - }; - err.code(error_code!(E0746)); err.set_primary_message("return type cannot have an unboxed trait object"); err.children.clear(); - let impl_trait_msg = "for information on `impl Trait`, see \ - <https://doc.rust-lang.org/book/ch10-02-traits.html\ - #returning-types-that-implement-traits>"; - let trait_obj_msg = "for information on trait objects, see \ - <https://doc.rust-lang.org/book/ch17-02-trait-objects.html\ - #using-trait-objects-that-allow-for-values-of-different-types>"; - - let has_dyn = snippet.split_whitespace().next().map_or(false, |s| s == "dyn"); - let trait_obj = if has_dyn { &snippet[4..] } else { &snippet }; - if only_never_return { - // No return paths, probably using `panic!()` or similar. - // Suggest `-> impl Trait`, and if `Trait` is object safe, `-> Box<dyn Trait>`. - suggest_trait_object_return_type_alternatives( - err, - ret_ty.span, - trait_obj, - is_object_safe, - ); - } else if let (Some(last_ty), true) = (last_ty, all_returns_have_same_type) { - // Suggest `-> impl Trait`. + + let span = obligation.cause.span; + if let Ok(snip) = self.tcx.sess.source_map().span_to_snippet(span) + && snip.starts_with("dyn ") + { err.span_suggestion( - ret_ty.span, - format!( - "use `impl {1}` as the return type, as all return paths are of type `{}`, \ - which implements `{1}`", - last_ty, trait_obj, - ), - format!("impl {}", trait_obj), - Applicability::MachineApplicable, + span.with_hi(span.lo() + BytePos(4)), + "return an `impl Trait` instead of a `dyn Trait`, \ + if all returned values are the same type", + "impl ", + Applicability::MaybeIncorrect, ); - err.note(impl_trait_msg); - } else { - if is_object_safe { - // Suggest `-> Box<dyn Trait>` and `Box::new(returned_value)`. - err.multipart_suggestion( - "return a boxed trait object instead", - vec![ - (ret_ty.span.shrink_to_lo(), "Box<".to_string()), - (span.shrink_to_hi(), ">".to_string()), - ], - Applicability::MaybeIncorrect, - ); - for (span, needs_box) in spans_and_needs_box { - if needs_box { - err.multipart_suggestion( - "... and box this value", - vec![ - (span.shrink_to_lo(), "Box::new(".to_string()), - (span.shrink_to_hi(), ")".to_string()), - ], - Applicability::MaybeIncorrect, - ); - } - } + } + + let body = self.tcx.hir().body(self.tcx.hir().body_owned_by(obligation.cause.body_id)); + + let mut visitor = ReturnsVisitor::default(); + visitor.visit_body(&body); + + let mut sugg = + vec![(span.shrink_to_lo(), "Box<".to_string()), (span.shrink_to_hi(), ">".to_string())]; + sugg.extend(visitor.returns.into_iter().flat_map(|expr| { + let span = expr.span.find_ancestor_in_same_ctxt(obligation.cause.span).unwrap_or(expr.span); + if !span.can_be_used_for_suggestions() { + vec![] + } else if let hir::ExprKind::Call(path, ..) = expr.kind + && let hir::ExprKind::Path(hir::QPath::TypeRelative(ty, method)) = path.kind + && method.ident.name == sym::new + && let hir::TyKind::Path(hir::QPath::Resolved(.., box_path)) = ty.kind + && box_path.res.opt_def_id().is_some_and(|def_id| Some(def_id) == self.tcx.lang_items().owned_box()) + { + // Don't box `Box::new` + vec![] } else { - // This is currently not possible to trigger because E0038 takes precedence, but - // leave it in for completeness in case anything changes in an earlier stage. - err.note(format!( - "if trait `{}` were object-safe, you could return a trait object", - trait_obj, - )); + vec![ + (span.shrink_to_lo(), "Box::new(".to_string()), + (span.shrink_to_hi(), ")".to_string()), + ] } - err.note(trait_obj_msg); - err.note(format!( - "if all the returned values were of the same type you could use `impl {}` as the \ - return type", - trait_obj, - )); - err.note(impl_trait_msg); - err.note("you can create a new `enum` with a variant for each returned type"); - } + })); + + err.multipart_suggestion( + "box the return type, and wrap all of the returned values in `Box::new`", + sugg, + Applicability::MaybeIncorrect, + ); + true } @@ -4139,37 +3989,6 @@ impl NextTypeParamName for &[hir::GenericParam<'_>] { } } -fn suggest_trait_object_return_type_alternatives( - err: &mut Diagnostic, - ret_ty: Span, - trait_obj: &str, - is_object_safe: bool, -) { - err.span_suggestion( - ret_ty, - format!( - "use `impl {}` as the return type if all return paths have the same type but you \ - want to expose only the trait in the signature", - trait_obj, - ), - format!("impl {}", trait_obj), - Applicability::MaybeIncorrect, - ); - if is_object_safe { - err.multipart_suggestion( - format!( - "use a boxed trait object if all return paths implement trait `{}`", - trait_obj, - ), - vec![ - (ret_ty.shrink_to_lo(), "Box<".to_string()), - (ret_ty.shrink_to_hi(), ">".to_string()), - ], - Applicability::MaybeIncorrect, - ); - } -} - /// Collect the spans that we see the generic param `param_did` struct ReplaceImplTraitVisitor<'a> { ty_spans: &'a mut Vec<Span>, |
