forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSApply.cpp
7018 lines (6039 loc) · 270 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 - 2016 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 "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/Basic/StringExtras.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace constraints;
/// \brief Get a substitution corresponding to the type witness.
/// Inspired by ProtocolConformance::getTypeWitnessByName.
const Substitution *
getTypeWitnessByName(ProtocolConformance *conformance,
Identifier name,
LazyResolver *resolver) {
// Find the named requirement.
AssociatedTypeDecl *assocType = nullptr;
auto members = conformance->getProtocol()->lookupDirect(name);
for (auto member : members) {
assocType = dyn_cast<AssociatedTypeDecl>(member);
if (assocType)
break;
}
if (!assocType)
return nullptr;
assert(conformance && "Missing conformance information");
return &conformance->getTypeWitness(assocType, resolver);
}
/// \brief 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<ArchetypeType>();
if (!archetype)
return false;
auto existential = archetype->getOpenedExistentialType();
if (!existential)
return false;
SmallVector<ProtocolDecl *, 2> protocols;
existential->isExistentialType(protocols);
return protocols.size() == 1 &&
protocols[0]->isSpecificProtocol(KnownProtocolKind::AnyObject);
}
Type Solution::computeSubstitutions(
Type origType, DeclContext *dc,
Type openedType,
ConstraintLocator *locator,
SmallVectorImpl<Substitution> &result) const {
auto &tc = getConstraintSystem().getTypeChecker();
// Gather the substitutions from dependent types to concrete types.
auto openedTypes = OpenedTypes.find(locator);
assert(openedTypes != OpenedTypes.end() && "Missing opened type information");
TypeSubstitutionMap subs;
for (const auto &opened : openedTypes->second) {
subs[opened.first->castTo<GenericTypeParamType>()] =
getFixedType(opened.second);
}
// Produce the concrete form of the opened type.
Type type = simplifyType(tc, openedType);
auto mod = getConstraintSystem().DC->getParentModule();
GenericSignature *sig;
if (auto genericFn = origType->getAs<GenericFunctionType>()) {
sig = genericFn->getGenericSignature();
} else {
sig = dc->getGenericSignatureOfContext();
}
auto lookupConformanceFn =
[&](CanType original, Type replacement, ProtocolType *protoType)
-> ProtocolConformanceRef {
auto conformance = tc.conformsToProtocol(
replacement,
protoType->getDecl(),
getConstraintSystem().DC,
(ConformanceCheckFlags::InExpression|
ConformanceCheckFlags::Used));
(void)&isOpenedAnyObject;
assert((conformance ||
replacement->hasError() ||
isOpenedAnyObject(replacement) ||
replacement->is<GenericTypeParamType>()) &&
"Constraint system missed a conformance?");
// Put an abstract conformance in place if we don't already have one.
// FIXME: Feels like a hack
if (!conformance &&
(replacement->hasDependentProtocolConformances() ||
replacement->hasError()))
conformance = ProtocolConformanceRef(protoType->getDecl());
assert(conformance->isConcrete() ||
replacement->hasError() ||
replacement->hasDependentProtocolConformances());
return *conformance;
};
sig->getSubstitutions(*mod, subs, lookupConformanceFn, result);
return type;
}
/// \brief Find a particular named function witness for a type that conforms to
/// the given protocol.
///
/// \param tc The type check we're using.
///
/// \param dc The context in which we need a witness.
///
/// \param type The type whose witness to find.
///
/// \param proto The protocol to which the type conforms.
///
/// \param name The name of the requirement.
///
/// \param diag The diagnostic to emit if the protocol definition doesn't
/// have a requirement with the given name.
///
/// \returns The named witness, or nullptr if no witness could be found.
template <typename DeclTy>
static DeclTy *findNamedWitnessImpl(
TypeChecker &tc, DeclContext *dc, Type type,
ProtocolDecl *proto, DeclName name,
Diag<> diag,
Optional<ProtocolConformanceRef> conformance = None) {
// Find the named requirement.
DeclTy *requirement = nullptr;
for (auto member : proto->getMembers()) {
auto d = dyn_cast<DeclTy>(member);
if (!d || !d->hasName())
continue;
if (d->getFullName().matchesRef(name)) {
requirement = d;
break;
}
}
if (!requirement || requirement->isInvalid()) {
tc.diagnose(proto->getLoc(), diag);
return nullptr;
}
// Find the member used to satisfy the named requirement.
if (!conformance) {
conformance = tc.conformsToProtocol(type, proto, dc,
ConformanceCheckFlags::InExpression);
if (!conformance)
return nullptr;
}
// For a type with dependent conformance, just return the requirement from
// the protocol. There are no protocol conformance tables.
if (type->hasDependentProtocolConformances()) {
return requirement;
}
if (!conformance->isConcrete()) return nullptr;
auto concrete = conformance->getConcrete();
// FIXME: Dropping substitutions here.
return cast_or_null<DeclTy>(concrete->getWitness(requirement, &tc).getDecl());
}
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()->getDeclaredTypeOfContext()->getCanonicalType() !=
member->getDeclContext()->getDeclaredTypeOfContext()->getCanonicalType())
return false;
return true;
}
/// 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)) {
// The storage better not be resilient.
assert(member->hasFixedLayout(DC->getParentModule(),
DC->getResilienceExpansion()) &&
"Designated initializers and destructors of resilient types "
"cannot be @_transparent or defined in extensions");
// Access this directly instead of going through (e.g.) observing or
// trivial accessors.
return AccessSemantics::DirectToStorage;
}
// Check for property behavior initializations.
if (auto *AFD_DC = dyn_cast<AbstractFunctionDecl>(DC)) {
if (member->hasBehaviorNeedingInitialization() &&
// In a ctor.
isa<ConstructorDecl>(AFD_DC) &&
// Ctor is for immediate class, not a derived class.
AFD_DC->getParent()->getDeclaredTypeOfContext()->getCanonicalType() ==
member->getDeclContext()->getDeclaredTypeOfContext()->getCanonicalType() &&
// Is a "self.property" reference.
isa<DeclRefExpr>(base) &&
AFD_DC->getImplicitSelfDecl() == cast<DeclRefExpr>(base)->getDecl()) {
// Do definite initialization analysis to handle this property.
return AccessSemantics::BehaviorInitialization;
}
}
// If the value is always directly accessed from this context, do it.
return member->getAccessSemanticsFromContext(DC);
}
namespace {
/// \brief 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;
const Solution &solution;
bool SuppressDiagnostics;
bool SkipClosures;
/// Recognize used conformances from an imported type when we must emit
/// the witness table.
///
/// This arises in _BridgedStoredNSError, where we wouldn't
/// otherwise pull in the witness table, causing dynamic casts to
/// perform incorrectly, and _ErrorCodeProtocol, where we need to
/// check for _BridgedStoredNSError conformances on the
/// corresponding ErrorType.
void checkForImportedUsedConformances(Type toType) {
cs.getTypeChecker().useBridgedNSErrorConformances(dc, toType);
}
/// \brief 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.
///
/// \param variadicArgs The source indices that are mapped to the variadic
/// parameter of the resulting tuple, as provided by \c computeTupleShuffle.
///
/// \param typeFromPattern Optionally, the caller can specify the pattern
/// from where the toType is derived, so that we can deliver better fixit.
Expr *coerceTupleToTuple(Expr *expr, TupleType *fromTuple,
TupleType *toTuple,
ConstraintLocatorBuilder locator,
SmallVectorImpl<int> &sources,
SmallVectorImpl<unsigned> &variadicArgs,
Optional<Pattern*> typeFromPattern = None);
/// \brief Coerce the given scalar value to the given tuple type.
///
/// \param expr The expression to be coerced.
/// \param toTuple The tuple type to which the expression will be coerced.
/// \param toScalarIdx The index of the scalar field within the tuple type
/// \c toType.
/// \param locator Locator describing where this conversion occurs.
///
/// \returns The coerced expression, whose type will be equivalent to
/// \c toTuple.
Expr *coerceScalarToTuple(Expr *expr, TupleType *toTuple,
int toScalarIdx,
ConstraintLocatorBuilder locator);
/// \brief 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.
/// \param locator Locator describing where this conversion occurs.
///
/// \return The coerced expression, whose type will be equivalent to
/// \c toType.
Expr *coerceExistential(Expr *expr, Type toType,
ConstraintLocatorBuilder locator);
/// \brief 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);
/// \brief 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,
ConstraintLocatorBuilder locator);
public:
/// \brief Build a reference to the given declaration.
Expr *buildDeclRef(ValueDecl *decl, DeclNameLoc loc, Type openedType,
ConstraintLocatorBuilder locator,
bool specialized, bool implicit,
FunctionRefKind functionRefKind,
AccessSemantics semantics) {
// 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 openedFnType = openedType->castTo<FunctionType>();
auto simplifiedFnType
= simplifyType(openedFnType)->castTo<FunctionType>();
auto baseTy = simplifiedFnType->getInput()->getRValueInstanceType();
// Handle operator requirements found in protocols.
if (auto proto = dyn_cast<ProtocolDecl>(decl->getDeclContext())) {
// If we don't have an archetype or existential, we have to call 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.
if (!baseTy->is<ArchetypeType>() && !baseTy->isAnyExistentialType()) {
auto &tc = cs.getTypeChecker();
auto conformance =
tc.conformsToProtocol(baseTy, proto, cs.DC,
(ConformanceCheckFlags::InExpression|
ConformanceCheckFlags::Used));
if (conformance && conformance->isConcrete()) {
if (auto witnessRef =
conformance->getConcrete()->getWitness(decl, &tc)) {
// Hack up an AST that we can type-check (independently) to get
// it into the right form.
// FIXME: the hop through 'getDecl()' is because
// SpecializedProtocolConformance doesn't substitute into
// witnesses' ConcreteDeclRefs.
Type expectedFnType = simplifiedFnType->getResult();
Expr *refExpr;
ValueDecl *witness = witnessRef.getDecl();
if (witness->getDeclContext()->isTypeContext()) {
Expr *base =
TypeExpr::createImplicitHack(loc.getBaseNameLoc(), baseTy,
ctx);
refExpr = new (ctx) MemberRefExpr(base, SourceLoc(), witness,
loc, /*Implicit=*/true);
} else {
auto declRefExpr = new (ctx) DeclRefExpr(witness, loc,
/*Implicit=*/false);
declRefExpr->setFunctionRefKind(functionRefKind);
refExpr = declRefExpr;
}
if (tc.typeCheckExpression(refExpr, cs.DC,
TypeLoc::withoutLoc(expectedFnType),
CTP_CannotFail))
return nullptr;
// Remove an outer function-conversion expression. This
// happens when we end up referring to a witness for a
// superclass conformance, and 'Self' differs.
if (auto fnConv = dyn_cast<FunctionConversionExpr>(refExpr))
refExpr = fnConv->getSubExpr();
return refExpr;
}
}
}
}
// Build a reference to the protocol requirement.
Expr *base = TypeExpr::createImplicitHack(loc.getBaseNameLoc(), baseTy,
ctx);
return buildMemberRef(base, openedType, SourceLoc(), decl,
loc, openedFnType->getResult(),
locator, locator, implicit, functionRefKind,
semantics, /*isDynamic=*/false);
}
// If this is a declaration with generic function type, build a
// specialized reference to it.
if (auto genericFn
= decl->getInterfaceType()->getAs<GenericFunctionType>()) {
auto dc = decl->getInnermostDeclContext();
SmallVector<Substitution, 4> substitutions;
auto type = solution.computeSubstitutions(
genericFn, dc, openedType,
getConstraintSystem().getConstraintLocator(locator),
substitutions);
auto declRefExpr =
new (ctx) DeclRefExpr(ConcreteDeclRef(ctx, decl, substitutions),
loc, implicit, semantics, type);
declRefExpr->setFunctionRefKind(functionRefKind);
return declRefExpr;
}
auto type = simplifyType(openedType);
// If we've ended up trying to assign an inout type here, it means we're
// missing an ampersand in front of the ref.
if (auto inoutType = type->getAs<InOutType>()) {
auto &tc = cs.getTypeChecker();
tc.diagnose(loc.getBaseNameLoc(), diag::missing_address_of,
inoutType->getInOutObjectType())
.fixItInsert(loc.getBaseNameLoc(), "&");
return nullptr;
}
auto declRefExpr = new (ctx) DeclRefExpr(decl, loc, implicit, semantics,
type);
declRefExpr->setFunctionRefKind(functionRefKind);
return declRefExpr;
}
/// Describes an opened existential that has not yet been closed.
struct OpenedExistential {
/// The archetype describing this opened existential.
ArchetypeType *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;
/// 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();
}
unsigned getNaturalArgumentCount(ValueDecl *member) {
if (auto func = dyn_cast<AbstractFunctionDecl>(member)) {
// For functions, close the existential once the function
// has been fully applied.
return func->getNumParameterLists();
} else {
// For storage, close the existential either when it's
// accessed (if it's an rvalue only) or when it is loaded or
// stored (if it's an lvalue).
assert(isa<AbstractStorageDecl>(member) &&
"unknown member when opening existential");
return 1;
}
}
/// 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 memberRef = dyn_cast<MemberRefExpr>(expr)) {
return memberRef->getBase();
} else if (auto dynMemberRef = dyn_cast<DynamicMemberRefExpr>(expr)) {
return dynMemberRef->getBase();
} else if (auto subscriptRef = dyn_cast<SubscriptExpr>(expr)) {
return subscriptRef->getBase();
} else if (auto dynSubscriptRef = dyn_cast<DynamicSubscriptExpr>(expr)) {
return dynSubscriptRef->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, ArchetypeType *archetype,
ValueDecl *member) {
assert(archetype && "archetype not already opened?");
auto &tc = cs.getTypeChecker();
// Dig out the base type.
auto baseTy = base->getType();
// 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 &&
(isNonMutatingMember(member) ||
isMetatype || baseTy->isClassExistentialType())) {
base = tc.coerceToRValue(base);
isLValue = false;
}
// Determine the number of applications that need to occur before
// we can close this existential, and record it.
unsigned maxArgCount = getNaturalArgumentCount(member);
unsigned depth = ExprStack.size() - getArgCount(maxArgCount);
// Create the opaque opened value. If we started with a
// metatype, it's a metatype.
Type opaqueType = archetype;
if (isMetatype)
opaqueType = MetatypeType::get(opaqueType);
if (isLValue)
opaqueType = LValueType::get(opaqueType);
ASTContext &ctx = tc.Context;
auto archetypeVal = new (ctx) OpaqueValueExpr(base->getLoc(), opaqueType);
// Record the opened existential.
OpenedExistentials.push_back({archetype, base, archetypeVal, depth});
return archetypeVal;
}
/// Trying to close the active existential, if there is one.
bool closeExistential(Expr *&result, bool force=false) {
if (OpenedExistentials.empty())
return false;
auto &record = OpenedExistentials.back();
assert(record.Depth <= ExprStack.size() - 1);
if (!force && record.Depth < ExprStack.size() - 1)
return false;
// If we had a return type of 'Self', erase it.
ConstraintSystem &cs = solution.getConstraintSystem();
auto &tc = cs.getTypeChecker();
auto resultTy = result->getType();
if (resultTy->hasOpenedExistential(record.Archetype)) {
Type erasedTy = resultTy->eraseOpenedExistential(
cs.DC->getParentModule(),
record.Archetype);
result = coerceToType(result, erasedTy, nullptr);
}
// If the opaque value has an l-value access kind, then
// the OpenExistentialExpr isn't making a derived l-value, which
// means this is our only chance to propagate the l-value access kind
// down to the original existential value. Otherwise, propagateLVAK
// will handle this.
if (record.OpaqueValue->hasLValueAccessKind())
record.ExistentialValue->propagateLValueAccessKind(
record.OpaqueValue->getLValueAccessKind());
// Form the open-existential expression.
result = new (tc.Context) OpenExistentialExpr(
record.ExistentialValue,
record.OpaqueValue,
result);
OpenedExistentials.pop_back();
return true;
}
/// Is the given function a constructor of a class or protocol?
/// Such functions are subject to DynamicSelf manipulations.
///
/// We want to avoid taking the DynamicSelf paths for other
/// constructors for two reasons:
/// - it's an unnecessary cost
/// - optionality preservation has a problem with constructors on
/// optional types
static bool isPolymorphicConstructor(AbstractFunctionDecl *fn) {
if (!isa<ConstructorDecl>(fn))
return false;
auto *parent =
fn->getParent()->getAsGenericTypeOrGenericTypeExtensionContext();
return parent && (isa<ClassDecl>(parent) || isa<ProtocolDecl>(parent));
}
/// \brief Build a new member reference with the given base and member.
Expr *buildMemberRef(Expr *base, Type openedFullType, SourceLoc dotLoc,
ValueDecl *member, DeclNameLoc memberLoc,
Type openedType, ConstraintLocatorBuilder locator,
ConstraintLocatorBuilder memberLocator,
bool Implicit, FunctionRefKind functionRefKind,
AccessSemantics semantics, bool isDynamic) {
auto &tc = cs.getTypeChecker();
auto &context = tc.Context;
bool isSuper = base->isSuperExpr();
Type baseTy = base->getType()->getRValueType();
// Explicit member accesses are permitted to implicitly look
// through ImplicitlyUnwrappedOptional<T>.
if (!Implicit) {
if (auto objTy = cs.lookThroughImplicitlyUnwrappedOptionalType(baseTy)) {
base = coerceImplicitlyUnwrappedOptionalToValue(base, objTy, locator);
baseTy = objTy;
}
}
// Figure out the actual base type, and whether we have an instance of
// that type or its metatype.
bool baseIsInstance = true;
if (auto baseMeta = baseTy->getAs<AnyMetatypeType>()) {
baseIsInstance = false;
baseTy = baseMeta->getInstanceType();
// If the member is a constructor, verify that it can be legally
// referenced from this base.
if (auto ctor = dyn_cast<ConstructorDecl>(member)) {
if (!tc.diagnoseInvalidDynamicConstructorReferences(base, memberLoc,
baseMeta, ctor, SuppressDiagnostics))
return nullptr;
}
}
// Produce a reference to the member, the type of the container it
// resides in, and the type produced by the reference itself.
Type containerTy;
ConcreteDeclRef memberRef;
Type refTy;
Type dynamicSelfFnType;
if (member->getInterfaceType()->is<GenericFunctionType>() ||
openedFullType->hasTypeVariable()) {
// We require substitutions. Figure out what they are.
// Figure out the declaration context where we'll get the generic
// parameters.
auto dc = member->getInnermostDeclContext();
// Build a reference to the generic member.
SmallVector<Substitution, 4> substitutions;
refTy = solution.computeSubstitutions(
member->getInterfaceType(),
dc,
openedFullType,
getConstraintSystem().getConstraintLocator(memberLocator),
substitutions);
memberRef = ConcreteDeclRef(context, member, substitutions);
if (auto openedFullFnType = openedFullType->getAs<FunctionType>()) {
auto openedBaseType = openedFullFnType->getInput()
->getRValueInstanceType();
containerTy = solution.simplifyType(tc, openedBaseType);
}
} else {
// No substitutions required; the declaration reference is simple.
containerTy = member->getDeclContext()->getDeclaredTypeOfContext();
memberRef = member;
refTy = openedFullType;
}
// If we opened up an existential when referencing this member, update
// the base accordingly.
auto knownOpened = solution.OpenedExistentialTypes.find(
getConstraintSystem().getConstraintLocator(
memberLocator));
bool openedExistential = false;
if (knownOpened != solution.OpenedExistentialTypes.end()) {
base = openExistentialReference(base, knownOpened->second, member);
baseTy = knownOpened->second;
containerTy = baseTy;
openedExistential = true;
}
// If this is a method whose result type is dynamic Self, or a
// construction, replace the result type with the actual object type.
if (auto func = dyn_cast<AbstractFunctionDecl>(member)) {
if ((isa<FuncDecl>(func) &&
(cast<FuncDecl>(func)->hasDynamicSelf() ||
(openedExistential &&
cast<FuncDecl>(func)->hasArchetypeSelf()))) ||
isPolymorphicConstructor(func)) {
refTy = refTy->replaceCovariantResultType(containerTy,
func->getNumParameterLists());
dynamicSelfFnType = refTy->replaceCovariantResultType(
baseTy,
func->getNumParameterLists());
if (openedExistential) {
// Replace the covariant result type in the opened type. We need to
// handle dynamic member references, which wrap the function type
// in an optional.
OptionalTypeKind optKind;
if (auto optObject = openedType->getAnyOptionalObjectType(optKind))
openedType = optObject;
openedType = openedType->replaceCovariantResultType(
baseTy,
func->getNumParameterLists()-1);
if (optKind != OptionalTypeKind::OTK_None)
openedType = OptionalType::get(optKind, openedType);
}
// If the type after replacing DynamicSelf with the provided base
// type is no different, we don't need to perform a conversion here.
if (refTy->isEqual(dynamicSelfFnType))
dynamicSelfFnType = nullptr;
}
}
// If we're referring to the member of a module, it's just a simple
// reference.
if (baseTy->is<ModuleType>()) {
assert(semantics == AccessSemantics::Ordinary &&
"Direct property access doesn't make sense for this");
assert(!dynamicSelfFnType && "No reference type to convert to");
auto ref = new (context) DeclRefExpr(memberRef, memberLoc, Implicit);
ref->setType(refTy);
ref->setFunctionRefKind(functionRefKind);
return new (context) DotSyntaxBaseIgnoredExpr(base, dotLoc, ref);
}
// Otherwise, we're referring to a member of a type.
// Is it an archetype member?
bool isDependentConformingRef
= isa<ProtocolDecl>(member->getDeclContext()) &&
baseTy->hasDependentProtocolConformances();
// References to properties with accessors and storage usually go
// through the accessors, but sometimes are direct.
if (auto *VD = dyn_cast<VarDecl>(member)) {
if (semantics == AccessSemantics::Ordinary)
semantics = getImplicitMemberReferenceAccessSemantics(base, VD, dc);
}
if (baseIsInstance) {
// Convert the base to the appropriate container type, turning it
// into an lvalue if required.
Type selfTy;
if (isDependentConformingRef)
selfTy = baseTy;
else
selfTy = containerTy;
// If the base is already an lvalue with the right base type, we can
// pass it as an inout qualified type.
if (selfTy->isEqual(baseTy))
if (base->getType()->is<LValueType>())
selfTy = InOutType::get(selfTy);
base = coerceObjectArgumentToType(
base, selfTy, member, semantics,
locator.withPathElement(ConstraintLocator::MemberRefBase));
} else {
// Convert the base to an rvalue of the appropriate metatype.
base = coerceToType(base,
MetatypeType::get(isDependentConformingRef
? baseTy
: containerTy),
locator.withPathElement(
ConstraintLocator::MemberRefBase));
if (!base)
return nullptr;
base = tc.coerceToRValue(base);
}
assert(base && "Unable to convert base?");
// Handle dynamic references.
if (isDynamic || member->getAttrs().hasAttribute<OptionalAttr>()) {
base = tc.coerceToRValue(base);
if (!base) return nullptr;
Expr *ref = new (context) DynamicMemberRefExpr(base, dotLoc, memberRef,
memberLoc);
ref->setImplicit(Implicit);
// FIXME: FunctionRefKind
// Compute the type of the reference.
Type refType = simplifyType(openedType);
// If the base was an opened existential, erase the opened
// existential.
if (openedExistential &&
refType->hasOpenedExistential(knownOpened->second)) {
refType = refType->eraseOpenedExistential(
cs.DC->getParentModule(),
knownOpened->second);
}
ref->setType(refType);
closeExistential(ref, /*force=*/openedExistential);
return ref;
}
// For types and properties, build member references.
if (isa<TypeDecl>(member) || isa<VarDecl>(member)) {
assert(!dynamicSelfFnType && "Converted type doesn't make sense here");
if (!baseIsInstance && member->isInstanceMember()) {
assert(memberLocator.getBaseLocator() &&
cs.UnevaluatedRootExprs.count(
memberLocator.getBaseLocator()->getAnchor()) &&
"Attempt to reference an instance member of a metatype");
auto baseInstanceTy = base->getType()->getRValueInstanceType();
base = new (context) UnevaluatedInstanceExpr(base, baseInstanceTy);
base->setImplicit();
}
auto memberRefExpr
= new (context) MemberRefExpr(base, dotLoc, memberRef,
memberLoc, Implicit, semantics);
memberRefExpr->setIsSuper(isSuper);
// Skip the synthesized 'self' input type of the opened type.
memberRefExpr->setType(simplifyType(openedType));
Expr *result = memberRefExpr;
closeExistential(result);
return result;
}
// Handle all other references.
auto declRefExpr = new (context) DeclRefExpr(memberRef, memberLoc,
Implicit, semantics);
declRefExpr->setFunctionRefKind(functionRefKind);
declRefExpr->setType(refTy);
Expr *ref = declRefExpr;
// If the reference needs to be converted, do so now.
if (dynamicSelfFnType) {
ref = new (context) CovariantFunctionConversionExpr(ref,
dynamicSelfFnType);
}
ApplyExpr *apply;
if (isa<ConstructorDecl>(member)) {
// FIXME: Provide type annotation.
apply = new (context) ConstructorRefCallExpr(ref, base);
} else if (!baseIsInstance && member->isInstanceMember()) {
// Reference to an unbound instance method.
Expr *result = new (context) DotSyntaxBaseIgnoredExpr(base, dotLoc,
ref);
closeExistential(result, /*force=*/openedExistential);
return result;
} else {
assert((!baseIsInstance || member->isInstanceMember()) &&
"can't call a static method on an instance");
apply = new (context) DotSyntaxCallExpr(ref, dotLoc, base);
if (Implicit) {
apply->setImplicit();
}
}
return finishApply(apply, openedType, locator);
}
/// \brief Describes either a type or the name of a type to be resolved.
typedef llvm::PointerUnion<Identifier, Type> TypeOrName;
/// \brief Convert the given literal expression via a protocol pair.
///
/// This routine handles the two-step literal conversion process used
/// by integer, float, character, extended grapheme cluster, and string