Skip to content

Commit 82ef3ad

Browse files
Uplift TypeError
1 parent c74efbc commit 82ef3ad

File tree

16 files changed

+216
-193
lines changed

16 files changed

+216
-193
lines changed

compiler/rustc_hir_analysis/src/check/check.rs

+1
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

+3-2
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ use rustc_infer::infer::InferOk;
4040
use rustc_infer::traits::query::NoSolution;
4141
use rustc_infer::traits::ObligationCause;
4242
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
43-
use rustc_middle::ty::error::{ExpectedFound, TypeError::Sorts};
43+
use rustc_middle::ty::error::{ExpectedFound, TypeError};
4444
use rustc_middle::ty::GenericArgsRef;
4545
use rustc_middle::ty::{self, AdtKind, Ty, TypeVisitableExt};
4646
use rustc_middle::{bug, span_bug};
@@ -682,7 +682,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
682682
self.suggest_mismatched_types_on_tail(
683683
&mut err, expr, ty, e_ty, target_id,
684684
);
685-
let error = Some(Sorts(ExpectedFound { expected: ty, found: e_ty }));
685+
let error =
686+
Some(TypeError::Sorts(ExpectedFound { expected: ty, found: e_ty }));
686687
self.annotate_loop_expected_due_to_inference(err, expr, error);
687688
if let Some(val) =
688689
self.err_ctxt().ty_kind_suggestion(self.param_env, ty)

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

+1
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

+3-4
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

+1-1
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

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

+39-124
Original file line numberDiff line numberDiff line change
@@ -1,89 +1,26 @@
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-
Traits(ExpectedFound<DefId>),
53-
VariadicMismatch(ExpectedFound<bool>),
54-
55-
/// Instantiating a type variable with the given type would have
56-
/// created a cycle (because it appears somewhere within that
57-
/// type).
58-
CyclicTy(Ty<'tcx>),
59-
CyclicConst(ty::Const<'tcx>),
60-
ProjectionMismatched(ExpectedFound<DefId>),
61-
ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>),
62-
ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
63-
64-
IntrinsicCast,
65-
/// Safe `#[target_feature]` functions are not assignable to safe function pointers.
66-
TargetFeatureCast(DefId),
67-
}
68-
69-
impl TypeError<'_> {
70-
pub fn involves_regions(self) -> bool {
71-
match self {
72-
TypeError::RegionsDoesNotOutlive(_, _)
73-
| TypeError::RegionsInsufficientlyPolymorphic(_, _)
74-
| TypeError::RegionsPlaceholderMismatch => true,
75-
_ => false,
76-
}
77-
}
78-
}
14+
pub type TypeError<'tcx> = rustc_type_ir::error::TypeError<TyCtxt<'tcx>>;
7915

80-
/// Explains the source of a type err in a short, human readable way. This is meant to be placed
81-
/// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
82-
/// afterwards to present additional details, particularly when it comes to lifetime-related
83-
/// errors.
16+
/// Explains the source of a type err in a short, human readable way.
17+
/// This is meant to be placed in parentheses after some larger message.
18+
/// You should also invoke `note_and_explain_type_err()` afterwards
19+
/// to present additional details, particularly when it comes to lifetime-
20+
/// related errors.
21+
#[extension(pub trait TypeErrorToStringExt<'tcx>)]
8422
impl<'tcx> TypeError<'tcx> {
85-
pub fn to_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
86-
use self::TypeError::*;
23+
fn to_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
8724
fn report_maybe_different(expected: &str, found: &str) -> String {
8825
// A naive approach to making sure that we're not reporting silly errors such as:
8926
// (expected closure, found closure).
@@ -95,53 +32,56 @@ impl<'tcx> TypeError<'tcx> {
9532
}
9633

9734
match self {
98-
CyclicTy(_) => "cyclic type of infinite size".into(),
99-
CyclicConst(_) => "encountered a self-referencing constant".into(),
100-
Mismatch => "types differ".into(),
101-
ConstnessMismatch(values) => {
35+
TypeError::CyclicTy(_) => "cyclic type of infinite size".into(),
36+
TypeError::CyclicConst(_) => "encountered a self-referencing constant".into(),
37+
TypeError::Mismatch => "types differ".into(),
38+
TypeError::ConstnessMismatch(values) => {
10239
format!("expected {} bound, found {} bound", values.expected, values.found).into()
10340
}
104-
PolarityMismatch(values) => {
41+
TypeError::PolarityMismatch(values) => {
10542
format!("expected {} polarity, found {} polarity", values.expected, values.found)
10643
.into()
10744
}
108-
SafetyMismatch(values) => {
45+
TypeError::SafetyMismatch(values) => {
10946
format!("expected {} fn, found {} fn", values.expected, values.found).into()
11047
}
111-
AbiMismatch(values) => {
48+
TypeError::AbiMismatch(values) => {
11249
format!("expected {} fn, found {} fn", values.expected, values.found).into()
11350
}
114-
ArgumentMutability(_) | Mutability => "types differ in mutability".into(),
115-
TupleSize(values) => format!(
51+
TypeError::ArgumentMutability(_) | TypeError::Mutability => {
52+
"types differ in mutability".into()
53+
}
54+
TypeError::TupleSize(values) => format!(
11655
"expected a tuple with {} element{}, found one with {} element{}",
11756
values.expected,
11857
pluralize!(values.expected),
11958
values.found,
12059
pluralize!(values.found)
12160
)
12261
.into(),
123-
FixedArraySize(values) => format!(
62+
TypeError::FixedArraySize(values) => format!(
12463
"expected an array with a fixed size of {} element{}, found one with {} element{}",
12564
values.expected,
12665
pluralize!(values.expected),
12766
values.found,
12867
pluralize!(values.found)
12968
)
13069
.into(),
131-
ArgCount => "incorrect number of function parameters".into(),
132-
FieldMisMatch(adt, field) => format!("field type mismatch: {adt}.{field}").into(),
133-
RegionsDoesNotOutlive(..) => "lifetime mismatch".into(),
70+
TypeError::ArgCount => "incorrect number of function parameters".into(),
71+
TypeError::RegionsDoesNotOutlive(..) => "lifetime mismatch".into(),
13472
// Actually naming the region here is a bit confusing because context is lacking
135-
RegionsInsufficientlyPolymorphic(..) => {
73+
TypeError::RegionsInsufficientlyPolymorphic(..) => {
74+
"one type is more general than the other".into()
75+
}
76+
TypeError::RegionsPlaceholderMismatch => {
13677
"one type is more general than the other".into()
13778
}
138-
RegionsPlaceholderMismatch => "one type is more general than the other".into(),
139-
ArgumentSorts(values, _) | Sorts(values) => {
79+
TypeError::ArgumentSorts(values, _) | TypeError::Sorts(values) => {
14080
let expected = values.expected.sort_string(tcx);
14181
let found = values.found.sort_string(tcx);
14282
report_maybe_different(&expected, &found).into()
14383
}
144-
Traits(values) => {
84+
TypeError::Traits(values) => {
14585
let (mut expected, mut found) = with_forced_trimmed_paths!((
14686
tcx.def_path_str(values.expected),
14787
tcx.def_path_str(values.found),
@@ -153,59 +93,34 @@ impl<'tcx> TypeError<'tcx> {
15393
report_maybe_different(&format!("trait `{expected}`"), &format!("trait `{found}`"))
15494
.into()
15595
}
156-
VariadicMismatch(ref values) => format!(
96+
TypeError::VariadicMismatch(ref values) => format!(
15797
"expected {} fn, found {} function",
15898
if values.expected { "variadic" } else { "non-variadic" },
15999
if values.found { "variadic" } else { "non-variadic" }
160100
)
161101
.into(),
162-
ProjectionMismatched(ref values) => format!(
102+
TypeError::ProjectionMismatched(ref values) => format!(
163103
"expected `{}`, found `{}`",
164104
tcx.def_path_str(values.expected),
165105
tcx.def_path_str(values.found)
166106
)
167107
.into(),
168-
ExistentialMismatch(ref values) => report_maybe_different(
108+
TypeError::ExistentialMismatch(ref values) => report_maybe_different(
169109
&format!("trait `{}`", values.expected),
170110
&format!("trait `{}`", values.found),
171111
)
172112
.into(),
173-
ConstMismatch(ref values) => {
113+
TypeError::ConstMismatch(ref values) => {
174114
format!("expected `{}`, found `{}`", values.expected, values.found).into()
175115
}
176-
IntrinsicCast => "cannot coerce intrinsics to function pointers".into(),
177-
TargetFeatureCast(_) => {
116+
TypeError::IntrinsicCast => "cannot coerce intrinsics to function pointers".into(),
117+
TypeError::TargetFeatureCast(_) => {
178118
"cannot coerce functions with `#[target_feature]` to safe function pointers".into()
179119
}
180120
}
181121
}
182122
}
183123

184-
impl<'tcx> TypeError<'tcx> {
185-
pub fn must_include_note(self) -> bool {
186-
use self::TypeError::*;
187-
match self {
188-
CyclicTy(_) | CyclicConst(_) | SafetyMismatch(_) | ConstnessMismatch(_)
189-
| PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
190-
| ArgumentSorts(..) | Sorts(_) | VariadicMismatch(_) | TargetFeatureCast(_) => false,
191-
192-
Mutability
193-
| ArgumentMutability(_)
194-
| TupleSize(_)
195-
| ArgCount
196-
| FieldMisMatch(..)
197-
| RegionsDoesNotOutlive(..)
198-
| RegionsInsufficientlyPolymorphic(..)
199-
| RegionsPlaceholderMismatch
200-
| Traits(_)
201-
| ProjectionMismatched(_)
202-
| ExistentialMismatch(_)
203-
| ConstMismatch(_)
204-
| IntrinsicCast => true,
205-
}
206-
}
207-
}
208-
209124
impl<'tcx> Ty<'tcx> {
210125
pub fn sort_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
211126
match *self.kind() {

compiler/rustc_middle/src/ty/mod.rs

-32
Original file line numberDiff line numberDiff line change
@@ -313,38 +313,6 @@ impl Visibility {
313313
}
314314
}
315315

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

0 commit comments

Comments
 (0)