Skip to content

Commit 7945eff

Browse files
committed
generalize diagnostic for x = y where type bool is expected.
1 parent 267fb90 commit 7945eff

File tree

3 files changed

+111
-85
lines changed

3 files changed

+111
-85
lines changed

src/librustc_typeck/check/coercion.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1233,7 +1233,12 @@ impl<'gcx, 'tcx, 'exprs, E> CoerceMany<'gcx, 'tcx, 'exprs, E>
12331233
augment_error(&mut db);
12341234
}
12351235

1236-
db.emit();
1236+
if expression.filter(|e| fcx.is_assign_to_bool(e, expected)).is_some() {
1237+
// Error reported in `check_assign` so avoid emitting error again.
1238+
db.delay_as_bug();
1239+
} else {
1240+
db.emit();
1241+
}
12371242

12381243
self.final_ty = Some(fcx.tcx.types.err);
12391244
}

src/librustc_typeck/check/demand.rs

Lines changed: 52 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -119,44 +119,65 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
119119
let expr_ty = self.resolve_type_vars_with_obligations(checked_ty);
120120
let mut err = self.report_mismatched_types(&cause, expected, expr_ty, e);
121121

122-
// If the expected type is an enum (Issue #55250) with any variants whose
123-
// sole field is of the found type, suggest such variants. (Issue #42764)
124-
if let ty::Adt(expected_adt, substs) = expected.sty {
125-
if expected_adt.is_enum() {
126-
let mut compatible_variants = expected_adt.variants
127-
.iter()
128-
.filter(|variant| variant.fields.len() == 1)
129-
.filter_map(|variant| {
130-
let sole_field = &variant.fields[0];
131-
let sole_field_ty = sole_field.ty(self.tcx, substs);
132-
if self.can_coerce(expr_ty, sole_field_ty) {
133-
let variant_path = self.tcx.def_path_str(variant.def_id);
134-
// FIXME #56861: DRYer prelude filtering
135-
Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
136-
} else {
137-
None
138-
}
139-
}).peekable();
140-
141-
if compatible_variants.peek().is_some() {
142-
let expr_text = print::to_string(print::NO_ANN, |s| s.print_expr(expr));
143-
let suggestions = compatible_variants
144-
.map(|v| format!("{}({})", v, expr_text));
145-
err.span_suggestions(
146-
expr.span,
147-
"try using a variant of the expected type",
148-
suggestions,
149-
Applicability::MaybeIncorrect,
150-
);
151-
}
152-
}
122+
if self.is_assign_to_bool(expr, expected) {
123+
// Error reported in `check_assign` so avoid emitting error again.
124+
err.delay_as_bug();
125+
return (expected, None)
153126
}
154127

128+
self.suggest_compatible_variants(&mut err, expr, expected, expr_ty);
155129
self.suggest_ref_or_into(&mut err, expr, expected, expr_ty);
156130

157131
(expected, Some(err))
158132
}
159133

134+
/// Returns whether the expected type is `bool` and the expression is `x = y`.
135+
pub fn is_assign_to_bool(&self, expr: &hir::Expr, expected: Ty<'tcx>) -> bool {
136+
if let hir::ExprKind::Assign(..) = expr.node {
137+
return expected == self.tcx.types.bool;
138+
}
139+
false
140+
}
141+
142+
/// If the expected type is an enum (Issue #55250) with any variants whose
143+
/// sole field is of the found type, suggest such variants. (Issue #42764)
144+
fn suggest_compatible_variants(
145+
&self,
146+
err: &mut DiagnosticBuilder<'_>,
147+
expr: &hir::Expr,
148+
expected: Ty<'tcx>,
149+
expr_ty: Ty<'tcx>,
150+
) {
151+
if let ty::Adt(expected_adt, substs) = expected.sty {
152+
if !expected_adt.is_enum() {
153+
return;
154+
}
155+
156+
let mut compatible_variants = expected_adt.variants
157+
.iter()
158+
.filter(|variant| variant.fields.len() == 1)
159+
.filter_map(|variant| {
160+
let sole_field = &variant.fields[0];
161+
let sole_field_ty = sole_field.ty(self.tcx, substs);
162+
if self.can_coerce(expr_ty, sole_field_ty) {
163+
let variant_path = self.tcx.def_path_str(variant.def_id);
164+
// FIXME #56861: DRYer prelude filtering
165+
Some(variant_path.trim_start_matches("std::prelude::v1::").to_string())
166+
} else {
167+
None
168+
}
169+
}).peekable();
170+
171+
if compatible_variants.peek().is_some() {
172+
let expr_text = print::to_string(print::NO_ANN, |s| s.print_expr(expr));
173+
let suggestions = compatible_variants
174+
.map(|v| format!("{}({})", v, expr_text));
175+
let msg = "try using a variant of the expected type";
176+
err.span_suggestions(expr.span, msg, suggestions, Applicability::MaybeIncorrect);
177+
}
178+
}
179+
}
180+
160181
pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>)
161182
-> Vec<AssociatedItem> {
162183
let mut methods = self.probe_for_return_type(span,

src/librustc_typeck/check/mod.rs

Lines changed: 53 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -246,9 +246,6 @@ pub enum Expectation<'tcx> {
246246
/// We know nothing about what type this expression should have.
247247
NoExpectation,
248248

249-
/// This expression is an `if` condition, it must resolve to `bool`.
250-
ExpectIfCondition,
251-
252249
/// This expression should have the type given (or some subtype).
253250
ExpectHasType(Ty<'tcx>),
254251

@@ -328,7 +325,6 @@ impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
328325
fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
329326
match self {
330327
NoExpectation => NoExpectation,
331-
ExpectIfCondition => ExpectIfCondition,
332328
ExpectCastableToType(t) => {
333329
ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
334330
}
@@ -344,7 +340,6 @@ impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
344340
fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
345341
match self.resolve(fcx) {
346342
NoExpectation => None,
347-
ExpectIfCondition => Some(fcx.tcx.types.bool),
348343
ExpectCastableToType(ty) |
349344
ExpectHasType(ty) |
350345
ExpectRvalueLikeUnsized(ty) => Some(ty),
@@ -358,7 +353,6 @@ impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
358353
fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
359354
match self.resolve(fcx) {
360355
ExpectHasType(ty) => Some(ty),
361-
ExpectIfCondition => Some(fcx.tcx.types.bool),
362356
NoExpectation | ExpectCastableToType(_) | ExpectRvalueLikeUnsized(_) => None,
363357
}
364358
}
@@ -3150,25 +3144,13 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
31503144
}
31513145

31523146
if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
3153-
// Add help to type error if this is an `if` condition with an assignment.
3154-
if let (ExpectIfCondition, &ExprKind::Assign(ref lhs, ref rhs))
3155-
= (expected, &expr.node)
3156-
{
3157-
let msg = "try comparing for equality";
3158-
if let (Ok(left), Ok(right)) = (
3159-
self.tcx.sess.source_map().span_to_snippet(lhs.span),
3160-
self.tcx.sess.source_map().span_to_snippet(rhs.span))
3161-
{
3162-
err.span_suggestion(
3163-
expr.span,
3164-
msg,
3165-
format!("{} == {}", left, right),
3166-
Applicability::MaybeIncorrect);
3167-
} else {
3168-
err.help(msg);
3169-
}
3147+
if self.is_assign_to_bool(expr, expected_ty) {
3148+
// Error reported in `check_assign` so avoid emitting error again.
3149+
// FIXME(centril): Consider removing if/when `if` desugars to `match`.
3150+
err.delay_as_bug();
3151+
} else {
3152+
err.emit();
31703153
}
3171-
err.emit();
31723154
}
31733155
ty
31743156
}
@@ -3339,7 +3321,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
33393321
opt_else_expr: Option<&'gcx hir::Expr>,
33403322
sp: Span,
33413323
expected: Expectation<'tcx>) -> Ty<'tcx> {
3342-
let cond_ty = self.check_expr_meets_expectation_or_error(cond_expr, ExpectIfCondition);
3324+
let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool);
33433325
let cond_diverges = self.diverges.get();
33443326
self.diverges.set(Diverges::Maybe);
33453327

@@ -4424,34 +4406,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
44244406
tcx.types.never
44254407
}
44264408
ExprKind::Assign(ref lhs, ref rhs) => {
4427-
let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
4428-
4429-
let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
4430-
4431-
match expected {
4432-
ExpectIfCondition => {
4433-
self.tcx.sess.delay_span_bug(lhs.span, "invalid lhs expression in if;\
4434-
expected error elsehwere");
4435-
}
4436-
_ => {
4437-
// Only check this if not in an `if` condition, as the
4438-
// mistyped comparison help is more appropriate.
4439-
if !lhs.is_place_expr() {
4440-
struct_span_err!(self.tcx.sess, expr.span, E0070,
4441-
"invalid left-hand side expression")
4442-
.span_label(expr.span, "left-hand of expression not valid")
4443-
.emit();
4444-
}
4445-
}
4446-
}
4447-
4448-
self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
4449-
4450-
if lhs_ty.references_error() || rhs_ty.references_error() {
4451-
tcx.types.err
4452-
} else {
4453-
tcx.mk_unit()
4454-
}
4409+
self.check_assign(expr, expected, lhs, rhs)
44554410
}
44564411
ExprKind::If(ref cond, ref then_expr, ref opt_else_expr) => {
44574412
self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
@@ -4752,6 +4707,51 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
47524707
}
47534708
}
47544709

4710+
/// Type check assignment expression `expr` of form `lhs = rhs`.
4711+
/// The expected type is `()` and is passsed to the function for the purposes of diagnostics.
4712+
fn check_assign(
4713+
&self,
4714+
expr: &'gcx hir::Expr,
4715+
expected: Expectation<'tcx>,
4716+
lhs: &'gcx hir::Expr,
4717+
rhs: &'gcx hir::Expr,
4718+
) -> Ty<'tcx> {
4719+
let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
4720+
let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
4721+
4722+
let expected_ty = expected.coercion_target_type(self, expr.span);
4723+
if expected_ty == self.tcx.types.bool {
4724+
// The expected type is `bool` but this will result in `()` so we can reasonably
4725+
// say that the user intended to write `lhs == rhs` instead of `lhs = rhs`.
4726+
// The likely cause of this is `if foo = bar { .. }`.
4727+
let actual_ty = self.tcx.mk_unit();
4728+
let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
4729+
let msg = "try comparing for equality";
4730+
let left = self.tcx.sess.source_map().span_to_snippet(lhs.span);
4731+
let right = self.tcx.sess.source_map().span_to_snippet(rhs.span);
4732+
if let (Ok(left), Ok(right)) = (left, right) {
4733+
let help = format!("{} == {}", left, right);
4734+
err.span_suggestion(expr.span, msg, help, Applicability::MaybeIncorrect);
4735+
} else {
4736+
err.help(msg);
4737+
}
4738+
err.emit();
4739+
} else if !lhs.is_place_expr() {
4740+
struct_span_err!(self.tcx.sess, expr.span, E0070,
4741+
"invalid left-hand side expression")
4742+
.span_label(expr.span, "left-hand of expression not valid")
4743+
.emit();
4744+
}
4745+
4746+
self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
4747+
4748+
if lhs_ty.references_error() || rhs_ty.references_error() {
4749+
self.tcx.types.err
4750+
} else {
4751+
self.tcx.mk_unit()
4752+
}
4753+
}
4754+
47554755
// Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
47564756
// The newly resolved definition is written into `type_dependent_defs`.
47574757
fn finish_resolving_struct_path(&self,

0 commit comments

Comments
 (0)