Skip to content

Commit e011175

Browse files
authored
Auto merge of #36915 - jfirebaugh:E0308-split, r=nikomatsakis
Use a distinct error code for "if may be missing an else clause" Introduce the possibility of assigning distinct error codes to the various origin types of E0308. Start by assigning E0317 for the "IfExpressionWithNoElse" case, and write a long diagnostic specific to this case. Fixes #36596
2 parents ce31626 + d07602b commit e011175

File tree

3 files changed

+28
-6
lines changed

3 files changed

+28
-6
lines changed

src/librustc/diagnostics.rs

+17
Original file line numberDiff line numberDiff line change
@@ -1407,6 +1407,23 @@ fn make_child<'elve>(x: &mut &'elve isize, y: &mut &'elve isize) {
14071407
```
14081408
"##,
14091409

1410+
E0317: r##"
1411+
This error occurs when an `if` expression without an `else` block is used in a
1412+
context where a type other than `()` is expected, for example a `let`
1413+
expression:
1414+
1415+
```compile_fail,E0317
1416+
fn main() {
1417+
let x = 5;
1418+
let a = if x == 5 { 1 };
1419+
}
1420+
```
1421+
1422+
An `if` expression without an `else` block has the type `()`, so this is a type
1423+
error. To resolve it, add an `else` block having the same type as the `if`
1424+
block.
1425+
"##,
1426+
14101427
E0398: r##"
14111428
In Rust 1.3, the default object lifetime bounds are expected to change, as
14121429
described in RFC #1156 [1]. You are getting a warning because the compiler

src/librustc/infer/error_reporting.rs

+10-5
Original file line numberDiff line numberDiff line change
@@ -577,11 +577,16 @@ impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
577577
terr: &TypeError<'tcx>)
578578
-> DiagnosticBuilder<'tcx>
579579
{
580-
// FIXME: do we want to use a different error code for each origin?
581-
let mut diag = struct_span_err!(
582-
self.tcx.sess, trace.origin.span(), E0308,
583-
"{}", trace.origin.as_failure_str()
584-
);
580+
let span = trace.origin.span();
581+
let failure_str = trace.origin.as_failure_str();
582+
let mut diag = match trace.origin {
583+
TypeOrigin::IfExpressionWithNoElse(_) => {
584+
struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
585+
},
586+
_ => {
587+
struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
588+
},
589+
};
585590
self.note_type_err(&mut diag, trace.origin, None, Some(trace.values), terr);
586591
diag
587592
}

src/test/compile-fail/if-without-else-result.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
fn main() {
1212
let a = if true { true };
13-
//~^ ERROR if may be missing an else clause
13+
//~^ ERROR if may be missing an else clause [E0317]
1414
//~| expected type `()`
1515
//~| found type `bool`
1616
//~| expected (), found bool

0 commit comments

Comments
 (0)