Skip to content

Commit

Permalink
Point at expressions where inference refines an unexpected type
Browse files Browse the repository at this point in the history
  • Loading branch information
estebank committed Jan 5, 2023
1 parent 1d284af commit ea43eb3
Show file tree
Hide file tree
Showing 24 changed files with 299 additions and 17 deletions.
162 changes: 159 additions & 3 deletions compiler/rustc_hir_typeck/src/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,19 @@ use rustc_errors::MultiSpan;
use rustc_errors::{Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed};
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::intravisit::Visitor;
use rustc_hir::lang_items::LangItem;
use rustc_hir::{is_range_literal, Node};
use rustc_infer::infer::InferOk;
use rustc_middle::lint::in_external_macro;
use rustc_middle::middle::stability::EvalResult;
use rustc_middle::ty::adjustment::AllowTwoPhase;
use rustc_middle::ty::error::{ExpectedFound, TypeError};
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, Article, AssocItem, Ty, TypeAndMut};
use rustc_middle::ty::fold::TypeFolder;
use rustc_middle::ty::print::{with_forced_trimmed_paths, with_no_trimmed_paths};
use rustc_middle::ty::{
self, Article, AssocItem, Ty, TyCtxt, TypeAndMut, TypeSuperFoldable, TypeVisitable,
};
use rustc_span::symbol::{sym, Symbol};
use rustc_span::{BytePos, Span};
use rustc_trait_selection::infer::InferCtxtExt as _;
Expand Down Expand Up @@ -53,7 +57,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|| self.suggest_block_to_brackets_peeling_refs(err, expr, expr_ty, expected)
|| self.suggest_copied_or_cloned(err, expr, expr_ty, expected)
|| self.suggest_into(err, expr, expr_ty, expected)
|| self.suggest_floating_point_literal(err, expr, expected);
|| self.suggest_floating_point_literal(err, expr, expected)
|| self.point_inference_types(err, expr);
}

pub fn emit_coerce_suggestions(
Expand Down Expand Up @@ -205,6 +210,157 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(expected, Some(err))
}

fn point_inference_types(&self, err: &mut Diagnostic, expr: &hir::Expr<'_>) -> bool {
let tcx = self.tcx;
let map = self.tcx.hir();

// Hack to make equality checks on types with inference variables and regions useful.
struct TypeEraser<'tcx> {
tcx: TyCtxt<'tcx>,
}
impl<'tcx> TypeFolder<'tcx> for TypeEraser<'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
self.tcx
}
fn fold_region(&mut self, _r: ty::Region<'tcx>) -> ty::Region<'tcx> {
self.tcx().lifetimes.re_erased
}
fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
if !t.needs_infer() && !t.has_erasable_regions() {
return t;
}
match *t.kind() {
ty::Infer(ty::TyVar(_) | ty::FreshTy(_)) => {
self.tcx.mk_ty_infer(ty::TyVar(ty::TyVid::from_u32(0)))
}
ty::Infer(ty::IntVar(_) | ty::FreshIntTy(_)) => {
self.tcx.mk_ty_infer(ty::IntVar(ty::IntVid { index: 0 }))
}
ty::Infer(ty::FloatVar(_) | ty::FreshFloatTy(_)) => {
self.tcx.mk_ty_infer(ty::FloatVar(ty::FloatVid { index: 0 }))
}
_ => t.super_fold_with(self),
}
}
fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
ct.super_fold_with(self)
}
}

let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind else { return false; };
let [hir::PathSegment { ident, args: None, .. }] = p.segments else { return false; };
let hir::def::Res::Local(hir_id) = p.res else { return false; };
let Some(node) = map.find(hir_id) else { return false; };
let hir::Node::Pat(pat) = node else { return false; };
let parent = map.get_parent_node(pat.hir_id);
let Some(hir::Node::Local(hir::Local {
ty: None,
init: Some(init),
..
})) = map.find(parent) else { return false; };

let ty = self.node_ty(init.hir_id);
if ty.is_closure() || init.span.overlaps(expr.span) {
return false;
}
let mut span_labels = vec![(
init.span,
with_forced_trimmed_paths!(format!(
"here the type of `{ident}` is inferred to be `{ty}`",
)),
)];

// Locate all the usages of the relevant binding.
struct FindExprs<'hir> {
hir_id: hir::HirId,
uses: Vec<&'hir hir::Expr<'hir>>,
}
impl<'v> Visitor<'v> for FindExprs<'v> {
fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = ex.kind
&& let hir::def::Res::Local(hir_id) = path.res
&& hir_id == self.hir_id
{
self.uses.push(ex);
}
hir::intravisit::walk_expr(self, ex);
}
}

let mut expr_finder = FindExprs { hir_id, uses: vec![] };
let id = map.get_parent_item(hir_id);
let hir_id: hir::HirId = id.into();

if let Some(node) = map.find(hir_id) && let Some(body_id) = node.body_id() {
let body = map.body(body_id);
expr_finder.visit_expr(body.value);
let mut eraser = TypeEraser { tcx };
let mut prev = eraser.fold_ty(ty);

for ex in expr_finder.uses {
if ex.span.overlaps(expr.span) { break; }
let parent = map.get_parent_node(ex.hir_id);
if let Some(hir::Node::Expr(expr))
| Some(hir::Node::Stmt(hir::Stmt {
kind: hir::StmtKind::Expr(expr) | hir::StmtKind::Semi(expr),
..
})) = &map.find(parent)
&& let hir::ExprKind::MethodCall(s, rcvr, args, span) = expr.kind
&& rcvr.hir_id == ex.hir_id
{
let ty = if let Ok(m) = self.lookup_method(ty, s, span, expr, rcvr, args) {
// We get the self type from `lookup_method` because the `rcvr` node
// type will not have had any adjustments from the fn arguments.
let ty = m.sig.inputs_and_output[0];
match ty.kind() {
// Remove one layer of references to account for `&mut self` and
// `&self`, so that we can compare it against the binding.
ty::Ref(_, ty, _) => *ty,
_ => ty,
}
} else {
self.node_ty(rcvr.hir_id)
};
let ty = eraser.fold_ty(ty);
if ty.references_error() {
break;
}
if ty != prev {
span_labels.push((
s.ident.span,
with_forced_trimmed_paths!(format!(
"here the type of `{ident}` is inferred to be `{ty}`",
)),
));
prev = ty;
}
} else {
let ty = eraser.fold_ty(self.node_ty(ex.hir_id));
if ty.references_error() {
break;
}
if ty != prev {
span_labels.push((
ex.span,
with_forced_trimmed_paths!(format!(
"here the type of `{ident}` is inferred to be `{ty}`",
)),
));
}
prev = ty;
}
if ex.hir_id == expr.hir_id {
// Stop showing spans after the error type was emitted.
break;
}
}
}
for (sp, label) in span_labels {
err.span_label(sp, &label);
}
true
}

fn annotate_expected_due_to_let_ty(
&self,
err: &mut Diagnostic,
Expand Down
2 changes: 2 additions & 0 deletions src/test/ui/argument-suggestions/two-mismatch-notes.stderr
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
error[E0308]: arguments to this function are incorrect
--> $DIR/two-mismatch-notes.rs:10:5
|
LL | let w = Wrapper::<isize>(1isize);
| ------------------------ here the type of `w` is inferred to be `Wrapper<isize>`
LL | foo(f, w);
| ^^^
|
Expand Down
2 changes: 2 additions & 0 deletions src/test/ui/async-await/dont-suggest-missing-await.stderr
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
error[E0308]: mismatched types
--> $DIR/dont-suggest-missing-await.rs:14:18
|
LL | let x = make_u32();
| ---------- here the type of `x` is inferred to be `impl Future<Output = u32>`
LL | take_u32(x)
| -------- ^ expected `u32`, found opaque type
| |
Expand Down
2 changes: 2 additions & 0 deletions src/test/ui/async-await/suggest-missing-await-closure.stderr
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
error[E0308]: mismatched types
--> $DIR/suggest-missing-await-closure.rs:16:18
|
LL | let x = make_u32();
| ---------- here the type of `x` is inferred to be `impl Future<Output = u32>`
LL | take_u32(x)
| -------- ^ expected `u32`, found opaque type
| |
Expand Down
2 changes: 2 additions & 0 deletions src/test/ui/async-await/suggest-missing-await.stderr
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
error[E0308]: mismatched types
--> $DIR/suggest-missing-await.rs:12:14
|
LL | let x = make_u32();
| ---------- here the type of `x` is inferred to be `impl Future<Output = u32>`
LL | take_u32(x)
| -------- ^ expected `u32`, found opaque type
| |
Expand Down
2 changes: 2 additions & 0 deletions src/test/ui/closures/closure-return-type-mismatch.stderr
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
error[E0308]: mismatched types
--> $DIR/closure-return-type-mismatch.rs:7:9
|
LL | let a = true;
| ---- here the type of `a` is inferred to be `bool`
LL | a
| ^ expected `&str`, found `bool`
|
Expand Down
9 changes: 9 additions & 0 deletions src/test/ui/coercion/coerce-to-bang.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ LL | fn foo(x: usize, y: !, z: usize) { }
error[E0308]: mismatched types
--> $DIR/coerce-to-bang.rs:26:12
|
LL | let b = 22;
| -- here the type of `b` is inferred to be `{integer}`
LL | let c = 44;
LL | foo(a, b, c); // ... and hence a reference to `a` is expected to diverge.
| --- ^ expected `!`, found integer
| |
Expand All @@ -49,6 +52,9 @@ LL | fn foo(x: usize, y: !, z: usize) { }
error[E0308]: mismatched types
--> $DIR/coerce-to-bang.rs:36:12
|
LL | let b = 22;
| -- here the type of `b` is inferred to be `{integer}`
LL | let c = 44;
LL | foo(a, b, c);
| --- ^ expected `!`, found integer
| |
Expand All @@ -65,6 +71,9 @@ LL | fn foo(x: usize, y: !, z: usize) { }
error[E0308]: mismatched types
--> $DIR/coerce-to-bang.rs:45:12
|
LL | let b = 22;
| -- here the type of `b` is inferred to be `{integer}`
LL | let c = 44;
LL | foo(a, b, c);
| --- ^ expected `!`, found integer
| |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ error[E0308]: mismatched types
LL | fn floatify_sibling<C>(ints: &C) -> <C as Collection<i32>>::Sibling<f32>
| ------------------------------------ expected `<C as Collection<i32>>::Sibling<f32>` because of return type
...
LL | let mut res = <C::Family as CollectionFamily>::Member::<f32>::empty();
| ------------------------------------------------------- here the type of `res` is inferred to be `<<C as Collection<i32>>::Family as CollectionFamily>::Member<f32>`
...
LL | res
| ^^^ expected Collection::Sibling, found CollectionFamily::Member
|
Expand Down
2 changes: 2 additions & 0 deletions src/test/ui/issues/issue-15783.stderr
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
error[E0308]: mismatched types
--> $DIR/issue-15783.rs:8:19
|
LL | let x = Some(&[name]);
| ------------- here the type of `x` is inferred to be `Option<_>`
LL | let msg = foo(x);
| --- ^ expected slice `[&str]`, found array `[&str; 1]`
| |
Expand Down
12 changes: 12 additions & 0 deletions src/test/ui/let-else/let-else-ref-bindings.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ LL | let Some(ref a): Option<&[u8]> = &some else { return };
error[E0308]: mismatched types
--> $DIR/let-else-ref-bindings.rs:24:34
|
LL | let some = Some(bytes);
| ----------- here the type of `some` is inferred to be `Option<_>`
...
LL | let Some(ref a): Option<&[u8]> = some else { return };
| ---- here the type of `some` is inferred to be `Option<Vec<u8>>`
...
LL | let Some(a): Option<&[u8]> = some else { return };
| ------------- ^^^^ expected `&[u8]`, found struct `Vec`
| |
Expand Down Expand Up @@ -59,6 +65,12 @@ LL | let Some(ref mut a): Option<&mut [u8]> = &mut some else { return };
error[E0308]: mismatched types
--> $DIR/let-else-ref-bindings.rs:52:38
|
LL | let mut some = Some(bytes);
| ----------- here the type of `some` is inferred to be `Option<_>`
...
LL | let Some(ref mut a): Option<&mut [u8]> = some else { return };
| ---- here the type of `some` is inferred to be `Option<Vec<u8>>`
...
LL | let Some(a): Option<&mut [u8]> = some else { return };
| ----------------- ^^^^ expected `&mut [u8]`, found struct `Vec`
| |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ LL | #![feature(unsized_locals, unsized_fn_params)]
error[E0308]: mismatched types
--> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:87:24
|
LL | let z = x.foo();
| ------- here the type of `z` is inferred to be `u32`
...
LL | let _seetype: () = z;
| -- ^ expected `()`, found `u32`
| |
Expand All @@ -18,6 +21,9 @@ LL | let _seetype: () = z;
error[E0308]: mismatched types
--> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:104:24
|
LL | let z = x.foo();
| ------- here the type of `z` is inferred to be `u64`
...
LL | let _seetype: () = z;
| -- ^ expected `()`, found `u64`
| |
Expand Down Expand Up @@ -60,6 +66,9 @@ LL | let z = FinalFoo::foo(x);
error[E0308]: mismatched types
--> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:139:24
|
LL | let z = x.foo();
| ------- here the type of `z` is inferred to be `u8`
...
LL | let _seetype: () = z;
| -- ^ expected `()`, found `u8`
| |
Expand All @@ -68,6 +77,9 @@ LL | let _seetype: () = z;
error[E0308]: mismatched types
--> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:157:24
|
LL | let z = x.foo();
| ------- here the type of `z` is inferred to be `u32`
...
LL | let _seetype: () = z;
| -- ^ expected `()`, found `u32`
| |
Expand All @@ -76,6 +88,9 @@ LL | let _seetype: () = z;
error[E0308]: mismatched types
--> $DIR/method-deref-to-same-trait-object-with-separate-params.rs:174:24
|
LL | let z = x.foo();
| ------- here the type of `z` is inferred to be `u32`
...
LL | let _seetype: () = z;
| -- ^ expected `()`, found `u32`
| |
Expand Down
Loading

0 comments on commit ea43eb3

Please sign in to comment.