]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/error_reporting/nice_region_error/trait_impl_difference.rs
b9e7ee12bc86df55872e82a103729820232a1483
[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::print::RegionHighlightMode;
13 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable, TypeVisitor};
14
15 use rustc_span::{MultiSpan, Span, Symbol};
16
17 use std::ops::ControlFlow;
18
19 impl<'a, 'tcx> NiceRegionError<'a, 'tcx> {
20     /// Print the error message for lifetime errors when the `impl` doesn't conform to the `trait`.
21     pub(super) fn try_report_impl_not_conforming_to_trait(&self) -> Option<ErrorReported> {
22         let error = self.error.as_ref()?;
23         debug!("try_report_impl_not_conforming_to_trait {:?}", error);
24         if let RegionResolutionError::SubSupConflict(
25             _,
26             var_origin,
27             sub_origin,
28             _sub,
29             sup_origin,
30             _sup,
31         ) = error.clone()
32         {
33             if let (&Subtype(ref sup_trace), &Subtype(ref sub_trace)) = (&sup_origin, &sub_origin) {
34                 if let (
35                     ValuePairs::Types(sub_expected_found),
36                     ValuePairs::Types(sup_expected_found),
37                     CompareImplMethodObligation { trait_item_def_id, .. },
38                 ) = (&sub_trace.values, &sup_trace.values, &sub_trace.cause.code)
39                 {
40                     if sup_expected_found == sub_expected_found {
41                         self.emit_err(
42                             var_origin.span(),
43                             sub_expected_found.expected,
44                             sub_expected_found.found,
45                             *trait_item_def_id,
46                         );
47                         return Some(ErrorReported);
48                     }
49                 }
50             }
51         }
52         if let RegionResolutionError::ConcreteFailure(origin, _, _)
53         | RegionResolutionError::GenericBoundFailure(origin, _, _) = error.clone()
54         {
55             if let SubregionOrigin::CompareImplTypeObligation {
56                 span,
57                 item_name,
58                 impl_item_def_id,
59                 trait_item_def_id,
60             } = origin
61             {
62                 self.emit_associated_type_err(span, item_name, impl_item_def_id, trait_item_def_id);
63                 return Some(ErrorReported);
64             }
65         }
66         None
67     }
68
69     fn emit_err(&self, sp: Span, expected: Ty<'tcx>, found: Ty<'tcx>, trait_def_id: DefId) {
70         let trait_sp = self.tcx().def_span(trait_def_id);
71         let mut err = self
72             .tcx()
73             .sess
74             .struct_span_err(sp, "`impl` item signature doesn't match `trait` item signature");
75
76         // Mark all unnamed regions in the type with a number.
77         // This diagnostic is called in response to lifetime errors, so be informative.
78         struct HighlightBuilder<'tcx> {
79             highlight: RegionHighlightMode,
80             tcx: TyCtxt<'tcx>,
81             counter: usize,
82         }
83
84         impl HighlightBuilder<'tcx> {
85             fn build(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> RegionHighlightMode {
86                 let mut builder =
87                     HighlightBuilder { highlight: RegionHighlightMode::default(), counter: 1, tcx };
88                 builder.visit_ty(ty);
89                 builder.highlight
90             }
91         }
92
93         impl<'tcx> ty::fold::TypeVisitor<'tcx> for HighlightBuilder<'tcx> {
94             fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
95                 Some(self.tcx)
96             }
97
98             fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
99                 if !r.has_name() && self.counter <= 3 {
100                     self.highlight.highlighting_region(r, self.counter);
101                     self.counter += 1;
102                 }
103                 r.super_visit_with(self)
104             }
105         }
106
107         let expected_highlight = HighlightBuilder::build(self.tcx(), expected);
108         let expected = self
109             .infcx
110             .extract_inference_diagnostics_data(expected.into(), Some(expected_highlight))
111             .name;
112         let found_highlight = HighlightBuilder::build(self.tcx(), found);
113         let found =
114             self.infcx.extract_inference_diagnostics_data(found.into(), Some(found_highlight)).name;
115
116         err.span_label(sp, &format!("found `{}`", found));
117         err.span_label(trait_sp, &format!("expected `{}`", expected));
118
119         // Get the span of all the used type parameters in the method.
120         let assoc_item = self.tcx().associated_item(trait_def_id);
121         let mut visitor = TypeParamSpanVisitor { tcx: self.tcx(), types: vec![] };
122         match assoc_item.kind {
123             ty::AssocKind::Fn => {
124                 let hir = self.tcx().hir();
125                 if let Some(hir_id) =
126                     assoc_item.def_id.as_local().map(|id| hir.local_def_id_to_hir_id(id))
127                 {
128                     if let Some(decl) = hir.fn_decl_by_hir_id(hir_id) {
129                         visitor.visit_fn_decl(decl);
130                     }
131                 }
132             }
133             _ => {}
134         }
135         let mut type_param_span: MultiSpan = visitor.types.to_vec().into();
136         for &span in &visitor.types {
137             type_param_span.push_span_label(
138                 span,
139                 "consider borrowing this type parameter in the trait".to_string(),
140             );
141         }
142
143         err.note(&format!("expected `{}`\n   found `{}`", expected, found));
144
145         err.span_help(
146             type_param_span,
147             "the lifetime requirements from the `impl` do not correspond to the requirements in \
148              the `trait`",
149         );
150         if visitor.types.is_empty() {
151             err.help(
152                 "verify the lifetime relationships in the `trait` and `impl` between the `self` \
153                  argument, the other inputs and its output",
154             );
155         }
156         err.emit();
157     }
158
159     fn emit_associated_type_err(
160         &self,
161         span: Span,
162         item_name: Symbol,
163         impl_item_def_id: DefId,
164         trait_item_def_id: DefId,
165     ) {
166         let impl_sp = self.tcx().def_span(impl_item_def_id);
167         let trait_sp = self.tcx().def_span(trait_item_def_id);
168         let mut err = self
169             .tcx()
170             .sess
171             .struct_span_err(span, &format!("`impl` associated type signature for `{}` doesn't match `trait` associated type signature", item_name));
172         err.span_label(impl_sp, "found");
173         err.span_label(trait_sp, "expected");
174
175         err.emit();
176     }
177 }
178
179 struct TypeParamSpanVisitor<'tcx> {
180     tcx: TyCtxt<'tcx>,
181     types: Vec<Span>,
182 }
183
184 impl Visitor<'tcx> for TypeParamSpanVisitor<'tcx> {
185     type Map = rustc_middle::hir::map::Map<'tcx>;
186
187     fn nested_visit_map(&mut self) -> hir::intravisit::NestedVisitorMap<Self::Map> {
188         hir::intravisit::NestedVisitorMap::OnlyBodies(self.tcx.hir())
189     }
190
191     fn visit_ty(&mut self, arg: &'tcx hir::Ty<'tcx>) {
192         match arg.kind {
193             hir::TyKind::Rptr(_, ref mut_ty) => {
194                 // We don't want to suggest looking into borrowing `&T` or `&Self`.
195                 hir::intravisit::walk_ty(self, mut_ty.ty);
196                 return;
197             }
198             hir::TyKind::Path(hir::QPath::Resolved(None, path)) => match &path.segments {
199                 [segment]
200                     if segment
201                         .res
202                         .map(|res| {
203                             matches!(
204                                 res,
205                                 Res::SelfTy(_, _) | Res::Def(hir::def::DefKind::TyParam, _)
206                             )
207                         })
208                         .unwrap_or(false) =>
209                 {
210                     self.types.push(path.span);
211                 }
212                 _ => {}
213             },
214             _ => {}
215         }
216         hir::intravisit::walk_ty(self, arg);
217     }
218 }