Skip to content

Commit 43dd386

Browse files
authored
Unrolled build for rust-lang#123924
Rollup merge of rust-lang#123924 - compiler-errors:tuple-sugg, r=estebank Fix various bugs in `ty_kind_suggestion` Consolidates two implementations of `ty_kind_suggestion` Fixes some misuse of the empty param-env Fixes a problem where we suggested `(42)` instead of `(42,)` for tuple suggestions Suggest a value when `return;`, making it consistent with `break;` Fixes rust-lang#123906
2 parents 99d0186 + 325b24d commit 43dd386

File tree

12 files changed

+139
-130
lines changed

12 files changed

+139
-130
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+2-63
Original file line numberDiff line numberDiff line change
@@ -671,68 +671,6 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
671671
err
672672
}
673673

674-
fn ty_kind_suggestion(&self, ty: Ty<'tcx>) -> Option<String> {
675-
// Keep in sync with `rustc_hir_analysis/src/check/mod.rs:ty_kind_suggestion`.
676-
// FIXME: deduplicate the above.
677-
let tcx = self.infcx.tcx;
678-
let implements_default = |ty| {
679-
let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
680-
return false;
681-
};
682-
self.infcx
683-
.type_implements_trait(default_trait, [ty], self.param_env)
684-
.must_apply_modulo_regions()
685-
};
686-
687-
Some(match ty.kind() {
688-
ty::Never | ty::Error(_) => return None,
689-
ty::Bool => "false".to_string(),
690-
ty::Char => "\'x\'".to_string(),
691-
ty::Int(_) | ty::Uint(_) => "42".into(),
692-
ty::Float(_) => "3.14159".into(),
693-
ty::Slice(_) => "[]".to_string(),
694-
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
695-
"vec![]".to_string()
696-
}
697-
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
698-
"String::new()".to_string()
699-
}
700-
ty::Adt(def, args) if def.is_box() => {
701-
format!("Box::new({})", self.ty_kind_suggestion(args[0].expect_ty())?)
702-
}
703-
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
704-
"None".to_string()
705-
}
706-
ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
707-
format!("Ok({})", self.ty_kind_suggestion(args[0].expect_ty())?)
708-
}
709-
ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
710-
ty::Ref(_, ty, mutability) => {
711-
if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
712-
"\"\"".to_string()
713-
} else {
714-
let Some(ty) = self.ty_kind_suggestion(*ty) else {
715-
return None;
716-
};
717-
format!("&{}{ty}", mutability.prefix_str())
718-
}
719-
}
720-
ty::Array(ty, len) => format!(
721-
"[{}; {}]",
722-
self.ty_kind_suggestion(*ty)?,
723-
len.eval_target_usize(tcx, ty::ParamEnv::reveal_all()),
724-
),
725-
ty::Tuple(tys) => format!(
726-
"({})",
727-
tys.iter()
728-
.map(|ty| self.ty_kind_suggestion(ty))
729-
.collect::<Option<Vec<String>>>()?
730-
.join(", ")
731-
),
732-
_ => "value".to_string(),
733-
})
734-
}
735-
736674
fn suggest_assign_value(
737675
&self,
738676
err: &mut Diag<'_>,
@@ -742,7 +680,8 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
742680
let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
743681
debug!("ty: {:?}, kind: {:?}", ty, ty.kind());
744682

745-
let Some(assign_value) = self.ty_kind_suggestion(ty) else {
683+
let Some(assign_value) = self.infcx.err_ctxt().ty_kind_suggestion(self.param_env, ty)
684+
else {
746685
return;
747686
};
748687

compiler/rustc_hir_analysis/src/check/mod.rs

+9-65
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ use rustc_errors::ErrorGuaranteed;
8181
use rustc_errors::{pluralize, struct_span_code_err, Diag};
8282
use rustc_hir::def_id::{DefId, LocalDefId};
8383
use rustc_hir::intravisit::Visitor;
84-
use rustc_hir::Mutability;
8584
use rustc_index::bit_set::BitSet;
8685
use rustc_infer::infer::error_reporting::ObligationCauseExt as _;
8786
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
@@ -96,8 +95,9 @@ use rustc_span::symbol::{kw, sym, Ident};
9695
use rustc_span::{def_id::CRATE_DEF_ID, BytePos, Span, Symbol, DUMMY_SP};
9796
use rustc_target::abi::VariantIdx;
9897
use rustc_target::spec::abi::Abi;
99-
use rustc_trait_selection::infer::InferCtxtExt;
100-
use rustc_trait_selection::traits::error_reporting::suggestions::ReturnsVisitor;
98+
use rustc_trait_selection::traits::error_reporting::suggestions::{
99+
ReturnsVisitor, TypeErrCtxtExt as _,
100+
};
101101
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
102102
use rustc_trait_selection::traits::ObligationCtxt;
103103

@@ -467,67 +467,6 @@ fn fn_sig_suggestion<'tcx>(
467467
)
468468
}
469469

470-
pub fn ty_kind_suggestion<'tcx>(ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<String> {
471-
// Keep in sync with `rustc_borrowck/src/diagnostics/conflict_errors.rs:ty_kind_suggestion`.
472-
// FIXME: deduplicate the above.
473-
let implements_default = |ty| {
474-
let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
475-
return false;
476-
};
477-
let infcx = tcx.infer_ctxt().build();
478-
infcx
479-
.type_implements_trait(default_trait, [ty], ty::ParamEnv::reveal_all())
480-
.must_apply_modulo_regions()
481-
};
482-
Some(match ty.kind() {
483-
ty::Never | ty::Error(_) => return None,
484-
ty::Bool => "false".to_string(),
485-
ty::Char => "\'x\'".to_string(),
486-
ty::Int(_) | ty::Uint(_) => "42".into(),
487-
ty::Float(_) => "3.14159".into(),
488-
ty::Slice(_) => "[]".to_string(),
489-
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
490-
"vec![]".to_string()
491-
}
492-
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
493-
"String::new()".to_string()
494-
}
495-
ty::Adt(def, args) if def.is_box() => {
496-
format!("Box::new({})", ty_kind_suggestion(args[0].expect_ty(), tcx)?)
497-
}
498-
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
499-
"None".to_string()
500-
}
501-
ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
502-
format!("Ok({})", ty_kind_suggestion(args[0].expect_ty(), tcx)?)
503-
}
504-
ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
505-
ty::Ref(_, ty, mutability) => {
506-
if let (ty::Str, Mutability::Not) = (ty.kind(), mutability) {
507-
"\"\"".to_string()
508-
} else {
509-
let Some(ty) = ty_kind_suggestion(*ty, tcx) else {
510-
return None;
511-
};
512-
format!("&{}{ty}", mutability.prefix_str())
513-
}
514-
}
515-
ty::Array(ty, len) => format!(
516-
"[{}; {}]",
517-
ty_kind_suggestion(*ty, tcx)?,
518-
len.eval_target_usize(tcx, ty::ParamEnv::reveal_all()),
519-
),
520-
ty::Tuple(tys) => format!(
521-
"({})",
522-
tys.iter()
523-
.map(|ty| ty_kind_suggestion(ty, tcx))
524-
.collect::<Option<Vec<String>>>()?
525-
.join(", ")
526-
),
527-
_ => "value".to_string(),
528-
})
529-
}
530-
531470
/// Return placeholder code for the given associated item.
532471
/// Similar to `ty::AssocItem::suggestion`, but appropriate for use as the code snippet of a
533472
/// structured suggestion.
@@ -562,7 +501,12 @@ fn suggestion_signature<'tcx>(
562501
}
563502
ty::AssocKind::Const => {
564503
let ty = tcx.type_of(assoc.def_id).instantiate_identity();
565-
let val = ty_kind_suggestion(ty, tcx).unwrap_or_else(|| "value".to_string());
504+
let val = tcx
505+
.infer_ctxt()
506+
.build()
507+
.err_ctxt()
508+
.ty_kind_suggestion(tcx.param_env(assoc.def_id), ty)
509+
.unwrap_or_else(|| "value".to_string());
566510
format!("const {}: {} = {};", assoc.name, ty, val)
567511
}
568512
}

compiler/rustc_hir_typeck/src/coercion.rs

+10
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ use rustc_span::DesugaringKind;
6363
use rustc_span::{BytePos, Span};
6464
use rustc_target::spec::abi::Abi;
6565
use rustc_trait_selection::infer::InferCtxtExt as _;
66+
use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt;
6667
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
6768
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
6869
use rustc_trait_selection::traits::TraitEngineExt as _;
@@ -1616,6 +1617,15 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
16161617
E0069,
16171618
"`return;` in a function whose return type is not `()`"
16181619
);
1620+
if let Some(value) = fcx.err_ctxt().ty_kind_suggestion(fcx.param_env, found)
1621+
{
1622+
err.span_suggestion_verbose(
1623+
cause.span.shrink_to_hi(),
1624+
"give the `return` a value of the expected type",
1625+
format!(" {value}"),
1626+
Applicability::HasPlaceholders,
1627+
);
1628+
}
16191629
err.span_label(cause.span, "return type is not `()`");
16201630
}
16211631
ObligationCauseCode::BlockTailExpression(blk_id, ..) => {

compiler/rustc_hir_typeck/src/expr.rs

+4-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ use rustc_hir::def_id::DefId;
3535
use rustc_hir::intravisit::Visitor;
3636
use rustc_hir::lang_items::LangItem;
3737
use rustc_hir::{ExprKind, HirId, QPath};
38-
use rustc_hir_analysis::check::ty_kind_suggestion;
3938
use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer as _;
4039
use rustc_infer::infer;
4140
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
@@ -57,6 +56,7 @@ use rustc_span::Span;
5756
use rustc_target::abi::{FieldIdx, FIRST_VARIANT};
5857
use rustc_target::spec::abi::Abi::RustIntrinsic;
5958
use rustc_trait_selection::infer::InferCtxtExt;
59+
use rustc_trait_selection::traits::error_reporting::suggestions::TypeErrCtxtExt as _;
6060
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
6161
use rustc_trait_selection::traits::ObligationCtxt;
6262
use rustc_trait_selection::traits::{self, ObligationCauseCode};
@@ -694,7 +694,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
694694
);
695695
let error = Some(Sorts(ExpectedFound { expected: ty, found: e_ty }));
696696
self.annotate_loop_expected_due_to_inference(err, expr, error);
697-
if let Some(val) = ty_kind_suggestion(ty, tcx) {
697+
if let Some(val) =
698+
self.err_ctxt().ty_kind_suggestion(self.param_env, ty)
699+
{
698700
err.span_suggestion_verbose(
699701
expr.span.shrink_to_hi(),
700702
"give the `break` a value of the expected type",

compiler/rustc_trait_selection/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
#![feature(box_patterns)]
2323
#![feature(control_flow_enum)]
2424
#![feature(extract_if)]
25+
#![feature(if_let_guard)]
2526
#![feature(let_chains)]
2627
#![feature(option_take_if)]
2728
#![feature(never_type)]

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

+55
Original file line numberDiff line numberDiff line change
@@ -4540,6 +4540,61 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
45404540
Applicability::MachineApplicable,
45414541
);
45424542
}
4543+
4544+
fn ty_kind_suggestion(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> Option<String> {
4545+
let tcx = self.infcx.tcx;
4546+
let implements_default = |ty| {
4547+
let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
4548+
return false;
4549+
};
4550+
self.type_implements_trait(default_trait, [ty], param_env).must_apply_modulo_regions()
4551+
};
4552+
4553+
Some(match ty.kind() {
4554+
ty::Never | ty::Error(_) => return None,
4555+
ty::Bool => "false".to_string(),
4556+
ty::Char => "\'x\'".to_string(),
4557+
ty::Int(_) | ty::Uint(_) => "42".into(),
4558+
ty::Float(_) => "3.14159".into(),
4559+
ty::Slice(_) => "[]".to_string(),
4560+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
4561+
"vec![]".to_string()
4562+
}
4563+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
4564+
"String::new()".to_string()
4565+
}
4566+
ty::Adt(def, args) if def.is_box() => {
4567+
format!("Box::new({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
4568+
}
4569+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
4570+
"None".to_string()
4571+
}
4572+
ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
4573+
format!("Ok({})", self.ty_kind_suggestion(param_env, args[0].expect_ty())?)
4574+
}
4575+
ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
4576+
ty::Ref(_, ty, mutability) => {
4577+
if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
4578+
"\"\"".to_string()
4579+
} else {
4580+
let ty = self.ty_kind_suggestion(param_env, *ty)?;
4581+
format!("&{}{ty}", mutability.prefix_str())
4582+
}
4583+
}
4584+
ty::Array(ty, len) if let Some(len) = len.try_eval_target_usize(tcx, param_env) => {
4585+
format!("[{}; {}]", self.ty_kind_suggestion(param_env, *ty)?, len)
4586+
}
4587+
ty::Tuple(tys) => format!(
4588+
"({}{})",
4589+
tys.iter()
4590+
.map(|ty| self.ty_kind_suggestion(param_env, ty))
4591+
.collect::<Option<Vec<String>>>()?
4592+
.join(", "),
4593+
if tys.len() == 1 { "," } else { "" }
4594+
),
4595+
_ => "value".to_string(),
4596+
})
4597+
}
45434598
}
45444599

45454600
/// Add a hint to add a missing borrow or remove an unnecessary one.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
fn as_chunks<const N: usize>() -> [u8; N] {
2+
loop {
3+
break;
4+
//~^ ERROR mismatched types
5+
}
6+
}
7+
8+
fn main() {}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
error[E0308]: mismatched types
2+
--> $DIR/value-suggestion-ice-123906.rs:3:9
3+
|
4+
LL | fn as_chunks<const N: usize>() -> [u8; N] {
5+
| ------- expected `[u8; ]` because of this return type
6+
LL | loop {
7+
| ---- this loop is expected to be of type `[u8; N]`
8+
LL | break;
9+
| ^^^^^ expected `[u8; N]`, found `()`
10+
|
11+
help: give the `break` a value of the expected type
12+
|
13+
LL | break value;
14+
| +++++
15+
16+
error: aborting due to 1 previous error
17+
18+
For more information about this error, try `rustc --explain E0308`.

tests/ui/error-codes/E0069.stderr

+5
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ LL | fn foo() -> u8 {
55
| -- expected `u8` because of this return type
66
LL | return;
77
| ^^^^^^ return type is not `()`
8+
|
9+
help: give the `return` a value of the expected type
10+
|
11+
LL | return 42;
12+
| ++
813

914
error: aborting due to 1 previous error
1015

tests/ui/ret-non-nil.stderr

+5
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,11 @@ LL | fn g() -> isize { return; }
55
| ----- ^^^^^^ return type is not `()`
66
| |
77
| expected `isize` because of this return type
8+
|
9+
help: give the `return` a value of the expected type
10+
|
11+
LL | fn g() -> isize { return 42; }
12+
| ++
813

914
error: aborting due to 1 previous error
1015

tests/ui/return/suggest-a-value.rs

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
fn test() -> (i32,) {
2+
return;
3+
//~^ ERROR `return;` in a function whose return type is not `()`
4+
}
5+
6+
fn main() {}
+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
error[E0069]: `return;` in a function whose return type is not `()`
2+
--> $DIR/suggest-a-value.rs:2:5
3+
|
4+
LL | fn test() -> (i32,) {
5+
| ------ expected `(i32,)` because of this return type
6+
LL | return;
7+
| ^^^^^^ return type is not `()`
8+
|
9+
help: give the `return` a value of the expected type
10+
|
11+
LL | return (42,);
12+
| +++++
13+
14+
error: aborting due to 1 previous error
15+
16+
For more information about this error, try `rustc --explain E0069`.

0 commit comments

Comments
 (0)