forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSSolver.cpp
1710 lines (1459 loc) · 61.4 KB
/
CSSolver.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
//===--- CSSolver.cpp - Constraint Solver ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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 the constraint solver used in the type checker.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "ConstraintGraph.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SaveAndRestore.h"
#include <memory>
#include <tuple>
using namespace swift;
using namespace constraints;
//===--------------------------------------------------------------------===//
// Constraint solver statistics
//===--------------------------------------------------------------------===//
#define DEBUG_TYPE "Constraint solver overall"
#define JOIN(X,Y) JOIN2(X,Y)
#define JOIN2(X,Y) X##Y
STATISTIC(NumSolutionAttempts, "# of solution attempts");
#define CS_STATISTIC(Name, Description) \
STATISTIC(JOIN2(Overall,Name), Description);
#include "ConstraintSolverStats.def"
#undef DEBUG_TYPE
#define DEBUG_TYPE "Constraint solver largest system"
#define CS_STATISTIC(Name, Description) \
STATISTIC(JOIN2(Largest,Name), Description);
#include "ConstraintSolverStats.def"
STATISTIC(LargestSolutionAttemptNumber, "# of the largest solution attempt");
/// \brief Check whether the given type can be used as a binding for the given
/// type variable.
///
/// \returns the type to bind to, if the binding is okay.
static Optional<Type> checkTypeOfBinding(ConstraintSystem &cs,
TypeVariableType *typeVar, Type type) {
if (!type)
return None;
// Simplify the type.
type = cs.simplifyType(type);
// If the type references the type variable, don't permit the binding.
SmallVector<TypeVariableType *, 4> referencedTypeVars;
type->getTypeVariables(referencedTypeVars);
if (std::count(referencedTypeVars.begin(), referencedTypeVars.end(), typeVar))
return None;
// If the type is a type variable itself, don't permit the binding.
// FIXME: This is a hack. We need to be smarter about whether there's enough
// structure in the type to produce an interesting binding, or not.
if (type->getRValueType()->is<TypeVariableType>())
return None;
// Okay, allow the binding (with the simplified type).
return type;
}
/// Reconsistitute type sugar, e.g., for array types, dictionary
/// types, optionals, etc.
static Type reconstituteSugar(Type type) {
if (auto boundGeneric = dyn_cast<BoundGenericType>(type.getPointer())) {
auto &ctx = type->getASTContext();
if (boundGeneric->getDecl() == ctx.getArrayDecl())
return ArraySliceType::get(boundGeneric->getGenericArgs()[0]);
if (boundGeneric->getDecl() == ctx.getDictionaryDecl())
return DictionaryType::get(boundGeneric->getGenericArgs()[0],
boundGeneric->getGenericArgs()[1]);
if (boundGeneric->getDecl() == ctx.getOptionalDecl())
return OptionalType::get(boundGeneric->getGenericArgs()[0]);
if (boundGeneric->getDecl() == ctx.getImplicitlyUnwrappedOptionalDecl())
return ImplicitlyUnwrappedOptionalType::get(
boundGeneric->getGenericArgs()[0]);
}
return type;
}
Solution ConstraintSystem::finalize(
FreeTypeVariableBinding allowFreeTypeVariables) {
// Create the solution.
Solution solution(*this, CurrentScore);
// Update the best score we've seen so far.
if (solverState) {
assert(!solverState->BestScore || CurrentScore <= *solverState->BestScore);
solverState->BestScore = CurrentScore;
}
// For any of the type variables that has no associated fixed type, assign a
// fresh generic type parameters.
// FIXME: We could gather the requirements on these as well.
unsigned index = 0;
for (auto tv : TypeVariables) {
if (getFixedType(tv))
continue;
switch (allowFreeTypeVariables) {
case FreeTypeVariableBinding::Disallow:
llvm_unreachable("Solver left free type variables");
case FreeTypeVariableBinding::Allow:
break;
case FreeTypeVariableBinding::GenericParameters:
assignFixedType(tv, GenericTypeParamType::get(0, index++, TC.Context));
break;
case FreeTypeVariableBinding::UnresolvedType:
assignFixedType(tv, TC.Context.TheUnresolvedType);
break;
}
}
// For each of the type variables, get its fixed type.
for (auto tv : TypeVariables) {
solution.typeBindings[tv] = reconstituteSugar(simplifyType(tv));
}
// For each of the overload sets, get its overload choice.
for (auto resolved = resolvedOverloadSets;
resolved; resolved = resolved->Previous) {
solution.overloadChoices[resolved->Locator]
= { resolved->Choice, resolved->OpenedFullType, resolved->ImpliedType };
}
// For each of the constraint restrictions, record it with simplified,
// canonical types.
if (solverState) {
for (auto &restriction : ConstraintRestrictions) {
using std::get;
CanType first = simplifyType(get<0>(restriction))->getCanonicalType();
CanType second = simplifyType(get<1>(restriction))->getCanonicalType();
solution.ConstraintRestrictions[{first, second}] = get<2>(restriction);
}
}
// For each of the fixes, record it as an operation on the affected
// expression.
unsigned firstFixIndex = 0;
if (solverState && solverState->PartialSolutionScope) {
firstFixIndex = solverState->PartialSolutionScope->numFixes;
}
solution.Fixes.append(Fixes.begin() + firstFixIndex, Fixes.end());
// Remember all the disjunction choices we made.
for (auto &choice : DisjunctionChoices) {
// We shouldn't ever register disjunction choices multiple times,
// but saving and re-applying solutions can cause us to get
// multiple entries. We should use an optimized PartialSolution
// structure for that use case, which would optimize a lot of
// stuff here.
assert(!solution.DisjunctionChoices.count(choice.first) ||
solution.DisjunctionChoices[choice.first] == choice.second);
solution.DisjunctionChoices.insert(choice);
}
// Remember the opened types.
for (const auto &opened : OpenedTypes) {
// We shouldn't ever register opened types multiple times,
// but saving and re-applying solutions can cause us to get
// multiple entries. We should use an optimized PartialSolution
// structure for that use case, which would optimize a lot of
// stuff here.
assert((solution.OpenedTypes.count(opened.first) == 0 ||
solution.OpenedTypes[opened.first] == opened.second)
&& "Already recorded");
solution.OpenedTypes.insert(opened);
}
// Remember the opened existential types.
for (const auto &openedExistential : OpenedExistentialTypes) {
assert(solution.OpenedExistentialTypes.count(openedExistential.first) == 0||
solution.OpenedExistentialTypes[openedExistential.first]
== openedExistential.second &&
"Already recorded");
solution.OpenedExistentialTypes.insert(openedExistential);
}
return std::move(solution);
}
void ConstraintSystem::applySolution(const Solution &solution) {
// Update the score.
CurrentScore += solution.getFixedScore();
// Assign fixed types to the type variables solved by this solution.
llvm::SmallPtrSet<TypeVariableType *, 4>
knownTypeVariables(TypeVariables.begin(), TypeVariables.end());
for (auto binding : solution.typeBindings) {
// If we haven't seen this type variable before, record it now.
if (knownTypeVariables.insert(binding.first).second)
TypeVariables.push_back(binding.first);
// If we don't already have a fixed type for this type variable,
// assign the fixed type from the solution.
if (!getFixedType(binding.first) && !binding.second->hasTypeVariable())
assignFixedType(binding.first, binding.second, /*updateScore=*/false);
}
// Register overload choices.
// FIXME: Copy these directly into some kind of partial solution?
for (auto overload : solution.overloadChoices) {
resolvedOverloadSets
= new (*this) ResolvedOverloadSetListItem{resolvedOverloadSets,
Type(),
overload.second.choice,
overload.first,
overload.second.openedFullType,
overload.second.openedType};
}
// Register constraint restrictions.
// FIXME: Copy these directly into some kind of partial solution?
for (auto restriction : solution.ConstraintRestrictions) {
ConstraintRestrictions.push_back(
std::make_tuple(restriction.first.first, restriction.first.second,
restriction.second));
}
// Register the solution's disjunction choices.
for (auto &choice : solution.DisjunctionChoices) {
DisjunctionChoices.push_back(choice);
}
// Register the solution's opened types.
for (const auto &opened : solution.OpenedTypes) {
OpenedTypes.push_back(opened);
}
// Register the solution's opened existential types.
for (const auto &openedExistential : solution.OpenedExistentialTypes) {
OpenedExistentialTypes.push_back(openedExistential);
}
// Register any fixes produced along this path.
Fixes.append(solution.Fixes.begin(), solution.Fixes.end());
}
/// \brief Restore the type variable bindings to what they were before
/// we attempted to solve this constraint system.
void ConstraintSystem::restoreTypeVariableBindings(unsigned numBindings) {
auto &savedBindings = *getSavedBindings();
std::for_each(savedBindings.rbegin(), savedBindings.rbegin() + numBindings,
[](SavedTypeVariableBinding &saved) {
saved.restore();
});
savedBindings.erase(savedBindings.end() - numBindings,
savedBindings.end());
}
/// \brief Enumerates all of the 'direct' supertypes of the given type.
///
/// The direct supertype S of a type T is a supertype of T (e.g., T < S)
/// such that there is no type U where T < U and U < S.
static SmallVector<Type, 4>
enumerateDirectSupertypes(TypeChecker &tc, Type type) {
SmallVector<Type, 4> result;
if (auto tupleTy = type->getAs<TupleType>()) {
// A tuple that can be constructed from a scalar has a value of that
// scalar type as its supertype.
// FIXME: There is a way more general property here, where we can drop
// one label from the tuple, maintaining the rest.
int scalarIdx = tupleTy->getElementForScalarInit();
if (scalarIdx >= 0) {
auto &elt = tupleTy->getElement(scalarIdx);
if (elt.isVararg()) // FIXME: Should we keep the name?
result.push_back(elt.getVarargBaseTy());
else if (elt.hasName())
result.push_back(elt.getType());
}
}
if (auto functionTy = type->getAs<FunctionType>()) {
// FIXME: Can weaken input type, but we really don't want to get in the
// business of strengthening the result type.
// An [autoclosure] function type can be viewed as scalar of the result
// type.
if (functionTy->isAutoClosure())
result.push_back(functionTy->getResult());
}
if (type->mayHaveSuperclass()) {
// FIXME: Can also weaken to the set of protocol constraints, but only
// if there are any protocols that the type conforms to but the superclass
// does not.
// If there is a superclass, it is a direct supertype.
if (auto superclass = tc.getSuperClassOf(type))
result.push_back(superclass);
}
if (auto lvalue = type->getAs<LValueType>())
result.push_back(lvalue->getObjectType());
if (auto iot = type->getAs<InOutType>())
result.push_back(iot->getObjectType());
// Try to unwrap implicitly unwrapped optional types.
if (auto objectType = type->getImplicitlyUnwrappedOptionalObjectType())
result.push_back(objectType);
// FIXME: lots of other cases to consider!
return result;
}
bool ConstraintSystem::simplify(bool ContinueAfterFailures) {
// While we have a constraint in the worklist, process it.
while (!ActiveConstraints.empty()) {
// Grab the next constraint from the worklist.
auto *constraint = &ActiveConstraints.front();
ActiveConstraints.pop_front();
assert(constraint->isActive() && "Worklist constraint is not active?");
// Simplify this constraint.
switch (simplifyConstraint(*constraint)) {
case SolutionKind::Error:
if (!failedConstraint) {
failedConstraint = constraint;
}
if (solverState)
solverState->retiredConstraints.push_front(constraint);
break;
case SolutionKind::Solved:
if (solverState) {
++solverState->NumSimplifiedConstraints;
// This constraint has already been solved; retire it.
solverState->retiredConstraints.push_front(constraint);
}
// Remove the constraint from the constraint graph.
CG.removeConstraint(constraint);
break;
case SolutionKind::Unsolved:
if (solverState)
++solverState->NumUnsimplifiedConstraints;
InactiveConstraints.push_back(constraint);
break;
}
// This constraint is not active. We delay this operation until
// after simplification to avoid re-insertion.
constraint->setActive(false);
// Check whether a constraint failed. If so, we're done.
if (failedConstraint && !ContinueAfterFailures) {
return true;
}
// If the current score is worse than the best score we've seen so far,
// there's no point in continuing. So don't.
if (worseThanBestSolution()) {
return true;
}
}
return false;
}
namespace {
/// \brief Truncate the given small vector to the given new size.
template<typename T>
void truncate(SmallVectorImpl<T> &vec, unsigned newSize) {
assert(newSize <= vec.size() && "Not a truncation!");
vec.erase(vec.begin() + newSize, vec.end());
}
} // end anonymous namespace
ConstraintSystem::SolverState::SolverState(ConstraintSystem &cs) : CS(cs) {
++NumSolutionAttempts;
SolutionAttempt = NumSolutionAttempts;
// If we're supposed to debug a specific constraint solver attempt,
// turn on debugging now.
ASTContext &ctx = CS.getTypeChecker().Context;
LangOptions &langOpts = ctx.LangOpts;
OldDebugConstraintSolver = langOpts.DebugConstraintSolver;
if (langOpts.DebugConstraintSolverAttempt &&
langOpts.DebugConstraintSolverAttempt == SolutionAttempt) {
langOpts.DebugConstraintSolver = true;
llvm::raw_ostream &dbgOut = ctx.TypeCheckerDebug->getStream();
dbgOut << "---Constraint system #" << SolutionAttempt << "---\n";
CS.print(dbgOut);
}
}
ConstraintSystem::SolverState::~SolverState() {
// Restore debugging state.
LangOptions &langOpts = CS.getTypeChecker().Context.LangOpts;
langOpts.DebugConstraintSolver = OldDebugConstraintSolver;
// Write our local statistics back to the overall statistics.
#define CS_STATISTIC(Name, Description) JOIN2(Overall,Name) += Name;
#include "ConstraintSolverStats.def"
// Update the "largest" statistics if this system is larger than the
// previous one.
// FIXME: This is not at all thread-safe.
if (NumStatesExplored > LargestNumStatesExplored.Value) {
LargestSolutionAttemptNumber.Value = SolutionAttempt-1;
++LargestSolutionAttemptNumber;
#define CS_STATISTIC(Name, Description) \
JOIN2(Largest,Name).Value = Name-1; \
++JOIN2(Largest,Name);
#include "ConstraintSolverStats.def"
}
}
ConstraintSystem::SolverScope::SolverScope(ConstraintSystem &cs)
: cs(cs), CGScope(cs.CG)
{
++cs.solverState->depth;
resolvedOverloadSets = cs.resolvedOverloadSets;
numTypeVariables = cs.TypeVariables.size();
numSavedBindings = cs.solverState->savedBindings.size();
firstRetired = cs.solverState->retiredConstraints.begin();
numConstraintRestrictions = cs.ConstraintRestrictions.size();
numFixes = cs.Fixes.size();
numDisjunctionChoices = cs.DisjunctionChoices.size();
numOpenedTypes = cs.OpenedTypes.size();
numOpenedExistentialTypes = cs.OpenedExistentialTypes.size();
numGeneratedConstraints = cs.solverState->generatedConstraints.size();
PreviousScore = cs.CurrentScore;
++cs.solverState->NumStatesExplored;
}
ConstraintSystem::SolverScope::~SolverScope() {
--cs.solverState->depth;
// Erase the end of various lists.
cs.resolvedOverloadSets = resolvedOverloadSets;
truncate(cs.TypeVariables, numTypeVariables);
// Restore bindings.
cs.restoreTypeVariableBindings(cs.solverState->savedBindings.size() -
numSavedBindings);
// Move any remaining active constraints into the inactive list.
while (!cs.ActiveConstraints.empty()) {
for (auto &constraint : cs.ActiveConstraints) {
constraint.setActive(false);
}
cs.InactiveConstraints.splice(cs.InactiveConstraints.end(),
cs.ActiveConstraints);
}
// Add the retired constraints back into circulation.
cs.InactiveConstraints.splice(cs.InactiveConstraints.end(),
cs.solverState->retiredConstraints,
cs.solverState->retiredConstraints.begin(),
firstRetired);
// Remove any constraints that were generated here.
auto &generatedConstraints = cs.solverState->generatedConstraints;
auto genStart = generatedConstraints.begin() + numGeneratedConstraints,
genEnd = generatedConstraints.end();
for (auto genI = genStart; genI != genEnd; ++genI) {
cs.InactiveConstraints.erase(ConstraintList::iterator(*genI));
}
generatedConstraints.erase(genStart, genEnd);
// Remove any constraint restrictions.
truncate(cs.ConstraintRestrictions, numConstraintRestrictions);
// Remove any fixes.
truncate(cs.Fixes, numFixes);
// Remove any disjunction choices.
truncate(cs.DisjunctionChoices, numDisjunctionChoices);
// Remove any opened types.
truncate(cs.OpenedTypes, numOpenedTypes);
// Remove any opened existential types.
truncate(cs.OpenedExistentialTypes, numOpenedExistentialTypes);
// Reset the previous score.
cs.CurrentScore = PreviousScore;
// Clear out other "failed" state.
cs.failedConstraint = nullptr;
}
namespace {
/// The kind of bindings that are permitted.
enum class AllowedBindingKind : unsigned char {
/// Only the exact type.
Exact,
/// Supertypes of the specified type.
Supertypes,
/// Subtypes of the specified type.
Subtypes
};
/// The kind of literal binding found.
enum class LiteralBindingKind : unsigned char {
None,
Collection,
Atom,
};
/// A potential binding from the type variable to a particular type,
/// along with information that can be used to construct related
/// bindings, e.g., the supertypes of a given type.
struct PotentialBinding {
/// The type to which the type variable can be bound.
Type BindingType;
/// The kind of bindings permitted.
AllowedBindingKind Kind;
/// The defaulted protocol associated with this binding.
Optional<ProtocolDecl *> DefaultedProtocol;
};
struct PotentialBindings {
/// The set of potential bindings.
SmallVector<PotentialBinding, 4> Bindings;
/// Whether this type variable is fully bound by one of its constraints.
bool FullyBound = false;
/// Whether the bindings of this type involve other type variables.
bool InvolvesTypeVariables = false;
/// Whether this type variable has literal bindings.
LiteralBindingKind LiteralBinding = LiteralBindingKind::None;
/// Whether this type variable is only bound above by existential types.
bool SubtypeOfExistentialType = false;
/// Determine whether the set of bindings is non-empty.
explicit operator bool() const {
return !Bindings.empty();
}
/// Compare two sets of bindings, where \c x < y indicates that
/// \c x is a better set of bindings that \c y.
friend bool operator<(const PotentialBindings &x,
const PotentialBindings &y) {
return std::make_tuple(x.FullyBound,
x.SubtypeOfExistentialType,
static_cast<unsigned char>(x.LiteralBinding),
x.InvolvesTypeVariables,
-x.Bindings.size())
< std::make_tuple(y.FullyBound,
y.SubtypeOfExistentialType,
static_cast<unsigned char>(y.LiteralBinding),
y.InvolvesTypeVariables,
-y.Bindings.size());
}
void foundLiteralBinding(ProtocolDecl *proto) {
switch (*proto->getKnownProtocolKind()) {
case KnownProtocolKind::DictionaryLiteralConvertible:
case KnownProtocolKind::ArrayLiteralConvertible:
case KnownProtocolKind::StringInterpolationConvertible:
LiteralBinding = LiteralBindingKind::Collection;
break;
default:
if (LiteralBinding != LiteralBindingKind::Collection)
LiteralBinding = LiteralBindingKind::Atom;
break;
}
}
};
}
/// Determine whether the given type variables occurs in the given type.
static bool typeVarOccursInType(ConstraintSystem &cs, TypeVariableType *typeVar,
Type type, bool &involvesOtherTypeVariables) {
SmallVector<TypeVariableType *, 4> typeVars;
type->getTypeVariables(typeVars);
bool result = false;
for (auto referencedTypeVar : typeVars) {
if (cs.getRepresentative(referencedTypeVar) == typeVar) {
result = true;
if (involvesOtherTypeVariables)
break;
continue;
}
involvesOtherTypeVariables = true;
}
return result;
}
/// \brief Return whether a relational constraint between a type variable and a
/// trivial wrapper type (autoclosure, unary tuple) should result in the type
/// variable being potentially bound to the value type, as opposed to the
/// wrapper type.
static bool shouldBindToValueType(Constraint *constraint)
{
switch (constraint->getKind()) {
case ConstraintKind::OperatorArgumentConversion:
case ConstraintKind::OperatorArgumentTupleConversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::ArgumentTupleConversion:
case ConstraintKind::Conversion:
case ConstraintKind::ExplicitConversion:
case ConstraintKind::Subtype:
return true;
case ConstraintKind::Bind:
case ConstraintKind::Equal:
case ConstraintKind::BindParam:
case ConstraintKind::ConformsTo:
case ConstraintKind::CheckedCast:
case ConstraintKind::SelfObjectOfProtocol:
case ConstraintKind::ApplicableFunction:
case ConstraintKind::BindOverload:
case ConstraintKind::OptionalObject:
return false;
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::ValueMember:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::TypeMember:
case ConstraintKind::Archetype:
case ConstraintKind::Class:
case ConstraintKind::BridgedToObjectiveC:
case ConstraintKind::Defaultable:
case ConstraintKind::Disjunction:
llvm_unreachable("shouldBindToValueType() may only be called on "
"relational constraints");
}
}
/// \brief Retrieve the set of potential type bindings for the given
/// representative type variable, along with flags indicating whether
/// those types should be opened.
static PotentialBindings getPotentialBindings(ConstraintSystem &cs,
TypeVariableType *typeVar) {
assert(typeVar->getImpl().getRepresentative(nullptr) == typeVar &&
"not a representative");
assert(!typeVar->getImpl().getFixedType(nullptr) && "has a fixed type");
// Gather the constraints associated with this type variable.
SmallVector<Constraint *, 8> constraints;
llvm::SmallPtrSet<Constraint *, 4> visitedConstraints;
cs.getConstraintGraph().gatherConstraints(typeVar, constraints);
// Consider each of the constraints related to this type variable.
PotentialBindings result;
llvm::SmallPtrSet<CanType, 4> exactTypes;
llvm::SmallPtrSet<ProtocolDecl *, 4> literalProtocols;
bool hasDefaultableConstraint = false;
auto &tc = cs.getTypeChecker();
for (auto constraint : constraints) {
// Only visit each constraint once.
if (!visitedConstraints.insert(constraint).second)
continue;
switch (constraint->getKind()) {
case ConstraintKind::Bind:
case ConstraintKind::Equal:
case ConstraintKind::BindParam:
case ConstraintKind::Subtype:
case ConstraintKind::Conversion:
case ConstraintKind::ExplicitConversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::ArgumentTupleConversion:
case ConstraintKind::OperatorArgumentTupleConversion:
case ConstraintKind::OperatorArgumentConversion:
case ConstraintKind::OptionalObject:
// Relational constraints: break out to look for types above/below.
break;
case ConstraintKind::CheckedCast:
// FIXME: Relational constraints for which we could perhaps do better
// than the default.
break;
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::Archetype:
case ConstraintKind::Class:
case ConstraintKind::BridgedToObjectiveC:
// Constraints from which we can't do anything.
// FIXME: Record this somehow?
continue;
case ConstraintKind::Defaultable:
// Do these in a separate pass.
hasDefaultableConstraint = true;
continue;
case ConstraintKind::Disjunction:
// FIXME: Recurse into these constraints to see whether this
// type variable is fully bound by any of them.
result.InvolvesTypeVariables = true;
continue;
case ConstraintKind::ConformsTo:
case ConstraintKind::SelfObjectOfProtocol: {
// FIXME: Can we always assume that the type variable is the lower bound?
TypeVariableType *lowerTypeVar = nullptr;
cs.getFixedTypeRecursive(constraint->getFirstType(), lowerTypeVar,
/*wantRValue=*/false);
if (lowerTypeVar != typeVar) {
continue;
}
// If there is a default literal type for this protocol, it's a
// potential binding.
auto defaultType = tc.getDefaultType(constraint->getProtocol(), cs.DC);
if (!defaultType)
continue;
// Note that we have a literal constraint with this protocol.
literalProtocols.insert(constraint->getProtocol());
// Handle unspecialized types directly.
if (!defaultType->isUnspecializedGeneric()) {
if (!exactTypes.insert(defaultType->getCanonicalType()).second)
continue;
result.foundLiteralBinding(constraint->getProtocol());
result.Bindings.push_back({defaultType, AllowedBindingKind::Subtypes,
constraint->getProtocol()});
continue;
}
// For generic literal types, check whether we already have a
// specialization of this generic within our list.
// FIXME: This assumes that, e.g., the default literal
// int/float/char/string types are never generic.
auto nominal = defaultType->getAnyNominal();
if (!nominal)
continue;
bool matched = false;
for (auto exactType : exactTypes) {
if (auto exactNominal = exactType->getAnyNominal()) {
// FIXME: Check parents?
if (nominal == exactNominal) {
matched = true;
break;
}
}
}
if (!matched) {
result.foundLiteralBinding(constraint->getProtocol());
exactTypes.insert(defaultType->getCanonicalType());
result.Bindings.push_back({defaultType, AllowedBindingKind::Subtypes,
constraint->getProtocol()});
}
continue;
}
case ConstraintKind::ApplicableFunction:
case ConstraintKind::BindOverload: {
// If this variable is in the left-hand side, it is fully bound.
// FIXME: Can we avoid simplification here by walking the graph? Is it
// worthwhile?
if (typeVarOccursInType(cs, typeVar,
cs.simplifyType(constraint->getFirstType()),
result.InvolvesTypeVariables)) {
result.FullyBound = true;
}
continue;
}
case ConstraintKind::ValueMember:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::TypeMember:
// If our type variable shows up in the base type, there's
// nothing to do.
// FIXME: Can we avoid simplification here?
if (typeVarOccursInType(cs, typeVar,
cs.simplifyType(constraint->getFirstType()),
result.InvolvesTypeVariables)) {
continue;
}
// If the type variable is in the list of member type
// variables, it is fully bound.
// FIXME: Can we avoid simplification here?
if (typeVarOccursInType(cs, typeVar,
cs.simplifyType(constraint->getSecondType()),
result.InvolvesTypeVariables)) {
result.FullyBound = true;
}
continue;
}
// Handle relational constraints.
assert(constraint->getClassification()
== ConstraintClassification::Relational &&
"only relational constraints handled here");
auto first = cs.simplifyType(constraint->getFirstType());
auto second = cs.simplifyType(constraint->getSecondType());
Type type;
AllowedBindingKind kind;
if (first->getAs<TypeVariableType>() == typeVar) {
// Upper bound for this type variable.
type = second;
kind = AllowedBindingKind::Subtypes;
} else if (second->getAs<TypeVariableType>() == typeVar) {
// Lower bound for this type variable.
type = first;
kind = AllowedBindingKind::Supertypes;
} else {
// Can't infer anything.
if (!result.InvolvesTypeVariables)
typeVarOccursInType(cs, typeVar, first, result.InvolvesTypeVariables);
if (!result.InvolvesTypeVariables)
typeVarOccursInType(cs, typeVar, second, result.InvolvesTypeVariables);
continue;
}
// Check whether we can perform this binding.
// FIXME: this has a super-inefficient extraneous simplifyType() in it.
if (auto boundType = checkTypeOfBinding(cs, typeVar, type)) {
type = *boundType;
if (type->hasTypeVariable())
result.InvolvesTypeVariables = true;
} else {
result.InvolvesTypeVariables = true;
continue;
}
// Don't deduce autoclosure types or single-element, non-variadic
// tuples.
if (shouldBindToValueType(constraint)) {
if (auto funcTy = type->getAs<FunctionType>()) {
if (funcTy->isAutoClosure())
type = funcTy->getResult();
}
if (auto tupleTy = type->getAs<TupleType>()) {
if (tupleTy->getNumElements() == 1 &&
!tupleTy->getElement(0).isVararg())
type = tupleTy->getElementType(0);
}
}
// Make sure we aren't trying to equate type variables with different
// lvalue-binding rules.
if (auto otherTypeVar = type->getAs<TypeVariableType>()) {
if (typeVar->getImpl().canBindToLValue() !=
otherTypeVar->getImpl().canBindToLValue())
continue;
}
// BindParam constraints are not reflexive and must be treated specially.
if (constraint->getKind() == ConstraintKind::BindParam) {
if (kind == AllowedBindingKind::Subtypes) {
if (auto *lvt = type->getAs<LValueType>()) {
type = InOutType::get(lvt->getObjectType());
}
} else if (kind == AllowedBindingKind::Supertypes) {
if (auto *iot = type->getAs<InOutType>()) {
type = LValueType::get(iot->getObjectType());
}
}
kind = AllowedBindingKind::Exact;
}
if (exactTypes.insert(type->getCanonicalType()).second)
result.Bindings.push_back({type, kind, None});
}
// If we have any literal constraints, check whether there is already a
// binding that provides a type that conforms to that literal protocol. In
// such cases, remove the default binding suggestion because the existing
// suggestion is better.
if (!literalProtocols.empty()) {
SmallPtrSet<ProtocolDecl *, 5> coveredLiteralProtocols;
for (auto &binding : result.Bindings) {
// Skip defaulted-protocol constraints.
if (binding.DefaultedProtocol)
continue;
Type testType;
switch (binding.Kind) {
case AllowedBindingKind::Exact:
testType = binding.BindingType;
break;
case AllowedBindingKind::Subtypes:
case AllowedBindingKind::Supertypes:
testType = binding.BindingType->getRValueType();
break;
}
// Check each non-covered literal protocol to determine which ones
bool updatedBindingType = false;
for (auto proto : literalProtocols) {
do {
// If the type conforms to this protocol, we're covered.
if (tc.conformsToProtocol(testType, proto, cs.DC,
ConformanceCheckFlags::InExpression)) {
coveredLiteralProtocols.insert(proto);
break;
}
// If we're allowed to bind to subtypes, look through optionals.
// FIXME: This is really crappy special case of computing a reasonable
// result based on the given constraints.
if (binding.Kind == AllowedBindingKind::Subtypes) {
if (auto objTy = testType->getAnyOptionalObjectType()) {
updatedBindingType = true;
testType = objTy;
continue;
}
}
updatedBindingType = false;
break;
} while (true);
}
if (updatedBindingType)
binding.BindingType = testType;
}
// For any literal type that has been covered, remove the default literal
// type.
if (!coveredLiteralProtocols.empty()) {
result.Bindings.erase(
std::remove_if(result.Bindings.begin(),
result.Bindings.end(),
[&](PotentialBinding &binding) {
return binding.DefaultedProtocol &&
coveredLiteralProtocols.count(*binding.DefaultedProtocol) > 0;
}),
result.Bindings.end());
}
}
// If we haven't found any other bindings yet, go ahead and consider
// the defaulting constraints.
if (result.Bindings.empty() && hasDefaultableConstraint) {
for (Constraint *constraint : constraints) {
if (constraint->getKind() != ConstraintKind::Defaultable)
continue;
result.Bindings.push_back({constraint->getSecondType(),
AllowedBindingKind::Exact,
None});
}
}
// Determine if the bindings only constrain the type variable from above with
// an existential type; such a binding is not very helpful because it's
// impossible to enumerate the existential type's subtypes.
result.SubtypeOfExistentialType =
std::all_of(result.Bindings.begin(), result.Bindings.end(),
[](const PotentialBinding &binding) {
return binding.BindingType->isExistentialType() &&
binding.Kind == AllowedBindingKind::Subtypes;
});
return result;
}
void ConstraintSystem::getComputedBindings(TypeVariableType *tvt,
SmallVectorImpl<Type> &bindings) {
// If the type variable is fixed, look no further.
if (auto fixedType = tvt->getImpl().getFixedType(nullptr)) {
bindings.push_back(fixedType);
return;
}
PotentialBindings potentialBindings = getPotentialBindings(*this, tvt);
for (auto binding : potentialBindings.Bindings) {
bindings.push_back(binding.BindingType);
}
}