-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathswift_api_digester_main.cpp
2682 lines (2455 loc) · 95.7 KB
/
swift_api_digester_main.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
//===--- swift-api-digester.cpp - API change detector ---------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// swift-api-digester is a test utility to detect source-breaking API changes
// during the evolution of a Swift library. The tool works on two phases:
// (1) dumping library contents as a JSON file, and (2) comparing two JSON
// files textually to report interesting changes.
//
// During phase (1), the api-digester looks up every declarations inside
// a module and outputs a singly-rooted tree that encloses interesting
// details of the API level.
//
// During phase (2), api-digester applies structure-information comparison
// algorithms on two given singly root trees, trying to figure out, as
// precise as possible, the branches/leaves in the trees that differ from
// each other. Further analysis decides whether the changed leaves/branches
// can be reflected as source-breaking changes for API users. If they are,
// the output of api-digester will include such changes.
#include "swift/APIDigester/ModuleAnalyzerNodes.h"
#include "swift/APIDigester/ModuleDiagsConsumer.h"
#include "swift/AST/DiagnosticsModuleDiffer.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Platform.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/Frontend/SerializedDiagnosticConsumer.h"
#include "swift/IDE/APIDigesterData.h"
#include "swift/Option/Options.h"
#include "swift/Parse/ParseVersion.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/Support/VirtualOutputBackends.h"
#include "llvm/Support/raw_ostream.h"
#include <functional>
using namespace swift;
using namespace ide;
using namespace api;
using namespace swift::options;
namespace {
enum class ActionType {
None,
DumpSDK,
MigratorGen,
DiagnoseSDKs,
// The following two are for testing purposes
DeserializeDiffItems,
DeserializeSDK,
GenerateNameCorrectionTemplate,
FindUsr,
GenerateEmptyBaseline,
};
} // end anonymous namespace
namespace {
using swift::ide::api::KnownProtocolKind;
// A node matcher will traverse two trees of SDKNode and find matched nodes
struct NodeMatcher {
virtual void match() = 0;
virtual ~NodeMatcher() = default;
};
// During the matching phase, any matched node will be reported using this API.
// For update Node left = {Node before change} Right = {Node after change};
// For added Node left = {NilNode} Right = {Node after change};
// For removed Node left = {Node before change} Right = {NilNode}
struct MatchedNodeListener {
virtual void foundMatch(NodePtr Left, NodePtr Right, NodeMatchReason Reason) = 0;
virtual ~MatchedNodeListener() = default;
};
static
void singleMatch(SDKNode* Left, SDKNode *Right, MatchedNodeListener &Listener) {
// Both null, be forgiving.
if (!Left && !Right)
return;
// If both are valid and identical to each other, we don't need to match them.
if (Left && Right && *Left == *Right)
return;
if (!Left || !Right)
Listener.foundMatch(Left, Right,
Left ? NodeMatchReason::Removed : NodeMatchReason::Added);
else
Listener.foundMatch(Left, Right, NodeMatchReason::Sequential);
}
// Given two NodeVector, this matches SDKNode by the order of their appearance
// in the respective NodeVector. We use this in the order-sensitive cases, such
// as parameters in a function decl.
class SequentialNodeMatcher : public NodeMatcher {
ArrayRef<SDKNode*> Left;
ArrayRef<SDKNode*> Right;
MatchedNodeListener &Listener;
public:
SequentialNodeMatcher(ArrayRef<SDKNode*> Left,
ArrayRef<SDKNode*> Right,
MatchedNodeListener &Listener) :
Left(Left), Right(Right), Listener(Listener) {}
void match() override {
for (unsigned long i = 0; i < std::max(Left.size(), Right.size()); i ++) {
auto L = i < Left.size() ? Left[i] : nullptr;
auto R = i < Right.size() ? Right[i] : nullptr;
singleMatch(L, R, Listener);
}
}
};
struct NodeMatch {
NodePtr Left;
NodePtr Right;
};
class BestMatchMatcher : public NodeMatcher {
NodeVector &Left;
NodeVector &Right;
llvm::function_ref<bool(NodePtr, NodePtr)> CanMatch;
llvm::function_ref<bool(NodeMatch, NodeMatch)> IsFirstMatchBetter;
NodeMatchReason Reason;
MatchedNodeListener &Listener;
llvm::SmallPtrSet<NodePtr, 16> MatchedRight;
bool internalCanMatch(NodePtr L, NodePtr R) {
return MatchedRight.count(R) == 0 && CanMatch(L, R);
}
std::optional<NodePtr> findBestMatch(NodePtr Pin, NodeVector &Candidates) {
std::optional<NodePtr> Best;
for (auto Can : Candidates) {
if (!internalCanMatch(Pin, Can))
continue;
if (!Best.has_value() ||
IsFirstMatchBetter({Pin, Can}, {Pin, Best.value()}))
Best = Can;
}
return Best;
}
public:
BestMatchMatcher(NodeVector &Left, NodeVector &Right,
llvm::function_ref<bool(NodePtr, NodePtr)> CanMatch,
llvm::function_ref<bool(NodeMatch, NodeMatch)> IsFirstMatchBetter,
NodeMatchReason Reason,
MatchedNodeListener &Listener) : Left(Left), Right(Right),
CanMatch(CanMatch),
IsFirstMatchBetter(IsFirstMatchBetter), Reason(Reason),
Listener(Listener){}
void match() override {
for (auto L : Left) {
if (auto Best = findBestMatch(L, Right)) {
MatchedRight.insert(Best.value());
Listener.foundMatch(L, Best.value(), Reason);
}
}
}
};
class RemovedAddedNodeMatcher : public NodeMatcher, public MatchedNodeListener {
NodeVector &Removed;
NodeVector &Added;
MatchedNodeListener &Listener;
NodeVector RemovedMatched;
NodeVector AddedMatched;
void handleUnmatch(NodeVector &Matched, NodeVector &All, bool Left) {
for (auto A : All) {
if (llvm::is_contained(Matched, A))
continue;
if (Left)
Listener.foundMatch(A, nullptr, NodeMatchReason::Removed);
else
Listener.foundMatch(nullptr, A, NodeMatchReason::Added);
}
}
bool detectFuncToProperty(SDKNode *R, SDKNode *A) {
if (R->getKind() == SDKNodeKind::DeclFunction) {
if (A->getKind() == SDKNodeKind::DeclVar) {
if (A->getName().compare_insensitive(R->getName()) == 0) {
R->annotate(NodeAnnotation::GetterToProperty);
} else if (R->getName().starts_with("get") &&
R->getName().substr(3).compare_insensitive(A->getName()) ==
0) {
R->annotate(NodeAnnotation::GetterToProperty);
} else if (R->getName().starts_with("set") &&
R->getName().substr(3).compare_insensitive(A->getName()) ==
0) {
R->annotate(NodeAnnotation::SetterToProperty);
} else {
return false;
}
R->annotate(NodeAnnotation::PropertyName, A->getPrintedName());
foundMatch(R, A, NodeMatchReason::FuncToProperty);
return true;
}
}
return false;
}
static bool isAnonymousEnum(SDKNodeDecl *N) {
return N->getKind() == SDKNodeKind::DeclVar &&
N->getUsr().starts_with("c:@Ea@");
}
static bool isNominalEnum(SDKNodeDecl *N) {
return N->getKind() == SDKNodeKind::DeclType &&
N->getUsr().starts_with("c:@E@");
}
static std::optional<StringRef> getLastPartOfUsr(SDKNodeDecl *N) {
auto LastPartIndex = N->getUsr().find_last_of('@');
if (LastPartIndex == StringRef::npos)
return std::nullopt;
return N->getUsr().substr(LastPartIndex + 1);
}
bool detectTypeAliasChange(SDKNodeDecl *R, SDKNodeDecl *A) {
if (R->getPrintedName() != A->getPrintedName())
return false;
if (R->getKind() == SDKNodeKind::DeclType &&
A->getKind() == SDKNodeKind::DeclTypeAlias) {
foundMatch(R, A, NodeMatchReason::TypeToTypeAlias);
return true;
} else {
return false;
}
}
bool detectModernizeEnum(SDKNodeDecl *R, SDKNodeDecl *A) {
if (!isAnonymousEnum(R) || !isNominalEnum(A))
return false;
auto LastPartOfR = getLastPartOfUsr(R);
if (!LastPartOfR)
return false;
for (auto Child : A->getChildren()) {
if (auto VC = dyn_cast<SDKNodeDeclVar>(Child)) {
auto LastPartOfA = getLastPartOfUsr(VC);
if (LastPartOfA && LastPartOfR.value() == LastPartOfA.value()) {
std::string FullName = (llvm::Twine(A->getName()) + "." +
Child->getName()).str();
R->annotate(NodeAnnotation::ModernizeEnum,
R->getSDKContext().buffer(FullName));
foundMatch(R, A, NodeMatchReason::ModernizeEnum);
return true;
}
}
}
return false;
}
bool detectSameAnonymousEnum(SDKNodeDecl *R, SDKNodeDecl *A) {
if (!isAnonymousEnum(R) || !isAnonymousEnum(A))
return false;
auto LastR = getLastPartOfUsr(R);
auto LastA = getLastPartOfUsr(A);
if (LastR && LastA && LastR.value() == LastA.value()) {
foundMatch(R, A, NodeMatchReason::Name);
return true;
}
return false;
}
static bool isNameTooSimple(StringRef N) {
static std::vector<std::string> SimpleNames = {"unit", "data", "log", "coding",
"url", "name", "date", "datecomponents", "notification", "urlrequest",
"personnamecomponents", "measurement", "dateinterval", "indexset"};
return std::find(SimpleNames.begin(), SimpleNames.end(), N) !=
SimpleNames.end();
}
static bool isSimilarName(StringRef L, StringRef R) {
auto LL = L.lower();
auto RR = R.lower();
if (isNameTooSimple(LL) || isNameTooSimple(RR))
return false;
if (((StringRef)LL).starts_with(RR) || ((StringRef)RR).starts_with(LL))
return true;
if (((StringRef)LL).starts_with((llvm::Twine("ns") + RR).str()) ||
((StringRef)RR).starts_with((llvm::Twine("ns") + LL).str()))
return true;
if (((StringRef)LL).ends_with(RR) || ((StringRef)RR).ends_with(LL))
return true;
return false;
}
/// Whether two decls of different decl kinds can be considered as rename.
static bool isDeclKindCrossable(DeclKind DK1, DeclKind DK2, bool First) {
if (DK1 == DK2)
return true;
if (DK1 == DeclKind::Var && DK2 == DeclKind::EnumElement)
return true;
return First && isDeclKindCrossable(DK2, DK1, false);
}
static bool isRename(NodePtr L, NodePtr R) {
if (L->getKind() != R->getKind())
return false;
if (isa<SDKNodeDeclConstructor>(L))
return false;
if (auto LD = dyn_cast<SDKNodeDecl>(L)) {
auto *RD = R->getAs<SDKNodeDecl>();
return isDeclKindCrossable(LD->getDeclKind(), RD->getDeclKind(), true) &&
isSimilarName(LD->getName(), RD->getName());
}
return false;
}
static bool isBetterMatch(NodeMatch Match1, NodeMatch Match2) {
assert(Match1.Left == Match2.Left);
auto Left = Match1.Left;
auto *M1Right = Match1.Right->getAs<SDKNodeDecl>();
auto *M2Right = Match2.Right->getAs<SDKNodeDecl>();
// Consider non-deprecated nodes better matches.
auto Dep1 = M1Right->isDeprecated();
auto Dep2 = M2Right->isDeprecated();
if (Dep1 ^ Dep2) {
return Dep2;
}
// If two names are identical, measure whose printed names is closer.
if (M1Right->getName() == M2Right->getName()) {
return
M1Right->getPrintedName().edit_distance(Left->getPrintedName()) <
M2Right->getPrintedName().edit_distance(Left->getPrintedName());
}
#define DIST(A, B) (std::max(A, B) - std::min(A, B))
return
DIST(Left->getName().size(), Match1.Right->getName().size()) <
DIST(Left->getName().size(), Match2.Right->getName().size());
#undef DIST
}
void foundMatch(NodePtr R, NodePtr A, NodeMatchReason Reason) override {
Listener.foundMatch(R, A, Reason);
RemovedMatched.push_back(R);
AddedMatched.push_back(A);
}
public:
RemovedAddedNodeMatcher(NodeVector &Removed, NodeVector &Added,
MatchedNodeListener &Listener) : Removed(Removed),
Added(Added), Listener(Listener) {}
void match() override {
auto IsDecl = [](NodePtr P) { return isa<SDKNodeDecl>(P); };
for (auto R : SDKNodeVectorViewer(Removed, IsDecl)) {
for (auto A : SDKNodeVectorViewer(Added, IsDecl)) {
auto RD = R->getAs<SDKNodeDecl>();
auto AD = A->getAs<SDKNodeDecl>();
if (detectFuncToProperty(RD, AD) || detectModernizeEnum(RD, AD) ||
detectSameAnonymousEnum(RD, AD) || detectTypeAliasChange(RD, AD)) {
break;
}
}
}
// Rename detection starts.
NodeVector RenameLeft;
NodeVector RenameRight;
for (auto Remain : Removed) {
if (!llvm::is_contained(RemovedMatched, Remain))
RenameLeft.push_back(Remain);
}
for (auto Remain : Added) {
if (!llvm::is_contained(AddedMatched, Remain))
RenameRight.push_back(Remain);
}
BestMatchMatcher RenameMatcher(RenameLeft, RenameRight, isRename,
isBetterMatch, NodeMatchReason::Name, *this);
RenameMatcher.match();
// Rename detection ends.
handleUnmatch(RemovedMatched, Removed, true);
handleUnmatch(AddedMatched, Added, false);
}
};
// Given two NodeVector, this matches SDKNode by the their names; only Nodes with
// the identical names will be matched. We use this in name-sensitive but
// order-insensitive cases, such as matching types in a module.
class SameNameNodeMatcher : public NodeMatcher {
ArrayRef<SDKNode*> Left;
ArrayRef<SDKNode*> Right;
MatchedNodeListener &Listener;
enum class NameMatchKind {
USR,
PrintedName,
PrintedNameAndUSR,
};
static bool isUSRSame(SDKNode *L, SDKNode *R) {
auto *LD = dyn_cast<SDKNodeDecl>(L);
auto *RD = dyn_cast<SDKNodeDecl>(R);
if (!LD || !RD)
return false;
return LD->getUsr() == RD->getUsr();
}
// Given two SDK nodes, figure out the reason for why they have the same name.
std::optional<NameMatchKind> getNameMatchKind(SDKNode *L, SDKNode *R) {
if (L->getKind() != R->getKind())
return std::nullopt;
auto NameEqual = L->getPrintedName() == R->getPrintedName();
auto UsrEqual = isUSRSame(L, R);
if (NameEqual && UsrEqual)
return NameMatchKind::PrintedNameAndUSR;
else if (NameEqual)
return NameMatchKind::PrintedName;
else if (UsrEqual)
return NameMatchKind::USR;
else
return std::nullopt;
}
struct NameMatchCandidate {
SDKNode *Node;
NameMatchKind Kind;
};
// Get the priority for the favored name match kind. Favored name match kind
// locals before less favored ones.
ArrayRef<NameMatchKind> getNameMatchKindPriority(SDKNodeKind Kind) {
if (Kind == SDKNodeKind::DeclFunction) {
static NameMatchKind FuncPriority[] = { NameMatchKind::PrintedNameAndUSR,
NameMatchKind::USR,
NameMatchKind::PrintedName };
return FuncPriority;
} else {
static NameMatchKind OtherPriority[] = { NameMatchKind::PrintedNameAndUSR,
NameMatchKind::PrintedName,
NameMatchKind::USR };
return OtherPriority;
}
}
// Given a list and a priority, find the best matched candidate SDK node.
SDKNode* findBestNameMatch(ArrayRef<NameMatchCandidate> Candidates,
ArrayRef<NameMatchKind> Kinds) {
for (auto Kind : Kinds)
for (auto &Can : Candidates)
if (Kind == Can.Kind)
return Can.Node;
return nullptr;
}
public:
SameNameNodeMatcher(ArrayRef<SDKNode*> Left, ArrayRef<SDKNode*> Right,
MatchedNodeListener &Listener) : Left(Left), Right(Right),
Listener(Listener) {}
void match() override ;
};
void SameNameNodeMatcher::match() {
NodeVector MatchedRight;
NodeVector Removed;
NodeVector Added;
for (auto *LN : Left) {
// This collects all the candidates that can match with LN.
std::vector<NameMatchCandidate> Candidates;
for (auto *RN : Right) {
// If RN has matched before, ignore it.
if (llvm::is_contained(MatchedRight, RN))
continue;
// If LN and RN have the same name for some reason, keep track of RN.
if (auto Kind = getNameMatchKind(LN, RN))
Candidates.push_back({RN, Kind.value()});
}
// Try to find the best match among all the candidates by the priority name
// match kind list.
if (auto Match = findBestNameMatch(Candidates,
getNameMatchKindPriority(LN->getKind()))) {
Listener.foundMatch(LN, Match, NodeMatchReason::Name);
MatchedRight.push_back(Match);
} else {
Removed.push_back(LN);
}
}
for (auto &R : Right) {
if (!llvm::is_contained(MatchedRight, R)) {
Added.push_back(R);
}
}
RemovedAddedNodeMatcher RAMatcher(Removed, Added, Listener);
RAMatcher.match();
}
// The recursive version of sequential matcher. We do not only match two vectors
// of NodePtr but also their descendents.
class SequentialRecursiveMatcher : public NodeMatcher {
NodePtr &Left;
NodePtr &Right;
MatchedNodeListener &Listener;
void matchInternal(NodePtr L, NodePtr R) {
Listener.foundMatch(L, R, NodeMatchReason::Sequential);
if (!L || !R)
return;
for (unsigned I = 0; I < std::max(L->getChildrenCount(),
R->getChildrenCount()); ++ I) {
auto Left = I < L->getChildrenCount() ? L->childAt(I) : nullptr;
auto Right = I < R->getChildrenCount() ? R->childAt(I): nullptr;
matchInternal(Left, Right);
}
}
public:
SequentialRecursiveMatcher(NodePtr &Left, NodePtr &Right,
MatchedNodeListener &Listener) : Left(Left),
Right(Right), Listener(Listener) {}
void match() override {
matchInternal(Left, Right);
}
};
// This is the interface of all passes on the given trees rooted at Left and Right.
class SDKTreeDiffPass {
public:
virtual void pass(NodePtr Left, NodePtr Right) = 0;
virtual ~SDKTreeDiffPass() {}
};
}// End of anonymous namespace
namespace {
static bool isMissingDeclAcceptable(const SDKNodeDecl *D) {
// Don't complain about removing importation of SwiftOnoneSupport.
if (D->getKind() == SDKNodeKind::DeclImport) {
return true;
}
return false;
}
static void diagnoseRemovedDecl(const SDKNodeDecl *D) {
if (D->getSDKContext().checkingABI()) {
// Don't complain about removing @_alwaysEmitIntoClient if we are checking ABI.
// We shouldn't include these decls in the ABI baseline file. This line is
// added so the checker is backward compatible.
if (D->hasDeclAttribute(DeclAttrKind::AlwaysEmitIntoClient))
return;
}
auto &Ctx = D->getSDKContext();
// Don't diagnose removal of deprecated APIs.
if (Ctx.getOpts().SkipRemoveDeprecatedCheck &&
D->isDeprecated())
return;
if (isMissingDeclAcceptable(D)) {
return;
}
D->emitDiag(SourceLoc(), diag::removed_decl, false);
}
// This is first pass on two given SDKNode trees. This pass removes the common part
// of two versions of SDK, leaving only the changed part.
class PrunePass : public MatchedNodeListener, public SDKTreeDiffPass {
static void removeCommon(NodeVector &Left, NodeVector &Right) {
NodeVector LeftMinusRight, RightMinusLeft;
nodeSetDifference(Left, Right, LeftMinusRight, RightMinusLeft);
Left = LeftMinusRight;
Right = RightMinusLeft;
}
static void removeCommonChildren(NodePtr Left, NodePtr Right) {
removeCommon(Left->getChildren(), Right->getChildren());
}
SDKContext &Ctx;
UpdatedNodesMap &UpdateMap;
llvm::StringSet<> ProtocolReqAllowlist;
SDKNodeRoot *LeftRoot;
SDKNodeRoot *RightRoot;
bool DebugMapping;
static void printSpaces(llvm::raw_ostream &OS, SDKNode *N) {
assert(N);
StringRef Space = " ";
// Accessor doesn't have parent.
if (auto *AC = dyn_cast<SDKNodeDeclAccessor>(N)) {
OS << Space;
printSpaces(OS, AC->getStorage());
return;
}
for (auto P = N; !isa<SDKNodeRoot>(P); P = P->getParent())
OS << Space;
}
static void debugMatch(SDKNode *Left, SDKNode *Right, NodeMatchReason Reason,
llvm::raw_ostream &OS) {
if (Left && !isa<SDKNodeDecl>(Left))
return;
if (Right && !isa<SDKNodeDecl>(Right))
return;
StringRef Arrow = " <--------> ";
switch (Reason) {
case NodeMatchReason::Added:
printSpaces(OS, Right);
OS << "<NULL>" << Arrow << Right->getPrintedName() << "\n";
return;
case NodeMatchReason::Removed:
printSpaces(OS, Left);
OS << Left->getPrintedName() << Arrow << "<NULL>\n";
return;
default:
printSpaces(OS, Left);
OS << Left->getPrintedName() << Arrow << Right->getPrintedName() << "\n";
return;
}
}
static StringRef getParentProtocolName(SDKNode *Node) {
if (auto *Acc = dyn_cast<SDKNodeDeclAccessor>(Node)) {
Node = Acc->getStorage();
}
return Node->getParent()->getAs<SDKNodeDecl>()->getFullyQualifiedName();
}
public:
PrunePass(SDKContext &Ctx, bool DebugMapping)
: Ctx(Ctx), UpdateMap(Ctx.getNodeUpdateMap()),
DebugMapping(DebugMapping) {}
PrunePass(SDKContext &Ctx, llvm::StringSet<> prAllowlist, bool DebugMapping)
: Ctx(Ctx), UpdateMap(Ctx.getNodeUpdateMap()),
ProtocolReqAllowlist(std::move(prAllowlist)),
DebugMapping(DebugMapping) {}
void diagnoseMissingAvailable(SDKNodeDecl *D) {
// For extensions of external types, we diagnose individual member's missing
// available attribute instead of the extension itself.
// The reason is we may merge several extensions into a single one; some
// attributes are missing.
if (auto *DT = dyn_cast<SDKNodeDeclType>(D)) {
if (DT->isExtension()) {
for(auto MD: DT->getChildren()) {
diagnoseMissingAvailable(cast<SDKNodeDecl>(MD));
}
return;
}
}
// Diagnose the missing of @available attributes.
// Decls with @_alwaysEmitIntoClient aren't required to have an
// @available attribute.
if (!Ctx.getOpts().SkipOSCheck &&
DeclAttribute::canAttributeAppearOnDeclKind(DeclAttrKind::Available,
D->getDeclKind()) &&
!D->getIntroducingVersion().hasOSAvailability() &&
!D->hasDeclAttribute(DeclAttrKind::AlwaysEmitIntoClient) &&
!D->hasDeclAttribute(DeclAttrKind::Marker)) {
D->emitDiag(D->getLoc(), diag::new_decl_without_intro);
}
}
void foundMatch(NodePtr Left, NodePtr Right, NodeMatchReason Reason) override {
if (DebugMapping)
debugMatch(Left, Right, Reason, llvm::errs());
switch (Reason) {
case NodeMatchReason::Added:
assert(!Left);
Right->annotate(NodeAnnotation::Added);
if (Ctx.checkingABI()) {
// Any order-important decl added to a non-resilient type breaks ABI.
if (auto *D = dyn_cast<SDKNodeDecl>(Right)) {
if (D->hasFixedBinaryOrder()) {
D->emitDiag(D->getLoc(), diag::decl_added);
}
diagnoseMissingAvailable(D);
}
}
// Complain about added protocol requirements
if (auto *D = dyn_cast<SDKNodeDecl>(Right)) {
if (D->isNonOptionalProtocolRequirement()) {
bool ShouldComplain = !D->isOverriding();
// We should allow added associated types with default.
if (auto ATD = dyn_cast<SDKNodeDeclAssociatedType>(D)) {
if (ATD->getDefault())
ShouldComplain = false;
}
if (ShouldComplain &&
ProtocolReqAllowlist.count(getParentProtocolName(D))) {
// Ignore protocol requirement additions if the protocol has been added
// to the allowlist.
ShouldComplain = false;
}
if (ShouldComplain) {
// Providing a default implementation via a protocol extension for
// a protocol requirement is both ABI and API safe.
if (auto *PD = dyn_cast<SDKNodeDecl>(D->getParent())) {
for (auto *SIB: PD->getChildren()) {
if (auto *SIBD = dyn_cast<SDKNodeDecl>(SIB)) {
if (SIBD->isFromExtension() &&
SIBD->getPrintedName() == D->getPrintedName()) {
ShouldComplain = false;
break;
}
}
}
}
}
if (ShouldComplain)
D->emitDiag(D->getLoc(), diag::protocol_req_added);
}
}
// Diagnose an inherited protocol has been added.
if (auto *Conf = dyn_cast<SDKNodeConformance>(Right)) {
auto *TD = Conf->getNominalTypeDecl();
if (TD->isProtocol()) {
TD->emitDiag(TD->getLoc(), diag::conformance_added, Conf->getName());
} else {
// Adding conformance to an existing type can be ABI breaking.
if (Ctx.checkingABI() &&
!LeftRoot->getDescendantsByUsr(Conf->getUsr()).empty()) {
TD->emitDiag(TD->getLoc(), diag::existing_conformance_added,
Conf->getName());
}
}
}
if (auto *CD = dyn_cast<SDKNodeDeclConstructor>(Right)) {
if (auto *TD = dyn_cast<SDKNodeDeclType>(Right->getParent())) {
if (TD->isOpen() && CD->getInitKind() == CtorInitializerKind::Designated) {
// If client's subclass provides an implementation of all of its superclass designated
// initializers, it automatically inherits all of the superclass convenience initializers.
// This means if a new designated init is added to the base class, the inherited
// convenience init may be missing and cause breakage.
CD->emitDiag(CD->getLoc(), diag::desig_init_added);
}
}
}
// Adding an enum case is source-breaking.
if (!Ctx.checkingABI()) {
if (auto *Var = dyn_cast<SDKNodeDeclVar>(Right)) {
if (Var->getDeclKind() == DeclKind::EnumElement) {
if (Var->getParent()->getAs<SDKNodeDeclType>()->isEnumExhaustive()) {
Var->emitDiag(Var->getLoc(), diag::enum_case_added);
}
}
}
}
return;
case NodeMatchReason::Removed:
assert(!Right);
Left->annotate(NodeAnnotation::Removed);
if (auto *LT = dyn_cast<SDKNodeType>(Left)) {
if (auto *AT = dyn_cast<SDKNodeDeclAssociatedType>(LT->getParent())) {
AT->emitDiag(SourceLoc(), diag::default_associated_type_removed,
LT->getPrintedName());
}
}
// Diagnose a protocol conformance has been removed.
if (auto *Conf = dyn_cast<SDKNodeConformance>(Left)) {
auto *TD = Conf->getNominalTypeDecl();
TD->emitDiag(SourceLoc(),
diag::conformance_removed,
Conf->getName(),
TD->isProtocol());
}
if (auto *Acc = dyn_cast<SDKNodeDeclAccessor>(Left)) {
diagnoseRemovedDecl(Acc);
}
return;
case NodeMatchReason::FuncToProperty:
case NodeMatchReason::ModernizeEnum:
case NodeMatchReason::TypeToTypeAlias:
Left->annotate(NodeAnnotation::Removed);
Right->annotate(NodeAnnotation::Added);
return;
case NodeMatchReason::Root:
case NodeMatchReason::Name:
case NodeMatchReason::Sequential:
break;
}
assert(Left && Right);
Left->annotate(NodeAnnotation::Updated);
Right->annotate(NodeAnnotation::Updated);
// Push the updated node to the map for future reference.
UpdateMap.insert(Left, Right);
Left->diagnose(Right);
if (Left->getKind() != Right->getKind()) {
assert(isa<SDKNodeType>(Left) && isa<SDKNodeType>(Right) &&
"only type nodes can match across kinds.");
return;
}
assert(Left->getKind() == Right->getKind());
SDKNodeKind Kind = Left->getKind();
assert(Kind == SDKNodeKind::Root || *Left != *Right);
switch(Kind) {
case SDKNodeKind::DeclType: {
// Remove common conformances and diagnose conformance changes.
auto LConf = cast<SDKNodeDeclType>(Left)->getConformances();
auto RConf = cast<SDKNodeDeclType>(Right)->getConformances();
removeCommon(LConf, RConf);
SameNameNodeMatcher(LConf, RConf, *this).match();
LLVM_FALLTHROUGH;
}
case SDKNodeKind::Conformance:
case SDKNodeKind::Root: {
// If the matched nodes are both modules, remove the contained
// type decls that are identical. If the matched nodes are both type decls,
// remove the contained function decls that are identical.
removeCommonChildren(Left, Right);
SameNameNodeMatcher SNMatcher(Left->getChildren(), Right->getChildren(), *this);
SNMatcher.match();
break;
}
case SDKNodeKind::TypeWitness:
case SDKNodeKind::DeclOperator:
case SDKNodeKind::DeclAssociatedType:
case SDKNodeKind::DeclFunction:
case SDKNodeKind::DeclAccessor:
case SDKNodeKind::DeclConstructor:
case SDKNodeKind::DeclTypeAlias:
case SDKNodeKind::DeclImport:
case SDKNodeKind::TypeFunc:
case SDKNodeKind::TypeNominal:
case SDKNodeKind::TypeAlias:
case SDKNodeKind::DeclMacro: {
// If matched nodes are both function/var/TypeAlias decls, mapping their
// parameters sequentially.
SequentialNodeMatcher SNMatcher(Left->getChildren(), Right->getChildren(),
*this);
SNMatcher.match();
break;
}
case SDKNodeKind::DeclSubscript: {
auto *LSub = dyn_cast<SDKNodeDeclSubscript>(Left);
auto *RSub = dyn_cast<SDKNodeDeclSubscript>(Right);
SequentialNodeMatcher(LSub->getChildren(), RSub->getChildren(), *this).match();
#define ACCESSOR(ID) \
singleMatch(LSub->getAccessor(AccessorKind::ID), \
RSub->getAccessor(AccessorKind::ID), *this);
#include "swift/AST/AccessorKinds.def"
break;
}
case SDKNodeKind::DeclVar: {
auto *LVar = dyn_cast<SDKNodeDeclVar>(Left);
auto *RVar = dyn_cast<SDKNodeDeclVar>(Right);
// Match property type.
singleMatch(LVar->getType(), RVar->getType(), *this);
#define ACCESSOR(ID) \
singleMatch(LVar->getAccessor(AccessorKind::ID), \
RVar->getAccessor(AccessorKind::ID), *this);
#include "swift/AST/AccessorKinds.def"
break;
}
}
}
void pass(NodePtr Left, NodePtr Right) override {
LeftRoot = Left->getAs<SDKNodeRoot>();
RightRoot = Right->getAs<SDKNodeRoot>();
foundMatch(Left, Right, NodeMatchReason::Root);
}
};
// Class to build up a diff of structurally different nodes, based on the given
// USR map for the left (original) side of the diff, based on parent types.
class TypeMemberDiffFinder : public SDKNodeVisitor {
friend class SDKNode; // for visit()
SDKNodeRoot *diffAgainst;
// Vector of {givenNodePtr, diffAgainstPtr}
NodePairVector TypeMemberDiffs;
void visit(NodePtr node) override {
// Skip nodes that we don't have a correlate for
auto declNode = dyn_cast<SDKNodeDecl>(node);
if (!declNode)
return;
auto usr = declNode->getUsr();
auto &usrName = usr;
// If we can find no nodes in the other tree with the same usr, abort.
auto candidates = diffAgainst->getDescendantsByUsr(usrName);
if (candidates.empty())
return;
// If any of the candidates has the same kind and name with the node, we
// shouldn't continue.
for (auto Can : candidates) {
if (Can->getKind() == declNode->getKind() &&
Can->getAs<SDKNodeDecl>()->getFullyQualifiedName() ==
declNode->getFullyQualifiedName())
return;
}
auto diffNode = candidates.front();
assert(node && diffNode && "nullptr visited?");
auto nodeParent = node->getParent();
auto diffParent = diffNode->getParent();
assert(nodeParent && diffParent && "trying to check Root?");
// Move from global variable to a member variable.
if (nodeParent->getKind() == SDKNodeKind::DeclType &&
diffParent->getKind() == SDKNodeKind::Root)
TypeMemberDiffs.insert({diffNode, node});
// Move from a member variable to global variable.
if (nodeParent->getKind() == SDKNodeKind::Root &&
diffParent->getKind() == SDKNodeKind::DeclType)
TypeMemberDiffs.insert({diffNode, node});
// Move from a member variable to another member variable
if (nodeParent->getKind() == SDKNodeKind::DeclType &&
diffParent->getKind() == SDKNodeKind::DeclType &&
declNode->isStatic())
TypeMemberDiffs.insert({diffNode, node});
// Move from a getter/setter function to a property
else if (node->getKind() == SDKNodeKind::DeclAccessor &&
diffNode->getKind() == SDKNodeKind::DeclFunction &&
node->isNameValid()) {
diffNode->annotate(NodeAnnotation::Rename);
diffNode->annotate(NodeAnnotation::RenameOldName,
diffNode->getPrintedName());
diffNode->annotate(NodeAnnotation::RenameNewName,
node->getParent()->getPrintedName());
}
}
public:
TypeMemberDiffFinder(SDKNodeRoot *diffAgainst):
diffAgainst(diffAgainst) {}
void findDiffsFor(NodePtr ptr) { SDKNode::preorderVisit(ptr, *this); }
const NodePairVector &getDiffs() const {
return TypeMemberDiffs;
}
void dump(llvm::raw_ostream &) const;
void dump() const { dump(llvm::errs()); }
private:
TypeMemberDiffFinder(const TypeMemberDiffFinder &) = delete;
TypeMemberDiffFinder &operator=(const TypeMemberDiffFinder &) = delete;
};
/// This is to find type alias of raw types being changed to RawRepresentable.
/// e.g. AttributeName was a typealias of String in the old SDK however it becomes
/// a RawRepresentable struct in the new SDK.
/// This happens typically when we use apinotes to preserve API stability by
/// using SwiftWrapper:none in the old SDK.
class TypeAliasDiffFinder: public SDKNodeVisitor {
SDKNodeRoot *leftRoot;
SDKNodeRoot *rightRoot;
NodeMap &result;
static bool checkTypeMatch(const SDKNodeType* aliasType,
const SDKNodeType* rawType) {
StringRef Left = aliasType->getPrintedName();
StringRef Right = rawType->getPrintedName();
if (Left == "NSString" && Right == "String")
return true;
if (Left == "String" && Right == "String")
return true;
if (Left == "Int" && Right == "Int")
return true;
if (Left == "UInt" && Right == "UInt")
return true;
return false;
}
void visit(NodePtr node) override {
auto alias = dyn_cast<SDKNodeDeclTypeAlias>(node);
if (!alias)
return;
const SDKNodeType* aliasType = alias->getUnderlyingType();
for (auto *counter: rightRoot->getDescendantsByUsr(alias->getUsr())) {
if (auto DT = dyn_cast<SDKNodeDeclType>(counter)) {
if (auto *rawType = DT->getRawValueType()) {
if (checkTypeMatch(aliasType, rawType)) {