forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeCheckAttr.cpp
2133 lines (1838 loc) · 74 KB
/
TypeCheckAttr.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
//===--- TypeCheckAttr.cpp - Type Checking for Attributes -----------------===//
//
// 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 attributes.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "MiscDiagnostics.h"
#include "TypeCheckType.h"
#include "swift/AST/GenericSignatureBuilder.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "swift/Parse/Lexer.h"
#include "llvm/Support/Debug.h"
using namespace swift;
namespace {
/// This emits a diagnostic with a fixit to remove the attribute.
template<typename ...ArgTypes>
void diagnoseAndRemoveAttr(TypeChecker &TC, Decl *D, DeclAttribute *attr,
ArgTypes &&...Args) {
assert(!D->hasClangNode() && "Clang imported propagated a bogus attribute");
if (!D->hasClangNode()) {
SourceLoc loc = attr->getLocation();
assert(loc.isValid() && "Diagnosing attribute with invalid location");
if (loc.isInvalid()) {
loc = D->getLoc();
}
if (loc.isValid()) {
TC.diagnose(loc, std::forward<ArgTypes>(Args)...)
.fixItRemove(attr->getRangeWithAt());
}
}
attr->setInvalid();
}
/// This visits each attribute on a decl early, before the majority of type
/// checking has been performed for the decl. The visitor should return true if
/// the attribute is invalid and should be marked as such.
class AttributeEarlyChecker : public AttributeVisitor<AttributeEarlyChecker> {
TypeChecker &TC;
Decl *D;
public:
AttributeEarlyChecker(TypeChecker &TC, Decl *D) : TC(TC), D(D) {}
/// This emits a diagnostic with a fixit to remove the attribute.
template<typename ...ArgTypes>
void diagnoseAndRemoveAttr(DeclAttribute *attr, ArgTypes &&...Args) {
::diagnoseAndRemoveAttr(TC, D, attr, std::forward<ArgTypes>(Args)...);
}
/// Deleting this ensures that all attributes are covered by the visitor
/// below.
bool visitDeclAttribute(DeclAttribute *A) = delete;
#define IGNORED_ATTR(X) void visit##X##Attr(X##Attr *) {}
IGNORED_ATTR(Available)
IGNORED_ATTR(HasInitialValue)
IGNORED_ATTR(CDecl)
IGNORED_ATTR(ClangImporterSynthesizedType)
IGNORED_ATTR(Convenience)
IGNORED_ATTR(DiscardableResult)
IGNORED_ATTR(DynamicMemberLookup)
IGNORED_ATTR(Effects)
IGNORED_ATTR(Exported)
IGNORED_ATTR(FixedLayout)
IGNORED_ATTR(ForbidSerializingReference)
IGNORED_ATTR(Frozen)
IGNORED_ATTR(Implements)
IGNORED_ATTR(ImplicitlyUnwrappedOptional)
IGNORED_ATTR(Infix)
IGNORED_ATTR(Inlinable)
IGNORED_ATTR(Inline)
IGNORED_ATTR(NonObjC)
IGNORED_ATTR(NSApplicationMain)
IGNORED_ATTR(NSCopying)
IGNORED_ATTR(ObjC)
IGNORED_ATTR(ObjCBridged)
IGNORED_ATTR(ObjCNonLazyRealization)
IGNORED_ATTR(ObjCRuntimeName)
IGNORED_ATTR(Optimize)
IGNORED_ATTR(Optional)
IGNORED_ATTR(Postfix)
IGNORED_ATTR(Prefix)
IGNORED_ATTR(RawDocComment)
IGNORED_ATTR(Required)
IGNORED_ATTR(RequiresStoredPropertyInits)
IGNORED_ATTR(RestatedObjCConformance)
IGNORED_ATTR(Rethrows)
IGNORED_ATTR(Semantics)
IGNORED_ATTR(ShowInInterface)
IGNORED_ATTR(SILGenName)
IGNORED_ATTR(Specialize)
IGNORED_ATTR(StaticInitializeObjCMetadata)
IGNORED_ATTR(SwiftNativeObjCRuntimeBase)
IGNORED_ATTR(SynthesizedProtocol)
IGNORED_ATTR(Testable)
IGNORED_ATTR(UIApplicationMain)
IGNORED_ATTR(UnsafeNoObjCTaggedPointer)
IGNORED_ATTR(UsableFromInline)
IGNORED_ATTR(WeakLinked)
#undef IGNORED_ATTR
// @noreturn has been replaced with a 'Never' return type.
void visitNoReturnAttr(NoReturnAttr *attr) {
if (auto FD = dyn_cast<FuncDecl>(D)) {
auto &SM = TC.Context.SourceMgr;
auto diag = TC.diagnose(attr->getLocation(),
diag::noreturn_not_supported);
auto range = attr->getRangeWithAt();
if (range.isValid())
range.End = range.End.getAdvancedLoc(1);
diag.fixItRemove(range);
auto *last = FD->getParameters();
// If the declaration already has a result type, we're going
// to change it to 'Never'.
bool hadResultType = false;
bool isEndOfLine = false;
SourceLoc resultLoc;
if (FD->getBodyResultTypeLoc().hasLocation()) {
const auto &typeLoc = FD->getBodyResultTypeLoc();
hadResultType = true;
resultLoc = typeLoc.getSourceRange().Start;
// If the function 'throws', insert the result type after the
// 'throws'.
} else {
if (FD->getThrowsLoc().isValid()) {
resultLoc = FD->getThrowsLoc();
// Otherwise, insert the result type after the final parameter
// list.
} else if (last->getRParenLoc().isValid()) {
resultLoc = last->getRParenLoc();
}
if (Lexer::getLocForEndOfToken(SM, resultLoc).getAdvancedLoc(1) ==
Lexer::getLocForEndOfLine(SM, resultLoc))
isEndOfLine = true;
resultLoc = Lexer::getLocForEndOfToken(SM, resultLoc);
}
if (hadResultType) {
diag.fixItReplace(resultLoc, "Never");
} else {
std::string fix = " -> Never";
if (!isEndOfLine)
fix = fix + " ";
diag.fixItInsert(resultLoc, fix);
}
auto neverType = TC.Context.getNeverType();
if (neverType)
FD->getBodyResultTypeLoc() = TypeLoc::withoutLoc(neverType);
}
}
void visitAlignmentAttr(AlignmentAttr *attr) {
// Alignment must be a power of two.
auto value = attr->getValue();
if (value == 0 || (value & (value - 1)) != 0)
TC.diagnose(attr->getLocation(), diag::alignment_not_power_of_two);
}
void visitTransparentAttr(TransparentAttr *attr);
void visitMutationAttr(DeclAttribute *attr);
void visitMutatingAttr(MutatingAttr *attr) { visitMutationAttr(attr); }
void visitNonMutatingAttr(NonMutatingAttr *attr) { visitMutationAttr(attr); }
void visitConsumingAttr(ConsumingAttr *attr) { visitMutationAttr(attr); }
void visitDynamicAttr(DynamicAttr *attr);
void visitReferenceOwnershipAttr(ReferenceOwnershipAttr *attr) {
TC.checkReferenceOwnershipAttr(cast<VarDecl>(D), attr);
}
void visitFinalAttr(FinalAttr *attr) {
// Reject combining 'final' with 'open'.
if (auto accessAttr = D->getAttrs().getAttribute<AccessControlAttr>()) {
if (accessAttr->getAccess() == AccessLevel::Open) {
TC.diagnose(attr->getLocation(), diag::open_decl_cannot_be_final,
D->getDescriptiveKind());
return;
}
}
if (isa<ClassDecl>(D))
return;
// 'final' only makes sense in the context of a class declaration.
// Reject it on global functions, protocols, structs, enums, etc.
if (!D->getDeclContext()->getSelfClassDecl()) {
if (TC.Context.isSwiftVersion3() &&
D->getDeclContext()->getExtendedProtocolDecl())
TC.diagnose(attr->getLocation(),
diag::protocol_extension_cannot_be_final)
.fixItRemove(attr->getRange());
else
TC.diagnose(attr->getLocation(), diag::member_cannot_be_final)
.fixItRemove(attr->getRange());
// Remove the attribute so child declarations are not flagged as final
// and duplicate the error message.
D->getAttrs().removeAttribute(attr);
return;
}
}
void visitIndirectAttr(IndirectAttr *attr) {
if (auto caseDecl = dyn_cast<EnumElementDecl>(D)) {
// An indirect case should have a payload.
if (!caseDecl->hasAssociatedValues())
TC.diagnose(attr->getLocation(),
diag::indirect_case_without_payload, caseDecl->getName());
// If the enum is already indirect, its cases don't need to be.
else if (caseDecl->getParentEnum()->getAttrs()
.hasAttribute<IndirectAttr>())
TC.diagnose(attr->getLocation(),
diag::indirect_case_in_indirect_enum);
}
}
void visitWarnUnqualifiedAccessAttr(WarnUnqualifiedAccessAttr *attr) {
if (!D->getDeclContext()->isTypeContext()) {
diagnoseAndRemoveAttr(attr, diag::attr_methods_only, attr);
}
}
void visitIBActionAttr(IBActionAttr *attr);
void visitLazyAttr(LazyAttr *attr);
void visitIBDesignableAttr(IBDesignableAttr *attr);
void visitIBInspectableAttr(IBInspectableAttr *attr);
void visitGKInspectableAttr(GKInspectableAttr *attr);
void visitIBOutletAttr(IBOutletAttr *attr);
void visitLLDBDebuggerFunctionAttr(LLDBDebuggerFunctionAttr *attr);
void visitNSManagedAttr(NSManagedAttr *attr);
void visitOverrideAttr(OverrideAttr *attr);
void visitNonOverrideAttr(NonOverrideAttr *attr);
void visitAccessControlAttr(AccessControlAttr *attr);
void visitSetterAccessAttr(SetterAccessAttr *attr);
bool visitAbstractAccessControlAttr(AbstractAccessControlAttr *attr);
void visitSILStoredAttr(SILStoredAttr *attr);
void visitObjCMembersAttr(ObjCMembersAttr *attr);
};
} // end anonymous namespace
void AttributeEarlyChecker::visitTransparentAttr(TransparentAttr *attr) {
DeclContext *Ctx = D->getDeclContext();
// Protocol declarations cannot be transparent.
if (isa<ProtocolDecl>(Ctx))
diagnoseAndRemoveAttr(attr, diag::transparent_in_protocols_not_supported);
// Class declarations cannot be transparent.
if (isa<ClassDecl>(Ctx)) {
// @transparent is always ok on implicitly generated accessors: they can
// be dispatched (even in classes) when the references are within the
// class themself.
if (!(isa<AccessorDecl>(D) && D->isImplicit()))
diagnoseAndRemoveAttr(attr, diag::transparent_in_classes_not_supported);
}
if (auto *VD = dyn_cast<VarDecl>(D)) {
// Stored properties and variables can't be transparent.
if (VD->hasStorage())
diagnoseAndRemoveAttr(attr, diag::attribute_invalid_on_stored_property,
attr);
}
}
void AttributeEarlyChecker::visitMutationAttr(DeclAttribute *attr) {
FuncDecl *FD = cast<FuncDecl>(D);
SelfAccessKind attrModifier;
switch (attr->getKind()) {
case DeclAttrKind::DAK_Consuming:
attrModifier = SelfAccessKind::__Consuming;
break;
case DeclAttrKind::DAK_Mutating:
attrModifier = SelfAccessKind::Mutating;
break;
case DeclAttrKind::DAK_NonMutating:
attrModifier = SelfAccessKind::NonMutating;
break;
default:
llvm_unreachable("unhandled attribute kind");
}
// mutation attributes may only appear in type context.
if (auto contextTy = FD->getDeclContext()->getDeclaredInterfaceType()) {
// 'mutating' and 'nonmutating' are not valid on types
// with reference semantics.
if (contextTy->hasReferenceSemantics()) {
if (attrModifier != SelfAccessKind::__Consuming)
diagnoseAndRemoveAttr(attr, diag::mutating_invalid_classes,
unsigned(attrModifier));
}
} else {
diagnoseAndRemoveAttr(attr, diag::mutating_invalid_global_scope,
unsigned(attrModifier));
}
// Verify we don't have more than one of mutating, nonmutating,
// and __consuming.
if ((FD->getAttrs().hasAttribute<MutatingAttr>() +
FD->getAttrs().hasAttribute<NonMutatingAttr>() +
FD->getAttrs().hasAttribute<ConsumingAttr>()) > 1) {
if (auto *NMA = FD->getAttrs().getAttribute<NonMutatingAttr>()) {
if (attrModifier != SelfAccessKind::NonMutating) {
diagnoseAndRemoveAttr(NMA, diag::functions_mutating_and_not,
unsigned(SelfAccessKind::NonMutating),
unsigned(attrModifier));
}
}
if (auto *MUA = FD->getAttrs().getAttribute<MutatingAttr>()) {
if (attrModifier != SelfAccessKind::Mutating) {
diagnoseAndRemoveAttr(MUA, diag::functions_mutating_and_not,
unsigned(SelfAccessKind::Mutating),
unsigned(attrModifier));
}
}
if (auto *CSA = FD->getAttrs().getAttribute<ConsumingAttr>()) {
if (attrModifier != SelfAccessKind::__Consuming) {
diagnoseAndRemoveAttr(CSA, diag::functions_mutating_and_not,
unsigned(SelfAccessKind::__Consuming),
unsigned(attrModifier));
}
}
}
// Verify that we don't have a static function.
if (FD->isStatic())
diagnoseAndRemoveAttr(attr, diag::static_functions_not_mutating);
}
void AttributeEarlyChecker::visitDynamicAttr(DynamicAttr *attr) {
// Members cannot be both dynamic and final.
if (D->getAttrs().hasAttribute<FinalAttr>())
diagnoseAndRemoveAttr(attr, diag::dynamic_with_final);
// Members cannot be both dynamic and @nonobjc.
if (D->getAttrs().hasAttribute<NonObjCAttr>())
diagnoseAndRemoveAttr(attr, diag::dynamic_with_nonobjc);
}
void AttributeEarlyChecker::visitIBActionAttr(IBActionAttr *attr) {
// Only instance methods returning () can be IBActions.
const FuncDecl *FD = cast<FuncDecl>(D);
if (!FD->isPotentialIBActionTarget())
diagnoseAndRemoveAttr(attr, diag::invalid_ibaction_decl);
}
void AttributeEarlyChecker::visitIBDesignableAttr(IBDesignableAttr *attr) {
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
if (auto nominalDecl = ED->getExtendedNominal()) {
if (!isa<ClassDecl>(nominalDecl))
diagnoseAndRemoveAttr(attr, diag::invalid_ibdesignable_extension);
}
}
}
void AttributeEarlyChecker::visitIBInspectableAttr(IBInspectableAttr *attr) {
// Only instance properties can be 'IBInspectable'.
auto *VD = cast<VarDecl>(D);
if (!VD->getDeclContext()->getSelfClassDecl() || VD->isStatic())
diagnoseAndRemoveAttr(attr, diag::invalid_ibinspectable,
attr->getAttrName());
}
void AttributeEarlyChecker::visitGKInspectableAttr(GKInspectableAttr *attr) {
// Only instance properties can be 'GKInspectable'.
auto *VD = cast<VarDecl>(D);
if (!VD->getDeclContext()->getSelfClassDecl() || VD->isStatic())
diagnoseAndRemoveAttr(attr, diag::invalid_ibinspectable,
attr->getAttrName());
}
void AttributeEarlyChecker::visitSILStoredAttr(SILStoredAttr *attr) {
auto *VD = cast<VarDecl>(D);
if (VD->getDeclContext()->getSelfClassDecl())
return;
auto nominalDecl = VD->getDeclContext()->getSelfNominalTypeDecl();
if (nominalDecl && isa<StructDecl>(nominalDecl))
return;
diagnoseAndRemoveAttr(attr, diag::invalid_decl_attribute_simple);
}
static Optional<Diag<bool,Type>>
isAcceptableOutletType(Type type, bool &isArray, TypeChecker &TC) {
if (type->isObjCExistentialType() || type->isAny())
return None; // @objc existential types are okay
auto nominal = type->getAnyNominal();
if (auto classDecl = dyn_cast_or_null<ClassDecl>(nominal)) {
if (classDecl->isObjC())
return None; // @objc class types are okay.
return diag::iboutlet_nonobjc_class;
}
if (nominal == TC.Context.getStringDecl()) {
// String is okay because it is bridged to NSString.
// FIXME: BridgesTypes.def is almost sufficient for this.
return None;
}
if (nominal == TC.Context.getArrayDecl()) {
// Arrays of arrays are not allowed.
if (isArray)
return diag::iboutlet_nonobject_type;
isArray = true;
// Handle Array<T>. T must be an Objective-C class or protocol.
auto boundTy = type->castTo<BoundGenericStructType>();
auto boundArgs = boundTy->getGenericArgs();
assert(boundArgs.size() == 1 && "invalid Array declaration");
Type elementTy = boundArgs.front();
return isAcceptableOutletType(elementTy, isArray, TC);
}
if (type->isExistentialType())
return diag::iboutlet_nonobjc_protocol;
// No other types are permitted.
return diag::iboutlet_nonobject_type;
}
void AttributeEarlyChecker::visitIBOutletAttr(IBOutletAttr *attr) {
// Only instance properties can be 'IBOutlet'.
auto *VD = cast<VarDecl>(D);
if (!VD->getDeclContext()->getSelfClassDecl() || VD->isStatic())
diagnoseAndRemoveAttr(attr, diag::invalid_iboutlet);
if (!VD->isSettable(nullptr))
diagnoseAndRemoveAttr(attr, diag::iboutlet_only_mutable);
// Verify that the field type is valid as an outlet.
auto type = VD->getType();
if (VD->isInvalid())
return;
// Look through ownership types, and optionals.
type = type->getReferenceStorageReferent();
bool wasOptional = false;
if (Type underlying = type->getOptionalObjectType()) {
type = underlying;
wasOptional = true;
}
bool isArray = false;
if (auto isError = isAcceptableOutletType(type, isArray, TC))
diagnoseAndRemoveAttr(attr, isError.getValue(),
/*array=*/isArray, type);
// If the type wasn't optional, an array, or unowned, complain.
if (!wasOptional && !isArray) {
TC.diagnose(attr->getLocation(), diag::iboutlet_non_optional, type);
auto typeRange = VD->getTypeSourceRangeForDiagnostics();
{ // Only one diagnostic can be active at a time.
auto diag = TC.diagnose(typeRange.Start, diag::note_make_optional,
OptionalType::get(type));
if (type->hasSimpleTypeRepr()) {
diag.fixItInsertAfter(typeRange.End, "?");
} else {
diag.fixItInsert(typeRange.Start, "(")
.fixItInsertAfter(typeRange.End, ")?");
}
}
{ // Only one diagnostic can be active at a time.
auto diag = TC.diagnose(typeRange.Start,
diag::note_make_implicitly_unwrapped_optional);
if (type->hasSimpleTypeRepr()) {
diag.fixItInsertAfter(typeRange.End, "!");
} else {
diag.fixItInsert(typeRange.Start, "(")
.fixItInsertAfter(typeRange.End, ")!");
}
}
}
}
void AttributeEarlyChecker::visitNSManagedAttr(NSManagedAttr *attr) {
// @NSManaged only applies to instance methods and properties within a class.
if (cast<ValueDecl>(D)->isStatic() ||
!D->getDeclContext()->getSelfClassDecl()) {
diagnoseAndRemoveAttr(attr, diag::attr_NSManaged_not_instance_member);
}
if (auto *method = dyn_cast<FuncDecl>(D)) {
// Separate out the checks for methods.
if (method->hasBody())
diagnoseAndRemoveAttr(attr, diag::attr_NSManaged_method_body);
return;
}
// Everything below deals with restrictions on @NSManaged properties.
auto *VD = cast<VarDecl>(D);
if (VD->isLet())
diagnoseAndRemoveAttr(attr, diag::attr_NSManaged_let_property);
auto diagnoseNotStored = [&](unsigned kind) {
TC.diagnose(attr->getLocation(), diag::attr_NSManaged_not_stored, kind);
return attr->setInvalid();
};
// @NSManaged properties must be written as stored.
auto impl = VD->getImplInfo();
if (impl.isSimpleStored()) {
// @NSManaged properties end up being computed; complain if there is
// an initializer.
if (VD->getParentInitializer()) {
TC.diagnose(attr->getLocation(), diag::attr_NSManaged_initial_value)
.highlight(VD->getParentInitializer()->getSourceRange());
auto PBD = VD->getParentPatternBinding();
PBD->setInit(PBD->getPatternEntryIndexForVarDecl(VD), nullptr);
}
// Otherwise, ok.
} else if (impl.getReadImpl() == ReadImplKind::Address ||
impl.getWriteImpl() == WriteImplKind::MutableAddress) {
return diagnoseNotStored(/*addressed*/ 2);
} else if (impl.getWriteImpl() == WriteImplKind::StoredWithObservers ||
impl.getWriteImpl() == WriteImplKind::InheritedWithObservers) {
return diagnoseNotStored(/*observing*/ 1);
} else {
return diagnoseNotStored(/*computed*/ 0);
}
// @NSManaged properties cannot be @NSCopying
if (auto *NSCopy = VD->getAttrs().getAttribute<NSCopyingAttr>())
diagnoseAndRemoveAttr(NSCopy, diag::attr_NSManaged_NSCopying);
}
void AttributeEarlyChecker::
visitLLDBDebuggerFunctionAttr(LLDBDebuggerFunctionAttr *attr) {
// This is only legal when debugger support is on.
if (!D->getASTContext().LangOpts.DebuggerSupport)
diagnoseAndRemoveAttr(attr, diag::attr_for_debugger_support_only);
}
void AttributeEarlyChecker::visitOverrideAttr(OverrideAttr *attr) {
if (!isa<ClassDecl>(D->getDeclContext()) &&
!isa<ProtocolDecl>(D->getDeclContext()) &&
!isa<ExtensionDecl>(D->getDeclContext()))
diagnoseAndRemoveAttr(attr, diag::override_nonclass_decl);
}
void AttributeEarlyChecker::visitNonOverrideAttr(NonOverrideAttr *attr) {
if (!isa<ClassDecl>(D->getDeclContext()) &&
!isa<ProtocolDecl>(D->getDeclContext()) &&
!isa<ExtensionDecl>(D->getDeclContext()))
diagnoseAndRemoveAttr(attr, diag::nonoverride_wrong_decl_context);
}
void AttributeEarlyChecker::visitLazyAttr(LazyAttr *attr) {
// lazy may only be used on properties.
auto *VD = cast<VarDecl>(D);
// It cannot currently be used on let's since we don't have a mutability model
// that supports it.
if (VD->isLet())
diagnoseAndRemoveAttr(attr, diag::lazy_not_on_let);
auto attrs = VD->getAttrs();
// 'lazy' is not allowed to have reference attributes
if (auto *refAttr = attrs.getAttribute<ReferenceOwnershipAttr>())
diagnoseAndRemoveAttr(attr, diag::lazy_not_strong, refAttr->get());
// lazy is not allowed on a protocol requirement.
auto varDC = VD->getDeclContext();
if (isa<ProtocolDecl>(varDC))
diagnoseAndRemoveAttr(attr, diag::lazy_not_in_protocol);
// 'lazy' is not allowed on a global variable or on a static property (which
// are already lazily initialized).
// TODO: we can't currently support lazy properties on non-type-contexts.
if (VD->isStatic() ||
(varDC->isModuleScopeContext() &&
!varDC->getParentSourceFile()->isScriptMode())) {
diagnoseAndRemoveAttr(attr, diag::lazy_on_already_lazy_global);
} else if (!VD->getDeclContext()->isTypeContext()) {
diagnoseAndRemoveAttr(attr, diag::lazy_must_be_property);
}
// lazy must have an initializer, and the pattern binding must be a simple
// one.
if (!VD->getParentInitializer())
diagnoseAndRemoveAttr(attr, diag::lazy_requires_initializer);
if (!VD->getParentPatternBinding()->getSingleVar())
diagnoseAndRemoveAttr(attr, diag::lazy_requires_single_var);
// TODO: Lazy properties can't yet be observed.
auto impl = VD->getImplInfo();
if (impl.isSimpleStored()) {
// ok
} else if (VD->hasStorage()) {
diagnoseAndRemoveAttr(attr, diag::lazy_not_observable);
} else {
diagnoseAndRemoveAttr(attr, diag::lazy_not_on_computed);
}
}
bool AttributeEarlyChecker::visitAbstractAccessControlAttr(
AbstractAccessControlAttr *attr) {
// Access control attr may only be used on value decls and extensions.
if (!isa<ValueDecl>(D) && !isa<ExtensionDecl>(D)) {
diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr);
return true;
}
if (auto extension = dyn_cast<ExtensionDecl>(D)) {
if (!extension->getInherited().empty()) {
diagnoseAndRemoveAttr(attr, diag::extension_access_with_conformances,
attr);
return true;
}
}
// And not on certain value decls.
if (isa<DestructorDecl>(D) || isa<EnumElementDecl>(D)) {
diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr);
return true;
}
// Or within protocols.
if (isa<ProtocolDecl>(D->getDeclContext())) {
diagnoseAndRemoveAttr(attr, diag::access_control_in_protocol, attr);
TC.diagnose(attr->getLocation(), diag::access_control_in_protocol_detail);
return true;
}
return false;
}
void AttributeEarlyChecker::visitAccessControlAttr(AccessControlAttr *attr) {
visitAbstractAccessControlAttr(attr);
}
void AttributeEarlyChecker::visitSetterAccessAttr(
SetterAccessAttr *attr) {
auto storage = dyn_cast<AbstractStorageDecl>(D);
if (!storage)
diagnoseAndRemoveAttr(attr, diag::access_control_setter, attr->getAccess());
if (visitAbstractAccessControlAttr(attr))
return;
if (!storage->isSettable(storage->getDeclContext())) {
// This must stay in sync with diag::access_control_setter_read_only.
enum {
SK_Constant = 0,
SK_Variable,
SK_Property,
SK_Subscript
} storageKind;
if (isa<SubscriptDecl>(storage))
storageKind = SK_Subscript;
else if (storage->getDeclContext()->isTypeContext())
storageKind = SK_Property;
else if (cast<VarDecl>(storage)->isImmutable())
storageKind = SK_Constant;
else
storageKind = SK_Variable;
diagnoseAndRemoveAttr(attr, diag::access_control_setter_read_only,
attr->getAccess(), storageKind);
}
}
void AttributeEarlyChecker::visitObjCMembersAttr(ObjCMembersAttr *attr) {
if (!isa<ClassDecl>(D))
diagnoseAndRemoveAttr(attr, diag::objcmembers_attribute_nonclass);
}
void TypeChecker::checkDeclAttributesEarly(Decl *D) {
// Don't perform early attribute validation more than once.
// FIXME: Crummy way to get idempotency.
if (D->didEarlyAttrValidation())
return;
D->setEarlyAttrValidation();
AttributeEarlyChecker Checker(*this, D);
for (auto attr : D->getAttrs()) {
if (!attr->isValid()) continue;
// If Attr.def says that the attribute cannot appear on this kind of
// declaration, diagnose it and disable it.
if (attr->canAppearOnDecl(D)) {
// Otherwise, check it.
Checker.visit(attr);
continue;
}
// Otherwise, this attribute cannot be applied to this declaration. If the
// attribute is only valid on one kind of declaration (which is pretty
// common) give a specific helpful error.
auto PossibleDeclKinds = attr->getOptions() & DeclAttribute::OnAnyDecl;
StringRef OnlyKind;
switch (PossibleDeclKinds) {
case DeclAttribute::OnAccessor: OnlyKind = "accessor"; break;
case DeclAttribute::OnClass: OnlyKind = "class"; break;
case DeclAttribute::OnConstructor: OnlyKind = "init"; break;
case DeclAttribute::OnDestructor: OnlyKind = "deinit"; break;
case DeclAttribute::OnEnum: OnlyKind = "enum"; break;
case DeclAttribute::OnEnumCase: OnlyKind = "case"; break;
case DeclAttribute::OnFunc | DeclAttribute::OnAccessor: // FIXME
case DeclAttribute::OnFunc: OnlyKind = "func"; break;
case DeclAttribute::OnImport: OnlyKind = "import"; break;
case DeclAttribute::OnModule: OnlyKind = "module"; break;
case DeclAttribute::OnParam: OnlyKind = "parameter"; break;
case DeclAttribute::OnProtocol: OnlyKind = "protocol"; break;
case DeclAttribute::OnStruct: OnlyKind = "struct"; break;
case DeclAttribute::OnSubscript: OnlyKind = "subscript"; break;
case DeclAttribute::OnTypeAlias: OnlyKind = "typealias"; break;
case DeclAttribute::OnVar: OnlyKind = "var"; break;
default: break;
}
if (!OnlyKind.empty())
Checker.diagnoseAndRemoveAttr(attr, diag::attr_only_one_decl_kind,
attr, OnlyKind);
else if (attr->isDeclModifier())
Checker.diagnoseAndRemoveAttr(attr, diag::invalid_decl_modifier, attr);
else
Checker.diagnoseAndRemoveAttr(attr, diag::invalid_decl_attribute, attr);
}
}
namespace {
class AttributeChecker : public AttributeVisitor<AttributeChecker> {
TypeChecker &TC;
Decl *D;
/// This emits a diagnostic with a fixit to remove the attribute.
template<typename ...ArgTypes>
void diagnoseAndRemoveAttr(DeclAttribute *attr, ArgTypes &&...Args) {
::diagnoseAndRemoveAttr(TC, D, attr, std::forward<ArgTypes>(Args)...);
}
public:
AttributeChecker(TypeChecker &TC, Decl *D) : TC(TC), D(D) {}
/// Deleting this ensures that all attributes are covered by the visitor
/// below.
void visitDeclAttribute(DeclAttribute *A) = delete;
#define IGNORED_ATTR(CLASS) \
void visit##CLASS##Attr(CLASS##Attr *) {}
IGNORED_ATTR(Alignment)
IGNORED_ATTR(HasInitialValue)
IGNORED_ATTR(ClangImporterSynthesizedType)
IGNORED_ATTR(Consuming)
IGNORED_ATTR(Convenience)
IGNORED_ATTR(Dynamic)
IGNORED_ATTR(Effects)
IGNORED_ATTR(Exported)
IGNORED_ATTR(ForbidSerializingReference)
IGNORED_ATTR(GKInspectable)
IGNORED_ATTR(IBDesignable)
IGNORED_ATTR(IBInspectable)
IGNORED_ATTR(IBOutlet) // checked early.
IGNORED_ATTR(ImplicitlyUnwrappedOptional)
IGNORED_ATTR(Indirect)
IGNORED_ATTR(Inline)
IGNORED_ATTR(Lazy) // checked early.
IGNORED_ATTR(LLDBDebuggerFunction)
IGNORED_ATTR(Mutating)
IGNORED_ATTR(NonMutating)
IGNORED_ATTR(NonObjC)
IGNORED_ATTR(NoReturn)
IGNORED_ATTR(NSManaged) // checked early.
IGNORED_ATTR(ObjC)
IGNORED_ATTR(ObjCBridged)
IGNORED_ATTR(ObjCMembers)
IGNORED_ATTR(ObjCNonLazyRealization)
IGNORED_ATTR(ObjCRuntimeName)
IGNORED_ATTR(Optional)
IGNORED_ATTR(Override)
IGNORED_ATTR(RawDocComment)
IGNORED_ATTR(ReferenceOwnership)
IGNORED_ATTR(RequiresStoredPropertyInits)
IGNORED_ATTR(RestatedObjCConformance)
IGNORED_ATTR(Semantics)
IGNORED_ATTR(ShowInInterface)
IGNORED_ATTR(SILGenName)
IGNORED_ATTR(SILStored)
IGNORED_ATTR(StaticInitializeObjCMetadata)
IGNORED_ATTR(SynthesizedProtocol)
IGNORED_ATTR(Testable)
IGNORED_ATTR(Transparent)
IGNORED_ATTR(WarnUnqualifiedAccess)
IGNORED_ATTR(WeakLinked)
#undef IGNORED_ATTR
void visitAvailableAttr(AvailableAttr *attr);
void visitCDeclAttr(CDeclAttr *attr);
void visitDynamicMemberLookupAttr(DynamicMemberLookupAttr *attr);
void visitFinalAttr(FinalAttr *attr);
void visitIBActionAttr(IBActionAttr *attr);
void visitNSCopyingAttr(NSCopyingAttr *attr);
void visitRequiredAttr(RequiredAttr *attr);
void visitRethrowsAttr(RethrowsAttr *attr);
void visitAccessControlAttr(AccessControlAttr *attr);
void visitSetterAccessAttr(SetterAccessAttr *attr);
void checkApplicationMainAttribute(DeclAttribute *attr,
Identifier Id_ApplicationDelegate,
Identifier Id_Kit,
Identifier Id_ApplicationMain);
void visitNSApplicationMainAttr(NSApplicationMainAttr *attr);
void visitUIApplicationMainAttr(UIApplicationMainAttr *attr);
void visitUnsafeNoObjCTaggedPointerAttr(UnsafeNoObjCTaggedPointerAttr *attr);
void visitSwiftNativeObjCRuntimeBaseAttr(
SwiftNativeObjCRuntimeBaseAttr *attr);
void checkOperatorAttribute(DeclAttribute *attr);
void visitInfixAttr(InfixAttr *attr) { checkOperatorAttribute(attr); }
void visitPostfixAttr(PostfixAttr *attr) { checkOperatorAttribute(attr); }
void visitPrefixAttr(PrefixAttr *attr) { checkOperatorAttribute(attr); }
void visitSpecializeAttr(SpecializeAttr *attr);
void visitFixedLayoutAttr(FixedLayoutAttr *attr);
void visitUsableFromInlineAttr(UsableFromInlineAttr *attr);
void visitInlinableAttr(InlinableAttr *attr);
void visitOptimizeAttr(OptimizeAttr *attr);
void visitDiscardableResultAttr(DiscardableResultAttr *attr);
void visitImplementsAttr(ImplementsAttr *attr);
void visitFrozenAttr(FrozenAttr *attr);
void visitNonOverrideAttr(NonOverrideAttr *attr);
};
} // end anonymous namespace
static bool checkObjectOrOptionalObjectType(TypeChecker &TC, Decl *D,
ParamDecl *param) {
Type ty = param->getType();
if (auto unwrapped = ty->getOptionalObjectType())
ty = unwrapped;
if (auto classDecl = ty->getClassOrBoundGenericClass()) {
// @objc class types are okay.
if (!classDecl->isObjC()) {
TC.diagnose(D, diag::ibaction_nonobjc_class_argument,
param->getType())
.highlight(param->getSourceRange());
return true;
}
} else if (ty->isObjCExistentialType() || ty->isAny()) {
// @objc existential types are okay, as is Any.
// Nothing to do.
} else {
// No other types are permitted.
TC.diagnose(D, diag::ibaction_nonobject_argument,
param->getType())
.highlight(param->getSourceRange());
return true;
}
return false;
}
static bool isiOS(TypeChecker &TC) {
return TC.getLangOpts().Target.isiOS();
}
static bool iswatchOS(TypeChecker &TC) {
return TC.getLangOpts().Target.isWatchOS();
}
static bool isRelaxedIBAction(TypeChecker &TC) {
return isiOS(TC) || iswatchOS(TC);
}
/// Given a subscript defined as "subscript(dynamicMember:)->T", return true if
/// it is an acceptable implementation of the @dynamicMemberLookup attribute's
/// requirement.
bool swift::isAcceptableDynamicMemberLookupSubscript(SubscriptDecl *decl,
DeclContext *DC,
TypeChecker &TC) {
// The only thing that we care about is that the index list has exactly one
// non-variadic entry. The type must conform to ExpressibleByStringLiteral.
auto indices = decl->getIndices();
auto EBSL =
TC.Context.getProtocol(KnownProtocolKind::ExpressibleByStringLiteral);
return indices->size() == 1 &&
!indices->get(0)->isVariadic() &&
TC.conformsToProtocol(indices->get(0)->getType(),
EBSL, DC, ConformanceCheckOptions());
}
/// The @dynamicMemberLookup attribute is only allowed on types that have at
/// least one subscript member declared like this:
///
/// subscript<KeywordType: ExpressibleByStringLiteral, LookupValue>
/// (dynamicMember name: KeywordType) -> LookupValue { get }
///
/// ... but doesn't care about the mutating'ness of the getter/setter. We just
/// manually check the requirements here.
///
void AttributeChecker::
visitDynamicMemberLookupAttr(DynamicMemberLookupAttr *attr) {
// This attribute is only allowed on nominal types.
auto decl = cast<NominalTypeDecl>(D);
auto type = decl->getDeclaredType();
// Lookup our subscript.
auto subscriptName =
DeclName(TC.Context, DeclBaseName::createSubscript(),
TC.Context.Id_dynamicMember);
auto lookupOptions = defaultMemberTypeLookupOptions;
lookupOptions -= NameLookupFlags::PerformConformanceCheck;
// Lookup the implementations of our subscript.
auto candidates = TC.lookupMember(decl, type, subscriptName, lookupOptions);
// If we have none, then there is no attribute.
if (candidates.empty()) {
TC.diagnose(attr->getLocation(), diag::type_invalid_dml, type);
attr->setInvalid();
return;
}
// If none of the ones we find are acceptable, then reject one.
auto oneCandidate = candidates.front();
candidates.filter([&](LookupResultEntry entry, bool isOuter) -> bool {
auto cand = cast<SubscriptDecl>(entry.getValueDecl());
TC.validateDeclForNameLookup(cand);
return isAcceptableDynamicMemberLookupSubscript(cand, decl, TC);
});
if (candidates.empty()) {
TC.diagnose(oneCandidate.getValueDecl()->getLoc(),
diag::type_invalid_dml, type);
attr->setInvalid();
}
}
void AttributeChecker::visitIBActionAttr(IBActionAttr *attr) {
// IBActions instance methods must have type Class -> (...) -> ().
auto *FD = cast<FuncDecl>(D);
Type CurriedTy = FD->getMethodInterfaceType();
Type ResultTy = CurriedTy->castTo<AnyFunctionType>()->getResult();
if (!ResultTy->isEqual(TupleType::getEmpty(TC.Context))) {
TC.diagnose(D, diag::invalid_ibaction_result, ResultTy);
attr->setInvalid();
return;
}
auto paramList = FD->getParameters();
bool relaxedIBActionUsedOnOSX = false;
bool Valid = true;