forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathASTScope.cpp
2202 lines (1833 loc) · 71.5 KB
/
ASTScope.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
//===--- ASTScope.cpp - Swift AST Scope -----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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 the ASTScope class and related functionality, which
// describes the scopes that exist within a Swift AST.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTScope.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/STLExtras.h"
#include <algorithm>
using namespace swift;
const ASTScope *ASTScope::getActiveContinuation() const {
switch (continuation.getInt()) {
case ContinuationKind::Historical:
return nullptr;
case ContinuationKind::Active:
case ContinuationKind::ActiveThenSourceFile:
return continuation.getPointer();
}
}
const ASTScope *ASTScope::getHistoricalContinuation() const {
switch (continuation.getInt()) {
case ContinuationKind::Historical:
case ContinuationKind::Active:
return continuation.getPointer();
case ContinuationKind::ActiveThenSourceFile:
return getSourceFileScope();
}
}
void ASTScope::addActiveContinuation(const ASTScope *newContinuation) const {
assert(newContinuation && "Use 'remove active continuation'");
// Add a new, active continuation, making sure we're not losing historical
// information.
// Simple case: this is the first time this node has had a continuation.
if (!continuation.getPointer()) {
continuation.setPointerAndInt(newContinuation, ContinuationKind::Active);
return;
}
// Setting a continuation to itself is a no-op.
if (continuation.getPointer() == newContinuation) return;
// Setting a new continuation is only valid when we're replacing a
// \c SourceFile continuation.
switch (continuation.getInt()) {
case ContinuationKind::Active:
// Only a \c SourceFile continuation can be replaced.
assert(continuation.getPointer()->getKind() == ASTScopeKind::SourceFile ||
continuation.getPointer()->getParent()->getKind()
== ASTScopeKind::TopLevelCode);
continuation.setPointerAndInt(newContinuation,
ContinuationKind::ActiveThenSourceFile);
break;
case ContinuationKind::Historical:
// Only a \c SourceFile continuation can be replaced.
assert(continuation.getPointer()->getKind() == ASTScopeKind::SourceFile ||
continuation.getPointer()->getParent()->getKind()
== ASTScopeKind::TopLevelCode);
continuation.setPointerAndInt(newContinuation, ContinuationKind::Active);
break;
case ContinuationKind::ActiveThenSourceFile:
llvm_unreachable("cannot replace a continuation twice");
}
}
void ASTScope::removeActiveContinuation() const {
switch (continuation.getInt()) {
case ContinuationKind::Active:
continuation.setInt(ContinuationKind::Historical);
break;
case ContinuationKind::Historical:
llvm_unreachable("nothing to remove");
break;
case ContinuationKind::ActiveThenSourceFile:
// Make the \c SourceFile the active continuation.
continuation.setPointerAndInt(getSourceFileScope(),
ContinuationKind::Active);
break;
}
}
void ASTScope::clearActiveContinuation() const {
switch (continuation.getInt()) {
case ContinuationKind::Active:
continuation.setInt(ContinuationKind::Historical);
break;
case ContinuationKind::Historical:
llvm_unreachable("nothing to clear");
break;
case ContinuationKind::ActiveThenSourceFile:
// Make the \c SourceFile the historical continuation.
continuation.setPointerAndInt(getSourceFileScope(),
ContinuationKind::Historical);
break;
}
}
ASTScope::ASTScope(const ASTScope *parent, ArrayRef<ASTScope *> children)
: ASTScope(ASTScopeKind::Preexpanded, parent) {
assert(children.size() > 1 && "Don't use this without multiple nodes");
// Add child nodes, reparenting them to this node.
storedChildren.reserve(children.size());
for (auto child : children) {
child->parentAndExpanded.setPointer(this);
storedChildren.push_back(child);
}
// Note that this node has already been expanded.
parentAndExpanded.setInt(true);
// Register the destructor.
ASTContext &ctx = parent->getASTContext();
ctx.addDestructorCleanup(storedChildren);
// Make sure the children were properly sorted.
assert(std::is_sorted(children.begin(), children.end(),
[&](ASTScope *s1, ASTScope *s2) {
return ctx.SourceMgr.isBeforeInBuffer(s1->getSourceRange().Start,
s2->getSourceRange().Start);
}));
}
/// Determine whether we should completely skip the given element in a
/// \c BraceStmt.
static bool shouldSkipBraceStmtElement(ASTNode element) {
if (auto decl = element.dyn_cast<Decl *>())
return isa<VarDecl>(decl);
return false;
}
/// Determine whether the given abstract storage declaration has accessors.
static bool hasAccessors(AbstractStorageDecl *asd) {
switch (asd->getStorageKind()) {
case AbstractStorageDecl::Addressed:
case AbstractStorageDecl::AddressedWithObservers:
case AbstractStorageDecl::AddressedWithTrivialAccessors:
case AbstractStorageDecl::Computed:
case AbstractStorageDecl::ComputedWithMutableAddress:
case AbstractStorageDecl::InheritedWithObservers:
case AbstractStorageDecl::StoredWithObservers:
return asd->getBracesRange().isValid();
case AbstractStorageDecl::Stored:
case AbstractStorageDecl::StoredWithTrivialAccessors:
return false;
}
}
/// Determine whether this is a top-level code declaration that isn't just
/// wrapping an #if.
static bool isRealTopLevelCodeDecl(Decl *decl) {
auto topLevelCode = dyn_cast<TopLevelCodeDecl>(decl);
if (!topLevelCode) return false;
// Drop top-level statements containing just an IfConfigStmt.
// FIXME: The modeling of IfConfig is weird.
auto braceStmt = topLevelCode->getBody();
auto elements = braceStmt->getElements();
if (elements.size() == 1 &&
elements[0].is<Stmt *>() &&
isa<IfConfigStmt>(elements[0].get<Stmt *>()))
return false;
return true;
}
void ASTScope::expand() const {
assert(!isExpanded() && "Already expanded the children of this node");
ASTContext &ctx = getASTContext();
SourceManager &sourceMgr = ctx.SourceMgr;
#ifndef NDEBUG
auto verificationError = [&]() -> llvm::raw_ostream& {
return llvm::errs() << "ASTScope verification error in source file '"
<< getSourceFile().getFilename()
<< "': ";
};
#endif
// Local function to add a child to the list of children.
bool previouslyEmpty = storedChildren.empty();
auto addChild = [&](ASTScope *child) -> bool {
assert(child->getParent() == this && "Wrong parent");
// If we have a continuation and the child can steal it, transfer the
// continuation to that child.
bool stoleContinuation = false;
if (getActiveContinuation() && child->canStealContinuation()) {
assert(!child->getActiveContinuation() &&
"Child cannot have a continuation already");
child->continuation = this->continuation;
this->clearActiveContinuation();
stoleContinuation = true;
}
#ifndef NDEBUG
// Check invariants in asserting builds.
// Check for containment of the child within the parent.
if (!sourceMgr.rangeContains(getSourceRange(), child->getSourceRange())) {
auto &out = verificationError() << "child not contained in its parent\n";
out << "***Child node***\n";
child->print(out);
out << "***Parent node***\n";
this->print(out);
abort();
}
// If there was a previous child, check it's source range.
if (!storedChildren.empty()) {
auto prevChild = storedChildren.back();
SourceRange prevChildRange = prevChild->getSourceRange();
SourceRange childRange = child->getSourceRange();
// This new child must come after the previous child.
if (sourceMgr.isBeforeInBuffer(childRange.Start, prevChildRange.End)) {
auto &out = verificationError() << "unexpected out-of-order nodes\n";
out << "***Child node***\n";
child->print(out);
out << "***Previous child node***\n";
prevChild->print(out);
out << "***Parent node***\n";
this->print(out);
abort();
}
// The previous child must not overlap this child.
if (sourceMgr.isBeforeInBuffer(childRange.End, prevChildRange.End)) {
auto &out = verificationError() << "unexpected child overlap\n";
out << "***Child node***\n";
child->print(out);
out << "***Previous child node***\n";
prevChild->print(out);
out << "***Parent node***\n";
this->print(out);
abort();
}
}
#endif
// Add the child.
storedChildren.push_back(child);
return stoleContinuation;
};
// Local function to add the accessors of the variables in the given pattern
// as children.
auto addAccessors = [&](Pattern *pattern) {
// Create children for the accessors of any variables in the pattern that
// have them.
pattern->forEachVariable([&](VarDecl *var) {
if (hasAccessors(var)) {
addChild(new (ctx) ASTScope(this, var));
}
});
};
if (!parentAndExpanded.getInt()) {
// Expand the children in the current scope.
switch (getKind()) {
case ASTScopeKind::Preexpanded:
llvm_unreachable("Node should be pre-expanded");
case ASTScopeKind::SourceFile: {
if (!getHistoricalContinuation()) {
/// Add declarations to the list of children directly.
for (unsigned i : range(sourceFile.nextElement,
sourceFile.file->Decls.size())) {
Decl *decl = sourceFile.file->Decls[i];
// If the declaration is a top-level code declaration, turn the source
// file into a continuation. We're done.
if (isRealTopLevelCodeDecl(decl)) {
addActiveContinuation(this);
break;
}
// Note the next element to be consumed.
sourceFile.nextElement = i + 1;
// Create a child node for this declaration.
if (ASTScope *child = createIfNeeded(this, decl))
(void)addChild(child);
}
}
break;
}
case ASTScopeKind::ExtensionGenericParams: {
// Create a child node.
if (ASTScope *child = createIfNeeded(this, extension))
addChild(child);
break;
}
case ASTScopeKind::TypeOrExtensionBody:
for (auto member : iterableDeclContext->getMembers()) {
// Create a child node for this declaration.
if (ASTScope *child = createIfNeeded(this, member))
addChild(child);
}
break;
case ASTScopeKind::GenericParams:
// Create a child of the generic parameters, if needed.
if (auto child = createIfNeeded(this, genericParams.decl))
addChild(child);
break;
case ASTScopeKind::TypeDecl:
// Create the child of the function, if any.
if (auto child = createIfNeeded(this, typeDecl))
addChild(child);
break;
case ASTScopeKind::AbstractFunctionDecl:
// Create the child of the function, if any.
if (auto child = createIfNeeded(this, abstractFunction))
addChild(child);
break;
case ASTScopeKind::AbstractFunctionParams:
// Create a child of the function parameters, which may eventually be
// the function body.
if (auto child = createIfNeeded(this, abstractFunctionParams.decl))
addChild(child);
break;
case ASTScopeKind::DefaultArgument:
// Create a child for the default argument expression.
if (auto child = createIfNeeded(this, parameter->getDefaultValue()))
addChild(child);
break;
case ASTScopeKind::AbstractFunctionBody:
// Create a child for the actual body.
if (auto child = createIfNeeded(this, abstractFunction->getBody()))
addChild(child);
break;
case ASTScopeKind::PatternBinding: {
const auto &patternEntry =
patternBinding.decl->getPatternList()[patternBinding.entry];
// Create a child for the initializer, if present.
if (patternEntry.getInitAsWritten() &&
patternEntry.getInitAsWritten()->getSourceRange().isValid()) {
addChild(new (ctx) ASTScope(ASTScopeKind::PatternInitializer, this,
patternBinding.decl, patternBinding.entry));
}
// If there is an active continuation, nest the remaining pattern bindings.
if (getActiveContinuation()) {
// Note: the accessors will follow the pattern binding.
addChild(new (ctx) ASTScope(ASTScopeKind::AfterPatternBinding, this,
patternBinding.decl, patternBinding.entry));
} else {
// Otherwise, add the accessors immediately.
addAccessors(patternEntry.getPattern());
}
break;
}
case ASTScopeKind::PatternInitializer: {
const auto &patternEntry =
patternBinding.decl->getPatternList()[patternBinding.entry];
// Create a child for the initializer expression.
if (auto child = createIfNeeded(this, patternEntry.getInitAsWritten()))
addChild(child);
break;
}
case ASTScopeKind::AfterPatternBinding: {
const auto &patternEntry =
patternBinding.decl->getPatternList()[patternBinding.entry];
// Add accessors for the variables in this pattern.
addAccessors(patternEntry.getPattern());
// Create a child for the next pattern binding.
if (auto child = createIfNeeded(this, patternBinding.decl))
addChild(child);
break;
}
case ASTScopeKind::BraceStmt:
// Expanding a brace statement means setting it as its own continuation,
// unless that's already been done.
addActiveContinuation(this);
break;
case ASTScopeKind::IfStmt:
// The first conditional clause or, failing that, the 'then' clause.
if (!ifStmt->getCond().empty()) {
addChild(new (ctx) ASTScope(this, ifStmt, 0,
/*isGuardContinuation=*/false));
} else {
if (auto thenChild = createIfNeeded(this, ifStmt->getThenStmt()))
addChild(thenChild);
}
// Add the 'else' branch, if needed.
if (auto elseChild = createIfNeeded(this, ifStmt->getElseStmt()))
addChild(elseChild);
break;
case ASTScopeKind::ConditionalClause: {
// If this is a boolean conditional not in a guard continuation, add a
// child for the expression.
if (!conditionalClause.isGuardContinuation) {
const auto &cond =
conditionalClause.stmt->getCond()[conditionalClause.index];
if (auto booleanChild = createIfNeeded(this, cond.getBooleanOrNull()))
addChild(booleanChild);
}
// If there's another conditional clause, add it as the child.
unsigned nextIndex = conditionalClause.index + 1;
if (nextIndex < conditionalClause.stmt->getCond().size()) {
addChild(new (ctx) ASTScope(this, conditionalClause.stmt, nextIndex,
conditionalClause.isGuardContinuation));
break;
}
// There aren't any additional conditional clauses. Add the appropriate
// nested scope based on the kind of statement.
if (auto ifStmt = dyn_cast<IfStmt>(conditionalClause.stmt)) {
if (auto child = createIfNeeded(this, ifStmt->getThenStmt()))
addChild(child);
} else if (auto whileStmt = dyn_cast<WhileStmt>(conditionalClause.stmt)) {
if (auto child = createIfNeeded(this, whileStmt->getBody()))
addChild(child);
} else {
// Note: guard statements have the continuation nested under the last
// condition.
assert(isa<GuardStmt>(conditionalClause.stmt) &&
"unknown labeled conditional statement");
}
break;
}
case ASTScopeKind::GuardStmt:
// Add a child to describe the guard condition.
addChild(new (ctx) ASTScope(this, guard, 0,
/*isGuardContinuation=*/false));
// Add a child for the 'guard' body, which always exits.
if (auto bodyChild = createIfNeeded(this, guard->getBody()))
addChild(bodyChild);
// Add a child to describe the guard condition for the continuation.
addChild(new (ctx) ASTScope(this, guard, 0,
/*isGuardContinuation=*/true));
break;
case ASTScopeKind::RepeatWhileStmt:
// Add a child for the loop body.
if (auto bodyChild = createIfNeeded(this, repeatWhile->getBody()))
addChild(bodyChild);
// Add a child for the loop condition.
if (auto conditionChild = createIfNeeded(this, repeatWhile->getCond()))
addChild(conditionChild);
break;
case ASTScopeKind::ForEachStmt:
// Add a child for the sequence.
if (auto seqChild = createIfNeeded(this, forEach->getSequence()))
addChild(seqChild);
// Add a child describing the scope of the pattern.
addChild(new (ctx) ASTScope(ASTScopeKind::ForEachPattern, this, forEach));
break;
case ASTScopeKind::ForEachPattern:
// Add a child for the 'where' clause.
if (auto whereChild = createIfNeeded(this, forEach->getWhere()))
addChild(whereChild);
// Add a child for the body.
if (auto bodyChild = createIfNeeded(this, forEach->getBody()))
addChild(bodyChild);
break;
case ASTScopeKind::DoCatchStmt:
// Add a child for the body.
if (auto bodyChild = createIfNeeded(this, doCatch->getBody()))
addChild(bodyChild);
// Add children for each of the 'catch' clauses.
for (auto catchClause : doCatch->getCatches()) {
if (auto catchChild = createIfNeeded(this, catchClause))
addChild(catchChild);
}
break;
case ASTScopeKind::CatchStmt:
// Add a child for the guard expression, if there is one.
if (auto guardChild = createIfNeeded(this, catchStmt->getGuardExpr()))
addChild(guardChild);
// Add a child for the catch body.
if (auto bodyChild = createIfNeeded(this, catchStmt->getBody()))
addChild(bodyChild);
break;
case ASTScopeKind::SwitchStmt:
// Add a child for the subject expression.
if (auto subjectChild = createIfNeeded(this, switchStmt->getSubjectExpr()))
addChild(subjectChild);
// Add children for each of the cases.
for (auto caseStmt : switchStmt->getCases()) {
if (auto caseChild = createIfNeeded(this, caseStmt))
addChild(caseChild);
}
break;
case ASTScopeKind::CaseStmt:
// Add children for the items.
for (auto &caseItem : caseStmt->getMutableCaseLabelItems()) {
if (auto guardChild = createIfNeeded(this, caseItem.getGuardExpr()))
addChild(guardChild);
}
// Add a child for the case body.
if (auto bodyChild = createIfNeeded(this, caseStmt->getBody()))
addChild(bodyChild);
break;
case ASTScopeKind::ForStmt:
// The for statement encloses the scope introduced by its initializers.
addChild(new (ctx) ASTScope(ASTScopeKind::ForStmtInitializer,
this, forStmt));
break;
case ASTScopeKind::ForStmtInitializer:
// Add a child for the condition, if present.
if (auto cond = forStmt->getCond()) {
if (auto condChild = createIfNeeded(this, cond.get()))
addChild(condChild);
}
// Add a child for the increment, if present.
if (auto incr = forStmt->getIncrement()) {
if (auto incrChild = createIfNeeded(this, incr.get()))
addChild(incrChild);
}
// Add a child for the body.
if (auto bodyChild = createIfNeeded(this, forStmt->getBody()))
addChild(bodyChild);
break;
case ASTScopeKind::Accessors: {
// Add children for all of the explicitly-written accessors.
SmallVector<ASTScope *, 4> accessors;
auto addAccessor = [&](FuncDecl *accessor) {
if (!accessor) return;
if (accessor->isImplicit()) return;
if (accessor->getStartLoc().isInvalid()) return;
if (auto accessorChild = createIfNeeded(this, accessor))
accessors.push_back(accessorChild);
};
addAccessor(abstractStorageDecl->getGetter());
addAccessor(abstractStorageDecl->getSetter());
addAccessor(abstractStorageDecl->getMaterializeForSetFunc());
if (abstractStorageDecl->hasAddressors()) {
addAccessor(abstractStorageDecl->getAddressor());
addAccessor(abstractStorageDecl->getMutableAddressor());
}
if (abstractStorageDecl->hasObservers()) {
addAccessor(abstractStorageDecl->getDidSetFunc());
addAccessor(abstractStorageDecl->getWillSetFunc());
}
// Sort the accessors, because they can come in any order.
std::sort(accessors.begin(), accessors.end(),
[&](ASTScope *s1, ASTScope *s2) {
return ctx.SourceMgr.isBeforeInBuffer(s1->getSourceRange().Start,
s2->getSourceRange().Start);
});
// Add the accessors.
for (auto accessor : accessors)
addChild(accessor);
break;
}
case ASTScopeKind::Closure:
// Add the child for a body.
if (auto bodyChild = createIfNeeded(this, closure->getBody()))
addChild(bodyChild);
break;
case ASTScopeKind::TopLevelCode:
/// Add a child for the body.
if (auto bodyChild = createIfNeeded(this, topLevelCode->getBody()))
addChild(bodyChild);
break;
}
}
// Enumerate any continuation scopes associated with this parent.
enumerateContinuationScopes(addChild);
// If this is the first time we've added children, notify the ASTContext
// that there's a SmallVector that needs to be cleaned up.
// FIXME: If we had access to SmallVector::isSmall(), we could do better.
if (previouslyEmpty && !storedChildren.empty())
getASTContext().addDestructorCleanup(storedChildren);
// The scope is considered "expanded" at this point, although there might be
// further work to do if there is an active continuation.
if (getKind() != ASTScopeKind::SourceFile || getHistoricalContinuation())
parentAndExpanded.setInt(true);
}
bool ASTScope::isExpanded() const {
// If the 'expanded' bit is not set, we haven't expanded.
if (!parentAndExpanded.getInt()) return false;
// If there is an active continuation, we're expanded if it's not the
// source-file continuation or if we're at the end of the list of
// declarations.
if (auto continuation = getActiveContinuation()) {
return continuation->getKind() != ASTScopeKind::SourceFile ||
(continuation->sourceFile.nextElement
== continuation->sourceFile.file->Decls.size());
}
// If it's a source file that has never been a continuation, check whether
// we're at the last declaration.
return getKind() != ASTScopeKind::SourceFile ||
((sourceFile.nextElement == sourceFile.file->Decls.size()) &&
!getHistoricalContinuation());
}
/// Create the AST scope for a source file, which is the root of the scope
/// tree.
ASTScope *ASTScope::createRoot(SourceFile *sourceFile) {
ASTContext &ctx = sourceFile->getASTContext();
// Create the scope.
ASTScope *scope = new (ctx) ASTScope(sourceFile, 0);
scope->sourceFile.file = sourceFile;
scope->sourceFile.nextElement = 0;
return scope;
}
/// Find the parameter list and parameter index (into that list) corresponding
/// to the next parameter.
static Optional<std::pair<unsigned, unsigned>>
findNextParameter(AbstractFunctionDecl *func, unsigned listIndex,
unsigned paramIndex) {
auto paramLists = func->getParameterLists();
unsigned paramOffset = 1;
while (listIndex < paramLists.size()) {
auto currentList = paramLists[listIndex];
// If there is a parameter in this list, return it.
if (paramIndex + paramOffset < currentList->size()) {
return std::make_pair(listIndex, paramIndex + paramOffset);
}
// Move on to the next list.
++listIndex;
paramIndex = 0;
paramOffset = 0;
}
return None;
}
/// Determine whether the given parent is the accessor node for an abstract
/// storage declaration or is directly descended from it.
static bool parentDirectDescendedFromAbstractStorageDecl(
const ASTScope *parent,
const AbstractStorageDecl *decl) {
while (true) {
switch (parent->getKind()) {
case ASTScopeKind::Preexpanded:
case ASTScopeKind::AbstractFunctionDecl:
case ASTScopeKind::AbstractFunctionParams:
case ASTScopeKind::GenericParams:
// Keep looking.
parent = parent->getParent();
continue;
case ASTScopeKind::Accessors:
return (parent->getAbstractStorageDecl() == decl);
case ASTScopeKind::SourceFile:
case ASTScopeKind::TypeDecl:
case ASTScopeKind::ExtensionGenericParams:
case ASTScopeKind::TypeOrExtensionBody:
case ASTScopeKind::DefaultArgument:
case ASTScopeKind::AbstractFunctionBody:
case ASTScopeKind::PatternBinding:
case ASTScopeKind::PatternInitializer:
case ASTScopeKind::AfterPatternBinding:
case ASTScopeKind::BraceStmt:
case ASTScopeKind::ConditionalClause:
case ASTScopeKind::IfStmt:
case ASTScopeKind::GuardStmt:
case ASTScopeKind::RepeatWhileStmt:
case ASTScopeKind::ForEachStmt:
case ASTScopeKind::ForEachPattern:
case ASTScopeKind::DoCatchStmt:
case ASTScopeKind::CatchStmt:
case ASTScopeKind::SwitchStmt:
case ASTScopeKind::CaseStmt:
case ASTScopeKind::ForStmt:
case ASTScopeKind::ForStmtInitializer:
case ASTScopeKind::Closure:
case ASTScopeKind::TopLevelCode:
// Not a direct descendant.
return false;
}
}
}
/// Determine whether the given parent is the node for a specific abstract
/// function declaration or is directly descended from it.
static bool parentDirectDescendedFromAbstractFunctionDecl(
const ASTScope *parent,
const AbstractFunctionDecl *decl) {
while (true) {
switch (parent->getKind()) {
case ASTScopeKind::Preexpanded:
case ASTScopeKind::AbstractFunctionParams:
case ASTScopeKind::DefaultArgument:
case ASTScopeKind::AbstractFunctionBody:
case ASTScopeKind::GenericParams:
// Keep looking.
parent = parent->getParent();
continue;
case ASTScopeKind::AbstractFunctionDecl:
return (parent->getAbstractFunctionDecl() == decl);
case ASTScopeKind::SourceFile:
case ASTScopeKind::TypeDecl:
case ASTScopeKind::ExtensionGenericParams:
case ASTScopeKind::TypeOrExtensionBody:
case ASTScopeKind::PatternBinding:
case ASTScopeKind::PatternInitializer:
case ASTScopeKind::AfterPatternBinding:
case ASTScopeKind::Accessors:
case ASTScopeKind::BraceStmt:
case ASTScopeKind::ConditionalClause:
case ASTScopeKind::IfStmt:
case ASTScopeKind::GuardStmt:
case ASTScopeKind::RepeatWhileStmt:
case ASTScopeKind::ForEachStmt:
case ASTScopeKind::ForEachPattern:
case ASTScopeKind::DoCatchStmt:
case ASTScopeKind::CatchStmt:
case ASTScopeKind::SwitchStmt:
case ASTScopeKind::CaseStmt:
case ASTScopeKind::ForStmt:
case ASTScopeKind::ForStmtInitializer:
case ASTScopeKind::Closure:
case ASTScopeKind::TopLevelCode:
// Not a direct descendant.
return false;
}
}
}
/// Determine whether the given parent is the node for a specific type
/// declaration or is directly descended from it.
static bool parentDirectDescendedFromTypeDecl(const ASTScope *parent,
const TypeDecl *decl) {
while (true) {
switch (parent->getKind()) {
case ASTScopeKind::Preexpanded:
case ASTScopeKind::GenericParams:
// Keep looking.
parent = parent->getParent();
continue;
case ASTScopeKind::TypeDecl:
return (parent->getTypeDecl() == decl);
case ASTScopeKind::SourceFile:
case ASTScopeKind::AbstractFunctionDecl:
case ASTScopeKind::AbstractFunctionParams:
case ASTScopeKind::DefaultArgument:
case ASTScopeKind::AbstractFunctionBody:
case ASTScopeKind::ExtensionGenericParams:
case ASTScopeKind::TypeOrExtensionBody:
case ASTScopeKind::PatternBinding:
case ASTScopeKind::PatternInitializer:
case ASTScopeKind::AfterPatternBinding:
case ASTScopeKind::Accessors:
case ASTScopeKind::BraceStmt:
case ASTScopeKind::ConditionalClause:
case ASTScopeKind::IfStmt:
case ASTScopeKind::GuardStmt:
case ASTScopeKind::RepeatWhileStmt:
case ASTScopeKind::ForEachStmt:
case ASTScopeKind::ForEachPattern:
case ASTScopeKind::DoCatchStmt:
case ASTScopeKind::CatchStmt:
case ASTScopeKind::SwitchStmt:
case ASTScopeKind::CaseStmt:
case ASTScopeKind::ForStmt:
case ASTScopeKind::ForStmtInitializer:
case ASTScopeKind::Closure:
case ASTScopeKind::TopLevelCode:
// Not a direct descendant.
return false;
}
}
}
ASTScope *ASTScope::createIfNeeded(const ASTScope *parent, Decl *decl) {
if (!decl) return nullptr;
// Implicit declarations don't have source information for name lookup.
if (decl->isImplicit()) return nullptr;
// Accessors are always nested within their abstract storage declaration.
bool isAccessor = false;
if (auto func = dyn_cast<FuncDecl>(decl)) {
if (func->isAccessor()) {
isAccessor = true;
if (!parentDirectDescendedFromAbstractStorageDecl(
parent, func->getAccessorStorageDecl()))
return nullptr;
}
}
ASTContext &ctx = decl->getASTContext();
// If this is a type declaration for which we have not introduced a TypeDecl
// scope, add it now.
if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
if (!parentDirectDescendedFromTypeDecl(parent, typeDecl)) {
return new (ctx) ASTScope(parent, typeDecl);
}
}
// If this is a function declaration for which we have not introduced
// an AbstractFunctionDecl scope, add it now.
if (auto func = dyn_cast<AbstractFunctionDecl>(decl)) {
if (!parentDirectDescendedFromAbstractFunctionDecl(parent, func)) {
return new (ctx) ASTScope(ASTScopeKind::AbstractFunctionDecl, parent,
func);
}
}
// Local function to handle generic parameters.
auto nextGenericParam =
[&](GenericParamList *genericParams, Decl *decl) -> ASTScope * {
if (!genericParams) return nullptr;
unsigned index = (parent->getKind() == ASTScopeKind::GenericParams &&
parent->genericParams.decl == decl)
? parent->genericParams.index + 1
: 0;
if (index < genericParams->size())
return new (ctx) ASTScope(parent, genericParams, decl, index);
return nullptr;
};
// Create the inner scope.
switch (decl->getKind()) {
case DeclKind::Import:
case DeclKind::EnumCase:
case DeclKind::PrecedenceGroup:
case DeclKind::InfixOperator:
case DeclKind::PrefixOperator:
case DeclKind::PostfixOperator:
case DeclKind::GenericTypeParam:
case DeclKind::AssociatedType:
case DeclKind::Module:
case DeclKind::Param:
case DeclKind::EnumElement:
case DeclKind::IfConfig:
// These declarations do not introduce scopes.
return nullptr;
case DeclKind::Var:
// Always handled by a pattern-binding declaration.
return nullptr;
case DeclKind::Extension: {
auto ext = cast<ExtensionDecl>(decl);
// If we already have a scope of the (possible) generic parameters,
// add the body.
if (parent->getKind() == ASTScopeKind::ExtensionGenericParams)
return new (ctx) ASTScope(parent, cast<IterableDeclContext>(ext));
// Otherwise, form the extension's generic parameters scope.
return new (ctx) ASTScope(parent, ext);
}
case DeclKind::TopLevelCode:
if (!isRealTopLevelCodeDecl(decl)) return nullptr;
return new (ctx) ASTScope(parent, cast<TopLevelCodeDecl>(decl));
case DeclKind::Protocol:
cast<ProtocolDecl>(decl)->createGenericParamsIfMissing();
SWIFT_FALLTHROUGH;
case DeclKind::Class:
case DeclKind::Enum:
case DeclKind::Struct: {
auto nominal = cast<NominalTypeDecl>(decl);
// If we have a generic type and our parent isn't describing our generic
// parameters, build the generic parameter scope.
if (auto scope = nextGenericParam(nominal->getGenericParams(), nominal))
return scope;
return new (ctx) ASTScope(parent, cast<IterableDeclContext>(nominal));
}
case DeclKind::TypeAlias: {
// If we have a generic typealias and our parent isn't describing our
// generic parameters, build the generic parameter scope.
auto typeAlias = cast<TypeAliasDecl>(decl);
if (auto scope = nextGenericParam(typeAlias->getGenericParams(), typeAlias))
return scope;
// Typealiases don't introduce any other scopes.
return nullptr;
}
case DeclKind::Func:
case DeclKind::Constructor:
case DeclKind::Destructor: {
auto abstractFunction = cast<AbstractFunctionDecl>(decl);
// If we have a generic function and our parent isn't describing our generic
// parameters or function parameters, build the generic parameter scope.
if (parent->getKind() != ASTScopeKind::AbstractFunctionParams ||
parent->abstractFunctionParams.decl != decl) {
if (auto scope = nextGenericParam(abstractFunction->getGenericParams(),
abstractFunction))
return scope;
}
// Figure out which parameter is next is the next one down.
Optional<std::pair<unsigned, unsigned>> nextParameter;
if (parent->getKind() == ASTScopeKind::AbstractFunctionParams &&
parent->abstractFunctionParams.decl == decl) {
nextParameter =
findNextParameter(parent->abstractFunctionParams.decl,
parent->abstractFunctionParams.listIndex,
parent->abstractFunctionParams.paramIndex);
} else if (abstractFunction->getParameterList(0)->size() > 0) {