-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckCircularity.cpp
613 lines (500 loc) · 18.4 KB
/
TypeCheckCircularity.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
//===--- TypeCheckCircularity.cpp - Type decl circularity checking --------===//
//
// 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 an infinitely-sized-type check.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Debug.h"
using namespace swift;
#define DEBUG_TYPE "TypeCheckCircularity"
namespace {
/// The information we track for a type.
class TrackingInfo {
/// The parent type; either null or a key for an entry in TrackingMap.
CanType Parent;
/// The member of the parent type that lead to this type, or null
/// for a tuple element; and whether the type is currently being
/// expanded.
llvm::PointerIntPair<ValueDecl *, 1, bool> ParentMemberAndIsBeingExpanded;
public:
TrackingInfo(CanType parent, ValueDecl *parentMember)
: Parent(parent), ParentMemberAndIsBeingExpanded(parentMember, false) {}
CanType getParentType() const {
return Parent;
}
ValueDecl *getParentMember() const {
return ParentMemberAndIsBeingExpanded.getPointer();
}
bool isBeingExpanded() const {
return ParentMemberAndIsBeingExpanded.getInt();
}
void setBeingExpanded(bool isBeingExpanded) {
ParentMemberAndIsBeingExpanded.setInt(isBeingExpanded);
}
};
struct WorkItem {
enum : unsigned {
/// A special depth we use to say that this work item
/// is to *finish* expanding the target type.
FinishExpandingType = ~0U
};
unsigned Depth;
CanType Type;
WorkItem(unsigned depth, CanType type)
: Depth(depth), Type(type) {}
};
struct PathElement {
ValueDecl *Member; // Or nullptr for a tuple element type.
size_t TupleIndex;
Type Ty;
SWIFT_DEBUG_DUMP;
void print(llvm::raw_ostream &out) const;
};
class Path {
SmallVector<PathElement, 8> Elements;
public:
void push_back(const PathElement &elt) { Elements.push_back(elt); }
bool empty() const { return Elements.empty(); }
size_t size() const { return Elements.size(); }
const PathElement &operator[](size_t index) const { return Elements[index]; }
const PathElement &back() const { return Elements.back(); }
SWIFT_DEBUG_DUMP;
void printCycle(llvm::raw_ostream &out, size_t cycleIndex) const;
void printInfinite(llvm::raw_ostream &out) const;
private:
void printSegment(llvm::raw_ostream &out, size_t begin, size_t end,
size_t maxContext, bool printFirstType = true) const;
};
/// A helper class for performing a circularity check.
class CircularityChecker final {
/// The original type declaration we're starting with.
NominalTypeDecl *OriginalDecl;
/// The maximum circularity depth.
unsigned MaxDepth;
llvm::DenseMap<CanType, TrackingInfo> TrackingMap;
SmallVector<WorkItem, 8> Workstack;
public:
CircularityChecker(NominalTypeDecl *typeDecl)
: OriginalDecl(typeDecl),
MaxDepth(typeDecl->getASTContext().LangOpts.MaxCircularityDepth) {}
void run();
private:
Type getOriginalType() const {
return OriginalDecl->getDeclaredInterfaceType();
}
bool expandType(CanType type, unsigned depth);
bool expandTuple(CanTupleType type, unsigned depth);
bool expandNominal(CanType type, NominalTypeDecl *D, unsigned depth);
bool expandStruct(CanType type, StructDecl *S, unsigned depth);
bool expandEnum(CanType type, EnumDecl *E, unsigned depth);
bool addMember(CanType parentType, ValueDecl *member, Type memberType,
unsigned parentDepth);
void startExpandingType(CanType type) {
auto it = TrackingMap.find(type);
assert(it != TrackingMap.end());
// Set the IsBeginExpanded flag.
assert(!it->second.isBeingExpanded() && "already expanding type");
it->second.setBeingExpanded(true);
// Push a work item to clear that flag.
pushFinishExpandingTypeWorkItem(type);
}
void finishExpandingType(CanType type) {
auto it = TrackingMap.find(type);
assert(it != TrackingMap.end());
// Clear the IsBeginExpanded flag.
assert(it->second.isBeingExpanded() && "not already expanding type");
it->second.setBeingExpanded(false);
}
void pushFinishExpandingTypeWorkItem(CanType type) {
Workstack.emplace_back(WorkItem::FinishExpandingType, type);
}
void pushExpandTypeWorkItem(CanType type, unsigned depth) {
assert(depth != WorkItem::FinishExpandingType);
Workstack.emplace_back(depth, type);
}
bool diagnoseCircularity(CanType parentType, ValueDecl *member,
CanType memberType);
bool diagnoseInfiniteRecursion(CanType parentType, ValueDecl *member,
CanType memberType);
void diagnoseNonWellFoundedEnum(EnumDecl *E);
void addPathElementsTo(Path &path, CanType type);
void addPathElement(Path &path, ValueDecl *member, CanType memberType);
Path buildPath(CanType parentType, ValueDecl *member, CanType memberType);
};
} // end anonymous namespace
void TypeChecker::checkDeclCircularity(NominalTypeDecl *decl) {
CircularityChecker(decl).run();
}
/// The main routine for performing circularity checks.
void CircularityChecker::run() {
auto type = getOriginalType()->getCanonicalType();
// Prime the tracking map.
TrackingMap.insert({type, TrackingInfo(CanType(), nullptr)});
// Recurse into the top-level nominal type.
expandNominal(type, OriginalDecl, 0);
// Execute the workstack.
while (!Workstack.empty()) {
auto item = Workstack.pop_back_val();
if (item.Depth == WorkItem::FinishExpandingType) {
finishExpandingType(item.Type);
} else if (expandType(item.Type, item.Depth)) {
return;
}
}
}
/// Visit a type and try to expand it one level.
///
/// \return true if a problem was found and all further processing
/// should be aborted.
bool CircularityChecker::expandType(CanType type, unsigned depth) {
if (auto D = type.getAnyNominal()) {
return expandNominal(type, D, depth);
} else if (auto tuple = dyn_cast<TupleType>(type)) {
return expandTuple(tuple, depth);
} else {
return false;
}
}
/// Visit a tuple type and try to expand it one level.
bool CircularityChecker::expandTuple(CanTupleType tupleType, unsigned depth) {
LLVM_DEBUG(llvm::dbgs() << std::string(depth, ' ') << "expanding tuple "
<< tupleType << "\n";);
startExpandingType(tupleType);
for (auto eltType : tupleType.getElementTypes()) {
if (addMember(tupleType, nullptr, eltType, depth))
return true;
}
return false;
}
/// Visit a nominal type and try to expand it one level.
bool CircularityChecker::expandNominal(CanType type, NominalTypeDecl *D,
unsigned depth) {
LLVM_DEBUG(llvm::dbgs() << std::string(depth, ' ') << "expanding nominal "
<< type << "\n";);
if (auto S = dyn_cast<StructDecl>(D)) {
return expandStruct(type, S, depth);
} else if (auto E = dyn_cast<EnumDecl>(D)) {
return expandEnum(type, E, depth);
} else {
// Other nominal types are representational leaves.
return false;
}
}
/// Visit a struct type and try to expand it one level.
bool CircularityChecker::expandStruct(CanType type, StructDecl *S,
unsigned depth) {
startExpandingType(type);
auto subMap = type->getContextSubstitutionMap();
for (auto field: S->getStoredProperties()) {
auto fieldType =field->getValueInterfaceType().subst(subMap);
if (addMember(type, field, fieldType, depth))
return true;
}
return false;
}
/// Visit an enum type and try to expand it one level.
bool CircularityChecker::expandEnum(CanType type, EnumDecl *E,
unsigned depth) {
// Indirect enums are representational leaves.
if (E->isIndirect()) {
// Diagnose whether the enum is non-well-founded before bailing
diagnoseNonWellFoundedEnum(E);
return false;
}
startExpandingType(type);
auto subMap = type->getContextSubstitutionMap();
for (auto elt: E->getAllElements()) {
// Indirect elements are representational leaves.
if (elt->isIndirect())
continue;
if (!elt->hasAssociatedValues())
continue;
auto eltType = elt->getPayloadInterfaceType().subst(subMap);
if (addMember(type, elt, eltType, depth))
return true;
}
diagnoseNonWellFoundedEnum(E);
return false;
}
bool CircularityChecker::addMember(CanType parentType, ValueDecl *member,
Type memberNCType, unsigned parentDepth) {
auto memberType = memberNCType->getCanonicalType();
unsigned depth = parentDepth + 1;
if (depth > MaxDepth) {
return diagnoseInfiniteRecursion(parentType, member, memberType);
}
// Fast path: if the type isn't some sort of interesting type,
// just ignore it.
if (isa<TupleType>(memberType)) {
// Ok, visit tuples.
} else if (memberType.getStructOrBoundGenericStruct()) {
// Ok, visit structs.
// TODO: skip non-generic types in different modules?
} else if (auto E = memberType.getEnumOrBoundGenericEnum()) {
// Ok, visit non-indirect enums.
if (E->isIndirect()) return false;
// TODO: skip non-generic types in different modules?
} else {
// Everything else is a representational leaf.
return false;
}
// Try to start tracking the type.
auto insertion = TrackingMap.insert({memberType,
TrackingInfo(parentType, member)});
// If it's not already there, add an item to recurse into it.
if (insertion.second) {
pushExpandTypeWorkItem(memberType, depth);
return false;
}
// Otherwise, we've already enqueued it. If we're not currently
// expanding it, there's no circularity to worry about.
auto &info = insertion.first->second;
if (!info.isBeingExpanded())
return false;
return diagnoseCircularity(parentType, member, memberType);
}
static size_t findCycleIndex(const Path &path) {
for (auto index : IntRange<size_t>(0, path.size() - 1)) {
if (path[index].Ty->isEqual(path.back().Ty))
return index;
}
llvm_unreachable("didn't find cycle in path");
}
static Type getMemberStorageInterfaceType(ValueDecl *member) {
if (auto elt = dyn_cast<EnumElementDecl>(member)) {
return elt->getPayloadInterfaceType();
} else {
return member->getInterfaceType();
}
}
static bool isNonDependentField(const PathElement &elt) {
if (!elt.Member) return false;
return !getMemberStorageInterfaceType(elt.Member)->hasTypeParameter();
}
void LLVM_ATTRIBUTE_USED Path::dump() const {
auto &out = llvm::errs();
printSegment(out, 0, size(), size());
out << '\n';
}
/// Prints:
/// TypeA -> (a: TypeB) -> (b: TypeB) -> (c: CycleType)
/// -> (d: TypeD) -> (e: CycleType)
void Path::printCycle(llvm::raw_ostream &out, size_t cycleIndex) const {
// If the cycle goes to Self or the member type, print the
// path in one segment starting from the field type.
if (cycleIndex <= 1) {
printSegment(out, 1, size(), 3);
// Otherwise, print the path in two segments.
} else {
printSegment(out, 1, cycleIndex + 1, 2);
printSegment(out, cycleIndex, size(), 2, false);
}
}
/// Prints:
/// TypeA -> (x: TypeB) -> (y: TypeB) -> (z: TypeC) -> ...
void Path::printInfinite(llvm::raw_ostream &out) const {
printSegment(out, 1, std::min(size(), size_t(7)), 7);
out << " -> ...";
}
/// Prints:
/// [TypeA] -> (a: TypeB) -> (b: TypeB) -> (c: TypeC)
/// If the path is too long, elides the middle with '-> ...'.
void Path::printSegment(llvm::raw_ostream &out, size_t begin, size_t end,
size_t maxContext, bool printFirstType) const {
if (printFirstType) {
out << Elements[begin].Ty;
}
size_t numElements = end - begin;
if (numElements > maxContext * 2) {
for (size_t i = begin + 1; i != begin + maxContext + 1; ++i)
Elements[i].print(out);
out << " -> ... ";
for (size_t i = end - maxContext; i != end; ++i)
Elements[i].print(out);
} else {
for (size_t i = begin + 1; i != end; ++i) {
Elements[i].print(out);
}
}
}
void LLVM_ATTRIBUTE_USED PathElement::dump() const {
auto &out = llvm::errs();
print(out);
out << '\n';
}
/// Prints:
/// -> (a: TypeA)
void PathElement::print(llvm::raw_ostream &out) const {
out << " -> (";
if (Member) {
auto name = Member->getName();
if (name) {
out << name;
} else {
out << "<anonymous>";
}
} else {
out << '.' << TupleIndex;
}
out << ": " << Ty << ')';
}
/// Recreate a non-canonical type path.
Path CircularityChecker::buildPath(CanType parentType, ValueDecl *member,
CanType memberType) {
Path path;
addPathElementsTo(path, parentType);
addPathElement(path, member, memberType);
return path;
}
/// Recreate a non-canonical path that leads to the target type.
void CircularityChecker::addPathElementsTo(Path &path, CanType targetType) {
auto it = TrackingMap.find(targetType);
assert(it != TrackingMap.end() && "no entry in tracking map?");
CanType canParentType = it->second.getParentType();
if (!canParentType) {
path.push_back({ nullptr, 0, getOriginalType()});
return;
}
addPathElementsTo(path, canParentType);
addPathElement(path, it->second.getParentMember(), targetType);
}
/// Add a non-canonical path element to a path.
void CircularityChecker::addPathElement(Path &path, ValueDecl *member,
CanType canMemberType) {
assert(!path.empty());
Type parentType = path.back().Ty;
PathElement elt;
if (member) {
elt.Member = member;
elt.TupleIndex = 0;
Type memberIfaceType = getMemberStorageInterfaceType(member);
elt.Ty = parentType->getTypeOfMember(member, memberIfaceType);
} else {
auto tupleType = parentType->castTo<TupleType>();
for (auto index : indices(tupleType->getElementTypes())) {
auto eltType = tupleType->getElementType(index);
if (eltType->getCanonicalType() == canMemberType) {
elt.Member = nullptr;
elt.TupleIndex = index;
elt.Ty = eltType;
break;
}
}
assert(elt.Ty && "didn't find matching element of tuple");
}
// We shouldn't print reference storage types here.
if (auto ref = elt.Ty->getAs<ReferenceStorageType>()) {
elt.Ty = ref->getReferentType();
}
path.push_back(elt);
}
/// Diagnose a circularity.
///
/// \returns always true
bool CircularityChecker::diagnoseCircularity(CanType parentType,
ValueDecl *member,
CanType memberType) {
auto path = buildPath(parentType, member, memberType);
// Find the index that the cycle leads back to.
auto cycleIndex = findCycleIndex(path);
// If the path to the cycle passes through a field (other than the one
// directly declared on this type) that does not depend on the original
// declaration in any way, then the type that contains that field should
// be responsible for reporting the cycle.
// TODO: we can also suppress this if the cycle would exist independently.
for (size_t i = 2; i < cycleIndex + 1; ++i) {
if (isNonDependentField(path[i]))
return true;
}
auto baseType = path[0].Ty;
if (cycleIndex != 0) {
OriginalDecl->diagnose(diag::unsupported_infinitely_sized_type, baseType);
} else if (isa<StructDecl>(OriginalDecl)) {
path[1].Member->diagnose(diag::unsupported_recursive_struct, baseType);
} else if (isa<EnumDecl>(OriginalDecl)) {
OriginalDecl->diagnose(diag::recursive_enum_not_indirect, baseType)
.fixItInsert(OriginalDecl->getStartLoc(), "indirect ");
} else {
llvm_unreachable("what kind of entity was this?");
}
// Add a note about the path we found unless it's completely trivial.
if (path.size() > 2) {
llvm::SmallString<128> pathString; {
llvm::raw_svector_ostream out(pathString);
path.printCycle(out, cycleIndex);
}
path[1].Member->diagnose(diag::note_type_cycle_starts_here, pathString);
} else if (isa<EnumDecl>(OriginalDecl)) {
path[1].Member->diagnose(diag::note_recursive_enum_case_here);
}
return true;
}
bool CircularityChecker::diagnoseInfiniteRecursion(CanType parentType,
ValueDecl *member,
CanType memberType) {
auto path = buildPath(parentType, member, memberType);
// If the path passes through a field (other than the one directly
// declared on this type) that does not depend on the original
// declaration in any way, then the type that contains that field should
// be responsible for reporting the cycle.
// Applying this heuristic only makes sense if we're assuming that
// it really is an infinite expansion.
for (size_t i = 2, e = path.size(); i < e; ++i) {
if (isNonDependentField(path[i]))
return true;
}
auto baseType = path[0].Ty;
OriginalDecl->diagnose(diag::unsupported_infinitely_sized_type, baseType);
// Add a note about the start of the path.
llvm::SmallString<128> pathString; {
llvm::raw_svector_ostream out(pathString);
path.printInfinite(out);
}
path[1].Member->diagnose(diag::note_type_cycle_starts_here, pathString);
return true;
}
/// Show a warning if all cases of the given enum are recursive,
/// making it impossible to be instantiated. Such an enum is 'non-well-founded'.
/// The outcome of this method is irrelevant.
void CircularityChecker::diagnoseNonWellFoundedEnum(EnumDecl *E) {
auto containsType = [](TupleType *tuple, Type E) -> bool {
for (auto type: tuple->getElementTypes()) {
if (type->isEqual(E))
return true;
}
return false;
};
auto isNonWellFounded = [&]() -> bool {
auto elts = E->getAllElements();
if (elts.empty())
return false;
for (auto elt: elts) {
if (!elt->isIndirect() && !E->isIndirect())
return false;
auto payloadTy = elt->getPayloadInterfaceType();
if (!payloadTy)
return false;
if (auto tuple = payloadTy->getAs<TupleType>()) {
if (!containsType(tuple, E->getSelfInterfaceType()))
return false;
} else {
if (!E->getSelfInterfaceType()->isEqual(payloadTy))
return false;
}
}
return true;
};
if (isNonWellFounded())
E->getASTContext().Diags.diagnose(E, diag::enum_non_well_founded);
}