Skip to content

Tweak assoc type obligation spans #91769

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

Merged
merged 1 commit into from
Dec 12, 2021
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
39 changes: 36 additions & 3 deletions compiler/rustc_infer/src/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1429,13 +1429,23 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}
}

/// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
/// the return type of `async fn`s.
///
/// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
///
/// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
/// the message in `secondary_span` as the primary label, and apply the message that would
/// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
/// E0271, like `src/test/ui/issues/issue-39970.stderr`.
pub fn note_type_err(
&self,
diag: &mut DiagnosticBuilder<'tcx>,
cause: &ObligationCause<'tcx>,
secondary_span: Option<(Span, String)>,
mut values: Option<ValuePairs<'tcx>>,
terr: &TypeError<'tcx>,
swap_secondary_and_primary: bool,
) {
let span = cause.span(self.tcx);
debug!("note_type_err cause={:?} values={:?}, terr={:?}", cause, values, terr);
Expand Down Expand Up @@ -1612,9 +1622,32 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
match terr {
TypeError::ObjectUnsafeCoercion(_) => {}
_ => {
diag.span_label(span, terr.to_string());
let mut label_or_note = |span: Span, msg: &str| {
if &[span] == diag.span.primary_spans() {
diag.span_label(span, msg);
} else {
diag.span_note(span, msg);
}
};
if let Some((sp, msg)) = secondary_span {
diag.span_label(sp, msg);
if swap_secondary_and_primary {
let terr = if let Some(infer::ValuePairs::Types(infer::ExpectedFound {
expected,
..
})) = values
{
format!("expected this to be `{}`", expected)
} else {
terr.to_string()
};
label_or_note(sp, &terr);
label_or_note(span, &msg);
} else {
label_or_note(span, &terr.to_string());
label_or_note(sp, &msg);
}
} else {
label_or_note(span, &terr.to_string());
}
}
};
Expand Down Expand Up @@ -2048,7 +2081,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
}
};
self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false);
diag
}

Expand Down
6 changes: 2 additions & 4 deletions compiler/rustc_middle/src/ty/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,17 +118,15 @@ impl<'tcx> fmt::Display for TypeError<'tcx> {
ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
TupleSize(values) => write!(
f,
"expected a tuple with {} element{}, \
found one with {} element{}",
"expected a tuple with {} element{}, found one with {} element{}",
values.expected,
pluralize!(values.expected),
values.found,
pluralize!(values.found)
),
FixedArraySize(values) => write!(
f,
"expected an array with a fixed size of {} element{}, \
found one with {} element{}",
"expected an array with a fixed size of {} element{}, found one with {} element{}",
values.expected,
pluralize!(values.expected),
values.found,
Expand Down
56 changes: 53 additions & 3 deletions compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1338,7 +1338,46 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
"type mismatch resolving `{}`",
predicate
);
self.note_type_err(&mut diag, &obligation.cause, None, values, err);
let secondary_span = match predicate.kind().skip_binder() {
ty::PredicateKind::Projection(proj) => self
.tcx
.opt_associated_item(proj.projection_ty.item_def_id)
.and_then(|trait_assoc_item| {
self.tcx
.trait_of_item(proj.projection_ty.item_def_id)
.map(|id| (trait_assoc_item, id))
})
.and_then(|(trait_assoc_item, id)| {
self.tcx.find_map_relevant_impl(
id,
proj.projection_ty.self_ty(),
|did| {
self.tcx
.associated_items(did)
.in_definition_order()
.filter(|assoc| assoc.ident == trait_assoc_item.ident)
.next()
},
)
})
.and_then(|item| match self.tcx.hir().get_if_local(item.def_id) {
Some(
hir::Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Type(_, Some(ty)),
..
})
| hir::Node::ImplItem(hir::ImplItem {
kind: hir::ImplItemKind::TyAlias(ty),
..
}),
) => {
Some((ty.span, format!("type mismatch resolving `{}`", predicate)))
}
_ => None,
}),
_ => None,
};
self.note_type_err(&mut diag, &obligation.cause, secondary_span, values, err, true);
self.note_obligation_cause(&mut diag, obligation);
diag.emit();
}
Expand Down Expand Up @@ -2095,10 +2134,21 @@ impl<'a, 'tcx> InferCtxtPrivExt<'tcx> for InferCtxt<'a, 'tcx> {
) -> bool {
if let ObligationCauseCode::BuiltinDerivedObligation(ref data) = cause_code {
let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_ref);

if obligated_types.iter().any(|ot| ot == &parent_trait_ref.skip_binder().self_ty()) {
let self_ty = parent_trait_ref.skip_binder().self_ty();
if obligated_types.iter().any(|ot| ot == &self_ty) {
return true;
}
if let ty::Adt(def, substs) = self_ty.kind() {
if let [arg] = &substs[..] {
if let ty::subst::GenericArgKind::Type(ty) = arg.unpack() {
if let ty::Adt(inner_def, _) = ty.kind() {
if inner_def == def {
return true;
}
}
}
}
}
}
false
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2186,6 +2186,16 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
seen_requirements,
)
});
} else {
ensure_sufficient_stack(|| {
self.note_obligation_cause_code(
err,
&parent_predicate,
&cause_code.peel_derives(),
obligated_types,
seen_requirements,
)
});
}
}
ObligationCauseCode::ImplDerivedObligation(ref data) => {
Expand Down
6 changes: 5 additions & 1 deletion compiler/rustc_typeck/src/check/cast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,11 @@ impl<'a, 'tcx> CastCheck<'tcx> {
self.expr_ty = fcx.structurally_resolved_type(self.expr.span, self.expr_ty);
self.cast_ty = fcx.structurally_resolved_type(self.cast_span, self.cast_ty);

if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span) {
debug!("check_cast({}, {:?} as {:?})", self.expr.hir_id, self.expr_ty, self.cast_ty);

if !fcx.type_is_known_to_be_sized_modulo_regions(self.cast_ty, self.span)
&& !self.cast_ty.has_infer_types()
{
self.report_cast_to_unsized_type(fcx);
} else if self.expr_ty.references_error() || self.cast_ty.references_error() {
// No sense in giving duplicate error messages
Expand Down
8 changes: 4 additions & 4 deletions compiler/rustc_typeck/src/check/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -730,15 +730,15 @@ pub fn check_item_type<'tcx>(tcx: TyCtxt<'tcx>, it: &'tcx hir::Item<'tcx>) {
let abi = sig.header.abi;
fn_maybe_err(tcx, item.ident.span, abi);
}
hir::TraitItemKind::Type(.., Some(_default)) => {
hir::TraitItemKind::Type(.., Some(default)) => {
let assoc_item = tcx.associated_item(item.def_id);
let trait_substs =
InternalSubsts::identity_for_item(tcx, it.def_id.to_def_id());
let _: Result<_, rustc_errors::ErrorReported> = check_type_bounds(
tcx,
assoc_item,
assoc_item,
item.span,
default.span,
ty::TraitRef { def_id: it.def_id.to_def_id(), substs: trait_substs },
);
}
Expand Down Expand Up @@ -987,12 +987,12 @@ pub(super) fn check_impl_items_against_trait<'tcx>(
opt_trait_span,
);
}
hir::ImplItemKind::TyAlias(_) => {
hir::ImplItemKind::TyAlias(impl_ty) => {
let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id);
compare_ty_impl(
tcx,
&ty_impl_item,
impl_item.span,
impl_ty.span,
&ty_trait_item,
impl_trait_ref,
opt_trait_span,
Expand Down
8 changes: 5 additions & 3 deletions compiler/rustc_typeck/src/check/compare_method.rs
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,7 @@ fn compare_predicate_entailment<'tcx>(
found: impl_fty,
})),
&terr,
false,
);
diag.emit();
return Err(ErrorReported);
Expand Down Expand Up @@ -734,8 +735,7 @@ fn compare_number_of_method_arguments<'tcx>(
tcx.sess,
impl_span,
E0050,
"method `{}` has {} but the declaration in \
trait `{}` has {}",
"method `{}` has {} but the declaration in trait `{}` has {}",
trait_m.ident,
potentially_plural_count(impl_number_args, "parameter"),
tcx.def_path_str(trait_m.def_id),
Expand Down Expand Up @@ -1069,6 +1069,7 @@ crate fn compare_const_impl<'tcx>(
found: impl_ty,
})),
&terr,
false,
);
diag.emit();
}
Expand Down Expand Up @@ -1099,7 +1100,8 @@ crate fn compare_ty_impl<'tcx>(
let _: Result<(), ErrorReported> = (|| {
compare_number_of_generics(tcx, impl_ty, impl_ty_span, trait_ty, trait_item_span)?;

compare_type_predicate_entailment(tcx, impl_ty, impl_ty_span, trait_ty, impl_trait_ref)?;
let sp = tcx.def_span(impl_ty.def_id);
compare_type_predicate_entailment(tcx, impl_ty, sp, trait_ty, impl_trait_ref)?;

check_type_bounds(tcx, trait_ty, impl_ty, impl_ty_span, impl_trait_ref)
})();
Expand Down
3 changes: 2 additions & 1 deletion compiler/rustc_typeck/src/check/wfcheck.rs
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,8 @@ pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: LocalDefId) {

let (method_sig, span) = match impl_item.kind {
hir::ImplItemKind::Fn(ref sig, _) => (Some(sig), impl_item.span),
hir::ImplItemKind::TyAlias(ty) => (None, ty.span),
// Constrain binding and overflow error spans to `<Ty>` in `type foo = <Ty>`.
hir::ImplItemKind::TyAlias(ty) if ty.span != DUMMY_SP => (None, ty.span),
_ => (None, impl_item.span),
};

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
error[E0326]: implemented const `FROM` has an incompatible type for trait
--> $DIR/associated-const-generic-obligations.rs:14:17
|
LL | const FROM: Self::Out;
| --------- type in trait
...
LL | const FROM: &'static str = "foo";
| ^^^^^^^^^^^^ expected associated type, found `&str`
|
note: type in trait
--> $DIR/associated-const-generic-obligations.rs:10:17
|
LL | const FROM: Self::Out;
| ^^^^^^^^^
= note: expected associated type `<T as Foo>::Out`
found reference `&'static str`

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
error[E0326]: implemented const `BAR` has an incompatible type for trait
--> $DIR/associated-const-impl-wrong-type.rs:8:16
|
LL | const BAR: u32;
| --- type in trait
...
LL | const BAR: i32 = -1;
| ^^^ expected `u32`, found `i32`
|
note: type in trait
--> $DIR/associated-const-impl-wrong-type.rs:2:16
|
LL | const BAR: u32;
| ^^^

error: aborting due to previous error

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@ error[E0271]: type mismatch resolving `<ModelT as Vehicle>::Color == Blue`
--> $DIR/associated-types-binding-to-type-defined-in-supertrait.rs:31:10
|
LL | fn b() { blue_car(ModelT); }
| ^^^^^^^^ expected struct `Blue`, found struct `Black`
| ^^^^^^^^ type mismatch resolving `<ModelT as Vehicle>::Color == Blue`
|
note: expected this to be `Blue`
--> $DIR/associated-types-binding-to-type-defined-in-supertrait.rs:16:40
|
LL | impl Vehicle for ModelT { type Color = Black; }
| ^^^^^
note: required by a bound in `blue_car`
--> $DIR/associated-types-binding-to-type-defined-in-supertrait.rs:27:19
|
Expand All @@ -14,8 +19,13 @@ error[E0271]: type mismatch resolving `<ModelU as Vehicle>::Color == Black`
--> $DIR/associated-types-binding-to-type-defined-in-supertrait.rs:32:10
|
LL | fn c() { black_car(ModelU); }
| ^^^^^^^^^ expected struct `Black`, found struct `Blue`
| ^^^^^^^^^ type mismatch resolving `<ModelU as Vehicle>::Color == Black`
|
note: expected this to be `Black`
--> $DIR/associated-types-binding-to-type-defined-in-supertrait.rs:21:40
|
LL | impl Vehicle for ModelU { type Color = Blue; }
| ^^^^
note: required by a bound in `black_car`
--> $DIR/associated-types-binding-to-type-defined-in-supertrait.rs:24:20
|
Expand Down
2 changes: 0 additions & 2 deletions src/test/ui/associated-types/associated-types-eq-3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,6 @@ pub fn main() {
let a = 42;
foo1(a);
//~^ ERROR type mismatch resolving
//~| expected struct `Bar`, found `usize`
baz(&a);
//~^ ERROR type mismatch resolving
//~| expected struct `Bar`, found `usize`
}
16 changes: 13 additions & 3 deletions src/test/ui/associated-types/associated-types-eq-3.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,30 @@ error[E0271]: type mismatch resolving `<isize as Foo>::A == Bar`
--> $DIR/associated-types-eq-3.rs:38:5
|
LL | foo1(a);
| ^^^^ expected struct `Bar`, found `usize`
| ^^^^ type mismatch resolving `<isize as Foo>::A == Bar`
|
note: expected this to be `Bar`
--> $DIR/associated-types-eq-3.rs:12:14
|
LL | type A = usize;
| ^^^^^
note: required by a bound in `foo1`
--> $DIR/associated-types-eq-3.rs:18:16
|
LL | fn foo1<I: Foo<A=Bar>>(x: I) {
| ^^^^^ required by this bound in `foo1`

error[E0271]: type mismatch resolving `<isize as Foo>::A == Bar`
--> $DIR/associated-types-eq-3.rs:41:9
--> $DIR/associated-types-eq-3.rs:40:9
|
LL | baz(&a);
| ^^ expected struct `Bar`, found `usize`
| ^^ type mismatch resolving `<isize as Foo>::A == Bar`
|
note: expected this to be `Bar`
--> $DIR/associated-types-eq-3.rs:12:14
|
LL | type A = usize;
| ^^^^^
= note: required for the cast to the object type `dyn Foo<A = Bar>`

error: aborting due to 3 previous errors
Expand Down
Loading