1 use crate::astconv::AstConv;
2 use crate::check::coercion::CoerceMany;
3 use crate::check::fn_ctxt::arg_matrix::{
4 ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx,
6 use crate::check::gather_locals::Declaration;
7 use crate::check::intrinsicck::InlineAsmCtxt;
8 use crate::check::method::MethodCallee;
9 use crate::check::Expectation::*;
10 use crate::check::TupleArgumentsFlag::*;
12 potentially_plural_count, struct_span_err, BreakableCtxt, Diverges, Expectation, FnCtxt,
13 LocalTy, Needs, TupleArgumentsFlag,
15 use crate::structured_errors::StructuredDiagnostic;
18 use rustc_errors::{Applicability, Diagnostic, DiagnosticId, MultiSpan};
20 use rustc_hir::def::{CtorOf, DefKind, Res};
21 use rustc_hir::def_id::DefId;
22 use rustc_hir::{ExprKind, Node, QPath};
23 use rustc_index::vec::IndexVec;
24 use rustc_infer::infer::error_reporting::{FailureCode, ObligationCauseExt};
25 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
26 use rustc_infer::infer::InferOk;
27 use rustc_infer::infer::TypeTrace;
28 use rustc_middle::ty::adjustment::AllowTwoPhase;
29 use rustc_middle::ty::visit::TypeVisitable;
30 use rustc_middle::ty::{self, DefIdTree, IsSuggestable, Ty};
31 use rustc_session::Session;
32 use rustc_span::symbol::Ident;
33 use rustc_span::{self, Span};
34 use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext};
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40 pub(in super::super) fn check_casts(&self) {
41 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
42 debug!("FnCtxt::check_casts: {} deferred checks", deferred_cast_checks.len());
43 for cast in deferred_cast_checks.drain(..) {
48 pub(in super::super) fn check_transmutes(&self) {
49 let mut deferred_transmute_checks = self.deferred_transmute_checks.borrow_mut();
50 debug!("FnCtxt::check_transmutes: {} deferred checks", deferred_transmute_checks.len());
51 for (from, to, span) in deferred_transmute_checks.drain(..) {
52 self.check_transmute(span, from, to);
56 pub(in super::super) fn check_asms(&self) {
57 let mut deferred_asm_checks = self.deferred_asm_checks.borrow_mut();
58 debug!("FnCtxt::check_asm: {} deferred checks", deferred_asm_checks.len());
59 for (asm, hir_id) in deferred_asm_checks.drain(..) {
60 let enclosing_id = self.tcx.hir().enclosing_body_owner(hir_id);
61 InlineAsmCtxt::new_in_fn(self).check_asm(asm, enclosing_id);
65 pub(in super::super) fn check_method_argument_types(
68 expr: &'tcx hir::Expr<'tcx>,
69 method: Result<MethodCallee<'tcx>, ()>,
70 args_no_rcvr: &'tcx [hir::Expr<'tcx>],
71 tuple_arguments: TupleArgumentsFlag,
72 expected: Expectation<'tcx>,
74 let has_error = match method {
75 Ok(method) => method.substs.references_error() || method.sig.references_error(),
79 let err_inputs = self.err_args(args_no_rcvr.len());
81 let err_inputs = match tuple_arguments {
82 DontTupleArguments => err_inputs,
83 TupleArguments => vec![self.tcx.intern_tup(&err_inputs)],
86 self.check_argument_types(
94 method.ok().map(|method| method.def_id),
96 return self.tcx.ty_error();
99 let method = method.unwrap();
100 // HACK(eddyb) ignore self in the definition (see above).
101 let expected_input_tys = self.expected_inputs_for_expected_output(
105 &method.sig.inputs()[1..],
107 self.check_argument_types(
110 &method.sig.inputs()[1..],
113 method.sig.c_variadic,
120 /// Generic function that factors out common logic from function calls,
121 /// method calls and overloaded operators.
122 pub(in super::super) fn check_argument_types(
124 // Span enclosing the call site
126 // Expression of the call site
127 call_expr: &'tcx hir::Expr<'tcx>,
128 // Types (as defined in the *signature* of the target function)
129 formal_input_tys: &[Ty<'tcx>],
130 // More specific expected types, after unifying with caller output types
131 expected_input_tys: Option<Vec<Ty<'tcx>>>,
132 // The expressions for each provided argument
133 provided_args: &'tcx [hir::Expr<'tcx>],
134 // Whether the function is variadic, for example when imported from C
136 // Whether the arguments have been bundled in a tuple (ex: closures)
137 tuple_arguments: TupleArgumentsFlag,
138 // The DefId for the function being called, for better error messages
139 fn_def_id: Option<DefId>,
143 // Conceptually, we've got some number of expected inputs, and some number of provided aguments
144 // and we can form a grid of whether each argument could satisfy a given input:
145 // in1 | in2 | in3 | ...
150 // Initially, we just check the diagonal, because in the case of correct code
151 // these are the only checks that matter
152 // However, in the unhappy path, we'll fill in this whole grid to attempt to provide
153 // better error messages about invalid method calls.
155 // All the input types from the fn signature must outlive the call
156 // so as to validate implied bounds.
157 for (&fn_input_ty, arg_expr) in iter::zip(formal_input_tys, provided_args) {
158 self.register_wf_obligation(fn_input_ty.into(), arg_expr.span, traits::MiscObligation);
161 let mut err_code = "E0061";
163 // If the arguments should be wrapped in a tuple (ex: closures), unwrap them here
164 let (formal_input_tys, expected_input_tys) = if tuple_arguments == TupleArguments {
165 let tuple_type = self.structurally_resolved_type(call_span, formal_input_tys[0]);
166 match tuple_type.kind() {
167 // We expected a tuple and got a tuple
168 ty::Tuple(arg_types) => {
169 // Argument length differs
170 if arg_types.len() != provided_args.len() {
173 let expected_input_tys = match expected_input_tys {
174 Some(expected_input_tys) => match expected_input_tys.get(0) {
175 Some(ty) => match ty.kind() {
176 ty::Tuple(tys) => Some(tys.iter().collect()),
183 (arg_types.iter().collect(), expected_input_tys)
186 // Otherwise, there's a mismatch, so clear out what we're expecting, and set
187 // our input types to err_args so we don't blow up the error messages
192 "cannot use call notation; the first type parameter \
193 for the function trait is neither a tuple nor unit"
196 (self.err_args(provided_args.len()), None)
200 (formal_input_tys.to_vec(), expected_input_tys)
203 // If there are no external expectations at the call site, just use the types from the function defn
204 let expected_input_tys = if let Some(expected_input_tys) = expected_input_tys {
205 assert_eq!(expected_input_tys.len(), formal_input_tys.len());
208 formal_input_tys.clone()
211 let minimum_input_count = expected_input_tys.len();
212 let provided_arg_count = provided_args.len();
214 // We introduce a helper function to demand that a given argument satisfy a given input
215 // This is more complicated than just checking type equality, as arguments could be coerced
216 // This version writes those types back so further type checking uses the narrowed types
217 let demand_compatible = |idx| {
218 let formal_input_ty: Ty<'tcx> = formal_input_tys[idx];
219 let expected_input_ty: Ty<'tcx> = expected_input_tys[idx];
220 let provided_arg = &provided_args[idx];
222 debug!("checking argument {}: {:?} = {:?}", idx, provided_arg, formal_input_ty);
224 // We're on the happy path here, so we'll do a more involved check and write back types
225 // To check compatibility, we'll do 3 things:
226 // 1. Unify the provided argument with the expected type
227 let expectation = Expectation::rvalue_hint(self, expected_input_ty);
229 let checked_ty = self.check_expr_with_expectation(provided_arg, expectation);
231 // 2. Coerce to the most detailed type that could be coerced
232 // to, which is `expected_ty` if `rvalue_hint` returns an
233 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
234 let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
236 // Cause selection errors caused by resolving a single argument to point at the
237 // argument and not the call. This lets us customize the span pointed to in the
238 // fulfillment error to be more accurate.
240 self.resolve_vars_with_obligations_and_mutate_fulfillment(coerced_ty, |errors| {
241 self.point_at_type_arg_instead_of_call_if_possible(errors, call_expr);
242 self.point_at_arg_instead_of_call_if_possible(
251 let coerce_error = self
252 .try_coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None)
255 if coerce_error.is_some() {
256 return Compatibility::Incompatible(coerce_error);
259 // 3. Check if the formal type is a supertype of the checked one
260 // and register any such obligations for future type checks
261 let supertype_error = self
262 .at(&self.misc(provided_arg.span), self.param_env)
263 .sup(formal_input_ty, coerced_ty);
264 let subtyping_error = match supertype_error {
265 Ok(InferOk { obligations, value: () }) => {
266 self.register_predicates(obligations);
269 Err(err) => Some(err),
272 // If neither check failed, the types are compatible
273 match subtyping_error {
274 None => Compatibility::Compatible,
275 Some(_) => Compatibility::Incompatible(subtyping_error),
279 // To start, we only care "along the diagonal", where we expect every
280 // provided arg to be in the right spot
281 let mut compatibility_diagonal =
282 vec![Compatibility::Incompatible(None); provided_args.len()];
284 // Keep track of whether we *could possibly* be satisfied, i.e. whether we're on the happy path
285 // if the wrong number of arguments were supplied, we CAN'T be satisfied,
286 // and if we're c_variadic, the supplied arguments must be >= the minimum count from the function
287 // otherwise, they need to be identical, because rust doesn't currently support variadic functions
288 let mut call_appears_satisfied = if c_variadic {
289 provided_arg_count >= minimum_input_count
291 provided_arg_count == minimum_input_count
294 // Check the arguments.
295 // We do this in a pretty awful way: first we type-check any arguments
296 // that are not closures, then we type-check the closures. This is so
297 // that we have more information about the types of arguments when we
298 // type-check the functions. This isn't really the right way to do this.
299 for check_closures in [false, true] {
300 // More awful hacks: before we check argument types, try to do
301 // an "opportunistic" trait resolution of any trait bounds on
302 // the call. This helps coercions.
304 self.select_obligations_where_possible(false, |errors| {
305 self.point_at_type_arg_instead_of_call_if_possible(errors, call_expr);
306 self.point_at_arg_instead_of_call_if_possible(
316 // Check each argument, to satisfy the input it was provided for
317 // Visually, we're traveling down the diagonal of the compatibility matrix
318 for (idx, arg) in provided_args.iter().enumerate() {
319 // Warn only for the first loop (the "no closures" one).
320 // Closure arguments themselves can't be diverging, but
321 // a previous argument can, e.g., `foo(panic!(), || {})`.
323 self.warn_if_unreachable(arg.hir_id, arg.span, "expression");
326 // For C-variadic functions, we don't have a declared type for all of
327 // the arguments hence we only do our usual type checking with
328 // the arguments who's types we do know. However, we *can* check
329 // for unreachable expressions (see above).
330 // FIXME: unreachable warning current isn't emitted
331 if idx >= minimum_input_count {
335 let is_closure = matches!(arg.kind, ExprKind::Closure { .. });
336 if is_closure != check_closures {
340 let compatible = demand_compatible(idx);
341 let is_compatible = matches!(compatible, Compatibility::Compatible);
342 compatibility_diagonal[idx] = compatible;
345 call_appears_satisfied = false;
350 if c_variadic && provided_arg_count < minimum_input_count {
354 for arg in provided_args.iter().skip(minimum_input_count) {
355 // Make sure we've checked this expr at least once.
356 let arg_ty = self.check_expr(&arg);
358 // If the function is c-style variadic, we skipped a bunch of arguments
359 // so we need to check those, and write out the types
360 // Ideally this would be folded into the above, for uniform style
361 // but c-variadic is already a corner case
363 fn variadic_error<'tcx>(
369 use crate::structured_errors::MissingCastForVariadicArg;
371 MissingCastForVariadicArg { sess, span, ty, cast_ty }.diagnostic().emit();
374 // There are a few types which get autopromoted when passed via varargs
375 // in C but we just error out instead and require explicit casts.
376 let arg_ty = self.structurally_resolved_type(arg.span, arg_ty);
377 match arg_ty.kind() {
378 ty::Float(ty::FloatTy::F32) => {
379 variadic_error(tcx.sess, arg.span, arg_ty, "c_double");
381 ty::Int(ty::IntTy::I8 | ty::IntTy::I16) | ty::Bool => {
382 variadic_error(tcx.sess, arg.span, arg_ty, "c_int");
384 ty::Uint(ty::UintTy::U8 | ty::UintTy::U16) => {
385 variadic_error(tcx.sess, arg.span, arg_ty, "c_uint");
388 let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx));
389 let ptr_ty = self.resolve_vars_if_possible(ptr_ty);
390 variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string());
397 if !call_appears_satisfied {
398 let compatibility_diagonal = IndexVec::from_raw(compatibility_diagonal);
399 let provided_args = IndexVec::from_iter(provided_args.iter().take(if c_variadic {
405 formal_input_tys.len(),
406 expected_input_tys.len(),
407 "expected formal_input_tys to be the same size as expected_input_tys"
409 let formal_and_expected_inputs = IndexVec::from_iter(
413 .zip(expected_input_tys.iter().copied())
414 .map(|vars| self.resolve_vars_if_possible(vars)),
417 self.report_arg_errors(
418 compatibility_diagonal,
419 formal_and_expected_inputs,
430 fn report_arg_errors(
432 compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
433 formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
434 provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
437 fn_def_id: Option<DefId>,
439 call_expr: &hir::Expr<'tcx>,
441 // Next, let's construct the error
442 let (error_span, full_call_span, ctor_of) = match &call_expr.kind {
444 hir::Expr { hir_id, span, kind: hir::ExprKind::Path(qpath), .. },
447 if let Res::Def(DefKind::Ctor(of, _), _) =
448 self.typeck_results.borrow().qpath_res(qpath, *hir_id)
450 (call_span, *span, Some(of))
452 (call_span, *span, None)
455 hir::ExprKind::Call(hir::Expr { span, .. }, _) => (call_span, *span, None),
456 hir::ExprKind::MethodCall(path_segment, _, span) => {
457 let ident_span = path_segment.ident.span;
458 let ident_span = if let Some(args) = path_segment.args {
459 ident_span.with_hi(args.span_ext.hi())
464 *span, ident_span, None, // methods are never ctors
467 k => span_bug!(call_span, "checking argument types on a non-call: `{:?}`", k),
469 let args_span = error_span.trim_start(full_call_span).unwrap_or(error_span);
470 let call_name = match ctor_of {
471 Some(CtorOf::Struct) => "struct",
472 Some(CtorOf::Variant) => "enum variant",
476 // Don't print if it has error types or is just plain `_`
477 fn has_error_or_infer<'tcx>(tys: impl IntoIterator<Item = Ty<'tcx>>) -> bool {
478 tys.into_iter().any(|ty| ty.references_error() || ty.is_ty_var())
481 self.set_tainted_by_errors();
484 // Precompute the provided types and spans, since that's all we typically need for below
485 let provided_arg_tys: IndexVec<ProvidedIdx, (Ty<'tcx>, Span)> = provided_args
491 .expr_ty_adjusted_opt(*expr)
492 .unwrap_or_else(|| tcx.ty_error());
493 (self.resolve_vars_if_possible(ty), expr.span)
496 let callee_expr = match &call_expr.peel_blocks().kind {
497 hir::ExprKind::Call(callee, _) => Some(*callee),
498 hir::ExprKind::MethodCall(_, callee, _) => {
499 if let Some((DefKind::AssocFn, def_id)) =
500 self.typeck_results.borrow().type_dependent_def(call_expr.hir_id)
501 && let Some(assoc) = tcx.opt_associated_item(def_id)
502 && assoc.fn_has_self_parameter
511 let callee_ty = callee_expr
512 .and_then(|callee_expr| self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr));
514 // A "softer" version of the `demand_compatible`, which checks types without persisting them,
515 // and treats error types differently
516 // This will allow us to "probe" for other argument orders that would likely have been correct
517 let check_compatible = |provided_idx: ProvidedIdx, expected_idx: ExpectedIdx| {
518 if provided_idx.as_usize() == expected_idx.as_usize() {
519 return compatibility_diagonal[provided_idx].clone();
522 let (formal_input_ty, expected_input_ty) = formal_and_expected_inputs[expected_idx];
523 // If either is an error type, we defy the usual convention and consider them to *not* be
524 // coercible. This prevents our error message heuristic from trying to pass errors into
526 if (formal_input_ty, expected_input_ty).references_error() {
527 return Compatibility::Incompatible(None);
530 let (arg_ty, arg_span) = provided_arg_tys[provided_idx];
532 let expectation = Expectation::rvalue_hint(self, expected_input_ty);
533 let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
534 let can_coerce = self.can_coerce(arg_ty, coerced_ty);
536 return Compatibility::Incompatible(None);
539 // Using probe here, since we don't want this subtyping to affect inference.
540 let subtyping_error = self.probe(|_| {
541 self.at(&self.misc(arg_span), self.param_env).sup(formal_input_ty, coerced_ty).err()
544 // Same as above: if either the coerce type or the checked type is an error type,
545 // consider them *not* compatible.
546 let references_error = (coerced_ty, arg_ty).references_error();
547 match (references_error, subtyping_error) {
548 (false, None) => Compatibility::Compatible,
549 (_, subtyping_error) => Compatibility::Incompatible(subtyping_error),
553 // The algorithm here is inspired by levenshtein distance and longest common subsequence.
554 // We'll try to detect 4 different types of mistakes:
555 // - An extra parameter has been provided that doesn't satisfy *any* of the other inputs
556 // - An input is missing, which isn't satisfied by *any* of the other arguments
557 // - Some number of arguments have been provided in the wrong order
558 // - A type is straight up invalid
560 // First, let's find the errors
561 let (mut errors, matched_inputs) =
562 ArgMatrix::new(provided_args.len(), formal_and_expected_inputs.len(), check_compatible)
565 // First, check if we just need to wrap some arguments in a tuple.
566 if let Some((mismatch_idx, terr)) =
567 compatibility_diagonal.iter().enumerate().find_map(|(i, c)| {
568 if let Compatibility::Incompatible(Some(terr)) = c { Some((i, terr)) } else { None }
571 // Is the first bad expected argument a tuple?
572 // Do we have as many extra provided arguments as the tuple's length?
573 // If so, we might have just forgotten to wrap some args in a tuple.
574 if let Some(ty::Tuple(tys)) =
575 formal_and_expected_inputs.get(mismatch_idx.into()).map(|tys| tys.1.kind())
576 // If the tuple is unit, we're not actually wrapping any arguments.
578 && provided_arg_tys.len() == formal_and_expected_inputs.len() - 1 + tys.len()
580 // Wrap up the N provided arguments starting at this position in a tuple.
581 let provided_as_tuple = tcx.mk_tup(
582 provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx).take(tys.len()),
585 let mut satisfied = true;
586 // Check if the newly wrapped tuple + rest of the arguments are compatible.
587 for ((_, expected_ty), provided_ty) in std::iter::zip(
588 formal_and_expected_inputs.iter().skip(mismatch_idx),
589 [provided_as_tuple].into_iter().chain(
590 provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx + tys.len()),
593 if !self.can_coerce(provided_ty, *expected_ty) {
599 // If they're compatible, suggest wrapping in an arg, and we're done!
600 // Take some care with spans, so we don't suggest wrapping a macro's
601 // innards in parenthesis, for example.
604 provided_args[mismatch_idx.into()].span.find_ancestor_inside(error_span)
605 && let Some(hi) = provided_args[(mismatch_idx + tys.len() - 1).into()]
607 .find_ancestor_inside(error_span)
611 // A tuple wrap suggestion actually occurs within,
612 // so don't do anything special here.
613 err = self.report_and_explain_type_error(
617 formal_and_expected_inputs[mismatch_idx.into()].1,
618 provided_arg_tys[mismatch_idx.into()].0,
624 format!("arguments to this {} are incorrect", call_name),
627 err = tcx.sess.struct_span_err_with_code(
630 "this {} takes {}{} but {} {} supplied",
632 if c_variadic { "at least " } else { "" },
633 potentially_plural_count(
634 formal_and_expected_inputs.len(),
637 potentially_plural_count(provided_args.len(), "argument"),
638 if provided_args.len() == 1 { "was" } else { "were" }
640 DiagnosticId::Error(err_code.to_owned()),
642 err.multipart_suggestion_verbose(
643 "wrap these arguments in parentheses to construct a tuple",
645 (lo.shrink_to_lo(), "(".to_string()),
646 (hi.shrink_to_hi(), ")".to_string()),
648 Applicability::MachineApplicable,
651 self.label_fn_like(&mut err, fn_def_id, callee_ty);
658 // Okay, so here's where it gets complicated in regards to what errors
660 // There are 3 different "types" of errors we might encounter.
661 // 1) Missing/extra/swapped arguments
662 // 2) Valid but incorrect arguments
663 // 3) Invalid arguments
664 // - Currently I think this only comes up with `CyclicTy`
666 // We first need to go through, remove those from (3) and emit those
667 // as their own error, particularly since they're error code and
668 // message is special. From what I can tell, we *must* emit these
669 // here (vs somewhere prior to this function) since the arguments
670 // become invalid *because* of how they get used in the function.
673 if errors.is_empty() {
674 if cfg!(debug_assertions) {
675 span_bug!(error_span, "expected errors from argument matrix");
680 "argument type mismatch was detected, \
681 but rustc had trouble determining where",
684 "we would appreciate a bug report: \
685 https://github.com/rust-lang/rust/issues/new",
692 errors.drain_filter(|error| {
693 let Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(error)) = error else { return false };
694 let (provided_ty, provided_span) = provided_arg_tys[*provided_idx];
695 let (expected_ty, _) = formal_and_expected_inputs[*expected_idx];
696 let cause = &self.misc(provided_span);
697 let trace = TypeTrace::types(cause, true, expected_ty, provided_ty);
698 if let Some(e) = error {
699 if !matches!(trace.cause.as_failure_code(e), FailureCode::Error0308(_)) {
700 self.report_and_explain_type_error(trace, e).emit();
707 // We're done if we found errors, but we already emitted them.
708 if errors.is_empty() {
712 // Okay, now that we've emitted the special errors separately, we
713 // are only left missing/extra/swapped and mismatched arguments, both
714 // can be collated pretty easily if needed.
716 // Next special case: if there is only one "Incompatible" error, just emit that
718 Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(err))),
721 let (formal_ty, expected_ty) = formal_and_expected_inputs[*expected_idx];
722 let (provided_ty, provided_arg_span) = provided_arg_tys[*provided_idx];
723 let cause = &self.misc(provided_arg_span);
724 let trace = TypeTrace::types(cause, true, expected_ty, provided_ty);
725 let mut err = self.report_and_explain_type_error(trace, err);
726 self.emit_coerce_suggestions(
728 &provided_args[*provided_idx],
730 Expectation::rvalue_hint(self, expected_ty)
732 .unwrap_or(formal_ty),
738 format!("arguments to this {} are incorrect", call_name),
740 // Call out where the function is defined
741 self.label_fn_like(&mut err, fn_def_id, callee_ty);
746 let mut err = if formal_and_expected_inputs.len() == provided_args.len() {
751 "arguments to this {} are incorrect",
755 tcx.sess.struct_span_err_with_code(
758 "this {} takes {}{} but {} {} supplied",
760 if c_variadic { "at least " } else { "" },
761 potentially_plural_count(formal_and_expected_inputs.len(), "argument"),
762 potentially_plural_count(provided_args.len(), "argument"),
763 if provided_args.len() == 1 { "was" } else { "were" }
765 DiagnosticId::Error(err_code.to_owned()),
769 // As we encounter issues, keep track of what we want to provide for the suggestion
770 let mut labels = vec![];
771 // If there is a single error, we give a specific suggestion; otherwise, we change to
772 // "did you mean" with the suggested function call
773 enum SuggestionText {
781 let mut suggestion_text = SuggestionText::None;
783 let mut errors = errors.into_iter().peekable();
784 while let Some(error) = errors.next() {
786 Error::Invalid(provided_idx, expected_idx, compatibility) => {
787 let (formal_ty, expected_ty) = formal_and_expected_inputs[expected_idx];
788 let (provided_ty, provided_span) = provided_arg_tys[provided_idx];
789 if let Compatibility::Incompatible(error) = &compatibility {
790 let cause = &self.misc(provided_span);
791 let trace = TypeTrace::types(cause, true, expected_ty, provided_ty);
792 if let Some(e) = error {
805 self.emit_coerce_suggestions(
807 &provided_args[provided_idx],
809 Expectation::rvalue_hint(self, expected_ty)
811 .unwrap_or(formal_ty),
816 Error::Extra(arg_idx) => {
817 let (provided_ty, provided_span) = provided_arg_tys[arg_idx];
818 let provided_ty_name = if !has_error_or_infer([provided_ty]) {
819 // FIXME: not suggestable, use something else
820 format!(" of type `{}`", provided_ty)
825 .push((provided_span, format!("argument{} unexpected", provided_ty_name)));
826 suggestion_text = match suggestion_text {
827 SuggestionText::None => SuggestionText::Remove(false),
828 SuggestionText::Remove(_) => SuggestionText::Remove(true),
829 _ => SuggestionText::DidYouMean,
832 Error::Missing(expected_idx) => {
833 // If there are multiple missing arguments adjacent to each other,
834 // then we can provide a single error.
836 let mut missing_idxs = vec![expected_idx];
837 while let Some(e) = errors.next_if(|e| {
838 matches!(e, Error::Missing(next_expected_idx)
839 if *next_expected_idx == *missing_idxs.last().unwrap() + 1)
842 Error::Missing(expected_idx) => missing_idxs.push(expected_idx),
847 // NOTE: Because we might be re-arranging arguments, might have extra
848 // arguments, etc. it's hard to *really* know where we should provide
849 // this error label, so as a heuristic, we point to the provided arg, or
850 // to the call if the missing inputs pass the provided args.
851 match &missing_idxs[..] {
853 let (_, input_ty) = formal_and_expected_inputs[expected_idx];
854 let span = if let Some((_, arg_span)) =
855 provided_arg_tys.get(expected_idx.to_provided_idx())
861 let rendered = if !has_error_or_infer([input_ty]) {
862 format!(" of type `{}`", input_ty)
866 labels.push((span, format!("an argument{} is missing", rendered)));
867 suggestion_text = match suggestion_text {
868 SuggestionText::None => SuggestionText::Provide(false),
869 SuggestionText::Provide(_) => SuggestionText::Provide(true),
870 _ => SuggestionText::DidYouMean,
873 &[first_idx, second_idx] => {
874 let (_, first_expected_ty) = formal_and_expected_inputs[first_idx];
875 let (_, second_expected_ty) = formal_and_expected_inputs[second_idx];
876 let span = if let (Some((_, first_span)), Some((_, second_span))) = (
877 provided_arg_tys.get(first_idx.to_provided_idx()),
878 provided_arg_tys.get(second_idx.to_provided_idx()),
880 first_span.to(*second_span)
885 if !has_error_or_infer([first_expected_ty, second_expected_ty]) {
887 " of type `{}` and `{}`",
888 first_expected_ty, second_expected_ty
893 labels.push((span, format!("two arguments{} are missing", rendered)));
894 suggestion_text = match suggestion_text {
895 SuggestionText::None | SuggestionText::Provide(_) => {
896 SuggestionText::Provide(true)
898 _ => SuggestionText::DidYouMean,
901 &[first_idx, second_idx, third_idx] => {
902 let (_, first_expected_ty) = formal_and_expected_inputs[first_idx];
903 let (_, second_expected_ty) = formal_and_expected_inputs[second_idx];
904 let (_, third_expected_ty) = formal_and_expected_inputs[third_idx];
905 let span = if let (Some((_, first_span)), Some((_, third_span))) = (
906 provided_arg_tys.get(first_idx.to_provided_idx()),
907 provided_arg_tys.get(third_idx.to_provided_idx()),
909 first_span.to(*third_span)
913 let rendered = if !has_error_or_infer([
919 " of type `{}`, `{}`, and `{}`",
920 first_expected_ty, second_expected_ty, third_expected_ty
925 labels.push((span, format!("three arguments{} are missing", rendered)));
926 suggestion_text = match suggestion_text {
927 SuggestionText::None | SuggestionText::Provide(_) => {
928 SuggestionText::Provide(true)
930 _ => SuggestionText::DidYouMean,
934 let first_idx = *missing_idxs.first().unwrap();
935 let last_idx = *missing_idxs.last().unwrap();
936 // NOTE: Because we might be re-arranging arguments, might have extra arguments, etc.
937 // It's hard to *really* know where we should provide this error label, so this is a
939 let span = if let (Some((_, first_span)), Some((_, last_span))) = (
940 provided_arg_tys.get(first_idx.to_provided_idx()),
941 provided_arg_tys.get(last_idx.to_provided_idx()),
943 first_span.to(*last_span)
947 labels.push((span, format!("multiple arguments are missing")));
948 suggestion_text = match suggestion_text {
949 SuggestionText::None | SuggestionText::Provide(_) => {
950 SuggestionText::Provide(true)
952 _ => SuggestionText::DidYouMean,
963 let (first_provided_ty, first_span) = provided_arg_tys[first_provided_idx];
964 let (_, first_expected_ty) = formal_and_expected_inputs[first_expected_idx];
965 let first_provided_ty_name = if !has_error_or_infer([first_provided_ty]) {
966 format!(", found `{}`", first_provided_ty)
972 format!("expected `{}`{}", first_expected_ty, first_provided_ty_name),
975 let (second_provided_ty, second_span) = provided_arg_tys[second_provided_idx];
976 let (_, second_expected_ty) = formal_and_expected_inputs[second_expected_idx];
977 let second_provided_ty_name = if !has_error_or_infer([second_provided_ty]) {
978 format!(", found `{}`", second_provided_ty)
984 format!("expected `{}`{}", second_expected_ty, second_provided_ty_name),
987 suggestion_text = match suggestion_text {
988 SuggestionText::None => SuggestionText::Swap,
989 _ => SuggestionText::DidYouMean,
992 Error::Permutation(args) => {
993 for (dst_arg, dest_input) in args {
994 let (_, expected_ty) = formal_and_expected_inputs[dst_arg];
995 let (provided_ty, provided_span) = provided_arg_tys[dest_input];
996 let provided_ty_name = if !has_error_or_infer([provided_ty]) {
997 format!(", found `{}`", provided_ty)
1003 format!("expected `{}`{}", expected_ty, provided_ty_name),
1007 suggestion_text = match suggestion_text {
1008 SuggestionText::None => SuggestionText::Reorder,
1009 _ => SuggestionText::DidYouMean,
1015 // If we have less than 5 things to say, it would be useful to call out exactly what's wrong
1016 if labels.len() <= 5 {
1017 for (span, label) in labels {
1018 err.span_label(span, label);
1022 // Call out where the function is defined
1023 self.label_fn_like(&mut err, fn_def_id, callee_ty);
1025 // And add a suggestion block for all of the parameters
1026 let suggestion_text = match suggestion_text {
1027 SuggestionText::None => None,
1028 SuggestionText::Provide(plural) => {
1029 Some(format!("provide the argument{}", if plural { "s" } else { "" }))
1031 SuggestionText::Remove(plural) => {
1032 Some(format!("remove the extra argument{}", if plural { "s" } else { "" }))
1034 SuggestionText::Swap => Some("swap these arguments".to_string()),
1035 SuggestionText::Reorder => Some("reorder these arguments".to_string()),
1036 SuggestionText::DidYouMean => Some("did you mean".to_string()),
1038 if let Some(suggestion_text) = suggestion_text {
1039 let source_map = self.sess().source_map();
1040 let mut suggestion = format!(
1042 source_map.span_to_snippet(full_call_span).unwrap_or_else(|_| fn_def_id
1043 .map_or("".to_string(), |fn_def_id| tcx.item_name(fn_def_id).to_string()))
1045 let mut needs_comma = false;
1046 for (expected_idx, provided_idx) in matched_inputs.iter_enumerated() {
1052 let suggestion_text = if let Some(provided_idx) = provided_idx
1053 && let (_, provided_span) = provided_arg_tys[*provided_idx]
1054 && let Ok(arg_text) =
1055 source_map.span_to_snippet(provided_span.source_callsite())
1059 // Propose a placeholder of the correct type
1060 let (_, expected_ty) = formal_and_expected_inputs[expected_idx];
1061 if expected_ty.is_unit() {
1063 } else if expected_ty.is_suggestable(tcx) {
1064 format!("/* {} */", expected_ty)
1066 "/* value */".to_string()
1069 suggestion += &suggestion_text;
1072 err.span_suggestion_verbose(
1076 Applicability::HasPlaceholders,
1083 // AST fragment checking
1084 pub(in super::super) fn check_lit(
1087 expected: Expectation<'tcx>,
1092 ast::LitKind::Str(..) => tcx.mk_static_str(),
1093 ast::LitKind::ByteStr(ref v) => {
1094 tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_array(tcx.types.u8, v.len() as u64))
1096 ast::LitKind::Byte(_) => tcx.types.u8,
1097 ast::LitKind::Char(_) => tcx.types.char,
1098 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(ty::int_ty(t)),
1099 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(ty::uint_ty(t)),
1100 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
1101 let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
1102 ty::Int(_) | ty::Uint(_) => Some(ty),
1103 ty::Char => Some(tcx.types.u8),
1104 ty::RawPtr(..) => Some(tcx.types.usize),
1105 ty::FnDef(..) | ty::FnPtr(_) => Some(tcx.types.usize),
1108 opt_ty.unwrap_or_else(|| self.next_int_var())
1110 ast::LitKind::Float(_, ast::LitFloatType::Suffixed(t)) => {
1111 tcx.mk_mach_float(ty::float_ty(t))
1113 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
1114 let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
1115 ty::Float(_) => Some(ty),
1118 opt_ty.unwrap_or_else(|| self.next_float_var())
1120 ast::LitKind::Bool(_) => tcx.types.bool,
1121 ast::LitKind::Err(_) => tcx.ty_error(),
1125 pub fn check_struct_path(
1129 ) -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
1130 let path_span = qpath.span();
1131 let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, hir_id);
1132 let variant = match def {
1134 self.set_tainted_by_errors();
1137 Res::Def(DefKind::Variant, _) => match ty.kind() {
1138 ty::Adt(adt, substs) => Some((adt.variant_of_res(def), adt.did(), substs)),
1139 _ => bug!("unexpected type: {:?}", ty),
1141 Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _)
1142 | Res::SelfTy { .. } => match ty.kind() {
1143 ty::Adt(adt, substs) if !adt.is_enum() => {
1144 Some((adt.non_enum_variant(), adt.did(), substs))
1148 _ => bug!("unexpected definition: {:?}", def),
1151 if let Some((variant, did, substs)) = variant {
1152 debug!("check_struct_path: did={:?} substs={:?}", did, substs);
1153 self.write_user_type_annotation_from_substs(hir_id, did, substs, None);
1155 // Check bounds on type arguments used in the path.
1156 self.add_required_obligations(path_span, did, substs);
1162 // E0071 might be caused by a spelling error, which will have
1163 // already caused an error message and probably a suggestion
1164 // elsewhere. Refrain from emitting more unhelpful errors here
1172 "expected struct, variant or union type, found {}",
1173 ty.sort_string(self.tcx)
1175 .span_label(path_span, "not a struct")
1183 pub fn check_decl_initializer(
1186 pat: &'tcx hir::Pat<'tcx>,
1187 init: &'tcx hir::Expr<'tcx>,
1189 // FIXME(tschottdorf): `contains_explicit_ref_binding()` must be removed
1190 // for #42640 (default match binding modes).
1193 let ref_bindings = pat.contains_explicit_ref_binding();
1195 let local_ty = self.local_ty(init.span, hir_id).revealed_ty;
1196 if let Some(m) = ref_bindings {
1197 // Somewhat subtle: if we have a `ref` binding in the pattern,
1198 // we want to avoid introducing coercions for the RHS. This is
1199 // both because it helps preserve sanity and, in the case of
1200 // ref mut, for soundness (issue #23116). In particular, in
1201 // the latter case, we need to be clear that the type of the
1202 // referent for the reference that results is *equal to* the
1203 // type of the place it is referencing, and not some
1204 // supertype thereof.
1205 let init_ty = self.check_expr_with_needs(init, Needs::maybe_mut_place(m));
1206 self.demand_eqtype(init.span, local_ty, init_ty);
1209 self.check_expr_coercable_to_type(init, local_ty, None)
1213 pub(in super::super) fn check_decl(&self, decl: Declaration<'tcx>) {
1214 // Determine and write the type which we'll check the pattern against.
1215 let decl_ty = self.local_ty(decl.span, decl.hir_id).decl_ty;
1216 self.write_ty(decl.hir_id, decl_ty);
1218 // Type check the initializer.
1219 if let Some(ref init) = decl.init {
1220 let init_ty = self.check_decl_initializer(decl.hir_id, decl.pat, &init);
1221 self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, decl_ty, init_ty);
1224 // Does the expected pattern type originate from an expression and what is the span?
1225 let (origin_expr, ty_span) = match (decl.ty, decl.init) {
1226 (Some(ty), _) => (false, Some(ty.span)), // Bias towards the explicit user type.
1227 (_, Some(init)) => (true, Some(init.span)), // No explicit type; so use the scrutinee.
1228 _ => (false, None), // We have `let $pat;`, so the expected type is unconstrained.
1231 // Type check the pattern. Override if necessary to avoid knock-on errors.
1232 self.check_pat_top(&decl.pat, decl_ty, ty_span, origin_expr);
1233 let pat_ty = self.node_ty(decl.pat.hir_id);
1234 self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, decl_ty, pat_ty);
1236 if let Some(blk) = decl.els {
1237 let previous_diverges = self.diverges.get();
1238 let else_ty = self.check_block_with_expected(blk, NoExpectation);
1239 let cause = self.cause(blk.span, ObligationCauseCode::LetElse);
1240 if let Some(mut err) =
1241 self.demand_eqtype_with_origin(&cause, self.tcx.types.never, else_ty)
1245 self.diverges.set(previous_diverges);
1249 /// Type check a `let` statement.
1250 pub fn check_decl_local(&self, local: &'tcx hir::Local<'tcx>) {
1251 self.check_decl(local.into());
1254 pub fn check_stmt(&self, stmt: &'tcx hir::Stmt<'tcx>, is_last: bool) {
1255 // Don't do all the complex logic below for `DeclItem`.
1257 hir::StmtKind::Item(..) => return,
1258 hir::StmtKind::Local(..) | hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {}
1261 self.warn_if_unreachable(stmt.hir_id, stmt.span, "statement");
1263 // Hide the outer diverging and `has_errors` flags.
1264 let old_diverges = self.diverges.replace(Diverges::Maybe);
1265 let old_has_errors = self.has_errors.replace(false);
1268 hir::StmtKind::Local(l) => {
1269 self.check_decl_local(l);
1272 hir::StmtKind::Item(_) => {}
1273 hir::StmtKind::Expr(ref expr) => {
1274 // Check with expected type of `()`.
1275 self.check_expr_has_type_or_error(&expr, self.tcx.mk_unit(), |err| {
1276 if expr.can_have_side_effects() {
1277 self.suggest_semicolon_at_end(expr.span, err);
1281 hir::StmtKind::Semi(ref expr) => {
1282 // All of this is equivalent to calling `check_expr`, but it is inlined out here
1283 // in order to capture the fact that this `match` is the last statement in its
1284 // function. This is done for better suggestions to remove the `;`.
1285 let expectation = match expr.kind {
1286 hir::ExprKind::Match(..) if is_last => IsLast(stmt.span),
1289 self.check_expr_with_expectation(expr, expectation);
1293 // Combine the diverging and `has_error` flags.
1294 self.diverges.set(self.diverges.get() | old_diverges);
1295 self.has_errors.set(self.has_errors.get() | old_has_errors);
1298 pub fn check_block_no_value(&self, blk: &'tcx hir::Block<'tcx>) {
1299 let unit = self.tcx.mk_unit();
1300 let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
1302 // if the block produces a `!` value, that can always be
1303 // (effectively) coerced to unit.
1305 self.demand_suptype(blk.span, unit, ty);
1309 pub(in super::super) fn check_block_with_expected(
1311 blk: &'tcx hir::Block<'tcx>,
1312 expected: Expectation<'tcx>,
1314 let prev = self.ps.replace(self.ps.get().recurse(blk));
1316 // In some cases, blocks have just one exit, but other blocks
1317 // can be targeted by multiple breaks. This can happen both
1318 // with labeled blocks as well as when we desugar
1319 // a `try { ... }` expression.
1323 // 'a: { if true { break 'a Err(()); } Ok(()) }
1325 // Here we would wind up with two coercions, one from
1326 // `Err(())` and the other from the tail expression
1327 // `Ok(())`. If the tail expression is omitted, that's a
1328 // "forced unit" -- unless the block diverges, in which
1329 // case we can ignore the tail expression (e.g., `'a: {
1330 // break 'a 22; }` would not force the type of the block
1332 let tail_expr = blk.expr.as_ref();
1333 let coerce_to_ty = expected.coercion_target_type(self, blk.span);
1334 let coerce = if blk.targeted_by_break {
1335 CoerceMany::new(coerce_to_ty)
1337 let tail_expr: &[&hir::Expr<'_>] = match tail_expr {
1338 Some(e) => slice::from_ref(e),
1341 CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
1344 let prev_diverges = self.diverges.get();
1345 let ctxt = BreakableCtxt { coerce: Some(coerce), may_break: false };
1347 let (ctxt, ()) = self.with_breakable_ctxt(blk.hir_id, ctxt, || {
1348 for (pos, s) in blk.stmts.iter().enumerate() {
1349 self.check_stmt(s, blk.stmts.len() - 1 == pos);
1352 // check the tail expression **without** holding the
1353 // `enclosing_breakables` lock below.
1354 let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
1356 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1357 let ctxt = enclosing_breakables.find_breakable(blk.hir_id);
1358 let coerce = ctxt.coerce.as_mut().unwrap();
1359 if let Some(tail_expr_ty) = tail_expr_ty {
1360 let tail_expr = tail_expr.unwrap();
1361 let span = self.get_expr_coercion_span(tail_expr);
1362 let cause = self.cause(span, ObligationCauseCode::BlockTailExpression(blk.hir_id));
1363 let ty_for_diagnostic = coerce.merged_ty();
1364 // We use coerce_inner here because we want to augment the error
1365 // suggesting to wrap the block in square brackets if it might've
1366 // been mistaken array syntax
1367 coerce.coerce_inner(
1372 Some(&mut |diag: &mut Diagnostic| {
1373 self.suggest_block_to_brackets(diag, blk, tail_expr_ty, ty_for_diagnostic);
1378 // Subtle: if there is no explicit tail expression,
1379 // that is typically equivalent to a tail expression
1380 // of `()` -- except if the block diverges. In that
1381 // case, there is no value supplied from the tail
1382 // expression (assuming there are no other breaks,
1383 // this implies that the type of the block will be
1386 // #41425 -- label the implicit `()` as being the
1387 // "found type" here, rather than the "expected type".
1388 if !self.diverges.get().is_always() {
1389 // #50009 -- Do not point at the entire fn block span, point at the return type
1390 // span, as it is the cause of the requirement, and
1391 // `consider_hint_about_removing_semicolon` will point at the last expression
1392 // if it were a relevant part of the error. This improves usability in editors
1393 // that highlight errors inline.
1394 let mut sp = blk.span;
1395 let mut fn_span = None;
1396 if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) {
1397 let ret_sp = decl.output.span();
1398 if let Some(block_sp) = self.parent_item_span(blk.hir_id) {
1399 // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the
1400 // output would otherwise be incorrect and even misleading. Make sure
1401 // the span we're aiming at correspond to a `fn` body.
1402 if block_sp == blk.span {
1404 fn_span = Some(ident.span);
1408 coerce.coerce_forced_unit(
1412 if let Some(expected_ty) = expected.only_has_type(self) {
1413 if !self.consider_removing_semicolon(blk, expected_ty, err) {
1414 self.consider_returning_binding(blk, expected_ty, err);
1416 if expected_ty == self.tcx.types.bool {
1417 // If this is caused by a missing `let` in a `while let`,
1418 // silence this redundant error, as we already emit E0070.
1420 // Our block must be a `assign desugar local; assignment`
1421 if let Some(hir::Node::Block(hir::Block {
1426 hir::StmtKind::Local(hir::Local {
1428 hir::LocalSource::AssignDesugar(_),
1435 hir::StmtKind::Expr(hir::Expr {
1436 kind: hir::ExprKind::Assign(..),
1443 })) = self.tcx.hir().find(blk.hir_id)
1445 self.comes_from_while_condition(blk.hir_id, |_| {
1446 err.downgrade_to_delayed_bug();
1451 if let Some(fn_span) = fn_span {
1454 "implicitly returns `()` as its body has no tail or `return` \
1466 // If we can break from the block, then the block's exit is always reachable
1467 // (... as long as the entry is reachable) - regardless of the tail of the block.
1468 self.diverges.set(prev_diverges);
1471 let mut ty = ctxt.coerce.unwrap().complete(self);
1473 if self.has_errors.get() || ty.references_error() {
1474 ty = self.tcx.ty_error()
1477 self.write_ty(blk.hir_id, ty);
1483 fn parent_item_span(&self, id: hir::HirId) -> Option<Span> {
1484 let node = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(id));
1486 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })
1487 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => {
1488 let body = self.tcx.hir().body(body_id);
1489 if let ExprKind::Block(block, _) = &body.value.kind {
1490 return Some(block.span);
1498 /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise.
1499 fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident)> {
1500 let parent = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(blk_id));
1501 self.get_node_fn_decl(parent).map(|(fn_decl, ident, _)| (fn_decl, ident))
1504 /// If `expr` is a `match` expression that has only one non-`!` arm, use that arm's tail
1505 /// expression's `Span`, otherwise return `expr.span`. This is done to give better errors
1506 /// when given code like the following:
1508 /// if false { return 0i32; } else { 1u32 }
1509 /// // ^^^^ point at this instead of the whole `if` expression
1511 fn get_expr_coercion_span(&self, expr: &hir::Expr<'_>) -> rustc_span::Span {
1512 let check_in_progress = |elem: &hir::Expr<'_>| {
1513 self.in_progress_typeck_results
1514 .and_then(|typeck_results| typeck_results.borrow().node_type_opt(elem.hir_id))
1519 Some(match elem.kind {
1520 // Point at the tail expression when possible.
1521 hir::ExprKind::Block(block, _) => {
1522 block.expr.map_or(block.span, |e| e.span)
1530 if let hir::ExprKind::If(_, _, Some(el)) = expr.kind {
1531 if let Some(rslt) = check_in_progress(el) {
1536 if let hir::ExprKind::Match(_, arms, _) = expr.kind {
1537 let mut iter = arms.iter().filter_map(|arm| check_in_progress(arm.body));
1538 if let Some(span) = iter.next() {
1539 if iter.next().is_none() {
1548 fn overwrite_local_ty_if_err(
1551 pat: &'tcx hir::Pat<'tcx>,
1555 if ty.references_error() {
1556 // Override the types everywhere with `err()` to avoid knock on errors.
1557 self.write_ty(hir_id, ty);
1558 self.write_ty(pat.hir_id, ty);
1559 let local_ty = LocalTy { decl_ty, revealed_ty: ty };
1560 self.locals.borrow_mut().insert(hir_id, local_ty);
1561 self.locals.borrow_mut().insert(pat.hir_id, local_ty);
1565 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
1566 // The newly resolved definition is written into `type_dependent_defs`.
1567 fn finish_resolving_struct_path(
1572 ) -> (Res, Ty<'tcx>) {
1574 QPath::Resolved(ref maybe_qself, ref path) => {
1575 let self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
1576 let ty = <dyn AstConv<'_>>::res_to_ty(self, self_ty, path, true);
1579 QPath::TypeRelative(ref qself, ref segment) => {
1580 let ty = self.to_ty(qself);
1582 let result = <dyn AstConv<'_>>::associated_path_to_ty(
1583 self, hir_id, path_span, ty, qself, segment, true,
1585 let ty = result.map(|(ty, _, _)| ty).unwrap_or_else(|_| self.tcx().ty_error());
1586 let result = result.map(|(_, kind, def_id)| (kind, def_id));
1588 // Write back the new resolution.
1589 self.write_resolution(hir_id, result);
1591 (result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), ty)
1593 QPath::LangItem(lang_item, span, id) => {
1594 self.resolve_lang_item_path(lang_item, span, hir_id, id)
1599 /// Given a vec of evaluated `FulfillmentError`s and an `fn` call argument expressions, we walk
1600 /// the checked and coerced types for each argument to see if any of the `FulfillmentError`s
1601 /// reference a type argument. The reason to walk also the checked type is that the coerced type
1602 /// can be not easily comparable with predicate type (because of coercion). If the types match
1603 /// for either checked or coerced type, and there's only *one* argument that does, we point at
1604 /// the corresponding argument's expression span instead of the `fn` call path span.
1605 fn point_at_arg_instead_of_call_if_possible(
1607 errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1608 expr: &'tcx hir::Expr<'tcx>,
1610 args: &'tcx [hir::Expr<'tcx>],
1611 expected_tys: &[Ty<'tcx>],
1613 // We *do not* do this for desugared call spans to keep good diagnostics when involving
1614 // the `?` operator.
1615 if call_sp.desugaring_kind().is_some() {
1619 'outer: for error in errors {
1620 // Only if the cause is somewhere inside the expression we want try to point at arg.
1621 // Otherwise, it means that the cause is somewhere else and we should not change
1622 // anything because we can break the correct span.
1623 if !call_sp.contains(error.obligation.cause.span) {
1627 // Peel derived obligation, because it's the type that originally
1628 // started this inference chain that matters, not the one we wound
1629 // up with at the end.
1630 fn unpeel_to_top<'a, 'tcx>(
1631 mut code: &'a ObligationCauseCode<'tcx>,
1632 ) -> &'a ObligationCauseCode<'tcx> {
1633 let mut result_code = code;
1635 let parent = match code {
1636 ObligationCauseCode::ImplDerivedObligation(c) => &c.derived.parent_code,
1637 ObligationCauseCode::BuiltinDerivedObligation(c)
1638 | ObligationCauseCode::DerivedObligation(c) => &c.parent_code,
1639 _ => break result_code,
1641 (result_code, code) = (code, parent);
1644 let self_: ty::subst::GenericArg<'_> =
1645 match unpeel_to_top(error.obligation.cause.code()) {
1646 ObligationCauseCode::BuiltinDerivedObligation(code)
1647 | ObligationCauseCode::DerivedObligation(code) => {
1648 code.parent_trait_pred.self_ty().skip_binder().into()
1650 ObligationCauseCode::ImplDerivedObligation(code) => {
1651 code.derived.parent_trait_pred.self_ty().skip_binder().into()
1653 _ if let ty::PredicateKind::Trait(predicate) =
1654 error.obligation.predicate.kind().skip_binder() =>
1656 predicate.self_ty().into()
1660 let self_ = self.resolve_vars_if_possible(self_);
1661 let ty_matches_self = |ty: Ty<'tcx>| ty.walk().any(|arg| arg == self_);
1663 let typeck_results = self.typeck_results.borrow();
1665 for (idx, arg) in args.iter().enumerate() {
1666 // Don't adjust the span if we already have a more precise span
1667 // within one of the args.
1668 if arg.span.contains(error.obligation.cause.span) {
1669 let references_arg =
1670 typeck_results.expr_ty_opt(arg).map_or(false, &ty_matches_self)
1671 || expected_tys.get(idx).copied().map_or(false, &ty_matches_self);
1672 if references_arg && !arg.span.from_expansion() {
1673 error.obligation.cause.map_code(|parent_code| {
1674 ObligationCauseCode::FunctionArgumentObligation {
1675 arg_hir_id: args[idx].hir_id,
1676 call_hir_id: expr.hir_id,
1685 // Collect the argument position for all arguments that could have caused this
1686 // `FulfillmentError`.
1687 let mut referenced_in: Vec<_> = std::iter::zip(expected_tys, args)
1689 .flat_map(|(idx, (expected_ty, arg))| {
1690 if let Some(arg_ty) = typeck_results.expr_ty_opt(arg) {
1691 vec![(idx, arg_ty), (idx, *expected_ty)]
1696 .filter_map(|(i, ty)| {
1697 let ty = self.resolve_vars_if_possible(ty);
1698 // We walk the argument type because the argument's type could have
1699 // been `Option<T>`, but the `FulfillmentError` references `T`.
1700 if ty_matches_self(ty) { Some(i) } else { None }
1704 // Both checked and coerced types could have matched, thus we need to remove
1707 // We sort primitive type usize here and can use unstable sort
1708 referenced_in.sort_unstable();
1709 referenced_in.dedup();
1711 if let &[idx] = &referenced_in[..] {
1712 // Do not point at the inside of a macro.
1713 // That would often result in poor error messages.
1714 if args[idx].span.from_expansion() {
1717 // We make sure that only *one* argument matches the obligation failure
1718 // and we assign the obligation's span to its expression's.
1719 error.obligation.cause.span = args[idx].span;
1720 error.obligation.cause.map_code(|parent_code| {
1721 ObligationCauseCode::FunctionArgumentObligation {
1722 arg_hir_id: args[idx].hir_id,
1723 call_hir_id: expr.hir_id,
1727 } else if error.obligation.cause.span == call_sp {
1728 // Make function calls point at the callee, not the whole thing.
1729 if let hir::ExprKind::Call(callee, _) = expr.kind {
1730 error.obligation.cause.span = callee.span;
1736 /// Given a vec of evaluated `FulfillmentError`s and an `fn` call expression, we walk the
1737 /// `PathSegment`s and resolve their type parameters to see if any of the `FulfillmentError`s
1738 /// were caused by them. If they were, we point at the corresponding type argument's span
1739 /// instead of the `fn` call path span.
1740 fn point_at_type_arg_instead_of_call_if_possible(
1742 errors: &mut Vec<traits::FulfillmentError<'tcx>>,
1743 call_expr: &'tcx hir::Expr<'tcx>,
1745 if let hir::ExprKind::Call(path, _) = &call_expr.kind {
1746 if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &path.kind {
1747 for error in errors {
1748 if let ty::PredicateKind::Trait(predicate) =
1749 error.obligation.predicate.kind().skip_binder()
1751 // If any of the type arguments in this path segment caused the
1752 // `FulfillmentError`, point at its span (#61860).
1756 .filter_map(|seg| seg.args.as_ref())
1757 .flat_map(|a| a.args.iter())
1759 if let hir::GenericArg::Type(hir_ty) = &arg {
1760 let ty = self.resolve_vars_if_possible(
1761 self.typeck_results.borrow().node_type(hir_ty.hir_id),
1763 if ty == predicate.self_ty() {
1764 error.obligation.cause.span = hir_ty.span;
1776 err: &mut rustc_errors::DiagnosticBuilder<'tcx, rustc_errors::ErrorGuaranteed>,
1777 callable_def_id: Option<DefId>,
1778 callee_ty: Option<Ty<'tcx>>,
1780 let Some(mut def_id) = callable_def_id else {
1784 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id)
1785 // Possibly points at either impl or trait item, so try to get it
1786 // to point to trait item, then get the parent.
1787 // This parent might be an impl in the case of an inherent function,
1788 // but the next check will fail.
1789 && let maybe_trait_item_def_id = assoc_item.trait_item_def_id.unwrap_or(def_id)
1790 && let maybe_trait_def_id = self.tcx.parent(maybe_trait_item_def_id)
1791 // Just an easy way to check "trait_def_id == Fn/FnMut/FnOnce"
1792 && let Some(call_kind) = ty::ClosureKind::from_def_id(self.tcx, maybe_trait_def_id)
1793 && let Some(callee_ty) = callee_ty
1795 let callee_ty = callee_ty.peel_refs();
1796 match *callee_ty.kind() {
1797 ty::Param(param) => {
1799 self.tcx.generics_of(self.body_id.owner).type_param(¶m, self.tcx);
1800 if param.kind.is_synthetic() {
1801 // if it's `impl Fn() -> ..` then just fall down to the def-id based logic
1802 def_id = param.def_id;
1804 // Otherwise, find the predicate that makes this generic callable,
1805 // and point at that.
1806 let instantiated = self
1808 .explicit_predicates_of(self.body_id.owner)
1809 .instantiate_identity(self.tcx);
1810 // FIXME(compiler-errors): This could be problematic if something has two
1811 // fn-like predicates with different args, but callable types really never
1812 // do that, so it's OK.
1813 for (predicate, span) in
1814 std::iter::zip(instantiated.predicates, instantiated.spans)
1816 if let ty::PredicateKind::Trait(pred) = predicate.kind().skip_binder()
1817 && pred.self_ty().peel_refs() == callee_ty
1818 && ty::ClosureKind::from_def_id(self.tcx, pred.def_id()).is_some()
1820 err.span_note(span, "callable defined here");
1826 ty::Opaque(new_def_id, _)
1827 | ty::Closure(new_def_id, _)
1828 | ty::FnDef(new_def_id, _) => {
1829 def_id = new_def_id;
1832 // Look for a user-provided impl of a `Fn` trait, and point to it.
1833 let new_def_id = self.probe(|_| {
1834 let trait_ref = ty::TraitRef::new(
1835 call_kind.to_def_id(self.tcx),
1836 self.tcx.mk_substs([
1837 ty::GenericArg::from(callee_ty),
1838 self.next_ty_var(TypeVariableOrigin {
1839 kind: TypeVariableOriginKind::MiscVariable,
1840 span: rustc_span::DUMMY_SP,
1845 let obligation = traits::Obligation::new(
1846 traits::ObligationCause::dummy(),
1848 ty::Binder::dummy(ty::TraitPredicate {
1850 constness: ty::BoundConstness::NotConst,
1851 polarity: ty::ImplPolarity::Positive,
1854 match SelectionContext::new(&self).select(&obligation) {
1855 Ok(Some(traits::ImplSource::UserDefined(impl_source))) => {
1856 Some(impl_source.impl_def_id)
1861 if let Some(new_def_id) = new_def_id {
1862 def_id = new_def_id;
1870 if let Some(def_span) = self.tcx.def_ident_span(def_id) && !def_span.is_dummy() {
1871 let mut spans: MultiSpan = def_span.into();
1876 .get_if_local(def_id)
1877 .and_then(|node| node.body_id())
1879 .flat_map(|id| self.tcx.hir().body(id).params);
1881 for param in params {
1882 spans.push_span_label(param.span, "");
1885 let def_kind = self.tcx.def_kind(def_id);
1886 err.span_note(spans, &format!("{} defined here", def_kind.descr(def_id)));
1888 let def_kind = self.tcx.def_kind(def_id);
1890 self.tcx.def_span(def_id),
1891 &format!("{} defined here", def_kind.descr(def_id)),