Skip to content

Commit d6ac50e

Browse files
Consolidate two copies of ty_kind_suggestion
1 parent 78bc0a5 commit d6ac50e

File tree

4 files changed

+73
-130
lines changed

4 files changed

+73
-130
lines changed

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

Lines changed: 2 additions & 63 deletions
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

Lines changed: 9 additions & 65 deletions
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/expr.rs

Lines changed: 4 additions & 2 deletions
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/traits/error_reporting/suggestions.rs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4540,6 +4540,64 @@ 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 Some(ty) = self.ty_kind_suggestion(param_env, *ty) else {
4581+
return None;
4582+
};
4583+
format!("&{}{ty}", mutability.prefix_str())
4584+
}
4585+
}
4586+
ty::Array(ty, len) => format!(
4587+
"[{}; {}]",
4588+
self.ty_kind_suggestion(param_env, *ty)?,
4589+
len.eval_target_usize(tcx, ty::ParamEnv::reveal_all()),
4590+
),
4591+
ty::Tuple(tys) => format!(
4592+
"({})",
4593+
tys.iter()
4594+
.map(|ty| self.ty_kind_suggestion(param_env, ty))
4595+
.collect::<Option<Vec<String>>>()?
4596+
.join(", ")
4597+
),
4598+
_ => "value".to_string(),
4599+
})
4600+
}
45434601
}
45444602

45454603
/// Add a hint to add a missing borrow or remove an unnecessary one.

0 commit comments

Comments
 (0)