]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs
New upstream version 1.69.0+dfsg1
[rustc.git] / compiler / rustc_hir_typeck / src / fn_ctxt / checks.rs
CommitLineData
2b03887a
FG
1use crate::coercion::CoerceMany;
2use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx};
3use crate::gather_locals::Declaration;
4use crate::method::MethodCallee;
5use crate::Expectation::*;
6use crate::TupleArgumentsFlag::*;
7use crate::{
9c376795 8 struct_span_err, BreakableCtxt, Diverges, Expectation, FnCtxt, LocalTy, Needs, RawTy,
2b03887a 9 TupleArgumentsFlag,
064997fb 10};
29967ef6 11use rustc_ast as ast;
9c376795 12use rustc_data_structures::fx::FxIndexSet;
9ffffee4
FG
13use rustc_errors::{
14 pluralize, Applicability, Diagnostic, DiagnosticId, ErrorGuaranteed, MultiSpan,
15};
29967ef6 16use rustc_hir as hir;
136023e0 17use rustc_hir::def::{CtorOf, DefKind, Res};
29967ef6
XL
18use rustc_hir::def_id::DefId;
19use rustc_hir::{ExprKind, Node, QPath};
2b03887a
FG
20use rustc_hir_analysis::astconv::AstConv;
21use rustc_hir_analysis::check::intrinsicck::InlineAsmCtxt;
22use rustc_hir_analysis::check::potentially_plural_count;
23use rustc_hir_analysis::structured_errors::StructuredDiagnostic;
064997fb 24use rustc_index::vec::IndexVec;
923072b8 25use rustc_infer::infer::error_reporting::{FailureCode, ObligationCauseExt};
064997fb 26use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
923072b8
FG
27use rustc_infer::infer::InferOk;
28use rustc_infer::infer::TypeTrace;
29967ef6 29use rustc_middle::ty::adjustment::AllowTwoPhase;
9ffffee4
FG
30use rustc_middle::ty::visit::TypeVisitableExt;
31use rustc_middle::ty::{self, DefIdTree, IsSuggestable, Ty};
29967ef6 32use rustc_session::Session;
9c376795 33use rustc_span::symbol::{kw, Ident};
f2b60f7d 34use rustc_span::{self, sym, Span};
064997fb 35use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext};
29967ef6 36
cdc7bbd5 37use std::iter;
2b03887a 38use std::mem;
29967ef6
XL
39
40impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
2b03887a
FG
41 pub(in super::super) fn check_casts(&mut self) {
42 // don't hold the borrow to deferred_cast_checks while checking to avoid borrow checker errors
43 // when writing to `self.param_env`.
44 let mut deferred_cast_checks = mem::take(&mut *self.deferred_cast_checks.borrow_mut());
45
94222f64 46 debug!("FnCtxt::check_casts: {} deferred checks", deferred_cast_checks.len());
29967ef6 47 for cast in deferred_cast_checks.drain(..) {
2b03887a
FG
48 let prev_env = self.param_env;
49 self.param_env = self.param_env.with_constness(cast.constness);
50
29967ef6 51 cast.check(self);
2b03887a
FG
52
53 self.param_env = prev_env;
29967ef6 54 }
2b03887a
FG
55
56 *self.deferred_cast_checks.borrow_mut() = deferred_cast_checks;
29967ef6
XL
57 }
58
923072b8
FG
59 pub(in super::super) fn check_transmutes(&self) {
60 let mut deferred_transmute_checks = self.deferred_transmute_checks.borrow_mut();
61 debug!("FnCtxt::check_transmutes: {} deferred checks", deferred_transmute_checks.len());
2b03887a
FG
62 for (from, to, hir_id) in deferred_transmute_checks.drain(..) {
63 self.check_transmute(from, to, hir_id);
923072b8
FG
64 }
65 }
66
67 pub(in super::super) fn check_asms(&self) {
68 let mut deferred_asm_checks = self.deferred_asm_checks.borrow_mut();
69 debug!("FnCtxt::check_asm: {} deferred checks", deferred_asm_checks.len());
70 for (asm, hir_id) in deferred_asm_checks.drain(..) {
71 let enclosing_id = self.tcx.hir().enclosing_body_owner(hir_id);
f2b60f7d
FG
72 let get_operand_ty = |expr| {
73 let ty = self.typeck_results.borrow().expr_ty_adjusted(expr);
74 let ty = self.resolve_vars_if_possible(ty);
2b03887a 75 if ty.has_non_region_infer() {
9ffffee4 76 self.tcx.ty_error_misc()
f2b60f7d
FG
77 } else {
78 self.tcx.erase_regions(ty)
79 }
80 };
81 InlineAsmCtxt::new_in_fn(self.tcx, self.param_env, get_operand_ty)
9ffffee4 82 .check_asm(asm, enclosing_id);
923072b8
FG
83 }
84 }
85
29967ef6
XL
86 pub(in super::super) fn check_method_argument_types(
87 &self,
88 sp: Span,
89 expr: &'tcx hir::Expr<'tcx>,
90 method: Result<MethodCallee<'tcx>, ()>,
91 args_no_rcvr: &'tcx [hir::Expr<'tcx>],
92 tuple_arguments: TupleArgumentsFlag,
93 expected: Expectation<'tcx>,
94 ) -> Ty<'tcx> {
95 let has_error = match method {
96 Ok(method) => method.substs.references_error() || method.sig.references_error(),
97 Err(_) => true,
98 };
99 if has_error {
100 let err_inputs = self.err_args(args_no_rcvr.len());
101
102 let err_inputs = match tuple_arguments {
103 DontTupleArguments => err_inputs,
9ffffee4 104 TupleArguments => vec![self.tcx.mk_tup(&err_inputs)],
29967ef6
XL
105 };
106
107 self.check_argument_types(
108 sp,
109 expr,
a2a8927a 110 &err_inputs,
923072b8 111 None,
29967ef6
XL
112 args_no_rcvr,
113 false,
114 tuple_arguments,
064997fb 115 method.ok().map(|method| method.def_id),
29967ef6 116 );
9ffffee4 117 return self.tcx.ty_error_misc();
29967ef6
XL
118 }
119
120 let method = method.unwrap();
121 // HACK(eddyb) ignore self in the definition (see above).
a2a8927a 122 let expected_input_tys = self.expected_inputs_for_expected_output(
29967ef6
XL
123 sp,
124 expected,
125 method.sig.output(),
126 &method.sig.inputs()[1..],
127 );
128 self.check_argument_types(
129 sp,
130 expr,
131 &method.sig.inputs()[1..],
a2a8927a 132 expected_input_tys,
29967ef6
XL
133 args_no_rcvr,
134 method.sig.c_variadic,
135 tuple_arguments,
136 Some(method.def_id),
137 );
487cf647 138
29967ef6
XL
139 method.sig.output()
140 }
141
142 /// Generic function that factors out common logic from function calls,
143 /// method calls and overloaded operators.
144 pub(in super::super) fn check_argument_types(
145 &self,
a2a8927a
XL
146 // Span enclosing the call site
147 call_span: Span,
148 // Expression of the call site
149 call_expr: &'tcx hir::Expr<'tcx>,
150 // Types (as defined in the *signature* of the target function)
151 formal_input_tys: &[Ty<'tcx>],
152 // More specific expected types, after unifying with caller output types
923072b8 153 expected_input_tys: Option<Vec<Ty<'tcx>>>,
a2a8927a
XL
154 // The expressions for each provided argument
155 provided_args: &'tcx [hir::Expr<'tcx>],
156 // Whether the function is variadic, for example when imported from C
29967ef6 157 c_variadic: bool,
a2a8927a 158 // Whether the arguments have been bundled in a tuple (ex: closures)
29967ef6 159 tuple_arguments: TupleArgumentsFlag,
a2a8927a
XL
160 // The DefId for the function being called, for better error messages
161 fn_def_id: Option<DefId>,
29967ef6
XL
162 ) {
163 let tcx = self.tcx;
923072b8 164
f2b60f7d 165 // Conceptually, we've got some number of expected inputs, and some number of provided arguments
923072b8
FG
166 // and we can form a grid of whether each argument could satisfy a given input:
167 // in1 | in2 | in3 | ...
168 // arg1 ? | | |
169 // arg2 | ? | |
170 // arg3 | | ? |
171 // ...
172 // Initially, we just check the diagonal, because in the case of correct code
173 // these are the only checks that matter
174 // However, in the unhappy path, we'll fill in this whole grid to attempt to provide
175 // better error messages about invalid method calls.
29967ef6
XL
176
177 // All the input types from the fn signature must outlive the call
178 // so as to validate implied bounds.
a2a8927a 179 for (&fn_input_ty, arg_expr) in iter::zip(formal_input_tys, provided_args) {
29967ef6
XL
180 self.register_wf_obligation(fn_input_ty.into(), arg_expr.span, traits::MiscObligation);
181 }
182
923072b8 183 let mut err_code = "E0061";
29967ef6 184
5099ac24 185 // If the arguments should be wrapped in a tuple (ex: closures), unwrap them here
a2a8927a
XL
186 let (formal_input_tys, expected_input_tys) = if tuple_arguments == TupleArguments {
187 let tuple_type = self.structurally_resolved_type(call_span, formal_input_tys[0]);
29967ef6 188 match tuple_type.kind() {
5099ac24 189 // We expected a tuple and got a tuple
29967ef6 190 ty::Tuple(arg_types) => {
5099ac24
FG
191 // Argument length differs
192 if arg_types.len() != provided_args.len() {
923072b8 193 err_code = "E0057";
5099ac24 194 }
923072b8
FG
195 let expected_input_tys = match expected_input_tys {
196 Some(expected_input_tys) => match expected_input_tys.get(0) {
197 Some(ty) => match ty.kind() {
198 ty::Tuple(tys) => Some(tys.iter().collect()),
199 _ => None,
200 },
201 None => None,
29967ef6 202 },
923072b8 203 None => None,
29967ef6 204 };
5e7ed085 205 (arg_types.iter().collect(), expected_input_tys)
29967ef6
XL
206 }
207 _ => {
5099ac24 208 // Otherwise, there's a mismatch, so clear out what we're expecting, and set
5e7ed085 209 // our input types to err_args so we don't blow up the error messages
29967ef6
XL
210 struct_span_err!(
211 tcx.sess,
a2a8927a 212 call_span,
29967ef6
XL
213 E0059,
214 "cannot use call notation; the first type parameter \
215 for the function trait is neither a tuple nor unit"
216 )
9c376795 217 .emit();
923072b8 218 (self.err_args(provided_args.len()), None)
29967ef6
XL
219 }
220 }
29967ef6 221 } else {
923072b8 222 (formal_input_tys.to_vec(), expected_input_tys)
29967ef6
XL
223 };
224
923072b8
FG
225 // If there are no external expectations at the call site, just use the types from the function defn
226 let expected_input_tys = if let Some(expected_input_tys) = expected_input_tys {
227 assert_eq!(expected_input_tys.len(), formal_input_tys.len());
a2a8927a
XL
228 expected_input_tys
229 } else {
230 formal_input_tys.clone()
231 };
29967ef6 232
923072b8
FG
233 let minimum_input_count = expected_input_tys.len();
234 let provided_arg_count = provided_args.len();
5099ac24 235
f2b60f7d
FG
236 let is_const_eval_select = matches!(fn_def_id, Some(def_id) if
237 self.tcx.def_kind(def_id) == hir::def::DefKind::Fn
238 && self.tcx.is_intrinsic(def_id)
239 && self.tcx.item_name(def_id) == sym::const_eval_select);
240
a2a8927a
XL
241 // We introduce a helper function to demand that a given argument satisfy a given input
242 // This is more complicated than just checking type equality, as arguments could be coerced
243 // This version writes those types back so further type checking uses the narrowed types
064997fb 244 let demand_compatible = |idx| {
a2a8927a
XL
245 let formal_input_ty: Ty<'tcx> = formal_input_tys[idx];
246 let expected_input_ty: Ty<'tcx> = expected_input_tys[idx];
247 let provided_arg = &provided_args[idx];
248
249 debug!("checking argument {}: {:?} = {:?}", idx, provided_arg, formal_input_ty);
250
923072b8
FG
251 // We're on the happy path here, so we'll do a more involved check and write back types
252 // To check compatibility, we'll do 3 things:
253 // 1. Unify the provided argument with the expected type
a2a8927a
XL
254 let expectation = Expectation::rvalue_hint(self, expected_input_ty);
255
256 let checked_ty = self.check_expr_with_expectation(provided_arg, expectation);
257
258 // 2. Coerce to the most detailed type that could be coerced
259 // to, which is `expected_ty` if `rvalue_hint` returns an
260 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
261 let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
262
a2a8927a 263 // Cause selection errors caused by resolving a single argument to point at the
923072b8 264 // argument and not the call. This lets us customize the span pointed to in the
a2a8927a 265 // fulfillment error to be more accurate.
f2b60f7d 266 let coerced_ty = self.resolve_vars_with_obligations(coerced_ty);
a2a8927a 267
923072b8
FG
268 let coerce_error = self
269 .try_coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None)
270 .err();
271
272 if coerce_error.is_some() {
273 return Compatibility::Incompatible(coerce_error);
274 }
275
f2b60f7d
FG
276 // Check that second and third argument of `const_eval_select` must be `FnDef`, and additionally that
277 // the second argument must be `const fn`. The first argument must be a tuple, but this is already expressed
278 // in the function signature (`F: FnOnce<ARG>`), so I did not bother to add another check here.
279 //
280 // This check is here because there is currently no way to express a trait bound for `FnDef` types only.
281 if is_const_eval_select && (1..=2).contains(&idx) {
282 if let ty::FnDef(def_id, _) = checked_ty.kind() {
283 if idx == 1 && !self.tcx.is_const_fn_raw(*def_id) {
284 self.tcx
285 .sess
286 .struct_span_err(provided_arg.span, "this argument must be a `const fn`")
287 .help("consult the documentation on `const_eval_select` for more information")
288 .emit();
289 }
290 } else {
291 self.tcx
292 .sess
293 .struct_span_err(provided_arg.span, "this argument must be a function item")
294 .note(format!("expected a function item, found {checked_ty}"))
295 .help(
296 "consult the documentation on `const_eval_select` for more information",
297 )
298 .emit();
299 }
300 }
301
923072b8
FG
302 // 3. Check if the formal type is a supertype of the checked one
303 // and register any such obligations for future type checks
304 let supertype_error = self
305 .at(&self.misc(provided_arg.span), self.param_env)
306 .sup(formal_input_ty, coerced_ty);
307 let subtyping_error = match supertype_error {
308 Ok(InferOk { obligations, value: () }) => {
309 self.register_predicates(obligations);
310 None
311 }
312 Err(err) => Some(err),
313 };
314
315 // If neither check failed, the types are compatible
316 match subtyping_error {
317 None => Compatibility::Compatible,
318 Some(_) => Compatibility::Incompatible(subtyping_error),
319 }
320 };
321
923072b8
FG
322 // To start, we only care "along the diagonal", where we expect every
323 // provided arg to be in the right spot
064997fb
FG
324 let mut compatibility_diagonal =
325 vec![Compatibility::Incompatible(None); provided_args.len()];
923072b8
FG
326
327 // Keep track of whether we *could possibly* be satisfied, i.e. whether we're on the happy path
328 // if the wrong number of arguments were supplied, we CAN'T be satisfied,
329 // and if we're c_variadic, the supplied arguments must be >= the minimum count from the function
330 // otherwise, they need to be identical, because rust doesn't currently support variadic functions
331 let mut call_appears_satisfied = if c_variadic {
332 provided_arg_count >= minimum_input_count
333 } else {
334 provided_arg_count == minimum_input_count
335 };
5e7ed085 336
29967ef6
XL
337 // Check the arguments.
338 // We do this in a pretty awful way: first we type-check any arguments
339 // that are not closures, then we type-check the closures. This is so
340 // that we have more information about the types of arguments when we
341 // type-check the functions. This isn't really the right way to do this.
136023e0 342 for check_closures in [false, true] {
29967ef6
XL
343 // More awful hacks: before we check argument types, try to do
344 // an "opportunistic" trait resolution of any trait bounds on
345 // the call. This helps coercions.
346 if check_closures {
487cf647 347 self.select_obligations_where_possible(|_| {})
29967ef6
XL
348 }
349
923072b8
FG
350 // Check each argument, to satisfy the input it was provided for
351 // Visually, we're traveling down the diagonal of the compatibility matrix
a2a8927a 352 for (idx, arg) in provided_args.iter().enumerate() {
29967ef6
XL
353 // Warn only for the first loop (the "no closures" one).
354 // Closure arguments themselves can't be diverging, but
355 // a previous argument can, e.g., `foo(panic!(), || {})`.
356 if !check_closures {
357 self.warn_if_unreachable(arg.hir_id, arg.span, "expression");
358 }
359
a2a8927a
XL
360 // For C-variadic functions, we don't have a declared type for all of
361 // the arguments hence we only do our usual type checking with
362 // the arguments who's types we do know. However, we *can* check
363 // for unreachable expressions (see above).
364 // FIXME: unreachable warning current isn't emitted
365 if idx >= minimum_input_count {
366 continue;
367 }
29967ef6 368
923072b8 369 let is_closure = matches!(arg.kind, ExprKind::Closure { .. });
29967ef6
XL
370 if is_closure != check_closures {
371 continue;
372 }
373
064997fb 374 let compatible = demand_compatible(idx);
923072b8 375 let is_compatible = matches!(compatible, Compatibility::Compatible);
064997fb 376 compatibility_diagonal[idx] = compatible;
923072b8
FG
377
378 if !is_compatible {
379 call_appears_satisfied = false;
380 }
29967ef6
XL
381 }
382 }
383
064997fb
FG
384 if c_variadic && provided_arg_count < minimum_input_count {
385 err_code = "E0060";
386 }
387
388 for arg in provided_args.iter().skip(minimum_input_count) {
389 // Make sure we've checked this expr at least once.
390 let arg_ty = self.check_expr(&arg);
391
392 // If the function is c-style variadic, we skipped a bunch of arguments
393 // so we need to check those, and write out the types
394 // Ideally this would be folded into the above, for uniform style
395 // but c-variadic is already a corner case
396 if c_variadic {
397 fn variadic_error<'tcx>(
398 sess: &'tcx Session,
399 span: Span,
400 ty: Ty<'tcx>,
401 cast_ty: &str,
402 ) {
2b03887a 403 use rustc_hir_analysis::structured_errors::MissingCastForVariadicArg;
064997fb
FG
404
405 MissingCastForVariadicArg { sess, span, ty, cast_ty }.diagnostic().emit();
406 }
407
408 // There are a few types which get autopromoted when passed via varargs
409 // in C but we just error out instead and require explicit casts.
410 let arg_ty = self.structurally_resolved_type(arg.span, arg_ty);
411 match arg_ty.kind() {
412 ty::Float(ty::FloatTy::F32) => {
413 variadic_error(tcx.sess, arg.span, arg_ty, "c_double");
414 }
415 ty::Int(ty::IntTy::I8 | ty::IntTy::I16) | ty::Bool => {
416 variadic_error(tcx.sess, arg.span, arg_ty, "c_int");
417 }
418 ty::Uint(ty::UintTy::U8 | ty::UintTy::U16) => {
419 variadic_error(tcx.sess, arg.span, arg_ty, "c_uint");
420 }
421 ty::FnDef(..) => {
422 let ptr_ty = self.tcx.mk_fn_ptr(arg_ty.fn_sig(self.tcx));
423 let ptr_ty = self.resolve_vars_if_possible(ptr_ty);
424 variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string());
425 }
426 _ => {}
427 }
923072b8 428 }
064997fb 429 }
923072b8 430
064997fb
FG
431 if !call_appears_satisfied {
432 let compatibility_diagonal = IndexVec::from_raw(compatibility_diagonal);
433 let provided_args = IndexVec::from_iter(provided_args.iter().take(if c_variadic {
434 minimum_input_count
435 } else {
436 provided_arg_count
437 }));
438 debug_assert_eq!(
439 formal_input_tys.len(),
440 expected_input_tys.len(),
441 "expected formal_input_tys to be the same size as expected_input_tys"
442 );
443 let formal_and_expected_inputs = IndexVec::from_iter(
444 formal_input_tys
445 .iter()
446 .copied()
447 .zip(expected_input_tys.iter().copied())
448 .map(|vars| self.resolve_vars_if_possible(vars)),
449 );
923072b8 450
064997fb
FG
451 self.report_arg_errors(
452 compatibility_diagonal,
453 formal_and_expected_inputs,
454 provided_args,
455 c_variadic,
456 err_code,
457 fn_def_id,
458 call_span,
459 call_expr,
460 );
461 }
462 }
923072b8 463
064997fb
FG
464 fn report_arg_errors(
465 &self,
466 compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
467 formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
468 provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
469 c_variadic: bool,
470 err_code: &str,
471 fn_def_id: Option<DefId>,
472 call_span: Span,
473 call_expr: &hir::Expr<'tcx>,
474 ) {
475 // Next, let's construct the error
9c376795 476 let (error_span, full_call_span, call_name, is_method) = match &call_expr.kind {
064997fb
FG
477 hir::ExprKind::Call(
478 hir::Expr { hir_id, span, kind: hir::ExprKind::Path(qpath), .. },
479 _,
480 ) => {
481 if let Res::Def(DefKind::Ctor(of, _), _) =
482 self.typeck_results.borrow().qpath_res(qpath, *hir_id)
483 {
9c376795
FG
484 let name = match of {
485 CtorOf::Struct => "struct",
486 CtorOf::Variant => "enum variant",
487 };
488 (call_span, *span, name, false)
064997fb 489 } else {
9c376795 490 (call_span, *span, "function", false)
064997fb
FG
491 }
492 }
9c376795 493 hir::ExprKind::Call(hir::Expr { span, .. }, _) => (call_span, *span, "function", false),
f2b60f7d 494 hir::ExprKind::MethodCall(path_segment, _, _, span) => {
064997fb
FG
495 let ident_span = path_segment.ident.span;
496 let ident_span = if let Some(args) = path_segment.args {
497 ident_span.with_hi(args.span_ext.hi())
498 } else {
499 ident_span
500 };
9c376795 501 (*span, ident_span, "method", true)
064997fb
FG
502 }
503 k => span_bug!(call_span, "checking argument types on a non-call: `{:?}`", k),
504 };
505 let args_span = error_span.trim_start(full_call_span).unwrap_or(error_span);
923072b8 506
064997fb
FG
507 // Don't print if it has error types or is just plain `_`
508 fn has_error_or_infer<'tcx>(tys: impl IntoIterator<Item = Ty<'tcx>>) -> bool {
509 tys.into_iter().any(|ty| ty.references_error() || ty.is_ty_var())
510 }
511
064997fb 512 let tcx = self.tcx;
487cf647
FG
513 // FIXME: taint after emitting errors and pass through an `ErrorGuaranteed`
514 self.set_tainted_by_errors(
515 tcx.sess.delay_span_bug(call_span, "no errors reported for args"),
516 );
064997fb
FG
517
518 // Get the argument span in the context of the call span so that
519 // suggestions and labels are (more) correct when an arg is a
520 // macro invocation.
521 let normalize_span = |span: Span| -> Span {
522 let normalized_span = span.find_ancestor_inside(error_span).unwrap_or(span);
523 // Sometimes macros mess up the spans, so do not normalize the
524 // arg span to equal the error span, because that's less useful
525 // than pointing out the arg expr in the wrong context.
526 if normalized_span.source_equal(error_span) { span } else { normalized_span }
527 };
528
529 // Precompute the provided types and spans, since that's all we typically need for below
530 let provided_arg_tys: IndexVec<ProvidedIdx, (Ty<'tcx>, Span)> = provided_args
531 .iter()
532 .map(|expr| {
533 let ty = self
534 .typeck_results
535 .borrow()
536 .expr_ty_adjusted_opt(*expr)
9ffffee4 537 .unwrap_or_else(|| tcx.ty_error_misc());
064997fb
FG
538 (self.resolve_vars_if_possible(ty), normalize_span(expr.span))
539 })
540 .collect();
541 let callee_expr = match &call_expr.peel_blocks().kind {
542 hir::ExprKind::Call(callee, _) => Some(*callee),
f2b60f7d 543 hir::ExprKind::MethodCall(_, receiver, ..) => {
064997fb
FG
544 if let Some((DefKind::AssocFn, def_id)) =
545 self.typeck_results.borrow().type_dependent_def(call_expr.hir_id)
546 && let Some(assoc) = tcx.opt_associated_item(def_id)
547 && assoc.fn_has_self_parameter
548 {
f2b60f7d 549 Some(*receiver)
064997fb
FG
550 } else {
551 None
923072b8 552 }
064997fb
FG
553 }
554 _ => None,
555 };
556 let callee_ty = callee_expr
557 .and_then(|callee_expr| self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr));
558
559 // A "softer" version of the `demand_compatible`, which checks types without persisting them,
560 // and treats error types differently
561 // This will allow us to "probe" for other argument orders that would likely have been correct
562 let check_compatible = |provided_idx: ProvidedIdx, expected_idx: ExpectedIdx| {
563 if provided_idx.as_usize() == expected_idx.as_usize() {
564 return compatibility_diagonal[provided_idx].clone();
565 }
566
567 let (formal_input_ty, expected_input_ty) = formal_and_expected_inputs[expected_idx];
568 // If either is an error type, we defy the usual convention and consider them to *not* be
569 // coercible. This prevents our error message heuristic from trying to pass errors into
570 // every argument.
571 if (formal_input_ty, expected_input_ty).references_error() {
572 return Compatibility::Incompatible(None);
573 }
574
575 let (arg_ty, arg_span) = provided_arg_tys[provided_idx];
576
577 let expectation = Expectation::rvalue_hint(self, expected_input_ty);
578 let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
579 let can_coerce = self.can_coerce(arg_ty, coerced_ty);
580 if !can_coerce {
f2b60f7d
FG
581 return Compatibility::Incompatible(Some(ty::error::TypeError::Sorts(
582 ty::error::ExpectedFound::new(true, coerced_ty, arg_ty),
583 )));
064997fb
FG
584 }
585
586 // Using probe here, since we don't want this subtyping to affect inference.
587 let subtyping_error = self.probe(|_| {
588 self.at(&self.misc(arg_span), self.param_env).sup(formal_input_ty, coerced_ty).err()
923072b8
FG
589 });
590
064997fb
FG
591 // Same as above: if either the coerce type or the checked type is an error type,
592 // consider them *not* compatible.
593 let references_error = (coerced_ty, arg_ty).references_error();
594 match (references_error, subtyping_error) {
595 (false, None) => Compatibility::Compatible,
596 (_, subtyping_error) => Compatibility::Incompatible(subtyping_error),
923072b8 597 }
064997fb 598 };
923072b8 599
487cf647
FG
600 let mk_trace = |span, (formal_ty, expected_ty), provided_ty| {
601 let mismatched_ty = if expected_ty == provided_ty {
602 // If expected == provided, then we must have failed to sup
603 // the formal type. Avoid printing out "expected Ty, found Ty"
604 // in that case.
605 formal_ty
606 } else {
607 expected_ty
608 };
609 TypeTrace::types(&self.misc(span), true, mismatched_ty, provided_ty)
610 };
611
064997fb
FG
612 // The algorithm here is inspired by levenshtein distance and longest common subsequence.
613 // We'll try to detect 4 different types of mistakes:
614 // - An extra parameter has been provided that doesn't satisfy *any* of the other inputs
615 // - An input is missing, which isn't satisfied by *any* of the other arguments
616 // - Some number of arguments have been provided in the wrong order
617 // - A type is straight up invalid
618
619 // First, let's find the errors
620 let (mut errors, matched_inputs) =
621 ArgMatrix::new(provided_args.len(), formal_and_expected_inputs.len(), check_compatible)
622 .find_errors();
623
624 // First, check if we just need to wrap some arguments in a tuple.
625 if let Some((mismatch_idx, terr)) =
626 compatibility_diagonal.iter().enumerate().find_map(|(i, c)| {
f2b60f7d
FG
627 if let Compatibility::Incompatible(Some(terr)) = c {
628 Some((i, *terr))
629 } else {
630 None
631 }
064997fb
FG
632 })
633 {
634 // Is the first bad expected argument a tuple?
635 // Do we have as many extra provided arguments as the tuple's length?
636 // If so, we might have just forgotten to wrap some args in a tuple.
637 if let Some(ty::Tuple(tys)) =
638 formal_and_expected_inputs.get(mismatch_idx.into()).map(|tys| tys.1.kind())
639 // If the tuple is unit, we're not actually wrapping any arguments.
640 && !tys.is_empty()
641 && provided_arg_tys.len() == formal_and_expected_inputs.len() - 1 + tys.len()
642 {
643 // Wrap up the N provided arguments starting at this position in a tuple.
9ffffee4 644 let provided_as_tuple = tcx.mk_tup_from_iter(
064997fb
FG
645 provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx).take(tys.len()),
646 );
647
648 let mut satisfied = true;
649 // Check if the newly wrapped tuple + rest of the arguments are compatible.
650 for ((_, expected_ty), provided_ty) in std::iter::zip(
651 formal_and_expected_inputs.iter().skip(mismatch_idx),
652 [provided_as_tuple].into_iter().chain(
653 provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx + tys.len()),
654 ),
655 ) {
656 if !self.can_coerce(provided_ty, *expected_ty) {
657 satisfied = false;
658 break;
659 }
5099ac24 660 }
5e7ed085 661
064997fb
FG
662 // If they're compatible, suggest wrapping in an arg, and we're done!
663 // Take some care with spans, so we don't suggest wrapping a macro's
664 // innards in parenthesis, for example.
665 if satisfied
666 && let Some((_, lo)) =
667 provided_arg_tys.get(ProvidedIdx::from_usize(mismatch_idx))
668 && let Some((_, hi)) =
669 provided_arg_tys.get(ProvidedIdx::from_usize(mismatch_idx + tys.len() - 1))
670 {
671 let mut err;
672 if tys.len() == 1 {
673 // A tuple wrap suggestion actually occurs within,
674 // so don't do anything special here.
2b03887a 675 err = self.err_ctxt().report_and_explain_type_error(
487cf647
FG
676 mk_trace(
677 *lo,
678 formal_and_expected_inputs[mismatch_idx.into()],
064997fb
FG
679 provided_arg_tys[mismatch_idx.into()].0,
680 ),
681 terr,
682 );
683 err.span_label(
684 full_call_span,
685 format!("arguments to this {} are incorrect", call_name),
686 );
687 } else {
688 err = tcx.sess.struct_span_err_with_code(
689 full_call_span,
690 &format!(
9c376795 691 "{call_name} takes {}{} but {} {} supplied",
064997fb
FG
692 if c_variadic { "at least " } else { "" },
693 potentially_plural_count(
694 formal_and_expected_inputs.len(),
695 "argument"
696 ),
697 potentially_plural_count(provided_args.len(), "argument"),
698 pluralize!("was", provided_args.len())
699 ),
700 DiagnosticId::Error(err_code.to_owned()),
701 );
702 err.multipart_suggestion_verbose(
703 "wrap these arguments in parentheses to construct a tuple",
704 vec![
705 (lo.shrink_to_lo(), "(".to_string()),
706 (hi.shrink_to_hi(), ")".to_string()),
707 ],
708 Applicability::MachineApplicable,
709 );
923072b8 710 };
f2b60f7d
FG
711 self.label_fn_like(
712 &mut err,
713 fn_def_id,
714 callee_ty,
715 Some(mismatch_idx),
716 is_method,
717 );
923072b8 718 err.emit();
064997fb 719 return;
04454e1e 720 }
923072b8 721 }
064997fb
FG
722 }
723
724 // Okay, so here's where it gets complicated in regards to what errors
725 // we emit and how.
726 // There are 3 different "types" of errors we might encounter.
727 // 1) Missing/extra/swapped arguments
728 // 2) Valid but incorrect arguments
729 // 3) Invalid arguments
730 // - Currently I think this only comes up with `CyclicTy`
731 //
732 // We first need to go through, remove those from (3) and emit those
733 // as their own error, particularly since they're error code and
734 // message is special. From what I can tell, we *must* emit these
735 // here (vs somewhere prior to this function) since the arguments
736 // become invalid *because* of how they get used in the function.
737 // It is what it is.
738
739 if errors.is_empty() {
740 if cfg!(debug_assertions) {
741 span_bug!(error_span, "expected errors from argument matrix");
742 } else {
743 tcx.sess
744 .struct_span_err(
745 error_span,
746 "argument type mismatch was detected, \
747 but rustc had trouble determining where",
748 )
749 .note(
750 "we would appreciate a bug report: \
751 https://github.com/rust-lang/rust/issues/new",
752 )
753 .emit();
754 }
755 return;
756 }
757
758 errors.drain_filter(|error| {
9ffffee4
FG
759 let Error::Invalid(
760 provided_idx,
761 expected_idx,
762 Compatibility::Incompatible(Some(e)),
763 ) = error else { return false };
764 let (provided_ty, provided_span) = provided_arg_tys[*provided_idx];
765 let trace =
766 mk_trace(provided_span, formal_and_expected_inputs[*expected_idx], provided_ty);
767 if !matches!(trace.cause.as_failure_code(*e), FailureCode::Error0308(_)) {
768 self.err_ctxt().report_and_explain_type_error(trace, *e).emit();
769 return true;
770 }
771 false
772 });
064997fb
FG
773
774 // We're done if we found errors, but we already emitted them.
775 if errors.is_empty() {
776 return;
777 }
778
779 // Okay, now that we've emitted the special errors separately, we
780 // are only left missing/extra/swapped and mismatched arguments, both
781 // can be collated pretty easily if needed.
782
783 // Next special case: if there is only one "Incompatible" error, just emit that
784 if let [
785 Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(err))),
786 ] = &errors[..]
787 {
788 let (formal_ty, expected_ty) = formal_and_expected_inputs[*expected_idx];
789 let (provided_ty, provided_arg_span) = provided_arg_tys[*provided_idx];
487cf647 790 let trace = mk_trace(provided_arg_span, (formal_ty, expected_ty), provided_ty);
2b03887a 791 let mut err = self.err_ctxt().report_and_explain_type_error(trace, *err);
064997fb
FG
792 self.emit_coerce_suggestions(
793 &mut err,
794 &provided_args[*provided_idx],
795 provided_ty,
796 Expectation::rvalue_hint(self, expected_ty)
797 .only_has_type(self)
798 .unwrap_or(formal_ty),
799 None,
800 None,
801 );
802 err.span_label(
803 full_call_span,
804 format!("arguments to this {} are incorrect", call_name),
805 );
9ffffee4
FG
806 if let (Some(callee_ty), hir::ExprKind::MethodCall(_, rcvr, _, _)) =
807 (callee_ty, &call_expr.kind)
808 {
809 // Type that would have accepted this argument if it hadn't been inferred earlier.
810 // FIXME: We leave an inference variable for now, but it'd be nice to get a more
811 // specific type to increase the accuracy of the diagnostic.
812 let expected = self.infcx.next_ty_var(TypeVariableOrigin {
813 kind: TypeVariableOriginKind::MiscVariable,
814 span: full_call_span,
815 });
816 self.point_at_expr_source_of_inferred_type(
817 &mut err,
818 rcvr,
819 expected,
820 callee_ty,
821 provided_arg_span,
822 );
823 }
064997fb 824 // Call out where the function is defined
f2b60f7d
FG
825 self.label_fn_like(
826 &mut err,
827 fn_def_id,
828 callee_ty,
829 Some(expected_idx.as_usize()),
830 is_method,
831 );
064997fb
FG
832 err.emit();
833 return;
834 }
835
836 let mut err = if formal_and_expected_inputs.len() == provided_args.len() {
837 struct_span_err!(
838 tcx.sess,
839 full_call_span,
840 E0308,
841 "arguments to this {} are incorrect",
842 call_name,
843 )
844 } else {
845 tcx.sess.struct_span_err_with_code(
846 full_call_span,
847 &format!(
848 "this {} takes {}{} but {} {} supplied",
849 call_name,
850 if c_variadic { "at least " } else { "" },
851 potentially_plural_count(formal_and_expected_inputs.len(), "argument"),
852 potentially_plural_count(provided_args.len(), "argument"),
853 pluralize!("was", provided_args.len())
854 ),
855 DiagnosticId::Error(err_code.to_owned()),
856 )
857 };
858
859 // As we encounter issues, keep track of what we want to provide for the suggestion
860 let mut labels = vec![];
861 // If there is a single error, we give a specific suggestion; otherwise, we change to
862 // "did you mean" with the suggested function call
863 enum SuggestionText {
864 None,
865 Provide(bool),
866 Remove(bool),
867 Swap,
868 Reorder,
869 DidYouMean,
870 }
871 let mut suggestion_text = SuggestionText::None;
872
9ffffee4
FG
873 let ty_to_snippet = |ty: Ty<'tcx>, expected_idx: ExpectedIdx| {
874 if ty.is_unit() {
875 "()".to_string()
876 } else if ty.is_suggestable(tcx, false) {
877 format!("/* {} */", ty)
878 } else if let Some(fn_def_id) = fn_def_id
879 && self.tcx.def_kind(fn_def_id).is_fn_like()
880 && let self_implicit =
881 matches!(call_expr.kind, hir::ExprKind::MethodCall(..)) as usize
882 && let Some(arg) = self.tcx.fn_arg_names(fn_def_id)
883 .get(expected_idx.as_usize() + self_implicit)
884 && arg.name != kw::SelfLower
885 {
886 format!("/* {} */", arg.name)
887 } else {
888 "/* value */".to_string()
889 }
890 };
891
064997fb 892 let mut errors = errors.into_iter().peekable();
9ffffee4 893 let mut suggestions = vec![];
064997fb
FG
894 while let Some(error) = errors.next() {
895 match error {
896 Error::Invalid(provided_idx, expected_idx, compatibility) => {
897 let (formal_ty, expected_ty) = formal_and_expected_inputs[expected_idx];
898 let (provided_ty, provided_span) = provided_arg_tys[provided_idx];
f2b60f7d 899 if let Compatibility::Incompatible(error) = compatibility {
487cf647 900 let trace = mk_trace(provided_span, (formal_ty, expected_ty), provided_ty);
064997fb 901 if let Some(e) = error {
2b03887a 902 self.err_ctxt().note_type_err(
064997fb
FG
903 &mut err,
904 &trace.cause,
905 None,
906 Some(trace.values),
907 e,
908 false,
909 true,
910 );
911 }
912 }
923072b8 913
923072b8
FG
914 self.emit_coerce_suggestions(
915 &mut err,
064997fb 916 &provided_args[provided_idx],
923072b8 917 provided_ty,
064997fb
FG
918 Expectation::rvalue_hint(self, expected_ty)
919 .only_has_type(self)
920 .unwrap_or(formal_ty),
923072b8
FG
921 None,
922 None,
923 );
923072b8 924 }
064997fb
FG
925 Error::Extra(arg_idx) => {
926 let (provided_ty, provided_span) = provided_arg_tys[arg_idx];
927 let provided_ty_name = if !has_error_or_infer([provided_ty]) {
928 // FIXME: not suggestable, use something else
929 format!(" of type `{}`", provided_ty)
930 } else {
931 "".to_string()
932 };
933 labels
9ffffee4
FG
934 .push((provided_span, format!("unexpected argument{}", provided_ty_name)));
935 let mut span = provided_span;
936 if span.can_be_used_for_suggestions() {
937 if arg_idx.index() > 0
938 && let Some((_, prev)) = provided_arg_tys
939 .get(ProvidedIdx::from_usize(arg_idx.index() - 1)
940 ) {
941 // Include previous comma
942 span = prev.shrink_to_hi().to(span);
943 }
944 suggestions.push((span, String::new()));
945
946 suggestion_text = match suggestion_text {
947 SuggestionText::None => SuggestionText::Remove(false),
948 SuggestionText::Remove(_) => SuggestionText::Remove(true),
949 _ => SuggestionText::DidYouMean,
950 };
951 }
064997fb
FG
952 }
953 Error::Missing(expected_idx) => {
954 // If there are multiple missing arguments adjacent to each other,
955 // then we can provide a single error.
956
957 let mut missing_idxs = vec![expected_idx];
958 while let Some(e) = errors.next_if(|e| {
959 matches!(e, Error::Missing(next_expected_idx)
960 if *next_expected_idx == *missing_idxs.last().unwrap() + 1)
961 }) {
962 match e {
963 Error::Missing(expected_idx) => missing_idxs.push(expected_idx),
964 _ => unreachable!(),
923072b8 965 }
923072b8 966 }
064997fb
FG
967
968 // NOTE: Because we might be re-arranging arguments, might have extra
969 // arguments, etc. it's hard to *really* know where we should provide
970 // this error label, so as a heuristic, we point to the provided arg, or
971 // to the call if the missing inputs pass the provided args.
972 match &missing_idxs[..] {
973 &[expected_idx] => {
974 let (_, input_ty) = formal_and_expected_inputs[expected_idx];
975 let span = if let Some((_, arg_span)) =
976 provided_arg_tys.get(expected_idx.to_provided_idx())
977 {
978 *arg_span
923072b8 979 } else {
064997fb
FG
980 args_span
981 };
982 let rendered = if !has_error_or_infer([input_ty]) {
983 format!(" of type `{}`", input_ty)
984 } else {
985 "".to_string()
986 };
987 labels.push((span, format!("an argument{} is missing", rendered)));
988 suggestion_text = match suggestion_text {
989 SuggestionText::None => SuggestionText::Provide(false),
990 SuggestionText::Provide(_) => SuggestionText::Provide(true),
991 _ => SuggestionText::DidYouMean,
992 };
923072b8 993 }
064997fb
FG
994 &[first_idx, second_idx] => {
995 let (_, first_expected_ty) = formal_and_expected_inputs[first_idx];
996 let (_, second_expected_ty) = formal_and_expected_inputs[second_idx];
997 let span = if let (Some((_, first_span)), Some((_, second_span))) = (
998 provided_arg_tys.get(first_idx.to_provided_idx()),
999 provided_arg_tys.get(second_idx.to_provided_idx()),
1000 ) {
1001 first_span.to(*second_span)
1002 } else {
1003 args_span
1004 };
1005 let rendered =
1006 if !has_error_or_infer([first_expected_ty, second_expected_ty]) {
923072b8
FG
1007 format!(
1008 " of type `{}` and `{}`",
064997fb 1009 first_expected_ty, second_expected_ty
923072b8
FG
1010 )
1011 } else {
064997fb 1012 "".to_string()
923072b8 1013 };
064997fb
FG
1014 labels.push((span, format!("two arguments{} are missing", rendered)));
1015 suggestion_text = match suggestion_text {
1016 SuggestionText::None | SuggestionText::Provide(_) => {
1017 SuggestionText::Provide(true)
1018 }
1019 _ => SuggestionText::DidYouMean,
1020 };
923072b8 1021 }
064997fb
FG
1022 &[first_idx, second_idx, third_idx] => {
1023 let (_, first_expected_ty) = formal_and_expected_inputs[first_idx];
1024 let (_, second_expected_ty) = formal_and_expected_inputs[second_idx];
1025 let (_, third_expected_ty) = formal_and_expected_inputs[third_idx];
1026 let span = if let (Some((_, first_span)), Some((_, third_span))) = (
1027 provided_arg_tys.get(first_idx.to_provided_idx()),
1028 provided_arg_tys.get(third_idx.to_provided_idx()),
1029 ) {
1030 first_span.to(*third_span)
923072b8 1031 } else {
064997fb 1032 args_span
923072b8 1033 };
064997fb
FG
1034 let rendered = if !has_error_or_infer([
1035 first_expected_ty,
1036 second_expected_ty,
1037 third_expected_ty,
1038 ]) {
1039 format!(
1040 " of type `{}`, `{}`, and `{}`",
1041 first_expected_ty, second_expected_ty, third_expected_ty
1042 )
923072b8 1043 } else {
064997fb
FG
1044 "".to_string()
1045 };
1046 labels.push((span, format!("three arguments{} are missing", rendered)));
1047 suggestion_text = match suggestion_text {
1048 SuggestionText::None | SuggestionText::Provide(_) => {
1049 SuggestionText::Provide(true)
1050 }
1051 _ => SuggestionText::DidYouMean,
1052 };
1053 }
1054 missing_idxs => {
1055 let first_idx = *missing_idxs.first().unwrap();
1056 let last_idx = *missing_idxs.last().unwrap();
1057 // NOTE: Because we might be re-arranging arguments, might have extra arguments, etc.
1058 // It's hard to *really* know where we should provide this error label, so this is a
1059 // decent heuristic
1060 let span = if let (Some((_, first_span)), Some((_, last_span))) = (
1061 provided_arg_tys.get(first_idx.to_provided_idx()),
1062 provided_arg_tys.get(last_idx.to_provided_idx()),
1063 ) {
1064 first_span.to(*last_span)
1065 } else {
1066 args_span
1067 };
9c376795 1068 labels.push((span, "multiple arguments are missing".to_string()));
064997fb
FG
1069 suggestion_text = match suggestion_text {
1070 SuggestionText::None | SuggestionText::Provide(_) => {
1071 SuggestionText::Provide(true)
1072 }
1073 _ => SuggestionText::DidYouMean,
923072b8 1074 };
923072b8 1075 }
923072b8
FG
1076 }
1077 }
064997fb
FG
1078 Error::Swap(
1079 first_provided_idx,
1080 second_provided_idx,
1081 first_expected_idx,
1082 second_expected_idx,
1083 ) => {
1084 let (first_provided_ty, first_span) = provided_arg_tys[first_provided_idx];
1085 let (_, first_expected_ty) = formal_and_expected_inputs[first_expected_idx];
1086 let first_provided_ty_name = if !has_error_or_infer([first_provided_ty]) {
1087 format!(", found `{}`", first_provided_ty)
923072b8 1088 } else {
064997fb
FG
1089 String::new()
1090 };
1091 labels.push((
1092 first_span,
1093 format!("expected `{}`{}", first_expected_ty, first_provided_ty_name),
1094 ));
1095
1096 let (second_provided_ty, second_span) = provided_arg_tys[second_provided_idx];
1097 let (_, second_expected_ty) = formal_and_expected_inputs[second_expected_idx];
1098 let second_provided_ty_name = if !has_error_or_infer([second_provided_ty]) {
1099 format!(", found `{}`", second_provided_ty)
1100 } else {
1101 String::new()
923072b8 1102 };
064997fb
FG
1103 labels.push((
1104 second_span,
1105 format!("expected `{}`{}", second_expected_ty, second_provided_ty_name),
1106 ));
1107
1108 suggestion_text = match suggestion_text {
1109 SuggestionText::None => SuggestionText::Swap,
1110 _ => SuggestionText::DidYouMean,
1111 };
1112 }
1113 Error::Permutation(args) => {
1114 for (dst_arg, dest_input) in args {
1115 let (_, expected_ty) = formal_and_expected_inputs[dst_arg];
1116 let (provided_ty, provided_span) = provided_arg_tys[dest_input];
1117 let provided_ty_name = if !has_error_or_infer([provided_ty]) {
1118 format!(", found `{}`", provided_ty)
1119 } else {
1120 String::new()
1121 };
1122 labels.push((
1123 provided_span,
1124 format!("expected `{}`{}", expected_ty, provided_ty_name),
1125 ));
923072b8 1126 }
064997fb
FG
1127
1128 suggestion_text = match suggestion_text {
1129 SuggestionText::None => SuggestionText::Reorder,
1130 _ => SuggestionText::DidYouMean,
1131 };
04454e1e 1132 }
5099ac24 1133 }
5099ac24
FG
1134 }
1135
9ffffee4
FG
1136 // Incorporate the argument changes in the removal suggestion.
1137 // When a type is *missing*, and the rest are additional, we want to suggest these with a
1138 // multipart suggestion, but in order to do so we need to figure out *where* the arg that
1139 // was provided but had the wrong type should go, because when looking at `expected_idx`
1140 // that is the position in the argument list in the definition, while `provided_idx` will
1141 // not be present. So we have to look at what the *last* provided position was, and point
1142 // one after to suggest the replacement. FIXME(estebank): This is hacky, and there's
1143 // probably a better more involved change we can make to make this work.
1144 // For example, if we have
1145 // ```
1146 // fn foo(i32, &'static str) {}
1147 // foo((), (), ());
1148 // ```
1149 // what should be suggested is
1150 // ```
1151 // foo(/* i32 */, /* &str */);
1152 // ```
1153 // which includes the replacement of the first two `()` for the correct type, and the
1154 // removal of the last `()`.
1155 let mut prev = -1;
1156 for (expected_idx, provided_idx) in matched_inputs.iter_enumerated() {
1157 // We want to point not at the *current* argument expression index, but rather at the
1158 // index position where it *should have been*, which is *after* the previous one.
1159 if let Some(provided_idx) = provided_idx {
1160 prev = provided_idx.index() as i64;
1161 }
1162 let idx = ProvidedIdx::from_usize((prev + 1) as usize);
1163 if let None = provided_idx
1164 && let Some((_, arg_span)) = provided_arg_tys.get(idx)
1165 {
1166 // There is a type that was *not* found anywhere, so it isn't a move, but a
1167 // replacement and we look at what type it should have been. This will allow us
1168 // To suggest a multipart suggestion when encountering `foo(1, "")` where the def
1169 // was `fn foo(())`.
1170 let (_, expected_ty) = formal_and_expected_inputs[expected_idx];
1171 suggestions.push((*arg_span, ty_to_snippet(expected_ty, expected_idx)));
1172 }
1173 }
1174
064997fb
FG
1175 // If we have less than 5 things to say, it would be useful to call out exactly what's wrong
1176 if labels.len() <= 5 {
1177 for (span, label) in labels {
1178 err.span_label(span, label);
1179 }
1180 }
5869c6ff 1181
064997fb 1182 // Call out where the function is defined
f2b60f7d 1183 self.label_fn_like(&mut err, fn_def_id, callee_ty, None, is_method);
29967ef6 1184
064997fb
FG
1185 // And add a suggestion block for all of the parameters
1186 let suggestion_text = match suggestion_text {
1187 SuggestionText::None => None,
1188 SuggestionText::Provide(plural) => {
1189 Some(format!("provide the argument{}", if plural { "s" } else { "" }))
1190 }
1191 SuggestionText::Remove(plural) => {
9ffffee4
FG
1192 err.multipart_suggestion(
1193 &format!("remove the extra argument{}", if plural { "s" } else { "" }),
1194 suggestions,
1195 Applicability::HasPlaceholders,
1196 );
1197 None
064997fb
FG
1198 }
1199 SuggestionText::Swap => Some("swap these arguments".to_string()),
1200 SuggestionText::Reorder => Some("reorder these arguments".to_string()),
1201 SuggestionText::DidYouMean => Some("did you mean".to_string()),
1202 };
1203 if let Some(suggestion_text) = suggestion_text {
1204 let source_map = self.sess().source_map();
f2b60f7d
FG
1205 let (mut suggestion, suggestion_span) =
1206 if let Some(call_span) = full_call_span.find_ancestor_inside(error_span) {
1207 ("(".to_string(), call_span.shrink_to_hi().to(error_span.shrink_to_hi()))
1208 } else {
1209 (
1210 format!(
1211 "{}(",
1212 source_map.span_to_snippet(full_call_span).unwrap_or_else(|_| {
1213 fn_def_id.map_or("".to_string(), |fn_def_id| {
1214 tcx.item_name(fn_def_id).to_string()
1215 })
1216 })
1217 ),
1218 error_span,
1219 )
1220 };
064997fb
FG
1221 let mut needs_comma = false;
1222 for (expected_idx, provided_idx) in matched_inputs.iter_enumerated() {
1223 if needs_comma {
1224 suggestion += ", ";
1225 } else {
1226 needs_comma = true;
5e7ed085 1227 }
064997fb
FG
1228 let suggestion_text = if let Some(provided_idx) = provided_idx
1229 && let (_, provided_span) = provided_arg_tys[*provided_idx]
f2b60f7d 1230 && let Ok(arg_text) = source_map.span_to_snippet(provided_span)
064997fb
FG
1231 {
1232 arg_text
1233 } else {
1234 // Propose a placeholder of the correct type
1235 let (_, expected_ty) = formal_and_expected_inputs[expected_idx];
9ffffee4 1236 ty_to_snippet(expected_ty, expected_idx)
064997fb
FG
1237 };
1238 suggestion += &suggestion_text;
29967ef6 1239 }
064997fb
FG
1240 suggestion += ")";
1241 err.span_suggestion_verbose(
f2b60f7d 1242 suggestion_span,
064997fb
FG
1243 &suggestion_text,
1244 suggestion,
1245 Applicability::HasPlaceholders,
1246 );
29967ef6 1247 }
5099ac24 1248
064997fb 1249 err.emit();
5099ac24
FG
1250 }
1251
29967ef6
XL
1252 // AST fragment checking
1253 pub(in super::super) fn check_lit(
1254 &self,
1255 lit: &hir::Lit,
1256 expected: Expectation<'tcx>,
1257 ) -> Ty<'tcx> {
1258 let tcx = self.tcx;
1259
1260 match lit.node {
1261 ast::LitKind::Str(..) => tcx.mk_static_str(),
9c376795 1262 ast::LitKind::ByteStr(ref v, _) => {
29967ef6
XL
1263 tcx.mk_imm_ref(tcx.lifetimes.re_static, tcx.mk_array(tcx.types.u8, v.len() as u64))
1264 }
1265 ast::LitKind::Byte(_) => tcx.types.u8,
1266 ast::LitKind::Char(_) => tcx.types.char,
5869c6ff
XL
1267 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(ty::int_ty(t)),
1268 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(ty::uint_ty(t)),
29967ef6
XL
1269 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
1270 let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
1271 ty::Int(_) | ty::Uint(_) => Some(ty),
1272 ty::Char => Some(tcx.types.u8),
1273 ty::RawPtr(..) => Some(tcx.types.usize),
1274 ty::FnDef(..) | ty::FnPtr(_) => Some(tcx.types.usize),
1275 _ => None,
1276 });
1277 opt_ty.unwrap_or_else(|| self.next_int_var())
1278 }
5869c6ff
XL
1279 ast::LitKind::Float(_, ast::LitFloatType::Suffixed(t)) => {
1280 tcx.mk_mach_float(ty::float_ty(t))
1281 }
29967ef6
XL
1282 ast::LitKind::Float(_, ast::LitFloatType::Unsuffixed) => {
1283 let opt_ty = expected.to_option(self).and_then(|ty| match ty.kind() {
1284 ty::Float(_) => Some(ty),
1285 _ => None,
1286 });
1287 opt_ty.unwrap_or_else(|| self.next_float_var())
1288 }
1289 ast::LitKind::Bool(_) => tcx.types.bool,
9ffffee4 1290 ast::LitKind::Err => tcx.ty_error_misc(),
29967ef6
XL
1291 }
1292 }
1293
1294 pub fn check_struct_path(
1295 &self,
1296 qpath: &QPath<'_>,
1297 hir_id: hir::HirId,
9ffffee4 1298 ) -> Result<(&'tcx ty::VariantDef, Ty<'tcx>), ErrorGuaranteed> {
6a06907d 1299 let path_span = qpath.span();
29967ef6
XL
1300 let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, hir_id);
1301 let variant = match def {
1302 Res::Err => {
9ffffee4
FG
1303 let guar =
1304 self.tcx.sess.delay_span_bug(path_span, "`Res::Err` but no error emitted");
1305 self.set_tainted_by_errors(guar);
1306 return Err(guar);
29967ef6 1307 }
9c376795
FG
1308 Res::Def(DefKind::Variant, _) => match ty.normalized.ty_adt_def() {
1309 Some(adt) => {
1310 Some((adt.variant_of_res(def), adt.did(), Self::user_substs_for_adt(ty)))
1311 }
1312 _ => bug!("unexpected type: {:?}", ty.normalized),
29967ef6
XL
1313 },
1314 Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _)
2b03887a 1315 | Res::SelfTyParam { .. }
9c376795
FG
1316 | Res::SelfTyAlias { .. } => match ty.normalized.ty_adt_def() {
1317 Some(adt) if !adt.is_enum() => {
1318 Some((adt.non_enum_variant(), adt.did(), Self::user_substs_for_adt(ty)))
29967ef6
XL
1319 }
1320 _ => None,
1321 },
1322 _ => bug!("unexpected definition: {:?}", def),
1323 };
1324
9c376795 1325 if let Some((variant, did, ty::UserSubsts { substs, user_self_ty })) = variant {
29967ef6 1326 debug!("check_struct_path: did={:?} substs={:?}", did, substs);
9c376795
FG
1327
1328 // Register type annotation.
1329 self.write_user_type_annotation_from_substs(hir_id, did, substs, user_self_ty);
29967ef6
XL
1330
1331 // Check bounds on type arguments used in the path.
f2b60f7d 1332 self.add_required_obligations_for_hir(path_span, did, substs, hir_id);
29967ef6 1333
9ffffee4 1334 Ok((variant, ty.normalized))
29967ef6 1335 } else {
9ffffee4
FG
1336 Err(match *ty.normalized.kind() {
1337 ty::Error(guar) => {
c295e0f8
XL
1338 // E0071 might be caused by a spelling error, which will have
1339 // already caused an error message and probably a suggestion
1340 // elsewhere. Refrain from emitting more unhelpful errors here
1341 // (issue #88844).
9ffffee4 1342 guar
c295e0f8 1343 }
9ffffee4
FG
1344 _ => struct_span_err!(
1345 self.tcx.sess,
1346 path_span,
1347 E0071,
1348 "expected struct, variant or union type, found {}",
1349 ty.normalized.sort_string(self.tcx)
1350 )
1351 .span_label(path_span, "not a struct")
1352 .emit(),
1353 })
29967ef6
XL
1354 }
1355 }
1356
1357 pub fn check_decl_initializer(
1358 &self,
a2a8927a
XL
1359 hir_id: hir::HirId,
1360 pat: &'tcx hir::Pat<'tcx>,
29967ef6
XL
1361 init: &'tcx hir::Expr<'tcx>,
1362 ) -> Ty<'tcx> {
1363 // FIXME(tschottdorf): `contains_explicit_ref_binding()` must be removed
1364 // for #42640 (default match binding modes).
1365 //
1366 // See #44848.
a2a8927a 1367 let ref_bindings = pat.contains_explicit_ref_binding();
29967ef6 1368
a2a8927a 1369 let local_ty = self.local_ty(init.span, hir_id).revealed_ty;
29967ef6
XL
1370 if let Some(m) = ref_bindings {
1371 // Somewhat subtle: if we have a `ref` binding in the pattern,
1372 // we want to avoid introducing coercions for the RHS. This is
1373 // both because it helps preserve sanity and, in the case of
1374 // ref mut, for soundness (issue #23116). In particular, in
1375 // the latter case, we need to be clear that the type of the
1376 // referent for the reference that results is *equal to* the
1377 // type of the place it is referencing, and not some
1378 // supertype thereof.
1379 let init_ty = self.check_expr_with_needs(init, Needs::maybe_mut_place(m));
1380 self.demand_eqtype(init.span, local_ty, init_ty);
1381 init_ty
1382 } else {
1383 self.check_expr_coercable_to_type(init, local_ty, None)
1384 }
1385 }
1386
a2a8927a 1387 pub(in super::super) fn check_decl(&self, decl: Declaration<'tcx>) {
29967ef6 1388 // Determine and write the type which we'll check the pattern against.
a2a8927a
XL
1389 let decl_ty = self.local_ty(decl.span, decl.hir_id).decl_ty;
1390 self.write_ty(decl.hir_id, decl_ty);
29967ef6
XL
1391
1392 // Type check the initializer.
a2a8927a
XL
1393 if let Some(ref init) = decl.init {
1394 let init_ty = self.check_decl_initializer(decl.hir_id, decl.pat, &init);
9c376795 1395 self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, init_ty);
29967ef6
XL
1396 }
1397
1398 // Does the expected pattern type originate from an expression and what is the span?
a2a8927a 1399 let (origin_expr, ty_span) = match (decl.ty, decl.init) {
9ffffee4 1400 (Some(ty), _) => (None, Some(ty.span)), // Bias towards the explicit user type.
064997fb 1401 (_, Some(init)) => {
9ffffee4 1402 (Some(init), Some(init.span.find_ancestor_inside(decl.span).unwrap_or(init.span)))
064997fb 1403 } // No explicit type; so use the scrutinee.
9ffffee4 1404 _ => (None, None), // We have `let $pat;`, so the expected type is unconstrained.
29967ef6
XL
1405 };
1406
1407 // Type check the pattern. Override if necessary to avoid knock-on errors.
a2a8927a
XL
1408 self.check_pat_top(&decl.pat, decl_ty, ty_span, origin_expr);
1409 let pat_ty = self.node_ty(decl.pat.hir_id);
9c376795 1410 self.overwrite_local_ty_if_err(decl.hir_id, decl.pat, pat_ty);
064997fb
FG
1411
1412 if let Some(blk) = decl.els {
1413 let previous_diverges = self.diverges.get();
1414 let else_ty = self.check_block_with_expected(blk, NoExpectation);
1415 let cause = self.cause(blk.span, ObligationCauseCode::LetElse);
1416 if let Some(mut err) =
1417 self.demand_eqtype_with_origin(&cause, self.tcx.types.never, else_ty)
1418 {
1419 err.emit();
1420 }
1421 self.diverges.set(previous_diverges);
1422 }
a2a8927a
XL
1423 }
1424
1425 /// Type check a `let` statement.
1426 pub fn check_decl_local(&self, local: &'tcx hir::Local<'tcx>) {
1427 self.check_decl(local.into());
29967ef6
XL
1428 }
1429
6a06907d 1430 pub fn check_stmt(&self, stmt: &'tcx hir::Stmt<'tcx>, is_last: bool) {
29967ef6
XL
1431 // Don't do all the complex logic below for `DeclItem`.
1432 match stmt.kind {
1433 hir::StmtKind::Item(..) => return,
1434 hir::StmtKind::Local(..) | hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {}
1435 }
1436
1437 self.warn_if_unreachable(stmt.hir_id, stmt.span, "statement");
1438
1439 // Hide the outer diverging and `has_errors` flags.
1440 let old_diverges = self.diverges.replace(Diverges::Maybe);
29967ef6
XL
1441
1442 match stmt.kind {
064997fb
FG
1443 hir::StmtKind::Local(l) => {
1444 self.check_decl_local(l);
29967ef6
XL
1445 }
1446 // Ignore for now.
1447 hir::StmtKind::Item(_) => {}
1448 hir::StmtKind::Expr(ref expr) => {
1449 // Check with expected type of `()`.
1450 self.check_expr_has_type_or_error(&expr, self.tcx.mk_unit(), |err| {
6a06907d
XL
1451 if expr.can_have_side_effects() {
1452 self.suggest_semicolon_at_end(expr.span, err);
1453 }
29967ef6
XL
1454 });
1455 }
1456 hir::StmtKind::Semi(ref expr) => {
6a06907d
XL
1457 // All of this is equivalent to calling `check_expr`, but it is inlined out here
1458 // in order to capture the fact that this `match` is the last statement in its
1459 // function. This is done for better suggestions to remove the `;`.
1460 let expectation = match expr.kind {
1461 hir::ExprKind::Match(..) if is_last => IsLast(stmt.span),
1462 _ => NoExpectation,
1463 };
1464 self.check_expr_with_expectation(expr, expectation);
29967ef6
XL
1465 }
1466 }
1467
1468 // Combine the diverging and `has_error` flags.
1469 self.diverges.set(self.diverges.get() | old_diverges);
29967ef6
XL
1470 }
1471
1472 pub fn check_block_no_value(&self, blk: &'tcx hir::Block<'tcx>) {
1473 let unit = self.tcx.mk_unit();
1474 let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
1475
1476 // if the block produces a `!` value, that can always be
1477 // (effectively) coerced to unit.
1478 if !ty.is_never() {
1479 self.demand_suptype(blk.span, unit, ty);
1480 }
1481 }
1482
1483 pub(in super::super) fn check_block_with_expected(
1484 &self,
1485 blk: &'tcx hir::Block<'tcx>,
1486 expected: Expectation<'tcx>,
1487 ) -> Ty<'tcx> {
29967ef6
XL
1488 // In some cases, blocks have just one exit, but other blocks
1489 // can be targeted by multiple breaks. This can happen both
1490 // with labeled blocks as well as when we desugar
1491 // a `try { ... }` expression.
1492 //
1493 // Example 1:
1494 //
1495 // 'a: { if true { break 'a Err(()); } Ok(()) }
1496 //
1497 // Here we would wind up with two coercions, one from
1498 // `Err(())` and the other from the tail expression
1499 // `Ok(())`. If the tail expression is omitted, that's a
1500 // "forced unit" -- unless the block diverges, in which
1501 // case we can ignore the tail expression (e.g., `'a: {
1502 // break 'a 22; }` would not force the type of the block
1503 // to be `()`).
1504 let tail_expr = blk.expr.as_ref();
1505 let coerce_to_ty = expected.coercion_target_type(self, blk.span);
1506 let coerce = if blk.targeted_by_break {
1507 CoerceMany::new(coerce_to_ty)
1508 } else {
9ffffee4 1509 CoerceMany::with_coercion_sites(coerce_to_ty, blk.expr.as_slice())
29967ef6
XL
1510 };
1511
1512 let prev_diverges = self.diverges.get();
1513 let ctxt = BreakableCtxt { coerce: Some(coerce), may_break: false };
1514
1515 let (ctxt, ()) = self.with_breakable_ctxt(blk.hir_id, ctxt, || {
6a06907d
XL
1516 for (pos, s) in blk.stmts.iter().enumerate() {
1517 self.check_stmt(s, blk.stmts.len() - 1 == pos);
29967ef6
XL
1518 }
1519
1520 // check the tail expression **without** holding the
1521 // `enclosing_breakables` lock below.
1522 let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
1523
1524 let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
1525 let ctxt = enclosing_breakables.find_breakable(blk.hir_id);
1526 let coerce = ctxt.coerce.as_mut().unwrap();
1527 if let Some(tail_expr_ty) = tail_expr_ty {
1528 let tail_expr = tail_expr.unwrap();
1529 let span = self.get_expr_coercion_span(tail_expr);
1530 let cause = self.cause(span, ObligationCauseCode::BlockTailExpression(blk.hir_id));
5e7ed085
FG
1531 let ty_for_diagnostic = coerce.merged_ty();
1532 // We use coerce_inner here because we want to augment the error
1533 // suggesting to wrap the block in square brackets if it might've
1534 // been mistaken array syntax
1535 coerce.coerce_inner(
1536 self,
1537 &cause,
1538 Some(tail_expr),
1539 tail_expr_ty,
1540 Some(&mut |diag: &mut Diagnostic| {
1541 self.suggest_block_to_brackets(diag, blk, tail_expr_ty, ty_for_diagnostic);
1542 }),
1543 false,
1544 );
29967ef6
XL
1545 } else {
1546 // Subtle: if there is no explicit tail expression,
1547 // that is typically equivalent to a tail expression
1548 // of `()` -- except if the block diverges. In that
1549 // case, there is no value supplied from the tail
1550 // expression (assuming there are no other breaks,
1551 // this implies that the type of the block will be
1552 // `!`).
1553 //
1554 // #41425 -- label the implicit `()` as being the
1555 // "found type" here, rather than the "expected type".
1556 if !self.diverges.get().is_always() {
1557 // #50009 -- Do not point at the entire fn block span, point at the return type
1558 // span, as it is the cause of the requirement, and
1559 // `consider_hint_about_removing_semicolon` will point at the last expression
1560 // if it were a relevant part of the error. This improves usability in editors
1561 // that highlight errors inline.
1562 let mut sp = blk.span;
1563 let mut fn_span = None;
1564 if let Some((decl, ident)) = self.get_parent_fn_decl(blk.hir_id) {
1565 let ret_sp = decl.output.span();
1566 if let Some(block_sp) = self.parent_item_span(blk.hir_id) {
1567 // HACK: on some cases (`ui/liveness/liveness-issue-2163.rs`) the
1568 // output would otherwise be incorrect and even misleading. Make sure
1569 // the span we're aiming at correspond to a `fn` body.
1570 if block_sp == blk.span {
1571 sp = ret_sp;
1572 fn_span = Some(ident.span);
1573 }
1574 }
1575 }
1576 coerce.coerce_forced_unit(
1577 self,
1578 &self.misc(sp),
1579 &mut |err| {
1580 if let Some(expected_ty) = expected.only_has_type(self) {
064997fb 1581 if !self.consider_removing_semicolon(blk, expected_ty, err) {
2b03887a
FG
1582 self.err_ctxt().consider_returning_binding(
1583 blk,
1584 expected_ty,
1585 err,
1586 );
064997fb 1587 }
3c0e092e
XL
1588 if expected_ty == self.tcx.types.bool {
1589 // If this is caused by a missing `let` in a `while let`,
1590 // silence this redundant error, as we already emit E0070.
5e7ed085
FG
1591
1592 // Our block must be a `assign desugar local; assignment`
1593 if let Some(hir::Node::Block(hir::Block {
1594 stmts:
1595 [
1596 hir::Stmt {
1597 kind:
1598 hir::StmtKind::Local(hir::Local {
1599 source:
1600 hir::LocalSource::AssignDesugar(_),
1601 ..
1602 }),
1603 ..
1604 },
1605 hir::Stmt {
1606 kind:
1607 hir::StmtKind::Expr(hir::Expr {
1608 kind: hir::ExprKind::Assign(..),
1609 ..
1610 }),
1611 ..
1612 },
1613 ],
1614 ..
1615 })) = self.tcx.hir().find(blk.hir_id)
1616 {
1617 self.comes_from_while_condition(blk.hir_id, |_| {
1618 err.downgrade_to_delayed_bug();
1619 })
3c0e092e
XL
1620 }
1621 }
29967ef6
XL
1622 }
1623 if let Some(fn_span) = fn_span {
1624 err.span_label(
1625 fn_span,
1626 "implicitly returns `()` as its body has no tail or `return` \
1627 expression",
1628 );
1629 }
1630 },
1631 false,
1632 );
1633 }
1634 }
1635 });
1636
1637 if ctxt.may_break {
1638 // If we can break from the block, then the block's exit is always reachable
1639 // (... as long as the entry is reachable) - regardless of the tail of the block.
1640 self.diverges.set(prev_diverges);
1641 }
1642
487cf647 1643 let ty = ctxt.coerce.unwrap().complete(self);
29967ef6
XL
1644
1645 self.write_ty(blk.hir_id, ty);
1646
29967ef6
XL
1647 ty
1648 }
1649
29967ef6 1650 fn parent_item_span(&self, id: hir::HirId) -> Option<Span> {
2b03887a 1651 let node = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(id).def_id);
29967ef6
XL
1652 match node {
1653 Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. })
1654 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => {
1655 let body = self.tcx.hir().body(body_id);
1656 if let ExprKind::Block(block, _) = &body.value.kind {
1657 return Some(block.span);
1658 }
1659 }
1660 _ => {}
1661 }
1662 None
1663 }
1664
1665 /// Given a function block's `HirId`, returns its `FnDecl` if it exists, or `None` otherwise.
1666 fn get_parent_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident)> {
2b03887a 1667 let parent = self.tcx.hir().get_by_def_id(self.tcx.hir().get_parent_item(blk_id).def_id);
29967ef6
XL
1668 self.get_node_fn_decl(parent).map(|(fn_decl, ident, _)| (fn_decl, ident))
1669 }
1670
1671 /// If `expr` is a `match` expression that has only one non-`!` arm, use that arm's tail
1672 /// expression's `Span`, otherwise return `expr.span`. This is done to give better errors
1673 /// when given code like the following:
1674 /// ```text
1675 /// if false { return 0i32; } else { 1u32 }
1676 /// // ^^^^ point at this instead of the whole `if` expression
1677 /// ```
1678 fn get_expr_coercion_span(&self, expr: &hir::Expr<'_>) -> rustc_span::Span {
5869c6ff 1679 let check_in_progress = |elem: &hir::Expr<'_>| {
064997fb
FG
1680 self.typeck_results.borrow().node_type_opt(elem.hir_id).filter(|ty| !ty.is_never()).map(
1681 |_| match elem.kind {
1682 // Point at the tail expression when possible.
1683 hir::ExprKind::Block(block, _) => block.expr.map_or(block.span, |e| e.span),
1684 _ => elem.span,
1685 },
1686 )
5869c6ff
XL
1687 };
1688
1689 if let hir::ExprKind::If(_, _, Some(el)) = expr.kind {
1690 if let Some(rslt) = check_in_progress(el) {
1691 return rslt;
29967ef6
XL
1692 }
1693 }
5869c6ff
XL
1694
1695 if let hir::ExprKind::Match(_, arms, _) = expr.kind {
1696 let mut iter = arms.iter().filter_map(|arm| check_in_progress(arm.body));
1697 if let Some(span) = iter.next() {
1698 if iter.next().is_none() {
1699 return span;
1700 }
1701 }
1702 }
1703
29967ef6
XL
1704 expr.span
1705 }
1706
1707 fn overwrite_local_ty_if_err(
1708 &self,
a2a8927a
XL
1709 hir_id: hir::HirId,
1710 pat: &'tcx hir::Pat<'tcx>,
29967ef6
XL
1711 ty: Ty<'tcx>,
1712 ) {
9ffffee4 1713 if let Err(guar) = ty.error_reported() {
29967ef6 1714 // Override the types everywhere with `err()` to avoid knock on errors.
9ffffee4 1715 let err = self.tcx.ty_error(guar);
9c376795
FG
1716 self.write_ty(hir_id, err);
1717 self.write_ty(pat.hir_id, err);
1718 let local_ty = LocalTy { decl_ty: err, revealed_ty: err };
a2a8927a
XL
1719 self.locals.borrow_mut().insert(hir_id, local_ty);
1720 self.locals.borrow_mut().insert(pat.hir_id, local_ty);
29967ef6
XL
1721 }
1722 }
1723
1724 // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
1725 // The newly resolved definition is written into `type_dependent_defs`.
1726 fn finish_resolving_struct_path(
1727 &self,
1728 qpath: &QPath<'_>,
1729 path_span: Span,
1730 hir_id: hir::HirId,
9c376795 1731 ) -> (Res, RawTy<'tcx>) {
29967ef6
XL
1732 match *qpath {
1733 QPath::Resolved(ref maybe_qself, ref path) => {
9c376795 1734 let self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself).raw);
9ffffee4 1735 let ty = self.astconv().res_to_ty(self_ty, path, hir_id, true);
9c376795 1736 (path.res, self.handle_raw_ty(path_span, ty))
29967ef6
XL
1737 }
1738 QPath::TypeRelative(ref qself, ref segment) => {
1739 let ty = self.to_ty(qself);
1740
9c376795
FG
1741 let result = self
1742 .astconv()
1743 .associated_path_to_ty(hir_id, path_span, ty.raw, qself, segment, true);
9ffffee4
FG
1744 let ty =
1745 result.map(|(ty, _, _)| ty).unwrap_or_else(|guar| self.tcx().ty_error(guar));
9c376795 1746 let ty = self.handle_raw_ty(path_span, ty);
29967ef6
XL
1747 let result = result.map(|(_, kind, def_id)| (kind, def_id));
1748
1749 // Write back the new resolution.
1750 self.write_resolution(hir_id, result);
1751
5869c6ff 1752 (result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), ty)
29967ef6 1753 }
a2a8927a 1754 QPath::LangItem(lang_item, span, id) => {
9c376795
FG
1755 let (res, ty) = self.resolve_lang_item_path(lang_item, span, hir_id, id);
1756 (res, self.handle_raw_ty(path_span, ty))
29967ef6
XL
1757 }
1758 }
1759 }
1760
f2b60f7d
FG
1761 /// Given a vector of fulfillment errors, try to adjust the spans of the
1762 /// errors to more accurately point at the cause of the failure.
1763 ///
1764 /// This applies to calls, methods, and struct expressions. This will also
1765 /// try to deduplicate errors that are due to the same cause but might
1766 /// have been created with different [`ObligationCause`][traits::ObligationCause]s.
1767 pub(super) fn adjust_fulfillment_errors_for_expr_obligation(
29967ef6
XL
1768 &self,
1769 errors: &mut Vec<traits::FulfillmentError<'tcx>>,
29967ef6 1770 ) {
f2b60f7d
FG
1771 // Store a mapping from `(Span, Predicate) -> ObligationCause`, so that
1772 // other errors that have the same span and predicate can also get fixed,
1773 // even if their `ObligationCauseCode` isn't an `Expr*Obligation` kind.
1774 // This is important since if we adjust one span but not the other, then
1775 // we will have "duplicated" the error on the UI side.
9c376795 1776 let mut remap_cause = FxIndexSet::default();
f2b60f7d
FG
1777 let mut not_adjusted = vec![];
1778
1779 for error in errors {
1780 let before_span = error.obligation.cause.span;
1781 if self.adjust_fulfillment_error_for_expr_obligation(error)
1782 || before_span != error.obligation.cause.span
1783 {
1784 // Store both the predicate and the predicate *without constness*
1785 // since sometimes we instantiate and check both of these in a
1786 // method call, for example.
1787 remap_cause.insert((
1788 before_span,
1789 error.obligation.predicate,
1790 error.obligation.cause.clone(),
1791 ));
1792 remap_cause.insert((
1793 before_span,
1794 error.obligation.predicate.without_const(self.tcx),
1795 error.obligation.cause.clone(),
1796 ));
1797 } else {
1798 // If it failed to be adjusted once around, it may be adjusted
1799 // via the "remap cause" mapping the second time...
1800 not_adjusted.push(error);
29967ef6 1801 }
f2b60f7d 1802 }
29967ef6 1803
9c376795
FG
1804 // Adjust any other errors that come from other cause codes, when these
1805 // errors are of the same predicate as one we successfully adjusted, and
1806 // when their spans overlap (suggesting they're due to the same root cause).
1807 //
1808 // This is because due to normalization, we often register duplicate
1809 // obligations with misc obligations that are basically impossible to
1810 // line back up with a useful ExprBindingObligation.
f2b60f7d
FG
1811 for error in not_adjusted {
1812 for (span, predicate, cause) in &remap_cause {
1813 if *predicate == error.obligation.predicate
1814 && span.contains(error.obligation.cause.span)
1815 {
1816 error.obligation.cause = cause.clone();
1817 continue;
3c0e092e 1818 }
3c0e092e 1819 }
f2b60f7d
FG
1820 }
1821 }
1822
064997fb
FG
1823 fn label_fn_like(
1824 &self,
f2b60f7d 1825 err: &mut Diagnostic,
064997fb
FG
1826 callable_def_id: Option<DefId>,
1827 callee_ty: Option<Ty<'tcx>>,
f2b60f7d
FG
1828 // A specific argument should be labeled, instead of all of them
1829 expected_idx: Option<usize>,
1830 is_method: bool,
064997fb
FG
1831 ) {
1832 let Some(mut def_id) = callable_def_id else {
1833 return;
1834 };
1835
1836 if let Some(assoc_item) = self.tcx.opt_associated_item(def_id)
1837 // Possibly points at either impl or trait item, so try to get it
1838 // to point to trait item, then get the parent.
1839 // This parent might be an impl in the case of an inherent function,
1840 // but the next check will fail.
1841 && let maybe_trait_item_def_id = assoc_item.trait_item_def_id.unwrap_or(def_id)
1842 && let maybe_trait_def_id = self.tcx.parent(maybe_trait_item_def_id)
1843 // Just an easy way to check "trait_def_id == Fn/FnMut/FnOnce"
487cf647 1844 && let Some(call_kind) = self.tcx.fn_trait_kind_from_def_id(maybe_trait_def_id)
064997fb
FG
1845 && let Some(callee_ty) = callee_ty
1846 {
1847 let callee_ty = callee_ty.peel_refs();
1848 match *callee_ty.kind() {
1849 ty::Param(param) => {
1850 let param =
9ffffee4 1851 self.tcx.generics_of(self.body_id).type_param(&param, self.tcx);
064997fb
FG
1852 if param.kind.is_synthetic() {
1853 // if it's `impl Fn() -> ..` then just fall down to the def-id based logic
1854 def_id = param.def_id;
1855 } else {
1856 // Otherwise, find the predicate that makes this generic callable,
1857 // and point at that.
1858 let instantiated = self
1859 .tcx
9ffffee4 1860 .explicit_predicates_of(self.body_id)
064997fb
FG
1861 .instantiate_identity(self.tcx);
1862 // FIXME(compiler-errors): This could be problematic if something has two
1863 // fn-like predicates with different args, but callable types really never
1864 // do that, so it's OK.
9c376795 1865 for (predicate, span) in instantiated
064997fb 1866 {
487cf647 1867 if let ty::PredicateKind::Clause(ty::Clause::Trait(pred)) = predicate.kind().skip_binder()
064997fb 1868 && pred.self_ty().peel_refs() == callee_ty
487cf647 1869 && self.tcx.is_fn_trait(pred.def_id())
064997fb
FG
1870 {
1871 err.span_note(span, "callable defined here");
1872 return;
1873 }
1874 }
1875 }
1876 }
9c376795 1877 ty::Alias(ty::Opaque, ty::AliasTy { def_id: new_def_id, .. })
064997fb
FG
1878 | ty::Closure(new_def_id, _)
1879 | ty::FnDef(new_def_id, _) => {
1880 def_id = new_def_id;
1881 }
1882 _ => {
1883 // Look for a user-provided impl of a `Fn` trait, and point to it.
1884 let new_def_id = self.probe(|_| {
9c376795 1885 let trait_ref = self.tcx.mk_trait_ref(
064997fb 1886 call_kind.to_def_id(self.tcx),
9c376795
FG
1887 [
1888 callee_ty,
1889 self.next_ty_var(TypeVariableOrigin {
1890 kind: TypeVariableOriginKind::MiscVariable,
1891 span: rustc_span::DUMMY_SP,
1892 }),
1893 ],
064997fb
FG
1894 );
1895 let obligation = traits::Obligation::new(
487cf647 1896 self.tcx,
064997fb
FG
1897 traits::ObligationCause::dummy(),
1898 self.param_env,
487cf647 1899 ty::Binder::dummy(trait_ref),
064997fb
FG
1900 );
1901 match SelectionContext::new(&self).select(&obligation) {
1902 Ok(Some(traits::ImplSource::UserDefined(impl_source))) => {
1903 Some(impl_source.impl_def_id)
1904 }
f2b60f7d 1905 _ => None,
064997fb
FG
1906 }
1907 });
1908 if let Some(new_def_id) = new_def_id {
1909 def_id = new_def_id;
1910 } else {
1911 return;
1912 }
1913 }
1914 }
923072b8
FG
1915 }
1916
064997fb
FG
1917 if let Some(def_span) = self.tcx.def_ident_span(def_id) && !def_span.is_dummy() {
1918 let mut spans: MultiSpan = def_span.into();
923072b8 1919
064997fb
FG
1920 let params = self
1921 .tcx
1922 .hir()
1923 .get_if_local(def_id)
1924 .and_then(|node| node.body_id())
1925 .into_iter()
f2b60f7d
FG
1926 .flat_map(|id| self.tcx.hir().body(id).params)
1927 .skip(if is_method { 1 } else { 0 });
923072b8 1928
f2b60f7d
FG
1929 for (_, param) in params
1930 .into_iter()
1931 .enumerate()
1932 .filter(|(idx, _)| expected_idx.map_or(true, |expected_idx| expected_idx == *idx))
1933 {
064997fb 1934 spans.push_span_label(param.span, "");
923072b8 1935 }
064997fb 1936
9ffffee4 1937 err.span_note(spans, &format!("{} defined here", self.tcx.def_descr(def_id)));
f2b60f7d
FG
1938 } else if let Some(hir::Node::Expr(e)) = self.tcx.hir().get_if_local(def_id)
1939 && let hir::ExprKind::Closure(hir::Closure { body, .. }) = &e.kind
1940 {
1941 let param = expected_idx
1942 .and_then(|expected_idx| self.tcx.hir().body(*body).params.get(expected_idx));
1943 let (kind, span) = if let Some(param) = param {
1944 ("closure parameter", param.span)
1945 } else {
1946 ("closure", self.tcx.def_span(def_id))
1947 };
1948 err.span_note(span, &format!("{} defined here", kind));
064997fb 1949 } else {
064997fb
FG
1950 err.span_note(
1951 self.tcx.def_span(def_id),
9ffffee4 1952 &format!("{} defined here", self.tcx.def_descr(def_id)),
064997fb 1953 );
923072b8
FG
1954 }
1955 }
1956}