-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathCSSimplify.cpp
4352 lines (3686 loc) · 159 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 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements simplifications of constraints within the constraint
// system.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangModule.h"
using namespace swift;
using namespace constraints;
MatchCallArgumentListener::~MatchCallArgumentListener() { }
void MatchCallArgumentListener::extraArgument(unsigned argIdx) { }
void MatchCallArgumentListener::missingArgument(unsigned paramIdx) { }
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;
// 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;
assert(parameterDepth < fn->getNumParameterLists());
ParameterList ¶ms = *fn->getParameterList(parameterDepth);
SmallVector<CallArgParam, 8> argInfos;
for (auto argLabel : labels) {
argInfos.push_back(CallArgParam());
argInfos.back().Label = argLabel;
}
SmallVector<CallArgParam, 8> paramInfos;
for (auto param : params) {
paramInfos.push_back(CallArgParam());
paramInfos.back().Label = param->getArgumentName();
paramInfos.back().HasDefaultArgument = param->isDefaultArgument();
paramInfos.back().Variadic = param->isVariadic();
}
MatchCallArgumentListener listener;
SmallVector<ParamBinding, 8> unusedParamBindings;
return !matchCallArguments(argInfos, paramInfos, hasTrailingClosure,
/*allow fixes*/ false,
listener, unusedParamBindings);
}
bool constraints::
matchCallArguments(ArrayRef<CallArgParam> args,
ArrayRef<CallArgParam> params,
bool hasTrailingClosure,
bool allowFixes,
MatchCallArgumentListener &listener,
SmallVectorImpl<ParamBinding> ¶meterBindings) {
// 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;
// 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].Label != 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.Label : 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 name, bool ignoreNameMismatch) -> 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;
// When the expected name is empty, we claim the next argument if it has
// no name.
if (name.empty()) {
// Nothing to claim.
if (nextArgIdx == numArgs ||
claimedArgs[nextArgIdx] ||
(args[nextArgIdx].hasLabel() && !ignoreNameMismatch))
return None;
return claim(name, nextArgIdx);
}
// If the name matches, claim this argument.
if (nextArgIdx != numArgs &&
(ignoreNameMismatch || args[nextArgIdx].Label == name)) {
return claim(name, nextArgIdx);
}
// The name didn't match. Go hunting for an unclaimed argument whose name
// does match.
Optional<unsigned> claimedWithSameName;
for (unsigned i = nextArgIdx; i != numArgs; ++i) {
// Skip arguments where the name doesn't match.
if (args[i].Label != name)
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)
potentiallyOutOfOrder = true;
// Claim it.
return claim(name, 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 keyword argument might be a typo for an actual argument name, in
// which case we should find the closest match to correct to.
// Redundant keyword arguments.
if (claimedWithSameName) {
// FIXME: We can provide better diagnostics here.
return None;
}
// Missing a keyword argument name.
if (nextArgIdx != numArgs && !args[nextArgIdx].hasLabel() &&
ignoreNameMismatch) {
// Claim the next argument.
return claim(name, nextArgIdx);
}
// 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.Variadic) {
// Claim the next argument with the name of this parameter.
auto claimed = claimNextNamed(param.Label, ignoreNameMismatch);
// If there was no such argument, leave the argument unf
if (!claimed) {
haveUnfulfilledParams = true;
return;
}
// Record the first argument for the variadic.
parameterBindings[paramIdx].push_back(*claimed);
// Claim any additional unnamed arguments.
while ((claimed = claimNextNamed(Identifier(), false))) {
parameterBindings[paramIdx].push_back(*claimed);
}
skipClaimedArgs();
return;
}
// Try to claim an argument for this parameter.
if (auto claimed = claimNextNamed(param.Label, 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].hasLabel())
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].hasLabel())
unfulfilledNamedParams.push_back(paramIdx);
else
hasUnfulfilledUnnamedParams = true;
}
}
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].Label;
// 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].Label;
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];
bindNextParameter(true);
// 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 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.Variadic)
continue;
// Parameters with defaults can be unfulfilled.
if (param.HasDefaultArgument)
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) {
// Build a mapping from arguments to parameters.
SmallVector<unsigned, 4> argumentBindings(numArgs);
for (paramIdx = 0; paramIdx != numParams; ++paramIdx) {
for (auto argIdx : parameterBindings[paramIdx])
argumentBindings[argIdx] = paramIdx;
}
// Walk through the arguments, determining if any were bound to parameters
// out-of-order where it is not permitted.
unsigned prevParamIdx = argumentBindings[0];
for (unsigned argIdx = 1; argIdx != numArgs; ++argIdx) {
unsigned paramIdx = argumentBindings[argIdx];
// If this argument binds to the same parameter as the previous one or to
// a later parameter, just update the parameter index.
if (paramIdx >= prevParamIdx) {
prevParamIdx = paramIdx;
continue;
}
unsigned prevArgIdx = parameterBindings[prevParamIdx].front();
listener.outOfOrderArgument(argIdx, prevArgIdx);
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::pair<ValueDecl *, unsigned>
getCalleeDecl(ConstraintSystem &cs, ConstraintLocatorBuilder callLocator) {
// If the call locator is not just a call expression, there's
// nothing to do.
SmallVector<LocatorPathElt, 2> path;
auto callExpr = callLocator.getLocatorParts(path);
if (!callExpr) return { nullptr, 0 };
// Our remaining path can only be 'ApplyArgument'.
if (!path.empty() &&
!(path.size() == 1 &&
path.back().getKind() == ConstraintLocator::ApplyArgument))
return { nullptr, 0 };
// Dig out the callee.
Expr *calleeExpr;
if (auto call = dyn_cast<CallExpr>(callExpr))
calleeExpr = call->getDirectCallee();
else if (isa<UnresolvedMemberExpr>(callExpr))
calleeExpr = callExpr;
else
return { nullptr, 0 };
// Determine the target locator.
// FIXME: Check whether the callee is of an expression kind that
// could describe a declaration. This is an optimization.
ConstraintLocator *targetLocator = cs.getConstraintLocator(calleeExpr);
// 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 { nullptr, 0 };
// 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.simplifyType(choice->getBaseType())->is<AnyMetatypeType>()))
level = 1;
} else if (isa<SubscriptDecl>(decl)) {
// Subscript level 1 == the indices.
level = 1;
}
}
return { decl, level };
}
return { nullptr, 0 };
}
// Match the argument of a call to the parameter.
static ConstraintSystem::SolutionKind
matchCallArguments(ConstraintSystem &cs, TypeMatchKind kind,
Type argType, Type paramType,
ConstraintLocatorBuilder locator) {
// In the empty existential parameter case, we don't need to decompose the
// arguments.
if (paramType->isEmptyExistentialComposition()) {
if (argType->is<InOutType>())
return ConstraintSystem::SolutionKind::Error;
// If the param type is an empty existential composition, the function can
// only have one argument. Check if exactly one argument was passed to this
// function, otherwise we obviously have a mismatch
if (auto tupleArgType = dyn_cast<TupleType>(argType.getPointer())) {
if (tupleArgType->getNumElements() != 1) {
return ConstraintSystem::SolutionKind::Error;
}
}
return ConstraintSystem::SolutionKind::Solved;
}
// Extract the arguments.
auto args = decomposeArgType(argType);
// Extract the parameters.
ValueDecl *callee;
unsigned calleeLevel;
std::tie(callee, calleeLevel) = getCalleeDecl(cs, locator);
auto params = decomposeParamType(paramType, callee, calleeLevel);
// Match up the call arguments to the parameters.
MatchCallArgumentListener listener;
SmallVector<ParamBinding, 4> parameterBindings;
if (constraints::matchCallArguments(args, params,
hasTrailingClosure(locator),
cs.shouldAttemptFixes(), listener,
parameterBindings))
return ConstraintSystem::SolutionKind::Error;
// Check the argument types for each of the parameters.
unsigned subflags = ConstraintSystem::TMF_GenerateConstraints;
TypeMatchKind subKind;
switch (kind) {
case TypeMatchKind::ArgumentTupleConversion:
subKind = TypeMatchKind::ArgumentConversion;
break;
case TypeMatchKind::OperatorArgumentTupleConversion:
subKind = TypeMatchKind::OperatorArgumentConversion;
break;
case TypeMatchKind::Conversion:
case TypeMatchKind::ExplicitConversion:
case TypeMatchKind::OperatorArgumentConversion:
case TypeMatchKind::ArgumentConversion:
case TypeMatchKind::BindType:
case TypeMatchKind::BindParamType:
case TypeMatchKind::BindToPointerType:
case TypeMatchKind::SameType:
case TypeMatchKind::ConformsTo:
case TypeMatchKind::Subtype:
llvm_unreachable("Not a call argument constraint");
}
auto haveOneNonUserConversion =
(subKind != TypeMatchKind::OperatorArgumentConversion);
auto haveNilArgument = false;
auto nilLiteralProto = cs.TC.getProtocol(SourceLoc(),
KnownProtocolKind::
ExpressibleByNilLiteral);
auto isNilLiteral = [&](Type t) -> bool {
if (auto tyvar = t->getAs<TypeVariableType>()) {
return tyvar->getImpl().literalConformanceProto == nilLiteralProto;
}
return false;
};
// If we're applying an operator function to a nil literal operand, we
// disallow value-to-optional conversions from taking place so as not to
// select an overly permissive overload.
auto allowOptionalConversion = [&](Type t) -> bool {
if (t->isLValueType())
t = t->getLValueOrInOutObjectType();
if (!t->getAnyOptionalObjectType().isNull())
return true;
if (isNilLiteral(t))
return true;
if (auto nt = t->getNominalOrBoundGenericNominal()) {
return nt->getName() == cs.TC.Context.Id_OptionalNilComparisonType;
}
return false;
};
// Pre-scan operator arguments for nil literals.
if (subKind == TypeMatchKind::OperatorArgumentConversion) {
for (auto arg : args) {
if (isNilLiteral(arg.Ty)) {
haveNilArgument = true;
break;
}
}
}
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.Ty;
// Compare each of the bound arguments for this parameter.
for (auto argIdx : parameterBindings[paramIdx]) {
auto loc = locator.withPathElement(LocatorPathElt::
getApplyArgToParam(argIdx,
paramIdx));
auto argTy = args[argIdx].Ty;
if (haveNilArgument && !allowOptionalConversion(argTy)) {
subflags |= ConstraintSystem::TMF_ApplyingOperatorWithNil;
}
if (!haveOneNonUserConversion) {
subflags |= ConstraintSystem::TMF_ApplyingOperatorParameter;
}
switch (cs.matchTypes(argTy,paramTy,
subKind, subflags,
loc)) {
case ConstraintSystem::SolutionKind::Error:
return ConstraintSystem::SolutionKind::Error;
case ConstraintSystem::SolutionKind::Solved:
case ConstraintSystem::SolutionKind::Unsolved:
break;
}
}
}
return ConstraintSystem::SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchTupleTypes(TupleType *tuple1, TupleType *tuple2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
unsigned subFlags = flags | TMF_GenerateConstraints;
// Equality and subtyping have fairly strict requirements on tuple matching,
// requiring element names to either match up or be disjoint.
if (kind < TypeMatchKind::Conversion) {
if (tuple1->getNumElements() != tuple2->getNumElements())
return SolutionKind::Error;
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 <= TypeMatchKind::SameType)
return SolutionKind::Error;
// 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 SolutionKind::Error;
}
// Variadic bit must match.
if (elt1.isVararg() != elt2.isVararg())
return SolutionKind::Error;
// Compare the element types.
switch (matchTypes(elt1.getType(), elt2.getType(), kind, subFlags,
locator.withPathElement(
LocatorPathElt::getTupleElement(i)))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
return SolutionKind::Solved;
}
assert(kind >= TypeMatchKind::Conversion);
TypeMatchKind subKind;
switch (kind) {
case TypeMatchKind::ArgumentTupleConversion:
subKind = TypeMatchKind::ArgumentConversion;
break;
case TypeMatchKind::OperatorArgumentTupleConversion:
subKind = TypeMatchKind::OperatorArgumentConversion;
break;
case TypeMatchKind::OperatorArgumentConversion:
case TypeMatchKind::ArgumentConversion:
case TypeMatchKind::ExplicitConversion:
case TypeMatchKind::Conversion:
subKind = TypeMatchKind::Conversion;
break;
case TypeMatchKind::BindType:
case TypeMatchKind::BindParamType:
case TypeMatchKind::BindToPointerType:
case TypeMatchKind::SameType:
case TypeMatchKind::Subtype:
case TypeMatchKind::ConformsTo:
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 SolutionKind::Error;
// 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);
switch (matchTypes(elt1.getType(), elt2.getType(), subKind, subFlags,
locator.withPathElement(
LocatorPathElt::getTupleElement(idx1)))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
// 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) {
switch (matchTypes(tuple1->getElementType(idx1), eltType2, subKind,
subFlags,
locator.withPathElement(
LocatorPathElt::getTupleElement(idx1)))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
}
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchScalarToTupleTypes(Type type1, TupleType *tuple2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
int scalarFieldIdx = tuple2->getElementForScalarInit();
assert(scalarFieldIdx >= 0 && "Invalid tuple for scalar-to-tuple");
const auto &elt = tuple2->getElement(scalarFieldIdx);
auto scalarFieldTy = elt.isVararg()? elt.getVarargBaseTy() : elt.getType();
return matchTypes(type1, scalarFieldTy, kind, flags,
locator.withPathElement(ConstraintLocator::ScalarToTuple));
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchTupleToScalarTypes(TupleType *tuple1, Type type2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
assert(tuple1->getNumElements() == 1 && "Wrong number of elements");
assert(!tuple1->getElement(0).isVararg() && "Should not be variadic");
return matchTypes(tuple1->getElementType(0),
type2, kind, flags,
locator.withPathElement(
LocatorPathElt::getTupleElement(0)));
}
// 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,
TypeMatchKind kind) {
switch (kind) {
case TypeMatchKind::BindType:
case TypeMatchKind::BindParamType:
case TypeMatchKind::BindToPointerType:
case TypeMatchKind::SameType:
return rep1 != rep2;
case TypeMatchKind::ConformsTo:
llvm_unreachable("Not sure if we can end up here");
case TypeMatchKind::Subtype:
case TypeMatchKind::Conversion:
case TypeMatchKind::ExplicitConversion:
case TypeMatchKind::ArgumentConversion:
case TypeMatchKind::ArgumentTupleConversion:
case TypeMatchKind::OperatorArgumentTupleConversion:
case TypeMatchKind::OperatorArgumentConversion:
return false;
}
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchFunctionTypes(FunctionType *func1, FunctionType *func2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
// An @autoclosure function type can be a subtype of a
// non-@autoclosure function type.
if (func1->isAutoClosure() != func2->isAutoClosure() &&
kind < TypeMatchKind::Subtype)
return SolutionKind::Error;
// A non-throwing function can be a subtype of a throwing function.
if (func1->throws() != func2->throws()) {
// Cannot drop 'throws'.
if (func1->throws() || (func2->throws() && kind < TypeMatchKind::Subtype))
return SolutionKind::Error;
}
// A @noreturn function type can be a subtype of a non-@noreturn function
// type.
if (func1->isNoReturn() != func2->isNoReturn() &&
(func2->isNoReturn() || kind < TypeMatchKind::SameType))
return SolutionKind::Error;
// A non-@noescape function type can be a subtype of a @noescape function
// type.
if (func1->isNoEscape() != func2->isNoEscape() &&
(func1->isNoEscape() || kind < TypeMatchKind::Subtype))
return SolutionKind::Error;
if (matchFunctionRepresentations(func1->getExtInfo().getRepresentation(),
func2->getExtInfo().getRepresentation(),
kind)) {
return SolutionKind::Error;
}
// Determine how we match up the input/result types.
TypeMatchKind subKind;
switch (kind) {
case TypeMatchKind::BindType:
case TypeMatchKind::BindParamType:
case TypeMatchKind::BindToPointerType:
case TypeMatchKind::SameType:
subKind = kind;
break;
case TypeMatchKind::ConformsTo:
llvm_unreachable("Not sure if we can end up here");
case TypeMatchKind::Subtype:
case TypeMatchKind::Conversion:
case TypeMatchKind::ExplicitConversion:
case TypeMatchKind::ArgumentConversion:
case TypeMatchKind::ArgumentTupleConversion:
case TypeMatchKind::OperatorArgumentTupleConversion:
case TypeMatchKind::OperatorArgumentConversion:
subKind = TypeMatchKind::Subtype;
break;
}
unsigned subFlags = flags | TMF_GenerateConstraints;
// Input types can be contravariant (or equal).
SolutionKind result = matchTypes(func2->getInput(), func1->getInput(),
subKind, subFlags,
locator.withPathElement(
ConstraintLocator::FunctionArgument));
if (result == SolutionKind::Error)
return SolutionKind::Error;
// Result type can be covariant (or equal).
return matchTypes(func1->getResult(), func2->getResult(), subKind,
subFlags,
locator.withPathElement(
ConstraintLocator::FunctionResult));
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchSuperclassTypes(Type type1, Type type2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
auto classDecl2 = type2->getClassOrBoundGenericClass();
bool done = false;
for (auto super1 = TC.getSuperClassOf(type1);
!done && super1;
super1 = TC.getSuperClassOf(super1)) {
if (super1->getClassOrBoundGenericClass() != classDecl2)
continue;
return matchTypes(super1, type2, TypeMatchKind::SameType,
TMF_GenerateConstraints, locator);
}
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchDeepEqualityTypes(Type type1, Type type2,