Skip to content

Commit 02c4769

Browse files
committed
Auto merge of rust-lang#139000 - compiler-errors:rigid-missing-item, r=
Rigidly project missing item due to guaranteed impossible sized predicate This is a somewhat involved change, but it amounts to treating missing impl items due to guaranteed impossible where clauses (dyn/str/slice sized, cc rust-lang#135480) as *rigid projections* rather than projecting to an error term, since that was preventing either reporting a proper error (in an empty param env) *or* successfully type checking the code (in the presence of trivially false where clauses). Fixes rust-lang#138970 r? `@lcnr` `@oli-obk`
2 parents 2196aff + 77e2d4a commit 02c4769

File tree

17 files changed

+448
-91
lines changed

17 files changed

+448
-91
lines changed

compiler/rustc_hir_analysis/src/check/check.rs

+3-27
Original file line numberDiff line numberDiff line change
@@ -949,31 +949,7 @@ fn check_impl_items_against_trait<'tcx>(
949949

950950
let trait_def = tcx.trait_def(trait_ref.def_id);
951951

952-
let infcx = tcx.infer_ctxt().ignoring_regions().build(TypingMode::non_body_analysis());
953-
954-
let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
955-
let cause = ObligationCause::misc(tcx.def_span(impl_id), impl_id);
956-
let param_env = tcx.param_env(impl_id);
957-
958-
let self_is_guaranteed_unsized = match tcx
959-
.struct_tail_raw(
960-
trait_ref.self_ty(),
961-
|ty| {
962-
ocx.structurally_normalize_ty(&cause, param_env, ty).unwrap_or_else(|_| {
963-
Ty::new_error_with_message(
964-
tcx,
965-
tcx.def_span(impl_id),
966-
"struct tail should be computable",
967-
)
968-
})
969-
},
970-
|| (),
971-
)
972-
.kind()
973-
{
974-
ty::Dynamic(_, _, ty::DynKind::Dyn) | ty::Slice(_) | ty::Str => true,
975-
_ => false,
976-
};
952+
let self_is_guaranteed_unsize_self = tcx.impl_self_is_guaranteed_unsized(impl_id);
977953

978954
for &impl_item in impl_item_refs {
979955
let ty_impl_item = tcx.associated_item(impl_item);
@@ -1004,7 +980,7 @@ fn check_impl_items_against_trait<'tcx>(
1004980
}
1005981
}
1006982

1007-
if self_is_guaranteed_unsized && tcx.generics_require_sized_self(ty_trait_item.def_id) {
983+
if self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(ty_trait_item.def_id) {
1008984
tcx.emit_node_span_lint(
1009985
rustc_lint_defs::builtin::DEAD_CODE,
1010986
tcx.local_def_id_to_hir_id(ty_impl_item.def_id.expect_local()),
@@ -1039,7 +1015,7 @@ fn check_impl_items_against_trait<'tcx>(
10391015
if !is_implemented
10401016
&& tcx.defaultness(impl_id).is_final()
10411017
// unsized types don't need to implement methods that have `Self: Sized` bounds.
1042-
&& !(self_is_guaranteed_unsized && tcx.generics_require_sized_self(trait_item_id))
1018+
&& !(self_is_guaranteed_unsize_self && tcx.generics_require_sized_self(trait_item_id))
10431019
{
10441020
missing_items.push(tcx.associated_item(trait_item_id));
10451021
}

compiler/rustc_middle/src/query/mod.rs

+7
Original file line numberDiff line numberDiff line change
@@ -1017,6 +1017,13 @@ rustc_queries! {
10171017
separate_provide_extern
10181018
}
10191019

1020+
/// Given an `impl_def_id`, return true if the self type is guaranteed to be unsized due
1021+
/// to either being one of the built-in unsized types (str/slice/dyn) or to be a struct
1022+
/// whose tail is one of those types.
1023+
query impl_self_is_guaranteed_unsized(impl_def_id: DefId) -> bool {
1024+
desc { |tcx| "computing whether `{}` has a guaranteed unsized self type", tcx.def_path_str(impl_def_id) }
1025+
}
1026+
10201027
/// Maps a `DefId` of a type to a list of its inherent impls.
10211028
/// Contains implementations of methods that are inherent to a type.
10221029
/// Methods in these implementations don't need to be exported.

compiler/rustc_middle/src/ty/context.rs

+4
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,10 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
434434
)
435435
}
436436

437+
fn impl_self_is_guaranteed_unsized(self, impl_def_id: DefId) -> bool {
438+
self.impl_self_is_guaranteed_unsized(impl_def_id)
439+
}
440+
437441
fn has_target_features(self, def_id: DefId) -> bool {
438442
!self.codegen_fn_attrs(def_id).target_features.is_empty()
439443
}

compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs

+13-3
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ where
134134
// Add GAT where clauses from the trait's definition
135135
// FIXME: We don't need these, since these are the type's own WF obligations.
136136
ecx.add_goals(
137-
GoalSource::Misc,
137+
GoalSource::AliasWellFormed,
138138
cx.own_predicates_of(goal.predicate.def_id())
139139
.iter_instantiated(cx, goal.predicate.alias.args)
140140
.map(|pred| goal.with(cx, pred)),
@@ -199,7 +199,7 @@ where
199199
// Add GAT where clauses from the trait's definition.
200200
// FIXME: We don't need these, since these are the type's own WF obligations.
201201
ecx.add_goals(
202-
GoalSource::Misc,
202+
GoalSource::AliasWellFormed,
203203
cx.own_predicates_of(goal.predicate.def_id())
204204
.iter_instantiated(cx, goal.predicate.alias.args)
205205
.map(|pred| goal.with(cx, pred)),
@@ -232,7 +232,17 @@ where
232232
};
233233

234234
if !cx.has_item_definition(target_item_def_id) {
235-
return error_response(ecx, cx.delay_bug("missing item"));
235+
// If the impl is missing an item, it's either because the user forgot to
236+
// provide it, or the user is not *obligated* to provide it (because it
237+
// has a trivially false `Sized` predicate). If it's the latter, we cannot
238+
// delay a bug because we can have trivially false where clauses, so we
239+
// treat it as rigid.
240+
if cx.impl_self_is_guaranteed_unsized(impl_def_id) {
241+
ecx.structurally_instantiate_normalizes_to_term(goal, goal.predicate.alias);
242+
return ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes);
243+
} else {
244+
return error_response(ecx, cx.delay_bug("missing item"));
245+
}
236246
}
237247

238248
let target_container_def_id = cx.parent(target_item_def_id);

compiler/rustc_trait_selection/src/traits/project.rs

+45-45
Original file line numberDiff line numberDiff line change
@@ -669,30 +669,11 @@ fn project<'cx, 'tcx>(
669669

670670
match candidates {
671671
ProjectionCandidateSet::Single(candidate) => {
672-
Ok(Projected::Progress(confirm_candidate(selcx, obligation, candidate)))
672+
confirm_candidate(selcx, obligation, candidate)
673673
}
674674
ProjectionCandidateSet::None => {
675675
let tcx = selcx.tcx();
676-
let term = match tcx.def_kind(obligation.predicate.def_id) {
677-
DefKind::AssocTy => Ty::new_projection_from_args(
678-
tcx,
679-
obligation.predicate.def_id,
680-
obligation.predicate.args,
681-
)
682-
.into(),
683-
DefKind::AssocConst => ty::Const::new_unevaluated(
684-
tcx,
685-
ty::UnevaluatedConst::new(
686-
obligation.predicate.def_id,
687-
obligation.predicate.args,
688-
),
689-
)
690-
.into(),
691-
kind => {
692-
bug!("unknown projection def-id: {}", kind.descr(obligation.predicate.def_id))
693-
}
694-
};
695-
676+
let term = obligation.predicate.to_term(tcx);
696677
Ok(Projected::NoProgress(term))
697678
}
698679
// Error occurred while trying to processing impls.
@@ -1243,18 +1224,16 @@ fn confirm_candidate<'cx, 'tcx>(
12431224
selcx: &mut SelectionContext<'cx, 'tcx>,
12441225
obligation: &ProjectionTermObligation<'tcx>,
12451226
candidate: ProjectionCandidate<'tcx>,
1246-
) -> Progress<'tcx> {
1227+
) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
12471228
debug!(?obligation, ?candidate, "confirm_candidate");
1248-
let mut progress = match candidate {
1229+
let mut result = match candidate {
12491230
ProjectionCandidate::ParamEnv(poly_projection)
1250-
| ProjectionCandidate::Object(poly_projection) => {
1251-
confirm_param_env_candidate(selcx, obligation, poly_projection, false)
1252-
}
1253-
1254-
ProjectionCandidate::TraitDef(poly_projection) => {
1255-
confirm_param_env_candidate(selcx, obligation, poly_projection, true)
1256-
}
1257-
1231+
| ProjectionCandidate::Object(poly_projection) => Ok(Projected::Progress(
1232+
confirm_param_env_candidate(selcx, obligation, poly_projection, false),
1233+
)),
1234+
ProjectionCandidate::TraitDef(poly_projection) => Ok(Projected::Progress(
1235+
confirm_param_env_candidate(selcx, obligation, poly_projection, true),
1236+
)),
12581237
ProjectionCandidate::Select(impl_source) => {
12591238
confirm_select_candidate(selcx, obligation, impl_source)
12601239
}
@@ -1265,23 +1244,26 @@ fn confirm_candidate<'cx, 'tcx>(
12651244
// with new region variables, we need to resolve them to existing variables
12661245
// when possible for this to work. See `auto-trait-projection-recursion.rs`
12671246
// for a case where this matters.
1268-
if progress.term.has_infer_regions() {
1247+
if let Ok(Projected::Progress(progress)) = &mut result
1248+
&& progress.term.has_infer_regions()
1249+
{
12691250
progress.term = progress.term.fold_with(&mut OpportunisticRegionResolver::new(selcx.infcx));
12701251
}
1271-
progress
1252+
1253+
result
12721254
}
12731255

12741256
fn confirm_select_candidate<'cx, 'tcx>(
12751257
selcx: &mut SelectionContext<'cx, 'tcx>,
12761258
obligation: &ProjectionTermObligation<'tcx>,
12771259
impl_source: Selection<'tcx>,
1278-
) -> Progress<'tcx> {
1260+
) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
12791261
match impl_source {
12801262
ImplSource::UserDefined(data) => confirm_impl_candidate(selcx, obligation, data),
12811263
ImplSource::Builtin(BuiltinImplSource::Misc | BuiltinImplSource::Trivial, data) => {
12821264
let tcx = selcx.tcx();
12831265
let trait_def_id = obligation.predicate.trait_def_id(tcx);
1284-
if tcx.is_lang_item(trait_def_id, LangItem::Coroutine) {
1266+
let progress = if tcx.is_lang_item(trait_def_id, LangItem::Coroutine) {
12851267
confirm_coroutine_candidate(selcx, obligation, data)
12861268
} else if tcx.is_lang_item(trait_def_id, LangItem::Future) {
12871269
confirm_future_candidate(selcx, obligation, data)
@@ -1303,7 +1285,8 @@ fn confirm_select_candidate<'cx, 'tcx>(
13031285
confirm_async_fn_kind_helper_candidate(selcx, obligation, data)
13041286
} else {
13051287
confirm_builtin_candidate(selcx, obligation, data)
1306-
}
1288+
};
1289+
Ok(Projected::Progress(progress))
13071290
}
13081291
ImplSource::Builtin(BuiltinImplSource::Object { .. }, _)
13091292
| ImplSource::Param(..)
@@ -1999,7 +1982,7 @@ fn confirm_impl_candidate<'cx, 'tcx>(
19991982
selcx: &mut SelectionContext<'cx, 'tcx>,
20001983
obligation: &ProjectionTermObligation<'tcx>,
20011984
impl_impl_source: ImplSourceUserDefinedData<'tcx, PredicateObligation<'tcx>>,
2002-
) -> Progress<'tcx> {
1985+
) -> Result<Projected<'tcx>, ProjectionError<'tcx>> {
20031986
let tcx = selcx.tcx();
20041987

20051988
let ImplSourceUserDefinedData { impl_def_id, args, mut nested } = impl_impl_source;
@@ -2010,19 +1993,33 @@ fn confirm_impl_candidate<'cx, 'tcx>(
20101993
let param_env = obligation.param_env;
20111994
let assoc_ty = match specialization_graph::assoc_def(tcx, impl_def_id, assoc_item_id) {
20121995
Ok(assoc_ty) => assoc_ty,
2013-
Err(guar) => return Progress::error(tcx, guar),
1996+
Err(guar) => return Ok(Projected::Progress(Progress::error(tcx, guar))),
20141997
};
1998+
1999+
// This means that the impl is missing a definition for the
2000+
// associated type. This is either because the associate item
2001+
// has impossible-to-satisfy predicates (since those were
2002+
// allowed in <https://github.com/rust-lang/rust/pull/135480>),
2003+
// or because the impl is literally missing the definition.
20152004
if !assoc_ty.item.defaultness(tcx).has_value() {
2016-
// This means that the impl is missing a definition for the
2017-
// associated type. This error will be reported by the type
2018-
// checker method `check_impl_items_against_trait`, so here we
2019-
// just return Error.
20202005
debug!(
20212006
"confirm_impl_candidate: no associated type {:?} for {:?}",
20222007
assoc_ty.item.name, obligation.predicate
20232008
);
2024-
return Progress { term: Ty::new_misc_error(tcx).into(), obligations: nested };
2009+
if tcx.impl_self_is_guaranteed_unsized(impl_def_id) {
2010+
// We treat this projection as rigid here, which is represented via
2011+
// `Projected::NoProgress`. This will ensure that the projection is
2012+
// checked for well-formedness, and it's either satisfied by a trivial
2013+
// where clause in its env or it results in an error.
2014+
return Ok(Projected::NoProgress(obligation.predicate.to_term(tcx)));
2015+
} else {
2016+
return Ok(Projected::Progress(Progress {
2017+
term: Ty::new_misc_error(tcx).into(),
2018+
obligations: nested,
2019+
}));
2020+
}
20252021
}
2022+
20262023
// If we're trying to normalize `<Vec<u32> as X>::A<S>` using
20272024
//`impl<T> X for Vec<T> { type A<Y> = Box<Y>; }`, then:
20282025
//
@@ -2032,6 +2029,7 @@ fn confirm_impl_candidate<'cx, 'tcx>(
20322029
let args = obligation.predicate.args.rebase_onto(tcx, trait_def_id, args);
20332030
let args = translate_args(selcx.infcx, param_env, impl_def_id, args, assoc_ty.defining_node);
20342031
let is_const = matches!(tcx.def_kind(assoc_ty.item.def_id), DefKind::AssocConst);
2032+
20352033
let term: ty::EarlyBinder<'tcx, ty::Term<'tcx>> = if is_const {
20362034
let did = assoc_ty.item.def_id;
20372035
let identity_args = crate::traits::GenericArgs::identity_for_item(tcx, did);
@@ -2040,7 +2038,8 @@ fn confirm_impl_candidate<'cx, 'tcx>(
20402038
} else {
20412039
tcx.type_of(assoc_ty.item.def_id).map_bound(|ty| ty.into())
20422040
};
2043-
if !tcx.check_args_compatible(assoc_ty.item.def_id, args) {
2041+
2042+
let progress = if !tcx.check_args_compatible(assoc_ty.item.def_id, args) {
20442043
let err = Ty::new_error_with_message(
20452044
tcx,
20462045
obligation.cause.span,
@@ -2050,7 +2049,8 @@ fn confirm_impl_candidate<'cx, 'tcx>(
20502049
} else {
20512050
assoc_ty_own_obligations(selcx, obligation, &mut nested);
20522051
Progress { term: term.instantiate(tcx, args), obligations: nested }
2053-
}
2052+
};
2053+
Ok(Projected::Progress(progress))
20542054
}
20552055

20562056
// Get obligations corresponding to the predicates from the where-clause of the

compiler/rustc_ty_utils/src/ty.rs

+57
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use rustc_hir as hir;
33
use rustc_hir::LangItem;
44
use rustc_hir::def::DefKind;
55
use rustc_index::bit_set::DenseBitSet;
6+
use rustc_infer::infer::TyCtxtInferExt;
67
use rustc_middle::bug;
78
use rustc_middle::query::Providers;
89
use rustc_middle::ty::{
@@ -312,6 +313,61 @@ fn unsizing_params_for_adt<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> DenseBitSe
312313
unsizing_params
313314
}
314315

316+
fn impl_self_is_guaranteed_unsized<'tcx>(tcx: TyCtxt<'tcx>, impl_def_id: DefId) -> bool {
317+
debug_assert_eq!(tcx.def_kind(impl_def_id), DefKind::Impl { of_trait: true });
318+
319+
let infcx = tcx.infer_ctxt().ignoring_regions().build(ty::TypingMode::non_body_analysis());
320+
321+
let ocx = traits::ObligationCtxt::new_with_diagnostics(&infcx);
322+
let cause = traits::ObligationCause::dummy();
323+
let param_env = tcx.param_env(impl_def_id);
324+
325+
let tail = tcx.struct_tail_raw(
326+
tcx.type_of(impl_def_id).instantiate_identity(),
327+
|ty| {
328+
ocx.structurally_normalize_ty(&cause, param_env, ty).unwrap_or_else(|_| {
329+
Ty::new_error_with_message(
330+
tcx,
331+
tcx.def_span(impl_def_id),
332+
"struct tail should be computable",
333+
)
334+
})
335+
},
336+
|| (),
337+
);
338+
339+
match tail.kind() {
340+
ty::Dynamic(_, _, ty::Dyn) | ty::Slice(_) | ty::Str => true,
341+
ty::Bool
342+
| ty::Char
343+
| ty::Int(_)
344+
| ty::Uint(_)
345+
| ty::Float(_)
346+
| ty::Adt(_, _)
347+
| ty::Foreign(_)
348+
| ty::Array(_, _)
349+
| ty::Pat(_, _)
350+
| ty::RawPtr(_, _)
351+
| ty::Ref(_, _, _)
352+
| ty::FnDef(_, _)
353+
| ty::FnPtr(_, _)
354+
| ty::UnsafeBinder(_)
355+
| ty::Closure(_, _)
356+
| ty::CoroutineClosure(_, _)
357+
| ty::Coroutine(_, _)
358+
| ty::CoroutineWitness(_, _)
359+
| ty::Never
360+
| ty::Tuple(_)
361+
| ty::Alias(_, _)
362+
| ty::Param(_)
363+
| ty::Bound(_, _)
364+
| ty::Placeholder(_)
365+
| ty::Infer(_)
366+
| ty::Error(_)
367+
| ty::Dynamic(_, _, ty::DynStar) => false,
368+
}
369+
}
370+
315371
pub(crate) fn provide(providers: &mut Providers) {
316372
*providers = Providers {
317373
asyncness,
@@ -320,6 +376,7 @@ pub(crate) fn provide(providers: &mut Providers) {
320376
param_env_normalized_for_post_analysis,
321377
defaultness,
322378
unsizing_params_for_adt,
379+
impl_self_is_guaranteed_unsized,
323380
..*providers
324381
};
325382
}

0 commit comments

Comments
 (0)