]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs
4d789d230913679648560e835cc84ef47e456175
[rust.git] / compiler / rustc_infer / src / infer / error_reporting / nice_region_error / trait_impl_difference.rs
1 //! Error Reporting for `impl` items that do not match the obligations from their `trait`.
2
3 use crate::infer::error_reporting::nice_region_error::NiceRegionError;
4 use crate::infer::lexical_region_resolve::RegionResolutionError;
5 use crate::infer::{SubregionOrigin, Subtype, ValuePairs};
6 use crate::traits::ObligationCauseCode::CompareImplMethodObligation;
7 use rustc_errors::ErrorReported;
8 use rustc_hir as hir;
9 use rustc_hir::def::Res;
10 use rustc_hir::def_id::DefId;
11 use rustc_hir::intravisit::Visitor;
12 use rustc_middle::ty::error::ExpectedFound;
13 use rustc_middle::ty::{self, Ty, TyCtxt};
14 use rustc_span::{MultiSpan, Span, Symbol};
15
16 impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
17     /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`.
18     pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option<ErrorReported> {
19         let error = self.error.as_ref()?;
20         debug!("try_report_impl_not_conforming_to_trait {:?}", error);
21         if let RegionResolutionError::SubSupConflict(
22             _,
23             var_origin,
24             sub_origin,
25             _sub,
26             sup_origin,
27             _sup,
28         ) = error.clone()
29         {
30             if let (&Subtype(ref sup_trace), &Subtype(ref sub_trace)) = (&sup_origin, &sub_origin) {
31                 if let (
32                     ValuePairs::Types(sub_expected_found),
33                     ValuePairs::Types(sup_expected_found),
34                     CompareImplMethodObligation { trait_item_def_id, .. },
35                 ) = (&sub_trace.values, &sup_trace.values, &sub_trace.cause.code)
36                 {
37                     if sup_expected_found == sub_expected_found {
38                         self.emit_err(
39                             var_origin.span(),
40                             sub_expected_found.expected,
41                             sub_expected_found.found,
42                             *trait_item_def_id,
43                         );
44                         return Some(ErrorReported);
45                     }
46                 }
47             }
48         }
49         if let RegionResolutionError::ConcreteFailure(origin, _, _) = error.clone() {
50             if let SubregionOrigin::CompareImplTypeObligation {
51                 span,
52                 item_name,
53                 impl_item_def_id,
54                 trait_item_def_id,
55             } = origin
56             {
57                 self.emit_associated_type_err(span, item_name, impl_item_def_id, trait_item_def_id);
58             }
59         }
60         None
61     }
62
63     fn emit_err(&self, sp: Span, expected: Ty<'tcx>, found: Ty<'tcx>, trait_def_id: DefId) {
64         let trait_sp = self.tcx().def_span(trait_def_id);
65         let mut err = self
66             .tcx()
67             .sess
68             .struct_span_err(sp, "`impl` item signature doesn't match `trait` item signature");
69         err.span_label(sp, &format!("found `{}`", found));
70         err.span_label(trait_sp, &format!("expected `{}`", expected));
71
72         // Get the span of all the used type parameters in the method.
73         let assoc_item = self.tcx().associated_item(trait_def_id);
74         let mut visitor = TypeParamSpanVisitor { tcx: self.tcx(), types: vec![] };
75         match assoc_item.kind {
76             ty::AssocKind::Fn => {
77                 let hir = self.tcx().hir();
78                 if let Some(hir_id) =
79                     assoc_item.def_id.as_local().map(|id| hir.local_def_id_to_hir_id(id))
80                 {
81                     if let Some(decl) = hir.fn_decl_by_hir_id(hir_id) {
82                         visitor.visit_fn_decl(decl);
83                     }
84                 }
85             }
86             _ => {}
87         }
88         let mut type_param_span: MultiSpan = visitor.types.to_vec().into();
89         for &span in &visitor.types {
90             type_param_span.push_span_label(
91                 span,
92                 "consider borrowing this type parameter in the trait".to_string(),
93             );
94         }
95
96         if let Some((expected, found)) =
97             self.infcx.expected_found_str_ty(ExpectedFound { expected, found })
98         {
99             // Highlighted the differences when showing the "expected/found" note.
100             err.note_expected_found(&"", expected, &"", found);
101         } else {
102             // This fallback shouldn't be necessary, but let's keep it in just in case.
103             err.note(&format!("expected `{}`\n   found `{}`", expected, found));
104         }
105         err.span_help(
106             type_param_span,
107             "the lifetime requirements from the `impl` do not correspond to the requirements in \
108              the `trait`",
109         );
110         if visitor.types.is_empty() {
111             err.help(
112                 "verify the lifetime relationships in the `trait` and `impl` between the `self` \
113                  argument, the other inputs and its output",
114             );
115         }
116         err.emit();
117     }
118
119     fn emit_associated_type_err(
120         &self,
121         span: Span,
122         item_name: Symbol,
123         impl_item_def_id: DefId,
124         trait_item_def_id: DefId,
125     ) {
126         let impl_sp = self.tcx().def_span(impl_item_def_id);
127         let trait_sp = self.tcx().def_span(trait_item_def_id);
128         let mut err = self
129             .tcx()
130             .sess
131             .struct_span_err(span, &format!("`impl` associated type signature for `{}` doesn't match `trait` associated type signature", item_name));
132         err.span_label(impl_sp, &format!("found"));
133         err.span_label(trait_sp, &format!("expected"));
134
135         err.emit();
136     }
137 }
138
139 struct TypeParamSpanVisitor<'tcx> {
140     tcx: TyCtxt<'tcx>,
141     types: Vec<Span>,
142 }
143
144 impl Visitor<'tcx> for TypeParamSpanVisitor<'tcx> {
145     type Map = rustc_middle::hir::map::Map<'tcx>;
146
147     fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
148         hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
149     }
150
151     fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
152         match arg.kind {
153             hir::TyKind::Rptr(_, ref mut_ty) => {
154                 // We don't want to suggest looking into borrowing `&T` or `&Self`.
155                 hir::intravisit::walk_ty(self, mut_ty.ty);
156                 return;
157             }
158             hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
159                 [segment]
160                     if segment
161                         .res
162                         .map(|res| {
163                             matches!(
164                                 res,
165                                 Res::SelfTy(_, _) | Res::Def(hir::def::DefKind::TyParam, _)
166                             )
167                         })
168                         .unwrap_or(false) =>
169                 {
170                     self.types.push(path.span);
171                 }
172                 _ => {}
173             },
174             _ => {}
175         }
176         hir::intravisit::walk_ty(self, arg);
177     }
178 }