-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckDeclOverride.cpp
2600 lines (2241 loc) · 95.7 KB
/
TypeCheckDeclOverride.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
//===--- TypeCheckOverride.cpp - Override Checking ------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements semantic analysis for declaration overrides.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckDecl.h"
#include "TypeCheckEffects.h"
#include "TypeCheckObjC.h"
#include "TypeCheckUnsafe.h"
#include "TypeChecker.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/AvailabilityInference.h"
#include "swift/AST/AvailabilityRange.h"
#include "swift/AST/Decl.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/UnsafeUse.h"
#include "swift/Basic/Assertions.h"
using namespace swift;
static void adjustFunctionTypeForOverride(Type &type) {
// Drop 'throws'.
// FIXME: Do we want to allow overriding a function returning a value
// with one returning Never?
auto fnType = type->castTo<AnyFunctionType>();
auto extInfo = fnType->getExtInfo();
extInfo = extInfo.withThrows(false, Type());
if (!fnType->getExtInfo().isEqualTo(extInfo, useClangTypes(fnType)))
type = fnType->withExtInfo(extInfo);
}
/// Drop the optionality of the result type of the given function type.
static Type dropResultOptionality(Type type, unsigned uncurryLevel) {
// We've hit the result type.
if (uncurryLevel == 0) {
if (auto objectTy = type->getOptionalObjectType())
return objectTy;
return type;
}
// Determine the input and result types of this function.
auto fnType = type->castTo<AnyFunctionType>();
auto parameters = fnType->getParams();
Type resultType =
dropResultOptionality(fnType->getResult(), uncurryLevel - 1);
// Produce the resulting function type.
if (auto genericFn = dyn_cast<GenericFunctionType>(fnType)) {
return GenericFunctionType::get(genericFn->getGenericSignature(),
parameters, resultType,
fnType->getExtInfo());
}
return FunctionType::get(parameters, resultType, fnType->getExtInfo());
}
Type swift::getMemberTypeForComparison(const ValueDecl *member,
const ValueDecl *derivedDecl) {
auto *method = dyn_cast<AbstractFunctionDecl>(member);
auto *ctor = dyn_cast_or_null<ConstructorDecl>(method);
auto abstractStorage = dyn_cast<AbstractStorageDecl>(member);
assert((method || abstractStorage) && "Not a method or abstractStorage?");
auto *subscript = dyn_cast_or_null<SubscriptDecl>(abstractStorage);
auto memberType = member->getInterfaceType();
if (memberType->is<ErrorType>())
return memberType;
if (derivedDecl) {
auto *dc = derivedDecl->getDeclContext();
auto owningType = dc->getDeclaredInterfaceType();
assert(owningType);
memberType = owningType->adjustSuperclassMemberDeclType(member, derivedDecl,
memberType);
}
if (method) {
// For methods, strip off the 'Self' type.
memberType = memberType->castTo<AnyFunctionType>()->getResult();
adjustFunctionTypeForOverride(memberType);
} else if (subscript) {
// For subscripts, we don't have a 'Self' type, but turn it
// into a monomorphic function type.
auto funcTy = memberType->castTo<AnyFunctionType>();
// FIXME: Verify ExtInfo state is correct, not working by accident.
FunctionType::ExtInfo info;
memberType =
FunctionType::get(funcTy->getParams(), funcTy->getResult(), info);
} else {
// For properties, strip off ownership.
memberType = memberType->getReferenceStorageReferent();
}
// Ignore the optionality of initializers when comparing types;
// we'll enforce this separately
if (ctor) {
memberType = dropResultOptionality(memberType, 1);
}
return memberType;
}
static bool
areAccessorsOverrideCompatible(const AbstractStorageDecl *storage,
const AbstractStorageDecl *parentStorage) {
// It's okay for the storage to disagree about whether to use a getter or
// a read accessor; we'll patch up any differences when setting overrides
// for the accessors. We don't want to diagnose anything involving
// `@_borrowed` because it is not yet part of the language.
// All the other checks are for non-static storage only.
if (storage->isStatic())
return true;
// The storage must agree on whether reads are mutating. For accessors,
// this is sufficient to imply that they use the same SelfAccessKind
// because we do not allow accessors to be consuming.
if (storage->isGetterMutating() != parentStorage->isGetterMutating())
return false;
// We allow covariance about whether the storage itself is mutable, so we
// can only check mutating-ness of setters if both have one.
if (storage->supportsMutation() && parentStorage->supportsMutation()) {
// The storage must agree on whether writes are mutating.
if (storage->isSetterMutating() != parentStorage->isSetterMutating())
return false;
// Those together should imply that read-write accesses have the same
// mutability.
}
return true;
}
bool swift::isOverrideBasedOnType(const ValueDecl *decl, Type declTy,
const ValueDecl *parentDecl) {
auto genericSig =
decl->getInnermostDeclContext()->getGenericSignatureOfContext();
auto canDeclTy = declTy->getReducedType(genericSig);
auto declIUOAttr = decl->isImplicitlyUnwrappedOptional();
auto parentDeclIUOAttr = parentDecl->isImplicitlyUnwrappedOptional();
if (declIUOAttr != parentDeclIUOAttr)
return false;
// If the generic signatures don't match, then return false because we don't
// want to complain if an overridden method matches multiple superclass
// methods which differ in generic signature.
//
// We can still succeed with a subtype match later in
// OverrideMatcher::match().
if (auto declCtx = decl->getAsGenericContext()) {
// The below logic now works correctly for protocol requirements which are
// themselves generic, but that would be an ABI break, since we would now
// drop the protocol requirements from witness tables. Simulate the old
// behavior by not considering generic declarations in protocols as
// overrides at all.
if (decl->getDeclContext()->getSelfProtocolDecl() &&
declCtx->isGeneric())
return false;
auto *parentCtx = parentDecl->getAsGenericContext();
if (declCtx->isGeneric() != parentCtx->isGeneric())
return false;
if (declCtx->isGeneric() &&
(declCtx->getGenericParams()->size() !=
parentCtx->getGenericParams()->size()))
return false;
auto &ctx = decl->getASTContext();
auto sig = ctx.getOverrideGenericSignature(parentDecl, decl);
if (sig &&
declCtx->getGenericSignature().getCanonicalSignature() !=
sig.getCanonicalSignature()) {
return false;
}
}
auto parentDeclTy = getMemberTypeForComparison(parentDecl, decl);
if (parentDeclTy->hasError())
return false;
auto canParentDeclTy = parentDeclTy->getReducedType(genericSig);
// If this is a constructor, let's compare only parameter types.
if (isa<ConstructorDecl>(decl)) {
// Within a protocol context, check for a failability mismatch.
if (isa<ProtocolDecl>(decl->getDeclContext())) {
if (cast<ConstructorDecl>(decl)->isFailable() !=
cast<ConstructorDecl>(parentDecl)->isFailable())
return false;
if (cast<ConstructorDecl>(decl)->isImplicitlyUnwrappedOptional() !=
cast<ConstructorDecl>(parentDecl)->isImplicitlyUnwrappedOptional())
return false;
}
auto fnType1 = declTy->castTo<AnyFunctionType>();
auto fnType2 = parentDeclTy->castTo<AnyFunctionType>();
return AnyFunctionType::equalParams(fnType1->getParams(),
fnType2->getParams());
// In a non-static protocol requirement, verify that the self access kind
// matches.
} else if (auto func = dyn_cast<FuncDecl>(decl)) {
// We only compare `isMutating()` rather than `getSelfAccessKind()`
// because we don't want to complain about `nonmutating` vs. `__consuming`
// conflicts at this time, especially since `__consuming` is not yet
// officially part of the language.
if (!func->isStatic() &&
func->isMutating() != cast<FuncDecl>(parentDecl)->isMutating())
return false;
// In abstract storage, verify that the accessor mutating-ness matches.
} else if (auto storage = dyn_cast<AbstractStorageDecl>(decl)) {
auto parentStorage = cast<AbstractStorageDecl>(parentDecl);
if (!areAccessorsOverrideCompatible(storage, parentStorage))
return false;
}
return canDeclTy == canParentDeclTy;
}
static bool isUnavailableInAllVersions(ValueDecl *decl) {
ASTContext &ctx = decl->getASTContext();
auto deploymentContext = AvailabilityContext::forDeploymentTarget(ctx);
auto constraints = getAvailabilityConstraintsForDecl(decl, deploymentContext);
for (auto constraint : constraints) {
switch (constraint.getReason()) {
case AvailabilityConstraint::Reason::UnconditionallyUnavailable:
case AvailabilityConstraint::Reason::UnavailableForDeployment:
return true;
case AvailabilityConstraint::Reason::Obsoleted:
case AvailabilityConstraint::Reason::PotentiallyUnavailable:
break;
}
}
return false;
}
/// Perform basic checking to determine whether a declaration can override a
/// declaration in a superclass.
static bool areOverrideCompatibleSimple(ValueDecl *decl,
ValueDecl *parentDecl) {
// If the number of argument labels does not match, these overrides cannot
// be compatible.
if (decl->getName().getArgumentNames().size() !=
parentDecl->getName().getArgumentNames().size())
return false;
// If the parent declaration is not in a class (or extension thereof) or
// a protocol, we cannot override it.
if (decl->getDeclContext()->getSelfClassDecl() &&
parentDecl->getDeclContext()->getSelfClassDecl()) {
// Okay: class override
} else if (isa<ProtocolDecl>(decl->getDeclContext()) &&
isa<ProtocolDecl>(parentDecl->getDeclContext())) {
// Okay: protocol override.
} else {
// Cannot be an override.
return false;
}
// Ignore declarations that are defined inside constrained extensions.
if (auto *ext = dyn_cast<ExtensionDecl>(parentDecl->getDeclContext()))
if (ext->isConstrainedExtension())
return false;
// The declarations must be of the same kind.
if (decl->getKind() != parentDecl->getKind())
return false;
// If the parent decl is unavailable, the subclass decl can shadow it, but it
// can't override it. To avoid complex version logic, we don't apply this to
// `obsoleted` members, only `unavailable` ones.
// FIXME: Refactor to allow that when the minimum version is always satisfied.
if (isUnavailableInAllVersions(parentDecl))
// If the subclass decl is trying to override, we'll diagnose it later.
if (!decl->getAttrs().hasAttribute<OverrideAttr>())
return false;
// Ignore invalid parent declarations.
// FIXME: Do we really need this?
if (parentDecl->isInvalid())
return false;
// If their staticness is different, they aren't compatible.
if (decl->isStatic() != parentDecl->isStatic())
return false;
// If their genericity is different, they aren't compatible.
if (auto genDecl = decl->getAsGenericContext()) {
auto genParentDecl = parentDecl->getAsGenericContext();
if (genDecl->isGeneric() != genParentDecl->isGeneric())
return false;
if (genDecl->isGeneric() &&
(genDecl->getGenericParams()->size() !=
genParentDecl->getGenericParams()->size()))
return false;
}
// Factory initializers cannot be overridden.
if (auto parentCtor = dyn_cast<ConstructorDecl>(parentDecl))
if (parentCtor->isFactoryInit())
return false;
return true;
}
static bool
diagnoseMismatchedOptionals(const ValueDecl *member,
const ParameterList *params, TypeLoc resultTL,
const ValueDecl *parentMember,
const ParameterList *parentParams, Type owningTy,
bool treatIUOResultAsError) {
auto &diags = member->getASTContext().Diags;
bool emittedError = false;
Type plainParentTy = owningTy->adjustSuperclassMemberDeclType(
parentMember, member, parentMember->getInterfaceType());
const auto *parentTy = plainParentTy->castTo<FunctionType>();
if (isa<AbstractFunctionDecl>(parentMember))
parentTy = parentTy->getResult()->castTo<FunctionType>();
// Check the parameter types.
auto checkParam = [&](const ParamDecl *decl, const ParamDecl *parentDecl) {
Type paramTy = decl->getTypeInContext();
Type parentParamTy = parentDecl->getTypeInContext();
auto *repr = decl->getTypeRepr();
if (!repr)
return;
bool paramIsOptional = (bool) paramTy->getOptionalObjectType();
bool parentIsOptional = (bool) parentParamTy->getOptionalObjectType();
if (paramIsOptional == parentIsOptional)
return;
if (!paramIsOptional) {
if (parentDecl->isImplicitlyUnwrappedOptional())
if (!treatIUOResultAsError)
return;
emittedError = true;
auto diag = diags.diagnose(decl->getStartLoc(),
diag::override_optional_mismatch,
member->getDescriptiveKind(),
isa<SubscriptDecl>(member),
parentParamTy, paramTy);
if (repr->isSimple()) {
diag.fixItInsertAfter(repr->getEndLoc(), "?");
} else {
diag.fixItInsert(repr->getStartLoc(), "(");
diag.fixItInsertAfter(repr->getEndLoc(), ")?");
}
return;
}
if (!decl->isImplicitlyUnwrappedOptional())
return;
// Allow silencing this warning using parens.
if (auto *TTR = dyn_cast<TupleTypeRepr>(repr)) {
if (TTR->isParenType())
return;
}
diags
.diagnose(decl->getStartLoc(), diag::override_unnecessary_IUO,
member->getDescriptiveKind(), parentParamTy, paramTy)
.highlight(repr->getSourceRange());
if (auto iuoRepr = dyn_cast<ImplicitlyUnwrappedOptionalTypeRepr>(repr)) {
diags
.diagnose(iuoRepr->getExclamationLoc(),
diag::override_unnecessary_IUO_remove)
.fixItRemove(iuoRepr->getExclamationLoc());
}
diags.diagnose(repr->getStartLoc(), diag::override_unnecessary_IUO_silence)
.fixItInsert(repr->getStartLoc(), "(")
.fixItInsertAfter(repr->getEndLoc(), ")");
};
// FIXME: If we ever allow argument reordering, this is incorrect.
ArrayRef<ParamDecl *> sharedParams = params->getArray();
ArrayRef<ParamDecl *> sharedParentParams = parentParams->getArray();
assert(sharedParams.size() == sharedParentParams.size());
for_each(sharedParams, sharedParentParams, checkParam);
if (!resultTL.getTypeRepr())
return emittedError;
auto checkResult = [&](TypeLoc resultTL, Type parentResultTy) {
Type resultTy = resultTL.getType();
if (!resultTy || !parentResultTy)
return;
if (!resultTy->getOptionalObjectType())
return;
TypeRepr *TR = resultTL.getTypeRepr();
bool resultIsPlainOptional = true;
if (member->isImplicitlyUnwrappedOptional())
resultIsPlainOptional = false;
if (resultIsPlainOptional || treatIUOResultAsError) {
if (parentResultTy->getOptionalObjectType())
return;
emittedError = true;
auto diag = diags.diagnose(resultTL.getSourceRange().Start,
diag::override_optional_result_mismatch,
member->getDescriptiveKind(),
isa<SubscriptDecl>(member),
parentResultTy, resultTy);
if (auto optForm = dyn_cast<OptionalTypeRepr>(TR)) {
diag.fixItRemove(optForm->getQuestionLoc());
} else if (auto iuoForm =
dyn_cast<ImplicitlyUnwrappedOptionalTypeRepr>(TR)) {
diag.fixItRemove(iuoForm->getExclamationLoc());
}
return;
}
if (!parentResultTy->getOptionalObjectType())
return;
// Allow silencing this warning using parens.
if (auto *TTR = dyn_cast<TupleTypeRepr>(TR)) {
if (TTR->isParenType())
return;
}
diags.diagnose(resultTL.getSourceRange().Start,
diag::override_unnecessary_result_IUO,
member->getDescriptiveKind(), parentResultTy, resultTy)
.highlight(resultTL.getSourceRange());
auto sugaredForm = dyn_cast<ImplicitlyUnwrappedOptionalTypeRepr>(TR);
if (sugaredForm) {
diags.diagnose(sugaredForm->getExclamationLoc(),
diag::override_unnecessary_IUO_use_strict)
.fixItReplace(sugaredForm->getExclamationLoc(), "?");
}
diags.diagnose(resultTL.getSourceRange().Start,
diag::override_unnecessary_IUO_silence)
.fixItInsert(resultTL.getSourceRange().Start, "(")
.fixItInsertAfter(resultTL.getSourceRange().End, ")");
};
checkResult(resultTL, parentTy->getResult());
return emittedError;
}
/// Record that the \c overriding declarations overrides the
/// \c overridden declaration.
///
/// \returns true if an error occurred.
static bool checkSingleOverride(ValueDecl *override, ValueDecl *base);
/// If the difference between the types of \p decl and \p base is something
/// we feel confident about fixing (even partially), emit a note with fix-its
/// attached. Otherwise, no note will be emitted.
///
/// \returns true iff a diagnostic was emitted.
static bool noteFixableMismatchedTypes(ValueDecl *decl, const ValueDecl *base) {
auto &ctx = decl->getASTContext();
auto &diags = ctx.Diags;
Type baseTy = base->getInterfaceType();
if (baseTy->hasError())
return false;
if (auto *baseInit = dyn_cast<ConstructorDecl>(base)) {
// Special-case initializers, whose "type" isn't useful besides the
// input arguments.
auto *fnType = baseTy->getAs<AnyFunctionType>();
baseTy = fnType->getResult();
Type argTy = FunctionType::composeTuple(
ctx, baseTy->getAs<AnyFunctionType>()->getParams(),
ParameterFlagHandling::IgnoreNonEmpty);
auto diagKind = diag::override_type_mismatch_with_fixits_init;
unsigned numArgs = baseInit->getParameters()->size();
return computeFixitsForOverriddenDeclaration(
decl, base, [&](bool HasNotes) -> std::optional<InFlightDiagnostic> {
if (!HasNotes)
return std::nullopt;
return diags.diagnose(decl, diagKind,
/*plural*/ std::min(numArgs, 2U), argTy);
});
} else {
if (isa<AbstractFunctionDecl>(base))
baseTy = baseTy->getAs<AnyFunctionType>()->getResult();
return computeFixitsForOverriddenDeclaration(
decl, base, [&](bool HasNotes) -> std::optional<InFlightDiagnostic> {
if (!HasNotes)
return std::nullopt;
return diags.diagnose(decl, diag::override_type_mismatch_with_fixits,
base->getDescriptiveKind(), baseTy);
});
}
return false;
}
namespace {
enum class OverrideCheckingAttempt {
PerfectMatch,
// Ignores only @Sendable and `any Sendable` annotations
MismatchedSendability,
// Ignores both sendability and global actor isolation annotations.
MismatchedConcurrency,
MismatchedOptional,
MismatchedTypes,
BaseName,
BaseNameWithMismatchedOptional,
Final
};
OverrideCheckingAttempt &operator++(OverrideCheckingAttempt &attempt) {
assert(attempt != OverrideCheckingAttempt::Final);
attempt = static_cast<OverrideCheckingAttempt>(1+static_cast<int>(attempt));
return attempt;
}
struct OverrideMatch {
ValueDecl *Decl;
bool IsExact;
};
}
static void diagnoseGeneralOverrideFailure(ValueDecl *decl,
ArrayRef<OverrideMatch> matches,
OverrideCheckingAttempt attempt) {
auto &diags = decl->getASTContext().Diags;
switch (attempt) {
case OverrideCheckingAttempt::PerfectMatch:
diags.diagnose(decl, diag::override_multiple_decls_base,
decl->getName());
break;
case OverrideCheckingAttempt::MismatchedSendability: {
SendableCheckContext fromContext(decl->getDeclContext(),
SendableCheck::Explicit);
for (const auto &match : matches) {
auto baseDeclClass = match.Decl->getDeclContext()->getSelfClassDecl();
diagnoseSendabilityErrorBasedOn(
baseDeclClass, fromContext, [&](DiagnosticBehavior limit) {
diags
.diagnose(decl, diag::override_sendability_mismatch,
decl->getName())
.limitBehaviorUntilSwiftVersion(limit, 6)
.limitBehaviorIf(
fromContext.preconcurrencyBehavior(baseDeclClass));
return false;
});
}
break;
}
case OverrideCheckingAttempt::MismatchedConcurrency: {
SendableCheckContext fromContext(decl->getDeclContext(),
SendableCheck::Explicit);
for (const auto &match : matches) {
auto baseDeclClass = match.Decl->getDeclContext()->getSelfClassDecl();
diags
.diagnose(decl, diag::override_global_actor_isolation_mismatch,
decl->getName())
.limitBehaviorUntilSwiftVersion(DiagnosticBehavior::Warning, 6)
.limitBehaviorIf(fromContext.preconcurrencyBehavior(baseDeclClass));
}
break;
}
case OverrideCheckingAttempt::BaseName:
diags.diagnose(decl, diag::override_multiple_decls_arg_mismatch,
decl->getName());
break;
case OverrideCheckingAttempt::MismatchedOptional:
case OverrideCheckingAttempt::MismatchedTypes:
case OverrideCheckingAttempt::BaseNameWithMismatchedOptional: {
auto isClassContext = decl->getDeclContext()->getSelfClassDecl() != nullptr;
auto diag = diag::method_does_not_override;
if (isa<ConstructorDecl>(decl))
diag = diag::initializer_does_not_override;
else if (isa<SubscriptDecl>(decl))
diag = diag::subscript_does_not_override;
else if (isa<VarDecl>(decl))
diag = diag::property_does_not_override;
diags.diagnose(decl, diag, isClassContext);
break;
}
case OverrideCheckingAttempt::Final:
llvm_unreachable("should have exited already");
}
for (auto match : matches) {
auto matchDecl = match.Decl;
if (attempt <= OverrideCheckingAttempt::MismatchedConcurrency) {
diags.diagnose(matchDecl, diag::overridden_here);
continue;
}
auto diag = diags.diagnose(matchDecl, diag::overridden_near_match_here,
matchDecl);
if (attempt == OverrideCheckingAttempt::BaseName) {
fixDeclarationName(diag, decl, matchDecl->getName());
}
}
}
static bool parameterTypesMatch(const ValueDecl *derivedDecl,
const ValueDecl *baseDecl,
TypeMatchOptions matchMode) {
const ParameterList *derivedParams = nullptr;
const ParameterList *baseParams = nullptr;
if ((isa<AbstractFunctionDecl>(derivedDecl) &&
isa<AbstractFunctionDecl>(baseDecl)) ||
isa<SubscriptDecl>(baseDecl)) {
derivedParams = getParameterList(const_cast<ValueDecl *>(derivedDecl));
baseParams = getParameterList(const_cast<ValueDecl *>(baseDecl));
}
if (!derivedParams && !baseParams) {
return false;
}
if (baseParams->size() != derivedParams->size())
return false;
auto subs = SubstitutionMap::getOverrideSubstitutions(baseDecl, derivedDecl);
for (auto i : indices(baseParams->getArray())) {
auto *baseParam = baseParams->get(i);
auto *derivedParam = derivedParams->get(i);
// Make sure inout-ness and varargs match.
if (baseParam->isInOut() != derivedParam->isInOut() ||
baseParam->isVariadic() != derivedParam->isVariadic()) {
return false;
}
auto baseParamTy = baseParam->getInterfaceType();
baseParamTy = baseParamTy.subst(subs);
auto derivedParamTy = derivedParam->getInterfaceType();
if (baseParam->isInOut() || baseParam->isVariadic()) {
// Inout and vararg parameters must match exactly.
if (baseParamTy->isEqual(derivedParamTy))
continue;
} else {
// Attempt contravariant match.
if (baseParamTy->matchesParameter(derivedParamTy, matchMode))
continue;
// Try once more for a match, using the underlying type of an
// IUO if we're allowing that.
if (baseParam->isImplicitlyUnwrappedOptional() &&
matchMode.contains(TypeMatchFlags::AllowNonOptionalForIUOParam)) {
baseParamTy = baseParamTy->getOptionalObjectType();
if (baseParamTy->matches(derivedParamTy, matchMode))
continue;
}
}
// If there is no match, then we're done.
return false;
}
return true;
}
/// Returns true if `derivedDecl` has a `@differentiable` attribute that
/// overrides one from `baseDecl`.
static bool hasOverridingDifferentiableAttribute(ValueDecl *derivedDecl,
ValueDecl *baseDecl) {
ASTContext &ctx = derivedDecl->getASTContext();
auto &diags = ctx.Diags;
auto *derivedAFD = dyn_cast<AbstractFunctionDecl>(derivedDecl);
auto *baseAFD = dyn_cast<AbstractFunctionDecl>(baseDecl);
if (!derivedAFD || !baseAFD)
return false;
auto derivedDAs =
derivedAFD->getAttrs()
.getAttributes<DifferentiableAttr, /*AllowInvalid*/ true>();
auto baseDAs = baseAFD->getAttrs().getAttributes<DifferentiableAttr>();
// Make sure all the `@differentiable` attributes on `baseDecl` are
// also declared on `derivedDecl`.
bool diagnosed = false;
for (auto *baseDA : baseDAs) {
auto baseParameters = baseDA->getParameterIndices();
auto defined = false;
for (auto derivedDA : derivedDAs) {
auto derivedParameters = derivedDA->getParameterIndices();
// If base and derived parameter indices are both defined, check whether
// base parameter indices are a subset of derived parameter indices.
if (derivedParameters && baseParameters &&
baseParameters->isSubsetOf(derivedParameters)) {
defined = true;
break;
}
// Parameter indices may not be resolved because override matching happens
// before attribute checking for declaration type-checking.
// If parameter indices have not been resolved, avoid emitting diagnostic.
// Assume that attributes are valid.
if (!derivedParameters || !baseParameters) {
defined = true;
break;
}
}
if (defined)
continue;
diagnosed = true;
// Emit an error and fix-it showing the missing base declaration's
// `@differentiable` attribute.
// Omit printing `wrt:` clause if attribute's differentiability parameters
// match inferred differentiability parameters.
auto *inferredParameters =
TypeChecker::inferDifferentiabilityParameters(derivedAFD, nullptr);
bool omitWrtClause =
!baseParameters ||
baseParameters->getNumIndices() == inferredParameters->getNumIndices();
// Get `@differentiable` attribute description.
std::string baseDiffAttrString;
llvm::raw_string_ostream os(baseDiffAttrString);
baseDA->print(os, derivedDecl, omitWrtClause);
os.flush();
diags
.diagnose(derivedDecl,
diag::overriding_decl_missing_differentiable_attr,
baseDiffAttrString)
.fixItInsert(derivedDecl->getStartLoc(), baseDiffAttrString + ' ');
diags.diagnose(baseDecl, diag::overridden_here);
}
// If a diagnostic was produced, return false.
if (diagnosed)
return false;
// If there is no `@differentiable` attribute in `derivedDecl`, then
// overriding is not allowed.
auto *derivedDC = derivedDecl->getDeclContext();
auto *baseDC = baseDecl->getDeclContext();
if (derivedDC->getSelfClassDecl() && baseDC->getSelfClassDecl())
return false;
// Finally, go through all `@differentiable` attributes in `derivedDecl` and
// check if they subsume any of the `@differentiable` attributes in
// `baseDecl`.
for (auto derivedDA : derivedDAs) {
auto derivedParameters = derivedDA->getParameterIndices();
auto overrides = true;
for (auto baseDA : baseDAs) {
auto baseParameters = baseDA->getParameterIndices();
// If the parameter indices of `derivedDA` are a subset of those of
// `baseDA`, then `baseDA` subsumes `derivedDA` and the function is
// marked as overridden.
if (derivedParameters && baseParameters &&
derivedParameters->isSubsetOf(baseParameters)) {
overrides = false;
break;
}
}
if (overrides)
return true;
}
return false;
}
/// Returns true if the given declaration is for the `NSObject.hashValue`
/// property.
static bool isNSObjectHashValue(ValueDecl *baseDecl) {
ASTContext &ctx = baseDecl->getASTContext();
if (auto baseVar = dyn_cast<VarDecl>(baseDecl)) {
if (auto classDecl = baseVar->getDeclContext()->getSelfClassDecl()) {
return baseVar->getName() == ctx.Id_hashValue &&
classDecl->isNSObject();
}
}
return false;
}
/// Returns true if the given declaration is for the `NSObject.hash(into:)`
/// function.
static bool isNSObjectHashMethod(ValueDecl *baseDecl) {
auto baseFunc = dyn_cast<FuncDecl>(baseDecl);
if (!baseFunc)
return false;
if (auto classDecl = baseFunc->getDeclContext()->getSelfClassDecl()) {
ASTContext &ctx = baseDecl->getASTContext();
return baseFunc->getBaseName() == ctx.Id_hash && classDecl->isNSObject();
}
return false;
}
namespace {
/// Class that handles the checking of a particular declaration against
/// superclass entities that it could override.
class OverrideMatcher {
ASTContext &ctx;
ValueDecl *decl;
/// The set of declarations in which we'll look for overridden
/// methods.
SmallVector<NominalTypeDecl *, 2> superContexts;
/// Cached member lookup results.
SmallVector<ValueDecl *, 4> members;
/// The lookup name used to find \c members.
DeclName membersName;
/// The type of the declaration, cached here once it has been computed.
Type cachedDeclType;
/// Whether to ignore missing imports when looking for overridden methods.
bool ignoreMissingImports;
public:
OverrideMatcher(ValueDecl *decl, bool ignoreMissingImports);
/// Returns true when it's possible to perform any override matching.
explicit operator bool() const {
return !superContexts.empty();
}
/// Whether this is an override of a class member.
bool isClassOverride() const {
return decl->getDeclContext()->getSelfClassDecl() != nullptr;
}
/// Whether this is an override of a protocol member.
bool isProtocolOverride() const {
return decl->getDeclContext()->getSelfProtocolDecl() != nullptr;
}
/// Match this declaration against potential members in the superclass,
/// using the heuristics appropriate for the given \c attempt.
SmallVector<OverrideMatch, 2> match(OverrideCheckingAttempt attempt);
/// Check each of the given matches, returning only those that
/// succeeded.
TinyPtrVector<ValueDecl *> checkPotentialOverrides(
SmallVectorImpl<OverrideMatch> &matches,
OverrideCheckingAttempt attempt);
private:
/// We have determined that we have an override of the given \c baseDecl.
///
/// Check that the override itself is valid.
bool checkOverride(ValueDecl *baseDecl,
OverrideCheckingAttempt attempt);
/// Retrieve the type of the declaration, to be used in comparisons.
Type getDeclComparisonType() {
if (!cachedDeclType) {
cachedDeclType = getMemberTypeForComparison(decl);
}
return cachedDeclType;
}
};
}
OverrideMatcher::OverrideMatcher(ValueDecl *decl, bool ignoreMissingImports)
: ctx(decl->getASTContext()), decl(decl),
ignoreMissingImports(ignoreMissingImports) {
// The final step for this constructor is to set up the superclass type,
// without which we will not perform an matching. Early exits therefore imply
// that there is no way we can match this declaration.
// FIXME: Break the cycle here.
if (decl->hasInterfaceType() && decl->isInvalid())
return;
auto *dc = decl->getDeclContext();
if (auto classDecl = dc->getSelfClassDecl()) {
if (auto superclassDecl = classDecl->getSuperclassDecl())
superContexts.push_back(superclassDecl);
} else if (auto protocol = dyn_cast<ProtocolDecl>(dc)) {
auto inheritedProtocols = protocol->getInheritedProtocols();
superContexts.insert(superContexts.end(), inheritedProtocols.begin(),
inheritedProtocols.end());
}
}
SmallVector<OverrideMatch, 2> OverrideMatcher::match(
OverrideCheckingAttempt attempt) {
// If there's no matching we can do, fail.
if (!*this) return { };
auto dc = decl->getDeclContext();
// Determine what name we should look for.
DeclName name;
switch (attempt) {
case OverrideCheckingAttempt::PerfectMatch:
case OverrideCheckingAttempt::MismatchedSendability:
case OverrideCheckingAttempt::MismatchedConcurrency:
case OverrideCheckingAttempt::MismatchedOptional:
case OverrideCheckingAttempt::MismatchedTypes:
name = decl->getName();
break;
case OverrideCheckingAttempt::BaseName:
case OverrideCheckingAttempt::BaseNameWithMismatchedOptional:
name = decl->getBaseName();
break;
case OverrideCheckingAttempt::Final:
// Give up.
return { };
}
// If we don't have members available yet, or we looked them up based on a
// different name, look them up now.
if (members.empty() || name != membersName) {
membersName = name;
members.clear();
// FIXME: This suggests we need to use TypeChecker's high-level lookup
// entrypoints. But first we need one that supports additive qualified
// lookup.
for (auto *ctx : superContexts) {
ctx->synthesizeSemanticMembersIfNeeded(membersName);
}
auto lookupOptions = NL_QualifiedDefault;
if (ignoreMissingImports)
lookupOptions |= NL_IgnoreMissingImports;
dc->lookupQualified(superContexts, DeclNameRef(membersName), decl->getLoc(),
lookupOptions, members);
}
// Check each member we found.
SmallVector<OverrideMatch, 2> matches;
for (auto parentDecl : members) {
// Check whether there are any obvious reasons why the two given
// declarations do not have an overriding relationship.
if (!areOverrideCompatibleSimple(decl, parentDecl))
continue;
// Check whether the derived declaration has a `@differentiable` attribute
// that overrides one from the parent declaration.
if (hasOverridingDifferentiableAttribute(decl, parentDecl))
continue;
auto parentMethod = dyn_cast<AbstractFunctionDecl>(parentDecl);
auto parentStorage = dyn_cast<AbstractStorageDecl>(parentDecl);
assert(parentMethod || parentStorage);
(void)parentMethod;
(void)parentStorage;
// If the generic requirements don't match, don't try anything else below,
// because it will compute an invalid interface type by applying malformed
// substitutions.
if (isClassOverride()) {
using Direction = ASTContext::OverrideGenericSignatureReqCheck;
if (decl->getAsGenericContext()) {
if (!ctx.overrideGenericSignatureReqsSatisfied(
parentDecl, decl, Direction::DerivedReqSatisfiedByBase)) {
continue;
}
}
}
// Check whether the types are identical.