forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeCheckDeclOverride.cpp
1843 lines (1586 loc) · 67.4 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 "TypeChecker.h"
#include "CodeSynthesis.h"
#include "MiscDiagnostics.h"
#include "TypeCheckAvailability.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Availability.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeCheckRequests.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);
if (fnType->getExtInfo() != extInfo)
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(ASTContext &ctx, ValueDecl *member,
ValueDecl *derivedDecl) {
auto *method = dyn_cast<AbstractFunctionDecl>(member);
ConstructorDecl *ctor = nullptr;
if (method)
ctor = dyn_cast<ConstructorDecl>(method);
auto abstractStorage = dyn_cast<AbstractStorageDecl>(member);
assert((method || abstractStorage) && "Not a method or abstractStorage?");
SubscriptDecl *subscript = dyn_cast_or_null<SubscriptDecl>(abstractStorage);
if (!member->hasInterfaceType()) {
auto lazyResolver = ctx.getLazyResolver();
assert(lazyResolver && "Need to resolve interface type");
lazyResolver->resolveDeclSignature(member);
}
auto memberType = member->getInterfaceType();
if (derivedDecl) {
if (!derivedDecl->hasInterfaceType()) {
auto lazyResolver = ctx.getLazyResolver();
assert(lazyResolver && "Need to resolve interface type");
lazyResolver->resolveDeclSignature(derivedDecl);
}
auto *dc = derivedDecl->getDeclContext();
auto owningType = dc->getDeclaredInterfaceType();
assert(owningType);
memberType = owningType->adjustSuperclassMemberDeclType(member, derivedDecl,
memberType);
if (memberType->hasError())
return 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>();
memberType = FunctionType::get(funcTy->getParams(), funcTy->getResult());
} 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;
}
bool swift::isOverrideBasedOnType(ValueDecl *decl, Type declTy,
ValueDecl *parentDecl, Type parentDeclTy) {
auto *genericSig =
decl->getInnermostDeclContext()->getGenericSignatureOfContext();
auto canDeclTy = declTy->getCanonicalType(genericSig);
auto canParentDeclTy = parentDeclTy->getCanonicalType(genericSig);
auto declIUOAttr =
decl->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
auto parentDeclIUOAttr =
parentDecl->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
if (declIUOAttr != parentDeclIUOAttr)
return false;
// 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)->getFailability() !=
cast<ConstructorDecl>(parentDecl)->getFailability())
return false;
}
auto fnType1 = declTy->castTo<AnyFunctionType>();
auto fnType2 = parentDeclTy->castTo<AnyFunctionType>();
return AnyFunctionType::equalParams(fnType1->getParams(),
fnType2->getParams());
}
return canDeclTy == canParentDeclTy;
}
/// 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->getFullName().getArgumentNames().size() !=
parentDecl->getFullName().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;
}
// The declarations must be of the same kind.
if (decl->getKind() != parentDecl->getKind())
return false;
// Ignore invalid parent declarations.
// FIXME: Do we really need this?
if (parentDecl->isInvalid())
return false;
if (auto func = dyn_cast<FuncDecl>(decl)) {
// Specific checking for methods.
auto parentFunc = cast<FuncDecl>(parentDecl);
if (func->isStatic() != parentFunc->isStatic())
return false;
if (func->isGeneric() != parentFunc->isGeneric())
return false;
} else if (auto ctor = dyn_cast<ConstructorDecl>(decl)) {
auto parentCtor = cast<ConstructorDecl>(parentDecl);
if (ctor->isGeneric() != parentCtor->isGeneric())
return false;
// Factory initializers cannot be overridden.
if (parentCtor->isFactoryInit())
return false;
} else if (auto var = dyn_cast<VarDecl>(decl)) {
auto parentVar = cast<VarDecl>(parentDecl);
if (var->isStatic() != parentVar->isStatic())
return false;
} else if (auto subscript = dyn_cast<SubscriptDecl>(decl)) {
auto parentSubscript = cast<SubscriptDecl>(parentDecl);
if (subscript->isGeneric() != parentSubscript->isGeneric())
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->getType();
Type parentParamTy = parentDecl->getType();
if (!paramTy || !parentParamTy)
return;
TypeLoc TL = decl->getTypeLoc();
if (!TL.getTypeRepr())
return;
bool paramIsOptional = (bool) paramTy->getOptionalObjectType();
bool parentIsOptional = (bool) parentParamTy->getOptionalObjectType();
if (paramIsOptional == parentIsOptional)
return;
if (!paramIsOptional) {
if (parentDecl->getAttrs()
.hasAttribute<ImplicitlyUnwrappedOptionalAttr>())
if (!treatIUOResultAsError)
return;
emittedError = true;
auto diag = diags.diagnose(decl->getStartLoc(),
diag::override_optional_mismatch,
member->getDescriptiveKind(),
isa<SubscriptDecl>(member),
parentParamTy, paramTy);
if (TL.getTypeRepr()->isSimple()) {
diag.fixItInsertAfter(TL.getSourceRange().End, "?");
} else {
diag.fixItInsert(TL.getSourceRange().Start, "(");
diag.fixItInsertAfter(TL.getSourceRange().End, ")?");
}
return;
}
if (!decl->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>())
return;
// Allow silencing this warning using parens.
if (TL.getType()->hasParenSugar())
return;
diags.diagnose(decl->getStartLoc(), diag::override_unnecessary_IUO,
member->getDescriptiveKind(), parentParamTy, paramTy)
.highlight(TL.getSourceRange());
auto sugaredForm =
dyn_cast<ImplicitlyUnwrappedOptionalTypeRepr>(TL.getTypeRepr());
if (sugaredForm) {
diags.diagnose(sugaredForm->getExclamationLoc(),
diag::override_unnecessary_IUO_remove)
.fixItRemove(sugaredForm->getExclamationLoc());
}
diags.diagnose(TL.getSourceRange().Start,
diag::override_unnecessary_IUO_silence)
.fixItInsert(TL.getSourceRange().Start, "(")
.fixItInsertAfter(TL.getSourceRange().End, ")");
};
// 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->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>())
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 (resultTy->hasParenSugar())
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;
DiagnosticTransaction tentativeDiags(diags);
{
Type baseTy = base->getInterfaceType();
if (baseTy->hasError())
return false;
Optional<InFlightDiagnostic> activeDiag;
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::composeInput(ctx,
baseTy->getAs<AnyFunctionType>()
->getParams(),
false);
auto diagKind = diag::override_type_mismatch_with_fixits_init;
unsigned numArgs = baseInit->getParameters()->size();
activeDiag.emplace(diags.diagnose(decl, diagKind,
/*plural*/std::min(numArgs, 2U),
argTy));
} else {
if (isa<AbstractFunctionDecl>(base))
baseTy = baseTy->getAs<AnyFunctionType>()->getResult();
activeDiag.emplace(
diags.diagnose(decl,
diag::override_type_mismatch_with_fixits,
base->getDescriptiveKind(), baseTy));
}
if (fixItOverrideDeclarationTypes(*activeDiag, decl, base))
return true;
}
// There weren't any fixes we knew how to make. Drop this diagnostic.
tentativeDiags.abort();
return false;
}
namespace {
enum class OverrideCheckingAttempt {
PerfectMatch,
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->getFullName());
break;
case OverrideCheckingAttempt::BaseName:
diags.diagnose(decl, diag::override_multiple_decls_arg_mismatch,
decl->getFullName());
break;
case OverrideCheckingAttempt::MismatchedOptional:
case OverrideCheckingAttempt::MismatchedTypes:
case OverrideCheckingAttempt::BaseNameWithMismatchedOptional:
if (isa<ConstructorDecl>(decl))
diags.diagnose(decl, diag::initializer_does_not_override);
else if (isa<SubscriptDecl>(decl))
diags.diagnose(decl, diag::subscript_does_not_override);
else if (isa<VarDecl>(decl))
diags.diagnose(decl, diag::property_does_not_override);
else
diags.diagnose(decl, diag::method_does_not_override);
break;
case OverrideCheckingAttempt::Final:
llvm_unreachable("should have exited already");
}
for (auto match : matches) {
auto matchDecl = match.Decl;
if (attempt == OverrideCheckingAttempt::PerfectMatch) {
diags.diagnose(matchDecl, diag::overridden_here);
continue;
}
auto diag = diags.diagnose(matchDecl, diag::overridden_near_match_here,
matchDecl->getDescriptiveKind(),
matchDecl->getFullName());
if (attempt == OverrideCheckingAttempt::BaseName) {
fixDeclarationName(diag, cast<AbstractFunctionDecl>(decl),
matchDecl->getFullName());
}
}
}
static bool parameterTypesMatch(const ValueDecl *derivedDecl,
const ValueDecl *baseDecl,
TypeMatchOptions matchMode) {
const ParameterList *derivedParams;
const ParameterList *baseParams;
if (auto *derived = dyn_cast<AbstractFunctionDecl>(derivedDecl)) {
auto *base = dyn_cast<AbstractFunctionDecl>(baseDecl);
if (!base)
return false;
baseParams = base->getParameters();
derivedParams = derived->getParameters();
} else {
auto *base = dyn_cast<SubscriptDecl>(baseDecl);
if (!base)
return false;
baseParams = base->getIndices();
derivedParams = cast<SubscriptDecl>(derivedDecl)->getIndices();
}
if (baseParams->size() != derivedParams->size())
return false;
auto subs = SubstitutionMap::getOverrideSubstitutions(baseDecl, derivedDecl,
/*derivedSubs=*/None);
for (auto i : indices(baseParams->getArray())) {
auto baseItfTy = baseParams->get(i)->getInterfaceType();
auto baseParamTy =
baseDecl->getAsGenericContext()->mapTypeIntoContext(baseItfTy);
baseParamTy = baseParamTy.subst(subs);
auto derivedParamTy = derivedParams->get(i)->getInterfaceType();
// 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 (baseParams->get(i)
->getAttrs()
.hasAttribute<ImplicitlyUnwrappedOptionalAttr>() &&
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;
}
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.
DirectlyReferencedTypeDecls 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;
public:
OverrideMatcher(ValueDecl *decl);
/// 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(ctx, decl);
}
return cachedDeclType;
}
/// Adjust the interface of the given declaration, which is found in
/// a supertype of the given type.
Type getSuperMemberDeclType(ValueDecl *baseDecl) const {
auto selfType = decl->getDeclContext()->getSelfInterfaceType();
if (selfType->getClassOrBoundGenericClass()) {
selfType = selfType->getSuperclass();
assert(selfType && "No superclass type?");
}
return selfType->adjustSuperclassMemberDeclType(
baseDecl, decl, baseDecl->getInterfaceType());
}
};
}
OverrideMatcher::OverrideMatcher(ValueDecl *decl)
: ctx(decl->getASTContext()), decl(decl) {
// 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.
if (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::MismatchedOptional:
case OverrideCheckingAttempt::MismatchedTypes:
name = decl->getFullName();
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();
dc->lookupQualified(superContexts, membersName,
NL_QualifiedDefault, 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;
auto parentMethod = dyn_cast<AbstractFunctionDecl>(parentDecl);
auto parentStorage = dyn_cast<AbstractStorageDecl>(parentDecl);
assert(parentMethod || parentStorage);
(void)parentMethod;
(void)parentStorage;
// Check whether the types are identical.
auto parentDeclTy = getMemberTypeForComparison(ctx, parentDecl, decl);
if (parentDeclTy->hasError())
continue;
Type declTy = getDeclComparisonType();
if (isOverrideBasedOnType(decl, declTy, parentDecl, parentDeclTy)) {
matches.push_back({parentDecl, true});
continue;
}
// If this is a property, we accept the match and then reject it below
// if the types don't line up, since you can't overload properties based
// on types.
if ((isa<VarDecl>(parentDecl) && isClassOverride()) ||
attempt == OverrideCheckingAttempt::MismatchedTypes) {
matches.push_back({parentDecl, false});
continue;
}
// For a protocol override, we require an exact match.
if (isProtocolOverride()) {
continue;
}
// Failing that, check for subtyping.
TypeMatchOptions matchMode = TypeMatchFlags::AllowOverride;
if (attempt == OverrideCheckingAttempt::MismatchedOptional ||
attempt == OverrideCheckingAttempt::BaseNameWithMismatchedOptional){
matchMode |= TypeMatchFlags::AllowTopLevelOptionalMismatch;
} else if (parentDecl->isObjC()) {
matchMode |= TypeMatchFlags::AllowNonOptionalForIUOParam;
matchMode |= TypeMatchFlags::IgnoreNonEscapingForOptionalFunctionParam;
}
auto declFnTy = getDeclComparisonType()->getAs<AnyFunctionType>();
auto parentDeclFnTy = parentDeclTy->getAs<AnyFunctionType>();
if (declFnTy && parentDeclFnTy) {
auto paramsAndResultMatch = [=]() -> bool {
return parameterTypesMatch(decl, parentDecl, matchMode) &&
declFnTy->getResult()->matches(parentDeclFnTy->getResult(),
matchMode);
};
if (declFnTy->matchesFunctionType(parentDeclFnTy, matchMode,
paramsAndResultMatch)) {
matches.push_back({parentDecl, false});
continue;
}
} else if (getDeclComparisonType()->matches(parentDeclTy, matchMode)) {
matches.push_back({parentDecl, false});
continue;
}
}
// If we have more than one match, and any of them was exact, remove all
// non-exact matches.
if (matches.size() > 1) {
bool hadExactMatch = std::find_if(matches.begin(), matches.end(),
[](const OverrideMatch &match) {
return match.IsExact;
}) != matches.end();
if (hadExactMatch) {
matches.erase(std::remove_if(matches.begin(), matches.end(),
[&](const OverrideMatch &match) {
return !match.IsExact;
}),
matches.end());
}
}
return matches;
}
bool OverrideMatcher::checkOverride(ValueDecl *baseDecl,
OverrideCheckingAttempt attempt) {
auto &diags = ctx.Diags;
auto baseTy = getMemberTypeForComparison(ctx, baseDecl, decl);
bool emittedMatchError = false;
// If the name of our match differs from the name we were looking for,
// complain.
if (decl->getFullName() != baseDecl->getFullName()) {
auto diag = diags.diagnose(decl, diag::override_argument_name_mismatch,
isa<ConstructorDecl>(decl),
decl->getFullName(),
baseDecl->getFullName());
fixDeclarationName(diag, cast<AbstractFunctionDecl>(decl),
baseDecl->getFullName());
emittedMatchError = true;
}
// If we have an explicit ownership modifier and our parent doesn't,
// complain.
auto parentAttr =
baseDecl->getAttrs().getAttribute<ReferenceOwnershipAttr>();
if (auto ownershipAttr =
decl->getAttrs().getAttribute<ReferenceOwnershipAttr>()) {
ReferenceOwnership parentOwnership;
if (parentAttr)
parentOwnership = parentAttr->get();
else
parentOwnership = ReferenceOwnership::Strong;
if (parentOwnership != ownershipAttr->get()) {
diags.diagnose(decl, diag::override_ownership_mismatch,
parentOwnership, ownershipAttr->get());
diags.diagnose(baseDecl, diag::overridden_here);
}
}
// If a super method returns Self, and the subclass overrides it to
// instead return the subclass type, complain.
// This case gets this far because the type matching above specifically
// strips out dynamic self via replaceCovariantResultType(), and that
// is helpful in several cases - just not this one.
auto dc = decl->getDeclContext();
auto classDecl = dc->getSelfClassDecl();
if (decl->getASTContext().isSwiftVersionAtLeast(5) &&
baseDecl->getInterfaceType()->hasDynamicSelfType() &&
!decl->getInterfaceType()->hasDynamicSelfType() &&
!classDecl->isFinal()) {
diags.diagnose(decl, diag::override_dynamic_self_mismatch);
diags.diagnose(baseDecl, diag::overridden_here);
}
bool isAccessor = isa<AccessorDecl>(decl);
// Check that the override has the required access level.
// Overrides have to be at least as accessible as what they
// override, except:
// - they don't have to be more accessible than their class and
// - a final method may be public instead of open.
// Also diagnose attempts to override a non-open method from outside its
// defining module. This is not required for constructors, which are
// never really "overridden" in the intended sense here, because of
// course derived classes will change how the class is initialized.
bool baseHasOpenAccess = baseDecl->hasOpenAccess(dc);
if (!isAccessor &&
!baseHasOpenAccess &&
baseDecl->getModuleContext() != decl->getModuleContext() &&
!isa<ConstructorDecl>(decl) &&
!isa<ProtocolDecl>(decl->getDeclContext())) {
diags.diagnose(decl, diag::override_of_non_open,
decl->getDescriptiveKind());
} else if (baseHasOpenAccess &&
classDecl->hasOpenAccess(dc) &&
decl->getFormalAccess() != AccessLevel::Open &&
!decl->isFinal()) {
{
auto diag = diags.diagnose(decl, diag::override_not_accessible,
/*setter*/false,
decl->getDescriptiveKind(),
/*fromOverridden*/true);
fixItAccess(diag, decl, AccessLevel::Open);
}
diags.diagnose(baseDecl, diag::overridden_here);
} else if (!isa<ConstructorDecl>(decl) &&
!isa<ProtocolDecl>(decl->getDeclContext())) {
auto matchAccessScope =
baseDecl->getFormalAccessScope(dc);
auto classAccessScope =
classDecl->getFormalAccessScope(dc);
auto requiredAccessScope =
matchAccessScope.intersectWith(classAccessScope);
auto scopeDC = requiredAccessScope->getDeclContext();
bool shouldDiagnose = !decl->isAccessibleFrom(scopeDC);
bool shouldDiagnoseSetter = false;
if (!shouldDiagnose && baseDecl->isSettable(dc)){
auto matchASD = cast<AbstractStorageDecl>(baseDecl);
if (matchASD->isSetterAccessibleFrom(dc)) {
auto matchSetterAccessScope = matchASD->getSetter()
->getFormalAccessScope(dc);
auto requiredSetterAccessScope =
matchSetterAccessScope.intersectWith(classAccessScope);
auto setterScopeDC = requiredSetterAccessScope->getDeclContext();
const auto *ASD = cast<AbstractStorageDecl>(decl);
shouldDiagnoseSetter =
ASD->isSettable(setterScopeDC) &&
!ASD->isSetterAccessibleFrom(setterScopeDC);
}
}
if (shouldDiagnose || shouldDiagnoseSetter) {
bool overriddenForcesAccess =
(requiredAccessScope->hasEqualDeclContextWith(matchAccessScope) &&
!baseHasOpenAccess);
AccessLevel requiredAccess =
requiredAccessScope->requiredAccessForDiagnostics();
{
auto diag = diags.diagnose(decl, diag::override_not_accessible,
shouldDiagnoseSetter,
decl->getDescriptiveKind(),
overriddenForcesAccess);
fixItAccess(diag, decl, requiredAccess, shouldDiagnoseSetter);
}
diags.diagnose(baseDecl, diag::overridden_here);
}
}
bool mayHaveMismatchedOptionals =
(attempt == OverrideCheckingAttempt::MismatchedOptional ||
attempt == OverrideCheckingAttempt::BaseNameWithMismatchedOptional);
auto declIUOAttr =
decl->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
auto matchDeclIUOAttr =
baseDecl->getAttrs().hasAttribute<ImplicitlyUnwrappedOptionalAttr>();
// If this is an exact type match, we're successful!
Type declTy = getDeclComparisonType();
Type owningTy = dc->getDeclaredInterfaceType();
if (declIUOAttr == matchDeclIUOAttr && declTy->isEqual(baseTy)) {
// Nothing to do.
} else if (auto method = dyn_cast<AbstractFunctionDecl>(decl)) {
if (attempt == OverrideCheckingAttempt::MismatchedTypes) {
auto diagKind = diag::method_does_not_override;
if (isa<ConstructorDecl>(method))
diagKind = diag::initializer_does_not_override;
diags.diagnose(decl, diagKind);
noteFixableMismatchedTypes(decl, baseDecl);
diags.diagnose(baseDecl, diag::overridden_near_match_here,
baseDecl->getDescriptiveKind(),
baseDecl->getFullName());
emittedMatchError = true;
} else if (!isa<AccessorDecl>(method) &&
(baseDecl->isObjC() || mayHaveMismatchedOptionals)) {
// Private migration help for overrides of Objective-C methods.
TypeLoc resultTL;
if (auto *methodAsFunc = dyn_cast<FuncDecl>(method))
resultTL = methodAsFunc->getBodyResultTypeLoc();
emittedMatchError |= diagnoseMismatchedOptionals(
method, method->getParameters(), resultTL, baseDecl,
cast<AbstractFunctionDecl>(baseDecl)->getParameters(),
owningTy, mayHaveMismatchedOptionals);
}
} else if (auto subscript = dyn_cast<SubscriptDecl>(decl)) {
// Otherwise, if this is a subscript, validate that covariance is ok.
// If the parent is non-mutable, it's okay to be covariant.
auto parentSubscript = cast<SubscriptDecl>(baseDecl);
if (parentSubscript->getSetter()) {
diags.diagnose(subscript, diag::override_mutable_covariant_subscript,
declTy, baseTy);
diags.diagnose(baseDecl, diag::subscript_override_here);
return true;
}
if (attempt == OverrideCheckingAttempt::MismatchedTypes) {
diags.diagnose(decl, diag::subscript_does_not_override);
noteFixableMismatchedTypes(decl, baseDecl);
diags.diagnose(baseDecl, diag::overridden_near_match_here,
baseDecl->getDescriptiveKind(),
baseDecl->getFullName());
emittedMatchError = true;
} else if (mayHaveMismatchedOptionals) {
emittedMatchError |= diagnoseMismatchedOptionals(
subscript, subscript->getIndices(),
subscript->getElementTypeLoc(), baseDecl,
cast<SubscriptDecl>(baseDecl)->getIndices(), owningTy,
mayHaveMismatchedOptionals);
}
} else if (auto property = dyn_cast<VarDecl>(decl)) {
auto propertyTy = property->getInterfaceType();
auto parentPropertyTy = getSuperMemberDeclType(baseDecl);
CanType parentPropertyCanTy =
parentPropertyTy->getCanonicalType(
decl->getInnermostDeclContext()->getGenericSignatureOfContext());
if (!propertyTy->matches(parentPropertyCanTy,
TypeMatchFlags::AllowOverride)) {
diags.diagnose(property, diag::override_property_type_mismatch,
property->getName(), propertyTy, parentPropertyTy);
noteFixableMismatchedTypes(decl, baseDecl);
diags.diagnose(baseDecl, diag::property_override_here);
return true;
}
// Differing only in Optional vs. ImplicitlyUnwrappedOptional is fine.
bool IsSilentDifference = false;
if (auto propertyTyNoOptional = propertyTy->getOptionalObjectType())
if (auto parentPropertyTyNoOptional =
parentPropertyTy->getOptionalObjectType())
if (propertyTyNoOptional->isEqual(parentPropertyTyNoOptional))
IsSilentDifference = true;
// The overridden property must not be mutable.
if (cast<AbstractStorageDecl>(baseDecl)->getSetter() &&
!IsSilentDifference) {
diags.diagnose(property, diag::override_mutable_covariant_property,
property->getName(), parentPropertyTy, propertyTy);
diags.diagnose(baseDecl, diag::property_override_here);
return true;
}
}
if (emittedMatchError)
return true;
// Catch-all to make sure we don't silently accept something we shouldn't.
if (attempt != OverrideCheckingAttempt::PerfectMatch) {
OverrideMatch match{decl, /*isExact=*/false};
diagnoseGeneralOverrideFailure(decl, match, attempt);
}