-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathCSDiagnostics.h
3331 lines (2769 loc) · 109 KB
/
CSDiagnostics.h
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.h - 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 provides necessary abstractions for constraint system diagnostics.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SEMA_CSDIAGNOSTICS_H
#define SWIFT_SEMA_CSDIAGNOSTICS_H
#include "TypeChecker.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/OperatorNameLookup.h"
#include "swift/AST/Types.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/FixBehavior.h"
#include "swift/Sema/OverloadChoice.h"
#include "llvm/ADT/ArrayRef.h"
#include <tuple>
namespace swift {
namespace constraints {
class FunctionArgApplyInfo;
/// Base class for all of the possible diagnostics,
/// provides most basic information such as location of
/// the problem, parent expression and some utility methods.
class FailureDiagnostic {
const Solution &S;
ConstraintLocator *Locator;
FixBehavior fixBehavior;
public:
FailureDiagnostic(const Solution &solution, ConstraintLocator *locator,
FixBehavior fixBehavior = FixBehavior::Error)
: S(solution), Locator(locator), fixBehavior(fixBehavior) {}
FailureDiagnostic(const Solution &solution, ASTNode anchor,
FixBehavior fixBehavior = FixBehavior::Error)
: FailureDiagnostic(solution, solution.getConstraintLocator(anchor),
fixBehavior) { }
virtual ~FailureDiagnostic();
virtual SourceLoc getLoc() const { return constraints::getLoc(getAnchor()); }
virtual SourceRange getSourceRange() const {
return constraints::getSourceRange(getAnchor());
}
/// Try to diagnose a problem given affected expression,
/// failure location, types and declarations deduced by
/// constraint system, and other auxiliary information.
///
/// \param asNote In ambiguity cases it's beneficial to
/// produce diagnostic as a note instead of an error if possible.
///
/// \returns true If the problem has been successfully diagnosed
/// and diagnostic message emitted, false otherwise.
bool diagnose(bool asNote = false);
/// Try to produce an error diagnostic for the problem at hand.
///
/// \returns true If anything was diagnosed, false otherwise.
virtual bool diagnoseAsError() = 0;
/// Instead of producing an error diagnostic, attempt to
/// produce a "note" to complement some other diagnostic
/// e.g. ambiguity error.
virtual bool diagnoseAsNote();
ASTNode getRawAnchor() const { return Locator->getAnchor(); }
virtual ASTNode getAnchor() const;
ConstraintLocator *getLocator() const { return Locator; }
Type getType(ASTNode node, bool wantRValue = true) const;
/// Get type associated with a given ASTNode without resolving it,
/// which means that returned type would have type variables.
Type getRawType(ASTNode node) const;
/// Resolve type variables present in the raw type, if any.
Type resolveType(Type rawType, bool reconstituteSugar = false,
bool wantRValue = true) const;
template <typename... ArgTypes>
InFlightDiagnostic emitDiagnostic(ArgTypes &&... Args) const;
template <typename... ArgTypes>
InFlightDiagnostic emitDiagnosticAt(ArgTypes &&... Args) const;
protected:
const Solution &getSolution() const { return S; }
ConstraintSystem &getConstraintSystem() const {
return S.getConstraintSystem();
}
Type getContextualType(ASTNode anchor) const {
auto &cs = getConstraintSystem();
return cs.getContextualType(anchor, /*forConstraint=*/false);
}
TypeLoc getContextualTypeLoc(ASTNode anchor) const {
auto &cs = getConstraintSystem();
return cs.getContextualTypeLoc(anchor);
}
ContextualTypePurpose getContextualTypePurpose(ASTNode anchor) const {
auto &cs = getConstraintSystem();
return cs.getContextualTypePurpose(anchor);
}
DeclContext *getDC() const {
auto &cs = getConstraintSystem();
return cs.DC;
}
ModuleDecl *getParentModule() const {
return getDC()->getParentModule();
}
ASTContext &getASTContext() const {
auto &cs = getConstraintSystem();
return cs.getASTContext();
}
/// Retrieve overload choice resolved for a given locator
/// by the constraint solver.
std::optional<SelectedOverload>
getOverloadChoiceIfAvailable(ConstraintLocator *locator) const {
return S.getOverloadChoiceIfAvailable(locator);
}
/// Retrieve the overload choice for the callee associated with the given
/// locator, if any.
std::optional<SelectedOverload>
getCalleeOverloadChoiceIfAvailable(ConstraintLocator *locator) const {
return S.getCalleeOverloadChoiceIfAvailable(locator);
}
ConstraintLocator *
getConstraintLocator(ASTNode anchor,
ConstraintLocator::PathElement element) const {
return S.getConstraintLocator(anchor, {element});
}
/// Retrieve the constraint locator for the given anchor and
/// path, uniqued and automatically calculate the summary flags
ConstraintLocator *getConstraintLocator(
ASTNode anchor,
ArrayRef<ConstraintLocator::PathElement> path = {}) const {
return S.getConstraintLocator(anchor, path);
}
ConstraintLocator *
getConstraintLocator(ConstraintLocator *baseLocator,
ConstraintLocator::PathElement element) const {
return S.getConstraintLocator(baseLocator, element);
}
std::optional<FunctionArgApplyInfo>
getFunctionArgApplyInfo(ConstraintLocator *locator) const {
return S.getFunctionArgApplyInfo(locator);
}
/// \returns A parent expression if sub-expression is contained anywhere
/// in the root expression or `nullptr` otherwise.
Expr *findParentExpr(const Expr *subExpr) const;
/// If given expression is some kind of a member reference e.g.
/// `x.foo` or `x[0]` extract and return its base expression.
Expr *getBaseExprFor(const Expr *anchor) const;
/// For a given locator describing an argument application, or a constraint
/// within an argument application, returns the argument list for that
/// application. If the locator is not for an argument application, or
/// the argument list cannot be found, returns \c nullptr.
ArgumentList *getArgumentListFor(ConstraintLocator *locator) const;
/// \returns A new type with all of the type variables associated with
/// generic parameters substituted back into being generic parameter type.
Type restoreGenericParameters(
Type type,
llvm::function_ref<void(GenericTypeParamType *, Type)> substitution =
[](GenericTypeParamType *, Type) {});
bool conformsToKnownProtocol(Type type, KnownProtocolKind protocol) const;
/// Retrieve an editor placeholder with a given description, or a given
/// type if specified.
StringRef getEditorPlaceholder(StringRef description, Type ty,
llvm::SmallVectorImpl<char> &scratch) const;
};
/// Base class for all of the diagnostics related to generic requirement
/// failures, provides common information like failed requirement,
/// declaration where such requirement comes from, etc.
class RequirementFailure : public FailureDiagnostic {
protected:
using PathEltKind = ConstraintLocator::PathElementKind;
using DiagOnDecl = Diag<const ValueDecl *, Type, Type>;
using DiagInReference = Diag<const ValueDecl *, Type, Type, Type>;
using DiagAsNote = Diag<Type, Type, Type, Type>;
/// If this failure associated with one of the conditional requirements,
/// this field would represent conformance where requirement comes from.
const ProtocolConformance *Conformance = nullptr;
/// The source of the requirement, if available. One exception
/// is failure associated with conditional requirement where
/// underlying conformance is specialized.
GenericSignature Signature;
const ValueDecl *AffectedDecl;
/// If possible, find application expression associated
/// with current generic requirement failure, that helps
/// to diagnose failures related to arguments.
const ApplyExpr *Apply = nullptr;
/// Types associated with requirement constraint this
/// failure originates from.
Type LHS, RHS;
public:
RequirementFailure(const Solution &solution, Type lhs, Type rhs,
ConstraintLocator *locator)
: FailureDiagnostic(solution, locator),
Conformance(getConformanceForConditionalReq(locator)),
Signature(getSignature(locator)), AffectedDecl(getDeclRef()),
LHS(resolveType(lhs)), RHS(resolveType(rhs)) {
assert(locator);
assert(isConditional() || Signature);
assert(AffectedDecl);
assert(getRequirementDC() &&
"Couldn't find where the requirement came from?");
assert(getGenericContext() &&
"Affected decl not within a generic context?");
if (auto *expr = getAsExpr(getRawAnchor()))
if (auto *parentExpr = findParentExpr(expr))
Apply = dyn_cast<ApplyExpr>(parentExpr);
}
virtual SourceLoc getLoc() const override {
return FailureDiagnostic::getLoc();
}
unsigned getRequirementIndex() const {
auto reqElt =
getLocator()->castLastElementTo<LocatorPathElt::AnyRequirement>();
return reqElt.getIndex();
}
/// The generic base type where failing requirement comes from.
Type getOwnerType() const;
/// Generic context associated with the failure.
const GenericContext *getGenericContext() const;
/// Generic requirement associated with the failure.
const Requirement &getRequirement() const;
Type getLHS() const { return LHS; }
Type getRHS() const { return RHS; }
bool diagnoseAsError() override;
bool diagnoseAsNote() override;
protected:
/// Determine whether this is a conditional requirement failure.
bool isConditional() const { return bool(Conformance); }
/// Check whether this requirement comes from the contextual type
/// that root expression is coerced/converted into.
bool isFromContextualType() const;
/// Retrieve declaration contextual where current
/// requirement has been introduced.
const DeclContext *getRequirementDC() const;
virtual DiagOnDecl getDiagnosticOnDecl() const = 0;
virtual DiagInReference getDiagnosticInRereference() const = 0;
virtual DiagAsNote getDiagnosticAsNote() const = 0;
static bool isOperator(const ApplyExpr *apply) {
return isa<PrefixUnaryExpr>(apply) || isa<PostfixUnaryExpr>(apply) ||
isa<BinaryExpr>(apply);
}
/// Determine whether given declaration represents a static
/// or instance property/method, excluding operators.
static bool isStaticOrInstanceMember(const ValueDecl *decl);
private:
/// Retrieve declaration associated with failing generic requirement.
ValueDecl *getDeclRef() const;
/// Retrieve generic signature where this parameter originates from.
GenericSignature getSignature(ConstraintLocator *locator);
void maybeEmitRequirementNote(const Decl *anchor, Type lhs, Type rhs) const;
/// If this is a failure in conditional requirement, retrieve
/// conformance information.
ProtocolConformance *
getConformanceForConditionalReq(ConstraintLocator *locator);
};
/// Diagnostics for failed conformance checks originating from
/// generic requirements e.g.
/// ```swift
/// struct S {}
/// func foo<T: Hashable>(_ t: T) {}
/// foo(S())
/// ```
class MissingConformanceFailure final : public RequirementFailure {
public:
MissingConformanceFailure(const Solution &solution,
ConstraintLocator *locator,
std::pair<Type, Type> conformance)
: RequirementFailure(solution, conformance.first, conformance.second,
locator) {
#ifndef NDEBUG
auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
assert(reqElt.getRequirementKind() == RequirementKind::Conformance ||
reqElt.getRequirementKind() == RequirementKind::Layout);
#endif
}
virtual SourceLoc getLoc() const override;
bool diagnoseAsError() override;
protected:
/// Check whether this requirement is associated with one of the
/// operator overloads, in cases like that sometimes it makes more
/// sense to produce a generic diagnostic about operator reference
/// instead of conformance, because it could be something like
/// `true + true`, and it doesn't make much sense to suggest to
/// add a conformance from one library type to another.
bool diagnoseAsAmbiguousOperatorRef();
DiagOnDecl getDiagnosticOnDecl() const override {
return (getRequirement().getKind() == RequirementKind::Layout ?
diag::type_does_not_conform_anyobject_decl_owner :
diag::type_does_not_conform_decl_owner);
}
DiagInReference getDiagnosticInRereference() const override {
return (getRequirement().getKind() == RequirementKind::Layout ?
diag::type_does_not_conform_anyobject_in_decl_ref :
diag::type_does_not_conform_in_decl_ref);
}
DiagAsNote getDiagnosticAsNote() const override {
return diag::candidate_types_conformance_requirement;
}
private:
bool diagnoseTypeCannotConform(Type nonConformingType,
Type protocolType) const;
};
/// Diagnose failures related to same-type generic requirements, e.g.
/// ```swift
/// protocol P {
/// associatedtype T
/// }
///
/// struct S : P {
/// typealias T = String
/// }
///
/// func foo<U: P>(_ t: [U]) where U.T == Int {}
/// foo([S()])
/// ```
///
/// `S.T` is not the same type as `Int`, which is required by `foo`.
class SameTypeRequirementFailure final : public RequirementFailure {
public:
SameTypeRequirementFailure(const Solution &solution, Type lhs, Type rhs,
ConstraintLocator *locator)
: RequirementFailure(solution, lhs, rhs, locator) {
#ifndef NDEBUG
auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
assert(reqElt.getRequirementKind() == RequirementKind::SameType);
#endif
}
protected:
DiagOnDecl getDiagnosticOnDecl() const override {
return diag::types_not_equal_decl;
}
DiagInReference getDiagnosticInRereference() const override {
return diag::types_not_equal_in_decl_ref;
}
DiagAsNote getDiagnosticAsNote() const override {
return diag::candidate_types_equal_requirement;
}
};
/// Diagnose failures related to same-shape generic requirements, e.g.
/// ```swift
/// func foo<T..., U...>(t: T..., u: U...) -> (T, U)... {}
/// func bar<T..., U...>(t: T..., u: U...) {
/// foo(t: t..., u: u...)
/// }
/// ```
///
/// The generic parameter packs `T` and `U` are not known to have the same
/// shape, which is required by `foo()`.
class SameShapeRequirementFailure final : public RequirementFailure {
public:
SameShapeRequirementFailure(const Solution &solution, Type lhs, Type rhs,
ConstraintLocator *locator)
: RequirementFailure(solution, lhs, rhs, locator) {
#ifndef NDEBUG
auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
assert(reqElt.getRequirementKind() == RequirementKind::SameShape);
#endif
}
protected:
DiagOnDecl getDiagnosticOnDecl() const override {
return diag::types_not_same_shape_decl;
}
DiagInReference getDiagnosticInRereference() const override {
return diag::types_not_same_shape_in_decl_ref;
}
DiagAsNote getDiagnosticAsNote() const override {
return diag::candidate_types_same_shape_requirement;
}
};
class SameShapeExpansionFailure final : public FailureDiagnostic {
Type lhs, rhs;
public:
SameShapeExpansionFailure(const Solution &solution, Type lhs, Type rhs,
ConstraintLocator *locator)
: FailureDiagnostic(solution, locator),
lhs(resolveType(lhs)),
rhs(resolveType(rhs)) {}
bool diagnoseAsError() override;
};
/// Diagnose failures related to superclass generic requirements, e.g.
/// ```swift
/// class A {
/// }
///
/// class B {
/// }
///
/// func foo<T>(_ t: [T]) where T: A {}
/// foo([B()])
/// ```
///
/// `A` is not the superclass of `B`, which is required by `foo<T>`.
class SuperclassRequirementFailure final : public RequirementFailure {
public:
SuperclassRequirementFailure(const Solution &solution, Type lhs, Type rhs,
ConstraintLocator *locator)
: RequirementFailure(solution, lhs, rhs, locator) {
#ifndef NDEBUG
auto reqElt = locator->castLastElementTo<LocatorPathElt::AnyRequirement>();
assert(reqElt.getRequirementKind() == RequirementKind::Superclass);
#endif
}
protected:
DiagOnDecl getDiagnosticOnDecl() const override {
return diag::types_not_inherited_decl;
}
DiagInReference getDiagnosticInRereference() const override {
return diag::types_not_inherited_in_decl_ref;
}
DiagAsNote getDiagnosticAsNote() const override {
return diag::candidate_types_inheritance_requirement;
}
};
/// Diagnose errors associated with missing, extraneous
/// or incorrect labels supplied by arguments, e.g.
/// ```swift
/// func foo(q: String, _ a: Int) {}
/// foo("ultimate question", a: 42)
/// ```
/// Call to `foo` is going to be diagnosed as missing `q:`
/// and having extraneous `a:` labels, with appropriate fix-its added.
class LabelingFailure final : public FailureDiagnostic {
ArrayRef<Identifier> CorrectLabels;
public:
LabelingFailure(const Solution &solution, ConstraintLocator *locator,
ArrayRef<Identifier> labels)
: FailureDiagnostic(solution, locator), CorrectLabels(labels) {}
bool diagnoseAsError() override;
bool diagnoseAsNote() override;
};
/// A diagnostic that will be emitted on the base if its locator points to a
/// member access.
class MemberReferenceFailure : public FailureDiagnostic {
public:
MemberReferenceFailure(const Solution &solution, ConstraintLocator *locator)
: FailureDiagnostic(solution, locator) {}
ASTNode getAnchor() const override;
};
/// Diagnose failures related to attempting member access on optional base
/// type without optional chaining or force-unwrapping it first.
class MemberAccessOnOptionalBaseFailure final : public MemberReferenceFailure {
DeclNameRef Member;
Type MemberBaseType;
bool ResultTypeIsOptional;
public:
MemberAccessOnOptionalBaseFailure(const Solution &solution,
ConstraintLocator *locator,
DeclNameRef memberName, Type memberBaseType,
bool resultOptional)
: MemberReferenceFailure(solution, locator), Member(memberName),
MemberBaseType(resolveType(memberBaseType)),
ResultTypeIsOptional(resultOptional) {}
bool diagnoseAsError() override;
Type getMemberBaseType() const {
return MemberBaseType;
}
SourceLoc getLoc() const override {
// The end location points to the dot in the member access.
return getSourceRange().End;
}
SourceRange getSourceRange() const override;
};
/// Diagnose errors associated with rvalues in positions
/// where an lvalue is required, such as inout arguments.
class RValueTreatedAsLValueFailure final : public FailureDiagnostic {
public:
RValueTreatedAsLValueFailure(const Solution &solution,
ConstraintLocator *locator)
: FailureDiagnostic(solution, locator) {}
bool diagnoseAsError() override;
bool diagnoseAsNote() override;
};
class TrailingClosureAmbiguityFailure final : public FailureDiagnostic {
ArrayRef<OverloadChoice> Choices;
public:
TrailingClosureAmbiguityFailure(ArrayRef<Solution> solutions, ASTNode anchor,
ArrayRef<OverloadChoice> choices)
: FailureDiagnostic(solutions.front(), anchor), Choices(choices) {}
bool diagnoseAsError() override { return false; }
bool diagnoseAsNote() override;
};
/// Diagnose errors related to assignment expressions e.g.
/// trying to assign something to immutable value, or trying
/// to access mutating member on immutable base.
class AssignmentFailure final : public FailureDiagnostic {
Expr *DestExpr;
SourceLoc Loc;
Diag<StringRef> DeclDiagnostic;
Diag<Type> TypeDiagnostic;
public:
AssignmentFailure(Expr *destExpr, const Solution &solution,
SourceLoc diagnosticLoc);
AssignmentFailure(Expr *destExpr, const Solution &solution,
SourceLoc diagnosticLoc, Diag<StringRef> declDiag,
Diag<Type> typeDiag)
: FailureDiagnostic(solution, destExpr), DestExpr(destExpr),
Loc(diagnosticLoc), DeclDiagnostic(declDiag), TypeDiagnostic(typeDiag) {
}
bool diagnoseAsError() override;
private:
/// 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.
///
/// \returns The base subexpression that looks immutable (or that can't be
/// analyzed any further) along with an OverloadChoice extracted from it if we
/// could.
std::pair<Expr *, std::optional<OverloadChoice>>
resolveImmutableBase(Expr *expr) const;
std::pair<Expr *, std::optional<OverloadChoice>>
resolveImmutableBase(const Expr *expr) const {
return resolveImmutableBase(const_cast<Expr *>(expr));
}
static Diag<StringRef> findDeclDiagnostic(ASTContext &ctx,
const Expr *destExpr);
/// Retrieve an member reference associated with given member
/// looking through dynamic member lookup on the way.
std::optional<OverloadChoice> getMemberRef(ConstraintLocator *locator) const;
};
/// Intended to diagnose any possible contextual failure
/// e.g. argument/parameter, closure result, conversions etc.
class ContextualFailure : public FailureDiagnostic {
ContextualTypePurpose CTP;
Type RawFromType, RawToType;
public:
ContextualFailure(const Solution &solution, Type lhs, Type rhs,
ConstraintLocator *locator,
FixBehavior fixBehavior = FixBehavior::Error)
: ContextualFailure(
solution,
locator->isForContextualType()
? locator->castLastElementTo<LocatorPathElt::ContextualType>()
.getPurpose()
: solution.getConstraintSystem().getContextualTypePurpose(
locator->getAnchor()),
lhs, rhs, locator, fixBehavior) {}
ContextualFailure(const Solution &solution, ContextualTypePurpose purpose,
Type lhs, Type rhs, ConstraintLocator *locator,
FixBehavior fixBehavior = FixBehavior::Error)
: FailureDiagnostic(solution, locator, fixBehavior), CTP(purpose),
RawFromType(lhs), RawToType(rhs) {
assert(lhs && "Expected a valid 'from' type");
assert(rhs && "Expected a valid 'to' type");
}
SourceLoc getLoc() const override;
Type getFromType() const { return resolve(RawFromType); }
Type getToType() const { return resolve(RawToType); }
Type getRawFromType() const { return RawFromType; }
Type getRawToType() const { return RawToType; }
bool diagnoseAsError() override;
bool diagnoseAsNote() override;
/// If we're trying to convert something to `nil`.
bool diagnoseConversionToNil() const;
/// Diagnose failed conversion in a `CoerceExpr`.
bool diagnoseCoercionToUnrelatedType() const;
/// Produce a specialized diagnostic if this is an invalid conversion to Bool.
bool diagnoseConversionToBool() const;
/// Produce a specialized diagnostic if this is an attempt to throw
/// something with doesn't conform to `Error`.
bool diagnoseThrowsTypeMismatch() const;
/// Produce a specialized diagnostic if this is an attempt to `yield`
/// something of incorrect type.
bool diagnoseYieldByReferenceMismatch() const;
/// Attempt to attach any relevant fix-its to already produced diagnostic.
void tryFixIts(InFlightDiagnostic &diagnostic) const;
/// Attempts to add fix-its for these two mistakes:
///
/// - Passing an integer with the right type but which is getting wrapped with
/// a different integer type unnecessarily. The fixit removes the cast.
///
/// - Passing an integer but expecting different integer type. The fixit adds
/// a wrapping cast.
///
/// - Return true on the fixit is added, false otherwise.
///
/// This helps migration with SDK changes.
bool tryIntegerCastFixIts(InFlightDiagnostic &diagnostic) const;
protected:
/// Try to add a fix-it when converting between a collection and its slice
/// type, such as String <-> Substring or (eventually) Array <-> ArraySlice
bool trySequenceSubsequenceFixIts(InFlightDiagnostic &diagnostic) const;
/// Try to add a fix-it that suggests to explicitly use `as` or `as!`
/// to coerce one type to another if type-checker can prove that such
/// conversion is possible.
bool tryTypeCoercionFixIt(InFlightDiagnostic &diagnostic) const;
/// Try to add a fix-it to conform the decl context (if it's a type) to the
/// protocol
bool tryProtocolConformanceFixIt(InFlightDiagnostic &diagnostic) const;
private:
Type resolve(Type rawType) const {
return resolveType(rawType)->getWithoutSpecifierType();
}
bool isIntegerType(Type type) const {
return conformsToKnownProtocol(
type, KnownProtocolKind::ExpressibleByIntegerLiteral);
}
/// Return true if the conversion from fromType to toType is
/// an invalid string index operation.
bool isIntegerToStringIndexConversion() const;
protected:
ContextualTypePurpose getContextualTypePurpose() const { return CTP; }
static std::optional<Diag<Type, Type>>
getDiagnosticFor(ContextualTypePurpose context, Type contextualType);
protected:
bool exprNeedsParensBeforeAddingAs(const Expr *expr, DeclContext *DC) const {
auto asPG = TypeChecker::lookupPrecedenceGroup(
DC, DC->getASTContext().Id_CastingPrecedence, SourceLoc())
.getSingle();
if (!asPG)
return true;
return exprNeedsParensInsideFollowingOperator(DC, const_cast<Expr *>(expr),
asPG);
}
bool exprNeedsParensAfterAddingAs(const Expr *expr, DeclContext *DC) const {
auto asPG = TypeChecker::lookupPrecedenceGroup(
DC, DC->getASTContext().Id_CastingPrecedence, SourceLoc())
.getSingle();
if (!asPG)
return true;
return exprNeedsParensOutsideFollowingOperator(
DC, const_cast<Expr *>(expr), asPG,
[&](auto *E) { return findParentExpr(E); });
}
};
class NonClassTypeToAnyObjectConversionFailure final
: public ContextualFailure {
public:
NonClassTypeToAnyObjectConversionFailure(const Solution &solution, Type lhs,
Type rhs, ConstraintLocator *locator)
: ContextualFailure(solution, lhs, rhs, locator, FixBehavior::Error) {}
bool diagnoseAsError() override;
bool diagnoseAsNote() override;
};
/// Diagnose errors related to using an array literal where a
/// dictionary is expected.
class ArrayLiteralToDictionaryConversionFailure final : public ContextualFailure {
public:
ArrayLiteralToDictionaryConversionFailure(const Solution &solution,
Type arrayTy, Type dictTy,
ConstraintLocator *locator)
: ContextualFailure(solution, arrayTy, dictTy, locator) {}
bool diagnoseAsError() override;
};
/// Diagnose errors related to converting function type which
/// isn't explicitly '@escaping' or '@Sendable' to some other type.
class AttributedFuncToTypeConversionFailure final : public ContextualFailure {
public:
enum AttributeKind {
Escaping,
Concurrent,
};
const AttributeKind attributeKind;
AttributedFuncToTypeConversionFailure(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator,
AttributeKind attributeKind,
FixBehavior fixBehavior =
FixBehavior::Error)
: ContextualFailure(solution, fromType, toType, locator, fixBehavior),
attributeKind(attributeKind) {}
bool diagnoseAsError() override;
private:
/// Emit tailored diagnostics for no-escape/non-sendable parameter
/// conversions e.g. passing such parameter as an @escaping or @Sendable
/// argument, or trying to assign it to a variable which expects @escaping
/// or @Sendable function.
bool diagnoseParameterUse() const;
/// Emit a tailored diagnostic for a no-escape/espace mismatch for function
/// arguments where the mismatch has to take into account that a
/// function type subtype relation in the parameter position is contravariant.
bool diagnoseFunctionParameterEscapenessMismatch(AssignExpr *) const;
};
/// Diagnose failure where a global actor attribute is dropped when
/// trying to convert one function type to another.
class DroppedGlobalActorFunctionAttr final : public ContextualFailure {
public:
DroppedGlobalActorFunctionAttr(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator,
FixBehavior fixBehavior)
: ContextualFailure(solution, fromType, toType, locator, fixBehavior) { }
bool diagnoseAsError() override;
};
/// Diagnose failures related to use of the unwrapped optional types,
/// which require some type of force-unwrap e.g. "!" or "try!".
class MissingOptionalUnwrapFailure final : public ContextualFailure {
public:
MissingOptionalUnwrapFailure(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator)
: ContextualFailure(solution, fromType, toType, locator) {}
bool diagnoseAsError() override;
private:
Type getBaseType() const {
return resolveType(getFromType(), /*reconstituteSugar=*/true);
}
Type getUnwrappedType() const {
return resolveType(getBaseType()->getOptionalObjectType(),
/*reconstituteSugar=*/true);
}
/// Suggest a default value via `?? <default value>`
void offerDefaultValueUnwrapFixIt(DeclContext *DC, const Expr *expr) const;
/// Suggest a force optional unwrap via `!`
void offerForceUnwrapFixIt(const Expr *expr) const;
};
class WrappedValueMismatch final : public ContextualFailure {
public:
WrappedValueMismatch(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator)
: ContextualFailure(solution, fromType, toType, locator) {
}
bool diagnoseAsError() override;
};
/// Diagnostics for mismatched generic arguments e.g
/// ```swift
/// struct F<G> {}
/// let _:F<Int> = F<Bool>()
/// ```
class GenericArgumentsMismatchFailure final : public ContextualFailure {
ArrayRef<unsigned> Mismatches;
public:
GenericArgumentsMismatchFailure(const Solution &solution, Type actualType,
Type requiredType,
ArrayRef<unsigned> mismatches,
ConstraintLocator *locator)
: ContextualFailure(solution, actualType, requiredType, locator),
Mismatches(mismatches) {
assert(actualType->is<BoundGenericType>());
assert(requiredType->is<BoundGenericType>());
}
bool diagnoseAsError() override;
private:
void emitNotesForMismatches() {
for (unsigned position : Mismatches) {
emitNoteForMismatch(position);
}
}
void emitNoteForMismatch(int mismatchPosition);
std::optional<Diag<Type, Type>>
getDiagnosticFor(ContextualTypePurpose context);
/// The actual type being used.
BoundGenericType *getActual() const {
return getFromType()->castTo<BoundGenericType>();
}
/// The type needed by the generic requirement.
BoundGenericType *getRequired() const {
return getToType()->castTo<BoundGenericType>();
}
};
/// Diagnose failures related to conversion between throwing function type
/// and non-throwing one e.g.
///
/// ```swift
/// func foo<T>(_ t: T) throws -> Void {}
/// let _: (Int) -> Void = foo // `foo` can't be implicitly converted to
/// // non-throwing type `(Int) -> Void`
/// ```
class ThrowingFunctionConversionFailure final : public ContextualFailure {
public:
ThrowingFunctionConversionFailure(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator)
: ContextualFailure(solution, fromType, toType, locator) {
#ifndef NDEBUG
auto fnType1 = fromType->castTo<FunctionType>();
auto fnType2 = toType->castTo<FunctionType>();
assert(fnType1->isThrowing() != fnType2->isThrowing());
#endif
}
bool diagnoseAsError() override;
};
/// Diagnose failures related to conversion between the thrown error type
/// of two function types, e.g.,
///
/// ```swift
/// func foo<T>(_ t: T) throws(MyError) -> Void {}
/// let _: (Int) throws (OtherError)-> Void = foo
/// // `MyError` can't be implicitly converted to `OtherError`
/// ```
class ThrownErrorTypeConversionFailure final : public ContextualFailure {
public:
ThrownErrorTypeConversionFailure(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator)
: ContextualFailure(solution, fromType, toType, locator) {
}
bool diagnoseAsError() override;
};
/// Diagnose failures related to conversion between 'async' function type
/// and a synchronous one e.g.
///
/// ```swift
/// func foo<T>(_ t: T) async -> Void {}
/// let _: (Int) -> Void = foo // `foo` can't be implicitly converted to
/// // synchronous function type `(Int) -> Void`
/// ```
class AsyncFunctionConversionFailure final : public ContextualFailure {
public:
AsyncFunctionConversionFailure(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator)
: ContextualFailure(solution, fromType, toType, locator) {
#ifndef NDEBUG
auto fnType1 = fromType->castTo<FunctionType>();
auto fnType2 = toType->castTo<FunctionType>();
assert(fnType1->isAsync() != fnType2->isAsync());
#endif
}
bool diagnoseAsError() override;
};
/// Diagnose failures related attempt to implicitly convert types which
/// do not support such implicit conversion.
/// "as" or "as!" has to be specified explicitly in cases like that.
class MissingExplicitConversionFailure final : public ContextualFailure {
public:
MissingExplicitConversionFailure(const Solution &solution, Type fromType,
Type toType, ConstraintLocator *locator)
: ContextualFailure(solution, fromType, toType, locator) {}
ASTNode getAnchor() const override;