forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSSimplify.cpp
5469 lines (4682 loc) · 203 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 "CSFix.h"
#include "ConstraintSystem.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangModule.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Compiler.h"
using namespace swift;
using namespace constraints;
MatchCallArgumentListener::~MatchCallArgumentListener() { }
void MatchCallArgumentListener::extraArgument(unsigned argIdx) { }
void MatchCallArgumentListener::missingArgument(unsigned paramIdx) { }
bool MatchCallArgumentListener::missingLabel(unsigned paramIdx) { return true; }
bool MatchCallArgumentListener::extraneousLabel(unsigned paramIdx) {
return true;
}
bool MatchCallArgumentListener::incorrectLabel(unsigned paramIdx) {
return true;
}
void MatchCallArgumentListener::outOfOrderArgument(unsigned argIdx,
unsigned prevArgIdx) {
}
bool MatchCallArgumentListener::relabelArguments(ArrayRef<Identifier> newNames){
return true;
}
/// 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 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 None;
// 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 None;
return dist;
}
bool constraints::
areConservativelyCompatibleArgumentLabels(ValueDecl *decl,
unsigned parameterDepth,
ArrayRef<Identifier> labels,
bool hasTrailingClosure) {
// Bail out conservatively if this isn't a function declaration.
auto fn = dyn_cast<AbstractFunctionDecl>(decl);
if (!fn) return true;
auto *fTy = fn->getInterfaceType()->castTo<AnyFunctionType>();
SmallVector<AnyFunctionType::Param, 8> argInfos;
for (auto argLabel : labels) {
argInfos.push_back(AnyFunctionType::Param(Type(), argLabel, {}));
}
const AnyFunctionType *levelTy = fTy;
for (auto level = parameterDepth; level != 0; --level) {
levelTy = levelTy->getResult()->getAs<AnyFunctionType>();
assert(levelTy && "Parameter list curry level does not match type");
}
auto params = levelTy->getParams();
llvm::SmallBitVector defaultMap =
computeDefaultMap(params, decl, parameterDepth);
MatchCallArgumentListener listener;
SmallVector<ParamBinding, 8> unusedParamBindings;
return !matchCallArguments(argInfos, params, defaultMap,
hasTrailingClosure,
/*allow fixes*/ false,
listener, unusedParamBindings);
}
/// 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;
}
// FIXME: This should return ConstraintSystem::TypeMatchResult instead
// to give more information to the solver about the failure.
bool constraints::
matchCallArguments(ArrayRef<AnyFunctionType::Param> args,
ArrayRef<AnyFunctionType::Param> params,
const llvm::SmallBitVector &defaultMap,
bool hasTrailingClosure,
bool allowFixes,
MatchCallArgumentListener &listener,
SmallVectorImpl<ParamBinding> ¶meterBindings) {
assert(params.size() == defaultMap.size() && "Default map does not match");
// Keep track of the parameter we're matching and what argument indices
// got bound to each parameter.
unsigned paramIdx, numParams = params.size();
parameterBindings.clear();
parameterBindings.resize(numParams);
// Keep track of which arguments we have claimed from the argument tuple.
unsigned nextArgIdx = 0, 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;
auto hasDefault = [&defaultMap, &numParams](unsigned idx) -> bool {
return idx < numParams ? defaultMap.test(idx) : false;
};
// Local function that claims the argument at \c argNumber, returning the
// index of the claimed argument. This is primarily a helper for
// \c claimNextNamed.
auto claim = [&](Identifier expectedName, unsigned argNumber,
bool ignoreNameClash = false) -> unsigned {
// Make sure we can claim this argument.
assert(argNumber != numArgs && "Must have a valid index to claim");
assert(!claimedArgs[argNumber] && "Argument already claimed");
if (!actualArgNames.empty()) {
// We're recording argument names; record this one.
actualArgNames[argNumber] = expectedName;
} else if (args[argNumber].getLabel() != expectedName && !ignoreNameClash) {
// We have an argument name mismatch. Start recording argument names.
actualArgNames.resize(numArgs);
// Figure out previous argument names from the parameter bindings.
for (unsigned i = 0; i != numParams; ++i) {
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[argNumber] = expectedName;
}
claimedArgs[argNumber] = true;
++numClaimedArgs;
return argNumber;
};
// Local function that skips over any claimed arguments.
auto skipClaimedArgs = [&]() {
while (nextArgIdx != numArgs && claimedArgs[nextArgIdx])
++nextArgIdx;
};
// Local function that retrieves the next unclaimed argument with the given
// name (which may be empty). This routine claims the argument.
auto claimNextNamed
= [&](Identifier paramLabel, bool ignoreNameMismatch,
bool forVariadic = false) -> Optional<unsigned> {
// Skip over any claimed arguments.
skipClaimedArgs();
// If we've claimed all of the arguments, there's nothing more to do.
if (numClaimedArgs == numArgs)
return None;
// Go hunting for an unclaimed argument whose name does match.
Optional<unsigned> claimedWithSameName;
for (unsigned i = nextArgIdx; i != numArgs; ++i) {
auto argLabel = args[i].getLabel();
if (argLabel != 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 None;
// Otherwise we can continue trying to find argument which
// matches parameter with or without label.
continue;
}
// Skip claimed arguments.
if (claimedArgs[i]) {
// 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) {
// 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() && (hasDefault(i) || !forVariadic))
continue;
potentiallyOutOfOrder = true;
}
// Claim it.
return claim(paramLabel, i);
}
// If we're not supposed to attempt any fixes, we're done.
if (!allowFixes)
return None;
// 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 None;
}
// Typo correction is handled in a later pass.
return None;
};
// Local function that attempts to bind the given parameter to arguments in
// the list.
bool haveUnfulfilledParams = false;
auto bindNextParameter = [&](bool ignoreNameMismatch) {
const auto ¶m = params[paramIdx];
// Handle variadic parameters.
if (param.isVariadic()) {
// Claim the next argument with the name of this parameter.
auto claimed = claimNextNamed(param.getLabel(), 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 ((claimed = claimNextNamed(Identifier(), false, true))) {
parameterBindings[paramIdx].push_back(*claimed);
}
}
nextArgIdx = currentNextArgIdx;
skipClaimedArgs();
return;
}
// Try to claim an argument for this parameter.
if (auto claimed = claimNextNamed(param.getLabel(), ignoreNameMismatch)) {
parameterBindings[paramIdx].push_back(*claimed);
skipClaimedArgs();
return;
}
// There was no argument to claim. Leave the argument unfulfilled.
haveUnfulfilledParams = true;
};
// If we have a trailing closure, it maps to the last parameter.
if (hasTrailingClosure && numParams > 0) {
claimedArgs[numArgs-1] = true;
++numClaimedArgs;
parameterBindings[numParams-1].push_back(numArgs-1);
}
// Mark through the parameters, binding them to their arguments.
for (paramIdx = 0; paramIdx != numParams; ++paramIdx) {
if (parameterBindings[paramIdx].empty())
bindNextParameter(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 (nextArgIdx = 0; skipClaimedArgs(), nextArgIdx != numArgs;
++nextArgIdx) {
if (!args[nextArgIdx].getLabel().empty())
unclaimedNamedArgs.push_back(nextArgIdx);
}
if (!unclaimedNamedArgs.empty()) {
// Find all of the named, unfulfilled parameters.
llvm::SmallVector<unsigned, 4> unfulfilledNamedParams;
bool hasUnfulfilledUnnamedParams = false;
for (paramIdx = 0; paramIdx != numParams; ++paramIdx) {
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 (unsigned i = 0, n = unfulfilledNamedParams.size(); i != n; ++i) {
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.
nextArgIdx = argIdx;
paramIdx = unfulfilledNamedParams[best];
auto paramLabel = params[paramIdx].getLabel();
parameterBindings[paramIdx].push_back(claim(paramLabel, argIdx));
skipClaimedArgs();
// 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.
nextArgIdx = 0;
skipClaimedArgs();
haveUnfulfilledParams = false;
for (paramIdx = 0; paramIdx != numParams; ++paramIdx) {
// Skip fulfilled parameters.
if (!parameterBindings[paramIdx].empty())
continue;
bindNextParameter(true);
}
}
// 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 (unsigned i = 0; i < numArgs; ++i) {
if (claimedArgs[i] || !parameterBindings[i].empty())
continue;
// If parameter has a default value, we don't really
// now if label doesn't match because it's incorrect
// or argument belongs to some other parameter, so
// we just leave this parameter unfulfilled.
if (defaultMap.test(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 (numClaimedArgs != numArgs) {
nextArgIdx = 0;
skipClaimedArgs();
listener.extraArgument(nextArgIdx);
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.
if (haveUnfulfilledParams) {
for (paramIdx = 0; paramIdx != numParams; ++paramIdx) {
// If we have a binding for this parameter, we're done.
if (!parameterBindings[paramIdx].empty())
continue;
const auto ¶m = params[paramIdx];
// Variadic parameters can be unfulfilled.
if (param.isVariadic())
continue;
// Parameters with defaults can be unfulfilled.
if (hasDefault(paramIdx))
continue;
listener.missingArgument(paramIdx);
return true;
}
}
// If any arguments were provided out-of-order, check whether we have
// violated any of the reordering rules.
if (potentiallyOutOfOrder) {
unsigned argIdx = 0;
// Enumerate the parameters and their bindings to see if any arguments are
// our of order
for (auto binding : parameterBindings) {
for (auto boundArgIdx : 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).
auto fromArgIdx = boundArgIdx;
auto toArgIdx = argIdx;
// If there is no re-ordering going on, and index is past
// the number of parameters, it could only mean that this
// is variadic parameter, so let's just move on.
if (fromArgIdx == toArgIdx && toArgIdx >= params.size()) {
assert(args[fromArgIdx].getLabel().empty());
argIdx++;
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.
auto expectedLabel = params[toArgIdx].getLabel();
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()) {
if (listener.extraneousLabel(toArgIdx))
return true;
// - The argument is unnamed, in which case we try to fix the
// problem by adding the name.
} else if (argumentLabel.empty()) {
if (listener.missingLabel(toArgIdx))
return true;
// - The argument label has a typo at the same position.
} else if (fromArgIdx == toArgIdx &&
listener.incorrectLabel(toArgIdx)) {
return true;
}
}
if (boundArgIdx == argIdx) {
// If the argument is in the right location, just continue
argIdx++;
continue;
}
listener.outOfOrderArgument(fromArgIdx, toArgIdx);
return true;
}
}
}
// If no arguments were renamed, the call arguments match up with the
// parameters.
if (actualArgNames.empty())
return false;
// The arguments were relabeled; notify the listener.
return listener.relabelArguments(actualArgNames);
}
/// Find the callee declaration and uncurry level for a given call
/// locator.
static std::tuple<ValueDecl *, unsigned, ArrayRef<Identifier>, bool>
getCalleeDeclAndArgs(ConstraintSystem &cs,
ConstraintLocatorBuilder callLocator,
SmallVectorImpl<Identifier> &argLabelsScratch) {
ArrayRef<Identifier> argLabels;
bool hasTrailingClosure = false;
// Break down the call.
SmallVector<LocatorPathElt, 2> path;
auto callExpr = callLocator.getLocatorParts(path);
if (!callExpr)
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
// Our remaining path can only be 'ApplyArgument'.
if (!path.empty() &&
!(path.size() <= 2 &&
path.back().getKind() == ConstraintLocator::ApplyArgument))
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
// Dig out the callee.
ConstraintLocator *targetLocator;
if (auto call = dyn_cast<CallExpr>(callExpr)) {
targetLocator = cs.getConstraintLocator(call->getDirectCallee());
argLabels = call->getArgumentLabels();
hasTrailingClosure = call->hasTrailingClosure();
} else if (auto unresolved = dyn_cast<UnresolvedMemberExpr>(callExpr)) {
targetLocator = cs.getConstraintLocator(callExpr);
argLabels = unresolved->getArgumentLabels();
hasTrailingClosure = unresolved->hasTrailingClosure();
} else if (auto subscript = dyn_cast<SubscriptExpr>(callExpr)) {
targetLocator = cs.getConstraintLocator(callExpr);
argLabels = subscript->getArgumentLabels();
hasTrailingClosure = subscript->hasTrailingClosure();
} else if (auto dynSubscript = dyn_cast<DynamicSubscriptExpr>(callExpr)) {
targetLocator = cs.getConstraintLocator(callExpr);
argLabels = dynSubscript->getArgumentLabels();
hasTrailingClosure = dynSubscript->hasTrailingClosure();
} else if (auto keyPath = dyn_cast<KeyPathExpr>(callExpr)) {
if (path.size() != 2 ||
path[0].getKind() != ConstraintLocator::KeyPathComponent ||
path[1].getKind() != ConstraintLocator::ApplyArgument)
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
auto componentIndex = path[0].getValue();
if (componentIndex >= keyPath->getComponents().size())
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
auto &component = keyPath->getComponents()[componentIndex];
switch (component.getKind()) {
case KeyPathExpr::Component::Kind::Subscript:
case KeyPathExpr::Component::Kind::UnresolvedSubscript:
targetLocator = cs.getConstraintLocator(callExpr, path[0]);
argLabels = component.getSubscriptLabels();
hasTrailingClosure = false; // key paths don't support trailing closures
break;
case KeyPathExpr::Component::Kind::Invalid:
case KeyPathExpr::Component::Kind::UnresolvedProperty:
case KeyPathExpr::Component::Kind::Property:
case KeyPathExpr::Component::Kind::OptionalForce:
case KeyPathExpr::Component::Kind::OptionalChain:
case KeyPathExpr::Component::Kind::OptionalWrap:
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
}
} else {
if (auto apply = dyn_cast<ApplyExpr>(callExpr)) {
argLabels = apply->getArgumentLabels(argLabelsScratch);
assert(!apply->hasTrailingClosure());
} else if (auto objectLiteral = dyn_cast<ObjectLiteralExpr>(callExpr)) {
argLabels = objectLiteral->getArgumentLabels();
hasTrailingClosure = objectLiteral->hasTrailingClosure();
}
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
}
// Find the overload choice corresponding to the callee locator.
// FIXME: This linearly walks the list of resolved overloads, which is
// potentially very expensive.
Optional<OverloadChoice> choice;
for (auto resolved = cs.getResolvedOverloadSets(); resolved;
resolved = resolved->Previous) {
// FIXME: Workaround null locators.
if (!resolved->Locator) continue;
auto resolvedLocator = resolved->Locator;
SmallVector<LocatorPathElt, 4> resolvedPath(
resolvedLocator->getPath().begin(),
resolvedLocator->getPath().end());
if (!resolvedPath.empty() &&
(resolvedPath.back().getKind() == ConstraintLocator::SubscriptMember ||
resolvedPath.back().getKind() == ConstraintLocator::Member ||
resolvedPath.back().getKind() == ConstraintLocator::UnresolvedMember ||
resolvedPath.back().getKind() ==
ConstraintLocator::ConstructorMember)) {
resolvedPath.pop_back();
resolvedLocator = cs.getConstraintLocator(
resolvedLocator->getAnchor(),
resolvedPath,
resolvedLocator->getSummaryFlags());
}
SourceRange range;
resolvedLocator = simplifyLocator(cs, resolvedLocator, range);
if (resolvedLocator == targetLocator) {
choice = resolved->Choice;
break;
}
}
// If we didn't find any matching overloads, we're done.
if (!choice)
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
// If there's a declaration, return it.
if (choice->isDecl()) {
auto decl = choice->getDecl();
unsigned level = 0;
if (decl->getDeclContext()->isTypeContext()) {
if (auto function = dyn_cast<AbstractFunctionDecl>(decl)) {
// References to instance members on a metatype stay at level 0.
// Everything else is level 1.
if (!(function->isInstanceMember() &&
cs.getFixedTypeRecursive(choice->getBaseType(),
/*wantRValue=*/true)
->is<AnyMetatypeType>()))
level = 1;
} else if (isa<SubscriptDecl>(decl)) {
// Subscript level 1 == the indices.
level = 1;
} else if (isa<EnumElementDecl>(decl)) {
// Enum element level 1 == the payload.
level = 1;
}
}
return std::make_tuple(decl, level, argLabels, hasTrailingClosure);
}
return std::make_tuple(nullptr, 0, argLabels, hasTrailingClosure);
}
class ArgumentFailureTracker : public MatchCallArgumentListener {
ConstraintSystem &CS;
ConstraintLocatorBuilder Locator;
public:
ArgumentFailureTracker(ConstraintSystem &cs, ConstraintLocatorBuilder locator)
: CS(cs), Locator(locator) {}
bool missingLabel(unsigned paramIndex) override {
return !CS.shouldAttemptFixes();
}
bool extraneousLabel(unsigned paramIndex) override {
return !CS.shouldAttemptFixes();
}
bool incorrectLabel(unsigned paramIndex) override {
return !CS.shouldAttemptFixes();
}
bool relabelArguments(ArrayRef<Identifier> newLabels) override {
if (!CS.shouldAttemptFixes())
return true;
auto *anchor = Locator.getBaseLocator()->getAnchor();
if (!anchor || !isa<CallExpr>(anchor))
return true;
auto *locator = CS.getConstraintLocator(anchor);
auto *fix = RelabelArguments::create(CS, newLabels, locator);
CS.recordFix(fix);
return false;
}
};
// Match the argument of a call to the parameter.
ConstraintSystem::TypeMatchResult
constraints::matchCallArguments(ConstraintSystem &cs, bool isOperator,
ArrayRef<AnyFunctionType::Param> args,
ArrayRef<AnyFunctionType::Param> params,
ConstraintLocatorBuilder locator) {
// Extract the parameters.
ValueDecl *callee;
unsigned calleeLevel;
ArrayRef<Identifier> argLabels;
SmallVector<Identifier, 2> argLabelsScratch;
bool hasTrailingClosure = false;
std::tie(callee, calleeLevel, argLabels, hasTrailingClosure) =
getCalleeDeclAndArgs(cs, locator, argLabelsScratch);
llvm::SmallBitVector defaultMap =
computeDefaultMap(params, callee, calleeLevel);
// Apply labels to arguments.
SmallVector<AnyFunctionType::Param, 8> argsWithLabels;
argsWithLabels.append(args.begin(), args.end());
AnyFunctionType::relabelParams(argsWithLabels, argLabels);
// FIXME: Remove this. It's functionally identical to the real code
// path below, except for some behavioral differences in solution ranking
// that I don't understand.
if (params.size() == 1 &&
args.size() == 1 &&
params[0].getLabel().empty() &&
args[0].getLabel().empty() &&
!params[0].getParameterFlags().isInOut() &&
!args[0].getParameterFlags().isInOut() &&
params[0].getPlainType()->isAny()) {
auto argType = args[0].getPlainType();
// Disallow assignment of noescape function to parameter of type
// Any. Allowing this would allow these functions to escape.
if (auto *fnTy = argType->getAs<AnyFunctionType>()) {
if (fnTy->isNoEscape()) {
auto *loc = cs.getConstraintLocator(locator);
// Allow assigned of 'no-escape' function with recorded fix.
if (cs.shouldAttemptFixes()) {
if (!cs.recordFix(MarkExplicitlyEscaping::create(cs, loc)))
return cs.getTypeMatchSuccess();
}
return cs.getTypeMatchFailure(locator);
}
}
return cs.getTypeMatchSuccess();
}
// Match up the call arguments to the parameters.
ArgumentFailureTracker listener(cs, locator);
SmallVector<ParamBinding, 4> parameterBindings;
if (constraints::matchCallArguments(argsWithLabels, params,
defaultMap,
hasTrailingClosure,
cs.shouldAttemptFixes(), listener,
parameterBindings))
return cs.getTypeMatchFailure(locator);
// Check the argument types for each of the parameters.
ConstraintSystem::TypeMatchOptions subflags =
ConstraintSystem::TMF_GenerateConstraints;
ConstraintKind subKind = (isOperator
? ConstraintKind::OperatorArgumentConversion
: ConstraintKind::ArgumentConversion);
for (unsigned paramIdx = 0, numParams = parameterBindings.size();
paramIdx != numParams; ++paramIdx){
// Skip unfulfilled parameters. There's nothing to do for them.
if (parameterBindings[paramIdx].empty())
continue;
// Determine the parameter type.
const auto ¶m = params[paramIdx];
auto paramTy = param.getType();
// Compare each of the bound arguments for this parameter.
for (auto argIdx : parameterBindings[paramIdx]) {
auto loc = locator.withPathElement(LocatorPathElt::
getApplyArgToParam(argIdx,
paramIdx));
auto argTy = argsWithLabels[argIdx].getType();
// FIXME: This should be revisited. If one of argTy or paramTy
// is a type variable, matchTypes() will add a constraint, and
// when the constraint is later solved, we will have lost the
// value of 'subflags'.
if (isOperator) {
subflags |= ConstraintSystem::TMF_ApplyingOperatorParameter;
}
auto result = cs.matchTypes(argTy, paramTy, subKind, subflags, loc);
if (result.isFailure())
return result;
}
}
return cs.getTypeMatchSuccess();
}
ConstraintSystem::TypeMatchResult
ConstraintSystem::matchTupleTypes(TupleType *tuple1, TupleType *tuple2,
ConstraintKind kind, TypeMatchOptions flags,
ConstraintLocatorBuilder locator) {
TypeMatchOptions subflags = getDefaultDecompositionOptions(flags);
// Equality and subtyping have fairly strict requirements on tuple matching,
// requiring element names to either match up or be disjoint.
if (kind < ConstraintKind::Conversion) {
if (tuple1->getNumElements() != tuple2->getNumElements())
return getTypeMatchFailure(locator);
for (unsigned i = 0, n = tuple1->getNumElements(); i != n; ++i) {
const auto &elt1 = tuple1->getElement(i);
const auto &elt2 = tuple2->getElement(i);
// If the names don't match, we may have a conflict.
if (elt1.getName() != elt2.getName()) {
// Same-type requirements require exact name matches.
if (kind <= ConstraintKind::Equal)
return getTypeMatchFailure(locator);
// For subtyping constraints, just make sure that this name isn't
// used at some other position.
if (elt2.hasName() && tuple1->getNamedElementId(elt2.getName()) != -1)
return getTypeMatchFailure(locator);
}
// Variadic bit must match.
if (elt1.isVararg() != elt2.isVararg())
return getTypeMatchFailure(locator);
// Compare the element types.
auto result = matchTypes(elt1.getType(), elt2.getType(), kind, subflags,
locator.withPathElement(
LocatorPathElt::getTupleElement(i)));
if (result.isFailure())
return result;
}
return getTypeMatchSuccess();
}
assert(kind >= ConstraintKind::Conversion);
ConstraintKind subKind;
switch (kind) {
case ConstraintKind::OperatorArgumentConversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::Conversion:
subKind = ConstraintKind::Conversion;
break;
case ConstraintKind::Bind:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Equal:
case ConstraintKind::Subtype:
case ConstraintKind::ApplicableFunction:
case ConstraintKind::BindOverload:
case ConstraintKind::CheckedCast:
case ConstraintKind::ConformsTo:
case ConstraintKind::Defaultable:
case ConstraintKind::Disjunction:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::OptionalObject:
case ConstraintKind::SelfObjectOfProtocol:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueMember:
case ConstraintKind::BridgingConversion:
case ConstraintKind::FunctionInput:
case ConstraintKind::FunctionResult:
llvm_unreachable("Not a conversion");
}
// Compute the element shuffles for conversions.
SmallVector<int, 16> sources;
SmallVector<unsigned, 4> variadicArguments;
if (computeTupleShuffle(tuple1, tuple2, sources, variadicArguments))
return getTypeMatchFailure(locator);
// Check each of the elements.
bool hasVariadic = false;
unsigned variadicIdx = sources.size();
for (unsigned idx2 = 0, n = sources.size(); idx2 != n; ++idx2) {
// Default-initialization always allowed for conversions.
if (sources[idx2] == TupleShuffleExpr::DefaultInitialize) {
continue;
}
// Variadic arguments handled below.
if (sources[idx2] == TupleShuffleExpr::Variadic) {
assert(!hasVariadic && "Multiple variadic parameters");
hasVariadic = true;
variadicIdx = idx2;
continue;
}
assert(sources[idx2] >= 0);
unsigned idx1 = sources[idx2];
// Match up the types.
const auto &elt1 = tuple1->getElement(idx1);
const auto &elt2 = tuple2->getElement(idx2);
auto result = matchTypes(elt1.getType(), elt2.getType(), subKind, subflags,
locator.withPathElement(
LocatorPathElt::getTupleElement(idx1)));
if (result.isFailure())
return result;
}
// If we have variadic arguments to check, do so now.
if (hasVariadic) {
const auto &elt2 = tuple2->getElements()[variadicIdx];
auto eltType2 = elt2.getVarargBaseTy();
for (unsigned idx1 : variadicArguments) {
auto result = matchTypes(tuple1->getElementType(idx1), eltType2, subKind,
subflags,
locator.withPathElement(
LocatorPathElt::getTupleElement(idx1)));
if (result.isFailure())
return result;
}
}
return getTypeMatchSuccess();
}
// Returns 'false' (i.e. no error) if it is legal to match functions with the
// corresponding function type representations and the given match kind.
static bool matchFunctionRepresentations(FunctionTypeRepresentation rep1,
FunctionTypeRepresentation rep2,
ConstraintKind kind) {
switch (kind) {
case ConstraintKind::Bind: