/
checks.rs
2246 lines (2094 loc) · 101 KB
/
checks.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::coercion::CoerceMany;
use crate::errors::SuggestPtrNullMut;
use crate::fn_ctxt::arg_matrix::{ArgMatrix, Compatibility, Error, ExpectedIdx, ProvidedIdx};
use crate::fn_ctxt::infer::FnCall;
use crate::gather_locals::Declaration;
use crate::method::probe::IsSuggestion;
use crate::method::probe::Mode::MethodCall;
use crate::method::probe::ProbeScope::TraitsInScope;
use crate::method::MethodCallee;
use crate::TupleArgumentsFlag::*;
use crate::{errors, Expectation::*};
use crate::{
struct_span_code_err, BreakableCtxt, Diverges, Expectation, FnCtxt, LoweredTy, Needs,
TupleArgumentsFlag,
};
use itertools::Itertools;
use rustc_ast as ast;
use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{
codes::*, pluralize, Applicability, Diag, ErrorGuaranteed, MultiSpan, StashKey,
};
use rustc_hir as hir;
use rustc_hir::def::{CtorOf, DefKind, Res};
use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::Visitor;
use rustc_hir::{ExprKind, Node, QPath};
use rustc_hir_analysis::astconv::AstConv;
use rustc_hir_analysis::check::intrinsicck::InlineAsmCtxt;
use rustc_hir_analysis::check::potentially_plural_count;
use rustc_hir_analysis::structured_errors::StructuredDiagnostic;
use rustc_index::IndexVec;
use rustc_infer::infer::error_reporting::{FailureCode, ObligationCauseExt};
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use rustc_infer::infer::TypeTrace;
use rustc_infer::infer::{DefineOpaqueTypes, InferOk};
use rustc_middle::traits::ObligationCauseCode::ExprBindingObligation;
use rustc_middle::ty::adjustment::AllowTwoPhase;
use rustc_middle::ty::visit::TypeVisitableExt;
use rustc_middle::ty::{self, IsSuggestable, Ty, TyCtxt};
use rustc_session::Session;
use rustc_span::symbol::{kw, Ident};
use rustc_span::{sym, BytePos, Span};
use rustc_trait_selection::traits::{self, ObligationCauseCode, SelectionContext};
use std::iter;
use std::mem;
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
pub(in super::super) fn check_casts(&mut self) {
// don't hold the borrow to deferred_cast_checks while checking to avoid borrow checker errors
// when writing to `self.param_env`.
let mut deferred_cast_checks = mem::take(&mut *self.deferred_cast_checks.borrow_mut());
debug!("FnCtxt::check_casts: {} deferred checks", deferred_cast_checks.len());
for cast in deferred_cast_checks.drain(..) {
cast.check(self);
}
*self.deferred_cast_checks.borrow_mut() = deferred_cast_checks;
}
pub(in super::super) fn check_transmutes(&self) {
let mut deferred_transmute_checks = self.deferred_transmute_checks.borrow_mut();
debug!("FnCtxt::check_transmutes: {} deferred checks", deferred_transmute_checks.len());
for (from, to, hir_id) in deferred_transmute_checks.drain(..) {
self.check_transmute(from, to, hir_id);
}
}
pub(in super::super) fn check_asms(&self) {
let mut deferred_asm_checks = self.deferred_asm_checks.borrow_mut();
debug!("FnCtxt::check_asm: {} deferred checks", deferred_asm_checks.len());
for (asm, hir_id) in deferred_asm_checks.drain(..) {
let enclosing_id = self.tcx.hir().enclosing_body_owner(hir_id);
let get_operand_ty = |expr| {
let ty = self.typeck_results.borrow().expr_ty_adjusted(expr);
let ty = self.resolve_vars_if_possible(ty);
if ty.has_non_region_infer() {
Ty::new_misc_error(self.tcx)
} else {
self.tcx.erase_regions(ty)
}
};
InlineAsmCtxt::new_in_fn(self.tcx, self.param_env, get_operand_ty)
.check_asm(asm, enclosing_id);
}
}
pub(in super::super) fn check_method_argument_types(
&self,
sp: Span,
expr: &'tcx hir::Expr<'tcx>,
method: Result<MethodCallee<'tcx>, ()>,
args_no_rcvr: &'tcx [hir::Expr<'tcx>],
tuple_arguments: TupleArgumentsFlag,
expected: Expectation<'tcx>,
) -> Ty<'tcx> {
let has_error = match method {
Ok(method) => method.args.references_error() || method.sig.references_error(),
Err(_) => true,
};
if has_error {
let err_inputs = self.err_args(args_no_rcvr.len());
let err_inputs = match tuple_arguments {
DontTupleArguments => err_inputs,
TupleArguments => vec![Ty::new_tup(self.tcx, &err_inputs)],
};
self.check_argument_types(
sp,
expr,
&err_inputs,
None,
args_no_rcvr,
false,
tuple_arguments,
method.ok().map(|method| method.def_id),
);
return Ty::new_misc_error(self.tcx);
}
let method = method.unwrap();
// HACK(eddyb) ignore self in the definition (see above).
let expected_input_tys = self.expected_inputs_for_expected_output(
sp,
expected,
method.sig.output(),
&method.sig.inputs()[1..],
);
self.check_argument_types(
sp,
expr,
&method.sig.inputs()[1..],
expected_input_tys,
args_no_rcvr,
method.sig.c_variadic,
tuple_arguments,
Some(method.def_id),
);
method.sig.output()
}
/// Generic function that factors out common logic from function calls,
/// method calls and overloaded operators.
pub(in super::super) fn check_argument_types(
&self,
// Span enclosing the call site
call_span: Span,
// Expression of the call site
call_expr: &'tcx hir::Expr<'tcx>,
// Types (as defined in the *signature* of the target function)
formal_input_tys: &[Ty<'tcx>],
// More specific expected types, after unifying with caller output types
expected_input_tys: Option<Vec<Ty<'tcx>>>,
// The expressions for each provided argument
provided_args: &'tcx [hir::Expr<'tcx>],
// Whether the function is variadic, for example when imported from C
c_variadic: bool,
// Whether the arguments have been bundled in a tuple (ex: closures)
tuple_arguments: TupleArgumentsFlag,
// The DefId for the function being called, for better error messages
fn_def_id: Option<DefId>,
) {
let tcx = self.tcx;
// Conceptually, we've got some number of expected inputs, and some number of provided arguments
// and we can form a grid of whether each argument could satisfy a given input:
// in1 | in2 | in3 | ...
// arg1 ? | | |
// arg2 | ? | |
// arg3 | | ? |
// ...
// Initially, we just check the diagonal, because in the case of correct code
// these are the only checks that matter
// However, in the unhappy path, we'll fill in this whole grid to attempt to provide
// better error messages about invalid method calls.
// All the input types from the fn signature must outlive the call
// so as to validate implied bounds.
for (&fn_input_ty, arg_expr) in iter::zip(formal_input_tys, provided_args) {
self.register_wf_obligation(fn_input_ty.into(), arg_expr.span, traits::MiscObligation);
}
let mut err_code = E0061;
// If the arguments should be wrapped in a tuple (ex: closures), unwrap them here
let (formal_input_tys, expected_input_tys) = if tuple_arguments == TupleArguments {
let tuple_type = self.structurally_resolve_type(call_span, formal_input_tys[0]);
match tuple_type.kind() {
// We expected a tuple and got a tuple
ty::Tuple(arg_types) => {
// Argument length differs
if arg_types.len() != provided_args.len() {
err_code = E0057;
}
let expected_input_tys = match expected_input_tys {
Some(expected_input_tys) => match expected_input_tys.get(0) {
Some(ty) => match ty.kind() {
ty::Tuple(tys) => Some(tys.iter().collect()),
_ => None,
},
None => None,
},
None => None,
};
(arg_types.iter().collect(), expected_input_tys)
}
_ => {
// Otherwise, there's a mismatch, so clear out what we're expecting, and set
// our input types to err_args so we don't blow up the error messages
struct_span_code_err!(
tcx.dcx(),
call_span,
E0059,
"cannot use call notation; the first type parameter \
for the function trait is neither a tuple nor unit"
)
.emit();
(self.err_args(provided_args.len()), None)
}
}
} else {
(formal_input_tys.to_vec(), expected_input_tys)
};
// If there are no external expectations at the call site, just use the types from the function defn
let expected_input_tys = if let Some(expected_input_tys) = expected_input_tys {
assert_eq!(expected_input_tys.len(), formal_input_tys.len());
expected_input_tys
} else {
formal_input_tys.clone()
};
let minimum_input_count = expected_input_tys.len();
let provided_arg_count = provided_args.len();
// We introduce a helper function to demand that a given argument satisfy a given input
// This is more complicated than just checking type equality, as arguments could be coerced
// This version writes those types back so further type checking uses the narrowed types
let demand_compatible = |idx| {
let formal_input_ty: Ty<'tcx> = formal_input_tys[idx];
let expected_input_ty: Ty<'tcx> = expected_input_tys[idx];
let provided_arg = &provided_args[idx];
debug!("checking argument {}: {:?} = {:?}", idx, provided_arg, formal_input_ty);
// We're on the happy path here, so we'll do a more involved check and write back types
// To check compatibility, we'll do 3 things:
// 1. Unify the provided argument with the expected type
let expectation = Expectation::rvalue_hint(self, expected_input_ty);
let checked_ty = self.check_expr_with_expectation(provided_arg, expectation);
// 2. Coerce to the most detailed type that could be coerced
// to, which is `expected_ty` if `rvalue_hint` returns an
// `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
// Cause selection errors caused by resolving a single argument to point at the
// argument and not the call. This lets us customize the span pointed to in the
// fulfillment error to be more accurate.
let coerced_ty = self.resolve_vars_with_obligations(coerced_ty);
let coerce_error =
self.coerce(provided_arg, checked_ty, coerced_ty, AllowTwoPhase::Yes, None).err();
if coerce_error.is_some() {
return Compatibility::Incompatible(coerce_error);
}
// 3. Check if the formal type is a supertype of the checked one
// and register any such obligations for future type checks
let supertype_error = self.at(&self.misc(provided_arg.span), self.param_env).sup(
DefineOpaqueTypes::No,
formal_input_ty,
coerced_ty,
);
let subtyping_error = match supertype_error {
Ok(InferOk { obligations, value: () }) => {
self.register_predicates(obligations);
None
}
Err(err) => Some(err),
};
// If neither check failed, the types are compatible
match subtyping_error {
None => Compatibility::Compatible,
Some(_) => Compatibility::Incompatible(subtyping_error),
}
};
// To start, we only care "along the diagonal", where we expect every
// provided arg to be in the right spot
let mut compatibility_diagonal =
vec![Compatibility::Incompatible(None); provided_args.len()];
// Keep track of whether we *could possibly* be satisfied, i.e. whether we're on the happy path
// if the wrong number of arguments were supplied, we CAN'T be satisfied,
// and if we're c_variadic, the supplied arguments must be >= the minimum count from the function
// otherwise, they need to be identical, because rust doesn't currently support variadic functions
let mut call_appears_satisfied = if c_variadic {
provided_arg_count >= minimum_input_count
} else {
provided_arg_count == minimum_input_count
};
// Check the arguments.
// We do this in a pretty awful way: first we type-check any arguments
// that are not closures, then we type-check the closures. This is so
// that we have more information about the types of arguments when we
// type-check the functions. This isn't really the right way to do this.
for check_closures in [false, true] {
// More awful hacks: before we check argument types, try to do
// an "opportunistic" trait resolution of any trait bounds on
// the call. This helps coercions.
if check_closures {
self.select_obligations_where_possible(|_| {})
}
// Check each argument, to satisfy the input it was provided for
// Visually, we're traveling down the diagonal of the compatibility matrix
for (idx, arg) in provided_args.iter().enumerate() {
// Warn only for the first loop (the "no closures" one).
// Closure arguments themselves can't be diverging, but
// a previous argument can, e.g., `foo(panic!(), || {})`.
if !check_closures {
self.warn_if_unreachable(arg.hir_id, arg.span, "expression");
}
// For C-variadic functions, we don't have a declared type for all of
// the arguments hence we only do our usual type checking with
// the arguments who's types we do know. However, we *can* check
// for unreachable expressions (see above).
// FIXME: unreachable warning current isn't emitted
if idx >= minimum_input_count {
continue;
}
// For this check, we do *not* want to treat async coroutine closures (async blocks)
// as proper closures. Doing so would regress type inference when feeding
// the return value of an argument-position async block to an argument-position
// closure wrapped in a block.
// See <https://github.com/rust-lang/rust/issues/112225>.
let is_closure = if let ExprKind::Closure(closure) = arg.kind {
!tcx.coroutine_is_async(closure.def_id.to_def_id())
} else {
false
};
if is_closure != check_closures {
continue;
}
let compatible = demand_compatible(idx);
let is_compatible = matches!(compatible, Compatibility::Compatible);
compatibility_diagonal[idx] = compatible;
if !is_compatible {
call_appears_satisfied = false;
}
}
}
if c_variadic && provided_arg_count < minimum_input_count {
err_code = E0060;
}
for arg in provided_args.iter().skip(minimum_input_count) {
// Make sure we've checked this expr at least once.
let arg_ty = self.check_expr(arg);
// If the function is c-style variadic, we skipped a bunch of arguments
// so we need to check those, and write out the types
// Ideally this would be folded into the above, for uniform style
// but c-variadic is already a corner case
if c_variadic {
fn variadic_error<'tcx>(
sess: &'tcx Session,
span: Span,
ty: Ty<'tcx>,
cast_ty: &str,
) {
use rustc_hir_analysis::structured_errors::MissingCastForVariadicArg;
MissingCastForVariadicArg { sess, span, ty, cast_ty }.diagnostic().emit();
}
// There are a few types which get autopromoted when passed via varargs
// in C but we just error out instead and require explicit casts.
let arg_ty = self.structurally_resolve_type(arg.span, arg_ty);
match arg_ty.kind() {
ty::Float(ty::FloatTy::F32) => {
variadic_error(tcx.sess, arg.span, arg_ty, "c_double");
}
ty::Int(ty::IntTy::I8 | ty::IntTy::I16) | ty::Bool => {
variadic_error(tcx.sess, arg.span, arg_ty, "c_int");
}
ty::Uint(ty::UintTy::U8 | ty::UintTy::U16) => {
variadic_error(tcx.sess, arg.span, arg_ty, "c_uint");
}
ty::FnDef(..) => {
let ptr_ty = Ty::new_fn_ptr(self.tcx, arg_ty.fn_sig(self.tcx));
let ptr_ty = self.resolve_vars_if_possible(ptr_ty);
variadic_error(tcx.sess, arg.span, arg_ty, &ptr_ty.to_string());
}
_ => {}
}
}
}
if !call_appears_satisfied {
let compatibility_diagonal = IndexVec::from_raw(compatibility_diagonal);
let provided_args = IndexVec::from_iter(provided_args.iter().take(if c_variadic {
minimum_input_count
} else {
provided_arg_count
}));
debug_assert_eq!(
formal_input_tys.len(),
expected_input_tys.len(),
"expected formal_input_tys to be the same size as expected_input_tys"
);
let formal_and_expected_inputs = IndexVec::from_iter(
formal_input_tys
.iter()
.copied()
.zip_eq(expected_input_tys.iter().copied())
.map(|vars| self.resolve_vars_if_possible(vars)),
);
self.set_tainted_by_errors(self.report_arg_errors(
compatibility_diagonal,
formal_and_expected_inputs,
provided_args,
c_variadic,
err_code,
fn_def_id,
call_span,
call_expr,
));
}
}
fn report_arg_errors(
&self,
compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>,
formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>,
provided_args: IndexVec<ProvidedIdx, &'tcx hir::Expr<'tcx>>,
c_variadic: bool,
err_code: ErrCode,
fn_def_id: Option<DefId>,
call_span: Span,
call_expr: &'tcx hir::Expr<'tcx>,
) -> ErrorGuaranteed {
// Next, let's construct the error
let (error_span, call_ident, full_call_span, call_name, is_method) = match &call_expr.kind {
hir::ExprKind::Call(
hir::Expr { hir_id, span, kind: hir::ExprKind::Path(qpath), .. },
_,
) => {
if let Res::Def(DefKind::Ctor(of, _), _) =
self.typeck_results.borrow().qpath_res(qpath, *hir_id)
{
let name = match of {
CtorOf::Struct => "struct",
CtorOf::Variant => "enum variant",
};
(call_span, None, *span, name, false)
} else {
(call_span, None, *span, "function", false)
}
}
hir::ExprKind::Call(hir::Expr { span, .. }, _) => {
(call_span, None, *span, "function", false)
}
hir::ExprKind::MethodCall(path_segment, _, _, span) => {
let ident_span = path_segment.ident.span;
let ident_span = if let Some(args) = path_segment.args {
ident_span.with_hi(args.span_ext.hi())
} else {
ident_span
};
(*span, Some(path_segment.ident), ident_span, "method", true)
}
k => span_bug!(call_span, "checking argument types on a non-call: `{:?}`", k),
};
let args_span = error_span.trim_start(full_call_span).unwrap_or(error_span);
// Don't print if it has error types or is just plain `_`
fn has_error_or_infer<'tcx>(tys: impl IntoIterator<Item = Ty<'tcx>>) -> bool {
tys.into_iter().any(|ty| ty.references_error() || ty.is_ty_var())
}
let tcx = self.tcx;
// Get the argument span in the context of the call span so that
// suggestions and labels are (more) correct when an arg is a
// macro invocation.
let normalize_span = |span: Span| -> Span {
let normalized_span = span.find_ancestor_inside_same_ctxt(error_span).unwrap_or(span);
// Sometimes macros mess up the spans, so do not normalize the
// arg span to equal the error span, because that's less useful
// than pointing out the arg expr in the wrong context.
if normalized_span.source_equal(error_span) { span } else { normalized_span }
};
// Precompute the provided types and spans, since that's all we typically need for below
let provided_arg_tys: IndexVec<ProvidedIdx, (Ty<'tcx>, Span)> = provided_args
.iter()
.map(|expr| {
let ty = self
.typeck_results
.borrow()
.expr_ty_adjusted_opt(*expr)
.unwrap_or_else(|| Ty::new_misc_error(tcx));
(self.resolve_vars_if_possible(ty), normalize_span(expr.span))
})
.collect();
let callee_expr = match &call_expr.peel_blocks().kind {
hir::ExprKind::Call(callee, _) => Some(*callee),
hir::ExprKind::MethodCall(_, receiver, ..) => {
if let Some((DefKind::AssocFn, def_id)) =
self.typeck_results.borrow().type_dependent_def(call_expr.hir_id)
&& let Some(assoc) = tcx.opt_associated_item(def_id)
&& assoc.fn_has_self_parameter
{
Some(*receiver)
} else {
None
}
}
_ => None,
};
let callee_ty = callee_expr
.and_then(|callee_expr| self.typeck_results.borrow().expr_ty_adjusted_opt(callee_expr));
// Obtain another method on `Self` that have similar name.
let similar_assoc = |call_name: Ident| -> Option<(ty::AssocItem, ty::FnSig<'_>)> {
if let Some(callee_ty) = callee_ty
&& let Ok(Some(assoc)) = self.probe_op(
call_name.span,
MethodCall,
Some(call_name),
None,
IsSuggestion(true),
callee_ty.peel_refs(),
callee_expr.unwrap().hir_id,
TraitsInScope,
|mut ctxt| ctxt.probe_for_similar_candidate(),
)
&& let ty::AssocKind::Fn = assoc.kind
&& assoc.fn_has_self_parameter
{
let args = self.infcx.fresh_args_for_item(call_name.span, assoc.def_id);
let fn_sig = tcx.fn_sig(assoc.def_id).instantiate(tcx, args);
self.instantiate_binder_with_fresh_vars(call_name.span, FnCall, fn_sig);
}
None
};
let suggest_confusable = |err: &mut Diag<'_>| {
let Some(call_name) = call_ident else {
return;
};
let Some(callee_ty) = callee_ty else {
return;
};
let input_types: Vec<Ty<'_>> = provided_arg_tys.iter().map(|(ty, _)| *ty).collect();
// Check for other methods in the following order
// - methods marked as `rustc_confusables` with the provided arguments
// - methods with the same argument type/count and short levenshtein distance
// - methods marked as `rustc_confusables` (done)
// - methods with short levenshtein distance
// Look for commonly confusable method names considering arguments.
if let Some(_name) = self.confusable_method_name(
err,
callee_ty.peel_refs(),
call_name,
Some(input_types.clone()),
) {
return;
}
// Look for method names with short levenshtein distance, considering arguments.
if let Some((assoc, fn_sig)) = similar_assoc(call_name)
&& fn_sig.inputs()[1..]
.iter()
.zip(input_types.iter())
.all(|(expected, found)| self.can_coerce(*expected, *found))
&& fn_sig.inputs()[1..].len() == input_types.len()
{
err.span_suggestion_verbose(
call_name.span,
format!("you might have meant to use `{}`", assoc.name),
assoc.name,
Applicability::MaybeIncorrect,
);
return;
}
// Look for commonly confusable method names disregarding arguments.
if let Some(_name) =
self.confusable_method_name(err, callee_ty.peel_refs(), call_name, None)
{
return;
}
// Look for similarly named methods with levenshtein distance with the right
// number of arguments.
if let Some((assoc, fn_sig)) = similar_assoc(call_name)
&& fn_sig.inputs()[1..].len() == input_types.len()
{
err.span_note(
tcx.def_span(assoc.def_id),
format!(
"there's is a method with similar name `{}`, but the arguments don't match",
assoc.name,
),
);
return;
}
// Fallthrough: look for similarly named methods with levenshtein distance.
if let Some((assoc, _)) = similar_assoc(call_name) {
err.span_note(
tcx.def_span(assoc.def_id),
format!(
"there's is a method with similar name `{}`, but their argument count \
doesn't match",
assoc.name,
),
);
return;
}
};
// A "softer" version of the `demand_compatible`, which checks types without persisting them,
// and treats error types differently
// This will allow us to "probe" for other argument orders that would likely have been correct
let check_compatible = |provided_idx: ProvidedIdx, expected_idx: ExpectedIdx| {
if provided_idx.as_usize() == expected_idx.as_usize() {
return compatibility_diagonal[provided_idx].clone();
}
let (formal_input_ty, expected_input_ty) = formal_and_expected_inputs[expected_idx];
// If either is an error type, we defy the usual convention and consider them to *not* be
// coercible. This prevents our error message heuristic from trying to pass errors into
// every argument.
if (formal_input_ty, expected_input_ty).references_error() {
return Compatibility::Incompatible(None);
}
let (arg_ty, arg_span) = provided_arg_tys[provided_idx];
let expectation = Expectation::rvalue_hint(self, expected_input_ty);
let coerced_ty = expectation.only_has_type(self).unwrap_or(formal_input_ty);
let can_coerce = self.can_coerce(arg_ty, coerced_ty);
if !can_coerce {
return Compatibility::Incompatible(Some(ty::error::TypeError::Sorts(
ty::error::ExpectedFound::new(true, coerced_ty, arg_ty),
)));
}
// Using probe here, since we don't want this subtyping to affect inference.
let subtyping_error = self.probe(|_| {
self.at(&self.misc(arg_span), self.param_env)
.sup(DefineOpaqueTypes::No, formal_input_ty, coerced_ty)
.err()
});
// Same as above: if either the coerce type or the checked type is an error type,
// consider them *not* compatible.
let references_error = (coerced_ty, arg_ty).references_error();
match (references_error, subtyping_error) {
(false, None) => Compatibility::Compatible,
(_, subtyping_error) => Compatibility::Incompatible(subtyping_error),
}
};
let mk_trace = |span, (formal_ty, expected_ty), provided_ty| {
let mismatched_ty = if expected_ty == provided_ty {
// If expected == provided, then we must have failed to sup
// the formal type. Avoid printing out "expected Ty, found Ty"
// in that case.
formal_ty
} else {
expected_ty
};
TypeTrace::types(&self.misc(span), true, mismatched_ty, provided_ty)
};
// The algorithm here is inspired by levenshtein distance and longest common subsequence.
// We'll try to detect 4 different types of mistakes:
// - An extra parameter has been provided that doesn't satisfy *any* of the other inputs
// - An input is missing, which isn't satisfied by *any* of the other arguments
// - Some number of arguments have been provided in the wrong order
// - A type is straight up invalid
// First, let's find the errors
let (mut errors, matched_inputs) =
ArgMatrix::new(provided_args.len(), formal_and_expected_inputs.len(), check_compatible)
.find_errors();
// First, check if we just need to wrap some arguments in a tuple.
if let Some((mismatch_idx, terr)) =
compatibility_diagonal.iter().enumerate().find_map(|(i, c)| {
if let Compatibility::Incompatible(Some(terr)) = c {
Some((i, *terr))
} else {
None
}
})
{
// Is the first bad expected argument a tuple?
// Do we have as many extra provided arguments as the tuple's length?
// If so, we might have just forgotten to wrap some args in a tuple.
if let Some(ty::Tuple(tys)) =
formal_and_expected_inputs.get(mismatch_idx.into()).map(|tys| tys.1.kind())
// If the tuple is unit, we're not actually wrapping any arguments.
&& !tys.is_empty()
&& provided_arg_tys.len() == formal_and_expected_inputs.len() - 1 + tys.len()
{
// Wrap up the N provided arguments starting at this position in a tuple.
let provided_as_tuple = Ty::new_tup_from_iter(
tcx,
provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx).take(tys.len()),
);
let mut satisfied = true;
// Check if the newly wrapped tuple + rest of the arguments are compatible.
for ((_, expected_ty), provided_ty) in std::iter::zip(
formal_and_expected_inputs.iter().skip(mismatch_idx),
[provided_as_tuple].into_iter().chain(
provided_arg_tys.iter().map(|(ty, _)| *ty).skip(mismatch_idx + tys.len()),
),
) {
if !self.can_coerce(provided_ty, *expected_ty) {
satisfied = false;
break;
}
}
// If they're compatible, suggest wrapping in an arg, and we're done!
// Take some care with spans, so we don't suggest wrapping a macro's
// innards in parenthesis, for example.
if satisfied
&& let Some((_, lo)) =
provided_arg_tys.get(ProvidedIdx::from_usize(mismatch_idx))
&& let Some((_, hi)) =
provided_arg_tys.get(ProvidedIdx::from_usize(mismatch_idx + tys.len() - 1))
{
let mut err;
if tys.len() == 1 {
// A tuple wrap suggestion actually occurs within,
// so don't do anything special here.
err = self.err_ctxt().report_and_explain_type_error(
mk_trace(
*lo,
formal_and_expected_inputs[mismatch_idx.into()],
provided_arg_tys[mismatch_idx.into()].0,
),
terr,
);
err.span_label(
full_call_span,
format!("arguments to this {call_name} are incorrect"),
);
} else {
err = tcx.dcx().struct_span_err(
full_call_span,
format!(
"{call_name} takes {}{} but {} {} supplied",
if c_variadic { "at least " } else { "" },
potentially_plural_count(
formal_and_expected_inputs.len(),
"argument"
),
potentially_plural_count(provided_args.len(), "argument"),
pluralize!("was", provided_args.len())
),
);
err.code(err_code.to_owned());
err.multipart_suggestion_verbose(
"wrap these arguments in parentheses to construct a tuple",
vec![
(lo.shrink_to_lo(), "(".to_string()),
(hi.shrink_to_hi(), ")".to_string()),
],
Applicability::MachineApplicable,
);
};
self.label_fn_like(
&mut err,
fn_def_id,
callee_ty,
call_expr,
None,
Some(mismatch_idx),
is_method,
);
suggest_confusable(&mut err);
return err.emit();
}
}
}
// Okay, so here's where it gets complicated in regards to what errors
// we emit and how.
// There are 3 different "types" of errors we might encounter.
// 1) Missing/extra/swapped arguments
// 2) Valid but incorrect arguments
// 3) Invalid arguments
// - Currently I think this only comes up with `CyclicTy`
//
// We first need to go through, remove those from (3) and emit those
// as their own error, particularly since they're error code and
// message is special. From what I can tell, we *must* emit these
// here (vs somewhere prior to this function) since the arguments
// become invalid *because* of how they get used in the function.
// It is what it is.
if errors.is_empty() {
if cfg!(debug_assertions) {
span_bug!(error_span, "expected errors from argument matrix");
} else {
let mut err =
tcx.dcx().create_err(errors::ArgMismatchIndeterminate { span: error_span });
suggest_confusable(&mut err);
return err.emit();
}
}
let mut reported = None;
errors.retain(|error| {
let Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(e))) =
error
else {
return true;
};
let (provided_ty, provided_span) = provided_arg_tys[*provided_idx];
let trace =
mk_trace(provided_span, formal_and_expected_inputs[*expected_idx], provided_ty);
if !matches!(trace.cause.as_failure_code(*e), FailureCode::Error0308) {
let mut err = self.err_ctxt().report_and_explain_type_error(trace, *e);
suggest_confusable(&mut err);
reported = Some(err.emit());
return false;
}
true
});
// We're done if we found errors, but we already emitted them.
if let Some(reported) = reported
&& errors.is_empty()
{
return reported;
}
assert!(!errors.is_empty());
// Okay, now that we've emitted the special errors separately, we
// are only left missing/extra/swapped and mismatched arguments, both
// can be collated pretty easily if needed.
// Next special case: if there is only one "Incompatible" error, just emit that
if let [
Error::Invalid(provided_idx, expected_idx, Compatibility::Incompatible(Some(err))),
] = &errors[..]
{
let (formal_ty, expected_ty) = formal_and_expected_inputs[*expected_idx];
let (provided_ty, provided_arg_span) = provided_arg_tys[*provided_idx];
let trace = mk_trace(provided_arg_span, (formal_ty, expected_ty), provided_ty);
let mut err = self.err_ctxt().report_and_explain_type_error(trace, *err);
self.emit_coerce_suggestions(
&mut err,
provided_args[*provided_idx],
provided_ty,
Expectation::rvalue_hint(self, expected_ty)
.only_has_type(self)
.unwrap_or(formal_ty),
None,
None,
);
err.span_label(full_call_span, format!("arguments to this {call_name} are incorrect"));
if let hir::ExprKind::MethodCall(_, rcvr, _, _) = call_expr.kind
&& provided_idx.as_usize() == expected_idx.as_usize()
{
self.note_source_of_type_mismatch_constraint(
&mut err,
rcvr,
crate::demand::TypeMismatchSource::Arg {
call_expr,
incompatible_arg: provided_idx.as_usize(),
},
);
}
self.suggest_ptr_null_mut(
expected_ty,
provided_ty,
provided_args[*provided_idx],
&mut err,
);
// Call out where the function is defined
self.label_fn_like(
&mut err,
fn_def_id,
callee_ty,
call_expr,
Some(expected_ty),
Some(expected_idx.as_usize()),
is_method,
);
suggest_confusable(&mut err);
return err.emit();
}
let mut err = if formal_and_expected_inputs.len() == provided_args.len() {
struct_span_code_err!(
tcx.dcx(),
full_call_span,
E0308,
"arguments to this {} are incorrect",
call_name,
)
} else {
tcx.dcx()
.struct_span_err(
full_call_span,
format!(
"this {} takes {}{} but {} {} supplied",
call_name,
if c_variadic { "at least " } else { "" },
potentially_plural_count(formal_and_expected_inputs.len(), "argument"),
potentially_plural_count(provided_args.len(), "argument"),
pluralize!("was", provided_args.len())
),
)
.with_code(err_code.to_owned())
};
suggest_confusable(&mut err);
// As we encounter issues, keep track of what we want to provide for the suggestion
let mut labels = vec![];
// If there is a single error, we give a specific suggestion; otherwise, we change to
// "did you mean" with the suggested function call
enum SuggestionText {
None,
Provide(bool),
Remove(bool),
Swap,
Reorder,
DidYouMean,
}
let mut suggestion_text = SuggestionText::None;
let ty_to_snippet = |ty: Ty<'tcx>, expected_idx: ExpectedIdx| {
if ty.is_unit() {
"()".to_string()
} else if ty.is_suggestable(tcx, false) {
format!("/* {ty} */")
} else if let Some(fn_def_id) = fn_def_id
&& self.tcx.def_kind(fn_def_id).is_fn_like()
&& let self_implicit =
matches!(call_expr.kind, hir::ExprKind::MethodCall(..)) as usize
&& let Some(arg) =
self.tcx.fn_arg_names(fn_def_id).get(expected_idx.as_usize() + self_implicit)
&& arg.name != kw::SelfLower
{
format!("/* {} */", arg.name)
} else {
"/* value */".to_string()
}
};
let mut errors = errors.into_iter().peekable();
let mut only_extras_so_far = errors
.peek()
.is_some_and(|first| matches!(first, Error::Extra(arg_idx) if arg_idx.index() == 0));
let mut suggestions = vec![];
while let Some(error) = errors.next() {
only_extras_so_far &= matches!(error, Error::Extra(_));
match error {
Error::Invalid(provided_idx, expected_idx, compatibility) => {
let (formal_ty, expected_ty) = formal_and_expected_inputs[expected_idx];
let (provided_ty, provided_span) = provided_arg_tys[provided_idx];
if let Compatibility::Incompatible(error) = compatibility {
let trace = mk_trace(provided_span, (formal_ty, expected_ty), provided_ty);
if let Some(e) = error {
self.err_ctxt().note_type_err(
&mut err,
&trace.cause,
None,
Some(trace.values),
e,
false,
true,
);
}