forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeSynthesis.cpp
2560 lines (2133 loc) · 97.3 KB
/
CodeSynthesis.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
//===--- CodeSynthesis.cpp - Type Checking for Declarations ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 semantic analysis for declarations.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "ConstraintSystem.h"
#include "TypeChecker.h"
#include "TypeCheckObjC.h"
#include "TypeCheckType.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Availability.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/Defer.h"
#include "swift/ClangImporter/ClangModule.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
using namespace swift;
const bool IsImplicit = true;
static SynthesizedFunction::Kind
getSynthKindForAccessorKind(AccessorKind kind) {
switch (kind) {
case AccessorKind::Read:
return SynthesizedFunction::ReadCoroutine;
case AccessorKind::Modify:
return SynthesizedFunction::ModifyCoroutine;
case AccessorKind::Get:
return SynthesizedFunction::Getter;
case AccessorKind::Set:
return SynthesizedFunction::Setter;
#define OPAQUE_ACCESSOR(ID, KEYWORD)
#define ACCESSOR(ID) \
case AccessorKind::ID:
#include "swift/AST/AccessorKinds.def"
llvm_unreachable("unexpected synthesized accessor");
}
llvm_unreachable("bad kind");
}
/// Should a particular accessor for the given storage be synthesized
/// on-demand, or is it always defined eagerly in the file that declared
/// the storage?
static bool isOnDemandAccessor(AbstractStorageDecl *storage,
AccessorKind kind) {
assert(kind == AccessorKind::Get ||
kind == AccessorKind::Set ||
kind == AccessorKind::Read ||
kind == AccessorKind::Modify);
// If the accessor isn't in the inherent opaque-accessor set of the
// declaration, it's on-demand.
if (!storage->requiresOpaqueAccessor(kind))
return true;
// Currently this only applies to imported declarations because we
// eagerly create accessors for all other member storage.
//
// Note that we can't just use hasClangNode() because the importer
// sometimes synthesizes things that lack clang nodes.
auto *mod = storage->getDeclContext()->getModuleScopeContext();
return (cast<FileUnit>(mod)->getKind() == FileUnitKind::ClangModule);
}
/// Insert the specified decl into the DeclContext's member list. If the hint
/// decl is specified, the new decl is inserted next to the hint.
static void addMemberToContextIfNeeded(Decl *D, DeclContext *DC,
Decl *Hint = nullptr) {
if (auto *ntd = dyn_cast<NominalTypeDecl>(DC)) {
ntd->addMember(D, Hint);
} else if (auto *ed = dyn_cast<ExtensionDecl>(DC)) {
ed->addMember(D, Hint);
} else {
assert((isa<AbstractFunctionDecl>(DC) || isa<FileUnit>(DC)) &&
"Unknown declcontext");
}
}
static ParamDecl *getParamDeclAtIndex(FuncDecl *fn, unsigned index) {
return fn->getParameters()->get(index);
}
static VarDecl *getFirstParamDecl(FuncDecl *fn) {
return getParamDeclAtIndex(fn, 0);
};
static ParamDecl *buildArgument(SourceLoc loc, DeclContext *DC,
StringRef name,
Type interfaceType,
VarDecl::Specifier specifier) {
auto &context = DC->getASTContext();
auto *param = new (context) ParamDecl(specifier, SourceLoc(), SourceLoc(),
Identifier(), loc,
context.getIdentifier(name),
DC);
param->setImplicit();
param->setInterfaceType(interfaceType);
return param;
}
/// Build a parameter list which can forward the formal index parameters of a
/// declaration.
///
/// \param prefix optional arguments to be prefixed onto the index
/// forwarding pattern.
static ParameterList *
buildIndexForwardingParamList(AbstractStorageDecl *storage,
ArrayRef<ParamDecl*> prefix) {
auto &context = storage->getASTContext();
auto subscript = dyn_cast<SubscriptDecl>(storage);
// Fast path: if this isn't a subscript, just use whatever we have.
if (!subscript)
return ParameterList::create(context, prefix);
// Clone the parameter list over for a new decl, so we get new ParamDecls.
auto indices = subscript->getIndices()->clone(context,
ParameterList::Implicit|
ParameterList::WithoutTypes);
// Give all of the parameters meaningless names so that we can forward
// them properly. If it's declared anonymously, SILGen will think
// it's unused.
// TODO: use some special DeclBaseName for this?
for (auto param : indices->getArray()) {
if (!param->hasName())
param->setName(context.getIdentifier("anonymous"));
assert(param->hasName());
}
if (prefix.empty())
return indices;
// Otherwise, we need to build up a new parameter list.
SmallVector<ParamDecl*, 4> elements;
// Start with the fields we were given, if there are any.
elements.append(prefix.begin(), prefix.end());
elements.append(indices->begin(), indices->end());
return ParameterList::create(context, elements);
}
static AccessorDecl *createGetterPrototype(TypeChecker &TC,
AbstractStorageDecl *storage) {
assert(!storage->getGetter());
SourceLoc loc = storage->getLoc();
GenericEnvironment *genericEnvironmentOfLazyAccessor = nullptr;
ParamDecl *selfDecl = nullptr;
if (storage->getDeclContext()->isTypeContext()) {
if (storage->getAttrs().hasAttribute<LazyAttr>()) {
// The getter is considered mutating if it's on a value type.
if (!storage->getDeclContext()->getSelfClassDecl() &&
!storage->isStatic()) {
storage->setIsGetterMutating(true);
}
// For lazy properties, steal the 'self' from the initializer context.
auto *varDecl = cast<VarDecl>(storage);
auto *bindingDecl = varDecl->getParentPatternBinding();
auto *bindingInit = cast<PatternBindingInitializer>(
bindingDecl->getPatternEntryForVarDecl(varDecl).getInitContext());
selfDecl = bindingInit->getImplicitSelfDecl();
genericEnvironmentOfLazyAccessor =
bindingInit->getGenericEnvironmentOfContext();
}
}
// Add an index-forwarding clause.
auto *getterParams = buildIndexForwardingParamList(storage, {});
SourceLoc staticLoc;
if (auto var = dyn_cast<VarDecl>(storage)) {
if (var->isStatic())
staticLoc = var->getLoc();
}
auto storageInterfaceType = storage->getValueInterfaceType();
auto getter = AccessorDecl::create(
TC.Context, loc, /*AccessorKeywordLoc*/ loc,
AccessorKind::Get, AddressorKind::NotAddressor, storage,
staticLoc, StaticSpellingKind::None,
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*GenericParams=*/nullptr,
getterParams,
TypeLoc::withoutLoc(storageInterfaceType),
storage->getDeclContext());
getter->setImplicit();
// If we're stealing the 'self' from a lazy initializer, set it now.
if (selfDecl) {
*getter->getImplicitSelfDeclStorage() = selfDecl;
selfDecl->setDeclContext(getter);
}
// We need to install the generic environment here because:
// 1) validating the getter will change the implicit self decl's DC to it,
// 2) it's likely that the initializer will be type-checked before the
// accessor (and therefore before the normal installation happens), and
// 3) type-checking a reference to the self decl will map its type into
// its context, which requires an environment to be installed on that
// context.
// We can safely use the enclosing environment because properties are never
// differently generic.
if (genericEnvironmentOfLazyAccessor)
getter->setGenericEnvironment(genericEnvironmentOfLazyAccessor);
if (storage->isGetterMutating())
getter->setSelfAccessKind(SelfAccessKind::Mutating);
if (storage->isStatic())
getter->setStatic();
// Always add the getter to the context immediately after the storage.
addMemberToContextIfNeeded(getter, storage->getDeclContext(), storage);
return getter;
}
static AccessorDecl *createSetterPrototype(TypeChecker &TC,
AbstractStorageDecl *storage,
AccessorDecl *getter = nullptr) {
assert(!storage->getSetter());
assert(storage->supportsMutation());
SourceLoc loc = storage->getLoc();
bool isStatic = storage->isStatic();
bool isMutating = storage->isSetterMutating();
// Add a "(value : T, indices...)" argument list.
auto storageInterfaceType = storage->getValueInterfaceType();
auto valueDecl = buildArgument(storage->getLoc(), storage->getDeclContext(),
"value", storageInterfaceType,
VarDecl::Specifier::Default);
auto *params = buildIndexForwardingParamList(storage, valueDecl);
Type setterRetTy = TupleType::getEmpty(TC.Context);
auto setter = AccessorDecl::create(
TC.Context, loc, /*AccessorKeywordLoc*/ SourceLoc(),
AccessorKind::Set, AddressorKind::NotAddressor, storage,
/*StaticLoc=*/SourceLoc(), StaticSpellingKind::None,
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*GenericParams=*/nullptr, params,
TypeLoc::withoutLoc(setterRetTy),
storage->getDeclContext());
setter->setImplicit();
if (isMutating)
setter->setSelfAccessKind(SelfAccessKind::Mutating);
if (isStatic)
setter->setStatic();
// Always add the setter to the context immediately after the getter.
if (!getter) getter = storage->getGetter();
assert(getter && "always synthesize setter prototype after getter");
addMemberToContextIfNeeded(setter, storage->getDeclContext(), getter);
return setter;
}
// True if the storage is dynamic or imported from Objective-C. In these cases,
// we need to emit static coroutine accessors that dynamically dispatch
// to 'get' and 'set', rather than the normal dynamically dispatched
// opaque accessors that peer dispatch to 'get' and 'set'.
static bool needsDynamicCoroutineAccessors(AbstractStorageDecl *storage) {
return storage->isDynamic() || storage->hasClangNode();
}
/// Mark the accessor as transparent if we can.
///
/// If the storage is inside a fixed-layout nominal type, we can mark the
/// accessor as transparent, since in this case we just want it for abstraction
/// purposes (i.e., to make access to the variable uniform and to be able to
/// put the getter in a vtable).
///
/// If the storage is for a global stored property or a stored property of a
/// resilient type, we are synthesizing accessors to present a resilient
/// interface to the storage and they should not be transparent.
static void maybeMarkTransparent(TypeChecker &TC, AccessorDecl *accessor) {
auto *DC = accessor->getDeclContext();
auto *nominalDecl = DC->getSelfNominalTypeDecl();
// Global variable accessors are not @_transparent.
if (!nominalDecl)
return;
// Accessors for resilient properties are not @_transparent.
if (accessor->getStorage()->isResilient())
return;
// Setters for lazy properties are not @_transparent (because the storage
// is not ABI-exposed).
if (accessor->getStorage()->getAttrs().hasAttribute<LazyAttr>() &&
accessor->getAccessorKind() == AccessorKind::Set)
return;
// Accessors for protocol storage requirements are never @_transparent
// since they do not have bodies.
//
// FIXME: Revisit this if we ever get 'real' default implementations.
if (isa<ProtocolDecl>(nominalDecl))
return;
// Accessors for classes with @objc ancestry are not @_transparent,
// since they use a field offset variable which is not exported.
if (auto *classDecl = dyn_cast<ClassDecl>(nominalDecl))
if (classDecl->checkObjCAncestry() != ObjCClassKind::NonObjC)
return;
// Accessors synthesized on-demand are never transaprent.
if (accessor->hasForcedStaticDispatch())
return;
accessor->getAttrs().add(new (TC.Context) TransparentAttr(IsImplicit));
}
template <class... Args>
static void triggerSynthesis(TypeChecker &TC, FuncDecl *fn, Args... args) {
if (fn->hasBody()) return;
auto synthesisRecord = SynthesizedFunction(fn, args...);
TC.FunctionsToSynthesize.insert({ fn, synthesisRecord });
}
static void finishSynthesis(TypeChecker &TC, FuncDecl *fn) {
TC.Context.addSynthesizedDecl(fn);
TC.DeclsToFinalize.insert(fn);
}
static AccessorDecl *
createCoroutineAccessorPrototype(TypeChecker &TC,
AbstractStorageDecl *storage,
AccessorKind kind) {
assert(kind == AccessorKind::Read || kind == AccessorKind::Modify);
auto &ctx = TC.Context;
SourceLoc loc = storage->getLoc();
bool isStatic = storage->isStatic();
bool isMutating = storage->isGetterMutating();
if (kind == AccessorKind::Modify)
isMutating |= storage->isSetterMutating();
auto dc = storage->getDeclContext();
// The forwarding index parameters.
auto *params = buildIndexForwardingParamList(storage, {});
// Coroutine accessors always return ().
Type retTy = TupleType::getEmpty(ctx);
// Accessors of generic subscripts get a copy of the subscript's
// generic parameter list, because they're not nested inside the
// subscript.
GenericParamList *genericParams = nullptr;
if (auto *subscript = dyn_cast<SubscriptDecl>(storage)) {
genericParams = subscript->getGenericParams();
if (genericParams)
genericParams = genericParams->clone(dc);
}
auto *accessor = AccessorDecl::create(
ctx, loc, /*AccessorKeywordLoc=*/SourceLoc(),
kind, AddressorKind::NotAddressor, storage,
/*StaticLoc=*/SourceLoc(), StaticSpellingKind::None,
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
genericParams, params, TypeLoc::withoutLoc(retTy), dc);
accessor->setImplicit();
if (isMutating)
accessor->setSelfAccessKind(SelfAccessKind::Mutating);
if (isStatic)
accessor->setStatic();
// The accessor is final if the storage is.
if (storage->isFinal())
makeFinal(ctx, accessor);
// If the storage is dynamic or ObjC-native, we can't add a dynamically-
// dispatched method entry for the accessor, so force it to be
// statically dispatched. ("final" would be inappropriate because the
// property can still be overridden.)
if (needsDynamicCoroutineAccessors(storage))
accessor->setForcedStaticDispatch(true);
// Make sure the coroutine is available enough to access
// the storage (and its getters/setters if it has them).
SmallVector<const Decl *, 2> asAvailableAs;
asAvailableAs.push_back(storage);
if (FuncDecl *getter = storage->getGetter()) {
asAvailableAs.push_back(getter);
}
if (kind == AccessorKind::Modify) {
if (FuncDecl *setter = storage->getSetter()) {
asAvailableAs.push_back(setter);
}
}
maybeMarkTransparent(TC, accessor);
AvailabilityInference::applyInferredAvailableAttrs(accessor,
asAvailableAs, ctx);
Decl *afterDecl;
if (kind == AccessorKind::Read) {
// Add the synthesized read coroutine after the getter, if one exists,
// or else immediately after the storage.
afterDecl = storage->getGetter();
if (!afterDecl) afterDecl = storage;
} else {
// Add the synthesized modify coroutine after the setter.
afterDecl = storage->getSetter();
}
addMemberToContextIfNeeded(accessor, dc, afterDecl);
return accessor;
}
static AccessorDecl *
createReadCoroutinePrototype(TypeChecker &tc, AbstractStorageDecl *storage) {
return createCoroutineAccessorPrototype(tc, storage, AccessorKind::Read);
}
static AccessorDecl *
createModifyCoroutinePrototype(TypeChecker &tc, AbstractStorageDecl *storage) {
return createCoroutineAccessorPrototype(tc, storage, AccessorKind::Modify);
}
/// Build an expression that evaluates the specified parameter list as a tuple
/// or paren expr, suitable for use in an applyexpr.
///
/// NOTE: This returns null if a varargs parameter exists in the list, as it
/// cannot be forwarded correctly yet.
///
static Expr *buildArgumentForwardingExpr(ArrayRef<ParamDecl*> params,
ASTContext &ctx) {
SmallVector<Identifier, 4> labels;
SmallVector<SourceLoc, 4> labelLocs;
SmallVector<Expr *, 4> args;
for (auto param : params) {
Expr *ref = new (ctx) DeclRefExpr(param, DeclNameLoc(), /*implicit*/ true);
if (param->isInOut())
ref = new (ctx) InOutExpr(SourceLoc(), ref, Type(), /*isImplicit=*/true);
else if (param->isVariadic())
ref = new (ctx) VarargExpansionExpr(ref, /*implicit*/ true);
args.push_back(ref);
labels.push_back(param->getArgumentName());
labelLocs.push_back(SourceLoc());
}
// A single unlabeled value is not a tuple.
if (args.size() == 1 && labels[0].empty()) {
return new (ctx) ParenExpr(SourceLoc(), args[0], SourceLoc(),
/*hasTrailingClosure=*/false);
}
return TupleExpr::create(ctx, SourceLoc(), args, labels, labelLocs,
SourceLoc(), false, IsImplicit);
}
/// Build a reference to the subscript index variables for this subscript
/// accessor.
static Expr *buildSubscriptIndexReference(ASTContext &ctx,
AccessorDecl *accessor) {
// Pull out the body parameters, which we should have cloned
// previously to be forwardable. Drop the initial buffer/value
// parameter in accessors that have one.
auto params = accessor->getParameters()->getArray();
auto accessorKind = accessor->getAccessorKind();
// Ignore the value parameter of a setter.
if (accessorKind == AccessorKind::Set) {
params = params.slice(1);
}
// Okay, everything else should be forwarded, build the expression.
auto result = buildArgumentForwardingExpr(params, ctx);
assert(result && "FIXME: Cannot forward expression");
return result;
}
enum class SelfAccessorKind {
/// We're building a derived accessor on top of whatever this
/// class provides.
Peer,
/// We're building a setter or something around an underlying
/// implementation, which might be storage or inherited from a
/// superclass.
Super,
};
static Expr *buildSelfReference(VarDecl *selfDecl,
SelfAccessorKind selfAccessorKind,
TypeChecker &TC) {
switch (selfAccessorKind) {
case SelfAccessorKind::Peer:
return new (TC.Context) DeclRefExpr(selfDecl, DeclNameLoc(), IsImplicit);
case SelfAccessorKind::Super:
return new (TC.Context) SuperRefExpr(selfDecl, SourceLoc(), IsImplicit);
}
llvm_unreachable("bad self access kind");
}
namespace {
enum class TargetImpl {
/// We're doing an ordinary storage reference.
Ordinary,
/// We're referencing the physical storage created for the storage.
Storage,
/// We're referencing this specific implementation of the storage, not
/// an override of it.
Implementation,
/// We're referencing the superclass's implementation of the storage.
Super
};
} // end anonymous namespace
/// Build an l-value for the storage of a declaration.
static Expr *buildStorageReference(AccessorDecl *accessor,
AbstractStorageDecl *storage,
TargetImpl target,
TypeChecker &TC) {
ASTContext &ctx = TC.Context;
AccessSemantics semantics;
SelfAccessorKind selfAccessKind;
switch (target) {
case TargetImpl::Ordinary:
semantics = AccessSemantics::Ordinary;
selfAccessKind = SelfAccessorKind::Peer;
break;
case TargetImpl::Storage:
semantics = AccessSemantics::DirectToStorage;
selfAccessKind = SelfAccessorKind::Peer;
break;
case TargetImpl::Implementation:
semantics = AccessSemantics::DirectToImplementation;
selfAccessKind = SelfAccessorKind::Peer;
break;
case TargetImpl::Super:
// If this really is an override, use a super-access.
if (auto override = storage->getOverriddenDecl()) {
semantics = AccessSemantics::Ordinary;
selfAccessKind = SelfAccessorKind::Super;
storage = override;
// Otherwise do a self-reference, which is dynamically bogus but
// should be statically valid. This should only happen in invalid cases.
} else {
assert(storage->isInvalid());
semantics = AccessSemantics::Ordinary;
selfAccessKind = SelfAccessorKind::Peer;
}
break;
}
VarDecl *selfDecl = accessor->getImplicitSelfDecl();
if (!selfDecl) {
assert(target != TargetImpl::Super);
return new (ctx) DeclRefExpr(storage, DeclNameLoc(), IsImplicit, semantics);
}
Expr *selfDRE =
buildSelfReference(selfDecl, selfAccessKind, TC);
if (auto subscript = dyn_cast<SubscriptDecl>(storage)) {
Expr *indices = buildSubscriptIndexReference(ctx, accessor);
return SubscriptExpr::create(ctx, selfDRE, indices, storage,
IsImplicit, semantics);
}
return new (ctx) MemberRefExpr(selfDRE, SourceLoc(), storage,
DeclNameLoc(), IsImplicit, semantics);
}
/// Load the value of VD. If VD is an @override of another value, we call the
/// superclass getter. Otherwise, we do a direct load of the value.
static Expr *createPropertyLoadOrCallSuperclassGetter(AccessorDecl *accessor,
AbstractStorageDecl *storage,
TargetImpl target,
TypeChecker &TC) {
return buildStorageReference(accessor, storage, target, TC);
}
/// Look up the NSCopying protocol from the Foundation module, if present.
/// Otherwise return null.
static ProtocolDecl *getNSCopyingProtocol(TypeChecker &TC,
DeclContext *DC) {
ASTContext &ctx = TC.Context;
auto foundation = ctx.getLoadedModule(ctx.Id_Foundation);
if (!foundation)
return nullptr;
SmallVector<ValueDecl *, 2> results;
DC->lookupQualified(foundation,
ctx.getSwiftId(KnownFoundationEntity::NSCopying),
NL_QualifiedDefault | NL_KnownNonCascadingDependency,
results);
if (results.size() != 1)
return nullptr;
return dyn_cast<ProtocolDecl>(results.front());
}
static bool checkConformanceToNSCopying(TypeChecker &TC, VarDecl *var,
Type type) {
auto dc = var->getDeclContext();
auto proto = getNSCopyingProtocol(TC, dc);
if (!proto || !TC.conformsToProtocol(type, proto, dc, None)) {
TC.diagnose(var->getLoc(), diag::nscopying_doesnt_conform);
return true;
}
return false;
}
static std::pair<Type, bool> getUnderlyingTypeOfVariable(VarDecl *var) {
Type type = var->getType()->getReferenceStorageReferent();
if (Type objectType = type->getOptionalObjectType()) {
return {objectType, true};
} else {
return {type, false};
}
}
bool TypeChecker::checkConformanceToNSCopying(VarDecl *var) {
Type type = getUnderlyingTypeOfVariable(var).first;
return ::checkConformanceToNSCopying(*this, var, type);
}
/// Synthesize the code to store 'Val' to 'VD', given that VD has an @NSCopying
/// attribute on it. We know that VD is a stored property in a class, so we
/// just need to generate something like "self.property = val.copy(zone: nil)"
/// here. This does some type checking to validate that the call will succeed.
static Expr *synthesizeCopyWithZoneCall(Expr *Val, VarDecl *VD,
TypeChecker &TC) {
auto &Ctx = TC.Context;
// We support @NSCopying on class types (which conform to NSCopying),
// protocols which conform, and option types thereof.
auto underlyingTypeAndIsOptional = getUnderlyingTypeOfVariable(VD);
auto underlyingType = underlyingTypeAndIsOptional.first;
auto isOptional = underlyingTypeAndIsOptional.second;
// The element type must conform to NSCopying. If not, emit an error and just
// recovery by synthesizing without the copy call.
if (checkConformanceToNSCopying(TC, VD, underlyingType)) {
return Val;
}
// If we have an optional type, we have to "?" the incoming value to only
// evaluate the subexpression if the incoming value is non-null.
if (isOptional)
Val = new (Ctx) BindOptionalExpr(Val, SourceLoc(), 0);
// Generate:
// (force_value_expr type='<null>'
// (call_expr type='<null>'
// (unresolved_dot_expr type='<null>' field 'copy'
// "Val")
// (paren_expr type='<null>'
// (nil_literal_expr type='<null>'))))
auto UDE = new (Ctx) UnresolvedDotExpr(Val, SourceLoc(),
Ctx.getIdentifier("copy"),
DeclNameLoc(), /*implicit*/true);
Expr *Nil = new (Ctx) NilLiteralExpr(SourceLoc(), /*implicit*/true);
//- (id)copyWithZone:(NSZone *)zone;
Expr *Call = CallExpr::createImplicit(Ctx, UDE, { Nil }, { Ctx.Id_with });
TypeLoc ResultTy;
ResultTy.setType(VD->getType());
// If we're working with non-optional types, we're forcing the cast.
if (!isOptional) {
Call = new (Ctx) ForcedCheckedCastExpr(Call, SourceLoc(), SourceLoc(),
TypeLoc::withoutLoc(underlyingType));
Call->setImplicit();
return Call;
}
// We're working with optional types, so perform a conditional checked
// downcast.
Call = new (Ctx) ConditionalCheckedCastExpr(Call, SourceLoc(), SourceLoc(),
TypeLoc::withoutLoc(underlyingType));
Call->setImplicit();
// Use OptionalEvaluationExpr to evaluate the "?".
return new (Ctx) OptionalEvaluationExpr(Call);
}
/// In a synthesized accessor body, store 'value' to the appropriate element.
///
/// If the property is an override, we call the superclass setter.
/// Otherwise, we do a direct store of the value.
static void createPropertyStoreOrCallSuperclassSetter(AccessorDecl *accessor,
Expr *value,
AbstractStorageDecl *storage,
TargetImpl target,
SmallVectorImpl<ASTNode> &body,
TypeChecker &TC) {
// If the storage is an @NSCopying property, then we store the
// result of a copyWithZone call on the value, not the value itself.
if (auto property = dyn_cast<VarDecl>(storage)) {
if (property->getAttrs().hasAttribute<NSCopyingAttr>())
value = synthesizeCopyWithZoneCall(value, property, TC);
}
// Create:
// (assign (decl_ref_expr(VD)), decl_ref_expr(value))
// or:
// (assign (member_ref_expr(decl_ref_expr(self), VD)), decl_ref_expr(value))
Expr *dest = buildStorageReference(accessor, storage, target, TC);
body.push_back(new (TC.Context) AssignExpr(dest, SourceLoc(), value,
IsImplicit));
}
LLVM_ATTRIBUTE_UNUSED
static bool isSynthesizedComputedProperty(AbstractStorageDecl *storage) {
return (storage->getAttrs().hasAttribute<LazyAttr>() ||
storage->getAttrs().hasAttribute<NSManagedAttr>());
}
/// Synthesize the body of a trivial getter. For a non-member vardecl or one
/// which is not an override of a base class property, it performs a direct
/// storage load. For an override of a base member property, it chains up to
/// super.
static void synthesizeTrivialGetterBody(TypeChecker &TC, AccessorDecl *getter,
TargetImpl target) {
auto storage = getter->getStorage();
assert(!storage->getAttrs().hasAttribute<LazyAttr>() &&
!storage->getAttrs().hasAttribute<NSManagedAttr>());
auto &ctx = TC.Context;
SourceLoc loc = storage->getLoc();
Expr *result =
createPropertyLoadOrCallSuperclassGetter(getter, storage, target, TC);
ASTNode returnStmt = new (ctx) ReturnStmt(SourceLoc(), result, IsImplicit);
getter->setBody(BraceStmt::create(ctx, loc, returnStmt, loc, true));
finishSynthesis(TC, getter);
maybeMarkTransparent(TC, getter);
}
/// Synthesize the body of a getter which just directly accesses the
/// underlying storage.
static void synthesizeTrivialGetterBody(TypeChecker &TC, AccessorDecl *getter) {
assert(getter->getStorage()->hasStorage());
synthesizeTrivialGetterBody(TC, getter, TargetImpl::Storage);
}
/// Synthesize the body of a getter which just delegates to its superclass
/// implementation.
static void synthesizeInheritedGetterBody(TypeChecker &TC,
AccessorDecl *getter) {
// This should call the superclass getter.
synthesizeTrivialGetterBody(TC, getter, TargetImpl::Super);
}
/// Synthesize the body of a getter which just delegates to an addressor.
static void synthesizeAddressedGetterBody(TypeChecker &TC,
AccessorDecl *getter) {
assert(getter->getStorage()->getAddressor());
// This should call the addressor.
synthesizeTrivialGetterBody(TC, getter, TargetImpl::Implementation);
}
/// Synthesize the body of a getter which just delegates to a read
/// coroutine accessor.
static void synthesizeReadCoroutineGetterBody(TypeChecker &TC,
AccessorDecl *getter) {
assert(getter->getStorage()->getReadCoroutine());
// This should call the read coroutine.
synthesizeTrivialGetterBody(TC, getter, TargetImpl::Implementation);
}
/// Synthesize the body of a setter which just stores to the given storage
/// declaration (which doesn't have to be the storage for the setter).
static void synthesizeTrivialSetterBodyWithStorage(TypeChecker &TC,
AccessorDecl *setter,
TargetImpl target,
AbstractStorageDecl *storageToUse) {
auto &ctx = TC.Context;
SourceLoc loc = setter->getStorage()->getLoc();
VarDecl *valueParamDecl = getFirstParamDecl(setter);
auto *valueDRE =
new (ctx) DeclRefExpr(valueParamDecl, DeclNameLoc(), IsImplicit);
SmallVector<ASTNode, 1> setterBody;
createPropertyStoreOrCallSuperclassSetter(setter, valueDRE, storageToUse,
target, setterBody, TC);
setter->setBody(BraceStmt::create(ctx, loc, setterBody, loc, true));
finishSynthesis(TC, setter);
maybeMarkTransparent(TC, setter);
}
static void synthesizeTrivialSetterBody(TypeChecker &TC, AccessorDecl *setter) {
auto storage = setter->getStorage();
assert(!isSynthesizedComputedProperty(storage));
synthesizeTrivialSetterBodyWithStorage(TC, setter, TargetImpl::Storage,
storage);
}
static void synthesizeCoroutineAccessorBody(TypeChecker &TC,
AccessorDecl *accessor) {
assert(accessor->isCoroutine());
auto storage = accessor->getStorage();
auto target = (accessor->hasForcedStaticDispatch()
? TargetImpl::Ordinary
: TargetImpl::Implementation);
SourceLoc loc = storage->getLoc();
SmallVector<ASTNode, 1> body;
// Build a reference to the storage.
Expr *ref = buildStorageReference(accessor, storage, target, TC);
// Wrap it with an `&` marker if this is a modify.
if (accessor->getAccessorKind() == AccessorKind::Modify) {
ref = new (TC.Context) InOutExpr(SourceLoc(), ref, Type(), true);
}
// Yield it.
YieldStmt *yield = YieldStmt::create(TC.Context, loc, loc, ref, loc, true);
body.push_back(yield);
accessor->setBody(BraceStmt::create(TC.Context, loc, body, loc, true));
finishSynthesis(TC, accessor);
maybeMarkTransparent(TC, accessor);
}
/// Synthesize the body of a read coroutine.
static void synthesizeReadCoroutineBody(TypeChecker &TC, AccessorDecl *read) {
assert(read->getStorage()->getReadImpl() != ReadImplKind::Read);
synthesizeCoroutineAccessorBody(TC, read);
}
/// Synthesize the body of a modify coroutine.
static void synthesizeModifyCoroutineBody(TypeChecker &TC,
AccessorDecl *modify) {
#ifndef NDEBUG
auto impl = modify->getStorage()->getReadWriteImpl();
assert(impl != ReadWriteImplKind::Modify &&
impl != ReadWriteImplKind::Immutable);
#endif
synthesizeCoroutineAccessorBody(TC, modify);
}
static void addGetterToStorage(TypeChecker &TC, AbstractStorageDecl *storage) {
auto getter = createGetterPrototype(TC, storage);
// Install the prototype.
storage->setSynthesizedGetter(getter);
}
static void addSetterToStorage(TypeChecker &TC, AbstractStorageDecl *storage) {
auto setter = createSetterPrototype(TC, storage);
// Install the prototype.
storage->setSynthesizedSetter(setter);
}
static void addReadCoroutineToStorage(TypeChecker &TC,
AbstractStorageDecl *storage) {
auto read = createReadCoroutinePrototype(TC, storage);
// Install the prototype.
storage->setSynthesizedReadCoroutine(read);
}
static void addModifyCoroutineToStorage(TypeChecker &TC,
AbstractStorageDecl *storage) {
auto modify = createModifyCoroutinePrototype(TC, storage);
// Install the prototype.
storage->setSynthesizedModifyCoroutine(modify);
}
static void addOpaqueAccessorToStorage(TypeChecker &TC,
AbstractStorageDecl *storage,
AccessorKind kind) {
switch (kind) {
case AccessorKind::Get:
return addGetterToStorage(TC, storage);
case AccessorKind::Set:
return addSetterToStorage(TC, storage);
case AccessorKind::Read:
return addReadCoroutineToStorage(TC, storage);
case AccessorKind::Modify:
return addModifyCoroutineToStorage(TC, storage);
#define OPAQUE_ACCESSOR(ID, KEYWORD)
#define ACCESSOR(ID) \
case AccessorKind::ID:
#include "swift/AST/AccessorKinds.def"
llvm_unreachable("not an opaque accessor");
}
}
static void addExpectedOpaqueAccessorsToStorage(TypeChecker &TC,
AbstractStorageDecl *storage) {
// Nameless vars from interface files should not have any accessors.
// TODO: Replace this check with a broader check that all storage decls
// from interface files have all their accessors up front.
if (storage->getBaseName().empty())
return;
storage->visitExpectedOpaqueAccessors([&](AccessorKind kind) {
// If the accessor is already present, there's nothing to do.
if (storage->getAccessor(kind))
return;
addOpaqueAccessorToStorage(TC, storage, kind);
});
}
/// Add trivial accessors to a Stored or Addressed property.
static void addTrivialAccessorsToStorage(AbstractStorageDecl *storage,
TypeChecker &TC) {
assert(!isSynthesizedComputedProperty(storage));
addExpectedOpaqueAccessorsToStorage(TC, storage);
}
static StorageImplInfo getProtocolStorageImpl(AbstractStorageDecl *storage) {
auto protocol = cast<ProtocolDecl>(storage->getDeclContext());
if (protocol->isObjC()) {
return StorageImplInfo::getComputed(storage->supportsMutation());
} else {
return StorageImplInfo::getOpaque(storage->supportsMutation(),
storage->getOpaqueReadOwnership());
}
}
/// Given a storage declaration in a protocol, set it up with the right
/// StorageImpl and add the right set of opaque accessors.
static void setProtocolStorageImpl(TypeChecker &TC,
AbstractStorageDecl *storage) {
addExpectedOpaqueAccessorsToStorage(TC, storage);
storage->overwriteImplInfo(getProtocolStorageImpl(storage));
}
/// Synthesize the body of a setter which just delegates to a mutable
/// addressor.
static void synthesizeMutableAddressSetterBody(TypeChecker &TC,