forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReferenceDependencies.cpp
425 lines (371 loc) · 13.4 KB
/
ReferenceDependencies.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
//===--- ReferenceDependencies.cpp - Generates swiftdeps files ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "ReferenceDependencies.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ReferencedNameTracker.h"
#include "swift/AST/Types.h"
#include "swift/Frontend/FrontendOptions.h"
#include "swift/Basic/LLVM.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/YAMLParser.h"
using namespace swift;
static void findNominalsAndOperators(
llvm::MapVector<const NominalTypeDecl *, bool> &foundNominals,
llvm::SmallVectorImpl<const FuncDecl *> &foundOperators,
DeclRange members) {
for (const Decl *D : members) {
auto *VD = dyn_cast<ValueDecl>(D);
if (!VD)
continue;
if (VD->hasAccessibility() &&
VD->getFormalAccess() <= Accessibility::FilePrivate) {
continue;
}
if (VD->getFullName().isOperator()) {
foundOperators.push_back(cast<FuncDecl>(VD));
continue;
}
auto nominal = dyn_cast<NominalTypeDecl>(D);
if (!nominal)
continue;
foundNominals[nominal] |= true;
findNominalsAndOperators(foundNominals, foundOperators,
nominal->getMembers());
}
}
static bool declIsPrivate(const Decl *member) {
auto *VD = dyn_cast<ValueDecl>(member);
if (!VD) {
switch (member->getKind()) {
case DeclKind::Import:
case DeclKind::PatternBinding:
case DeclKind::EnumCase:
case DeclKind::TopLevelCode:
case DeclKind::IfConfig:
return true;
case DeclKind::Extension:
case DeclKind::InfixOperator:
case DeclKind::PrefixOperator:
case DeclKind::PostfixOperator:
return false;
default:
llvm_unreachable("everything else is a ValueDecl");
}
}
return VD->getFormalAccess() <= Accessibility::FilePrivate;
}
static bool extendedTypeIsPrivate(TypeLoc inheritedType) {
auto type = inheritedType.getType();
if (!type)
return true;
if (!type->isExistentialType()) {
// Be conservative. We don't know how to deal with other extended types.
return false;
}
auto layout = type->getExistentialLayout();
assert(!layout.superclass && "Should not have a subclass existential "
"in the inheritance clause of an extension");
for (auto protoTy : layout.getProtocols()) {
if (!declIsPrivate(protoTy->getDecl()))
return false;
}
return true;
}
static std::string mangleTypeAsContext(const NominalTypeDecl *type) {
Mangle::ASTMangler Mangler;
return Mangler.mangleTypeAsContextUSR(type);
}
std::vector<std::string>
swift::reversePathSortedFilenames(const ArrayRef<std::string> elts) {
std::vector<std::string> tmp(elts.begin(), elts.end());
std::sort(tmp.begin(), tmp.end(), [](const std::string &a,
const std::string &b) -> bool {
return std::lexicographical_compare(a.rbegin(), a.rend(),
b.rbegin(), b.rend());
});
return tmp;
}
bool swift::emitReferenceDependencies(DiagnosticEngine &diags,
SourceFile *SF,
DependencyTracker &depTracker,
const FrontendOptions &opts) {
if (!SF) {
diags.diagnose(SourceLoc(),
diag::emit_reference_dependencies_without_primary_file);
return true;
}
// Before writing to the dependencies file path, preserve any previous file
// that may have been there. No error handling -- this is just a nicety, it
// doesn't matter if it fails.
llvm::sys::fs::rename(opts.ReferenceDependenciesFilePath,
opts.ReferenceDependenciesFilePath + "~");
std::error_code EC;
llvm::raw_fd_ostream out(opts.ReferenceDependenciesFilePath, EC,
llvm::sys::fs::F_None);
if (out.has_error() || EC) {
diags.diagnose(SourceLoc(), diag::error_opening_output,
opts.ReferenceDependenciesFilePath, EC.message());
out.clear_error();
return true;
}
auto escape = [](Identifier name) -> std::string {
return llvm::yaml::escape(name.str());
};
out << "### Swift dependencies file v0 ###\n";
llvm::MapVector<const NominalTypeDecl *, bool> extendedNominals;
llvm::SmallVector<const FuncDecl *, 8> memberOperatorDecls;
llvm::SmallVector<const ExtensionDecl *, 8> extensionsWithJustMembers;
out << "provides-top-level:\n";
for (const Decl *D : SF->Decls) {
switch (D->getKind()) {
case DeclKind::Module:
break;
case DeclKind::Import:
// FIXME: Handle re-exported decls.
break;
case DeclKind::Extension: {
auto *ED = cast<ExtensionDecl>(D);
auto *NTD = ED->getExtendedType()->getAnyNominal();
if (!NTD)
break;
if (NTD->hasAccessibility() &&
NTD->getFormalAccess() <= Accessibility::FilePrivate) {
break;
}
// Check if the extension is just adding members, or if it is
// introducing a conformance to a public protocol.
bool justMembers = std::all_of(ED->getInherited().begin(),
ED->getInherited().end(),
extendedTypeIsPrivate);
if (justMembers) {
if (std::all_of(ED->getMembers().begin(), ED->getMembers().end(),
declIsPrivate)) {
break;
} else {
extensionsWithJustMembers.push_back(ED);
}
}
extendedNominals[NTD] |= !justMembers;
findNominalsAndOperators(extendedNominals, memberOperatorDecls,
ED->getMembers());
break;
}
case DeclKind::InfixOperator:
case DeclKind::PrefixOperator:
case DeclKind::PostfixOperator:
out << "- \"" << escape(cast<OperatorDecl>(D)->getName()) << "\"\n";
break;
case DeclKind::PrecedenceGroup:
out << "- \"" << escape(cast<PrecedenceGroupDecl>(D)->getName()) << "\"\n";
break;
case DeclKind::Enum:
case DeclKind::Struct:
case DeclKind::Class:
case DeclKind::Protocol: {
auto *NTD = cast<NominalTypeDecl>(D);
if (!NTD->hasName())
break;
if (NTD->hasAccessibility() &&
NTD->getFormalAccess() <= Accessibility::FilePrivate) {
break;
}
out << "- \"" << escape(NTD->getName()) << "\"\n";
extendedNominals[NTD] |= true;
findNominalsAndOperators(extendedNominals, memberOperatorDecls,
NTD->getMembers());
break;
}
case DeclKind::TypeAlias:
case DeclKind::Var:
case DeclKind::Func: {
auto *VD = cast<ValueDecl>(D);
if (!VD->hasName())
break;
if (VD->hasAccessibility() &&
VD->getFormalAccess() <= Accessibility::FilePrivate) {
break;
}
out << "- \"" << escape(VD->getName()) << "\"\n";
break;
}
case DeclKind::PatternBinding:
case DeclKind::TopLevelCode:
case DeclKind::IfConfig:
// No action necessary.
break;
case DeclKind::EnumCase:
case DeclKind::GenericTypeParam:
case DeclKind::AssociatedType:
case DeclKind::Param:
case DeclKind::Subscript:
case DeclKind::Constructor:
case DeclKind::Destructor:
case DeclKind::EnumElement:
llvm_unreachable("cannot appear at the top level of a file");
}
}
// This is also part of "provides-top-level".
for (auto *operatorFunction : memberOperatorDecls)
out << "- \"" << escape(operatorFunction->getName()) << "\"\n";
out << "provides-nominal:\n";
for (auto entry : extendedNominals) {
if (!entry.second)
continue;
out << "- \"";
out << mangleTypeAsContext(entry.first);
out << "\"\n";
}
out << "provides-member:\n";
for (auto entry : extendedNominals) {
out << "- [\"";
out << mangleTypeAsContext(entry.first);
out << "\", \"\"]\n";
}
// This is also part of "provides-member".
for (auto *ED : extensionsWithJustMembers) {
auto mangledName = mangleTypeAsContext(
ED->getExtendedType()->getAnyNominal());
for (auto *member : ED->getMembers()) {
auto *VD = dyn_cast<ValueDecl>(member);
if (!VD || !VD->hasName() ||
VD->getFormalAccess() <= Accessibility::FilePrivate) {
continue;
}
out << "- [\"" << mangledName << "\", \""
<< escape(VD->getName()) << "\"]\n";
}
}
if (SF->getASTContext().LangOpts.EnableObjCInterop) {
// FIXME: This requires a traversal of the whole file to compute.
// We should (a) see if there's a cheaper way to keep it up to date,
// and/or (b) see if we can fast-path cases where there's no ObjC involved.
out << "provides-dynamic-lookup:\n";
class NameCollector : public VisibleDeclConsumer {
private:
SmallVector<Identifier, 16> names;
public:
void foundDecl(ValueDecl *VD, DeclVisibilityKind Reason) override {
names.push_back(VD->getName());
}
ArrayRef<Identifier> getNames() {
llvm::array_pod_sort(names.begin(), names.end(),
[](const Identifier *lhs, const Identifier *rhs) {
return lhs->compare(*rhs);
});
names.erase(std::unique(names.begin(), names.end()), names.end());
return names;
}
};
NameCollector collector;
SF->lookupClassMembers({}, collector);
for (Identifier name : collector.getNames()) {
out << "- \"" << escape(name) << "\"\n";
}
}
ReferencedNameTracker *tracker = SF->getReferencedNameTracker();
auto sortedByIdentifier =
[](const llvm::DenseMap<Identifier, bool> map) ->
SmallVector<std::pair<Identifier, bool>, 16> {
SmallVector<std::pair<Identifier, bool>, 16> pairs{map.begin(), map.end()};
llvm::array_pod_sort(pairs.begin(), pairs.end(),
[](const std::pair<Identifier, bool> *first,
const std::pair<Identifier, bool> *second) -> int {
return first->first.compare(second->first);
});
return pairs;
};
out << "depends-top-level:\n";
for (auto &entry : sortedByIdentifier(tracker->getTopLevelNames())) {
assert(!entry.first.empty());
out << "- ";
if (!entry.second)
out << "!private ";
out << "\"" << escape(entry.first) << "\"\n";
}
out << "depends-member:\n";
auto &memberLookupTable = tracker->getUsedMembers();
using TableEntryTy = std::pair<ReferencedNameTracker::MemberPair, bool>;
std::vector<TableEntryTy> sortedMembers{
memberLookupTable.begin(), memberLookupTable.end()
};
llvm::array_pod_sort(sortedMembers.begin(), sortedMembers.end(),
[](const TableEntryTy *lhs,
const TableEntryTy *rhs) -> int {
if (lhs->first.first == rhs->first.first)
return lhs->first.second.compare(rhs->first.second);
if (lhs->first.first->getName() != rhs->first.first->getName())
return lhs->first.first->getName().compare(rhs->first.first->getName());
// Break type name ties by mangled name.
auto lhsMangledName = mangleTypeAsContext(lhs->first.first);
auto rhsMangledName = mangleTypeAsContext(rhs->first.first);
return lhsMangledName.compare(rhsMangledName);
});
for (auto &entry : sortedMembers) {
assert(entry.first.first != nullptr);
if (entry.first.first->hasAccessibility() &&
entry.first.first->getFormalAccess() <= Accessibility::FilePrivate)
continue;
out << "- ";
if (!entry.second)
out << "!private ";
out << "[\"";
out << mangleTypeAsContext(entry.first.first);
out << "\", \"";
if (!entry.first.second.empty())
out << escape(entry.first.second);
out << "\"]\n";
}
out << "depends-nominal:\n";
for (auto i = sortedMembers.begin(), e = sortedMembers.end(); i != e; ++i) {
bool isCascading = i->second;
while (i+1 != e && i[0].first.first == i[1].first.first) {
++i;
isCascading |= i->second;
}
if (i->first.first->hasAccessibility() &&
i->first.first->getFormalAccess() <= Accessibility::FilePrivate)
continue;
out << "- ";
if (!isCascading)
out << "!private ";
out << "\"";
out << mangleTypeAsContext(i->first.first);
out << "\"\n";
}
out << "depends-dynamic-lookup:\n";
for (auto &entry : sortedByIdentifier(tracker->getDynamicLookupNames())) {
assert(!entry.first.empty());
out << "- ";
if (!entry.second)
out << "!private ";
out << "\"" << escape(entry.first) << "\"\n";
}
out << "depends-external:\n";
for (auto &entry : reversePathSortedFilenames(depTracker.getDependencies())) {
out << "- \"" << llvm::yaml::escape(entry) << "\"\n";
}
llvm::SmallString<32> interfaceHash;
SF->getInterfaceHash(interfaceHash);
out << "interface-hash: \"" << interfaceHash << "\"\n";
return false;
}