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