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