Skip to main content

rustc_middle/ty/
error.rs

1use std::borrow::Cow;
2use std::fs::File;
3use std::hash::{DefaultHasher, Hash, Hasher};
4use std::io::{Read, Write};
5use std::path::PathBuf;
6
7use rustc_errors::pluralize;
8use rustc_hir as hir;
9use rustc_hir::def::{CtorOf, DefKind};
10use rustc_hir::limit::Limit;
11use rustc_macros::extension;
12pub use rustc_type_ir::error::ExpectedFound;
13
14use crate::ty::print::{FmtPrinter, Print, with_forced_trimmed_paths};
15use crate::ty::{self, Ty, TyCtxt};
16
17pub type TypeError<'tcx> = rustc_type_ir::error::TypeError<TyCtxt<'tcx>>;
18
19/// Explains the source of a type err in a short, human readable way.
20/// This is meant to be placed in parentheses after some larger message.
21/// You should also invoke `note_and_explain_type_err()` afterwards
22/// to present additional details, particularly when it comes to lifetime-
23/// related errors.
24impl<'tcx> TypeErrorToStringExt<'tcx> for TypeError<'tcx> {
    fn to_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
        fn report_maybe_different(expected: &str, found: &str) -> String {
            if expected == found {
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected {0}, found a different {1}",
                                expected, found))
                    })
            } else {
                ::alloc::__export::must_use({
                        ::alloc::fmt::format(format_args!("expected {0}, found {1}",
                                expected, found))
                    })
            }
        }
        match self {
            TypeError::CyclicTy(_) =>
                "recursive type with infinite-size name".into(),
            TypeError::CyclicConst(_) =>
                "encountered a self-referencing constant".into(),
            TypeError::Mismatch => "types differ".into(),
            TypeError::PolarityMismatch(values) => {
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected {0} polarity, found {1} polarity",
                                    values.expected, values.found))
                        }).into()
            }
            TypeError::SafetyMismatch(values) => {
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected {0} fn, found {1} fn",
                                    values.expected, values.found))
                        }).into()
            }
            TypeError::AbiMismatch(values) => {
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected {0} fn, found {1} fn",
                                    values.expected, values.found))
                        }).into()
            }
            TypeError::ArgumentMutability(_) | TypeError::Mutability => {
                "types differ in mutability".into()
            }
            TypeError::TupleSize(values) =>
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected a tuple with {0} element{1}, found one with {2} element{3}",
                                    values.expected,
                                    if values.expected == 1 { "" } else { "s" }, values.found,
                                    if values.found == 1 { "" } else { "s" }))
                        }).into(),
            TypeError::ArraySize(values) =>
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected an array with a size of {0}, found one with a size of {1}",
                                    values.expected, values.found))
                        }).into(),
            TypeError::ArgCount =>
                "incorrect number of function parameters".into(),
            TypeError::RegionsDoesNotOutlive(..) =>
                "lifetime mismatch".into(),
            TypeError::RegionsInsufficientlyPolymorphic(..) => {
                "one type is more general than the other".into()
            }
            TypeError::RegionsPlaceholderMismatch => {
                "one type is more general than the other".into()
            }
            TypeError::ArgumentSorts(values, _) | TypeError::Sorts(values) =>
                {
                let expected = values.expected.sort_string(tcx);
                let found = values.found.sort_string(tcx);
                report_maybe_different(&expected, &found).into()
            }
            TypeError::Traits(values) => {
                let (mut expected, mut found) =
                    {
                        let _guard = ForceTrimmedGuard::new();
                        (tcx.def_path_str(values.expected),
                            tcx.def_path_str(values.found))
                    };
                if expected == found {
                    expected = tcx.def_path_str(values.expected);
                    found = tcx.def_path_str(values.found);
                }
                report_maybe_different(&::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("trait `{0}`", expected))
                                }),
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("trait `{0}`", found))
                                })).into()
            }
            TypeError::VariadicMismatch(ref values) =>
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected {0} fn, found {1} function",
                                    if values.expected { "variadic" } else { "non-variadic" },
                                    if values.found { "variadic" } else { "non-variadic" }))
                        }).into(),
            TypeError::SplatMismatch(ref values) =>
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected fn with {0}, found fn with {1}",
                                    if let Some(index) = values.expected {
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("arg {0} splatted",
                                                        index))
                                            })
                                    } else { "no splatted arg".to_string() },
                                    if let Some(index) = values.found {
                                        ::alloc::__export::must_use({
                                                ::alloc::fmt::format(format_args!("arg {0} splatted",
                                                        index))
                                            })
                                    } else { "no splatted arg".to_string() }))
                        }).into(),
            TypeError::ProjectionMismatched(ref values) =>
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected `{0}`, found `{1}`",
                                    tcx.alias_term_kind_def_path_str(values.expected),
                                    tcx.alias_term_kind_def_path_str(values.found)))
                        }).into(),
            TypeError::ExistentialMismatch(ref values) =>
                report_maybe_different(&::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("trait `{0}`",
                                            values.expected))
                                }),
                        &::alloc::__export::must_use({
                                    ::alloc::fmt::format(format_args!("trait `{0}`",
                                            values.found))
                                })).into(),
            TypeError::ConstMismatch(ref values) => {
                ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("expected `{0}`, found `{1}`",
                                    values.expected, values.found))
                        }).into()
            }
            TypeError::ForceInlineCast => {
                "cannot coerce functions which must be inlined to function pointers".into()
            }
            TypeError::IntrinsicCast =>
                "cannot coerce intrinsics to function pointers".into(),
            TypeError::TargetFeatureCast(_) => {
                "cannot coerce functions with `#[target_feature]` to safe function pointers".into()
            }
        }
    }
}#[extension(pub trait TypeErrorToStringExt<'tcx>)]
25impl<'tcx> TypeError<'tcx> {
26    fn to_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
27        fn report_maybe_different(expected: &str, found: &str) -> String {
28            // A naive approach to making sure that we're not reporting silly errors such as:
29            // (expected closure, found closure).
30            if expected == found {
31                format!("expected {expected}, found a different {found}")
32            } else {
33                format!("expected {expected}, found {found}")
34            }
35        }
36
37        match self {
38            TypeError::CyclicTy(_) => "recursive type with infinite-size name".into(),
39            TypeError::CyclicConst(_) => "encountered a self-referencing constant".into(),
40            TypeError::Mismatch => "types differ".into(),
41            TypeError::PolarityMismatch(values) => {
42                format!("expected {} polarity, found {} polarity", values.expected, values.found)
43                    .into()
44            }
45            TypeError::SafetyMismatch(values) => {
46                format!("expected {} fn, found {} fn", values.expected, values.found).into()
47            }
48            TypeError::AbiMismatch(values) => {
49                format!("expected {} fn, found {} fn", values.expected, values.found).into()
50            }
51            TypeError::ArgumentMutability(_) | TypeError::Mutability => {
52                "types differ in mutability".into()
53            }
54            TypeError::TupleSize(values) => format!(
55                "expected a tuple with {} element{}, found one with {} element{}",
56                values.expected,
57                pluralize!(values.expected),
58                values.found,
59                pluralize!(values.found)
60            )
61            .into(),
62            TypeError::ArraySize(values) => format!(
63                "expected an array with a size of {}, found one with a size of {}",
64                values.expected, values.found,
65            )
66            .into(),
67            TypeError::ArgCount => "incorrect number of function parameters".into(),
68            TypeError::RegionsDoesNotOutlive(..) => "lifetime mismatch".into(),
69            // Actually naming the region here is a bit confusing because context is lacking
70            TypeError::RegionsInsufficientlyPolymorphic(..) => {
71                "one type is more general than the other".into()
72            }
73            TypeError::RegionsPlaceholderMismatch => {
74                "one type is more general than the other".into()
75            }
76            TypeError::ArgumentSorts(values, _) | TypeError::Sorts(values) => {
77                let expected = values.expected.sort_string(tcx);
78                let found = values.found.sort_string(tcx);
79                report_maybe_different(&expected, &found).into()
80            }
81            TypeError::Traits(values) => {
82                let (mut expected, mut found) = with_forced_trimmed_paths!((
83                    tcx.def_path_str(values.expected),
84                    tcx.def_path_str(values.found),
85                ));
86                if expected == found {
87                    expected = tcx.def_path_str(values.expected);
88                    found = tcx.def_path_str(values.found);
89                }
90                report_maybe_different(&format!("trait `{expected}`"), &format!("trait `{found}`"))
91                    .into()
92            }
93            TypeError::VariadicMismatch(ref values) => format!(
94                "expected {} fn, found {} function",
95                if values.expected { "variadic" } else { "non-variadic" },
96                if values.found { "variadic" } else { "non-variadic" }
97            )
98            .into(),
99            TypeError::SplatMismatch(ref values) => format!(
100                "expected fn with {}, found fn with {}",
101                if let Some(index) = values.expected {
102                    format!("arg {index} splatted")
103                } else {
104                    "no splatted arg".to_string()
105                },
106                if let Some(index) = values.found {
107                    format!("arg {index} splatted")
108                } else {
109                    "no splatted arg".to_string()
110                }
111            )
112            .into(),
113            TypeError::ProjectionMismatched(ref values) => format!(
114                "expected `{}`, found `{}`",
115                tcx.alias_term_kind_def_path_str(values.expected),
116                tcx.alias_term_kind_def_path_str(values.found)
117            )
118            .into(),
119            TypeError::ExistentialMismatch(ref values) => report_maybe_different(
120                &format!("trait `{}`", values.expected),
121                &format!("trait `{}`", values.found),
122            )
123            .into(),
124            TypeError::ConstMismatch(ref values) => {
125                format!("expected `{}`, found `{}`", values.expected, values.found).into()
126            }
127            TypeError::ForceInlineCast => {
128                "cannot coerce functions which must be inlined to function pointers".into()
129            }
130            TypeError::IntrinsicCast => "cannot coerce intrinsics to function pointers".into(),
131            TypeError::TargetFeatureCast(_) => {
132                "cannot coerce functions with `#[target_feature]` to safe function pointers".into()
133            }
134        }
135    }
136}
137
138impl<'tcx> Ty<'tcx> {
139    pub fn sort_string(self, tcx: TyCtxt<'tcx>) -> Cow<'static, str> {
140        match *self.kind() {
141            ty::Foreign(def_id) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("extern type `{0}`",
                tcx.def_path_str(def_id)))
    })format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
142            ty::FnDef(def_id, ..) => match tcx.def_kind(def_id) {
143                DefKind::Ctor(CtorOf::Struct, _) => "struct constructor".into(),
144                DefKind::Ctor(CtorOf::Variant, _) => "enum constructor".into(),
145                _ => "fn item".into(),
146            },
147            ty::FnPtr(..) => "fn pointer".into(),
148            ty::Dynamic(inner, ..) if let Some(principal) = inner.principal() => {
149                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`dyn {0}`",
                tcx.def_path_str(principal.def_id())))
    })format!("`dyn {}`", tcx.def_path_str(principal.def_id())).into()
150            }
151            ty::Dynamic(..) => "trait object".into(),
152            ty::Closure(..) => "closure".into(),
153            ty::Coroutine(def_id, ..) => {
154                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:#}",
                tcx.coroutine_kind(def_id).unwrap()))
    })format!("{:#}", tcx.coroutine_kind(def_id).unwrap()).into()
155            }
156            ty::CoroutineWitness(..) => "coroutine witness".into(),
157            ty::Infer(ty::TyVar(_)) => "inferred type".into(),
158            ty::Infer(ty::IntVar(_)) => "integer".into(),
159            ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
160            ty::Placeholder(..) => "placeholder type".into(),
161            ty::Bound(..) => "bound type".into(),
162            ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
163            ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
164            ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
165            ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. }) => {
166                "associated type".into()
167            }
168            ty::Param(p) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type parameter `{0}`", p))
    })format!("type parameter `{p}`").into(),
169            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => {
170                if tcx.ty_is_opaque_future(self) { "future".into() } else { "opaque type".into() }
171            }
172            ty::Error(_) => "type error".into(),
173            _ => {
174                let width = tcx.sess.diagnostic_width();
175                let length_limit = std::cmp::max(width / 4, 40);
176                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`",
                tcx.string_with_limit(self, length_limit,
                    hir::def::Namespace::TypeNS)))
    })format!(
177                    "`{}`",
178                    tcx.string_with_limit(self, length_limit, hir::def::Namespace::TypeNS)
179                )
180                .into()
181            }
182        }
183    }
184
185    pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
186        match *self.kind() {
187            ty::Infer(_)
188            | ty::Error(_)
189            | ty::Bool
190            | ty::Char
191            | ty::Int(_)
192            | ty::Uint(_)
193            | ty::Float(_)
194            | ty::Str
195            | ty::Never => "type".into(),
196            ty::Tuple(tys) if tys.is_empty() => "unit type".into(),
197            ty::Adt(def, _) => def.descr().into(),
198            ty::Foreign(_) => "extern type".into(),
199            ty::Array(..) => "array".into(),
200            ty::Pat(..) => "pattern type".into(),
201            ty::Slice(_) => "slice".into(),
202            ty::RawPtr(_, _) => "raw pointer".into(),
203            ty::Ref(.., mutbl) => match mutbl {
204                hir::Mutability::Mut => "mutable reference",
205                _ => "reference",
206            }
207            .into(),
208            ty::FnDef(def_id, ..) => match tcx.def_kind(def_id) {
209                DefKind::Ctor(CtorOf::Struct, _) => "struct constructor".into(),
210                DefKind::Ctor(CtorOf::Variant, _) => "enum constructor".into(),
211                _ => "fn item".into(),
212            },
213            ty::FnPtr(..) => "fn pointer".into(),
214            ty::UnsafeBinder(_) => "unsafe binder".into(),
215            ty::Dynamic(..) => "trait object".into(),
216            ty::Closure(..) | ty::CoroutineClosure(..) => "closure".into(),
217            ty::Coroutine(def_id, ..) => {
218                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:#}",
                tcx.coroutine_kind(def_id).unwrap()))
    })format!("{:#}", tcx.coroutine_kind(def_id).unwrap()).into()
219            }
220            ty::CoroutineWitness(..) => "coroutine witness".into(),
221            ty::Tuple(..) => "tuple".into(),
222            ty::Placeholder(..) => "higher-ranked type".into(),
223            ty::Bound(..) => "bound type variable".into(),
224            ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. } | ty::Inherent { .. }, .. }) => {
225                "associated type".into()
226            }
227            ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => "type alias".into(),
228            ty::Param(_) => "type parameter".into(),
229            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => "opaque type".into(),
230        }
231    }
232}
233
234impl<'tcx> TyCtxt<'tcx> {
235    pub fn string_with_limit<T>(self, t: T, length_limit: usize, ns: hir::def::Namespace) -> String
236    where
237        T: Copy + for<'a> Print<FmtPrinter<'a, 'tcx>>,
238    {
239        let mut type_limit = 50;
240        let regular = FmtPrinter::print_string(self, ns, |p| t.print(p))
241            .expect("could not write to `String`");
242        if regular.len() <= length_limit {
243            return regular;
244        }
245        let mut short;
246        loop {
247            // Look for the longest properly trimmed path that still fits in length_limit.
248            short = {
    let _guard = ForceTrimmedGuard::new();
    {
        let mut p = FmtPrinter::new_with_limit(self, ns, Limit(type_limit));
        t.print(&mut p).expect("could not print type");
        p.into_buffer()
    }
}with_forced_trimmed_paths!({
249                let mut p = FmtPrinter::new_with_limit(self, ns, Limit(type_limit));
250                t.print(&mut p).expect("could not print type");
251                p.into_buffer()
252            });
253            if short.len() <= length_limit || type_limit == 0 {
254                break;
255            }
256            type_limit -= 1;
257        }
258        short
259    }
260
261    /// When calling this after a `Diag` is constructed, the preferred way of doing so is
262    /// `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that keeps
263    /// the existence of a "long type" anywhere in the diagnostic, so the note telling the user
264    /// where we wrote the file to is only printed once. The path will use the type namespace.
265    pub fn short_string<T>(self, t: T, path: &mut Option<PathBuf>) -> String
266    where
267        T: Copy + Hash + for<'a> Print<FmtPrinter<'a, 'tcx>>,
268    {
269        self.short_string_namespace(t, path, hir::def::Namespace::TypeNS)
270    }
271
272    /// When calling this after a `Diag` is constructed, the preferred way of doing so is
273    /// `tcx.short_string(ty, diag.long_ty_path())`. The diagnostic itself is the one that keeps
274    /// the existence of a "long type" anywhere in the diagnostic, so the note telling the user
275    /// where we wrote the file to is only printed once.
276    pub fn short_string_namespace<T>(
277        self,
278        t: T,
279        path: &mut Option<PathBuf>,
280        namespace: hir::def::Namespace,
281    ) -> String
282    where
283        T: Copy + Hash + for<'a> Print<FmtPrinter<'a, 'tcx>>,
284    {
285        let regular = FmtPrinter::print_string(self, namespace, |p| t.print(p))
286            .expect("could not write to `String`");
287
288        if !self.sess.opts.unstable_opts.write_long_types_to_disk || self.sess.opts.verbose {
289            return regular;
290        }
291
292        let width = self.sess.diagnostic_width();
293        let length_limit = width / 2;
294        if regular.len() <= width * 2 / 3 {
295            return regular;
296        }
297        let short = self.string_with_limit(t, length_limit, namespace);
298        if regular == short {
299            return regular;
300        }
301        // Ensure we create an unique file for the type passed in when we create a file.
302        let mut s = DefaultHasher::new();
303        t.hash(&mut s);
304        let hash = s.finish();
305        *path = Some(path.take().unwrap_or_else(|| {
306            self.output_filenames(()).temp_path_for_diagnostic(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("long-type-{0}.txt", hash))
    })format!("long-type-{hash}.txt"))
307        }));
308        let Ok(mut file) =
309            File::options().create(true).read(true).append(true).open(&path.as_ref().unwrap())
310        else {
311            return regular;
312        };
313
314        // Do not write the same type to the file multiple times.
315        let mut contents = String::new();
316        let _ = file.read_to_string(&mut contents);
317        if let Some(_) = contents.lines().find(|line| line == &regular) {
318            return short;
319        }
320
321        match file.write_fmt(format_args!("{0}\n", regular))write!(file, "{regular}\n") {
322            Ok(_) => short,
323            Err(_) => regular,
324        }
325    }
326
327    pub fn alias_term_kind_def_path_str(self, alias: ty::AliasTermKind<'tcx>) -> String {
328        match alias {
329            ty::AliasTermKind::ProjectionTy { def_id }
330            | ty::AliasTermKind::InherentTy { def_id }
331            | ty::AliasTermKind::OpaqueTy { def_id }
332            | ty::AliasTermKind::FreeTy { def_id }
333            | ty::AliasTermKind::AnonConst { def_id }
334            | ty::AliasTermKind::ProjectionConst { def_id }
335            | ty::AliasTermKind::FreeConst { def_id }
336            | ty::AliasTermKind::InherentConst { def_id } => self.def_path_str(def_id),
337        }
338    }
339}