Skip to content

Commit 1fa6ada

Browse files
committed
Detect bindings assigned blocks without tail expressions in trait errors
Address rust-lang#44173 for trait errors.
1 parent 1983a62 commit 1fa6ada

File tree

4 files changed

+172
-28
lines changed

4 files changed

+172
-28
lines changed

compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs

+36-18
Original file line numberDiff line numberDiff line change
@@ -771,7 +771,11 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
771771
),
772772
}
773773
};
774-
774+
self.check_for_binding_assigned_block_without_tail_expression(
775+
&obligation,
776+
&mut err,
777+
trait_predicate,
778+
);
775779
if self.suggest_add_reference_to_arg(
776780
&obligation,
777781
&mut err,
@@ -2267,23 +2271,7 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
22672271
if let (Some(body_id), Some(ty::subst::GenericArgKind::Type(_))) =
22682272
(body_id, subst.map(|subst| subst.unpack()))
22692273
{
2270-
struct FindExprBySpan<'hir> {
2271-
span: Span,
2272-
result: Option<&'hir hir::Expr<'hir>>,
2273-
}
2274-
2275-
impl<'v> hir::intravisit::Visitor<'v> for FindExprBySpan<'v> {
2276-
fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2277-
if self.span == ex.span {
2278-
self.result = Some(ex);
2279-
} else {
2280-
hir::intravisit::walk_expr(self, ex);
2281-
}
2282-
}
2283-
}
2284-
2285-
let mut expr_finder = FindExprBySpan { span, result: None };
2286-
2274+
let mut expr_finder = FindExprBySpan::new(span);
22872275
expr_finder.visit_expr(&self.tcx.hir().body(body_id).value);
22882276

22892277
if let Some(hir::Expr {
@@ -2770,6 +2758,36 @@ impl<'tcx> InferCtxtPrivExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
27702758
}
27712759
}
27722760

2761+
/// Crude way of getting back an `Expr` from a `Span`.
2762+
pub struct FindExprBySpan<'hir> {
2763+
pub span: Span,
2764+
pub result: Option<&'hir hir::Expr<'hir>>,
2765+
pub ty_result: Option<&'hir hir::Ty<'hir>>,
2766+
}
2767+
2768+
impl<'hir> FindExprBySpan<'hir> {
2769+
fn new(span: Span) -> Self {
2770+
Self { span, result: None, ty_result: None }
2771+
}
2772+
}
2773+
2774+
impl<'v> Visitor<'v> for FindExprBySpan<'v> {
2775+
fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
2776+
if self.span == ex.span {
2777+
self.result = Some(ex);
2778+
} else {
2779+
hir::intravisit::walk_expr(self, ex);
2780+
}
2781+
}
2782+
fn visit_ty(&mut self, ty: &'v hir::Ty<'v>) {
2783+
if self.span == ty.span {
2784+
self.ty_result = Some(ty);
2785+
} else {
2786+
hir::intravisit::walk_ty(self, ty);
2787+
}
2788+
}
2789+
}
2790+
27732791
/// Look for type `param` in an ADT being used only through a reference to confirm that suggesting
27742792
/// `param: ?Sized` would be a valid constraint.
27752793
struct FindTypeParam {

compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs

+71-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// ignore-tidy-filelength
22

3-
use super::{DefIdOrName, Obligation, ObligationCause, ObligationCauseCode, PredicateObligation};
3+
use super::{
4+
DefIdOrName, FindExprBySpan, Obligation, ObligationCause, ObligationCauseCode,
5+
PredicateObligation,
6+
};
47

58
use crate::autoderef::Autoderef;
69
use crate::infer::InferCtxt;
@@ -196,6 +199,13 @@ pub trait TypeErrCtxtExt<'tcx> {
196199
trait_pred: ty::PolyTraitPredicate<'tcx>,
197200
) -> bool;
198201

202+
fn check_for_binding_assigned_block_without_tail_expression(
203+
&self,
204+
obligation: &PredicateObligation<'tcx>,
205+
err: &mut Diagnostic,
206+
trait_pred: ty::PolyTraitPredicate<'tcx>,
207+
);
208+
199209
fn suggest_add_reference_to_arg(
200210
&self,
201211
obligation: &PredicateObligation<'tcx>,
@@ -1032,6 +1042,66 @@ impl<'tcx> TypeErrCtxtExt<'tcx> for TypeErrCtxt<'_, 'tcx> {
10321042
true
10331043
}
10341044

1045+
fn check_for_binding_assigned_block_without_tail_expression(
1046+
&self,
1047+
obligation: &PredicateObligation<'tcx>,
1048+
err: &mut Diagnostic,
1049+
trait_pred: ty::PolyTraitPredicate<'tcx>,
1050+
) {
1051+
let mut span = obligation.cause.span;
1052+
while span.from_expansion() {
1053+
// Remove all the desugaring and macro contexts.
1054+
span.remove_mark();
1055+
}
1056+
let mut expr_finder = FindExprBySpan::new(span);
1057+
let Some(hir::Node::Expr(body)) = self.tcx.hir().find(obligation.cause.body_id) else { return; };
1058+
expr_finder.visit_expr(&body);
1059+
let Some(expr) = expr_finder.result else { return; };
1060+
let Some(typeck) = &self.typeck_results else { return; };
1061+
let Some(ty) = typeck.expr_ty_adjusted_opt(expr) else { return; };
1062+
if !ty.is_unit() {
1063+
return;
1064+
};
1065+
let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind else { return; };
1066+
let hir::def::Res::Local(hir_id) = path.res else { return; };
1067+
let Some(hir::Node::Pat(pat)) = self.tcx.hir().find(hir_id) else {
1068+
return;
1069+
};
1070+
let Some(hir::Node::Local(hir::Local {
1071+
ty: None,
1072+
init: Some(init),
1073+
..
1074+
})) = self.tcx.hir().find_parent(pat.hir_id) else { return; };
1075+
let hir::ExprKind::Block(block, None) = init.kind else { return; };
1076+
if block.expr.is_some() {
1077+
return;
1078+
}
1079+
let [.., stmt] = block.stmts else {
1080+
err.span_help(block.span, "this empty block is missing a tail expression");
1081+
return;
1082+
};
1083+
let hir::StmtKind::Semi(tail_expr) = stmt.kind else { return; };
1084+
let Some(ty) = typeck.expr_ty_opt(tail_expr) else {
1085+
err.span_help(block.span, "this block is missing a tail expression");
1086+
return;
1087+
};
1088+
let ty = self.resolve_numeric_literals_with_default(self.resolve_vars_if_possible(ty));
1089+
let trait_pred_and_self = trait_pred.map_bound(|trait_pred| (trait_pred, ty));
1090+
1091+
let new_obligation =
1092+
self.mk_trait_obligation_with_new_self_ty(obligation.param_env, trait_pred_and_self);
1093+
if self.predicate_must_hold_modulo_regions(&new_obligation) {
1094+
err.span_suggestion_verbose(
1095+
stmt.span.with_lo(tail_expr.span.hi()),
1096+
"remove this semicolon",
1097+
"",
1098+
Applicability::MachineApplicable,
1099+
);
1100+
} else {
1101+
err.span_help(block.span, "this block is missing a tail expression");
1102+
}
1103+
}
1104+
10351105
fn suggest_add_reference_to_arg(
10361106
&self,
10371107
obligation: &PredicateObligation<'tcx>,

src/test/ui/type/binding-assigned-block-without-tail-expression.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
struct S;
12
fn main() {
23
let x = {
34
println!("foo");
@@ -7,10 +8,15 @@ fn main() {
78
let z = {
89
"hi";
910
};
11+
let s = {
12+
S;
13+
};
1014
println!("{}", x); //~ ERROR E0277
1115
println!("{}", y); //~ ERROR E0277
1216
println!("{}", z); //~ ERROR E0277
17+
println!("{}", s); //~ ERROR E0277
1318
let _: i32 = x; //~ ERROR E0308
1419
let _: i32 = y; //~ ERROR E0308
1520
let _: i32 = z; //~ ERROR E0308
21+
let _: i32 = s; //~ ERROR E0308
1622
}
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,68 @@
11
error[E0277]: `()` doesn't implement `std::fmt::Display`
2-
--> $DIR/binding-assigned-block-without-tail-expression.rs:10:20
2+
--> $DIR/binding-assigned-block-without-tail-expression.rs:14:20
33
|
44
LL | println!("{}", x);
55
| ^ `()` cannot be formatted with the default formatter
66
|
77
= help: the trait `std::fmt::Display` is not implemented for `()`
88
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
99
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
10+
help: remove this semicolon
11+
|
12+
LL - 42;
13+
LL + 42
14+
|
1015

1116
error[E0277]: `()` doesn't implement `std::fmt::Display`
12-
--> $DIR/binding-assigned-block-without-tail-expression.rs:11:20
17+
--> $DIR/binding-assigned-block-without-tail-expression.rs:15:20
1318
|
1419
LL | println!("{}", y);
1520
| ^ `()` cannot be formatted with the default formatter
1621
|
22+
help: this empty block is missing a tail expression
23+
--> $DIR/binding-assigned-block-without-tail-expression.rs:7:13
24+
|
25+
LL | let y = {};
26+
| ^^
1727
= help: the trait `std::fmt::Display` is not implemented for `()`
1828
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
1929
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
2030

2131
error[E0277]: `()` doesn't implement `std::fmt::Display`
22-
--> $DIR/binding-assigned-block-without-tail-expression.rs:12:20
32+
--> $DIR/binding-assigned-block-without-tail-expression.rs:16:20
2333
|
2434
LL | println!("{}", z);
2535
| ^ `()` cannot be formatted with the default formatter
2636
|
2737
= help: the trait `std::fmt::Display` is not implemented for `()`
2838
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
2939
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
40+
help: remove this semicolon
41+
|
42+
LL - "hi";
43+
LL + "hi"
44+
|
45+
46+
error[E0277]: `()` doesn't implement `std::fmt::Display`
47+
--> $DIR/binding-assigned-block-without-tail-expression.rs:17:20
48+
|
49+
LL | println!("{}", s);
50+
| ^ `()` cannot be formatted with the default formatter
51+
|
52+
help: this block is missing a tail expression
53+
--> $DIR/binding-assigned-block-without-tail-expression.rs:11:13
54+
|
55+
LL | let s = {
56+
| _____________^
57+
LL | | S;
58+
LL | | };
59+
| |_____^
60+
= help: the trait `std::fmt::Display` is not implemented for `()`
61+
= note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
62+
= note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
3063

3164
error[E0308]: mismatched types
32-
--> $DIR/binding-assigned-block-without-tail-expression.rs:13:18
65+
--> $DIR/binding-assigned-block-without-tail-expression.rs:18:18
3366
|
3467
LL | let _: i32 = x;
3568
| --- ^ expected `i32`, found `()`
@@ -43,37 +76,54 @@ LL + 42
4376
|
4477

4578
error[E0308]: mismatched types
46-
--> $DIR/binding-assigned-block-without-tail-expression.rs:14:18
79+
--> $DIR/binding-assigned-block-without-tail-expression.rs:19:18
4780
|
4881
LL | let _: i32 = y;
4982
| --- ^ expected `i32`, found `()`
5083
| |
5184
| expected due to this
5285
|
5386
help: this empty block is missing a tail expression
54-
--> $DIR/binding-assigned-block-without-tail-expression.rs:6:13
87+
--> $DIR/binding-assigned-block-without-tail-expression.rs:7:13
5588
|
5689
LL | let y = {};
5790
| ^^
5891

5992
error[E0308]: mismatched types
60-
--> $DIR/binding-assigned-block-without-tail-expression.rs:15:18
93+
--> $DIR/binding-assigned-block-without-tail-expression.rs:20:18
6194
|
6295
LL | let _: i32 = z;
6396
| --- ^ expected `i32`, found `()`
6497
| |
6598
| expected due to this
6699
|
67100
help: this block is missing a tail expression
68-
--> $DIR/binding-assigned-block-without-tail-expression.rs:7:13
101+
--> $DIR/binding-assigned-block-without-tail-expression.rs:8:13
69102
|
70103
LL | let z = {
71104
| _____________^
72105
LL | | "hi";
73106
LL | | };
74107
| |_____^
75108

76-
error: aborting due to 6 previous errors
109+
error[E0308]: mismatched types
110+
--> $DIR/binding-assigned-block-without-tail-expression.rs:21:18
111+
|
112+
LL | let _: i32 = s;
113+
| --- ^ expected `i32`, found `()`
114+
| |
115+
| expected due to this
116+
|
117+
help: this block is missing a tail expression
118+
--> $DIR/binding-assigned-block-without-tail-expression.rs:11:13
119+
|
120+
LL | let s = {
121+
| _____________^
122+
LL | | S;
123+
LL | | };
124+
| |_____^
125+
126+
error: aborting due to 8 previous errors
77127

78128
Some errors have detailed explanations: E0277, E0308.
79129
For more information about an error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)