-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathSwiftDispatcher.h
361 lines (327 loc) · 13 KB
/
SwiftDispatcher.h
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
#pragma once
#include <filesystem>
#include <swift/AST/SourceFile.h>
#include <swift/Basic/SourceManager.h>
#include <swift/Parse/Token.h>
#include "absl/strings/str_cat.h"
#include "swift/extractor/trap/TrapDomain.h"
#include "swift/extractor/infra/SwiftTagTraits.h"
#include "swift/extractor/trap/generated/TrapClasses.h"
#include "swift/extractor/infra/SwiftLocationExtractor.h"
#include "swift/extractor/infra/SwiftBodyEmissionStrategy.h"
#include "swift/extractor/infra/SwiftMangledName.h"
#include "swift/extractor/config/SwiftExtractorState.h"
#include "swift/logging/SwiftAssert.h"
namespace codeql {
// The main responsibilities of the SwiftDispatcher are as follows:
// * redirect specific AST node emission to a corresponding visitor (statements, expressions, etc.)
// * storing TRAP labels for emitted AST nodes (in the TrapLabelStore) to avoid re-emission
// Since SwiftDispatcher sees all the AST nodes, it also attaches a location to every 'locatable'
// node (AST nodes that are not types: declarations, statements, expressions, etc.).
class SwiftDispatcher {
// types to be supported by assignNewLabel/fetchLabel need to be listed here
using Handle = std::variant<const swift::Decl*,
const swift::Stmt*,
const swift::StmtCondition*,
const swift::StmtConditionElement*,
const swift::CaseLabelItem*,
const swift::Expr*,
const swift::Pattern*,
const swift::TypeRepr*,
const swift::TypeBase*,
const swift::CapturedValue*,
const swift::PoundAvailableInfo*,
const swift::AvailabilitySpec*,
const swift::MacroRoleAttr*>;
public:
// all references and pointers passed as parameters to this constructor are supposed to outlive
// the SwiftDispatcher
SwiftDispatcher(const swift::SourceManager& sourceManager,
SwiftExtractorState& state,
TrapDomain& trap,
SwiftLocationExtractor& locationExtractor,
SwiftBodyEmissionStrategy& bodyEmissionStrategy)
: sourceManager{sourceManager},
state{state},
trap{trap},
locationExtractor{locationExtractor},
bodyEmissionStrategy{bodyEmissionStrategy} {}
const std::unordered_set<swift::ModuleDecl*> getEncounteredModules() && {
return std::move(encounteredModules);
}
template <typename Entry>
void emit(Entry&& entry) {
bool valid = true;
entry.forEachLabel([&valid, &entry, this](const char* field, int index, auto& label) {
using Label = std::remove_reference_t<decltype(label)>;
if (!label.valid()) {
const char* action;
if constexpr (std::derived_from<UnspecifiedElementTag, typename Label::Tag>) {
action = "replacing with unspecified element";
label = emitUnspecified(idOf(entry), field, index);
} else {
action = "skipping emission";
valid = false;
}
LOG_ERROR("{} has undefined field {}{}, {}", entry.NAME, field,
index >= 0 ? absl::StrCat("[", index, "]") : "", action);
}
});
if (valid) {
trap.emit(entry, /* check */ false);
}
}
template <typename Entry>
void emit(std::optional<Entry>&& entry) {
if (entry) {
emit(std::move(*entry));
}
}
template <typename... Cases>
void emit(std::variant<Cases...>&& entry) {
std::visit([this](auto&& e) { this->emit(std::move(e)); }, std::move(entry));
}
// This is a helper method to emit TRAP entries for AST nodes that we don't fully support yet.
template <typename E>
void emitUnknown(E* entity) {
auto label = assignNewLabel(entity);
using Trap = BindingTrapOf<E>;
static_assert(sizeof(Trap) == sizeof(label),
"Binding traps of unknown entities must only have the `id` field (the class "
"should be empty in schema.yml)");
emit(Trap{label});
emit(ElementIsUnknownTrap{label});
}
TrapLabel<UnspecifiedElementTag> emitUnspecified(std::optional<TrapLabel<ElementTag>>&& parent,
const char* property,
int index) {
UnspecifiedElement entry{trap.createTypedLabel<UnspecifiedElementTag>()};
entry.error = "element was unspecified by the extractor";
entry.parent = std::move(parent);
entry.property = property;
if (index >= 0) {
entry.index = index;
}
trap.emit(entry);
return entry.id;
}
template <typename E>
std::optional<TrapLabel<ElementTag>> idOf(const E& entry) {
if constexpr (requires { entry.id; }) {
return entry.id;
} else {
return std::nullopt;
}
}
// This method gives a TRAP label for already emitted AST node.
// If the AST node was not emitted yet, then the emission is dispatched to a corresponding
// visitor (see `visit(T *)` methods below).
// clang-format off
template <typename E>
requires std::constructible_from<Handle, E*>
TrapLabelOf<E> fetchLabel(const E* e, swift::Type type = {}) {
// clang-format on
if (!e) {
// this will be treated on emission
return undefined_label;
}
if constexpr (std::derived_from<swift::VarDecl, E>) {
// canonicalize all VarDecls. For details, see doc of getCanonicalVarDecl
if (auto var = llvm::dyn_cast<const swift::VarDecl>(e)) {
e = var->getCanonicalVarDecl();
}
}
auto& stored = store[e];
if (!stored.valid()) {
auto inserted = fetching.insert(e);
CODEQL_ASSERT(inserted.second, "detected infinite fetchLabel recursion");
stored = createLabel(e, type);
fetching.erase(e);
}
return TrapLabelOf<E>::unsafeCreateFromUntyped(stored);
}
// convenience `fetchLabel` overload for `swift::Type` (which is just a wrapper for
// `swift::TypeBase*`)
TrapLabel<TypeTag> fetchLabel(swift::Type t) { return fetchLabel(t.getPointer()); }
TrapLabel<AstNodeTag> fetchLabel(swift::ASTNode node) {
auto ret = fetchLabelFromUnion<AstNodeTag>(node);
if (!ret.valid()) {
// TODO to be more useful, we need a generic way of attaching original source location info
// to logs, this will come in upcoming work
LOG_ERROR("Unable to fetch label for ASTNode");
}
return ret;
}
// clang-format off
template <typename E>
requires std::constructible_from<Handle, E*>
TrapLabelOf<E> fetchLabel(const E& e) {
// clang-format on
return fetchLabel(&e);
}
// convenience methods for structured C++ creation
template <typename E>
auto createEntry(const E& e) {
auto found = store.find(&e);
CODEQL_ASSERT(found != store.end(), "createEntry called on non-fetched label");
using Tag = ConcreteTrapTagOf<E>;
auto label = TrapLabel<Tag>::unsafeCreateFromUntyped(found->second);
if constexpr (IsLocatable<E>) {
locationExtractor.attachLocation(sourceManager, e, label);
}
return TrapClassOf<E>{label};
}
// used to create a new entry for entities that should not be cached
// an example is swift::Argument, that are created on the fly and thus have no stable pointer
template <typename E>
auto createUncachedEntry(const E& e) {
using Tag = TrapTagOf<E>;
auto label = trap.createTypedLabel<Tag>();
locationExtractor.attachLocation(sourceManager, &e, label);
return TrapClassOf<E>{label};
}
// return `std::optional(fetchLabel(arg))` if arg converts to true, otherwise std::nullopt
// universal reference `Arg&&` is used to catch both temporary and non-const references, not
// for perfect forwarding
template <typename Arg, typename... Args>
auto fetchOptionalLabel(Arg&& arg, Args&&... args) -> std::optional<decltype(fetchLabel(arg))> {
if (arg) {
return fetchLabel(arg, std::forward<Args>(args)...);
}
return std::nullopt;
}
// map `fetchLabel` on the iterable `arg`
// universal reference `Arg&&` is used to catch both temporary and non-const references, not
// for perfect forwarding
template <typename Iterable>
auto fetchRepeatedLabels(Iterable&& arg) {
using Label = decltype(fetchLabel(*arg.begin()));
TrapLabelVectorWrapper<typename Label::Tag> ret;
if constexpr (requires { arg.size(); }) {
ret.data.reserve(arg.size());
}
for (auto&& e : arg) {
ret.data.push_back(fetchLabel(e));
}
return ret;
}
template <typename... Args>
void emitDebugInfo(const Args&... args) {
trap.debug(args...);
}
void emitComment(swift::Token& comment) {
CommentsTrap entry{trap.createTypedLabel<CommentTag>(), comment.getRawText().str()};
trap.emit(entry);
locationExtractor.attachLocation(sourceManager, comment, entry.id);
}
protected:
void visitPending() {
while (!toBeVisited.empty()) {
auto [next, type] = toBeVisited.back();
toBeVisited.pop_back();
// TODO: add tracing logs for visited stuff, maybe within the translators?
std::visit([this, type = type](const auto* e) { visit(e, type); }, next);
}
}
private:
template <typename E>
UntypedTrapLabel createLabel(const E& e, swift::Type type) {
if constexpr (requires { name(e); }) {
if (auto mangledName = name(e)) {
if (shouldVisit(e)) {
toBeVisited.emplace_back(e, type);
}
return trap.createLabel(mangledName);
}
}
// we always need to visit unnamed things
toBeVisited.emplace_back(e, type);
return trap.createLabel();
}
template <typename E>
bool shouldVisit(const E& e) {
if constexpr (std::convertible_to<E, const swift::Decl*>) {
encounteredModules.insert(e->getModuleContext());
if (bodyEmissionStrategy.shouldEmitDeclBody(*e)) {
extractedDeclaration(e);
return true;
}
skippedDeclaration(e);
return false;
}
return true;
}
void extractedDeclaration(const swift::Decl* decl) {
if (isLazyDeclaration(decl)) {
state.emittedDeclarations.insert(decl);
}
}
void skippedDeclaration(const swift::Decl* decl) {
if (isLazyDeclaration(decl)) {
state.pendingDeclarations.insert(decl);
}
}
static bool isLazyDeclaration(const swift::Decl* decl) {
swift::ModuleDecl* module = decl->getModuleContext();
return module->isBuiltinModule() || module->getName().str() == "__ObjC" ||
module->isNonSwiftModule();
}
template <typename Tag, typename... Ts>
TrapLabel<Tag> fetchLabelFromUnion(const llvm::PointerUnion<Ts...> u) {
TrapLabel<Tag> ret{};
// with logical op short-circuiting, this will stop trying on the first successful fetch
bool unionCaseFound = (... || fetchLabelFromUnionCase<Tag, Ts>(u, ret));
if (!unionCaseFound) {
return undefined_label;
}
return ret;
}
template <typename Tag, typename T, typename... Ts>
bool fetchLabelFromUnionCase(const llvm::PointerUnion<Ts...> u, TrapLabel<Tag>& output) {
// we rely on the fact that when we extract `ASTNode` instances (which only happens
// on `BraceStmt`/`IfConfigDecl` elements), we cannot encounter a standalone `TypeRepr` there,
// so we skip this case; extracting `TypeRepr`s here would be problematic as we would not be
// able to provide the corresponding type
if constexpr (!std::same_as<T, swift::TypeRepr*>) {
if (auto e = u.template dyn_cast<T>()) {
output = fetchLabel(e);
return true;
}
}
return false;
}
virtual SwiftMangledName name(const swift::Decl* decl) = 0;
virtual SwiftMangledName name(const swift::TypeBase* type) = 0;
virtual void visit(const swift::Decl* decl) = 0;
virtual void visit(const swift::Stmt* stmt) = 0;
virtual void visit(const swift::StmtCondition* cond) = 0;
virtual void visit(const swift::StmtConditionElement* cond) = 0;
virtual void visit(const swift::PoundAvailableInfo* availability) = 0;
virtual void visit(const swift::AvailabilitySpec* spec) = 0;
virtual void visit(const swift::CaseLabelItem* item) = 0;
virtual void visit(const swift::Expr* expr) = 0;
virtual void visit(const swift::Pattern* pattern) = 0;
virtual void visit(const swift::TypeRepr* typeRepr, swift::Type type) = 0;
virtual void visit(const swift::TypeBase* type) = 0;
virtual void visit(const swift::CapturedValue* capture) = 0;
virtual void visit(const swift::MacroRoleAttr* attr) = 0;
template <typename T>
requires(!std::derived_from<T, swift::TypeRepr>)
void visit(const T* e, swift::Type) {
visit(e);
}
const swift::SourceManager& sourceManager;
SwiftExtractorState& state;
TrapDomain& trap;
std::unordered_map<Handle, UntypedTrapLabel> store;
std::unordered_set<Handle> fetching;
std::vector<std::pair<Handle, swift::Type>> toBeVisited;
SwiftLocationExtractor& locationExtractor;
SwiftBodyEmissionStrategy& bodyEmissionStrategy;
std::unordered_set<swift::ModuleDecl*> encounteredModules;
Logger& logger() {
static Logger ret{"dispatcher"};
return ret;
}
};
} // namespace codeql