-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathConstraintSystem.cpp
5410 lines (4530 loc) · 185 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 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the constraint-based type checker, anchored by the
// \c ConstraintSystem class, which provides type checking and type
// inference for expressions.
//
//===----------------------------------------------------------------------===//
#include "swift/Sema/ConstraintSystem.h"
#include "CSDiagnostics.h"
#include "OpenedExistentials.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckMacros.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/MacroDefinition.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeTransform.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Statistic.h"
#include "swift/Sema/CSFix.h"
#include "swift/Sema/ConstraintGraph.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Sema/SolutionResult.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Format.h"
#include <cmath>
using namespace swift;
using namespace constraints;
using namespace inference;
#define DEBUG_TYPE "ConstraintSystem"
ExpressionTimer::ExpressionTimer(AnchorType Anchor, ConstraintSystem &CS,
unsigned thresholdInSecs)
: Anchor(Anchor), Context(CS.getASTContext()),
StartTime(llvm::TimeRecord::getCurrentTime()),
ThresholdInSecs(thresholdInSecs),
PrintDebugTiming(CS.getASTContext().TypeCheckerOpts.DebugTimeExpressions),
PrintWarning(true) {}
SourceRange ExpressionTimer::getAffectedRange() const {
ASTNode anchor;
if (auto *locator = Anchor.dyn_cast<ConstraintLocator *>()) {
anchor = simplifyLocatorToAnchor(locator);
// If locator couldn't be simplified down to a single AST
// element, let's use its root.
if (!anchor)
anchor = locator->getAnchor();
} else {
anchor = Anchor.get<Expr *>();
}
return anchor.getSourceRange();
}
ExpressionTimer::~ExpressionTimer() {
auto elapsed = getElapsedProcessTimeInFractionalSeconds();
unsigned elapsedMS = static_cast<unsigned>(elapsed * 1000);
if (PrintDebugTiming) {
// Round up to the nearest 100th of a millisecond.
llvm::errs() << llvm::format("%0.2f", std::ceil(elapsed * 100000) / 100)
<< "ms\t";
if (auto *E = Anchor.dyn_cast<Expr *>()) {
E->getLoc().print(llvm::errs(), Context.SourceMgr);
} else {
auto *locator = Anchor.get<ConstraintLocator *>();
locator->dump(&Context.SourceMgr, llvm::errs());
}
llvm::errs() << "\n";
}
if (!PrintWarning)
return;
const auto WarnLimit = getWarnLimit();
if (WarnLimit == 0 || elapsedMS < WarnLimit)
return;
auto sourceRange = getAffectedRange();
if (sourceRange.Start.isValid()) {
Context.Diags
.diagnose(sourceRange.Start, diag::debug_long_expression, elapsedMS,
WarnLimit)
.highlight(sourceRange);
}
}
ConstraintSystem::ConstraintSystem(DeclContext *dc,
ConstraintSystemOptions options,
DiagnosticTransaction *diagnosticTransaction)
: Context(dc->getASTContext()), DC(dc), Options(options),
diagnosticTransaction(diagnosticTransaction),
Arena(dc->getASTContext(), Allocator),
CG(*this)
{
assert(DC && "context required");
// Respect the global debugging flag, but turn off debugging while
// parsing and loading other modules.
if (Context.TypeCheckerOpts.DebugConstraintSolver &&
DC->getParentModule()->isMainModule()) {
Options |= ConstraintSystemFlags::DebugConstraints;
}
if (Context.LangOpts.UseClangFunctionTypes)
Options |= ConstraintSystemFlags::UseClangFunctionTypes;
}
ConstraintSystem::~ConstraintSystem() {
for (unsigned i = 0, n = TypeVariables.size(); i != n; ++i) {
auto &impl = TypeVariables[i]->getImpl();
delete impl.getGraphNode();
impl.setGraphNode(nullptr);
}
}
void ConstraintSystem::startExpressionTimer(ExpressionTimer::AnchorType anchor) {
ASSERT(!Timer);
unsigned timeout = getASTContext().TypeCheckerOpts.ExpressionTimeoutThreshold;
if (timeout == 0)
return;
Timer.emplace(anchor, *this, timeout);
}
void ConstraintSystem::incrementScopeCounter() {
++NumSolverScopes;
if (auto *Stats = getASTContext().Stats)
++Stats->getFrontendCounters().NumConstraintScopes;
}
void ConstraintSystem::incrementLeafScopes() {
if (auto *Stats = getASTContext().Stats)
++Stats->getFrontendCounters().NumLeafScopes;
}
bool ConstraintSystem::hasFreeTypeVariables() {
// Look for any free type variables.
return llvm::any_of(TypeVariables, [](const TypeVariableType *typeVar) {
return !typeVar->getImpl().hasRepresentativeOrFixed();
});
}
void ConstraintSystem::addTypeVariable(TypeVariableType *typeVar) {
TypeVariables.insert(typeVar);
// Notify the constraint graph.
CG.addTypeVariable(typeVar);
}
void ConstraintSystem::mergeEquivalenceClasses(TypeVariableType *typeVar1,
TypeVariableType *typeVar2,
bool updateWorkList) {
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");
// Always merge 'up' the constraint stack, because it is simpler.
if (typeVar1->getImpl().getID() > typeVar2->getImpl().getID())
std::swap(typeVar1, typeVar2);
CG.mergeNodesPre(typeVar2);
typeVar1->getImpl().mergeEquivalenceClasses(typeVar2, getTrail());
CG.mergeNodes(typeVar1, typeVar2);
if (updateWorkList) {
addTypeVariableConstraintsToWorkList(typeVar1);
}
}
/// Determine whether the given type variables occurs in the given type.
bool ConstraintSystem::typeVarOccursInType(TypeVariableType *typeVar,
Type type,
bool *involvesOtherTypeVariables) {
SmallPtrSet<TypeVariableType *, 4> typeVars;
type->getTypeVariables(typeVars);
bool occurs = typeVars.count(typeVar);
if (involvesOtherTypeVariables) {
*involvesOtherTypeVariables =
occurs ? typeVars.size() > 1 : !typeVars.empty();
}
return occurs;
}
void ConstraintSystem::assignFixedType(TypeVariableType *typeVar, Type type,
bool updateState,
bool notifyBindingInference) {
assert(!type->hasError() &&
"Should not be assigning a type involving ErrorType!");
CG.retractFromInference(typeVar);
typeVar->getImpl().assignFixedType(type, getTrail());
if (!updateState)
return;
if (!type->isTypeVariableOrMember()) {
// If this type variable represents a literal, check whether we picked the
// default literal type. First, find the corresponding protocol.
//
// 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->directlyAt<CollectionExpr>() ||
locator->directlyAt<LiteralExpr>())))
continue;
auto *literalProtocol = TypeChecker::getLiteralProtocol(
getASTContext(), castToExpr(locator->getAnchor()));
if (!literalProtocol)
continue;
// If the protocol has a default type, check it.
if (auto defaultType = TypeChecker::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, locator);
}
}
break;
}
}
// Notify the constraint graph.
CG.bindTypeVariable(typeVar, type);
addTypeVariableConstraintsToWorkList(typeVar);
if (notifyBindingInference)
CG.introduceToInference(typeVar, type);
}
void ConstraintSystem::addTypeVariableConstraintsToWorkList(
TypeVariableType *typeVar) {
// Activate the constraints affected by a change to this type variable.
auto gatheringKind = ConstraintGraph::GatheringKind::AllMentions;
for (auto *constraint : CG.gatherConstraints(typeVar, gatheringKind))
if (!constraint->isActive())
activateConstraint(constraint);
}
void ConstraintSystem::addConversionRestriction(
Type srcType, Type dstType,
ConversionRestrictionKind restriction) {
auto key = std::make_pair(srcType.getPointer(), dstType.getPointer());
bool inserted = ConstraintRestrictions.insert(
std::make_pair(key, restriction)).second;
if (!inserted)
return;
if (solverState) {
recordChange(SolverTrail::Change::AddedConversionRestriction(
srcType, dstType));
}
}
void ConstraintSystem::removeConversionRestriction(
Type srcType, Type dstType) {
auto key = std::make_pair(srcType.getPointer(), dstType.getPointer());
bool erased = ConstraintRestrictions.erase(key);
ASSERT(erased);
}
void ConstraintSystem::addFix(ConstraintFix *fix) {
bool inserted = Fixes.insert(fix);
ASSERT(inserted);
if (solverState)
recordChange(SolverTrail::Change::AddedFix(fix));
}
void ConstraintSystem::removeFix(ConstraintFix *fix) {
ASSERT(Fixes.back() == fix);
Fixes.pop_back();
}
void ConstraintSystem::recordDisjunctionChoice(
ConstraintLocator *locator, unsigned index) {
bool inserted = DisjunctionChoices.insert({locator, index}).second;
ASSERT(inserted);
if (solverState)
recordChange(SolverTrail::Change::RecordedDisjunctionChoice(locator));
}
void ConstraintSystem::recordAppliedDisjunction(
ConstraintLocator *locator, FunctionType *fnType) {
// We shouldn't ever register disjunction choices multiple times.
bool inserted = AppliedDisjunctions.insert(
std::make_pair(locator, fnType)).second;
ASSERT(inserted);
if (solverState)
recordChange(SolverTrail::Change::RecordedAppliedDisjunction(locator));
}
/// Retrieve a dynamic result signature for the given declaration.
static std::tuple<char, ObjCSelector, CanType>
getDynamicResultSignature(ValueDecl *decl) {
if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
// Handle functions.
auto type = func->getMethodInterfaceType();
return std::make_tuple(func->isStatic(), func->getObjCSelector(),
type->getCanonicalType());
}
if (auto asd = dyn_cast<AbstractStorageDecl>(decl)) {
auto ty = asd->getInterfaceType();
// Strip off a generic signature if we have one. This matches the logic
// for methods, and ensures that we don't take a protocol's generic
// signature into account for a subscript requirement.
if (auto *genericFn = ty->getAs<GenericFunctionType>()) {
ty = FunctionType::get(genericFn->getParams(), genericFn->getResult(),
genericFn->getExtInfo());
}
// Handle properties and subscripts, anchored by the getter's selector.
return std::make_tuple(asd->isStatic(), asd->getObjCGetterSelector(),
ty->getCanonicalType());
}
llvm_unreachable("Not a valid @objc member");
}
LookupResult &ConstraintSystem::lookupMember(Type base, DeclNameRef name,
SourceLoc loc) {
// Check whether we've already performed this lookup.
auto &result = MemberLookups[{base, name}];
if (result) return *result;
// Lookup the member.
result = TypeChecker::lookupMember(
DC, base, name, loc, defaultConstraintSolverMemberLookupOptions);
// If we are in an @_unsafeInheritExecutor context, swap out
// declarations for their _unsafeInheritExecutor_ counterparts if they
// exist.
if (enclosingUnsafeInheritsExecutor(DC)) {
introduceUnsafeInheritExecutorReplacements(DC, base, loc, *result);
}
// If we aren't performing dynamic lookup, we're done.
if (!*result || !base->isAnyObject())
return *result;
// We are performing dynamic lookup. Filter out redundant results early.
llvm::DenseMap<std::tuple<char, ObjCSelector, CanType>, ValueDecl *> known;
bool anyRemovals = false;
for (const auto &entry : *result) {
auto *decl = entry.getValueDecl();
// Remove invalid declarations so the constraint solver doesn't need to
// cope with them.
if (decl->isInvalid()) {
anyRemovals = true;
continue;
}
// If this is the first entry with the signature, record it.
auto &uniqueEntry = known[getDynamicResultSignature(decl)];
if (!uniqueEntry) {
uniqueEntry = decl;
continue;
}
// We have duplication; note that we'll need to remove something,
anyRemovals = true;
// If the entry we recorded was unavailable but this new entry is not,
// replace the recorded entry with this one.
if (isDeclUnavailable(uniqueEntry) && !isDeclUnavailable(decl)) {
uniqueEntry = decl;
}
}
// If there's anything to remove, filter it out now.
if (anyRemovals) {
result->filter([&](LookupResultEntry entry, bool isOuter) -> bool {
auto *decl = entry.getValueDecl();
// Remove invalid declarations so the constraint solver doesn't need to
// cope with them.
if (decl->isInvalid())
return false;
return known[getDynamicResultSignature(decl)] == decl;
});
}
return *result;
}
ArrayRef<Type>
ConstraintSystem::getAlternativeLiteralTypes(KnownProtocolKind kind,
SmallVectorImpl<Type> &scratch) {
assert(scratch.empty());
if (kind == KnownProtocolKind::ExpressibleByIntegerLiteral) {
// Integer literals can be treated as floating point literals.
if (auto floatProto = getASTContext().getProtocol(
KnownProtocolKind::ExpressibleByFloatLiteral)) {
if (auto defaultType = TypeChecker::getDefaultType(floatProto, DC))
scratch.push_back(defaultType);
}
}
return scratch;
}
bool ConstraintSystem::containsIDEInspectionTarget(ASTNode node) const {
return swift::containsIDEInspectionTarget(node.getSourceRange(),
Context.SourceMgr);
}
bool ConstraintSystem::containsIDEInspectionTarget(
const ArgumentList *args) const {
return swift::containsIDEInspectionTarget(args->getSourceRange(),
Context.SourceMgr);
}
void ConstraintSystem::recordPotentialThrowSite(
CatchNode catchNode, PotentialThrowSite site) {
potentialThrowSites.push_back({catchNode, site});
if (solverState)
recordChange(SolverTrail::Change::RecordedPotentialThrowSite(catchNode));
}
void ConstraintSystem::removePotentialThrowSite(CatchNode catchNode) {
ASSERT(potentialThrowSites.back().first == catchNode);
potentialThrowSites.pop_back();
}
void ConstraintSystem::recordPotentialThrowSite(
PotentialThrowSite::Kind kind, Type type,
ConstraintLocatorBuilder locator) {
ASTContext &ctx = getASTContext();
// Only record potential throw sites when typed throws is enabled.
if (!ctx.LangOpts.hasFeature(Feature::FullTypedThrows))
return;
// Catch node location is determined by the source location.
auto sourceLoc = locator.getAnchor().getStartLoc();
if (!sourceLoc)
return;
auto catchNode = ASTScope::lookupCatchNode(DC->getParentModule(), sourceLoc);
if (!catchNode)
return;
// If there is an explicit caught type for this node, we don't need to
// record a potential throw site.
if (Type explicitCaughtType = catchNode.getExplicitCaughtType(ctx))
return;
// do..catch statements without an explicit `throws` clause do infer
// thrown types.
if (catchNode.is<DoCatchStmt *>()) {
PotentialThrowSite site{kind, type, getConstraintLocator(locator)};
recordPotentialThrowSite(catchNode, site);
return;
}
// Closures without an explicit `throws` clause, and which syntactically
// appear that they can throw, do infer thrown types.
auto closure = catchNode.get<ClosureExpr *>();
// Check whether the closure syntactically throws. If not, there is no
// need to record a throw site.
if (!closureEffects(closure).isThrowing())
return;
PotentialThrowSite site{kind, type, getConstraintLocator(locator)};
recordPotentialThrowSite(catchNode, site);
}
Type ConstraintSystem::getCaughtErrorType(CatchNode catchNode) {
ASTContext &ctx = getASTContext();
// If there is an explicit caught type for this node, use it.
if (Type explicitCaughtType = catchNode.getExplicitCaughtType(ctx)) {
if (explicitCaughtType->hasTypeParameter())
explicitCaughtType = DC->mapTypeIntoContext(explicitCaughtType);
return explicitCaughtType;
}
// Retrieve the thrown error type of a closure.
// FIXME: This will need to change when we do inference of thrown error
// types in closures.
if (auto closure = catchNode.dyn_cast<ClosureExpr *>()) {
return getClosureType(closure)->getEffectiveThrownErrorTypeOrNever();
}
if (!ctx.LangOpts.hasFeature(Feature::FullTypedThrows))
return ctx.getErrorExistentialType();
// Handle inference of caught error types.
// Collect all of the potential throw sites for this catch node.
SmallVector<PotentialThrowSite, 2> throwSites;
for (const auto &potentialThrowSite : potentialThrowSites) {
if (potentialThrowSite.first == catchNode) {
throwSites.push_back(potentialThrowSite.second);
}
}
Type caughtErrorType = ctx.getNeverType();
for (const auto &throwSite : throwSites) {
Type type = simplifyType(throwSite.type);
Type thrownErrorType;
switch (throwSite.kind) {
case PotentialThrowSite::Application: {
auto fnType = type->castTo<AnyFunctionType>();
thrownErrorType = fnType->getEffectiveThrownErrorTypeOrNever();
break;
}
case PotentialThrowSite::ExplicitThrow:
case PotentialThrowSite::NonExhaustiveDoCatch:
case PotentialThrowSite::PropertyAccess:
thrownErrorType = type;
break;
}
// Perform the errorUnion() of the caught error type so far with the
// thrown error type of this potential throw site.
caughtErrorType = TypeChecker::errorUnion(
caughtErrorType, thrownErrorType,
[&](Type type) {
return simplifyType(type);
});
// If we ended up at 'any Error', we're done.
if (caughtErrorType->isErrorExistentialType())
break;
}
return caughtErrorType;
}
ConstraintLocator *ConstraintSystem::getConstraintLocator(
ASTNode anchor, ArrayRef<ConstraintLocator::PathElement> path) {
auto summaryFlags = ConstraintLocator::getSummaryFlagsForPath(path);
return getConstraintLocator(anchor, path, summaryFlags);
}
ConstraintLocator *ConstraintSystem::getConstraintLocator(
ASTNode 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;
auto anchor = builder.getLocatorParts(path);
return getConstraintLocator(anchor, path, builder.getSummaryFlags());
}
ConstraintLocator *ConstraintSystem::getConstraintLocator(
ConstraintLocator *locator,
ArrayRef<ConstraintLocator::PathElement> newElts) {
auto oldPath = locator->getPath();
SmallVector<ConstraintLocator::PathElement, 4> newPath;
newPath.append(oldPath.begin(), oldPath.end());
newPath.append(newElts.begin(), newElts.end());
return getConstraintLocator(locator->getAnchor(), newPath);
}
ConstraintLocator *ConstraintSystem::getConstraintLocator(
const ConstraintLocatorBuilder &builder,
ArrayRef<ConstraintLocator::PathElement> newElts) {
SmallVector<ConstraintLocator::PathElement, 4> newPath;
auto anchor = builder.getLocatorParts(newPath);
newPath.append(newElts.begin(), newElts.end());
return getConstraintLocator(anchor, newPath);
}
ConstraintLocator *ConstraintSystem::getImplicitValueConversionLocator(
ConstraintLocatorBuilder root, ConversionRestrictionKind restriction) {
SmallVector<LocatorPathElt, 4> path;
auto anchor = root.getLocatorParts(path);
{
if (isExpr<DictionaryExpr>(anchor) && path.size() > 1) {
// Drop everything except for first `tuple element #`.
path.pop_back_n(path.size() - 1);
}
// Drop any value-to-optional conversions that were applied along the
// way to reach this one.
while (!path.empty()) {
if (path.back().is<LocatorPathElt::OptionalInjection>()) {
path.pop_back();
continue;
}
break;
}
// If conversion is for a tuple element, let's drop `TupleType`
// components from the path since they carry information for
// diagnostics that `ExprRewriter` won't be able to re-construct
// during solution application.
if (!path.empty() && path.back().is<LocatorPathElt::TupleElement>()) {
path.erase(llvm::remove_if(path,
[](const LocatorPathElt &elt) {
return elt.is<LocatorPathElt::TupleType>();
}),
path.end());
}
}
return getConstraintLocator(/*base=*/getConstraintLocator(anchor, path),
LocatorPathElt::ImplicitConversion(restriction));
}
ConstraintLocator *ConstraintSystem::getCalleeLocator(
ConstraintLocator *locator, bool lookThroughApply,
llvm::function_ref<Type(Expr *)> getType,
llvm::function_ref<Type(Type)> simplifyType,
llvm::function_ref<std::optional<SelectedOverload>(ConstraintLocator *)>
getOverloadFor) {
if (locator->findLast<LocatorPathElt::ImplicitConversion>())
return locator;
auto anchor = locator->getAnchor();
auto path = locator->getPath();
{
// If we have an implicit x[dynamicMember:] subscript call, the callee
// is given by the original member locator it is based on, which we can get
// by stripping away the implicit member element and everything after it.
auto iter = path.rbegin();
using ImplicitSubscriptElt = LocatorPathElt::ImplicitDynamicMemberSubscript;
if (locator->findLast<ImplicitSubscriptElt>(iter)) {
auto newPath = path.drop_back(iter - path.rbegin() + 1);
return getConstraintLocator(anchor, newPath);
}
}
{
// If we have a locator for a member found through key path dynamic member
// lookup, then we need to chop off the elements after the
// KeyPathDynamicMember element to get the callee locator.
auto iter = path.rbegin();
if (locator->findLast<LocatorPathElt::KeyPathDynamicMember>(iter)) {
auto newPath = path.drop_back(iter - path.rbegin());
return getConstraintLocator(anchor, newPath);
}
}
{
// Pattern match is always a callee regardless of what comes after it.
auto iter = path.rbegin();
if (locator->findLast<LocatorPathElt::PatternMatch>(iter)) {
auto newPath = path.drop_back(iter - path.rbegin());
return getConstraintLocator(anchor, newPath);
}
}
if (locator->findLast<LocatorPathElt::DynamicCallable>()) {
return getConstraintLocator(anchor, LocatorPathElt::ApplyFunction());
}
if (locator->isLastElement<LocatorPathElt::ArgumentAttribute>()) {
return getConstraintLocator(anchor, path.drop_back());
}
// If we have a locator that starts with a key path component element, we
// may have a callee given by a property or subscript component.
if (auto componentElt =
locator->getFirstElementAs<LocatorPathElt::KeyPathComponent>()) {
auto *kpExpr = castToExpr<KeyPathExpr>(anchor);
auto component = kpExpr->getComponents()[componentElt->getIndex()];
using ComponentKind = KeyPathExpr::Component::Kind;
switch (component.getKind()) {
case ComponentKind::UnresolvedSubscript:
case ComponentKind::Subscript:
// For a subscript the callee is given by 'component -> subscript member'.
return getConstraintLocator(
anchor, {*componentElt, ConstraintLocator::SubscriptMember});
case ComponentKind::UnresolvedProperty:
case ComponentKind::Property:
// For a property, the choice is just given by the component.
return getConstraintLocator(anchor, *componentElt);
case ComponentKind::TupleElement:
llvm_unreachable("Not implemented by CSGen");
break;
case ComponentKind::Invalid:
case ComponentKind::OptionalForce:
case ComponentKind::OptionalChain:
case ComponentKind::OptionalWrap:
case ComponentKind::Identity:
case ComponentKind::DictionaryKey:
case ComponentKind::CodeCompletion:
// These components don't have any callee associated, so just continue.
break;
}
}
// Make sure we handle subscripts before looking at apply exprs. We don't
// want to return a subscript member locator for an expression such as x[](y),
// as its callee is not the subscript, but rather the function it returns.
if (isExpr<SubscriptExpr>(anchor))
return getConstraintLocator(anchor, ConstraintLocator::SubscriptMember);
auto getSpecialFnCalleeLoc = [&](Type fnTy) -> ConstraintLocator * {
fnTy = simplifyType(fnTy);
// It's okay for function type to contain type variable(s) e.g.
// opened generic function types, but not to be one.
assert(!fnTy->is<TypeVariableType>());
// For an apply of a metatype, we have a short-form constructor. Unlike
// other locators to callees, these are anchored on the apply expression
// rather than the function expr.
if (fnTy->is<AnyMetatypeType>()) {
return getConstraintLocator(anchor,
{LocatorPathElt::ApplyFunction(),
LocatorPathElt::ConstructorMember()});
}
// Handle an apply of a nominal type which supports callAsFunction.
if (fnTy->isCallAsFunctionType(DC)) {
return getConstraintLocator(anchor,
{LocatorPathElt::ApplyFunction(),
LocatorPathElt::ImplicitCallAsFunction()});
}
// Handling an apply for a nominal type that supports @dynamicCallable.
if (fnTy->hasDynamicCallableAttribute()) {
return getConstraintLocator(anchor, LocatorPathElt::ApplyFunction());
}
return nullptr;
};
if (lookThroughApply) {
if (auto *applyExpr = getAsExpr<ApplyExpr>(anchor)) {
auto *fnExpr = applyExpr->getFn();
// Handle special cases for applies of non-function types.
if (auto *loc = getSpecialFnCalleeLoc(getType(fnExpr)))
return loc;
// Otherwise fall through and look for locators anchored on the function
// expr. For CallExprs, this can look through things like parens and
// optional chaining.
if (auto *callExpr = getAsExpr<CallExpr>(anchor)) {
anchor = callExpr->getDirectCallee();
} else {
anchor = fnExpr;
}
}
}
if (auto *UDE = getAsExpr<UnresolvedDotExpr>(anchor)) {
if (UDE->isImplicit() &&
UDE->getName().getBaseName() == Context.Id_callAsFunction) {
return getConstraintLocator(anchor,
{LocatorPathElt::ApplyFunction(),
LocatorPathElt::ImplicitCallAsFunction()});
}
return getConstraintLocator(
anchor, TypeChecker::getSelfForInitDelegationInConstructor(DC, UDE)
? ConstraintLocator::ConstructorMember
: ConstraintLocator::Member);
}
if (auto *UME = getAsExpr<UnresolvedMemberExpr>(anchor)) {
return getConstraintLocator(UME, ConstraintLocator::UnresolvedMember);
}
if (isExpr<MemberRefExpr>(anchor))
return getConstraintLocator(anchor, ConstraintLocator::Member);
if (isExpr<ObjectLiteralExpr>(anchor))
return getConstraintLocator(anchor, ConstraintLocator::ConstructorMember);
if (locator->isFirstElement<LocatorPathElt::CoercionOperand>()) {
auto *CE = castToExpr<CoerceExpr>(anchor);
locator = getConstraintLocator(CE->getSubExpr()->getValueProvidingExpr(),
path.drop_front());
return getCalleeLocator(locator, lookThroughApply, getType, simplifyType,
getOverloadFor);
}
if (auto FVE = getAsExpr<ForceValueExpr>(anchor))
return getConstraintLocator(FVE->getSubExpr(), ConstraintLocator::Member);
return getConstraintLocator(anchor);
}
ConstraintLocator *ConstraintSystem::getOpenOpaqueLocator(
ConstraintLocatorBuilder locator, OpaqueTypeDecl *opaqueDecl) {
// Use only the opaque type declaration.
return getConstraintLocator(
ASTNode(opaqueDecl),
{ LocatorPathElt::OpenedOpaqueArchetype(opaqueDecl) }, 0);
}
std::pair<Type, OpenedArchetypeType *>
ConstraintSystem::openAnyExistentialType(Type type,
ConstraintLocator *locator) {
Type result = OpenedArchetypeType::getAny(type);
Type t = result;
while (t->is<MetatypeType>())
t = t->getMetatypeInstanceType();
auto *opened = t->castTo<OpenedArchetypeType>();
recordOpenedExistentialType(locator, opened);
return {result, opened};
}
void ConstraintSystem::recordOpenedExistentialType(
ConstraintLocator *locator, OpenedArchetypeType *opened) {
bool inserted = OpenedExistentialTypes.insert({locator, opened}).second;
ASSERT(inserted);
if (solverState)
recordChange(SolverTrail::Change::RecordedOpenedExistentialType(locator));
}
GenericEnvironment *
ConstraintSystem::getPackExpansionEnvironment(PackExpansionExpr *expr) const {
auto result = PackExpansionEnvironments.find(expr);
if (result == PackExpansionEnvironments.end())
return nullptr;
return result->second;
}
GenericEnvironment *ConstraintSystem::createPackExpansionEnvironment(
PackExpansionExpr *expr, CanGenericTypeParamType shapeParam) {
auto *contextEnv = DC->getGenericEnvironmentOfContext();
auto elementSig = getASTContext().getOpenedElementSignature(
contextEnv->getGenericSignature().getCanonicalSignature(), shapeParam);
auto contextSubs = contextEnv->getForwardingSubstitutionMap();
auto *env = GenericEnvironment::forOpenedElement(elementSig, UUID::fromTime(),
shapeParam, contextSubs);
recordPackExpansionEnvironment(expr, env);
return env;
}
void ConstraintSystem::recordPackExpansionEnvironment(PackExpansionExpr *expr,
GenericEnvironment *env) {
bool inserted = PackExpansionEnvironments.insert({expr, env}).second;
ASSERT(inserted);
if (solverState)
recordChange(SolverTrail::Change::RecordedPackExpansionEnvironment(expr));
}
PackExpansionExpr *
ConstraintSystem::getPackElementExpansion(PackElementExpr *packElement) const {
const auto match = PackElementExpansions.find(packElement);
return (match == PackElementExpansions.end()) ? nullptr : match->second;
}
void ConstraintSystem::recordPackElementExpansion(
PackElementExpr *packElement, PackExpansionExpr *packExpansion) {
bool inserted =
PackElementExpansions.insert({packElement, packExpansion}).second;
ASSERT(inserted);
if (solverState) {
recordChange(
SolverTrail::Change::RecordedPackElementExpansion(packElement));
}
}
/// Extend the given depth map by adding depths for all of the subexpressions
/// of the given expression.
static void extendDepthMap(
Expr *expr,
llvm::DenseMap<Expr *, std::pair<unsigned, Expr *>> &depthMap) {
// If we already have an entry in the map, we don't need to update it. This
// avoids invalidating previous entries when solving a smaller component of a
// larger AST node, e.g during conjunction solving.
if (depthMap.contains(expr))
return;
class RecordingTraversal : public ASTWalker {
SmallVector<ClosureExpr *, 4> Closures;
public:
llvm::DenseMap<Expr *, std::pair<unsigned, Expr *>> &DepthMap;
unsigned Depth = 0;
explicit RecordingTraversal(
llvm::DenseMap<Expr *, std::pair<unsigned, Expr *>> &depthMap)
: DepthMap(depthMap) {}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
// For argument lists, bump the depth of the arguments, as they are
// effectively nested within the argument list. It's debatable whether we
// should actually do this, as it doesn't reflect the true expression depth,
// but it's needed to preserve compatibility with the behavior from when
// TupleExpr and ParenExpr were used to represent argument lists.
PreWalkResult<ArgumentList *>
walkToArgumentListPre(ArgumentList *ArgList) override {
++Depth;
return Action::Continue(ArgList);
}
PostWalkResult<ArgumentList *>
walkToArgumentListPost(ArgumentList *ArgList) override {
--Depth;
return Action::Continue(ArgList);
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
DepthMap[E] = {Depth, Parent.getAsExpr()};
++Depth;
if (auto CE = dyn_cast<ClosureExpr>(E))
Closures.push_back(CE);
return Action::Continue(E);
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
if (auto CE = dyn_cast<ClosureExpr>(E)) {
assert(Closures.back() == CE);
Closures.pop_back();
}
--Depth;
return Action::Continue(E);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
if (auto RS = dyn_cast<ReturnStmt>(S)) {
// For return statements, treat the parent of the return expression
// as the closure itself.
if (RS->hasResult() && !Closures.empty()) {
llvm::SaveAndRestore<ParentTy> SavedParent(Parent, Closures.back());
auto E = RS->getResult();
E->walk(*this);
return Action::SkipNode(S);
}
}