forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathType.cpp
3260 lines (2735 loc) · 106 KB
/
Type.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
//===--- Type.cpp - Swift Language Type ASTs ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the Type class and subclasses.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/Types.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/AST.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/TypeLoc.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <functional>
#include <iterator>
using namespace swift;
using llvm::Fixnum;
bool TypeLoc::isError() const {
assert(wasValidated() && "Type not yet validated");
return getType()->is<ErrorType>();
}
SourceRange TypeLoc::getSourceRange() const {
if (TyR)
return TyR->getSourceRange();
return SourceRange();
}
// Only allow allocation of Types using the allocator in ASTContext.
void *TypeBase::operator new(size_t bytes, const ASTContext &ctx,
AllocationArena arena, unsigned alignment) {
return ctx.Allocate(bytes, alignment, arena);
}
bool CanType::isActuallyCanonicalOrNull() const {
return getPointer() == 0 ||
getPointer() == llvm::DenseMapInfo<TypeBase*>::getTombstoneKey() ||
getPointer()->isCanonical();
}
//===----------------------------------------------------------------------===//
// Various Type Methods.
//===----------------------------------------------------------------------===//
/// isEqual - Return true if these two types are equal, ignoring sugar.
bool TypeBase::isEqual(Type Other) {
return getCanonicalType() == Other.getPointer()->getCanonicalType();
}
/// hasReferenceSemantics - Does this type have reference semantics?
bool TypeBase::hasReferenceSemantics() {
return getCanonicalType().hasReferenceSemantics();
}
bool TypeBase::isAnyClassReferenceType() {
return getCanonicalType().isAnyClassReferenceType();
}
bool CanType::isReferenceTypeImpl(CanType type, bool functionsCount) {
switch (type->getKind()) {
#define SUGARED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("sugared canonical type?");
// These types are always class references.
case TypeKind::BuiltinUnknownObject:
case TypeKind::BuiltinNativeObject:
case TypeKind::BuiltinBridgeObject:
case TypeKind::Class:
case TypeKind::BoundGenericClass:
case TypeKind::SILBox:
return true;
// For Self types, recur on the underlying type.
case TypeKind::DynamicSelf:
return isReferenceTypeImpl(cast<DynamicSelfType>(type).getSelfType(),
functionsCount);
// Archetypes and existentials are only class references if class-bounded.
case TypeKind::Archetype:
return cast<ArchetypeType>(type)->requiresClass();
case TypeKind::Protocol:
return cast<ProtocolType>(type)->requiresClass();
case TypeKind::ProtocolComposition:
return cast<ProtocolCompositionType>(type)->requiresClass();
case TypeKind::UnboundGeneric:
return isa<ClassDecl>(cast<UnboundGenericType>(type)->getDecl());
// Functions have reference semantics, but are not class references.
case TypeKind::Function:
case TypeKind::PolymorphicFunction:
case TypeKind::GenericFunction:
case TypeKind::SILFunction:
return functionsCount;
// Nothing else is statically just a class reference.
case TypeKind::SILBlockStorage:
case TypeKind::Error:
case TypeKind::Unresolved:
case TypeKind::BuiltinInteger:
case TypeKind::BuiltinFloat:
case TypeKind::BuiltinRawPointer:
case TypeKind::BuiltinUnsafeValueBuffer:
case TypeKind::BuiltinVector:
case TypeKind::Tuple:
case TypeKind::Enum:
case TypeKind::Struct:
case TypeKind::Metatype:
case TypeKind::ExistentialMetatype:
case TypeKind::Module:
case TypeKind::LValue:
case TypeKind::InOut:
case TypeKind::TypeVariable:
case TypeKind::BoundGenericEnum:
case TypeKind::BoundGenericStruct:
case TypeKind::UnownedStorage:
case TypeKind::UnmanagedStorage:
case TypeKind::WeakStorage:
return false;
case TypeKind::GenericTypeParam:
case TypeKind::DependentMember:
llvm_unreachable("Dependent types can't answer reference-semantics query");
}
llvm_unreachable("Unhandled type kind!");
}
/// hasOwnership - Are variables of this type permitted to have
/// ownership attributes?
///
/// This includes:
/// - class types, generic or not
/// - archetypes with class or class protocol bounds
/// - existentials with class or class protocol bounds
/// But not:
/// - function types
bool TypeBase::allowsOwnership() {
return getCanonicalType().isAnyClassReferenceType();
}
bool TypeBase::isAnyExistentialType(SmallVectorImpl<ProtocolDecl*> &protocols) {
return getCanonicalType().isAnyExistentialType(protocols);
}
bool CanType::isAnyExistentialTypeImpl(CanType type,
SmallVectorImpl<ProtocolDecl*> &protocols) {
if (auto metatype = dyn_cast<ExistentialMetatypeType>(type)) {
metatype.getInstanceType().getAnyExistentialTypeProtocols(protocols);
return true;
}
return isExistentialTypeImpl(type, protocols);
}
bool TypeBase::isExistentialType(SmallVectorImpl<ProtocolDecl *> &protocols) {
return getCanonicalType().isExistentialType(protocols);
}
bool CanType::isExistentialTypeImpl(CanType type,
SmallVectorImpl<ProtocolDecl*> &protocols) {
if (auto proto = dyn_cast<ProtocolType>(type)) {
proto.getAnyExistentialTypeProtocols(protocols);
return true;
}
if (auto comp = dyn_cast<ProtocolCompositionType>(type)) {
comp.getAnyExistentialTypeProtocols(protocols);
return true;
}
assert(!type.isExistentialType());
return false;
}
void TypeBase::getAnyExistentialTypeProtocols(
SmallVectorImpl<ProtocolDecl*> &protocols) {
getCanonicalType().getAnyExistentialTypeProtocols(protocols);
}
void CanType::getAnyExistentialTypeProtocolsImpl(CanType type,
SmallVectorImpl<ProtocolDecl*> &protocols) {
if (auto proto = dyn_cast<ProtocolType>(type)) {
proto.getAnyExistentialTypeProtocols(protocols);
} else if (auto comp = dyn_cast<ProtocolCompositionType>(type)) {
comp.getAnyExistentialTypeProtocols(protocols);
} else if (auto metatype = dyn_cast<ExistentialMetatypeType>(type)) {
metatype.getAnyExistentialTypeProtocols(protocols);
} else {
llvm_unreachable("type was not any kind of existential type!");
}
}
bool TypeBase::isObjCExistentialType() {
return getCanonicalType().isObjCExistentialType();
}
bool CanType::isObjCExistentialTypeImpl(CanType type) {
if (!type.isExistentialType()) return false;
SmallVector<ProtocolDecl *, 4> protocols;
type.getAnyExistentialTypeProtocols(protocols);
// Must have at least one protocol to be class-bounded.
if (protocols.empty())
return false;
// Any non-AnyObject, non-@objc protocol makes this no longer ObjC-compatible.
for (auto proto : protocols) {
if (proto->isSpecificProtocol(KnownProtocolKind::AnyObject))
continue;
if (proto->isObjC())
continue;
return false;
}
return true;
}
bool TypeBase::isSpecialized() {
CanType CT = getCanonicalType();
if (CT.getPointer() != this)
return CT->isSpecialized();
return CT.findIf([](Type type) -> bool {
return isa<BoundGenericType>(type.getPointer());
});
}
ArrayRef<Type> TypeBase::getAllGenericArgs(SmallVectorImpl<Type> &scratch) {
Type type(this);
SmallVector<ArrayRef<Type>, 2> allGenericArgs;
while (type) {
// Gather generic arguments from a bound generic type.
if (auto bound = type->getAs<BoundGenericType>()) {
allGenericArgs.push_back(bound->getGenericArgs());
// Continue up to the parent.
type = bound->getParent();
continue;
}
// Use the generic type parameter types for an unbound generic type.
if (auto unbound = type->getAs<UnboundGenericType>()) {
auto genericSig = unbound->getDecl()->getGenericSignature();
auto genericParams = genericSig->getInnermostGenericParams();
allGenericArgs.push_back(
llvm::makeArrayRef((const Type *)genericParams.data(),
genericParams.size()));
// Continue up to the parent.
type = unbound->getParent();
continue;
}
// For a protocol type, use its Self parameter.
if (auto protoType = type->getAs<ProtocolType>()) {
auto proto = protoType->getDecl();
allGenericArgs.push_back(
llvm::makeArrayRef(
proto->getProtocolSelf()->getDeclaredInterfaceType()));
// Continue up to the parent.
type = protoType->getParent();
continue;
}
// Look through non-generic nominal types.
if (auto nominal = type->getAs<NominalType>()) {
type = nominal->getParent();
continue;
}
break;
}
// Trivial case: no generic arguments.
if (allGenericArgs.empty())
return { };
// Common case: a single set of generic arguments, for which we need no
// allocation.
if (allGenericArgs.size() == 1)
return allGenericArgs.front();
// General case: concatenate all of the generic argument lists together.
scratch.clear();
for (auto args : reversed(allGenericArgs))
scratch.append(args.begin(), args.end());
return scratch;
}
ArrayRef<Substitution>
TypeBase::gatherAllSubstitutions(Module *module,
SmallVectorImpl<Substitution> &scratchSpace,
LazyResolver *resolver,
DeclContext *gpContext) {
Type type(this);
SmallVector<ArrayRef<Substitution>, 2> allSubstitutions;
scratchSpace.clear();
while (type) {
// Record the substitutions in a bound generic type.
if (auto boundGeneric = type->getAs<BoundGenericType>()) {
allSubstitutions.push_back(boundGeneric->getSubstitutions(module,
resolver,
gpContext));
type = boundGeneric->getParent();
if (gpContext)
gpContext = gpContext->getParent();
continue;
}
// Skip to the parent of a nominal type.
if (auto nominal = type->getAs<NominalType>()) {
type = nominal->getParent();
if (gpContext)
gpContext = gpContext->getParent();
continue;
}
llvm_unreachable("Not a nominal or bound generic type");
}
// If there are no substitutions, return an empty array.
if (allSubstitutions.empty())
return { };
// If there is only one list of substitutions, return it. There's no
// need to copy it.
if (allSubstitutions.size() == 1)
return allSubstitutions.front();
for (auto substitutions : allSubstitutions)
scratchSpace.append(substitutions.begin(), substitutions.end());
return scratchSpace;
}
ArrayRef<Substitution> TypeBase::gatherAllSubstitutions(Module *module,
LazyResolver *resolver,
DeclContext *gpContext){
SmallVector<Substitution, 4> scratchSpace;
auto subs = gatherAllSubstitutions(module, scratchSpace, resolver,
gpContext);
if (scratchSpace.empty())
return subs;
return getASTContext().AllocateCopy(subs);
}
bool TypeBase::isUnspecializedGeneric() {
CanType CT = getCanonicalType();
if (CT.getPointer() != this)
return CT->isUnspecializedGeneric();
switch (getKind()) {
#define SUGARED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
return false;
case TypeKind::Error:
case TypeKind::Unresolved:
case TypeKind::TypeVariable:
llvm_unreachable("querying invalid type");
case TypeKind::UnboundGeneric:
return true;
case TypeKind::BoundGenericClass:
case TypeKind::BoundGenericEnum:
case TypeKind::BoundGenericStruct:
return true;
case TypeKind::Function:
case TypeKind::PolymorphicFunction: {
auto funcTy = cast<AnyFunctionType>(this);
return funcTy->getInput()->isUnspecializedGeneric() ||
funcTy->getResult()->isUnspecializedGeneric();
}
case TypeKind::GenericFunction:
return true;
case TypeKind::Class:
case TypeKind::Struct:
case TypeKind::Enum:
if (auto parentTy = cast<NominalType>(this)->getParent())
return parentTy->isUnspecializedGeneric();
return false;
case TypeKind::ExistentialMetatype:
case TypeKind::Metatype:
return cast<AnyMetatypeType>(this)->getInstanceType()
->isUnspecializedGeneric();
case TypeKind::UnownedStorage:
case TypeKind::UnmanagedStorage:
case TypeKind::WeakStorage:
return cast<ReferenceStorageType>(this)->getReferentType()
->isUnspecializedGeneric();
case TypeKind::LValue:
return cast<LValueType>(this)->getObjectType()->isUnspecializedGeneric();
case TypeKind::InOut:
return cast<InOutType>(this)->getObjectType()->isUnspecializedGeneric();
case TypeKind::Tuple: {
auto tupleTy = cast<TupleType>(this);
for (auto &Elt : tupleTy->getElements())
if (Elt.getType()->isUnspecializedGeneric())
return true;
return false;
}
case TypeKind::Archetype:
case TypeKind::BuiltinFloat:
case TypeKind::BuiltinInteger:
case TypeKind::BuiltinUnknownObject:
case TypeKind::BuiltinNativeObject:
case TypeKind::BuiltinBridgeObject:
case TypeKind::BuiltinRawPointer:
case TypeKind::BuiltinUnsafeValueBuffer:
case TypeKind::BuiltinVector:
case TypeKind::Module:
case TypeKind::DynamicSelf:
case TypeKind::Protocol:
case TypeKind::ProtocolComposition:
case TypeKind::SILFunction:
return false;
case TypeKind::GenericTypeParam:
case TypeKind::DependentMember:
return false;
case TypeKind::SILBlockStorage:
return cast<SILBlockStorageType>(this)->getCaptureType()
->isUnspecializedGeneric();
case TypeKind::SILBox:
return cast<SILBoxType>(this)->getBoxedType()
->isUnspecializedGeneric();
}
llvm_unreachable("bad TypeKind");
}
bool TypeBase::hasOpenedExistential(ArchetypeType *opened) {
assert(opened->getOpenedExistentialType() &&
"not an opened existential type");
if (!hasOpenedExistential())
return false;
return getCanonicalType().findIf([&](Type type) -> bool {
return opened == dyn_cast<ArchetypeType>(type.getPointer());
});
}
void TypeBase::getOpenedExistentials(
SmallVectorImpl<ArchetypeType *> &opened) {
if (!hasOpenedExistential())
return;
SmallPtrSet<ArchetypeType *, 4> known;
getCanonicalType().findIf([&](Type type) -> bool {
auto archetype = dyn_cast<ArchetypeType>(type.getPointer());
if (!archetype)
return false;
if (!archetype->getOpenedExistentialType())
return false;
if (known.insert(archetype).second)
opened.push_back(archetype);
return false;
});
}
Type TypeBase::eraseOpenedExistential(Module *module,
ArchetypeType *opened) {
assert(opened->getOpenedExistentialType() &&
"Not an opened existential type?");
if (!hasOpenedExistential())
return Type(this);
TypeSubstitutionMap substitutions;
substitutions[opened] = opened->getOpenedExistentialType();
return Type(this).subst(module, substitutions, None);
}
void
TypeBase::getTypeVariables(SmallVectorImpl<TypeVariableType *> &typeVariables) {
// If we know we don't have any type variables, we're done.
if (hasTypeVariable()) {
// Use Type::findIf() to walk the types, finding type variables along the
// way.
getCanonicalType().findIf([&](Type type) -> bool {
if (auto tv = dyn_cast<TypeVariableType>(type.getPointer())) {
typeVariables.push_back(tv);
}
return false;
});
assert(!typeVariables.empty() && "Did not find type variables!");
}
}
static bool isLegalSILType(CanType type) {
if (!type->isMaterializable()) return false;
if (isa<AnyFunctionType>(type)) return false;
if (auto meta = dyn_cast<AnyMetatypeType>(type))
return meta->hasRepresentation();
if (auto tupleType = dyn_cast<TupleType>(type)) {
for (auto eltType : tupleType.getElementTypes()) {
if (!isLegalSILType(eltType)) return false;
}
return true;
}
return true;
}
bool TypeBase::isLegalSILType() {
return ::isLegalSILType(getCanonicalType());
}
bool TypeBase::isVoid() {
return isEqual(getASTContext().TheEmptyTupleType);
}
bool TypeBase::isAssignableType() {
if (isLValueType()) return true;
if (auto tuple = getAs<TupleType>()) {
for (auto eltType : tuple->getElementTypes()) {
if (!eltType->isAssignableType())
return false;
}
return true;
}
return false;
}
namespace {
class GetRValueTypeVisitor : public TypeVisitor<GetRValueTypeVisitor, Type> {
public:
Type visitLValueType(LValueType *lvt) {
// Look through lvalue types.
assert(!lvt->getObjectType()->isLValueType()
&& "unexpected nested lvalue");
return lvt->getObjectType();
}
Type visitTupleType(TupleType *tt) {
// Look through lvalues in tuples.
SmallVector<TupleTypeElt, 4> elts;
for (auto &elt : tt->getElements()) {
elts.push_back(elt.getWithType(visit(elt.getType())));
}
return TupleType::get(elts, tt->getASTContext());
}
Type visitParenType(ParenType *pt) {
return ParenType::get(pt->getASTContext(), visit(pt->getUnderlyingType()));
}
Type visitType(TypeBase *t) {
// Other types should not structurally contain lvalues.
assert(!t->isLValueType()
&& "unexpected structural lvalue");
return t;
}
};
} // end anonymous namespace
Type TypeBase::getRValueType() {
// If the type is not an lvalue, this is a no-op.
if (!isLValueType())
return this;
return GetRValueTypeVisitor().visit(this);
}
Type TypeBase::getOptionalObjectType() {
if (auto boundTy = getAs<BoundGenericEnumType>())
if (boundTy->getDecl()->classifyAsOptionalType() == OTK_Optional)
return boundTy->getGenericArgs()[0];
return Type();
}
Type TypeBase::getImplicitlyUnwrappedOptionalObjectType() {
if (auto boundTy = getAs<BoundGenericEnumType>())
if (boundTy->getDecl()->classifyAsOptionalType() == OTK_ImplicitlyUnwrappedOptional)
return boundTy->getGenericArgs()[0];
return Type();
}
Type TypeBase::getAnyOptionalObjectType(OptionalTypeKind &kind) {
if (auto boundTy = getAs<BoundGenericEnumType>())
if ((kind = boundTy->getDecl()->classifyAsOptionalType()))
return boundTy->getGenericArgs()[0];
kind = OTK_None;
return Type();
}
CanType CanType::getAnyOptionalObjectTypeImpl(CanType type,
OptionalTypeKind &kind) {
if (auto boundTy = dyn_cast<BoundGenericEnumType>(type))
if ((kind = boundTy->getDecl()->classifyAsOptionalType()))
return boundTy.getGenericArgs()[0];
kind = OTK_None;
return CanType();
}
Type TypeBase::getAnyPointerElementType(PointerTypeKind &PTK) {
if (auto boundTy = getAs<BoundGenericType>()) {
auto &C = getASTContext();
if (boundTy->getDecl() == C.getUnsafeMutablePointerDecl()) {
PTK = PTK_UnsafeMutablePointer;
} else if (boundTy->getDecl() == C.getUnsafePointerDecl()) {
PTK = PTK_UnsafePointer;
} else if (
boundTy->getDecl() == C.getAutoreleasingUnsafeMutablePointerDecl()
) {
PTK = PTK_AutoreleasingUnsafeMutablePointer;
} else {
return Type();
}
return boundTy->getGenericArgs()[0];
}
return Type();
}
Type TypeBase::lookThroughAllAnyOptionalTypes() {
Type type(this);
while (auto objType = type->getAnyOptionalObjectType())
type = objType;
return type;
}
Type TypeBase::lookThroughAllAnyOptionalTypes(SmallVectorImpl<Type> &optionals){
Type type(this);
while (auto objType = type->getAnyOptionalObjectType()) {
optionals.push_back(type);
type = objType;
}
return type;
}
ClassDecl *CanType::getClassBoundImpl(CanType type) {
if (auto classTy = dyn_cast<ClassType>(type))
return classTy->getDecl();
if (auto boundTy = dyn_cast<BoundGenericClassType>(type))
return boundTy->getDecl();
if (auto archetypeTy = dyn_cast<ArchetypeType>(type)) {
assert(archetypeTy->requiresClass());
if (Type supertype = archetypeTy->getSuperclass()) {
return supertype->getClassOrBoundGenericClass();
}
return nullptr;
}
llvm_unreachable("class has no class bound!");
}
bool TypeBase::isAnyObject() {
if (auto proto = getAs<ProtocolType>())
return proto->getDecl()->isSpecificProtocol(KnownProtocolKind::AnyObject);
return false;
}
bool TypeBase::isEmptyExistentialComposition() {
if (auto emtType = ExistentialMetatypeType::get(this)) {
if (auto pcType = emtType->getInstanceType()->
getAs<ProtocolCompositionType>()) {
return pcType->getProtocols().empty();
}
}
return false;
}
static Type getStrippedType(const ASTContext &context, Type type,
bool stripLabels, bool stripDefaultArgs) {
return type.transform([&](Type type) -> Type {
auto *tuple = dyn_cast<TupleType>(type.getPointer());
if (!tuple)
return type;
SmallVector<TupleTypeElt, 4> elements;
bool anyChanged = false;
unsigned idx = 0;
for (const auto &elt : tuple->getElements()) {
Type eltTy = getStrippedType(context, elt.getType(),
stripLabels, stripDefaultArgs);
if (anyChanged || eltTy.getPointer() != elt.getType().getPointer() ||
(elt.hasInit() && stripDefaultArgs) ||
(elt.hasName() && stripLabels)) {
if (!anyChanged) {
elements.reserve(tuple->getNumElements());
for (unsigned i = 0; i != idx; ++i) {
const TupleTypeElt &elt = tuple->getElement(i);
Identifier newName = stripLabels? Identifier() : elt.getName();
DefaultArgumentKind newDefArg
= stripDefaultArgs? DefaultArgumentKind::None
: elt.getDefaultArgKind();
elements.push_back(TupleTypeElt(elt.getType(), newName, newDefArg,
elt.isVararg()));
}
anyChanged = true;
}
Identifier newName = stripLabels? Identifier() : elt.getName();
DefaultArgumentKind newDefArg
= stripDefaultArgs? DefaultArgumentKind::None
: elt.getDefaultArgKind();
elements.push_back(TupleTypeElt(eltTy, newName, newDefArg,
elt.isVararg()));
}
++idx;
}
if (!anyChanged)
return type;
// An unlabeled 1-element tuple type is represented as a parenthesized
// type.
if (elements.size() == 1 && !elements[0].isVararg() &&
!elements[0].hasName())
return ParenType::get(context, elements[0].getType());
return TupleType::get(elements, context);
});
}
Type TypeBase::getUnlabeledType(ASTContext &Context) {
return getStrippedType(Context, Type(this), /*labels=*/true,
/*defaultArgs=*/true);
}
Type TypeBase::getRelabeledType(ASTContext &ctx,
ArrayRef<Identifier> labels) {
if (auto tupleTy = dyn_cast<TupleType>(this)) {
assert(labels.size() == tupleTy->getNumElements() &&
"Wrong number of labels");
SmallVector<TupleTypeElt, 4> elements;
unsigned i = 0;
bool anyChanged = false;
for (const auto &elt : tupleTy->getElements()) {
if (elt.getName() != labels[i])
anyChanged = true;
elements.push_back(TupleTypeElt(elt.getType(), labels[i],
elt.getDefaultArgKind(), elt.isVararg()));
++i;
}
if (!anyChanged)
return this;
return TupleType::get(elements, ctx);
}
// If there is no label, the type is unchanged.
if (labels[0].empty())
return this;
// Create a one-element tuple to capture the label.
TupleTypeElt elt(this, labels[0]);
return TupleType::get(elt, ctx);
}
Type TypeBase::getWithoutDefaultArgs(const ASTContext &Context) {
return getStrippedType(Context, Type(this), /*labels=*/false,
/*defaultArgs=*/true);
}
Type TypeBase::getWithoutParens() {
Type Ty = this;
while (auto ParenTy = dyn_cast<ParenType>(Ty.getPointer()))
Ty = ParenTy->getUnderlyingType();
return Ty;
}
Type TypeBase::replaceCovariantResultType(Type newResultType,
unsigned uncurryLevel,
bool preserveOptionality) {
if (uncurryLevel == 0) {
if (preserveOptionality) {
assert(!newResultType->getAnyOptionalObjectType());
OptionalTypeKind resultOTK;
if (getAnyOptionalObjectType(resultOTK))
return OptionalType::get(resultOTK, newResultType);
}
return newResultType;
}
// Determine the input and result types of this function.
auto fnType = this->castTo<AnyFunctionType>();
Type inputType = fnType->getInput();
Type resultType =
fnType->getResult()->replaceCovariantResultType(newResultType,
uncurryLevel - 1,
preserveOptionality);
// Produce the resulting function type.
if (auto genericFn = dyn_cast<GenericFunctionType>(fnType)) {
return GenericFunctionType::get(genericFn->getGenericSignature(),
inputType, resultType,
fnType->getExtInfo());
}
if (auto polyFn = dyn_cast<PolymorphicFunctionType>(fnType)) {
return PolymorphicFunctionType::get(inputType, resultType,
&polyFn->getGenericParams(),
fnType->getExtInfo());
}
return FunctionType::get(inputType, resultType, fnType->getExtInfo());
}
/// Rebuilds the given 'self' type using the given object type as the
/// replacement for the object type of self.
static Type rebuildSelfTypeWithObjectType(Type selfTy, Type objectTy) {
auto existingObjectTy = selfTy->getRValueInstanceType();
return selfTy.transform([=](Type type) -> Type {
if (type->isEqual(existingObjectTy))
return objectTy;
return type;
});
}
/// Returns a new function type exactly like this one but with the self
/// parameter replaced. Only makes sense for members of types.
Type TypeBase::replaceSelfParameterType(Type newSelf) {
auto fnTy = castTo<AnyFunctionType>();
Type input = rebuildSelfTypeWithObjectType(fnTy->getInput(), newSelf);
if (auto genericFnTy = getAs<GenericFunctionType>()) {
return GenericFunctionType::get(genericFnTy->getGenericSignature(),
input,
fnTy->getResult(),
fnTy->getExtInfo());
}
if (auto polyFnTy = getAs<PolymorphicFunctionType>()) {
return PolymorphicFunctionType::get(input,
fnTy->getResult(),
&polyFnTy->getGenericParams());
}
return FunctionType::get(input,
fnTy->getResult(),
fnTy->getExtInfo());
}
Type TypeBase::getWithoutNoReturn(unsigned UncurryLevel) {
if (UncurryLevel == 0)
return this;
auto *FnType = this->castTo<AnyFunctionType>();
Type InputType = FnType->getInput();
Type ResultType = FnType->getResult()->getWithoutNoReturn(UncurryLevel - 1);
auto TheExtInfo = FnType->getExtInfo().withIsNoReturn(false);
if (auto *GFT = dyn_cast<GenericFunctionType>(FnType)) {
return GenericFunctionType::get(GFT->getGenericSignature(),
InputType, ResultType,
TheExtInfo);
}
if (auto *PFT = dyn_cast<PolymorphicFunctionType>(FnType)) {
return PolymorphicFunctionType::get(InputType, ResultType,
&PFT->getGenericParams(),
TheExtInfo);
}
return FunctionType::get(InputType, ResultType, TheExtInfo);
}
/// Retrieve the object type for a 'self' parameter, digging into one-element
/// tuples, inout types, and metatypes.
Type TypeBase::getRValueInstanceType() {
Type type = this;
// Look through argument list tuples.
if (auto tupleTy = type->getAs<TupleType>()) {
if (tupleTy->getNumElements() == 1 && !tupleTy->getElement(0).isVararg())
type = tupleTy->getElementType(0);
}
if (auto metaTy = type->getAs<AnyMetatypeType>())
return metaTy->getInstanceType();
// For mutable value type methods, we need to dig through inout types.
return type->getInOutObjectType();
}
TypeDecl *TypeBase::getDirectlyReferencedTypeDecl() const {
if (auto module = dyn_cast<ModuleType>(this))
return module->getModule();
if (auto nominal = dyn_cast<NominalType>(this))
return nominal->getDecl();
if (auto bound = dyn_cast<BoundGenericType>(this))
return bound->getDecl();
if (auto unbound = dyn_cast<UnboundGenericType>(this))
return unbound->getDecl();
if (auto alias = dyn_cast<NameAliasType>(this))
return alias->getDecl();
if (auto gp = dyn_cast<GenericTypeParamType>(this))
return gp->getDecl();
if (auto depMem = dyn_cast<DependentMemberType>(this))
return depMem->getAssocType();
if (auto archetype = dyn_cast<ArchetypeType>(this)) {
if (auto proto = archetype->getSelfProtocol())
return proto->getProtocolSelf();
if (auto assoc = archetype->getAssocType())
return assoc;
return nullptr;
}
return nullptr;
}
StringRef TypeBase::getInferredDefaultArgString() {
if (auto structDecl = getStructOrBoundGenericStruct()) {
if (structDecl->getClangDecl()) {
for (auto attr : structDecl->getAttrs()) {
if (auto synthesizedProto = dyn_cast<SynthesizedProtocolAttr>(attr)) {
if (synthesizedProto->getProtocolKind()
== KnownProtocolKind::OptionSetType)
return "[]";
}
}
}
}
return "nil";
}
/// \brief Collect the protocols in the existential type T into the given
/// vector.
static void addProtocols(Type T, SmallVectorImpl<ProtocolDecl *> &Protocols) {
if (auto Proto = T->getAs<ProtocolType>()) {
Protocols.push_back(Proto->getDecl());
} else if (auto PC = T->getAs<ProtocolCompositionType>()) {
for (auto P : PC->getProtocols())
addProtocols(P, Protocols);
}
}
/// \brief Add the protocol (or protocols) in the type T to the stack of
/// protocols, checking whether any of the protocols had already been seen and
/// zapping those in the original list that we find again.
static void addMinimumProtocols(Type T,
SmallVectorImpl<ProtocolDecl *> &Protocols,
llvm::SmallDenseMap<ProtocolDecl *, unsigned> &Known,
llvm::SmallPtrSet<ProtocolDecl *, 16> &Visited,
SmallVector<ProtocolDecl *, 16> &Stack,
bool &ZappedAny) {
if (auto Proto = T->getAs<ProtocolType>()) {
auto KnownPos = Known.find(Proto->getDecl());
if (KnownPos != Known.end()) {
// We've come across a protocol that is in our original list. Zap it.
Protocols[KnownPos->second] = nullptr;
ZappedAny = true;