-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckStmt.cpp
3309 lines (2840 loc) · 114 KB
/
TypeCheckStmt.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
//===--- TypeCheckStmt.cpp - Type Checking for Statements -----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 semantic analysis for statements.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckDistributed.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "TypeCheckUnsafe.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTScope.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/DiagnosticSuppression.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Range.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/TopCollection.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/Timer.h"
#include <cmath>
#include <iterator>
using namespace swift;
#define DEBUG_TYPE "TypeCheckStmt"
namespace {
/// After forming autoclosures and lazy initializer getters, we must update
/// the DeclContexts for any AST nodes that store the DeclContext they're
/// within. This includes e.g closures and decls, as well as some other
/// expressions, statements, and patterns.
class ContextualizationWalker : public ASTWalker {
DeclContext *ParentDC;
ContextualizationWalker(DeclContext *parent) : ParentDC(parent) {}
public:
static void contextualize(ASTNode node, DeclContext *DC) {
node.walk(ContextualizationWalker(DC));
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
LazyInitializerWalking getLazyInitializerWalkingBehavior() override {
// Don't walk lazy initializers, we contextualize the getter body
// specially when synthesizing.
return LazyInitializerWalking::None;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (auto *CE = dyn_cast<AbstractClosureExpr>(E)) {
CE->setParent(ParentDC);
contextualize(CE->getBody(), CE);
TypeChecker::computeCaptures(CE);
return Action::SkipNode(E);
}
// Caller-side default arguments need their @autoclosures checked.
if (auto *DAE = dyn_cast<DefaultArgumentExpr>(E)) {
if (DAE->isCallerSide() &&
(DAE->getParamDecl()->isAutoClosure() ||
(DAE->getParamDecl()->getDefaultArgumentKind() ==
DefaultArgumentKind::ExpressionMacro)))
DAE->getCallerSideDefaultExpr()->walk(*this);
}
// Macro expansion expressions require a DeclContext as well.
if (auto macroExpansion = dyn_cast<MacroExpansionExpr>(E)) {
macroExpansion->setDeclContext(ParentDC);
}
return Action::Continue(E);
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *P) override {
// A couple of patterns store DeclContexts.
if (auto *EP = dyn_cast<ExprPattern>(P))
EP->setDeclContext(ParentDC);
if (auto *EP = dyn_cast<EnumElementPattern>(P))
EP->setDeclContext(ParentDC);
return Action::Continue(P);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
// The ASTWalker doesn't walk the case body variables, contextualize them
// ourselves.
if (auto *CS = dyn_cast<CaseStmt>(S)) {
for (auto *CaseVar : CS->getCaseBodyVariablesOrEmptyArray())
CaseVar->setDeclContext(ParentDC);
}
// A few statements store DeclContexts, update them.
if (auto *BS = dyn_cast<BreakStmt>(S))
BS->setDeclContext(ParentDC);
if (auto *CS = dyn_cast<ContinueStmt>(S))
CS->setDeclContext(ParentDC);
if (auto *FS = dyn_cast<FallthroughStmt>(S))
FS->setDeclContext(ParentDC);
return Action::Continue(S);
}
PreWalkAction walkToDeclPre(Decl *D) override {
// We may encounter some decls parented outside of a local context, e.g
// VarDecls in TopLevelCodeDecls are parented to the file. In such cases,
// assume the DeclContext they already have is correct, autoclosures
// and lazy var inits cannot be defined in such contexts anyway.
if (!D->getDeclContext()->isLocalContext())
return Action::SkipNode();
D->setDeclContext(ParentDC);
// Auxiliary decls need to have their contexts adjusted too.
if (auto *VD = dyn_cast<VarDecl>(D)) {
VD->visitAuxiliaryDecls([&](VarDecl *D) {
D->setDeclContext(ParentDC);
});
}
// We don't currently support peer macro declarations in local contexts,
// however we don't reject them either; so just to be safe, adjust their
// context too.
D->visitAuxiliaryDecls([&](Decl *D) {
D->setDeclContext(ParentDC);
});
// Only recurse into decls that aren't themselves DeclContexts. This
// allows us to visit e.g initializers for PatternBindingDecls and
// accessors for VarDecls.
return Action::SkipNodeIf(isa<DeclContext>(D));
}
};
/// Used for debugging which parts of the code are taking a long time to
/// compile.
class FunctionBodyTimer {
AnyFunctionRef Function;
llvm::TimeRecord StartTime = llvm::TimeRecord::getCurrentTime();
public:
FunctionBodyTimer(AnyFunctionRef Fn) : Function(Fn) {}
~FunctionBodyTimer() {
llvm::TimeRecord endTime = llvm::TimeRecord::getCurrentTime(false);
auto elapsed = endTime.getProcessTime() - StartTime.getProcessTime();
unsigned elapsedMS = static_cast<unsigned>(elapsed * 1000);
ASTContext &ctx = Function.getAsDeclContext()->getASTContext();
auto *AFD = Function.getAbstractFunctionDecl();
if (ctx.TypeCheckerOpts.DebugTimeFunctionBodies) {
// Round up to the nearest 100th of a millisecond.
llvm::errs() << llvm::format("%0.2f", std::ceil(elapsed * 100000) / 100) << "ms\t";
Function.getLoc().print(llvm::errs(), ctx.SourceMgr);
if (AFD) {
llvm::errs()
<< "\t" << Decl::getDescriptiveKindName(AFD->getDescriptiveKind())
<< " ";
AFD->dumpRef(llvm::errs());
} else {
llvm::errs() << "\t(closure)";
}
llvm::errs() << "\n";
}
const auto WarnLimit = ctx.TypeCheckerOpts.WarnLongFunctionBodies;
if (WarnLimit != 0 && elapsedMS >= WarnLimit) {
if (AFD) {
ctx.Diags.diagnose(AFD, diag::debug_long_function_body,
AFD, elapsedMS, WarnLimit);
} else {
ctx.Diags.diagnose(Function.getLoc(), diag::debug_long_closure_body,
elapsedMS, WarnLimit);
}
}
}
};
} // end anonymous namespace
void TypeChecker::contextualizeExpr(Expr *E, DeclContext *DC) {
ContextualizationWalker::contextualize(E, DC);
}
void TypeChecker::contextualizeTopLevelCode(TopLevelCodeDecl *TLCD) {
if (auto *body = TLCD->getBody())
ContextualizationWalker::contextualize(body, TLCD);
}
namespace {
/// Visitor that assigns local discriminators through whatever it walks.
class SetLocalDiscriminators : public ASTWalker {
/// The initial discriminator that everything starts with.
unsigned InitialDiscriminator;
// Next (explicit) closure discriminator.
unsigned NextClosureDiscriminator;
// Next autoclosure discriminator.
unsigned NextAutoclosureDiscriminator;
/// Local declaration discriminators.
llvm::SmallDenseMap<Identifier, unsigned> DeclDiscriminators;
public:
SetLocalDiscriminators(
unsigned initialDiscriminator = 0
) : InitialDiscriminator(initialDiscriminator),
NextClosureDiscriminator(initialDiscriminator),
NextAutoclosureDiscriminator(initialDiscriminator) { }
/// Determine the maximum discriminator assigned to any local.
unsigned maxAssignedDiscriminator() const {
unsigned result = std::max(
NextClosureDiscriminator, NextAutoclosureDiscriminator);
for (const auto &decl : DeclDiscriminators) {
result = std::max(result, decl.second);
}
return result;
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
// Autoclosures need to be numbered and potentially reparented.
// Reparenting is required with:
// - nested autoclosures, because the inner autoclosure will be
// parented to the outer context, not the outer autoclosure
// - non-local initializers
if (auto CE = dyn_cast<AutoClosureExpr>(E)) {
if (CE->getRawDiscriminator() != AutoClosureExpr::InvalidDiscriminator)
return Action::SkipNode(E);
assert(
CE->getRawDiscriminator() == AutoClosureExpr::InvalidDiscriminator);
CE->setDiscriminator(NextAutoclosureDiscriminator++);
// Recurse into the autoclosure body using the same sequence,
// but parenting to the autoclosure instead of the outer closure.
CE->getBody()->walk(*this);
return Action::SkipNode(E);
}
// Explicit closures start their own sequence.
if (auto CE = dyn_cast<ClosureExpr>(E)) {
if(CE->getRawDiscriminator() == ClosureExpr::InvalidDiscriminator)
CE->setDiscriminator(NextClosureDiscriminator++);
// We need to walk into closure bodies with a new sequence.
SetLocalDiscriminators innerVisitor;
if (auto params = CE->getParameters()) {
for (auto *param : *params) {
innerVisitor.setLocalDiscriminator(param);
}
}
CE->getBody()->walk(innerVisitor);
return Action::SkipNode(E);
}
// Caller-side default arguments need their @autoclosures checked.
if (auto *DAE = dyn_cast<DefaultArgumentExpr>(E))
if (DAE->isCallerSide() && DAE->getParamDecl()->isAutoClosure())
DAE->getCallerSideDefaultExpr()->walk(*this);
// Tap expression bodies have an $interpolation variable that doesn't
// normally get visited. Visit it specifically.
if (auto tap = dyn_cast<TapExpr>(E)) {
if (auto body = tap->getBody()) {
if (!body->empty()) {
if (auto decl = body->getFirstElement().dyn_cast<Decl *>()) {
if (auto var = dyn_cast<VarDecl>(decl))
if (var->getName() ==
var->getASTContext().Id_dollarInterpolation)
setLocalDiscriminator(var);
}
}
}
}
return Action::Continue(E);
}
/// We don't want to recurse into most local declarations.
PreWalkAction walkToDeclPre(Decl *D) override {
// If we have a local declaration, assign a local discriminator to it.
if (auto valueDecl = dyn_cast<ValueDecl>(D)) {
setLocalDiscriminator(valueDecl);
}
// But we do want to walk into the initializers of local
// variables.
return Action::VisitNodeIf(isa<PatternBindingDecl>(D));
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
if (auto caseStmt = dyn_cast<CaseStmt>(S)) {
for (auto var : caseStmt->getCaseBodyVariablesOrEmptyArray())
setLocalDiscriminator(var);
}
return Action::Continue(S);
}
/// Set the local discriminator for a named declaration.
void setLocalDiscriminator(ValueDecl *valueDecl) {
if (valueDecl->hasLocalDiscriminator()) {
if (valueDecl->getRawLocalDiscriminator() ==
ValueDecl::InvalidDiscriminator) {
// Assign the next discriminator.
Identifier name = valueDecl->getBaseIdentifier();
auto &discriminator = DeclDiscriminators[name];
if (discriminator < InitialDiscriminator)
discriminator = InitialDiscriminator;
valueDecl->setLocalDiscriminator(discriminator++);
} else {
// Assign the next discriminator.
Identifier name = valueDecl->getBaseIdentifier();
auto &discriminator = DeclDiscriminators[name];
discriminator = std::max(discriminator, std::max(InitialDiscriminator, valueDecl->getLocalDiscriminator() + 1));
}
}
// If this is a property wrapper, check for projected storage.
if (auto var = dyn_cast<VarDecl>(valueDecl)) {
if (auto auxVars = var->getPropertyWrapperAuxiliaryVariables()) {
if (auxVars.backingVar && auxVars.backingVar != var)
setLocalDiscriminator(auxVars.backingVar);
// If there is a projection variable, give it a local discriminator.
if (auxVars.projectionVar && auxVars.projectionVar != var) {
if (var->hasLocalDiscriminator() &&
var->getName() == auxVars.projectionVar->getName()) {
auxVars.projectionVar->setLocalDiscriminator(
var->getRawLocalDiscriminator());
} else {
setLocalDiscriminator(auxVars.projectionVar);
}
}
// For the wrapped local variable, adopt the same discriminator as
// the parameter. For all intents and purposes, these are the same.
if (auxVars.localWrappedValueVar &&
auxVars.localWrappedValueVar != var) {
if (var->hasLocalDiscriminator() &&
var->getName() == auxVars.localWrappedValueVar->getName()) {
auxVars.localWrappedValueVar->setLocalDiscriminator(
var->getRawLocalDiscriminator());
} else {
setLocalDiscriminator(
auxVars.localWrappedValueVar);
}
}
}
}
}
};
}
unsigned LocalDiscriminatorsRequest::evaluate(
Evaluator &evaluator, DeclContext *dc
) const {
ASTContext &ctx = dc->getASTContext();
// Autoclosures aren't their own contexts; look to the parent instead.
if (isa<AutoClosureExpr>(dc)) {
return evaluateOrDefault(evaluator,
LocalDiscriminatorsRequest{dc->getParent()}, 0);
}
ASTNode node;
ParameterList *params = nullptr;
ParamDecl *selfParam = nullptr;
if (auto func = dyn_cast<AbstractFunctionDecl>(dc)) {
if (!func->isBodySkipped())
node = func->getBody();
selfParam = func->getImplicitSelfDecl();
params = func->getParameters();
// Accessors for lazy properties should be walked as part of the property's
// pattern.
if (auto accessor = dyn_cast<AccessorDecl>(func)) {
if (accessor->isImplicit() &&
accessor->getStorage()->getAttrs().hasAttribute<LazyAttr>()) {
if (auto var = dyn_cast<VarDecl>(accessor->getStorage())) {
if (auto binding = var->getParentPatternBinding()) {
node = binding;
}
}
}
}
} else if (auto closure = dyn_cast<ClosureExpr>(dc)) {
node = closure->getBody();
params = closure->getParameters();
} else if (auto topLevel = dyn_cast<TopLevelCodeDecl>(dc)) {
node = topLevel->getBody();
dc = topLevel->getParentModule();
} else if (auto patternBindingInit = dyn_cast<PatternBindingInitializer>(dc)){
auto patternBinding = patternBindingInit->getBinding();
node = patternBinding->getInit(patternBindingInit->getBindingIndex());
} else if (auto defaultArgInit = dyn_cast<DefaultArgumentInitializer>(dc)) {
auto param = getParameterAt(
cast<ValueDecl>(dc->getParent()->getAsDecl()),
defaultArgInit->getIndex());
if (!param)
return 0;
node = param->getTypeCheckedDefaultExpr();
} else if (auto propertyWrapperInit =
dyn_cast<PropertyWrapperInitializer>(dc)) {
auto var = propertyWrapperInit->getWrappedVar();
auto initInfo = var->getPropertyWrapperInitializerInfo();
switch (propertyWrapperInit->getKind()) {
case PropertyWrapperInitializer::Kind::WrappedValue:
node = initInfo.getInitFromWrappedValue();
break;
case PropertyWrapperInitializer::Kind::ProjectedValue:
node = initInfo.getInitFromProjectedValue();
break;
}
} else {
params = getParameterList(dc);
}
auto startDiscriminator = ctx.getNextDiscriminator(dc);
if (!node && !params && !selfParam)
return startDiscriminator;
SetLocalDiscriminators visitor(startDiscriminator);
// Set local discriminator for the 'self' parameter.
if (selfParam)
visitor.setLocalDiscriminator(selfParam);
// Set local discriminators for the parameters, which might have property
// wrappers that need it.
if (params) {
for (auto *param : *params)
visitor.setLocalDiscriminator(param);
}
if (node)
node.walk(visitor);
unsigned nextDiscriminator = visitor.maxAssignedDiscriminator();
ctx.setMaxAssignedDiscriminator(dc, nextDiscriminator);
// Return the next discriminator.
return nextDiscriminator;
}
/// Emits an error with a fixit for the case of unnecessary cast over a
/// OptionSet value. The primary motivation is to help with SDK changes.
/// Example:
/// \code
/// func supported() -> MyMask {
/// return Int(MyMask.Bingo.rawValue)
/// }
/// \endcode
static void tryDiagnoseUnnecessaryCastOverOptionSet(ASTContext &Ctx,
Expr *E,
Type ResultType) {
auto *NTD = ResultType->getAnyNominal();
if (!NTD)
return;
auto optionSetType = dyn_cast_or_null<ProtocolDecl>(Ctx.getOptionSetDecl());
if (!optionSetType)
return;
if (!lookupConformance(ResultType, optionSetType))
return;
auto *CE = dyn_cast<CallExpr>(E);
if (!CE)
return;
if (!isa<ConstructorRefCallExpr>(CE->getFn()))
return;
auto *unaryArg = CE->getArgs()->getUnlabeledUnaryExpr();
if (!unaryArg)
return;
auto *ME = dyn_cast<MemberRefExpr>(unaryArg);
if (!ME)
return;
ValueDecl *VD = ME->getMember().getDecl();
if (!VD || VD->getBaseName() != Ctx.Id_rawValue)
return;
auto *BME = dyn_cast<MemberRefExpr>(ME->getBase());
if (!BME)
return;
if (!BME->getType()->isEqual(ResultType))
return;
Ctx.Diags.diagnose(E->getLoc(), diag::unnecessary_cast_over_optionset,
ResultType)
.highlight(E->getSourceRange())
.fixItRemoveChars(E->getLoc(), ME->getStartLoc())
.fixItRemove(SourceRange(ME->getDotLoc(), E->getEndLoc()));
}
/// Whether the given enclosing context is a "defer" body.
static bool isDefer(DeclContext *dc) {
if (auto *func = dyn_cast<FuncDecl>(dc))
return func->isDeferBody();
return false;
}
/// Climb the context to find the method or accessor we're within. We do not
/// look past local functions or closures, since those cannot contain a
/// discard statement.
/// \param dc the inner decl context containing the discard statement
/// \return either the type member we reside in, or the offending context that
/// stopped the search for the type member (e.g. closure).
static DeclContext *climbContextForDiscardStmt(DeclContext *dc) {
do {
if (auto decl = dc->getAsDecl()) {
auto func = dyn_cast<AbstractFunctionDecl>(decl);
// If we found a non-func decl, we're done.
if (func == nullptr)
break;
// If this function's parent is the type context, our search is done.
if (func->getDeclContext()->isTypeContext())
break;
// Only continue if we're in a defer. We want to stop at the first local
// function or closure.
if (!isDefer(dc))
break;
}
} while ((dc = dc->getParent()));
return dc;
}
/// Check that a labeled statement doesn't shadow another statement with the
/// same label.
static void checkLabeledStmtShadowing(
ASTContext &ctx, SourceFile *sourceFile, LabeledStmt *ls) {
auto name = ls->getLabelInfo().Name;
if (name.empty() || !sourceFile || ls->getStartLoc().isInvalid())
return;
auto activeLabeledStmtsVec = ASTScope::lookupLabeledStmts(
sourceFile, ls->getStartLoc());
auto activeLabeledStmts = llvm::ArrayRef(activeLabeledStmtsVec);
for (auto prevLS : activeLabeledStmts.slice(1)) {
if (prevLS->getLabelInfo().Name == name) {
ctx.Diags.diagnose(
ls->getLabelInfo().Loc, diag::label_shadowed, name);
ctx.Diags.diagnose(
prevLS->getLabelInfo().Loc, diag::invalid_redecl_prev_name, name);
}
}
}
static void
emitUnresolvedLabelDiagnostics(DiagnosticEngine &DE,
SourceLoc targetLoc, Identifier targetName,
TopCollection<unsigned, LabeledStmt *> corrections) {
// If an unresolved label was used, but we have a single correction,
// produce the specific diagnostic and fixit.
if (corrections.size() == 1) {
DE.diagnose(targetLoc, diag::unresolved_label_corrected,
targetName, corrections.begin()->Value->getLabelInfo().Name)
.highlight(SourceRange(targetLoc))
.fixItReplace(SourceRange(targetLoc),
corrections.begin()->Value->getLabelInfo().Name.str());
DE.diagnose(corrections.begin()->Value->getLabelInfo().Loc,
diag::name_declared_here,
corrections.begin()->Value->getLabelInfo().Name);
} else {
// If we have multiple corrections or none, produce a generic diagnostic
// and all corrections available.
DE.diagnose(targetLoc, diag::unresolved_label, targetName)
.highlight(SourceRange(targetLoc));
for (auto &entry : corrections)
DE.diagnose(entry.Value->getLabelInfo().Loc, diag::note_typo_candidate,
entry.Value->getLabelInfo().Name.str())
.fixItReplace(SourceRange(targetLoc),
entry.Value->getLabelInfo().Name.str());
}
}
/// Find the target of a break or continue statement without a label.
///
/// \returns the target, if one was found, or \c nullptr if no such target
/// exists.
static LabeledStmt *findUnlabeledBreakOrContinueStmtTarget(
ASTContext &ctx, SourceFile *sourceFile, SourceLoc loc,
bool isContinue, DeclContext *dc,
ArrayRef<LabeledStmt *> activeLabeledStmts) {
for (auto labeledStmt : activeLabeledStmts) {
// 'break' with no label looks through non-loop structures
// except 'switch'.
// 'continue' ignores non-loop structures.
if (!labeledStmt->requiresLabelOnJump() &&
(!isContinue || labeledStmt->isPossibleContinueTarget())) {
return labeledStmt;
}
}
// If we're in a defer, produce a tailored diagnostic.
if (isDefer(dc)) {
ctx.Diags.diagnose(
loc, diag::jump_out_of_defer, isContinue ? "continue": "break");
return nullptr;
}
// If we're dealing with an unlabeled break inside of an 'if' or 'do'
// statement, produce a more specific error.
if (!isContinue &&
llvm::any_of(activeLabeledStmts,
[&](Stmt *S) -> bool {
return isa<IfStmt>(S) || isa<DoStmt>(S);
})) {
ctx.Diags.diagnose(
loc, diag::unlabeled_break_outside_loop);
return nullptr;
}
// Otherwise produce a generic error.
ctx.Diags.diagnose(
loc,
isContinue ? diag::continue_outside_loop : diag::break_outside_loop);
return nullptr;
}
/// Find the target of a break or continue statement.
///
/// \returns the target, if one was found, or \c nullptr if no such target
/// exists.
LabeledStmt *swift::findBreakOrContinueStmtTarget(
ASTContext &ctx, SourceFile *sourceFile,
SourceLoc loc, Identifier targetName, SourceLoc targetLoc,
bool isContinue, DeclContext *dc) {
// Retrieve the active set of labeled statements.
SmallVector<LabeledStmt *, 4> activeLabeledStmts;
activeLabeledStmts = ASTScope::lookupLabeledStmts(sourceFile, loc);
// Handle an unlabeled break separately; that's the easy case.
if (targetName.empty()) {
return findUnlabeledBreakOrContinueStmtTarget(
ctx, sourceFile, loc, isContinue, dc, activeLabeledStmts);
}
// Scan inside out until we find something with the right label.
TopCollection<unsigned, LabeledStmt *> labelCorrections(3);
for (auto labeledStmt : activeLabeledStmts) {
if (targetName == labeledStmt->getLabelInfo().Name) {
// Continue cannot be used to repeat switches, use fallthrough instead.
if (isContinue && !labeledStmt->isPossibleContinueTarget()) {
ctx.Diags.diagnose(
loc, diag::continue_not_in_this_stmt,
isa<SwitchStmt>(labeledStmt) ? "switch" : "if");
return nullptr;
}
return labeledStmt;
}
unsigned distance =
TypeChecker::getCallEditDistance(
DeclNameRef(targetName),
labeledStmt->getLabelInfo().Name,
TypeChecker::UnreasonableCallEditDistance);
if (distance < TypeChecker::UnreasonableCallEditDistance)
labelCorrections.insert(distance, std::move(labeledStmt));
}
labelCorrections.filterMaxScoreRange(
TypeChecker::MaxCallEditDistanceFromBestCandidate);
// If we're in a defer, produce a tailored diagnostic.
if (isDefer(dc)) {
ctx.Diags.diagnose(
loc, diag::jump_out_of_defer, isContinue ? "continue": "break");
return nullptr;
}
// Provide potential corrections for an incorrect label.
emitUnresolvedLabelDiagnostics(
ctx.Diags, targetLoc, targetName, labelCorrections);
return nullptr;
}
LabeledStmt *
BreakTargetRequest::evaluate(Evaluator &evaluator, const BreakStmt *BS) const {
auto *DC = BS->getDeclContext();
return findBreakOrContinueStmtTarget(
DC->getASTContext(), DC->getParentSourceFile(), BS->getLoc(),
BS->getTargetName(), BS->getTargetLoc(), /*isContinue*/ false, DC);
}
LabeledStmt *
ContinueTargetRequest::evaluate(Evaluator &evaluator,
const ContinueStmt *CS) const {
auto *DC = CS->getDeclContext();
return findBreakOrContinueStmtTarget(
DC->getASTContext(), DC->getParentSourceFile(), CS->getLoc(),
CS->getTargetName(), CS->getTargetLoc(), /*isContinue*/ true, DC);
}
FallthroughSourceAndDest
FallthroughSourceAndDestRequest::evaluate(Evaluator &evaluator,
const FallthroughStmt *FS) const {
auto *SF = FS->getDeclContext()->getParentSourceFile();
auto &ctx = SF->getASTContext();
auto loc = FS->getLoc();
auto [src, dest] = ASTScope::lookupFallthroughSourceAndDest(SF, loc);
if (!src) {
ctx.Diags.diagnose(loc, diag::fallthrough_outside_switch);
return {};
}
if (!dest) {
ctx.Diags.diagnose(loc, diag::fallthrough_from_last_case);
return {};
}
return {src, dest};
}
static Expr *getDeclRefProvidingExpressionForHasSymbol(Expr *E) {
// Strip coercions, which are necessary in source to disambiguate overloaded
// functions or generic functions, e.g.
//
// if #_hasSymbol(foo as () -> ()) { ... }
//
if (auto CE = dyn_cast<CoerceExpr>(E))
return getDeclRefProvidingExpressionForHasSymbol(CE->getSubExpr());
// Unwrap curry thunks which are injected into the AST to wrap some forms of
// unapplied method references, e.g.
//
// if #_hasSymbol(SomeStruct.foo(_:)) { ... }
//
if (auto ACE = dyn_cast<AutoClosureExpr>(E))
return getDeclRefProvidingExpressionForHasSymbol(
ACE->getUnwrappedCurryThunkExpr());
// Drill into the function expression for a DotSyntaxCallExpr. These sometimes
// wrap or are wrapped by an AutoClosureExpr.
//
// if #_hasSymbol(someStruct.foo(_:)) { ... }
//
if (auto DSCE = dyn_cast<DotSyntaxCallExpr>(E))
return getDeclRefProvidingExpressionForHasSymbol(DSCE->getFn());
return E;
}
ConcreteDeclRef TypeChecker::getReferencedDeclForHasSymbolCondition(Expr *E) {
// Match DotSelfExprs (e.g. `SomeStruct.self`) when the type is static.
if (auto DSE = dyn_cast<DotSelfExpr>(E)) {
if (DSE->isStaticallyDerivedMetatype())
return DSE->getType()->getMetatypeInstanceType()->getAnyNominal();
}
if (auto declRefExpr = getDeclRefProvidingExpressionForHasSymbol(E)) {
if (auto CDR = declRefExpr->getReferencedDecl())
return CDR;
}
return ConcreteDeclRef();
}
static bool typeCheckHasSymbolStmtConditionElement(StmtConditionElement &elt,
DeclContext *dc) {
auto Info = elt.getHasSymbolInfo();
auto E = Info->getSymbolExpr();
if (!E)
return false;
auto exprTy = TypeChecker::typeCheckExpression(E, dc);
Info->setSymbolExpr(E);
if (!exprTy) {
Info->setInvalid();
return true;
}
Info->setReferencedDecl(
TypeChecker::getReferencedDeclForHasSymbolCondition(E));
return false;
}
static bool typeCheckBooleanStmtConditionElement(StmtConditionElement &elt,
DeclContext *dc) {
Expr *E = elt.getBoolean();
assert(!E->getType() && "the bool condition is already type checked");
bool hadError = TypeChecker::typeCheckCondition(E, dc);
elt.setBoolean(E);
return hadError;
}
static bool
typeCheckPatternBindingStmtConditionElement(StmtConditionElement &elt,
bool &isFalsable, DeclContext *dc) {
auto &Context = dc->getASTContext();
// This is cleanup goop run on the various paths where type checking of the
// pattern binding fails.
auto typeCheckPatternFailed = [&] {
elt.getPattern()->setType(ErrorType::get(Context));
elt.getInitializer()->setType(ErrorType::get(Context));
elt.getPattern()->forEachVariable([&](VarDecl *var) {
// Don't change the type of a variable that we've been able to
// compute a type for.
if (var->hasInterfaceType() && !var->isInvalid())
return;
var->setInvalid();
});
};
// Resolve the pattern.
assert(!elt.getPattern()->hasType() &&
"the pattern binding condition is already type checked");
auto *pattern = TypeChecker::resolvePattern(elt.getPattern(), dc,
/*isStmtCondition*/ true);
if (!pattern) {
typeCheckPatternFailed();
return true;
}
elt.setPattern(pattern);
// Check the pattern, it allows unspecified types because the pattern can
// provide type information.
auto contextualPattern = ContextualPattern::forRawPattern(pattern, dc);
Type patternType = TypeChecker::typeCheckPattern(contextualPattern);
if (patternType->hasError()) {
typeCheckPatternFailed();
return true;
}
// If the pattern didn't get a type, it's because we ran into some
// unknown types along the way. We'll need to check the initializer.
auto init = elt.getInitializer();
bool hadError = TypeChecker::typeCheckBinding(pattern, init, dc, patternType);
elt.setPattern(pattern);
elt.setInitializer(init);
isFalsable |= pattern->isRefutablePattern();
return hadError;
}
bool TypeChecker::typeCheckStmtConditionElement(StmtConditionElement &elt,
bool &isFalsable,
DeclContext *dc) {
switch (elt.getKind()) {
case StmtConditionElement::CK_Availability:
isFalsable = true;
return false;
case StmtConditionElement::CK_HasSymbol:
isFalsable = true;
return typeCheckHasSymbolStmtConditionElement(elt, dc);
case StmtConditionElement::CK_Boolean:
isFalsable = true;
return typeCheckBooleanStmtConditionElement(elt, dc);
case StmtConditionElement::CK_PatternBinding:
return typeCheckPatternBindingStmtConditionElement(elt, isFalsable, dc);
}
}
/// Type check the given 'if', 'while', or 'guard' statement condition.
///
/// \param stmt The conditional statement to type-check, which will be modified
/// in place.
///
/// \returns true if an error occurred, false otherwise.
static bool typeCheckConditionForStatement(LabeledConditionalStmt *stmt,
DeclContext *dc) {
bool hadError = false;
bool hadAnyFalsable = false;
auto cond = stmt->getCond();
for (auto &elt : cond) {
hadError |=
TypeChecker::typeCheckStmtConditionElement(elt, hadAnyFalsable, dc);
}
// If the binding is not refutable, and there *is* an else, reject it as
// unreachable.
if (!hadAnyFalsable && !hadError) {
auto &diags = dc->getASTContext().Diags;
Diag<> msg = diag::invalid_diagnostic;
switch (stmt->getKind()) {
case StmtKind::If:
msg = diag::if_always_true;
break;
case StmtKind::While:
msg = diag::while_always_true;
break;
case StmtKind::Guard:
msg = diag::guard_always_succeeds;
break;
default:
llvm_unreachable("unknown LabeledConditionalStmt kind");
}
diags.diagnose(cond[0].getStartLoc(), msg);
}
stmt->setCond(cond);
return false;
}
/// Check the correctness of a 'fallthrough' statement.
///
/// \returns true if an error occurred.
bool swift::checkFallthroughStmt(FallthroughStmt *FS) {
auto &ctx = FS->getDeclContext()->getASTContext();
auto *caseBlock = FS->getFallthroughDest();
auto *previousBlock = FS->getFallthroughSource();
if (!previousBlock || !caseBlock)
return true;
// Verify that the pattern bindings for the cases that we're falling through
// from and to are equivalent.
auto firstPattern = caseBlock->getCaseLabelItems()[0].getPattern();
SmallVector<VarDecl *, 4> vars;
firstPattern->collectVariables(vars);
// We know that the typechecker has already guaranteed that all of
// the case label items in the fallthrough have the same var
// decls. So if we match against the case body var decls,
// transitively we will match all of the other case label items in
// the fallthrough destination as well.
auto previousVars = previousBlock->getCaseBodyVariablesOrEmptyArray();
for (auto *expected : vars) {
bool matched = false;
if (!expected->hasName())
continue;
for (auto *previous : previousVars) {
if (!previous->hasName() ||
expected->getName() != previous->getName()) {
continue;
}
if (!previous->getTypeInContext()->isEqual(expected->getTypeInContext())) {
ctx.Diags.diagnose(
previous->getLoc(), diag::type_mismatch_fallthrough_pattern_list,
previous->getTypeInContext(), expected->getTypeInContext());
previous->setInvalid();
expected->setInvalid();
}
// Ok, we found our match. Make the previous fallthrough statement var
// decl our parent var decl.
expected->setParentVarDecl(previous);
matched = true;
break;
}
if (!matched) {