Skip to content

Commit dbaacb7

Browse files
authored
Rollup merge of rust-lang#123704 - estebank:diag-changes, r=compiler-errors
Tweak value suggestions in `borrowck` and `hir_analysis` Unify the output of `suggest_assign_value` and `ty_kind_suggestion`. Ideally we'd make these a single function, but doing so would likely require modify the crate dependency tree.
2 parents 22c488d + ad8bfbf commit dbaacb7

File tree

56 files changed

+385
-190
lines changed

Some content is hidden

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

56 files changed

+385
-190
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+70-26
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,68 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
652652
err
653653
}
654654

655+
fn ty_kind_suggestion(&self, ty: Ty<'tcx>) -> Option<String> {
656+
// Keep in sync with `rustc_hir_analysis/src/check/mod.rs:ty_kind_suggestion`.
657+
// FIXME: deduplicate the above.
658+
let tcx = self.infcx.tcx;
659+
let implements_default = |ty| {
660+
let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
661+
return false;
662+
};
663+
self.infcx
664+
.type_implements_trait(default_trait, [ty], self.param_env)
665+
.must_apply_modulo_regions()
666+
};
667+
668+
Some(match ty.kind() {
669+
ty::Never | ty::Error(_) => return None,
670+
ty::Bool => "false".to_string(),
671+
ty::Char => "\'x\'".to_string(),
672+
ty::Int(_) | ty::Uint(_) => "42".into(),
673+
ty::Float(_) => "3.14159".into(),
674+
ty::Slice(_) => "[]".to_string(),
675+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
676+
"vec![]".to_string()
677+
}
678+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
679+
"String::new()".to_string()
680+
}
681+
ty::Adt(def, args) if def.is_box() => {
682+
format!("Box::new({})", self.ty_kind_suggestion(args[0].expect_ty())?)
683+
}
684+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
685+
"None".to_string()
686+
}
687+
ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
688+
format!("Ok({})", self.ty_kind_suggestion(args[0].expect_ty())?)
689+
}
690+
ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
691+
ty::Ref(_, ty, mutability) => {
692+
if let (ty::Str, hir::Mutability::Not) = (ty.kind(), mutability) {
693+
"\"\"".to_string()
694+
} else {
695+
let Some(ty) = self.ty_kind_suggestion(*ty) else {
696+
return None;
697+
};
698+
format!("&{}{ty}", mutability.prefix_str())
699+
}
700+
}
701+
ty::Array(ty, len) => format!(
702+
"[{}; {}]",
703+
self.ty_kind_suggestion(*ty)?,
704+
len.eval_target_usize(tcx, ty::ParamEnv::reveal_all()),
705+
),
706+
ty::Tuple(tys) => format!(
707+
"({})",
708+
tys.iter()
709+
.map(|ty| self.ty_kind_suggestion(ty))
710+
.collect::<Option<Vec<String>>>()?
711+
.join(", ")
712+
),
713+
_ => "value".to_string(),
714+
})
715+
}
716+
655717
fn suggest_assign_value(
656718
&self,
657719
err: &mut Diag<'_>,
@@ -661,34 +723,16 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
661723
let ty = moved_place.ty(self.body, self.infcx.tcx).ty;
662724
debug!("ty: {:?}, kind: {:?}", ty, ty.kind());
663725

664-
let tcx = self.infcx.tcx;
665-
let implements_default = |ty, param_env| {
666-
let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
667-
return false;
668-
};
669-
self.infcx
670-
.type_implements_trait(default_trait, [ty], param_env)
671-
.must_apply_modulo_regions()
672-
};
673-
674-
let assign_value = match ty.kind() {
675-
ty::Bool => "false",
676-
ty::Float(_) => "0.0",
677-
ty::Int(_) | ty::Uint(_) => "0",
678-
ty::Never | ty::Error(_) => "",
679-
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => "vec![]",
680-
ty::Adt(_, _) if implements_default(ty, self.param_env) => "Default::default()",
681-
_ => "todo!()",
726+
let Some(assign_value) = self.ty_kind_suggestion(ty) else {
727+
return;
682728
};
683729

684-
if !assign_value.is_empty() {
685-
err.span_suggestion_verbose(
686-
sugg_span.shrink_to_hi(),
687-
"consider assigning a value",
688-
format!(" = {assign_value}"),
689-
Applicability::MaybeIncorrect,
690-
);
691-
}
730+
err.span_suggestion_verbose(
731+
sugg_span.shrink_to_hi(),
732+
"consider assigning a value",
733+
format!(" = {assign_value}"),
734+
Applicability::MaybeIncorrect,
735+
);
692736
}
693737

694738
fn suggest_borrow_fn_like(

compiler/rustc_hir_analysis/src/check/check.rs

-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ use rustc_middle::ty::{
2222
AdtDef, ParamEnv, RegionKind, TypeSuperVisitable, TypeVisitable, TypeVisitableExt,
2323
};
2424
use rustc_session::lint::builtin::{UNINHABITED_STATIC, UNSUPPORTED_CALLING_CONVENTIONS};
25-
use rustc_span::symbol::sym;
2625
use rustc_target::abi::FieldIdx;
2726
use rustc_trait_selection::traits::error_reporting::on_unimplemented::OnUnimplementedDirective;
2827
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;

compiler/rustc_hir_analysis/src/check/mod.rs

+62-10
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ 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;
8485
use rustc_index::bit_set::BitSet;
8586
use rustc_infer::infer::error_reporting::ObligationCauseExt as _;
8687
use rustc_infer::infer::outlives::env::OutlivesEnvironment;
@@ -91,10 +92,11 @@ use rustc_middle::ty::error::{ExpectedFound, TypeError};
9192
use rustc_middle::ty::{self, Ty, TyCtxt};
9293
use rustc_middle::ty::{GenericArgs, GenericArgsRef};
9394
use rustc_session::parse::feature_err;
94-
use rustc_span::symbol::{kw, Ident};
95-
use rustc_span::{self, def_id::CRATE_DEF_ID, BytePos, Span, Symbol, DUMMY_SP};
95+
use rustc_span::symbol::{kw, sym, Ident};
96+
use rustc_span::{def_id::CRATE_DEF_ID, BytePos, Span, Symbol, DUMMY_SP};
9697
use rustc_target::abi::VariantIdx;
9798
use rustc_target::spec::abi::Abi;
99+
use rustc_trait_selection::infer::InferCtxtExt;
98100
use rustc_trait_selection::traits::error_reporting::suggestions::ReturnsVisitor;
99101
use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt as _;
100102
use rustc_trait_selection::traits::ObligationCtxt;
@@ -466,14 +468,64 @@ fn fn_sig_suggestion<'tcx>(
466468
)
467469
}
468470

469-
pub fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
471+
pub fn ty_kind_suggestion<'tcx>(ty: Ty<'tcx>, tcx: TyCtxt<'tcx>) -> Option<String> {
472+
// Keep in sync with `rustc_borrowck/src/diagnostics/conflict_errors.rs:ty_kind_suggestion`.
473+
// FIXME: deduplicate the above.
474+
let implements_default = |ty| {
475+
let Some(default_trait) = tcx.get_diagnostic_item(sym::Default) else {
476+
return false;
477+
};
478+
let infcx = tcx.infer_ctxt().build();
479+
infcx
480+
.type_implements_trait(default_trait, [ty], ty::ParamEnv::reveal_all())
481+
.must_apply_modulo_regions()
482+
};
470483
Some(match ty.kind() {
471-
ty::Bool => "true",
472-
ty::Char => "'a'",
473-
ty::Int(_) | ty::Uint(_) => "42",
474-
ty::Float(_) => "3.14159",
475-
ty::Error(_) | ty::Never => return None,
476-
_ => "value",
484+
ty::Never | ty::Error(_) => return None,
485+
ty::Bool => "false".to_string(),
486+
ty::Char => "\'x\'".to_string(),
487+
ty::Int(_) | ty::Uint(_) => "42".into(),
488+
ty::Float(_) => "3.14159".into(),
489+
ty::Slice(_) => "[]".to_string(),
490+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Vec) => {
491+
"vec![]".to_string()
492+
}
493+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::String) => {
494+
"String::new()".to_string()
495+
}
496+
ty::Adt(def, args) if def.is_box() => {
497+
format!("Box::new({})", ty_kind_suggestion(args[0].expect_ty(), tcx)?)
498+
}
499+
ty::Adt(def, _) if Some(def.did()) == tcx.get_diagnostic_item(sym::Option) => {
500+
"None".to_string()
501+
}
502+
ty::Adt(def, args) if Some(def.did()) == tcx.get_diagnostic_item(sym::Result) => {
503+
format!("Ok({})", ty_kind_suggestion(args[0].expect_ty(), tcx)?)
504+
}
505+
ty::Adt(_, _) if implements_default(ty) => "Default::default()".to_string(),
506+
ty::Ref(_, ty, mutability) => {
507+
if let (ty::Str, Mutability::Not) = (ty.kind(), mutability) {
508+
"\"\"".to_string()
509+
} else {
510+
let Some(ty) = ty_kind_suggestion(*ty, tcx) else {
511+
return None;
512+
};
513+
format!("&{}{ty}", mutability.prefix_str())
514+
}
515+
}
516+
ty::Array(ty, len) => format!(
517+
"[{}; {}]",
518+
ty_kind_suggestion(*ty, tcx)?,
519+
len.eval_target_usize(tcx, ty::ParamEnv::reveal_all()),
520+
),
521+
ty::Tuple(tys) => format!(
522+
"({})",
523+
tys.iter()
524+
.map(|ty| ty_kind_suggestion(ty, tcx))
525+
.collect::<Option<Vec<String>>>()?
526+
.join(", ")
527+
),
528+
_ => "value".to_string(),
477529
})
478530
}
479531

@@ -511,7 +563,7 @@ fn suggestion_signature<'tcx>(
511563
}
512564
ty::AssocKind::Const => {
513565
let ty = tcx.type_of(assoc.def_id).instantiate_identity();
514-
let val = ty_kind_suggestion(ty).unwrap_or("todo!()");
566+
let val = ty_kind_suggestion(ty, tcx).unwrap_or_else(|| "value".to_string());
515567
format!("const {}: {} = {};", assoc.name, ty, val)
516568
}
517569
}

compiler/rustc_hir_typeck/src/expr.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -694,10 +694,10 @@ 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) {
697+
if let Some(val) = ty_kind_suggestion(ty, tcx) {
698698
err.span_suggestion_verbose(
699699
expr.span.shrink_to_hi(),
700-
"give it a value of the expected type",
700+
"give the `break` a value of the expected type",
701701
format!(" {val}"),
702702
Applicability::HasPlaceholders,
703703
);

tests/ui/asm/x86_64/type-check-5.stderr

+4-4
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | asm!("{}", in(reg) x);
88
|
99
help: consider assigning a value
1010
|
11-
LL | let x: u64 = 0;
12-
| +++
11+
LL | let x: u64 = 42;
12+
| ++++
1313

1414
error[E0381]: used binding `y` isn't initialized
1515
--> $DIR/type-check-5.rs:18:9
@@ -21,8 +21,8 @@ LL | asm!("{}", inout(reg) y);
2121
|
2222
help: consider assigning a value
2323
|
24-
LL | let mut y: u64 = 0;
25-
| +++
24+
LL | let mut y: u64 = 42;
25+
| ++++
2626

2727
error[E0596]: cannot borrow `v` as mutable, as it is not declared as mutable
2828
--> $DIR/type-check-5.rs:24:13

tests/ui/binop/issue-77910-1.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,8 @@ LL | xs
3232
|
3333
help: consider assigning a value
3434
|
35-
LL | let xs = todo!();
36-
| +++++++++
35+
LL | let xs = &42;
36+
| +++++
3737

3838
error: aborting due to 3 previous errors
3939

tests/ui/binop/issue-77910-2.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@ LL | xs
2121
|
2222
help: consider assigning a value
2323
|
24-
LL | let xs = todo!();
25-
| +++++++++
24+
LL | let xs = &42;
25+
| +++++
2626

2727
error: aborting due to 2 previous errors
2828

tests/ui/borrowck/borrowck-block-uninit.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ LL | println!("{}", x);
1010
|
1111
help: consider assigning a value
1212
|
13-
LL | let x: isize = 0;
14-
| +++
13+
LL | let x: isize = 42;
14+
| ++++
1515

1616
error: aborting due to 1 previous error
1717

tests/ui/borrowck/borrowck-break-uninit-2.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ LL | println!("{}", x);
1010
= 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)
1111
help: consider assigning a value
1212
|
13-
LL | let x: isize = 0;
14-
| +++
13+
LL | let x: isize = 42;
14+
| ++++
1515

1616
error: aborting due to 1 previous error
1717

tests/ui/borrowck/borrowck-break-uninit.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ LL | println!("{}", x);
1010
= 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)
1111
help: consider assigning a value
1212
|
13-
LL | let x: isize = 0;
14-
| +++
13+
LL | let x: isize = 42;
14+
| ++++
1515

1616
error: aborting due to 1 previous error
1717

tests/ui/borrowck/borrowck-init-in-called-fn-expr.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | i
88
|
99
help: consider assigning a value
1010
|
11-
LL | let i: isize = 0;
12-
| +++
11+
LL | let i: isize = 42;
12+
| ++++
1313

1414
error: aborting due to 1 previous error
1515

tests/ui/borrowck/borrowck-init-in-fn-expr.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | i
88
|
99
help: consider assigning a value
1010
|
11-
LL | let i: isize = 0;
12-
| +++
11+
LL | let i: isize = 42;
12+
| ++++
1313

1414
error: aborting due to 1 previous error
1515

tests/ui/borrowck/borrowck-init-in-fru.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | origin = Point { x: 10, ..origin };
88
|
99
help: consider assigning a value
1010
|
11-
LL | let mut origin: Point = todo!();
12-
| +++++++++
11+
LL | let mut origin: Point = value;
12+
| +++++++
1313

1414
error: aborting due to 1 previous error
1515

tests/ui/borrowck/borrowck-init-op-equal.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | v += 1;
88
|
99
help: consider assigning a value
1010
|
11-
LL | let v: isize = 0;
12-
| +++
11+
LL | let v: isize = 42;
12+
| ++++
1313

1414
error: aborting due to 1 previous error
1515

tests/ui/borrowck/borrowck-init-plus-equal.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | v = v + 1;
88
|
99
help: consider assigning a value
1010
|
11-
LL | let mut v: isize = 0;
12-
| +++
11+
LL | let mut v: isize = 42;
12+
| ++++
1313

1414
error: aborting due to 1 previous error
1515

tests/ui/borrowck/borrowck-return.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | return x;
88
|
99
help: consider assigning a value
1010
|
11-
LL | let x: isize = 0;
12-
| +++
11+
LL | let x: isize = 42;
12+
| ++++
1313

1414
error: aborting due to 1 previous error
1515

tests/ui/borrowck/borrowck-storage-dead.stderr

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,8 @@ LL | let _ = x + 1;
88
|
99
help: consider assigning a value
1010
|
11-
LL | let x: i32 = 0;
12-
| +++
11+
LL | let x: i32 = 42;
12+
| ++++
1313

1414
error: aborting due to 1 previous error
1515

0 commit comments

Comments
 (0)