forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSDiag.cpp
1845 lines (1552 loc) · 69.6 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 - 2018 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 diagnostics for the type checker.
//
//===----------------------------------------------------------------------===//
#include "CSDiag.h"
#include "CSDiagnostics.h"
#include "CalleeCandidateInfo.h"
#include "ConstraintSystem.h"
#include "MiscDiagnostics.h"
#include "TypeCheckAvailability.h"
#include "TypoCorrection.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeMatcher.h"
#include "swift/AST/TypeWalker.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/StringExtras.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace constraints;
namespace swift {
Type replaceTypeParametersWithUnresolved(Type ty) {
if (!ty) return ty;
if (!ty->hasTypeParameter() && !ty->hasArchetype()) return ty;
auto &ctx = ty->getASTContext();
return ty.transform([&](Type type) -> Type {
if (type->is<ArchetypeType>() ||
type->isTypeParameter())
return ctx.TheUnresolvedType;
return type;
});
}
Type replaceTypeVariablesWithUnresolved(Type ty) {
if (!ty) return ty;
if (!ty->hasTypeVariable()) return ty;
auto &ctx = ty->getASTContext();
return ty.transform([&](Type type) -> Type {
if (type->isTypeVariableOrMember())
return ctx.TheUnresolvedType;
return type;
});
}
};
static bool isUnresolvedOrTypeVarType(Type ty) {
return ty->isTypeVariableOrMember() || ty->is<UnresolvedType>();
}
/// Flags that can be used to control name lookup.
enum TCCFlags {
/// Allow the result of the subexpression to be an lvalue. If this is not
/// specified, any lvalue will be forced to be loaded into an rvalue.
TCC_AllowLValue = 0x01,
/// Re-type-check the given subexpression even if the expression has already
/// been checked already. The client is asserting that infinite recursion is
/// not possible because it has relaxed a constraint on the system.
TCC_ForceRecheck = 0x02,
/// tell typeCheckExpression that it is ok to produce an ambiguous result,
/// it can just fill in holes with UnresolvedType and we'll deal with it.
TCC_AllowUnresolvedTypeVariables = 0x04
};
using TCCOptions = OptionSet<TCCFlags>;
inline TCCOptions operator|(TCCFlags flag1, TCCFlags flag2) {
return TCCOptions(flag1) | flag2;
}
namespace {
/// If a constraint system fails to converge on a solution for a given
/// expression, this class can produce a reasonable diagnostic for the failure
/// by analyzing the remnants of the failed constraint system. (Specifically,
/// left-over inactive, active and failed constraints.)
/// This class does not tune its diagnostics for a specific expression kind,
/// for that, you'll want to use an instance of the FailureDiagnosis class.
class FailureDiagnosis :public ASTVisitor<FailureDiagnosis, /*exprresult*/bool>{
friend class ASTVisitor<FailureDiagnosis, /*exprresult*/bool>;
Expr *expr = nullptr;
ConstraintSystem &CS;
public:
FailureDiagnosis(Expr *expr, ConstraintSystem &cs) : expr(expr), CS(cs) {
assert(expr);
}
template<typename ...ArgTypes>
InFlightDiagnostic diagnose(ArgTypes &&...Args) {
return CS.getASTContext().Diags.diagnose(std::forward<ArgTypes>(Args)...);
}
/// Unless we've already done this, retypecheck the specified child of the
/// current expression on its own, without including any contextual
/// constraints or the parent expr nodes. This is more likely to succeed than
/// type checking the original expression.
///
/// This mention may only be used on immediate children of the current expr
/// node, because ClosureExpr parameters need to be treated specially.
///
/// This can return a new expression (for e.g. when a UnresolvedDeclRef gets
/// resolved) and returns null when the subexpression fails to typecheck.
///
Expr *typeCheckChildIndependently(
Expr *subExpr, Type convertType = Type(),
ContextualTypePurpose convertTypePurpose = CTP_Unused,
TCCOptions options = TCCOptions(),
ExprTypeCheckListener *listener = nullptr,
bool allowFreeTypeVariables = true);
Expr *typeCheckChildIndependently(Expr *subExpr, TCCOptions options,
bool allowFreeTypeVariables = true) {
return typeCheckChildIndependently(subExpr, Type(), CTP_Unused, options,
nullptr, allowFreeTypeVariables);
}
Type getTypeOfTypeCheckedChildIndependently(Expr *subExpr,
TCCOptions options = TCCOptions()) {
auto e = typeCheckChildIndependently(subExpr, options);
return e ? CS.getType(e) : Type();
}
/// Find a nearest declaration context which could be used
/// to type-check this sub-expression.
DeclContext *findDeclContext(Expr *subExpr) const;
/// Special magic to handle inout exprs and tuples in argument lists.
Expr *typeCheckArgumentChildIndependently(Expr *argExpr, Type argType,
const CalleeCandidateInfo &candidates,
TCCOptions options = TCCOptions());
void getPossibleTypesOfExpressionWithoutApplying(
Expr *&expr, DeclContext *dc, SmallPtrSetImpl<TypeBase *> &types,
FreeTypeVariableBinding allowFreeTypeVariables =
FreeTypeVariableBinding::Disallow,
ExprTypeCheckListener *listener = nullptr) {
TypeChecker::getPossibleTypesOfExpressionWithoutApplying(
expr, dc, types, allowFreeTypeVariables, listener);
CS.cacheExprTypes(expr);
}
Type getTypeOfExpressionWithoutApplying(
Expr *&expr, DeclContext *dc, ConcreteDeclRef &referencedDecl,
FreeTypeVariableBinding allowFreeTypeVariables =
FreeTypeVariableBinding::Disallow,
ExprTypeCheckListener *listener = nullptr) {
auto type =
TypeChecker::getTypeOfExpressionWithoutApplying(expr, dc,
referencedDecl,
allowFreeTypeVariables,
listener);
CS.cacheExprTypes(expr);
return type;
}
/// Diagnose common failures due to applications of an argument list to an
/// ApplyExpr or SubscriptExpr.
bool diagnoseParameterErrors(CalleeCandidateInfo &CCI,
Expr *fnExpr, Expr *argExpr,
ArrayRef<Identifier> argLabels);
/// Attempt to diagnose a specific failure from the info we've collected from
/// the failed constraint system.
bool diagnoseExprFailure();
/// Emit an ambiguity diagnostic about the specified expression.
void diagnoseAmbiguity(Expr *E);
/// Attempt to produce a diagnostic for a mismatch between an expression's
/// type and its assumed contextual type.
bool diagnoseContextualConversionError(Expr *expr, Type contextualType,
ContextualTypePurpose CTP,
Type suggestedType = Type());
bool diagnoseImplicitSelfErrors(Expr *fnExpr, Expr *argExpr,
CalleeCandidateInfo &CCI,
ArrayRef<Identifier> argLabels);
private:
/// Validate potential contextual type for type-checking one of the
/// sub-expressions, usually correct/valid types are the ones which
/// either don't have type variables or are not generic, because
/// generic types with left-over type variables or unresolved types
/// degrade quality of diagnostics if allowed to be used as contextual.
///
/// \param contextualType The candidate contextual type.
/// \param CTP The contextual purpose attached to the given candidate.
///
/// \returns Pair of validated type and it's purpose, potentially nullified
/// if it wasn't an appropriate type to be used.
std::pair<Type, ContextualTypePurpose>
validateContextualType(Type contextualType, ContextualTypePurpose CTP);
bool visitExpr(Expr *E);
bool visitTryExpr(TryExpr *E);
bool visitApplyExpr(ApplyExpr *AE);
bool visitRebindSelfInConstructorExpr(RebindSelfInConstructorExpr *E);
};
} // end anonymous namespace
namespace {
class ExprTypeSaverAndEraser {
llvm::DenseMap<Expr*, Type> ExprTypes;
llvm::DenseMap<TypeLoc*, Type> TypeLocTypes;
llvm::DenseMap<Pattern*, Type> PatternTypes;
ExprTypeSaverAndEraser(const ExprTypeSaverAndEraser&) = delete;
void operator=(const ExprTypeSaverAndEraser&) = delete;
public:
ExprTypeSaverAndEraser(Expr *E) {
struct TypeSaver : public ASTWalker {
ExprTypeSaverAndEraser *TS;
TypeSaver(ExprTypeSaverAndEraser *TS) : TS(TS) {}
std::pair<bool, Expr *> walkToExprPre(Expr *expr) override {
TS->ExprTypes[expr] = expr->getType();
SWIFT_DEFER {
assert((!expr->getType() || !expr->getType()->hasTypeVariable()
// FIXME: We shouldn't allow these, either.
|| isa<LiteralExpr>(expr)) &&
"Type variable didn't get erased!");
};
// Preserve module expr type data to prevent further lookups.
if (auto *declRef = dyn_cast<DeclRefExpr>(expr))
if (isa<ModuleDecl>(declRef->getDecl()))
return { false, expr };
// Don't strip type info off OtherConstructorDeclRefExpr, because
// CSGen doesn't know how to reconstruct it.
if (isa<OtherConstructorDeclRefExpr>(expr))
return { false, expr };
// If a literal has a Builtin.Int or Builtin.FP type on it already,
// then sema has already expanded out a call to
// Init.init(<builtinliteral>)
// and we don't want it to make
// Init.init(Init.init(<builtinliteral>))
// preserve the type info to prevent this from happening.
if (isa<LiteralExpr>(expr) && !isa<InterpolatedStringLiteralExpr>(expr) &&
!(expr->getType() && expr->getType()->hasError()))
return { false, expr };
expr->setType(nullptr);
return { true, expr };
}
// If we find a TypeLoc (e.g. in an as? expr), save and erase it.
bool walkToTypeLocPre(TypeLoc &TL) override {
if (TL.getTypeRepr() && TL.getType()) {
TS->TypeLocTypes[&TL] = TL.getType();
TL.setType(Type());
}
return true;
}
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
if (P->hasType()) {
TS->PatternTypes[P] = P->getType();
P->setType(Type());
}
return { true, P };
}
// Don't walk into statements. This handles the BraceStmt in
// non-single-expr closures, so we don't walk into their body.
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
return { false, S };
}
};
E->walk(TypeSaver(this));
}
void restore() {
for (auto exprElt : ExprTypes)
exprElt.first->setType(exprElt.second);
for (auto typelocElt : TypeLocTypes)
typelocElt.first->setType(typelocElt.second);
for (auto patternElt : PatternTypes)
patternElt.first->setType(patternElt.second);
// Done, don't do redundant work on destruction.
ExprTypes.clear();
TypeLocTypes.clear();
PatternTypes.clear();
}
// On destruction, if a type got wiped out, reset it from null to its
// original type. This is helpful because type checking a subexpression
// can lead to replacing the nodes in that subexpression. However, the
// failed ConstraintSystem still has locators pointing to the old nodes,
// and if expr-specific diagnostics fail to turn up anything useful to say,
// we go digging through failed constraints, and expect their locators to
// still be meaningful.
~ExprTypeSaverAndEraser() {
for (auto exprElt : ExprTypes)
if (!exprElt.first->getType())
exprElt.first->setType(exprElt.second);
for (auto typelocElt : TypeLocTypes)
if (!typelocElt.first->getType())
typelocElt.first->setType(typelocElt.second);
for (auto patternElt : PatternTypes)
if (!patternElt.first->hasType())
patternElt.first->setType(patternElt.second);
}
};
} // end anonymous namespace
/// Unless we've already done this, retypecheck the specified subexpression on
/// its own, without including any contextual constraints or parent expr
/// nodes. This is more likely to succeed than type checking the original
/// expression.
///
/// This can return a new expression (for e.g. when a UnresolvedDeclRef gets
/// resolved) and returns null when the subexpression fails to typecheck.
Expr *FailureDiagnosis::typeCheckChildIndependently(
Expr *subExpr, Type convertType, ContextualTypePurpose convertTypePurpose,
TCCOptions options, ExprTypeCheckListener *listener,
bool allowFreeTypeVariables) {
// If this sub-expression is currently being diagnosed, refuse to recheck the
// expression (which may lead to infinite recursion). If the client is
// telling us that it knows what it is doing, then believe it.
if (!options.contains(TCC_ForceRecheck)) {
if (CS.isExprBeingDiagnosed(subExpr)) {
auto *savedExpr = CS.getExprBeingDiagnosed(subExpr);
if (subExpr == savedExpr)
return subExpr;
CS.cacheExprTypes(savedExpr);
return savedExpr;
}
}
// Mark current expression as about to be diagnosed.
CS.addExprForDiagnosis(subExpr, subExpr);
// Validate contextual type before trying to use it.
std::tie(convertType, convertTypePurpose) =
validateContextualType(convertType, convertTypePurpose);
// If we have no contextual type information and the subexpr is obviously a
// overload set, don't recursively simplify this. The recursive solver will
// sometimes pick one based on arbitrary ranking behavior (e.g. like
// which is the most specialized) even then all the constraints are being
// fulfilled by UnresolvedType, which doesn't tell us anything.
if (convertTypePurpose == CTP_Unused &&
(isa<OverloadedDeclRefExpr>(subExpr->getValueProvidingExpr()))) {
return subExpr;
}
// Save any existing type data of the subexpr tree, and reset it to null in
// prep for re-type-checking the tree. If things fail, we can revert the
// types back to their original state.
ExprTypeSaverAndEraser SavedTypeData(subExpr);
// Store off the sub-expression, in case a new one is provided via the
// type check operation.
Expr *preCheckedExpr = subExpr;
// Disable structural checks, because we know that the overall expression
// has type constraint problems, and we don't want to know about any
// syntactic issues in a well-typed subexpression (which might be because
// the context is missing).
TypeCheckExprOptions TCEOptions = TypeCheckExprFlags::DisableStructuralChecks;
// Make sure that typechecker knows that this is an attempt
// to diagnose a problem.
TCEOptions |= TypeCheckExprFlags::SubExpressionDiagnostics;
// Claim that the result is discarded to preserve the lvalue type of
// the expression.
if (options.contains(TCC_AllowLValue))
TCEOptions |= TypeCheckExprFlags::IsDiscarded;
// If there is no contextual type available, tell typeCheckExpression that it
// is ok to produce an ambiguous result, it can just fill in holes with
// UnresolvedType and we'll deal with it.
if ((!convertType || options.contains(TCC_AllowUnresolvedTypeVariables)) &&
allowFreeTypeVariables)
TCEOptions |= TypeCheckExprFlags::AllowUnresolvedTypeVariables;
// When we're type checking a single-expression closure, we need to reset the
// DeclContext to this closure for the recursive type checking. Otherwise,
// if there is a closure in the subexpression, we can violate invariants.
auto *DC = findDeclContext(subExpr);
auto resultTy =
TypeChecker::typeCheckExpression(subExpr, DC,
TypeLoc::withoutLoc(convertType),
convertTypePurpose, TCEOptions,
listener, &CS);
CS.cacheExprTypes(subExpr);
// This is a terrible hack to get around the fact that typeCheckExpression()
// might change subExpr to point to a new OpenExistentialExpr. In that case,
// since the caller passed subExpr by value here, they would be left
// holding on to an expression containing open existential types but
// no OpenExistentialExpr, which breaks invariants enforced by the
// ASTChecker.
// Another reason why we need to do this is because diagnostics might pick
// constraint anchor for re-typechecking which would only have opaque value
// expression and not enclosing open existential, which is going to trip up
// sanitizer.
eraseOpenedExistentials(CS, subExpr);
// If recursive type checking failed, then an error was emitted. Return
// null to indicate this to the caller.
if (!resultTy)
return nullptr;
// If we type checked the result but failed to get a usable output from it,
// just pretend as though nothing happened.
if (resultTy->is<ErrorType>()) {
subExpr = preCheckedExpr;
if (subExpr->getType())
CS.cacheType(subExpr);
SavedTypeData.restore();
}
if (preCheckedExpr != subExpr)
CS.addExprForDiagnosis(preCheckedExpr, subExpr);
return subExpr;
}
DeclContext *FailureDiagnosis::findDeclContext(Expr *subExpr) const {
if (auto *closure =
dyn_cast<ClosureExpr>(subExpr->getSemanticsProvidingExpr()))
return closure->getParent();
struct DCFinder : public ASTWalker {
DeclContext *DC, *CurrDC;
Expr *SubExpr;
DCFinder(DeclContext *DC, Expr *expr) : DC(DC), CurrDC(DC), SubExpr(expr) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (E == SubExpr) {
DC = CurrDC;
return {false, nullptr};
}
if (auto *closure = dyn_cast<ClosureExpr>(E)) {
CurrDC = closure;
// If we have a ClosureExpr parent of the specified node, check to make
// sure none of its arguments are type variables. If so, these type
// variables would be accessible to name lookup of the subexpression and
// may thus leak in. Reset them to UnresolvedTypes for safe measures.
assert(llvm::all_of(*closure->getParameters(), [](const ParamDecl *PD) {
if (PD->hasInterfaceType()) {
auto paramTy = PD->getType();
return !(paramTy->hasTypeVariable() || paramTy->hasError());
}
return true;
}));
}
return {true, E};
}
Expr *walkToExprPost(Expr *E) override {
if (auto *closure = dyn_cast<ClosureExpr>(E)) {
assert(CurrDC == closure && "DeclContext imbalance");
CurrDC = closure->getParent();
}
return E;
}
} finder(CS.DC, subExpr);
expr->walk(finder);
return finder.DC;
}
bool FailureDiagnosis::diagnoseContextualConversionError(
Expr *expr, Type contextualType, ContextualTypePurpose CTP,
Type suggestedType) {
// If the constraint system has a contextual type, then we can test to see if
// this is the problem that prevents us from solving the system.
if (!contextualType)
return false;
// Try re-type-checking the expression without the contextual type to see if
// it can work without it. If so, the contextual type is the problem. We
// force a recheck, because "expr" is likely in our table with the extra
// contextual constraint that we know we are relaxing.
TCCOptions options = TCC_ForceRecheck;
if (contextualType->is<InOutType>())
options |= TCC_AllowLValue;
auto *recheckedExpr = typeCheckChildIndependently(expr, options);
auto exprType = recheckedExpr ? CS.getType(recheckedExpr) : Type();
// If there is a suggested type and re-typecheck failed, let's use it.
if (!exprType)
exprType = suggestedType;
// If it failed and diagnosed something, then we're done.
if (!exprType)
return CS.getASTContext().Diags.hadAnyError();
// If we don't have a type for the expression, then we cannot use it in
// conversion constraint diagnostic generation. If the types match, then it
// must not be the contextual type that is the problem.
if (isUnresolvedOrTypeVarType(exprType) || exprType->isEqual(contextualType))
return false;
// Don't attempt fixits if we have an unsolved type variable, since
// the recovery path's recursion into the type checker via typeCheckCast()
// will confuse matters.
if (exprType->hasTypeVariable())
return false;
ContextualFailure failure(
CS, CTP, exprType, contextualType,
CS.getConstraintLocator(expr, LocatorPathElt::ContextualType()));
return failure.diagnoseAsError();
}
//===----------------------------------------------------------------------===//
// Diagnose assigning variable to itself.
//===----------------------------------------------------------------------===//
static bool isSymmetricBinaryOperator(const CalleeCandidateInfo &CCI) {
// If we don't have at least one known candidate, don't trigger.
if (CCI.candidates.empty()) return false;
for (auto &candidate : CCI.candidates) {
// Each candidate must be a non-assignment operator function.
auto decl = dyn_cast_or_null<FuncDecl>(candidate.getDecl());
if (!decl) return false;
auto op = dyn_cast_or_null<InfixOperatorDecl>(decl->getOperatorDecl());
if (!op || !op->getPrecedenceGroup() ||
op->getPrecedenceGroup()->isAssignment())
return false;
// It must have exactly two parameters.
auto params = decl->getParameters();
if (params->size() != 2) return false;
// Require the types to be the same.
if (!params->get(0)->getInterfaceType()->isEqual(
params->get(1)->getInterfaceType()))
return false;
}
return true;
}
/// Determine whether any of the given callee candidates have a default value.
static bool candidatesHaveAnyDefaultValues(
const CalleeCandidateInfo &candidates) {
for (const auto &cand : candidates.candidates) {
auto function = dyn_cast_or_null<AbstractFunctionDecl>(cand.getDecl());
if (!function) continue;
if (function->hasImplicitSelfDecl()) {
if (!cand.skipCurriedSelf)
return false;
} else {
if (cand.skipCurriedSelf)
return false;
}
for (auto param : *function->getParameters()) {
if (param->getDefaultArgumentKind() != DefaultArgumentKind::None)
return true;
}
}
return false;
}
/// Find the tuple element that can be initialized by a scalar.
static Optional<unsigned> getElementForScalarInitOfArg(
const TupleType *tupleTy,
const CalleeCandidateInfo &candidates) {
// Empty tuples cannot be initialized with a scalar.
if (tupleTy->getNumElements() == 0) return None;
auto getElementForScalarInitSimple =
[](const TupleType *tupleTy) -> Optional<unsigned> {
Optional<unsigned> result = None;
for (unsigned i = 0, e = tupleTy->getNumElements(); i != e; ++i) {
// If we already saw a non-vararg field, then we have more than
// one candidate field.
if (result.hasValue()) {
// Vararg fields are okay; they'll just end up being empty.
if (tupleTy->getElement(i).isVararg())
continue;
// Give up.
return None;
}
// Otherwise, remember this field number.
result = i;
}
return result;
};
// If there aren't any candidates, we're done.
if (candidates.empty()) return getElementForScalarInitSimple(tupleTy);
// Dig out the candidate.
const auto &cand = candidates[0];
auto function = dyn_cast_or_null<AbstractFunctionDecl>(cand.getDecl());
if (!function) return getElementForScalarInitSimple(tupleTy);
if (function->hasImplicitSelfDecl()) {
if (!cand.skipCurriedSelf)
return getElementForScalarInitSimple(tupleTy);
} else {
if (cand.skipCurriedSelf)
return getElementForScalarInitSimple(tupleTy);
}
auto paramList = function->getParameters();
if (tupleTy->getNumElements() != paramList->size())
return getElementForScalarInitSimple(tupleTy);
// Find a tuple element without a default.
Optional<unsigned> elementWithoutDefault;
for (unsigned i : range(tupleTy->getNumElements())) {
auto param = paramList->get(i);
// Skip parameters with default arguments.
if (param->getDefaultArgumentKind() != DefaultArgumentKind::None)
continue;
// If we already have an element without a default, check whether there are
// two fields that need initialization.
if (elementWithoutDefault) {
// Variadic fields are okay; they'll just end up being empty.
if (param->isVariadic()) continue;
// If the element we saw before was variadic, it can be empty as well.
auto priorParam = paramList->get(*elementWithoutDefault);
if (!priorParam->isVariadic()) return None;
}
elementWithoutDefault = i;
}
if (elementWithoutDefault) return elementWithoutDefault;
// All of the fields have default values; initialize the first one.
return 0;
}
/// Return true if the argument of a CallExpr (or related node) has a trailing
/// closure.
static bool callArgHasTrailingClosure(Expr *E) {
if (!E) return false;
if (auto *PE = dyn_cast<ParenExpr>(E))
return PE->hasTrailingClosure();
else if (auto *TE = dyn_cast<TupleExpr>(E))
return TE->hasTrailingClosure();
return false;
}
/// Special magic to handle inout exprs and tuples in argument lists.
Expr *FailureDiagnosis::
typeCheckArgumentChildIndependently(Expr *argExpr, Type argType,
const CalleeCandidateInfo &candidates,
TCCOptions options) {
// Grab one of the candidates (if present) and get its input list to help
// identify operators that have implicit inout arguments.
Type exampleInputType;
if (!candidates.empty()) {
exampleInputType = candidates[0].getArgumentType(CS.getASTContext());
// If we found a single candidate, and have no contextually known argument
// type information, use that one candidate as the type information for
// subexpr checking.
//
// TODO: If all candidates have the same type for some argument, we could
// pass down partial information.
if (candidates.size() == 1 && !argType)
argType = candidates[0].getArgumentType(CS.getASTContext());
}
// If our candidates are instance members at curry level #0, then the argument
// being provided is the receiver type for the instance. We produce better
// diagnostics when we don't force the self type down.
if (argType && !candidates.empty())
if (auto decl = candidates[0].getDecl())
if (decl->isInstanceMember() && !candidates[0].skipCurriedSelf &&
!isa<SubscriptDecl>(decl))
argType = Type();
// Similarly, we get better results when we don't push argument types down
// to symmetric operators.
if (argType && isSymmetricBinaryOperator(candidates))
argType = Type();
// FIXME: This should all just be a matter of getting the type of the
// sub-expression, but this doesn't work well when typeCheckChildIndependently
// is over-conservative w.r.t. TupleExprs.
auto *TE = dyn_cast<TupleExpr>(argExpr);
if (!TE) {
// If the argument isn't a tuple, it is some scalar value for a
// single-argument call.
if (exampleInputType && exampleInputType->is<InOutType>())
options |= TCC_AllowLValue;
// If the argtype is a tuple type with default arguments, or a labeled tuple
// with a single element, pull the scalar element type for the subexpression
// out. If we can't do that and the tuple has default arguments, we have to
// punt on passing down the type information, since type checking the
// subexpression won't be able to find the default argument provider.
if (argType) {
if (auto *PT = dyn_cast<ParenType>(argType.getPointer())) {
const auto &flags = PT->getParameterFlags();
if (flags.isAutoClosure()) {
auto resultTy = PT->castTo<FunctionType>()->getResult();
argType = ParenType::get(PT->getASTContext(), resultTy);
}
} else if (auto argTT = argType->getAs<TupleType>()) {
if (auto scalarElt = getElementForScalarInitOfArg(argTT, candidates)) {
// If we found the single argument being initialized, use it.
auto &arg = argTT->getElement(*scalarElt);
// If the argument being specified is actually varargs, then we're
// just specifying one element of a variadic list. Use the type of
// the individual varargs argument, not the overall array type.
if (arg.isVararg())
argType = arg.getVarargBaseTy();
else if (arg.isAutoClosure())
argType = arg.getType()->castTo<FunctionType>()->getResult();
else
argType = arg.getType();
} else if (candidatesHaveAnyDefaultValues(candidates)) {
argType = Type();
}
} else if (candidatesHaveAnyDefaultValues(candidates)) {
argType = Type();
}
}
auto CTPurpose = argType ? CTP_CallArgument : CTP_Unused;
return typeCheckChildIndependently(argExpr, argType, CTPurpose, options);
}
// If we know the requested argType to use, use computeTupleShuffle to produce
// the shuffle of input arguments to destination values. It requires a
// TupleType to compute the mapping from argExpr. Conveniently, it doesn't
// care about the actual types though, so we can just use 'void' for them.
// FIXME: This doesn't need to be limited to tuple types.
if (argType && argType->is<TupleType>()) {
// Decompose the parameter type.
SmallVector<AnyFunctionType::Param, 4> params;
AnyFunctionType::decomposeInput(argType, params);
// If we have a candidate function around, compute the position of its
// default arguments.
ParameterListInfo paramInfo;
if (!candidates.empty()) {
paramInfo = candidates[0].getParameterListInfo(params);
} else {
paramInfo = ParameterListInfo(params, nullptr, /*skipCurriedSelf=*/false);
}
// Form a set of call arguments, using a dummy type (Void), because the
// argument/parameter matching code doesn't need it.
auto voidTy = CS.getASTContext().TheEmptyTupleType;
SmallVector<AnyFunctionType::Param, 4> args;
for (unsigned i = 0, e = TE->getNumElements(); i != e; ++i) {
args.push_back(AnyFunctionType::Param(voidTy, TE->getElementName(i), {}));
}
/// Use a match call argument listener that allows relabeling.
struct RelabelMatchCallArgumentListener : MatchCallArgumentListener {
bool relabelArguments(ArrayRef<Identifier> newNames) override {
return false;
}
} listener;
SmallVector<ParamBinding, 4> paramBindings;
if (!matchCallArguments(args, params, paramInfo,
callArgHasTrailingClosure(argExpr),
/*allowFixes=*/true,
listener, paramBindings)) {
SmallVector<Expr*, 4> resultElts(TE->getNumElements(), nullptr);
SmallVector<TupleTypeElt, 4> resultEltTys(TE->getNumElements(), voidTy);
// Perform analysis of the input elements.
for (unsigned paramIdx : range(paramBindings.size())) {
// Extract the parameter.
const auto ¶m = params[paramIdx];
// Determine the parameter type.
if (param.isInOut())
options |= TCC_AllowLValue;
// Look at each of the arguments assigned to this parameter.
auto currentParamType = param.getOldType();
// Since this is diagnostics, let's make sure that parameter
// marked as @autoclosure indeed has a function type, because
// it can also be an error type and possibly unresolved type.
if (param.isAutoClosure()) {
if (auto *funcType = currentParamType->getAs<FunctionType>())
currentParamType = funcType->getResult();
}
for (auto inArgNo : paramBindings[paramIdx]) {
// Determine the argument type.
auto currentArgType = TE->getElement(inArgNo);
auto exprResult =
typeCheckChildIndependently(currentArgType, currentParamType,
CTP_CallArgument, options);
// If there was an error type checking this argument, then we're done.
if (!exprResult)
return nullptr;
auto resultTy = CS.getType(exprResult);
resultElts[inArgNo] = exprResult;
resultEltTys[inArgNo] = {resultTy->getInOutObjectType(),
TE->getElementName(inArgNo),
ParameterTypeFlags().withInOut(resultTy->is<InOutType>())};
}
}
auto TT = TupleType::get(resultEltTys, CS.getASTContext());
return CS.cacheType(TupleExpr::create(
CS.getASTContext(), TE->getLParenLoc(), resultElts,
TE->getElementNames(), TE->getElementNameLocs(), TE->getRParenLoc(),
TE->hasTrailingClosure(), TE->isImplicit(), TT));
}
}
// Get the simplified type of each element and rebuild the aggregate.
SmallVector<TupleTypeElt, 4> resultEltTys;
SmallVector<Expr*, 4> resultElts;
TupleType *exampleInputTuple = nullptr;
if (exampleInputType)
exampleInputTuple = exampleInputType->getAs<TupleType>();
for (unsigned i = 0, e = TE->getNumElements(); i != e; i++) {
if (exampleInputTuple && i < exampleInputTuple->getNumElements() &&
exampleInputTuple->getElement(i).isInOut())
options |= TCC_AllowLValue;
auto elExpr = typeCheckChildIndependently(TE->getElement(i), options);
if (!elExpr) return nullptr; // already diagnosed.
resultElts.push_back(elExpr);
auto resFlags =
ParameterTypeFlags().withInOut(elExpr->isSemanticallyInOutExpr());
resultEltTys.push_back({CS.getType(elExpr)->getInOutObjectType(),
TE->getElementName(i), resFlags});
}
auto TT = TupleType::get(resultEltTys, CS.getASTContext());
return CS.cacheType(TupleExpr::create(
CS.getASTContext(), TE->getLParenLoc(), resultElts, TE->getElementNames(),
TE->getElementNameLocs(), TE->getRParenLoc(), TE->hasTrailingClosure(),
TE->isImplicit(), TT));
}
static DeclName getBaseName(DeclContext *context) {
if (auto generic = context->getSelfNominalTypeDecl()) {
return generic->getName();
} else if (context->isModuleScopeContext())
return context->getParentModule()->getName();
else
llvm_unreachable("Unsupported base");
};
static void emitFixItForExplicitlyQualifiedReference(
DiagnosticEngine &de, UnresolvedDotExpr *UDE,
decltype(diag::fix_unqualified_access_top_level) diag, DeclName baseName,
DescriptiveDeclKind kind) {
auto name = baseName.getBaseIdentifier();
SmallString<32> namePlusDot = name.str();
namePlusDot.push_back('.');
de.diagnose(UDE->getLoc(), diag, namePlusDot, kind, name)
.fixItInsert(UDE->getStartLoc(), namePlusDot);
}
void ConstraintSystem::diagnoseDeprecatedConditionalConformanceOuterAccess(
UnresolvedDotExpr *UDE, ValueDecl *choice) {
auto result =
TypeChecker::lookupUnqualified(DC, UDE->getName(), UDE->getLoc());
assert(result && "names can't just disappear");
// These should all come from the same place.
auto exampleInner = result.front();
auto innerChoice = exampleInner.getValueDecl();
auto innerDC = exampleInner.getDeclContext()->getInnermostTypeContext();
auto innerParentDecl = innerDC->getSelfNominalTypeDecl();
auto innerBaseName = getBaseName(innerDC);
auto choiceKind = choice->getDescriptiveKind();
auto choiceDC = choice->getDeclContext();
auto choiceBaseName = getBaseName(choiceDC);
auto choiceParentDecl = choiceDC->getAsDecl();
auto choiceParentKind = choiceParentDecl
? choiceParentDecl->getDescriptiveKind()
: DescriptiveDeclKind::Module;
auto &DE = getASTContext().Diags;
DE.diagnose(UDE->getLoc(),
diag::warn_deprecated_conditional_conformance_outer_access,
UDE->getName(), choiceKind, choiceParentKind, choiceBaseName,
innerChoice->getDescriptiveKind(),
innerParentDecl->getDescriptiveKind(), innerBaseName);
emitFixItForExplicitlyQualifiedReference(
getASTContext().Diags, UDE,
diag::fix_deprecated_conditional_conformance_outer_access,
choiceBaseName, choiceKind);
}
static SmallVector<AnyFunctionType::Param, 4>
decomposeArgType(Type argType, ArrayRef<Identifier> argLabels) {
SmallVector<AnyFunctionType::Param, 4> result;
AnyFunctionType::decomposeInput(argType, result);
AnyFunctionType::relabelParams(result, argLabels);
return result;
}
bool FailureDiagnosis::diagnoseImplicitSelfErrors(
Expr *fnExpr, Expr *argExpr, CalleeCandidateInfo &CCI,
ArrayRef<Identifier> argLabels) {
// If candidate list is empty it means that problem is somewhere else,
// since we need to have candidates which might be shadowing other funcs.
if (CCI.empty() || !CCI[0].getDecl())
return false;
auto &ctx = CS.getASTContext();
// Call expression is formed as 'foo.bar' where 'foo' might be an
// implicit "Self" reference, such use wouldn't provide good diagnostics
// for situations where instance members have equal names to functions in
// Swift Standard Library e.g. min/max.
auto UDE = dyn_cast<UnresolvedDotExpr>(fnExpr);
if (!UDE)
return false;
auto baseExpr = dyn_cast<DeclRefExpr>(UDE->getBase());
if (!baseExpr)
return false;
auto baseDecl = baseExpr->getDecl();
if (!baseExpr->isImplicit() || baseDecl->getFullName() != ctx.Id_self)
return false;
// Our base expression is an implicit 'self.' reference e.g.
//
// extension Sequence {
// func test() -> Int {
// return max(1, 2)
// }
// }
//
// In this example the Sequence class already has two methods named 'max'