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