-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathCSFix.h
1884 lines (1464 loc) · 67.3 KB
/
CSFix.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
//===--- CSFix.h - Constraint Fixes ---------------------------------------===//
//
// 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 fixes.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SEMA_CSFIX_H
#define SWIFT_SEMA_CSFIX_H
#include "ConstraintLocator.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Identifier.h"
#include "swift/AST/Type.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Debug.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/TrailingObjects.h"
#include <string>
namespace llvm {
class raw_ostream;
}
namespace swift {
class SourceManager;
namespace constraints {
class OverloadChoice;
class ConstraintSystem;
class ConstraintLocator;
class ConstraintLocatorBuilder;
enum class ConversionRestrictionKind;
class Solution;
/// Describes the kind of fix to apply to the given constraint before
/// visiting it.
///
/// Note: values 0 and 1 are reserved for empty and tombstone kinds.
enum class FixKind : uint8_t {
/// Introduce a '!' to force an optional unwrap.
ForceOptional = 2,
/// Unwrap an optional base when we have a member access.
UnwrapOptionalBase,
UnwrapOptionalBaseWithOptionalResult,
/// Append 'as! T' to force a downcast to the specified type.
ForceDowncast,
/// Introduce a '&' to take the address of an lvalue.
AddressOf,
/// Remove extraneous use of `&`.
RemoveAddressOf,
/// Replace a coercion ('as') with a forced checked cast ('as!').
CoerceToCheckedCast,
/// Mark function type as explicitly '@escaping'.
ExplicitlyEscaping,
/// Arguments have labeling failures - missing/extraneous or incorrect
/// labels attached to the, fix it by suggesting proper labels.
RelabelArguments,
/// Treat rvalue as lvalue
TreatRValueAsLValue,
/// Add a new conformance to the type to satisfy a requirement.
AddConformance,
/// Skip same-type generic requirement constraint,
/// and assume that types are equal.
SkipSameTypeRequirement,
/// Skip superclass generic requirement constraint,
/// and assume that types are related.
SkipSuperclassRequirement,
/// Fix up one of the sides of conversion to make it seem
/// like the types are aligned.
ContextualMismatch,
/// Fix up the generic arguments of two types so they match each other.
GenericArgumentsMismatch,
/// Fix up @autoclosure argument to the @autoclosure parameter,
/// to for a call to be able to foward it properly, since
/// @autoclosure conversions are unsupported starting from
/// Swift version 5.
AutoClosureForwarding,
/// Remove `!` or `?` because base is not an optional type.
RemoveUnwrap,
/// Add explicit `()` at the end of function or member to call it.
InsertCall,
/// Add '$' or '_' to refer to the property wrapper or storage instead
/// of the wrapped property type.
UsePropertyWrapper,
/// Remove '$' or '_' to refer to the wrapped property type instead of
/// the storage or property wrapper.
UseWrappedValue,
/// Instead of spelling out `subscript` directly, use subscript operator.
UseSubscriptOperator,
/// Requested name is not associated with a give base type,
/// fix this issue by pretending that member exists and matches
/// given arguments/result types exactly.
DefineMemberBasedOnUse,
/// Allow access to type member on instance or instance member on type
AllowTypeOrInstanceMember,
/// Allow expressions where 'mutating' method is only partially applied,
/// which means either not applied at all e.g. `Foo.bar` or only `Self`
/// is applied e.g. `foo.bar` or `Foo.bar(&foo)`.
///
/// Allow expressions where initializer call (either `self.init` or
/// `super.init`) is only partially applied.
AllowInvalidPartialApplication,
/// Non-required constructors may not be not inherited. Therefore when
/// constructing a class object, either the metatype must be statically
/// derived (rather than an arbitrary value of metatype type) or the
/// referenced constructor must be required.
AllowInvalidInitRef,
/// Allow a tuple to be destructured with mismatched arity, or mismatched
/// types.
AllowTupleTypeMismatch,
/// Allow a function type to be destructured with mismatched parameter types
/// or return type.
AllowFunctionTypeMismatch,
/// Allow an invalid member access on a value of protocol type as if
/// that protocol type were a generic constraint requiring conformance
/// to that protocol.
AllowMemberRefOnExistential,
/// If there are fewer arguments than parameters, let's fix that up
/// by adding new arguments to the list represented as type variables.
AddMissingArguments,
/// If there are more arguments than parameters, let's fix that up
/// by removing extraneous arguments.
RemoveExtraneousArguments,
/// Allow single tuple closure parameter destructuring into N arguments.
AllowClosureParameterDestructuring,
/// If there is out-of-order argument, let's fix that by re-ordering.
MoveOutOfOrderArgument,
/// If there is a matching inaccessible member - allow it as if there
/// no access control.
AllowInaccessibleMember,
/// Allow KeyPaths to use AnyObject as root type
AllowAnyObjectKeyPathRoot,
/// Using subscript references in the keypath requires that each
/// of the index arguments to be Hashable.
TreatKeyPathSubscriptIndexAsHashable,
/// Allow an invalid reference to a member declaration as part
/// of a key path component.
AllowInvalidRefInKeyPath,
/// Remove `return` or default last expression of single expression
/// function to `Void` to conform to expected result type.
RemoveReturn,
/// Default ambiguous generic arguments to \c Any
DefaultGenericArgument,
/// Skip any unhandled constructs that occur within a closure argument that
/// matches up with a
/// parameter that has a function builder.
SkipUnhandledConstructInFunctionBuilder,
/// Allow invalid reference to a member declared as `mutating`
/// when base is an r-value type.
AllowMutatingMemberOnRValueBase,
/// Allow a single tuple parameter to be matched with N arguments
/// by forming all of the given arguments into a single tuple.
AllowTupleSplatForSingleParameter,
/// Allow a single argument type mismatch. This is the most generic
/// failure related to argument-to-parameter conversions.
AllowArgumentTypeMismatch,
/// Explicitly construct type conforming to `RawRepresentable` protocol
/// via forming `Foo(rawValue:)` instead of using its `RawValue` directly.
ExplicitlyConstructRawRepresentable,
/// Use raw value type associated with raw representative accessible
/// using `.rawValue` member.
UseValueTypeOfRawRepresentative,
/// If an array was passed to a variadic argument, give a specific diagnostic
/// and offer to drop the brackets if it's a literal.
ExpandArrayIntoVarargs,
/// Remove extraneous call to something which can't be invoked e.g.
/// a variable, a property etc.
RemoveCall,
AllowInvalidUseOfTrailingClosure,
/// Allow an ephemeral argument conversion for a parameter marked as being
/// non-ephemeral.
TreatEphemeralAsNonEphemeral,
/// Base type in reference to the contextual member e.g. `.foo` couldn't be
/// inferred and has to be specified explicitly.
SpecifyBaseTypeForContextualMember,
/// Type of the closure parameter used in the body couldn't be inferred
/// and has to be specified explicitly.
SpecifyClosureParameterType,
/// Closure return type has to be explicitly specified because it can't be
/// inferred in current context e.g. because it's a multi-statement closure.
SpecifyClosureReturnType,
/// Object literal type coudn't be inferred because the module where
/// the default type that implements the associated literal protocol
/// is declared was not imported.
SpecifyObjectLiteralTypeImport,
/// Allow any type (and not just class or class-constrained type) to
/// be convertible to AnyObject.
AllowNonClassTypeToConvertToAnyObject,
/// Member shadows a top-level name, such a name could only be accessed by
/// prefixing it with a module name.
AddQualifierToAccessTopLevelName,
/// A warning fix that allows a coercion to perform a force-cast.
AllowCoercionToForceCast,
/// Allow key path root type mismatch when applying a key path that has a
/// root type not convertible to the type of the base instance.
AllowKeyPathRootTypeMismatch,
/// Allow key path to be bound to a function type with more than 1 argument
AllowMultiArgFuncKeyPathMismatch,
/// Specify key path root type when it cannot be infered from context.
SpecifyKeyPathRootType,
};
class ConstraintFix {
ConstraintSystem &CS;
FixKind Kind;
ConstraintLocator *Locator;
/// Determines whether this fix is simplify a warning which doesn't
/// require immediate source changes.
bool IsWarning;
public:
ConstraintFix(ConstraintSystem &cs, FixKind kind, ConstraintLocator *locator,
bool warning = false)
: CS(cs), Kind(kind), Locator(locator), IsWarning(warning) {}
virtual ~ConstraintFix();
template <typename Fix>
const Fix *getAs() const {
return Fix::classof(this) ? static_cast<const Fix *>(this) : nullptr;
}
FixKind getKind() const { return Kind; }
bool isWarning() const { return IsWarning; }
virtual std::string getName() const = 0;
/// Coalesce this fix with the given secondary fixes and diagnose the failure.
///
/// The default implementation ignores \c secondaryFixes and calls
/// \c diagnose.
virtual bool coalesceAndDiagnose(const Solution &solution,
ArrayRef<ConstraintFix *> secondaryFixes,
bool asNote = false) const {
return diagnose(solution, asNote);
}
/// Diagnose a failure associated with this fix.
virtual bool diagnose(const Solution &solution,
bool asNote = false) const = 0;
using CommonFixesArray =
ArrayRef<std::pair<const Solution *, const ConstraintFix *>>;
virtual bool diagnoseForAmbiguity(CommonFixesArray commonFixes) const {
return false;
}
void print(llvm::raw_ostream &Out) const;
SWIFT_DEBUG_DUMP;
/// Retrieve anchor expression associated with this fix.
/// NOTE: such anchor comes directly from locator without
/// any simplication attempts.
ASTNode getAnchor() const;
ConstraintLocator *getLocator() const { return Locator; }
protected:
ConstraintSystem &getConstraintSystem() const { return CS; }
};
/// Unwrap an optional base when we have a member access.
class UnwrapOptionalBase final : public ConstraintFix {
DeclNameRef MemberName;
UnwrapOptionalBase(ConstraintSystem &cs, FixKind kind, DeclNameRef member,
ConstraintLocator *locator)
: ConstraintFix(cs, kind, locator), MemberName(member) {
assert(kind == FixKind::UnwrapOptionalBase ||
kind == FixKind::UnwrapOptionalBaseWithOptionalResult);
}
public:
std::string getName() const override {
return "unwrap optional base of member lookup";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static UnwrapOptionalBase *create(ConstraintSystem &cs, DeclNameRef member,
ConstraintLocator *locator);
static UnwrapOptionalBase *
createWithOptionalResult(ConstraintSystem &cs, DeclNameRef member,
ConstraintLocator *locator);
};
// Treat rvalue as if it was an lvalue
class TreatRValueAsLValue final : public ConstraintFix {
TreatRValueAsLValue(ConstraintSystem &cs, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::TreatRValueAsLValue, locator) {}
public:
std::string getName() const override { return "treat rvalue as lvalue"; }
bool diagnose(const Solution &solution, bool asNote = false) const override;
static TreatRValueAsLValue *create(ConstraintSystem &cs,
ConstraintLocator *locator);
};
/// Arguments have labeling failures - missing/extraneous or incorrect
/// labels attached to the, fix it by suggesting proper labels.
class RelabelArguments final
: public ConstraintFix,
private llvm::TrailingObjects<RelabelArguments, Identifier> {
friend TrailingObjects;
unsigned NumLabels;
RelabelArguments(ConstraintSystem &cs,
llvm::ArrayRef<Identifier> correctLabels,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::RelabelArguments, locator),
NumLabels(correctLabels.size()) {
std::uninitialized_copy(correctLabels.begin(), correctLabels.end(),
getLabelsBuffer().begin());
}
public:
std::string getName() const override { return "re-label argument(s)"; }
ArrayRef<Identifier> getLabels() const {
return {getTrailingObjects<Identifier>(), NumLabels};
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static RelabelArguments *create(ConstraintSystem &cs,
llvm::ArrayRef<Identifier> correctLabels,
ConstraintLocator *locator);
private:
MutableArrayRef<Identifier> getLabelsBuffer() {
return {getTrailingObjects<Identifier>(), NumLabels};
}
};
/// Add a new conformance to the type to satisfy a requirement.
class MissingConformance final : public ConstraintFix {
// Determines whether given protocol type comes from the context e.g.
// assignment destination or argument comparison.
bool IsContextual;
Type NonConformingType;
// This could either be a protocol or protocol composition.
Type ProtocolType;
MissingConformance(ConstraintSystem &cs, bool isContextual, Type type,
Type protocolType, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::AddConformance, locator),
IsContextual(isContextual), NonConformingType(type),
ProtocolType(protocolType) {}
public:
std::string getName() const override {
return "add missing protocol conformance";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static MissingConformance *forRequirement(ConstraintSystem &cs, Type type,
Type protocolType,
ConstraintLocator *locator);
static MissingConformance *forContextual(ConstraintSystem &cs, Type type,
Type protocolType,
ConstraintLocator *locator);
Type getNonConformingType() { return NonConformingType; }
Type getProtocolType() { return ProtocolType; }
};
/// Skip same-type generic requirement constraint,
/// and assume that types are equal.
class SkipSameTypeRequirement final : public ConstraintFix {
Type LHS, RHS;
SkipSameTypeRequirement(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::SkipSameTypeRequirement, locator), LHS(lhs),
RHS(rhs) {}
public:
std::string getName() const override {
return "skip same-type generic requirement";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
Type lhsType() { return LHS; }
Type rhsType() { return RHS; }
static SkipSameTypeRequirement *create(ConstraintSystem &cs, Type lhs,
Type rhs, ConstraintLocator *locator);
};
/// Skip 'superclass' generic requirement constraint,
/// and assume that types are equal.
class SkipSuperclassRequirement final : public ConstraintFix {
Type LHS, RHS;
SkipSuperclassRequirement(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::SkipSuperclassRequirement, locator),
LHS(lhs), RHS(rhs) {}
public:
std::string getName() const override {
return "skip superclass generic requirement";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
Type subclassType() { return LHS; }
Type superclassType() { return RHS; }
static SkipSuperclassRequirement *
create(ConstraintSystem &cs, Type lhs, Type rhs, ConstraintLocator *locator);
};
/// For example: Sometimes type returned from the body of the
/// closure doesn't match expected contextual type:
///
/// func foo(_: () -> Int) {}
/// foo { "ultimate question" }
///
/// Body of the closure produces `String` type when `Int` is expected
/// by the context.
class ContextualMismatch : public ConstraintFix {
Type LHS, RHS;
protected:
ContextualMismatch(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::ContextualMismatch, locator), LHS(lhs),
RHS(rhs) {}
ContextualMismatch(ConstraintSystem &cs, FixKind kind, Type lhs, Type rhs,
ConstraintLocator *locator, bool warning = false)
: ConstraintFix(cs, kind, locator, warning), LHS(lhs), RHS(rhs) {}
public:
std::string getName() const override { return "fix contextual mismatch"; }
Type getFromType() const { return LHS; }
Type getToType() const { return RHS; }
bool diagnose(const Solution &solution, bool asNote = false) const override;
static ContextualMismatch *create(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator);
};
/// Mark function type as explicitly '@escaping'.
class MarkExplicitlyEscaping final : public ContextualMismatch {
MarkExplicitlyEscaping(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::ExplicitlyEscaping, lhs, rhs, locator) {
}
public:
std::string getName() const override { return "add @escaping"; }
bool diagnose(const Solution &solution, bool asNote = false) const override;
static MarkExplicitlyEscaping *create(ConstraintSystem &cs, Type lhs,
Type rhs, ConstraintLocator *locator);
};
/// Introduce a '!' to force an optional unwrap.
class ForceOptional final : public ContextualMismatch {
ForceOptional(ConstraintSystem &cs, Type fromType, Type toType,
ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::ForceOptional, fromType, toType,
locator) {
assert(fromType && "Base type must not be null");
assert(fromType->getOptionalObjectType() &&
"Unwrapped type must not be null");
}
public:
std::string getName() const override { return "force optional"; }
bool diagnose(const Solution &solution, bool asNote = false) const override;
static ForceOptional *create(ConstraintSystem &cs, Type fromType, Type toType,
ConstraintLocator *locator);
};
/// This is a contextual mismatch between throwing and non-throwing
/// function types, repair it by dropping `throws` attribute.
class DropThrowsAttribute final : public ContextualMismatch {
DropThrowsAttribute(ConstraintSystem &cs, FunctionType *fromType,
FunctionType *toType, ConstraintLocator *locator)
: ContextualMismatch(cs, fromType, toType, locator) {
assert(fromType->throws() != toType->throws());
}
public:
std::string getName() const override { return "drop 'throws' attribute"; }
bool diagnose(const Solution &solution, bool asNote = false) const override;
static DropThrowsAttribute *create(ConstraintSystem &cs,
FunctionType *fromType,
FunctionType *toType,
ConstraintLocator *locator);
};
/// Append 'as! T' to force a downcast to the specified type.
class ForceDowncast final : public ContextualMismatch {
ForceDowncast(ConstraintSystem &cs, Type fromType, Type toType,
ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::ForceDowncast, fromType, toType,
locator) {}
public:
std::string getName() const override;
bool diagnose(const Solution &solution, bool asNote = false) const override;
static ForceDowncast *create(ConstraintSystem &cs, Type fromType, Type toType,
ConstraintLocator *locator);
};
/// Introduce a '&' to take the address of an lvalue.
class AddAddressOf final : public ContextualMismatch {
AddAddressOf(ConstraintSystem &cs, Type argTy, Type paramTy,
ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::AddressOf, argTy, paramTy, locator) {}
public:
std::string getName() const override { return "add address-of"; }
bool diagnose(const Solution &solution, bool asNote = false) const override;
static AddAddressOf *create(ConstraintSystem &cs, Type argTy, Type paramTy,
ConstraintLocator *locator);
};
class RemoveAddressOf final : public ContextualMismatch {
RemoveAddressOf(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::RemoveAddressOf, lhs, rhs, locator) {}
public:
std::string getName() const override {
return "remove extraneous use of `&`";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static RemoveAddressOf *create(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator);
};
/// Detect situations where two type's generic arguments must
/// match but are not convertible e.g.
///
/// ```swift
/// struct F<G> {}
/// let _:F<Int> = F<Bool>()
/// ```
class GenericArgumentsMismatch final
: public ContextualMismatch,
private llvm::TrailingObjects<GenericArgumentsMismatch, unsigned> {
friend TrailingObjects;
unsigned NumMismatches;
protected:
GenericArgumentsMismatch(ConstraintSystem &cs, Type actual, Type required,
llvm::ArrayRef<unsigned> mismatches,
ConstraintLocator *locator)
: ContextualMismatch(cs, FixKind::GenericArgumentsMismatch, actual,
required, locator),
NumMismatches(mismatches.size()) {
assert(actual->is<BoundGenericType>());
assert(required->is<BoundGenericType>());
std::uninitialized_copy(mismatches.begin(), mismatches.end(),
getMismatchesBuf().begin());
}
public:
std::string getName() const override {
return "fix generic argument mismatch";
}
ArrayRef<unsigned> getMismatches() const {
return {getTrailingObjects<unsigned>(), NumMismatches};
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static GenericArgumentsMismatch *create(ConstraintSystem &cs, Type actual,
Type required,
llvm::ArrayRef<unsigned> mismatches,
ConstraintLocator *locator);
private:
MutableArrayRef<unsigned> getMismatchesBuf() {
return {getTrailingObjects<unsigned>(), NumMismatches};
}
};
/// Detect situations where key path doesn't have capability required
/// by the context e.g. read-only vs. writable, or either root or value
/// types are incorrect e.g.
///
/// ```swift
/// struct S { let foo: Int }
/// let _: WritableKeyPath<S, Int> = \.foo
/// ```
///
/// Here context requires a writable key path but `foo` property is
/// read-only.
class KeyPathContextualMismatch final : public ContextualMismatch {
KeyPathContextualMismatch(ConstraintSystem &cs, Type lhs, Type rhs,
ConstraintLocator *locator)
: ContextualMismatch(cs, lhs, rhs, locator) {}
public:
std::string getName() const override {
return "fix key path contextual mismatch";
}
static KeyPathContextualMismatch *
create(ConstraintSystem &cs, Type lhs, Type rhs, ConstraintLocator *locator);
};
/// Detect situations when argument of the @autoclosure parameter is itself
/// marked as @autoclosure and is not applied. Form a fix which suggests a
/// proper way to forward such arguments, e.g.:
///
/// ```swift
/// func foo(_ fn: @autoclosure () -> Int) {}
/// func bar(_ fn: @autoclosure () -> Int) {
/// foo(fn) // error - fn should be called
/// }
/// ```
class AutoClosureForwarding final : public ConstraintFix {
AutoClosureForwarding(ConstraintSystem &cs, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::AutoClosureForwarding, locator) {}
public:
std::string getName() const override { return "fix @autoclosure forwarding"; }
bool diagnose(const Solution &solution, bool asNote = false) const override;
static AutoClosureForwarding *create(ConstraintSystem &cs,
ConstraintLocator *locator);
};
/// Allow invalid pointer conversions for autoclosure result types as if the
/// pointer type is a function parameter rather than an autoclosure result.
class AllowAutoClosurePointerConversion final : public ContextualMismatch {
AllowAutoClosurePointerConversion(ConstraintSystem &cs, Type pointeeType,
Type pointerType, ConstraintLocator *locator)
: ContextualMismatch(cs, pointeeType, pointerType, locator) {}
public:
std::string getName() const override {
return "allow pointer conversion for autoclosure result type";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static AllowAutoClosurePointerConversion *create(ConstraintSystem &cs,
Type pointeeType,
Type pointerType,
ConstraintLocator *locator);
};
class RemoveUnwrap final : public ConstraintFix {
Type BaseType;
RemoveUnwrap(ConstraintSystem &cs, Type baseType, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::RemoveUnwrap, locator), BaseType(baseType) {}
public:
std::string getName() const override {
return "remove unwrap operator `!` or `?`";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static RemoveUnwrap *create(ConstraintSystem &cs, Type baseType,
ConstraintLocator *locator);
};
class InsertExplicitCall final : public ConstraintFix {
InsertExplicitCall(ConstraintSystem &cs, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::InsertCall, locator) {}
public:
std::string getName() const override {
return "insert explicit `()` to make a call";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static InsertExplicitCall *create(ConstraintSystem &cs,
ConstraintLocator *locator);
};
class UsePropertyWrapper final : public ConstraintFix {
VarDecl *Wrapped;
bool UsingStorageWrapper;
Type Base;
Type Wrapper;
UsePropertyWrapper(ConstraintSystem &cs, VarDecl *wrapped,
bool usingStorageWrapper, Type base, Type wrapper,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::UsePropertyWrapper, locator),
Wrapped(wrapped), UsingStorageWrapper(usingStorageWrapper), Base(base),
Wrapper(wrapper) {}
public:
std::string getName() const override {
return "insert '$' or '_' to use property wrapper type instead of wrapped type";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static UsePropertyWrapper *create(ConstraintSystem &cs, VarDecl *wrapped,
bool usingStorageWrapper, Type base,
Type wrapper, ConstraintLocator *locator);
};
class UseWrappedValue final : public ConstraintFix {
VarDecl *PropertyWrapper;
Type Base;
Type Wrapper;
UseWrappedValue(ConstraintSystem &cs, VarDecl *propertyWrapper, Type base,
Type wrapper, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::UseWrappedValue, locator),
PropertyWrapper(propertyWrapper), Base(base), Wrapper(wrapper) {}
bool usingStorageWrapper() const {
auto nameStr = PropertyWrapper->getName().str();
return !nameStr.startswith("_");
}
public:
std::string getName() const override {
return "remove '$' or _ to use wrapped type instead of wrapper type";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static UseWrappedValue *create(ConstraintSystem &cs, VarDecl *propertyWrapper,
Type base, Type wrapper,
ConstraintLocator *locator);
};
class UseSubscriptOperator final : public ConstraintFix {
UseSubscriptOperator(ConstraintSystem &cs, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::UseSubscriptOperator, locator) {}
public:
std::string getName() const override {
return "replace '.subscript(...)' with subscript operator";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static UseSubscriptOperator *create(ConstraintSystem &cs,
ConstraintLocator *locator);
};
class DefineMemberBasedOnUse final : public ConstraintFix {
Type BaseType;
DeclNameRef Name;
/// Whether or not the member error is already diagnosed. This can happen
/// when referencing an erroneous member, and the error is diagnosed at the
/// member declaration.
///
/// We still want to define erroneous members based on use in order to find
/// a solution through the new diagnostic infrastructure, but we don't
/// want to report a second error message.
bool AlreadyDiagnosed;
DefineMemberBasedOnUse(ConstraintSystem &cs, Type baseType, DeclNameRef member,
bool alreadyDiagnosed, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::DefineMemberBasedOnUse, locator),
BaseType(baseType), Name(member), AlreadyDiagnosed(alreadyDiagnosed) {}
public:
std::string getName() const override {
llvm::SmallVector<char, 16> scratch;
auto memberName = Name.getString(scratch);
return "define missing member named '" + memberName.str() +
"' based on its use";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
bool diagnoseForAmbiguity(CommonFixesArray commonFixes) const override;
static DefineMemberBasedOnUse *create(ConstraintSystem &cs, Type baseType,
DeclNameRef member, bool alreadyDiagnosed,
ConstraintLocator *locator);
static bool classof(const ConstraintFix *fix) {
return fix->getKind() == FixKind::DefineMemberBasedOnUse;
}
};
class AllowInvalidMemberRef : public ConstraintFix {
Type BaseType;
ValueDecl *Member;
DeclNameRef Name;
protected:
AllowInvalidMemberRef(ConstraintSystem &cs, FixKind kind, Type baseType,
ValueDecl *member, DeclNameRef name,
ConstraintLocator *locator)
: ConstraintFix(cs, kind, locator), BaseType(baseType), Member(member),
Name(name) {}
public:
Type getBaseType() const { return BaseType; }
ValueDecl *getMember() const { return Member; }
DeclNameRef getMemberName() const { return Name; }
};
class AllowMemberRefOnExistential final : public AllowInvalidMemberRef {
AllowMemberRefOnExistential(ConstraintSystem &cs, Type baseType,
DeclNameRef memberName, ValueDecl *member,
ConstraintLocator *locator)
: AllowInvalidMemberRef(cs, FixKind::AllowMemberRefOnExistential,
baseType, member, memberName, locator) {}
public:
std::string getName() const override {
llvm::SmallVector<char, 16> scratch;
auto memberName = getMemberName().getString(scratch);
return "allow access to invalid member '" + memberName.str() +
"' on value of protocol type";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static AllowMemberRefOnExistential *create(ConstraintSystem &cs,
Type baseType, ValueDecl *member,
DeclNameRef memberName,
ConstraintLocator *locator);
};
class AllowTypeOrInstanceMember final : public AllowInvalidMemberRef {
AllowTypeOrInstanceMember(ConstraintSystem &cs, Type baseType,
ValueDecl *member, DeclNameRef name,
ConstraintLocator *locator)
: AllowInvalidMemberRef(cs, FixKind::AllowTypeOrInstanceMember, baseType,
member, name, locator) {
assert(member);
}
public:
std::string getName() const override {
return "allow access to instance member on type or a type member on instance";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static AllowTypeOrInstanceMember *create(ConstraintSystem &cs, Type baseType,
ValueDecl *member, DeclNameRef usedName,
ConstraintLocator *locator);
};
class AllowInvalidPartialApplication final : public ConstraintFix {
AllowInvalidPartialApplication(bool isWarning, ConstraintSystem &cs,
ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::AllowInvalidPartialApplication, locator,
isWarning) {}
public:
std::string getName() const override {
return "allow partially applied 'mutating' method";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static AllowInvalidPartialApplication *create(bool isWarning,
ConstraintSystem &cs,
ConstraintLocator *locator);
};
class AllowInvalidInitRef final : public ConstraintFix {
enum class RefKind {
DynamicOnMetatype,
ProtocolMetatype,
NonConstMetatype,
} Kind;
Type BaseType;
const ConstructorDecl *Init;
bool IsStaticallyDerived;
SourceRange BaseRange;
AllowInvalidInitRef(ConstraintSystem &cs, RefKind kind, Type baseTy,
ConstructorDecl *init, bool isStaticallyDerived,
SourceRange baseRange, ConstraintLocator *locator)
: ConstraintFix(cs, FixKind::AllowInvalidInitRef, locator), Kind(kind),
BaseType(baseTy), Init(init), IsStaticallyDerived(isStaticallyDerived),
BaseRange(baseRange) {}
public:
std::string getName() const override {
return "allow invalid initializer reference";
}
bool diagnose(const Solution &solution, bool asNote = false) const override;
static AllowInvalidInitRef *
dynamicOnMetatype(ConstraintSystem &cs, Type baseTy, ConstructorDecl *init,
SourceRange baseRange, ConstraintLocator *locator);
static AllowInvalidInitRef *
onProtocolMetatype(ConstraintSystem &cs, Type baseTy, ConstructorDecl *init,
bool isStaticallyDerived, SourceRange baseRange,