-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckType.cpp
5469 lines (4706 loc) · 204 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 "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckProtocol.h"
#include "TypeCheckType.h"
#include "TypoCorrection.h"
#include "swift/AST/ASTDemangler.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PackExpansionMatcher.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SILLayout.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/TypeResolutionStage.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/SILTypeResolutionContext.h"
#include "swift/Strings.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclTemplate.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;
#define DEBUG_TYPE "TypeCheckType"
/// Type resolution.
TypeResolution
TypeResolution::forStructural(DeclContext *dc, TypeResolutionOptions options,
OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler,
OpenPackElementFn packElementOpener) {
return TypeResolution(dc, {}, TypeResolutionStage::Structural, options,
unboundTyOpener, placeholderHandler, packElementOpener);
}
TypeResolution
TypeResolution::forInterface(DeclContext *dc, TypeResolutionOptions options,
OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler,
OpenPackElementFn packElementOpener) {
return forInterface(dc, dc->getGenericSignatureOfContext(), options,
unboundTyOpener, placeholderHandler, packElementOpener);
}
TypeResolution
TypeResolution::forInterface(DeclContext *dc, GenericSignature genericSig,
TypeResolutionOptions options,
OpenUnboundGenericTypeFn unboundTyOpener,
HandlePlaceholderTypeReprFn placeholderHandler,
OpenPackElementFn packElementOpener) {
return TypeResolution(dc, genericSig, TypeResolutionStage::Interface, options,
unboundTyOpener, placeholderHandler, packElementOpener);
}
TypeResolution TypeResolution::withOptions(TypeResolutionOptions opts) const {
return TypeResolution(dc, genericSig, stage, opts, unboundTyOpener,
placeholderHandler, packElementOpener);
}
TypeResolution TypeResolution::withoutPackElementOpener() const {
return TypeResolution(dc, genericSig, stage, options, unboundTyOpener,
placeholderHandler, {});
}
ASTContext &TypeResolution::getASTContext() const {
return dc->getASTContext();
}
GenericSignature TypeResolution::getGenericSignature() const {
assert(
stage == TypeResolutionStage::Interface &&
"Structural resolution shouldn't require generic signature computation");
if (genericSig)
return genericSig;
return dc->getGenericSignatureOfContext();
}
// FIXME: It would be nice to have a 'DescriptiveTypeKind' abstraction instead.
static DescriptiveDeclKind describeDeclOfType(Type t) {
if (!t) {
return DescriptiveDeclKind::Type;
}
if (auto *NTD = t->getAnyNominal()) {
return NTD->getDescriptiveKind();
}
return DescriptiveDeclKind::Type;
}
static unsigned getGenericRequirementKind(TypeResolutionOptions options) {
switch (options.getBaseContext()) {
case TypeResolverContext::GenericRequirement:
case TypeResolverContext::SameTypeRequirement:
return 0;
case TypeResolverContext::GenericParameterInherited:
return 1;
case TypeResolverContext::AssociatedTypeInherited:
return 2;
case TypeResolverContext::None:
case TypeResolverContext::Inherited:
case TypeResolverContext::FunctionInput:
case TypeResolverContext::PackElement:
case TypeResolverContext::TupleElement:
case TypeResolverContext::GenericArgument:
case TypeResolverContext::ProtocolGenericArgument:
case TypeResolverContext::ExtensionBinding:
case TypeResolverContext::TypeAliasDecl:
case TypeResolverContext::GenericTypeAliasDecl:
case TypeResolverContext::ExistentialConstraint:
case TypeResolverContext::MetatypeBase:
case TypeResolverContext::InExpression:
case TypeResolverContext::ExplicitCastExpr:
case TypeResolverContext::ForEachStmt:
case TypeResolverContext::PatternBindingDecl:
case TypeResolverContext::EditorPlaceholderExpr:
case TypeResolverContext::ClosureExpr:
case TypeResolverContext::VariadicFunctionInput:
case TypeResolverContext::InoutFunctionInput:
case TypeResolverContext::FunctionResult:
case TypeResolverContext::SubscriptDecl:
case TypeResolverContext::EnumElementDecl:
case TypeResolverContext::MacroDecl:
case TypeResolverContext::EnumPatternPayload:
case TypeResolverContext::ProtocolMetatypeBase:
case TypeResolverContext::ImmediateOptionalTypeArgument:
case TypeResolverContext::AbstractFunctionDecl:
case TypeResolverContext::CustomAttr:
break;
}
llvm_unreachable("Invalid type resolution context");
}
Type TypeResolution::resolveDependentMemberType(Type baseTy, DeclContext *DC,
SourceRange baseRange,
IdentTypeRepr *repr) const {
// FIXME(ModQual): Reject qualified names immediately; they cannot be
// dependent member types.
Identifier refIdentifier = repr->getNameRef().getBaseIdentifier();
ASTContext &ctx = DC->getASTContext();
switch (stage) {
case TypeResolutionStage::Structural:
return DependentMemberType::get(baseTy, refIdentifier);
case TypeResolutionStage::Interface:
// Handled below.
break;
}
assert(stage == TypeResolutionStage::Interface);
auto genericSig = getGenericSignature();
if (!genericSig)
return ErrorType::get(baseTy);
// Look for a nested type with the given name.
if (auto nestedType = genericSig->lookupNestedType(baseTy, refIdentifier)) {
if (options.isGenericRequirement()) {
if (auto *protoDecl = nestedType->getDeclContext()->getExtendedProtocolDecl()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
unsigned kind = getGenericRequirementKind(options);
ctx.Diags.diagnose(repr->getNameLoc(),
diag::protocol_extension_in_where_clause,
nestedType->getName(), protoDecl->getName(), kind);
if (protoDecl->getLoc() && nestedType->getLoc()) {
ctx.Diags.diagnose(nestedType->getLoc(),
diag::protocol_extension_in_where_clause_note,
nestedType->getName(), protoDecl->getName());
}
}
return ErrorType::get(ctx);
}
}
// Record the type we found.
repr->setValue(nestedType, nullptr);
} else {
// Resolve the base to a potential archetype.
// Perform typo correction.
TypoCorrectionResults corrections(repr->getNameRef(), repr->getNameLoc());
TypeChecker::performTypoCorrection(DC, DeclRefKind::Ordinary,
MetatypeType::get(baseTy),
defaultMemberLookupOptions,
corrections, genericSig);
// Check whether we have a single type result.
auto singleType = cast_or_null<TypeDecl>(
corrections.getUniqueCandidateMatching([](ValueDecl *result) {
return isa<TypeDecl>(result);
}));
// If we don't have a single result, complain and fail.
if (!singleType) {
auto name = repr->getNameRef();
auto nameLoc = repr->getNameLoc();
const auto kind = describeDeclOfType(baseTy);
ctx.Diags.diagnose(nameLoc, diag::invalid_member_type, name, kind, baseTy)
.highlight(baseRange);
corrections.noteAllCandidates();
return ErrorType::get(ctx);
}
// We have a single type result. Suggest it.
ctx.Diags
.diagnose(repr->getNameLoc(), diag::invalid_member_type_suggest, baseTy,
repr->getNameRef(), singleType->getBaseName())
.fixItReplace(repr->getNameLoc().getSourceRange(),
singleType->getBaseName().userFacingName());
// Correct to the single type result.
repr->setValue(singleType, nullptr);
}
auto *concrete = repr->getBoundDecl();
if (auto concreteBase = genericSig->getConcreteType(baseTy)) {
bool hasUnboundOpener = !!getUnboundTypeOpener();
switch (TypeChecker::isUnsupportedMemberTypeAccess(concreteBase, concrete,
hasUnboundOpener)) {
case TypeChecker::UnsupportedMemberTypeAccessKind::TypeAliasOfExistential:
ctx.Diags.diagnose(repr->getNameLoc(),
diag::typealias_outside_of_protocol,
repr->getNameRef(), concreteBase);
break;
case TypeChecker::UnsupportedMemberTypeAccessKind::AssociatedTypeOfExistential:
ctx.Diags.diagnose(repr->getNameLoc(),
diag::assoc_type_outside_of_protocol,
repr->getNameRef(), concreteBase);
break;
default:
break;
};
}
// If the nested type has been resolved to an associated type, use it.
if (auto assocType = dyn_cast<AssociatedTypeDecl>(concrete)) {
return DependentMemberType::get(baseTy, assocType);
}
// There are two situations possible here:
//
// 1. Member comes from the protocol, which means that it has been
// found through a conformance constraint placed on base e.g. `T: P`.
// In this case member is a `typealias` declaration located in
// protocol or protocol extension.
//
// 2. Member comes from struct/enum/class type, which means that it
// has been found through same-type constraint on base e.g. `T == Q`.
//
// If this is situation #2 we need to make sure to switch base to
// a concrete type (according to equivalence class) otherwise we'd
// end up using incorrect generic signature while attempting to form
// a substituted type for the member we found.
if (!concrete->getDeclContext()->getSelfProtocolDecl()) {
if (auto concreteTy = genericSig->getConcreteType(baseTy))
baseTy = concreteTy;
else {
baseTy = genericSig->getSuperclassBound(baseTy);
assert(baseTy);
}
}
return TypeChecker::substMemberTypeWithBase(DC->getParentModule(), concrete,
baseTy);
}
bool TypeResolution::areSameType(Type type1, Type type2) const {
if (type1->isEqual(type2))
return true;
// If neither type has a type parameter, we're done.
if (!type1->hasTypeParameter() && !type2->hasTypeParameter()) {
return false;
}
if (stage == TypeResolutionStage::Interface) {
// If we have a generic signature, canonicalize using it.
if (auto genericSig = getGenericSignature()) {
// If both are type parameters, we can use a cheaper check
// that avoids transforming the type and computing anchors.
if (type1->isTypeParameter() && type2->isTypeParameter()) {
return genericSig->areReducedTypeParametersEqual(type1, type2);
}
return genericSig.getReducedType(type1) ==
genericSig.getReducedType(type2);
}
}
assert(stage == TypeResolutionStage::Structural);
return false;
}
Type TypeChecker::getOptionalType(SourceLoc loc, Type elementType) {
ASTContext &ctx = elementType->getASTContext();
if (!ctx.getOptionalDecl()) {
ctx.Diags.diagnose(loc, diag::sugar_type_not_found, 1);
return ErrorType::get(ctx);
}
return OptionalType::get(elementType);
}
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 dc->getASTContext().getBridgedToObjC(dc, valueType);
}
/// Retrieve the identity form of the opaque type archetype type.
static Type getOpaqueArchetypeIdentity(
OpaqueTypeDecl *opaqueDecl, unsigned ordinal) {
auto outerGenericSignature = opaqueDecl->getNamingDecl()
->getInnermostDeclContext()
->getGenericSignatureOfContext();
SubstitutionMap subs;
if (outerGenericSignature)
subs = outerGenericSignature->getIdentitySubstitutionMap();
Type interfaceType = opaqueDecl->getOpaqueGenericParams()[ordinal];
return OpaqueTypeArchetypeType::get(opaqueDecl, interfaceType, subs);
}
/// Adjust the underlying type of a typealias within the given context to
/// account for @preconcurrency.
static Type adjustTypeAliasTypeInContext(
Type type, TypeAliasDecl *aliasDecl, DeclContext *fromDC,
TypeResolutionOptions options) {
// If we are in a @preconcurrency declaration, don't adjust the types of
// type aliases.
if (options.contains(TypeResolutionFlags::Preconcurrency))
return type;
// If the type alias itself isn't marked with @preconcurrency, don't
// adjust the type.
if (!aliasDecl->preconcurrency())
return type;
// Only adjust the type within a strict concurrency context, so we don't
// change the types as seen by code that hasn't adopted concurrency.
if (contextRequiresStrictConcurrencyChecking(
fromDC,
[](const AbstractClosureExpr *closure) {
return closure->getType();
},
[](const ClosureExpr *closure) {
return closure->isIsolatedByPreconcurrency();
}))
return type;
return type->stripConcurrency(
/*recurse=*/true, /*dropGlobalActor=*/true);
}
Type TypeResolution::resolveTypeInContext(TypeDecl *typeDecl,
DeclContext *foundDC,
bool isSpecialized) const {
auto fromDC = getDeclContext();
ASTContext &ctx = fromDC->getASTContext();
// If we found a generic parameter, map to the archetype if there is one.
if (auto genericParam = dyn_cast<GenericTypeParamDecl>(typeDecl)) {
// If this generic parameter is for an opaque type, map to the opened
// archetype.
if (auto opaqueDecl = dyn_cast<OpaqueTypeDecl>(getDeclContext())) {
if (genericParam->getDepth() ==
opaqueDecl->getOpaqueGenericParams().front()->getDepth()) {
return getOpaqueArchetypeIdentity(opaqueDecl, genericParam->getIndex());
}
}
return genericParam->getDeclaredInterfaceType();
}
/// Call this function before returning the underlying type of a typealias,
/// to adjust its type for concurrency.
auto adjustAliasType = [&](Type type) -> Type {
return adjustTypeAliasTypeInContext(
type, cast<TypeAliasDecl>(typeDecl), fromDC, options);
};
if (!isSpecialized) {
// 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)) {
for (auto *parentDC = fromDC; !parentDC->isModuleScopeContext();
parentDC = parentDC->getParentForLookup()) {
auto *parentNominal = parentDC->getSelfNominalTypeDecl();
if (parentNominal == nominalType)
return parentDC->getDeclaredInterfaceType();
if (isa<ExtensionDecl>(parentDC)) {
auto *extendedType = parentNominal;
while (extendedType != nullptr) {
if (extendedType == nominalType)
return extendedType->getDeclaredInterfaceType();
extendedType = extendedType->getParent()->getSelfNominalTypeDecl();
}
}
}
}
// If we're inside an extension of a type alias, allow the type alias to be
// referenced without generic arguments as well.
if (auto *aliasDecl = dyn_cast<TypeAliasDecl>(typeDecl)) {
for (auto *parentDC = fromDC; !parentDC->isModuleScopeContext();
parentDC = parentDC->getParentForLookup()) {
if (auto *ext = dyn_cast<ExtensionDecl>(parentDC)) {
auto extendedType = ext->getExtendedType();
if (auto *unboundGeneric =
dyn_cast<UnboundGenericType>(extendedType.getPointer())) {
if (auto *ugAliasDecl =
dyn_cast<TypeAliasDecl>(unboundGeneric->getAnyGeneric())) {
if (ugAliasDecl == aliasDecl) {
if (getStage() == TypeResolutionStage::Structural &&
aliasDecl->getUnderlyingTypeRepr() != nullptr) {
return adjustAliasType(aliasDecl->getStructuralType());
}
return adjustAliasType(aliasDecl->getDeclaredInterfaceType());
}
extendedType = unboundGeneric->getParent();
continue;
}
}
if (auto *aliasType =
dyn_cast<TypeAliasType>(extendedType.getPointer())) {
if (aliasType->getDecl() == aliasDecl) {
if (getStage() == TypeResolutionStage::Structural &&
aliasDecl->getUnderlyingTypeRepr() != nullptr) {
return adjustAliasType(aliasDecl->getStructuralType());
}
return adjustAliasType(aliasDecl->getDeclaredInterfaceType());
}
extendedType = aliasType->getParent();
continue;
}
}
}
}
}
// 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, return the appropriate type.
if (getStage() == TypeResolutionStage::Structural &&
aliasDecl->getUnderlyingTypeRepr() != nullptr) {
return adjustAliasType(aliasDecl->getStructuralType());
}
return adjustAliasType(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()->getSelfProtocolDecl()) {
// 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(ctx);
selfType = foundDC->getDeclaredInterfaceType();
} else {
// Otherwise, we want the protocol 'Self' type for
// substituting into alias types and associated types.
selfType = foundDC->getSelfInterfaceType();
if (selfType->is<GenericTypeParamType>()) {
if (isa<ProtocolDecl>(typeDecl->getDeclContext())) {
if (isa<AssociatedTypeDecl>(typeDecl) ||
(isa<TypeAliasDecl>(typeDecl) &&
!cast<TypeAliasDecl>(typeDecl)->isGeneric() &&
!isSpecialized)) {
if (getStage() == TypeResolutionStage::Structural) {
return DependentMemberType::get(selfType, typeDecl->getName());
} else if (auto assocType = dyn_cast<AssociatedTypeDecl>(typeDecl)) {
typeDecl = assocType->getAssociatedTypeAnchor();
}
}
}
if (typeDecl->getDeclContext()->getSelfClassDecl()) {
// 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();
if (!sig)
return ErrorType::get(ctx);
auto superclassType = sig->getSuperclassBound(selfType);
if (!superclassType)
return ErrorType::get(ctx);
selfType = superclassType;
}
}
}
// Finally, substitute the base type into the member type.
return TypeChecker::substMemberTypeWithBase(
fromDC->getParentModule(), typeDecl, selfType, /*useArchetypes=*/false);
}
/// 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->isUnsafePointer() && !BGT->isUnsafeMutablePointer())
return false;
IsMutable = BGT->isUnsafeMutablePointer();
assert(BGT->getGenericArgs().size() == 1);
return BGT->getGenericArgs().front()->isVoid();
}
bool TypeChecker::checkContextualRequirements(GenericTypeDecl *decl,
Type parentTy, SourceLoc loc,
ModuleDecl *module,
GenericSignature contextSig) {
assert(parentTy && "expected a parent type");
if (parentTy->hasUnboundGenericType() || parentTy->hasTypeVariable()) {
return true;
}
SourceLoc noteLoc;
{
// We are interested in either a contextual where clause or
// a constrained extension context.
const auto ext = dyn_cast<ExtensionDecl>(decl->getDeclContext());
if (decl->getTrailingWhereClause())
noteLoc = decl->getLoc();
else if (ext && ext->isConstrainedExtension())
noteLoc = ext->getLoc();
else
return true;
if (noteLoc.isInvalid())
noteLoc = loc;
}
const auto subMap = parentTy->getContextSubstitutions(decl->getDeclContext());
const auto genericSig = decl->getGenericSignature();
const auto substitutions = [&](SubstitutableType *type) -> Type {
auto result = QueryTypeSubstitutionMap{subMap}(type);
if (result->hasTypeParameter()) {
if (contextSig) {
auto *genericEnv = contextSig.getGenericEnvironment();
return genericEnv->mapTypeIntoContext(result);
}
}
return result;
};
const auto result = TypeChecker::checkGenericArgumentsForDiagnostics(
module, genericSig.getRequirements(), substitutions);
switch (result) {
case CheckGenericArgumentsResult::RequirementFailure:
if (loc.isValid()) {
TypeChecker::diagnoseRequirementFailure(
result.getRequirementFailureInfo(), loc, noteLoc,
decl->getDeclaredInterfaceType(), genericSig.getGenericParams(),
substitutions, module);
}
return false;
case CheckGenericArgumentsResult::SubstitutionFailure:
return false;
case CheckGenericArgumentsResult::Success:
return true;
}
llvm_unreachable("invalid requirement check type");
}
/// Apply generic arguments to the given type.
///
/// If the type is itself not generic, this does nothing.
///
/// This function emits diagnostics about an invalid type or the wrong number
/// of generic arguments, whereas
/// \c TypeResolution::applyUnboundGenericArguments requires this
/// to be in a correct and valid form.
///
/// \param type The generic type to which to apply arguments.
/// \param resolution The type resolution to perform.
/// \param silContext Used to look up generic parameters in SIL mode.
/// \param repr The arguments to apply with the angle bracket range for
/// diagnostics.
///
/// \returns A BoundGenericType bound to the given arguments, or null on
/// error.
///
/// \see TypeResolution::applyUnboundGenericArguments
static Type applyGenericArguments(Type type, TypeResolution resolution,
SILTypeResolutionContext *silContext,
IdentTypeRepr *repr) {
auto options = resolution.getOptions();
auto dc = resolution.getDeclContext();
auto loc = repr->getNameLoc().getBaseNameLoc();
auto *generic = dyn_cast<GenericIdentTypeRepr>(repr);
if (!generic) {
if (auto *const unboundTy = type->getAs<UnboundGenericType>()) {
if (!options.is(TypeResolverContext::TypeAliasDecl) &&
!options.is(TypeResolverContext::ExtensionBinding)) {
// If the resolution object carries an opener, attempt to open
// the unbound generic type.
// TODO: We should be able to just open the generic arguments as N
// different PlaceholderTypes.
if (const auto openerFn = resolution.getUnboundTypeOpener())
if (const auto boundTy = openerFn(unboundTy))
return boundTy;
return type;
}
}
if (resolution.getStage() == TypeResolutionStage::Structural)
return type;
GenericTypeDecl *decl;
Type parentTy;
if (auto *aliasTy = dyn_cast<TypeAliasType>(type.getPointer())) {
decl = aliasTy->getDecl();
parentTy = aliasTy->getParent();
} else if (auto *nominalTy = type->getAs<NominalType>()) {
decl = nominalTy->getDecl();
parentTy = nominalTy->getParent();
} else {
return type;
}
if (!parentTy) {
return type;
}
if (TypeChecker::checkContextualRequirements(
decl, parentTy, loc, dc->getParentModule(),
resolution.getGenericSignature()))
return type;
return ErrorType::get(resolution.getASTContext());
}
if (type->hasError()) {
generic->setInvalid();
return type;
}
auto &ctx = dc->getASTContext();
auto &diags = ctx.Diags;
auto genericArgs = generic->getGenericArgs();
if (auto *protoType = type->getAs<ProtocolType>()) {
auto *protoDecl = protoType->getDecl();
auto assocTypes = protoDecl->getPrimaryAssociatedTypes();
if (assocTypes.empty()) {
diags.diagnose(loc, diag::protocol_does_not_have_primary_assoc_type,
protoType)
.fixItRemove(generic->getAngleBrackets());
if (!protoDecl->isImplicit()) {
diags.diagnose(protoDecl, diag::decl_declared_here,
protoDecl->getName());
}
return ErrorType::get(ctx);
}
if (genericArgs.size() != assocTypes.size()) {
diags.diagnose(loc,
diag::parameterized_protocol_type_argument_count_mismatch,
protoType, genericArgs.size(), assocTypes.size(),
(genericArgs.size() < assocTypes.size()) ? 1 : 0);
return ErrorType::get(ctx);
}
// Build ParameterizedProtocolType if the protocol has a primary associated
// type and we're in a supported context.
if (resolution.getOptions().isConstraintImplicitExistential() &&
!ctx.LangOpts.hasFeature(Feature::ImplicitSome)) {
if (!genericArgs.empty()) {
SmallVector<Type, 2> argTys;
for (auto *genericArg : genericArgs) {
Type argTy = resolution.resolveType(genericArg);
if (!argTy || argTy->hasError())
return ErrorType::get(ctx);
argTys.push_back(argTy);
}
auto parameterized =
ParameterizedProtocolType::get(ctx, protoType, argTys);
diags.diagnose(loc, diag::existential_requires_any, parameterized,
ExistentialType::get(parameterized),
/*isAlias=*/isa<TypeAliasType>(type.getPointer()));
} else {
diags.diagnose(loc, diag::existential_requires_any,
protoDecl->getDeclaredInterfaceType(),
protoDecl->getDeclaredExistentialType(),
/*isAlias=*/isa<TypeAliasType>(type.getPointer()));
}
return ErrorType::get(ctx);
}
// Disallow opaque types anywhere in the structure of the generic arguments
// to a parameterized existential type.
if (options.is(TypeResolverContext::ExistentialConstraint))
options |= TypeResolutionFlags::DisallowOpaqueTypes;
auto argOptions = options.withoutContext().withContext(
TypeResolverContext::GenericArgument);
auto genericResolution = resolution.withOptions(argOptions);
SmallVector<Type, 2> argTys;
for (auto *genericArg : genericArgs) {
Type argTy = genericResolution.resolveType(genericArg, silContext);
if (!argTy || argTy->hasError())
return ErrorType::get(ctx);
argTys.push_back(argTy);
}
return ParameterizedProtocolType::get(ctx, protoType, argTys);
}
// We must either have an unbound generic type, or a generic type alias.
if (!type->is<UnboundGenericType>()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
auto diag = diags.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 ErrorType::get(ctx);
}
auto *unboundType = type->castTo<UnboundGenericType>();
auto *decl = unboundType->getDecl();
// Make sure we have the right number of generic arguments.
auto genericParams = decl->getGenericParams();
auto hasParameterPack = llvm::any_of(
*genericParams, [](auto *paramDecl) {
return paramDecl->isParameterPack();
});
// Resolve the types of the generic arguments.
auto argOptions = options.withoutContext().withContext(
TypeResolverContext::GenericArgument);
auto genericResolution = resolution.withOptions(argOptions);
// 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()) {
genericResolution = resolution;
}
}
}
SmallVector<Type, 2> args;
for (auto tyR : genericArgs) {
// Propagate failure.
Type substTy = genericResolution.resolveType(tyR, silContext);
if (!substTy || substTy->hasError())
return ErrorType::get(ctx);
args.push_back(substTy);
}
if (!hasParameterPack) {
// For generic types without type parameter packs, we require
// the number of declared generic parameters match the number of
// arguments.
if (genericArgs.size() != genericParams->size()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
diags
.diagnose(loc, diag::type_parameter_count_mismatch, decl->getName(),
genericParams->size(),
genericArgs.size(),
genericArgs.size() < genericParams->size(),
/*hasParameterPack=*/0)
.highlight(generic->getAngleBrackets());
decl->diagnose(diag::kind_declname_declared_here,
DescriptiveDeclKind::GenericType, decl->getName());
}
return ErrorType::get(ctx);
}
} else {
// For generic types with type parameter packs, we only require
// that the number of arguments is enough to saturate the number of
// regular generic parameters. The parameter pack will absorb
// zero or arguments.
SmallVector<Type, 2> params;
for (auto paramDecl : genericParams->getParams()) {
auto paramType = paramDecl->getDeclaredInterfaceType();
params.push_back(paramDecl->isParameterPack()
? PackExpansionType::get(paramType, paramType)
: paramType);
}
PackMatcher matcher(params, args, ctx);
if (matcher.match()) {
if (!options.contains(TypeResolutionFlags::SilenceErrors)) {
diags
.diagnose(loc, diag::type_parameter_count_mismatch, decl->getName(),
genericParams->size() - 1,
genericArgs.size(),
genericArgs.size() < genericParams->size(),
/*hasParameterPack=*/1)
.highlight(generic->getAngleBrackets());
decl->diagnose(diag::kind_declname_declared_here,
DescriptiveDeclKind::GenericType, decl->getName());
}
return ErrorType::get(ctx);
}
args.clear();
for (unsigned i : indices(params)) {
auto found = std::find_if(matcher.pairs.begin(),
matcher.pairs.end(),
[&](const MatchedPair &pair) -> bool {
return pair.lhsIdx == i;
});
assert(found != matcher.pairs.end());
auto arg = found->rhs;
// PackMatcher will always produce a PackExpansionType as the
// arg for a pack parameter, if necessary by wrapping a PackType
// in one. (It's a weird representation.) Look for that pattern
// and unwrap the pack. Otherwise, we must have matched with a
// single component which happened to be an expansion; wrap that
// in a PackType. In either case, we always want arg to end up
// a PackType.
if (auto *expansionType = arg->getAs<PackExpansionType>()) {
auto pattern = expansionType->getPatternType();
if (auto pack = pattern->getAs<PackType>()) {
arg = pack;
} else {
arg = PackType::get(ctx, {expansionType});
}
}
args.push_back(arg);
}
}
const auto result = resolution.applyUnboundGenericArguments(
decl, unboundType->getParent(), loc, args);
// Migration hack.
bool isMutablePointer;
if (isPointerToVoid(dc->getASTContext(), result, isMutablePointer)) {
if (isMutablePointer)
diags.diagnose(loc, diag::use_of_void_pointer, "Mutable").
fixItReplace(generic->getSourceRange(), "UnsafeMutableRawPointer");
else
diags.diagnose(loc, diag::use_of_void_pointer, "").
fixItReplace(generic->getSourceRange(), "UnsafeRawPointer");
}
if (auto clangDecl = decl->getClangDecl()) {
if (auto classTemplateDecl =
dyn_cast<clang::ClassTemplateDecl>(clangDecl)) {
SmallVector<Type, 2> typesOfGenericArgs;
for (auto typeRepr : generic->getGenericArgs()) {
typesOfGenericArgs.push_back(resolution.resolveType(typeRepr));
}
SmallVector<clang::TemplateArgument, 2> templateArguments;
std::unique_ptr<TemplateInstantiationError> error =
ctx.getClangTemplateArguments(
classTemplateDecl->getTemplateParameters(), typesOfGenericArgs,
templateArguments);
if (error) {
std::string failedTypesStr;
llvm::raw_string_ostream failedTypesStrStream(failedTypesStr);
llvm::interleaveComma(error->failedTypes, failedTypesStrStream);
// TODO: This error message should not reference implementation details.
// See: https://github.com/apple/swift/pull/33053#discussion_r477003350
ctx.Diags.diagnose(
loc, diag::unable_to_convert_generic_swift_types.ID,
{classTemplateDecl->getName(), StringRef(failedTypesStr)});
return ErrorType::get(ctx);
}
auto *clangModuleLoader = decl->getASTContext().getClangModuleLoader();
auto instantiatedDecl = clangModuleLoader->instantiateCXXClassTemplate(
const_cast<clang::ClassTemplateDecl *>(classTemplateDecl),
templateArguments);
if (instantiatedDecl) {
instantiatedDecl->setTemplateInstantiationType(result);
return instantiatedDecl->getDeclaredInterfaceType();
} else {
diags.diagnose(loc, diag::cxx_class_instantiation_failed);
return ErrorType::get(ctx);
}
}
}
return result;
}
/// if any of the generic args are a concrete move-only type, emit an error.
/// returns true iff an error diagnostic was emitted