forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstraintSystem.cpp
1616 lines (1390 loc) · 61.1 KB
/
ConstraintSystem.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
//===--- ConstraintSystem.cpp - Constraint-based Type Checking ------------===//
//
// 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-based type checker, anchored by the
// \c ConstraintSystem class, which provides type checking and type
// inference for expressions.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "ConstraintGraph.h"
#include "swift/AST/ArchetypeBuilder.h"
#include "llvm/ADT/SmallString.h"
using namespace swift;
using namespace constraints;
ConstraintSystem::ConstraintSystem(TypeChecker &tc, DeclContext *dc,
ConstraintSystemOptions options)
: TC(tc), DC(dc), Options(options),
Arena(tc.Context, Allocator,
[&](TypeVariableType *baseTypeVar, AssociatedTypeDecl *assocType) {
return getMemberType(baseTypeVar, assocType,
ConstraintLocatorBuilder(nullptr),
/*options=*/0);
}),
CG(*new ConstraintGraph(*this))
{
assert(DC && "context required");
}
ConstraintSystem::~ConstraintSystem() {
delete &CG;
}
bool ConstraintSystem::hasFreeTypeVariables() {
// Look for any free type variables.
for (auto tv : TypeVariables) {
if (!tv->getImpl().hasRepresentativeOrFixed()) {
return true;
}
}
return false;
}
void ConstraintSystem::addTypeVariable(TypeVariableType *typeVar) {
TypeVariables.push_back(typeVar);
// Notify the constraint graph.
(void)CG[typeVar];
}
void ConstraintSystem::mergeEquivalenceClasses(TypeVariableType *typeVar1,
TypeVariableType *typeVar2) {
assert(typeVar1 == getRepresentative(typeVar1) &&
"typeVar1 is not the representative");
assert(typeVar2 == getRepresentative(typeVar2) &&
"typeVar2 is not the representative");
assert(typeVar1 != typeVar2 && "cannot merge type with itself");
typeVar1->getImpl().mergeEquivalenceClasses(typeVar2, getSavedBindings());
// Merge nodes in the constraint graph.
CG.mergeNodes(typeVar1, typeVar2);
addTypeVariableConstraintsToWorkList(typeVar1);
}
void ConstraintSystem::assignFixedType(TypeVariableType *typeVar, Type type,
bool updateState) {
// If the type to be fixed is an optional type that wraps the type parameter
// itself, we do not want to go through with the assignment. To do so would
// force the type variable to be adjacent to itself.
if (auto optValueType = type->getOptionalObjectType()) {
if (optValueType->isEqual(typeVar))
return;
}
typeVar->getImpl().assignFixedType(type, getSavedBindings());
if (!updateState)
return;
if (!type->is<TypeVariableType>()) {
// If this type variable represents a literal, check whether we picked the
// default literal type. First, find the corresponding protocol.
ProtocolDecl *literalProtocol = nullptr;
// If we have the constraint graph, we can check all type variables in
// the equivalence class. This is the More Correct path.
// FIXME: Eliminate the less-correct path.
auto typeVarRep = getRepresentative(typeVar);
for (auto tv : CG[typeVarRep].getEquivalenceClass()) {
auto locator = tv->getImpl().getLocator();
if (!locator || !locator->getPath().empty())
continue;
auto anchor = locator->getAnchor();
if (!anchor)
continue;
literalProtocol = TC.getLiteralProtocol(anchor);
if (literalProtocol)
break;
}
// If the protocol has a default type, check it.
if (literalProtocol) {
if (auto defaultType = TC.getDefaultType(literalProtocol, DC)) {
// Check whether the nominal types match. This makes sure that we
// properly handle Array vs. Array<T>.
if (defaultType->getAnyNominal() != type->getAnyNominal())
increaseScore(SK_NonDefaultLiteral);
}
}
}
// Notify the constraint graph.
CG.bindTypeVariable(typeVar, type);
addTypeVariableConstraintsToWorkList(typeVar);
}
void ConstraintSystem::setMustBeMaterializableRecursive(Type type)
{
assert(type->isMaterializable() &&
"argument to setMustBeMaterializableRecursive may not be inherently "
"non-materializable");
TypeVariableType *typeVar = nullptr;
type = getFixedTypeRecursive(type, typeVar, /*wantRValue=*/false);
if (typeVar) {
typeVar->getImpl().setMustBeMaterializable(getSavedBindings());
} else if (auto *tupleTy = type->getAs<TupleType>()) {
for (auto elt : tupleTy->getElementTypes()) {
setMustBeMaterializableRecursive(elt);
}
}
}
void ConstraintSystem::addTypeVariableConstraintsToWorkList(
TypeVariableType *typeVar) {
// Gather the constraints affected by a change to this type variable.
SmallVector<Constraint *, 8> constraints;
CG.gatherConstraints(typeVar, constraints);
// Add any constraints that aren't already active to the worklist.
for (auto constraint : constraints) {
if (!constraint->isActive()) {
ActiveConstraints.splice(ActiveConstraints.end(),
InactiveConstraints, constraint);
constraint->setActive(true);
}
}
}
/// Retrieve a uniqued selector ID for the given declaration.
static std::pair<unsigned, CanType>
getDynamicResultSignature(ValueDecl *decl,
llvm::StringMap<unsigned> &selectors) {
llvm::SmallString<32> buffer;
StringRef selector;
Type type;
if (auto func = dyn_cast<FuncDecl>(decl)) {
// Handle functions.
// FIXME: Use ObjCSelector here!
selector = func->getObjCSelector().getString(buffer);
type = decl->getType()->castTo<AnyFunctionType>()->getResult();
// Append a '+' for static methods, '-' for instance methods. This
// distinguishes methods with a given name from properties that
// might have the same name.
if (func->isStatic()) {
buffer += '+';
} else {
buffer += '-';
}
selector = buffer.str();
} else if (auto asd = dyn_cast<AbstractStorageDecl>(decl)) {
// Handle properties and subscripts. Only the getter matters.
selector = asd->getObjCGetterSelector().getString(buffer);
type = asd->getType();
} else if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
// Handle constructors.
selector = ctor->getObjCSelector().getString(buffer);
type = decl->getType()->castTo<AnyFunctionType>()->getResult();
} else {
llvm_unreachable("Dynamic lookup found a non-[objc] result");
}
// Look for this selector in the table. If we find it, we're done.
auto known = selectors.find(selector);
if (known != selectors.end())
return { known->second, type->getCanonicalType() };
// Add this selector to the table.
unsigned result = selectors.size();
selectors[selector] = result;
return { result, type->getCanonicalType() };
}
LookupResult &ConstraintSystem::lookupMember(Type base, DeclName name) {
base = base->getCanonicalType();
// Check whether we've already performed this lookup.
auto knownMember = MemberLookups.find({base, name});
if (knownMember != MemberLookups.end())
return *knownMember->second;
// Lookup the member.
NameLookupOptions lookupOptions = defaultMemberLookupOptions;
if (isa<AbstractFunctionDecl>(DC))
lookupOptions |= NameLookupFlags::KnownPrivate;
MemberLookups[{base, name}] = None;
auto lookup = TC.lookupMember(DC, base, name, lookupOptions);
auto &result = MemberLookups[{base, name}];
result = std::move(lookup);
// If we aren't performing dynamic lookup, we're done.
auto instanceTy = base->getRValueType();
if (auto metaTy = instanceTy->getAs<AnyMetatypeType>())
instanceTy = metaTy->getInstanceType();
auto protoTy = instanceTy->getAs<ProtocolType>();
if (!*result ||
!protoTy ||
!protoTy->getDecl()->isSpecificProtocol(
KnownProtocolKind::AnyObject))
return *result;
// We are performing dynamic lookup. Filter out redundant results early.
llvm::DenseSet<std::pair<unsigned, CanType>> known;
llvm::StringMap<unsigned> selectors;
result->filter([&](ValueDecl *decl) -> bool {
if (decl->isInvalid())
return false;
return known.insert(getDynamicResultSignature(decl, selectors)).second;
});
return *result;
}
ArrayRef<Type> ConstraintSystem::
getAlternativeLiteralTypes(KnownProtocolKind kind) {
unsigned index;
switch (kind) {
#define PROTOCOL_WITH_NAME(Id, Name) \
case KnownProtocolKind::Id: llvm_unreachable("Not a literal protocol");
#define LITERAL_CONVERTIBLE_PROTOCOL_WITH_NAME(Id, Name)
#include "swift/AST/KnownProtocols.def"
case KnownProtocolKind::ArrayLiteralConvertible: index = 0; break;
case KnownProtocolKind::DictionaryLiteralConvertible:index = 1; break;
case KnownProtocolKind::ExtendedGraphemeClusterLiteralConvertible: index = 2;
break;
case KnownProtocolKind::FloatLiteralConvertible: index = 3; break;
case KnownProtocolKind::IntegerLiteralConvertible: index = 4; break;
case KnownProtocolKind::StringInterpolationConvertible: index = 5; break;
case KnownProtocolKind::StringLiteralConvertible: index = 6; break;
case KnownProtocolKind::NilLiteralConvertible: index = 7; break;
case KnownProtocolKind::BooleanLiteralConvertible: index = 8; break;
case KnownProtocolKind::UnicodeScalarLiteralConvertible: index = 9; break;
case KnownProtocolKind::ColorLiteralConvertible: index = 10; break;
case KnownProtocolKind::ImageLiteralConvertible: index = 11; break;
case KnownProtocolKind::FileReferenceLiteralConvertible: index = 12; break;
}
// If we already looked for alternative literal types, return those results.
if (AlternativeLiteralTypes[index])
return *AlternativeLiteralTypes[index];
SmallVector<Type, 4> types;
// If the default literal type is bridged to a class type, add the class type.
if (auto proto = TC.Context.getProtocol(kind)) {
if (auto defaultType = TC.getDefaultType(proto, DC)) {
if (auto bridgedClassType = TC.getBridgedToObjC(DC, defaultType)) {
types.push_back(bridgedClassType);
}
}
}
// Some literal kinds are related.
switch (kind) {
#define PROTOCOL_WITH_NAME(Id, Name) \
case KnownProtocolKind::Id: llvm_unreachable("Not a literal protocol");
#define LITERAL_CONVERTIBLE_PROTOCOL_WITH_NAME(Id, Name)
#include "swift/AST/KnownProtocols.def"
case KnownProtocolKind::ArrayLiteralConvertible:
case KnownProtocolKind::DictionaryLiteralConvertible:
break;
case KnownProtocolKind::ExtendedGraphemeClusterLiteralConvertible:
case KnownProtocolKind::StringInterpolationConvertible:
case KnownProtocolKind::StringLiteralConvertible:
case KnownProtocolKind::UnicodeScalarLiteralConvertible:
break;
case KnownProtocolKind::IntegerLiteralConvertible:
// Integer literals can be treated as floating point literals.
if (auto floatProto = TC.Context.getProtocol(
KnownProtocolKind::FloatLiteralConvertible)) {
if (auto defaultType = TC.getDefaultType(floatProto, DC)) {
types.push_back(defaultType);
}
}
break;
case KnownProtocolKind::FloatLiteralConvertible:
break;
case KnownProtocolKind::NilLiteralConvertible:
case KnownProtocolKind::BooleanLiteralConvertible:
break;
case KnownProtocolKind::ColorLiteralConvertible:
case KnownProtocolKind::ImageLiteralConvertible:
case KnownProtocolKind::FileReferenceLiteralConvertible:
break;
}
AlternativeLiteralTypes[index] = allocateCopy(types);
return *AlternativeLiteralTypes[index];
}
ConstraintLocator *ConstraintSystem::getConstraintLocator(
Expr *anchor,
ArrayRef<ConstraintLocator::PathElement> path,
unsigned summaryFlags) {
assert(summaryFlags == ConstraintLocator::getSummaryFlagsForPath(path));
// Check whether a locator with this anchor + path already exists.
llvm::FoldingSetNodeID id;
ConstraintLocator::Profile(id, anchor, path);
void *insertPos = nullptr;
auto locator = ConstraintLocators.FindNodeOrInsertPos(id, insertPos);
if (locator)
return locator;
// Allocate a new locator and add it to the set.
locator = ConstraintLocator::create(getAllocator(), anchor, path,
summaryFlags);
ConstraintLocators.InsertNode(locator, insertPos);
return locator;
}
ConstraintLocator *ConstraintSystem::getConstraintLocator(
const ConstraintLocatorBuilder &builder) {
// If the builder has an empty path, just extract its base locator.
if (builder.hasEmptyPath()) {
return builder.getBaseLocator();
}
// We have to build a new locator. Extract the paths from the builder.
SmallVector<LocatorPathElt, 4> path;
Expr *anchor = builder.getLocatorParts(path);
return getConstraintLocator(anchor, path, builder.getSummaryFlags());
}
bool ConstraintSystem::addConstraint(Constraint *constraint,
bool isExternallySolved,
bool simplifyExisting) {
switch (simplifyConstraint(*constraint)) {
case SolutionKind::Error:
if (!failedConstraint) {
failedConstraint = constraint;
}
if (solverState) {
solverState->retiredConstraints.push_front(constraint);
if (!simplifyExisting) {
solverState->generatedConstraints.push_back(constraint);
}
}
return false;
case SolutionKind::Solved:
// This constraint has already been solved; there is nothing more
// to do.
// Record solved constraint.
if (solverState) {
solverState->retiredConstraints.push_front(constraint);
if (!simplifyExisting)
solverState->generatedConstraints.push_back(constraint);
}
// Remove the constraint from the constraint graph.
if (simplifyExisting)
CG.removeConstraint(constraint);
return true;
case SolutionKind::Unsolved:
// We couldn't solve this constraint; add it to the pile.
if (!isExternallySolved) {
InactiveConstraints.push_back(constraint);
}
// Add this constraint to the constraint graph.
if (!simplifyExisting)
CG.addConstraint(constraint);
if (!simplifyExisting && solverState) {
solverState->generatedConstraints.push_back(constraint);
}
return false;
}
}
TypeVariableType *
ConstraintSystem::getMemberType(TypeVariableType *baseTypeVar,
AssociatedTypeDecl *assocType,
ConstraintLocatorBuilder locator,
unsigned options) {
return CG.getMemberType(baseTypeVar, assocType->getName(), [&]() {
// FIXME: Premature associated type -> identifier mapping. We should
// retain the associated type throughout.
auto loc = getConstraintLocator(locator);
auto memberTypeVar = createTypeVariable(loc, options);
addConstraint(Constraint::create(*this, ConstraintKind::TypeMember,
baseTypeVar, memberTypeVar,
assocType->getName(), loc));
return memberTypeVar;
});
}
/// Check whether this is the depth 0, index 0 generic parameter, which is
/// used for the 'Self' type of a protocol.
static bool isProtocolSelfType(Type type) {
auto gp = type->getAs<GenericTypeParamType>();
if (!gp)
return false;
return gp->getDepth() == 0 && gp->getIndex() == 0;
}
namespace {
/// Function object that retrieves a type variable corresponding to the
/// given dependent type.
class GetTypeVariable {
ConstraintSystem &CS;
ConstraintGraph &CG;
ConstraintLocatorBuilder &Locator;
DependentTypeOpener *Opener;
public:
GetTypeVariable(ConstraintSystem &cs,
ConstraintLocatorBuilder &locator,
DependentTypeOpener *opener)
: CS(cs), CG(CS.getConstraintGraph()), Locator(locator), Opener(opener) {}
TypeVariableType *operator()(Type base, AssociatedTypeDecl *member) {
// FIXME: Premature associated type -> identifier mapping. We should
// retain the associated type throughout.
auto baseTypeVar = base->castTo<TypeVariableType>();
return CG.getMemberType(baseTypeVar, member->getName(),
[&]() -> TypeVariableType* {
auto implArchetype = baseTypeVar->getImpl().getArchetype();
if (!implArchetype) {
// If the base type variable doesn't have an associated archetype,
// just form the member constraint.
// FIXME: Additional requirements?
auto locator = CS.getConstraintLocator(
Locator.withPathElement(member));
auto memberTypeVar = CS.createTypeVariable(locator,
TVO_PrefersSubtypeBinding);
CS.addConstraint(Constraint::create(CS, ConstraintKind::TypeMember,
baseTypeVar, memberTypeVar,
member->getName(), locator));
return memberTypeVar;
}
ArchetypeType::NestedType nestedType;
ArchetypeType* archetype = nullptr;
if (implArchetype->hasNestedType(member->getName())) {
nestedType = implArchetype->getNestedType(member->getName());
archetype = nestedType.getValue()->getAs<ArchetypeType>();
} else if (implArchetype->isSelfDerived()) {
archetype = implArchetype;
}
ConstraintLocator *locator;
if (archetype) {
locator = CS.getConstraintLocator(
Locator.withPathElement(LocatorPathElt(archetype)));
} else {
// FIXME: Occurs when the nested type is a concrete type,
// in which case it's quite silly to create a type variable at all.
locator = CS.getConstraintLocator(Locator.withPathElement(member));
}
auto memberTypeVar = CS.createTypeVariable(locator,
TVO_PrefersSubtypeBinding);
// Determine whether we should bind the new type variable as a
// member of the base type variable, or let it float.
Type replacementType;
bool shouldBindMember = true;
if (Opener) {
shouldBindMember = Opener->shouldBindAssociatedType(base, baseTypeVar,
member,
memberTypeVar,
replacementType);
}
// Bind the member's type variable as a type member of the base,
// if needed.
if (shouldBindMember) {
CS.addConstraint(Constraint::create(CS, ConstraintKind::TypeMember,
baseTypeVar, memberTypeVar,
member->getName(), locator));
}
// If we have a replacement type, bind the member's type
// variable to it.
if (replacementType)
CS.addConstraint(ConstraintKind::Bind, memberTypeVar,
replacementType, locator);
if (!archetype) {
// If the nested type is not an archetype (because it was constrained
// to a concrete type by a requirement), return the fresh type
// variable now, and let binding occur during overload resolution.
return memberTypeVar;
}
// FIXME: Would be better to walk the requirements of the protocol
// of which the associated type is a member.
if (auto superclass = member->getSuperclass()) {
CS.addConstraint(ConstraintKind::Subtype, memberTypeVar,
superclass, locator);
}
for (auto proto : member->getArchetype()->getConformsTo()) {
CS.addConstraint(ConstraintKind::ConformsTo, memberTypeVar,
proto->getDeclaredType(), locator);
}
return memberTypeVar;
});
}
};
/// Function object that replaces all occurrences of archetypes and
/// dependent types with type variables.
class ReplaceDependentTypes {
ConstraintSystem &cs;
DeclContext *dc;
bool skipProtocolSelfConstraint;
DependentTypeOpener *opener;
ConstraintLocatorBuilder &locator;
llvm::DenseMap<CanType, TypeVariableType *> &replacements;
GetTypeVariable &getTypeVariable;
public:
ReplaceDependentTypes(
ConstraintSystem &cs,
DeclContext *dc,
bool skipProtocolSelfConstraint,
DependentTypeOpener *opener,
ConstraintLocatorBuilder &locator,
llvm::DenseMap<CanType, TypeVariableType *> &replacements,
GetTypeVariable &getTypeVariable)
: cs(cs), dc(dc), skipProtocolSelfConstraint(skipProtocolSelfConstraint),
opener(opener), locator(locator), replacements(replacements),
getTypeVariable(getTypeVariable) { }
Type operator()(Type type) {
assert(!type->is<PolymorphicFunctionType>() && "Shouldn't get here");
// Preserve parens when opening types.
if (isa<ParenType>(type.getPointer())) {
return type;
}
// Replace archetypes with fresh type variables.
if (auto archetype = type->getAs<ArchetypeType>()) {
auto known = replacements.find(archetype->getCanonicalType());
if (known != replacements.end())
return known->second;
return archetype;
}
// Replace a generic type parameter with its corresponding type variable.
if (auto genericParam = type->getAs<GenericTypeParamType>()) {
if (opener) {
// If we have a mapping for this type parameter, there's nothing else to do.
if (Type replacement = opener->mapGenericTypeParamType(genericParam)){
return replacement;
}
}
auto known = replacements.find(genericParam->getCanonicalType());
if (known == replacements.end())
return cs.createTypeVariable(nullptr, TVO_PrefersSubtypeBinding);
return known->second;
}
// Replace a dependent member with a fresh type variable and make it a
// member of its base type.
if (auto dependentMember = type->getAs<DependentMemberType>()) {
if (opener) {
// If we have a mapping for this type parameter, there's nothing else to do.
if (Type replacement
= opener->mapDependentMemberType(dependentMember)) {
return replacement;
}
}
// Check whether we've already dealt with this dependent member.
auto known = replacements.find(dependentMember->getCanonicalType());
if (known != replacements.end())
return known->second;
// Replace archetypes in the base type.
if (auto base =
((*this)(dependentMember->getBase()))->getAs<TypeVariableType>()) {
auto result = getTypeVariable(base, dependentMember->getAssocType());
replacements[dependentMember->getCanonicalType()] = result;
return result;
}
}
// Create type variables for all of the parameters in a generic function
// type.
if (auto genericFn = type->getAs<GenericFunctionType>()) {
// Open up the generic parameters and requirements.
cs.openGeneric(dc,
genericFn->getGenericParams(),
genericFn->getRequirements(),
skipProtocolSelfConstraint,
opener,
locator,
replacements);
// Transform the input and output types.
Type inputTy = genericFn->getInput().transform(*this);
if (!inputTy)
return Type();
Type resultTy = genericFn->getResult().transform(*this);
if (!resultTy)
return Type();
// Build the resulting (non-generic) function type.
return FunctionType::get(inputTy, resultTy,
FunctionType::ExtInfo().
withThrows(genericFn->throws()));
}
// Open up unbound generic types, turning them into bound generic
// types with type variables for each parameter.
if (auto unbound = type->getAs<UnboundGenericType>()) {
auto parentTy = unbound->getParent();
if (parentTy)
parentTy = parentTy.transform(*this);
auto unboundDecl = unbound->getDecl();
if (unboundDecl->isInvalid())
return ErrorType::get(cs.getASTContext());
// Open up the generic type.
cs.openGeneric(unboundDecl,
unboundDecl->getGenericParamTypes(),
unboundDecl->getGenericRequirements(),
/*skipProtocolSelfConstraint=*/false,
opener,
locator,
replacements);
// Map the generic parameters to their corresponding type variables.
llvm::SmallVector<Type, 4> arguments;
for (auto gp : unboundDecl->getGenericParamTypes()) {
assert(replacements.count(gp->getCanonicalType()) &&
"Missing generic parameter?");
arguments.push_back(replacements[gp->getCanonicalType()]);
}
return BoundGenericType::get(unboundDecl, parentTy, arguments);
}
return type;
}
};
}
Type ConstraintSystem::openType(
Type startingType,
ConstraintLocatorBuilder locator,
llvm::DenseMap<CanType, TypeVariableType *> &replacements,
DeclContext *dc,
bool skipProtocolSelfConstraint,
DependentTypeOpener *opener) {
GetTypeVariable getTypeVariable{*this, locator, opener};
ReplaceDependentTypes replaceDependentTypes(*this, dc,
skipProtocolSelfConstraint,
opener,
locator,
replacements, getTypeVariable);
return startingType.transform(replaceDependentTypes);
}
bool ConstraintSystem::isArrayType(Type t) {
t = t->getDesugaredType();
// ArraySliceType<T> desugars to Array<T>.
if (isa<ArraySliceType>(t.getPointer()))
return true;
if (auto boundStruct = dyn_cast<BoundGenericStructType>(t.getPointer())) {
return boundStruct->getDecl() == TC.Context.getArrayDecl();
}
return false;
}
Optional<std::pair<Type, Type>> ConstraintSystem::isDictionaryType(Type type) {
if (auto boundStruct = type->getAs<BoundGenericStructType>()) {
if (boundStruct->getDecl() != TC.Context.getDictionaryDecl())
return None;
auto genericArgs = boundStruct->getGenericArgs();
return std::make_pair(genericArgs[0], genericArgs[1]);
}
return None;
}
bool ConstraintSystem::isSetType(Type type) {
if (auto boundStruct = type->getAs<BoundGenericStructType>()) {
return boundStruct->getDecl() == TC.Context.getSetDecl();
}
return false;
}
Type ConstraintSystem::openBindingType(Type type,
ConstraintLocatorBuilder locator,
DeclContext *dc) {
Type result = openType(type, locator, dc);
if (isArrayType(type)) {
auto boundStruct = cast<BoundGenericStructType>(type.getPointer());
if (auto replacement = getTypeChecker().getArraySliceType(
SourceLoc(), boundStruct->getGenericArgs()[0])) {
return replacement;
}
}
if (auto dict = isDictionaryType(type)) {
if (auto replacement = getTypeChecker().getDictionaryType(
SourceLoc(), dict->first, dict->second))
return replacement;
}
return result;
}
static Type getFixedTypeRecursiveHelper(ConstraintSystem &cs,
TypeVariableType *typeVar,
bool wantRValue) {
while (auto fixed = cs.getFixedType(typeVar)) {
if (wantRValue)
fixed = fixed->getRValueType();
typeVar = fixed->getAs<TypeVariableType>();
if (!typeVar)
return fixed;
}
return nullptr;
}
Type ConstraintSystem::getFixedTypeRecursive(Type type,
TypeVariableType *&typeVar,
bool wantRValue,
bool retainParens) {
if (wantRValue)
type = type->getRValueType();
if (retainParens) {
if (auto parenTy = dyn_cast<ParenType>(type.getPointer())) {
type = getFixedTypeRecursive(parenTy->getUnderlyingType(), typeVar,
wantRValue, retainParens);
return ParenType::get(getASTContext(), type);
}
}
auto desugar = type->getDesugaredType();
typeVar = desugar->getAs<TypeVariableType>();
if (typeVar) {
if (auto fixed = getFixedTypeRecursiveHelper(*this, typeVar, wantRValue)) {
type = fixed;
typeVar = nullptr;
}
}
return type;
}
void ConstraintSystem::recordOpenedTypes(
ConstraintLocatorBuilder locator,
const llvm::DenseMap<CanType, TypeVariableType *> &replacements) {
if (replacements.empty())
return;
// If the last path element is an archetype or associated type, ignore it.
SmallVector<LocatorPathElt, 2> pathElts;
Expr *anchor = locator.getLocatorParts(pathElts);
if (!pathElts.empty() &&
(pathElts.back().getKind() == ConstraintLocator::Archetype ||
pathElts.back().getKind() == ConstraintLocator::AssociatedType))
return;
// If the locator is empty, ignore it.
if (!anchor && pathElts.empty())
return;
ConstraintLocator *locatorPtr = getConstraintLocator(locator);
assert(locatorPtr && "No locator for opened types?");
assert(std::find_if(OpenedTypes.begin(), OpenedTypes.end(),
[&](const std::pair<ConstraintLocator *,
ArrayRef<OpenedType>> &entry) {
return entry.first == locatorPtr;
}) == OpenedTypes.end() &&
"already registered opened types for this locator");
OpenedType* openedTypes
= Allocator.Allocate<OpenedType>(replacements.size());
std::copy(replacements.begin(), replacements.end(), openedTypes);
OpenedTypes.push_back({ locatorPtr,
llvm::makeArrayRef(openedTypes,
replacements.size()) });
}
std::pair<Type, Type>
ConstraintSystem::getTypeOfReference(ValueDecl *value,
bool isTypeReference,
bool isSpecialized,
ConstraintLocatorBuilder locator,
const DeclRefExpr *base,
DependentTypeOpener *opener) {
llvm::DenseMap<CanType, TypeVariableType *> replacements;
if (value->getDeclContext()->isTypeContext() && isa<FuncDecl>(value)) {
// Unqualified lookup can find operator names within nominal types.
auto func = cast<FuncDecl>(value);
assert(func->isOperator() && "Lookup should only find operators");
auto openedType = openType(func->getInterfaceType(), locator,
replacements, func, false, opener);
auto openedFnType = openedType->castTo<FunctionType>();
// If this is a method whose result type is dynamic Self, replace
// DynamicSelf with the actual object type.
if (func->hasDynamicSelf()) {
Type selfTy = openedFnType->getInput()->getRValueInstanceType();
openedType = openedType->replaceCovariantResultType(
selfTy,
func->getNumParamPatterns());
openedFnType = openedType->castTo<FunctionType>();
}
// The 'Self' type must be bound to an archetype.
// FIXME: We eventually want to loosen this constraint, to allow us
// to find operator functions both in classes and in protocols to which
// a class conforms (if there's a default implementation).
addArchetypeConstraint(openedFnType->getInput()->getRValueInstanceType(),
getConstraintLocator(locator));
// If we opened up any type variables, record the replacements.
recordOpenedTypes(locator, replacements);
// The reference implicitly binds 'self'.
return { openedType, openedFnType->getResult() };
}
// If we have a type declaration, resolve it within the current context.
if (auto typeDecl = dyn_cast<TypeDecl>(value)) {
// Resolve the reference to this type declaration in our current context.
auto type = getTypeChecker().resolveTypeInContext(typeDecl, DC,
TR_InExpression,
isSpecialized);
if (!type)
return { nullptr, nullptr };
// Open the type.
type = openType(type, locator, replacements,
value->getInnermostDeclContext(), false, opener);
// If we opened up any type variables, record the replacements.
recordOpenedTypes(locator, replacements);
// If it's a type reference or it's a module type, we're done.
if (isTypeReference || type->is<ModuleType>())
return { type, type };
// If it's a value reference, refer to the metatype.
type = MetatypeType::get(type);
return { type, type };
}
// Determine the type of the value, opening up that type if necessary.
Type valueType = TC.getUnopenedTypeOfReference(value, Type(), DC, base,
/*wantInterfaceType=*/true);
// If this is a let-param whose type is a type variable, this is an untyped
// closure param that may be bound to an inout type later. References to the
// param should have lvalue type instead. Express the relationship with a new
// constraint.
if (auto *param = dyn_cast<ParamDecl>(value)) {
if (param->isLet() && valueType->is<TypeVariableType>()) {
Type paramType = valueType;
valueType = createTypeVariable(getConstraintLocator(locator),
TVO_CanBindToLValue);
addConstraint(ConstraintKind::BindParam, paramType, valueType,
getConstraintLocator(locator));
}
}
// Adjust the type of the reference.
valueType = openType(valueType, locator,
replacements,
value->getPotentialGenericDeclContext(),
/*skipProtocolSelfConstraint=*/false,
opener);
// If we opened up any type variables, record the replacements.
recordOpenedTypes(locator, replacements);
return { valueType, valueType };
}
void ConstraintSystem::openGeneric(
DeclContext *dc,
ArrayRef<GenericTypeParamType *> params,
ArrayRef<Requirement> requirements,
bool skipProtocolSelfConstraint,
DependentTypeOpener *opener,
ConstraintLocatorBuilder locator,
llvm::DenseMap<CanType, TypeVariableType *> &replacements) {
auto locatorPtr = getConstraintLocator(locator);
// Create the type variables for the generic parameters.
for (auto gp : params) {
// If we have a mapping for this type parameter, there's nothing else to do.
if (opener && opener->mapGenericTypeParamType(gp)) {
continue;
}
ArchetypeType *archetype = ArchetypeBuilder::mapTypeIntoContext(dc, gp)
->castTo<ArchetypeType>();
auto typeVar = createTypeVariable(getConstraintLocator(
locator.withPathElement(
LocatorPathElt(archetype))),
TVO_PrefersSubtypeBinding |
TVO_MustBeMaterializable);
replacements[gp->getCanonicalType()] = typeVar;
// Note that we opened a generic parameter to a type variable.
if (opener) {
Type replacementType;
opener->openedGenericParameter(gp, typeVar, replacementType);
if (replacementType)
addConstraint(ConstraintKind::Bind, typeVar, replacementType,
locatorPtr);
}
}
GetTypeVariable getTypeVariable{*this, locator, opener};
ReplaceDependentTypes replaceDependentTypes(*this, dc,
skipProtocolSelfConstraint,
opener, locator, replacements,
getTypeVariable);
// Remember that any new constraints generated by opening this generic are
// due to the opening.
locatorPtr = getConstraintLocator(
locator.withPathElement(ConstraintLocator::OpenedGeneric));
// Add the requirements as constraints.
for (auto req : requirements) {
switch (req.getKind()) {
case RequirementKind::Conformance: {
auto subjectTy = req.getFirstType().transform(replaceDependentTypes);
if (auto proto = req.getSecondType()->getAs<ProtocolType>()) {