Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Actually taint InferCtxt when a fulfillment error is emitted #126620

Merged
merged 4 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 1 addition & 10 deletions compiler/rustc_hir_analysis/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,16 +119,7 @@ where

let errors = wfcx.select_all_or_error();
if !errors.is_empty() {
let err = infcx.err_ctxt().report_fulfillment_errors(errors);
if tcx.dcx().has_errors().is_some() {
return Err(err);
} else {
// HACK(oli-obk): tests/ui/specialization/min_specialization/specialize_on_type_error.rs
// causes an delayed bug during normalization, without reporting an error, so we need
// to act as if no error happened, in order to let our callers continue and report an
// error later in check_impl_items_against_trait.
return Ok(());
}
return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
}

debug!(?assumed_wf_types);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/writeback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -793,7 +793,7 @@ impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
}

fn report_error(&self, p: impl Into<ty::GenericArg<'tcx>>) -> ErrorGuaranteed {
if let Some(guar) = self.fcx.dcx().has_errors() {
if let Some(guar) = self.fcx.tainted_by_errors() {
guar
} else {
self.fcx
Expand Down
188 changes: 103 additions & 85 deletions compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2776,97 +2776,115 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
let mut this = "this bound";
let mut note = None;
let mut help = None;
if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder()
&& let ty::ClauseKind::Trait(trait_pred) = clause
{
let def_id = trait_pred.def_id();
let visible_item = if let Some(local) = def_id.as_local() {
// Check for local traits being reachable.
let vis = &tcx.resolutions(()).effective_visibilities;
// Account for non-`pub` traits in the root of the local crate.
let is_locally_reachable = tcx.parent(def_id).is_crate_root();
vis.is_reachable(local) || is_locally_reachable
} else {
// Check for foreign traits being reachable.
tcx.visible_parent_map(()).get(&def_id).is_some()
};
if tcx.is_lang_item(def_id, LangItem::Sized) {
// Check if this is an implicit bound, even in foreign crates.
if tcx
.generics_of(item_def_id)
.own_params
.iter()
.any(|param| tcx.def_span(param.def_id) == span)
{
a = "an implicit `Sized`";
this = "the implicit `Sized` requirement on this type parameter";
}
if let Some(hir::Node::TraitItem(hir::TraitItem {
generics,
kind: hir::TraitItemKind::Type(bounds, None),
..
})) = tcx.hir().get_if_local(item_def_id)
// Do not suggest relaxing if there is an explicit `Sized` obligation.
&& !bounds.iter()
.filter_map(|bound| bound.trait_ref())
.any(|tr| tr.trait_def_id() == tcx.lang_items().sized_trait())
{
let (span, separator) = if let [.., last] = bounds {
(last.span().shrink_to_hi(), " +")
if let ty::PredicateKind::Clause(clause) = predicate.kind().skip_binder() {
match clause {
ty::ClauseKind::Trait(trait_pred) => {
let def_id = trait_pred.def_id();
let visible_item = if let Some(local) = def_id.as_local() {
// Check for local traits being reachable.
let vis = &tcx.resolutions(()).effective_visibilities;
// Account for non-`pub` traits in the root of the local crate.
let is_locally_reachable = tcx.parent(def_id).is_crate_root();
vis.is_reachable(local) || is_locally_reachable
} else {
(generics.span.shrink_to_hi(), ":")
// Check for foreign traits being reachable.
tcx.visible_parent_map(()).get(&def_id).is_some()
};
err.span_suggestion_verbose(
span,
"consider relaxing the implicit `Sized` restriction",
format!("{separator} ?Sized"),
Applicability::MachineApplicable,
);
if tcx.is_lang_item(def_id, LangItem::Sized) {
// Check if this is an implicit bound, even in foreign crates.
if tcx
.generics_of(item_def_id)
.own_params
.iter()
.any(|param| tcx.def_span(param.def_id) == span)
{
a = "an implicit `Sized`";
this =
"the implicit `Sized` requirement on this type parameter";
}
if let Some(hir::Node::TraitItem(hir::TraitItem {
generics,
kind: hir::TraitItemKind::Type(bounds, None),
..
})) = tcx.hir().get_if_local(item_def_id)
// Do not suggest relaxing if there is an explicit `Sized` obligation.
&& !bounds.iter()
.filter_map(|bound| bound.trait_ref())
.any(|tr| tr.trait_def_id() == tcx.lang_items().sized_trait())
{
let (span, separator) = if let [.., last] = bounds {
(last.span().shrink_to_hi(), " +")
} else {
(generics.span.shrink_to_hi(), ":")
};
err.span_suggestion_verbose(
span,
"consider relaxing the implicit `Sized` restriction",
format!("{separator} ?Sized"),
Applicability::MachineApplicable,
);
}
}
if let DefKind::Trait = tcx.def_kind(item_def_id)
&& !visible_item
{
note = Some(format!(
"`{short_item_name}` is a \"sealed trait\", because to implement it \
you also need to implement `{}`, which is not accessible; this is \
usually done to force you to use one of the provided types that \
already implement it",
with_no_trimmed_paths!(tcx.def_path_str(def_id)),
));
let impls_of = tcx.trait_impls_of(def_id);
let impls = impls_of
.non_blanket_impls()
.values()
.flatten()
.chain(impls_of.blanket_impls().iter())
.collect::<Vec<_>>();
if !impls.is_empty() {
let len = impls.len();
let mut types = impls
.iter()
.map(|t| {
with_no_trimmed_paths!(format!(
" {}",
tcx.type_of(*t).instantiate_identity(),
))
})
.collect::<Vec<_>>();
let post = if types.len() > 9 {
types.truncate(8);
format!("\nand {} others", len - 8)
} else {
String::new()
};
help = Some(format!(
"the following type{} implement{} the trait:\n{}{post}",
pluralize!(len),
if len == 1 { "s" } else { "" },
types.join("\n"),
));
}
}
}
}
if let DefKind::Trait = tcx.def_kind(item_def_id)
&& !visible_item
{
note = Some(format!(
"`{short_item_name}` is a \"sealed trait\", because to implement it \
you also need to implement `{}`, which is not accessible; this is \
usually done to force you to use one of the provided types that \
already implement it",
with_no_trimmed_paths!(tcx.def_path_str(def_id)),
));
let impls_of = tcx.trait_impls_of(def_id);
let impls = impls_of
.non_blanket_impls()
.values()
.flatten()
.chain(impls_of.blanket_impls().iter())
.collect::<Vec<_>>();
if !impls.is_empty() {
let len = impls.len();
let mut types = impls
.iter()
.map(|t| {
with_no_trimmed_paths!(format!(
" {}",
tcx.type_of(*t).instantiate_identity(),
))
})
.collect::<Vec<_>>();
let post = if types.len() > 9 {
types.truncate(8);
format!("\nand {} others", len - 8)
ty::ClauseKind::ConstArgHasType(..) => {
let descr =
format!("required by a const generic parameter in `{item_name}`");
if span.is_visible(sm) {
let msg = format!(
"required by this const generic parameter in `{short_item_name}`"
);
multispan.push_span_label(span, msg);
err.span_note(multispan, descr);
} else {
String::new()
};
help = Some(format!(
"the following type{} implement{} the trait:\n{}{post}",
pluralize!(len),
if len == 1 { "s" } else { "" },
types.join("\n"),
));
err.span_note(tcx.def_span(item_def_id), descr);
}
return;
}
_ => (),
}
};
}
let descr = format!("required by {a} bound in `{item_name}`");
if span.is_visible(sm) {
let msg = format!("required by {this} in `{short_item_name}`");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
for (error, suppressed) in iter::zip(&errors, &is_suppressed) {
if !suppressed && error.obligation.cause.span.from_expansion() == from_expansion {
let guar = self.report_fulfillment_error(error);
self.infcx.set_tainted_by_errors(guar);
reported = Some(guar);
// We want to ignore desugarings here: spans are equivalent even
// if one is the result of a desugaring and the other is not.
Expand Down Expand Up @@ -2686,22 +2687,14 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
}
}

// Given some `ConstArgHasType(?x, usize)`, we should not emit an error such as
// "type annotations needed: cannot satisfy the constant `_` has type `usize`"
// Instead we should emit a normal error suggesting the user to turbofish the
// const parameter that is currently being inferred. Unfortunately we cannot
// nicely emit such an error so we delay an ICE incase nobody else reports it
// for us.
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ty)) => {
return self.tcx.sess.dcx().span_delayed_bug(
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ..)) => self
.emit_inference_failure_err(
obligation.cause.body_id,
span,
format!(
"`ambiguous ConstArgHasType({:?}, {:?}) unaccompanied by inference error`",
ct, ty
),
);
}

ct.into(),
ErrorCode::E0284,
true,
),
ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term })
if term.is_infer() =>
{
Expand Down
38 changes: 0 additions & 38 deletions tests/crashes/122044.rs

This file was deleted.

13 changes: 0 additions & 13 deletions tests/crashes/123255.rs

This file was deleted.

2 changes: 2 additions & 0 deletions tests/incremental/const-generics/issue-64087.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@ fn combinator<T, const S: usize>() -> [T; S] {}
fn main() {
combinator().into_iter();
//[cfail1]~^ ERROR type annotations needed
//[cfail1]~| ERROR type annotations needed
//[cfail1]~| ERROR type annotations needed
}
1 change: 1 addition & 0 deletions tests/ui/const-generics/defaults/doesnt_infer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ fn main() {
let foo = Foo::<1>::foo();
let foo = Foo::foo();
//~^ ERROR type annotations needed for `Foo<_>`
//~| ERROR type annotations needed
}
31 changes: 27 additions & 4 deletions tests/ui/const-generics/defaults/doesnt_infer.stderr
Original file line number Diff line number Diff line change
@@ -1,14 +1,37 @@
error[E0282]: type annotations needed for `Foo<_>`
error[E0284]: type annotations needed for `Foo<_>`
--> $DIR/doesnt_infer.rs:13:9
|
LL | let foo = Foo::foo();
| ^^^
| ^^^ ---------- type must be known at this point
|
note: required by a const generic parameter in `Foo::<N>::foo`
--> $DIR/doesnt_infer.rs:5:6
|
LL | impl<const N: u32> Foo<N> {
| ^^^^^^^^^^^^ required by this const generic parameter in `Foo::<N>::foo`
LL | fn foo() -> Self {
| --- required by a bound in this associated function
help: consider giving `foo` an explicit type, where the value of const parameter `N` is specified
|
LL | let foo: Foo<N> = Foo::foo();
| ++++++++

error[E0284]: type annotations needed for `Foo<_>`
--> $DIR/doesnt_infer.rs:13:9
|
LL | let foo = Foo::foo();
| ^^^ --- type must be known at this point
|
note: required by a const generic parameter in `Foo`
--> $DIR/doesnt_infer.rs:3:12
|
LL | struct Foo<const N: u32 = 2>;
| ^^^^^^^^^^^^^^^^ required by this const generic parameter in `Foo`
help: consider giving `foo` an explicit type, where the value of const parameter `N` is specified
|
LL | let foo: Foo<N> = Foo::foo();
| ++++++++

error: aborting due to 1 previous error
error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0282`.
For more information about this error, try `rustc --explain E0284`.
9 changes: 7 additions & 2 deletions tests/ui/const-generics/defaults/rp_impl_trait_fail.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,23 @@ LL | 1_u64
|
= help: the trait `Traitor<1, 2>` is implemented for `u64`

error[E0282]: type annotations needed
error[E0284]: type annotations needed
--> $DIR/rp_impl_trait_fail.rs:28:5
|
LL | uwu();
| ^^^ cannot infer the value of the const parameter `N` declared on the function `uwu`
|
note: required by a const generic parameter in `uwu`
--> $DIR/rp_impl_trait_fail.rs:16:8
|
LL | fn uwu<const N: u8>() -> impl Traitor<N> {
| ^^^^^^^^^^^ required by this const generic parameter in `uwu`
help: consider specifying the generic argument
|
LL | uwu::<N>();
| +++++

error: aborting due to 4 previous errors

Some errors have detailed explanations: E0277, E0282.
Some errors have detailed explanations: E0277, E0284.
For more information about an error, try `rustc --explain E0277`.
Loading
Loading