]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/ty/error.rs
Rollup merge of #103488 - oli-obk:impl_trait_for_tait, r=lcnr
[rust.git] / compiler / rustc_middle / src / ty / error.rs
1 use crate::traits::{ObligationCause, ObligationCauseCode};
2 use crate::ty::diagnostics::suggest_constraining_type_param;
3 use crate::ty::print::{FmtPrinter, Printer};
4 use crate::ty::{self, BoundRegionKind, Region, Ty, TyCtxt};
5 use hir::def::DefKind;
6 use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
7 use rustc_errors::{pluralize, Diagnostic, MultiSpan};
8 use rustc_hir as hir;
9 use rustc_hir::def_id::DefId;
10 use rustc_span::symbol::{sym, Symbol};
11 use rustc_span::{BytePos, Span};
12 use rustc_target::spec::abi;
13
14 use std::borrow::Cow;
15 use std::collections::hash_map::DefaultHasher;
16 use std::fmt;
17 use std::hash::{Hash, Hasher};
18 use std::path::PathBuf;
19
20 use super::print::PrettyPrinter;
21
22 #[derive(Clone, Copy, Debug, PartialEq, Eq, TypeFoldable, TypeVisitable, Lift)]
23 pub struct ExpectedFound<T> {
24     pub expected: T,
25     pub found: T,
26 }
27
28 impl<T> ExpectedFound<T> {
29     pub fn new(a_is_expected: bool, a: T, b: T) -> Self {
30         if a_is_expected {
31             ExpectedFound { expected: a, found: b }
32         } else {
33             ExpectedFound { expected: b, found: a }
34         }
35     }
36 }
37
38 // Data structures used in type unification
39 #[derive(Copy, Clone, Debug, TypeFoldable, TypeVisitable, Lift)]
40 #[rustc_pass_by_value]
41 pub enum TypeError<'tcx> {
42     Mismatch,
43     ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
44     PolarityMismatch(ExpectedFound<ty::ImplPolarity>),
45     UnsafetyMismatch(ExpectedFound<hir::Unsafety>),
46     AbiMismatch(ExpectedFound<abi::Abi>),
47     Mutability,
48     ArgumentMutability(usize),
49     TupleSize(ExpectedFound<usize>),
50     FixedArraySize(ExpectedFound<u64>),
51     ArgCount,
52     FieldMisMatch(Symbol, Symbol),
53
54     RegionsDoesNotOutlive(Region<'tcx>, Region<'tcx>),
55     RegionsInsufficientlyPolymorphic(BoundRegionKind, Region<'tcx>),
56     RegionsOverlyPolymorphic(BoundRegionKind, Region<'tcx>),
57     RegionsPlaceholderMismatch,
58
59     Sorts(ExpectedFound<Ty<'tcx>>),
60     ArgumentSorts(ExpectedFound<Ty<'tcx>>, usize),
61     IntMismatch(ExpectedFound<ty::IntVarValue>),
62     FloatMismatch(ExpectedFound<ty::FloatTy>),
63     Traits(ExpectedFound<DefId>),
64     VariadicMismatch(ExpectedFound<bool>),
65
66     /// Instantiating a type variable with the given type would have
67     /// created a cycle (because it appears somewhere within that
68     /// type).
69     CyclicTy(Ty<'tcx>),
70     CyclicConst(ty::Const<'tcx>),
71     ProjectionMismatched(ExpectedFound<DefId>),
72     ExistentialMismatch(ExpectedFound<&'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>>),
73     ObjectUnsafeCoercion(DefId),
74     ConstMismatch(ExpectedFound<ty::Const<'tcx>>),
75
76     IntrinsicCast,
77     /// Safe `#[target_feature]` functions are not assignable to safe function pointers.
78     TargetFeatureCast(DefId),
79 }
80
81 impl TypeError<'_> {
82     pub fn involves_regions(self) -> bool {
83         match self {
84             TypeError::RegionsDoesNotOutlive(_, _)
85             | TypeError::RegionsInsufficientlyPolymorphic(_, _)
86             | TypeError::RegionsOverlyPolymorphic(_, _)
87             | TypeError::RegionsPlaceholderMismatch => true,
88             _ => false,
89         }
90     }
91 }
92
93 /// Explains the source of a type err in a short, human readable way. This is meant to be placed
94 /// in parentheses after some larger message. You should also invoke `note_and_explain_type_err()`
95 /// afterwards to present additional details, particularly when it comes to lifetime-related
96 /// errors.
97 impl<'tcx> fmt::Display for TypeError<'tcx> {
98     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99         use self::TypeError::*;
100         fn report_maybe_different(
101             f: &mut fmt::Formatter<'_>,
102             expected: &str,
103             found: &str,
104         ) -> fmt::Result {
105             // A naive approach to making sure that we're not reporting silly errors such as:
106             // (expected closure, found closure).
107             if expected == found {
108                 write!(f, "expected {}, found a different {}", expected, found)
109             } else {
110                 write!(f, "expected {}, found {}", expected, found)
111             }
112         }
113
114         let br_string = |br: ty::BoundRegionKind| match br {
115             ty::BrNamed(_, name) => format!(" {}", name),
116             _ => String::new(),
117         };
118
119         match *self {
120             CyclicTy(_) => write!(f, "cyclic type of infinite size"),
121             CyclicConst(_) => write!(f, "encountered a self-referencing constant"),
122             Mismatch => write!(f, "types differ"),
123             ConstnessMismatch(values) => {
124                 write!(f, "expected {} bound, found {} bound", values.expected, values.found)
125             }
126             PolarityMismatch(values) => {
127                 write!(f, "expected {} polarity, found {} polarity", values.expected, values.found)
128             }
129             UnsafetyMismatch(values) => {
130                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
131             }
132             AbiMismatch(values) => {
133                 write!(f, "expected {} fn, found {} fn", values.expected, values.found)
134             }
135             ArgumentMutability(_) | Mutability => write!(f, "types differ in mutability"),
136             TupleSize(values) => write!(
137                 f,
138                 "expected a tuple with {} element{}, found one with {} element{}",
139                 values.expected,
140                 pluralize!(values.expected),
141                 values.found,
142                 pluralize!(values.found)
143             ),
144             FixedArraySize(values) => write!(
145                 f,
146                 "expected an array with a fixed size of {} element{}, found one with {} element{}",
147                 values.expected,
148                 pluralize!(values.expected),
149                 values.found,
150                 pluralize!(values.found)
151             ),
152             ArgCount => write!(f, "incorrect number of function parameters"),
153             FieldMisMatch(adt, field) => write!(f, "field type mismatch: {}.{}", adt, field),
154             RegionsDoesNotOutlive(..) => write!(f, "lifetime mismatch"),
155             // Actually naming the region here is a bit confusing because context is lacking
156             RegionsInsufficientlyPolymorphic(..) => {
157                 write!(f, "one type is more general than the other")
158             }
159             RegionsOverlyPolymorphic(br, _) => write!(
160                 f,
161                 "expected concrete lifetime, found bound lifetime parameter{}",
162                 br_string(br)
163             ),
164             RegionsPlaceholderMismatch => write!(f, "one type is more general than the other"),
165             ArgumentSorts(values, _) | Sorts(values) => ty::tls::with(|tcx| {
166                 report_maybe_different(
167                     f,
168                     &values.expected.sort_string(tcx),
169                     &values.found.sort_string(tcx),
170                 )
171             }),
172             Traits(values) => ty::tls::with(|tcx| {
173                 report_maybe_different(
174                     f,
175                     &format!("trait `{}`", tcx.def_path_str(values.expected)),
176                     &format!("trait `{}`", tcx.def_path_str(values.found)),
177                 )
178             }),
179             IntMismatch(ref values) => {
180                 let expected = match values.expected {
181                     ty::IntVarValue::IntType(ty) => ty.name_str(),
182                     ty::IntVarValue::UintType(ty) => ty.name_str(),
183                 };
184                 let found = match values.found {
185                     ty::IntVarValue::IntType(ty) => ty.name_str(),
186                     ty::IntVarValue::UintType(ty) => ty.name_str(),
187                 };
188                 write!(f, "expected `{}`, found `{}`", expected, found)
189             }
190             FloatMismatch(ref values) => {
191                 write!(
192                     f,
193                     "expected `{}`, found `{}`",
194                     values.expected.name_str(),
195                     values.found.name_str()
196                 )
197             }
198             VariadicMismatch(ref values) => write!(
199                 f,
200                 "expected {} fn, found {} function",
201                 if values.expected { "variadic" } else { "non-variadic" },
202                 if values.found { "variadic" } else { "non-variadic" }
203             ),
204             ProjectionMismatched(ref values) => ty::tls::with(|tcx| {
205                 write!(
206                     f,
207                     "expected {}, found {}",
208                     tcx.def_path_str(values.expected),
209                     tcx.def_path_str(values.found)
210                 )
211             }),
212             ExistentialMismatch(ref values) => report_maybe_different(
213                 f,
214                 &format!("trait `{}`", values.expected),
215                 &format!("trait `{}`", values.found),
216             ),
217             ConstMismatch(ref values) => {
218                 write!(f, "expected `{}`, found `{}`", values.expected, values.found)
219             }
220             IntrinsicCast => write!(f, "cannot coerce intrinsics to function pointers"),
221             TargetFeatureCast(_) => write!(
222                 f,
223                 "cannot coerce functions with `#[target_feature]` to safe function pointers"
224             ),
225             ObjectUnsafeCoercion(_) => write!(f, "coercion to object-unsafe trait object"),
226         }
227     }
228 }
229
230 impl<'tcx> TypeError<'tcx> {
231     pub fn must_include_note(self) -> bool {
232         use self::TypeError::*;
233         match self {
234             CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_)
235             | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
236             | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
237             | VariadicMismatch(_) | TargetFeatureCast(_) => false,
238
239             Mutability
240             | ArgumentMutability(_)
241             | TupleSize(_)
242             | ArgCount
243             | FieldMisMatch(..)
244             | RegionsDoesNotOutlive(..)
245             | RegionsInsufficientlyPolymorphic(..)
246             | RegionsOverlyPolymorphic(..)
247             | RegionsPlaceholderMismatch
248             | Traits(_)
249             | ProjectionMismatched(_)
250             | ExistentialMismatch(_)
251             | ConstMismatch(_)
252             | IntrinsicCast
253             | ObjectUnsafeCoercion(_) => true,
254         }
255     }
256 }
257
258 impl<'tcx> Ty<'tcx> {
259     pub fn sort_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
260         match *self.kind() {
261             ty::Bool | ty::Char | ty::Int(_) | ty::Uint(_) | ty::Float(_) | ty::Str | ty::Never => {
262                 format!("`{}`", self).into()
263             }
264             ty::Tuple(ref tys) if tys.is_empty() => format!("`{}`", self).into(),
265
266             ty::Adt(def, _) => format!("{} `{}`", def.descr(), tcx.def_path_str(def.did())).into(),
267             ty::Foreign(def_id) => format!("extern type `{}`", tcx.def_path_str(def_id)).into(),
268             ty::Array(t, n) => {
269                 if t.is_simple_ty() {
270                     return format!("array `{}`", self).into();
271                 }
272
273                 let n = tcx.lift(n).unwrap();
274                 if let ty::ConstKind::Value(v) = n.kind() {
275                     if let Some(n) = v.try_to_machine_usize(tcx) {
276                         return format!("array of {} element{}", n, pluralize!(n)).into();
277                     }
278                 }
279                 "array".into()
280             }
281             ty::Slice(ty) if ty.is_simple_ty() => format!("slice `{}`", self).into(),
282             ty::Slice(_) => "slice".into(),
283             ty::RawPtr(tymut) => {
284                 let tymut_string = match tymut.mutbl {
285                     hir::Mutability::Mut => tymut.to_string(),
286                     hir::Mutability::Not => format!("const {}", tymut.ty),
287                 };
288
289                 if tymut_string != "_" && (tymut.ty.is_simple_text() || tymut_string.len() < "const raw pointer".len()) {
290                     format!("`*{}`", tymut_string).into()
291                 } else {
292                     // Unknown type name, it's long or has type arguments
293                     "raw pointer".into()
294                 }
295             },
296             ty::Ref(_, ty, mutbl) => {
297                 let tymut = ty::TypeAndMut { ty, mutbl };
298                 let tymut_string = tymut.to_string();
299
300                 if tymut_string != "_"
301                     && (ty.is_simple_text() || tymut_string.len() < "mutable reference".len())
302                 {
303                     format!("`&{}`", tymut_string).into()
304                 } else {
305                     // Unknown type name, it's long or has type arguments
306                     match mutbl {
307                         hir::Mutability::Mut => "mutable reference",
308                         _ => "reference",
309                     }
310                     .into()
311                 }
312             }
313             ty::FnDef(..) => "fn item".into(),
314             ty::FnPtr(_) => "fn pointer".into(),
315             ty::Dynamic(ref inner, ..) if let Some(principal) = inner.principal() => {
316                 format!("trait object `dyn {}`", tcx.def_path_str(principal.def_id())).into()
317             }
318             ty::Dynamic(..) => "trait object".into(),
319             ty::Closure(..) => "closure".into(),
320             ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
321             ty::GeneratorWitness(..) => "generator witness".into(),
322             ty::Tuple(..) => "tuple".into(),
323             ty::Infer(ty::TyVar(_)) => "inferred type".into(),
324             ty::Infer(ty::IntVar(_)) => "integer".into(),
325             ty::Infer(ty::FloatVar(_)) => "floating-point number".into(),
326             ty::Placeholder(..) => "placeholder type".into(),
327             ty::Bound(..) => "bound type".into(),
328             ty::Infer(ty::FreshTy(_)) => "fresh type".into(),
329             ty::Infer(ty::FreshIntTy(_)) => "fresh integral type".into(),
330             ty::Infer(ty::FreshFloatTy(_)) => "fresh floating-point type".into(),
331             ty::Projection(_) => "associated type".into(),
332             ty::Param(p) => format!("type parameter `{}`", p).into(),
333             ty::Opaque(..) => "opaque type".into(),
334             ty::Error(_) => "type error".into(),
335         }
336     }
337
338     pub fn prefix_string(self, tcx: TyCtxt<'_>) -> Cow<'static, str> {
339         match *self.kind() {
340             ty::Infer(_)
341             | ty::Error(_)
342             | ty::Bool
343             | ty::Char
344             | ty::Int(_)
345             | ty::Uint(_)
346             | ty::Float(_)
347             | ty::Str
348             | ty::Never => "type".into(),
349             ty::Tuple(ref tys) if tys.is_empty() => "unit type".into(),
350             ty::Adt(def, _) => def.descr().into(),
351             ty::Foreign(_) => "extern type".into(),
352             ty::Array(..) => "array".into(),
353             ty::Slice(_) => "slice".into(),
354             ty::RawPtr(_) => "raw pointer".into(),
355             ty::Ref(.., mutbl) => match mutbl {
356                 hir::Mutability::Mut => "mutable reference",
357                 _ => "reference",
358             }
359             .into(),
360             ty::FnDef(..) => "fn item".into(),
361             ty::FnPtr(_) => "fn pointer".into(),
362             ty::Dynamic(..) => "trait object".into(),
363             ty::Closure(..) => "closure".into(),
364             ty::Generator(def_id, ..) => tcx.generator_kind(def_id).unwrap().descr().into(),
365             ty::GeneratorWitness(..) => "generator witness".into(),
366             ty::Tuple(..) => "tuple".into(),
367             ty::Placeholder(..) => "higher-ranked type".into(),
368             ty::Bound(..) => "bound type variable".into(),
369             ty::Projection(_) => "associated type".into(),
370             ty::Param(_) => "type parameter".into(),
371             ty::Opaque(..) => "opaque type".into(),
372         }
373     }
374 }
375
376 impl<'tcx> TyCtxt<'tcx> {
377     pub fn note_and_explain_type_err(
378         self,
379         diag: &mut Diagnostic,
380         err: TypeError<'tcx>,
381         cause: &ObligationCause<'tcx>,
382         sp: Span,
383         body_owner_def_id: DefId,
384     ) {
385         use self::TypeError::*;
386         debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
387         match err {
388             ArgumentSorts(values, _) | Sorts(values) => {
389                 match (values.expected.kind(), values.found.kind()) {
390                     (ty::Closure(..), ty::Closure(..)) => {
391                         diag.note("no two closures, even if identical, have the same type");
392                         diag.help("consider boxing your closure and/or using it as a trait object");
393                     }
394                     (ty::Opaque(..), ty::Opaque(..)) => {
395                         // Issue #63167
396                         diag.note("distinct uses of `impl Trait` result in different opaque types");
397                     }
398                     (ty::Float(_), ty::Infer(ty::IntVar(_)))
399                         if let Ok(
400                             // Issue #53280
401                             snippet,
402                         ) = self.sess.source_map().span_to_snippet(sp) =>
403                     {
404                         if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
405                             diag.span_suggestion(
406                                 sp,
407                                 "use a float literal",
408                                 format!("{}.0", snippet),
409                                 MachineApplicable,
410                             );
411                         }
412                     }
413                     (ty::Param(expected), ty::Param(found)) => {
414                         let generics = self.generics_of(body_owner_def_id);
415                         let e_span = self.def_span(generics.type_param(expected, self).def_id);
416                         if !sp.contains(e_span) {
417                             diag.span_label(e_span, "expected type parameter");
418                         }
419                         let f_span = self.def_span(generics.type_param(found, self).def_id);
420                         if !sp.contains(f_span) {
421                             diag.span_label(f_span, "found type parameter");
422                         }
423                         diag.note(
424                             "a type parameter was expected, but a different one was found; \
425                              you might be missing a type parameter or trait bound",
426                         );
427                         diag.note(
428                             "for more information, visit \
429                              https://doc.rust-lang.org/book/ch10-02-traits.html\
430                              #traits-as-parameters",
431                         );
432                     }
433                     (ty::Projection(_), ty::Projection(_)) => {
434                         diag.note("an associated type was expected, but a different one was found");
435                     }
436                     (ty::Param(p), ty::Projection(proj)) | (ty::Projection(proj), ty::Param(p))
437                         if self.def_kind(proj.item_def_id) != DefKind::ImplTraitPlaceholder =>
438                     {
439                         let generics = self.generics_of(body_owner_def_id);
440                         let p_span = self.def_span(generics.type_param(p, self).def_id);
441                         if !sp.contains(p_span) {
442                             diag.span_label(p_span, "this type parameter");
443                         }
444                         let hir = self.hir();
445                         let mut note = true;
446                         if let Some(generics) = generics
447                             .type_param(p, self)
448                             .def_id
449                             .as_local()
450                             .map(|id| hir.local_def_id_to_hir_id(id))
451                             .and_then(|id| self.hir().find(self.hir().get_parent_node(id)))
452                             .as_ref()
453                             .and_then(|node| node.generics())
454                         {
455                             // Synthesize the associated type restriction `Add<Output = Expected>`.
456                             // FIXME: extract this logic for use in other diagnostics.
457                             let (trait_ref, assoc_substs) = proj.trait_ref_and_own_substs(self);
458                             let path =
459                                 self.def_path_str_with_substs(trait_ref.def_id, trait_ref.substs);
460                             let item_name = self.item_name(proj.item_def_id);
461                             let item_args = self.format_generic_args(assoc_substs);
462
463                             let path = if path.ends_with('>') {
464                                 format!(
465                                     "{}, {}{} = {}>",
466                                     &path[..path.len() - 1],
467                                     item_name,
468                                     item_args,
469                                     p
470                                 )
471                             } else {
472                                 format!("{}<{}{} = {}>", path, item_name, item_args, p)
473                             };
474                             note = !suggest_constraining_type_param(
475                                 self,
476                                 generics,
477                                 diag,
478                                 &format!("{}", proj.self_ty()),
479                                 &path,
480                                 None,
481                             );
482                         }
483                         if note {
484                             diag.note("you might be missing a type parameter or trait bound");
485                         }
486                     }
487                     (ty::Param(p), ty::Dynamic(..) | ty::Opaque(..))
488                     | (ty::Dynamic(..) | ty::Opaque(..), ty::Param(p)) => {
489                         let generics = self.generics_of(body_owner_def_id);
490                         let p_span = self.def_span(generics.type_param(p, self).def_id);
491                         if !sp.contains(p_span) {
492                             diag.span_label(p_span, "this type parameter");
493                         }
494                         diag.help("type parameters must be constrained to match other types");
495                         if self.sess.teach(&diag.get_code().unwrap()) {
496                             diag.help(
497                                 "given a type parameter `T` and a method `foo`:
498 ```
499 trait Trait<T> { fn foo(&self) -> T; }
500 ```
501 the only ways to implement method `foo` are:
502 - constrain `T` with an explicit type:
503 ```
504 impl Trait<String> for X {
505     fn foo(&self) -> String { String::new() }
506 }
507 ```
508 - add a trait bound to `T` and call a method on that trait that returns `Self`:
509 ```
510 impl<T: std::default::Default> Trait<T> for X {
511     fn foo(&self) -> T { <T as std::default::Default>::default() }
512 }
513 ```
514 - change `foo` to return an argument of type `T`:
515 ```
516 impl<T> Trait<T> for X {
517     fn foo(&self, x: T) -> T { x }
518 }
519 ```",
520                             );
521                         }
522                         diag.note(
523                             "for more information, visit \
524                              https://doc.rust-lang.org/book/ch10-02-traits.html\
525                              #traits-as-parameters",
526                         );
527                     }
528                     (ty::Param(p), ty::Closure(..) | ty::Generator(..)) => {
529                         let generics = self.generics_of(body_owner_def_id);
530                         let p_span = self.def_span(generics.type_param(p, self).def_id);
531                         if !sp.contains(p_span) {
532                             diag.span_label(p_span, "this type parameter");
533                         }
534                         diag.help(&format!(
535                             "every closure has a distinct type and so could not always match the \
536                              caller-chosen type of parameter `{}`",
537                             p
538                         ));
539                     }
540                     (ty::Param(p), _) | (_, ty::Param(p)) => {
541                         let generics = self.generics_of(body_owner_def_id);
542                         let p_span = self.def_span(generics.type_param(p, self).def_id);
543                         if !sp.contains(p_span) {
544                             diag.span_label(p_span, "this type parameter");
545                         }
546                     }
547                     (ty::Projection(proj_ty), _) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
548                         self.expected_projection(
549                             diag,
550                             proj_ty,
551                             values,
552                             body_owner_def_id,
553                             cause.code(),
554                         );
555                     }
556                     (_, ty::Projection(proj_ty)) if self.def_kind(proj_ty.item_def_id) != DefKind::ImplTraitPlaceholder => {
557                         let msg = format!(
558                             "consider constraining the associated type `{}` to `{}`",
559                             values.found, values.expected,
560                         );
561                         if !(self.suggest_constraining_opaque_associated_type(
562                             diag,
563                             &msg,
564                             proj_ty,
565                             values.expected,
566                         ) || self.suggest_constraint(
567                             diag,
568                             &msg,
569                             body_owner_def_id,
570                             proj_ty,
571                             values.expected,
572                         )) {
573                             diag.help(&msg);
574                             diag.note(
575                                 "for more information, visit \
576                                 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
577                             );
578                         }
579                     }
580                     _ => {}
581                 }
582                 debug!(
583                     "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
584                     values.expected,
585                     values.expected.kind(),
586                     values.found,
587                     values.found.kind(),
588                 );
589             }
590             CyclicTy(ty) => {
591                 // Watch out for various cases of cyclic types and try to explain.
592                 if ty.is_closure() || ty.is_generator() {
593                     diag.note(
594                         "closures cannot capture themselves or take themselves as argument;\n\
595                          this error may be the result of a recent compiler bug-fix,\n\
596                          see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
597                          for more information",
598                     );
599                 }
600             }
601             TargetFeatureCast(def_id) => {
602                 let target_spans =
603                     self.get_attrs(def_id, sym::target_feature).map(|attr| attr.span);
604                 diag.note(
605                     "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
606                 );
607                 diag.span_labels(target_spans, "`#[target_feature]` added here");
608             }
609             _ => {}
610         }
611     }
612
613     fn suggest_constraint(
614         self,
615         diag: &mut Diagnostic,
616         msg: &str,
617         body_owner_def_id: DefId,
618         proj_ty: &ty::ProjectionTy<'tcx>,
619         ty: Ty<'tcx>,
620     ) -> bool {
621         let assoc = self.associated_item(proj_ty.item_def_id);
622         let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
623         if let Some(item) = self.hir().get_if_local(body_owner_def_id) {
624             if let Some(hir_generics) = item.generics() {
625                 // Get the `DefId` for the type parameter corresponding to `A` in `<A as T>::Foo`.
626                 // This will also work for `impl Trait`.
627                 let def_id = if let ty::Param(param_ty) = proj_ty.self_ty().kind() {
628                     let generics = self.generics_of(body_owner_def_id);
629                     generics.type_param(param_ty, self).def_id
630                 } else {
631                     return false;
632                 };
633                 let Some(def_id) = def_id.as_local() else {
634                     return false;
635                 };
636
637                 // First look in the `where` clause, as this might be
638                 // `fn foo<T>(x: T) where T: Trait`.
639                 for pred in hir_generics.bounds_for_param(def_id) {
640                     if self.constrain_generic_bound_associated_type_structured_suggestion(
641                         diag,
642                         &trait_ref,
643                         pred.bounds,
644                         &assoc,
645                         assoc_substs,
646                         ty,
647                         msg,
648                         false,
649                     ) {
650                         return true;
651                     }
652                 }
653             }
654         }
655         false
656     }
657
658     /// An associated type was expected and a different type was found.
659     ///
660     /// We perform a few different checks to see what we can suggest:
661     ///
662     ///  - In the current item, look for associated functions that return the expected type and
663     ///    suggest calling them. (Not a structured suggestion.)
664     ///  - If any of the item's generic bounds can be constrained, we suggest constraining the
665     ///    associated type to the found type.
666     ///  - If the associated type has a default type and was expected inside of a `trait`, we
667     ///    mention that this is disallowed.
668     ///  - If all other things fail, and the error is not because of a mismatch between the `trait`
669     ///    and the `impl`, we provide a generic `help` to constrain the assoc type or call an assoc
670     ///    fn that returns the type.
671     fn expected_projection(
672         self,
673         diag: &mut Diagnostic,
674         proj_ty: &ty::ProjectionTy<'tcx>,
675         values: ExpectedFound<Ty<'tcx>>,
676         body_owner_def_id: DefId,
677         cause_code: &ObligationCauseCode<'_>,
678     ) {
679         let msg = format!(
680             "consider constraining the associated type `{}` to `{}`",
681             values.expected, values.found
682         );
683         let body_owner = self.hir().get_if_local(body_owner_def_id);
684         let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
685
686         // We don't want to suggest calling an assoc fn in a scope where that isn't feasible.
687         let callable_scope = matches!(
688             body_owner,
689             Some(
690                 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn(..), .. })
691                     | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
692                     | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
693             )
694         );
695         let impl_comparison =
696             matches!(cause_code, ObligationCauseCode::CompareImplItemObligation { .. });
697         let assoc = self.associated_item(proj_ty.item_def_id);
698         if !callable_scope || impl_comparison {
699             // We do not want to suggest calling functions when the reason of the
700             // type error is a comparison of an `impl` with its `trait` or when the
701             // scope is outside of a `Body`.
702         } else {
703             // If we find a suitable associated function that returns the expected type, we don't
704             // want the more general suggestion later in this method about "consider constraining
705             // the associated type or calling a method that returns the associated type".
706             let point_at_assoc_fn = self.point_at_methods_that_satisfy_associated_type(
707                 diag,
708                 assoc.container_id(self),
709                 current_method_ident,
710                 proj_ty.item_def_id,
711                 values.expected,
712             );
713             // Possibly suggest constraining the associated type to conform to the
714             // found type.
715             if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
716                 || point_at_assoc_fn
717             {
718                 return;
719             }
720         }
721
722         self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
723
724         if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
725             return;
726         }
727
728         if !impl_comparison {
729             // Generic suggestion when we can't be more specific.
730             if callable_scope {
731                 diag.help(&format!(
732                     "{} or calling a method that returns `{}`",
733                     msg, values.expected
734                 ));
735             } else {
736                 diag.help(&msg);
737             }
738             diag.note(
739                 "for more information, visit \
740                  https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
741             );
742         }
743         if self.sess.teach(&diag.get_code().unwrap()) {
744             diag.help(
745                 "given an associated type `T` and a method `foo`:
746 ```
747 trait Trait {
748 type T;
749 fn foo(&self) -> Self::T;
750 }
751 ```
752 the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
753 ```
754 impl Trait for X {
755 type T = String;
756 fn foo(&self) -> Self::T { String::new() }
757 }
758 ```",
759             );
760         }
761     }
762
763     /// When the expected `impl Trait` is not defined in the current item, it will come from
764     /// a return type. This can occur when dealing with `TryStream` (#71035).
765     fn suggest_constraining_opaque_associated_type(
766         self,
767         diag: &mut Diagnostic,
768         msg: &str,
769         proj_ty: &ty::ProjectionTy<'tcx>,
770         ty: Ty<'tcx>,
771     ) -> bool {
772         let assoc = self.associated_item(proj_ty.item_def_id);
773         if let ty::Opaque(def_id, _) = *proj_ty.self_ty().kind() {
774             let opaque_local_def_id = def_id.as_local();
775             let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
776                 match &self.hir().expect_item(opaque_local_def_id).kind {
777                     hir::ItemKind::OpaqueTy(opaque_hir_ty) => opaque_hir_ty,
778                     _ => bug!("The HirId comes from a `ty::Opaque`"),
779                 }
780             } else {
781                 return false;
782             };
783
784             let (trait_ref, assoc_substs) = proj_ty.trait_ref_and_own_substs(self);
785
786             self.constrain_generic_bound_associated_type_structured_suggestion(
787                 diag,
788                 &trait_ref,
789                 opaque_hir_ty.bounds,
790                 assoc,
791                 assoc_substs,
792                 ty,
793                 msg,
794                 true,
795             )
796         } else {
797             false
798         }
799     }
800
801     fn point_at_methods_that_satisfy_associated_type(
802         self,
803         diag: &mut Diagnostic,
804         assoc_container_id: DefId,
805         current_method_ident: Option<Symbol>,
806         proj_ty_item_def_id: DefId,
807         expected: Ty<'tcx>,
808     ) -> bool {
809         let items = self.associated_items(assoc_container_id);
810         // Find all the methods in the trait that could be called to construct the
811         // expected associated type.
812         // FIXME: consider suggesting the use of associated `const`s.
813         let methods: Vec<(Span, String)> = items
814             .items
815             .iter()
816             .filter(|(name, item)| {
817                 ty::AssocKind::Fn == item.kind && Some(**name) != current_method_ident
818             })
819             .filter_map(|(_, item)| {
820                 let method = self.fn_sig(item.def_id);
821                 match *method.output().skip_binder().kind() {
822                     ty::Projection(ty::ProjectionTy { item_def_id, .. })
823                         if item_def_id == proj_ty_item_def_id =>
824                     {
825                         Some((
826                             self.def_span(item.def_id),
827                             format!("consider calling `{}`", self.def_path_str(item.def_id)),
828                         ))
829                     }
830                     _ => None,
831                 }
832             })
833             .collect();
834         if !methods.is_empty() {
835             // Use a single `help:` to show all the methods in the trait that can
836             // be used to construct the expected associated type.
837             let mut span: MultiSpan =
838                 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
839             let msg = format!(
840                 "{some} method{s} {are} available that return{r} `{ty}`",
841                 some = if methods.len() == 1 { "a" } else { "some" },
842                 s = pluralize!(methods.len()),
843                 are = pluralize!("is", methods.len()),
844                 r = if methods.len() == 1 { "s" } else { "" },
845                 ty = expected
846             );
847             for (sp, label) in methods.into_iter() {
848                 span.push_span_label(sp, label);
849             }
850             diag.span_help(span, &msg);
851             return true;
852         }
853         false
854     }
855
856     fn point_at_associated_type(
857         self,
858         diag: &mut Diagnostic,
859         body_owner_def_id: DefId,
860         found: Ty<'tcx>,
861     ) -> bool {
862         let Some(hir_id) = body_owner_def_id.as_local() else {
863             return false;
864         };
865         let hir_id = self.hir().local_def_id_to_hir_id(hir_id);
866         // When `body_owner` is an `impl` or `trait` item, look in its associated types for
867         // `expected` and point at it.
868         let parent_id = self.hir().get_parent_item(hir_id);
869         let item = self.hir().find_by_def_id(parent_id.def_id);
870         debug!("expected_projection parent item {:?}", item);
871         match item {
872             Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Trait(.., items), .. })) => {
873                 // FIXME: account for `#![feature(specialization)]`
874                 for item in &items[..] {
875                     match item.kind {
876                         hir::AssocItemKind::Type => {
877                             // FIXME: account for returning some type in a trait fn impl that has
878                             // an assoc type as a return type (#72076).
879                             if let hir::Defaultness::Default { has_value: true } =
880                                 self.impl_defaultness(item.id.owner_id)
881                             {
882                                 if self.type_of(item.id.owner_id) == found {
883                                     diag.span_label(
884                                         item.span,
885                                         "associated type defaults can't be assumed inside the \
886                                             trait defining them",
887                                     );
888                                     return true;
889                                 }
890                             }
891                         }
892                         _ => {}
893                     }
894                 }
895             }
896             Some(hir::Node::Item(hir::Item {
897                 kind: hir::ItemKind::Impl(hir::Impl { items, .. }),
898                 ..
899             })) => {
900                 for item in &items[..] {
901                     if let hir::AssocItemKind::Type = item.kind {
902                         if self.type_of(item.id.owner_id) == found {
903                             diag.span_label(item.span, "expected this associated type");
904                             return true;
905                         }
906                     }
907                 }
908             }
909             _ => {}
910         }
911         false
912     }
913
914     /// Given a slice of `hir::GenericBound`s, if any of them corresponds to the `trait_ref`
915     /// requirement, provide a structured suggestion to constrain it to a given type `ty`.
916     ///
917     /// `is_bound_surely_present` indicates whether we know the bound we're looking for is
918     /// inside `bounds`. If that's the case then we can consider `bounds` containing only one
919     /// trait bound as the one we're looking for. This can help in cases where the associated
920     /// type is defined on a supertrait of the one present in the bounds.
921     fn constrain_generic_bound_associated_type_structured_suggestion(
922         self,
923         diag: &mut Diagnostic,
924         trait_ref: &ty::TraitRef<'tcx>,
925         bounds: hir::GenericBounds<'_>,
926         assoc: &ty::AssocItem,
927         assoc_substs: &[ty::GenericArg<'tcx>],
928         ty: Ty<'tcx>,
929         msg: &str,
930         is_bound_surely_present: bool,
931     ) -> bool {
932         // FIXME: we would want to call `resolve_vars_if_possible` on `ty` before suggesting.
933
934         let trait_bounds = bounds.iter().filter_map(|bound| match bound {
935             hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::None) => Some(ptr),
936             _ => None,
937         });
938
939         let matching_trait_bounds = trait_bounds
940             .clone()
941             .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
942             .collect::<Vec<_>>();
943
944         let span = match &matching_trait_bounds[..] {
945             &[ptr] => ptr.span,
946             &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
947                 &[ptr] => ptr.span,
948                 _ => return false,
949             },
950             _ => return false,
951         };
952
953         self.constrain_associated_type_structured_suggestion(
954             diag,
955             span,
956             assoc,
957             assoc_substs,
958             ty,
959             msg,
960         )
961     }
962
963     /// Given a span corresponding to a bound, provide a structured suggestion to set an
964     /// associated type to a given type `ty`.
965     fn constrain_associated_type_structured_suggestion(
966         self,
967         diag: &mut Diagnostic,
968         span: Span,
969         assoc: &ty::AssocItem,
970         assoc_substs: &[ty::GenericArg<'tcx>],
971         ty: Ty<'tcx>,
972         msg: &str,
973     ) -> bool {
974         if let Ok(has_params) =
975             self.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
976         {
977             let (span, sugg) = if has_params {
978                 let pos = span.hi() - BytePos(1);
979                 let span = Span::new(pos, pos, span.ctxt(), span.parent());
980                 (span, format!(", {} = {}", assoc.ident(self), ty))
981             } else {
982                 let item_args = self.format_generic_args(assoc_substs);
983                 (span.shrink_to_hi(), format!("<{}{} = {}>", assoc.ident(self), item_args, ty))
984             };
985             diag.span_suggestion_verbose(span, msg, sugg, MaybeIncorrect);
986             return true;
987         }
988         false
989     }
990
991     pub fn short_ty_string(self, ty: Ty<'tcx>) -> (String, Option<PathBuf>) {
992         let length_limit = 50;
993         let type_limit = 4;
994         let regular = FmtPrinter::new(self, hir::def::Namespace::TypeNS)
995             .pretty_print_type(ty)
996             .expect("could not write to `String`")
997             .into_buffer();
998         if regular.len() <= length_limit {
999             return (regular, None);
1000         }
1001         let short = FmtPrinter::new_with_limit(
1002             self,
1003             hir::def::Namespace::TypeNS,
1004             rustc_session::Limit(type_limit),
1005         )
1006         .pretty_print_type(ty)
1007         .expect("could not write to `String`")
1008         .into_buffer();
1009         if regular == short {
1010             return (regular, None);
1011         }
1012         // Multiple types might be shortened in a single error, ensure we create a file for each.
1013         let mut s = DefaultHasher::new();
1014         ty.hash(&mut s);
1015         let hash = s.finish();
1016         let path = self.output_filenames(()).temp_path_ext(&format!("long-type-{hash}.txt"), None);
1017         match std::fs::write(&path, &regular) {
1018             Ok(_) => (short, Some(path)),
1019             Err(_) => (regular, None),
1020         }
1021     }
1022
1023     fn format_generic_args(self, args: &[ty::GenericArg<'tcx>]) -> String {
1024         FmtPrinter::new(self, hir::def::Namespace::TypeNS)
1025             .path_generic_args(Ok, args)
1026             .expect("could not write to `String`.")
1027             .into_buffer()
1028     }
1029 }