-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathCodeSynthesis.cpp
2230 lines (1870 loc) · 89.1 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 - 2016 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 semantic analysis for declarations.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "ConstraintSystem.h"
#include "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Availability.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ParameterList.h"
#include "swift/Basic/Defer.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
using namespace swift;
const bool IsImplicit = true;
/// 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 if (isa<SourceFile>(DC)) {
auto *mod = DC->getParentModule();
mod->getDerivedFileUnit().addDerivedDecl(cast<FuncDecl>(D));
} else {
assert((isa<AbstractFunctionDecl>(DC) || isa<FileUnit>(DC)) &&
"Unknown declcontext");
}
}
static ParamDecl *getParamDeclAtIndex(FuncDecl *fn, unsigned index) {
return fn->getParameterLists().back()->get(index);
}
static VarDecl *getFirstParamDecl(FuncDecl *fn) {
return getParamDeclAtIndex(fn, 0);
};
static ParamDecl *buildArgument(SourceLoc loc, DeclContext *DC,
StringRef name, Type type, bool isLet) {
auto &context = DC->getASTContext();
auto *param = new (context) ParamDecl(isLet, SourceLoc(), SourceLoc(),
Identifier(), loc,
context.getIdentifier(name),Type(), DC);
param->setImplicit();
param->getTypeLoc().setType(type);
return param;
}
static ParamDecl *buildLetArgument(SourceLoc loc, DeclContext *DC,
StringRef name, Type type) {
return buildArgument(loc, DC, name, type, /*isLet*/ true);
}
static ParamDecl *buildInOutArgument(SourceLoc loc, DeclContext *DC,
StringRef name, Type type) {
return buildArgument(loc, DC, name, InOutType::get(type), /*isLet*/ false);
}
static Type getTypeOfStorage(AbstractStorageDecl *storage,
TypeChecker &TC) {
if (auto var = dyn_cast<VarDecl>(storage)) {
return TC.getTypeOfRValue(var, /*want interface type*/ false);
} else {
// None of the transformations done by getTypeOfRValue are
// necessary for subscripts.
auto subscript = cast<SubscriptDecl>(storage);
return subscript->getElementType();
}
}
/// 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);
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 FuncDecl *createGetterPrototype(AbstractStorageDecl *storage,
TypeChecker &TC) {
SourceLoc loc = storage->getLoc();
// Create the parameter list for the getter.
SmallVector<ParameterList*, 2> getterParams;
// The implicit 'self' argument if in a type context.
if (storage->getDeclContext()->isTypeContext())
getterParams.push_back(ParameterList::createUnboundSelf(loc,
storage->getDeclContext(),
/*isStatic*/false));
// Add an index-forwarding clause.
getterParams.push_back(buildIndexForwardingParamList(storage, {}));
SourceLoc staticLoc;
if (auto var = dyn_cast<VarDecl>(storage)) {
if (var->isStatic())
staticLoc = var->getLoc();
}
auto storageType = getTypeOfStorage(storage, TC);
auto getter = FuncDecl::create(
TC.Context, staticLoc, StaticSpellingKind::None, loc, Identifier(), loc,
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*AccessorKeywordLoc=*/SourceLoc(), /*GenericParams=*/nullptr,
getterParams, Type(), TypeLoc::withoutLoc(storageType),
storage->getDeclContext());
getter->setImplicit();
if (storage->isGetterMutating())
getter->setMutating();
// If the var is marked final, then so is the getter.
if (storage->isFinal())
makeFinal(TC.Context, getter);
if (storage->isStatic())
getter->setStatic();
return getter;
}
static FuncDecl *createSetterPrototype(AbstractStorageDecl *storage,
ParamDecl *&valueDecl,
TypeChecker &TC) {
SourceLoc loc = storage->getLoc();
// Create the parameter list for the setter.
SmallVector<ParameterList*, 2> params;
// The implicit 'self' argument if in a type context.
if (storage->getDeclContext()->isTypeContext()) {
params.push_back(ParameterList::createUnboundSelf(loc,
storage->getDeclContext(),
/*isStatic*/false));
}
// Add a "(value : T, indices...)" argument list.
auto storageType = getTypeOfStorage(storage, TC);
valueDecl = buildLetArgument(storage->getLoc(),
storage->getDeclContext(), "value",
storageType);
params.push_back(buildIndexForwardingParamList(storage, valueDecl));
Type setterRetTy = TupleType::getEmpty(TC.Context);
FuncDecl *setter = FuncDecl::create(
TC.Context, /*StaticLoc=*/SourceLoc(), StaticSpellingKind::None, loc,
Identifier(), loc, /*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*AccessorKeywordLoc=*/SourceLoc(), /*GenericParams=*/nullptr,
params, Type(), TypeLoc::withoutLoc(setterRetTy),
storage->getDeclContext());
setter->setImplicit();
if (!storage->isSetterNonMutating())
setter->setMutating();
// If the var is marked final, then so is the getter.
if (storage->isFinal())
makeFinal(TC.Context, setter);
if (storage->isStatic())
setter->setStatic();
return setter;
}
// True if the storage is dynamic or imported from Objective-C. In these cases,
// we need to emit a static materializeForSet thunk that dynamically dispatches
// to 'get' and 'set', rather than the normal dynamically dispatched
// materializeForSet that peer dispatches to 'get' and 'set'.
static bool needsDynamicMaterializeForSet(AbstractStorageDecl *storage) {
return storage->isDynamic() || storage->hasClangNode();
}
// True if a generated accessor needs to be registered as an external decl.
bool needsToBeRegisteredAsExternalDecl(AbstractStorageDecl *storage) {
// Either the storage itself was imported from Clang...
if (storage->hasClangNode())
return true;
// ...or it was synthesized into an imported type.
auto nominal = dyn_cast<NominalTypeDecl>(storage->getDeclContext());
if (!nominal)
return false;
return nominal->hasClangNode();
}
static FuncDecl *createMaterializeForSetPrototype(AbstractStorageDecl *storage,
TypeChecker &TC) {
auto &ctx = storage->getASTContext();
SourceLoc loc = storage->getLoc();
// Create the parameter list:
SmallVector<ParameterList*, 2> params;
// - The implicit 'self' argument if in a type context.
auto DC = storage->getDeclContext();
if (DC->isTypeContext())
params.push_back(ParameterList::createUnboundSelf(loc, DC, /*isStatic*/false));
// - The buffer parameter, (buffer: Builtin.RawPointer,
// inout storage: Builtin.UnsafeValueBuffer,
// indices...).
ParamDecl *bufferElements[] = {
buildLetArgument(loc, DC, "buffer", ctx.TheRawPointerType),
buildInOutArgument(loc, DC, "callbackStorage", ctx.TheUnsafeValueBufferType)
};
params.push_back(buildIndexForwardingParamList(storage, bufferElements));
// The accessor returns (temporary: Builtin.RawPointer,
// callback: Builtin.RawPointer),
// where the first pointer is the materialized address and the
// second is the address of an optional callback.
TupleTypeElt retElts[] = {
{ ctx.TheRawPointerType },
{ OptionalType::get(ctx.TheRawPointerType) },
};
Type retTy = TupleType::get(retElts, ctx);
auto *materializeForSet = FuncDecl::create(
ctx, /*StaticLoc=*/SourceLoc(), StaticSpellingKind::None, loc,
Identifier(), loc, /*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*AccessorKeywordLoc=*/SourceLoc(), /*GenericParams=*/nullptr,
params, Type(), TypeLoc::withoutLoc(retTy), DC);
materializeForSet->setImplicit();
// materializeForSet is mutating and static if the setter is.
auto setter = storage->getSetter();
// Open-code the setMutating() calculation since we might run before
// the setter has been type checked. Also as a hack, always mark the
// setter mutating if we're inside a protocol, because it seems some
// things break otherwise -- the root cause should be fixed eventually.
materializeForSet->setMutating(
setter->getDeclContext()->getAsProtocolOrProtocolExtensionContext() ||
(!setter->getAttrs().hasAttribute<NonMutatingAttr>() &&
!storage->isSetterNonMutating()));
materializeForSet->setStatic(setter->isStatic());
// materializeForSet is final if the storage is.
if (storage->isFinal())
makeFinal(ctx, materializeForSet);
// If the storage is dynamic or ObjC-native, we can't add a dynamically-
// dispatched method entry for materializeForSet, so force it to be
// statically dispatched. ("final" would be inappropriate because the
// property can still be overridden.)
if (needsDynamicMaterializeForSet(storage))
materializeForSet->setForcedStaticDispatch(true);
// Make sure materializeForSet 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 (FuncDecl *setter = storage->getSetter()) {
asAvailableAs.push_back(setter);
}
AvailabilityInference::applyInferredAvailableAttrs(materializeForSet,
asAvailableAs, ctx);
// If the property came from ObjC, we need to register this as an external
// definition to be compiled.
if (needsToBeRegisteredAsExternalDecl(storage))
TC.Context.addExternalDecl(materializeForSet);
return materializeForSet;
}
void swift::convertStoredVarInProtocolToComputed(VarDecl *VD, TypeChecker &TC) {
auto *Get = createGetterPrototype(VD, TC);
// Okay, we have both the getter and setter. Set them in VD.
VD->makeComputed(VD->getLoc(), Get, nullptr, nullptr, VD->getLoc());
// We've added some members to our containing class, add them to the members
// list.
addMemberToContextIfNeeded(Get, VD->getDeclContext());
// Type check the getter declaration.
TC.typeCheckDecl(VD->getGetter(), true);
TC.typeCheckDecl(VD->getGetter(), false);
}
/// 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) {
// We cannot express how to forward variadic parameters yet.
if (param->isVariadic())
return nullptr;
Expr *ref = new (ctx) DeclRefExpr(param, DeclNameLoc(), /*implicit*/ true);
if (param->getType()->is<InOutType>())
ref = new (ctx) InOutExpr(SourceLoc(), ref, Type(), /*implicit=*/true);
args.push_back(ref);
labels.push_back(param->getArgumentName());
labelLocs.push_back(SourceLoc());
}
// A single unlabelled value is not a tuple.
if (args.size() == 1 && labels[0].empty())
return args[0];
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, FuncDecl *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->getParameterLists().back()->getArray();
auto accessorKind = accessor->getAccessorKind();
// Ignore the value/buffer parameter.
if (accessorKind != AccessorKind::IsGetter)
params = params.slice(1);
// Ignore the materializeForSet callback storage parameter.
if (accessorKind == AccessorKind::IsMaterializeForSet)
params = params.slice(1);
// Okay, everything else should be forwarded, build the expression.
auto result = buildArgumentForwardingExpr(params, ctx);
assert(result && "FIXME: Cannot forward varargs");
return result;
}
enum class SelfAccessKind {
/// 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,
SelfAccessKind selfAccessKind,
TypeChecker &TC) {
switch (selfAccessKind) {
case SelfAccessKind::Peer:
return new (TC.Context) DeclRefExpr(selfDecl, DeclNameLoc(), IsImplicit);
case SelfAccessKind::Super:
return new (TC.Context) SuperRefExpr(selfDecl, SourceLoc(), IsImplicit);
}
llvm_unreachable("bad self access kind");
}
namespace {
/// A simple helper interface for buildStorageReference.
class StorageReferenceContext {
StorageReferenceContext(const StorageReferenceContext &) = delete;
public:
StorageReferenceContext() = default;
virtual ~StorageReferenceContext() = default;
/// Returns the declaration of the entity to use as the base of
/// the access, or nil if no base is required.
virtual VarDecl *getSelfDecl() const = 0;
/// Returns an expression producing the index value, assuming that
/// the storage is a subscript declaration.
virtual Expr *getIndexRefExpr(ASTContext &ctx,
SubscriptDecl *subscript) const = 0;
};
/// A reference to storage from within an accessor.
class AccessorStorageReferenceContext : public StorageReferenceContext {
FuncDecl *Accessor;
public:
AccessorStorageReferenceContext(FuncDecl *accessor) : Accessor(accessor) {}
virtual ~AccessorStorageReferenceContext() = default;
VarDecl *getSelfDecl() const override {
return Accessor->getImplicitSelfDecl();
}
Expr *getIndexRefExpr(ASTContext &ctx,
SubscriptDecl *subscript) const override {
return buildSubscriptIndexReference(ctx, Accessor);
}
};
}
/// Build an l-value for the storage of a declaration.
static Expr *buildStorageReference(
const StorageReferenceContext &referenceContext,
AbstractStorageDecl *storage,
AccessSemantics semantics,
SelfAccessKind selfAccessKind,
TypeChecker &TC) {
ASTContext &ctx = TC.Context;
VarDecl *selfDecl = referenceContext.getSelfDecl();
if (!selfDecl) {
return new (ctx) DeclRefExpr(storage, DeclNameLoc(), IsImplicit, semantics);
}
// If we should use a super access if applicable, and we have an
// overridden decl, then use ordinary access to it.
if (selfAccessKind == SelfAccessKind::Super) {
if (auto overridden = storage->getOverriddenDecl()) {
storage = overridden;
semantics = AccessSemantics::Ordinary;
} else {
selfAccessKind = SelfAccessKind::Peer;
}
}
Expr *selfDRE = buildSelfReference(selfDecl, selfAccessKind, TC);
if (auto subscript = dyn_cast<SubscriptDecl>(storage)) {
Expr *indices = referenceContext.getIndexRefExpr(ctx, subscript);
return new (ctx) SubscriptExpr(selfDRE, indices, storage,
IsImplicit, semantics);
}
// This is a potentially polymorphic access, which is unnecessary;
// however, it shouldn't be problematic because any overrides
// should also redefine materializeForSet.
return new (ctx) MemberRefExpr(selfDRE, SourceLoc(), storage,
DeclNameLoc(), IsImplicit, semantics);
}
static Expr *buildStorageReference(FuncDecl *accessor,
AbstractStorageDecl *storage,
AccessSemantics semantics,
SelfAccessKind selfAccessKind,
TypeChecker &TC) {
return buildStorageReference(AccessorStorageReferenceContext(accessor),
storage, semantics, selfAccessKind, TC);
}
/// 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(FuncDecl *accessor,
AbstractStorageDecl *storage,
TypeChecker &TC) {
return buildStorageReference(accessor, storage,
AccessSemantics::DirectToStorage,
SelfAccessKind::Super, 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(ModuleType::get(foundation),
ctx.getSwiftId(KnownFoundationEntity::NSCopying),
NL_QualifiedDefault | NL_KnownNonCascadingDependency,
/*resolver=*/nullptr,
results);
if (results.size() != 1)
return nullptr;
return dyn_cast<ProtocolDecl>(results.front());
}
/// 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.
Type UnderlyingType = TC.getTypeOfRValue(VD, /*want interface type*/false);
bool isOptional = false;
if (Type optionalEltTy = UnderlyingType->getAnyOptionalObjectType()) {
UnderlyingType = optionalEltTy;
isOptional = true;
}
// The element type must conform to NSCopying. If not, emit an error and just
// recovery by synthesizing without the copy call.
auto *CopyingProto = getNSCopyingProtocol(TC, VD->getDeclContext());
if (!CopyingProto || !TC.conformsToProtocol(UnderlyingType, CopyingProto,
VD->getDeclContext(), None)) {
TC.diagnose(VD->getLoc(), diag::nscopying_doesnt_conform);
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);
Nil = TupleExpr::create(Ctx, SourceLoc(), { Nil }, { Ctx.Id_with },
{ SourceLoc() }, SourceLoc(), false, true);
//- (id)copyWithZone:(NSZone *)zone;
Expr *Call = new (Ctx) CallExpr(UDE, Nil, /*implicit*/true);
TypeLoc ResultTy;
ResultTy.setType(VD->getType(), true);
// 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(FuncDecl *accessor,
Expr *value,
AbstractStorageDecl *storage,
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,
AccessSemantics::DirectToStorage,
SelfAccessKind::Super, TC);
body.push_back(new (TC.Context) AssignExpr(dest, SourceLoc(), value,
IsImplicit));
}
/// 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(FuncDecl *accessor,
AbstractStorageDecl *storage,
TypeChecker &TC) {
auto *nominal = storage->getDeclContext()
->getAsNominalTypeOrNominalTypeExtensionContext();
if (nominal && nominal->hasFixedLayout())
accessor->getAttrs().add(new (TC.Context) TransparentAttr(IsImplicit));
}
/// 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 synthesizeTrivialGetter(FuncDecl *getter,
AbstractStorageDecl *storage,
TypeChecker &TC) {
auto &ctx = TC.Context;
Expr *result = createPropertyLoadOrCallSuperclassGetter(getter, storage, TC);
ASTNode returnStmt = new (ctx) ReturnStmt(SourceLoc(), result, IsImplicit);
SourceLoc loc = storage->getLoc();
getter->setBody(BraceStmt::create(ctx, loc, returnStmt, loc, true));
maybeMarkTransparent(getter, storage, TC);
// Register the accessor as an external decl if the storage was imported.
if (needsToBeRegisteredAsExternalDecl(storage))
TC.Context.addExternalDecl(getter);
}
/// Synthesize the body of a trivial setter.
static void synthesizeTrivialSetter(FuncDecl *setter,
AbstractStorageDecl *storage,
VarDecl *valueVar,
TypeChecker &TC) {
if (storage->isInvalid()) return;
auto &ctx = TC.Context;
SourceLoc loc = storage->getLoc();
auto *valueDRE = new (ctx) DeclRefExpr(valueVar, DeclNameLoc(), IsImplicit);
SmallVector<ASTNode, 1> setterBody;
createPropertyStoreOrCallSuperclassSetter(setter, valueDRE, storage,
setterBody, TC);
setter->setBody(BraceStmt::create(ctx, loc, setterBody, loc, true));
maybeMarkTransparent(setter, storage, TC);
// Register the accessor as an external decl if the storage was imported.
if (needsToBeRegisteredAsExternalDecl(storage))
TC.Context.addExternalDecl(setter);
}
/// Does a storage decl currently lacking accessor functions require a
/// setter to be synthesized?
static bool doesStorageNeedSetter(AbstractStorageDecl *storage) {
assert(!storage->hasAccessorFunctions());
switch (storage->getStorageKind()) {
// Add a setter to a stored variable unless it's a let.
case AbstractStorageDecl::Stored:
return !cast<VarDecl>(storage)->isLet();
// Addressed storage gets a setter if it has a mutable addressor.
case AbstractStorageDecl::Addressed:
return storage->getMutableAddressor() != nullptr;
// These should already have accessor functions.
case AbstractStorageDecl::StoredWithTrivialAccessors:
case AbstractStorageDecl::StoredWithObservers:
case AbstractStorageDecl::InheritedWithObservers:
case AbstractStorageDecl::AddressedWithTrivialAccessors:
case AbstractStorageDecl::AddressedWithObservers:
case AbstractStorageDecl::ComputedWithMutableAddress:
llvm_unreachable("already has accessor functions");
case AbstractStorageDecl::Computed:
llvm_unreachable("not stored");
}
llvm_unreachable("bad storage kind");
}
/// Add a materializeForSet accessor to the given declaration.
static FuncDecl *addMaterializeForSet(AbstractStorageDecl *storage,
TypeChecker &TC) {
auto materializeForSet = createMaterializeForSetPrototype(storage, TC);
addMemberToContextIfNeeded(materializeForSet, storage->getDeclContext(),
storage->getSetter());
storage->setMaterializeForSetFunc(materializeForSet);
TC.computeAccessibility(materializeForSet);
TC.validateDecl(materializeForSet);
return materializeForSet;
}
/// Add trivial accessors to a Stored or Addressed property.
void swift::addTrivialAccessorsToStorage(AbstractStorageDecl *storage,
TypeChecker &TC) {
assert(!storage->hasAccessorFunctions() && "already has accessors?");
// Create the getter.
auto *getter = createGetterPrototype(storage, TC);
if (storage->hasAccessorFunctions()) return;
// Create the setter.
FuncDecl *setter = nullptr;
ParamDecl *setterValueParam = nullptr;
if (doesStorageNeedSetter(storage)) {
setter = createSetterPrototype(storage, setterValueParam, TC);
if (storage->hasAccessorFunctions()) return;
}
// Okay, we have both the getter and setter. Set them in VD.
storage->addTrivialAccessors(getter, setter, nullptr);
bool isDynamic = (storage->isDynamic() && storage->isObjC());
if (isDynamic)
getter->getAttrs().add(new (TC.Context) DynamicAttr(IsImplicit));
// Synthesize and type-check the body of the getter.
synthesizeTrivialGetter(getter, storage, TC);
TC.typeCheckDecl(getter, true);
TC.typeCheckDecl(getter, false);
if (setter) {
if (isDynamic)
setter->getAttrs().add(new (TC.Context) DynamicAttr(IsImplicit));
// Synthesize and type-check the body of the setter.
synthesizeTrivialSetter(setter, storage, setterValueParam, TC);
TC.typeCheckDecl(setter, true);
TC.typeCheckDecl(setter, false);
}
auto *DC = storage->getDeclContext();
// We've added some members to our containing context, add them to
// the right list.
addMemberToContextIfNeeded(getter, DC);
if (setter)
addMemberToContextIfNeeded(setter, DC);
// If we're creating trivial accessors for a stored property of a
// nominal type, the stored property is either witnessing a
// protocol requirement or the nominal type is resilient. In both
// cases, we need to expose a materializeForSet.
//
// Global stored properties don't get a materializeForSet.
if (setter && DC->getAsNominalTypeOrNominalTypeExtensionContext()) {
FuncDecl *materializeForSet = addMaterializeForSet(storage, TC);
synthesizeMaterializeForSet(materializeForSet, storage, TC);
TC.typeCheckDecl(materializeForSet, false);
}
}
/// Add a trivial setter and materializeForSet to a
/// ComputedWithMutableAddress storage decl.
void swift::
synthesizeSetterForMutableAddressedStorage(AbstractStorageDecl *storage,
TypeChecker &TC) {
auto setter = storage->getSetter();
assert(setter);
assert(!storage->getSetter()->getBody());
assert(storage->getStorageKind() ==
AbstractStorageDecl::ComputedWithMutableAddress);
// Synthesize and type-check the body of the setter.
VarDecl *valueParamDecl = getFirstParamDecl(setter);
synthesizeTrivialSetter(setter, storage, valueParamDecl, TC);
TC.typeCheckDecl(setter, true);
TC.typeCheckDecl(setter, false);
}
void TypeChecker::synthesizeAccessorsForStorage(AbstractStorageDecl *storage,
bool wantMaterializeForSet) {
// If the decl is stored, convert it to StoredWithTrivialAccessors
// by synthesizing the full set of accessors.
if (!storage->hasAccessorFunctions()) {
addTrivialAccessorsToStorage(storage, *this);
return;
}
// If we want wantMaterializeForSet, create it now.
if (wantMaterializeForSet && !storage->getMaterializeForSetFunc()) {
FuncDecl *materializeForSet = addMaterializeForSet(storage, *this);
synthesizeMaterializeForSet(materializeForSet, storage, *this);
typeCheckDecl(materializeForSet, false);
}
}
/// The specified AbstractStorageDecl was just found to satisfy a
/// protocol property requirement. Ensure that it has the full
/// complement of accessors.
void TypeChecker::synthesizeWitnessAccessorsForStorage(
AbstractStorageDecl *requirement,
AbstractStorageDecl *storage) {
// @objc protocols don't need a materializeForSet since ObjC doesn't
// have that concept.
bool wantMaterializeForSet =
!requirement->isObjC() && requirement->getSetter();
synthesizeAccessorsForStorage(storage, wantMaterializeForSet);
}
void swift::synthesizeMaterializeForSet(FuncDecl *materializeForSet,
AbstractStorageDecl *storage,
TypeChecker &TC) {
// The body is actually emitted by SILGen
maybeMarkTransparent(materializeForSet, storage, TC);
TC.typeCheckDecl(materializeForSet, true);
// Register the accessor as an external decl if the storage was imported.
if (needsToBeRegisteredAsExternalDecl(storage))
TC.Context.addExternalDecl(materializeForSet);
}
/// Given a VarDecl with a willSet: and/or didSet: specifier, synthesize the
/// (trivial) getter and the setter, which calls these.
void swift::synthesizeObservingAccessors(VarDecl *VD, TypeChecker &TC) {
assert(VD->hasObservers());
assert(VD->getGetter() && VD->getSetter() &&
!VD->getGetter()->hasBody() && !VD->getSetter()->hasBody() &&
"willSet/didSet var already has a getter or setter");
auto &Ctx = VD->getASTContext();
SourceLoc Loc = VD->getLoc();
// The getter is always trivial: just perform a (direct!) load of storage, or
// a call of a superclass getter if this is an override.
auto *Get = VD->getGetter();
synthesizeTrivialGetter(Get, VD, TC);
// Okay, the getter is done, create the setter now. Start by finding the
// decls for 'self' and 'value'.
auto *Set = VD->getSetter();
auto *SelfDecl = Set->getImplicitSelfDecl();
VarDecl *ValueDecl = Set->getParameterLists().back()->get(0);
// The setter loads the oldValue, invokes willSet with the incoming value,
// does a direct store, then invokes didSet with the oldValue.
SmallVector<ASTNode, 6> SetterBody;
// If there is a didSet, it will take the old value. Load it into a temporary
// 'let' so we have it for later.
// TODO: check the body of didSet to only do this load (which may call the
// superclass getter) if didSet takes an argument.
VarDecl *OldValue = nullptr;
if (VD->getDidSetFunc()) {
Expr *OldValueExpr
= createPropertyLoadOrCallSuperclassGetter(Set, VD, TC);
OldValue = new (Ctx) VarDecl(/*isStatic*/false, /*isLet*/ true,
SourceLoc(), Ctx.getIdentifier("tmp"),
Type(), Set);
OldValue->setImplicit();
auto *tmpPattern = new (Ctx) NamedPattern(OldValue, /*implicit*/ true);
auto tmpPBD = PatternBindingDecl::create(Ctx, SourceLoc(),
StaticSpellingKind::None,
SourceLoc(),
tmpPattern, OldValueExpr, Set);
tmpPBD->setImplicit();
SetterBody.push_back(tmpPBD);
SetterBody.push_back(OldValue);
}
// Create:
// (call_expr (dot_syntax_call_expr (decl_ref_expr(willSet)),
// (decl_ref_expr(self))),
// (declrefexpr(value)))
// or:
// (call_expr (decl_ref_expr(willSet)), (declrefexpr(value)))
if (auto willSet = VD->getWillSetFunc()) {
Expr *Callee = new (Ctx) DeclRefExpr(willSet, DeclNameLoc(), /*imp*/true);
auto *ValueDRE = new (Ctx) DeclRefExpr(ValueDecl, DeclNameLoc(),
/*imp*/true);
if (SelfDecl) {
auto *SelfDRE = new (Ctx) DeclRefExpr(SelfDecl, DeclNameLoc(),
/*imp*/true);
Callee = new (Ctx) DotSyntaxCallExpr(Callee, SourceLoc(), SelfDRE);
}
SetterBody.push_back(new (Ctx) CallExpr(Callee, ValueDRE, true));
// Make sure the didSet/willSet accessors are marked final if in a class.
if (!willSet->isFinal() &&
VD->getDeclContext()->getAsClassOrClassExtensionContext())
makeFinal(Ctx, willSet);
}
// Create an assignment into the storage or call to superclass setter.
auto *ValueDRE = new (Ctx) DeclRefExpr(ValueDecl, DeclNameLoc(), true);
createPropertyStoreOrCallSuperclassSetter(Set, ValueDRE, VD, SetterBody, TC);
// Create:
// (call_expr (dot_syntax_call_expr (decl_ref_expr(didSet)),
// (decl_ref_expr(self))),
// (decl_ref_expr(tmp)))
// or:
// (call_expr (decl_ref_expr(didSet)), (decl_ref_expr(tmp)))
if (auto didSet = VD->getDidSetFunc()) {
auto *OldValueExpr = new (Ctx) DeclRefExpr(OldValue, DeclNameLoc(),
/*impl*/true);
Expr *Callee = new (Ctx) DeclRefExpr(didSet, DeclNameLoc(), /*imp*/true);
if (SelfDecl) {
auto *SelfDRE = new (Ctx) DeclRefExpr(SelfDecl, DeclNameLoc(),
/*imp*/true);
Callee = new (Ctx) DotSyntaxCallExpr(Callee, SourceLoc(), SelfDRE);
}
SetterBody.push_back(new (Ctx) CallExpr(Callee, OldValueExpr, true));
// Make sure the didSet/willSet accessors are marked final if in a class.
if (!didSet->isFinal() &&
VD->getDeclContext()->getAsClassOrClassExtensionContext())
makeFinal(Ctx, didSet);
}
Set->setBody(BraceStmt::create(Ctx, Loc, SetterBody, Loc, true));
// Type check the body of the getter and setter.
TC.typeCheckDecl(Get, true);
TC.typeCheckDecl(Get, false);
TC.typeCheckDecl(Set, true);
TC.typeCheckDecl(Set, false);
}
static void convertNSManagedStoredVarToComputed(VarDecl *VD, TypeChecker &TC) {
assert(VD->getStorageKind() == AbstractStorageDecl::Stored);
// Create the getter.
auto *Get = createGetterPrototype(VD, TC);
if (VD->hasAccessorFunctions()) return;
// Create the setter.
ParamDecl *SetValueDecl = nullptr;
auto *Set = createSetterPrototype(VD, SetValueDecl, TC);
if (VD->hasAccessorFunctions()) return;
// Okay, we have both the getter and setter. Set them in VD.
VD->makeComputed(VD->getLoc(), Get, Set, nullptr, VD->getLoc());
TC.validateDecl(Get);
TC.validateDecl(Set);
// We've added some members to our containing class/extension, add them to
// the members list.
addMemberToContextIfNeeded(Get, VD->getDeclContext());
addMemberToContextIfNeeded(Set, VD->getDeclContext());
}
namespace {
/// This ASTWalker explores an expression tree looking for expressions (which
/// are DeclContext's) and changes their parent DeclContext to NewDC.
class RecontextualizeClosures : public ASTWalker {