forked from apple/swift
/
GenericSignatureBuilder.h
1723 lines (1437 loc) · 66.8 KB
/
GenericSignatureBuilder.h
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
//===--- GenericSignatureBuilder.h - Generic signature builder --*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// Support for collecting a set of generic requirements, whether they are
// explicitly stated, inferred from a type signature, or implied by other
// requirements, and computing the canonicalized, minimized generic signature
// from those requirements.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_GENERICSIGNATUREBUILDER_H
#define SWIFT_GENERICSIGNATUREBUILDER_H
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/GenericParamList.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/ProtocolConformanceRef.h"
#include "swift/AST/Types.h"
#include "swift/AST/TypeLoc.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/Debug.h"
#include "swift/Basic/LLVM.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FoldingSet.h"
#include "llvm/ADT/ilist.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/TinyPtrVector.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/TrailingObjects.h"
#include <functional>
#include <memory>
namespace swift {
class DeclContext;
class DependentMemberType;
class GenericParamList;
class GenericSignatureBuilder;
class GenericTypeParamType;
class ModuleDecl;
class Pattern;
class ProtocolConformance;
class Requirement;
class RequirementRepr;
class SILModule;
class SourceLoc;
class SubstitutionMap;
class Type;
class TypeRepr;
class ASTContext;
class DiagnosticEngine;
/// Determines how to resolve a dependent type to a potential archetype.
enum class ArchetypeResolutionKind {
/// Only create a potential archetype when it is well-formed (e.g., a nested
/// type should exist) and make sure we have complete information about
/// that potential archetype.
CompleteWellFormed,
/// Only create a new potential archetype to describe this dependent type
/// if it is already known.
AlreadyKnown,
/// Only create a potential archetype when it is well-formed (i.e., we know
/// that there is a nested type with that name), but (unlike \c AlreadyKnown)
/// allow the creation of a new potential archetype.
WellFormed,
};
/// Collects a set of requirements of generic parameters, both explicitly
/// stated and inferred, and determines the set of archetypes for each of
/// the generic parameters.
class GenericSignatureBuilder {
public:
/// Describes a potential archetype, which stands in for a generic parameter
/// type or some type derived from it.
class PotentialArchetype;
using UnresolvedType = llvm::PointerUnion<PotentialArchetype *, Type>;
class ResolvedType;
using UnresolvedRequirementRHS =
llvm::PointerUnion<Type, PotentialArchetype *, LayoutConstraint>;
using RequirementRHS =
llvm::PointerUnion<Type, ProtocolDecl *, LayoutConstraint>;
/// The location of a requirement as written somewhere in the source.
typedef llvm::PointerUnion<const TypeRepr *, const RequirementRepr *>
WrittenRequirementLoc;
class RequirementSource;
class FloatingRequirementSource;
class DelayedRequirement;
template<typename T> struct Constraint;
/// Describes a concrete constraint on a potential archetype where, where the
/// other parameter is a concrete type.
typedef Constraint<Type> ConcreteConstraint;
/// Describes an equivalence class of potential archetypes.
struct EquivalenceClass : llvm::ilist_node<EquivalenceClass> {
/// The list of protocols to which this equivalence class conforms.
///
/// The keys form the (semantic) list of protocols to which this type
/// conforms. The values are the conformance constraints as written on
/// this equivalence class.
llvm::MapVector<ProtocolDecl *, std::vector<Constraint<ProtocolDecl *>>>
conformsTo;
/// Same-type constraints within this equivalence class.
std::vector<Constraint<Type>> sameTypeConstraints;
/// Concrete type to which this equivalence class is equal.
///
/// This is the semantic concrete type; the constraints as written
/// (or implied) are stored in \c concreteTypeConstraints;
Type concreteType;
/// The same-type-to-concrete constraints written within this
/// equivalence class.
std::vector<ConcreteConstraint> concreteTypeConstraints;
/// Superclass constraint, which requires that the type fulfilling the
/// requirements of this equivalence class to be the same as or a subtype
/// of this superclass.
Type superclass;
/// Superclass constraints written within this equivalence class.
std::vector<ConcreteConstraint> superclassConstraints;
/// \The layout constraint for this equivalence class.
LayoutConstraint layout;
/// Layout constraints written within this equivalence class.
std::vector<Constraint<LayoutConstraint>> layoutConstraints;
/// The members of the equivalence class.
///
/// This list of members is slightly ordered, in that the first
/// element always has a depth no greater than the depth of any other
/// member.
TinyPtrVector<PotentialArchetype *> members;
/// Describes a component within the graph of same-type constraints within
/// the equivalence class that is held together by derived constraints.
struct DerivedSameTypeComponent {
/// The type that acts as the anchor for this component.
Type type;
/// The (best) requirement source within the component that makes the
/// potential archetypes in this component equivalent to the concrete
/// type.
const RequirementSource *concreteTypeSource;
};
/// The set of connected components within this equivalence class, using
/// only the derived same-type constraints in the graph.
std::vector<DerivedSameTypeComponent> derivedSameTypeComponents;
/// Delayed requirements that could be resolved by a change to this
/// equivalence class.
std::vector<DelayedRequirement> delayedRequirements;
/// Whether we have detected recursion during the substitution of
/// the concrete type.
unsigned recursiveConcreteType : 1;
/// Whether we have an invalid concrete type.
unsigned invalidConcreteType : 1;
/// Whether we have detected recursion during the substitution of
/// the superclass type.
unsigned recursiveSuperclassType : 1;
/// Construct a new equivalence class containing only the given
/// potential archetype (which represents itself).
EquivalenceClass(PotentialArchetype *representative);
/// Note that this equivalence class has been modified.
void modified(GenericSignatureBuilder &builder);
EquivalenceClass(const EquivalenceClass &) = delete;
EquivalenceClass(EquivalenceClass &&) = delete;
EquivalenceClass &operator=(const EquivalenceClass &) = delete;
EquivalenceClass &operator=(EquivalenceClass &&) = delete;
/// Add a new member to this equivalence class.
void addMember(PotentialArchetype *pa);
/// Record the conformance of this equivalence class to the given
/// protocol as found via the given requirement source.
///
/// \returns true if this conformance is new to the equivalence class,
/// and false otherwise.
bool recordConformanceConstraint(GenericSignatureBuilder &builder,
ResolvedType type,
ProtocolDecl *proto,
const RequirementSource *source);
/// Find a source of the same-type constraint that maps a potential
/// archetype in this equivalence class to a concrete type along with
/// that concrete type as written.
Optional<ConcreteConstraint>
findAnyConcreteConstraintAsWritten(Type preferredType = Type()) const;
/// Find a source of the superclass constraint in this equivalence class
/// that has a type equivalence to \c superclass, along with that
/// superclass type as written.
Optional<ConcreteConstraint>
findAnySuperclassConstraintAsWritten(Type preferredType = Type()) const;
/// Determine whether conformance to the given protocol is satisfied by
/// a superclass requirement.
bool isConformanceSatisfiedBySuperclass(ProtocolDecl *proto) const;
/// Lookup a nested type with the given name within this equivalence
/// class.
///
/// \param otherConcreteTypes If non-null, will be filled in the all of the
/// concrete types we found (other than the result) with the same name.
TypeDecl *lookupNestedType(
GenericSignatureBuilder &builder,
Identifier name,
SmallVectorImpl<TypeDecl *> *otherConcreteTypes = nullptr);
/// Retrieve the "anchor" type that canonically describes this equivalence
/// class, for use in the canonical type.
Type getAnchor(GenericSignatureBuilder &builder,
TypeArrayView<GenericTypeParamType> genericParams);
/// Retrieve (or build) the contextual type corresponding to
/// this equivalence class within the given generic environment.
Type getTypeInContext(GenericSignatureBuilder &builder,
GenericEnvironment *genericEnv);
/// Dump a debugging representation of this equivalence class,
void dump(llvm::raw_ostream &out,
GenericSignatureBuilder *builder = nullptr) const;
SWIFT_DEBUG_DUMPER(dump(GenericSignatureBuilder *builder = nullptr));
/// Caches.
/// The cached archetype anchor.
struct {
/// The cached anchor itself.
Type anchor;
/// The generation at which the anchor was last computed.
unsigned lastGeneration;
} archetypeAnchorCache;
/// Describes a cached nested type.
struct CachedNestedType {
unsigned numConformancesPresent;
CanType superclassPresent;
CanType concreteTypePresent;
llvm::TinyPtrVector<TypeDecl *> types;
};
/// Cached nested-type information, which contains the best declaration
/// for a given name.
llvm::SmallDenseMap<Identifier, CachedNestedType> nestedTypeNameCache;
};
friend class RequirementSource;
/// The result of introducing a new constraint.
enum class ConstraintResult {
/// The constraint was resolved and the relative potential archetypes
/// have been updated.
Resolved,
/// The constraint was written directly on a concrete type.
Concrete,
/// The constraint conflicted with existing constraints in some way;
/// the generic signature is ill-formed.
Conflicting,
/// The constraint could not be resolved immediately.
Unresolved,
};
/// Enum used to indicate how we should handle a constraint that cannot be
/// processed immediately for some reason.
enum class UnresolvedHandlingKind : char {
/// Generate a new, unresolved constraint and consider the constraint
/// "resolved" at this point.
GenerateConstraints = 0,
/// Generate an unresolved constraint but still return
/// \c ConstraintResult::Unresolved so the caller knows what happened.
GenerateUnresolved = 1,
};
/// The set of constraints that are invalid because the constraint
/// type isn't constrained to a protocol or a class
std::vector<Constraint<Type>> invalidIsaConstraints;
private:
class InferRequirementsWalker;
friend class InferRequirementsWalker;
friend class GenericSignature;
ASTContext &Context;
DiagnosticEngine &Diags;
struct Implementation;
std::unique_ptr<Implementation> Impl;
GenericSignatureBuilder(const GenericSignatureBuilder &) = delete;
GenericSignatureBuilder &operator=(const GenericSignatureBuilder &) = delete;
/// When a particular requirement cannot be resolved due to, e.g., a
/// currently-unresolvable or nested type, this routine should be
/// called to cope with the unresolved requirement.
///
/// \returns \c ConstraintResult::Resolved or ConstraintResult::Delayed,
/// as appropriate based on \c unresolvedHandling.
ConstraintResult handleUnresolvedRequirement(RequirementKind kind,
UnresolvedType lhs,
UnresolvedRequirementRHS rhs,
FloatingRequirementSource source,
EquivalenceClass *unresolvedEquivClass,
UnresolvedHandlingKind unresolvedHandling);
/// Add any conditional requirements from the given conformance.
///
/// \returns \c true if an error occurred, \c false if not.
bool addConditionalRequirements(ProtocolConformanceRef conformance,
ModuleDecl *inferForModule, SourceLoc loc);
/// Resolve the conformance of the given type to the given protocol when the
/// potential archetype is known to be equivalent to a concrete type.
///
/// \returns the requirement source for the resolved conformance, or nullptr
/// if the conformance could not be resolved.
const RequirementSource *resolveConcreteConformance(ResolvedType type,
ProtocolDecl *proto);
/// Retrieve the constraint source conformance for the superclass constraint
/// of the given potential archetype (if present) to the given protocol.
///
/// \param type The type whose superclass constraint is being queried.
///
/// \param proto The protocol to which we are establishing conformance.
const RequirementSource *resolveSuperConformance(ResolvedType type,
ProtocolDecl *proto);
public:
/// Add a new conformance requirement specifying that the given
/// type conforms to the given protocol.
ConstraintResult addConformanceRequirement(ResolvedType type,
ProtocolDecl *proto,
FloatingRequirementSource source);
/// "Expand" the conformance of the given \c pa to the protocol \c proto,
/// adding the requirements from its requirement signature, rooted at
/// the given requirement \c source.
ConstraintResult expandConformanceRequirement(
ResolvedType selfType,
ProtocolDecl *proto,
const RequirementSource *source,
bool onlySameTypeConstraints);
/// Add a new same-type requirement between two fully resolved types
/// (output of \c GenericSignatureBuilder::resolve).
///
/// If the types refer to two concrete types that are fundamentally
/// incompatible (e.g. \c Foo<Bar<T>> and \c Foo<Baz>), \c diagnoseMismatch is
/// called with the two types that don't match (\c Bar<T> and \c Baz for the
/// previous example).
ConstraintResult
addSameTypeRequirementDirect(
ResolvedType paOrT1, ResolvedType paOrT2,
FloatingRequirementSource Source,
llvm::function_ref<void(Type, Type)> diagnoseMismatch);
/// Add a new same-type requirement between two unresolved types.
///
/// The types are resolved with \c GenericSignatureBuilder::resolve, and must
/// not be incompatible concrete types.
ConstraintResult addSameTypeRequirement(
UnresolvedType paOrT1,
UnresolvedType paOrT2,
FloatingRequirementSource Source,
UnresolvedHandlingKind unresolvedHandling);
/// Add a new same-type requirement between two unresolved types.
///
/// The types are resolved with \c GenericSignatureBuilder::resolve. \c
/// diagnoseMismatch is called if the two types refer to incompatible concrete
/// types.
ConstraintResult
addSameTypeRequirement(UnresolvedType paOrT1, UnresolvedType paOrT2,
FloatingRequirementSource Source,
UnresolvedHandlingKind unresolvedHandling,
llvm::function_ref<void(Type, Type)> diagnoseMismatch);
/// Update the superclass for the equivalence class of \c T.
///
/// This assumes that the constraint has already been recorded.
///
/// \returns true if anything in the equivalence class changed, false
/// otherwise.
bool updateSuperclass(ResolvedType type,
Type superclass,
FloatingRequirementSource source);
/// Update the layout constraint for the equivalence class of \c T.
///
/// This assumes that the constraint has already been recorded.
///
/// \returns true if anything in the equivalence class changed, false
/// otherwise.
bool updateLayout(ResolvedType type,
LayoutConstraint layout);
private:
/// Add a new superclass requirement specifying that the given
/// potential archetype has the given type as an ancestor.
ConstraintResult addSuperclassRequirementDirect(
ResolvedType type,
Type superclass,
FloatingRequirementSource source);
/// Add a new type requirement specifying that the given
/// type conforms-to or is a superclass of the second type.
///
/// \param inferForModule Infer additional requirements from the types
/// relative to the given module.
ConstraintResult addTypeRequirement(UnresolvedType subject,
UnresolvedType constraint,
FloatingRequirementSource source,
UnresolvedHandlingKind unresolvedHandling,
ModuleDecl *inferForModule);
/// Note that we have added the nested type nestedPA
void addedNestedType(PotentialArchetype *nestedPA);
/// Add a rewrite rule from that makes the two types equivalent.
///
/// \returns true if a new rewrite rule was added, and false otherwise.
bool addSameTypeRewriteRule(CanType type1, CanType type2);
/// Add a same-type requirement between two types that are known to
/// refer to type parameters.
ConstraintResult addSameTypeRequirementBetweenTypeParameters(
ResolvedType type1, ResolvedType type2,
const RequirementSource *source);
/// Add a new conformance requirement specifying that the given
/// potential archetype is bound to a concrete type.
ConstraintResult addSameTypeRequirementToConcrete(ResolvedType type,
Type concrete,
const RequirementSource *Source);
/// Add a new same-type requirement specifying that the given two
/// types should be the same.
///
/// \param diagnoseMismatch Callback invoked when the types in the same-type
/// requirement mismatch.
ConstraintResult addSameTypeRequirementBetweenConcrete(
Type T1, Type T2, FloatingRequirementSource Source,
llvm::function_ref<void(Type, Type)> diagnoseMismatch);
/// Add a new layout requirement directly on the potential archetype.
///
/// \returns true if this requirement makes the set of requirements
/// inconsistent, in which case a diagnostic will have been issued.
ConstraintResult addLayoutRequirementDirect(ResolvedType type,
LayoutConstraint layout,
FloatingRequirementSource source);
/// Add a new layout requirement to the subject.
ConstraintResult addLayoutRequirement(
UnresolvedType subject,
LayoutConstraint layout,
FloatingRequirementSource source,
UnresolvedHandlingKind unresolvedHandling);
/// Add the requirements placed on the given type parameter
/// to the given potential archetype.
///
/// \param inferForModule Infer additional requirements from the types
/// relative to the given module.
ConstraintResult addInheritedRequirements(
TypeDecl *decl,
UnresolvedType type,
const RequirementSource *parentSource,
ModuleDecl *inferForModule);
public:
/// Construct a new generic signature builder.
explicit GenericSignatureBuilder(ASTContext &ctx);
GenericSignatureBuilder(GenericSignatureBuilder &&);
~GenericSignatureBuilder();
/// Retrieve the AST context.
ASTContext &getASTContext() const { return Context; }
/// Functor class suitable for use as a \c LookupConformanceFn to look up a
/// conformance in a generic signature builder.
class LookUpConformanceInBuilder {
GenericSignatureBuilder *builder;
public:
explicit LookUpConformanceInBuilder(GenericSignatureBuilder *builder)
: builder(builder) {}
ProtocolConformanceRef operator()(CanType dependentType,
Type conformingReplacementType,
ProtocolDecl *conformedProtocol) const;
};
/// Retrieve a function that can perform conformance lookup for this
/// builder.
LookUpConformanceInBuilder getLookupConformanceFn();
/// Lookup a protocol conformance in a module-agnostic manner.
ProtocolConformanceRef lookupConformance(Type conformingReplacementType,
ProtocolDecl *conformedProtocol);
/// Enumerate the requirements that describe the signature of this
/// generic signature builder.
void enumerateRequirements(
TypeArrayView<GenericTypeParamType> genericParams,
SmallVectorImpl<Requirement> &requirements);
/// Retrieve the generic parameters used to describe the generic
/// signature being built.
TypeArrayView<GenericTypeParamType> getGenericParams() const;
/// Add a new generic parameter for which there may be requirements.
void addGenericParameter(GenericTypeParamDecl *GenericParam);
/// Add the requirements placed on the given abstract type parameter
/// to the given potential archetype.
///
/// \returns true if an error occurred, false otherwise.
bool addGenericParameterRequirements(GenericTypeParamDecl *GenericParam);
/// Add a new generic parameter for which there may be requirements.
void addGenericParameter(GenericTypeParamType *GenericParam);
/// Add a new requirement.
///
/// \param inferForModule Infer additional requirements from the types
/// relative to the given module.
///
/// \returns true if this requirement makes the set of requirements
/// inconsistent, in which case a diagnostic will have been issued.
ConstraintResult addRequirement(const Requirement &req,
FloatingRequirementSource source,
ModuleDecl *inferForModule);
/// Add an already-checked requirement.
///
/// Adding an already-checked requirement cannot fail. This is used to
/// re-inject requirements from outer contexts.
///
/// \param inferForModule Infer additional requirements from the types
/// relative to the given module.
///
/// \returns true if this requirement makes the set of requirements
/// inconsistent, in which case a diagnostic will have been issued.
ConstraintResult addRequirement(const Requirement &req,
const RequirementRepr *reqRepr,
FloatingRequirementSource source,
const SubstitutionMap *subMap,
ModuleDecl *inferForModule);
/// Add all of a generic signature's parameters and requirements.
void addGenericSignature(GenericSignature sig);
/// Infer requirements from the given type, recursively.
///
/// This routine infers requirements from a type that occurs within the
/// signature of a generic function. For example, given:
///
/// \code
/// func f<K, V>(dict : Dictionary<K, V>) { ... }
/// \endcode
///
/// where \c Dictionary requires that its key type be \c Hashable,
/// the requirement \c K : Hashable is inferred from the parameter type,
/// because the type \c Dictionary<K,V> cannot be formed without it.
void inferRequirements(ModuleDecl &module,
Type type,
FloatingRequirementSource source);
/// Infer requirements from the given pattern, recursively.
///
/// This routine infers requirements from a type that occurs within the
/// signature of a generic function. For example, given:
///
/// \code
/// func f<K, V>(dict : Dictionary<K, V>) { ... }
/// \endcode
///
/// where \c Dictionary requires that its key type be \c Hashable,
/// the requirement \c K : Hashable is inferred from the parameter type,
/// because the type \c Dictionary<K,V> cannot be formed without it.
void inferRequirements(ModuleDecl &module, ParameterList *params);
GenericSignature rebuildSignatureWithoutRedundantRequirements(
bool allowConcreteGenericParams,
const ProtocolDecl *requirementSignatureSelfProto) &&;
/// Finalize the set of requirements and compute the generic
/// signature.
///
/// After this point, one cannot introduce new requirements, and the
/// generic signature builder no longer has valid state.
GenericSignature computeGenericSignature(
bool allowConcreteGenericParams = false,
const ProtocolDecl *requirementSignatureSelfProto = nullptr,
bool rebuildingWithoutRedundantConformances = false) &&;
/// Compute the requirement signature for the given protocol.
static GenericSignature computeRequirementSignature(ProtocolDecl *proto);
private:
/// Finalize the set of requirements, performing any remaining checking
/// required before generating archetypes.
///
/// \param allowConcreteGenericParams If true, allow generic parameters to
/// be made concrete.
void finalize(TypeArrayView<GenericTypeParamType> genericParams,
bool allowConcreteGenericParams,
const ProtocolDecl *requirementSignatureSelfProto);
public:
/// Process any delayed requirements that can be handled now.
void processDelayedRequirements();
class ExplicitRequirement;
bool isRedundantExplicitRequirement(const ExplicitRequirement &req) const;
private:
using GetKindAndRHS = llvm::function_ref<std::pair<RequirementKind, RequirementRHS>()>;
void getBaseRequirements(
GetKindAndRHS getKindAndRHS,
const RequirementSource *source,
const ProtocolDecl *requirementSignatureSelfProto,
SmallVectorImpl<ExplicitRequirement> &result);
/// Determine if an explicit requirement can be derived from the
/// requirement given by \p otherSource and \p otherRHS, using the
/// knowledge of any existing redundant requirements discovered so far.
Optional<ExplicitRequirement>
isValidRequirementDerivationPath(
llvm::SmallDenseSet<ExplicitRequirement, 4> &visited,
RequirementKind otherKind,
const RequirementSource *otherSource,
RequirementRHS otherRHS,
const ProtocolDecl *requirementSignatureSelfProto);
/// Determine if the explicit requirement \p req can be derived from any
/// of the constraints in \p constraints, using the knowledge of any
/// existing redundant requirements discovered so far.
///
/// Use \p filter to screen out less-specific and conflicting constraints
/// if the requirement is a superclass, concrete type or layout requirement.
template<typename T, typename Filter>
void checkIfRequirementCanBeDerived(
const ExplicitRequirement &req,
const std::vector<Constraint<T>> &constraints,
const ProtocolDecl *requirementSignatureSelfProto,
Filter filter);
void computeRedundantRequirements(
const ProtocolDecl *requirementSignatureSelfProto);
void diagnoseRedundantRequirements() const;
void diagnoseConflictingConcreteTypeRequirements(
const ProtocolDecl *requirementSignatureSelfProto);
/// Describes the relationship between a given constraint and
/// the canonical constraint of the equivalence class.
enum class ConstraintRelation {
/// The constraint is unrelated.
///
/// This is a conservative result that can be used when, for example,
/// we have incomplete information to make a determination.
Unrelated,
/// The constraint is redundant and can be removed without affecting the
/// semantics.
Redundant,
/// The constraint conflicts, meaning that the signature is erroneous.
Conflicting,
};
/// Check a list of constraints, removing self-derived constraints
/// and diagnosing redundant constraints.
///
/// \param isSuitableRepresentative Determines whether the given constraint
/// is a suitable representative.
///
/// \param checkConstraint Checks the given constraint against the
/// canonical constraint to determine which diagnostics (if any) should be
/// emitted.
///
/// \returns the representative constraint.
template<typename T>
Constraint<T> checkConstraintList(
TypeArrayView<GenericTypeParamType> genericParams,
std::vector<Constraint<T>> &constraints,
RequirementKind kind,
llvm::function_ref<bool(const Constraint<T> &)>
isSuitableRepresentative,
llvm::function_ref<
ConstraintRelation(const Constraint<T>&)>
checkConstraint,
Optional<Diag<unsigned, Type, T, T>>
conflictingDiag,
Diag<Type, T> redundancyDiag,
Diag<unsigned, Type, T> otherNoteDiag);
/// Check the concrete type constraints within the equivalence
/// class of the given potential archetype.
void checkConcreteTypeConstraints(
TypeArrayView<GenericTypeParamType> genericParams,
EquivalenceClass *equivClass);
/// Check same-type constraints within the equivalence class of the
/// given potential archetype.
void checkSameTypeConstraints(
TypeArrayView<GenericTypeParamType> genericParams,
EquivalenceClass *equivClass);
public:
/// Try to resolve the equivalence class of the given type.
///
/// \param type The type to resolve.
///
/// \param resolutionKind How to perform the resolution.
///
/// \param wantExactPotentialArchetype Whether to return the precise
/// potential archetype described by the type (vs. just the equivalence
/// class and resolved type).
ResolvedType maybeResolveEquivalenceClass(
Type type,
ArchetypeResolutionKind resolutionKind,
bool wantExactPotentialArchetype);
/// Resolve the equivalence class for the given type parameter,
/// which provides information about that type.
///
/// The \c resolutionKind parameter describes how resolution should be
/// performed. If the potential archetype named by the given dependent type
/// already exists, it will be always returned. If it doesn't exist yet,
/// the \c resolutionKind dictates whether the potential archetype will
/// be created or whether null will be returned.
///
/// For any type that cannot refer to an equivalence class, this routine
/// returns null.
EquivalenceClass *resolveEquivalenceClass(
Type type,
ArchetypeResolutionKind resolutionKind);
/// Resolve the given type as far as this Builder knows how.
///
/// If successful, this returns either a non-typealias potential archetype
/// or a Type, if \c type is concrete.
/// If the type cannot be resolved, e.g., because it is "too" recursive
/// given the source, returns an unresolved result containing the equivalence
/// class that would need to change to resolve this type.
ResolvedType resolve(UnresolvedType type, FloatingRequirementSource source);
/// Determine whether the two given types are in the same equivalence class.
bool areInSameEquivalenceClass(Type type1, Type type2);
/// Simplify the given dependent type down to its canonical representation.
Type getCanonicalTypeParameter(Type type);
/// Replace any non-canonical dependent types in the given type with their
/// canonical representation. This is not a canonical type in the AST sense;
/// type sugar is preserved. The GenericSignature::getCanonicalTypeInContext()
/// method combines this with a subsequent getCanonicalType() call.
Type getCanonicalTypeInContext(Type type,
TypeArrayView<GenericTypeParamType> genericParams);
/// Retrieve the conformance access path used to extract the conformance of
/// interface \c type to the given \c protocol.
///
/// \param type The interface type whose conformance access path is to be
/// queried.
/// \param protocol A protocol to which \c type conforms.
///
/// \returns the conformance access path that starts at a requirement of
/// this generic signature and ends at the conformance that makes \c type
/// conform to \c protocol.
///
/// \seealso ConformanceAccessPath
ConformanceAccessPath getConformanceAccessPath(Type type,
ProtocolDecl *protocol,
GenericSignature sig);
/// Verify the correctness of the given generic signature.
///
/// This routine will test that the given generic signature is both minimal
/// and canonical, emitting errors if it is not.
static void verifyGenericSignature(ASTContext &context,
GenericSignature sig);
/// Verify all of the generic sigantures in the given module.
static void verifyGenericSignaturesInModule(ModuleDecl *module);
/// Dump all of the requirements, both specified and inferred. It cannot be
/// statically proven that this doesn't modify the GSB.
SWIFT_DEBUG_HELPER(void dump());
/// Dump all of the requirements to the given output stream. It cannot be
/// statically proven that this doesn't modify the GSB.
void dump(llvm::raw_ostream &out);
};
/// Describes how a generic signature determines a requirement, from its origin
/// in some requirement written in the source, inferred through a path of
/// other implications (e.g., introduced by a particular protocol).
///
/// Requirement sources are uniqued within a generic signature builder.
class GenericSignatureBuilder::RequirementSource final
: public llvm::FoldingSetNode,
private llvm::TrailingObjects<RequirementSource, ProtocolDecl *,
WrittenRequirementLoc> {
friend class FloatingRequirementSource;
friend class GenericSignature;
public:
enum Kind : uint8_t {
/// A requirement stated explicitly, e.g., in a where clause or type
/// parameter declaration.
///
/// Explicitly-stated requirement can be tied to a specific requirement
/// in a 'where' clause (which stores a \c RequirementRepr), a type in an
/// 'inheritance' clause (which stores a \c TypeRepr), or can be 'abstract',
/// , e.g., due to canonicalization, deserialization, or other
/// source-independent formulation.
///
/// This is a root requirement source.
Explicit,
/// A requirement inferred from part of the signature of a declaration,
/// e.g., the type of a generic function. For example:
///
/// func f<T>(_: Set<T>) { } // infers T: Hashable
///
/// This is a root requirement source, which can be described by a
/// \c TypeRepr.
Inferred,
/// A requirement for the creation of the requirement signature of a
/// protocol.
///
/// This is a root requirement source, which is described by the protocol
/// whose requirement signature is being computed.
RequirementSignatureSelf,
/// The requirement came from two nested types of the equivalent types whose
/// names match.
///
/// This is a root requirement source.
NestedTypeNameMatch,
/// The requirement is a protocol requirement.
///
/// This stores the protocol that introduced the requirement as well as the
/// dependent type (relative to that protocol) to which the conformance
/// appertains.
ProtocolRequirement,
/// The requirement is a protocol requirement that is inferred from
/// some part of the protocol definition.
///
/// This stores the protocol that introduced the requirement as well as the
/// dependent type (relative to that protocol) to which the conformance
/// appertains.
InferredProtocolRequirement,
/// A requirement that was resolved via a superclass requirement.
///
/// This stores the \c ProtocolConformanceRef used to resolve the
/// requirement.
Superclass,
/// A requirement that was resolved for a nested type via its parent
/// type.
Parent,
/// A requirement that was resolved for a nested type via a same-type-to-
/// concrete constraint.
///
/// This stores the \c ProtocolConformance* used to resolve the
/// requirement.
Concrete,
/// A requirement that was resolved based on a layout requirement
/// imposed by a superclass constraint.
///
/// This stores the \c LayoutConstraint used to resolve the
/// requirement.
Layout,
/// A requirement that was provided for another type in the
/// same equivalence class, but which we want to "re-root" on a new
/// type.
EquivalentType,
};
/// The kind of requirement source.
const Kind kind;
private:
/// The kind of storage we have.
enum class StorageKind : uint8_t {
None,
StoredType,
ProtocolConformance,
AssociatedTypeDecl,
};
/// The kind of storage we have.
const StorageKind storageKind;
/// Whether there is a trailing written requirement location.
const bool hasTrailingWrittenRequirementLoc;
private:
/// The actual storage, described by \c storageKind.
union {
/// The type to which a requirement applies.
TypeBase *type;
/// A protocol conformance used to satisfy the requirement.
void *conformance;
/// An associated type to which a requirement is being applied.
AssociatedTypeDecl *assocType;
} storage;
friend TrailingObjects;
/// The trailing protocol declaration, if there is one.
size_t numTrailingObjects(OverloadToken<ProtocolDecl *>) const {
switch (kind) {
case RequirementSignatureSelf:
case ProtocolRequirement:
case InferredProtocolRequirement:
return 1;
case Explicit:
case Inferred:
case NestedTypeNameMatch:
case Superclass:
case Parent:
case Concrete:
case Layout:
case EquivalentType:
return 0;
}
llvm_unreachable("Unhandled RequirementSourceKind in switch.");
}
/// The trailing written requirement location, if there is one.
size_t numTrailingObjects(OverloadToken<WrittenRequirementLoc>) const {
return hasTrailingWrittenRequirementLoc ? 1 : 0;
}
#ifndef NDEBUG
/// Determines whether we have been provided with an acceptable storage kind
/// for the given requirement source kind.
static bool isAcceptableStorageKind(Kind kind, StorageKind storageKind);
#endif
/// Retrieve the opaque storage as a single pointer, for use in uniquing.
const void *getOpaqueStorage1() const;
/// Retrieve the second opaque storage as a single pointer, for use in