Skip to content

Commit cfce3a9

Browse files
Rollup merge of #116296 - compiler-errors:default-return, r=estebank
More accurately point to where default return type should go When getting the "default return type" span, instead of pointing to the low span of the next token, point to the high span of the previous token. This: 1. Makes forming return type suggestions more uniform, since we expect them all in the same place. 2. Arguably makes labels easier to understand, since we're pointing to where the implicit `-> ()` would've gone, rather than the starting brace or the semicolon. r? ```@estebank```
2 parents ea3454e + dd5f26c commit cfce3a9

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

42 files changed

+105
-89
lines changed

compiler/rustc_hir_analysis/src/check/compare_impl_item.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1189,7 +1189,7 @@ fn report_trait_method_mismatch<'tcx>(
11891189
let ap = Applicability::MachineApplicable;
11901190
match sig.decl.output {
11911191
hir::FnRetTy::DefaultReturn(sp) => {
1192-
let sugg = format!("-> {} ", trait_sig.output());
1192+
let sugg = format!(" -> {}", trait_sig.output());
11931193
diag.span_suggestion_verbose(sp, msg, sugg, ap);
11941194
}
11951195
hir::FnRetTy::Return(hir_ty) => {

compiler/rustc_hir_typeck/src/check.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,11 @@ pub(super) fn check_fn<'a, 'tcx>(
113113

114114
fcx.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
115115

116-
fcx.require_type_is_sized(declared_ret_ty, decl.output.span(), traits::SizedReturnType);
116+
let return_or_body_span = match decl.output {
117+
hir::FnRetTy::DefaultReturn(_) => body.value.span,
118+
hir::FnRetTy::Return(ty) => ty.span,
119+
};
120+
fcx.require_type_is_sized(declared_ret_ty, return_or_body_span, traits::SizedReturnType);
117121
fcx.check_return_expr(&body.value, false);
118122

119123
// We insert the deferred_generator_interiors entry after visiting the body.

compiler/rustc_hir_typeck/src/errors.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ pub struct AddressOfTemporaryTaken {
110110
pub enum AddReturnTypeSuggestion {
111111
#[suggestion(
112112
hir_typeck_add_return_type_add,
113-
code = "-> {found} ",
113+
code = " -> {found}",
114114
applicability = "machine-applicable"
115115
)]
116116
Add {
@@ -120,7 +120,7 @@ pub enum AddReturnTypeSuggestion {
120120
},
121121
#[suggestion(
122122
hir_typeck_add_return_type_missing_here,
123-
code = "-> _ ",
123+
code = " -> _",
124124
applicability = "has-placeholders"
125125
)]
126126
MissingHere {

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+18-20
Original file line numberDiff line numberDiff line change
@@ -782,8 +782,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
782782
}
783783
}
784784
hir::FnRetTy::Return(hir_ty) => {
785-
let span = hir_ty.span;
786-
787785
if let hir::TyKind::OpaqueDef(item_id, ..) = hir_ty.kind
788786
&& let hir::Node::Item(hir::Item {
789787
kind: hir::ItemKind::OpaqueTy(op_ty),
@@ -799,28 +797,28 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
799797
debug!(?found);
800798
if found.is_suggestable(self.tcx, false) {
801799
if term.span.is_empty() {
802-
err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span, found: found.to_string() });
800+
err.subdiagnostic(errors::AddReturnTypeSuggestion::Add { span: term.span, found: found.to_string() });
803801
return true;
804802
} else {
805-
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other { span, expected });
803+
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other { span: term.span, expected });
806804
}
807805
}
808-
}
809-
810-
// Only point to return type if the expected type is the return type, as if they
811-
// are not, the expectation must have been caused by something else.
812-
debug!("return type {:?}", hir_ty);
813-
let ty = self.astconv().ast_ty_to_ty(hir_ty);
814-
debug!("return type {:?}", ty);
815-
debug!("expected type {:?}", expected);
816-
let bound_vars = self.tcx.late_bound_vars(hir_ty.hir_id.owner.into());
817-
let ty = Binder::bind_with_vars(ty, bound_vars);
818-
let ty = self.normalize(span, ty);
819-
let ty = self.tcx.erase_late_bound_regions(ty);
820-
if self.can_coerce(expected, ty) {
821-
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other { span, expected });
822-
self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
823-
return true;
806+
} else {
807+
// Only point to return type if the expected type is the return type, as if they
808+
// are not, the expectation must have been caused by something else.
809+
debug!("return type {:?}", hir_ty);
810+
let ty = self.astconv().ast_ty_to_ty(hir_ty);
811+
debug!("return type {:?}", ty);
812+
debug!("expected type {:?}", expected);
813+
let bound_vars = self.tcx.late_bound_vars(hir_ty.hir_id.owner.into());
814+
let ty = Binder::bind_with_vars(ty, bound_vars);
815+
let ty = self.normalize(hir_ty.span, ty);
816+
let ty = self.tcx.erase_late_bound_regions(ty);
817+
if self.can_coerce(expected, ty) {
818+
err.subdiagnostic(errors::ExpectedReturnTypeLabel::Other { span: hir_ty.span, expected });
819+
self.try_suggest_return_impl_trait(err, expected, ty, fn_id);
820+
return true;
821+
}
824822
}
825823
}
826824
_ => {}

compiler/rustc_infer/src/errors/mod.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -194,13 +194,13 @@ impl<'a> SourceKindMultiSuggestion<'a> {
194194
data: &'a FnRetTy<'a>,
195195
should_wrap_expr: Option<Span>,
196196
) -> Self {
197-
let (arrow, post) = match data {
198-
FnRetTy::DefaultReturn(_) => ("-> ", " "),
199-
_ => ("", ""),
197+
let arrow = match data {
198+
FnRetTy::DefaultReturn(_) => " -> ",
199+
_ => "",
200200
};
201201
let (start_span, start_span_code, end_span) = match should_wrap_expr {
202-
Some(end_span) => (data.span(), format!("{arrow}{ty_info}{post}{{ "), Some(end_span)),
203-
None => (data.span(), format!("{arrow}{ty_info}{post}"), None),
202+
Some(end_span) => (data.span(), format!("{arrow}{ty_info} {{"), Some(end_span)),
203+
None => (data.span(), format!("{arrow}{ty_info}"), None),
204204
};
205205
Self::ClosureReturn { start_span, start_span_code, end_span }
206206
}

compiler/rustc_parse/src/parser/ty.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ impl<'a> Parser<'a> {
247247
)?;
248248
FnRetTy::Ty(ty)
249249
} else {
250-
FnRetTy::Default(self.token.span.shrink_to_lo())
250+
FnRetTy::Default(self.prev_token.span.shrink_to_hi())
251251
})
252252
}
253253

src/tools/clippy/clippy_lints/src/methods/unnecessary_literal_unwrap.rs

+2-6
Original file line numberDiff line numberDiff line change
@@ -102,14 +102,10 @@ pub(super) fn check(
102102
]),
103103
("None", "unwrap_or_else", _) => match args[0].kind {
104104
hir::ExprKind::Closure(hir::Closure {
105-
fn_decl:
106-
hir::FnDecl {
107-
output: hir::FnRetTy::DefaultReturn(span) | hir::FnRetTy::Return(hir::Ty { span, .. }),
108-
..
109-
},
105+
body,
110106
..
111107
}) => Some(vec![
112-
(expr.span.with_hi(span.hi()), String::new()),
108+
(expr.span.with_hi(cx.tcx.hir().body(*body).value.span.lo()), String::new()),
113109
(expr.span.with_lo(args[0].span.hi()), String::new()),
114110
]),
115111
_ => None,

src/tools/clippy/tests/ui-toml/too_many_arguments/too_many_arguments.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error: this function has too many arguments (11/10)
22
--> $DIR/too_many_arguments.rs:4:1
33
|
44
LL | fn too_many(p1: u8, p2: u8, p3: u8, p4: u8, p5: u8, p6: u8, p7: u8, p8: u8, p9: u8, p10: u8, p11: u8) {}
5-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
66
|
77
= note: `-D clippy::too-many-arguments` implied by `-D warnings`
88
= help: to override `-D warnings` add `#[allow(clippy::too_many_arguments)]`

src/tools/clippy/tests/ui/functions.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error: this function has too many arguments (8/7)
22
--> $DIR/functions.rs:8:1
33
|
44
LL | fn bad(_one: u32, _two: u32, _three: &str, _four: bool, _five: f32, _six: f32, _seven: bool, _eight: ()) {}
5-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
66
|
77
= note: `-D clippy::too-many-arguments` implied by `-D warnings`
88
= help: to override `-D warnings` add `#[allow(clippy::too_many_arguments)]`
@@ -17,7 +17,7 @@ LL | | two: u32,
1717
... |
1818
LL | | eight: ()
1919
LL | | ) {
20-
| |__^
20+
| |_^
2121

2222
error: this function has too many arguments (8/7)
2323
--> $DIR/functions.rs:48:5
@@ -29,7 +29,7 @@ error: this function has too many arguments (8/7)
2929
--> $DIR/functions.rs:58:5
3030
|
3131
LL | fn bad_method(_one: u32, _two: u32, _three: &str, _four: bool, _five: f32, _six: f32, _seven: bool, _eight: ()) {}
32-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
32+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3333

3434
error: this public function might dereference a raw pointer but is not marked `unsafe`
3535
--> $DIR/functions.rs:68:34

src/tools/clippy/tests/ui/must_use_unit.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ error: this unit-returning function has a `#[must_use]` attribute
44
LL | #[must_use]
55
| ----------- help: remove the attribute
66
LL | pub fn must_use_default() {}
7-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
7+
| ^^^^^^^^^^^^^^^^^^^^^^^^^
88
|
99
= note: `-D clippy::must-use-unit` implied by `-D warnings`
1010
= help: to override `-D warnings` add `#[allow(clippy::must_use_unit)]`
@@ -23,7 +23,7 @@ error: this unit-returning function has a `#[must_use]` attribute
2323
LL | #[must_use = "With note"]
2424
| ------------------------- help: remove the attribute
2525
LL | pub fn must_use_with_note() {}
26-
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
26+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^
2727

2828
error: aborting due to 3 previous errors
2929

src/tools/clippy/tests/ui/unnecessary_literal_unwrap.fixed

+2-2
Original file line numberDiff line numberDiff line change
@@ -23,15 +23,15 @@ fn unwrap_option_none() {
2323
let _val: u16 = 234;
2424
let _val: u16 = 234;
2525
let _val: u16 = { 234 };
26-
let _val: u16 = { 234 };
26+
let _val: u16 = { 234 };
2727

2828
panic!();
2929
panic!("this always happens");
3030
String::default();
3131
234;
3232
234;
3333
{ 234 };
34-
{ 234 };
34+
{ 234 };
3535
}
3636

3737
fn unwrap_result_ok() {

src/tools/clippy/tests/ui/unnecessary_literal_unwrap.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ LL | let _val: u16 = None.unwrap_or_else(|| -> u16 { 234 });
116116
help: remove the `None` and `unwrap_or_else()`
117117
|
118118
LL - let _val: u16 = None.unwrap_or_else(|| -> u16 { 234 });
119-
LL + let _val: u16 = { 234 };
119+
LL + let _val: u16 = { 234 };
120120
|
121121

122122
error: used `unwrap()` on `None` value
@@ -187,7 +187,7 @@ LL | None::<u16>.unwrap_or_else(|| -> u16 { 234 });
187187
help: remove the `None` and `unwrap_or_else()`
188188
|
189189
LL - None::<u16>.unwrap_or_else(|| -> u16 { 234 });
190-
LL + { 234 };
190+
LL + { 234 };
191191
|
192192

193193
error: used `unwrap()` on `Ok` value

src/tools/rustfmt/src/items.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -2599,7 +2599,8 @@ fn rewrite_fn_base(
25992599
if where_clause_str.is_empty() {
26002600
if let ast::FnRetTy::Default(ret_span) = fd.output {
26012601
match recover_missing_comment_in_span(
2602-
mk_sp(params_span.hi(), ret_span.hi()),
2602+
// from after the closing paren to right before block or semicolon
2603+
mk_sp(ret_span.lo(), span.hi()),
26032604
shape,
26042605
context,
26052606
last_line_width(&result),

tests/ui/associated-type-bounds/issue-71443-1.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error[E0308]: mismatched types
22
--> $DIR/issue-71443-1.rs:6:5
33
|
44
LL | fn hello<F: for<'a> Iterator<Item: 'a>>() {
5-
| - help: try adding a return type: `-> Incorrect`
5+
| - help: try adding a return type: `-> Incorrect`
66
LL | Incorrect
77
| ^^^^^^^^^ expected `()`, found `Incorrect`
88

tests/ui/block-result/block-must-not-have-result-res.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error[E0308]: mismatched types
22
--> $DIR/block-must-not-have-result-res.rs:5:9
33
|
44
LL | fn drop(&mut self) {
5-
| - expected `()` because of default return type
5+
| - expected `()` because of default return type
66
LL | true
77
| ^^^^ expected `()`, found `bool`
88

tests/ui/block-result/issue-20862.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error[E0308]: mismatched types
22
--> $DIR/issue-20862.rs:2:5
33
|
44
LL | fn foo(x: i32) {
5-
| - help: a return type might be missing here: `-> _`
5+
| - help: a return type might be missing here: `-> _`
66
LL | |y| x + y
77
| ^^^^^^^^^ expected `()`, found closure
88
|

tests/ui/block-result/issue-22645.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ error[E0308]: mismatched types
1717
--> $DIR/issue-22645.rs:15:3
1818
|
1919
LL | fn main() {
20-
| - expected `()` because of default return type
20+
| - expected `()` because of default return type
2121
LL | let b = Bob + 3.5;
2222
LL | b + 3
2323
| ^^^^^ expected `()`, found `Bob`

tests/ui/block-result/issue-5500.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error[E0308]: mismatched types
22
--> $DIR/issue-5500.rs:2:5
33
|
44
LL | fn main() {
5-
| - expected `()` because of default return type
5+
| - expected `()` because of default return type
66
LL | &panic!()
77
| ^^^^^^^^^ expected `()`, found `&_`
88
|

tests/ui/closures/add_semicolon_non_block_closure.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ error[E0308]: mismatched types
22
--> $DIR/add_semicolon_non_block_closure.rs:8:12
33
|
44
LL | fn main() {
5-
| - expected `()` because of default return type
5+
| - expected `()` because of default return type
66
LL | foo(|| bar())
77
| ^^^^^ expected `()`, found `i32`
88
|

tests/ui/closures/binder/implicit-return.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
error: implicit types in closure signatures are forbidden when `for<...>` is present
2-
--> $DIR/implicit-return.rs:4:34
2+
--> $DIR/implicit-return.rs:4:33
33
|
44
LL | let _f = for<'a> |_: &'a ()| {};
5-
| ------- ^
5+
| ------- ^
66
| |
77
| `for<...>` is here
88

tests/ui/closures/binder/implicit-stuff.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,10 @@ LL | let _ = for<'a> |x: &'a ()| -> &() { x };
4141
| ^ explicit lifetime name needed here
4242

4343
error: implicit types in closure signatures are forbidden when `for<...>` is present
44-
--> $DIR/implicit-stuff.rs:5:22
44+
--> $DIR/implicit-stuff.rs:5:21
4545
|
4646
LL | let _ = for<> || {};
47-
| ----- ^
47+
| ----- ^
4848
| |
4949
| `for<...>` is here
5050

tests/ui/codemap_tests/tab.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ error[E0308]: mismatched types
88
--> $DIR/tab.rs:8:2
99
|
1010
LL | fn foo() {
11-
| - help: try adding a return type: `-> &'static str`
11+
| - help: try adding a return type: `-> &'static str`
1212
LL | "bar boo"
1313
| ^^^^^^^^^^^^^^^^^^^^ expected `()`, found `&str`
1414

tests/ui/compare-method/bad-self-type.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ LL | fn foo(self);
2828
found signature `fn(Box<MyFuture>)`
2929

3030
error[E0053]: method `bar` has an incompatible type for trait
31-
--> $DIR/bad-self-type.rs:24:18
31+
--> $DIR/bad-self-type.rs:24:17
3232
|
3333
LL | fn bar(self) {}
34-
| ^ expected `Option<()>`, found `()`
34+
| ^ expected `Option<()>`, found `()`
3535
|
3636
note: type in trait
3737
--> $DIR/bad-self-type.rs:18:21

tests/ui/impl-trait/in-trait/refine.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,8 +30,8 @@ LL | fn bar() {}
3030
= note: add `#[allow(refining_impl_trait)]` if it is intended for this to be part of the public API of this crate
3131
help: replace the return type so that it matches the trait
3232
|
33-
LL | fn bar() -> impl Sized {}
34-
| +++++++++++++
33+
LL | fn bar()-> impl Sized {}
34+
| +++++++++++++
3535

3636
error: impl trait in impl method signature does not match trait method signature
3737
--> $DIR/refine.rs:22:17

tests/ui/issues/issue-66667-function-cmp-cycle.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ error[E0308]: mismatched types
1919
--> $DIR/issue-66667-function-cmp-cycle.rs:2:5
2020
|
2121
LL | fn first() {
22-
| - help: try adding a return type: `-> bool`
22+
| - help: try adding a return type: `-> bool`
2323
LL | second == 1
2424
| ^^^^^^^^^^^ expected `()`, found `bool`
2525

@@ -44,7 +44,7 @@ error[E0308]: mismatched types
4444
--> $DIR/issue-66667-function-cmp-cycle.rs:8:5
4545
|
4646
LL | fn second() {
47-
| - help: try adding a return type: `-> bool`
47+
| - help: try adding a return type: `-> bool`
4848
LL | first == 1
4949
| ^^^^^^^^^^ expected `()`, found `bool`
5050

@@ -69,7 +69,7 @@ error[E0308]: mismatched types
6969
--> $DIR/issue-66667-function-cmp-cycle.rs:14:5
7070
|
7171
LL | fn bar() {
72-
| - help: try adding a return type: `-> bool`
72+
| - help: try adding a return type: `-> bool`
7373
LL | bar == 1
7474
| ^^^^^^^^ expected `()`, found `bool`
7575

tests/ui/lang-items/start_lang_item_args.missing_ret.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
error[E0308]: lang item `start` function has wrong type
2-
--> $DIR/start_lang_item_args.rs:29:84
2+
--> $DIR/start_lang_item_args.rs:29:83
33
|
44
LL | fn start<T>(_main: fn() -> T, _argc: isize, _argv: *const *const u8, _sigpipe: u8) {}
5-
| ^ expected `isize`, found `()`
5+
| ^ expected `isize`, found `()`
66
|
77
= note: expected signature `fn(fn() -> _, _, _, _) -> isize`
88
found signature `fn(fn() -> _, _, _, _)`

tests/ui/loops/loop-break-value.stderr

+1-1
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ error[E0308]: mismatched types
319319
--> $DIR/loop-break-value.rs:159:15
320320
|
321321
LL | fn main() {
322-
| - expected `()` because of this return type
322+
| - expected `()` because of this return type
323323
...
324324
LL | loop { // point at the return type
325325
| ---- this loop is expected to be of type `()`

0 commit comments

Comments
 (0)