forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCSDiagnostics.cpp
6957 lines (5810 loc) · 233 KB
/
CSDiagnostics.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
//===--- CSDiagnostics.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 constraint system.
//
//===----------------------------------------------------------------------===//
#include "CSDiagnostics.h"
#include "ConstraintSystem.h"
#include "MiscDiagnostics.h"
#include "TypeCheckProtocol.h"
#include "TypoCorrection.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/ProtocolConformanceRef.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/Types.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/Parse/Lexer.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SmallString.h"
#include <string>
using namespace swift;
using namespace constraints;
static bool hasFixFor(const Solution &solution, ConstraintLocator *locator) {
return llvm::any_of(solution.Fixes, [&locator](const ConstraintFix *fix) {
return fix->getLocator() == locator;
});
}
FailureDiagnostic::~FailureDiagnostic() {}
bool FailureDiagnostic::diagnose(bool asNote) {
return asNote ? diagnoseAsNote() : diagnoseAsError();
}
bool FailureDiagnostic::diagnoseAsNote() {
return false;
}
ASTNode FailureDiagnostic::getAnchor() const {
auto *locator = getLocator();
// Resolve the locator to a specific expression.
auto anchor = locator->getAnchor();
{
SourceRange range;
auto path = locator->getPath();
simplifyLocator(anchor, path, range);
if (!anchor)
return locator->getAnchor();
}
// FIXME: Work around an odd locator representation that doesn't separate the
// base of a subscript member from the member access.
if (locator->isLastElement<LocatorPathElt::SubscriptMember>()) {
if (auto subscript = getAsExpr<SubscriptExpr>(anchor))
anchor = subscript->getBase();
}
return anchor;
}
Type FailureDiagnostic::getType(ASTNode node, bool wantRValue) const {
return resolveType(getRawType(node), /*reconstituteSugar=*/false, wantRValue);
}
Type FailureDiagnostic::getRawType(ASTNode node) const {
return S.getType(node);
}
template <typename... ArgTypes>
InFlightDiagnostic
FailureDiagnostic::emitDiagnostic(ArgTypes &&... Args) const {
return emitDiagnosticAt(getLoc(), std::forward<ArgTypes>(Args)...);
}
template <typename... ArgTypes>
InFlightDiagnostic
FailureDiagnostic::emitDiagnosticAt(ArgTypes &&... Args) const {
auto &DE = getASTContext().Diags;
return DE.diagnose(std::forward<ArgTypes>(Args)...);
}
Expr *FailureDiagnostic::findParentExpr(const Expr *subExpr) const {
auto &cs = getConstraintSystem();
return cs.getParentExpr(const_cast<Expr *>(subExpr));
}
Expr *
FailureDiagnostic::getArgumentListExprFor(ConstraintLocator *locator) const {
auto path = locator->getPath();
auto iter = path.begin();
if (!locator->findFirst<LocatorPathElt::ApplyArgument>(iter))
return nullptr;
// Form a new locator that ends at the ApplyArgument element, then simplify
// to get the argument list.
auto newPath = ArrayRef<LocatorPathElt>(path.begin(), iter + 1);
auto argListLoc = getConstraintLocator(locator->getAnchor(), newPath);
return getAsExpr(simplifyLocatorToAnchor(argListLoc));
}
Expr *FailureDiagnostic::getBaseExprFor(const Expr *anchor) const {
if (!anchor)
return nullptr;
if (auto *UDE = dyn_cast<UnresolvedDotExpr>(anchor))
return UDE->getBase();
else if (auto *SE = dyn_cast<SubscriptExpr>(anchor))
return SE->getBase();
else if (auto *MRE = dyn_cast<MemberRefExpr>(anchor))
return MRE->getBase();
else if (auto *call = dyn_cast<CallExpr>(anchor)) {
auto fnType = getType(call->getFn());
if (fnType->isCallableNominalType(getDC())) {
return call->getFn();
}
}
return nullptr;
}
Type FailureDiagnostic::restoreGenericParameters(
Type type,
llvm::function_ref<void(GenericTypeParamType *, Type)> substitution) {
llvm::SmallPtrSet<GenericTypeParamType *, 4> processed;
return type.transform([&](Type type) -> Type {
if (auto *typeVar = type->getAs<TypeVariableType>()) {
type = resolveType(typeVar);
if (auto *GP = typeVar->getImpl().getGenericParameter()) {
if (processed.insert(GP).second)
substitution(GP, type);
return GP;
}
}
return type;
});
}
bool FailureDiagnostic::conformsToKnownProtocol(
Type type, KnownProtocolKind protocol) const {
auto &cs = getConstraintSystem();
return constraints::conformsToKnownProtocol(cs.DC, type, protocol);
}
Type RequirementFailure::getOwnerType() const {
auto anchor = getRawAnchor();
// If diagnostic is anchored at assignment expression
// it means that requirement failure happend while trying
// to convert source to destination, which means that
// owner type is actually not an assignment expression
// itself but its source.
if (auto *assignment = getAsExpr<AssignExpr>(anchor))
anchor = assignment->getSrc();
return getType(anchor)->getInOutObjectType()->getMetatypeInstanceType();
}
const GenericContext *RequirementFailure::getGenericContext() const {
if (auto *genericCtx = AffectedDecl->getAsGenericContext())
return genericCtx;
auto parentDecl = AffectedDecl->getDeclContext()->getAsDecl();
if (!parentDecl)
return nullptr;
return parentDecl->getAsGenericContext();
}
const Requirement &RequirementFailure::getRequirement() const {
// If this is a conditional requirement failure we need to
// fetch conformance from constraint system associated with
// type requirement this conditional conformance belongs to.
auto requirements = isConditional()
? Conformance->getConditionalRequirements()
: Signature->getRequirements();
return requirements[getRequirementIndex()];
}
ProtocolConformance *RequirementFailure::getConformanceForConditionalReq(
ConstraintLocator *locator) {
auto &solution = getSolution();
auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
if (!reqElt.isConditionalRequirement())
return nullptr;
auto path = locator->getPath();
auto *typeReqLoc = getConstraintLocator(getRawAnchor(), path.drop_back());
auto result = llvm::find_if(
solution.Conformances,
[&](const std::pair<ConstraintLocator *, ProtocolConformanceRef>
&conformance) { return conformance.first == typeReqLoc; });
assert(result != solution.Conformances.end());
auto conformance = result->second;
assert(conformance.isConcrete());
return conformance.getConcrete();
}
ValueDecl *RequirementFailure::getDeclRef() const {
// Get a declaration associated with given type (if any).
// This is used to retrieve affected declaration when
// failure is in any way contextual, and declaration can't
// be fetched directly from constraint system.
auto getAffectedDeclFromType = [](Type type) -> ValueDecl * {
assert(type);
// If problem is related to a typealias, let's point this
// diagnostic directly to its declaration without desugaring.
if (auto *alias = dyn_cast<TypeAliasType>(type.getPointer()))
return alias->getDecl();
if (auto *opaque = type->getAs<OpaqueTypeArchetypeType>())
return opaque->getDecl();
return type->getAnyGeneric();
};
// If the locator is for a function builder body result type, the requirement
// came from the function's return type.
if (getLocator()->isForFunctionBuilderBodyResult()) {
auto *func = getAsDecl<FuncDecl>(getAnchor());
return getAffectedDeclFromType(func->getResultInterfaceType());
}
if (isFromContextualType())
return getAffectedDeclFromType(getContextualType(getRawAnchor()));
if (auto overload = getCalleeOverloadChoiceIfAvailable(getLocator())) {
// If there is a declaration associated with this
// failure e.g. an overload choice of the call
// expression, let's see whether failure is
// associated with it directly or rather with
// one of its parents.
if (auto *decl = overload->choice.getDeclOrNull()) {
// If declaration is an operator let's always use
// it to produce `in reference to` diagnostics.
if (decl->isOperator())
return decl;
auto *DC = decl->getDeclContext();
do {
if (auto *parent = DC->getAsDecl()) {
if (auto *GC = parent->getAsGenericContext()) {
// FIXME: Is this intending an exact match?
if (GC->getGenericSignature().getPointer() != Signature.getPointer())
continue;
// If this is a signature if an extension
// then it means that code has referenced
// something incorrectly and diagnostic
// should point to the referenced declaration.
if (isa<ExtensionDecl>(parent))
break;
return cast<ValueDecl>(parent);
}
}
} while ((DC = DC->getParent()));
return decl;
}
}
return getAffectedDeclFromType(getOwnerType());
}
GenericSignature RequirementFailure::getSignature(ConstraintLocator *locator) {
if (isConditional())
return Conformance->getGenericSignature();
if (auto genericElt = locator->findLast<LocatorPathElt::OpenedGeneric>())
return genericElt->getSignature();
llvm_unreachable("Type requirement failure should always have signature");
}
bool RequirementFailure::isFromContextualType() const {
auto path = getLocator()->getPath();
assert(!path.empty());
return path.front().getKind() == ConstraintLocator::ContextualType;
}
const DeclContext *RequirementFailure::getRequirementDC() const {
// In case of conditional requirement failure, we don't
// have to guess where the it comes from.
if (isConditional())
return Conformance->getDeclContext();
const auto &req = getRequirement();
auto *DC = AffectedDecl->getDeclContext();
do {
if (auto sig = DC->getGenericSignatureOfContext()) {
if (sig->isRequirementSatisfied(req))
return DC;
}
} while ((DC = DC->getParent()));
return AffectedDecl->getAsGenericContext();
}
bool RequirementFailure::isStaticOrInstanceMember(const ValueDecl *decl) {
if (decl->isInstanceMember())
return true;
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(decl))
return AFD->isStatic() && !AFD->isOperator();
return decl->isStatic();
}
bool RequirementFailure::diagnoseAsError() {
const auto *reqDC = getRequirementDC();
auto *genericCtx = getGenericContext();
auto lhs = getLHS();
auto rhs = getRHS();
if (auto *OTD = dyn_cast<OpaqueTypeDecl>(AffectedDecl)) {
auto *namingDecl = OTD->getNamingDecl();
emitDiagnostic(diag::type_does_not_conform_in_opaque_return,
namingDecl->getDescriptiveKind(), namingDecl->getName(),
lhs, rhs, rhs->isAnyObject());
if (auto *repr = namingDecl->getOpaqueResultTypeRepr()) {
emitDiagnosticAt(repr->getLoc(), diag::opaque_return_type_declared_here)
.highlight(repr->getSourceRange());
}
return true;
}
if (reqDC->isTypeContext() && genericCtx != reqDC &&
(genericCtx->isChildContextOf(reqDC) ||
isStaticOrInstanceMember(AffectedDecl))) {
auto *NTD = reqDC->getSelfNominalTypeDecl();
emitDiagnostic(
getDiagnosticInRereference(), AffectedDecl->getDescriptiveKind(),
AffectedDecl->getName(), NTD->getDeclaredType(), lhs, rhs);
} else {
emitDiagnostic(getDiagnosticOnDecl(), AffectedDecl->getDescriptiveKind(),
AffectedDecl->getName(), lhs, rhs);
}
emitRequirementNote(reqDC->getAsDecl(), lhs, rhs);
return true;
}
bool RequirementFailure::diagnoseAsNote() {
const auto &req = getRequirement();
const auto *reqDC = getRequirementDC();
emitDiagnosticAt(reqDC->getAsDecl(), getDiagnosticAsNote(), getLHS(),
getRHS(), req.getFirstType(), req.getSecondType(), "");
return true;
}
void RequirementFailure::emitRequirementNote(const Decl *anchor, Type lhs,
Type rhs) const {
auto &req = getRequirement();
if (req.getKind() != RequirementKind::SameType) {
if (auto wrappedType = lhs->getOptionalObjectType()) {
auto kind = (req.getKind() == RequirementKind::Superclass ?
ConstraintKind::Subtype : ConstraintKind::ConformsTo);
if (TypeChecker::typesSatisfyConstraint(wrappedType, rhs,
/*openArchetypes=*/false,
kind, getDC()))
emitDiagnostic(diag::wrapped_type_satisfies_requirement, wrappedType);
}
}
if (isConditional()) {
emitDiagnosticAt(anchor,
diag::requirement_implied_by_conditional_conformance,
resolveType(Conformance->getType()),
Conformance->getProtocol()->getDeclaredInterfaceType());
return;
}
if (req.getKind() == RequirementKind::Layout ||
rhs->isEqual(req.getSecondType())) {
emitDiagnosticAt(anchor, diag::where_requirement_failure_one_subst,
req.getFirstType(), lhs);
return;
}
if (lhs->isEqual(req.getFirstType())) {
emitDiagnosticAt(anchor, diag::where_requirement_failure_one_subst,
req.getSecondType(), rhs);
return;
}
emitDiagnosticAt(anchor, diag::where_requirement_failure_both_subst,
req.getFirstType(), lhs, req.getSecondType(), rhs);
}
bool MissingConformanceFailure::diagnoseAsError() {
auto anchor = getAnchor();
auto nonConformingType = getLHS();
auto protocolType = getRHS();
// If this is a requirement of a pattern-matching operator,
// let's see whether argument already has a fix associated
// with it and if so skip conformance error, otherwise we'd
// produce an unrelated `<type> doesn't conform to Equatable protocol`
// diagnostic.
if (isPatternMatchingOperator(anchor)) {
auto *expr = castToExpr(anchor);
if (auto *binaryOp = dyn_cast_or_null<BinaryExpr>(findParentExpr(expr))) {
auto *caseExpr = binaryOp->getArg()->getElement(0);
llvm::SmallPtrSet<Expr *, 4> anchors;
for (const auto *fix : getSolution().Fixes) {
if (auto anchor = fix->getAnchor()) {
if (anchor.is<Expr *>())
anchors.insert(getAsExpr(anchor));
}
}
bool hasFix = false;
forEachExprInConstraintSystem(caseExpr, [&](Expr *expr) -> Expr * {
hasFix |= anchors.count(expr);
return hasFix ? nullptr : expr;
});
if (hasFix)
return false;
}
}
// If the problem has been (unambiguously) determined to be related
// to one of of the standard comparison operators and argument is
// enum with associated values, let's produce a tailored note which
// says that conformances for enums with associated values can't be
// synthesized.
if (isStandardComparisonOperator(anchor)) {
auto *expr = castToExpr(anchor);
auto isEnumWithAssociatedValues = [](Type type) -> bool {
if (auto *enumType = type->getAs<EnumType>())
return !enumType->getDecl()->hasOnlyCasesWithoutAssociatedValues();
return false;
};
// Limit this to `Equatable` and `Comparable` protocols for now.
auto *protocol = getRHS()->castTo<ProtocolType>()->getDecl();
if (isEnumWithAssociatedValues(getLHS()) &&
(protocol->isSpecificProtocol(KnownProtocolKind::Equatable) ||
protocol->isSpecificProtocol(KnownProtocolKind::Comparable))) {
if (RequirementFailure::diagnoseAsError()) {
auto opName = getOperatorName(expr);
emitDiagnostic(diag::no_binary_op_overload_for_enum_with_payload,
opName->str());
return true;
}
}
}
if (diagnoseAsAmbiguousOperatorRef())
return true;
if (nonConformingType->isObjCExistentialType()) {
emitDiagnostic(diag::protocol_does_not_conform_static, nonConformingType,
protocolType);
return true;
}
if (diagnoseTypeCannotConform(nonConformingType, protocolType))
return true;
// If none of the special cases could be diagnosed,
// let's fallback to the most general diagnostic.
return RequirementFailure::diagnoseAsError();
}
bool MissingConformanceFailure::diagnoseTypeCannotConform(
Type nonConformingType, Type protocolType) const {
if (getRequirement().getKind() == RequirementKind::Layout ||
!(nonConformingType->is<AnyFunctionType>() ||
nonConformingType->is<TupleType>() ||
nonConformingType->isExistentialType() ||
nonConformingType->is<AnyMetatypeType>())) {
return false;
}
emitDiagnostic(diag::type_cannot_conform,
nonConformingType->isExistentialType(),
nonConformingType,
nonConformingType->isEqual(protocolType),
protocolType);
if (auto *OTD = dyn_cast<OpaqueTypeDecl>(AffectedDecl)) {
auto *namingDecl = OTD->getNamingDecl();
if (auto *repr = namingDecl->getOpaqueResultTypeRepr()) {
emitDiagnosticAt(repr->getLoc(), diag::required_by_opaque_return,
namingDecl->getDescriptiveKind(),
namingDecl->getName())
.highlight(repr->getSourceRange());
}
return true;
}
auto &req = getRequirement();
auto *reqDC = getRequirementDC();
auto *genericCtx = getGenericContext();
auto noteLocation = reqDC->getAsDecl()->getLoc();
if (!noteLocation.isValid())
noteLocation = getLoc();
if (isConditional()) {
emitDiagnosticAt(noteLocation,
diag::requirement_implied_by_conditional_conformance,
resolveType(Conformance->getType()),
Conformance->getProtocol()->getDeclaredInterfaceType());
} else if (genericCtx != reqDC && (genericCtx->isChildContextOf(reqDC) ||
isStaticOrInstanceMember(AffectedDecl))) {
emitDiagnosticAt(noteLocation, diag::required_by_decl_ref,
AffectedDecl->getDescriptiveKind(),
AffectedDecl->getName(),
reqDC->getSelfNominalTypeDecl()->getDeclaredType(),
req.getFirstType(), nonConformingType);
} else {
emitDiagnosticAt(noteLocation, diag::required_by_decl,
AffectedDecl->getDescriptiveKind(),
AffectedDecl->getName(), req.getFirstType(),
nonConformingType);
}
return true;
}
bool MissingConformanceFailure::diagnoseAsAmbiguousOperatorRef() {
auto anchor = getRawAnchor();
auto *ODRE = getAsExpr<OverloadedDeclRefExpr>(anchor);
if (!ODRE)
return false;
auto name = ODRE->getDecls().front()->getBaseName();
if (!(name.isOperator() && getLHS()->isStdlibType() && getRHS()->isStdlibType()))
return false;
// If this is an operator reference and both types are from stdlib,
// let's produce a generic diagnostic about invocation and a note
// about missing conformance just in case.
auto operatorID = name.getIdentifier();
auto *fnType = getType(anchor)->getAs<AnyFunctionType>();
auto params = fnType->getParams();
if (params.size() == 2) {
auto lhsType = params[0].getPlainType();
auto rhsType = params[1].getPlainType();
if (lhsType->isEqual(rhsType)) {
emitDiagnostic(diag::cannot_apply_binop_to_same_args, operatorID.str(),
lhsType);
} else {
emitDiagnostic(diag::cannot_apply_binop_to_args, operatorID.str(),
lhsType, rhsType);
}
} else {
emitDiagnostic(diag::cannot_apply_unop_to_arg, operatorID.str(),
params[0].getPlainType());
}
diagnoseAsNote();
return true;
}
Optional<Diag<Type, Type>> GenericArgumentsMismatchFailure::getDiagnosticFor(
ContextualTypePurpose context) {
switch (context) {
case CTP_Initialization:
case CTP_AssignSource:
return diag::cannot_convert_assign;
case CTP_ReturnStmt:
case CTP_ReturnSingleExpr:
return diag::cannot_convert_to_return_type;
case CTP_DefaultParameter:
case CTP_AutoclosureDefaultParameter:
return diag::cannot_convert_default_arg_value;
case CTP_YieldByValue:
return diag::cannot_convert_yield_value;
case CTP_CallArgument:
return diag::cannot_convert_argument_value;
case CTP_ClosureResult:
return diag::cannot_convert_closure_result;
case CTP_ArrayElement:
return diag::cannot_convert_array_element;
case CTP_DictionaryKey:
return diag::cannot_convert_dict_key;
case CTP_DictionaryValue:
return diag::cannot_convert_dict_value;
case CTP_CoerceOperand:
return diag::cannot_convert_coerce;
case CTP_SubscriptAssignSource:
return diag::cannot_convert_subscript_assign;
case CTP_Condition:
return diag::cannot_convert_condition_value;
case CTP_WrappedProperty:
return diag::wrapped_value_mismatch;
case CTP_ComposedPropertyWrapper:
return diag::composed_property_wrapper_mismatch;
case CTP_ThrowStmt:
case CTP_ForEachStmt:
case CTP_Unused:
case CTP_CannotFail:
case CTP_YieldByReference:
case CTP_CalleeResult:
case CTP_EnumCaseRawValue:
break;
}
return None;
}
void GenericArgumentsMismatchFailure::emitNoteForMismatch(int position) {
auto *locator = getLocator();
// Since there could be implicit conversions associated with argument
// to parameter conversions, let's use parameter type as a source of
// generic parameter information.
auto paramSourceTy =
locator->isLastElement<LocatorPathElt::ApplyArgToParam>() ? getRequired()
: getActual();
auto genericTypeDecl = paramSourceTy->getAnyGeneric();
auto param = genericTypeDecl->getGenericParams()->getParams()[position];
auto lhs = getActual()->getGenericArgs()[position];
auto rhs = getRequired()->getGenericArgs()[position];
auto noteLocation = param->getLoc();
if (!noteLocation.isValid())
noteLocation = getLoc();
emitDiagnosticAt(noteLocation, diag::generic_argument_mismatch,
param->getName(), lhs, rhs);
}
bool GenericArgumentsMismatchFailure::diagnoseAsError() {
auto anchor = getAnchor();
auto fromType = getFromType();
auto toType = getToType();
// This is a situation where right-hand size type is wrapped
// into a number of optionals and argument isn't e.g.
//
// func test(_: UnsafePointer<Int>??) {}
//
// var value: Float = 0
// test(&value)
//
// `value` has to get implicitly wrapped into 2 optionals
// before pointer types could be compared.
auto path = getLocator()->getPath();
unsigned toDrop = 0;
for (const auto &elt : llvm::reverse(path)) {
if (!elt.is<LocatorPathElt::OptionalPayload>())
break;
// Disregard optional payload element to look at its source.
++toDrop;
}
path = path.drop_back(toDrop);
Optional<Diag<Type, Type>> diagnostic;
if (path.empty()) {
if (isExpr<AssignExpr>(anchor)) {
diagnostic = getDiagnosticFor(CTP_AssignSource);
} else if (isExpr<CoerceExpr>(anchor)) {
diagnostic = getDiagnosticFor(CTP_CoerceOperand);
} else {
return false;
}
} else {
const auto &last = path.back();
switch (last.getKind()) {
case ConstraintLocator::ContextualType: {
auto purpose = getContextualTypePurpose();
assert(!(purpose == CTP_Unused || purpose == CTP_CannotFail));
// If this is call to a closure e.g. `let _: A = { B() }()`
// let's point diagnostic to its result.
if (auto *call = getAsExpr<CallExpr>(anchor)) {
auto *fnExpr = call->getFn();
if (auto *closure = dyn_cast<ClosureExpr>(fnExpr)) {
purpose = CTP_ClosureResult;
if (closure->hasSingleExpressionBody())
anchor = closure->getSingleExpressionBody();
}
}
diagnostic = getDiagnosticFor(purpose);
break;
}
case ConstraintLocator::AutoclosureResult:
case ConstraintLocator::ApplyArgToParam:
case ConstraintLocator::ApplyArgument: {
diagnostic = diag::cannot_convert_argument_value;
break;
}
case ConstraintLocator::ParentType: {
diagnostic = diag::cannot_convert_parent_type;
break;
}
case ConstraintLocator::ClosureBody:
case ConstraintLocator::ClosureResult: {
diagnostic = diag::cannot_convert_closure_result;
break;
}
case ConstraintLocator::TupleElement: {
auto rawAnchor = getRawAnchor();
if (isExpr<ArrayExpr>(rawAnchor)) {
diagnostic = getDiagnosticFor(CTP_ArrayElement);
} else if (isExpr<DictionaryExpr>(rawAnchor)) {
auto eltLoc = last.castTo<LocatorPathElt::TupleElement>();
diagnostic = getDiagnosticFor(
eltLoc.getIndex() == 0 ? CTP_DictionaryKey : CTP_DictionaryValue);
}
break;
}
case ConstraintLocator::UnresolvedMemberChainResult: {
diagnostic = diag::cannot_convert_chain_result_type;
break;
}
default:
break;
}
}
if (!diagnostic) {
// Handle all mismatches involving an `AssignExpr`
if (auto *assignExpr = getAsExpr<AssignExpr>(anchor)) {
diagnostic = getDiagnosticFor(CTP_AssignSource);
fromType = getType(assignExpr->getSrc());
toType = getType(assignExpr->getDest());
} else {
// If we couldn't find a specific diagnostic let's fallback to
// attempt to handle cases where we have an apply arg to param.
auto applyInfo = getFunctionArgApplyInfo(getLocator());
if (applyInfo) {
diagnostic = diag::cannot_convert_argument_value;
fromType = applyInfo->getArgType();
toType = applyInfo->getParamType();
}
}
}
if (!diagnostic)
return false;
emitDiagnosticAt(::getLoc(anchor), *diagnostic, fromType, toType);
emitNotesForMismatches();
return true;
}
bool LabelingFailure::diagnoseAsError() {
auto *argExpr = getArgumentListExprFor(getLocator());
if (!argExpr)
return false;
return diagnoseArgumentLabelError(getASTContext(), argExpr, CorrectLabels,
isExpr<SubscriptExpr>(getRawAnchor()));
}
bool LabelingFailure::diagnoseAsNote() {
auto *argExpr = getArgumentListExprFor(getLocator());
if (!argExpr)
return false;
SmallVector<Identifier, 4> argLabels;
if (isa<ParenExpr>(argExpr)) {
argLabels.push_back(Identifier());
} else if (auto *tuple = dyn_cast<TupleExpr>(argExpr)) {
argLabels.append(tuple->getElementNames().begin(),
tuple->getElementNames().end());
} else {
return false;
}
auto stringifyLabels = [](ArrayRef<Identifier> labels) -> std::string {
std::string str;
for (auto label : labels) {
str += label.empty() ? "_" : label.str();
str += ':';
}
return "(" + str + ")";
};
auto selectedOverload = getCalleeOverloadChoiceIfAvailable(getLocator());
if (!selectedOverload)
return false;
const auto &choice = selectedOverload->choice;
if (auto *decl = choice.getDeclOrNull()) {
emitDiagnosticAt(decl, diag::candidate_expected_different_labels,
stringifyLabels(argLabels),
stringifyLabels(CorrectLabels));
return true;
}
return false;
}
bool NoEscapeFuncToTypeConversionFailure::diagnoseAsError() {
if (diagnoseParameterUse())
return true;
if (auto *typeVar = getRawFromType()->getAs<TypeVariableType>()) {
if (auto *GP = typeVar->getImpl().getGenericParameter()) {
emitDiagnostic(diag::converting_noescape_to_type, GP);
return true;
}
}
emitDiagnostic(diag::converting_noescape_to_type, getToType());
return true;
}
bool NoEscapeFuncToTypeConversionFailure::diagnoseParameterUse() const {
auto convertTo = getToType();
// If the other side is not a function, we have common case diagnostics
// which handle function-to-type conversion diagnostics.
if (!convertTo->is<FunctionType>())
return false;
auto anchor = getAnchor();
auto diagnostic = diag::general_noescape_to_escaping;
ParamDecl *PD = nullptr;
if (auto *DRE = getAsExpr<DeclRefExpr>(anchor)) {
PD = dyn_cast<ParamDecl>(DRE->getDecl());
// If anchor is not a parameter declaration there
// is no need to dig up more information.
if (!PD)
return false;
// Let's check whether this is a function parameter passed
// as an argument to another function which accepts @escaping
// function at that position.
if (auto argApplyInfo = getFunctionArgApplyInfo(getLocator())) {
auto paramInterfaceTy = argApplyInfo->getParamInterfaceType();
if (paramInterfaceTy->isTypeParameter()) {
auto diagnoseGenericParamFailure = [&](GenericTypeParamDecl *decl) {
emitDiagnostic(diag::converting_noespace_param_to_generic_type,
PD->getName(), paramInterfaceTy);
auto declLoc = decl->getLoc();
if (declLoc.isValid())
emitDiagnosticAt(decl, diag::generic_parameters_always_escaping);
};
// If this is a situation when non-escaping parameter is passed
// to the argument which represents generic parameter, there is
// a tailored diagnostic for that.
if (auto *DMT = paramInterfaceTy->getAs<DependentMemberType>()) {
diagnoseGenericParamFailure(DMT->getRootGenericParam()->getDecl());
return true;
}
if (auto *GP = paramInterfaceTy->getAs<GenericTypeParamType>()) {
diagnoseGenericParamFailure(GP->getDecl());
return true;
}
}
// If there are no generic parameters involved, this could
// only mean that parameter is expecting @escaping function type.
diagnostic = diag::passing_noescape_to_escaping;
}
} else if (auto *AE = getAsExpr<AssignExpr>(getRawAnchor())) {
if (auto *DRE = dyn_cast<DeclRefExpr>(AE->getSrc())) {
PD = dyn_cast<ParamDecl>(DRE->getDecl());
diagnostic = diag::assigning_noescape_to_escaping;
}
}
if (!PD)
return false;
emitDiagnostic(diagnostic, PD->getName());
// Give a note and fix-it
auto note = emitDiagnosticAt(PD, diag::noescape_parameter, PD->getName());
SourceLoc reprLoc;
SourceLoc autoclosureEndLoc;
if (auto *repr = PD->getTypeRepr()) {
reprLoc = repr->getStartLoc();
if (auto *attrRepr = dyn_cast<AttributedTypeRepr>(repr)) {
autoclosureEndLoc = Lexer::getLocForEndOfToken(
getASTContext().SourceMgr,
attrRepr->getAttrs().getLoc(TAK_autoclosure));
}
}
if (!PD->isAutoClosure()) {
note.fixItInsert(reprLoc, "@escaping ");
} else {
note.fixItInsertAfter(autoclosureEndLoc, " @escaping");
}
return true;
}
ASTNode MissingForcedDowncastFailure::getAnchor() const {
auto anchor = FailureDiagnostic::getAnchor();
if (auto *assignExpr = getAsExpr<AssignExpr>(anchor))
return assignExpr->getSrc();
return anchor;
}
bool MissingForcedDowncastFailure::diagnoseAsError() {
auto fromType = getFromType();
auto toType = getToType();
emitDiagnostic(diag::missing_forced_downcast, fromType, toType)
.highlight(getSourceRange())
.fixItReplace(getLoc(), "as!");
return true;
}
bool MissingAddressOfFailure::diagnoseAsError() {
auto argTy = getFromType();
auto paramTy = getToType();
if (paramTy->getAnyPointerElementType()) {
emitDiagnostic(diag::cannot_convert_argument_value, argTy, paramTy)
.fixItInsert(getSourceRange().Start, "&");
} else {
emitDiagnostic(diag::missing_address_of, argTy)
.fixItInsert(getSourceRange().Start, "&");
}
return true;
}
ASTNode MissingExplicitConversionFailure::getAnchor() const {
auto anchor = FailureDiagnostic::getAnchor();
if (auto *assign = getAsExpr<AssignExpr>(anchor))
return assign->getSrc();
if (auto *paren = getAsExpr<ParenExpr>(anchor))
return paren->getSubExpr();
return anchor;
}
bool MissingExplicitConversionFailure::diagnoseAsError() {
auto *DC = getDC();
auto *anchor = castToExpr(getAnchor());
auto fromType = getFromType();
auto toType = getToType();
if (!toType->hasTypeRepr())
return false;
bool useAs = TypeChecker::isExplicitlyConvertibleTo(fromType, toType, DC);
auto *expr = findParentExpr(anchor);