-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckGeneric.cpp
1111 lines (928 loc) · 37.2 KB
/
TypeCheckGeneric.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
//===--- TypeCheckGeneric.cpp - Generics ----------------------------------===//
//
// 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 support for generics.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "GenericTypeResolver.h"
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/Basic/Defer.h"
using namespace swift;
Type DependentGenericTypeResolver::resolveGenericTypeParamType(
GenericTypeParamType *gp) {
// Don't resolve generic parameters.
return gp;
}
Type DependentGenericTypeResolver::resolveDependentMemberType(
Type baseTy,
DeclContext *DC,
SourceRange baseRange,
ComponentIdentTypeRepr *ref) {
auto archetype = Builder.resolveArchetype(baseTy);
assert(archetype && "Bad generic context nesting?");
return archetype->getRepresentative()
->getNestedType(ref->getIdentifier(), Builder)
->getDependentType(Builder, true);
}
Type DependentGenericTypeResolver::resolveSelfAssociatedType(
Type selfTy,
DeclContext *DC,
AssociatedTypeDecl *assocType) {
auto archetype = Builder.resolveArchetype(selfTy);
assert(archetype && "Bad generic context nesting?");
return archetype->getRepresentative()
->getNestedType(assocType->getName(), Builder)
->getDependentType(Builder, true);
}
Type DependentGenericTypeResolver::resolveTypeOfContext(DeclContext *dc) {
// FIXME: Should be the interface type of the extension.
return dc->getDeclaredInterfaceType();
}
Type DependentGenericTypeResolver::resolveTypeOfDecl(TypeDecl *decl) {
return decl->getDeclaredInterfaceType();
}
Type GenericTypeToArchetypeResolver::resolveGenericTypeParamType(
GenericTypeParamType *gp) {
auto gpDecl = gp->getDecl();
assert(gpDecl && "Missing generic parameter declaration");
auto archetype = gpDecl->getArchetype();
if (!archetype)
return ErrorType::get(gp->getASTContext());
return archetype;
}
Type GenericTypeToArchetypeResolver::resolveDependentMemberType(
Type baseTy,
DeclContext *DC,
SourceRange baseRange,
ComponentIdentTypeRepr *ref) {
llvm_unreachable("Dependent type after archetype substitution");
}
Type GenericTypeToArchetypeResolver::resolveSelfAssociatedType(
Type selfTy,
DeclContext *DC,
AssociatedTypeDecl *assocType) {
llvm_unreachable("Dependent type after archetype substitution");
}
Type GenericTypeToArchetypeResolver::resolveTypeOfContext(DeclContext *dc) {
return dc->getDeclaredTypeInContext();
}
Type GenericTypeToArchetypeResolver::resolveTypeOfDecl(TypeDecl *decl) {
return decl->getDeclaredType();
}
Type PartialGenericTypeToArchetypeResolver::resolveGenericTypeParamType(
GenericTypeParamType *gp) {
auto gpDecl = gp->getDecl();
if (!gpDecl)
return Type(gp);
auto archetype = gpDecl->getArchetype();
if (!archetype)
return Type(gp);
return archetype;
}
Type PartialGenericTypeToArchetypeResolver::resolveDependentMemberType(
Type baseTy,
DeclContext *DC,
SourceRange baseRange,
ComponentIdentTypeRepr *ref) {
// We don't have enough information to find the associated type.
// FIXME: Nonsense, but we shouldn't need this code anyway.
return DependentMemberType::get(baseTy, ref->getIdentifier(), TC.Context);
}
Type PartialGenericTypeToArchetypeResolver::resolveSelfAssociatedType(
Type selfTy,
DeclContext *DC,
AssociatedTypeDecl *assocType) {
// We don't have enough information to find the associated type.
// FIXME: Nonsense, but we shouldn't need this code anyway.
return DependentMemberType::get(selfTy, assocType, TC.Context);
}
Type
PartialGenericTypeToArchetypeResolver::resolveTypeOfContext(DeclContext *dc) {
return dc->getDeclaredTypeInContext();
}
Type
PartialGenericTypeToArchetypeResolver::resolveTypeOfDecl(TypeDecl *decl) {
return decl->getDeclaredType();
}
Type CompleteGenericTypeResolver::resolveGenericTypeParamType(
GenericTypeParamType *gp) {
// Retrieve the potential archetype corresponding to this generic type
// parameter.
// FIXME: When generic parameters can map down to specific types, do so
// here.
auto pa = Builder.resolveArchetype(gp);
(void)pa;
return gp;
}
Type CompleteGenericTypeResolver::resolveDependentMemberType(
Type baseTy,
DeclContext *DC,
SourceRange baseRange,
ComponentIdentTypeRepr *ref) {
// Resolve the base to a potential archetype.
auto basePA = Builder.resolveArchetype(baseTy);
assert(basePA && "Missing potential archetype for base");
basePA = basePA->getRepresentative();
// Retrieve the potential archetype for the nested type.
auto nestedPA = basePA->getNestedType(ref->getIdentifier(), Builder);
// If this potential archetype was renamed due to typo correction,
// complain and fix it.
if (nestedPA->wasRenamed()) {
auto newName = nestedPA->getName();
TC.diagnose(ref->getIdLoc(), diag::invalid_member_type_suggest,
baseTy, ref->getIdentifier(), newName)
.fixItReplace(ref->getIdLoc(), newName.str());
ref->overwriteIdentifier(newName);
// Go get the actual nested type.
nestedPA = basePA->getNestedType(newName, Builder);
assert(!nestedPA->wasRenamed());
}
// If the nested type has been resolved to an associated type, use it.
if (auto assocType = nestedPA->getResolvedAssociatedType()) {
return DependentMemberType::get(baseTy, assocType, TC.Context);
}
// If the nested type comes from a type alias, use either the alias's
// concrete type, or resolve its components down to another dependent member.
if (auto alias = nestedPA->getTypeAliasDecl()) {
return TC.substMemberTypeWithBase(DC->getParentModule(), alias,
baseTy, true);
}
Identifier name = ref->getIdentifier();
SourceLoc nameLoc = ref->getIdLoc();
// Check whether the name can be found in the superclass.
// FIXME: The archetype builder should be doing this and mapping down to a
// concrete type.
if (auto superclassTy = basePA->getSuperclass()) {
if (auto lookup = TC.lookupMemberType(DC, superclassTy, name)) {
if (lookup.isAmbiguous()) {
TC.diagnoseAmbiguousMemberType(baseTy, baseRange, name, nameLoc,
lookup);
return ErrorType::get(TC.Context);
}
// FIXME: Record (via type sugar) that this was referenced via baseTy.
return lookup.front().second;
}
}
// Complain that there is no suitable type.
TC.diagnose(nameLoc, diag::invalid_member_type, name, baseTy)
.highlight(baseRange);
return ErrorType::get(TC.Context);
}
Type CompleteGenericTypeResolver::resolveSelfAssociatedType(Type selfTy,
DeclContext *DC,
AssociatedTypeDecl *assocType) {
return Builder.resolveArchetype(selfTy)->getRepresentative()
->getNestedType(assocType->getName(), Builder)
->getDependentType(Builder, false);
}
Type CompleteGenericTypeResolver::resolveTypeOfContext(DeclContext *dc) {
// FIXME: Should be the interface type of the extension.
return dc->getDeclaredInterfaceType();
}
Type CompleteGenericTypeResolver::resolveTypeOfDecl(TypeDecl *decl) {
return decl->getDeclaredInterfaceType();
}
/// Check the generic parameters in the given generic parameter list (and its
/// parent generic parameter lists) according to the given resolver.
bool TypeChecker::checkGenericParamList(ArchetypeBuilder *builder,
GenericParamList *genericParams,
GenericSignature *parentSig,
bool adoptArchetypes,
GenericTypeResolver *resolver) {
bool invalid = false;
// If there is a parent context, add the generic parameters and requirements
// from that context.
if (builder)
builder->addGenericSignature(parentSig, adoptArchetypes);
// If there aren't any generic parameters at this level, we're done.
if (!genericParams)
return false;
assert(genericParams->size() > 0 && "Parsed an empty generic parameter list?");
// Determine where and how to perform name lookup for the generic
// parameter lists and where clause.
TypeResolutionOptions options;
DeclContext *lookupDC = genericParams->begin()[0]->getDeclContext();
if (!lookupDC->isModuleScopeContext()) {
assert(isa<GenericTypeDecl>(lookupDC) || isa<ExtensionDecl>(lookupDC) ||
isa<AbstractFunctionDecl>(lookupDC) &&
"not a proper generic parameter context?");
options = TR_GenericSignature;
}
// First, set the depth of each generic parameter, and add them to the
// archetype builder. Do this before checking the inheritance clause,
// since it may itself be dependent on one of these parameters.
unsigned depth = genericParams->getDepth();
for (auto param : *genericParams) {
param->setDepth(depth);
if (builder) {
if (builder->addGenericParameter(param))
invalid = true;
}
}
// Now, check the inheritance clauses of each parameter.
for (auto param : *genericParams) {
checkInheritanceClause(param, resolver);
if (builder) {
builder->addGenericParameterRequirements(param);
// Infer requirements from the inherited types.
for (const auto &inherited : param->getInherited()) {
if (builder->inferRequirements(inherited, genericParams))
invalid = true;
}
}
}
// Visit each of the requirements, adding them to the builder.
// Add the requirements clause to the builder, validating the types in
// the requirements clause along the way.
for (auto &req : genericParams->getRequirements()) {
if (req.isInvalid())
continue;
switch (req.getKind()) {
case RequirementReprKind::TypeConstraint: {
// Validate the types.
if (validateType(req.getSubjectLoc(), lookupDC, options, resolver)) {
invalid = true;
req.setInvalid();
continue;
}
if (validateType(req.getConstraintLoc(), lookupDC, options,
resolver)) {
invalid = true;
req.setInvalid();
continue;
}
// FIXME: Feels too early to perform this check.
if (!req.getConstraint()->isExistentialType() &&
!req.getConstraint()->getClassOrBoundGenericClass()) {
diagnose(genericParams->getWhereLoc(),
diag::requires_conformance_nonprotocol,
req.getSubjectLoc(), req.getConstraintLoc());
req.getConstraintLoc().setInvalidType(Context);
invalid = true;
req.setInvalid();
continue;
}
break;
}
case RequirementReprKind::SameType:
if (validateType(req.getFirstTypeLoc(), lookupDC, options,
resolver)) {
invalid = true;
req.setInvalid();
continue;
}
if (validateType(req.getSecondTypeLoc(), lookupDC, options,
resolver)) {
invalid = true;
req.setInvalid();
continue;
}
break;
}
if (builder && builder->addRequirement(req)) {
invalid = true;
req.setInvalid();
}
}
return invalid;
}
/// Collect all of the generic parameter types at every level in the generic
/// parameter list.
static void collectGenericParamTypes(
GenericParamList *genericParams,
GenericSignature *parentSig,
SmallVectorImpl<GenericTypeParamType *> &allParams) {
// If the parent context has a generic signature, add its generic parameters.
if (parentSig) {
allParams.append(parentSig->getGenericParams().begin(),
parentSig->getGenericParams().end());
}
if (genericParams) {
// Add our parameters.
for (auto param : *genericParams) {
allParams.push_back(param->getDeclaredType()
->castTo<GenericTypeParamType>());
}
}
}
/// Check the signature of a generic function.
static bool checkGenericFuncSignature(TypeChecker &tc,
ArchetypeBuilder *builder,
AbstractFunctionDecl *func,
GenericTypeResolver &resolver) {
bool badType = false;
func->setIsBeingTypeChecked();
// Check the generic parameter list.
auto genericParams = func->getGenericParams();
tc.checkGenericParamList(builder, genericParams,
func->getDeclContext()->getGenericSignatureOfContext(),
false, &resolver);
// Check the parameter patterns.
for (auto params : func->getParameterLists()) {
// Check the pattern.
if (tc.typeCheckParameterList(params, func, TypeResolutionOptions(),
&resolver))
badType = true;
// Infer requirements from the pattern.
if (builder) {
builder->inferRequirements(params, genericParams);
}
}
// If there is a declared result type, check that as well.
if (auto fn = dyn_cast<FuncDecl>(func)) {
if (!fn->getBodyResultTypeLoc().isNull()) {
// Check the result type of the function.
TypeResolutionOptions options;
if (fn->hasDynamicSelf())
options |= TR_DynamicSelfResult;
if (tc.validateType(fn->getBodyResultTypeLoc(), fn, options, &resolver)) {
badType = true;
}
// Infer requirements from it.
if (builder && fn->getBodyResultTypeLoc().getTypeRepr()) {
builder->inferRequirements(fn->getBodyResultTypeLoc(), genericParams);
}
}
}
func->setIsBeingTypeChecked(false);
return badType;
}
static Type getResultType(TypeChecker &TC, FuncDecl *fn, Type resultType) {
// Look through optional types.
OptionalTypeKind optKind;
if (auto origValueType = resultType->getAnyOptionalObjectType(optKind)) {
// Get the interface type of the result.
Type ifaceValueType = getResultType(TC, fn, origValueType);
// Preserve the optional type's original spelling if the interface
// type is the same as the original.
if (origValueType.getPointer() == ifaceValueType.getPointer()) {
return resultType;
}
// Wrap the interface type in the right kind of optional.
switch (optKind) {
case OTK_None: llvm_unreachable("impossible");
case OTK_Optional:
return OptionalType::get(ifaceValueType);
case OTK_ImplicitlyUnwrappedOptional:
return ImplicitlyUnwrappedOptionalType::get(ifaceValueType);
}
llvm_unreachable("bad optional kind");
}
// Rewrite dynamic self to the appropriate interface type.
if (resultType->is<DynamicSelfType>()) {
return fn->getDynamicSelfInterface();
}
// Weird hacky special case.
if (!fn->getBodyResultTypeLoc().hasLocation() &&
fn->isGenericContext()) {
// FIXME: This should not be rewritten. This is only needed in cases where
// we synthesize a function which returns a generic value. In that case,
// the return type is specified in terms of archetypes, but has no TypeLoc
// in the TypeRepr. Because of this, Sema isn't able to rebuild it in
// terms of interface types. When interface types prevail, this should be
// removed. Until then, we hack the mapping here.
return ArchetypeBuilder::mapTypeOutOfContext(fn, resultType);
}
return resultType;
}
void TypeChecker::markInvalidGenericSignature(ValueDecl *VD) {
GenericParamList *genericParams;
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(VD))
genericParams = AFD->getGenericParams();
else
genericParams = cast<GenericTypeDecl>(VD)->getGenericParams();
// If there aren't any generic parameters at this level, we're done.
if (genericParams == nullptr)
return;
DeclContext *DC = VD->getDeclContext();
ArchetypeBuilder builder = createArchetypeBuilder(DC->getParentModule());
if (auto sig = DC->getGenericSignatureOfContext())
builder.addGenericSignature(sig, true);
// Visit each of the generic parameters.
for (auto param : *genericParams)
builder.addGenericParameter(param);
// Wire up the archetypes.
for (auto GP : *genericParams)
GP->setArchetype(builder.getArchetype(GP));
genericParams->setAllArchetypes(
Context.AllocateCopy(builder.getAllArchetypes()));
}
bool TypeChecker::validateGenericFuncSignature(AbstractFunctionDecl *func) {
bool invalid = false;
// Create the archetype builder.
ArchetypeBuilder builder = createArchetypeBuilder(func->getParentModule());
// Type check the function declaration, treating all generic type
// parameters as dependent, unresolved.
DependentGenericTypeResolver dependentResolver(builder);
if (checkGenericFuncSignature(*this, &builder, func, dependentResolver))
invalid = true;
// If this triggered a recursive validation, back out: we're done.
// FIXME: This is an awful hack.
if (func->hasType())
return !func->isInvalid();
// Finalize the generic requirements.
(void)builder.finalize(func->getLoc());
// The archetype builder now has all of the requirements, although there might
// still be errors that have not yet been diagnosed. Revert the generic
// function signature and type-check it again, completely.
revertGenericFuncSignature(func);
CompleteGenericTypeResolver completeResolver(*this, builder);
if (checkGenericFuncSignature(*this, nullptr, func, completeResolver))
invalid = true;
// The generic function signature is complete and well-formed. Determine
// the type of the generic function.
// Collect the complete set of generic parameter types.
SmallVector<GenericTypeParamType *, 4> allGenericParams;
collectGenericParamTypes(func->getGenericParams(),
func->getDeclContext()->getGenericSignatureOfContext(),
allGenericParams);
auto sig = builder.getGenericSignature(allGenericParams);
// Debugging of the archetype builder and generic signature generation.
if (sig && Context.LangOpts.DebugGenericSignatures) {
func->dumpRef(llvm::errs());
llvm::errs() << "\n";
builder.dump(llvm::errs());
llvm::errs() << "Generic signature: ";
sig->print(llvm::errs());
llvm::errs() << "\n";
llvm::errs() << "Canonical generic signature: ";
sig->getCanonicalSignature()->print(llvm::errs());
llvm::errs() << "\n";
llvm::errs() << "Canonical generic signature for mangling: ";
sig->getCanonicalManglingSignature(*func->getParentModule())
->print(llvm::errs());
llvm::errs() << "\n";
}
func->setGenericSignature(sig);
if (invalid) {
func->overwriteType(ErrorType::get(Context));
func->setInterfaceType(ErrorType::get(Context));
return true;
}
configureInterfaceType(func);
return false;
}
void TypeChecker::configureInterfaceType(AbstractFunctionDecl *func) {
Type funcTy;
Type initFuncTy;
auto *sig = func->getGenericSignature();
if (auto fn = dyn_cast<FuncDecl>(func)) {
funcTy = fn->getBodyResultTypeLoc().getType();
if (!funcTy) {
funcTy = TupleType::getEmpty(Context);
} else {
funcTy = getResultType(*this, fn, funcTy);
}
} else if (auto ctor = dyn_cast<ConstructorDecl>(func)) {
auto *dc = ctor->getDeclContext();
funcTy = dc->getSelfInterfaceType();
// Adjust result type for failability.
if (ctor->getFailability() != OTK_None)
funcTy = OptionalType::get(ctor->getFailability(), funcTy);
initFuncTy = funcTy;
} else {
assert(isa<DestructorDecl>(func));
funcTy = TupleType::getEmpty(Context);
}
auto paramLists = func->getParameterLists();
SmallVector<ParameterList*, 4> storedParamLists;
// FIXME: Destructors don't have the '()' pattern in their signature, so
// paste it here.
if (isa<DestructorDecl>(func)) {
assert(paramLists.size() == 1 && "Only the self paramlist");
storedParamLists.push_back(paramLists[0]);
storedParamLists.push_back(ParameterList::createEmpty(Context));
paramLists = storedParamLists;
}
bool hasSelf = func->getDeclContext()->isTypeContext();
for (unsigned i = 0, e = paramLists.size(); i != e; ++i) {
Type argTy;
Type initArgTy;
Type selfTy;
if (i == e-1 && hasSelf) {
selfTy = func->computeInterfaceSelfType(/*isInitializingCtor=*/false);
// Substitute in our own 'self' parameter.
argTy = selfTy;
if (initFuncTy) {
initArgTy = func->computeInterfaceSelfType(/*isInitializingCtor=*/true);
}
} else {
argTy = paramLists[e - i - 1]->getInterfaceType(func);
if (initFuncTy)
initArgTy = argTy;
}
auto info = applyFunctionTypeAttributes(func, i);
if (sig && i == e-1) {
funcTy = GenericFunctionType::get(sig, argTy, funcTy, info);
if (initFuncTy)
initFuncTy = GenericFunctionType::get(sig, initArgTy, initFuncTy, info);
} else {
funcTy = FunctionType::get(argTy, funcTy, info);
if (initFuncTy)
initFuncTy = FunctionType::get(initArgTy, initFuncTy, info);
}
}
// Record the interface type.
assert(!funcTy->hasArchetype());
func->setInterfaceType(funcTy);
if (initFuncTy) {
assert(!initFuncTy->hasArchetype());
cast<ConstructorDecl>(func)->setInitializerInterfaceType(initFuncTy);
}
if (func->getGenericParams()) {
// Collect all generic params referenced in parameter types,
// return type or requirements.
SmallPtrSet<GenericTypeParamDecl *, 4> referencedGenericParams;
auto visitorFn = [&referencedGenericParams](Type t) {
if (auto *paramTy = t->getAs<GenericTypeParamType>())
referencedGenericParams.insert(paramTy->getDecl());
};
funcTy->castTo<AnyFunctionType>()->getInput().visit(visitorFn);
funcTy->castTo<AnyFunctionType>()->getResult().visit(visitorFn);
auto requirements = sig->getRequirements();
for (auto req : requirements) {
if (req.getKind() == RequirementKind::SameType) {
// Same type requirements may allow for generic
// inference, even if this generic parameter
// is not mentioned in the function signature.
// TODO: Make the test more precise.
auto left = req.getFirstType();
auto right = req.getSecondType();
// For now consider any references inside requirements
// as a possibility to infer the generic type.
left.visit(visitorFn);
right.visit(visitorFn);
}
}
// Find the depth of the function's own generic parameters.
unsigned fnGenericParamsDepth = func->getGenericParams()->getDepth();
// Check that every generic parameter type from the signature is
// among referencedArchetypes.
for (auto *genParam : sig->getGenericParams()) {
auto *paramDecl = genParam->getDecl();
if (paramDecl->getDepth() != fnGenericParamsDepth)
continue;
if (!referencedGenericParams.count(paramDecl)) {
// Produce an error that this generic parameter cannot be bound.
diagnose(paramDecl->getLoc(), diag::unreferenced_generic_parameter,
paramDecl->getNameStr());
func->setInvalid();
}
}
}
}
GenericSignature *TypeChecker::validateGenericSignature(
GenericParamList *genericParams,
DeclContext *dc,
GenericSignature *outerSignature,
std::function<bool(ArchetypeBuilder &)> inferRequirements,
bool &invalid) {
assert(genericParams && "Missing generic parameters?");
// Create the archetype builder.
Module *module = dc->getParentModule();
ArchetypeBuilder builder = createArchetypeBuilder(module);
auto *parentSig = (outerSignature
? outerSignature
: dc->getGenericSignatureOfContext());
// Type check the generic parameters, treating all generic type
// parameters as dependent, unresolved.
DependentGenericTypeResolver dependentResolver(builder);
if (checkGenericParamList(&builder, genericParams, parentSig,
false, &dependentResolver)) {
invalid = true;
}
/// Perform any necessary requirement inference.
if (inferRequirements && inferRequirements(builder)) {
invalid = true;
}
// Finalize the generic requirements.
(void)builder.finalize(genericParams->getSourceRange().Start);
// The archetype builder now has all of the requirements, although there might
// still be errors that have not yet been diagnosed. Revert the signature
// and type-check it again, completely.
revertGenericParamList(genericParams);
CompleteGenericTypeResolver completeResolver(*this, builder);
if (checkGenericParamList(nullptr, genericParams, parentSig,
false, &completeResolver)) {
invalid = true;
}
// The generic signature is complete and well-formed. Gather the
// generic parameter types at all levels.
SmallVector<GenericTypeParamType *, 4> allGenericParams;
collectGenericParamTypes(genericParams, parentSig, allGenericParams);
// Record the generic type parameter types and the requirements.
auto sig = builder.getGenericSignature(allGenericParams);
// Debugging of the archetype builder and generic signature generation.
if (Context.LangOpts.DebugGenericSignatures) {
dc->printContext(llvm::errs());
llvm::errs() << "\n";
builder.dump(llvm::errs());
llvm::errs() << "Generic signature: ";
sig->print(llvm::errs());
llvm::errs() << "\n";
llvm::errs() << "Canonical generic signature: ";
sig->getCanonicalSignature()->print(llvm::errs());
llvm::errs() << "\n";
llvm::errs() << "Canonical generic signature for mangling: ";
sig->getCanonicalManglingSignature(*dc->getParentModule())
->print(llvm::errs());
llvm::errs() << "\n";
}
return sig;
}
static void revertDependentTypeLoc(TypeLoc &tl) {
// If there's no type representation, there's nothing to revert.
if (!tl.getTypeRepr())
return;
// Don't revert an error type; we've already complained.
if (tl.wasValidated() && tl.isError())
return;
// Make sure we validate the type again.
tl.setType(Type(), /*validated=*/false);
}
/// Finalize the given generic parameter list, assigning archetypes to
/// the generic parameters.
void TypeChecker::finalizeGenericParamList(ArchetypeBuilder &builder,
GenericParamList *genericParams,
DeclContext *dc) {
Accessibility access;
if (auto *fd = dyn_cast<FuncDecl>(dc))
access = fd->getFormalAccess();
else if (auto *nominal = dyn_cast<NominalTypeDecl>(dc))
access = nominal->getFormalAccess();
else
access = Accessibility::Internal;
// Wire up the archetypes.
for (auto GP : *genericParams) {
GP->setArchetype(builder.getArchetype(GP));
checkInheritanceClause(GP);
if (!GP->hasAccessibility())
GP->setAccessibility(access);
}
genericParams->setAllArchetypes(
Context.AllocateCopy(builder.getAllArchetypes()));
#ifndef NDEBUG
// Record archetype contexts.
for (auto archetype : genericParams->getAllArchetypes()) {
if (Context.ArchetypeContexts.count(archetype) == 0)
Context.ArchetypeContexts[archetype] = dc;
}
#endif
// Replace the generic parameters with their archetypes throughout the
// types in the requirements.
// FIXME: This should not be necessary at this level; it is a transitional
// step.
for (auto &Req : genericParams->getRequirements()) {
if (Req.isInvalid())
continue;
switch (Req.getKind()) {
case RequirementReprKind::TypeConstraint: {
revertDependentTypeLoc(Req.getSubjectLoc());
if (validateType(Req.getSubjectLoc(), dc)) {
Req.setInvalid();
continue;
}
revertDependentTypeLoc(Req.getConstraintLoc());
if (validateType(Req.getConstraintLoc(), dc)) {
Req.setInvalid();
continue;
}
break;
}
case RequirementReprKind::SameType:
revertDependentTypeLoc(Req.getFirstTypeLoc());
if (validateType(Req.getFirstTypeLoc(), dc)) {
Req.setInvalid();
continue;
}
revertDependentTypeLoc(Req.getSecondTypeLoc());
if (validateType(Req.getSecondTypeLoc(), dc)) {
Req.setInvalid();
continue;
}
break;
}
}
}
/// Revert the dependent types within the given generic parameter list.
void TypeChecker::revertGenericParamList(GenericParamList *genericParams) {
// Revert the inherited clause of the generic parameter list.
for (auto param : *genericParams) {
param->setCheckedInheritanceClause(false);
for (auto &inherited : param->getInherited())
revertDependentTypeLoc(inherited);
}
// Revert the requirements of the generic parameter list.
for (auto &req : genericParams->getRequirements()) {
if (req.isInvalid())
continue;
switch (req.getKind()) {
case RequirementReprKind::TypeConstraint: {
revertDependentTypeLoc(req.getSubjectLoc());
revertDependentTypeLoc(req.getConstraintLoc());
break;
}
case RequirementReprKind::SameType:
revertDependentTypeLoc(req.getFirstTypeLoc());
revertDependentTypeLoc(req.getSecondTypeLoc());
break;
}
}
}
bool TypeChecker::validateGenericTypeSignature(GenericTypeDecl *typeDecl) {
bool invalid = false;
if (typeDecl->isValidatingGenericSignature())
return invalid;
typeDecl->setIsValidatingGenericSignature();
SWIFT_DEFER { typeDecl->setIsValidatingGenericSignature(false); };
auto *gp = typeDecl->getGenericParams();
auto *dc = typeDecl->getDeclContext();
auto sig = validateGenericSignature(gp, dc, nullptr, nullptr, invalid);
assert(sig->getInnermostGenericParams().size()
== typeDecl->getGenericParams()->size());
typeDecl->setGenericSignature(sig);
if (invalid) {
markInvalidGenericSignature(typeDecl);
return invalid;
}
revertGenericParamList(gp);
ArchetypeBuilder builder =
createArchetypeBuilder(typeDecl->getModuleContext());
auto *parentSig = dc->getGenericSignatureOfContext();
checkGenericParamList(&builder, gp, parentSig);
finalizeGenericParamList(builder, gp, typeDecl);
return invalid;
}
void TypeChecker::revertGenericFuncSignature(AbstractFunctionDecl *func) {
// Revert the result type.
if (auto fn = dyn_cast<FuncDecl>(func))
if (!fn->getBodyResultTypeLoc().isNull())
revertDependentTypeLoc(fn->getBodyResultTypeLoc());
// Revert the body parameter types.
for (auto paramList : func->getParameterLists()) {
for (auto ¶m : *paramList) {
// Clear out the type of the decl.
if (param->hasType() && !param->isInvalid())
param->overwriteType(Type());
revertDependentTypeLoc(param->getTypeLoc());
}
}
// Revert the generic parameter list.
if (func->getGenericParams())
revertGenericParamList(func->getGenericParams());
// Clear out the types.
if (auto fn = dyn_cast<FuncDecl>(func))
fn->revertType();
else
func->overwriteType(Type());
}
/// Create a text string that describes the bindings of generic parameters that
/// are relevant to the given set of types, e.g., "[with T = Bar, U = Wibble]".
///
/// \param types The types that will be scanned for generic type parameters,
/// which will be used in the resulting type.
///
/// \param genericParams The actual generic parameters, whose names will be used
/// in the resulting text.
///
/// \param substitutions The generic parameter -> generic argument substitutions
/// that will have been applied to these types. These are used to produce the
/// "parameter = argument" bindings in the test.
static std::string gatherGenericParamBindingsText(
ArrayRef<Type> types,
ArrayRef<GenericTypeParamType *> genericParams,
TypeSubstitutionMap &substitutions) {
llvm::SmallPtrSet<GenericTypeParamType *, 2> knownGenericParams;
for (auto type : types) {
type.findIf([&](Type type) -> bool {
if (auto gp = type->getAs<GenericTypeParamType>()) {
knownGenericParams.insert(gp->getCanonicalType()
->castTo<GenericTypeParamType>());
}
return false;
});
}
if (knownGenericParams.empty())
return "";
SmallString<128> result;
for (auto gp : genericParams) {
auto canonGP = gp->getCanonicalType()->castTo<GenericTypeParamType>();
if (!knownGenericParams.count(canonGP))
continue;
if (result.empty())
result += " [with ";
else
result += ", ";
result += gp->getName().str();
result += " = ";
result += substitutions[canonGP].getString();
}
result += "]";
return result.str().str();
}
bool TypeChecker::checkGenericArguments(DeclContext *dc, SourceLoc loc,
SourceLoc noteLoc,
Type owner,