1 use crate::infer::type_variable::TypeVariableOriginKind;
2 use crate::infer::InferCtxt;
3 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticBuilder};
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;
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>>,
27 impl<'a, 'tcx> FindHirNodeVisitor<'a, 'tcx> {
28 fn new(infcx: &'a InferCtxt<'a, 'tcx>, target: GenericArg<'tcx>) -> Self {
33 found_local_pattern: None,
34 found_arg_pattern: None,
36 found_method_call: None,
40 fn node_ty_contains_target(&mut self, hir_id: HirId) -> Option<Ty<'tcx>> {
42 self.infcx.in_progress_tables.and_then(|tables| tables.borrow().node_type_opt(hir_id));
45 let ty = self.infcx.resolve_vars_if_possible(&ty);
46 if ty.walk().any(|inner| {
48 || match (inner.unpack(), self.target.unpack()) {
49 (GenericArgKind::Type(inner_ty), GenericArgKind::Type(target_ty)) => {
50 match (&inner_ty.kind, &target_ty.kind) {
52 &ty::Infer(ty::TyVar(a_vid)),
53 &ty::Infer(ty::TyVar(b_vid)),
59 .sub_unified(a_vid, b_vid),
76 impl<'a, 'tcx> Visitor<'tcx> for FindHirNodeVisitor<'a, 'tcx> {
79 fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> {
80 NestedVisitorMap::OnlyBodies(self.infcx.tcx.hir())
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))
87 self.found_local_pattern = Some(&*local.pat);
88 self.found_node_ty = Some(ty);
90 intravisit::walk_local(self, local);
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))
98 self.found_arg_pattern = Some(&*param.pat);
99 self.found_node_ty = Some(ty);
102 intravisit::walk_body(self, body);
105 fn visit_expr(&mut self, expr: &'tcx Expr<'tcx>) {
106 if self.node_ty_contains_target(expr.hir_id).is_some() {
108 ExprKind::Closure(..) => self.found_closure = Some(&expr),
109 ExprKind::MethodCall(..) => self.found_method_call = Some(&expr),
113 intravisit::walk_expr(self, expr);
117 /// Suggest giving an appropriate return type to a closure expression.
118 fn closure_return_type_suggestion(
120 err: &mut DiagnosticBuilder<'_>,
121 output: &FnRetTy<'_>,
126 parent_name: Option<String>,
127 parent_descr: Option<&str>,
129 let (arrow, post) = match output {
130 FnRetTy::DefaultReturn(_) => ("-> ", " "),
133 let suggestion = match body.value.kind {
134 ExprKind::Block(..) => vec![(output.span(), format!("{}{}{}", arrow, ret, post))],
136 (output.span(), format!("{}{}{}{{ ", arrow, ret, post)),
137 (body.value.span.shrink_to_hi(), " }".to_string()),
140 err.multipart_suggestion(
141 "give this closure an explicit return type without `_` placeholders",
143 Applicability::HasPlaceholders,
145 err.span_label(span, InferCtxt::missing_type_msg(&name, &descr, parent_name, parent_descr));
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 {
155 .map(|args| args.tuple_fields().map(|arg| arg.to_string()).collect::<Vec<_>>().join(", "))
159 pub enum TypeAnnotationNeeded {
165 impl Into<rustc_errors::DiagnosticId> for TypeAnnotationNeeded {
166 fn into(self) -> rustc_errors::DiagnosticId {
168 Self::E0282 => rustc_errors::error_code!(E0282),
169 Self::E0283 => rustc_errors::error_code!(E0283),
170 Self::E0284 => rustc_errors::error_code!(E0284),
175 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
176 pub fn extract_type_name(
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
189 .def_key(parent_def_id)
193 .map(|parent_symbol| parent_symbol.to_string());
195 let type_parent_desc = self
197 .def_kind(parent_def_id)
198 .map(|parent_def_kind| parent_def_kind.descr(parent_def_id));
200 (parent_name, type_parent_desc)
205 if name != kw::SelfUpper {
208 Some(var_origin.span),
209 "type parameter".into(),
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;
222 let _ = ty.print(printer);
223 (s, None, ty.prefix_string(), None, None)
226 // FIXME(eddyb) generalize all of this to handle `ty::Const` inference variables as well.
227 pub fn need_type_info_err(
229 body_id: Option<hir::BodyId>,
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);
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());
249 printer.name_resolver = Some(Box::new(&getter));
250 let _ = ty.print(printer);
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);
258 let err_span = if let Some(pattern) = local_visitor.found_arg_pattern {
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
265 // 3 | let _ = x.sum() as f64;
266 // | ^^^ cannot infer type for `S`
268 } else if let Some(ExprKind::MethodCall(_, call_span, _)) =
269 local_visitor.found_method_call.map(|e| &e.kind)
271 // Point at the call instead of the whole expression:
272 // error[E0284]: type annotations needed
275 // 2 | vec![Ok(2)].into_iter().collect()?;
276 // | ^^^^^^^ cannot infer type
278 // = note: cannot resolve `<_ as std::ops::Try>::Ok == _`
279 if span.contains(*call_span) { *call_span } else { span }
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)
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)
297 Some(ty) if is_named_and_not_impl_trait(ty) => {
298 let ty = ty_to_string(ty);
299 format!(" for `{}`", ty)
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>`":
308 // error[E0282]: type annotations needed for `std::result::Result<i32, E>`
311 // L | let b = Ok(4);
312 // | - ^^ cannot infer type for `E` in `std::result::Result<i32, E>`
314 // | consider giving `b` the explicit type `std::result::Result<i32, E>`, where
315 // | the type parameter `E` is specified
317 let error_code = error_code.into();
318 let mut err = self.tcx.sess.struct_span_err_with_code(
320 &format!("type annotations needed{}", ty_msg),
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();
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)),
335 if let Some((decl, body_id)) = closure_decl_and_body_id {
336 closure_return_type_suggestion(
340 self.tcx.hir().body(body_id),
347 // We don't want to give the other suggestions when the problem is the
348 // closure return type.
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)
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)
363 Some(ty) if is_named_and_not_impl_trait(ty) && ty.to_string() != name => {
364 let ty = ty_to_string(ty);
366 "the explicit type `{}`, where the type parameter `{}` is specified",
370 _ => "a type".to_string(),
373 if let Some(pattern) = local_visitor.found_arg_pattern {
374 // We don't want to show the default label for closures.
376 // So, before clearing, the output would look something like this:
379 // - ^^^^ cannot infer type for `[_; 0]`
381 // consider giving this closure parameter a type
384 // After clearing, it looks something like this:
387 // ^ consider giving this closure parameter the type `[_; 0]`
388 // with the type parameter `_` specified
392 format!("consider giving this closure parameter {}", suffix),
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()
401 _ => format!("this needs {}", suffix),
404 format!("consider giving this pattern {}", suffix)
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:
411 // error[E0282]: type annotations needed
412 // --> $DIR/type-annotations-needed-expr.rs:2:39
414 // LL | let _ = x.into_iter().sum() as f64;
417 // | cannot infer type for `S`
418 // | help: consider specifying the type argument in
419 // | the method call: `sum::<S>`
421 // = note: type must be known at this point
425 // error[E0282]: type annotations needed
426 // --> $DIR/issue-65611.rs:59:20
428 // LL | let x = buffer.last().unwrap().0.clone();
431 // | | cannot infer type for `T`
432 // | this method call resolves to `std::option::Option<&T>`
434 // = note: type must be known at this point
435 self.annotate_method_call(segment, e, &mut err);
438 // Instead of the following:
439 // error[E0282]: type annotations needed
442 // 3 | let _ = x.sum() as f64;
443 // | --^^^--------- cannot infer type for `S`
445 // = note: type must be known at this point
447 // error[E0282]: type annotations needed
450 // 3 | let _ = x.sum() as f64;
451 // | ^^^ cannot infer type for `S`
453 // = note: type must be known at this point
454 let span = name_sp.unwrap_or(err_span);
459 .any(|span_label| span_label.label.is_some() && span_label.span == span)
460 && local_visitor.found_arg_pattern.is_none()
462 // Avoid multiple labels pointing at `span`.
465 InferCtxt::missing_type_msg(&name, &descr, parent_name, parent_descr),
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(
476 segment: &hir::PathSegment<'_>,
478 err: &mut DiagnosticBuilder<'_>,
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(),
488 "consider specifying the type argument{} in the method call",
489 pluralize!(generics.params.len()),
496 .map(|p| p.name.to_string())
497 .collect::<Vec<String>>()
500 Applicability::HasPlaceholders,
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));
518 pub fn need_type_info_err_in_generator(
520 kind: hir::GeneratorKind,
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);
527 let mut err = struct_span_err!(
531 "type inside {} must be known in this context",
534 err.span_label(span, InferCtxt::missing_type_msg(&name, &descr, parent_name, parent_descr));
541 parent_name: Option<String>,
542 parent_descr: Option<&str>,
543 ) -> Cow<'static, str> {
544 if type_name == "_" {
545 "cannot infer type".into()
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)
554 format!(" declared on{} `{}`", parent_type_descr, parent_name)
559 format!("cannot infer type for {} `{}`{}", descr, type_name, parent_desc).into()