forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeCheckProtocol.cpp
4218 lines (3546 loc) · 149 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 - 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 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/AST/ArchetypeBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.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 "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
namespace {
struct RequirementMatch;
/// The result of attempting to resolve a witness.
enum class ResolveWitnessResult {
/// The resolution succeeded.
Success,
/// There was an explicit witness available, but it failed some
/// criteria.
ExplicitFailed,
/// There was no witness available.
Missing
};
/// Describes the result of checking a type witness.
///
/// This class evaluates true if an error occurred.
class CheckTypeWitnessResult {
ProtocolDecl *Proto = nullptr;
public:
CheckTypeWitnessResult() { }
CheckTypeWitnessResult(ProtocolDecl *proto) : Proto(proto) { }
ProtocolDecl *getProtocol() const { return Proto; }
explicit operator bool() const { return Proto != nullptr; }
};
/// The set of associated types that have been inferred by matching
/// the given value witness to its corresponding requirement.
struct InferredAssociatedTypesByWitness {
/// The witness we matched.
ValueDecl *Witness = nullptr;
/// The associated types inferred from matching this witness.
SmallVector<std::pair<AssociatedTypeDecl *, Type>, 4> Inferred;
/// Inferred associated types that don't meet the associated type
/// requirements.
SmallVector<std::tuple<AssociatedTypeDecl *, Type, CheckTypeWitnessResult>,
2> NonViable;
};
/// The set of witnesses that were considered when attempting to
/// infer associated types.
typedef SmallVector<InferredAssociatedTypesByWitness, 2>
InferredAssociatedTypesByWitnesses;
/// A mapping from requirements to the set of matches with witnesses.
typedef SmallVector<std::pair<ValueDecl *,
InferredAssociatedTypesByWitnesses>, 4>
InferredAssociatedTypes;
/// The protocol conformance checker.
///
/// This helper class handles most of the details of checking whether a
/// given type (\c Adoptee) conforms to a protocol (\c Proto).
class ConformanceChecker {
TypeChecker &TC;
NormalProtocolConformance *Conformance;
ProtocolDecl *Proto;
Type Adoptee;
DeclContext *DC;
SourceLoc Loc;
/// Witnesses that are currently being resolved.
llvm::SmallPtrSet<ValueDecl *, 4> ResolvingWitnesses;
/// Caches the set of associated types that are referenced in each
/// requirement.
llvm::DenseMap<ValueDecl *, llvm::SmallVector<AssociatedTypeDecl *, 2>>
ReferencedAssociatedTypes;
/// True if we shouldn't complain about problems with this conformance
/// right now, i.e. if methods are being called outside
/// checkConformance().
bool SuppressDiagnostics;
/// Whether we've already complained about problems with this conformance.
bool AlreadyComplained = false;
/// Retrieve the associated types that are referenced by the given
/// requirement with a base of 'Self'.
ArrayRef<AssociatedTypeDecl *> getReferencedAssociatedTypes(ValueDecl *req);
/// Record a (non-type) witness for the given requirement.
void recordWitness(ValueDecl *requirement, const RequirementMatch &match);
/// Record that the given optional requirement has no witness.
void recordOptionalWitness(ValueDecl *requirement);
/// Check whether there is a potential non-@objc witness for an
/// @objc optional requirement.
void checkOptionalWitnessNonObjCMatch(ValueDecl *requirement);
/// Record a type witness.
///
/// \param assocType The associated type whose witness is being recorded.
///
/// \param type The witness type.
///
/// \param typeDecl The decl the witness type came from; can be null.
///
/// \param fromDC The DeclContext from which this associated type was
/// computed, which may be different from the context associated with the
/// protocol conformance.
///
/// \param wasDeducedOrDefaulted Whether this witness was deduced or
/// defaulted (rather than being explicitly provided).
void recordTypeWitness(AssociatedTypeDecl *assocType, Type type,
TypeDecl *typeDecl, DeclContext *fromDC,
bool wasDeducedOrDefaulted,
bool performRedeclarationCheck = true);
/// Resolve a (non-type) witness via name lookup.
ResolveWitnessResult resolveWitnessViaLookup(ValueDecl *requirement);
/// Resolve a (non-type) witness via derivation.
ResolveWitnessResult resolveWitnessViaDerivation(ValueDecl *requirement);
/// Resolve a (non-type) witness via default definition or optional.
ResolveWitnessResult resolveWitnessViaDefault(ValueDecl *requirement);
/// 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);
/// Attempt to resolve a type witness via member name lookup.
ResolveWitnessResult resolveTypeWitnessViaLookup(
AssociatedTypeDecl *assocType);
/// Infer associated type witnesses for the given tentative
/// requirement/witness match.
InferredAssociatedTypesByWitness inferTypeWitnessesViaValueWitness(
ValueDecl *req,
ValueDecl *witness);
/// Infer associated type witnesses for the given value requirement.
InferredAssociatedTypesByWitnesses inferTypeWitnessesViaValueWitnesses(
ValueDecl *req);
/// Infer associated type witnesses for all relevant value requirements.
///
/// \param assocTypes The set of associated types we're interested in.
InferredAssociatedTypes
inferTypeWitnessesViaValueWitnesses(
const llvm::SetVector<AssociatedTypeDecl *> &assocTypes);
/// Diagnose or defer a diagnostic, as appropriate.
///
/// \param requirement The requirement with which this diagnostic is
/// associated, if any.
///
/// \param isError Whether this diagnostic is an error.
///
/// \param fn A function to call to emit the actual diagnostic. If
/// diagnostics are being deferred,
void diagnoseOrDefer(
ValueDecl *requirement, bool isError,
std::function<void(TypeChecker &, NormalProtocolConformance *)> fn);
public:
/// Emit any diagnostics that have been delayed.
void emitDelayedDiags();
ConformanceChecker(TypeChecker &tc, NormalProtocolConformance *conformance,
bool suppressDiagnostics = true)
: TC(tc), Conformance(conformance),
Proto(conformance->getProtocol()),
Adoptee(conformance->getType()),
DC(conformance->getDeclContext()),
Loc(conformance->getLoc()),
SuppressDiagnostics(suppressDiagnostics) { }
/// Resolve all of the type witnesses.
void resolveTypeWitnesses();
/// Resolve the witness for the given non-type requirement as
/// directly as possible, only resolving other witnesses if
/// needed, e.g., to determine type witnesses used within the
/// requirement.
///
/// This entry point is designed to be used when the witness for a
/// particular requirement and adoptee is required, before the
/// conformance has been completed checked.
void resolveSingleWitness(ValueDecl *requirement);
/// Resolve the type witness for the given associated type as
/// directly as possible.
void resolveSingleTypeWitness(AssociatedTypeDecl *assocType);
/// Check the entire protocol conformance, ensuring that all
/// witnesses are resolved and emitting any diagnostics.
void checkConformance();
};
}
# pragma mark Witness resolution
/// \brief Retrieve the kind of requirement described by the given declaration,
/// for use in some diagnostics.
static diag::RequirementKind getRequirementKind(ValueDecl *VD) {
if (isa<ConstructorDecl>(VD))
return diag::RequirementKind::Constructor;
if (isa<FuncDecl>(VD))
return diag::RequirementKind::Func;
if (isa<VarDecl>(VD))
return diag::RequirementKind::Var;
assert(isa<SubscriptDecl>(VD) && "Unhandled requirement kind");
return diag::RequirementKind::Subscript;
}
namespace {
/// \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 @noreturn, but the requirement is.
NoReturnConflict,
/// The witness is not rethrows, but the requirement is.
RethrowsConflict,
/// The witness has a different Objective-C selector than the
/// requirement.
ObjCSelectorConflict,
/// The witness is not @objc but the requirement is.
NotObjC,
};
/// 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,
};
/// 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;
}
}
/// 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::NoReturnConflict:
case MatchKind::RethrowsConflict:
case MatchKind::ThrowsConflict:
case MatchKind::ObjCSelectorConflict:
case MatchKind::NotObjC:
return false;
}
}
/// \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::NoReturnConflict:
case MatchKind::RethrowsConflict:
case MatchKind::ThrowsConflict:
case MatchKind::ObjCSelectorConflict:
case MatchKind::NotObjC:
return false;
}
}
/// \brief Associated type substitutions needed to match the witness.
SmallVector<Substitution, 2> WitnessSubstitutions;
/// 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;
};
}
SourceLoc OptionalAdjustment::getOptionalityLoc(ValueDecl *witness) const {
// For non-parameter adjustments, use the result type or whole type,
// as appropriate.
if (!isParameterAdjustment()) {
// For a function, use the result type.
if (auto func = dyn_cast<FuncDecl>(witness)) {
return getOptionalityLoc(
func->getBodyResultTypeLoc().getTypeRepr());
}
// For a subscript, use the element type.
if (auto subscript = dyn_cast<SubscriptDecl>(witness)) {
return getOptionalityLoc(
subscript->getElementTypeLoc().getTypeRepr());
}
// Otherwise, we have a variable.
// FIXME: Dig into the pattern.
return SourceLoc();
}
// For parameter adjustments, dig out the pattern.
Pattern *pattern = nullptr;
if (auto func = dyn_cast<AbstractFunctionDecl>(witness)) {
auto bodyPatterns = func->getBodyParamPatterns();
if (func->getDeclContext()->isTypeContext())
bodyPatterns = bodyPatterns.slice(1);
pattern = bodyPatterns[0];
} else if (auto subscript = dyn_cast<SubscriptDecl>(witness)) {
pattern = subscript->getIndices();
} else {
return SourceLoc();
}
// Handle parentheses.
if (auto paren = dyn_cast<ParenPattern>(pattern)) {
assert(getParameterIndex() == 0 && "just the one parameter");
if (auto typed = dyn_cast<TypedPattern>(paren->getSubPattern())) {
return getOptionalityLoc(typed->getTypeLoc().getTypeRepr());
}
return SourceLoc();
}
// Handle tuples.
auto tuple = dyn_cast<TuplePattern>(pattern);
if (!tuple)
return SourceLoc();
const auto &tupleElt = tuple->getElement(getParameterIndex());
if (auto typed = dyn_cast<TypedPattern>(tupleElt.getPattern())) {
return getOptionalityLoc(typed->getTypeLoc().getTypeRepr());
}
return SourceLoc();
}
SourceLoc OptionalAdjustment::getOptionalityLoc(TypeRepr *tyR) const {
if (!tyR)
return SourceLoc();
switch (getKind()) {
case OptionalAdjustmentKind::None:
llvm_unreachable("not an adjustment");
case OptionalAdjustmentKind::ConsumesUnhandledNil:
case OptionalAdjustmentKind::WillNeverProduceNil:
// The location of the '?' to be inserted is after the type.
return tyR->getEndLoc();
case OptionalAdjustmentKind::ProducesUnhandledNil:
case OptionalAdjustmentKind::WillNeverConsumeNil:
case OptionalAdjustmentKind::RemoveIUO:
case OptionalAdjustmentKind::IUOToOptional:
// Find the location of optionality, below.
break;
}
if (auto optRepr = dyn_cast<OptionalTypeRepr>(tyR))
return optRepr->getQuestionLoc();
if (auto iuoRepr = dyn_cast<ImplicitlyUnwrappedOptionalTypeRepr>(tyR))
return iuoRepr->getExclamationLoc();
return SourceLoc();
}
void RequirementMatch::addOptionalityFixIts(
const ASTContext &ctx,
ValueDecl *witness,
InFlightDiagnostic &diag) const {
for (const auto &adjustment : OptionalAdjustments) {
SourceLoc adjustmentLoc = adjustment.getOptionalityLoc(witness);
if (adjustmentLoc.isInvalid())
continue;
switch (adjustment.getKind()) {
case OptionalAdjustmentKind::None:
llvm_unreachable("not an optional adjustment");
case OptionalAdjustmentKind::ProducesUnhandledNil:
case OptionalAdjustmentKind::WillNeverConsumeNil:
case OptionalAdjustmentKind::RemoveIUO:
diag.fixItRemove(adjustmentLoc);
break;
case OptionalAdjustmentKind::WillNeverProduceNil:
case OptionalAdjustmentKind::ConsumesUnhandledNil:
diag.fixItInsertAfter(adjustmentLoc, "?");
break;
case OptionalAdjustmentKind::IUOToOptional:
diag.fixItReplace(adjustmentLoc, "?");
break;
}
}
}
///\ 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;
}
namespace {
/// Dependent type opener that maps the type of a requirement, replacing
/// already-known associated types to their type witnesses and inner generic
/// parameters to their archetypes.
class RequirementTypeOpener : public constraints::DependentTypeOpener {
/// The type variable that represents the 'Self' type.
constraints::ConstraintSystem &CS;
NormalProtocolConformance *Conformance;
DeclContext *DC;
ProtocolDecl *Proto;
public:
RequirementTypeOpener(constraints::ConstraintSystem &cs,
NormalProtocolConformance *conformance,
DeclContext *dc)
: CS(cs), Conformance(conformance), DC(dc),
Proto(conformance->getProtocol())
{
}
virtual void openedGenericParameter(GenericTypeParamType *param,
TypeVariableType *typeVar,
Type &replacementType) {
// If this is the 'Self' type, record it.
if (param->getDepth() == 0 && param->getIndex() == 0)
CS.SelfTypeVar = typeVar;
else
replacementType = ArchetypeBuilder::mapTypeIntoContext(DC, param);
}
virtual bool shouldBindAssociatedType(Type baseType,
TypeVariableType *baseTypeVar,
AssociatedTypeDecl *assocType,
TypeVariableType *memberTypeVar,
Type &replacementType) {
// If the base is our 'Self' type, we have a witness for this
// associated type already.
if (baseTypeVar == CS.SelfTypeVar &&
cast<ProtocolDecl>(assocType->getDeclContext()) == Proto) {
replacementType = Conformance->getTypeWitness(assocType, nullptr)
.getReplacement();
// Let the member type variable float; we don't want to
// resolve it as a member.
return false;
}
// If the base is somehow derived from our 'Self' type, we can go ahead
// and bind it. There's nothing more to do.
auto rootBaseType = baseType;
while (auto dependentMember = rootBaseType->getAs<DependentMemberType>())
rootBaseType = dependentMember->getBase();
if (auto rootGP = rootBaseType->getAs<GenericTypeParamType>()) {
if (rootGP->getDepth() == 0 && rootGP->getIndex() == 0)
return true;
} else {
return true;
}
// We have a dependent member type based on a generic parameter; map it
// to an archetype.
auto memberType = DependentMemberType::get(baseType, assocType,
DC->getASTContext());
replacementType = ArchetypeBuilder::mapTypeIntoContext(DC, memberType);
return true;
}
};
/// 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 = 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");
}
}
// If the requirement is for a nonmutating member, then the witness may not
// mutate self.
return !requirement->isMutating() && 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,
bool complain) {
// Simple case: for methods, check that the selectors match.
if (auto reqFunc = dyn_cast<AbstractFunctionDecl>(req)) {
auto witnessFunc = cast<AbstractFunctionDecl>(witness);
if (reqFunc->getObjCSelector() == witnessFunc->getObjCSelector())
return false;
if (complain) {
auto diagInfo = getObjCMethodDiagInfo(witnessFunc);
tc.diagnose(witness, diag::objc_witness_selector_mismatch,
diagInfo.first, diagInfo.second,
witnessFunc->getObjCSelector(), reqFunc->getObjCSelector());
}
return true;
}
// Otherwise, we have an abstract storage declaration.
auto reqStorage = cast<AbstractStorageDecl>(req);
auto witnessStorage = cast<AbstractStorageDecl>(witness);
// Check the getter.
if (auto reqGetter = reqStorage->getGetter()) {
if (checkObjCWitnessSelector(tc, reqGetter, witnessStorage->getGetter(),
complain))
return true;
}
// Check the setter.
if (auto reqSetter = reqStorage->getSetter()) {
if (checkObjCWitnessSelector(tc, reqSetter, witnessStorage->getSetter(),
complain))
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, NormalProtocolConformance *conformance,
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())
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);