-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathCSDiag.cpp
6099 lines (5148 loc) · 229 KB
/
CSDiag.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
//===--- CSDiag.cpp - Constraint Diagnostics ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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 diagnostics for the type checker.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "MiscDiagnostics.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/TypeMatcher.h"
#include "swift/Basic/StringExtras.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace constraints;
static bool isUnresolvedOrTypeVarType(Type ty) {
return ty->is<TypeVariableType>() || ty->is<UnresolvedType>();
}
/// Given a subpath of an old locator, compute its summary flags.
static unsigned recomputeSummaryFlags(ConstraintLocator *oldLocator,
ArrayRef<LocatorPathElt> path) {
if (oldLocator->getSummaryFlags() != 0)
return ConstraintLocator::getSummaryFlagsForPath(path);
return 0;
}
ConstraintLocator *
constraints::simplifyLocator(ConstraintSystem &cs, ConstraintLocator *locator,
SourceRange &range,
ConstraintLocator **targetLocator) {
// Clear out the target locator result.
if (targetLocator)
*targetLocator = nullptr;
// The path to be tacked on to the target locator to identify the specific
// target.
Expr *targetAnchor;
SmallVector<LocatorPathElt, 4> targetPath;
auto path = locator->getPath();
auto anchor = locator->getAnchor();
simplifyLocator(anchor, path, targetAnchor, targetPath, range);
// If we have a target anchor, build and simplify the target locator.
if (targetLocator && targetAnchor) {
SourceRange targetRange;
unsigned targetFlags = recomputeSummaryFlags(locator, targetPath);
auto loc = cs.getConstraintLocator(targetAnchor, targetPath, targetFlags);
*targetLocator = simplifyLocator(cs, loc, targetRange);
}
// If we didn't simplify anything, just return the input.
if (anchor == locator->getAnchor() &&
path.size() == locator->getPath().size()) {
return locator;
}
// Recompute the summary flags if we had any to begin with. This is
// necessary because we might remove e.g. tuple elements from the path.
unsigned summaryFlags = recomputeSummaryFlags(locator, path);
return cs.getConstraintLocator(anchor, path, summaryFlags);
}
void constraints::simplifyLocator(Expr *&anchor,
ArrayRef<LocatorPathElt> &path,
Expr *&targetAnchor,
SmallVectorImpl<LocatorPathElt> &targetPath,
SourceRange &range) {
range = SourceRange();
targetAnchor = nullptr;
while (!path.empty()) {
switch (path[0].getKind()) {
case ConstraintLocator::ApplyArgument:
// Extract application argument.
if (auto applyExpr = dyn_cast<ApplyExpr>(anchor)) {
// The target anchor is the function being called.
targetAnchor = applyExpr->getFn();
targetPath.push_back(path[0]);
anchor = applyExpr->getArg();
path = path.slice(1);
continue;
}
if (auto objectLiteralExpr = dyn_cast<ObjectLiteralExpr>(anchor)) {
targetAnchor = nullptr;
targetPath.clear();
anchor = objectLiteralExpr->getArg();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::ApplyFunction:
// Extract application function.
if (auto applyExpr = dyn_cast<ApplyExpr>(anchor)) {
// No additional target locator information.
targetAnchor = nullptr;
targetPath.clear();
anchor = applyExpr->getFn();
path = path.slice(1);
continue;
}
// The unresolved member itself is the function.
if (auto unresolvedMember = dyn_cast<UnresolvedMemberExpr>(anchor)) {
if (unresolvedMember->getArgument()) {
// No additional target locator information.
targetAnchor = nullptr;
targetPath.clear();
anchor = unresolvedMember;
path = path.slice(1);
continue;
}
}
break;
case ConstraintLocator::Load:
case ConstraintLocator::RvalueAdjustment:
case ConstraintLocator::ScalarToTuple:
case ConstraintLocator::UnresolvedMember:
// Loads, rvalue adjustment, and scalar-to-tuple conversions are implicit.
path = path.slice(1);
continue;
case ConstraintLocator::NamedTupleElement:
case ConstraintLocator::TupleElement:
// Extract tuple element.
if (auto tupleExpr = dyn_cast<TupleExpr>(anchor)) {
unsigned index = path[0].getValue();
if (index < tupleExpr->getNumElements()) {
// Append this extraction to the target locator path.
if (targetAnchor) {
targetPath.push_back(path[0]);
}
anchor = tupleExpr->getElement(index);
path = path.slice(1);
continue;
}
}
break;
case ConstraintLocator::ApplyArgToParam:
// Extract tuple element.
if (auto tupleExpr = dyn_cast<TupleExpr>(anchor)) {
unsigned index = path[0].getValue();
if (index < tupleExpr->getNumElements()) {
// Append this extraction to the target locator path.
if (targetAnchor) {
targetPath.push_back(path[0]);
}
anchor = tupleExpr->getElement(index);
path = path.slice(1);
continue;
}
}
// Extract subexpression in parentheses.
if (auto parenExpr = dyn_cast<ParenExpr>(anchor)) {
assert(path[0].getValue() == 0);
// Append this extraction to the target locator path.
if (targetAnchor) {
targetPath.push_back(path[0]);
}
anchor = parenExpr->getSubExpr();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::ConstructorMember:
if (auto typeExpr = dyn_cast<TypeExpr>(anchor)) {
// This is really an implicit 'init' MemberRef, so point at the base,
// i.e. the TypeExpr.
targetAnchor = nullptr;
targetPath.clear();
range = SourceRange();
anchor = typeExpr;
path = path.slice(1);
continue;
}
SWIFT_FALLTHROUGH;
case ConstraintLocator::Member:
case ConstraintLocator::MemberRefBase:
if (auto UDE = dyn_cast<UnresolvedDotExpr>(anchor)) {
// No additional target locator information.
targetAnchor = nullptr;
targetPath.clear();
range = UDE->getNameLoc().getSourceRange();
anchor = UDE->getBase();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::InterpolationArgument:
if (auto interp = dyn_cast<InterpolatedStringLiteralExpr>(anchor)) {
unsigned index = path[0].getValue();
if (index < interp->getSegments().size()) {
// No additional target locator information.
// FIXME: Dig out the constructor we're trying to call?
targetAnchor = nullptr;
targetPath.clear();
anchor = interp->getSegments()[index];
path = path.slice(1);
continue;
}
}
break;
case ConstraintLocator::SubscriptIndex:
if (auto subscript = dyn_cast<SubscriptExpr>(anchor)) {
targetAnchor = subscript->getBase();
targetPath.clear();
anchor = subscript->getIndex();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::SubscriptMember:
if (auto subscript = dyn_cast<SubscriptExpr>(anchor)) {
anchor = subscript->getBase();
targetAnchor = nullptr;
targetPath.clear();
path = path.slice(1);
continue;
}
break;
case ConstraintLocator::ClosureResult:
if (auto CE = dyn_cast<ClosureExpr>(anchor)) {
if (CE->hasSingleExpressionBody()) {
targetAnchor = nullptr;
targetPath.clear();
anchor = CE->getSingleExpressionBody();
path = path.slice(1);
continue;
}
}
break;
default:
// FIXME: Lots of other cases to handle.
break;
}
// If we get here, we couldn't simplify the path further.
break;
}
}
/// Simplify the given locator down to a specific anchor expression,
/// if possible.
///
/// \returns the anchor expression if it fully describes the locator, or
/// null otherwise.
static Expr *simplifyLocatorToAnchor(ConstraintSystem &cs,
ConstraintLocator *locator) {
if (!locator || !locator->getAnchor())
return nullptr;
SourceRange range;
locator = simplifyLocator(cs, locator, range);
if (!locator->getAnchor() || !locator->getPath().empty())
return nullptr;
return locator->getAnchor();
}
/// \brief Determine the number of distinct overload choices in the
/// provided set.
static unsigned countDistinctOverloads(ArrayRef<OverloadChoice> choices) {
llvm::SmallPtrSet<void *, 4> uniqueChoices;
unsigned result = 0;
for (auto choice : choices) {
if (uniqueChoices.insert(choice.getOpaqueChoiceSimple()).second)
++result;
}
return result;
}
/// \brief Determine the name of the overload in a set of overload choices.
static DeclName getOverloadChoiceName(ArrayRef<OverloadChoice> choices) {
for (auto choice : choices) {
if (choice.isDecl())
return choice.getDecl()->getFullName();
}
return DeclName();
}
static bool diagnoseAmbiguity(ConstraintSystem &cs,
ArrayRef<Solution> solutions,
Expr *expr) {
// Produce a diff of the solutions.
SolutionDiff diff(solutions);
// Find the locators which have the largest numbers of distinct overloads.
Optional<unsigned> bestOverload;
unsigned maxDistinctOverloads = 0;
unsigned maxDepth = 0;
unsigned minIndex = std::numeric_limits<unsigned>::max();
// Get a map of expressions to their depths and post-order traversal indices.
// Heuristically, all other things being equal, we should complain about the
// ambiguous expression that (1) has the most overloads, (2) is deepest, or
// (3) comes earliest in the expression.
auto depthMap = expr->getDepthMap();
auto indexMap = expr->getPreorderIndexMap();
for (unsigned i = 0, n = diff.overloads.size(); i != n; ++i) {
auto &overload = diff.overloads[i];
// If we can't resolve the locator to an anchor expression with no path,
// we can't diagnose this well.
auto *anchor = simplifyLocatorToAnchor(cs, overload.locator);
if (!anchor)
continue;
auto it = indexMap.find(anchor);
if (it == indexMap.end())
continue;
unsigned index = it->second;
it = depthMap.find(anchor);
if (it == depthMap.end())
continue;
unsigned depth = it->second;
// If we don't have a name to hang on to, it'll be hard to diagnose this
// overload.
if (!getOverloadChoiceName(overload.choices))
continue;
unsigned distinctOverloads = countDistinctOverloads(overload.choices);
// We need at least two overloads to make this interesting.
if (distinctOverloads < 2)
continue;
// If we have more distinct overload choices for this locator than for
// prior locators, just keep this locator.
bool better = false;
if (bestOverload) {
if (distinctOverloads > maxDistinctOverloads) {
better = true;
} else if (distinctOverloads == maxDistinctOverloads) {
if (depth > maxDepth) {
better = true;
} else if (depth == maxDepth) {
if (index < minIndex) {
better = true;
}
}
}
}
if (!bestOverload || better) {
bestOverload = i;
maxDistinctOverloads = distinctOverloads;
maxDepth = depth;
minIndex = index;
continue;
}
// We have better results. Ignore this one.
}
// FIXME: Should be able to pick the best locator, e.g., based on some
// depth-first numbering of expressions.
if (bestOverload) {
auto &overload = diff.overloads[*bestOverload];
auto name = getOverloadChoiceName(overload.choices);
auto anchor = simplifyLocatorToAnchor(cs, overload.locator);
// Emit the ambiguity diagnostic.
auto &tc = cs.getTypeChecker();
tc.diagnose(anchor->getLoc(),
name.isOperator() ? diag::ambiguous_operator_ref
: diag::ambiguous_decl_ref,
name);
// Emit candidates. Use a SmallPtrSet to make sure only emit a particular
// candidate once. FIXME: Why is one candidate getting into the overload
// set multiple times?
SmallPtrSet<Decl*, 8> EmittedDecls;
for (auto choice : overload.choices) {
switch (choice.getKind()) {
case OverloadChoiceKind::Decl:
case OverloadChoiceKind::DeclViaDynamic:
case OverloadChoiceKind::TypeDecl:
case OverloadChoiceKind::DeclViaBridge:
case OverloadChoiceKind::DeclViaUnwrappedOptional:
// FIXME: show deduced types, etc, etc.
if (EmittedDecls.insert(choice.getDecl()).second)
tc.diagnose(choice.getDecl(), diag::found_candidate);
break;
case OverloadChoiceKind::BaseType:
case OverloadChoiceKind::TupleIndex:
// FIXME: Actually diagnose something here.
break;
}
}
return true;
}
// FIXME: If we inferred different types for literals (for example),
// could diagnose ambiguity that way as well.
return false;
}
static std::string getTypeListString(Type type) {
// Assemble the parameter type list.
auto tupleType = type->getAs<TupleType>();
if (!tupleType) {
if (auto PT = dyn_cast<ParenType>(type.getPointer()))
type = PT->getUnderlyingType();
return "(" + type->getString() + ")";
}
std::string result = "(";
for (auto field : tupleType->getElements()) {
if (result.size() != 1)
result += ", ";
if (!field.getName().empty()) {
result += field.getName().str();
result += ": ";
}
if (!field.isVararg())
result += field.getType()->getString();
else {
result += field.getVarargBaseTy()->getString();
result += "...";
}
}
result += ")";
return result;
}
/// If an UnresolvedDotExpr, SubscriptMember, etc has been resolved by the
/// constraint system, return the decl that it references.
static ValueDecl *findResolvedMemberRef(ConstraintLocator *locator,
ConstraintSystem &CS) {
auto *resolvedOverloadSets = CS.getResolvedOverloadSets();
if (!resolvedOverloadSets) return nullptr;
// Search through the resolvedOverloadSets to see if we have a resolution for
// this member. This is an O(n) search, but only happens when producing an
// error diagnostic.
for (auto resolved = resolvedOverloadSets;
resolved; resolved = resolved->Previous) {
if (resolved->Locator != locator) continue;
// We only handle the simplest decl binding.
if (resolved->Choice.getKind() != OverloadChoiceKind::Decl)
return nullptr;
return resolved->Choice.getDecl();
}
return nullptr;
}
/// Given an expression that has a non-lvalue type, dig into it until we find
/// the part of the expression that prevents the entire subexpression from being
/// mutable. For example, in a sequence like "x.v.v = 42" we want to complain
/// about "x" being a let property if "v.v" are both mutable.
///
/// This returns the base subexpression that looks immutable (or that can't be
/// analyzed any further) along with a decl extracted from it if we could.
///
static std::pair<Expr*, ValueDecl*>
resolveImmutableBase(Expr *expr, ConstraintSystem &CS) {
expr = expr->getValueProvidingExpr();
// Provide specific diagnostics for assignment to subscripts whose base expr
// is known to be an rvalue.
if (auto *SE = dyn_cast<SubscriptExpr>(expr)) {
// If we found a decl for the subscript, check to see if it is a set-only
// subscript decl.
SubscriptDecl *member = nullptr;
if (SE->hasDecl())
member = dyn_cast_or_null<SubscriptDecl>(SE->getDecl().getDecl());
if (!member) {
auto loc = CS.getConstraintLocator(SE,ConstraintLocator::SubscriptMember);
member = dyn_cast_or_null<SubscriptDecl>(findResolvedMemberRef(loc, CS));
}
// If it isn't settable, return it.
if (member) {
if (!member->isSettable() ||
!member->isSetterAccessibleFrom(CS.DC))
return { expr, member };
}
// If it is settable, then the base must be the problem, recurse.
return resolveImmutableBase(SE->getBase(), CS);
}
// Look through property references.
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(expr)) {
// If we found a decl for the UDE, check it.
auto loc = CS.getConstraintLocator(UDE, ConstraintLocator::Member);
auto *member = dyn_cast_or_null<VarDecl>(findResolvedMemberRef(loc, CS));
// If the member isn't settable, then it is the problem: return it.
if (member) {
if (!member->isSettable(nullptr) ||
!member->isSetterAccessibleFrom(CS.DC))
return { expr, member };
}
// If we weren't able to resolve a member or if it is mutable, then the
// problem must be with the base, recurse.
return resolveImmutableBase(UDE->getBase(), CS);
}
if (auto *MRE = dyn_cast<MemberRefExpr>(expr)) {
// If the member isn't settable, then it is the problem: return it.
if (auto member = dyn_cast<AbstractStorageDecl>(MRE->getMember().getDecl()))
if (!member->isSettable(nullptr) ||
!member->isSetterAccessibleFrom(CS.DC))
return { expr, member };
// If we weren't able to resolve a member or if it is mutable, then the
// problem must be with the base, recurse.
return resolveImmutableBase(MRE->getBase(), CS);
}
if (auto *DRE = dyn_cast<DeclRefExpr>(expr))
return { expr, DRE->getDecl() };
// Look through x!
if (auto *FVE = dyn_cast<ForceValueExpr>(expr))
return resolveImmutableBase(FVE->getSubExpr(), CS);
// Look through x?
if (auto *BOE = dyn_cast<BindOptionalExpr>(expr))
return resolveImmutableBase(BOE->getSubExpr(), CS);
return { expr, nullptr };
}
static bool isLoadedLValue(Expr *expr) {
expr = expr->getSemanticsProvidingExpr();
if (isa<LoadExpr>(expr))
return true;
if (auto ifExpr = dyn_cast<IfExpr>(expr))
return isLoadedLValue(ifExpr->getThenExpr())
&& isLoadedLValue(ifExpr->getElseExpr());
return false;
}
static void diagnoseSubElementFailure(Expr *destExpr,
SourceLoc loc,
ConstraintSystem &CS,
Diag<StringRef> diagID,
Diag<Type> unknownDiagID) {
auto &TC = CS.getTypeChecker();
// Walk through the destination expression, resolving what the problem is. If
// we find a node in the lvalue path that is problematic, this returns it.
auto immInfo = resolveImmutableBase(destExpr, CS);
// Otherwise, we cannot resolve this because the available setter candidates
// are all mutating and the base must be mutating. If we dug out a
// problematic decl, we can produce a nice tailored diagnostic.
if (auto *VD = dyn_cast_or_null<VarDecl>(immInfo.second)) {
std::string message = "'";
message += VD->getName().str().str();
message += "'";
if (VD->isImplicit())
message += " is immutable";
else if (VD->isLet())
message += " is a 'let' constant";
else if (!VD->isSettable(CS.DC))
message += " is a get-only property";
else if (!VD->isSetterAccessibleFrom(CS.DC))
message += " setter is inaccessible";
else {
message += " is immutable";
}
TC.diagnose(loc, diagID, message)
.highlight(immInfo.first->getSourceRange());
// If this is a simple variable marked with a 'let', emit a note to fixit
// hint it to 'var'.
VD->emitLetToVarNoteIfSimple(CS.DC);
return;
}
// If the underlying expression was a read-only subscript, diagnose that.
if (auto *SD = dyn_cast_or_null<SubscriptDecl>(immInfo.second)) {
StringRef message;
if (!SD->isSettable())
message = "subscript is get-only";
else if (!SD->isSetterAccessibleFrom(CS.DC))
message = "subscript setter is inaccessible";
else
message = "subscript is immutable";
TC.diagnose(loc, diagID, message)
.highlight(immInfo.first->getSourceRange());
return;
}
// If the expression is the result of a call, it is an rvalue, not a mutable
// lvalue.
if (auto *AE = dyn_cast<ApplyExpr>(immInfo.first)) {
// Handle literals, which are a call to the conversion function.
auto argsTuple =
dyn_cast<TupleExpr>(AE->getArg()->getSemanticsProvidingExpr());
if (isa<CallExpr>(AE) && AE->isImplicit() && argsTuple &&
argsTuple->getNumElements() == 1 &&
isa<LiteralExpr>(argsTuple->getElement(0)->
getSemanticsProvidingExpr())) {
TC.diagnose(loc, diagID, "literals are not mutable");
return;
}
std::string name = "call";
if (isa<PrefixUnaryExpr>(AE) || isa<PostfixUnaryExpr>(AE))
name = "unary operator";
else if (isa<BinaryExpr>(AE))
name = "binary operator";
else if (isa<CallExpr>(AE))
name = "function call";
else if (isa<DotSyntaxCallExpr>(AE) || isa<DotSyntaxBaseIgnoredExpr>(AE))
name = "method call";
if (auto *DRE =
dyn_cast<DeclRefExpr>(AE->getFn()->getValueProvidingExpr()))
name = std::string("'") + DRE->getDecl()->getName().str().str() + "'";
TC.diagnose(loc, diagID, name + " returns immutable value")
.highlight(AE->getSourceRange());
return;
}
if (auto *ICE = dyn_cast<ImplicitConversionExpr>(immInfo.first))
if (isa<LoadExpr>(ICE->getSubExpr())) {
TC.diagnose(loc, diagID, "implicit conversion from '" +
ICE->getSubExpr()->getType()->getString() + "' to '" +
ICE->getType()->getString() + "' requires a temporary")
.highlight(ICE->getSourceRange());
return;
}
if (auto IE = dyn_cast<IfExpr>(immInfo.first)) {
if (isLoadedLValue(IE)) {
TC.diagnose(loc, diagID,
"result of conditional operator '? :' is never mutable")
.highlight(IE->getQuestionLoc())
.highlight(IE->getColonLoc());
return;
}
}
TC.diagnose(loc, unknownDiagID, destExpr->getType())
.highlight(immInfo.first->getSourceRange());
}
namespace {
/// Each match in an ApplyExpr is evaluated for how close of a match it is.
/// The result is captured in this enum value, where the earlier entries are
/// most specific.
enum CandidateCloseness {
CC_ExactMatch, ///< This is a perfect match for the arguments.
CC_Unavailable, ///< Marked unavailable with @available.
CC_Inaccessible, ///< Not accessible from the current context.
CC_NonLValueInOut, ///< First arg is inout but no lvalue present.
CC_SelfMismatch, ///< Self argument mismatches.
CC_OneArgumentNearMismatch, ///< All arguments except one match, near miss.
CC_OneArgumentMismatch, ///< All arguments except one match.
CC_OneGenericArgumentNearMismatch, ///< All arguments except one match, guessing generic binding, near miss.
CC_OneGenericArgumentMismatch, ///< All arguments except one match, guessing generic binding.
CC_ArgumentNearMismatch, ///< Argument list mismatch, near miss.
CC_ArgumentMismatch, ///< Argument list mismatch.
CC_GenericNonsubstitutableMismatch, ///< Arguments match each other, but generic binding not substitutable.
CC_ArgumentLabelMismatch, ///< Argument label mismatch.
CC_ArgumentCountMismatch, ///< This candidate has wrong # arguments.
CC_GeneralMismatch ///< Something else is wrong.
};
/// This is a candidate for a callee, along with an uncurry level.
///
/// The uncurry level specifies how far much of a curried value has already
/// been applied. For example, in a funcdecl of:
/// func f(a:Int)(b:Double) -> Int
/// Uncurry level of 0 indicates that we're looking at the "a" argument, an
/// uncurry level of 1 indicates that we're looking at the "b" argument.
///
/// entityType specifies a specific type to use for this decl/expr that may be
/// more resolved than the concrete type. For example, it may have generic
/// arguments substituted in.
///
struct UncurriedCandidate {
PointerUnion<ValueDecl *, Expr*> declOrExpr;
unsigned level;
Type entityType;
UncurriedCandidate(ValueDecl *decl, unsigned level)
: declOrExpr(decl), level(level), entityType(decl->getType()) {
// For some reason, subscripts and properties don't include their self
// type. Tack it on for consistency with other members.
if (isa<AbstractStorageDecl>(decl)) {
if (decl->getDeclContext()->isTypeContext()) {
auto instanceTy = decl->getDeclContext()->getSelfTypeInContext();
entityType = FunctionType::get(instanceTy, entityType);
}
}
}
UncurriedCandidate(Expr *expr)
: declOrExpr(expr), level(0), entityType(expr->getType()) {
}
ValueDecl *getDecl() const {
return declOrExpr.dyn_cast<ValueDecl*>();
}
Expr *getExpr() const {
return declOrExpr.dyn_cast<Expr*>();
}
Type getUncurriedType() const {
// Start with the known type of the decl.
auto type = entityType;
for (unsigned i = 0, e = level; i != e; ++i) {
auto funcTy = type->getAs<AnyFunctionType>();
if (!funcTy) return Type();
type = funcTy->getResult();
}
return type;
}
AnyFunctionType *getUncurriedFunctionType() const {
if (auto type = getUncurriedType())
return type->getAs<AnyFunctionType>();
return nullptr;
}
/// Given a function candidate with an uncurry level, return the parameter
/// type at the specified uncurry level. If there is an error getting to
/// the specified input, this returns a null Type.
Type getArgumentType() const {
if (auto *funcTy = getUncurriedFunctionType())
return funcTy->getInput();
return Type();
}
/// Given a function candidate with an uncurry level, return the parameter
/// type at the specified uncurry level. If there is an error getting to
/// the specified input, this returns a null Type.
Type getResultType() const {
if (auto *funcTy = getUncurriedFunctionType())
return funcTy->getResult();
return Type();
}
void dump() const {
if (auto decl = getDecl())
decl->dumpRef(llvm::errs());
else
llvm::errs() << "<<EXPR>>";
llvm::errs() << " - uncurry level " << level;
if (auto FT = getUncurriedFunctionType())
llvm::errs() << " - type: " << Type(FT) << "\n";
else
llvm::errs() << " - type <<NONFUNCTION>>: " << entityType << "\n";
}
};
/// This struct represents an analyzed function pointer to determine the
/// candidates that could be called, or the one concrete decl that will be
/// called if not ambiguous.
class CalleeCandidateInfo {
public:
ConstraintSystem *const CS;
/// This is the name of the callee as extracted from the call expression.
/// This can be empty in cases like calls to closure exprs.
std::string declName;
/// True if the call site for this callee syntactically has a trailing
/// closure specified.
bool hasTrailingClosure;
/// This is the list of candidates identified.
SmallVector<UncurriedCandidate, 4> candidates;
/// This tracks how close the candidates are, after filtering.
CandidateCloseness closeness = CC_GeneralMismatch;
/// When we have a candidate that differs by a single argument mismatch, we
/// keep track of which argument passed to the call is failed, and what the
/// expected type is. If the candidate set disagrees, or if there is more
/// than a single argument mismatch, then this is "{ -1, Type() }".
struct FailedArgumentInfo {
int argumentNumber = -1; ///< Arg # at the call site.
Type parameterType = Type(); ///< Expected type at the decl site.
DeclContext *declContext = nullptr; ///< Context at the candidate declaration.
bool isValid() const { return argumentNumber != -1; }
bool operator!=(const FailedArgumentInfo &other) {
if (argumentNumber != other.argumentNumber) return true;
if (declContext != other.declContext) return true;
// parameterType can be null, and isEqual doesn't handle this.
if (!parameterType || !other.parameterType)
return parameterType.getPointer() != other.parameterType.getPointer();
return !parameterType->isEqual(other.parameterType);
}
};
FailedArgumentInfo failedArgument = FailedArgumentInfo();
/// Analyze a function expr and break it into a candidate set. On failure,
/// this leaves the candidate list empty.
CalleeCandidateInfo(Expr *Fn, bool hasTrailingClosure,
ConstraintSystem *CS)
: CS(CS), hasTrailingClosure(hasTrailingClosure) {
collectCalleeCandidates(Fn);
}
CalleeCandidateInfo(Type baseType, ArrayRef<OverloadChoice> candidates,
bool hasTrailingClosure, ConstraintSystem *CS,
bool selfAlreadyApplied = true);
typedef std::pair<CandidateCloseness, FailedArgumentInfo> ClosenessResultTy;
typedef const std::function<ClosenessResultTy(UncurriedCandidate)>
&ClosenessPredicate;
/// After the candidate list is formed, it can be filtered down to discard
/// obviously mismatching candidates and compute a "closeness" for the
/// resultant set.
ClosenessResultTy
evaluateCloseness(DeclContext *dc, Type candArgListType,
ValueDecl *candidateDecl,
unsigned level,
ArrayRef<CallArgParam> actualArgs);
void filterListArgs(ArrayRef<CallArgParam> actualArgs);
void filterList(Type actualArgsType) {
return filterListArgs(decomposeArgType(actualArgsType));
}
void filterList(ClosenessPredicate predicate);
void filterContextualMemberList(Expr *argExpr);
bool empty() const { return candidates.empty(); }
unsigned size() const { return candidates.size(); }
UncurriedCandidate operator[](unsigned i) const {
return candidates[i];
}
/// Given a set of parameter lists from an overload group, and a list of
/// arguments, emit a diagnostic indicating any partially matching
/// overloads.
void suggestPotentialOverloads(SourceLoc loc, bool isResult = false);
/// If the candidate set has been narrowed to a single parameter or single
/// archetype that has argument type errors, diagnose that error and
/// return true.
bool diagnoseGenericParameterErrors(Expr *badArgExpr);
/// Emit a diagnostic and return true if this is an error condition we can
/// handle uniformly. This should be called after filtering the candidate
/// list.
bool diagnoseSimpleErrors(const Expr *E);
void dump() const LLVM_ATTRIBUTE_USED;
private:
void collectCalleeCandidates(Expr *fnExpr);
};
}
void CalleeCandidateInfo::dump() const {
llvm::errs() << "CalleeCandidateInfo for '" << declName << "': closeness="
<< unsigned(closeness) << "\n";
llvm::errs() << candidates.size() << " candidates:\n";
for (auto c : candidates) {
llvm::errs() << " ";
c.dump();
}
}
/// Given a candidate list, this computes the narrowest closeness to the match
/// we're looking for and filters out any worse matches. The predicate
/// indicates how close a given candidate is to the desired match.
void CalleeCandidateInfo::filterList(ClosenessPredicate predicate) {
closeness = CC_GeneralMismatch;
// If we couldn't find anything, give up.
if (candidates.empty())
return;
// Now that we have the candidate list, figure out what the best matches from
// the candidate list are, and remove all the ones that aren't at that level.
SmallVector<ClosenessResultTy, 4> closenessList;
closenessList.reserve(candidates.size());
for (auto decl : candidates) {
auto declCloseness = predicate(decl);
// If we have a decl identified, refine the match.
if (auto VD = decl.getDecl()) {
// If this candidate otherwise matched but was marked unavailable, then
// treat it as unavailable, which is a very close failure.
if (declCloseness.first == CC_ExactMatch &&
VD->getAttrs().isUnavailable(CS->getASTContext()) &&
!CS->TC.getLangOpts().DisableAvailabilityChecking)
declCloseness.first = CC_Unavailable;
// Likewise, if the candidate is inaccessible from the scope it is being
// accessed from, mark it as inaccessible or a general mismatch.
if (VD->hasAccessibility() &&
!VD->isAccessibleFrom(CS->DC)) {
// If this was an exact match, downgrade it to inaccessible, so that
// accessible decls that are also an exact match will take precedence.
// Otherwise consider it to be a general mismatch so we only list it in
// an overload set as a last resort.
if (declCloseness.first == CC_ExactMatch)
declCloseness.first = CC_Inaccessible;
else
declCloseness.first = CC_GeneralMismatch;
}
}
closenessList.push_back(declCloseness);
closeness = std::min(closeness, closenessList.back().first);
}
// Now that we know the minimum closeness, remove all the elements that aren't
// as close. Keep track of argument failure information if the entire
// matching candidate set agrees.
unsigned NextElt = 0;
for (unsigned i = 0, e = candidates.size(); i != e; ++i) {
// If this decl in the result list isn't a close match, ignore it.
if (closeness != closenessList[i].first)
continue;
// Otherwise, preserve it.
candidates[NextElt++] = candidates[i];
if (NextElt == 1)
failedArgument = closenessList[i].second;
else if (failedArgument != closenessList[i].second)
failedArgument = FailedArgumentInfo();
}
candidates.erase(candidates.begin()+NextElt, candidates.end());
}
/// Given an incompatible argument being passed to a parameter, decide whether
/// it is a "near" miss or not. We consider something to be a near miss if it
/// is due to a common sort of problem (e.g. function type passed to wrong
/// function type, or T? passed to something expecting T) where a far miss is a