forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeCheckType.cpp
3099 lines (2644 loc) · 114 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 - 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 validation for Swift types, emitting semantic errors as
// appropriate and checking default initializer values.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "GenericTypeResolver.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckProtocol.h"
#include "swift/Strings.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeLoc.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.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"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
#define DEBUG_TYPE "TypeCheckType"
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);
}
static Type getPointerType(TypeChecker &tc, SourceLoc loc, Type pointeeType,
PointerTypeKind kind) {
auto pointerDecl = [&] {
switch (kind) {
case PTK_UnsafeMutableRawPointer:
case PTK_UnsafeRawPointer:
llvm_unreachable("these pointer types don't take arguments");
case PTK_UnsafePointer:
return tc.Context.getUnsafePointerDecl();
case PTK_UnsafeMutablePointer:
return tc.Context.getUnsafeMutablePointerDecl();
case PTK_AutoreleasingUnsafeMutablePointer:
return tc.Context.getAutoreleasingUnsafeMutablePointerDecl();
}
llvm_unreachable("bad kind");
}();
if (!pointerDecl) {
tc.diagnose(loc, diag::pointer_type_not_found,
kind == PTK_UnsafePointer ? 0 :
kind == PTK_UnsafeMutablePointer ? 1 : 2);
return Type();
}
tc.validateDecl(pointerDecl);
if (pointerDecl->isInvalid())
return Type();
// TODO: validate generic signature?
return BoundGenericType::get(pointerDecl, nullptr, pointeeType);
}
Type TypeChecker::getUnsafePointerType(SourceLoc loc, Type pointeeType) {
return getPointerType(*this, loc, pointeeType, PTK_UnsafePointer);
}
Type TypeChecker::getUnsafeMutablePointerType(SourceLoc loc, Type pointeeType) {
return getPointerType(*this, loc, pointeeType, PTK_UnsafeMutablePointer);
}
static Type getStdlibType(TypeChecker &TC, Type &cached, DeclContext *dc,
StringRef name) {
if (cached.isNull()) {
ModuleDecl *stdlib = TC.Context.getStdlibModule();
LookupTypeResult lookup = TC.lookupMemberType(dc, ModuleType::get(stdlib),
TC.Context.getIdentifier(
name));
if (lookup)
cached = lookup.back().MemberType;
}
return cached;
}
Type TypeChecker::getStringType(DeclContext *dc) {
return ::getStdlibType(*this, StringType, dc, "String");
}
Type TypeChecker::getSubstringType(DeclContext *dc) {
return ::getStdlibType(*this, SubstringType, dc, "Substring");
}
Type TypeChecker::getIntType(DeclContext *dc) {
return ::getStdlibType(*this, IntType, dc, "Int");
}
Type TypeChecker::getInt8Type(DeclContext *dc) {
return ::getStdlibType(*this, Int8Type, dc, "Int8");
}
Type TypeChecker::getUInt8Type(DeclContext *dc) {
return ::getStdlibType(*this, UInt8Type, dc, "UInt8");
}
/// Returns the maximum-sized builtin integer type.
Type TypeChecker::getMaxIntegerType(DeclContext *dc) {
if (!MaxIntegerType.isNull())
return MaxIntegerType;
SmallVector<ValueDecl *, 1> lookupResults;
getStdlibModule(dc)->lookupValue(/*AccessPath=*/{},
Context.Id_MaxBuiltinIntegerType,
NLKind::QualifiedLookup, lookupResults);
if (lookupResults.size() != 1)
return MaxIntegerType;
auto *maxIntegerTypeDecl = dyn_cast<TypeAliasDecl>(lookupResults.front());
if (!maxIntegerTypeDecl)
return MaxIntegerType;
validateDecl(maxIntegerTypeDecl);
if (!maxIntegerTypeDecl->hasInterfaceType() ||
!maxIntegerTypeDecl->getDeclaredInterfaceType()->is<BuiltinIntegerType>())
return MaxIntegerType;
MaxIntegerType = maxIntegerTypeDecl->getUnderlyingTypeLoc().getType();
return MaxIntegerType;
}
/// 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();
}
Type
TypeChecker::getDynamicBridgedThroughObjCClass(DeclContext *dc,
Type dynamicType,
Type valueType) {
// We can only bridge from class or Objective-C existential types.
if (!dynamicType->satisfiesClassConstraint())
return Type();
// If the value type cannot be bridged, we're done.
if (!valueType->isPotentiallyBridgedValueType())
return Type();
return Context.getBridgedToObjC(dc, valueType);
}
Type TypeChecker::resolveTypeInContext(
TypeDecl *typeDecl,
DeclContext *foundDC,
DeclContext *fromDC,
TypeResolutionOptions options,
bool isSpecialized,
GenericTypeResolver *resolver) {
// If we're just resolving the structure, the decl itself is all we need to
// know: return the unbound generic type.
if (options.contains(TypeResolutionFlags::ResolveStructure))
return typeDecl->getDeclaredInterfaceType();
GenericTypeToArchetypeResolver defaultResolver(fromDC);
if (!resolver)
resolver = &defaultResolver;
// If we found a generic parameter, map to the archetype if there is one.
if (auto genericParam = dyn_cast<GenericTypeParamDecl>(typeDecl)) {
return resolver->mapTypeIntoContext(
genericParam->getDeclaredInterfaceType());
}
// 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 (auto nominalType = dyn_cast<NominalTypeDecl>(typeDecl)) {
if (!isa<ProtocolDecl>(nominalType) &&
(!nominalType->getGenericParams() || !isSpecialized)) {
for (auto parentDC = fromDC;
!parentDC->isModuleScopeContext();
parentDC = parentDC->getParent()) {
auto *parentNominal =
parentDC->getAsNominalTypeOrNominalTypeExtensionContext();
if (parentNominal == nominalType)
return resolver->mapTypeIntoContext(
parentDC->getSelfInterfaceType());
if (isa<ExtensionDecl>(parentDC)) {
auto *extendedType = parentNominal;
while (extendedType != nullptr) {
if (extendedType == nominalType)
return resolver->mapTypeIntoContext(
extendedType->getDeclaredInterfaceType());
extendedType = extendedType->getParent()
->getAsNominalTypeOrNominalTypeExtensionContext();
}
}
}
}
}
// Simple case -- the type is not nested inside of another type.
// However, it might be nested inside another generic context, so
// we do want to write the type in terms of interface types or
// context archetypes, depending on the resolver given to us.
if (!typeDecl->getDeclContext()->isTypeContext()) {
if (auto *aliasDecl = dyn_cast<TypeAliasDecl>(typeDecl)) {
// For a generic typealias, return the unbound generic form of the type.
if (aliasDecl->getGenericParams())
return aliasDecl->getUnboundGenericType();
// Otherwise, simply return the underlying type.
return resolver->mapTypeIntoContext(
aliasDecl->getDeclaredInterfaceType());
}
// When a nominal type used outside its context, return the unbound
// generic form of the type.
if (auto *nominalDecl = dyn_cast<NominalTypeDecl>(typeDecl))
return nominalDecl->getDeclaredType();
assert(isa<ModuleDecl>(typeDecl));
return typeDecl->getDeclaredInterfaceType();
}
assert(foundDC);
// selfType is the self type of the context, unless the
// context is a protocol type, in which case we might have
// to use the existential type or superclass bound as a
// parent type instead.
Type selfType;
if (isa<NominalTypeDecl>(typeDecl) &&
typeDecl->getDeclContext()->getAsProtocolOrProtocolExtensionContext()) {
// When looking up a nominal type declaration inside of a
// protocol extension, always use the nominal type and
// not the protocol 'Self' type.
if (!foundDC->getDeclaredInterfaceType())
return ErrorType::get(Context);
selfType = resolver->mapTypeIntoContext(
foundDC->getDeclaredInterfaceType());
} else {
// Otherwise, we want the protocol 'Self' type for
// substituting into alias types and associated types.
selfType = resolver->mapTypeIntoContext(
foundDC->getSelfInterfaceType());
if (selfType->is<GenericTypeParamType>() &&
typeDecl->getDeclContext()->getAsClassOrClassExtensionContext()) {
// We found a member of a class from a protocol or protocol
// extension.
//
// Get the superclass of the 'Self' type parameter.
auto *sig = foundDC->getGenericSignatureOfContext();
auto superclassType = sig->getSuperclassBound(selfType);
assert(superclassType);
selfType = superclassType;
}
}
// Finally, substitute the base type into the member type.
return substMemberTypeWithBase(fromDC->getParentModule(), typeDecl,
selfType, resolver->usesArchetypes());
}
static TypeResolutionOptions
adjustOptionsForGenericArgs(TypeResolutionOptions options) {
options -= TypeResolutionFlags::SILType;
options -= TypeResolutionFlags::FunctionInput;
options -= TypeResolutionFlags::TypeAliasUnderlyingType;
options -= TypeResolutionFlags::AllowUnavailableProtocol;
options -= TypeResolutionFlags::AllowIUO;
return options;
}
/// This function checks if a bound generic type is UnsafePointer<Void> or
/// UnsafeMutablePointer<Void>. For these two type representations, we should
/// warn users that they are deprecated and replace them with more handy
/// UnsafeRawPointer and UnsafeMutableRawPointer, respectively.
static bool isPointerToVoid(ASTContext &Ctx, Type Ty, bool &IsMutable) {
if (Ty.isNull())
return false;
auto *BGT = Ty->getAs<BoundGenericType>();
if (!BGT)
return false;
if (BGT->getDecl() != Ctx.getUnsafePointerDecl() &&
BGT->getDecl() != Ctx.getUnsafeMutablePointerDecl())
return false;
IsMutable = BGT->getDecl() == Ctx.getUnsafeMutablePointerDecl();
assert(BGT->getGenericArgs().size() == 1);
return BGT->getGenericArgs().front()->isVoid();
}
Type TypeChecker::applyGenericArguments(Type type,
SourceLoc loc, DeclContext *dc,
GenericIdentTypeRepr *generic,
TypeResolutionOptions options,
GenericTypeResolver *resolver) {
assert(!options.contains(TypeResolutionFlags::ResolveStructure) &&
"should not touch generic arguments when resolving structure");
if (type->hasError()) {
generic->setInvalid();
return type;
}
// We must either have an unbound generic type, or a generic type alias.
if (!type->is<UnboundGenericType>()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
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>()) {
// When turning a SourceRange into CharSourceRange the closing angle
// brackets on nested generics are lexed as one token.
SourceRange angles = generic->getAngleBrackets();
diag.fixItRemoveChars(angles.Start,
angles.End.getAdvancedLocOrInvalid(1));
}
generic->setInvalid();
}
return type;
}
auto *unboundType = type->castTo<UnboundGenericType>();
auto *decl = unboundType->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()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
diagnose(loc, diag::type_parameter_count_mismatch, decl->getName(),
genericParams->size(), genericArgs.size(),
genericArgs.size() < genericParams->size())
.highlight(generic->getAngleBrackets());
diagnose(decl, diag::kind_identifier_declared_here,
DescriptiveDeclKind::GenericType, decl->getName());
}
return ErrorType::get(Context);
}
// In SIL mode, Optional<T> interprets T as a SIL type.
if (options.contains(TypeResolutionFlags::SILType)) {
if (auto nominal = dyn_cast<NominalTypeDecl>(decl)) {
if (nominal->isOptionalDecl()) {
// Validate the generic argument.
TypeLoc arg = genericArgs[0];
if (validateType(arg, dc, withoutContext(options, true), resolver))
return nullptr;
Type objectType = arg.getType();
if (!objectType)
return nullptr;
return BoundGenericType::get(nominal, /*parent*/ Type(), objectType);
}
}
}
// Cannot extend a bound generic type.
if (options.contains(TypeResolutionFlags::ExtensionBinding)) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
diagnose(loc, diag::extension_specialization,
genericDecl->getName())
.highlight(generic->getSourceRange());
}
return ErrorType::get(Context);
}
// FIXME: More principled handling of circularity.
if (!genericDecl->hasValidSignature()) {
diagnose(loc, diag::recursive_type_reference,
genericDecl->getDescriptiveKind(), genericDecl->getName());
diagnose(genericDecl, diag::kind_declared_here,
DescriptiveDeclKind::Type);
return ErrorType::get(Context);
}
// Resolve the types of the generic arguments.
assert(!options.contains(TypeResolutionFlags::ResolveStructure) &&
"should not touch generic arguments when resolving structure");
options = adjustOptionsForGenericArgs(options);
SmallVector<Type, 2> args;
for (auto tyR : genericArgs) {
// Propagate failure.
TypeLoc genericArg = tyR;
if (validateType(genericArg, dc, options, resolver))
return ErrorType::get(Context);
auto substTy = genericArg.getType();
// Unsatisfied dependency case.
if (!substTy)
return nullptr;
args.push_back(substTy);
}
auto result = applyUnboundGenericArguments(unboundType, genericDecl, loc,
dc, args, resolver);
if (!result)
return result;
// Migration hack.
bool isMutablePointer;
if (isPointerToVoid(dc->getASTContext(), result, isMutablePointer)) {
if (isMutablePointer)
diagnose(loc, diag::use_of_void_pointer, "Mutable").
fixItReplace(generic->getSourceRange(), "UnsafeMutableRawPointer");
else
diagnose(loc, diag::use_of_void_pointer, "").
fixItReplace(generic->getSourceRange(), "UnsafeRawPointer");
}
return result;
}
/// Apply generic arguments to the given type.
Type TypeChecker::applyUnboundGenericArguments(
UnboundGenericType *unboundType, GenericTypeDecl *decl,
SourceLoc loc, DeclContext *dc,
ArrayRef<Type> genericArgs,
GenericTypeResolver *resolver) {
assert(genericArgs.size() == decl->getGenericParams()->size() &&
"invalid arguments, use applyGenericArguments for diagnostic emitting");
// Make sure we always have a resolver to use.
GenericTypeToArchetypeResolver defaultResolver(dc);
if (!resolver)
resolver = &defaultResolver;
auto genericSig = decl->getGenericSignature();
assert(genericSig != nullptr);
TypeSubstitutionMap subs;
// Get the interface type for the declaration. We will be substituting
// type parameters that appear inside this type with the provided
// generic arguments.
auto resultType = decl->getDeclaredInterfaceType();
bool hasTypeVariable = false;
// Get the substitutions for outer generic parameters from the parent
// type.
if (auto parentType = unboundType->getParent()) {
if (parentType->hasUnboundGenericType()) {
// If we're working with a nominal type declaration, just construct
// a bound generic type without checking the generic arguments.
if (auto *nominalDecl = dyn_cast<NominalTypeDecl>(decl)) {
return BoundGenericType::get(nominalDecl, parentType, genericArgs);
}
assert(!resultType->hasTypeParameter());
return resultType;
}
subs = parentType->getContextSubstitutions(decl->getDeclContext());
hasTypeVariable |= parentType->hasTypeVariable();
}
SourceLoc noteLoc = decl->getLoc();
if (noteLoc.isInvalid())
noteLoc = loc;
// Realize the types of the generic arguments and add them to the
// substitution map.
for (unsigned i = 0, e = genericArgs.size(); i < e; i++) {
auto origTy = genericSig->getInnermostGenericParams()[i];
auto substTy = genericArgs[i];
// Enter a substitution.
subs[origTy->getCanonicalType()->castTo<GenericTypeParamType>()] =
substTy;
hasTypeVariable |= substTy->hasTypeVariable();
}
// Check the generic arguments against the requirements of the declaration's
// generic signature.
if (!hasTypeVariable) {
auto result =
checkGenericArguments(dc, loc, noteLoc, unboundType,
genericSig->getGenericParams(),
genericSig->getRequirements(),
QueryTypeSubstitutionMap{subs},
LookUpConformance(*this, dc));
switch (result) {
case RequirementCheckResult::Failure:
case RequirementCheckResult::SubstitutionFailure:
return ErrorType::get(Context);
case RequirementCheckResult::Success:
break;
}
}
// For a typealias, use the underlying type. We'll wrap up the result
// later.
auto typealias = dyn_cast<TypeAliasDecl>(decl);
if (typealias) {
resultType = typealias->getUnderlyingTypeLoc().getType();
}
// Apply the substitution map to the interface type of the declaration.
resultType = resultType.subst(QueryTypeSubstitutionMap{subs},
LookUpConformance(*this, dc),
SubstFlags::UseErrorType);
// Form a sugared typealias reference.
Type parentType = unboundType->getParent();
if (typealias && (!parentType || !parentType->isAnyExistentialType())) {
auto genericSig = typealias->getGenericSignature();
auto subMap = SubstitutionMap::get(genericSig,
QueryTypeSubstitutionMap{subs},
LookUpConformance(*this, dc));
resultType = NameAliasType::get(typealias, parentType,
subMap, resultType);
}
if (isa<NominalTypeDecl>(decl) && resultType) {
(void)useObjectiveCBridgeableConformancesOfArgs(
dc, resultType->castTo<BoundGenericType>());
}
return resultType;
}
/// \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()) {
SmallString<64> genericArgsToAdd;
if (tc.getDefaultGenericArgumentsString(genericArgsToAdd, genericD))
diag.fixItInsertAfter(loc, genericArgsToAdd);
}
}
tc.diagnose(unbound->getDecl(), diag::kind_identifier_declared_here,
DescriptiveDeclKind::GenericType, unbound->getDecl()->getName());
}
// Produce a diagnostic if the type we referenced was an
// associated type but the type itself was erroneous. We'll produce a
// diagnostic here if the diagnostic for the bad type witness would show up in
// a different context.
static void maybeDiagnoseBadConformanceRef(TypeChecker &tc,
DeclContext *dc,
Type parentTy,
SourceLoc loc,
AssociatedTypeDecl *assocType) {
// If we weren't given a conformance, go look it up.
ProtocolConformance *conformance = nullptr;
if (auto conformanceRef = tc.conformsToProtocol(
parentTy, assocType->getProtocol(), dc,
(ConformanceCheckFlags::InExpression |
ConformanceCheckFlags::SuppressDependencyTracking |
ConformanceCheckFlags::AllowUnavailableConditionalRequirements))) {
if (conformanceRef->isConcrete())
conformance = conformanceRef->getConcrete();
}
// If any errors have occurred, don't bother diagnosing this cross-file
// issue.
if (tc.Context.Diags.hadAnyError())
return;
auto diagCode =
(conformance && !conformance->getConditionalRequirementsIfAvailable())
? diag::unsupported_recursion_in_associated_type_reference
: diag::broken_associated_type_witness;
tc.diagnose(loc, diagCode, assocType->getFullName(), parentTy);
}
/// \brief Returns a valid type or ErrorType in case of an error.
static Type resolveTypeDecl(TypeChecker &TC, TypeDecl *typeDecl, SourceLoc loc,
DeclContext *foundDC,
DeclContext *fromDC,
GenericIdentTypeRepr *generic,
TypeResolutionOptions options,
GenericTypeResolver *resolver) {
assert(fromDC && "No declaration context for type resolution?");
// Don't validate nominal type declarations during extension binding.
if (!options.contains(TypeResolutionFlags::ExtensionBinding) ||
!isa<NominalTypeDecl>(typeDecl)) {
// Validate the declaration.
TC.validateDeclForNameLookup(typeDecl);
// If we were not able to validate recursively, bail out.
if (!typeDecl->hasInterfaceType()) {
TC.diagnose(loc, diag::recursive_type_reference,
typeDecl->getDescriptiveKind(), typeDecl->getName());
TC.diagnose(typeDecl->getLoc(), diag::kind_declared_here,
DescriptiveDeclKind::Type);
return ErrorType::get(TC.Context);
}
}
// 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, foundDC, fromDC, options,
generic, resolver);
if (type->is<UnboundGenericType>() && !generic &&
!options.contains(TypeResolutionFlags::AllowUnboundGenerics) &&
!options.contains(TypeResolutionFlags::TypeAliasUnderlyingType) &&
!options.contains(TypeResolutionFlags::ResolveStructure)) {
diagnoseUnboundGenericType(TC, type, loc);
return ErrorType::get(TC.Context);
}
if (type->hasError() && isa<AssociatedTypeDecl>(typeDecl)) {
maybeDiagnoseBadConformanceRef(TC, fromDC,
foundDC->getDeclaredInterfaceType(),
loc, cast<AssociatedTypeDecl>(typeDecl));
}
if (generic && !options.contains(TypeResolutionFlags::ResolveStructure)) {
// Apply the generic arguments to the type.
type = TC.applyGenericArguments(type, loc, fromDC, generic,
options, resolver);
if (!type)
return nullptr;
}
assert(type);
return type;
}
static std::string getDeclNameFromContext(DeclContext *dc,
NominalTypeDecl *nominal) {
// We don't allow an unqualified reference to a type inside an
// extension if the type is itself nested inside another type,
// eg:
//
// extension A.B { ... B ... }
//
// Instead, you must write 'A.B'. Calculate the right name to use
// for fixits.
if (!isa<ExtensionDecl>(dc)) {
SmallVector<Identifier, 2> idents;
auto *parentNominal = nominal;
while (parentNominal != nullptr) {
idents.push_back(parentNominal->getName());
parentNominal = parentNominal->getDeclContext()
->getAsNominalTypeOrNominalTypeExtensionContext();
}
std::reverse(idents.begin(), idents.end());
std::string result;
for (auto ident : idents) {
if (!result.empty())
result += ".";
result += ident.str();
}
return result;
} else {
return nominal->getName().str();
}
}
/// 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,
NameLookupOptions lookupOptions,
GenericTypeResolver *resolver) {
// Unqualified lookup case.
if (parentType.isNull()) {
if (comp->getIdentifier() == tc.Context.Id_Self &&
!isa<GenericIdentTypeRepr>(comp)) {
DeclContext *nominalDC = nullptr;
NominalTypeDecl *nominal = nullptr;
if ((nominalDC = dc->getInnermostTypeContext()) &&
(nominal = nominalDC->getAsNominalTypeOrNominalTypeExtensionContext())) {
// Attempt to refer to 'Self' within a non-protocol nominal
// type. Fix this by replacing 'Self' with the nominal type name.
assert(!isa<ProtocolDecl>(nominal) && "Cannot be a protocol");
// Produce a Fix-It replacing 'Self' with the nominal type name.
auto name = getDeclNameFromContext(dc, nominal);
tc.diagnose(comp->getIdLoc(), diag::self_in_nominal, name)
.fixItReplace(comp->getIdLoc(), name);
// If this is a requirement, replacing 'Self' with a valid type will
// result in additional unnecessary diagnostics (does not refer to a
// generic parameter or associated type). Simply return an error type.
if (options.contains(TypeResolutionFlags::GenericRequirement))
return ErrorType::get(tc.Context);
auto type = resolver->mapTypeIntoContext(
dc->getInnermostTypeContext()->getSelfInterfaceType());
comp->overwriteIdentifier(nominal->getName());
comp->setValue(nominal, nominalDC->getParent());
return type;
}
// Attempt to refer to 'Self' from a free function.
tc.diagnose(comp->getIdLoc(), diag::dynamic_self_non_method,
dc->getParent()->isLocalContext());
return ErrorType::get(tc.Context);
}
// Try ignoring access control.
DeclContext *lookupDC = dc;
if (options.contains(TypeResolutionFlags::GenericSignature))
lookupDC = dc->getParentForLookup();
NameLookupOptions relookupOptions = lookupOptions;
relookupOptions |= NameLookupFlags::KnownPrivate;
relookupOptions |= NameLookupFlags::IgnoreAccessControl;
auto inaccessibleResults =
tc.lookupUnqualifiedType(lookupDC, comp->getIdentifier(), comp->getIdLoc(),
relookupOptions);
if (!inaccessibleResults.empty()) {
// FIXME: What if the unviable candidates have different levels of access?
auto first = cast<TypeDecl>(inaccessibleResults.front().getValueDecl());
tc.diagnose(comp->getIdLoc(), diag::candidate_inaccessible,
comp->getIdentifier(), first->getFormalAccess());
// FIXME: If any of the candidates (usually just one) are in the same
// module we could offer a fix-it.
for (auto lookupResult : inaccessibleResults)
tc.diagnose(lookupResult.getValueDecl(), diag::kind_declared_here,
DescriptiveDeclKind::Type);
// Don't try to recover here; we'll get more access-related diagnostics
// downstream if we do.
return ErrorType::get(tc.Context);
}
// 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.
if (!parentType->mayHaveMembers()) {
tc.diagnose(comp->getIdLoc(), diag::invalid_member_type,
comp->getIdentifier(), parentType)
.highlight(parentRange);
return ErrorType::get(tc.Context);
}
// Try ignoring access control.
NameLookupOptions relookupOptions = lookupOptions;
relookupOptions |= NameLookupFlags::KnownPrivate;
relookupOptions |= NameLookupFlags::IgnoreAccessControl;
auto inaccessibleMembers = tc.lookupMemberType(dc, parentType,
comp->getIdentifier(),
relookupOptions);
if (inaccessibleMembers) {
// FIXME: What if the unviable candidates have different levels of access?
const TypeDecl *first = inaccessibleMembers.front().Member;
tc.diagnose(comp->getIdLoc(), diag::candidate_inaccessible,
comp->getIdentifier(), first->getFormalAccess());
// FIXME: If any of the candidates (usually just one) are in the same module
// we could offer a fix-it.
for (auto lookupResult : inaccessibleMembers)
tc.diagnose(lookupResult.Member, diag::kind_declared_here,
DescriptiveDeclKind::Type);
// Don't try to recover here; we'll get more access-related diagnostics
// downstream if we do.
return ErrorType::get(tc.Context);
}
// 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 {
LookupResult memberLookup;
// Let's try to lookup given identifier as a member of the parent type,
// this allows for more precise diagnostic, which distinguishes between
// identifier not found as a member type vs. not found at all.
NameLookupOptions memberLookupOptions = lookupOptions;
memberLookupOptions |= NameLookupFlags::IgnoreAccessControl;
memberLookupOptions |= NameLookupFlags::KnownPrivate;
memberLookup = tc.lookupMember(dc, parentType, comp->getIdentifier(),
memberLookupOptions);
// Looks like this is not a member type, but simply a member of parent type.
if (!memberLookup.empty()) {
auto member = memberLookup[0].getValueDecl();
tc.diagnose(comp->getIdLoc(), diag::invalid_member_reference,
member->getDescriptiveKind(), comp->getIdentifier(),
parentType)
.highlight(parentRange);
} else {
tc.diagnose(comp->getIdLoc(), diag::invalid_member_type,
comp->getIdentifier(), parentType)
.highlight(parentRange);
}
}
return ErrorType::get(tc.Context);
}
static Type
resolveTopLevelIdentTypeComponent(TypeChecker &TC, DeclContext *DC,
ComponentIdentTypeRepr *comp,
TypeResolutionOptions options,
GenericTypeResolver *resolver);
static Type
resolveGenericSignatureComponent(TypeChecker &TC, DeclContext *DC,
ComponentIdentTypeRepr *comp,
TypeResolutionOptions options,
GenericTypeResolver *resolver) {
if (!DC->isInnermostContextGeneric())
return Type();
auto *genericParams = DC->getGenericParamsOfContext();
if (!isa<ExtensionDecl>(DC)) {
auto matchingParam =
std::find_if(genericParams->begin(), genericParams->end(),
[comp](const GenericTypeParamDecl *param) {
return param->getFullName().matchesRef(comp->getIdentifier());
});
if (matchingParam == genericParams->end())
return Type();
comp->setValue(*matchingParam, nullptr);
return resolveTopLevelIdentTypeComponent(TC, DC, comp, options, resolver);
}
// If we are inside an extension of a nested type, we have to visit
// all outer parameter lists. Otherwise, we will visit them when
// name lookup goes ahead and checks the outer DeclContext.
for (auto *outerParams = genericParams;
outerParams != nullptr;
outerParams = outerParams->getOuterParameters()) {
auto matchingParam =
std::find_if(outerParams->begin(), outerParams->end(),
[comp](const GenericTypeParamDecl *param) {
return param->getFullName().matchesRef(comp->getIdentifier());
});
if (matchingParam != outerParams->end()) {
comp->setValue(*matchingParam, nullptr);
return resolveTopLevelIdentTypeComponent(TC, DC, comp, options, resolver);
}
}
// If the lookup occurs from within a trailing 'where' clause of
// a constrained extension, also look for associated types and typealiases
// in the protocol.
if (genericParams->hasTrailingWhereClause() &&
comp->getIdLoc().isValid() &&
TC.Context.SourceMgr.rangeContainsTokenLoc(
genericParams->getTrailingWhereClauseSourceRange(),
comp->getIdLoc())) {
auto nominal = DC->getAsNominalTypeOrNominalTypeExtensionContext();
SmallVector<ValueDecl *, 4> decls;
if (DC->lookupQualified(nominal->getDeclaredInterfaceType(),
comp->getIdentifier(),
NL_OnlyTypes|NL_QualifiedDefault|NL_ProtocolMembers,
&TC,
decls)) {
for (const auto decl : decls) {
// FIXME: Better ambiguity handling.
auto typeDecl = cast<TypeDecl>(decl);
if (!isa<ProtocolDecl>(typeDecl->getDeclContext())) continue;
comp->setValue(typeDecl, DC);
return resolveTopLevelIdentTypeComponent(TC, DC, comp, options,
resolver);
}
}
}
return Type();
}
/// 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,
GenericTypeResolver *resolver) {
// Short-circuiting.
if (comp->isInvalid()) return ErrorType::get(TC.Context);
// If the component has already been bound to a declaration, handle
// that now.
if (auto *typeDecl = comp->getBoundDecl()) {