Skip to content

Commit 3493a56

Browse files
committed
Auto merge of rust-lang#123982 - compiler-errors:rollup-m2v4epp, r=compiler-errors
Rollup of 4 pull requests Successful merges: - rust-lang#123900 (Stop using `PolyTraitRef` for closure/coroutine predicates already instantiated w placeholders) - rust-lang#123924 (Fix various bugs in `ty_kind_suggestion`) - rust-lang#123943 (Use the rustc_private libc less in tests) - rust-lang#123970 (zkvm: fix references to `os_str` module) r? `@ghost` `@rustbot` modify labels: rollup
2 parents 99d0186 + 27cb6bc commit 3493a56

Some content is hidden

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

48 files changed

+270
-318
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_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
367367
}),
368368
) = error.code
369369
&& let ty::Closure(def_id, _) | ty::Coroutine(def_id, ..) =
370-
expected_trait_ref.skip_binder().self_ty().kind()
370+
expected_trait_ref.self_ty().kind()
371371
&& span.overlaps(self.tcx.def_span(*def_id))
372372
{
373373
true

compiler/rustc_infer/src/infer/at.rs

+1-19
Original file line numberDiff line numberDiff line change
@@ -424,25 +424,7 @@ impl<'tcx> ToTrace<'tcx> for ty::TraitRef<'tcx> {
424424
) -> TypeTrace<'tcx> {
425425
TypeTrace {
426426
cause: cause.clone(),
427-
values: PolyTraitRefs(ExpectedFound::new(
428-
a_is_expected,
429-
ty::Binder::dummy(a),
430-
ty::Binder::dummy(b),
431-
)),
432-
}
433-
}
434-
}
435-
436-
impl<'tcx> ToTrace<'tcx> for ty::PolyTraitRef<'tcx> {
437-
fn to_trace(
438-
cause: &ObligationCause<'tcx>,
439-
a_is_expected: bool,
440-
a: Self,
441-
b: Self,
442-
) -> TypeTrace<'tcx> {
443-
TypeTrace {
444-
cause: cause.clone(),
445-
values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)),
427+
values: TraitRefs(ExpectedFound::new(a_is_expected, a, b)),
446428
}
447429
}
448430
}

compiler/rustc_infer/src/infer/error_reporting/mod.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -1653,7 +1653,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
16531653
.report(diag);
16541654
(false, Mismatch::Fixed("signature"))
16551655
}
1656-
ValuePairs::PolyTraitRefs(_) => (false, Mismatch::Fixed("trait")),
1656+
ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
16571657
ValuePairs::Aliases(infer::ExpectedFound { expected, .. }) => {
16581658
(false, Mismatch::Fixed(self.tcx.def_descr(expected.def_id)))
16591659
}
@@ -1969,8 +1969,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
19691969
self.note_and_explain_type_err(diag, exp_found, cause, span, cause.body_id.to_def_id());
19701970
}
19711971

1972-
if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1973-
&& let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1972+
if let Some(ValuePairs::TraitRefs(exp_found)) = values
1973+
&& let ty::Closure(def_id, _) = exp_found.expected.self_ty().kind()
19741974
&& let Some(def_id) = def_id.as_local()
19751975
&& terr.involves_regions()
19761976
{
@@ -2188,7 +2188,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
21882188
infer::Aliases(exp_found) => self.expected_found_str(exp_found),
21892189
infer::ExistentialTraitRef(exp_found) => self.expected_found_str(exp_found),
21902190
infer::ExistentialProjection(exp_found) => self.expected_found_str(exp_found),
2191-
infer::PolyTraitRefs(exp_found) => {
2191+
infer::TraitRefs(exp_found) => {
21922192
let pretty_exp_found = ty::error::ExpectedFound {
21932193
expected: exp_found.expected.print_trait_sugared(),
21942194
found: exp_found.found.print_trait_sugared(),

compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -195,13 +195,13 @@ impl<'tcx> NiceRegionError<'_, 'tcx> {
195195
value_pairs: &ValuePairs<'tcx>,
196196
) -> Option<Diag<'tcx>> {
197197
let (expected_args, found_args, trait_def_id) = match value_pairs {
198-
ValuePairs::PolyTraitRefs(ExpectedFound { expected, found })
199-
if expected.def_id() == found.def_id() =>
198+
ValuePairs::TraitRefs(ExpectedFound { expected, found })
199+
if expected.def_id == found.def_id =>
200200
{
201201
// It's possible that the placeholders come from a binder
202202
// outside of this value pair. Use `no_bound_vars` as a
203203
// simple heuristic for that.
204-
(expected.no_bound_vars()?.args, found.no_bound_vars()?.args, expected.def_id())
204+
(expected.args, found.args, expected.def_id)
205205
}
206206
_ => return None,
207207
};

compiler/rustc_infer/src/infer/error_reporting/suggest.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
599599
&self,
600600
span: Span,
601601
hir: hir::Node<'_>,
602-
exp_found: &ty::error::ExpectedFound<ty::PolyTraitRef<'tcx>>,
602+
exp_found: &ty::error::ExpectedFound<ty::TraitRef<'tcx>>,
603603
diag: &mut Diag<'_>,
604604
) {
605605
// 0. Extract fn_decl from hir
@@ -614,10 +614,10 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
614614

615615
// 1. Get the args of the closure.
616616
// 2. Assume exp_found is FnOnce / FnMut / Fn, we can extract function parameters from [1].
617-
let Some(expected) = exp_found.expected.skip_binder().args.get(1) else {
617+
let Some(expected) = exp_found.expected.args.get(1) else {
618618
return;
619619
};
620-
let Some(found) = exp_found.found.skip_binder().args.get(1) else {
620+
let Some(found) = exp_found.found.args.get(1) else {
621621
return;
622622
};
623623
let expected = expected.unpack();

compiler/rustc_infer/src/infer/mod.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -403,7 +403,7 @@ pub enum ValuePairs<'tcx> {
403403
Regions(ExpectedFound<ty::Region<'tcx>>),
404404
Terms(ExpectedFound<ty::Term<'tcx>>),
405405
Aliases(ExpectedFound<ty::AliasTy<'tcx>>),
406-
PolyTraitRefs(ExpectedFound<ty::PolyTraitRef<'tcx>>),
406+
TraitRefs(ExpectedFound<ty::TraitRef<'tcx>>),
407407
PolySigs(ExpectedFound<ty::PolyFnSig<'tcx>>),
408408
ExistentialTraitRef(ExpectedFound<ty::PolyExistentialTraitRef<'tcx>>),
409409
ExistentialProjection(ExpectedFound<ty::PolyExistentialProjection<'tcx>>),
@@ -1882,15 +1882,15 @@ impl<'tcx> TypeTrace<'tcx> {
18821882
}
18831883
}
18841884

1885-
pub fn poly_trait_refs(
1885+
pub fn trait_refs(
18861886
cause: &ObligationCause<'tcx>,
18871887
a_is_expected: bool,
1888-
a: ty::PolyTraitRef<'tcx>,
1889-
b: ty::PolyTraitRef<'tcx>,
1888+
a: ty::TraitRef<'tcx>,
1889+
b: ty::TraitRef<'tcx>,
18901890
) -> TypeTrace<'tcx> {
18911891
TypeTrace {
18921892
cause: cause.clone(),
1893-
values: PolyTraitRefs(ExpectedFound::new(a_is_expected, a, b)),
1893+
values: TraitRefs(ExpectedFound::new(a_is_expected, a, b)),
18941894
}
18951895
}
18961896

compiler/rustc_middle/src/traits/mod.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -620,11 +620,10 @@ pub enum SelectionError<'tcx> {
620620
OpaqueTypeAutoTraitLeakageUnknown(DefId),
621621
}
622622

623-
// FIXME(@lcnr): The `Binder` here should be unnecessary. Just use `TraitRef` instead.
624623
#[derive(Clone, Debug, TypeVisitable)]
625624
pub struct SignatureMismatchData<'tcx> {
626-
pub found_trait_ref: ty::PolyTraitRef<'tcx>,
627-
pub expected_trait_ref: ty::PolyTraitRef<'tcx>,
625+
pub found_trait_ref: ty::TraitRef<'tcx>,
626+
pub expected_trait_ref: ty::TraitRef<'tcx>,
628627
pub terr: ty::error::TypeError<'tcx>,
629628
}
630629

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)]

0 commit comments

Comments
 (0)