/
ConstraintSystem.h
6500 lines (5378 loc) · 242 KB
/
ConstraintSystem.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
//===--- ConstraintSystem.h - Constraint-based Type Checking ----*- C++ -*-===//
//
// 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 the constraint-based type checker, anchored by the
// \c ConstraintSystem class, which provides type checking and type
// inference for expressions.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SEMA_CONSTRAINT_SYSTEM_H
#define SWIFT_SEMA_CONSTRAINT_SYSTEM_H
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Debug.h"
#include "swift/Basic/LLVM.h"
#include "swift/Basic/OptionSet.h"
#include "swift/Sema/CSBindings.h"
#include "swift/Sema/CSFix.h"
#include "swift/Sema/Constraint.h"
#include "swift/Sema/ConstraintGraph.h"
#include "swift/Sema/ConstraintGraphScope.h"
#include "swift/Sema/ConstraintLocator.h"
#include "swift/Sema/OverloadChoice.h"
#include "swift/Sema/SolutionResult.h"
#include "swift/Sema/SyntacticElementTarget.h"
#include "llvm/ADT/MapVector.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetOperations.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/ilist.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Timer.h"
#include "llvm/Support/raw_ostream.h"
#include <cstddef>
#include <functional>
using namespace swift::constraints::inference;
namespace swift {
class Expr;
class FuncDecl;
class BraseStmt;
enum class TypeCheckExprFlags;
namespace constraints {
class ConstraintGraph;
class ConstraintGraphNode;
class ConstraintSystem;
class SyntacticElementTarget;
} // end namespace constraints
// Forward declare some TypeChecker related functions
// so they could be made friends of ConstraintSystem.
namespace TypeChecker {
llvm::Optional<BraceStmt *> applyResultBuilderBodyTransform(
FuncDecl *func, Type builderType,
bool ClosuresInResultBuilderDontParticipateInInference);
llvm::Optional<constraints::SyntacticElementTarget>
typeCheckExpression(constraints::SyntacticElementTarget &target,
OptionSet<TypeCheckExprFlags> options);
llvm::Optional<constraints::SyntacticElementTarget>
typeCheckTarget(constraints::SyntacticElementTarget &target,
OptionSet<TypeCheckExprFlags> options);
Type typeCheckParameterDefault(Expr *&, DeclContext *, Type, bool);
} // end namespace TypeChecker
} // end namespace swift
/// Allocate memory within the given constraint system.
void *operator new(size_t bytes, swift::constraints::ConstraintSystem& cs,
size_t alignment = 8);
namespace swift {
/// Specify how we handle the binding of underconstrained (free) type variables
/// within a solution to a constraint system.
enum class FreeTypeVariableBinding {
/// Disallow any binding of such free type variables.
Disallow,
/// Allow the free type variables to persist in the solution.
Allow,
/// Bind the type variables to UnresolvedType to represent the ambiguity.
UnresolvedType
};
/// Describes whether or not a result builder method is supported.
struct ResultBuilderOpSupport {
enum Classification {
Unsupported,
Unavailable,
Supported
};
Classification Kind;
ResultBuilderOpSupport(Classification Kind) : Kind(Kind) {}
/// Returns whether or not the builder method is supported. If
/// \p requireAvailable is true, an unavailable method will be considered
/// unsupported.
bool isSupported(bool requireAvailable) const {
switch (Kind) {
case Unsupported:
return false;
case Unavailable:
return !requireAvailable;
case Supported:
return true;
}
llvm_unreachable("Unhandled case in switch!");
}
};
namespace constraints {
struct ResultBuilder {
private:
DeclContext *DC;
/// An implicit variable that represents `Self` type of the result builder.
VarDecl *BuilderSelf;
Type BuilderType;
/// Cache of supported result builder operations.
llvm::SmallDenseMap<DeclName, ResultBuilderOpSupport> SupportedOps;
Identifier BuildOptionalId;
/// Counter used to give unique names to the variables that are
/// created implicitly.
unsigned VarCounter = 0;
public:
ResultBuilder(ConstraintSystem &CS, DeclContext *DC, Type builderType);
DeclContext *getDeclContext() const { return DC; }
Type getType() const { return BuilderType; }
NominalTypeDecl *getBuilderDecl() const {
return BuilderType->getAnyNominal();
}
VarDecl *getBuilderSelf() const { return BuilderSelf; }
Identifier getBuildOptionalId() const { return BuildOptionalId; }
bool supports(Identifier fnBaseName, ArrayRef<Identifier> argLabels = {},
bool checkAvailability = false);
bool supportsOptional() { return supports(getBuildOptionalId()); }
/// Checks whether the `buildPartialBlock` method is supported.
bool supportsBuildPartialBlock(bool checkAvailability);
/// Checks whether the builder can use `buildPartialBlock` to combine
/// expressions, instead of `buildBlock`.
bool canUseBuildPartialBlock();
Expr *buildCall(SourceLoc loc, Identifier fnName,
ArrayRef<Expr *> argExprs,
ArrayRef<Identifier> argLabels) const;
/// Build an implicit variable in this context.
VarDecl *buildVar(SourceLoc loc);
/// Build a reference to a given variable and mark it
/// as located at a given source location.
DeclRefExpr *buildVarRef(VarDecl *var, SourceLoc loc);
};
/// Describes the algorithm to use for trailing closure matching.
enum class TrailingClosureMatching {
/// Match a trailing closure to the first parameter that appears to work.
Forward,
/// Match a trailing closure to the last parameter.
Backward,
};
/// A handle that holds the saved state of a type variable, which
/// can be restored.
class SavedTypeVariableBinding {
/// The type variable that we saved the state of.
TypeVariableType *TypeVar;
/// The saved type variable options.
unsigned Options;
/// The parent or fixed type.
llvm::PointerUnion<TypeVariableType *, TypeBase *> ParentOrFixed;
public:
explicit SavedTypeVariableBinding(TypeVariableType *typeVar);
/// Restore the state of the type variable to the saved state.
void restore();
};
/// A set of saved type variable bindings.
using SavedTypeVariableBindings = SmallVector<SavedTypeVariableBinding, 16>;
class ConstraintLocator;
/// Describes a conversion restriction or a fix.
struct RestrictionOrFix {
union {
ConversionRestrictionKind Restriction;
ConstraintFix *TheFix;
};
bool IsRestriction;
public:
RestrictionOrFix(ConversionRestrictionKind restriction)
: Restriction(restriction), IsRestriction(true) { }
RestrictionOrFix(ConstraintFix *fix) : TheFix(fix), IsRestriction(false) {}
llvm::Optional<ConversionRestrictionKind> getRestriction() const {
if (IsRestriction)
return Restriction;
return llvm::None;
}
llvm::Optional<ConstraintFix *> getFix() const {
if (!IsRestriction)
return TheFix;
return llvm::None;
}
};
class ExpressionTimer {
public:
using AnchorType = llvm::PointerUnion<Expr *, ConstraintLocator *>;
private:
AnchorType Anchor;
ASTContext &Context;
llvm::TimeRecord StartTime;
/// The number of milliseconds from creation until
/// this timer is considered expired.
unsigned ThresholdInMillis;
bool PrintDebugTiming;
bool PrintWarning;
public:
/// This constructor sets a default threshold defined for all expressions
/// via compiler flag `solver-expression-time-threshold`.
ExpressionTimer(AnchorType Anchor, ConstraintSystem &CS);
ExpressionTimer(AnchorType Anchor, ConstraintSystem &CS, unsigned thresholdInMillis);
~ExpressionTimer();
AnchorType getAnchor() const { return Anchor; }
SourceRange getAffectedRange() const;
unsigned getWarnLimit() const {
return Context.TypeCheckerOpts.WarnLongExpressionTypeChecking;
}
llvm::TimeRecord startedAt() const { return StartTime; }
/// Return the elapsed process time (including fractional seconds)
/// as a double.
double getElapsedProcessTimeInFractionalSeconds() const {
llvm::TimeRecord endTime = llvm::TimeRecord::getCurrentTime(false);
return endTime.getProcessTime() - StartTime.getProcessTime();
}
/// Return the remaining process time in milliseconds until the
/// threshold specified during construction is reached.
unsigned getRemainingProcessTimeInMillis() const {
auto elapsed = unsigned(getElapsedProcessTimeInFractionalSeconds());
return elapsed >= ThresholdInMillis ? 0 : ThresholdInMillis - elapsed;
}
// Disable emission of warnings about expressions that take longer
// than the warning threshold.
void disableWarning() { PrintWarning = false; }
bool isExpired() const {
return getRemainingProcessTimeInMillis() == 0;
}
};
} // end namespace constraints
/// Options that describe how a type variable can be used.
enum TypeVariableOptions {
/// Whether the type variable can be bound to an lvalue type or not.
TVO_CanBindToLValue = 0x01,
/// Whether the type variable can be bound to an inout type or not.
TVO_CanBindToInOut = 0x02,
/// Whether the type variable can be bound to a non-escaping type or not.
TVO_CanBindToNoEscape = 0x04,
/// Whether the type variable can be bound to a hole or not.
TVO_CanBindToHole = 0x08,
/// Whether a more specific deduction for this type variable implies a
/// better solution to the constraint system.
TVO_PrefersSubtypeBinding = 0x10,
/// Whether the type variable can be bound to a pack type or not.
TVO_CanBindToPack = 0x20,
/// Whether the type variable can be bound only to a pack expansion type.
TVO_PackExpansion = 0x40,
};
/// The implementation object for a type variable used within the
/// constraint-solving type checker.
///
/// The implementation object for a type variable contains information about
/// the type variable, where it was generated, what protocols it must conform
/// to, what specific types it might be and, eventually, the fixed type to
/// which it is assigned.
class TypeVariableType::Implementation {
/// The locator that describes where this type variable was generated.
constraints::ConstraintLocator *locator;
/// Either the parent of this type variable within an equivalence
/// class of type variables, or the fixed type to which this type variable
/// type is bound.
llvm::PointerUnion<TypeVariableType *, TypeBase *> ParentOrFixed;
/// The corresponding node in the constraint graph.
constraints::ConstraintGraphNode *GraphNode = nullptr;
/// Index into the list of type variables, as used by the
/// constraint graph.
unsigned GraphIndex;
friend class constraints::SavedTypeVariableBinding;
public:
/// Retrieve the type variable associated with this implementation.
TypeVariableType *getTypeVariable() {
return reinterpret_cast<TypeVariableType *>(this) - 1;
}
/// Retrieve the type variable associated with this implementation.
const TypeVariableType *getTypeVariable() const {
return reinterpret_cast<const TypeVariableType *>(this) - 1;
}
explicit Implementation(constraints::ConstraintLocator *locator,
unsigned options)
: locator(locator), ParentOrFixed(getTypeVariable()) {
getTypeVariable()->Bits.TypeVariableType.Options = options;
}
/// Retrieve the unique ID corresponding to this type variable.
unsigned getID() const { return getTypeVariable()->getID(); }
unsigned getRawOptions() const {
return getTypeVariable()->Bits.TypeVariableType.Options;
}
void setRawOptions(unsigned bits) {
getTypeVariable()->Bits.TypeVariableType.Options = bits;
assert(getTypeVariable()->Bits.TypeVariableType.Options == bits
&& "Truncation");
}
/// Whether this type variable can bind to an LValueType.
bool canBindToLValue() const { return getRawOptions() & TVO_CanBindToLValue; }
/// Whether this type variable can bind to an InOutType.
bool canBindToInOut() const { return getRawOptions() & TVO_CanBindToInOut; }
/// Whether this type variable can bind to a noescape FunctionType.
bool canBindToNoEscape() const { return getRawOptions() & TVO_CanBindToNoEscape; }
/// Whether this type variable can bind to a PlaceholderType.
bool canBindToHole() const { return getRawOptions() & TVO_CanBindToHole; }
/// Whether this type variable can bind to a PackType.
bool canBindToPack() const { return getRawOptions() & TVO_CanBindToPack; }
/// Whether this type variable can bind only to PackExpansionType.
bool isPackExpansion() const { return getRawOptions() & TVO_PackExpansion; }
/// Whether this type variable prefers a subtype binding over a supertype
/// binding.
bool prefersSubtypeBinding() const {
return getRawOptions() & TVO_PrefersSubtypeBinding;
}
/// Retrieve the corresponding node in the constraint graph.
constraints::ConstraintGraphNode *getGraphNode() const { return GraphNode; }
/// Set the corresponding node in the constraint graph.
void setGraphNode(constraints::ConstraintGraphNode *newNode) {
GraphNode = newNode;
}
/// Retrieve the index into the constraint graph's list of type variables.
unsigned getGraphIndex() const {
assert(GraphNode && "Graph node isn't set");
return GraphIndex;
}
/// Set the index into the constraint graph's list of type variables.
void setGraphIndex(unsigned newIndex) {
GraphIndex = newIndex;
}
/// Check whether this type variable either has a representative that
/// is not itself or has a fixed type binding.
bool hasRepresentativeOrFixed() const {
// If we have a fixed type, we're done.
if (!ParentOrFixed.is<TypeVariableType *>())
return true;
// Check whether the representative is different from our own type
// variable.
return ParentOrFixed.get<TypeVariableType *>() != getTypeVariable();
}
/// Record the current type-variable binding.
void recordBinding(constraints::SavedTypeVariableBindings &record) {
record.push_back(constraints::SavedTypeVariableBinding(getTypeVariable()));
}
/// Retrieve the locator describing where this type variable was
/// created.
constraints::ConstraintLocator *getLocator() const {
return locator;
}
/// Retrieve the generic parameter opened by this type variable.
GenericTypeParamType *getGenericParameter() const;
/// Returns the \c ExprKind of this type variable if it's the type of an
/// atomic literal expression, meaning the literal can't be composed of subexpressions.
/// Otherwise, returns \c None.
llvm::Optional<ExprKind> getAtomicLiteralKind() const;
/// Determine whether this type variable represents a closure type.
bool isClosureType() const;
/// Determine whether this type variable represents a type of tap expression.
bool isTapType() const;
/// Determine whether this type variable represents one of the
/// parameter types associated with a closure.
bool isClosureParameterType() const;
/// Determine whether this type variable represents a closure result type.
bool isClosureResultType() const;
/// Determine whether this type variable represents
/// a type of a key path expression.
bool isKeyPathType() const;
/// Determine whether this type variable represents a value type of a key path
/// expression.
bool isKeyPathValue() const;
/// Determine whether this type variable represents a subscript result type.
bool isSubscriptResultType() const;
/// Determine whether this type variable represents an opened
/// type parameter pack.
bool isParameterPack() const;
/// Determine whether this type variable represents a code completion
/// expression.
bool isCodeCompletionToken() const;
/// Determine whether this type variable represents an opened opaque type.
bool isOpaqueType() const;
/// Retrieve the representative of the equivalence class to which this
/// type variable belongs.
///
/// \param record The record of changes made by retrieving the representative,
/// which can happen due to path compression. If null, path compression is
/// not performed.
TypeVariableType *
getRepresentative(constraints::SavedTypeVariableBindings *record) {
// Find the representative type variable.
auto result = getTypeVariable();
Implementation *impl = this;
while (impl->ParentOrFixed.is<TypeVariableType *>()) {
// Extract the representative.
auto nextTV = impl->ParentOrFixed.get<TypeVariableType *>();
if (nextTV == result)
break;
result = nextTV;
impl = &nextTV->getImpl();
}
if (impl == this || !record)
return result;
// Perform path compression.
impl = this;
while (impl->ParentOrFixed.is<TypeVariableType *>()) {
// Extract the representative.
auto nextTV = impl->ParentOrFixed.get<TypeVariableType *>();
if (nextTV == result)
break;
// Record the state change.
impl->recordBinding(*record);
impl->ParentOrFixed = result;
impl = &nextTV->getImpl();
}
return result;
}
/// Merge the equivalence class of this type variable with the
/// equivalence class of another type variable.
///
/// \param other The type variable to merge with.
///
/// \param record The record of state changes.
void mergeEquivalenceClasses(TypeVariableType *other,
constraints::SavedTypeVariableBindings *record) {
// Merge the equivalence classes corresponding to these two type
// variables. Always merge 'up' the constraint stack, because it is simpler.
if (getID() > other->getImpl().getID()) {
other->getImpl().mergeEquivalenceClasses(getTypeVariable(), record);
return;
}
auto otherRep = other->getImpl().getRepresentative(record);
if (record)
otherRep->getImpl().recordBinding(*record);
otherRep->getImpl().ParentOrFixed = getTypeVariable();
if (canBindToLValue() && !otherRep->getImpl().canBindToLValue()) {
if (record)
recordBinding(*record);
getTypeVariable()->Bits.TypeVariableType.Options &= ~TVO_CanBindToLValue;
}
if (canBindToInOut() && !otherRep->getImpl().canBindToInOut()) {
if (record)
recordBinding(*record);
getTypeVariable()->Bits.TypeVariableType.Options &= ~TVO_CanBindToInOut;
}
if (canBindToNoEscape() && !otherRep->getImpl().canBindToNoEscape()) {
if (record)
recordBinding(*record);
getTypeVariable()->Bits.TypeVariableType.Options &= ~TVO_CanBindToNoEscape;
}
}
/// Retrieve the fixed type that corresponds to this type variable,
/// if there is one.
///
/// \returns the fixed type associated with this type variable, or a null
/// type if there is no fixed type.
///
/// \param record The record of changes made by retrieving the representative,
/// which can happen due to path compression. If null, path compression is
/// not performed.
Type getFixedType(constraints::SavedTypeVariableBindings *record) {
// Find the representative type variable.
auto rep = getRepresentative(record);
Implementation &repImpl = rep->getImpl();
// Return the bound type if there is one, otherwise, null.
return repImpl.ParentOrFixed.dyn_cast<TypeBase *>();
}
/// Assign a fixed type to this equivalence class.
void assignFixedType(Type type,
constraints::SavedTypeVariableBindings *record) {
assert((!getFixedType(0) || getFixedType(0)->isEqual(type)) &&
"Already has a fixed type!");
auto rep = getRepresentative(record);
if (record)
rep->getImpl().recordBinding(*record);
rep->getImpl().ParentOrFixed = type.getPointer();
}
void setCanBindToLValue(constraints::SavedTypeVariableBindings *record,
bool enabled) {
auto &impl = getRepresentative(record)->getImpl();
if (record)
impl.recordBinding(*record);
if (enabled)
impl.getTypeVariable()->Bits.TypeVariableType.Options |=
TVO_CanBindToLValue;
else
impl.getTypeVariable()->Bits.TypeVariableType.Options &=
~TVO_CanBindToLValue;
}
void setCanBindToNoEscape(constraints::SavedTypeVariableBindings *record,
bool enabled) {
auto &impl = getRepresentative(record)->getImpl();
if (record)
impl.recordBinding(*record);
if (enabled)
impl.getTypeVariable()->Bits.TypeVariableType.Options |=
TVO_CanBindToNoEscape;
else
impl.getTypeVariable()->Bits.TypeVariableType.Options &=
~TVO_CanBindToNoEscape;
}
void enableCanBindToHole(constraints::SavedTypeVariableBindings *record) {
auto &impl = getRepresentative(record)->getImpl();
if (record)
impl.recordBinding(*record);
impl.getTypeVariable()->Bits.TypeVariableType.Options |= TVO_CanBindToHole;
}
/// Print the type variable to the given output stream.
void print(llvm::raw_ostream &OS);
private:
StringRef getTypeVariableOptions(TypeVariableOptions TVO) const {
#define ENTRY(Kind, String) case TypeVariableOptions::Kind: return String
switch (TVO) {
ENTRY(TVO_CanBindToLValue, "lvalue");
ENTRY(TVO_CanBindToInOut, "inout");
ENTRY(TVO_CanBindToNoEscape, "noescape");
ENTRY(TVO_CanBindToHole, "hole");
ENTRY(TVO_PrefersSubtypeBinding, "");
ENTRY(TVO_CanBindToPack, "pack");
ENTRY(TVO_PackExpansion, "pack expansion");
}
#undef ENTRY
}
};
namespace constraints {
template <typename T = Expr> T *castToExpr(ASTNode node) {
return cast<T>(node.get<Expr *>());
}
template <typename T = Expr> T *getAsExpr(ASTNode node) {
if (node.isNull())
return nullptr;
if (auto *E = node.dyn_cast<Expr *>())
return dyn_cast_or_null<T>(E);
return nullptr;
}
template <typename T> bool isExpr(ASTNode node) {
if (node.isNull() || !node.is<Expr *>())
return false;
auto *E = node.get<Expr *>();
return isa<T>(E);
}
template <typename T = Decl> T *getAsDecl(ASTNode node) {
if (auto *E = node.dyn_cast<Decl *>())
return dyn_cast_or_null<T>(E);
return nullptr;
}
template <typename T = TypeRepr>
T *getAsTypeRepr(ASTNode node) {
if (auto *type = node.dyn_cast<TypeRepr *>())
return dyn_cast_or_null<T>(type);
return nullptr;
}
template <typename T = Stmt>
T *getAsStmt(ASTNode node) {
if (auto *S = node.dyn_cast<Stmt *>())
return dyn_cast_or_null<T>(S);
return nullptr;
}
template <typename T = Pattern>
T *getAsPattern(ASTNode node) {
if (auto *P = node.dyn_cast<Pattern *>())
return dyn_cast_or_null<T>(P);
return nullptr;
}
template <typename T = Stmt> T *castToStmt(ASTNode node) {
return cast<T>(node.get<Stmt *>());
}
SourceLoc getLoc(ASTNode node);
SourceRange getSourceRange(ASTNode node);
/// The result of comparing two constraint systems that are a solutions
/// to the given set of constraints.
enum class SolutionCompareResult {
/// The two solutions are incomparable, because, e.g., because one
/// solution has some better decisions and some worse decisions than the
/// other.
Incomparable,
/// The two solutions are identical.
Identical,
/// The first solution is better than the second.
Better,
/// The second solution is better than the first.
Worse
};
/// An overload that has been selected in a particular solution.
///
/// A selected overload captures the specific overload choice (e.g., a
/// particular declaration) as well as the type to which the reference to the
/// declaration was opened, which may involve type variables.
struct SelectedOverload {
/// The overload choice.
const OverloadChoice choice;
/// The opened type of the base of the reference to this overload, if
/// we're referencing a member.
const Type openedFullType;
/// The opened type of the base of the reference to this overload, adjusted
/// for `@preconcurrency` or other contextual type-altering attributes.
const Type adjustedOpenedFullType;
/// The opened type produced by referring to this overload.
const Type openedType;
/// The opened type produced by referring to this overload, adjusted for
/// `@preconcurrency` or other contextual type-altering attributes.
const Type adjustedOpenedType;
/// The type that this overload binds. Note that this may differ from
/// adjustedOpenedType, for example it will include any IUO unwrapping that has taken
/// place.
const Type boundType;
};
/// Provides information about the application of a function argument to a
/// parameter.
class FunctionArgApplyInfo {
ArgumentList *ArgList;
Expr *ArgExpr;
unsigned ArgIdx;
Type ArgType;
unsigned ParamIdx;
Type FnInterfaceType;
FunctionType *FnType;
const ValueDecl *Callee;
FunctionArgApplyInfo(ArgumentList *argList, Expr *argExpr, unsigned argIdx,
Type argType, unsigned paramIdx, Type fnInterfaceType,
FunctionType *fnType, const ValueDecl *callee)
: ArgList(argList), ArgExpr(argExpr), ArgIdx(argIdx), ArgType(argType),
ParamIdx(paramIdx), FnInterfaceType(fnInterfaceType), FnType(fnType),
Callee(callee) {}
public:
static llvm::Optional<FunctionArgApplyInfo>
get(ArgumentList *argList, Expr *argExpr, unsigned argIdx, Type argType,
unsigned paramIdx, Type fnInterfaceType, FunctionType *fnType,
const ValueDecl *callee) {
assert(fnType);
if (argIdx >= argList->size())
return llvm::None;
if (paramIdx >= fnType->getNumParams())
return llvm::None;
return FunctionArgApplyInfo(argList, argExpr, argIdx, argType, paramIdx,
fnInterfaceType, fnType, callee);
}
/// \returns The list of the arguments used for this application.
ArgumentList *getArgList() const { return ArgList; }
/// \returns The argument being applied.
Expr *getArgExpr() const { return ArgExpr; }
/// \returns The position of the argument, starting at 1.
unsigned getArgPosition() const { return ArgIdx + 1; }
/// \returns The position of the parameter, starting at 1.
unsigned getParamPosition() const { return ParamIdx + 1; }
/// \returns The type of the argument being applied, including any generic
/// substitutions.
///
/// \param withSpecifier Whether to keep the inout or @lvalue specifier of
/// the argument, if any.
Type getArgType(bool withSpecifier = false) const {
return withSpecifier ? ArgType : ArgType->getWithoutSpecifierType();
}
/// \returns The label for the argument being applied.
Identifier getArgLabel() const {
return ArgList->getLabel(ArgIdx);
}
Identifier getParamLabel() const {
auto param = FnType->getParams()[ParamIdx];
return param.getLabel();
}
/// \returns A textual description of the argument suitable for diagnostics.
/// For an argument with an unambiguous label, this will the label. Otherwise
/// it will be its position in the argument list.
StringRef getArgDescription(SmallVectorImpl<char> &scratch) const {
llvm::raw_svector_ostream stream(scratch);
// Use the argument label only if it's unique within the argument list.
auto argLabel = getArgLabel();
auto useArgLabel = [&]() -> bool {
if (argLabel.empty())
return false;
SmallVector<Identifier, 4> scratch;
return llvm::count(ArgList->getArgumentLabels(scratch), argLabel) == 1;
};
if (useArgLabel()) {
stream << "'";
stream << argLabel;
stream << "'";
} else {
stream << "#";
stream << getArgPosition();
}
return StringRef(scratch.data(), scratch.size());
}
/// Whether the argument is a trailing closure.
bool isTrailingClosure() const {
return ArgList->isTrailingClosureIndex(ArgIdx);
}
/// \returns The interface type for the function being applied. Note that this
/// may not a function type, for example it could be a generic parameter.
Type getFnInterfaceType() const { return FnInterfaceType; }
/// \returns The function type being applied, including any generic
/// substitutions.
FunctionType *getFnType() const { return FnType; }
/// \returns The callee for the application.
const ValueDecl *getCallee() const { return Callee; }
private:
Type getParamTypeImpl(AnyFunctionType *fnTy,
bool lookThroughAutoclosure) const {
auto param = fnTy->getParams()[ParamIdx];
auto paramTy = param.getPlainType();
if (lookThroughAutoclosure && param.isAutoClosure())
paramTy = paramTy->castTo<FunctionType>()->getResult();
return paramTy;
}
public:
/// \returns The type of the parameter which the argument is being applied to,
/// including any generic substitutions.
///
/// \param lookThroughAutoclosure Whether an @autoclosure () -> T parameter
/// should be treated as being of type T.
Type getParamType(bool lookThroughAutoclosure = true) const {
return getParamTypeImpl(FnType, lookThroughAutoclosure);
}
/// \returns The interface type of the parameter which the argument is being
/// applied to.
///
/// \param lookThroughAutoclosure Whether an @autoclosure () -> T parameter
/// should be treated as being of type T.
Type getParamInterfaceType(bool lookThroughAutoclosure = true) const {
auto interfaceFnTy = FnInterfaceType->getAs<AnyFunctionType>();
if (!interfaceFnTy) {
// If the interface type isn't a function, then just return the resolved
// parameter type.
return getParamType(lookThroughAutoclosure)->mapTypeOutOfContext();
}
return getParamTypeImpl(interfaceFnTy, lookThroughAutoclosure);
}
/// \returns The flags of the parameter which the argument is being applied
/// to.
ParameterTypeFlags getParameterFlags() const {
return FnType->getParams()[ParamIdx].getParameterFlags();
}
ParameterTypeFlags getParameterFlagsAtIndex(unsigned idx) const {
return FnType->getParams()[idx].getParameterFlags();
}
};
/// Describes an aspect of a solution that affects its overall score, i.e., a
/// user-defined conversions.
enum ScoreKind: unsigned int {
// These values are used as indices into a Score value.
/// A fix needs to be applied to the source.
SK_Fix,
/// A hole in the constraint system.
SK_Hole,
/// A reference to an @unavailable declaration.
SK_Unavailable,
/// A reference to an async function in a synchronous context.
///
/// \note Any score kind after this is considered a conversion that doesn't
/// require fixing the source and will be ignored during code completion.
SK_AsyncInSyncMismatch,
/// Synchronous function in an asynchronous context or a conversion of
/// a synchronous function to an asynchronous one.
SK_SyncInAsync,
/// A use of the "forward" scan for trailing closures.
SK_ForwardTrailingClosure,
/// A use of a disfavored overload.
SK_DisfavoredOverload,
/// A member for an \c UnresolvedMemberExpr found via unwrapped optional base.
SK_UnresolvedMemberViaOptional,
/// An implicit force of an implicitly unwrapped optional value.
SK_ForceUnchecked,
/// An implicit conversion from a value of one type (lhs)
/// to another type (rhs) via implicit initialization of
/// `rhs` type with an argument of `lhs` value.
SK_ImplicitValueConversion,
/// A user-defined conversion.
SK_UserConversion,
/// A non-trivial function conversion.
SK_FunctionConversion,
/// A literal expression bound to a non-default literal type.
SK_NonDefaultLiteral,
/// An implicit upcast conversion between collection types.
SK_CollectionUpcastConversion,
/// A value-to-optional conversion.
SK_ValueToOptional,
/// A conversion to an empty existential type ('Any' or '{}').
SK_EmptyExistentialConversion,
/// A key path application subscript.
SK_KeyPathSubscript,
/// A conversion from a string, array, or inout to a pointer.
SK_ValueToPointerConversion,
/// A closure/function conversion to an autoclosure parameter.
SK_FunctionToAutoClosureConversion,
/// A type with a missing conformance(s) that has be synthesized
/// or diagnosed later, such types are allowed to appear in
/// a valid solution.
SK_MissingSynthesizableConformance,
/// An unapplied reference to a function. The purpose of this
/// score bit is to prune overload choices that are functions
/// when a solution has already been found using property.
///
/// \Note The solver only prefers variables over functions
/// to resolve ambiguities, so please be sure that any score
/// kind added after this is truly less impactful. Only other
/// ambiguity tie-breakers should go after this; anything else
/// should be added above.
SK_UnappliedFunction,
SK_LastScoreKind = SK_UnappliedFunction,
};
/// The number of score kinds.