-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
CSSimplify.cpp
16335 lines (13933 loc) · 620 KB
/
CSSimplify.cpp
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
//===--- CSSimplify.cpp - Constraint Simplification -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements simplifications of constraints within the constraint
// system.
//
//===----------------------------------------------------------------------===//
#include "CSDiagnostics.h"
#include "OpenedExistentials.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckEffects.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/PackExpansionMatcher.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Requirement.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Sema/CSFix.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace constraints;
MatchCallArgumentListener::~MatchCallArgumentListener() { }
bool MatchCallArgumentListener::extraArgument(unsigned argIdx) { return true; }
std::optional<unsigned>
MatchCallArgumentListener::missingArgument(unsigned paramIdx,
unsigned argInsertIdx) {
return std::nullopt;
}
bool MatchCallArgumentListener::missingLabel(unsigned paramIdx) { return true; }
bool MatchCallArgumentListener::extraneousLabel(unsigned paramIdx) {
return true;
}
bool MatchCallArgumentListener::incorrectLabel(unsigned paramIdx) {
return true;
}
bool MatchCallArgumentListener::outOfOrderArgument(
unsigned argIdx, unsigned prevArgIdx, ArrayRef<ParamBinding> bindings) {
return true;
}
bool MatchCallArgumentListener::relabelArguments(ArrayRef<Identifier> newNames){
return true;
}
bool MatchCallArgumentListener::shouldClaimArgDuringRecovery(unsigned argIdx) {
return true;
}
bool MatchCallArgumentListener::canClaimArgIgnoringNameMismatch(
const AnyFunctionType::Param &arg) {
return false;
}
/// Produce a score (smaller is better) comparing a parameter name and
/// potentially-typo'd argument name.
///
/// \param paramName The name of the parameter.
/// \param argName The name of the argument.
/// \param maxScore The maximum score permitted by this comparison, or
/// 0 if there is no limit.
///
/// \returns the score, if it is good enough to even consider this a match.
/// Otherwise, an empty optional.
///
static std::optional<unsigned> scoreParamAndArgNameTypo(StringRef paramName,
StringRef argName,
unsigned maxScore) {
using namespace camel_case;
// Compute the edit distance.
unsigned dist = argName.edit_distance(paramName, /*AllowReplacements=*/true,
/*MaxEditDistance=*/maxScore);
// If the edit distance would be too long, we're done.
if (maxScore != 0 && dist > maxScore)
return std::nullopt;
// The distance can be zero due to the "with" transformation above.
if (dist == 0)
return 1;
// If this is just a single character label on both sides,
// simply return distance.
if (paramName.size() == 1 && argName.size() == 1)
return dist;
// Only allow about one typo for every two properly-typed characters, which
// prevents completely-wacky suggestions in many cases.
if (dist > (argName.size() + 1) / 3)
return std::nullopt;
return dist;
}
bool constraints::isPackExpansionType(Type type) {
if (type->is<PackExpansionType>())
return true;
if (auto *typeVar = type->getAs<TypeVariableType>())
return typeVar->getImpl().isPackExpansion();
return false;
}
bool constraints::isSingleUnlabeledPackExpansionTuple(Type type) {
auto *tuple = type->getRValueType()->getAs<TupleType>();
return tuple && (tuple->getNumElements() == 1) &&
isPackExpansionType(tuple->getElementType(0)) &&
!tuple->getElement(0).hasName();
}
Type constraints::getPatternTypeOfSingleUnlabeledPackExpansionTuple(Type type) {
if (isSingleUnlabeledPackExpansionTuple(type)) {
auto tuple = type->getRValueType()->castTo<TupleType>();
const auto &tupleElement = tuple->getElementType(0);
if (auto *expansion = tupleElement->getAs<PackExpansionType>()) {
return expansion->getPatternType();
}
if (auto *typeVar = tupleElement->getAs<TypeVariableType>()) {
auto *locator = typeVar->getImpl().getLocator();
if (auto expansionElement =
locator->getLastElementAs<LocatorPathElt::PackExpansionType>()) {
return expansionElement->getOpenedType()->getPatternType();
}
}
}
return {};
}
bool constraints::containsPackExpansionType(ArrayRef<AnyFunctionType::Param> params) {
return llvm::any_of(params, [&](const auto ¶m) {
return isPackExpansionType(param.getPlainType());
});
}
bool constraints::containsPackExpansionType(TupleType *tuple) {
return llvm::any_of(tuple->getElements(), [&](const auto &elt) {
return isPackExpansionType(elt.getType());
});
}
bool constraints::doesMemberRefApplyCurriedSelf(Type baseTy,
const ValueDecl *decl) {
assert(decl->getDeclContext()->isTypeContext() &&
"Expected a member reference");
// For a reference to an instance method on a metatype, we want to keep the
// curried self.
if (decl->isInstanceMember()) {
assert(baseTy);
if (isa<AbstractFunctionDecl>(decl) &&
baseTy->getRValueType()->is<AnyMetatypeType>())
return false;
}
// Otherwise the reference applies self.
return true;
}
static bool areConservativelyCompatibleArgumentLabels(
ConstraintSystem &cs, OverloadChoice choice,
SmallVectorImpl<FunctionType::Param> &args,
MatchCallArgumentListener &listener,
std::optional<unsigned> unlabeledTrailingClosureArgIndex) {
ValueDecl *decl = nullptr;
switch (choice.getKind()) {
case OverloadChoiceKind::Decl:
case OverloadChoiceKind::DeclViaBridge:
case OverloadChoiceKind::DeclViaDynamic:
case OverloadChoiceKind::DeclViaUnwrappedOptional:
decl = choice.getDecl();
break;
// KeyPath application is not filtered in `performMemberLookup`.
case OverloadChoiceKind::KeyPathApplication:
case OverloadChoiceKind::DynamicMemberLookup:
case OverloadChoiceKind::KeyPathDynamicMemberLookup:
case OverloadChoiceKind::TupleIndex:
case OverloadChoiceKind::MaterializePack:
case OverloadChoiceKind::ExtractFunctionIsolation:
return true;
}
// If this is a member lookup, the call arguments (if we have any) will
// generally be applied to the second level of parameters, with the member
// lookup applying the curried self at the first level. But there are cases
// where we can get an unapplied declaration reference back.
auto hasAppliedSelf =
decl->hasCurriedSelf() &&
doesMemberRefApplyCurriedSelf(choice.getBaseType(), decl);
AnyFunctionType *fnType = nullptr;
if (decl->hasParameterList()) {
fnType = decl->getInterfaceType()->castTo<AnyFunctionType>();
if (hasAppliedSelf) {
fnType = fnType->getResult()->getAs<AnyFunctionType>();
assert(fnType && "Parameter list curry level does not match type");
}
} else if (auto *VD = dyn_cast<VarDecl>(decl)) {
// For variables, we can reject any type that we know cannot be callable.
auto varTy = VD->getValueInterfaceType()->lookThroughAllOptionalTypes();
if (!varTy->mayBeCallable(cs.DC))
return false;
fnType = varTy->getAs<AnyFunctionType>();
} else if (auto *MD = dyn_cast<MacroDecl>(decl)) {
fnType = MD->getInterfaceType()->getAs<AnyFunctionType>();
}
// Given we want to be conservative with this checking, if there's any case
// we can't match arguments for (e.g callable nominals, type parameters),
// default to returning true.
if (!fnType)
return true;
auto params = fnType->getParams();
ParameterListInfo paramInfo(params, decl, hasAppliedSelf);
return matchCallArguments(args, params, paramInfo,
unlabeledTrailingClosureArgIndex,
/*allow fixes*/ false, listener, std::nullopt)
.has_value();
}
Expr *constraints::getArgumentLabelTargetExpr(Expr *fn) {
// Dig out the function, looking through, parentheses, ?, and !.
do {
fn = fn->getSemanticsProvidingExpr();
if (auto force = dyn_cast<ForceValueExpr>(fn)) {
fn = force->getSubExpr();
continue;
}
if (auto bind = dyn_cast<BindOptionalExpr>(fn)) {
fn = bind->getSubExpr();
continue;
}
return fn;
} while (true);
}
/// Determine the default type-matching options to use when decomposing a
/// constraint into smaller constraints.
static ConstraintSystem::TypeMatchOptions getDefaultDecompositionOptions(
ConstraintSystem::TypeMatchOptions flags) {
return flags | ConstraintSystem::TMF_GenerateConstraints;
}
/// Whether the given parameter requires an argument.
bool swift::parameterRequiresArgument(
ArrayRef<AnyFunctionType::Param> params,
const ParameterListInfo ¶mInfo,
unsigned paramIdx) {
return !paramInfo.hasDefaultArgument(paramIdx)
&& !params[paramIdx].isVariadic();
}
/// Determine whether the given parameter can accept a trailing closure for the
/// "backward" logic.
static bool backwardScanAcceptsTrailingClosure(
const AnyFunctionType::Param ¶m) {
Type paramTy = param.getPlainType();
if (!paramTy)
return true;
paramTy = paramTy->lookThroughAllOptionalTypes();
return paramTy->isTypeParameter() ||
paramTy->is<ArchetypeType>() ||
paramTy->is<AnyFunctionType>() ||
paramTy->isTypeVariableOrMember() ||
paramTy->is<UnresolvedType>() ||
paramTy->isAny();
}
/// Determine whether any parameter from the given index up until the end
/// requires an argument to be provided.
///
/// \param params The parameters themselves.
/// \param paramInfo Declaration-provided information about the parameters.
/// \param firstParamIdx The first parameter to examine to determine whether any
/// parameter in the range \c [paramIdx, params.size()) requires an argument.
/// \param beforeLabel If non-empty, stop examining parameters when we reach
/// a parameter with this label.
static bool anyParameterRequiresArgument(
ArrayRef<AnyFunctionType::Param> params, const ParameterListInfo ¶mInfo,
unsigned firstParamIdx, std::optional<Identifier> beforeLabel) {
for (unsigned paramIdx : range(firstParamIdx, params.size())) {
// If have been asked to stop when we reach a parameter with a particular
// label, and we see a parameter with that label, we're done: no parameter
// requires an argument.
if (beforeLabel && *beforeLabel == params[paramIdx].getLabel())
break;
// If this parameter requires an argument, tell the caller.
if (parameterRequiresArgument(params, paramInfo, paramIdx))
return true;
}
// No parameters required arguments.
return false;
}
static bool isCodeCompletionTypeVar(Type type) {
if (auto *TVT = type->getAs<TypeVariableType>()) {
if (TVT->getImpl().isCodeCompletionToken()) {
return true;
}
}
return false;
}
static bool matchCallArgumentsImpl(
SmallVectorImpl<AnyFunctionType::Param> &args,
ArrayRef<AnyFunctionType::Param> params, const ParameterListInfo ¶mInfo,
std::optional<unsigned> unlabeledTrailingClosureArgIndex, bool allowFixes,
TrailingClosureMatching trailingClosureMatching,
MatchCallArgumentListener &listener,
SmallVectorImpl<ParamBinding> ¶meterBindings) {
assert(params.size() == paramInfo.size() && "Default map does not match");
assert(!unlabeledTrailingClosureArgIndex ||
*unlabeledTrailingClosureArgIndex < args.size());
// Keep track of the parameter we're matching and what argument indices
// got bound to each parameter.
unsigned numParams = params.size();
parameterBindings.clear();
parameterBindings.resize(numParams);
// Keep track of which arguments we have claimed from the argument tuple.
unsigned numArgs = args.size();
SmallVector<bool, 4> claimedArgs(numArgs, false);
SmallVector<Identifier, 4> actualArgNames;
unsigned numClaimedArgs = 0;
// Indicates whether any of the arguments are potentially out-of-order,
// requiring further checking at the end.
bool potentiallyOutOfOrder = false;
// Local function that claims the argument at \c argIdx, returning the
// index of the claimed argument. This is primarily a helper for
// \c claimNextNamed.
auto claim = [&](Identifier expectedName, unsigned argIdx,
bool ignoreNameClash = false) -> unsigned {
// Make sure we can claim this argument.
assert(argIdx != numArgs && "Must have a valid index to claim");
assert(!claimedArgs[argIdx] && "Argument already claimed");
if (!actualArgNames.empty()) {
// We're recording argument names; record this one.
actualArgNames[argIdx] = expectedName;
} else if (!ignoreNameClash && !args[argIdx].matchParameterLabel(expectedName)) {
// We have an argument name mismatch. Start recording argument names.
actualArgNames.resize(numArgs);
// Figure out previous argument names from the parameter bindings.
for (auto i : indices(params)) {
const auto ¶m = params[i];
bool firstArg = true;
for (auto argIdx : parameterBindings[i]) {
actualArgNames[argIdx] = firstArg ? param.getLabel() : Identifier();
firstArg = false;
}
}
// Record this argument name.
actualArgNames[argIdx] = expectedName;
}
claimedArgs[argIdx] = true;
++numClaimedArgs;
return argIdx;
};
// Local function that skips over any claimed arguments.
auto skipClaimedArgs = [&](unsigned &nextArgIdx) {
while (nextArgIdx != numArgs && claimedArgs[nextArgIdx])
++nextArgIdx;
return nextArgIdx;
};
// Local function that retrieves the next unclaimed argument with the given
// name (which may be empty). This routine claims the argument.
auto claimNextNamed =
[&](unsigned &nextArgIdx, Identifier paramLabel, bool ignoreNameMismatch,
bool forVariadic = false) -> std::optional<unsigned> {
// Skip over any claimed arguments.
skipClaimedArgs(nextArgIdx);
// If we've claimed all of the arguments, there's nothing more to do.
if (numClaimedArgs == numArgs)
return std::nullopt;
// Go hunting for an unclaimed argument whose name does match.
std::optional<unsigned> claimedWithSameName;
unsigned firstArgIdx = nextArgIdx;
for (unsigned i = nextArgIdx; i != numArgs; ++i) {
auto argLabel = args[i].getLabel();
bool claimIgnoringNameMismatch = false;
if (!args[i].matchParameterLabel(paramLabel)) {
// If this is an attempt to claim additional unlabeled arguments
// for variadic parameter, we have to stop at first labeled argument.
if (forVariadic)
return std::nullopt;
if ((i == firstArgIdx || ignoreNameMismatch) &&
listener.canClaimArgIgnoringNameMismatch(args[i])) {
// Avoid triggering relabelling fixes about the completion arg.
claimIgnoringNameMismatch = true;
} else {
// Otherwise we can continue trying to find argument which
// matches parameter with or without label.
continue;
}
}
// Skip claimed arguments.
if (claimedArgs[i]) {
assert(!forVariadic && "Cannot be for a variadic claim");
// Note that we have already claimed an argument with the same name.
if (!claimedWithSameName)
claimedWithSameName = i;
continue;
}
// We found a match. If the match wasn't the next one, we have
// potentially out of order arguments.
if (i != nextArgIdx) {
assert(!forVariadic && "Cannot be for a variadic claim");
// Avoid claiming un-labeled defaulted parameters
// by out-of-order un-labeled arguments or parts
// of variadic argument sequence, because that might
// be incorrect:
// ```swift
// func foo(_ a: Int, _ b: Int = 0, c: Int = 0, _ d: Int) {}
// foo(1, c: 2, 3) // -> `3` will be claimed as '_ b:'.
// ```
if (argLabel.empty() && !claimIgnoringNameMismatch)
continue;
potentiallyOutOfOrder = true;
}
// Claim it.
return claim(paramLabel, i, claimIgnoringNameMismatch);
}
// If we're not supposed to attempt any fixes, we're done.
if (!allowFixes)
return std::nullopt;
// Several things could have gone wrong here, and we'll check for each
// of them at some point:
// - The keyword argument might be redundant, in which case we can point
// out the issue.
// - The argument might be unnamed, in which case we try to fix the
// problem by adding the name.
// - The argument might have extraneous label, in which case we try to
// fix the problem by removing such label.
// - The keyword argument might be a typo for an actual argument name, in
// which case we should find the closest match to correct to.
// Missing or extraneous label.
if (nextArgIdx != numArgs && ignoreNameMismatch) {
auto argLabel = args[nextArgIdx].getLabel();
// Claim this argument if we are asked to ignore labeling failure,
// only if argument doesn't have a label when parameter expected
// it to, or vice versa.
if (paramLabel.empty() || argLabel.empty())
return claim(paramLabel, nextArgIdx);
}
// Redundant keyword arguments.
if (claimedWithSameName) {
// FIXME: We can provide better diagnostics here.
return std::nullopt;
}
// Typo correction is handled in a later pass.
return std::nullopt;
};
// Local function that attempts to bind the given parameter to arguments in
// the list.
bool haveUnfulfilledParams = false;
auto bindNextParameter = [&](unsigned paramIdx, unsigned &nextArgIdx,
bool ignoreNameMismatch) {
const auto ¶m = params[paramIdx];
Identifier paramLabel = param.getLabel();
// If we have the trailing closure argument and are performing a forward
// match, look for the matching parameter.
if (trailingClosureMatching == TrailingClosureMatching::Forward &&
unlabeledTrailingClosureArgIndex &&
skipClaimedArgs(nextArgIdx) == *unlabeledTrailingClosureArgIndex) {
// If the parameter we are looking at does not support the (unlabeled)
// trailing closure argument, this parameter is unfulfilled.
if (!paramInfo.acceptsUnlabeledTrailingClosureArgument(paramIdx) &&
!ignoreNameMismatch) {
haveUnfulfilledParams = true;
return;
}
// Let's consider current closure to be extraneous if:
//
// - current parameter has a default value and doesn't accept a trailing
// closure; and
// - no other free parameter after this one accepts a trailing closure via
// forward or backward scan. This check makes sure that it's safe to
// reject and push it to the next parameter without affecting backward
// scan logic.
//
// In other words - let's push the closure argument through defaulted
// parameters until it can be considered extraneous if no parameters
// could possibly match it.
if (!paramInfo.acceptsUnlabeledTrailingClosureArgument(paramIdx) &&
!parameterRequiresArgument(params, paramInfo, paramIdx)) {
if (llvm::none_of(
range(paramIdx + 1, params.size()), [&](unsigned idx) {
return parameterBindings[idx].empty() &&
(paramInfo.acceptsUnlabeledTrailingClosureArgument(
idx) ||
backwardScanAcceptsTrailingClosure(params[idx]));
})) {
haveUnfulfilledParams = true;
return;
}
// If one or more parameters can match the closure, let's check
// whether backward scan is applicable here.
}
// If this parameter does not require an argument, consider applying a
// backward-match rule that skips this parameter if doing so is the only
// way to successfully match arguments to parameters.
if (!parameterRequiresArgument(params, paramInfo, paramIdx) &&
anyParameterRequiresArgument(
params, paramInfo, paramIdx + 1,
nextArgIdx + 1 < numArgs
? std::optional<Identifier>(args[nextArgIdx + 1].getLabel())
: std::optional<Identifier>(std::nullopt))) {
haveUnfulfilledParams = true;
return;
}
// The argument is unlabeled, so mark the parameter as unlabeled as
// well.
paramLabel = Identifier();
}
// Handle variadic parameters.
if (param.isVariadic() || isPackExpansionType(param.getPlainType())) {
// Claim the next argument with the name of this parameter.
auto claimed =
claimNextNamed(nextArgIdx, paramLabel, ignoreNameMismatch);
// If there was no such argument, leave the parameter unfulfilled.
if (!claimed) {
haveUnfulfilledParams = true;
return;
}
// Record the first argument for the variadic.
parameterBindings[paramIdx].push_back(*claimed);
auto currentNextArgIdx = nextArgIdx;
{
nextArgIdx = *claimed;
// Claim any additional unnamed arguments.
while (true) {
// If the next argument is the unlabeled trailing closure and the
// variadic parameter does not accept the unlabeled trailing closure
// argument, we're done.
if (trailingClosureMatching == TrailingClosureMatching::Forward &&
unlabeledTrailingClosureArgIndex &&
skipClaimedArgs(nextArgIdx)
== *unlabeledTrailingClosureArgIndex &&
!paramInfo.acceptsUnlabeledTrailingClosureArgument(paramIdx))
break;
if ((claimed = claimNextNamed(nextArgIdx, Identifier(), false, true)))
parameterBindings[paramIdx].push_back(*claimed);
else
break;
}
}
nextArgIdx = currentNextArgIdx;
return;
}
// Try to claim an argument for this parameter.
if (auto claimed =
claimNextNamed(nextArgIdx, paramLabel, ignoreNameMismatch)) {
parameterBindings[paramIdx].push_back(*claimed);
return;
}
// There was no argument to claim. Leave the argument unfulfilled.
haveUnfulfilledParams = true;
};
// If we have an unlabeled trailing closure and are matching backward, match
// the trailing closure argument near the end.
if (unlabeledTrailingClosureArgIndex &&
trailingClosureMatching == TrailingClosureMatching::Backward) {
assert(!claimedArgs[*unlabeledTrailingClosureArgIndex]);
// One past the next parameter index to look at.
unsigned prevParamIdx = numParams;
// Scan backwards from the end to match the unlabeled trailing closure.
std::optional<unsigned> unlabeledParamIdx;
if (prevParamIdx > 0) {
unsigned paramIdx = prevParamIdx - 1;
bool lastAcceptsTrailingClosure =
backwardScanAcceptsTrailingClosure(params[paramIdx]);
// If the last parameter is defaulted, this might be
// an attempt to use a trailing closure with previous
// parameter that accepts a function type e.g.
//
// func foo(_: () -> Int, _ x: Int = 0) {}
// foo { 42 }
if (!lastAcceptsTrailingClosure && paramIdx > 0 &&
paramInfo.hasDefaultArgument(paramIdx)) {
auto paramType = params[paramIdx - 1].getPlainType();
// If the parameter before defaulted last accepts.
if (paramType->is<AnyFunctionType>()) {
lastAcceptsTrailingClosure = true;
paramIdx -= 1;
}
}
if (lastAcceptsTrailingClosure)
unlabeledParamIdx = paramIdx;
}
// Trailing closure argument couldn't be matched to anything. Fail fast.
if (!unlabeledParamIdx) {
return true;
}
// Claim the parameter/argument pair.
claim(
params[*unlabeledParamIdx].getLabel(),
*unlabeledTrailingClosureArgIndex,
/*ignoreNameClash=*/true);
parameterBindings[*unlabeledParamIdx].push_back(
*unlabeledTrailingClosureArgIndex);
}
{
unsigned nextArgIdx = 0;
// Mark through the parameters, binding them to their arguments.
for (auto paramIdx : indices(params)) {
if (parameterBindings[paramIdx].empty())
bindNextParameter(paramIdx, nextArgIdx, false);
}
}
// If we have any unclaimed arguments, complain about those.
if (numClaimedArgs != numArgs) {
// Find all of the named, unclaimed arguments.
llvm::SmallVector<unsigned, 4> unclaimedNamedArgs;
for (auto argIdx : indices(args)) {
if (claimedArgs[argIdx]) continue;
if (!listener.shouldClaimArgDuringRecovery(argIdx))
continue;
if (!args[argIdx].getLabel().empty())
unclaimedNamedArgs.push_back(argIdx);
}
if (!unclaimedNamedArgs.empty()) {
// Find all of the named, unfulfilled parameters.
llvm::SmallVector<unsigned, 4> unfulfilledNamedParams;
bool hasUnfulfilledUnnamedParams = false;
for (auto paramIdx : indices(params)) {
if (parameterBindings[paramIdx].empty()) {
if (params[paramIdx].getLabel().empty())
hasUnfulfilledUnnamedParams = true;
else
unfulfilledNamedParams.push_back(paramIdx);
}
}
if (!unfulfilledNamedParams.empty()) {
// Use typo correction to find the best matches.
// FIXME: There is undoubtedly a good dynamic-programming algorithm
// to find the best assignment here.
for (auto argIdx : unclaimedNamedArgs) {
auto argName = args[argIdx].getLabel();
// Find the closest matching unfulfilled named parameter.
unsigned bestScore = 0;
unsigned best = 0;
for (auto i : indices(unfulfilledNamedParams)) {
unsigned param = unfulfilledNamedParams[i];
auto paramName = params[param].getLabel();
if (auto score = scoreParamAndArgNameTypo(paramName.str(),
argName.str(),
bestScore)) {
if (*score < bestScore || bestScore == 0) {
bestScore = *score;
best = i;
}
}
}
// If we found a parameter to fulfill, do it.
if (bestScore > 0) {
// Bind this parameter to the argument.
auto paramIdx = unfulfilledNamedParams[best];
auto paramLabel = params[paramIdx].getLabel();
parameterBindings[paramIdx].push_back(claim(paramLabel, argIdx));
// Erase this parameter from the list of unfulfilled named
// parameters, so we don't try to fulfill it again.
unfulfilledNamedParams.erase(unfulfilledNamedParams.begin() + best);
if (unfulfilledNamedParams.empty())
break;
}
}
// Update haveUnfulfilledParams, because we may have fulfilled some
// parameters above.
haveUnfulfilledParams = hasUnfulfilledUnnamedParams ||
!unfulfilledNamedParams.empty();
}
}
// Find all of the unfulfilled parameters, and match them up
// semi-positionally.
if (numClaimedArgs != numArgs) {
// Restart at the first argument/parameter.
unsigned nextArgIdx = 0;
haveUnfulfilledParams = false;
for (auto paramIdx : indices(params)) {
// Skip fulfilled parameters.
if (!parameterBindings[paramIdx].empty())
continue;
bindNextParameter(paramIdx, nextArgIdx, true);
if (!listener.shouldClaimArgDuringRecovery(nextArgIdx))
continue;
}
}
// If there are as many arguments as parameters but we still
// haven't claimed all of the arguments, it could mean that
// labels don't line up, if so let's try to claim arguments
// with incorrect labels, and let OoO/re-labeling logic diagnose that.
if (numArgs == numParams && numClaimedArgs != numArgs) {
for (auto i : indices(args)) {
if (claimedArgs[i] || !parameterBindings[i].empty())
continue;
// If parameter has a default value, we don't really
// know if label doesn't match because it's incorrect
// or argument belongs to some other parameter, so
// we just leave this parameter unfulfilled.
if (paramInfo.hasDefaultArgument(i))
continue;
if (!listener.shouldClaimArgDuringRecovery(i))
continue;
// Looks like there was no parameter claimed at the same
// position, it could only mean that label is completely
// different, because typo correction has been attempted already.
parameterBindings[i].push_back(claim(params[i].getLabel(), i));
}
}
// If we still haven't claimed all of the arguments,
// fail if there is no recovery.
if (numClaimedArgs != numArgs) {
for (auto index : indices(claimedArgs)) {
if (claimedArgs[index])
continue;
if (listener.extraArgument(index))
return true;
}
}
// FIXME: If we had the actual parameters and knew the body names, those
// matches would be best.
potentiallyOutOfOrder = true;
}
// If we have any unfulfilled parameters, check them now.
std::optional<unsigned> prevArgIdx;
if (haveUnfulfilledParams) {
for (auto paramIdx : indices(params)) {
// If we have a binding for this parameter, we're done.
if (!parameterBindings[paramIdx].empty()) {
prevArgIdx = parameterBindings[paramIdx].back();
continue;
}
const auto ¶m = params[paramIdx];
// Variadic parameters can be unfulfilled.
if (param.isVariadic() || isPackExpansionType(param.getPlainType()))
continue;
// Parameters with defaults can be unfulfilled.
if (paramInfo.hasDefaultArgument(paramIdx))
continue;
unsigned argInsertIdx = prevArgIdx ? *prevArgIdx + 1 : 0;
if (auto newArgIdx = listener.missingArgument(paramIdx, argInsertIdx)) {
parameterBindings[paramIdx].push_back(*newArgIdx);
continue;
}
return true;
}
}
// If any arguments were provided out-of-order, check whether we have
// violated any of the reordering rules.
if (potentiallyOutOfOrder) {
// If we've seen label failures and now there is an out-of-order
// parameter (or even worse - OoO parameter with label re-naming),
// we most likely have no idea what would be the best
// diagnostic for this situation, so let's just try to re-label.
auto isOutOfOrderArgument = [&](unsigned toParamIdx, unsigned fromArgIdx,
unsigned toArgIdx) {
if (fromArgIdx <= toArgIdx) {
return false;
}
auto newLabel = args[fromArgIdx].getLabel();
auto oldLabel = args[toArgIdx].getLabel();
if (newLabel != params[toParamIdx].getLabel()) {
return false;
}
auto paramIdx = toParamIdx + 1;
for (; paramIdx < params.size(); ++paramIdx) {
// Looks like new position (excluding defaulted parameters),
// has a valid label.
if (oldLabel == params[paramIdx].getLabel())
break;
// If we are moving the position with a different label
// and there is no default value for it, can't diagnose the
// problem as a simple re-ordering.
if (!paramInfo.hasDefaultArgument(paramIdx))
return false;
}
// label was not found
if (paramIdx == params.size()) {
return false;
}
return true;
};
SmallVector<unsigned, 4> paramToArgMap;
paramToArgMap.reserve(params.size());
{
unsigned argIdx = 0;
for (const auto &binding : parameterBindings) {
paramToArgMap.push_back(argIdx);
// Ignore argument bindings that were synthesized due to missing args.
argIdx += llvm::count_if(
binding, [numArgs](unsigned argIdx) { return argIdx < numArgs; });
}
}
// Enumerate the parameters and their bindings to see if any arguments are
// our of order
bool hadLabelMismatch = false;
for (const auto paramIdx : indices(params)) {
const auto toArgIdx = paramToArgMap[paramIdx];
const auto &binding = parameterBindings[paramIdx];
for (const auto paramBindIdx : indices(binding)) {
// We've found the parameter that has an out of order
// argument, and know the indices of the argument that
// needs to move (fromArgIdx) and the argument location
// it should move to (toArgIdx).
const auto fromArgIdx = binding[paramBindIdx];
// Ignore argument bindings that were synthesized due to missing args.
if (fromArgIdx >= numArgs)
continue;
// Does nothing for variadic tail.
if ((params[paramIdx].isVariadic() ||
isPackExpansionType(params[paramIdx].getPlainType())) &&
paramBindIdx > 0) {
assert(args[fromArgIdx].getLabel().empty());
continue;
}
// First let's double check if out-of-order argument is nothing
// more than a simple label mismatch, because in situation where
// one argument requires label and another one doesn't, but caller
// doesn't provide either, problem is going to be identified as
// out-of-order argument instead of label mismatch.
const auto expectedLabel =
fromArgIdx == unlabeledTrailingClosureArgIndex
? Identifier()
: params[paramIdx].getLabel();
const auto argumentLabel = args[fromArgIdx].getLabel();
if (argumentLabel != expectedLabel) {
// - The parameter is unnamed, in which case we try to fix the
// problem by removing the name.
if (expectedLabel.empty()) {
hadLabelMismatch = true;
if (listener.extraneousLabel(paramIdx))
return true;
// - The argument is unnamed, in which case we try to fix the
// problem by adding the name.
} else if (argumentLabel.empty()) {
hadLabelMismatch = true;
if (listener.missingLabel(paramIdx))
return true;
// - The argument label has a typo at the same position.
} else if (fromArgIdx == toArgIdx) {
hadLabelMismatch = true;
if (listener.incorrectLabel(paramIdx))
return true;
}
}
if (fromArgIdx == toArgIdx) {
// If the argument is in the right location, just continue
continue;
}
// This situation looks like out-of-order argument but it's hard
// to say exactly without considering other factors, because it
// could be invalid labeling too.
if (!hadLabelMismatch &&
isOutOfOrderArgument(paramIdx, fromArgIdx, toArgIdx)) {
return listener.outOfOrderArgument(
fromArgIdx, toArgIdx, parameterBindings);
}
SmallVector<Identifier, 8> expectedLabels;
llvm::transform(params, std::back_inserter(expectedLabels),
[](const AnyFunctionType::Param ¶m) {
return param.getLabel();
});
return listener.relabelArguments(expectedLabels);
}
}
}
// If no arguments were renamed, the call arguments match up with the
// parameters.
if (actualArgNames.empty())
return false;