-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathDerivedConformanceCodable.cpp
2157 lines (1834 loc) · 83.3 KB
/
DerivedConformanceCodable.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
//===--- DerivedConformanceCodable.cpp - Derived Codable ------------------===//
//
// 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 explicit derivation of the Encodable and Decodable
// protocols for a struct or class.
//
//===----------------------------------------------------------------------===//
#include "CodeSynthesis.h"
#include "TypeChecker.h"
#include "llvm/ADT/STLExtras.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/StringExtras.h"
#include "DerivedConformances.h"
using namespace swift;
/// Returns whether the type represented by the given ClassDecl inherits from a
/// type which conforms to the given protocol.
static bool superclassConformsTo(ClassDecl *target, KnownProtocolKind kpk) {
if (!target) {
return false;
}
auto superclass = target->getSuperclassDecl();
if (!superclass)
return false;
return !lookupConformance(target->getSuperclass(),
target->getASTContext().getProtocol(kpk))
.isInvalid();
}
/// Retrieve the variable name for the purposes of encoding/decoding.
///
/// \param paramIndex if set will be used to generate name in the form of
/// '_$paramIndex' when VarDecl has no name.
static Identifier
getVarNameForCoding(VarDecl *var,
std::optional<int> paramIndex = std::nullopt) {
auto &C = var->getASTContext();
Identifier identifier;
if (auto *PD = dyn_cast<ParamDecl>(var)) {
identifier = PD->getArgumentName();
} else {
identifier = var->getName();
}
if (auto originalVar = var->getOriginalWrappedProperty())
identifier = originalVar->getName();
if (identifier.empty() && paramIndex.has_value())
return C.getIdentifier("_" + std::to_string(paramIndex.value()));
return identifier;
}
/// Compute the Identifier for the CodingKey of an enum case
static Identifier caseCodingKeysIdentifier(const ASTContext &C,
EnumElementDecl *elt) {
llvm::SmallString<16> scratch;
camel_case::appendSentenceCase(scratch, elt->getBaseIdentifier().str());
scratch += C.Id_CodingKeys.str();
return C.getIdentifier(scratch.str());
}
/// Fetches the \c CodingKeys enum nested in \c target, potentially reaching
/// through a typealias if the "CodingKeys" entity is a typealias.
///
/// This is only useful once a \c CodingKeys enum has been validated (via \c
/// hasValidCodingKeysEnum) or synthesized (via \c synthesizeCodingKeysEnum).
///
/// \param C The \c ASTContext to perform the lookup in.
///
/// \param target The target type to look in.
///
/// \return A retrieved canonical \c CodingKeys enum if \c target has a valid
/// one; \c nullptr otherwise.
static EnumDecl *lookupEvaluatedCodingKeysEnum(ASTContext &C,
NominalTypeDecl *target,
Identifier identifier) {
auto codingKeyDecls = target->lookupDirect(DeclName(identifier));
if (codingKeyDecls.empty())
return nullptr;
auto *codingKeysDecl = codingKeyDecls.front();
if (auto *typealiasDecl = dyn_cast<TypeAliasDecl>(codingKeysDecl))
codingKeysDecl = typealiasDecl->getDeclaredInterfaceType()->getAnyNominal();
return dyn_cast<EnumDecl>(codingKeysDecl);
}
static EnumDecl *lookupEvaluatedCodingKeysEnum(ASTContext &C,
NominalTypeDecl *target) {
return lookupEvaluatedCodingKeysEnum(C, target, C.Id_CodingKeys);
}
static EnumElementDecl *lookupEnumCase(ASTContext &C, NominalTypeDecl *target,
Identifier identifier) {
auto elementDecls = target->lookupDirect(DeclName(identifier));
if (elementDecls.empty())
return nullptr;
auto *elementDecl = elementDecls.front();
return dyn_cast<EnumElementDecl>(elementDecl);
}
static NominalTypeDecl *lookupErrorContext(ASTContext &C,
NominalTypeDecl *errorDecl) {
auto elementDecls = errorDecl->lookupDirect(C.Id_Context);
if (elementDecls.empty())
return nullptr;
auto *decl = elementDecls.front();
return dyn_cast<NominalTypeDecl>(decl);
}
static EnumDecl *
addImplicitCodingKeys(NominalTypeDecl *target,
llvm::SmallVectorImpl<Identifier> &caseIdentifiers,
Identifier codingKeysEnumIdentifier) {
auto &C = target->getASTContext();
assert(target->lookupDirect(DeclName(codingKeysEnumIdentifier)).empty());
// We want to look through all the var declarations of this type to create
// enum cases based on those var names.
auto *codingKeyProto = C.getProtocol(KnownProtocolKind::CodingKey);
auto codingKeyType = codingKeyProto->getDeclaredInterfaceType();
InheritedEntry protoTypeLoc[1] = {
InheritedEntry(TypeLoc::withoutLoc(codingKeyType))};
ArrayRef<InheritedEntry> inherited = C.AllocateCopy(protoTypeLoc);
auto *enumDecl = new (C) EnumDecl(SourceLoc(), codingKeysEnumIdentifier,
SourceLoc(), inherited, nullptr, target);
enumDecl->setImplicit();
enumDecl->setSynthesized();
enumDecl->setAccess(AccessLevel::Private);
// For classes which inherit from something Encodable or Decodable, we
// provide case `super` as the first key (to be used in encoding super).
auto *classDecl = dyn_cast<ClassDecl>(target);
if (superclassConformsTo(classDecl, KnownProtocolKind::Encodable) ||
superclassConformsTo(classDecl, KnownProtocolKind::Decodable)) {
// TODO: Ensure the class doesn't already have or inherit a variable named
// "`super`"; otherwise we will generate an invalid enum. In that case,
// diagnose and bail.
auto *super = new (C) EnumElementDecl(SourceLoc(), C.Id_super, nullptr,
SourceLoc(), nullptr, enumDecl);
super->setImplicit();
enumDecl->addMember(super);
}
for (auto caseIdentifier : caseIdentifiers) {
auto *elt = new (C) EnumElementDecl(SourceLoc(), caseIdentifier, nullptr,
SourceLoc(), nullptr, enumDecl);
elt->setImplicit();
enumDecl->addMember(elt);
}
// Forcibly derive conformance to CodingKey.
TypeChecker::checkConformancesInContext(enumDecl);
// Add to the type.
target->addMember(enumDecl);
return enumDecl;
}
static EnumDecl *addImplicitCaseCodingKeys(EnumDecl *target,
EnumElementDecl *elementDecl,
EnumDecl *codingKeysEnum) {
auto &C = target->getASTContext();
// Only derive if this case exist in the CodingKeys enum
auto *codingKeyCase =
lookupEnumCase(C, codingKeysEnum, elementDecl->getBaseIdentifier());
if (!codingKeyCase)
return nullptr;
auto enumIdentifier = caseCodingKeysIdentifier(C, elementDecl);
llvm::SmallVector<Identifier, 4> caseIdentifiers;
if (elementDecl->hasAssociatedValues()) {
for (auto entry : llvm::enumerate(*elementDecl->getParameterList())) {
auto *paramDecl = entry.value();
// if the type conforms to {En,De}codable, add it to the enum.
Identifier paramIdentifier =
getVarNameForCoding(paramDecl, entry.index());
caseIdentifiers.push_back(paramIdentifier);
}
}
return addImplicitCodingKeys(target, caseIdentifiers, enumIdentifier);
}
// Create CodingKeys in the parent type always, because both
// Encodable and Decodable might want to use it, and they may have
// different conditional bounds. CodingKeys is simple and can't
// depend on those bounds.
//
// FIXME: Eventually we should find a way to expose this function to the lookup
// machinery so it no longer costs two protocol conformance lookups to retrieve
// CodingKeys. It will also help in our quest to separate semantic and parsed
// members.
static EnumDecl *addImplicitCodingKeys(NominalTypeDecl *target) {
auto &C = target->getASTContext();
llvm::SmallVector<Identifier, 4> caseIdentifiers;
if (auto *enumDecl = dyn_cast<EnumDecl>(target)) {
for (auto *elementDecl : enumDecl->getAllElements()) {
caseIdentifiers.push_back(elementDecl->getBaseIdentifier());
}
} else {
for (auto *varDecl : target->getStoredProperties()) {
if (!varDecl->isUserAccessible()) {
continue;
}
caseIdentifiers.push_back(getVarNameForCoding(varDecl));
}
}
return addImplicitCodingKeys(target, caseIdentifiers, C.Id_CodingKeys);
}
namespace {
/// Container for a set of functions that produces notes used when a
/// synthesized conformance fails.
struct DelayedNotes : public std::vector<std::function<void()>> {
~DelayedNotes() {
for (const auto &fn : *this) {
fn();
}
}
};
}
static EnumDecl *validateCodingKeysType(const DerivedConformance &derived,
TypeDecl *_codingKeysTypeDecl,
DelayedNotes &delayedNotes) {
auto &C = derived.Context;
// CodingKeys may be a typealias. If so, follow the alias to its canonical
// type. We are creating a copy here, so we can hold on to the original
// `TypeDecl` in case we need to produce a diagnostic.
auto *codingKeysTypeDecl = _codingKeysTypeDecl;
auto codingKeysType = codingKeysTypeDecl->getDeclaredInterfaceType();
if (isa<TypeAliasDecl>(codingKeysTypeDecl))
codingKeysTypeDecl = codingKeysType->getAnyNominal();
// Ensure that the type we found conforms to the CodingKey protocol.
auto *codingKeyProto = C.getProtocol(KnownProtocolKind::CodingKey);
if (!lookupConformance(codingKeysType, codingKeyProto)) {
// If CodingKeys is a typealias which doesn't point to a valid nominal type,
// codingKeysTypeDecl will be nullptr here. In that case, we need to warn on
// the location of the usage, since there isn't an underlying type to
// diagnose on.
SourceLoc loc = codingKeysTypeDecl ? codingKeysTypeDecl->getLoc()
: cast<TypeDecl>(_codingKeysTypeDecl)->getLoc();
delayedNotes.push_back([=] {
ASTContext &C = derived.getProtocolType()->getASTContext();
C.Diags.diagnose(loc, diag::codable_codingkeys_type_does_not_conform_here,
derived.getProtocolType());
});
return nullptr;
}
auto *codingKeysDecl =
dyn_cast_or_null<EnumDecl>(codingKeysType->getAnyNominal());
if (!codingKeysDecl) {
delayedNotes.push_back([=] {
codingKeysTypeDecl->diagnose(
diag::codable_codingkeys_type_is_not_an_enum_here,
derived.getProtocolType());
});
return nullptr;
}
return codingKeysDecl;
}
/// Validates the given CodingKeys enum decl by ensuring its cases are a 1-to-1
/// match with the given VarDecls.
///
/// \param varDecls The \c var decls to validate against.
/// \param codingKeysTypeDecl The \c CodingKeys enum decl to validate.
static bool validateCodingKeysEnum(const DerivedConformance &derived,
llvm::SmallMapVector<Identifier, VarDecl *, 8> varDecls,
TypeDecl *codingKeysTypeDecl,
DelayedNotes &delayedNotes) {
auto *codingKeysDecl = validateCodingKeysType(
derived, codingKeysTypeDecl, delayedNotes);
if (!codingKeysDecl)
return false;
// Look through all var decls.
//
// If any of the entries in the CodingKeys decl are not present in the type
// by name, then this decl doesn't match.
// If there are any vars left in the type which don't have a default value
// (for Decodable), then this decl doesn't match.
bool varDeclsAreValid = true;
for (auto elt : codingKeysDecl->getAllElements()) {
auto it = varDecls.find(elt->getBaseIdentifier());
if (it == varDecls.end()) {
delayedNotes.push_back([=] {
elt->diagnose(diag::codable_extraneous_codingkey_case_here,
elt->getBaseIdentifier());
});
// TODO: Investigate typo-correction here; perhaps the case name was
// misspelled and we can provide a fix-it.
varDeclsAreValid = false;
continue;
}
// We have a property to map to. Ensure it's {En,De}codable.
auto target = derived.getConformanceContext()->mapTypeIntoContext(
it->second->getValueInterfaceType());
if (checkConformance(target, derived.Protocol).isInvalid()) {
TypeLoc typeLoc = {
it->second->getTypeReprOrParentPatternTypeRepr(),
it->second->getTypeInContext(),
};
auto var = it->second;
auto proto = derived.getProtocolType();
delayedNotes.push_back([=] {
var->diagnose(diag::codable_non_conforming_property_here,
proto, typeLoc);
});
varDeclsAreValid = false;
} else {
// The property was valid. Remove it from the list.
varDecls.erase(it);
}
}
if (!varDeclsAreValid)
return false;
// If there are any remaining var decls which the CodingKeys did not cover,
// we can skip them on encode. On decode, though, we can only skip them if
// they have a default value.
if (derived.Protocol->isSpecificProtocol(KnownProtocolKind::Decodable)) {
for (auto &entry : varDecls) {
const auto *pbd = entry.second->getParentPatternBinding();
if (pbd && pbd->isDefaultInitializable()) {
continue;
}
if (entry.second->isParentInitialized()) {
continue;
}
if (auto *paramDecl = dyn_cast<ParamDecl>(entry.second)) {
if (paramDecl->hasDefaultExpr()) {
continue;
}
}
// The var was not default initializable, and did not have an explicit
// initial value.
varDeclsAreValid = false;
delayedNotes.push_back([=] {
entry.second->diagnose(diag::codable_non_decoded_property_here,
derived.getProtocolType(), entry.first);
});
}
}
return varDeclsAreValid;
}
static bool validateCodingKeysEnum_enum(const DerivedConformance &derived,
TypeDecl *codingKeysTypeDecl,
DelayedNotes &delayedNotes) {
auto *enumDecl = dyn_cast<EnumDecl>(derived.Nominal);
if (!enumDecl) {
return false;
}
llvm::SmallSetVector<Identifier, 4> caseNames;
for (auto *elt : enumDecl->getAllElements()) {
caseNames.insert(elt->getBaseIdentifier());
}
auto *codingKeysDecl = validateCodingKeysType(
derived, codingKeysTypeDecl, delayedNotes);
if (!codingKeysDecl)
return false;
bool casesAreValid = true;
for (auto *elt : codingKeysDecl->getAllElements()) {
if (!caseNames.contains(elt->getBaseIdentifier())) {
delayedNotes.push_back([=] {
elt->diagnose(diag::codable_extraneous_codingkey_case_here,
elt->getBaseIdentifier());
});
casesAreValid = false;
}
}
return casesAreValid;
}
/// Looks up and validates a CodingKeys enum for the given DerivedConformance.
/// If a CodingKeys enum does not exist, one will be derived.
static bool validateCodingKeysEnum(const DerivedConformance &derived,
DelayedNotes &delayedNotes) {
auto &C = derived.Context;
auto codingKeysDecls =
derived.Nominal->lookupDirect(DeclName(C.Id_CodingKeys));
if (codingKeysDecls.size() > 1) {
return false;
}
ValueDecl *result = codingKeysDecls.empty()
? addImplicitCodingKeys(derived.Nominal)
: codingKeysDecls.front();
auto *codingKeysTypeDecl = dyn_cast<TypeDecl>(result);
if (!codingKeysTypeDecl) {
delayedNotes.push_back([=] {
result->diagnose(diag::codable_codingkeys_type_is_not_an_enum_here,
derived.getProtocolType());
});
return false;
}
if (dyn_cast<EnumDecl>(derived.Nominal)) {
return validateCodingKeysEnum_enum(
derived, codingKeysTypeDecl, delayedNotes);
} else {
// Look through all var decls in the given type.
// * Filter out lazy/computed vars.
// * Filter out ones which are present in the given decl (by name).
// Here we'll hold on to properties by name -- when we've validated a property
// against its CodingKey entry, it will get removed.
llvm::SmallMapVector<Identifier, VarDecl *, 8> properties;
for (auto *varDecl : derived.Nominal->getStoredProperties()) {
if (!varDecl->isUserAccessible())
continue;
properties[getVarNameForCoding(varDecl)] = varDecl;
}
return validateCodingKeysEnum(
derived, properties, codingKeysTypeDecl, delayedNotes);
}
}
/// Looks up and validates a CaseCodingKeys enum for the given elementDecl.
/// If a CaseCodingKeys enum does not exist, one will be derived.
///
/// \param elementDecl The \c EnumElementDecl to validate against.
static bool validateCaseCodingKeysEnum(const DerivedConformance &derived,
EnumElementDecl *elementDecl,
DelayedNotes &delayedNotes) {
auto &C = derived.Context;
auto *enumDecl = dyn_cast<EnumDecl>(derived.Nominal);
if (!enumDecl) {
return false;
}
auto *codingKeysEnum = lookupEvaluatedCodingKeysEnum(C, enumDecl);
// At this point we ran validation for this and should have
// a CodingKeys decl.
assert(codingKeysEnum && "Missing CodingKeys decl.");
auto cckIdentifier = caseCodingKeysIdentifier(C, elementDecl);
auto caseCodingKeysDecls =
enumDecl->lookupDirect(DeclName(cckIdentifier));
if (caseCodingKeysDecls.size() > 1) {
return false;
}
ValueDecl *result = caseCodingKeysDecls.empty()
? addImplicitCaseCodingKeys(
enumDecl, elementDecl, codingKeysEnum)
: caseCodingKeysDecls.front();
if (!result) {
// There is no coding key defined for this element,
// which is okay, because not all elements have to
// be considered for serialization. Attempts to
// en-/decode them will be handled at runtime.
return true;
}
auto *codingKeysTypeDecl = dyn_cast<TypeDecl>(result);
if (!codingKeysTypeDecl) {
delayedNotes.push_back([=] {
result->diagnose(diag::codable_codingkeys_type_is_not_an_enum_here,
derived.getProtocolType());
});
return false;
}
// Here we'll hold on to parameters by name -- when we've validated a parameter
// against its CodingKey entry, it will get removed.
llvm::SmallMapVector<Identifier, VarDecl *, 8> properties;
if (elementDecl->hasAssociatedValues()) {
for (auto entry : llvm::enumerate(*elementDecl->getParameterList())) {
auto paramDecl = entry.value();
if (!paramDecl->isUserAccessible())
continue;
auto identifier = getVarNameForCoding(paramDecl, entry.index());
properties[identifier] = paramDecl;
}
}
return validateCodingKeysEnum(
derived, properties, codingKeysTypeDecl, delayedNotes);
}
/// Creates a new var decl representing
///
/// var/let identifier : containerBase<keyType>
///
/// \c containerBase is the name of the type to use as the base (either
/// \c KeyedEncodingContainer or \c KeyedDecodingContainer).
///
/// \param C The AST context to create the decl in.
///
/// \param DC The \c DeclContext to create the decl in.
///
/// \param keyedContainerDecl The generic type to bind the key type in.
///
/// \param keyType The key type to bind to the container type.
///
/// \param introducer Whether to declare the variable as immutable.
///
/// \param identifier Identifier of the variable.
static VarDecl *createKeyedContainer(ASTContext &C, DeclContext *DC,
NominalTypeDecl *keyedContainerDecl,
Type keyType,
VarDecl::Introducer introducer,
Identifier identifier) {
// Bind Keyed*Container to Keyed*Container<KeyType>
Type boundType[1] = {keyType};
auto containerType = BoundGenericType::get(keyedContainerDecl, Type(),
C.AllocateCopy(boundType));
// let container : Keyed*Container<KeyType>
auto *containerDecl = new (C) VarDecl(/*IsStatic=*/false, introducer,
SourceLoc(), identifier, DC);
containerDecl->setImplicit();
containerDecl->setSynthesized();
containerDecl->setInterfaceType(containerType);
return containerDecl;
}
/// Creates a new var decl representing
///
/// var/let container : containerBase<keyType>
///
/// \c containerBase is the name of the type to use as the base (either
/// \c KeyedEncodingContainer or \c KeyedDecodingContainer).
///
/// \param C The AST context to create the decl in.
///
/// \param DC The \c DeclContext to create the decl in.
///
/// \param keyedContainerDecl The generic type to bind the key type in.
///
/// \param keyType The key type to bind to the container type.
///
/// \param introducer Whether to declare the variable as immutable.
static VarDecl *createKeyedContainer(ASTContext &C, DeclContext *DC,
NominalTypeDecl *keyedContainerDecl,
Type keyType,
VarDecl::Introducer introducer) {
return createKeyedContainer(C, DC, keyedContainerDecl, keyType,
introducer, C.Id_container);
}
/// Creates a new \c CallExpr representing
///
/// base.container(keyedBy: CodingKeys.self)
///
/// \param C The AST context to create the expression in.
///
/// \param DC The \c DeclContext to create any decls in.
///
/// \param base The base expression to make the call on.
///
/// \param returnType The return type of the call.
///
/// \param param The parameter to the call.
static CallExpr *createContainerKeyedByCall(ASTContext &C, DeclContext *DC,
Expr *base, Type returnType,
NominalTypeDecl *param) {
// (keyedBy:)
auto *keyedByDecl = new (C)
ParamDecl(SourceLoc(), SourceLoc(),
C.Id_keyedBy, SourceLoc(), C.Id_keyedBy, DC);
keyedByDecl->setImplicit();
keyedByDecl->setSpecifier(ParamSpecifier::Default);
keyedByDecl->setInterfaceType(returnType);
// base.container(keyedBy:) expr
auto *paramList = ParameterList::createWithoutLoc(keyedByDecl);
auto *unboundCall = UnresolvedDotExpr::createImplicit(C, base, C.Id_container,
paramList);
// CodingKeys.self expr
auto *codingKeysExpr = TypeExpr::createImplicitForDecl(
DeclNameLoc(), param, param->getDeclContext(),
DC->mapTypeIntoContext(param->getInterfaceType()));
auto *codingKeysMetaTypeExpr = new (C) DotSelfExpr(codingKeysExpr,
SourceLoc(), SourceLoc());
// Full bound base.container(keyedBy: CodingKeys.self) call
auto *argList =
ArgumentList::forImplicitSingle(C, C.Id_keyedBy, codingKeysMetaTypeExpr);
return CallExpr::createImplicit(C, unboundCall, argList);
}
static CallExpr *createNestedContainerKeyedByForKeyCall(
ASTContext &C, DeclContext *DC, Expr *base, NominalTypeDecl *codingKeysType,
EnumElementDecl *key) {
// base.nestedContainer(keyedBy:, forKey:) expr
auto *unboundCall = UnresolvedDotExpr::createImplicit(
C, base, C.Id_nestedContainer, {C.Id_keyedBy, C.Id_forKey});
// CodingKeys.self expr
auto *codingKeysExpr = TypeExpr::createImplicitForDecl(
DeclNameLoc(), codingKeysType, codingKeysType->getDeclContext(),
DC->mapTypeIntoContext(codingKeysType->getInterfaceType()));
auto *codingKeysMetaTypeExpr =
new (C) DotSelfExpr(codingKeysExpr, SourceLoc(), SourceLoc());
// key expr
auto *metaTyRef = TypeExpr::createImplicit(
DC->mapTypeIntoContext(key->getParentEnum()->getDeclaredInterfaceType()),
C);
auto *keyExpr = new (C) MemberRefExpr(metaTyRef, SourceLoc(), key,
DeclNameLoc(), /*Implicit=*/true);
// Full bound base.nestedContainer(keyedBy: CodingKeys.self, forKey: key) call
auto *argList = ArgumentList::forImplicitCallTo(
unboundCall->getName(), {codingKeysMetaTypeExpr, keyExpr}, C);
return CallExpr::createImplicit(C, unboundCall, argList);
}
static ThrowStmt *createThrowCodingErrorStmt(ASTContext &C, Expr *containerExpr,
NominalTypeDecl *errorDecl,
Identifier errorId,
std::optional<Expr *> argument,
StringRef debugMessage) {
auto *contextDecl = lookupErrorContext(C, errorDecl);
assert(contextDecl && "Missing Context decl.");
auto *debugMessageExpr = new (C) StringLiteralExpr(
C.AllocateCopy(debugMessage), SourceRange(),
/* Implicit */ true);
auto *contextTypeExpr =
TypeExpr::createImplicit(contextDecl->getDeclaredType(), C);
// Context.init(codingPath:, debugDescription:)
auto *contextInitCall = UnresolvedDotExpr::createImplicit(
C, contextTypeExpr, DeclBaseName::createConstructor(),
{C.Id_codingPath, C.Id_debugDescription, C.Id_underlyingError});
auto *codingPathExpr =
UnresolvedDotExpr::createImplicit(C, containerExpr, C.Id_codingPath);
auto *underlyingErrorExpr =
new (C) NilLiteralExpr(SourceLoc(), /*implicit*/ true);
auto *initArgList = ArgumentList::forImplicitCallTo(
contextInitCall->getName(),
{codingPathExpr, debugMessageExpr, underlyingErrorExpr}, C);
auto *contextInitCallExpr = CallExpr::createImplicit(C, contextInitCall,
initArgList);
llvm::SmallVector<Expr *, 2> arguments;
if (argument.has_value()) {
arguments.push_back(argument.value());
}
arguments.push_back(contextInitCallExpr);
SmallVector<Identifier, 2> scratch;
auto *decodeArgList = ArgumentList::forImplicitUnlabeled(C, arguments);
auto *decodingErrorTypeExpr =
TypeExpr::createImplicit(errorDecl->getDeclaredType(), C);
auto *decodingErrorCall = UnresolvedDotExpr::createImplicit(
C, decodingErrorTypeExpr, errorId,
decodeArgList->getArgumentLabels(scratch));
auto *decodingErrorCallExpr =
CallExpr::createImplicit(C, decodingErrorCall, decodeArgList);
return new (C) ThrowStmt(SourceLoc(), decodingErrorCallExpr);
}
/// Looks up the property corresponding to the indicated coding key.
///
/// \param conformanceDC The DeclContext we're generating code within.
/// \param elt The CodingKeys enum case.
/// \param targetDecl The type to look up properties in.
///
/// \return A tuple containing the \c VarDecl for the property, the type that
/// should be passed when decoding it, and a boolean which is true if
/// \c encodeIfPresent/\c decodeIfPresent should be used for this property.
static std::tuple<VarDecl *, Type, bool>
lookupVarDeclForCodingKeysCase(DeclContext *conformanceDC,
EnumElementDecl *elt,
NominalTypeDecl *targetDecl) {
for (auto decl : targetDecl->lookupDirect(
DeclName(elt->getBaseIdentifier()))) {
if (auto *vd = dyn_cast<VarDecl>(decl)) {
// If we found a property with an attached wrapper, retrieve the
// backing property.
if (auto backingVar = vd->getPropertyWrapperBackingProperty())
vd = backingVar;
if (!vd->isStatic()) {
// This is the VarDecl we're looking for.
auto varType =
conformanceDC->mapTypeIntoContext(vd->getValueInterfaceType());
bool useIfPresentVariant = false;
if (auto objType = varType->getOptionalObjectType()) {
varType = objType;
useIfPresentVariant = true;
}
return std::make_tuple(vd, varType, useIfPresentVariant);
}
}
}
llvm_unreachable("Should have found at least 1 var decl");
}
static TryExpr *createEncodeCall(ASTContext &C, Type codingKeysType,
EnumElementDecl *codingKey,
Expr *containerExpr, Expr *varExpr,
bool useIfPresentVariant) {
// CodingKeys.x
auto *metaTyRef = TypeExpr::createImplicit(codingKeysType, C);
auto *keyExpr = new (C) MemberRefExpr(metaTyRef, SourceLoc(), codingKey,
DeclNameLoc(), /*Implicit=*/true);
// encode(_:forKey:)/encodeIfPresent(_:forKey:)
auto methodName = useIfPresentVariant ? C.Id_encodeIfPresent : C.Id_encode;
auto *encodeCall = UnresolvedDotExpr::createImplicit(
C, containerExpr, methodName, {Identifier(), C.Id_forKey});
// container.encode(x, forKey: CodingKeys.x)
auto *argList = ArgumentList::forImplicitCallTo(encodeCall->getName(),
{varExpr, keyExpr}, C);
auto *callExpr = CallExpr::createImplicit(C, encodeCall, argList);
// try container.encode(x, forKey: CodingKeys.x)
auto *tryExpr = new (C) TryExpr(SourceLoc(), callExpr, Type(),
/*Implicit=*/true);
return tryExpr;
}
/// Synthesizes the body for `func encode(to encoder: Encoder) throws`.
///
/// \param encodeDecl The function decl whose body to synthesize.
static std::pair<BraceStmt *, bool>
deriveBodyEncodable_encode(AbstractFunctionDecl *encodeDecl, void *) {
// struct Foo : Codable {
// var x: Int
// var y: String
//
// // Already derived by this point if possible.
// @derived enum CodingKeys : CodingKey {
// case x
// case y
// }
//
// @derived func encode(to encoder: Encoder) throws {
// var container = encoder.container(keyedBy: CodingKeys.self)
// try container.encode(x, forKey: .x)
// try container.encode(y, forKey: .y)
// }
// }
// The enclosing type decl.
auto conformanceDC = encodeDecl->getDeclContext();
auto *targetDecl = conformanceDC->getSelfNominalTypeDecl();
auto *funcDC = cast<DeclContext>(encodeDecl);
auto &C = funcDC->getASTContext();
// We'll want the CodingKeys enum for this type, potentially looking through
// a typealias.
auto *codingKeysEnum = lookupEvaluatedCodingKeysEnum(C, targetDecl);
// We should have bailed already if:
// a) The type does not have CodingKeys
// b) The type is not an enum
assert(codingKeysEnum && "Missing CodingKeys decl.");
SmallVector<ASTNode, 5> statements;
// Generate a reference to containerExpr ahead of time in case there are no
// properties to encode or decode, but the type is a class which inherits from
// something Codable and needs to encode super.
// let container : KeyedEncodingContainer<CodingKeys>
auto codingKeysType = codingKeysEnum->getDeclaredType();
auto *containerDecl = createKeyedContainer(C, funcDC,
C.getKeyedEncodingContainerDecl(),
codingKeysEnum->getDeclaredInterfaceType(),
VarDecl::Introducer::Var);
auto *containerExpr = new (C) DeclRefExpr(ConcreteDeclRef(containerDecl),
DeclNameLoc(), /*Implicit=*/true,
AccessSemantics::DirectToStorage);
// Need to generate
// `let container = encoder.container(keyedBy: CodingKeys.self)`
// This is unconditional because a type with no properties should encode as an
// empty container.
//
// `let container` (containerExpr) is generated above.
// encoder
auto encoderParam = encodeDecl->getParameters()->get(0);
auto *encoderExpr = new (C) DeclRefExpr(ConcreteDeclRef(encoderParam),
DeclNameLoc(), /*Implicit=*/true);
// Bound encoder.container(keyedBy: CodingKeys.self) call
auto containerType = containerDecl->getInterfaceType();
auto *callExpr = createContainerKeyedByCall(C, funcDC, encoderExpr,
containerType, codingKeysEnum);
// Full `let container = encoder.container(keyedBy: CodingKeys.self)`
// binding.
auto *containerPattern = NamedPattern::createImplicit(C, containerDecl);
auto *bindingDecl = PatternBindingDecl::createImplicit(
C, StaticSpellingKind::None, containerPattern, callExpr, funcDC);
statements.push_back(bindingDecl);
statements.push_back(containerDecl);
// Now need to generate `try container.encode(x, forKey: .x)` for all
// existing properties. Optional properties get `encodeIfPresent`.
for (auto *elt : codingKeysEnum->getAllElements()) {
VarDecl *varDecl;
Type varType; // not used in Encodable synthesis
bool useIfPresentVariant;
std::tie(varDecl, varType, useIfPresentVariant) =
lookupVarDeclForCodingKeysCase(conformanceDC, elt, targetDecl);
// self.x
auto *selfRef = DerivedConformance::createSelfDeclRef(encodeDecl);
auto *varExpr = new (C) MemberRefExpr(selfRef, SourceLoc(),
ConcreteDeclRef(varDecl),
DeclNameLoc(), /*Implicit=*/true);
auto *encodeCallExpr = createEncodeCall(
C, codingKeysType, elt, containerExpr, varExpr, useIfPresentVariant);
statements.push_back(encodeCallExpr);
}
// Classes which inherit from something Codable should encode super as well.
if (superclassConformsTo(dyn_cast<ClassDecl>(targetDecl),
KnownProtocolKind::Encodable)) {
// Need to generate `try super.encode(to: container.superEncoder())`
// superEncoder()
auto *method = UnresolvedDeclRefExpr::createImplicit(C, C.Id_superEncoder);
// container.superEncoder()
auto *superEncoderRef = DotSyntaxCallExpr::create(
C, method, SourceLoc(), Argument::unlabeled(containerExpr));
// encode(to:) expr
auto *encodeDeclRef = new (C) DeclRefExpr(ConcreteDeclRef(encodeDecl),
DeclNameLoc(), /*Implicit=*/true);
// super
auto *superRef = new (C) SuperRefExpr(encodeDecl->getImplicitSelfDecl(),
SourceLoc(), /*Implicit=*/true);
// super.encode(to:)
auto *encodeCall = DotSyntaxCallExpr::create(C, encodeDeclRef, SourceLoc(),
Argument::unlabeled(superRef));
// super.encode(to: container.superEncoder())
auto *args = ArgumentList::forImplicitSingle(C, C.Id_to, superEncoderRef);
auto *callExpr = CallExpr::createImplicit(C, encodeCall, args);
// try super.encode(to: container.superEncoder())
auto *tryExpr = new (C) TryExpr(SourceLoc(), callExpr, Type(),
/*Implicit=*/true);
statements.push_back(tryExpr);
}
auto *body = BraceStmt::create(C, SourceLoc(), statements, SourceLoc(),
/*implicit=*/true);
return { body, /*isTypeChecked=*/false };
}
static SwitchStmt *
createEnumSwitch(ASTContext &C, DeclContext *DC, Expr *expr, EnumDecl *enumDecl,
EnumDecl *codingKeysEnum, bool createSubpattern,
std::function<std::tuple<EnumElementDecl *, BraceStmt *>(
EnumElementDecl *, EnumElementDecl *, ArrayRef<VarDecl *>)>
createCase) {
SmallVector<CaseStmt *, 4> cases;
for (auto elt : enumDecl->getAllElements()) {
// .<elt>(let a0, let a1, ...)
SmallVector<VarDecl *, 3> payloadVars;
Pattern *subpattern = nullptr;
std::optional<MutableArrayRef<VarDecl *>> caseBodyVarDecls;
if (createSubpattern) {
subpattern = DerivedConformance::enumElementPayloadSubpattern(
elt, 'a', DC, payloadVars, /* useLabels */ true);
auto hasBoundDecls = !payloadVars.empty();
if (hasBoundDecls) {
// We allocated a direct copy of our var decls for the case
// body.
auto copy = C.Allocate<VarDecl *>(payloadVars.size());
for (unsigned i : indices(payloadVars)) {
auto *vOld = payloadVars[i];
auto *vNew = new (C) VarDecl(
/*IsStatic*/ false, vOld->getIntroducer(), vOld->getNameLoc(),
vOld->getName(), vOld->getDeclContext());
vNew->setImplicit();
copy[i] = vNew;
}
caseBodyVarDecls.emplace(copy);
}
}
// CodingKeys.x
auto *codingKeyCase =
lookupEnumCase(C, codingKeysEnum, elt->getName().getBaseIdentifier());
EnumElementDecl *targetElt;
BraceStmt *caseBody;
std::tie(targetElt, caseBody) = createCase(elt, codingKeyCase, payloadVars);
if (caseBody) {
// generate: case .<Case>:
auto parentTy = DC->mapTypeIntoContext(
targetElt->getParentEnum()->getDeclaredInterfaceType());
auto *pat = EnumElementPattern::createImplicit(parentTy, targetElt,
subpattern, DC);
auto labelItem = CaseLabelItem(pat);
auto stmt =
CaseStmt::create(C, CaseParentKind::Switch, SourceLoc(), labelItem,
SourceLoc(), SourceLoc(), caseBody,
/*case body vardecls*/
createSubpattern ? caseBodyVarDecls : std::nullopt);
cases.push_back(stmt);
}
}
// generate: switch $expr { }
return SwitchStmt::createImplicit(LabeledStmtInfo(), expr, cases, C);
}
static DeclRefExpr *createContainer(ASTContext &C, DeclContext *DC,
VarDecl::Introducer introducer,
NominalTypeDecl *containerTypeDecl,
VarDecl *target, EnumDecl *codingKeysEnum,
llvm::SmallVectorImpl<ASTNode> &statements,
bool throws) {
// let/var container : KeyedDecodingContainer<CodingKeys>
auto *containerDecl = createKeyedContainer(
C, DC, containerTypeDecl, codingKeysEnum->getDeclaredInterfaceType(),
introducer);