]> git.lizzy.rs Git - rust.git/blob - src/librustc_infer/infer/error_reporting/need_type_info.rs
Rollup merge of #70937 - mati865:mingw-staticlib-suffix, r=petrochenkov
[rust.git] / src / librustc_infer / infer / error_reporting / need_type_info.rs
1 use crate::infer::type_variable::TypeVariableOriginKind;
2 use crate::infer::InferCtxt;
3 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
4 use rustc_hir as hir;
5 use rustc_hir::def::{DefKind, Namespace};
6 use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor};
7 use rustc_hir::{Body, Expr, ExprKind, FnRetTy, HirId, Local, Pat};
8 use rustc_middle::hir::map::Map;
9 use rustc_middle::ty::print::Print;
10 use rustc_middle::ty::subst::{GenericArg, GenericArgKind};
11 use rustc_middle::ty::{self, DefIdTree, Ty};
12 use rustc_span::source_map::DesugaringKind;
13 use rustc_span::symbol::kw;
14 use rustc_span::Span;
15 use std::borrow::Cow;
16
17 struct FindHirNodeVisitor<'a, 'tcx> {
18     infcx: &'a InferCtxt<'a, 'tcx>,
19     target: GenericArg<'tcx>,
20     found_node_ty: Option<Ty<'tcx>>,
21     found_local_pattern: Option<&'tcx Pat<'tcx>>,
22     found_arg_pattern: Option<&'tcx Pat<'tcx>>,
23     found_closure: Option<&'tcx Expr<'tcx>>,
24     found_method_call: Option<&'tcx Expr<'tcx>>,
25 }
26
27 impl<'a, 'tcx> FindHirNodeVisitor<'a, 'tcx> {
28     fn new(infcx: &'a InferCtxt<'a, 'tcx>, target: GenericArg<'tcx>) -> Self {
29         Self {
30             infcx,
31             target,
32             found_node_ty: None,
33             found_local_pattern: None,
34             found_arg_pattern: None,
35             found_closure: None,
36             found_method_call: None,
37         }
38     }
39
40     fn node_ty_contains_target(&mut self, hir_id: HirId) -> Option<Ty<'tcx>> {
41         let ty_opt =
42             self.infcx.in_progress_tables.and_then(|tables| tables.borrow().node_type_opt(hir_id));
43         match ty_opt {
44             Some(ty) => {
45                 let ty = self.infcx.resolve_vars_if_possible(&ty);
46                 if ty.walk().any(|inner| {
47                     inner == self.target
48                         || match (inner.unpack(), self.target.unpack()) {
49                             (GenericArgKind::Type(inner_ty), GenericArgKind::Type(target_ty)) => {
50                                 match (&inner_ty.kind, &target_ty.kind) {
51                                     (
52                                         &ty::Infer(ty::TyVar(a_vid)),
53                                         &ty::Infer(ty::TyVar(b_vid)),
54                                     ) => self
55                                         .infcx
56                                         .inner
57                                         .borrow_mut()
58                                         .type_variables
59                                         .sub_unified(a_vid, b_vid),
60                                     _ => false,
61                                 }
62                             }
63                             _ => false,
64                         }
65                 }) {
66                     Some(ty)
67                 } else {
68                     None
69                 }
70             }
71             None => None,
72         }
73     }
74 }
75
76 impl<'a, 'tcx> Visitor<'tcx> for FindHirNodeVisitor<'a, 'tcx> {
77     type Map = Map<'tcx>;
78
79     fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
80         NestedVisitorMap::OnlyBodies(self.infcx.tcx.hir())
81     }
82
83     fn visit_local(&mut self, local: &'tcx Local<'tcx>) {
84         if let (None, Some(ty)) =
85             (self.found_local_pattern, self.node_ty_contains_target(local.hir_id))
86         {
87             self.found_local_pattern = Some(&*local.pat);
88             self.found_node_ty = Some(ty);
89         }
90         intravisit::walk_local(self, local);
91     }
92
93     fn visit_body(&mut self, body: &'tcx Body<'tcx>) {
94         for param in body.params {
95             if let (None, Some(ty)) =
96                 (self.found_arg_pattern, self.node_ty_contains_target(param.hir_id))
97             {
98                 self.found_arg_pattern = Some(&*param.pat);
99                 self.found_node_ty = Some(ty);
100             }
101         }
102         intravisit::walk_body(self, body);
103     }
104
105     fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
106         if self.node_ty_contains_target(expr.hir_id).is_some() {
107             match expr.kind {
108                 ExprKind::Closure(..) => self.found_closure = Some(&expr),
109                 ExprKind::MethodCall(..) => self.found_method_call = Some(&expr),
110                 _ => {}
111             }
112         }
113         intravisit::walk_expr(self, expr);
114     }
115 }
116
117 /// Suggest giving an appropriate return type to a closure expression.
118 fn closure_return_type_suggestion(
119     span: Span,
120     err: &mut DiagnosticBuilder<'_>,
121     output: &FnRetTy<'_>,
122     body: &Body<'_>,
123     descr: &str,
124     name: &str,
125     ret: &str,
126     parent_name: Option<String>,
127     parent_descr: Option<&str>,
128 ) {
129     let (arrow, post) = match output {
130         FnRetTy::DefaultReturn(_) => ("-> ", " "),
131         _ => ("", ""),
132     };
133     let suggestion = match body.value.kind {
134         ExprKind::Block(..) => vec![(output.span(), format!("{}{}{}", arrow, ret, post))],
135         _ => vec![
136             (output.span(), format!("{}{}{}{{ ", arrow, ret, post)),
137             (body.value.span.shrink_to_hi(), " }".to_string()),
138         ],
139     };
140     err.multipart_suggestion(
141         "give this closure an explicit return type without `_` placeholders",
142         suggestion,
143         Applicability::HasPlaceholders,
144     );
145     err.span_label(span, InferCtxt::missing_type_msg(&name, &descr, parent_name, parent_descr));
146 }
147
148 /// Given a closure signature, return a `String` containing a list of all its argument types.
149 fn closure_args(fn_sig: &ty::PolyFnSig<'_>) -> String {
150     fn_sig
151         .inputs()
152         .skip_binder()
153         .iter()
154         .next()
155         .map(|args| args.tuple_fields().map(|arg| arg.to_string()).collect::<Vec<_>>().join(", "))
156         .unwrap_or_default()
157 }
158
159 pub enum TypeAnnotationNeeded {
160     E0282,
161     E0283,
162     E0284,
163 }
164
165 impl Into<rustc_errors::DiagnosticId> for TypeAnnotationNeeded {
166     fn into(self) -> rustc_errors::DiagnosticId {
167         match self {
168             Self::E0282 => rustc_errors::error_code!(E0282),
169             Self::E0283 => rustc_errors::error_code!(E0283),
170             Self::E0284 => rustc_errors::error_code!(E0284),
171         }
172     }
173 }
174
175 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
176     pub fn extract_type_name(
177         &self,
178         ty: Ty<'tcx>,
179         highlight: Option<ty::print::RegionHighlightMode>,
180     ) -> (String, Option<Span>, Cow<'static, str>, Option<String>, Option<&'static str>) {
181         if let ty::Infer(ty::TyVar(ty_vid)) = ty.kind {
182             let ty_vars = &self.inner.borrow().type_variables;
183             let var_origin = ty_vars.var_origin(ty_vid);
184             if let TypeVariableOriginKind::TypeParameterDefinition(name, def_id) = var_origin.kind {
185                 let parent_def_id = def_id.and_then(|def_id| self.tcx.parent(def_id));
186                 let (parent_name, parent_desc) = if let Some(parent_def_id) = parent_def_id {
187                     let parent_name = self
188                         .tcx
189                         .def_key(parent_def_id)
190                         .disambiguated_data
191                         .data
192                         .get_opt_name()
193                         .map(|parent_symbol| parent_symbol.to_string());
194
195                     let type_parent_desc = self
196                         .tcx
197                         .def_kind(parent_def_id)
198                         .map(|parent_def_kind| parent_def_kind.descr(parent_def_id));
199
200                     (parent_name, type_parent_desc)
201                 } else {
202                     (None, None)
203                 };
204
205                 if name != kw::SelfUpper {
206                     return (
207                         name.to_string(),
208                         Some(var_origin.span),
209                         "type parameter".into(),
210                         parent_name,
211                         parent_desc,
212                     );
213                 }
214             }
215         }
216
217         let mut s = String::new();
218         let mut printer = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS);
219         if let Some(highlight) = highlight {
220             printer.region_highlight_mode = highlight;
221         }
222         let _ = ty.print(printer);
223         (s, None, ty.prefix_string(), None, None)
224     }
225
226     // FIXME(eddyb) generalize all of this to handle `ty::Const` inference variables as well.
227     pub fn need_type_info_err(
228         &self,
229         body_id: Option<hir::BodyId>,
230         span: Span,
231         ty: Ty<'tcx>,
232         error_code: TypeAnnotationNeeded,
233     ) -> DiagnosticBuilder<'tcx> {
234         let ty = self.resolve_vars_if_possible(&ty);
235         let (name, name_sp, descr, parent_name, parent_descr) = self.extract_type_name(&ty, None);
236
237         let mut local_visitor = FindHirNodeVisitor::new(&self, ty.into());
238         let ty_to_string = |ty: Ty<'tcx>| -> String {
239             let mut s = String::new();
240             let mut printer = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS);
241             let ty_vars = &self.inner.borrow().type_variables;
242             let getter = move |ty_vid| {
243                 let var_origin = ty_vars.var_origin(ty_vid);
244                 if let TypeVariableOriginKind::TypeParameterDefinition(name, _) = var_origin.kind {
245                     return Some(name.to_string());
246                 }
247                 None
248             };
249             printer.name_resolver = Some(Box::new(&getter));
250             let _ = ty.print(printer);
251             s
252         };
253
254         if let Some(body_id) = body_id {
255             let expr = self.tcx.hir().expect_expr(body_id.hir_id);
256             local_visitor.visit_expr(expr);
257         }
258         let err_span = if let Some(pattern) = local_visitor.found_arg_pattern {
259             pattern.span
260         } else if let Some(span) = name_sp {
261             // `span` here lets us point at `sum` instead of the entire right hand side expr:
262             // error[E0282]: type annotations needed
263             //  --> file2.rs:3:15
264             //   |
265             // 3 |     let _ = x.sum() as f64;
266             //   |               ^^^ cannot infer type for `S`
267             span
268         } else if let Some(ExprKind::MethodCall(_, call_span, _)) =
269             local_visitor.found_method_call.map(|e| &e.kind)
270         {
271             // Point at the call instead of the whole expression:
272             // error[E0284]: type annotations needed
273             //  --> file.rs:2:5
274             //   |
275             // 2 |     vec![Ok(2)].into_iter().collect()?;
276             //   |                             ^^^^^^^ cannot infer type
277             //   |
278             //   = note: cannot resolve `<_ as std::ops::Try>::Ok == _`
279             if span.contains(*call_span) { *call_span } else { span }
280         } else {
281             span
282         };
283
284         let is_named_and_not_impl_trait = |ty: Ty<'_>| {
285             &ty.to_string() != "_" &&
286                 // FIXME: Remove this check after `impl_trait_in_bindings` is stabilized. #63527
287                 (!ty.is_impl_trait() || self.tcx.features().impl_trait_in_bindings)
288         };
289
290         let ty_msg = match local_visitor.found_node_ty {
291             Some(ty::TyS { kind: ty::Closure(_, substs), .. }) => {
292                 let fn_sig = substs.as_closure().sig();
293                 let args = closure_args(&fn_sig);
294                 let ret = fn_sig.output().skip_binder().to_string();
295                 format!(" for the closure `fn({}) -> {}`", args, ret)
296             }
297             Some(ty) if is_named_and_not_impl_trait(ty) => {
298                 let ty = ty_to_string(ty);
299                 format!(" for `{}`", ty)
300             }
301             _ => String::new(),
302         };
303
304         // When `name` corresponds to a type argument, show the path of the full type we're
305         // trying to infer. In the following example, `ty_msg` contains
306         // " in `std::result::Result<i32, E>`":
307         // ```
308         // error[E0282]: type annotations needed for `std::result::Result<i32, E>`
309         //  --> file.rs:L:CC
310         //   |
311         // L |     let b = Ok(4);
312         //   |         -   ^^ cannot infer type for `E` in `std::result::Result<i32, E>`
313         //   |         |
314         //   |         consider giving `b` the explicit type `std::result::Result<i32, E>`, where
315         //   |         the type parameter `E` is specified
316         // ```
317         let error_code = error_code.into();
318         let mut err = self.tcx.sess.struct_span_err_with_code(
319             err_span,
320             &format!("type annotations needed{}", ty_msg),
321             error_code,
322         );
323
324         let suffix = match local_visitor.found_node_ty {
325             Some(ty::TyS { kind: ty::Closure(_, substs), .. }) => {
326                 let fn_sig = substs.as_closure().sig();
327                 let ret = fn_sig.output().skip_binder().to_string();
328
329                 let closure_decl_and_body_id =
330                     local_visitor.found_closure.and_then(|closure| match &closure.kind {
331                         ExprKind::Closure(_, decl, body_id, ..) => Some((decl, *body_id)),
332                         _ => None,
333                     });
334
335                 if let Some((decl, body_id)) = closure_decl_and_body_id {
336                     closure_return_type_suggestion(
337                         span,
338                         &mut err,
339                         &decl.output,
340                         self.tcx.hir().body(body_id),
341                         &descr,
342                         &name,
343                         &ret,
344                         parent_name,
345                         parent_descr,
346                     );
347                     // We don't want to give the other suggestions when the problem is the
348                     // closure return type.
349                     return err;
350                 }
351
352                 // This shouldn't be reachable, but just in case we leave a reasonable fallback.
353                 let args = closure_args(&fn_sig);
354                 // This suggestion is incomplete, as the user will get further type inference
355                 // errors due to the `_` placeholders and the introduction of `Box`, but it does
356                 // nudge them in the right direction.
357                 format!("a boxed closure type like `Box<dyn Fn({}) -> {}>`", args, ret)
358             }
359             Some(ty) if is_named_and_not_impl_trait(ty) && name == "_" => {
360                 let ty = ty_to_string(ty);
361                 format!("the explicit type `{}`, with the type parameters specified", ty)
362             }
363             Some(ty) if is_named_and_not_impl_trait(ty) && ty.to_string() != name => {
364                 let ty = ty_to_string(ty);
365                 format!(
366                     "the explicit type `{}`, where the type parameter `{}` is specified",
367                     ty, name,
368                 )
369             }
370             _ => "a type".to_string(),
371         };
372
373         if let Some(pattern) = local_visitor.found_arg_pattern {
374             // We don't want to show the default label for closures.
375             //
376             // So, before clearing, the output would look something like this:
377             // ```
378             // let x = |_| {  };
379             //          -  ^^^^ cannot infer type for `[_; 0]`
380             //          |
381             //          consider giving this closure parameter a type
382             // ```
383             //
384             // After clearing, it looks something like this:
385             // ```
386             // let x = |_| {  };
387             //          ^ consider giving this closure parameter the type `[_; 0]`
388             //            with the type parameter `_` specified
389             // ```
390             err.span_label(
391                 pattern.span,
392                 format!("consider giving this closure parameter {}", suffix),
393             );
394         } else if let Some(pattern) = local_visitor.found_local_pattern {
395             let msg = if let Some(simple_ident) = pattern.simple_ident() {
396                 match pattern.span.desugaring_kind() {
397                     None => format!("consider giving `{}` {}", simple_ident, suffix),
398                     Some(DesugaringKind::ForLoop) => {
399                         "the element type for this iterator is not specified".to_string()
400                     }
401                     _ => format!("this needs {}", suffix),
402                 }
403             } else {
404                 format!("consider giving this pattern {}", suffix)
405             };
406             err.span_label(pattern.span, msg);
407         } else if let Some(e) = local_visitor.found_method_call {
408             if let ExprKind::MethodCall(segment, ..) = &e.kind {
409                 // Suggest specifying type params or point out the return type of the call:
410                 //
411                 // error[E0282]: type annotations needed
412                 //   --> $DIR/type-annotations-needed-expr.rs:2:39
413                 //    |
414                 // LL |     let _ = x.into_iter().sum() as f64;
415                 //    |                           ^^^
416                 //    |                           |
417                 //    |                           cannot infer type for `S`
418                 //    |                           help: consider specifying the type argument in
419                 //    |                           the method call: `sum::<S>`
420                 //    |
421                 //    = note: type must be known at this point
422                 //
423                 // or
424                 //
425                 // error[E0282]: type annotations needed
426                 //   --> $DIR/issue-65611.rs:59:20
427                 //    |
428                 // LL |     let x = buffer.last().unwrap().0.clone();
429                 //    |             -------^^^^--
430                 //    |             |      |
431                 //    |             |      cannot infer type for `T`
432                 //    |             this method call resolves to `std::option::Option<&T>`
433                 //    |
434                 //    = note: type must be known at this point
435                 self.annotate_method_call(segment, e, &mut err);
436             }
437         }
438         // Instead of the following:
439         // error[E0282]: type annotations needed
440         //  --> file2.rs:3:15
441         //   |
442         // 3 |     let _ = x.sum() as f64;
443         //   |             --^^^--------- cannot infer type for `S`
444         //   |
445         //   = note: type must be known at this point
446         // We want:
447         // error[E0282]: type annotations needed
448         //  --> file2.rs:3:15
449         //   |
450         // 3 |     let _ = x.sum() as f64;
451         //   |               ^^^ cannot infer type for `S`
452         //   |
453         //   = note: type must be known at this point
454         let span = name_sp.unwrap_or(err_span);
455         if !err
456             .span
457             .span_labels()
458             .iter()
459             .any(|span_label| span_label.label.is_some() && span_label.span == span)
460             && local_visitor.found_arg_pattern.is_none()
461         {
462             // Avoid multiple labels pointing at `span`.
463             err.span_label(
464                 span,
465                 InferCtxt::missing_type_msg(&name, &descr, parent_name, parent_descr),
466             );
467         }
468
469         err
470     }
471
472     /// If the `FnSig` for the method call can be found and type arguments are identified as
473     /// needed, suggest annotating the call, otherwise point out the resulting type of the call.
474     fn annotate_method_call(
475         &self,
476         segment: &hir::PathSegment<'_>,
477         e: &Expr<'_>,
478         err: &mut DiagnosticBuilder<'_>,
479     ) {
480         if let (Some(tables), None) = (self.in_progress_tables, &segment.args) {
481             let borrow = tables.borrow();
482             if let Some((DefKind::AssocFn, did)) = borrow.type_dependent_def(e.hir_id) {
483                 let generics = self.tcx.generics_of(did);
484                 if !generics.params.is_empty() {
485                     err.span_suggestion_verbose(
486                         segment.ident.span.shrink_to_hi(),
487                         &format!(
488                             "consider specifying the type argument{} in the method call",
489                             pluralize!(generics.params.len()),
490                         ),
491                         format!(
492                             "::<{}>",
493                             generics
494                                 .params
495                                 .iter()
496                                 .map(|p| p.name.to_string())
497                                 .collect::<Vec<String>>()
498                                 .join(", ")
499                         ),
500                         Applicability::HasPlaceholders,
501                     );
502                 } else {
503                     let sig = self.tcx.fn_sig(did);
504                     let bound_output = sig.output();
505                     let output = bound_output.skip_binder();
506                     err.span_label(e.span, &format!("this method call resolves to `{:?}`", output));
507                     let kind = &output.kind;
508                     if let ty::Projection(proj) | ty::UnnormalizedProjection(proj) = kind {
509                         if let Some(span) = self.tcx.hir().span_if_local(proj.item_def_id) {
510                             err.span_label(span, &format!("`{:?}` defined here", output));
511                         }
512                     }
513                 }
514             }
515         }
516     }
517
518     pub fn need_type_info_err_in_generator(
519         &self,
520         kind: hir::GeneratorKind,
521         span: Span,
522         ty: Ty<'tcx>,
523     ) -> DiagnosticBuilder<'tcx> {
524         let ty = self.resolve_vars_if_possible(&ty);
525         let (name, _, descr, parent_name, parent_descr) = self.extract_type_name(&ty, None);
526
527         let mut err = struct_span_err!(
528             self.tcx.sess,
529             span,
530             E0698,
531             "type inside {} must be known in this context",
532             kind,
533         );
534         err.span_label(span, InferCtxt::missing_type_msg(&name, &descr, parent_name, parent_descr));
535         err
536     }
537
538     fn missing_type_msg(
539         type_name: &str,
540         descr: &str,
541         parent_name: Option<String>,
542         parent_descr: Option<&str>,
543     ) -> Cow<'static, str> {
544         if type_name == "_" {
545             "cannot infer type".into()
546         } else {
547             let parent_desc = if let Some(parent_name) = parent_name {
548                 let parent_type_descr = if let Some(parent_descr) = parent_descr {
549                     format!(" the {}", parent_descr)
550                 } else {
551                     "".into()
552                 };
553
554                 format!(" declared on{} `{}`", parent_type_descr, parent_name)
555             } else {
556                 "".to_string()
557             };
558
559             format!("cannot infer type for {} `{}`{}", descr, type_name, parent_desc).into()
560         }
561     }
562 }