-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
ConstraintSystem.cpp
1099 lines (954 loc) · 41 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"
using namespace swift;
using namespace constraints;
ConstraintSystem::ConstraintSystem(TypeChecker &tc, DeclContext *dc)
: TC(tc), DC(dc), Arena(tc.Context, Allocator) {
assert(DC && "context required");
// Create the constraint graph.
CG = new ConstraintGraph(*this);
}
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.
if (CG)
(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.
if (CG) {
CG->mergeNodes(typeVar1, typeVar2);
addTypeVariableConstraintsToWorkList(typeVar1);
}
}
void ConstraintSystem::assignFixedType(TypeVariableType *typeVar, Type type,
bool updateScore) {
typeVar->getImpl().assignFixedType(type, getSavedBindings());
if (updateScore && !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 (CG) {
// 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;
}
} else {
// FIXME: This is the less-correct path.
auto locator = typeVar->getImpl().getLocator();
if (locator && locator->getPath().empty() && locator->getAnchor()) {
literalProtocol = TC.getLiteralProtocol(locator->getAnchor());
}
}
// 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 Slice vs. Slice<T>.
if (defaultType->getAnyNominal() != type->getAnyNominal())
increaseScore(SK_NonDefaultLiteral);
}
}
}
// Notify the constraint graph.
if (CG) {
CG->bindTypeVariable(typeVar, type);
addTypeVariableConstraintsToWorkList(typeVar);
}
}
void ConstraintSystem::addTypeVariableConstraintsToWorkList(
TypeVariableType *typeVar) {
assert(CG && "No constraint graph available");
// 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()) {
Worklist.push_back(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.
selector = func->getObjCSelector(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 var = dyn_cast<VarDecl>(decl)) {
// Handle properties. Only the getter matters.
selector = var->getObjCGetterSelector(buffer);
type = decl->getType();
} else if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
// Handle constructors.
selector = ctor->getObjCSelector(buffer);
type = decl->getType()->castTo<AnyFunctionType>()->getResult();
} else if (auto subscript = dyn_cast<SubscriptDecl>(decl)) {
selector = subscript->getObjCGetterSelector();
type = subscript->getType();
} 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, Identifier 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.
MemberLookups[{base, name}] = Nothing;
auto lookup = TC.lookupMember(base, name, DC);
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<MetaTypeType>())
instanceTy = metaTy->getInstanceType();
auto protoTy = instanceTy->getAs<ProtocolType>();
if (!*result ||
!protoTy ||
!protoTy->getDecl()->isSpecificProtocol(
KnownProtocolKind::DynamicLookup))
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 {
return known.insert(getDynamicResultSignature(decl, selectors)).second;
});
return *result;
}
ConstraintLocator *ConstraintSystem::getConstraintLocator(
Expr *anchor,
ArrayRef<ConstraintLocator::PathElement> 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);
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);
if (!anchor)
return nullptr;
return getConstraintLocator(anchor, path);
}
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) {
solverState->generatedConstraints->insert(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)
solverState->generatedConstraints->insert(constraint);
}
// Remove the constraint from the constraint graph.
if (simplifyExisting && CG)
CG->removeConstraint(constraint);
return true;
case SolutionKind::Unsolved:
// We couldn't solve this constraint; add it to the pile.
if (!isExternallySolved) {
Constraints.push_back(constraint);
}
// Add this constraint to the constraint graph.
if (!simplifyExisting && CG)
CG->addConstraint(constraint);
if (!simplifyExisting && solverState && solverState->generatedConstraints) {
solverState->generatedConstraints->insert(constraint);
}
return false;
}
}
/// 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;
DependentTypeOpener *Opener;
/// The type variables introduced for (base type, associated type) pairs.
llvm::DenseMap<std::pair<CanType, AssociatedTypeDecl *>, TypeVariableType *>
MemberReplacements;
public:
GetTypeVariable(ConstraintSystem &cs, DependentTypeOpener *opener)
: CS(cs), Opener(opener) { }
TypeVariableType *operator()(Type base, AssociatedTypeDecl *member) {
auto known = MemberReplacements.find({base->getCanonicalType(), member});
if (known != MemberReplacements.end())
return known->second;
auto baseTypeVar = base->castTo<TypeVariableType>();
auto archetype = baseTypeVar->getImpl().getArchetype()
->getNestedType(member->getName());
auto tv = CS.createTypeVariable(CS.getConstraintLocator(
(Expr *)nullptr,
LocatorPathElt(archetype)),
TVO_PrefersSubtypeBinding);
MemberReplacements[{base->getCanonicalType(), member}] = tv;
// 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, tv,
replacementType);
}
// Bind the member's type variable as a type member of the base,
// if needed.
if (shouldBindMember)
CS.addTypeMemberConstraint(base, member->getName(), tv);
// If we have a replacement type, bind the member's type
// variable to it.
if (replacementType)
CS.addConstraint(ConstraintKind::Bind, tv, replacementType);
// Add associated type constraints.
// 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, tv, superclass);
}
for (auto proto : member->getArchetype()->getConformsTo()) {
CS.addConstraint(ConstraintKind::ConformsTo, tv,
proto->getDeclaredType());
}
return tv;
}
};
/// Function object that replaces all occurrences of archetypes and
/// dependent types with type variables.
class ReplaceDependentTypes {
ConstraintSystem &cs;
DeclContext *dc;
bool skipProtocolSelfConstraint;
DependentTypeOpener *opener;
llvm::DenseMap<CanType, TypeVariableType *> &replacements;
GetTypeVariable &getTypeVariable;
public:
ReplaceDependentTypes(
ConstraintSystem &cs,
DeclContext *dc,
bool skipProtocolSelfConstraint,
DependentTypeOpener *opener,
llvm::DenseMap<CanType, TypeVariableType *> &replacements,
GetTypeVariable &getTypeVariable)
: cs(cs), dc(dc), skipProtocolSelfConstraint(skipProtocolSelfConstraint),
opener(opener), replacements(replacements),
getTypeVariable(getTypeVariable) { }
Type operator()(Type type) {
assert(!type->is<PolymorphicFunctionType>() && "Shouldn't get here");
// 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>()) {
auto known = replacements.find(genericParam->getCanonicalType());
assert(known != replacements.end());
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>()) {
// 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.
auto base = (*this)(dependentMember->getBase());
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,
replacements);
// Transform the input and output types.
Type inputTy = cs.TC.transformType(genericFn->getInput(), *this);
if (!inputTy)
return Type();
Type resultTy = cs.TC.transformType(genericFn->getResult(), *this);
if (!resultTy)
return Type();
// Build the resulting (non-generic) function type.
return FunctionType::get(inputTy, resultTy, cs.TC.Context);
}
// 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 = cs.TC.transformType(parentTy, *this);
auto unboundDecl = unbound->getDecl();
// Open up the generic type.
cs.openGeneric(unboundDecl,
unboundDecl->getGenericParamTypes(),
unboundDecl->getGenericRequirements(),
/*skipProtocolSelfConstraint=*/false,
opener,
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,
llvm::DenseMap<CanType, TypeVariableType *> &replacements,
DeclContext *dc,
bool skipProtocolSelfConstraint,
DependentTypeOpener *opener) {
GetTypeVariable getTypeVariable{*this, opener};
ReplaceDependentTypes replaceDependentTypes(*this, dc,
skipProtocolSelfConstraint,
opener,
replacements, getTypeVariable);
return TC.transformType(startingType, replaceDependentTypes);
}
Type ConstraintSystem::openBindingType(Type type, DeclContext *dc) {
Type result = openType(type, dc);
// FIXME: Better way to identify Slice<T>.
if (auto boundStruct
= dyn_cast<BoundGenericStructType>(result.getPointer())) {
if (!boundStruct->getParent() &&
boundStruct->getDecl()->getName().str() == "Array" &&
boundStruct->getGenericArgs().size() == 1) {
if (auto replacement = getTypeChecker().getArraySliceType(
SourceLoc(), boundStruct->getGenericArgs()[0])) {
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) {
if (wantRValue)
type = type->getRValueType();
auto desugar = type->getDesugaredType();
typeVar = desugar->getAs<TypeVariableType>();
if (typeVar) {
if (auto fixed = getFixedTypeRecursiveHelper(*this, typeVar, wantRValue)) {
type = fixed;
typeVar = nullptr;
}
}
return type;
}
// A variable or subscript is settable if:
// - its base type (the type of the 'a' in 'a[n]' or 'a.b') either has
// reference semantics or has value semantics and is settable, AND
// - the 'var' or 'subscript' decl provides a setter
template<typename SomeValueDecl>
static LValueType::Qual settableQualForDecl(Type baseType,
SomeValueDecl *decl) {
if (decl->isSettableOnBase(baseType))
return LValueType::Qual(0);
return LValueType::Qual::NonSettable;
}
std::pair<Type, Type>
ConstraintSystem::getTypeOfReference(ValueDecl *value,
bool isTypeReference,
bool isSpecialized,
DependentTypeOpener *opener) {
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(), func, false, opener);
auto 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());
// 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,
isSpecialized);
if (!type)
return { nullptr, nullptr };
// Open the type.
type = openType(type, value->getInnermostDeclContext(), false, opener);
// If it's a type reference, we're done.
if (isTypeReference)
return { type, type };
// If it's a value reference, refer to the metatype.
type = MetaTypeType::get(type, getASTContext());
return { type, type };
}
// Determine the type of the value, opening up that type if necessary.
Type valueType = TC.getUnopenedTypeOfReference(value, Type(),
/*wantInterfaceType=*/true);
// Adjust the type of the reference.
valueType = adjustLValueForReference(
openType(valueType,
value->getPotentialGenericDeclContext(),
/*skipProtocolSelfConstraint=*/false,
opener),
value->getAttrs().isAssignment(),
TC.Context);
return { valueType, valueType };
}
void ConstraintSystem::openGeneric(
DeclContext *dc,
ArrayRef<GenericTypeParamType *> params,
ArrayRef<Requirement> requirements,
bool skipProtocolSelfConstraint,
DependentTypeOpener *opener,
llvm::DenseMap<CanType, TypeVariableType *> &replacements) {
// Create the type variables for the generic parameters.
for (auto gp : params) {
ArchetypeType *archetype = ArchetypeBuilder::mapTypeIntoContext(dc, gp)
->castTo<ArchetypeType>();
auto typeVar = createTypeVariable(getConstraintLocator(
(Expr *)nullptr,
LocatorPathElt(archetype)),
TVO_PrefersSubtypeBinding);
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);
}
}
GetTypeVariable getTypeVariable{*this, opener};
ReplaceDependentTypes replaceDependentTypes(*this, dc,
skipProtocolSelfConstraint,
opener, replacements,
getTypeVariable);
// Add the requirements as constraints.
for (auto req : requirements) {
switch (req.getKind()) {
case RequirementKind::Conformance: {
auto subjectTy = TC.transformType(req.getFirstType(),
replaceDependentTypes);
if (auto proto = req.getSecondType()->getAs<ProtocolType>()) {
if (!skipProtocolSelfConstraint ||
!(isa<ProtocolDecl>(dc) || isa<ProtocolDecl>(dc->getParent())) ||
!isProtocolSelfType(req.getFirstType())) {
addConstraint(ConstraintKind::ConformsTo, subjectTy,
proto);
}
} else {
addConstraint(ConstraintKind::Subtype, subjectTy,
req.getSecondType());
}
break;
}
case RequirementKind::SameType: {
auto firstTy = TC.transformType(req.getFirstType(),
replaceDependentTypes);
auto secondTy = TC.transformType(req.getSecondType(),
replaceDependentTypes);
addConstraint(ConstraintKind::Bind, firstTy, secondTy);
break;
}
case RequirementKind::ValueWitnessMarker:
break;
}
}
}
/// Add the constraint on the type used for the 'Self' type for a member
/// reference.
///
/// \param cs The constraint system.
///
/// \param objectTy The type of the object that we're using to access the
/// member.
///
/// \param selfTy The instance type of the context in which the member is
/// declared.
static void addSelfConstraint(ConstraintSystem &cs, Type objectTy, Type selfTy){
// When referencing a protocol member, we need the object type to be usable
// as the Self type of the protocol, which covers anything that conforms to
// the protocol as well as existentials that include that protocol.
if (selfTy->is<ProtocolType>()) {
cs.addConstraint(ConstraintKind::SelfObjectOfProtocol, objectTy, selfTy);
return;
}
// Otherwise, use a subtype constraint for classes to cope with inheritance.
if (selfTy->getClassOrBoundGenericClass()) {
cs.addConstraint(ConstraintKind::Subtype, objectTy, selfTy);
return;
}
// Otherwise, the types must be equivalent.
cs.addConstraint(ConstraintKind::Equal, objectTy, selfTy);
}
/// Collect all of the generic parameters and requirements from the
/// given context and its outer contexts.
static void collectContextParamsAndRequirements(
DeclContext *dc,
SmallVectorImpl<GenericTypeParamType *> &genericParams,
SmallVectorImpl<Requirement> &genericRequirements) {
if (!dc->isTypeContext())
return;
// Recurse to outer context.
collectContextParamsAndRequirements(dc->getParent(), genericParams,
genericRequirements);
// Add our generic parameters and requirements.
auto nominal = dc->getDeclaredTypeOfContext()->getAnyNominal();
genericParams.append(nominal->getGenericParamTypes().begin(),
nominal->getGenericParamTypes().end());
genericRequirements.append(nominal->getGenericRequirements().begin(),
nominal->getGenericRequirements().end());
}
std::pair<Type, Type>
ConstraintSystem::getTypeOfMemberReference(Type baseTy, ValueDecl *value,
bool isTypeReference,
bool isDynamicResult,
DependentTypeOpener *opener) {
// Figure out the instance type used for the base.
TypeVariableType *baseTypeVar = nullptr;
Type baseObjTy = getFixedTypeRecursive(baseTy, baseTypeVar,
/*wantRValue=*/true);
bool isInstance = true;
if (auto baseMeta = baseObjTy->getAs<MetaTypeType>()) {
baseObjTy = baseMeta->getInstanceType();
isInstance = false;
}
// If the base is a module type, just use the type of the decl.
if (baseObjTy->is<ModuleType>()) {
return getTypeOfReference(value, isTypeReference, /*isSpecialized=*/false,
opener);
}
// Handle associated type lookup as a special case, horribly.
// FIXME: This is an awful hack.
if (auto assocType = dyn_cast<AssociatedTypeDecl>(value)) {
// Refer to a member of the archetype directly.
if (auto archetype = baseObjTy->getAs<ArchetypeType>()) {
Type memberTy = archetype->getNestedType(value->getName());
if (!isTypeReference)
memberTy = MetaTypeType::get(memberTy, TC.Context);
auto openedType = FunctionType::get(baseObjTy, memberTy, TC.Context);
return { openedType, memberTy };
}
// If we have a nominal type that conforms to the protocol in which the
// associated type resides, use the witness.
if (!baseObjTy->isExistentialType() &&
!baseObjTy->hasTypeVariable() &&
baseObjTy->getAnyNominal()) {
auto proto = cast<ProtocolDecl>(assocType->getDeclContext());
ProtocolConformance *conformance = nullptr;
if (TC.conformsToProtocol(baseObjTy, proto, DC, &conformance)) {
auto memberTy = conformance->getTypeWitness(assocType).Replacement;
if (!isTypeReference)
memberTy = MetaTypeType::get(memberTy, TC.Context);
auto openedType = FunctionType::get(baseObjTy, memberTy, TC.Context);
return { openedType, memberTy };
}
}
// FIXME: Totally bogus fallthrough.
Type memberTy = isTypeReference? assocType->getDeclaredType()
: assocType->getType();
auto openedType = FunctionType::get(baseObjTy, memberTy, TC.Context);
return { openedType, memberTy };
}
// Figure out the declaration context to use when opening this type.
DeclContext *dc = value->getPotentialGenericDeclContext();
// Open the type of the generic function or member of a generic type.
Type openedType;
if (auto genericFn = value->getInterfaceType()->getAs<GenericFunctionType>()){
openedType = openType(genericFn, dc, /*skipProtocolSelfConstraint=*/true,
opener);
} else {
openedType = TC.getUnopenedTypeOfReference(value, baseTy,
/*wantInterfaceType=*/true);
Type selfTy;
if (dc->isGenericContext()) {
// Open up the generic parameter list for the container.
auto nominal = dc->getDeclaredTypeOfContext()->getAnyNominal();
llvm::DenseMap<CanType, TypeVariableType *> replacements;
SmallVector<GenericTypeParamType *, 4> genericParams;
SmallVector<Requirement, 4> genericRequirements;
collectContextParamsAndRequirements(dc, genericParams, genericRequirements);
openGeneric(dc, genericParams, genericRequirements,
/*skipProtocolSelfConstraint=*/true,
opener,
replacements);
// Open up the type of the member.
openedType = openType(openedType, replacements, nullptr, false, opener);
// Determine the object type of 'self'.
if (auto protocol = dyn_cast<ProtocolDecl>(nominal)) {
// Retrieve the type variable for 'Self'.
selfTy = replacements[protocol->getSelf()->getDeclaredType()
->getCanonicalType()];
} else {
// Open the nominal type.
selfTy = openType(nominal->getDeclaredInterfaceType(), replacements);
}
} else {
selfTy = value->getDeclContext()->getDeclaredTypeOfContext();
}
// If we have a type reference, look through the metatype.
if (isTypeReference)
openedType = openedType->castTo<MetaTypeType>()->getInstanceType();
// If we're not coming from something function-like, prepend the type
// for 'self' to the type.
if (!isa<AbstractFunctionDecl>(value) && !isa<EnumElementDecl>(value))
openedType = FunctionType::get(selfTy, openedType, TC.Context);
}
// Constrain the 'self' object type.
auto openedFnType = openedType->castTo<FunctionType>();
Type selfObjTy = openedFnType->getInput()->getRValueInstanceType();
if (isa<ProtocolDecl>(value->getDeclContext())) {
// For a protocol, substitute the base object directly. We don't need a
// conformance constraint because we wouldn't have found the declaration
// if it didn't conform.
addConstraint(ConstraintKind::Equal, baseObjTy, selfObjTy);
} else if (!isDynamicResult) {
addSelfConstraint(*this, baseObjTy, selfObjTy);
}
// Compute the type of the reference.
Type type;
if (auto subscript = dyn_cast<SubscriptDecl>(value)) {
// For a subscript, turn the element type into an optional or lvalue,
// depending on
auto fnType = openedFnType->getResult()->castTo<FunctionType>();
auto elementTy = fnType->getResult();
if (isDynamicResult || subscript->getAttrs().isOptional())
elementTy = OptionalType::get(elementTy, TC.Context);
else
elementTy = LValueType::get(elementTy,
LValueType::Qual::DefaultForMemberAccess|
settableQualForDecl(baseTy, subscript),
TC.Context);
type = FunctionType::get(fnType->getInput(), elementTy, TC.Context);
} else if (isa<ProtocolDecl>(value->getDeclContext()) &&
isa<AssociatedTypeDecl>(value)) {
// When we have an associated type, the base type conforms to the
// given protocol, so use the type witness directly.
// FIXME: Diagnose existentials properly.
// FIXME: Eliminate the "hasTypeVariables()" hack here.
auto proto = cast<ProtocolDecl>(value->getDeclContext());
auto assocType = cast<AssociatedTypeDecl>(value);
type = openedFnType->getResult();
if (baseObjTy->is<ArchetypeType>()) {
// For an archetype, we substitute the base object for the base.
// FIXME: Feels like a total hack.
} else if (!baseObjTy->isExistentialType() &&
!baseObjTy->is<ArchetypeType>() &&
!baseObjTy->hasTypeVariable()) {
ProtocolConformance *conformance = nullptr;
if (TC.conformsToProtocol(baseObjTy, proto, DC, &conformance)) {
type = conformance->getTypeWitness(assocType).Replacement;
}
}
} else if (isa<ConstructorDecl>(value) || isa<EnumElementDecl>(value) ||
(isa<FuncDecl>(value) && cast<FuncDecl>(value)->isStatic()) ||
(isa<VarDecl>(value) && cast<VarDecl>(value)->isStatic()) ||
isa<TypeDecl>(value) ||
isInstance) {
// For a constructor, enum element, static method, static property,
// or an instance method referenced through an instance, we've consumed the
// curried 'self' already. For a type, strip off the 'self' we artificially
// added.
type = openedFnType->getResult();
} else if (isDynamicResult && isa<AbstractFunctionDecl>(value)) {
// For a dynamic result referring to an instance function through
// an object of metatype type, replace the 'Self' parameter with
// a DynamicLookup member.
auto funcTy = type->castTo<AnyFunctionType>();
Type resultTy = funcTy->getResult();
Type inputTy = TC.getProtocol(SourceLoc(), KnownProtocolKind::DynamicLookup)
->getDeclaredTypeOfContext();
type = FunctionType::get(inputTy, resultTy, funcTy->getExtInfo(),
TC.Context);
} else {
type = openedType;
}
return { openedType, type };
}
void ConstraintSystem::addOverloadSet(Type boundType,
ArrayRef<OverloadChoice> choices,
ConstraintLocator *locator) {
assert(!choices.empty() && "Empty overload set");
SmallVector<Constraint *, 4> overloads;
for (auto choice : choices) {
overloads.push_back(Constraint::createBindOverload(*this, boundType, choice,
locator));
}
addConstraint(Constraint::createDisjunction(*this, overloads,
locator));
}
/// \brief Retrieve the fully-materialized form of the given type.
static Type getMateralizedType(Type type, ASTContext &context) {
if (auto lvalue = type->getAs<LValueType>()) {
return lvalue->getObjectType();
}
if (auto tuple = type->getAs<TupleType>()) {
bool anyChanged = false;
SmallVector<TupleTypeElt, 4> elements;
for (unsigned i = 0, n = tuple->getFields().size(); i != n; ++i) {
auto elt = tuple->getFields()[i];
auto eltType = getMateralizedType(elt.getType(), context);
if (anyChanged) {
elements.push_back(elt.getWithType(eltType));
continue;
}
if (eltType.getPointer() != elt.getType().getPointer()) {
elements.append(tuple->getFields().begin(),
tuple->getFields().begin() + i);
elements.push_back(elt.getWithType(eltType));
anyChanged = true;
}
}
if (anyChanged) {
return TupleType::get(elements, context);
}
}
return type;
}
void ConstraintSystem::resolveOverload(ConstraintLocator *locator,
Type boundType,
OverloadChoice choice){
// Determie the type to which we'll bind the overload set's type.
Type refType;
Type openedFullType;
switch (choice.getKind()) {
case OverloadChoiceKind::Decl:
case OverloadChoiceKind::DeclViaDynamic:
case OverloadChoiceKind::TypeDecl: {
bool isTypeReference = choice.getKind() == OverloadChoiceKind::TypeDecl;
bool isDynamicResult
= choice.getKind() == OverloadChoiceKind::DeclViaDynamic;
// Retrieve the type of a reference to the specific declaration choice.
if (choice.getBaseType())
std::tie(openedFullType, refType)
= getTypeOfMemberReference(choice.getBaseType(), choice.getDecl(),
isTypeReference, isDynamicResult,
nullptr);
else
std::tie(openedFullType, refType)