forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMiscDiagnostics.cpp
2411 lines (2026 loc) · 83.6 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 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements AST-level diagnostics.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeChecker.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Pattern.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Parse/Lexer.h"
#include "llvm/ADT/MapVector.h"
using namespace swift;
//===--------------------------------------------------------------------===//
// Diagnose assigning variable to itself.
//===--------------------------------------------------------------------===//
static Decl *findSimpleReferencedDecl(const Expr *E) {
if (auto *LE = dyn_cast<LoadExpr>(E))
E = LE->getSubExpr();
if (auto *DRE = dyn_cast<DeclRefExpr>(E))
return DRE->getDecl();
return nullptr;
}
static std::pair<Decl *, Decl *> findReferencedDecl(const Expr *E) {
if (auto *LE = dyn_cast<LoadExpr>(E))
E = LE->getSubExpr();
if (auto *D = findSimpleReferencedDecl(E))
return std::make_pair(nullptr, D);
if (auto *MRE = dyn_cast<MemberRefExpr>(E)) {
if (auto *BaseDecl = findSimpleReferencedDecl(MRE->getBase()))
return std::make_pair(BaseDecl, MRE->getMember().getDecl());
}
return std::make_pair(nullptr, nullptr);
}
/// Diagnose assigning variable to itself.
static void diagSelfAssignment(TypeChecker &TC, const Expr *E) {
auto *AE = dyn_cast<AssignExpr>(E);
if (!AE)
return;
auto LHSDecl = findReferencedDecl(AE->getDest());
auto RHSDecl = findReferencedDecl(AE->getSrc());
if (LHSDecl.second && LHSDecl == RHSDecl) {
TC.diagnose(AE->getLoc(), LHSDecl.first ? diag::self_assignment_prop
: diag::self_assignment_var)
.highlight(AE->getDest()->getSourceRange())
.highlight(AE->getSrc()->getSourceRange());
}
}
/// 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.
///
static void diagSyntacticUseRestrictions(TypeChecker &TC, const Expr *E,
const DeclContext *DC,
bool isExprStmt) {
class DiagnoseWalker : public ASTWalker {
SmallPtrSet<Expr*, 4> AlreadyDiagnosedMetatypes;
SmallPtrSet<DeclRefExpr*, 4> AlreadyDiagnosedNoEscapes;
// Keep track of acceptable DiscardAssignmentExpr's.
SmallPtrSet<DiscardAssignmentExpr*, 2> CorrectDiscardAssignmentExprs;
/// Keep track of InOutExprs
SmallPtrSet<InOutExpr*, 2> AcceptableInOutExprs;
bool IsExprStmt;
public:
TypeChecker &TC;
const DeclContext *DC;
DiagnoseWalker(TypeChecker &TC, const DeclContext *DC, bool isExprStmt)
: IsExprStmt(isExprStmt), TC(TC), DC(DC) {}
// Selector for the partial_application_of_function_invalid diagnostic
// message.
struct PartialApplication {
unsigned level : 29;
enum : unsigned {
Function,
MutatingMethod,
ObjCProtocolMethod,
SuperInit,
SelfInit,
};
unsigned kind : 3;
};
// Partial applications of functions that are not permitted. This is
// tracked in post-order and unravelled as subsequent applications complete
// the call (or not).
llvm::SmallDenseMap<Expr*, PartialApplication,2> InvalidPartialApplications;
~DiagnoseWalker() {
for (auto &unapplied : InvalidPartialApplications) {
unsigned kind = unapplied.second.kind;
TC.diagnose(unapplied.first->getLoc(),
diag::partial_application_of_function_invalid,
kind);
}
}
/// If this is an application of a function that cannot be partially
/// applied, arrange for us to check that it gets fully applied.
void recordUnsupportedPartialApply(DeclRefExpr *expr) {
bool requiresFullApply = false;
unsigned kind;
auto fn = dyn_cast<FuncDecl>(expr->getDecl());
if (!fn)
return;
// @objc protocol methods cannot be partially applied.
if (auto proto = fn->getDeclContext()->isProtocolOrProtocolExtensionContext()) {
if (proto->isObjC()) {
requiresFullApply = true;
kind = PartialApplication::ObjCProtocolMethod;
}
}
if (requiresFullApply) {
// We need to apply all argument clauses.
InvalidPartialApplications.insert({
expr, {fn->getNaturalArgumentCount(), kind}
});
}
}
/// If this is an application of a function that cannot be partially
/// applied, arrange for us to check that it gets fully applied.
void recordUnsupportedPartialApply(ApplyExpr *expr, Expr *fnExpr) {
if (isa<OtherConstructorDeclRefExpr>(fnExpr)) {
auto kind = expr->getArg()->isSuperExpr()
? PartialApplication::SuperInit
: PartialApplication::SelfInit;
// Partial applications of delegated initializers aren't allowed, and
// don't really make sense to begin with.
InvalidPartialApplications.insert({ expr, {1, kind} });
return;
}
auto fnDeclRef = dyn_cast<DeclRefExpr>(fnExpr);
if (!fnDeclRef)
return;
recordUnsupportedPartialApply(fnDeclRef);
auto fn = dyn_cast<FuncDecl>(fnDeclRef->getDecl());
if (!fn)
return;
unsigned kind =
fn->isInstanceMember() ? PartialApplication::MutatingMethod
: PartialApplication::Function;
// Functions with inout parameters cannot be partially applied.
if (expr->getArg()->getType()->hasInOut()) {
// We need to apply all argument clauses.
InvalidPartialApplications.insert({
fnExpr, {fn->getNaturalArgumentCount(), kind}
});
}
}
/// This method is called in post-order over the AST to validate that
/// methods are fully applied when they can't support partial application.
void checkInvalidPartialApplication(Expr *E) {
if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
recordUnsupportedPartialApply(DRE);
return;
}
if (auto AE = dyn_cast<ApplyExpr>(E)) {
Expr *fnExpr = AE->getFn()->getSemanticsProvidingExpr();
if (auto forceExpr = dyn_cast<ForceValueExpr>(fnExpr))
fnExpr = forceExpr->getSubExpr()->getSemanticsProvidingExpr();
if (auto dotSyntaxExpr = dyn_cast<DotSyntaxBaseIgnoredExpr>(fnExpr))
fnExpr = dotSyntaxExpr->getRHS();
// Check to see if this is a potentially unsupported partial
// application.
recordUnsupportedPartialApply(AE, fnExpr);
// If this is adding a level to an active partial application, advance
// it to the next level.
auto foundApplication = InvalidPartialApplications.find(fnExpr);
if (foundApplication == InvalidPartialApplications.end())
return;
unsigned level = foundApplication->second.level;
auto kind = foundApplication->second.kind;
assert(level > 0);
InvalidPartialApplications.erase(foundApplication);
if (level > 1) {
// We have remaining argument clauses.
InvalidPartialApplications.insert({ AE, {level - 1, kind} });
}
return;
}
}
// Not interested in going outside a basic expression.
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
return { false, S };
}
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
return { false, P };
}
bool walkToDeclPre(Decl *D) override { return false; }
bool walkToTypeReprPre(TypeRepr *T) override { return true; }
std::pair<bool, 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 noescape parameter uses.
checkNoEscapeParameterUse(DRE, nullptr);
// Verify warn_unqualified_access uses.
checkUnqualifiedAccessUse(DRE);
}
if (auto *MRE = dyn_cast<MemberRefExpr>(Base)) {
if (isa<TypeDecl>(MRE->getMember().getDecl()))
checkUseOfMetaTypeName(Base);
// Check whether there are needless words that could be omitted.
TC.checkOmitNeedlessWords(MRE);
}
if (isa<TypeExpr>(Base))
checkUseOfMetaTypeName(Base);
if (auto *SE = dyn_cast<SubscriptExpr>(E)) {
// Implicit InOutExpr's are allowed in the base of a subscript expr.
if (auto *IOE = dyn_cast<InOutExpr>(SE->getBase()))
if (IOE->isImplicit())
AcceptableInOutExprs.insert(IOE);
}
// Check function calls, looking through implicit conversions on the
// function and inspecting the arguments directly.
if (auto *Call = dyn_cast<ApplyExpr>(E)) {
// Check the callee, looking through implicit conversions.
auto Base = Call->getFn();
while (auto Conv = dyn_cast<ImplicitConversionExpr>(Base))
Base = Conv->getSubExpr();
if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
checkNoEscapeParameterUse(DRE, Call);
auto *Arg = Call->getArg();
// The argument could be shuffled if it includes default arguments,
// label differences, or other exciting things like that.
if (auto *TSE = dyn_cast<TupleShuffleExpr>(Arg))
Arg = TSE->getSubExpr();
// The argument is either a ParenExpr or TupleExpr.
ArrayRef<Expr*> arguments;
if (auto *TE = dyn_cast<TupleExpr>(Arg))
arguments = TE->getElements();
else if (auto *PE = dyn_cast<ParenExpr>(Arg))
arguments = PE->getSubExpr();
else
arguments = Call->getArg();
// Check each argument.
for (auto arg : arguments) {
// InOutExpr's are allowed in argument lists directly.
if (auto *IOE = dyn_cast<InOutExpr>(arg)) {
if (isa<CallExpr>(Call))
AcceptableInOutExprs.insert(IOE);
}
// InOutExprs can be wrapped in some implicit casts.
if (auto *ICO = dyn_cast<ImplicitConversionExpr>(arg)) {
if (isa<InOutToPointerExpr>(ICO) ||
isa<ArrayToPointerExpr>(ICO) ||
isa<ErasureExpr>(ICO))
if (auto *IOE = dyn_cast<InOutExpr>(ICO->getSubExpr()))
AcceptableInOutExprs.insert(IOE);
}
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;
}
if (auto *DRE = dyn_cast<DeclRefExpr>(arg))
checkNoEscapeParameterUse(DRE, Call);
}
// Check whether there are needless words that could be omitted.
TC.checkOmitNeedlessWords(Call);
}
// If we have an assignment expression, scout ahead for acceptable _'s.
if (auto *AE = dyn_cast<AssignExpr>(E))
markAcceptableDiscardExprs(AE->getDest());
/// Diagnose a '_' that isn't on the immediate LHS of an assignment.
if (auto *DAE = dyn_cast<DiscardAssignmentExpr>(E)) {
if (!CorrectDiscardAssignmentExprs.count(DAE) &&
!DAE->getType()->is<ErrorType>())
TC.diagnose(DAE->getLoc(), diag::discard_expr_outside_of_assignment);
}
// Diagnose an '&' that isn't in an argument lists.
if (auto *IOE = dyn_cast<InOutExpr>(E)) {
if (!IOE->isImplicit() && !AcceptableInOutExprs.count(IOE) &&
!IOE->getType()->is<ErrorType>())
TC.diagnose(IOE->getLoc(), diag::inout_expr_outside_of_call)
.highlight(IOE->getSubExpr()->getSourceRange());
}
// Diagnose 'self.init' or 'super.init' nested in another expression.
if (auto *rebindSelfExpr = dyn_cast<RebindSelfInConstructorExpr>(E)) {
if (!Parent.isNull() || !IsExprStmt) {
bool isChainToSuper;
(void)rebindSelfExpr->getCalledConstructor(isChainToSuper);
TC.diagnose(E->getLoc(), diag::init_delegation_nested,
isChainToSuper, !IsExprStmt);
}
}
return { true, E };
}
Expr *walkToExprPost(Expr *E) override {
checkInvalidPartialApplication(E);
return E;
}
/// Scout out the specified destination of an AssignExpr to recursively
/// identify DiscardAssignmentExpr in legal places. We can only allow them
/// in simple pattern-like expressions, so we reject anything complex here.
void markAcceptableDiscardExprs(Expr *E) {
if (!E) return;
if (auto *PE = dyn_cast<ParenExpr>(E))
return markAcceptableDiscardExprs(PE->getSubExpr());
if (auto *TE = dyn_cast<TupleExpr>(E)) {
for (auto &elt : TE->getElements())
markAcceptableDiscardExprs(elt);
return;
}
if (auto *DAE = dyn_cast<DiscardAssignmentExpr>(E))
CorrectDiscardAssignmentExprs.insert(DAE);
// Otherwise, we can't support this.
}
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;
}
TC.diagnose(E->getStartLoc(), diag::value_of_module_type);
}
/// The DRE argument is a reference to a noescape parameter. Verify that
/// its uses are ok.
void checkNoEscapeParameterUse(DeclRefExpr *DRE, Expr *ParentExpr=nullptr) {
// This only cares about declarations marked noescape.
if (!DRE->getDecl()->getAttrs().hasAttribute<NoEscapeAttr>())
return;
// Only diagnose this once. If we check and accept this use higher up in
// the AST, don't recheck here.
if (!AlreadyDiagnosedNoEscapes.insert(DRE).second)
return;
// The only valid use of the noescape parameter is an immediate call,
// either as the callee or as an argument (in which case, the typechecker
// validates that the noescape bit didn't get stripped off).
if (ParentExpr && isa<ApplyExpr>(ParentExpr)) // param()
return;
TC.diagnose(DRE->getStartLoc(), diag::invalid_noescape_use,
DRE->getDecl()->getName());
if (DRE->getDecl()->getAttrs().hasAttribute<AutoClosureAttr>() &&
DRE->getDecl()->getAttrs().getAttribute<NoEscapeAttr>()->isImplicit())
TC.diagnose(DRE->getDecl()->getLoc(), diag::noescape_autoclosure,
DRE->getDecl()->getName());
}
// 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;
// Allow references to types as a part of:
// - member references T.foo, T.Type, T.self, etc. (but *not* T.type)
// - constructor calls T()
if (auto *ParentExpr = Parent.getAsExpr()) {
// Reject use of "T.dynamicType", it should be written as "T.self".
if (auto metaExpr = dyn_cast<DynamicTypeExpr>(ParentExpr)) {
// Add a fixit to replace '.dynamicType' with '.self'.
TC.diagnose(E->getStartLoc(), diag::type_of_metatype)
.fixItReplace(metaExpr->getMetatypeLoc(), "self");
return;
}
// This is the white-list of accepted syntactic forms.
if (isa<ErrorExpr>(ParentExpr) ||
isa<DotSelfExpr>(ParentExpr) || // T.self
isa<CallExpr>(ParentExpr) || // T()
isa<MemberRefExpr>(ParentExpr) || // T.foo
isa<UnresolvedMemberExpr>(ParentExpr) ||
isa<SelfApplyExpr>(ParentExpr) || // T.foo() T()
isa<UnresolvedDotExpr>(ParentExpr) ||
isa<DotSyntaxBaseIgnoredExpr>(ParentExpr) ||
isa<UnresolvedConstructorExpr>(ParentExpr) ||
isa<UnresolvedSelectorExpr>(ParentExpr) ||
isa<UnresolvedSpecializeExpr>(ParentExpr) ||
isa<OpenExistentialExpr>(ParentExpr)) {
return;
}
}
// Is this a protocol metatype?
TC.diagnose(E->getStartLoc(), diag::value_of_metatype_type);
// Add fix-t to insert '()', unless this is a protocol metatype.
bool isProtocolMetatype = false;
if (auto metaTy = E->getType()->getAs<MetatypeType>())
isProtocolMetatype = metaTy->getInstanceType()->is<ProtocolType>();
if (!isProtocolMetatype) {
TC.diagnose(E->getEndLoc(), diag::add_parens_to_type)
.fixItInsertAfter(E->getEndLoc(), "()");
}
// Add fix-it to insert ".self".
TC.diagnose(E->getEndLoc(), diag::add_self_to_type)
.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()->isNominalTypeOrNominalTypeExtensionContext();
if (!declParent) {
assert(VD->getDeclContext()->isModuleScopeContext());
declParent = VD->getDeclContext()->getParentModule();
}
TC.diagnose(DRE->getLoc(), diag::warn_unqualified_access,
VD->getName(), VD->getDescriptiveKind(),
declParent->getDescriptiveKind(), declParent->getFullName());
TC.diagnose(VD, diag::decl_declared_here, VD->getName());
if (VD->getDeclContext()->isTypeContext()) {
TC.diagnose(DRE->getLoc(), diag::fix_unqualified_access_member)
.fixItInsert(DRE->getStartLoc(), "self.");
}
DeclContext *topLevelContext = DC->getModuleScopeContext();
UnqualifiedLookup lookup(VD->getBaseName(), topLevelContext, &TC,
/*knownPrivate*/true);
// Group results by module. Pick an arbitrary result from each module.
llvm::SmallDenseMap<const ModuleDecl*,const ValueDecl*,4> resultsByModule;
for (auto &result : lookup.Results) {
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('.');
TC.diagnose(DRE->getLoc(), topLevelDiag,
namePlusDot, k, pair.first->getName())
.fixItInsert(DRE->getStartLoc(), namePlusDot);
}
}
};
DiagnoseWalker Walker(TC, DC, isExprStmt);
const_cast<Expr *>(E)->walk(Walker);
}
/// Diagnose recursive use of properties within their own accessors
static void diagRecursivePropertyAccess(TypeChecker &TC, const Expr *E,
const DeclContext *DC) {
auto fn = dyn_cast<FuncDecl>(DC);
if (!fn || !fn->isAccessor())
return;
auto var = dyn_cast<VarDecl>(fn->getAccessorStorageDecl());
if (!var) // Ignore subscripts
return;
class DiagnoseWalker : public ASTWalker {
TypeChecker &TC;
VarDecl *Var;
const FuncDecl *Accessor;
public:
explicit DiagnoseWalker(TypeChecker &TC, VarDecl *var,
const FuncDecl *Accessor)
: TC(TC), Var(var), Accessor(Accessor) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
Expr *subExpr;
bool isStore = false;
if (auto *AE = dyn_cast<AssignExpr>(E)) {
subExpr = AE->getDest();
// If we couldn't flatten this expression, don't explode.
if (!subExpr)
return { true, E };
isStore = true;
} else if (auto *IOE = dyn_cast<InOutExpr>(E)) {
subExpr = IOE->getSubExpr();
isStore = true;
} else {
subExpr = E;
}
if (auto *BOE = dyn_cast<BindOptionalExpr>(subExpr))
subExpr = BOE;
if (auto *DRE = dyn_cast<DeclRefExpr>(subExpr)) {
if (DRE->getDecl() == Var) {
// Handle local and top-level computed variables.
if (DRE->getAccessSemantics() != AccessSemantics::DirectToStorage) {
bool shouldDiagnose = false;
// Warn about any property access in the getter.
if (Accessor->isGetter())
shouldDiagnose = !isStore;
// Warn about stores in the setter, but allow loads.
if (Accessor->isSetter())
shouldDiagnose = isStore;
// But silence the warning if the base was explicitly qualified.
if (dyn_cast_or_null<DotSyntaxBaseIgnoredExpr>(Parent.getAsExpr()))
shouldDiagnose = false;
if (shouldDiagnose) {
TC.diagnose(subExpr->getLoc(), diag::recursive_accessor_reference,
Var->getName(), Accessor->isSetter());
}
}
// If this is a direct store in a "willSet", we reject this because
// it is about to get overwritten.
if (isStore &&
DRE->getAccessSemantics() == AccessSemantics::DirectToStorage &&
Accessor->getAccessorKind() == AccessorKind::IsWillSet) {
TC.diagnose(E->getLoc(), diag::store_in_willset, Var->getName());
}
}
} else if (auto *MRE = dyn_cast<MemberRefExpr>(subExpr)) {
// Handle instance and type computed variables.
// Find MemberRefExprs that have an implicit "self" base.
if (MRE->getMember().getDecl() == Var &&
isa<DeclRefExpr>(MRE->getBase()) &&
MRE->getBase()->isImplicit()) {
if (MRE->getAccessSemantics() != AccessSemantics::DirectToStorage) {
bool shouldDiagnose = false;
// Warn about any property access in the getter.
if (Accessor->isGetter())
shouldDiagnose = !isStore;
// Warn about stores in the setter, but allow loads.
if (Accessor->isSetter())
shouldDiagnose = isStore;
if (shouldDiagnose) {
TC.diagnose(subExpr->getLoc(), diag::recursive_accessor_reference,
Var->getName(), Accessor->isSetter());
TC.diagnose(subExpr->getLoc(),
diag::recursive_accessor_reference_silence)
.fixItInsert(subExpr->getStartLoc(), "self.");
}
}
// If this is a direct store in a "willSet", we reject this because
// it is about to get overwritten.
if (isStore &&
MRE->getAccessSemantics() == AccessSemantics::DirectToStorage &&
Accessor->getAccessorKind() == AccessorKind::IsWillSet) {
TC.diagnose(subExpr->getLoc(), diag::store_in_willset,
Var->getName());
}
}
}
return { true, E };
}
};
DiagnoseWalker walker(TC, var, fn);
const_cast<Expr *>(E)->walk(walker);
}
/// Look for any property references in closures that lack a "self." qualifier.
/// Within a closure, we require that the source code contain "self." explicitly
/// because 'self' is captured, not the property value. This is a common source
/// of confusion, so we force an explicit self.
static void diagnoseImplicitSelfUseInClosure(TypeChecker &TC, const Expr *E,
const DeclContext *DC) {
class DiagnoseWalker : public ASTWalker {
TypeChecker &TC;
unsigned InClosure;
public:
explicit DiagnoseWalker(TypeChecker &TC, bool isAlreadyInClosure)
: TC(TC), InClosure(isAlreadyInClosure) {}
/// Return true if this is an implicit reference to self.
static bool isImplicitSelfUse(Expr *E) {
auto *DRE = dyn_cast<DeclRefExpr>(E);
return DRE && DRE->isImplicit() && DRE->getDecl()->hasName() &&
DRE->getDecl()->getName().str() == "self" &&
// Metatype self captures don't extend the lifetime of an object.
!DRE->getType()->is<MetatypeType>();
}
/// Return true if this is a closure expression that will require "self."
/// qualification of member references.
static bool isClosureRequiringSelfQualification(
const AbstractClosureExpr *CE) {
// If the closure's type was inferred to be noescape, then it doesn't
// need qualification.
return !AnyFunctionRef(const_cast<AbstractClosureExpr *>(CE))
.isKnownNoEscape();
}
// Don't walk into nested decls.
bool walkToDeclPre(Decl *D) override {
return false;
}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (auto *CE = dyn_cast<AbstractClosureExpr>(E)) {
if (!CE->hasSingleExpressionBody())
return { false, E };
// If this is a potentially-escaping closure expression, start looking
// for references to self if we aren't already.
if (isClosureRequiringSelfQualification(CE))
++InClosure;
}
// If we aren't in a closure, no diagnostics will be produced.
if (!InClosure)
return { true, E };
// If we see a property reference with an implicit base from within a
// closure, then reject it as requiring an explicit "self." qualifier. We
// do this in explicit closures, not autoclosures, because otherwise the
// transparence of autoclosures is lost.
if (auto *MRE = dyn_cast<MemberRefExpr>(E))
if (isImplicitSelfUse(MRE->getBase())) {
TC.diagnose(MRE->getLoc(),
diag::property_use_in_closure_without_explicit_self,
MRE->getMember().getDecl()->getName())
.fixItInsert(MRE->getLoc(), "self.");
return { false, E };
}
// Handle method calls with a specific diagnostic + fixit.
if (auto *DSCE = dyn_cast<DotSyntaxCallExpr>(E))
if (isImplicitSelfUse(DSCE->getBase()) &&
isa<DeclRefExpr>(DSCE->getFn())) {
auto MethodExpr = cast<DeclRefExpr>(DSCE->getFn());
TC.diagnose(DSCE->getLoc(),
diag::method_call_in_closure_without_explicit_self,
MethodExpr->getDecl()->getName())
.fixItInsert(DSCE->getLoc(), "self.");
return { false, E };
}
// Catch any other implicit uses of self with a generic diagnostic.
if (isImplicitSelfUse(E))
TC.diagnose(E->getLoc(), diag::implicit_use_of_self_in_closure);
return { true, E };
}
Expr *walkToExprPost(Expr *E) override {
if (auto *CE = dyn_cast<AbstractClosureExpr>(E)) {
if (isClosureRequiringSelfQualification(CE)) {
assert(InClosure);
--InClosure;
}
}
return E;
}
};
bool isAlreadyInClosure = false;
if (DC->isLocalContext()) {
while (DC->getParent()->isLocalContext() && !isAlreadyInClosure) {
if (auto *closure = dyn_cast<AbstractClosureExpr>(DC))
if (DiagnoseWalker::isClosureRequiringSelfQualification(closure))
isAlreadyInClosure = true;
DC = DC->getParent();
}
}
const_cast<Expr *>(E)->walk(DiagnoseWalker(TC, isAlreadyInClosure));
}
//===--------------------------------------------------------------------===//
// Diagnose availability.
//===--------------------------------------------------------------------===//
static void tryFixPrintWithAppendNewline(const ValueDecl *D,
const Expr *ParentExpr,
InFlightDiagnostic &Diag) {
if (!D || !ParentExpr)
return;
if (!D->getModuleContext()->isStdlibModule())
return;
DeclName Name = D->getFullName();
if (Name.getBaseName().str() != "print")
return;
auto ArgNames = Name.getArgumentNames();
if (ArgNames.size() != 2)
return;
if (ArgNames[1].str() != "appendNewline")
return;
// Go through the expr to determine if second parameter is boolean literal.
auto *CE = dyn_cast_or_null<CallExpr>(ParentExpr);
if (!CE)
return;
auto *TE = dyn_cast<TupleExpr>(CE->getArg());
if (!TE)
return;
if (TE->getNumElements() != 2)
return;
auto *SCE = dyn_cast<CallExpr>(TE->getElement(1));
if (!SCE || !SCE->isImplicit())
return;
auto *STE = dyn_cast<TupleExpr>(SCE->getArg());
if (!STE || !STE->isImplicit())
return;
if (STE->getNumElements() != 1)
return;
auto *BE = dyn_cast<BooleanLiteralExpr>(STE->getElement(0));
if (!BE)
return;
SmallString<20> termStr = StringRef("terminator: \"");
if (BE->getValue())
termStr += "\\n";
termStr += "\"";
SourceRange RangeToFix(TE->getElementNameLoc(1), BE->getEndLoc());
Diag.fixItReplace(RangeToFix, termStr);
}
/// Emit a diagnostic for references to declarations that have been
/// marked as unavailable, either through "unavailable" or "obsoleted=".
bool TypeChecker::diagnoseExplicitUnavailability(const ValueDecl *D,
SourceRange R,
const DeclContext *DC,
const Expr *ParentExpr) {
auto *Attr = AvailableAttr::isUnavailable(D);
if (!Attr)
return false;
// Suppress the diagnostic if we are in synthesized code inside
// a synthesized function and the reference is lexically
// contained in a declaration that is itself marked unavailable.
// The right thing to do here is to not synthesize that code in the
// first place. rdar://problem/20491640
if (R.isInvalid() && isInsideImplicitFunction(R, DC) &&
isInsideUnavailableDeclaration(R, DC)) {
return false;
}
SourceLoc Loc = R.Start;
auto Name = D->getFullName();
switch (Attr->getUnconditionalAvailability()) {
case UnconditionalAvailabilityKind::Deprecated:
break;
case UnconditionalAvailabilityKind::None:
case UnconditionalAvailabilityKind::Unavailable:
if (!Attr->Rename.empty()) {
if (Attr->Message.empty()) {
diagnose(Loc, diag::availability_decl_unavailable_rename, Name,
Attr->Rename)
.fixItReplace(R, Attr->Rename);
} else {
diagnose(Loc, diag::availability_decl_unavailable_rename_msg, Name,
Attr->Rename, Attr->Message)
.fixItReplace(R, Attr->Rename);
}
} else if (Attr->Message.empty()) {
diagnose(Loc, diag::availability_decl_unavailable, Name).highlight(R);
} else {
EncodedDiagnosticMessage EncodedMessage(Attr->Message);
tryFixPrintWithAppendNewline(D, ParentExpr,
diagnose(Loc, diag::availability_decl_unavailable_msg, Name,
EncodedMessage.Message).highlight(R));
}
break;
case UnconditionalAvailabilityKind::UnavailableInSwift:
if (Attr->Message.empty()) {
diagnose(Loc, diag::availability_decl_unavailable_in_swift, Name)
.highlight(R);
} else {
EncodedDiagnosticMessage EncodedMessage(Attr->Message);
diagnose(Loc, diag::availability_decl_unavailable_in_swift_msg, Name,
EncodedMessage.Message).highlight(R);
}
break;
}
auto MinVersion = Context.LangOpts.getMinPlatformVersion();
switch (Attr->getMinVersionAvailability(MinVersion)) {
case MinVersionComparison::Available:
case MinVersionComparison::PotentiallyUnavailable:
llvm_unreachable("These aren't considered unavailable");
case MinVersionComparison::Unavailable:
diagnose(D, diag::availability_marked_unavailable, Name)
.highlight(Attr->getRange());
break;
case MinVersionComparison::Obsoleted:
// FIXME: Use of the platformString here is non-awesome for application
// extensions.
diagnose(D, diag::availability_obsoleted, Name,
Attr->prettyPlatformString(),
*Attr->Obsoleted).highlight(Attr->getRange());
break;
}
return true;
}
/// Diagnose uses of unavailable declarations. Returns true if a diagnostic
/// was emitted.
static bool diagAvailability(TypeChecker &TC, const ValueDecl *D,
SourceRange R, const DeclContext *DC,
const Expr *ParentExpr = nullptr) {
if (!D)
return false;
if (TC.diagnoseExplicitUnavailability(D, R, DC, ParentExpr))
return true;
// Diagnose for deprecation
if (const AvailableAttr *Attr = TypeChecker::getDeprecated(D)) {
TC.diagnoseDeprecated(R, DC, Attr, D->getFullName());
}
if (TC.getLangOpts().DisableAvailabilityChecking) {
return false;
}
// Diagnose for potential unavailability
auto maybeUnavail = TC.checkDeclarationAvailability(D, R.Start, DC);
if (maybeUnavail.hasValue()) {
TC.diagnosePotentialUnavailability(D, R, DC, maybeUnavail.getValue());
return true;
}
return false;
}
namespace {
class AvailabilityWalker : public ASTWalker {
/// Describes how the next member reference will be treated as we traverse
/// the AST.
enum class MemberAccessContext : unsigned {
/// The member reference is in a context where an access will call
/// the getter.
Getter,
/// The member reference is in a context where an access will call
/// the setter.
Setter,
/// The member reference is in a context where it will be turned into
/// an inout argument. (Once this happens, we have to conservatively assume
/// that both the getter and setter could be called.)
InOut
};
TypeChecker &TC;
const DeclContext *DC;
const MemberAccessContext AccessContext;
SmallVector<const Expr *, 16> ExprStack;
public:
AvailabilityWalker(
TypeChecker &TC, const DeclContext *DC,
MemberAccessContext AccessContext = MemberAccessContext::Getter)
: TC(TC), DC(DC), AccessContext(AccessContext) {}