forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeChecker.cpp
2337 lines (1956 loc) · 83.8 KB
/
TypeChecker.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
//===--- TypeChecker.cpp - Type Checking ----------------------------------===//
//
// 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the swift::performTypeChecking entry point for
// semantic analysis.
//
//===----------------------------------------------------------------------===//
#include "swift/Subsystems.h"
#include "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Attr.h"
#include "swift/AST/ExprHandle.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/TypeRefinementContext.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/Timer.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Strings.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/ADT/Twine.h"
#include <algorithm>
using namespace swift;
TypeChecker::TypeChecker(ASTContext &Ctx, DiagnosticEngine &Diags)
: Context(Ctx), Diags(Diags)
{
auto clangImporter =
static_cast<ClangImporter *>(Context.getClangModuleLoader());
clangImporter->setTypeResolver(*this);
Context.setLazyResolver(this);
}
TypeChecker::~TypeChecker() {
auto clangImporter =
static_cast<ClangImporter *>(Context.getClangModuleLoader());
clangImporter->clearTypeResolver();
Context.setLazyResolver(nullptr);
}
void TypeChecker::handleExternalDecl(Decl *decl) {
if (auto SD = dyn_cast<StructDecl>(decl)) {
addImplicitConstructors(SD);
addImplicitStructConformances(SD);
}
if (auto CD = dyn_cast<ClassDecl>(decl)) {
addImplicitDestructor(CD);
}
if (auto ED = dyn_cast<EnumDecl>(decl)) {
addImplicitEnumConformances(ED);
}
}
ProtocolDecl *TypeChecker::getProtocol(SourceLoc loc, KnownProtocolKind kind) {
auto protocol = Context.getProtocol(kind);
if (!protocol && loc.isValid()) {
diagnose(loc, diag::missing_protocol,
Context.getIdentifier(getProtocolName(kind)));
}
if (protocol && !protocol->hasType()) {
validateDecl(protocol);
if (protocol->isInvalid())
return nullptr;
}
return protocol;
}
ProtocolDecl *TypeChecker::getLiteralProtocol(Expr *expr) {
if (isa<ArrayExpr>(expr))
return getProtocol(expr->getLoc(),
KnownProtocolKind::ArrayLiteralConvertible);
if (isa<DictionaryExpr>(expr))
return getProtocol(expr->getLoc(),
KnownProtocolKind::DictionaryLiteralConvertible);
if (!isa<LiteralExpr>(expr))
return nullptr;
if (isa<NilLiteralExpr>(expr))
return getProtocol(expr->getLoc(),
KnownProtocolKind::NilLiteralConvertible);
if (isa<IntegerLiteralExpr>(expr))
return getProtocol(expr->getLoc(),
KnownProtocolKind::IntegerLiteralConvertible);
if (isa<FloatLiteralExpr>(expr))
return getProtocol(expr->getLoc(),
KnownProtocolKind::FloatLiteralConvertible);
if (isa<BooleanLiteralExpr>(expr))
return getProtocol(expr->getLoc(),
KnownProtocolKind::BooleanLiteralConvertible);
if (const auto *SLE = dyn_cast<StringLiteralExpr>(expr)) {
if (SLE->isSingleUnicodeScalar())
return getProtocol(
expr->getLoc(),
KnownProtocolKind::UnicodeScalarLiteralConvertible);
if (SLE->isSingleExtendedGraphemeCluster())
return getProtocol(
expr->getLoc(),
KnownProtocolKind::ExtendedGraphemeClusterLiteralConvertible);
return getProtocol(expr->getLoc(),
KnownProtocolKind::StringLiteralConvertible);
}
if (isa<InterpolatedStringLiteralExpr>(expr))
return getProtocol(expr->getLoc(),
KnownProtocolKind::StringInterpolationConvertible);
if (auto E = dyn_cast<MagicIdentifierLiteralExpr>(expr)) {
switch (E->getKind()) {
case MagicIdentifierLiteralExpr::File:
case MagicIdentifierLiteralExpr::Function:
return getProtocol(expr->getLoc(),
KnownProtocolKind::StringLiteralConvertible);
case MagicIdentifierLiteralExpr::Line:
case MagicIdentifierLiteralExpr::Column:
return getProtocol(expr->getLoc(),
KnownProtocolKind::IntegerLiteralConvertible);
case MagicIdentifierLiteralExpr::DSOHandle:
return nullptr;
}
}
if (auto E = dyn_cast<ObjectLiteralExpr>(expr)) {
Identifier name = E->getName();
if (name.str().equals("Color")) {
return getProtocol(expr->getLoc(),
KnownProtocolKind::ColorLiteralConvertible);
} else if (name.str().equals("Image")) {
return getProtocol(expr->getLoc(),
KnownProtocolKind::ImageLiteralConvertible);
} else if (name.str().equals("FileReference")) {
return getProtocol(expr->getLoc(),
KnownProtocolKind::FileReferenceLiteralConvertible);
} else {
return nullptr;
}
}
return nullptr;
}
DeclName TypeChecker::getObjectLiteralConstructorName(ObjectLiteralExpr *expr) {
Identifier name = expr->getName();
if (name.str().equals("Color")) {
return DeclName(Context, Context.Id_init,
{ Context.getIdentifier("colorLiteralRed"),
Context.getIdentifier("green"),
Context.getIdentifier("blue"),
Context.getIdentifier("alpha") });
} else if (name.str().equals("Image")) {
return DeclName(Context, Context.Id_init,
{ Context.getIdentifier("imageLiteral") });
} else if (name.str().equals("FileReference")) {
return DeclName(Context, Context.Id_init,
{ Context.getIdentifier("fileReferenceLiteral") });
} else {
return DeclName();
}
}
Module *TypeChecker::getStdlibModule(const DeclContext *dc) {
if (StdlibModule)
return StdlibModule;
if (!StdlibModule)
StdlibModule = Context.getStdlibModule();
if (!StdlibModule)
StdlibModule = dc->getParentModule();
assert(StdlibModule && "no main module found");
Context.recordKnownProtocols(StdlibModule);
return StdlibModule;
}
Type TypeChecker::lookupBoolType(const DeclContext *dc) {
if (!boolType) {
boolType = ([&] {
SmallVector<ValueDecl *, 2> results;
getStdlibModule(dc)->lookupValue({}, Context.getIdentifier("Bool"),
NLKind::QualifiedLookup, results);
if (results.size() != 1) {
diagnose(SourceLoc(), diag::bool_type_broken);
return Type();
}
auto tyDecl = dyn_cast<TypeDecl>(results.front());
if (!tyDecl) {
diagnose(SourceLoc(), diag::bool_type_broken);
return Type();
}
return tyDecl->getDeclaredType();
})();
}
return *boolType;
}
namespace swift {
/// Clone the given generic parameters in the given list. We don't need any
/// of the requirements, because they will be inferred.
GenericParamList *cloneGenericParams(ASTContext &ctx,
DeclContext *dc,
GenericParamList *fromParams,
GenericParamList *outerParams) {
// Clone generic parameters.
SmallVector<GenericTypeParamDecl *, 2> toGenericParams;
for (auto fromGP : *fromParams) {
// Create the new generic parameter.
auto toGP = new (ctx) GenericTypeParamDecl(dc, fromGP->getName(),
SourceLoc(),
fromGP->getDepth(),
fromGP->getIndex());
toGP->setImplicit(true);
// Record new generic parameter.
toGenericParams.push_back(toGP);
}
auto toParams = GenericParamList::create(ctx, SourceLoc(), toGenericParams,
SourceLoc());
toParams->setOuterParameters(outerParams);
return toParams;
}
}
// FIXME: total hack
GenericParamList *createProtocolGenericParams(ASTContext &ctx,
ProtocolDecl *proto,
DeclContext *dc);
static void bindExtensionDecl(ExtensionDecl *ED, TypeChecker &TC) {
if (ED->getExtendedType())
return;
// If we didn't parse a type, fill in an error type and bail out.
if (!ED->getExtendedTypeLoc().getTypeRepr()) {
ED->setInvalid();
ED->getExtendedTypeLoc().setInvalidType(TC.Context);
return;
}
auto dc = ED->getDeclContext();
// Validate the representation.
// FIXME: Perform some kind of "shallow" validation here?
TypeResolutionOptions options;
options |= TR_AllowUnboundGenerics;
options |= TR_ExtensionBinding;
if (TC.validateType(ED->getExtendedTypeLoc(), dc, options)) {
ED->setInvalid();
return;
}
// Dig out the extended type.
auto extendedType = ED->getExtendedType();
// Handle easy cases.
// Cannot extend a metatype.
if (extendedType->is<AnyMetatypeType>()) {
TC.diagnose(ED->getLoc(), diag::extension_metatype, extendedType)
.highlight(ED->getExtendedTypeLoc().getSourceRange());
ED->setInvalid();
ED->getExtendedTypeLoc().setInvalidType(TC.Context);
return;
}
// Cannot extend a bound generic type.
if (extendedType->isSpecialized() && extendedType->getAnyNominal()) {
TC.diagnose(ED->getLoc(), diag::extension_specialization,
extendedType->getAnyNominal()->getName())
.highlight(ED->getExtendedTypeLoc().getSourceRange());
ED->setInvalid();
ED->getExtendedTypeLoc().setInvalidType(TC.Context);
return;
}
// Dig out the nominal type being extended.
NominalTypeDecl *extendedNominal = extendedType->getAnyNominal();
if (!extendedNominal) {
TC.diagnose(ED->getLoc(), diag::non_nominal_extension, extendedType)
.highlight(ED->getExtendedTypeLoc().getSourceRange());
ED->setInvalid();
ED->getExtendedTypeLoc().setInvalidType(TC.Context);
return;
}
assert(extendedNominal && "Should have the nominal type being extended");
// If the extended type is generic or is a protocol. Clone or create
// the generic parameters.
if (extendedNominal->getGenericParams()) {
if (auto proto = dyn_cast<ProtocolDecl>(extendedNominal)) {
// For a protocol extension, build the generic parameter list.
ED->setGenericParams(proto->createGenericParams(ED));
} else {
// Clone the existing generic parameter list.
ED->setGenericParams(
cloneGenericParams(TC.Context, ED,
extendedNominal->getGenericParams(),
nullptr));
}
}
// If we have a trailing where clause, deal with it now.
// For now, trailing where clauses are only permitted on protocol extensions.
if (auto trailingWhereClause = ED->getTrailingWhereClause()) {
if (!extendedNominal->getGenericParams()) {
// Only generic and protocol types are permitted to have
// trailing where clauses.
TC.diagnose(ED, diag::extension_nongeneric_trailing_where, extendedType)
.highlight(trailingWhereClause->getSourceRange());
ED->setTrailingWhereClause(nullptr);
} else {
// Merge the trailing where clause into the generic parameter list.
// FIXME: Long-term, we'd like clients to deal with the trailing where
// clause explicitly, but for now it's far more direct to represent
// the trailing where clause as part of the requirements.
ED->getGenericParams()->addTrailingWhereClause(
TC.Context,
trailingWhereClause->getWhereLoc(),
trailingWhereClause->getRequirements());
}
}
extendedNominal->addExtension(ED);
}
static void typeCheckFunctionsAndExternalDecls(TypeChecker &TC) {
unsigned currentFunctionIdx = 0;
unsigned currentExternalDef = TC.Context.LastCheckedExternalDefinition;
do {
// Type check the body of each of the function in turn. Note that outside
// functions must be visited before nested functions for type-checking to
// work correctly.
for (unsigned n = TC.definedFunctions.size(); currentFunctionIdx != n;
++currentFunctionIdx) {
auto *AFD = TC.definedFunctions[currentFunctionIdx];
// HACK: don't type-check the same function body twice. This is
// supposed to be handled by just not enqueuing things twice,
// but that gets tricky with synthesized function bodies.
if (AFD->isBodyTypeChecked()) continue;
PrettyStackTraceDecl StackEntry("type-checking", AFD);
TC.typeCheckAbstractFunctionBody(AFD);
AFD->setBodyTypeCheckedIfPresent();
}
for (unsigned n = TC.Context.ExternalDefinitions.size();
currentExternalDef != n;
++currentExternalDef) {
auto decl = TC.Context.ExternalDefinitions[currentExternalDef];
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(decl)) {
// HACK: don't type-check the same function body twice. This is
// supposed to be handled by just not enqueuing things twice,
// but that gets tricky with synthesized function bodies.
if (AFD->isBodyTypeChecked()) continue;
PrettyStackTraceDecl StackEntry("type-checking", AFD);
TC.typeCheckAbstractFunctionBody(AFD);
continue;
}
if (isa<NominalTypeDecl>(decl)) {
TC.handleExternalDecl(decl);
continue;
}
if (isa<VarDecl>(decl))
continue;
llvm_unreachable("Unhandled external definition kind");
}
// Validate the contents of any referenced nominal types for SIL's purposes.
// Note: if we ever start putting extension members in vtables, we'll need
// to validate those members too.
// FIXME: If we're not planning to run SILGen, this is wasted effort.
while (!TC.ValidatedTypes.empty()) {
auto nominal = TC.ValidatedTypes.pop_back_val();
if (nominal->isInvalid() || TC.Context.hadError())
continue;
Optional<bool> lazyVarsAlreadyHaveImplementation;
for (auto *D : nominal->getMembers()) {
auto VD = dyn_cast<ValueDecl>(D);
if (!VD)
continue;
TC.validateDecl(VD);
// The only thing left to do is synthesize storage for lazy variables.
// We only have to do that if it's a type from another file, though.
// In NDEBUG builds, bail out as soon as we can.
#ifdef NDEBUG
if (lazyVarsAlreadyHaveImplementation.hasValue() &&
lazyVarsAlreadyHaveImplementation.getValue())
continue;
#endif
auto *prop = dyn_cast<VarDecl>(D);
if (!prop)
continue;
if (prop->getAttrs().hasAttribute<LazyAttr>() && !prop->isStatic()
&& prop->getGetter()) {
bool hasImplementation = prop->getGetter()->hasBody();
if (lazyVarsAlreadyHaveImplementation.hasValue()) {
assert(lazyVarsAlreadyHaveImplementation.getValue() ==
hasImplementation &&
"only some lazy vars already have implementations");
} else {
lazyVarsAlreadyHaveImplementation = hasImplementation;
}
if (!hasImplementation)
TC.completeLazyVarImplementation(prop);
}
}
// FIXME: We need to add implicit initializers and dtors when a decl is
// touched, because it affects vtable layout. If you're not defining the
// class, you shouldn't have to know what the vtable layout is.
if (auto *CD = dyn_cast<ClassDecl>(nominal)) {
TC.addImplicitConstructors(CD);
TC.addImplicitDestructor(CD);
}
}
// Complete any conformances that we used.
for (unsigned i = 0; i != TC.UsedConformances.size(); ++i) {
auto conformance = TC.UsedConformances[i];
if (conformance->isIncomplete())
TC.checkConformance(conformance);
}
TC.UsedConformances.clear();
} while (currentFunctionIdx < TC.definedFunctions.size() ||
currentExternalDef < TC.Context.ExternalDefinitions.size() ||
!TC.UsedConformances.empty());
// FIXME: Horrible hack. Store this somewhere more sane.
TC.Context.LastCheckedExternalDefinition = currentExternalDef;
// Compute captures for functions and closures we visited.
for (AnyFunctionRef closure : TC.ClosuresWithUncomputedCaptures) {
TC.computeCaptures(closure);
}
for (AbstractFunctionDecl *FD : reversed(TC.definedFunctions)) {
TC.computeCaptures(FD);
}
// Check error-handling correctness for all the functions defined in
// this file. This can depend on all of their interior function
// bodies having been type-checked.
for (AbstractFunctionDecl *FD : TC.definedFunctions) {
TC.checkFunctionErrorHandling(FD);
}
for (auto decl : TC.Context.ExternalDefinitions) {
if (auto fn = dyn_cast<AbstractFunctionDecl>(decl)) {
TC.checkFunctionErrorHandling(fn);
}
}
}
void swift::typeCheckExternalDefinitions(SourceFile &SF) {
assert(SF.ASTStage == SourceFile::TypeChecked);
auto &Ctx = SF.getASTContext();
TypeChecker TC(Ctx);
typeCheckFunctionsAndExternalDecls(TC);
}
void swift::performTypeChecking(SourceFile &SF, TopLevelContext &TLC,
OptionSet<TypeCheckingFlags> Options,
unsigned StartElem) {
if (SF.ASTStage == SourceFile::TypeChecked)
return;
// Make sure that name binding has been completed before doing any type
// checking.
{
SharedTimer timer("Name binding");
performNameBinding(SF, StartElem);
}
auto &Ctx = SF.getASTContext();
{
// NOTE: The type checker is scoped to be torn down before AST
// verification.
TypeChecker TC(Ctx);
SharedTimer timer("Type checking / Semantic analysis");
if (Options.contains(TypeCheckingFlags::DebugTimeFunctionBodies))
TC.enableDebugTimeFunctionBodies();
if (Options.contains(TypeCheckingFlags::ForImmediateMode))
TC.setInImmediateMode(true);
// Lookup the swift module. This ensures that we record all known
// protocols in the AST.
(void) TC.getStdlibModule(&SF);
if (!Ctx.LangOpts.DisableAvailabilityChecking) {
// Build the type refinement hierarchy for the primary
// file before type checking.
TC.buildTypeRefinementContextHierarchy(SF, StartElem);
}
// Resolve extensions. This has to occur first during type checking,
// because the extensions need to be wired into the AST for name lookup
// to work.
// FIXME: We can have interesting ordering dependencies among the various
// extensions, so we'll need to be smarter here.
// FIXME: The current source file needs to be handled specially, because of
// private extensions.
SF.forAllVisibleModules([&](Module::ImportedModule import) {
// FIXME: Respect the access path?
for (auto file : import.second->getFiles()) {
auto SF = dyn_cast<SourceFile>(file);
if (!SF)
continue;
for (auto D : SF->Decls) {
if (auto ED = dyn_cast<ExtensionDecl>(D))
bindExtensionDecl(ED, TC);
}
}
});
// FIXME: Check for cycles in class inheritance here?
// Type check the top-level elements of the source file.
for (auto D : llvm::makeArrayRef(SF.Decls).slice(StartElem)) {
if (isa<TopLevelCodeDecl>(D))
continue;
TC.typeCheckDecl(D, /*isFirstPass*/true);
}
// At this point, we can perform general name lookup into any type.
// We don't know the types of all the global declarations in the first
// pass, which means we can't completely analyze everything. Perform the
// second pass now.
bool hasTopLevelCode = false;
for (auto D : llvm::makeArrayRef(SF.Decls).slice(StartElem)) {
if (TopLevelCodeDecl *TLCD = dyn_cast<TopLevelCodeDecl>(D)) {
hasTopLevelCode = true;
// Immediately perform global name-binding etc.
TC.typeCheckTopLevelCodeDecl(TLCD);
} else {
TC.typeCheckDecl(D, /*isFirstPass*/false);
}
}
if (hasTopLevelCode) {
TC.contextualizeTopLevelCode(TLC,
llvm::makeArrayRef(SF.Decls).slice(StartElem));
}
// If we're in REPL mode, inject temporary result variables and other stuff
// that the REPL needs to synthesize.
if (SF.Kind == SourceFileKind::REPL && !TC.Context.hadError())
TC.processREPLTopLevel(SF, TLC, StartElem);
typeCheckFunctionsAndExternalDecls(TC);
}
// Checking that benefits from having the whole module available.
if (!(Options & TypeCheckingFlags::DelayWholeModuleChecking)) {
performWholeModuleTypeChecking(SF);
}
// Verify that we've checked types correctly.
SF.ASTStage = SourceFile::TypeChecked;
{
SharedTimer timer("AST verification");
// Verify the SourceFile.
verify(SF);
// Verify imported modules.
#ifndef NDEBUG
if (SF.Kind != SourceFileKind::REPL &&
!Ctx.LangOpts.DebuggerSupport) {
Ctx.verifyAllLoadedModules();
}
#endif
}
}
void swift::finishTypeChecking(SourceFile &SF) {
auto &Ctx = SF.getASTContext();
TypeChecker TC(Ctx);
for (auto D : SF.Decls)
if (auto PD = dyn_cast<ProtocolDecl>(D))
TC.inferDefaultWitnesses(PD);
}
void swift::performWholeModuleTypeChecking(SourceFile &SF) {
auto &Ctx = SF.getASTContext();
Ctx.diagnoseAttrsRequiringFoundation(SF);
Ctx.diagnoseObjCMethodConflicts(SF);
Ctx.diagnoseObjCUnsatisfiedOptReqConflicts(SF);
Ctx.diagnoseUnintendedObjCMethodOverrides(SF);
}
bool swift::performTypeLocChecking(ASTContext &Ctx, TypeLoc &T,
bool isSILType, DeclContext *DC,
bool ProduceDiagnostics) {
TypeResolutionOptions options;
// Fine to have unbound generic types.
options |= TR_AllowUnboundGenerics;
if (isSILType)
options |= TR_SILType;
if (ProduceDiagnostics) {
return TypeChecker(Ctx).validateType(T, DC, options);
} else {
// Set up a diagnostics engine that swallows diagnostics.
DiagnosticEngine Diags(Ctx.SourceMgr);
return TypeChecker(Ctx, Diags).validateType(T, DC, options);
}
}
/// Expose TypeChecker's handling of GenericParamList to SIL parsing.
GenericSignature *swift::handleSILGenericParams(ASTContext &Ctx,
GenericParamList *genericParams,
DeclContext *DC) {
return TypeChecker(Ctx).handleSILGenericParams(genericParams, DC);
}
bool swift::typeCheckCompletionDecl(Decl *D) {
auto &Ctx = D->getASTContext();
// Set up a diagnostics engine that swallows diagnostics.
DiagnosticEngine Diags(Ctx.SourceMgr);
TypeChecker TC(Ctx, Diags);
TC.typeCheckDecl(D, true);
return true;
}
bool swift::isConvertibleTo(Type Ty1, Type Ty2, DeclContext &DC) {
auto &Ctx = DC.getASTContext();
// We try to reuse the type checker associated with the ast context first.
if (Ctx.getLazyResolver()) {
TypeChecker *TC = static_cast<TypeChecker*>(Ctx.getLazyResolver());
return TC->isConvertibleTo(Ty1, Ty2, &DC);
} else {
DiagnosticEngine Diags(Ctx.SourceMgr);
return (new TypeChecker(Ctx, Diags))->isConvertibleTo(Ty1, Ty2, &DC);
}
}
Type swift::lookUpTypeInContext(DeclContext *DC, StringRef Name) {
auto &Ctx = DC->getASTContext();
auto ReturnResult = [](UnqualifiedLookup &Lookup) {
if (auto Result = Lookup.getSingleTypeResult())
return Result->getDeclaredType();
return Type();
};
if (Ctx.getLazyResolver()) {
UnqualifiedLookup Lookup(DeclName(Ctx.getIdentifier(Name)), DC,
Ctx.getLazyResolver(), false, SourceLoc(), true);
return ReturnResult(Lookup);
} else {
DiagnosticEngine Diags(Ctx.SourceMgr);
LazyResolver *Resolver = new TypeChecker(Ctx, Diags);
UnqualifiedLookup Lookup(DeclName(Ctx.getIdentifier(Name)), DC,
Resolver, false, SourceLoc(), true);
return ReturnResult(Lookup);
}
}
static Optional<Type> getTypeOfCompletionContextExpr(TypeChecker &TC,
DeclContext *DC,
Expr *&parsedExpr) {
CanType originalType = parsedExpr->getType().getCanonicalTypeOrNull();
if (auto T = TC.getTypeOfExpressionWithoutApplying(parsedExpr, DC,
FreeTypeVariableBinding::GenericParameters))
return T;
// Try to recover if we've made any progress.
if (parsedExpr && !isa<ErrorExpr>(parsedExpr) && parsedExpr->getType() &&
!parsedExpr->getType()->is<ErrorType>() &&
parsedExpr->getType().getCanonicalTypeOrNull() != originalType) {
return parsedExpr->getType();
}
return None;
}
/// \brief Return the type of an expression parsed during code completion, or
/// a null \c Type on error.
Optional<Type> swift::getTypeOfCompletionContextExpr(ASTContext &Ctx,
DeclContext *DC,
Expr *&parsedExpr) {
if (Ctx.getLazyResolver()) {
TypeChecker *TC = static_cast<TypeChecker *>(Ctx.getLazyResolver());
return ::getTypeOfCompletionContextExpr(*TC, DC, parsedExpr);
} else {
// Set up a diagnostics engine that swallows diagnostics.
DiagnosticEngine diags(Ctx.SourceMgr);
TypeChecker TC(Ctx, diags);
// Try to solve for the actual type of the expression.
return ::getTypeOfCompletionContextExpr(TC, DC, parsedExpr);
}
}
bool swift::typeCheckCompletionSequence(DeclContext *DC, Expr *&parsedExpr) {
auto &ctx = DC->getASTContext();
if (ctx.getLazyResolver()) {
TypeChecker *TC = static_cast<TypeChecker *>(ctx.getLazyResolver());
return TC->typeCheckCompletionSequence(parsedExpr, DC);
} else {
// Set up a diagnostics engine that swallows diagnostics.
DiagnosticEngine diags(ctx.SourceMgr);
TypeChecker TC(ctx, diags);
return TC.typeCheckCompletionSequence(parsedExpr, DC);
}
}
bool swift::typeCheckExpression(DeclContext *DC, Expr *&parsedExpr) {
auto &ctx = DC->getASTContext();
if (ctx.getLazyResolver()) {
TypeChecker *TC = static_cast<TypeChecker *>(ctx.getLazyResolver());
return TC->typeCheckExpression(parsedExpr, DC);
} else {
// Set up a diagnostics engine that swallows diagnostics.
DiagnosticEngine diags(ctx.SourceMgr);
TypeChecker TC(ctx, diags);
return TC.typeCheckExpression(parsedExpr, DC);
}
}
bool swift::typeCheckAbstractFunctionBodyUntil(AbstractFunctionDecl *AFD,
SourceLoc EndTypeCheckLoc) {
auto &Ctx = AFD->getASTContext();
// Set up a diagnostics engine that swallows diagnostics.
DiagnosticEngine Diags(Ctx.SourceMgr);
TypeChecker TC(Ctx, Diags);
return !TC.typeCheckAbstractFunctionBodyUntil(AFD, EndTypeCheckLoc);
}
bool swift::typeCheckTopLevelCodeDecl(TopLevelCodeDecl *TLCD) {
auto &Ctx = static_cast<Decl *>(TLCD)->getASTContext();
// Set up a diagnostics engine that swallows diagnostics.
DiagnosticEngine Diags(Ctx.SourceMgr);
TypeChecker TC(Ctx, Diags);
TC.typeCheckTopLevelCodeDecl(TLCD);
return true;
}
static void deleteTypeCheckerAndDiags(LazyResolver *resolver) {
DiagnosticEngine &diags = static_cast<TypeChecker*>(resolver)->Diags;
delete resolver;
delete &diags;
}
OwnedResolver swift::createLazyResolver(ASTContext &Ctx) {
auto diags = new DiagnosticEngine(Ctx.SourceMgr);
return OwnedResolver(new TypeChecker(Ctx, *diags),
&deleteTypeCheckerAndDiags);
}
void TypeChecker::diagnoseAmbiguousMemberType(Type baseTy,
SourceRange baseRange,
Identifier name,
SourceLoc nameLoc,
LookupTypeResult &lookup) {
if (auto moduleTy = baseTy->getAs<ModuleType>()) {
diagnose(nameLoc, diag::ambiguous_module_type, name,
moduleTy->getModule()->getName())
.highlight(baseRange);
} else {
diagnose(nameLoc, diag::ambiguous_member_type, name, baseTy)
.highlight(baseRange);
}
for (const auto &member : lookup) {
diagnose(member.first, diag::found_candidate_type,
member.second);
}
}
/// Returns the first availability attribute on the declaration that is active
/// on the target platform.
static const AvailableAttr *getActiveAvailableAttribute(const Decl *D,
ASTContext &AC) {
for (auto Attr : D->getAttrs())
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (!AvAttr->isInvalid() && AvAttr->isActivePlatform(AC)) {
return AvAttr;
}
}
return nullptr;
}
/// Returns true if there is any availability attribute on the declaration
/// that is active on the target platform.
static bool hasActiveAvailableAttribute(Decl *D,
ASTContext &AC) {
return getActiveAvailableAttribute(D, AC);
}
namespace {
/// A class to walk the AST to build the type refinement context hierarchy.
class TypeRefinementContextBuilder : private ASTWalker {
struct ContextInfo {
TypeRefinementContext *TRC;
/// The node whose end marks the end of the refinement context.
/// If the builder sees this node in a post-visitor, it will pop
/// the context from the stack. This node can be null (ParentTy()),
/// indicating that custom logic elsewhere will handle removing
/// the context when needed.
ParentTy ScopeNode;
};
std::vector<ContextInfo> ContextStack;
TypeChecker &TC;
/// A mapping from abstract storage declarations with accessors to
/// to the type refinement contexts for those declarations. We refer to
/// this map to determine the appropriate parent TRC to use when
/// walking the accessor function.
llvm::DenseMap<AbstractStorageDecl *, TypeRefinementContext *>
StorageContexts;
TypeRefinementContext *getCurrentTRC() {
return ContextStack.back().TRC;
}
void pushContext(TypeRefinementContext *TRC, ParentTy PopAfterNode) {
ContextInfo Info;
Info.TRC = TRC;
Info.ScopeNode = PopAfterNode;
ContextStack.push_back(Info);
}
public:
TypeRefinementContextBuilder(TypeRefinementContext *TRC, TypeChecker &TC)
: TC(TC) {
assert(TRC);
pushContext(TRC, ParentTy());
}
void build(Decl *D) {
unsigned StackHeight = ContextStack.size();
D->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
void build(Stmt *S) {
unsigned StackHeight = ContextStack.size();
S->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
void build(Expr *E) {
unsigned StackHeight = ContextStack.size();
E->walk(*this);
assert(ContextStack.size() == StackHeight);
(void)StackHeight;
}
private:
virtual bool walkToDeclPre(Decl *D) override {
TypeRefinementContext *DeclTRC = getNewContextForWalkOfDecl(D);
if (DeclTRC) {
pushContext(DeclTRC, D);
}
return true;
}
virtual bool walkToDeclPost(Decl *D) override {
if (ContextStack.back().ScopeNode.getAsDecl() == D) {
ContextStack.pop_back();
}
return true;
}
/// Returns a new context to be introduced for the declaration, or nullptr
/// if no new context should be introduced.
TypeRefinementContext *getNewContextForWalkOfDecl(Decl *D) {
if (auto FD = dyn_cast<FuncDecl>(D)) {
if (FD->isAccessor()) {
// Use TRC of the storage rather the current TRC when walking this
// function.
auto it = StorageContexts.find(FD->getAccessorStorageDecl());
if (it != StorageContexts.end()) {
return it->second;
}
}
}
if (declarationIntroducesNewContext(D)) {
return buildDeclarationRefinementContext(D);
}
return nullptr;
}
/// Builds the type refinement hierarchy for the body of the function.
TypeRefinementContext *buildDeclarationRefinementContext(Decl *D) {
// We require a valid range in order to be able to query for the TRC
// corresponding to a given SourceLoc.
// If this assert fires, it means we have probably synthesized an implicit
// declaration without location information. The appropriate fix is
// probably to gin up a source range for the declaration when synthesizing
// it.
assert(D->getSourceRange().isValid());
// The potential versions in the declaration are constrained by both
// the declared availability of the declaration and the potential versions
// of its lexical context.
AvailabilityContext DeclInfo =
swift::AvailabilityInference::availableRange(D, TC.Context);
DeclInfo.intersectWith(getCurrentTRC()->getAvailabilityInfo());
TypeRefinementContext *NewTRC =
TypeRefinementContext::createForDecl(TC.Context, D, getCurrentTRC(),
DeclInfo,
refinementSourceRangeForDecl(D));
// Record the TRC for this storage declaration so that
// when we process the accessor, we can use this TRC as the
// parent.
if (auto *StorageDecl = dyn_cast<AbstractStorageDecl>(D)) {
if (StorageDecl->hasAccessorFunctions()) {
StorageContexts[StorageDecl] = NewTRC;
}
}
return NewTRC;
}
/// Returns true if the declaration should introduce a new refinement context.
bool declarationIntroducesNewContext(Decl *D) {
if (!isa<ValueDecl>(D) && !isa<ExtensionDecl>(D)) {
return false;
}
// No need to introduce a context if the declaration does not have an
// availability attribute.
if (!hasActiveAvailableAttribute(D, TC.Context)) {
return false;
}
// Only introduce for an AbstractStorageDecl if it is not local.