Skip to content

Commit 500a5a7

Browse files
Uplift TypeError
1 parent 4b7a2a4 commit 500a5a7

File tree

16 files changed

+194
-174
lines changed

16 files changed

+194
-174
lines changed

compiler/rustc_hir_analysis/src/check/check.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use rustc_lint_defs::builtin::REPR_TRANSPARENT_EXTERNAL_PRIVATE_FIELDS;
1515
use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
1616
use rustc_middle::middle::stability::EvalResult;
1717
use rustc_middle::span_bug;
18+
use rustc_middle::ty::error::TypeErrorToStringExt;
1819
use rustc_middle::ty::fold::BottomUpFolder;
1920
use rustc_middle::ty::layout::{LayoutError, MAX_SIMD_LANES};
2021
use rustc_middle::ty::util::{Discr, InspectCoroutineFields, IntTypeExt};

compiler/rustc_hir_typeck/src/expr.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ use rustc_infer::infer::InferOk;
4141
use rustc_infer::traits::query::NoSolution;
4242
use rustc_infer::traits::ObligationCause;
4343
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
44-
use rustc_middle::ty::error::{ExpectedFound, TypeError::Sorts};
44+
use rustc_middle::ty::error::{ExpectedFound, TypeError};
4545
use rustc_middle::ty::GenericArgsRef;
4646
use rustc_middle::ty::{self, AdtKind, Ty, TypeVisitableExt};
4747
use rustc_middle::{bug, span_bug};
@@ -683,7 +683,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
683683
self.suggest_mismatched_types_on_tail(
684684
&mut err, expr, ty, e_ty, target_id,
685685
);
686-
let error = Some(Sorts(ExpectedFound { expected: ty, found: e_ty }));
686+
let error =
687+
Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
687688
self.annotate_loop_expected_due_to_inference(err, expr, error);
688689
if let Some(val) =
689690
self.err_ctxt().ty_kind_suggestion(self.param_env, ty)

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ use rustc_hir::lang_items::LangItem;
7171
use rustc_macros::extension;
7272
use rustc_middle::bug;
7373
use rustc_middle::dep_graph::DepContext;
74+
use rustc_middle::ty::error::TypeErrorToStringExt;
7475
use rustc_middle::ty::print::{with_forced_trimmed_paths, PrintError, PrintTraitRefExt as _};
7576
use rustc_middle::ty::relate::{self, RelateResult, TypeRelation};
7677
use rustc_middle::ty::Upcast;

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

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,12 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
2121
sp: Span,
2222
body_owner_def_id: DefId,
2323
) {
24-
use ty::error::TypeError::*;
2524
debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
2625

2726
let tcx = self.tcx;
2827

2928
match err {
30-
ArgumentSorts(values, _) | Sorts(values) => {
29+
TypeError::ArgumentSorts(values, _) | TypeError::Sorts(values) => {
3130
match (*values.expected.kind(), *values.found.kind()) {
3231
(ty::Closure(..), ty::Closure(..)) => {
3332
diag.note("no two closures, even if identical, have the same type");
@@ -483,7 +482,7 @@ impl<T> Trait<T> for X {
483482
values.found.kind(),
484483
);
485484
}
486-
CyclicTy(ty) => {
485+
TypeError::CyclicTy(ty) => {
487486
// Watch out for various cases of cyclic types and try to explain.
488487
if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() {
489488
diag.note(
@@ -494,7 +493,7 @@ impl<T> Trait<T> for X {
494493
);
495494
}
496495
}
497-
TargetFeatureCast(def_id) => {
496+
TypeError::TargetFeatureCast(def_id) => {
498497
let target_spans = tcx.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
499498
diag.note(
500499
"functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"

compiler/rustc_infer/src/infer/region_constraints/leak_check.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ impl<'a, 'b, 'tcx> LeakCheck<'a, 'b, 'tcx> {
276276
other_region: ty::Region<'tcx>,
277277
) -> TypeError<'tcx> {
278278
debug!("error: placeholder={:?}, other_region={:?}", placeholder, other_region);
279-
TypeError::RegionsInsufficientlyPolymorphic(placeholder.bound.kind, other_region)
279+
TypeError::RegionsInsufficientlyPolymorphic(placeholder.bound, other_region)
280280
}
281281
}
282282

compiler/rustc_middle/src/traits/query.rs

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
88
use crate::error::DropCheckOverflow;
99
use crate::infer::canonical::{Canonical, QueryResponse};
10-
use crate::ty::error::TypeError;
1110
use crate::ty::GenericArg;
1211
use crate::ty::{self, Ty, TyCtxt};
1312
use rustc_macros::{HashStable, TypeFoldable, TypeVisitable};
@@ -91,12 +90,6 @@ pub type CanonicalTypeOpProvePredicateGoal<'tcx> =
9190
pub type CanonicalTypeOpNormalizeGoal<'tcx, T> =
9291
Canonical<'tcx, ty::ParamEnvAnd<'tcx, type_op::Normalize<T>>>;
9392

94-
impl<'tcx> From<TypeError<'tcx>> for NoSolution {
95-
fn from(_: TypeError<'tcx>) -> NoSolution {
96-
NoSolution
97-
}
98-
}
99-
10093
#[derive(Clone, Debug, Default, HashStable, TypeFoldable, TypeVisitable)]
10194
pub struct DropckOutlivesResult<'tcx> {
10295
pub kinds: Vec<GenericArg<'tcx>>,

compiler/rustc_middle/src/ty/error.rs

Lines changed: 14 additions & 105 deletions
Original file line numberDiff line numberDiff line change
@@ -1,91 +1,27 @@
11
use crate::ty::print::{with_forced_trimmed_paths, FmtPrinter, PrettyPrinter};
2-
use crate::ty::{self, BoundRegionKind, Region, Ty, TyCtxt};
2+
use crate::ty::{self, Ty, TyCtxt};
3+
34
use rustc_errors::pluralize;
45
use rustc_hir as hir;
56
use rustc_hir::def::{CtorOf, DefKind};
6-
use rustc_hir::def_id::DefId;
7-
use rustc_macros::{TypeFoldable, TypeVisitable};
8-
use rustc_span::symbol::Symbol;
9-
use rustc_target::spec::abi;
7+
use rustc_macros::extension;
8+
pub use rustc_type_ir::error::ExpectedFound;
9+
1010
use std::borrow::Cow;
1111
use std::hash::{DefaultHasher, Hash, Hasher};
1212
use std::path::PathBuf;
1313

14-
#[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable)]
15-
pub struct ExpectedFound<T> {
16-
pub expected: T,
17-
pub found: T,
18-
}
19-
20-
impl<T> ExpectedFound<T> {
21-
pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
22-
if a_is_expected {
23-
ExpectedFound { expected: a, found: b }
24-
} else {
25-
ExpectedFound { expected: b, found: a }
26-
}
27-
}
28-
}
29-
30-
// Data structures used in type unification
31-
#[derive(Copy, Clone, Debug, TypeVisitable, PartialEq, Eq)]
32-
#[rustc_pass_by_value]
33-
pub enum TypeError<'tcx> {
34-
Mismatch,
35-
ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
36-
PolarityMismatch(ExpectedFound<ty::PredicatePolarity>),
37-
SafetyMismatch(ExpectedFound<hir::Safety>),
38-
AbiMismatch(ExpectedFound<abi::Abi>),
39-
Mutability,
40-
ArgumentMutability(usize),
41-
TupleSize(ExpectedFound<usize>),
42-
FixedArraySize(ExpectedFound<u64>),
43-
ArgCount,
44-
FieldMisMatch(Symbol, Symbol),
45-
46-
RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
47-
RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
48-
RegionsPlaceholderMismatch,
49-
50-
Sorts(ExpectedFound<Ty<'tcx>>),
51-
ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
52-
IntMismatch(ExpectedFound<ty::IntVarValue>),
53-
FloatMismatch(ExpectedFound<ty::FloatTy>),
54-
Traits(ExpectedFound<DefId>),
55-
VariadicMismatch(ExpectedFound<bool>),
56-
57-
/// Instantiating a type variable with the given type would have
58-
/// created a cycle (because it appears somewhere within that
59-
/// type).
60-
CyclicTy(Ty<'tcx>),
61-
CyclicConst(ty::Const<'tcx>),
62-
ProjectionMismatched(ExpectedFound<DefId>),
63-
ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>),
64-
ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
65-
66-
IntrinsicCast,
67-
/// Safe `#[target_feature]` functions are not assignable to safe function pointers.
68-
TargetFeatureCast(DefId),
69-
}
14+
pub type TypeError<'tcx> = rustc_type_ir::error::TypeError<TyCtxt<'tcx>>;
7015

71-
impl TypeError<'_> {
72-
pub fn involves_regions(self) -> bool {
73-
match self {
74-
TypeError::RegionsDoesNotOutlive(_, _)
75-
| TypeError::RegionsInsufficientlyPolymorphic(_, _)
76-
| TypeError::RegionsPlaceholderMismatch => true,
77-
_ => false,
78-
}
79-
}
80-
}
81-
82-
/// Explains the source of a type err in a short, human readable way. This is meant to be placed
83-
/// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
84-
/// afterwards to present additional details, particularly when it comes to lifetime-related
85-
/// errors.
16+
#[extension(pub trait TypeErrorToStringExt<'tcx>)]
17+
/// Explains the source of a type err in a short, human readable way.
18+
/// This is meant to be placed in parentheses after some larger message.
19+
/// You should also invoke `note_and_explain_type_err()` afterwards
20+
/// to present additional details, particularly when it comes to lifetime-
21+
/// related errors.
8622
impl<'tcx> TypeError<'tcx> {
87-
pub fn to_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
88-
use self::TypeError::*;
23+
fn to_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
24+
use IrTypeError::*;
8925
fn report_maybe_different(expected: &str, found: &str) -> String {
9026
// A naive approach to making sure that we're not reporting silly errors such as:
9127
// (expected closure, found closure).
@@ -131,7 +67,6 @@ impl<'tcx> TypeError<'tcx> {
13167
)
13268
.into(),
13369
ArgCount => "incorrect number of function parameters".into(),
134-
FieldMisMatch(adt, field) => format!("field type mismatch: {adt}.{field}").into(),
13570
RegionsDoesNotOutlive(..) => "lifetime mismatch".into(),
13671
// Actually naming the region here is a bit confusing because context is lacking
13772
RegionsInsufficientlyPolymorphic(..) => {
@@ -200,32 +135,6 @@ impl<'tcx> TypeError<'tcx> {
200135
}
201136
}
202137

203-
impl<'tcx> TypeError<'tcx> {
204-
pub fn must_include_note(self) -> bool {
205-
use self::TypeError::*;
206-
match self {
207-
CyclicTy(_) | CyclicConst(_) | SafetyMismatch(_) | ConstnessMismatch(_)
208-
| PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
209-
| ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
210-
| VariadicMismatch(_) | TargetFeatureCast(_) => false,
211-
212-
Mutability
213-
| ArgumentMutability(_)
214-
| TupleSize(_)
215-
| ArgCount
216-
| FieldMisMatch(..)
217-
| RegionsDoesNotOutlive(..)
218-
| RegionsInsufficientlyPolymorphic(..)
219-
| RegionsPlaceholderMismatch
220-
| Traits(_)
221-
| ProjectionMismatched(_)
222-
| ExistentialMismatch(_)
223-
| ConstMismatch(_)
224-
| IntrinsicCast => true,
225-
}
226-
}
227-
}
228-
229138
impl<'tcx> Ty<'tcx> {
230139
pub fn sort_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
231140
match *self.kind() {

compiler/rustc_middle/src/ty/mod.rs

Lines changed: 0 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -315,38 +315,6 @@ impl Visibility {
315315
}
316316
}
317317

318-
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable, TyEncodable, TyDecodable)]
319-
pub enum BoundConstness {
320-
/// `Type: Trait`
321-
NotConst,
322-
/// `Type: const Trait`
323-
Const,
324-
/// `Type: ~const Trait`
325-
///
326-
/// Requires resolving to const only when we are in a const context.
327-
ConstIfConst,
328-
}
329-
330-
impl BoundConstness {
331-
pub fn as_str(self) -> &'static str {
332-
match self {
333-
Self::NotConst => "",
334-
Self::Const => "const",
335-
Self::ConstIfConst => "~const",
336-
}
337-
}
338-
}
339-
340-
impl fmt::Display for BoundConstness {
341-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
342-
match self {
343-
Self::NotConst => f.write_str("normal"),
344-
Self::Const => f.write_str("const"),
345-
Self::ConstIfConst => f.write_str("~const"),
346-
}
347-
}
348-
}
349-
350318
#[derive(Clone, Debug, PartialEq, Eq, Copy, Hash, TyEncodable, TyDecodable, HashStable)]
351319
#[derive(TypeFoldable, TypeVisitable)]
352320
pub struct ClosureSizeProfileData<'tcx> {

compiler/rustc_middle/src/ty/structural_impls.rs

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -293,7 +293,6 @@ TrivialTypeTraversalImpls! {
293293
::rustc_target::abi::FieldIdx,
294294
::rustc_target::abi::VariantIdx,
295295
crate::middle::region::Scope,
296-
crate::ty::FloatTy,
297296
::rustc_ast::InlineAsmOptions,
298297
::rustc_ast::InlineAsmTemplatePiece,
299298
::rustc_ast::NodeId,
@@ -313,24 +312,19 @@ TrivialTypeTraversalImpls! {
313312
crate::traits::Reveal,
314313
crate::ty::adjustment::AutoBorrowMutability,
315314
crate::ty::AdtKind,
316-
crate::ty::BoundConstness,
315+
crate::ty::BoundRegion,
317316
// Including `BoundRegionKind` is a *bit* dubious, but direct
318317
// references to bound region appear in `ty::Error`, and aren't
319318
// really meant to be folded. In general, we can only fold a fully
320319
// general `Region`.
321320
crate::ty::BoundRegionKind,
322321
crate::ty::AssocItem,
323322
crate::ty::AssocKind,
324-
crate::ty::AliasTyKind,
325323
crate::ty::Placeholder<crate::ty::BoundRegion>,
326324
crate::ty::Placeholder<crate::ty::BoundTy>,
327325
crate::ty::Placeholder<ty::BoundVar>,
328326
crate::ty::LateParamRegion,
329-
crate::ty::InferTy,
330-
crate::ty::IntVarValue,
331327
crate::ty::adjustment::PointerCoercion,
332-
crate::ty::RegionVid,
333-
crate::ty::Variance,
334328
::rustc_span::Span,
335329
::rustc_span::symbol::Ident,
336330
::rustc_errors::ErrorGuaranteed,

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk};
2828
use rustc_macros::extension;
2929
use rustc_middle::hir::map;
3030
use rustc_middle::traits::IsConstable;
31-
use rustc_middle::ty::error::TypeError::{self, Sorts};
31+
use rustc_middle::ty::error::TypeError;
3232
use rustc_middle::ty::{
3333
self, suggest_arbitrary_trait_bound, suggest_constraining_type_param, AdtKind, GenericArgs,
3434
InferTy, IsSuggestable, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
@@ -3846,7 +3846,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
38463846
&& let Some(failed_pred) = failed_pred.as_projection_clause()
38473847
&& let Some(found) = failed_pred.skip_binder().term.ty()
38483848
{
3849-
type_diffs = vec![Sorts(ty::error::ExpectedFound {
3849+
type_diffs = vec![TypeError::Sorts(ty::error::ExpectedFound {
38503850
expected: where_pred
38513851
.skip_binder()
38523852
.projection_term
@@ -3989,7 +3989,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
39893989
continue;
39903990
};
39913991
for diff in type_diffs {
3992-
let Sorts(expected_found) = diff else {
3992+
let TypeError::Sorts(expected_found) = diff else {
39933993
continue;
39943994
};
39953995
if tcx.is_diagnostic_item(sym::IteratorItem, *def_id)
@@ -4169,7 +4169,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
41694169
};
41704170
if primary_spans.is_empty()
41714171
|| type_diffs.iter().any(|diff| {
4172-
let Sorts(expected_found) = diff else {
4172+
let TypeError::Sorts(expected_found) = diff else {
41734173
return false;
41744174
};
41754175
self.can_eq(param_env, expected_found.found, ty)
@@ -4202,7 +4202,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
42024202
let assoc = with_forced_trimmed_paths!(self.tcx.def_path_str(assoc));
42034203
if !self.can_eq(param_env, ty, *prev_ty) {
42044204
if type_diffs.iter().any(|diff| {
4205-
let Sorts(expected_found) = diff else {
4205+
let TypeError::Sorts(expected_found) = diff else {
42064206
return false;
42074207
};
42084208
self.can_eq(param_env, expected_found.found, ty)
@@ -4252,7 +4252,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
42524252
let ocx = ObligationCtxt::new(self.infcx);
42534253
let mut assocs_in_this_method = Vec::with_capacity(type_diffs.len());
42544254
for diff in type_diffs {
4255-
let Sorts(expected_found) = diff else {
4255+
let TypeError::Sorts(expected_found) = diff else {
42564256
continue;
42574257
};
42584258
let ty::Alias(ty::Projection, proj) = expected_found.expected.kind() else {

compiler/rustc_trait_selection/src/traits/select/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ use rustc_middle::dep_graph::DepNodeIndex;
4242
use rustc_middle::mir::interpret::ErrorHandled;
4343
use rustc_middle::ty::_match::MatchAgainstFreshVars;
4444
use rustc_middle::ty::abstract_const::NotConstEvaluatable;
45+
use rustc_middle::ty::error::TypeErrorToStringExt;
4546
use rustc_middle::ty::print::PrintTraitRefExt as _;
4647
use rustc_middle::ty::relate::TypeRelation;
4748
use rustc_middle::ty::GenericArgsRef;

0 commit comments

Comments
 (0)