-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
CSApply.cpp
8362 lines (7118 loc) · 321 KB
/
CSApply.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
//===--- CSApply.cpp - Constraint Application -----------------------------===//
//
// 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 application of a solution to a constraint
// system to a particular expression, resulting in a
// fully-type-checked expression.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "CodeSynthesis.h"
#include "CSDiagnostics.h"
#include "MiscDiagnostics.h"
#include "SolutionResult.h"
#include "TypeCheckProtocol.h"
#include "TypeCheckType.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/Basic/StringExtras.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace constraints;
/// Retrieve the fixed type for the given type variable.
Type Solution::getFixedType(TypeVariableType *typeVar) const {
auto knownBinding = typeBindings.find(typeVar);
assert(knownBinding != typeBindings.end());
return knownBinding->second;
}
/// Determine whether the given type is an opened AnyObject.
///
/// This comes up in computeSubstitutions() when accessing
/// members via dynamic lookup.
static bool isOpenedAnyObject(Type type) {
auto archetype = type->getAs<OpenedArchetypeType>();
if (!archetype)
return false;
return archetype->getOpenedExistentialType()->isAnyObject();
}
SubstitutionMap
Solution::computeSubstitutions(GenericSignature sig,
ConstraintLocator *locator) const {
if (sig.isNull())
return SubstitutionMap();
// Gather the substitutions from dependent types to concrete types.
auto openedTypes = OpenedTypes.find(locator);
// If we have a member reference on an existential, there are no
// opened types or substitutions.
if (openedTypes == OpenedTypes.end())
return SubstitutionMap();
TypeSubstitutionMap subs;
for (const auto &opened : openedTypes->second)
subs[opened.first] = getFixedType(opened.second);
auto lookupConformanceFn =
[&](CanType original, Type replacement,
ProtocolDecl *protoType) -> ProtocolConformanceRef {
if (replacement->hasError() ||
isOpenedAnyObject(replacement) ||
replacement->is<GenericTypeParamType>()) {
return ProtocolConformanceRef(protoType);
}
// FIXME: Retrieve the conformance from the solution itself.
return TypeChecker::conformsToProtocol(replacement, protoType,
getConstraintSystem().DC,
ConformanceCheckFlags::InExpression);
};
return SubstitutionMap::get(sig,
QueryTypeSubstitutionMap{subs},
lookupConformanceFn);
}
ConcreteDeclRef
Solution::resolveConcreteDeclRef(ValueDecl *decl,
ConstraintLocator *locator) const {
if (!decl)
return ConcreteDeclRef();
// Get the generic signatue of the decl and compute the substitutions.
auto sig = decl->getInnermostDeclContext()->getGenericSignatureOfContext();
return ConcreteDeclRef(decl, computeSubstitutions(sig, locator));
}
static bool shouldAccessStorageDirectly(Expr *base, VarDecl *member,
DeclContext *DC) {
// This only matters for stored properties.
if (!member->hasStorage())
return false;
// ... referenced from constructors and destructors.
auto *AFD = dyn_cast<AbstractFunctionDecl>(DC);
if (AFD == nullptr)
return false;
if (!isa<ConstructorDecl>(AFD) && !isa<DestructorDecl>(AFD))
return false;
// ... via a "self.property" reference.
auto *DRE = dyn_cast<DeclRefExpr>(base);
if (DRE == nullptr)
return false;
if (AFD->getImplicitSelfDecl() != cast<DeclRefExpr>(base)->getDecl())
return false;
// Convenience initializers do not require special handling.
// FIXME: This is a language change -- for now, keep the old behavior
#if 0
if (auto *CD = dyn_cast<ConstructorDecl>(AFD))
if (!CD->isDesignatedInit())
return false;
#endif
// Ctor or dtor are for immediate class, not a derived class.
if (!AFD->getParent()->getDeclaredInterfaceType()->isEqual(
member->getDeclContext()->getDeclaredInterfaceType()))
return false;
// If the storage is resilient, we cannot access it directly at all.
if (member->isResilient(DC->getParentModule(),
DC->getResilienceExpansion()))
return false;
return true;
}
ConstraintLocator *Solution::getCalleeLocator(ConstraintLocator *locator,
bool lookThroughApply) const {
auto &cs = getConstraintSystem();
return cs.getCalleeLocator(
locator, lookThroughApply,
[&](const Expr *expr) -> Type { return getType(expr); },
[&](Type type) -> Type { return simplifyType(type)->getRValueType(); },
[&](ConstraintLocator *locator) -> Optional<SelectedOverload> {
return getOverloadChoiceIfAvailable(locator);
});
}
ConstraintLocator *
Solution::getConstraintLocator(Expr *anchor,
ArrayRef<LocatorPathElt> path) const {
auto &cs = getConstraintSystem();
return cs.getConstraintLocator(anchor, path);
}
/// Return the implicit access kind for a MemberRefExpr with the
/// specified base and member in the specified DeclContext.
static AccessSemantics
getImplicitMemberReferenceAccessSemantics(Expr *base, VarDecl *member,
DeclContext *DC) {
// Properties that have storage and accessors are frequently accessed through
// accessors. However, in the init and destructor methods for the type
// immediately containing the property, accesses are done direct.
if (shouldAccessStorageDirectly(base, member, DC)) {
// Access this directly instead of going through (e.g.) observing or
// trivial accessors.
return AccessSemantics::DirectToStorage;
}
// Check whether this is a member access on 'self'.
bool isAccessOnSelf = false;
if (auto *baseDRE = dyn_cast<DeclRefExpr>(base->getValueProvidingExpr()))
if (auto *baseVar = dyn_cast<VarDecl>(baseDRE->getDecl()))
isAccessOnSelf = baseVar->isSelfParameter();
// If the value is always directly accessed from this context, do it.
return member->getAccessSemanticsFromContext(DC, isAccessOnSelf);
}
/// This extends functionality of `Expr::isTypeReference` with
/// support for `UnresolvedDotExpr` and `UnresolvedMemberExpr`.
/// This method could be used on not yet fully type-checked AST.
bool ConstraintSystem::isTypeReference(const Expr *E) {
return E->isTypeReference(
[&](const Expr *E) -> Type { return simplifyType(getType(E)); },
[&](const Expr *E) -> Decl * {
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(E)) {
return findResolvedMemberRef(
getConstraintLocator(UDE, ConstraintLocator::Member));
}
if (auto *UME = dyn_cast<UnresolvedMemberExpr>(E)) {
return findResolvedMemberRef(
getConstraintLocator(UME, ConstraintLocator::UnresolvedMember));
}
if (isa<OverloadSetRefExpr>(E))
return findResolvedMemberRef(
getConstraintLocator(const_cast<Expr *>(E)));
return nullptr;
});
}
bool ConstraintSystem::isStaticallyDerivedMetatype(const Expr *E) {
return E->isStaticallyDerivedMetatype(
[&](const Expr *E) -> Type { return simplifyType(getType(E)); },
[&](const Expr *E) -> bool { return isTypeReference(E); });
}
Type ConstraintSystem::getInstanceType(const TypeExpr *E) {
return E->getInstanceType([&](const Expr *E) -> bool { return hasType(E); },
[&](const Expr *E) -> Type { return getType(E); });
}
Type ConstraintSystem::getResultType(const AbstractClosureExpr *E) {
return E->getResultType([&](const Expr *E) -> Type { return getType(E); });
}
static bool buildObjCKeyPathString(KeyPathExpr *E,
llvm::SmallVectorImpl<char> &buf) {
for (auto &component : E->getComponents()) {
switch (component.getKind()) {
case KeyPathExpr::Component::Kind::OptionalChain:
case KeyPathExpr::Component::Kind::OptionalForce:
case KeyPathExpr::Component::Kind::OptionalWrap:
// KVC propagates nulls, so these don't affect the key path string.
continue;
case KeyPathExpr::Component::Kind::Identity:
// The identity component can be elided from the KVC string (unless it's
// the only component, in which case we use @"self").
continue;
case KeyPathExpr::Component::Kind::Property: {
// Property references must be to @objc properties.
// TODO: If we added special properties matching KVC operators like '@sum',
// '@count', etc. those could be mapped too.
auto property = cast<VarDecl>(component.getDeclRef().getDecl());
if (!property->isObjC())
return false;
if (!buf.empty()) {
buf.push_back('.');
}
auto objcName = property->getObjCPropertyName().str();
buf.append(objcName.begin(), objcName.end());
continue;
}
case KeyPathExpr::Component::Kind::TupleElement:
case KeyPathExpr::Component::Kind::Subscript:
// Subscripts and tuples aren't generally represented in KVC.
// TODO: There are some subscript forms we could map to KVC, such as
// when indexing a Dictionary or NSDictionary by string, or when applying
// a mapping subscript operation to Array/Set or NSArray/NSSet.
return false;
case KeyPathExpr::Component::Kind::Invalid:
case KeyPathExpr::Component::Kind::UnresolvedProperty:
case KeyPathExpr::Component::Kind::UnresolvedSubscript:
// Don't bother building the key path string if the key path didn't even
// resolve.
return false;
}
}
// If there are no non-identity components, this is the "self" key.
if (buf.empty()) {
auto self = StringRef("self");
buf.append(self.begin(), self.end());
}
return true;
}
namespace {
/// Rewrites an expression by applying the solution of a constraint
/// system to that expression.
class ExprRewriter : public ExprVisitor<ExprRewriter, Expr *> {
public:
ConstraintSystem &cs;
DeclContext *dc;
Solution &solution;
bool SuppressDiagnostics;
/// Coerce the given tuple to another tuple type.
///
/// \param expr The expression we're converting.
///
/// \param fromTuple The tuple type we're converting from, which is the same
/// as \c expr->getType().
///
/// \param toTuple The tuple type we're converting to.
///
/// \param locator Locator describing where this tuple conversion occurs.
///
/// \param sources The sources of each of the elements to be used in the
/// resulting tuple, as provided by \c computeTupleShuffle.
Expr *coerceTupleToTuple(Expr *expr, TupleType *fromTuple,
TupleType *toTuple,
ConstraintLocatorBuilder locator,
ArrayRef<unsigned> sources);
/// Coerce a subclass, class-constrained archetype, class-constrained
/// existential or to a superclass type.
///
/// Also supports metatypes of the above.
///
/// \param expr The expression to be coerced.
/// \param toType The type to which the expression will be coerced.
///
/// \return The coerced expression, whose type will be equivalent to
/// \c toType.
Expr *coerceSuperclass(Expr *expr, Type toType);
/// Coerce the given value to existential type.
///
/// The following conversions are supported:
/// - concrete to existential
/// - existential to existential
/// - concrete metatype to existential metatype
/// - existential metatype to existential metatype
///
/// \param expr The expression to be coerced.
/// \param toType The type to which the expression will be coerced.
///
/// \return The coerced expression, whose type will be equivalent to
/// \c toType.
Expr *coerceExistential(Expr *expr, Type toType);
/// Coerce an expression of (possibly unchecked) optional
/// type to have a different (possibly unchecked) optional type.
Expr *coerceOptionalToOptional(Expr *expr, Type toType,
ConstraintLocatorBuilder locator,
Optional<Pattern*> typeFromPattern = None);
/// Coerce an expression of implicitly unwrapped optional type to its
/// underlying value type, in the correct way for an implicit
/// look-through.
Expr *coerceImplicitlyUnwrappedOptionalToValue(Expr *expr, Type objTy);
/// Peephole an array upcast.
void peepholeArrayUpcast(ArrayExpr *expr, Type toType, bool bridged,
Type elementType,
ConstraintLocatorBuilder locator);
/// Peephole a dictionary upcast.
void peepholeDictionaryUpcast(DictionaryExpr *expr, Type toType,
bool bridged, Type keyType,
Type valueType,
ConstraintLocatorBuilder locator);
/// Try to peephole the collection upcast, eliminating the need for
/// a separate collection-upcast expression.
///
/// \returns true if the peephole operation succeeded, in which case
/// \c expr already subsumes the upcast.
bool peepholeCollectionUpcast(Expr *expr, Type toType, bool bridged,
ConstraintLocatorBuilder locator);
/// Build a collection upcast expression.
///
/// \param bridged Whether this is a bridging conversion, meaning that the
/// element types themselves are bridged (vs. simply coerced).
Expr *buildCollectionUpcastExpr(Expr *expr, Type toType,
bool bridged,
ConstraintLocatorBuilder locator);
/// Build the expression that performs a bridging operation from the
/// given expression to the given \c toType.
Expr *buildObjCBridgeExpr(Expr *expr, Type toType,
ConstraintLocatorBuilder locator);
static Type getBaseType(AnyFunctionType *fnType,
bool wantsRValueInstanceType = true) {
auto params = fnType->getParams();
assert(params.size() == 1);
const auto &base = params.front();
if (wantsRValueInstanceType)
return base.getPlainType()->getMetatypeInstanceType();
return base.getOldType();
}
// Returns None if the AST does not contain enough information to recover
// substitutions; this is different from an Optional(SubstitutionMap()),
// indicating a valid call to a non-generic operator.
Optional<SubstitutionMap>
getOperatorSubstitutions(ValueDecl *witness, Type refType) {
// We have to recover substitutions in this hacky way because
// the AST does not retain enough information to devirtualize
// calls like this.
auto witnessType = witness->getInterfaceType();
// Compute the substitutions.
auto *gft = witnessType->getAs<GenericFunctionType>();
if (gft == nullptr) {
if (refType->isEqual(witnessType))
return SubstitutionMap();
return None;
}
auto sig = gft->getGenericSignature();
auto *env = sig->getGenericEnvironment();
witnessType = FunctionType::get(gft->getParams(),
gft->getResult(),
gft->getExtInfo());
witnessType = env->mapTypeIntoContext(witnessType);
TypeSubstitutionMap subs;
auto substType = witnessType->substituteBindingsTo(
refType,
[&](ArchetypeType *origType, CanType substType,
ArchetypeType*, ArrayRef<ProtocolConformanceRef>) -> CanType {
if (auto gpType = dyn_cast<GenericTypeParamType>(
origType->getInterfaceType()->getCanonicalType()))
subs[gpType] = substType;
return substType;
});
// If substitution failed, it means that the protocol requirement type
// and the witness type did not match up. The only time that this
// should happen is when the witness is defined in a base class and
// the actual call uses a derived class. For example,
//
// protocol P { func +(lhs: Self, rhs: Self) }
// class Base : P { func +(lhs: Base, rhs: Base) {} }
// class Derived : Base {}
//
// If we enter this code path with two operands of type Derived,
// we know we're calling the protocol requirement P.+, with a
// substituted type of (Derived, Derived) -> (). But the type of
// the witness is (Base, Base) -> (). Just bail out and make a
// witness method call in this rare case; SIL mandatory optimizations
// will likely devirtualize it anyway.
if (!substType)
return None;
return SubstitutionMap::get(sig,
QueryTypeSubstitutionMap{subs},
TypeChecker::LookUpConformance(cs.DC));
}
public:
/// Build a reference to the given declaration.
Expr *buildDeclRef(SelectedOverload overload, DeclNameLoc loc,
ConstraintLocatorBuilder locator, bool implicit,
AccessSemantics semantics) {
auto choice = overload.choice;
assert(choice.getKind() != OverloadChoiceKind::DeclViaDynamic);
auto *decl = choice.getDecl();
auto fullType = simplifyType(overload.openedFullType);
// Determine the declaration selected for this overloaded reference.
auto &ctx = cs.getASTContext();
// If this is a member of a nominal type, build a reference to the
// member with an implied base type.
if (decl->getDeclContext()->isTypeContext() && isa<FuncDecl>(decl)) {
assert(cast<FuncDecl>(decl)->isOperator() && "Must be an operator");
auto baseTy = getBaseType(fullType->castTo<FunctionType>());
// Handle operator requirements found in protocols.
if (auto proto = dyn_cast<ProtocolDecl>(decl->getDeclContext())) {
bool isCurried = shouldBuildCurryThunk(choice,
/*baseIsInstance=*/false,
/*extraUncurryLevel=*/false);
// If we have a concrete conformance, build a call to the witness.
//
// FIXME: This is awful. We should be able to handle this as a call to
// the protocol requirement with Self == the concrete type, and SILGen
// (or later) can devirtualize as appropriate.
auto conformance =
TypeChecker::conformsToProtocol(
baseTy, proto, cs.DC,
ConformanceCheckFlags::InExpression);
if (conformance.isConcrete()) {
if (auto witness = conformance.getConcrete()->getWitnessDecl(decl)) {
bool isMemberOperator = witness->getDeclContext()->isTypeContext();
if (!isMemberOperator || !isCurried) {
// The fullType was computed by substituting the protocol
// requirement so it always has a (Self) -> ... curried
// application. Strip it off if the witness was a top-level
// function.
Type refType;
if (isMemberOperator)
refType = fullType;
else
refType = fullType->castTo<AnyFunctionType>()->getResult();
// Build the AST for the call to the witness.
auto subMap = getOperatorSubstitutions(witness, refType);
if (subMap) {
ConcreteDeclRef witnessRef(witness, *subMap);
auto declRefExpr = new (ctx) DeclRefExpr(witnessRef, loc,
/*Implicit=*/false);
declRefExpr->setFunctionRefKind(choice.getFunctionRefKind());
cs.setType(declRefExpr, refType);
Expr *refExpr;
if (isMemberOperator) {
// If the operator is a type member, add the implicit
// (Self) -> ... call.
Expr *base =
TypeExpr::createImplicitHack(loc.getBaseNameLoc(), baseTy,
ctx);
cs.setType(base, MetatypeType::get(baseTy));
refExpr = new (ctx) DotSyntaxCallExpr(declRefExpr,
SourceLoc(), base);
auto refType = fullType->castTo<FunctionType>()->getResult();
cs.setType(refExpr, refType);
} else {
refExpr = declRefExpr;
}
return forceUnwrapIfExpected(refExpr, choice, locator);
}
}
}
}
}
// Build a reference to the member.
Expr *base =
TypeExpr::createImplicitHack(loc.getBaseNameLoc(), baseTy, ctx);
cs.cacheExprTypes(base);
return buildMemberRef(base, SourceLoc(), overload, loc, locator,
locator, implicit, /*extraUncurryLevel=*/false,
semantics);
}
if (isa<TypeDecl>(decl) && !isa<ModuleDecl>(decl)) {
auto typeExpr = TypeExpr::createImplicitHack(
loc.getBaseNameLoc(), fullType->getMetatypeInstanceType(), ctx);
cs.cacheType(typeExpr);
return typeExpr;
}
auto ref = resolveConcreteDeclRef(decl, locator);
auto declRefExpr =
new (ctx) DeclRefExpr(ref, loc, implicit, semantics, fullType);
cs.cacheType(declRefExpr);
declRefExpr->setFunctionRefKind(choice.getFunctionRefKind());
return forceUnwrapIfExpected(declRefExpr, choice, locator);
}
/// Describes an opened existential that has not yet been closed.
struct OpenedExistential {
/// The archetype describing this opened existential.
OpenedArchetypeType *Archetype;
/// The existential value being opened.
Expr *ExistentialValue;
/// The opaque value (of archetype type) stored within the
/// existential.
OpaqueValueExpr *OpaqueValue;
/// The depth of this currently-opened existential. Once the
/// depth of the expression stack is equal to this value, the
/// existential can be closed.
unsigned Depth;
};
/// A stack of opened existentials that have not yet been closed.
/// Ordered by decreasing depth.
llvm::SmallVector<OpenedExistential, 2> OpenedExistentials;
/// A stack of expressions being walked, used to compute existential depth.
llvm::SmallVector<Expr *, 8> ExprStack;
/// A map of apply exprs to their callee locators. This is necessary
/// because after rewriting an apply's function expr, its callee locator
/// will no longer be equivalent to the one stored in the solution.
llvm::DenseMap<ApplyExpr *, ConstraintLocator *> CalleeLocators;
/// A cache of decl references with their contextual substitutions for a
/// given callee locator.
llvm::DenseMap<ConstraintLocator *, ConcreteDeclRef> CachedConcreteRefs;
/// Resolves the contextual substitutions for a reference to a declaration
/// at a given locator. This should be preferred to
/// Solution::resolveConcreteDeclRef as it caches the result.
ConcreteDeclRef
resolveConcreteDeclRef(ValueDecl *decl, ConstraintLocatorBuilder locator) {
if (!decl)
return ConcreteDeclRef();
// Cache the resulting concrete reference. Ideally this would be done on
// Solution, however unfortunately that would require a const_cast which
// would be undefined behaviour if we ever had a `const Solution`.
auto *loc = getConstraintSystem().getConstraintLocator(locator);
auto &ref = CachedConcreteRefs[loc];
if (!ref)
ref = solution.resolveConcreteDeclRef(decl, loc);
assert(ref.getDecl() == decl);
return ref;
}
/// Members which are AbstractFunctionDecls but not FuncDecls cannot
/// mutate self.
bool isNonMutatingMember(ValueDecl *member) {
if (!isa<AbstractFunctionDecl>(member))
return false;
return !isa<FuncDecl>(member) || !cast<FuncDecl>(member)->isMutating();
}
/// If the expression might be a dynamic method call, return the base
/// value for the call.
Expr *getBaseExpr(Expr *expr) {
// Keep going up as long as this expression is the parent's base.
if (auto unresolvedDot = dyn_cast<UnresolvedDotExpr>(expr)) {
return unresolvedDot->getBase();
// Remaining cases should only come up when we're re-typechecking.
// FIXME: really it would be much better if Sema had stricter phase
// separation.
} else if (auto dotSyntax = dyn_cast<DotSyntaxCallExpr>(expr)) {
return dotSyntax->getArg();
} else if (auto ctorRef = dyn_cast<ConstructorRefCallExpr>(expr)) {
return ctorRef->getArg();
} else if (auto apply = dyn_cast<ApplyExpr>(expr)) {
return apply->getFn();
} else if (auto lookupRef = dyn_cast<LookupExpr>(expr)) {
return lookupRef->getBase();
} else if (auto load = dyn_cast<LoadExpr>(expr)) {
return load->getSubExpr();
} else if (auto inout = dyn_cast<InOutExpr>(expr)) {
return inout->getSubExpr();
} else if (auto force = dyn_cast<ForceValueExpr>(expr)) {
return force->getSubExpr();
} else {
return nullptr;
}
}
/// Calculates the nesting depth of the current application.
unsigned getArgCount(unsigned maxArgCount) {
unsigned e = ExprStack.size();
unsigned argCount;
// Starting from the current expression, count up if the expression is
// equal to its parent expression's base.
Expr *prev = ExprStack.back();
for (argCount = 1; argCount < maxArgCount && argCount < e; argCount++) {
Expr *result = ExprStack[e - argCount - 1];
Expr *base = getBaseExpr(result);
if (base != prev)
break;
prev = result;
}
return argCount;
}
/// Open an existential value into a new, opaque value of
/// archetype type.
///
/// \param base An expression of existential type whose value will
/// be opened.
///
/// \param archetype The archetype that describes the opened existential
/// type.
///
/// \param member The member that is being referenced on the existential
/// type.
///
/// \returns An OpaqueValueExpr that provides a reference to the value
/// stored within the expression or its metatype (if the base was a
/// metatype).
Expr *openExistentialReference(Expr *base, OpenedArchetypeType *archetype,
ValueDecl *member) {
assert(archetype && "archetype not already opened?");
// Dig out the base type.
Type baseTy = cs.getType(base);
// Look through lvalues.
bool isLValue = false;
if (auto lvalueTy = baseTy->getAs<LValueType>()) {
isLValue = true;
baseTy = lvalueTy->getObjectType();
}
// Look through metatypes.
bool isMetatype = false;
if (auto metaTy = baseTy->getAs<AnyMetatypeType>()) {
isMetatype = true;
baseTy = metaTy->getInstanceType();
}
assert(baseTy->isAnyExistentialType() && "Type must be existential");
// If the base was an lvalue but it will only be treated as an
// rvalue, turn the base into an rvalue now. This results in
// better SILGen.
if (isLValue &&