-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckType.cpp
3343 lines (2857 loc) · 121 KB
/
TypeCheckType.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
//===--- TypeCheckType.cpp - Type Validation ------------------------------===//
//
// 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 validation for Swift types, emitting semantic errors as
// appropriate and checking default initializer values.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "GenericTypeResolver.h"
#include "MiscDiagnostics.h"
#include "swift/Strings.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ExprHandle.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/TypeLoc.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
using namespace swift;
GenericTypeResolver::~GenericTypeResolver() { }
Type TypeChecker::getArraySliceType(SourceLoc loc, Type elementType) {
if (!Context.getArrayDecl()) {
diagnose(loc, diag::sugar_type_not_found, 0);
return Type();
}
return ArraySliceType::get(elementType);
}
Type TypeChecker::getDictionaryType(SourceLoc loc, Type keyType,
Type valueType) {
if (!Context.getDictionaryDecl()) {
diagnose(loc, diag::sugar_type_not_found, 3);
return Type();
}
return DictionaryType::get(keyType, valueType);
}
Type TypeChecker::getOptionalType(SourceLoc loc, Type elementType) {
if (!Context.getOptionalDecl()) {
diagnose(loc, diag::sugar_type_not_found, 1);
return Type();
}
return OptionalType::get(elementType);
}
Type TypeChecker::getImplicitlyUnwrappedOptionalType(SourceLoc loc, Type elementType) {
if (!Context.getImplicitlyUnwrappedOptionalDecl()) {
diagnose(loc, diag::sugar_type_not_found, 2);
return Type();
}
return ImplicitlyUnwrappedOptionalType::get(elementType);
}
static Type getStdlibType(TypeChecker &TC, Type &cached, DeclContext *dc,
StringRef name) {
if (cached.isNull()) {
Module *stdlib = TC.Context.getStdlibModule();
LookupTypeResult lookup = TC.lookupMemberType(dc, ModuleType::get(stdlib),
TC.Context.getIdentifier(
name));
if (lookup)
cached = lookup.back().second;
}
return cached;
}
Type TypeChecker::getStringType(DeclContext *dc) {
return ::getStdlibType(*this, StringType, dc, "String");
}
Type TypeChecker::getInt8Type(DeclContext *dc) {
return ::getStdlibType(*this, Int8Type, dc, "Int8");
}
Type TypeChecker::getUInt8Type(DeclContext *dc) {
return ::getStdlibType(*this, UInt8Type, dc, "UInt8");
}
/// Find the standard type of exceptions.
///
/// We call this the "exception type" to try to avoid confusion with
/// the AST's ErrorType node.
Type TypeChecker::getExceptionType(DeclContext *dc, SourceLoc loc) {
if (NominalTypeDecl *decl = Context.getErrorDecl())
return decl->getDeclaredType();
// Not really sugar, but the actual diagnostic text is fine.
diagnose(loc, diag::sugar_type_not_found, 4);
return Type();
}
static Type getObjectiveCNominalType(TypeChecker &TC,
Type &cache,
Identifier ModuleName,
Identifier TypeName,
DeclContext *dc) {
if (cache)
return cache;
auto &Context = TC.Context;
// FIXME: Does not respect visibility of the module.
Module *module = Context.getLoadedModule(ModuleName);
if (!module)
return nullptr;
NameLookupOptions lookupOptions
= defaultMemberLookupOptions |
NameLookupFlags::KnownPrivate |
NameLookupFlags::OnlyTypes;
if (auto result = TC.lookupMember(dc, ModuleType::get(module), TypeName,
lookupOptions)) {
for (auto decl : result) {
if (auto nominal = dyn_cast<NominalTypeDecl>(decl.Decl)) {
cache = nominal->getDeclaredType();
return cache;
}
}
}
return nullptr;
}
Type TypeChecker::getNSObjectType(DeclContext *dc) {
return getObjectiveCNominalType(*this, NSObjectType, Context.Id_ObjectiveC,
Context.getSwiftId(
KnownFoundationEntity::NSObject),
dc);
}
Type TypeChecker::getNSErrorType(DeclContext *dc) {
return getObjectiveCNominalType(*this, NSObjectType, Context.Id_Foundation,
Context.getSwiftId(
KnownFoundationEntity::NSError),
dc);
}
Type TypeChecker::getObjCSelectorType(DeclContext *dc) {
return getObjectiveCNominalType(*this, ObjCSelectorType,
Context.Id_ObjectiveC,
Context.Id_Selector,
dc);
}
Type TypeChecker::getBridgedToObjC(const DeclContext *dc, Type type) {
if (auto bridged = Context.getBridgedToObjC(dc, type, this))
return *bridged;
return nullptr;
}
Type
TypeChecker::getDynamicBridgedThroughObjCClass(DeclContext *dc,
Type dynamicType,
Type valueType) {
// We can only bridge from class or Objective-C existential types.
if (!dynamicType->isObjCExistentialType() &&
!dynamicType->getClassOrBoundGenericClass())
return Type();
// If the value type cannot be bridged, we're done.
if (!valueType->isPotentiallyBridgedValueType())
return Type();
return getBridgedToObjC(dc, valueType);
}
void TypeChecker::forceExternalDeclMembers(NominalTypeDecl *nominalDecl) {
// Force any delayed members added to the nominal type declaration.
if (nominalDecl->hasDelayedMembers()) {
this->handleExternalDecl(nominalDecl);
nominalDecl->setHasDelayedMembers(false);
}
}
Type TypeChecker::resolveTypeInContext(
TypeDecl *typeDecl,
DeclContext *fromDC,
TypeResolutionOptions options,
bool isSpecialized,
GenericTypeResolver *resolver,
UnsatisfiedDependency *unsatisfiedDependency) {
PartialGenericTypeToArchetypeResolver defaultResolver(*this);
if (!resolver)
resolver = &defaultResolver;
// If we have a callback to report dependencies, do so.
if (unsatisfiedDependency &&
(*unsatisfiedDependency)(requestResolveTypeDecl(typeDecl)))
return Type();
// If we found a generic parameter, map to the archetype if there is one.
if (auto genericParam = dyn_cast<GenericTypeParamDecl>(typeDecl)) {
return resolver->resolveGenericTypeParamType(
genericParam->getDeclaredType()->castTo<GenericTypeParamType>());
}
auto nominalType = dyn_cast<NominalTypeDecl>(typeDecl);
if (nominalType && (!nominalType->getGenericParams() || !isSpecialized)) {
forceExternalDeclMembers(nominalType);
} else {
nominalType = nullptr;
}
// Walk up through the type scopes to find the context containing the type
// being resolved.
auto ownerDC = typeDecl->getDeclContext();
bool nonTypeOwner = !ownerDC->isTypeContext();
auto ownerNominal = ownerDC->getAsNominalTypeOrNominalTypeExtensionContext();
// We might have an invalid extension that didn't resolve.
if (ownerNominal == nullptr && ownerDC->isExtensionContext()) {
assert(cast<ExtensionDecl>(ownerDC)->isInvalid());
return ErrorType::get(Context);
}
auto assocType = dyn_cast<AssociatedTypeDecl>(typeDecl);
assert((ownerNominal || nonTypeOwner) &&
"Owner must be a nominal type or a non type context");
// If true, we could not resolve some types, so we did not visit all
// relevant contexts.
bool incomplete = false;
for (auto parentDC = fromDC; !parentDC->isModuleContext();
parentDC = parentDC->getParent()) {
// If we are referring to a type within its own context, and we have either
// a generic type with no generic arguments or a non-generic type, use the
// type within the context.
if (nominalType) {
if (parentDC->getAsNominalTypeOrNominalTypeExtensionContext() == nominalType)
return resolver->resolveTypeOfContext(parentDC);
if (!parentDC->isModuleScopeContext() && !isa<TopLevelCodeDecl>(parentDC))
continue;
// If we didn't find a matching declaration, the iteration is restarted
// but we won't look anymore for the specific nominal type declaration
parentDC = fromDC;
nominalType = nullptr;
}
if (nonTypeOwner) {
// If this is a typealias not in type context, we still need the
// interface type; the typealias might be in a function context, and
// its underlying type might reference outer generic parameters.
if (isa<TypeAliasDecl>(typeDecl))
return resolver->resolveTypeOfDecl(typeDecl);
// When a nominal type used outside its context, return the unbound
// generic form of the type.
assert(isa<NominalTypeDecl>(typeDecl) || isa<ModuleDecl>(typeDecl));
return typeDecl->getDeclaredType();
}
// For the next steps we need our parentDC to be a type context
if (!parentDC->isTypeContext())
continue;
// Search the type of this context and its supertypes (if its a
// class) or refined protocols (if its a protocol).
llvm::SmallPtrSet<const NominalTypeDecl *, 8> visited;
llvm::SmallVector<Type, 8> stack;
// Start with the type of the current context.
auto fromType = resolver->resolveTypeOfContext(parentDC);
if (!fromType || fromType->is<ErrorType>())
incomplete = true;
else
stack.push_back(fromType);
// If we are in a protocol extension there might be other type aliases and
// nominal types brought into the context through requirements on Self,
// for example:
//
// extension MyProtocol where Self : YourProtocol { ... }
if (parentDC->getAsProtocolExtensionContext()) {
auto ED = cast<ExtensionDecl>(parentDC);
if (auto genericParams = ED->getGenericParams()) {
for (auto req : genericParams->getTrailingRequirements()) {
// We might be resolving 'req.getSubject()' itself.
// This whole case feels like a hack -- there should be a
// more principled way to represent extensions of protocol
// compositions.
if (req.getKind() == RequirementReprKind::TypeConstraint) {
if (!req.getSubject() ||
!req.getSubject()->is<ArchetypeType>() ||
!req.getSubject()->castTo<ArchetypeType>()->getSelfProtocol())
continue;
stack.push_back(req.getConstraint());
}
}
}
}
while (!stack.empty()) {
auto fromType = stack.back();
auto *fromProto = parentDC->getAsProtocolOrProtocolExtensionContext();
stack.pop_back();
// If we hit circularity, we will diagnose at some point in typeCheckDecl().
// However we have to explicitly guard against that here because we get
// called as part of validateDecl().
if (!visited.insert(fromType->getAnyNominal()).second)
continue;
// Handle this case:
// - Current context: concrete type
// - Nested type: associated type
// - Nested type's context: protocol or protocol extension
//
if (!fromProto &&
ownerNominal->getAsProtocolOrProtocolExtensionContext()) {
ProtocolConformance *conformance = nullptr;
// If the conformance check failed, the associated type is for a
// conformance of an outer context.
if (!options.contains(TR_InheritanceClause) &&
conformsToProtocol(fromType,
cast<ProtocolDecl>(ownerNominal),
parentDC, ConformanceCheckFlags::Used,
&conformance) &&
conformance) {
if (assocType) {
return conformance->getTypeWitness(assocType, this).getReplacement();
}
return substMemberTypeWithBase(parentDC->getParentModule(), typeDecl,
fromType, /*isTypeReference=*/true);
}
}
// Handle these cases:
// - Current context: concrete type
// - Nested type: concrete type or type alias
// - Nested type's context: concrete type
//
// - Current context: protocol or protocol extension
// - Nested type: type alias
// - Nested type's context: protocol or protocol extension
//
// Note: this is not supported yet, FIXME:
// - Current context: concrete type
// - Nested type: type alias
// - Nested type's context: protocol or protocol extension
//
if (fromType->getAnyNominal() == ownerNominal) {
if (fromProto &&
ownerNominal->getAsProtocolOrProtocolExtensionContext()) {
// If we are looking up an associated type or a protocol's type alias
// from a protocol or protocol extension, use the archetype for 'Self'
// instead of the existential type.
assert(fromType->is<ProtocolType>());
auto selfType = parentDC->getSelfInterfaceType();
if (!selfType)
return ErrorType::get(Context);
fromType = resolver->resolveGenericTypeParamType(
selfType->castTo<GenericTypeParamType>());
if (assocType) {
// Odd special case, ask Doug to explain it over pizza one day
if (fromType->isTypeParameter())
return resolver->resolveSelfAssociatedType(
fromType, parentDC, assocType);
}
}
return substMemberTypeWithBase(parentDC->getParentModule(), typeDecl,
fromType, /*isTypeReference=*/true);
}
if (auto superclassTy = getSuperClassOf(fromType))
stack.push_back(superclassTy);
else if (auto protoTy = fromType->getAs<ProtocolType>()) {
for (auto *proto : protoTy->getDecl()->getInheritedProtocols(this))
if (auto refinedTy = proto->getDeclaredTypeInContext())
stack.push_back(refinedTy);
}
}
}
assert(incomplete && "Should have found type by now");
return ErrorType::get(Context);
}
Type TypeChecker::applyGenericArguments(Type type, TypeDecl *decl,
SourceLoc loc, DeclContext *dc,
GenericIdentTypeRepr *generic,
bool isGenericSignature,
GenericTypeResolver *resolver) {
if (type->is<ErrorType>()) {
generic->setInvalid();
return type;
}
// We must either have an unbound generic type, or a generic type alias.
if (!type->is<UnboundGenericType>() &&
!(isa<TypeAliasDecl>(decl) &&
cast<TypeAliasDecl>(decl)->getGenericParams())) {
auto diag = diagnose(loc, diag::not_a_generic_type, type);
// Don't add fixit on module type; that isn't the right type regardless
// of whether it had generic arguments.
if (!type->is<ModuleType>())
diag.fixItRemove(generic->getAngleBrackets());
generic->setInvalid();
return type;
}
// If we have a non-generic type alias, we have an unbound generic type.
// Grab the decl from the unbound generic type.
//
// The idea is if you write:
//
// typealias Foo = Bar.Baz
//
// Then 'Foo<Int>' applies arguments to Bar.Baz, whereas if you write:
//
// typealias Foo<T> = Bar.Baz<T>
//
// Then 'Foo<Int>' applies arguments to Foo itself.
//
if (isa<TypeAliasDecl>(decl) &&
!cast<TypeAliasDecl>(decl)->getGenericParams()) {
decl = type->castTo<UnboundGenericType>()->getDecl();
}
// Make sure we have the right number of generic arguments.
// FIXME: If we have fewer arguments than we need, that might be okay, if
// we're allowed to deduce the remaining arguments from context.
auto genericDecl = cast<GenericTypeDecl>(decl);
auto genericArgs = generic->getGenericArgs();
auto genericParams = genericDecl->getGenericParams();
if (genericParams->size() != genericArgs.size()) {
diagnose(loc, diag::type_parameter_count_mismatch, decl->getName(),
genericParams->size(), genericArgs.size(),
genericArgs.size() < genericParams->size())
.highlight(generic->getAngleBrackets());
diagnose(decl, diag::generic_type_declared_here,
decl->getName());
return nullptr;
}
SmallVector<TypeLoc, 8> args;
for (auto tyR : genericArgs)
args.push_back(tyR);
return applyUnboundGenericArguments(type, genericDecl, loc, dc, args,
isGenericSignature, resolver);
}
/// Apply generic arguments to the given type.
Type TypeChecker::applyUnboundGenericArguments(
Type type, GenericTypeDecl *decl, SourceLoc loc, DeclContext *dc,
MutableArrayRef<TypeLoc> genericArgs, bool isGenericSignature,
GenericTypeResolver *resolver) {
assert(genericArgs.size() == decl->getGenericParams()->size() &&
"invalid arguments, use applyGenericArguments for diagnostic emitting");
// Make sure we always have a resolver to use.
PartialGenericTypeToArchetypeResolver defaultResolver(*this);
if (!resolver)
resolver = &defaultResolver;
TypeResolutionOptions options;
if (isGenericSignature)
options |= TR_GenericSignature;
// Validate the generic arguments and capture just the types.
SmallVector<Type, 4> genericArgTypes;
for (auto &genericArg : genericArgs) {
// Validate the generic argument.
if (validateType(genericArg, dc, options, resolver))
return nullptr;
genericArgTypes.push_back(genericArg.getType());
}
// If we're completing a generic TypeAlias, then we map the types provided
// onto the underlying type.
if (auto *TAD = dyn_cast<TypeAliasDecl>(decl)) {
auto signature = TAD->getGenericSignature();
TypeSubstitutionMap subs;
for (unsigned i = 0, e = genericArgs.size(); i < e; i++) {
auto t = signature->getInnermostGenericParams()[i];
subs[t->getCanonicalType().getPointer()] = genericArgs[i].getType();
}
if (auto outerSig = TAD->getDeclContext()->getGenericSignatureOfContext()) {
for (auto outerParam : outerSig->getGenericParams()) {
subs[outerParam->getCanonicalType().getPointer()] =
ArchetypeBuilder::mapTypeIntoContext(TAD->getDeclContext(),
outerParam);
}
}
// FIXME: Change callers to pass the right type in for generic typealiases
if (type->is<UnboundGenericType>() || isa<NameAliasType>(type.getPointer())) {
type = ArchetypeBuilder::mapTypeOutOfContext(TAD, TAD->getUnderlyingType());
}
type = type.subst(dc->getParentModule(), subs, None);
// FIXME: return a SubstitutedType to preserve the fact that
// we resolved a generic TypeAlias, for availability diagnostics.
// A better fix might be to introduce a BoundGenericAliasType
// which desugars as appropriate.
return SubstitutedType::get(TAD->getDeclaredType(), type, Context);
}
// Form the bound generic type.
auto *UGT = type->castTo<UnboundGenericType>();
auto *BGT = BoundGenericType::get(cast<NominalTypeDecl>(decl),
UGT->getParent(), genericArgTypes);
// Check protocol conformance.
if (!BGT->hasTypeParameter() && !BGT->hasTypeVariable()) {
SourceLoc noteLoc = decl->getLoc();
if (noteLoc.isInvalid())
noteLoc = loc;
// FIXME: Record that we're checking substitutions, so we can't end up
// with infinite recursion.
// Collect the complete set of generic arguments.
SmallVector<Type, 4> scratch;
ArrayRef<Type> allGenericArgs = BGT->getAllGenericArgs(scratch);
// Check the generic arguments against the generic signature.
auto genericSig = decl->getGenericSignature();
if (!decl->hasType() || decl->isValidatingGenericSignature()) {
diagnose(loc, diag::recursive_requirement_reference);
return nullptr;
}
assert(genericSig != nullptr);
if (checkGenericArguments(dc, loc, noteLoc, UGT, genericSig,
allGenericArgs))
return nullptr;
useObjectiveCBridgeableConformancesOfArgs(dc, BGT);
}
return BGT;
}
static Type applyGenericTypeReprArgs(TypeChecker &TC, Type type,
TypeDecl *decl,
SourceLoc loc,
DeclContext *dc,
GenericIdentTypeRepr *generic,
bool isGenericSignature,
GenericTypeResolver *resolver) {
Type ty = TC.applyGenericArguments(type, decl, loc, dc, generic,
isGenericSignature, resolver);
if (!ty)
return ErrorType::get(TC.Context);
return ty;
}
/// \brief Diagnose a use of an unbound generic type.
static void diagnoseUnboundGenericType(TypeChecker &tc, Type ty,SourceLoc loc) {
auto unbound = ty->castTo<UnboundGenericType>();
{
InFlightDiagnostic diag = tc.diagnose(loc,
diag::generic_type_requires_arguments, ty);
if (auto *genericD = unbound->getDecl()) {
// Tries to infer the type arguments to pass.
// Currently it only works if all the generic arguments have a super type,
// or it requires a class, in which case it infers 'AnyObject'.
auto inferGenericArgs = [](GenericTypeDecl *genericD)->std::string {
GenericParamList *genParamList = genericD->getGenericParams();
if (!genParamList)
return std::string();
auto params= genParamList->getParams();
if (params.empty())
return std::string();
std::string argsToAdd = "<";
for (unsigned i = 0, e = params.size(); i != e; ++i) {
auto param = params[i];
auto archTy = param->getArchetype();
if (!archTy)
return std::string();
if (auto superTy = archTy->getSuperclass()) {
argsToAdd += superTy.getString();
} else if (archTy->requiresClass()) {
argsToAdd += "AnyObject";
} else {
return std::string(); // give up.
}
if (i < e-1)
argsToAdd += ", ";
}
argsToAdd += ">";
return argsToAdd;
};
std::string genericArgsToAdd = inferGenericArgs(genericD);
if (!genericArgsToAdd.empty()) {
diag.fixItInsertAfter(loc, genericArgsToAdd);
}
}
}
tc.diagnose(unbound->getDecl()->getLoc(), diag::generic_type_declared_here,
unbound->getDecl()->getName());
}
/// \brief Returns a valid type or ErrorType in case of an error.
static Type resolveTypeDecl(TypeChecker &TC, TypeDecl *typeDecl, SourceLoc loc,
DeclContext *dc,
GenericIdentTypeRepr *generic,
TypeResolutionOptions options,
GenericTypeResolver *resolver,
UnsatisfiedDependency *unsatisfiedDependency) {
assert(dc && "No declaration context for type resolution?");
// If we have a callback to report dependencies, do so.
if (unsatisfiedDependency) {
if ((*unsatisfiedDependency)(requestResolveTypeDecl(typeDecl)))
return nullptr;
} else {
// Validate the declaration.
TC.validateDecl(typeDecl);
}
// Resolve the type declaration to a specific type. How this occurs
// depends on the current context and where the type was found.
Type type =
TC.resolveTypeInContext(typeDecl, dc, options, generic, resolver);
// FIXME: Defensive check that shouldn't be needed, but prevents a
// huge number of crashes on ill-formed code.
if (!type)
return ErrorType::get(TC.Context);
if (type->is<UnboundGenericType>() && !generic &&
!options.contains(TR_AllowUnboundGenerics) &&
!options.contains(TR_ResolveStructure)) {
diagnoseUnboundGenericType(TC, type, loc);
return ErrorType::get(TC.Context);
}
// If we found a generic parameter, try to resolve it.
// FIXME: Jump through hoops to maintain syntactic sugar. We shouldn't care
// about this, because we shouldn't have to do this at all.
if (auto genericParam = type->getAs<GenericTypeParamType>()) {
auto resolvedGP = resolver->resolveGenericTypeParamType(genericParam);
if (auto substituted = dyn_cast<SubstitutedType>(type.getPointer())) {
type = SubstitutedType::get(substituted->getOriginal(), resolvedGP,
TC.Context);
} else {
type = resolvedGP;
}
}
if (generic && !options.contains(TR_ResolveStructure)) {
// Apply the generic arguments to the type.
type = applyGenericTypeReprArgs(TC, type, typeDecl, loc, dc, generic,
options.contains(TR_GenericSignature),
resolver);
}
assert(type);
return type;
}
/// Retrieve the nearest enclosing nominal type context.
static NominalTypeDecl *getEnclosingNominalContext(DeclContext *dc) {
while (dc->isLocalContext())
dc = dc->getParent();
if (auto nominal = dc->getAsNominalTypeOrNominalTypeExtensionContext())
return nominal;
return nullptr;
}
/// Diagnose a reference to an unknown type.
///
/// This routine diagnoses a reference to an unknown type, and
/// attempts to fix the reference via various means.
///
/// \param tc The type checker through which we should emit the diagnostic.
/// \param dc The context in which name lookup occurred.
///
/// \returns either the corrected type, if possible, or an error type to
/// that correction failed.
static Type diagnoseUnknownType(TypeChecker &tc, DeclContext *dc,
Type parentType,
SourceRange parentRange,
ComponentIdentTypeRepr *comp,
TypeResolutionOptions options,
GenericTypeResolver *resolver,
UnsatisfiedDependency *unsatisfiedDependency) {
// Unqualified lookup case.
if (parentType.isNull()) {
// Attempt to refer to 'Self' within a non-protocol nominal
// type. Fix this by replacing 'Self' with the nominal type name.
NominalTypeDecl *nominal = nullptr;
if (comp->getIdentifier() == tc.Context.Id_Self &&
!isa<GenericIdentTypeRepr>(comp) &&
(nominal = getEnclosingNominalContext(dc))) {
// Retrieve the nominal type and resolve it within this context.
assert(!isa<ProtocolDecl>(nominal) && "Cannot be a protocol");
auto type = resolveTypeDecl(tc, nominal, comp->getIdLoc(), dc, nullptr,
options, resolver, unsatisfiedDependency);
if (type->is<ErrorType>())
return type;
// Produce a Fix-It replacing 'Self' with the nominal type name.
tc.diagnose(comp->getIdLoc(), diag::self_in_nominal, nominal->getName())
.fixItReplace(comp->getIdLoc(), nominal->getName().str());
comp->overwriteIdentifier(nominal->getName());
comp->setValue(nominal);
return type;
}
// Fallback.
SourceLoc L = comp->getIdLoc();
SourceRange R = SourceRange(comp->getIdLoc());
// Check if the unknown type is in the type remappings.
auto &Remapped = tc.Context.RemappedTypes;
auto TypeName = comp->getIdentifier().str();
auto I = Remapped.find(TypeName);
if (I != Remapped.end()) {
auto RemappedTy = I->second->getString();
tc.diagnose(L, diag::use_undeclared_type_did_you_mean,
comp->getIdentifier(), RemappedTy)
.highlight(R)
.fixItReplace(R, RemappedTy);
// Replace the computed type with the suggested type.
comp->overwriteIdentifier(tc.Context.getIdentifier(RemappedTy));
// HACK: 'NSUInteger' suggests both 'UInt' and 'Int'.
if (TypeName
== tc.Context.getSwiftName(KnownFoundationEntity::NSUInteger)) {
tc.diagnose(L, diag::note_remapped_type, "UInt")
.fixItReplace(R, "UInt");
}
return I->second;
}
tc.diagnose(L, diag::use_undeclared_type,
comp->getIdentifier())
.highlight(R);
return ErrorType::get(tc.Context);
}
// Qualified lookup case.
// FIXME: Typo correction!
// Lookup into a type.
if (auto moduleType = parentType->getAs<ModuleType>()) {
tc.diagnose(comp->getIdLoc(), diag::no_module_type,
comp->getIdentifier(), moduleType->getModule()->getName());
} else {
tc.diagnose(comp->getIdLoc(), diag::invalid_member_type,
comp->getIdentifier(), parentType)
.highlight(parentRange);
}
return ErrorType::get(tc.Context);
}
/// Resolve the given identifier type representation as an unqualified type,
/// returning the type it references.
///
/// \returns Either the resolved type or a null type, the latter of
/// which indicates that some dependencies were unsatisfied.
static Type
resolveTopLevelIdentTypeComponent(TypeChecker &TC, DeclContext *DC,
ComponentIdentTypeRepr *comp,
TypeResolutionOptions options,
bool diagnoseErrors,
GenericTypeResolver *resolver,
UnsatisfiedDependency *unsatisfiedDependency){
// Short-circuiting.
if (comp->isInvalid()) return ErrorType::get(TC.Context);
// If the component has already been bound to a declaration, handle
// that now.
if (ValueDecl *VD = comp->getBoundDecl()) {
auto *typeDecl = cast<TypeDecl>(VD);
// Resolve the type declaration within this context.
return resolveTypeDecl(TC, typeDecl, comp->getIdLoc(), DC,
dyn_cast<GenericIdentTypeRepr>(comp), options,
resolver, unsatisfiedDependency);
}
// Resolve the first component, which is the only one that requires
// unqualified name lookup.
DeclContext *lookupDC = DC;
// Dynamic 'Self' in the result type of a function body.
if (options.contains(TR_DynamicSelfResult) &&
comp->getIdentifier() == TC.Context.Id_Self) {
auto func = cast<FuncDecl>(DC);
assert(func->hasDynamicSelf() && "Not marked as having dynamic Self?");
return func->getDynamicSelf();
}
// For lookups within the generic signature, look at the generic
// parameters (only), then move up to the enclosing context.
if (options.contains(TR_GenericSignature)) {
GenericParamList *genericParams;
if (auto *generic = dyn_cast<GenericTypeDecl>(DC)) {
genericParams = generic->getGenericParams();
} else if (auto *ext = dyn_cast<ExtensionDecl>(DC)) {
genericParams = ext->getGenericParams();
} else {
genericParams = cast<AbstractFunctionDecl>(DC)->getGenericParams();
}
if (genericParams) {
auto matchingParam =
std::find_if(genericParams->begin(), genericParams->end(),
[comp](const GenericTypeParamDecl *param) {
return param->getFullName().matchesRef(comp->getIdentifier());
});
if (matchingParam != genericParams->end()) {
comp->setValue(*matchingParam);
return resolveTopLevelIdentTypeComponent(TC, DC, comp, options,
diagnoseErrors, resolver,
unsatisfiedDependency);
}
}
// If the lookup occurs from within a trailing 'where' clause of
// a constrained extension, also look for associated types.
if (genericParams && genericParams->hasTrailingWhereClause() &&
isa<ExtensionDecl>(DC) && comp->getIdLoc().isValid() &&
TC.Context.SourceMgr.rangeContainsTokenLoc(
genericParams->getTrailingWhereClauseSourceRange(),
comp->getIdLoc())) {
// We need to be able to perform qualified lookup into the given
// declaration context.
if (unsatisfiedDependency &&
(*unsatisfiedDependency)(
requestQualifiedLookupInDeclContext({ DC, comp->getIdentifier(),
comp->getIdLoc() })))
return nullptr;
auto nominal = DC->getAsNominalTypeOrNominalTypeExtensionContext();
SmallVector<ValueDecl *, 4> decls;
if (DC->lookupQualified(nominal->getDeclaredInterfaceType(),
comp->getIdentifier(),
NL_QualifiedDefault|NL_ProtocolMembers,
&TC,
decls)) {
for (const auto decl : decls) {
// FIXME: Better ambiguity handling.
if (auto assocType = dyn_cast<AssociatedTypeDecl>(decl)) {
comp->setValue(assocType);
return resolveTopLevelIdentTypeComponent(TC, DC, comp, options,
diagnoseErrors, resolver,
unsatisfiedDependency);
}
}
}
}
if (!DC->isCascadingContextForLookup(/*excludeFunctions*/false))
options |= TR_KnownNonCascadingDependency;
// The remaining lookups will be in the parent context.
lookupDC = DC->getParent();
}
// We need to be able to perform unqualified lookup into the given
// declaration context.
if (unsatisfiedDependency &&
(*unsatisfiedDependency)(
requestUnqualifiedLookupInDeclContext({ lookupDC,
comp->getIdentifier(),
comp->getIdLoc() })))
return nullptr;
NameLookupOptions lookupOptions = defaultUnqualifiedLookupOptions;
lookupOptions |= NameLookupFlags::OnlyTypes;
if (options.contains(TR_KnownNonCascadingDependency))
lookupOptions |= NameLookupFlags::KnownPrivate;
// FIXME: Eliminate this once we can handle finding protocol members
// in resolveTypeInContext.
lookupOptions -= NameLookupFlags::ProtocolMembers;
LookupResult globals = TC.lookupUnqualified(lookupDC, comp->getIdentifier(),
comp->getIdLoc(), lookupOptions);
// Process the names we found.
Type current;
TypeDecl *currentDecl = nullptr;
bool isAmbiguous = false;
for (const auto &result : globals) {
auto typeDecl = cast<TypeDecl>(result.Decl);
// If necessary, add delayed members to the declaration.
if (auto nomDecl = dyn_cast<NominalTypeDecl>(typeDecl)) {
TC.forceExternalDeclMembers(nomDecl);
}
Type type = resolveTypeDecl(TC, typeDecl, comp->getIdLoc(), DC,
dyn_cast<GenericIdentTypeRepr>(comp), options,
resolver, unsatisfiedDependency);
if (!type || type->is<ErrorType>())
return type;
// If this is the first result we found, record it.
if (current.isNull()) {
current = type;
currentDecl = typeDecl;
continue;
}
// Otherwise, check for an ambiguity.
if (!current->isEqual(type)) {
isAmbiguous = true;
break;
}
// We have a found multiple type aliases that refer to the same thing.
// Ignore the duplicate.
}
// Complain about any ambiguities we detected.
// FIXME: We could recover by looking at later components.
if (isAmbiguous) {
if (diagnoseErrors) {
TC.diagnose(comp->getIdLoc(), diag::ambiguous_type_base,
comp->getIdentifier())
.highlight(comp->getIdLoc());
for (auto result : globals) {
TC.diagnose(result.Decl, diag::found_candidate);
}
}
comp->setInvalid();
return ErrorType::get(TC.Context);
}
// If we found nothing, complain and give ourselves a chance to recover.
if (current.isNull()) {
// If we're not allowed to complain or we couldn't fix the
// source, bail out.
if (!diagnoseErrors)
return ErrorType::get(TC.Context);
return diagnoseUnknownType(TC, DC, nullptr, SourceRange(), comp, options,
resolver, unsatisfiedDependency);
}
comp->setValue(currentDecl);
return current;
}
/// Resolve the given identifier type representation as a qualified
/// lookup within the given parent type, returning the type it
/// references.
static Type resolveNestedIdentTypeComponent(
TypeChecker &TC, DeclContext *DC,
Type parentTy,
SourceRange parentRange,
ComponentIdentTypeRepr *comp,