-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathMiscDiagnostics.cpp
6669 lines (5734 loc) · 242 KB
/
MiscDiagnostics.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
//===--- MiscDiagnostics.cpp - AST-Level Diagnostics ----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 AST-level diagnostics.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckConcurrency.h"
#include "TypeCheckInvertible.h"
#include "TypeChecker.h"
#include "swift/AST/ASTBridging.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AvailabilitySpec.h"
#include "swift/AST/ConformanceLookup.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/SemanticAttrs.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/SaveAndRestore.h"
#define DEBUG_TYPE "Sema"
using namespace swift;
using namespace constraints;
/// Return true if this expression is an implicit promotion from T to T?.
static Expr *isImplicitPromotionToOptional(Expr *E) {
if (E->isImplicit())
if (auto IIOE = dyn_cast<InjectIntoOptionalExpr>(
E->getSemanticsProvidingExpr()))
return IIOE->getSubExpr();
return nullptr;
}
/// Diagnose syntactic restrictions of expressions.
///
/// - Module values may only occur as part of qualification.
/// - Metatype names cannot generally be used as values: they need a "T.self"
/// qualification unless used in narrow case (e.g. T() for construction).
/// - '_' may only exist on the LHS of an assignment expression.
/// - warn_unqualified_access values must not be accessed except via qualified
/// lookup.
/// - Partial application of some decls isn't allowed due to implementation
/// limitations.
/// - "&" (aka InOutExpressions) may only exist directly in function call
/// argument lists.
/// - 'self.init' and 'super.init' cannot be wrapped in a larger expression
/// or statement.
/// - Warn about promotions to optional in specific syntactic forms.
/// - Error about collection literals that default to Any collections in
/// invalid positions.
/// - Marker protocols cannot occur as the type of an as? or is expression.
/// - KeyPath expressions cannot refer to effectful properties / subscripts
/// - SingleValueStmtExprs may only appear in certain places and has
/// restrictions on the control flow allowed.
/// - Move expressions must have a declref expr subvalue.
///
static void diagSyntacticUseRestrictions(const Expr *E, const DeclContext *DC,
bool isExprStmt) {
class DiagnoseWalker : public BaseDiagnosticWalker {
SmallPtrSet<Expr*, 4> AlreadyDiagnosedMetatypes;
SmallPtrSet<DeclRefExpr*, 4> AlreadyDiagnosedBitCasts;
bool IsExprStmt;
ASTContext &Ctx;
const DeclContext *DC;
public:
DiagnoseWalker(const DeclContext *DC, bool isExprStmt)
: IsExprStmt(isExprStmt), Ctx(DC->getASTContext()), DC(DC) {}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
return Action::Continue();
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
// See through implicit conversions of the expression. We want to be able
// to associate the parent of this expression with the ultimate callee.
auto Base = E;
while (auto Conv = dyn_cast<ImplicitConversionExpr>(Base))
Base = Conv->getSubExpr();
if (auto *DRE = dyn_cast<DeclRefExpr>(Base)) {
// Verify metatype uses.
if (isa<TypeDecl>(DRE->getDecl())) {
if (isa<ModuleDecl>(DRE->getDecl()))
checkUseOfModule(DRE);
else
checkUseOfMetaTypeName(Base);
}
// Verify warn_unqualified_access uses.
checkUnqualifiedAccessUse(DRE);
// Verify that special decls are eliminated.
checkForDeclWithSpecialTypeCheckingSemantics(DRE);
// Verify that `unsafeBitCast` isn't misused.
checkForSuspiciousBitCasts(DRE, nullptr);
}
if (auto *MRE = dyn_cast<MemberRefExpr>(Base)) {
if (isa<TypeDecl>(MRE->getMember().getDecl()))
checkUseOfMetaTypeName(Base);
}
// Don't diagnose a missing '.self' for type value expressions.
if (isa<TypeExpr>(Base) && !isa<TypeValueExpr>(E))
checkUseOfMetaTypeName(Base);
if (auto *KPE = dyn_cast<KeyPathExpr>(E))
checkForInvalidKeyPath(KPE);
// Check function calls, looking through implicit conversions on the
// function and inspecting the arguments directly.
if (auto *Call = dyn_cast<ApplyExpr>(E)) {
// Warn about surprising implicit optional promotions.
checkOptionalPromotions(Call);
// Check the callee, looking through implicit conversions.
auto base = Call->getFn();
unsigned uncurryLevel = 0;
while (auto conv = dyn_cast<ImplicitConversionExpr>(base))
base = conv->getSubExpr();
const auto findDynamicMemberRefExpr =
[](Expr *e) -> DynamicMemberRefExpr* {
if (auto open = dyn_cast<OpenExistentialExpr>(e)) {
return dyn_cast<DynamicMemberRefExpr>(open->getSubExpr());
}
return nullptr;
};
if (auto force = dyn_cast<ForceValueExpr>(base)) {
if (auto ref = findDynamicMemberRefExpr(force->getSubExpr()))
base = ref;
} else if (auto bind = dyn_cast<BindOptionalExpr>(base)) {
if (auto ref = findDynamicMemberRefExpr(bind->getSubExpr()))
base = ref;
}
while (auto ignoredBase = dyn_cast<DotSyntaxBaseIgnoredExpr>(base))
base = ignoredBase->getRHS();
ConcreteDeclRef callee;
if (auto *calleeDRE = dyn_cast<DeclRefExpr>(base)) {
checkForSuspiciousBitCasts(calleeDRE, Call);
callee = calleeDRE->getDeclRef();
// Otherwise, try to drill down through member calls for the purposes
// of argument-matching code below.
} else if (auto selfApply = dyn_cast<SelfApplyExpr>(base)) {
++uncurryLevel;
base = selfApply->getSemanticFn();
if (auto calleeDRE = dyn_cast<DeclRefExpr>(base))
callee = calleeDRE->getDeclRef();
// Otherwise, check for a dynamic member.
} else if (auto dynamicMRE = dyn_cast<DynamicMemberRefExpr>(base)) {
++uncurryLevel;
callee = dynamicMRE->getMember();
}
if (callee) {
auto *args = Call->getArgs();
for (auto idx : indices(*args)) {
auto *arg = args->getExpr(idx);
checkMagicIdentifierMismatch(callee, uncurryLevel, idx, arg);
// InOutExprs can be wrapped in some implicit casts.
Expr *unwrapped = arg;
if (auto *IIO = dyn_cast<InjectIntoOptionalExpr>(arg))
unwrapped = IIO->getSubExpr();
if (isa<InOutToPointerExpr>(unwrapped) ||
isa<ArrayToPointerExpr>(unwrapped) ||
isa<ErasureExpr>(unwrapped)) {
auto operand =
cast<ImplicitConversionExpr>(unwrapped)->getSubExpr();
if (auto *IOE = dyn_cast<InOutExpr>(operand))
operand = IOE->getSubExpr();
// Also do some additional work based on how the function uses
// the argument.
checkConvertedPointerArgument(callee, uncurryLevel, idx,
unwrapped, operand);
}
}
}
}
// If we have an assignment expression, scout ahead for acceptable _'s.
if (auto *AE = dyn_cast<AssignExpr>(E)) {
auto destExpr = AE->getDest();
// If the user is assigning the result of a function that returns
// Void to _ then warn, because that is redundant.
if (auto DAE = dyn_cast<DiscardAssignmentExpr>(destExpr)) {
if (auto CE = dyn_cast<CallExpr>(AE->getSrc())) {
if (getAsDecl<FuncDecl>(
CE->getCalledValue(/*skipFunctionConversions=*/true)) &&
CE->getType()->isVoid()) {
Ctx.Diags
.diagnose(DAE->getLoc(),
diag::discard_expr_void_result_redundant)
.fixItRemoveChars(DAE->getStartLoc(),
AE->getSrc()->getStartLoc());
}
}
}
}
// Diagnose 'self.init' or 'super.init' nested in another expression
// or closure.
if (auto *rebindSelfExpr = dyn_cast<RebindSelfInConstructorExpr>(E)) {
if (!Parent.isNull() || !IsExprStmt || DC->getParent()->isLocalContext()) {
bool isChainToSuper;
(void)rebindSelfExpr->getCalledConstructor(isChainToSuper);
Ctx.Diags.diagnose(E->getLoc(), diag::init_delegation_nested,
isChainToSuper, !IsExprStmt);
}
}
// Diagnose single-element tuple expressions.
if (auto *tupleExpr = dyn_cast<TupleExpr>(E)) {
if (tupleExpr->getNumElements() == 1 &&
!isa<PackExpansionExpr>(tupleExpr->getElement(0))) {
Ctx.Diags.diagnose(tupleExpr->getElementNameLoc(0),
diag::tuple_single_element)
.fixItRemoveChars(tupleExpr->getElementNameLoc(0),
tupleExpr->getElement(0)->getStartLoc());
}
}
auto diagnoseDuplicateLabels = [&](SourceLoc loc,
ArrayRef<Identifier> labels) {
llvm::SmallDenseSet<Identifier> names;
names.reserve(labels.size());
for (auto name : labels) {
if (name.empty())
continue;
auto inserted = names.insert(name).second;
if (!inserted) {
Ctx.Diags.diagnose(loc, diag::tuple_duplicate_label);
return;
}
}
};
// FIXME: Duplicate labels on enum payloads should be diagnosed
// when declared, not when called.
if (auto *CE = dyn_cast_or_null<CallExpr>(E)) {
auto calledValue = CE->getCalledValue(/*skipFunctionConversions=*/true);
if (calledValue && isa<EnumElementDecl>(calledValue)) {
auto *args = CE->getArgs();
SmallVector<Identifier, 4> scratch;
diagnoseDuplicateLabels(args->getLoc(),
args->getArgumentLabels(scratch));
}
}
if (auto *tupleExpr = dyn_cast<TupleExpr>(E)) {
// Diagnose tuple expressions with duplicate element label.
diagnoseDuplicateLabels(tupleExpr->getLoc(),
tupleExpr->getElementNames());
// Diagnose attempts to form a tuple with any noncopyable elements.
if (E->getType()->isNoncopyable()
&& !Ctx.LangOpts.hasFeature(Feature::MoveOnlyTuples)) {
auto noncopyableTy = E->getType();
assert(noncopyableTy->is<TupleType>() && "will use poor wording");
Ctx.Diags.diagnose(E->getLoc(),
diag::tuple_containing_move_only_not_supported,
noncopyableTy);
}
}
// Specially diagnose some checked casts that are illegal.
if (auto cast = dyn_cast<CheckedCastExpr>(E)) {
checkCheckedCastExpr(cast);
}
// Diagnose move expression uses where the sub expression is not a declref
// expr.
if (auto *consumeExpr = dyn_cast<ConsumeExpr>(E)) {
checkConsumeExpr(consumeExpr);
}
// Diagnose copy expression uses where the sub expression is not a declref
// expr.
if (auto *copyExpr = dyn_cast<CopyExpr>(E)) {
checkCopyExpr(copyExpr);
}
// Diagnose move expression uses where the sub expression is not a declref expr
if (auto *borrowExpr = dyn_cast<BorrowExpr>(E)) {
checkBorrowExpr(borrowExpr);
}
return Action::Continue(E);
}
/// Visit each component of the keypath and emit a diagnostic if they
/// refer to a member that meets any of the following:
/// - has effects.
/// - is a noncopyable type.
void checkForInvalidKeyPath(KeyPathExpr *keyPath) {
for (const auto &component : keyPath->getComponents()) {
if (component.hasDeclRef()) {
auto decl = component.getDeclRef().getDecl();
// Check for effects
if (auto asd = dyn_cast<AbstractStorageDecl>(decl)) {
if (asd->getEffectfulGetAccessor()) {
Ctx.Diags.diagnose(component.getLoc(),
diag::effectful_keypath_component,
asd->getDescriptiveKind(),
/*dynamic member lookup*/ false);
Ctx.Diags.diagnose(asd->getLoc(), diag::kind_declared_here,
asd->getDescriptiveKind());
}
}
// Check for the ability to copy.
if (component.getComponentType()->isNoncopyable()) {
Ctx.Diags.diagnose(component.getLoc(),
diag::expr_keypath_noncopyable_type,
component.getComponentType()->getRValueType());
}
}
}
}
void checkCheckedCastExpr(CheckedCastExpr *cast) {
Type castType = cast->getCastType();
if (!castType)
return;
if (castType->isNoncopyable()) {
// can't cast anything to move-only; there should be no valid ones.
Ctx.Diags.diagnose(cast->getLoc(), diag::noncopyable_cast);
return;
}
// no support for runtime casts from move-only types.
// as of now there is no type it could be cast to except itself, so
// there's no reason for it to happen at runtime.
if (auto fromType = cast->getSubExpr()->getType()) {
if (fromType->isNoncopyable()) {
// can't cast move-only to anything.
Ctx.Diags.diagnose(cast->getLoc(), diag::noncopyable_cast);
return;
}
}
// now, look for conditional casts to marker protocols.
if (!isa<ConditionalCheckedCastExpr>(cast) && !isa<IsExpr>(cast))
return;
if(!castType->isExistentialType())
return;
auto layout = castType->getExistentialLayout();
for (auto proto : layout.getProtocols()) {
if (proto->isMarkerProtocol() && !proto->getInvertibleProtocolKind()) {
// can't conditionally cast to a marker protocol
Ctx.Diags.diagnose(cast->getLoc(), diag::marker_protocol_cast,
proto->getName());
}
}
}
void checkConsumeExpr(ConsumeExpr *consumeExpr) {
auto diags = findSyntacticErrorForConsume(DC->getParentModule(),
consumeExpr->getLoc(),
consumeExpr->getSubExpr());
for (auto &diag : diags)
diag.emit(Ctx);
// As of now, SE-366 is not correctly implemented (rdar://102780553),
// so warn about certain consume's being no-ops today that will no longer
// be a no-op in the future once we fix this.
if (auto ty = consumeExpr->getType()) {
bool shouldWarn = true;
// Look through any load.
auto *expr = consumeExpr->getSubExpr();
if (auto *load = dyn_cast<LoadExpr>(expr))
expr = load->getSubExpr();
// Don't warn if explicit ownership was provided on a parameter.
// Those seem to be checked just fine in SIL.
if (auto *declRef = dyn_cast<DeclRefExpr>(expr)) {
if (auto *decl = declRef->getDecl()) {
if (auto *paramDecl = dyn_cast<ParamDecl>(decl)) {
switch (paramDecl->getSpecifier()) {
case ParamSpecifier::InOut:
case ParamSpecifier::Borrowing:
case ParamSpecifier::Consuming:
case ParamSpecifier::ImplicitlyCopyableConsuming:
shouldWarn = false;
break;
case ParamSpecifier::Default:
case ParamSpecifier::LegacyShared:
case ParamSpecifier::LegacyOwned:
break; // warn
}
}
}
}
// Only warn about obviously concrete BitwiseCopyable types, since we
// know those won't get checked for consumption.
if (diags.empty() &&
shouldWarn &&
!ty->hasError() &&
!ty->hasTypeParameter() &&
!ty->hasUnboundGenericType() &&
!ty->hasArchetype()) {
auto bitCopy = Ctx.getProtocol(KnownProtocolKind::BitwiseCopyable);
if (checkConformance(ty, bitCopy)) {
Ctx.Diags.diagnose(consumeExpr->getLoc(),
diag::consume_of_bitwisecopyable_noop, ty)
.fixItRemoveChars(consumeExpr->getStartLoc(),
consumeExpr->getSubExpr()->getStartLoc());
}
}
}
}
void checkCopyExpr(CopyExpr *copyExpr) {
// Do not allow for copy_expr to be used with pure move only types. We
// /do/ allow it to be used with no implicit copy types though.
if (copyExpr->getType()->isNoncopyable()) {
Ctx.Diags.diagnose(
copyExpr->getLoc(),
diag::copy_expression_cannot_be_used_with_noncopyable_types);
}
// We only allow for copy_expr to be applied directly to lvalues. We do
// not allow currently for it to be applied to fields.
auto *subExpr = copyExpr->getSubExpr();
if (auto *li = dyn_cast<LoadExpr>(subExpr))
subExpr = li->getSubExpr();
if (!isa<DeclRefExpr>(subExpr)) {
Ctx.Diags.diagnose(copyExpr->getLoc(),
diag::copy_expression_not_passed_lvalue);
}
}
void checkBorrowExpr(BorrowExpr *borrowExpr) {
// Allow for a chain of member_ref exprs that end in a decl_ref expr.
auto *subExpr = borrowExpr->getSubExpr();
while (auto *memberRef = dyn_cast<MemberRefExpr>(subExpr))
subExpr = memberRef->getBase();
if (!isa<DeclRefExpr>(subExpr)) {
Ctx.Diags.diagnose(borrowExpr->getLoc(),
diag::borrow_expression_not_passed_lvalue);
}
}
static Expr *lookThroughArgument(Expr *arg) {
while (1) {
if (auto conv = dyn_cast<ImplicitConversionExpr>(arg))
arg = conv->getSubExpr();
else if (auto *PE = dyn_cast<ParenExpr>(arg))
arg = PE->getSubExpr();
else
break;
}
return arg;
}
void checkConvertedPointerArgument(ConcreteDeclRef callee,
unsigned uncurryLevel,
unsigned argIndex,
Expr *pointerExpr,
Expr *storage) {
if (!isPointerIdentityArgument(callee, uncurryLevel, argIndex))
return;
// Flag that the argument is non-accessing.
if (auto inout = dyn_cast<InOutToPointerExpr>(pointerExpr)) {
inout->setNonAccessing(true);
} else if (auto array = dyn_cast<ArrayToPointerExpr>(pointerExpr)) {
array->setNonAccessing(true);
}
// TODO: warn if taking the address of 'storage' will definitely
// yield a temporary address.
}
/// Is the given call argument, known to be of pointer type, just used
/// for its pointer identity?
bool isPointerIdentityArgument(ConcreteDeclRef ref, unsigned uncurryLevel,
unsigned argIndex) {
// FIXME: derive this from an attribute instead of hacking it based
// on the target name!
auto decl = ref.getDecl();
// Assume that == and != are non-accessing uses.
if (decl->isOperator()) {
auto op = decl->getBaseName();
if (op == "==" || op == "!=")
return true;
return false;
}
// NSObject.addObserver(_:forKeyPath:options:context:)
if (uncurryLevel == 1 && argIndex == 3) {
return decl->getName().isCompoundName("addObserver",
{ "", "forKeyPath",
"options", "context" });
}
// NSObject.removeObserver(_:forKeyPath:context:)
if (uncurryLevel == 1 && argIndex == 2) {
return decl->getName().isCompoundName("removeObserver",
{ "", "forKeyPath", "context" });
}
return false;
}
/// We have a collection literal with a defaulted type, e.g. of [Any]. Emit
/// an error if it was inferred to this type in an invalid context, which is
/// one in which the parent expression is not itself a collection literal.
void checkTypeDefaultedCollectionExpr(CollectionExpr *c) {
// If the parent is a non-expression, or is not itself a literal, then
// produce an error with a fixit to add the type as an explicit
// annotation.
if (c->getNumElements() == 0)
Ctx.Diags.diagnose(c->getLoc(), diag::collection_literal_empty)
.highlight(c->getSourceRange());
else {
assert(c->getType()->hasTypeRepr() &&
"a defaulted type should always be printable");
Ctx.Diags
.diagnose(c->getLoc(), diag::collection_literal_heterogeneous,
c->getType())
.highlight(c->getSourceRange())
.fixItInsertAfter(c->getEndLoc(),
" as " + c->getType()->getString());
}
}
void checkMagicIdentifierMismatch(ConcreteDeclRef callee,
unsigned uncurryLevel,
unsigned argIndex,
Expr *arg) {
// We only care about args in the arg list.
if (uncurryLevel != (callee.getDecl()->hasCurriedSelf() ? 1 : 0))
return;
// Get underlying params for both callee and caller, if declared.
auto *calleeParam = getParameterAt(callee, argIndex);
auto *callerParam = dyn_cast_or_null<ParamDecl>(
arg->getReferencedDecl(/*stopAtParenExpr=*/true).getDecl()
);
// (Otherwise, we don't need to do anything.)
if (!calleeParam || !callerParam)
return;
auto calleeDefaultArg = getMagicIdentifierDefaultArgKind(calleeParam);
auto callerDefaultArg = getMagicIdentifierDefaultArgKind(callerParam);
// If one of the parameters doesn't have a default arg, or they're both
// compatible, everything's fine.
if (!calleeDefaultArg || !callerDefaultArg ||
areMagicIdentifiersCompatible(*calleeDefaultArg, *callerDefaultArg))
return;
StringRef calleeDefaultArgString =
MagicIdentifierLiteralExpr::getKindString(*calleeDefaultArg);
StringRef callerDefaultArgString =
MagicIdentifierLiteralExpr::getKindString(*callerDefaultArg);
// Emit main warning
Ctx.Diags.diagnose(arg->getLoc(), diag::default_magic_identifier_mismatch,
callerParam->getName(), callerDefaultArgString,
calleeParam->getName(), calleeDefaultArgString);
// Add "change caller default arg" fixit
SourceLoc callerDefaultArgLoc =
callerParam->getStructuralDefaultExpr()->getLoc();
Ctx.Diags.diagnose(callerDefaultArgLoc,
diag::change_caller_default_to_match_callee,
callerParam->getName(), calleeDefaultArgString)
.fixItReplace(callerDefaultArgLoc, calleeDefaultArgString);
// Add "silence with parens" fixit
Ctx.Diags.diagnose(arg->getLoc(),
diag::silence_default_magic_identifier_mismatch)
.fixItInsert(arg->getStartLoc(), "(")
.fixItInsertAfter(arg->getEndLoc(), ")");
// Point to callee parameter
Ctx.Diags.diagnose(calleeParam, diag::decl_declared_here, calleeParam);
}
std::optional<MagicIdentifierLiteralExpr::Kind>
getMagicIdentifierDefaultArgKind(const ParamDecl *param) {
switch (param->getDefaultArgumentKind()) {
#define MAGIC_IDENTIFIER(NAME, STRING) \
case DefaultArgumentKind::NAME: \
return MagicIdentifierLiteralExpr::Kind::NAME;
#include "swift/AST/MagicIdentifierKinds.def"
case DefaultArgumentKind::None:
case DefaultArgumentKind::Normal:
case DefaultArgumentKind::Inherited:
case DefaultArgumentKind::NilLiteral:
case DefaultArgumentKind::EmptyArray:
case DefaultArgumentKind::EmptyDictionary:
case DefaultArgumentKind::StoredProperty:
case DefaultArgumentKind::ExpressionMacro:
return std::nullopt;
}
llvm_unreachable("Unhandled DefaultArgumentKind in "
"getMagicIdentifierDefaultArgKind");
}
static bool
areMagicIdentifiersCompatible(MagicIdentifierLiteralExpr::Kind a,
MagicIdentifierLiteralExpr::Kind b) {
if (a == b)
return true;
// The rest of this handles special compatibility rules between the
// `*SpelledAsFile` cases and various other File-related cases.
//
// The way we're going to do this is a bit magical. We will arrange the
// cases in MagicIdentifierLiteralExpr::Kind so that they sort in
// this order:
//
// #fileID < Swift 6 #file < #filePath < Swift 5 #file < others
//
// Before we continue, let's verify that this holds.
using Kind = MagicIdentifierLiteralExpr::Kind;
static_assert(Kind::FileID < Kind::FileIDSpelledAsFile,
"#fileID < Swift 6 #file");
static_assert(Kind::FileIDSpelledAsFile < Kind::FilePath,
"Swift 6 #file < #filePath");
static_assert(Kind::FilePath < Kind::FilePathSpelledAsFile,
"#filePath < Swift 5 #file");
static_assert(Kind::FilePathSpelledAsFile < Kind::Line,
"Swift 5 #file < #line");
static_assert(Kind::FilePathSpelledAsFile < Kind::Column,
"Swift 5 #file < #column");
static_assert(Kind::FilePathSpelledAsFile < Kind::Function,
"Swift 5 #file < #function");
static_assert(Kind::FilePathSpelledAsFile < Kind::DSOHandle,
"Swift 5 #file < #dsohandle");
// The rules are all commutative, so we will take the greater of the two
// kinds.
auto maxKind = std::max(a, b);
// Both Swift 6 #file and Swift 5 #file are greater than all of the cases
// they're compatible with. So if `maxCase` is one of those two, the other
// case must have been compatible with it!
return maxKind == Kind::FileIDSpelledAsFile ||
maxKind == Kind::FilePathSpelledAsFile;
}
void checkUseOfModule(DeclRefExpr *E) {
// Allow module values as a part of:
// - ignored base expressions;
// - expressions that failed to type check.
if (auto *ParentExpr = Parent.getAsExpr()) {
if (isa<DotSyntaxBaseIgnoredExpr>(ParentExpr) ||
isa<UnresolvedDotExpr>(ParentExpr))
return;
}
Ctx.Diags.diagnose(E->getStartLoc(), diag::value_of_module_type);
}
// Diagnose metatype values that don't appear as part of a property,
// method, or constructor reference.
void checkUseOfMetaTypeName(Expr *E) {
// If we've already checked this at a higher level, we're done.
if (!AlreadyDiagnosedMetatypes.insert(E).second)
return;
DiagnosticBehavior behavior = DiagnosticBehavior::Error;
if (auto *ParentExpr = Parent.getAsExpr()) {
if (ParentExpr->isValidParentOfTypeExpr(E))
return;
// In Swift < 6 warn about
// - plain type name passed as an argument to a subscript, dynamic
// subscript, or ObjC literal since it used to be accepted.
// - member type expressions rooted on non-identifier types, e.g.
// '[X].Y' since they used to be accepted without the '.self'.
if (!Ctx.LangOpts.isSwiftVersionAtLeast(6)) {
if (isa<SubscriptExpr>(ParentExpr) ||
isa<DynamicSubscriptExpr>(ParentExpr) ||
isa<ObjectLiteralExpr>(ParentExpr)) {
auto *argList = ParentExpr->getArgs();
assert(argList);
if (argList->isUnlabeledUnary())
behavior = DiagnosticBehavior::Warning;
} else if (auto *TE = dyn_cast<TypeExpr>(E)) {
if (auto *QualIdentTR = dyn_cast_or_null<QualifiedIdentTypeRepr>(
TE->getTypeRepr())) {
if (!isa<UnqualifiedIdentTypeRepr>(QualIdentTR->getRoot())) {
behavior = DiagnosticBehavior::Warning;
}
}
}
}
}
// Is this a protocol metatype?
Ctx.Diags
.diagnose(E->getStartLoc(), diag::value_of_metatype_type,
behavior == DiagnosticBehavior::Warning)
.limitBehavior(behavior);
// Add fix-it to insert '()', only if this is a metatype of
// non-existential type and has any initializers.
bool isExistential = false;
if (auto metaTy = E->getType()->getAs<MetatypeType>()) {
auto instanceTy = metaTy->getInstanceType();
isExistential = instanceTy->isExistentialType();
if (!isExistential &&
instanceTy->mayHaveMembers() &&
!TypeChecker::lookupMember(const_cast<DeclContext *>(DC), instanceTy,
DeclNameRef::createConstructor()).empty()) {
Ctx.Diags.diagnose(E->getEndLoc(), diag::add_parens_to_type)
.fixItInsertAfter(E->getEndLoc(), "()");
}
}
// Add fix-it to insert ".self".
auto diag = Ctx.Diags.diagnose(E->getEndLoc(), diag::add_self_to_type);
if (E->canAppendPostfixExpression()) {
diag.fixItInsertAfter(E->getEndLoc(), ".self");
} else {
diag.fixItInsert(E->getStartLoc(), "(");
diag.fixItInsertAfter(E->getEndLoc(), ").self");
}
}
void checkUnqualifiedAccessUse(const DeclRefExpr *DRE) {
const Decl *D = DRE->getDecl();
if (!D->getAttrs().hasAttribute<WarnUnqualifiedAccessAttr>())
return;
if (auto *parentExpr = Parent.getAsExpr()) {
if (auto *ignoredBase = dyn_cast<DotSyntaxBaseIgnoredExpr>(parentExpr)){
if (!ignoredBase->isImplicit())
return;
}
if (auto *calledBase = dyn_cast<DotSyntaxCallExpr>(parentExpr)) {
if (!calledBase->isImplicit())
return;
}
}
const auto *VD = cast<ValueDecl>(D);
const TypeDecl *declParent =
VD->getDeclContext()->getSelfNominalTypeDecl();
if (!declParent) {
// If the declaration has been validated but not fully type-checked,
// the attribute might be applied to something invalid.
if (!VD->getDeclContext()->isModuleScopeContext())
return;
declParent = VD->getDeclContext()->getParentModule();
}
Ctx.Diags.diagnose(DRE->getLoc(), diag::warn_unqualified_access,
VD->getBaseIdentifier(),
VD->getDescriptiveKind(),
declParent);
Ctx.Diags.diagnose(VD, diag::decl_declared_here, VD);
if (VD->getDeclContext()->isTypeContext()) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::fix_unqualified_access_member)
.fixItInsert(DRE->getStartLoc(), "self.");
}
DeclContext *topLevelSubcontext = DC->getModuleScopeContext();
auto descriptor = UnqualifiedLookupDescriptor(
DeclNameRef(VD->getBaseName()), topLevelSubcontext, SourceLoc());
auto lookup = evaluateOrDefault(Ctx.evaluator,
UnqualifiedLookupRequest{descriptor}, {});
// Group results by module. Pick an arbitrary result from each module.
llvm::SmallDenseMap<const ModuleDecl*,const ValueDecl*,4> resultsByModule;
for (auto &result : lookup) {
const ValueDecl *value = result.getValueDecl();
resultsByModule.insert(std::make_pair(value->getModuleContext(),value));
}
// Sort by module name.
using ModuleValuePair = std::pair<const ModuleDecl *, const ValueDecl *>;
SmallVector<ModuleValuePair, 4> sortedResults{
resultsByModule.begin(), resultsByModule.end()
};
llvm::array_pod_sort(sortedResults.begin(), sortedResults.end(),
[](const ModuleValuePair *lhs,
const ModuleValuePair *rhs) {
return lhs->first->getName().compare(rhs->first->getName());
});
auto topLevelDiag = diag::fix_unqualified_access_top_level;
if (sortedResults.size() > 1)
topLevelDiag = diag::fix_unqualified_access_top_level_multi;
for (const ModuleValuePair &pair : sortedResults) {
DescriptiveDeclKind k = pair.second->getDescriptiveKind();
SmallString<32> namePlusDot = pair.first->getName().str();
namePlusDot.push_back('.');
Ctx.Diags.diagnose(DRE->getLoc(), topLevelDiag,
namePlusDot, k, pair.first->getName())
.fixItInsert(DRE->getStartLoc(), namePlusDot);
}
}
void checkForDeclWithSpecialTypeCheckingSemantics(const DeclRefExpr *DRE) {
// Referencing type(of:) and other decls with special type-checking
// behavior as functions is not implemented. Maybe we could wrap up the
// special-case behavior in a closure someday...
if (TypeChecker::getDeclTypeCheckingSemantics(DRE->getDecl())
!= DeclTypeCheckingSemantics::Normal) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::unsupported_special_decl_ref,
DRE->getDecl()->getBaseIdentifier());
}
}
enum BitcastableNumberKind {
BNK_None = 0,
BNK_Int8,
BNK_Int16,
BNK_Int32,
BNK_Int64,
BNK_Int,
BNK_UInt8,
BNK_UInt16,
BNK_UInt32,
BNK_UInt64,
BNK_UInt,
BNK_Float,
BNK_Double,
};
BitcastableNumberKind getBitcastableNumberKind(Type t) const {
auto decl = t->getNominalOrBoundGenericNominal();
#define MATCH_DECL(type) \
if (decl == Ctx.get##type##Decl()) \
return BNK_##type;
MATCH_DECL(Int8)
MATCH_DECL(Int16)
MATCH_DECL(Int32)
MATCH_DECL(Int64)
MATCH_DECL(Int)
MATCH_DECL(UInt8)
MATCH_DECL(UInt16)
MATCH_DECL(UInt32)
MATCH_DECL(UInt64)
MATCH_DECL(UInt)
MATCH_DECL(Float)
MATCH_DECL(Double)
#undef MATCH_DECL
return BNK_None;
}
static constexpr unsigned BNKPair(BitcastableNumberKind a,
BitcastableNumberKind b) {
return (a << 8) | b;
}
void checkForSuspiciousBitCasts(DeclRefExpr *DRE,
Expr *Parent = nullptr) {
if (DRE->getDecl() != Ctx.getUnsafeBitCast())
return;
if (DRE->getDeclRef().getSubstitutions().empty())
return;
// Don't check the same use of unsafeBitCast twice.
if (!AlreadyDiagnosedBitCasts.insert(DRE).second)
return;
auto subMap = DRE->getDeclRef().getSubstitutions();
auto fromTy = subMap.getReplacementTypes()[0];
auto toTy = subMap.getReplacementTypes()[1];
// Warn about `unsafeBitCast` formulations that are undefined behavior
// or have better-defined alternative APIs that can be used instead.
// If we have a parent ApplyExpr that calls bitcast, extract the argument
// for fixits.
Expr *subExpr = nullptr;
CharSourceRange removeBeforeRange, removeAfterRange;
if (auto apply = dyn_cast_or_null<ApplyExpr>(Parent)) {
subExpr = apply->getArgs()->getExpr(0);
// Determine the fixit range from the start of the application to
// the first argument, `unsafeBitCast(`
removeBeforeRange = CharSourceRange(Ctx.SourceMgr, DRE->getLoc(),
subExpr->getStartLoc());
// Determine the fixit range from the end of the first argument to
// the end of the application, `, to: T.self)`
removeAfterRange = CharSourceRange(Ctx.SourceMgr,
Lexer::getLocForEndOfToken(Ctx.SourceMgr,
subExpr->getEndLoc()),
Lexer::getLocForEndOfToken(Ctx.SourceMgr,
apply->getEndLoc()));
}
// Casting to the same type or a superclass is a no-op.
if (toTy->isEqual(fromTy) ||
toTy->isExactSuperclassOf(fromTy)) {
auto d = Ctx.Diags.diagnose(DRE->getLoc(), diag::bitcasting_is_no_op,
fromTy, toTy);
if (subExpr) {
d.fixItRemoveChars(removeBeforeRange.getStart(),
removeBeforeRange.getEnd())
.fixItRemoveChars(removeAfterRange.getStart(),
removeAfterRange.getEnd());
}
return;
}
if (auto fromFnTy = fromTy->getAs<FunctionType>()) {
if (auto toFnTy = toTy->getAs<FunctionType>()) {
// Casting a nonescaping function to escaping is UB.
// `withoutActuallyEscaping` ought to be used instead.
if (fromFnTy->isNoEscape() && !toFnTy->isNoEscape()) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::bitcasting_away_noescape,
fromTy, toTy);
}
// Changing function representation (say, to try to force a
// @convention(c) function pointer to exist) is also unlikely to work.
if (fromFnTy->getRepresentation() != toFnTy->getRepresentation()) {
Ctx.Diags.diagnose(DRE->getLoc(),
diag::bitcasting_to_change_function_rep, fromTy,
toTy);
}
return;
}
}
// Unchecked casting to a subclass is better done by unsafeDowncast.
if (fromTy->isBindableToSuperclassOf(toTy)) {
Ctx.Diags.diagnose(DRE->getLoc(), diag::bitcasting_to_downcast,
fromTy, toTy)
.fixItReplace(DRE->getNameLoc().getBaseNameLoc(),
"unsafeDowncast");
return;
}
// Casting among pointer types should use the Unsafe*Pointer APIs for
// rebinding typed memory or accessing raw memory instead.
PointerTypeKind fromPTK, toPTK;
Type fromPointee = fromTy->getAnyPointerElementType(fromPTK);
Type toPointee = toTy->getAnyPointerElementType(toPTK);
if (fromPointee && toPointee) {
// Casting to a pointer to the same type or UnsafeRawPointer can use