forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCSApply.cpp
6526 lines (5620 loc) · 250 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 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements 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/AST/Attr.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.
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> &substitutions) const {
auto &tc = getConstraintSystem().getTypeChecker();
auto &ctx = tc.Context;
// Gather the substitutions from dependent types to concrete types.
auto openedTypes = OpenedTypes.find(locator);
assert(openedTypes != OpenedTypes.end() && "Missing opened type information");
TypeSubstitutionMap typeSubstitutions;
for (const auto &opened : openedTypes->second) {
typeSubstitutions[opened.first.getPointer()] = getFixedType(opened.second);
}
// Produce the concrete form of the opened type.
auto type = openedType.transform([&](Type type) -> Type {
if (auto tv = dyn_cast<TypeVariableType>(type.getPointer())) {
auto archetype = tv->getImpl().getArchetype();
auto simplified = getFixedType(tv);
return SubstitutedType::get(archetype, simplified,
tc.Context);
}
return type;
});
auto currentModule = getConstraintSystem().DC->getParentModule();
ArchetypeType *currentArchetype = nullptr;
Type currentReplacement;
SmallVector<ProtocolConformance *, 4> currentConformances;
ArrayRef<Requirement> requirements;
if (auto genericFn = origType->getAs<GenericFunctionType>()) {
requirements = genericFn->getRequirements();
} else {
requirements = dc->getGenericSignatureOfContext()->getRequirements();
}
for (const auto &req : requirements) {
// Drop requirements for parameters that have been constrained away to
// concrete types.
auto firstArchetype
= ArchetypeBuilder::mapTypeIntoContext(dc, req.getFirstType(), &tc)
->getAs<ArchetypeType>();
if (!firstArchetype)
continue;
switch (req.getKind()) {
case RequirementKind::Conformance:
// If this is a protocol conformance requirement, get the conformance
// and record it.
if (auto protoType = req.getSecondType()->getAs<ProtocolType>()) {
assert(firstArchetype == currentArchetype
&& "Archetype out-of-sync");
ProtocolConformance *conformance = nullptr;
Type replacement = currentReplacement;
bool conforms = tc.conformsToProtocol(
replacement,
protoType->getDecl(),
getConstraintSystem().DC,
(ConformanceCheckFlags::InExpression|
ConformanceCheckFlags::Used),
&conformance);
(void)isOpenedAnyObject;
assert((conforms ||
firstArchetype->getIsRecursive() ||
isOpenedAnyObject(replacement) ||
replacement->is<GenericTypeParamType>()) &&
"Constraint system missed a conformance?");
(void)conforms;
assert(conformance || replacement->hasDependentProtocolConformances());
currentConformances.push_back(conformance);
break;
}
break;
case RequirementKind::SameType:
// Same-type requirements aren't recorded in substitutions.
break;
case RequirementKind::WitnessMarker:
// Flush the current conformances.
if (currentArchetype) {
substitutions.push_back({
currentArchetype,
currentReplacement,
ctx.AllocateCopy(currentConformances)
});
currentConformances.clear();
}
// Each witness marker starts a new substitution.
currentArchetype = firstArchetype;
currentReplacement = req.getFirstType().subst(currentModule,
typeSubstitutions,
None);
break;
}
}
// Flush the final conformances.
if (currentArchetype) {
substitutions.push_back({
currentArchetype,
currentReplacement,
ctx.AllocateCopy(currentConformances),
});
currentConformances.clear();
}
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) {
// 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.
ProtocolConformance *conformance = 0;
bool conforms = tc.conformsToProtocol(type, proto, dc,
ConformanceCheckFlags::InExpression,
&conformance);
if (!conforms)
return nullptr;
// For an type with dependent conformance, just return the requirement from
// the protocol. There are no protocol conformance tables.
if (type->hasDependentProtocolConformances()) {
return requirement;
}
assert(conformance && "Missing conformance information");
// FIXME: Dropping substitutions here.
return cast_or_null<DeclTy>(
conformance->getWitness(requirement, &tc).getDecl());
}
static VarDecl *findNamedPropertyWitness(TypeChecker &tc, DeclContext *dc,
Type type, ProtocolDecl *proto,
Identifier name, Diag<> diag) {
return findNamedWitnessImpl<VarDecl>(tc, dc, type, proto, name, diag);
}
/// 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 (auto *AFD_DC = dyn_cast<AbstractFunctionDecl>(DC))
if (member->hasStorage() &&
// In a ctor or dtor.
(isa<ConstructorDecl>(AFD_DC) || isa<DestructorDecl>(AFD_DC)) &&
// Ctor or dtor are 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()) {
// Access this directly instead of going through (e.g.) observing or
// trivial accessors.
return AccessSemantics::DirectToStorage;
}
// 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;
private:
/// \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.
Expr *coerceTupleToTuple(Expr *expr, TupleType *fromTuple,
TupleType *toTuple,
ConstraintLocatorBuilder locator,
SmallVectorImpl<int> &sources,
SmallVectorImpl<unsigned> &variadicArgs);
/// \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);
/// \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, SourceLoc loc, Type openedType,
ConstraintLocatorBuilder locator,
bool specialized, bool implicit,
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 baseTy = simplifyType(openedFnType->getInput())
->getRValueInstanceType();
Expr *base = TypeExpr::createImplicitHack(loc, baseTy, ctx);
auto result = buildMemberRef(base, openedType, SourceLoc(), decl,
loc, openedFnType->getResult(),
locator, locator, implicit, semantics,
/*isDynamic=*/false);
if (!result)
return nullptr;
return result;
}
// 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);
return new (ctx) DeclRefExpr(ConcreteDeclRef(ctx, decl, substitutions),
loc, implicit, semantics, type);
}
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, diag::missing_address_of, inoutType->getInOutObjectType())
.fixItInsert(loc, "&");
return nullptr;
}
return new (ctx) DeclRefExpr(decl, loc, implicit, semantics, type);
}
/// 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->getNaturalArgumentCount();
} 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)) {
// Erase the opened existential.
// Remove the optional, if present.
OptionalTypeKind optKind;
if (auto optValueTy = resultTy->getAnyOptionalObjectType(optKind)) {
resultTy = optValueTy;
}
// - Drill down to the optional value (if necessary).
if (optKind) {
result = new (tc.Context) BindOptionalExpr(result,
result->getEndLoc(),
0,
resultTy);
result->setImplicit(true);
}
Type erasedTy;
if (resultTy->isEqual(record.Archetype)) {
// - Coerce to an existential value.
erasedTy = record.Archetype->getOpenedExistentialType();
result = coerceToType(result, erasedTy, nullptr);
// FIXME: can this really ever fail? We'll leave behind rogue
// OpaqueValueExprs if that is the case.
assert(result);
} else {
// - Perform a covariant function coercion.
erasedTy = resultTy->eraseOpenedExistential(
cs.DC->getParentModule(),
record.Archetype);
result = new (tc.Context) CovariantFunctionConversionExpr(
result,
erasedTy);
}
// - Bind up the result back up as an optional (if necessary).
if (optKind) {
Type optErasedTy = OptionalType::get(optKind, erasedTy);
result = new (tc.Context) InjectIntoOptionalExpr(result,
optErasedTy);
result = new (tc.Context) OptionalEvaluationExpr(result,
optErasedTy);
}
}
// 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;
DeclContext *parent = fn->getParent();
if (auto extension = dyn_cast<ExtensionDecl>(parent))
parent = extension->getExtendedType()->getAnyNominal();
return (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, SourceLoc memberLoc,
Type openedType, ConstraintLocatorBuilder locator,
ConstraintLocatorBuilder memberLocator,
bool Implicit, 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 (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;
auto baseDeclRefExpr = dyn_cast<DeclRefExpr>(base);
refTy = tc.getUnopenedTypeOfReference(member, Type(), dc,
baseDeclRefExpr,
/*wantInterfaceType=*/true);
}
// 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->getNumParamPatterns());
dynamicSelfFnType = refTy->replaceCovariantResultType(
baseTy,
func->getNumParamPatterns());
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->getNumParamPatterns()-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");
Expr *ref = new (context) DeclRefExpr(memberRef, memberLoc, Implicit);
ref->setType(refTy);
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);
// 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");
assert(baseIsInstance || !member->isInstanceMember());
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.
Expr *ref = new (context) DeclRefExpr(memberRef, memberLoc, Implicit,
semantics);
ref->setType(refTy);
// 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);
}
return finishApply(apply, openedType, nullptr);
}
/// \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
/// literals. The first step uses \c builtinProtocol while the second
/// step uses \c protocol.
///
/// \param literal The literal expression.
///
/// \param type The literal type. This type conforms to \c protocol,
/// and may also conform to \c builtinProtocol.
///
/// \param openedType The literal type as it was opened in the type system.
///
/// \param protocol The protocol that describes the literal requirement.
///
/// \param literalType Either the name of the associated type in
/// \c protocol that describes the argument type of the conversion function
/// (\c literalFuncName) or the argument type itself.
///
/// \param literalFuncName The name of the conversion function requirement
/// in \c protocol.
///
/// \param builtinProtocol The "builtin" form of the protocol, which
/// always takes builtin types and can only be properly implemented
/// by standard library types. If \c type does not conform to this
/// protocol, it's literal type will.
///
/// \param builtinLiteralType Either the name of the associated type in
/// \c builtinProtocol that describes the argument type of the builtin
/// conversion function (\c builtinLiteralFuncName) or the argument type
/// itself.
///
/// \param builtinLiteralFuncName The name of the conversion function
/// requirement in \c builtinProtocol.
///
/// \param isBuiltinArgType Function that determines whether the given
/// type is acceptable as the argument type for the builtin conversion.
///
/// \param brokenProtocolDiag The diagnostic to emit if the protocol
/// is broken.
///
/// \param brokenBuiltinProtocolDiag The diagnostic to emit if the builtin
/// protocol is broken.
///
/// \returns the converted literal expression.
Expr *convertLiteral(Expr *literal,
Type type,
Type openedType,