forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeCheckProtocol.cpp
5545 lines (4673 loc) · 202 KB
/
TypeCheckProtocol.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
//===--- TypeCheckProtocol.cpp - Protocol Checking ------------------------===//
//
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for protocols, in particular, checking
// whether a given type conforms to a given protocol.
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "DerivedConformances.h"
#include "MiscDiagnostics.h"
#include "TypeChecker.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/StringExtras.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ReferencedNameTracker.h"
#include "swift/AST/TypeMatcher.h"
#include "swift/AST/TypeWalker.h"
#include "swift/Basic/Defer.h"
#include "swift/Sema/IDETypeChecking.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
namespace {
struct RequirementMatch;
struct RequirementCheck;
/// Describes the environment of a requirement that will be used when
/// matching witnesses against the requirement and to form the resulting
/// \c Witness value.
///
/// The produced generic environment will have a fresh set of archetypes that
/// describe the combined constraints of the requirement (because those
/// are available to all potential witnesses) as well as the constraints from
/// the context to which the protocol conformance is ascribed, which may
/// include additional constraints beyond those of the extended type if the
/// conformance is conditional. The type parameters for the generic
/// environment are the type parameters of the conformance context
/// (\c conformanceDC) with another (deeper) level of type parameters for
/// generic requirements. See the \c Witness class for more information about
/// this synthetic environment.
class RequirementEnvironment {
GenericSignature *syntheticSignature = nullptr;
GenericEnvironment *syntheticEnvironment = nullptr;
SubstitutionMap reqToSyntheticEnvMap;
bool valid = true;
public:
/// Create a new environment for matching the given requirement within a
/// particular conformance.
///
/// \param conformanceDC The \c DeclContext to which the protocol
/// conformance is ascribed, which provides additional constraints.
///
/// \param req The requirement for which we are creating a generic
/// environment.
///
/// \param conformance The protocol conformance, or null if there is no
/// conformance (because we're finding default implementations).
RequirementEnvironment(TypeChecker &tc,
DeclContext *conformanceDC,
ValueDecl *req,
ProtocolConformance *conformance);
/// Retrieve the generic signature of the synthetic environment.
GenericSignature *getSyntheticSignature() const {
assert(valid && "Already stole from this generic environment");
return syntheticSignature;
}
/// Retrieve the synthetic generic environment.
GenericEnvironment *getSyntheticEnvironment() const {
assert(valid && "Already stole from this generic environment");
return syntheticEnvironment;
}
/// Retrieve the substitution map that maps the interface types of the
/// requirement to the interface types of the synthetic environment.
const SubstitutionMap &getRequirementToSyntheticMap() const {
assert(valid && "Already stole from this generic environment");
return reqToSyntheticEnvMap;
}
/// Take the substitution map that maps the interface types of the
/// requirement to the interface types of the synthetic environment.
///
/// This can only be done once, and makes the requirement environment
/// invalid.
SubstitutionMap &&takeRequirementToSyntheticMap() {
assert(valid && "Already stole from this generic environment");
valid = false;
return std::move(reqToSyntheticEnvMap);
}
};
class WitnessChecker {
protected:
TypeChecker &TC;
ProtocolDecl *Proto;
Type Adoptee;
// The conforming context, either a nominal type or extension.
DeclContext *DC;
WitnessChecker(TypeChecker &tc, ProtocolDecl *proto,
Type adoptee, DeclContext *dc)
: TC(tc), Proto(proto), Adoptee(adoptee), DC(dc) { }
/// Gather the value witnesses for the given requirement.
///
/// \param ignoringNames If non-null and there are no value
/// witnesses with the correct full name, the results will reflect
/// lookup for just the base name and the pointee will be set to
/// \c true.
SmallVector<ValueDecl *, 4> lookupValueWitnesses(ValueDecl *req,
bool *ignoringNames);
bool findBestWitness(ValueDecl *requirement,
bool *ignoringNames,
NormalProtocolConformance *conformance,
const RequirementEnvironment &reqEnvironment,
SmallVectorImpl<RequirementMatch> &matches,
unsigned &numViable,
unsigned &bestIdx,
bool &doNotDiagnoseMatches);
bool checkWitnessAccessibility(AccessScope &requiredAccessScope,
ValueDecl *requirement,
ValueDecl *witness,
bool *isSetter);
bool checkWitnessAvailability(ValueDecl *requirement,
ValueDecl *witness,
AvailabilityContext *requirementInfo);
RequirementCheck checkWitness(AccessScope requiredAccessScope,
ValueDecl *requirement,
RequirementMatch match);
};
/// \brief The result of matching a particular declaration to a given
/// requirement.
enum class MatchKind : unsigned char {
/// \brief The witness matched the requirement exactly.
ExactMatch,
/// \brief There is a difference in optionality.
OptionalityConflict,
/// \brief The witness matched the requirement with some renaming.
RenamedMatch,
/// \brief The witness is invalid or has an invalid type.
WitnessInvalid,
/// \brief The kind of the witness and requirement differ, e.g., one
/// is a function and the other is a variable.
KindConflict,
/// \brief The types conflict.
TypeConflict,
/// The witness throws, but the requirement does not.
ThrowsConflict,
/// \brief The witness did not match due to static/non-static differences.
StaticNonStaticConflict,
/// \brief The witness is not settable, but the requirement is.
SettableConflict,
/// \brief The witness did not match due to prefix/non-prefix differences.
PrefixNonPrefixConflict,
/// \brief The witness did not match due to postfix/non-postfix differences.
PostfixNonPostfixConflict,
/// \brief The witness did not match because of mutating conflicts.
MutatingConflict,
/// The witness is not rethrows, but the requirement is.
RethrowsConflict,
/// The witness is explicitly @nonobjc but the requirement is @objc.
NonObjC,
};
/// Describes the kind of optional adjustment performed when
/// comparing two types.
enum class OptionalAdjustmentKind {
// No adjustment required.
None,
/// The witness can produce a 'nil' that won't be handled by
/// callers of the requirement. This is a type-safety problem.
ProducesUnhandledNil,
/// Callers of the requirement can provide 'nil', but the witness
/// does not handle it. This is a type-safety problem.
ConsumesUnhandledNil,
/// The witness handles 'nil', but won't ever be given a 'nil'.
/// This is not a type-safety problem.
WillNeverConsumeNil,
/// Callers of the requirement can expect to receive 'nil', but
/// the witness will never produce one. This is not a type-safety
/// problem.
WillNeverProduceNil,
/// The witness has an IUO that can be removed, because the
/// protocol doesn't need it. This is not a type-safety problem.
RemoveIUO,
/// The witness has an IUO that should be translated into a true
/// optional. This is not a type-safety problem.
IUOToOptional,
};
/// Once a witness has been found, there are several reasons it may
/// not be usable.
enum class CheckKind : unsigned {
/// The witness is OK.
Success,
/// The witness is less accessible than the requirement.
Accessibility,
/// The witness is storage whose setter is less accessible than the
/// requirement.
AccessibilityOfSetter,
/// The witness is less available than the requirement.
Availability,
/// The requirement was marked explicitly unavailable.
Unavailable,
/// The witness requires optional adjustments.
OptionalityConflict,
/// The witness is a constructor which is more failable than the
/// requirement.
ConstructorFailability,
};
/// Describes an optional adjustment made to a witness.
class OptionalAdjustment {
/// The kind of adjustment.
unsigned Kind : 16;
/// Whether this is a parameter adjustment (with an index) vs. a
/// result or value type adjustment (no index needed).
unsigned IsParameterAdjustment : 1;
/// The adjustment index, for parameter adjustments.
unsigned ParameterAdjustmentIndex : 15;
public:
/// Create a non-parameter optional adjustment.
explicit OptionalAdjustment(OptionalAdjustmentKind kind)
: Kind(static_cast<unsigned>(kind)), IsParameterAdjustment(false),
ParameterAdjustmentIndex(0) { }
/// Create an optional adjustment to a parameter.
OptionalAdjustment(OptionalAdjustmentKind kind,
unsigned parameterIndex)
: Kind(static_cast<unsigned>(kind)), IsParameterAdjustment(true),
ParameterAdjustmentIndex(parameterIndex) { }
/// Determine the kind of optional adjustment.
OptionalAdjustmentKind getKind() const {
return static_cast<OptionalAdjustmentKind>(Kind);
}
/// Determine whether this is a parameter adjustment.
bool isParameterAdjustment() const {
return IsParameterAdjustment;
}
/// Return the index of a parameter adjustment.
unsigned getParameterIndex() const {
assert(isParameterAdjustment() && "Not a parameter adjustment");
return ParameterAdjustmentIndex;
}
/// Determines whether the optional adjustment is an error.
bool isError() const {
switch (getKind()) {
case OptionalAdjustmentKind::None:
return false;
case OptionalAdjustmentKind::ProducesUnhandledNil:
case OptionalAdjustmentKind::ConsumesUnhandledNil:
return true;
case OptionalAdjustmentKind::WillNeverConsumeNil:
case OptionalAdjustmentKind::WillNeverProduceNil:
case OptionalAdjustmentKind::RemoveIUO:
case OptionalAdjustmentKind::IUOToOptional:
// Warnings at most.
return false;
}
llvm_unreachable("Unhandled OptionalAdjustmentKind in switch.");
}
/// Retrieve the source location at which the optional is
/// specified or would be inserted.
SourceLoc getOptionalityLoc(ValueDecl *witness) const;
/// Retrieve the optionality location for the given type
/// representation.
SourceLoc getOptionalityLoc(TypeRepr *tyR) const;
};
/// Whether any of the given optional adjustments is an error (vs. a
/// warning).
bool hasAnyError(ArrayRef<OptionalAdjustment> adjustments) {
for (const auto &adjustment : adjustments)
if (adjustment.isError())
return true;
return false;
}
/// \brief Describes a match between a requirement and a witness.
struct RequirementMatch {
RequirementMatch(ValueDecl *witness, MatchKind kind)
: Witness(witness), Kind(kind), WitnessType() {
assert(!hasWitnessType() && "Should have witness type");
}
RequirementMatch(ValueDecl *witness, MatchKind kind,
Type witnessType,
ArrayRef<OptionalAdjustment> optionalAdjustments = {})
: Witness(witness), Kind(kind), WitnessType(witnessType),
OptionalAdjustments(optionalAdjustments.begin(),
optionalAdjustments.end())
{
assert(hasWitnessType() == !witnessType.isNull() &&
"Should (or should not) have witness type");
}
/// \brief The witness that matches the (implied) requirement.
ValueDecl *Witness;
/// \brief The kind of match.
MatchKind Kind;
/// \brief The type of the witness when it is referenced.
Type WitnessType;
/// The set of optional adjustments performed on the witness.
SmallVector<OptionalAdjustment, 2> OptionalAdjustments;
/// \brief Determine whether this match is viable.
bool isViable() const {
switch(Kind) {
case MatchKind::ExactMatch:
case MatchKind::OptionalityConflict:
case MatchKind::RenamedMatch:
return true;
case MatchKind::WitnessInvalid:
case MatchKind::KindConflict:
case MatchKind::TypeConflict:
case MatchKind::StaticNonStaticConflict:
case MatchKind::SettableConflict:
case MatchKind::PrefixNonPrefixConflict:
case MatchKind::PostfixNonPostfixConflict:
case MatchKind::MutatingConflict:
case MatchKind::RethrowsConflict:
case MatchKind::ThrowsConflict:
case MatchKind::NonObjC:
return false;
}
llvm_unreachable("Unhandled MatchKind in switch.");
}
/// \brief Determine whether this requirement match has a witness type.
bool hasWitnessType() const {
switch(Kind) {
case MatchKind::ExactMatch:
case MatchKind::RenamedMatch:
case MatchKind::TypeConflict:
case MatchKind::OptionalityConflict:
return true;
case MatchKind::WitnessInvalid:
case MatchKind::KindConflict:
case MatchKind::StaticNonStaticConflict:
case MatchKind::SettableConflict:
case MatchKind::PrefixNonPrefixConflict:
case MatchKind::PostfixNonPostfixConflict:
case MatchKind::MutatingConflict:
case MatchKind::RethrowsConflict:
case MatchKind::ThrowsConflict:
case MatchKind::NonObjC:
return false;
}
llvm_unreachable("Unhandled MatchKind in switch.");
}
SmallVector<Substitution, 2> WitnessSubstitutions;
swift::Witness getWitness(ASTContext &ctx,
RequirementEnvironment &&reqEnvironment) const {
auto environment = reqEnvironment.getSyntheticEnvironment();
auto map = reqEnvironment.takeRequirementToSyntheticMap();
return swift::Witness(this->Witness, WitnessSubstitutions,
environment,
map);
}
/// Classify the provided optionality issues for use in diagnostics.
/// FIXME: Enumify this
unsigned classifyOptionalityIssues(ValueDecl *requirement) const {
unsigned numParameterAdjustments = 0;
bool hasNonParameterAdjustment = false;
for (const auto &adjustment : OptionalAdjustments) {
if (adjustment.isParameterAdjustment())
++numParameterAdjustments;
else
hasNonParameterAdjustment = true;
}
if (hasNonParameterAdjustment) {
// Both return and parameter adjustments.
if (numParameterAdjustments > 0)
return 4;
// The type of a variable.
if (isa<VarDecl>(requirement))
return 0;
// The result type of something.
return 1;
}
// Only parameter adjustments.
assert(numParameterAdjustments > 0 && "No adjustments?");
return numParameterAdjustments == 1 ? 2 : 3;
}
/// Add Fix-Its that correct the optionality in the witness.
void addOptionalityFixIts(const ASTContext &ctx,
ValueDecl *witness,
InFlightDiagnostic &diag) const;
};
/// \brief Describes the suitability of the chosen witness for
/// the requirement.
struct RequirementCheck {
CheckKind Kind;
/// The required access scope, if the check failed due to the
/// witness being less accessible than the requirement.
AccessScope RequiredAccessScope;
/// The required availability, if the check failed due to the
/// witness being less available than the requirement.
AvailabilityContext RequiredAvailability;
RequirementCheck(CheckKind kind)
: Kind(kind), RequiredAccessScope(AccessScope::getPublic()),
RequiredAvailability(AvailabilityContext::alwaysAvailable()) { }
RequirementCheck(CheckKind kind, AccessScope requiredAccessScope)
: Kind(kind), RequiredAccessScope(requiredAccessScope),
RequiredAvailability(AvailabilityContext::alwaysAvailable()) { }
RequirementCheck(CheckKind kind, AvailabilityContext requiredAvailability)
: Kind(kind), RequiredAccessScope(AccessScope::getPublic()),
RequiredAvailability(requiredAvailability) { }
};
}
///\ brief Decompose the given type into a set of tuple elements.
static SmallVector<TupleTypeElt, 4> decomposeIntoTupleElements(Type type) {
SmallVector<TupleTypeElt, 4> result;
if (auto tupleTy = dyn_cast<TupleType>(type.getPointer())) {
result.append(tupleTy->getElements().begin(), tupleTy->getElements().end());
return result;
}
result.push_back(type);
return result;
}
/// If the given type is a direct reference to an associated type of
/// the given protocol, return the referenced associated type.
static AssociatedTypeDecl *
getReferencedAssocTypeOfProtocol(Type type, ProtocolDecl *proto) {
if (auto dependentMember = type->getAs<DependentMemberType>()) {
if (auto genericParam
= dependentMember->getBase()->getAs<GenericTypeParamType>()) {
if (genericParam->getDepth() == 0 && genericParam->getIndex() == 0) {
if (auto assocType = dependentMember->getAssocType()) {
if (assocType->getDeclContext() == proto)
return assocType;
}
}
}
}
return nullptr;
}
namespace {
/// The kind of variance (none, covariance, contravariance) to apply
/// when comparing types from a witness to types in the requirement
/// we're matching it against.
enum class VarianceKind {
None,
Covariant,
Contravariant
};
} // end anonymous namespace
static std::tuple<Type,Type, OptionalAdjustmentKind>
getTypesToCompare(ValueDecl *reqt,
Type reqtType,
Type witnessType,
VarianceKind variance) {
// For @objc protocols, deal with differences in the optionality.
// FIXME: It probably makes sense to extend this to non-@objc
// protocols as well, but this requires more testing.
OptionalAdjustmentKind optAdjustment = OptionalAdjustmentKind::None;
if (reqt->isObjC()) {
OptionalTypeKind reqtOptKind;
if (Type reqtValueType
= reqtType->getAnyOptionalObjectType(reqtOptKind))
reqtType = reqtValueType;
OptionalTypeKind witnessOptKind;
if (Type witnessValueType
= witnessType->getAnyOptionalObjectType(witnessOptKind))
witnessType = witnessValueType;
switch (reqtOptKind) {
case OTK_None:
switch (witnessOptKind) {
case OTK_None:
// Exact match is always okay.
break;
case OTK_Optional:
switch (variance) {
case VarianceKind::None:
case VarianceKind::Covariant:
optAdjustment = OptionalAdjustmentKind::ProducesUnhandledNil;
break;
case VarianceKind::Contravariant:
optAdjustment = OptionalAdjustmentKind::WillNeverConsumeNil;
break;
}
break;
case OTK_ImplicitlyUnwrappedOptional:
optAdjustment = OptionalAdjustmentKind::RemoveIUO;
break;
}
break;
case OTK_Optional:
switch (witnessOptKind) {
case OTK_None:
switch (variance) {
case VarianceKind::None:
case VarianceKind::Contravariant:
optAdjustment = OptionalAdjustmentKind::ConsumesUnhandledNil;
break;
case VarianceKind::Covariant:
optAdjustment = OptionalAdjustmentKind::WillNeverProduceNil;
break;
}
break;
case OTK_Optional:
// Exact match is always okay.
break;
case OTK_ImplicitlyUnwrappedOptional:
optAdjustment = OptionalAdjustmentKind::IUOToOptional;
break;
}
break;
case OTK_ImplicitlyUnwrappedOptional:
// When the requirement is an IUO, all is permitted, because we
// assume that the user knows more about the signature than we
// have information in the protocol.
break;
}
}
return std::make_tuple(reqtType, witnessType, optAdjustment);
}
// Given that we're looking at a stored property, should we use the
// mutating rules for the setter or the getter when trying to match
// the given requirement?
static bool shouldUseSetterRequirements(AccessorKind reqtKind) {
// We have cases for addressors here because we might reasonably
// allow them as protocol requirements someday.
switch (reqtKind) {
case AccessorKind::IsGetter:
case AccessorKind::IsAddressor:
return false;
case AccessorKind::IsSetter:
case AccessorKind::IsMutableAddressor:
case AccessorKind::IsMaterializeForSet:
return true;
case AccessorKind::NotAccessor:
case AccessorKind::IsWillSet:
case AccessorKind::IsDidSet:
llvm_unreachable("willSet/didSet protocol requirement?");
}
llvm_unreachable("bad accessor kind");
}
static FuncDecl *getAddressorForRequirement(AbstractStorageDecl *witness,
AccessorKind reqtKind) {
assert(witness->hasAddressors());
if (shouldUseSetterRequirements(reqtKind))
return witness->getMutableAddressor();
return witness->getAddressor();
}
// Verify that the mutating bit is correct between a protocol requirement and a
// witness. This returns true on invalid.
static bool checkMutating(FuncDecl *requirement, FuncDecl *witness,
ValueDecl *witnessDecl) {
// Witnesses in classes never have mutating conflicts.
if (auto contextType =
witnessDecl->getDeclContext()->getDeclaredTypeInContext())
if (contextType->hasReferenceSemantics())
return false;
// Determine whether the witness will be mutating or not. If the witness is
// stored property accessor, it may not be synthesized yet.
bool witnessMutating;
if (witness)
witnessMutating = (requirement->isInstanceMember() &&
witness->isMutating());
else {
assert(requirement->isAccessor());
auto storage = cast<AbstractStorageDecl>(witnessDecl);
switch (storage->getStorageKind()) {
// A stored property on a value type will have a mutating setter
// and a non-mutating getter.
case AbstractStorageDecl::Stored:
witnessMutating = requirement->isInstanceMember() &&
shouldUseSetterRequirements(requirement->getAccessorKind());
break;
// For an addressed property, consider the appropriate addressor.
case AbstractStorageDecl::Addressed: {
FuncDecl *addressor =
getAddressorForRequirement(storage, requirement->getAccessorKind());
witnessMutating = addressor->isMutating();
break;
}
case AbstractStorageDecl::StoredWithObservers:
case AbstractStorageDecl::StoredWithTrivialAccessors:
case AbstractStorageDecl::InheritedWithObservers:
case AbstractStorageDecl::AddressedWithTrivialAccessors:
case AbstractStorageDecl::AddressedWithObservers:
case AbstractStorageDecl::ComputedWithMutableAddress:
case AbstractStorageDecl::Computed:
llvm_unreachable("missing witness reference for kind with accessors");
}
}
// Requirements in class-bound protocols never 'mutate' self.
auto *proto = cast<ProtocolDecl>(requirement->getDeclContext());
bool requirementMutating = (requirement->isMutating() &&
!proto->requiresClass());
// The witness must not be more mutating than the requirement.
return !requirementMutating && witnessMutating;
}
/// Check that the Objective-C method(s) provided by the witness have
/// the same selectors as those required by the requirement.
static bool checkObjCWitnessSelector(TypeChecker &tc, ValueDecl *req,
ValueDecl *witness) {
// Simple case: for methods and initializers, check that the selectors match.
if (auto reqFunc = dyn_cast<AbstractFunctionDecl>(req)) {
auto witnessFunc = cast<AbstractFunctionDecl>(witness);
if (reqFunc->getObjCSelector() == witnessFunc->getObjCSelector())
return false;
auto diagInfo = getObjCMethodDiagInfo(witnessFunc);
auto diag = tc.diagnose(witness, diag::objc_witness_selector_mismatch,
diagInfo.first, diagInfo.second,
witnessFunc->getObjCSelector(),
reqFunc->getObjCSelector());
fixDeclarationObjCName(diag, witnessFunc, reqFunc->getObjCSelector());
return true;
}
// Otherwise, we have an abstract storage declaration.
auto reqStorage = cast<AbstractStorageDecl>(req);
auto witnessStorage = cast<AbstractStorageDecl>(witness);
// FIXME: Check property names!
// Check the getter.
if (auto reqGetter = reqStorage->getGetter()) {
if (checkObjCWitnessSelector(tc, reqGetter, witnessStorage->getGetter()))
return true;
}
// Check the setter.
if (auto reqSetter = reqStorage->getSetter()) {
if (checkObjCWitnessSelector(tc, reqSetter, witnessStorage->getSetter()))
return true;
}
return false;
}
/// \brief Match the given witness to the given requirement.
///
/// \returns the result of performing the match.
static RequirementMatch
matchWitness(TypeChecker &tc,
DeclContext *dc, ValueDecl *req, ValueDecl *witness,
const std::function<
std::tuple<Optional<RequirementMatch>, Type, Type>(void)>
&setup,
const std::function<Optional<RequirementMatch>(Type, Type)>
&matchTypes,
const std::function<
RequirementMatch(bool, ArrayRef<OptionalAdjustment>)
> &finalize) {
assert(!req->isInvalid() && "Cannot have an invalid requirement here");
/// Make sure the witness is of the same kind as the requirement.
if (req->getKind() != witness->getKind())
return RequirementMatch(witness, MatchKind::KindConflict);
// If the witness is invalid, record that and stop now.
if (witness->isInvalid())
return RequirementMatch(witness, MatchKind::WitnessInvalid);
// Get the requirement and witness attributes.
const auto &reqAttrs = req->getAttrs();
const auto &witnessAttrs = witness->getAttrs();
// Perform basic matching of the requirement and witness.
bool decomposeFunctionType = false;
bool ignoreReturnType = false;
if (auto funcReq = dyn_cast<FuncDecl>(req)) {
auto funcWitness = cast<FuncDecl>(witness);
// Either both must be 'static' or neither.
if (funcReq->isStatic() != funcWitness->isStatic() &&
!(funcReq->isOperator() &&
!funcWitness->getDeclContext()->isTypeContext()))
return RequirementMatch(witness, MatchKind::StaticNonStaticConflict);
// If we require a prefix operator and the witness is not a prefix operator,
// these don't match.
if (reqAttrs.hasAttribute<PrefixAttr>() &&
!witnessAttrs.hasAttribute<PrefixAttr>())
return RequirementMatch(witness, MatchKind::PrefixNonPrefixConflict);
// If we require a postfix operator and the witness is not a postfix
// operator, these don't match.
if (reqAttrs.hasAttribute<PostfixAttr>() &&
!witnessAttrs.hasAttribute<PostfixAttr>())
return RequirementMatch(witness, MatchKind::PostfixNonPostfixConflict);
// Check that the mutating bit is ok.
if (checkMutating(funcReq, funcWitness, funcWitness))
return RequirementMatch(witness, MatchKind::MutatingConflict);
// If the requirement is rethrows, the witness must either be
// rethrows or be non-throwing.
if (reqAttrs.hasAttribute<RethrowsAttr>() &&
!witnessAttrs.hasAttribute<RethrowsAttr>() &&
cast<AbstractFunctionDecl>(witness)->hasThrows())
return RequirementMatch(witness, MatchKind::RethrowsConflict);
// We want to decompose the parameters to handle them separately.
decomposeFunctionType = true;
} else if (auto *witnessASD = dyn_cast<AbstractStorageDecl>(witness)) {
auto *reqASD = cast<AbstractStorageDecl>(req);
// If this is a property requirement, check that the static-ness matches.
if (auto *vdWitness = dyn_cast<VarDecl>(witness)) {
if (cast<VarDecl>(req)->isStatic() != vdWitness->isStatic())
return RequirementMatch(witness, MatchKind::StaticNonStaticConflict);
}
// If the requirement is settable and the witness is not, reject it.
if (req->isSettable(req->getDeclContext()) &&
!witness->isSettable(witness->getDeclContext()))
return RequirementMatch(witness, MatchKind::SettableConflict);
// Find a standin declaration to place the diagnostic at for the
// given accessor kind.
auto getStandinForAccessor = [&](AccessorKind kind) -> ValueDecl* {
// If the witness actually explicitly provided that accessor,
// then great.
if (auto accessor = witnessASD->getAccessorFunction(kind))
if (!accessor->isImplicit())
return accessor;
// If it didn't, check to see if it provides something else.
if (witnessASD->hasAddressors()) {
return getAddressorForRequirement(witnessASD, kind);
}
// Otherwise, just diagnose starting at the storage declaration
// itself.
return witnessASD;
};
// Validate that the 'mutating' bit lines up for getters and setters.
if (checkMutating(reqASD->getGetter(), witnessASD->getGetter(),
witnessASD))
return RequirementMatch(getStandinForAccessor(AccessorKind::IsGetter),
MatchKind::MutatingConflict);
if (req->isSettable(req->getDeclContext()) &&
checkMutating(reqASD->getSetter(), witnessASD->getSetter(), witnessASD))
return RequirementMatch(getStandinForAccessor(AccessorKind::IsSetter),
MatchKind::MutatingConflict);
// Decompose the parameters for subscript declarations.
decomposeFunctionType = isa<SubscriptDecl>(req);
} else if (isa<ConstructorDecl>(witness)) {
decomposeFunctionType = true;
ignoreReturnType = true;
}
// If the requirement is @objc, the witness must not be marked with @nonobjc.
// @objc-ness will be inferred (separately) and the selector will be checked
// later.
if (req->isObjC() && witness->getAttrs().hasAttribute<NonObjCAttr>())
return RequirementMatch(witness, MatchKind::NonObjC);
// Set up the match, determining the requirement and witness types
// in the process.
Type reqType, witnessType;
{
Optional<RequirementMatch> result;
std::tie(result, reqType, witnessType) = setup();
if (result) {
return *result;
}
}
SmallVector<OptionalAdjustment, 2> optionalAdjustments;
bool anyRenaming = req->getFullName() != witness->getFullName();
if (decomposeFunctionType) {
// Decompose function types into parameters and result type.
auto reqFnType = reqType->castTo<AnyFunctionType>();
auto reqInputType = reqFnType->getInput();
auto reqResultType = reqFnType->getResult()->getRValueType();
auto witnessFnType = witnessType->castTo<AnyFunctionType>();
auto witnessInputType = witnessFnType->getInput();
auto witnessResultType = witnessFnType->getResult()->getRValueType();
// Result types must match.
// FIXME: Could allow (trivial?) subtyping here.
if (!ignoreReturnType) {
auto types = getTypesToCompare(req, reqResultType,
witnessResultType,
VarianceKind::Covariant);
// Record optional adjustment, if any.
if (std::get<2>(types) != OptionalAdjustmentKind::None) {
optionalAdjustments.push_back(
OptionalAdjustment(std::get<2>(types)));
}
if (auto result = matchTypes(std::get<0>(types),
std::get<1>(types))) {
return *result;
}
}
// Parameter types and kinds must match. Start by decomposing the input
// types into sets of tuple elements.
// Decompose the input types into parameters.
auto reqParams = decomposeIntoTupleElements(reqInputType);
auto witnessParams = decomposeIntoTupleElements(witnessInputType);
// If the number of parameters doesn't match, we're done.
if (reqParams.size() != witnessParams.size())
return RequirementMatch(witness, MatchKind::TypeConflict,
witnessType);
// Match each of the parameters.
for (unsigned i = 0, n = reqParams.size(); i != n; ++i) {
// Variadic bits must match.
// FIXME: Specialize the match failure kind
if (reqParams[i].isVararg() != witnessParams[i].isVararg())
return RequirementMatch(witness, MatchKind::TypeConflict, witnessType);
// Gross hack: strip a level of unchecked-optionality off both
// sides when matching against a protocol imported from Objective-C.
auto types = getTypesToCompare(req, reqParams[i].getType(),
witnessParams[i].getType(),
VarianceKind::Contravariant);
// Record any optional adjustment that occurred.
if (std::get<2>(types) != OptionalAdjustmentKind::None) {
optionalAdjustments.push_back(
OptionalAdjustment(std::get<2>(types), i));
}
// Check whether the parameter types match.
if (auto result = matchTypes(std::get<0>(types),
std::get<1>(types))) {
return *result;
}
// FIXME: Consider default arguments here?
}
// If the witness is 'throws', the requirement must be.
if (witnessFnType->getExtInfo().throws() &&
!reqFnType->getExtInfo().throws()) {
return RequirementMatch(witness, MatchKind::ThrowsConflict);
}
} else {
// Simple case: add the constraint.
auto types = getTypesToCompare(req, reqType, witnessType,
VarianceKind::None);
// Record optional adjustment, if any.
if (std::get<2>(types) != OptionalAdjustmentKind::None) {
optionalAdjustments.push_back(
OptionalAdjustment(std::get<2>(types)));
}
if (auto result = matchTypes(std::get<0>(types), std::get<1>(types))) {
return *result;
}
}
// Now finalize the match.
return finalize(anyRenaming, optionalAdjustments);
}
RequirementEnvironment::RequirementEnvironment(
TypeChecker &tc,
DeclContext *conformanceDC,
ValueDecl *req,
ProtocolConformance *conformance) {
ASTContext &ctx = tc.Context;
auto proto = cast<ProtocolDecl>(req->getDeclContext());
// Build a substitution map to replace the protocol's \c Self and the type
// parameters of the requirement into a combined context that provides the
// type parameters of the conformance context and the parameters of the
// requirement.
Type concreteType = conformanceDC->getSelfInterfaceType();
auto selfType = proto->getSelfInterfaceType()->getCanonicalType();
reqToSyntheticEnvMap.addSubstitution(selfType, concreteType);
// 'Self' is always at depth 0, index 0. Anything else is invalid code.
auto selfGenericParam = selfType->castTo<GenericTypeParamType>();
if (selfGenericParam->getDepth() != 0 ||
selfGenericParam->getIndex() != 0) {
return;
}