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