-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathConstraint.cpp
1143 lines (1017 loc) · 43.7 KB
/
Constraint.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- Constraint.cpp - Constraint in the Type Checker ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the \c Constraint class and its related types,
// which is used by the constraint-based type checker to describe a
// constraint that must be solved.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Compiler.h"
#include "swift/Sema/Constraint.h"
#include "swift/Sema/ConstraintSystem.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
using namespace swift;
using namespace constraints;
Constraint::Constraint(ConstraintKind kind, ArrayRef<Constraint *> constraints,
bool isIsolated, ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(kind), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(false), HasRestriction(false),
IsActive(false), IsDisabled(false), IsDisabledForPerformance(false),
RememberChoice(false), IsFavored(false), IsIsolated(isIsolated),
Nested(constraints), Locator(locator) {
assert(kind == ConstraintKind::Disjunction ||
kind == ConstraintKind::Conjunction);
#ifndef NDEBUG
if (isIsolated)
assert(kind == ConstraintKind::Conjunction &&
"Isolation applies only to conjunctions");
#endif
std::uninitialized_copy(typeVars.begin(), typeVars.end(),
getTypeVariablesBuffer().begin());
}
static bool isAdmissibleType(Type type) {
return !type->hasUnboundGenericType() && !type->hasTypeParameter();
}
Constraint::Constraint(ConstraintKind Kind, Type First, Type Second,
ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(Kind), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(false), HasRestriction(false),
IsActive(false), IsDisabled(false), IsDisabledForPerformance(false),
RememberChoice(false), IsFavored(false), IsIsolated(false),
Types{First, Second, Type()},
Locator(locator) {
ASSERT(isAdmissibleType(First));
ASSERT(isAdmissibleType(Second));
switch (Kind) {
case ConstraintKind::Bind:
case ConstraintKind::Equal:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Subtype:
case ConstraintKind::Conversion:
case ConstraintKind::BridgingConversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion:
case ConstraintKind::SubclassOf:
case ConstraintKind::NonisolatedConformsTo:
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::TransitivelyConformsTo:
case ConstraintKind::CheckedCast:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::OptionalObject:
case ConstraintKind::OneWayEqual:
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PropertyWrapper:
case ConstraintKind::BindTupleOfFunctionParams:
case ConstraintKind::PackElementOf:
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
case ConstraintKind::LValueObject:
break;
case ConstraintKind::DynamicCallableApplicableFunction:
ASSERT(First->is<FunctionType>()
&& "The left-hand side type should be a function type");
break;
case ConstraintKind::ValueMember:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueWitness:
llvm_unreachable("Wrong constructor for member constraint");
case ConstraintKind::Defaultable:
case ConstraintKind::FallbackType:
break;
case ConstraintKind::BindOverload:
llvm_unreachable("Wrong constructor for overload binding constraint");
case ConstraintKind::Disjunction:
llvm_unreachable("Disjunction constraints should use create()");
case ConstraintKind::Conjunction:
llvm_unreachable("Conjunction constraints should use create()");
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
llvm_unreachable("Key path constraint takes three types");
case ConstraintKind::SyntacticElement:
llvm_unreachable("Syntactic element constraint should use create()");
case ConstraintKind::ApplicableFunction:
llvm_unreachable(
"Application constraint should use create()");
}
std::uninitialized_copy(typeVars.begin(), typeVars.end(),
getTypeVariablesBuffer().begin());
}
Constraint::Constraint(ConstraintKind Kind, Type First, Type Second, Type Third,
ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(Kind), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(false), HasRestriction(false),
IsActive(false), IsDisabled(false), IsDisabledForPerformance(false),
RememberChoice(false), IsFavored(false), IsIsolated(false),
Types{First, Second, Third},
Locator(locator) {
ASSERT(isAdmissibleType(First));
ASSERT(isAdmissibleType(Second));
ASSERT(isAdmissibleType(Third));
switch (Kind) {
case ConstraintKind::Bind:
case ConstraintKind::Equal:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::Subtype:
case ConstraintKind::Conversion:
case ConstraintKind::BridgingConversion:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::OperatorArgumentConversion:
case ConstraintKind::SubclassOf:
case ConstraintKind::NonisolatedConformsTo:
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::TransitivelyConformsTo:
case ConstraintKind::CheckedCast:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::OptionalObject:
case ConstraintKind::ApplicableFunction:
case ConstraintKind::DynamicCallableApplicableFunction:
case ConstraintKind::ValueMember:
case ConstraintKind::ValueWitness:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::Defaultable:
case ConstraintKind::BindOverload:
case ConstraintKind::Disjunction:
case ConstraintKind::Conjunction:
case ConstraintKind::OneWayEqual:
case ConstraintKind::FallbackType:
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PropertyWrapper:
case ConstraintKind::SyntacticElement:
case ConstraintKind::BindTupleOfFunctionParams:
case ConstraintKind::PackElementOf:
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
case ConstraintKind::LValueObject:
llvm_unreachable("Wrong constructor");
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
break;
}
std::uninitialized_copy(typeVars.begin(), typeVars.end(),
getTypeVariablesBuffer().begin());
}
Constraint::Constraint(ConstraintKind kind, Type first, Type second,
DeclNameRef member, DeclContext *useDC,
FunctionRefInfo functionRefInfo,
ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(kind), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(true), HasRestriction(false),
IsActive(false), IsDisabled(false), IsDisabledForPerformance(false),
RememberChoice(false), IsFavored(false), IsIsolated(false),
Member{first, second, {member}},
Locator(locator) {
assert(kind == ConstraintKind::ValueMember ||
kind == ConstraintKind::UnresolvedValueMember);
TheFunctionRefInfo = functionRefInfo.getOpaqueValue();
assert(getFunctionRefInfo() == functionRefInfo);
assert(member && "Member constraint has no member");
assert(useDC && "Member constraint has no use DC");
std::copy(typeVars.begin(), typeVars.end(), getTypeVariablesBuffer().begin());
*getTrailingObjects<DeclContext *>() = useDC;
}
Constraint::Constraint(ConstraintKind kind, Type first, Type second,
ValueDecl *requirement, DeclContext *useDC,
FunctionRefInfo functionRefInfo,
ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(kind), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(true), HasRestriction(false),
IsActive(false), IsDisabled(false), IsDisabledForPerformance(false),
RememberChoice(false), IsFavored(false), IsIsolated(false),
Locator(locator) {
Member.First = first;
Member.Second = second;
Member.Member.Ref = requirement;
TheFunctionRefInfo = functionRefInfo.getOpaqueValue();
assert(kind == ConstraintKind::ValueWitness);
assert(getFunctionRefInfo() == functionRefInfo);
assert(requirement && "Value witness constraint has no requirement");
assert(useDC && "Member constraint has no use DC");
std::copy(typeVars.begin(), typeVars.end(), getTypeVariablesBuffer().begin());
*getTrailingObjects<DeclContext *>() = useDC;
}
Constraint::Constraint(Type type, OverloadChoice choice, DeclContext *useDC,
ConstraintFix *fix, ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(ConstraintKind::BindOverload), NumTypeVariables(typeVars.size()),
HasFix(fix != nullptr), HasDeclContext(true), HasRestriction(false),
IsActive(false), IsDisabled(bool(fix)), IsDisabledForPerformance(false),
RememberChoice(false), IsFavored(false), IsIsolated(false),
Overload{type}, Locator(locator) {
std::copy(typeVars.begin(), typeVars.end(), getTypeVariablesBuffer().begin());
if (fix)
*getTrailingObjects<ConstraintFix *>() = fix;
*getTrailingObjects<DeclContext *>() = useDC;
*getTrailingObjects<OverloadChoice>() = choice;
}
Constraint::Constraint(ConstraintKind kind,
ConversionRestrictionKind restriction, Type first,
Type second, ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(kind), Restriction(restriction), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(false), HasRestriction(true), IsActive(false),
IsDisabled(false), IsDisabledForPerformance(false), RememberChoice(false),
IsFavored(false), IsIsolated(false), Types{first, second, Type()},
Locator(locator) {
ASSERT(isAdmissibleType(first));
ASSERT(isAdmissibleType(second));
std::copy(typeVars.begin(), typeVars.end(), getTypeVariablesBuffer().begin());
}
Constraint::Constraint(ConstraintKind kind, ConstraintFix *fix, Type first,
Type second, ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(kind), NumTypeVariables(typeVars.size()),
HasFix(fix != nullptr), HasDeclContext(false), HasRestriction(false),
IsActive(false), IsDisabled(false), IsDisabledForPerformance(false),
RememberChoice(false), IsFavored(false), IsIsolated(false),
Types{first, second, Type()},
Locator(locator) {
ASSERT(isAdmissibleType(first));
ASSERT(isAdmissibleType(second));
std::copy(typeVars.begin(), typeVars.end(), getTypeVariablesBuffer().begin());
if (fix)
*getTrailingObjects<ConstraintFix *>() = fix;
}
Constraint::Constraint(ASTNode node, ContextualTypeInfo context,
bool isDiscarded, ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(ConstraintKind::SyntacticElement), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(false), HasRestriction(false), IsActive(false),
IsDisabled(false), IsDisabledForPerformance(false), RememberChoice(false),
IsFavored(false), IsIsolated(false), isDiscarded(isDiscarded),
SyntacticElement{node},
Locator(locator) {
std::copy(typeVars.begin(), typeVars.end(), getTypeVariablesBuffer().begin());
*getTrailingObjects<ContextualTypeInfo>() = context;
}
Constraint::Constraint(FunctionType *appliedFn, Type calleeType,
unsigned trailingClosureMatching, DeclContext *useDC,
ConstraintLocator *locator,
SmallPtrSetImpl<TypeVariableType *> &typeVars)
: Kind(ConstraintKind::ApplicableFunction), NumTypeVariables(typeVars.size()),
HasFix(false), HasDeclContext(true), HasRestriction(false), IsActive(false),
IsDisabled(false), IsDisabledForPerformance(false), RememberChoice(false),
IsFavored(false), IsIsolated(false),
trailingClosureMatching(trailingClosureMatching),
Locator(locator) {
ASSERT(isAdmissibleType(appliedFn));
ASSERT(isAdmissibleType(calleeType));
assert(trailingClosureMatching >= 0 && trailingClosureMatching <= 2);
assert(useDC);
Apply.AppliedFn = appliedFn;
Apply.Callee = calleeType;
std::copy(typeVars.begin(), typeVars.end(), getTypeVariablesBuffer().begin());
*getTrailingObjects<DeclContext *>() = useDC;
}
ProtocolDecl *Constraint::getProtocol() const {
assert((Kind == ConstraintKind::ConformsTo ||
Kind == ConstraintKind::NonisolatedConformsTo ||
Kind == ConstraintKind::LiteralConformsTo ||
Kind == ConstraintKind::TransitivelyConformsTo)
&& "Not a conformance constraint");
return Types.Second->castTo<ProtocolType>()->getDecl();
}
void Constraint::print(llvm::raw_ostream &Out, SourceManager *sm,
unsigned indent, bool skipLocator) const {
// Print all type variables as $T0 instead of _ here.
PrintOptions PO;
PO.PrintTypesForDebugging = true;
if (Kind == ConstraintKind::Disjunction ||
Kind == ConstraintKind::Conjunction) {
Out << (Kind == ConstraintKind::Disjunction ? "disjunction"
: "conjunction");
if (shouldRememberChoice())
Out << " (remembered)";
if (isIsolated())
Out << " (isolated)";
if (Locator) {
Out << " @ ";
Locator->dump(sm, Out);
}
Out << ":\n";
// Sort constraints by favored, unmarked, disabled
// for printing only.
std::vector<Constraint *> sortedConstraints(getNestedConstraints().begin(),
getNestedConstraints().end());
llvm::sort(sortedConstraints,
[](const Constraint *lhs, const Constraint *rhs) {
if (lhs->isFavored() != rhs->isFavored())
return lhs->isFavored();
if (lhs->isDisabled() != rhs->isDisabled())
return rhs->isDisabled();
return false;
});
interleave(
sortedConstraints,
[&](Constraint *constraint) {
Out.indent(indent + 2);
if (constraint->isDisabled())
Out << "> [disabled] ";
else if (constraint->isFavored())
Out << "> [favored] ";
else
Out << "> ";
constraint->print(Out, sm, indent,
/*skipLocator=*/constraint->getLocator() ==
Locator);
},
[&] { Out << "\n"; });
return;
}
if (Kind == ConstraintKind::SyntacticElement) {
auto *locator = getLocator();
auto element = getSyntacticElement();
if (auto patternBindingElt =
locator
->getLastElementAs<LocatorPathElt::PatternBindingElement>()) {
auto *patternBinding = cast<PatternBindingDecl>(element.get<Decl *>());
Out << "pattern binding element @ ";
Out << patternBindingElt->getIndex() << " : ";
Out << '\n';
patternBinding->getPattern(patternBindingElt->getIndex())->dump(Out, indent);
} else {
Out << "syntactic element ";
Out << '\n';
element.dump(Out, indent);
}
return;
}
Out << getFirstType()->getString(PO);
bool skipSecond = false;
switch (Kind) {
case ConstraintKind::Bind: Out << " bind "; break;
case ConstraintKind::Equal: Out << " equal "; break;
case ConstraintKind::BindParam: Out << " bind param "; break;
case ConstraintKind::BindToPointerType: Out << " bind to pointer "; break;
case ConstraintKind::Subtype: Out << " subtype "; break;
case ConstraintKind::Conversion: Out << " conv "; break;
case ConstraintKind::BridgingConversion: Out << " bridging conv "; break;
case ConstraintKind::ArgumentConversion: Out << " arg conv "; break;
case ConstraintKind::OperatorArgumentConversion:
Out << " operator arg conv "; break;
case ConstraintKind::SubclassOf: Out << " subclass of "; break;
case ConstraintKind::ConformsTo: Out << " conforms to "; break;
case ConstraintKind::NonisolatedConformsTo:
Out << " nonisolated conforms to ";
break;
case ConstraintKind::LiteralConformsTo: Out << " literal conforms to "; break;
case ConstraintKind::TransitivelyConformsTo: Out << " transitive conformance to "; break;
case ConstraintKind::CheckedCast: Out << " checked cast to "; break;
case ConstraintKind::ApplicableFunction: Out << " applicable fn "; break;
case ConstraintKind::DynamicCallableApplicableFunction:
Out << " dynamic callable applicable fn "; break;
case ConstraintKind::DynamicTypeOf: Out << " dynamicType type of "; break;
case ConstraintKind::EscapableFunctionOf: Out << " @escaping type of "; break;
case ConstraintKind::OpenedExistentialOf: Out << " opened archetype of "; break;
case ConstraintKind::OneWayEqual: Out << " one-way bind to "; break;
case ConstraintKind::FallbackType:
Out << " can fallback to ";
break;
case ConstraintKind::UnresolvedMemberChainBase:
Out << " unresolved member chain base ";
break;
case ConstraintKind::PropertyWrapper:
Out << " property wrapper with wrapped value of ";
break;
case ConstraintKind::KeyPath:
Out << " key path from ";
Out << getSecondType()->getString(PO);
Out << " → ";
Out << getThirdType()->getString(PO);
skipSecond = true;
break;
case ConstraintKind::KeyPathApplication:
Out << " key path projecting ";
Out << getSecondType()->getString(PO);
Out << " → ";
Out << getThirdType()->getString(PO);
skipSecond = true;
break;
case ConstraintKind::OptionalObject:
Out << " optional with object type "; break;
case ConstraintKind::BindOverload: {
Out << " bound to ";
auto overload = getOverloadChoice();
auto printDecl = [&] {
auto decl = overload.getDecl();
decl->dumpRef(Out);
Out << " : " << decl->getInterfaceType();
};
switch (overload.getKind()) {
case OverloadChoiceKind::Decl:
Out << "decl ";
printDecl();
break;
case OverloadChoiceKind::DeclViaDynamic:
Out << "decl-via-dynamic ";
printDecl();
break;
case OverloadChoiceKind::DeclViaBridge:
Out << "decl-via-bridge ";
printDecl();
break;
case OverloadChoiceKind::DeclViaUnwrappedOptional:
Out << "decl-via-unwrapped-optional ";
printDecl();
break;
case OverloadChoiceKind::DynamicMemberLookup:
case OverloadChoiceKind::KeyPathDynamicMemberLookup:
Out << "dynamic member lookup '" << overload.getName() << "'";
break;
case OverloadChoiceKind::TupleIndex:
Out << "tuple index " << overload.getTupleIndex();
break;
case OverloadChoiceKind::MaterializePack:
Out << "materialize pack";
break;
case OverloadChoiceKind::ExtractFunctionIsolation:
Out << "extract function islation";
break;
case OverloadChoiceKind::KeyPathApplication:
Out << "key path application";
break;
}
skipSecond = true;
break;
}
case ConstraintKind::ValueMember:
Out << "[." << getMember() << ": value] == ";
break;
case ConstraintKind::UnresolvedValueMember:
Out << "[(implicit) ." << getMember() << ": value] == ";
break;
case ConstraintKind::ValueWitness: {
auto requirement = getRequirement();
auto selfNominal = requirement->getDeclContext()->getSelfNominalTypeDecl();
Out << "[." << selfNominal->getName() << "::" << requirement->getName()
<< ": witness] == ";
break;
}
case ConstraintKind::Defaultable:
Out << " can default to ";
break;
case ConstraintKind::BindTupleOfFunctionParams:
Out << " bind tuple of function params to ";
break;
case ConstraintKind::PackElementOf:
Out << " element of pack expansion pattern ";
break;
case ConstraintKind::ShapeOf:
Out << " shape of ";
break;
case ConstraintKind::SameShape:
Out << " same-shape ";
break;
case ConstraintKind::ExplicitGenericArguments:
Out << " explicit generic argument binding ";
break;
case ConstraintKind::MaterializePackExpansion:
Out << " materialize pack expansion ";
break;
case ConstraintKind::LValueObject:
Out << " l-value object type ";
break;
case ConstraintKind::Disjunction:
llvm_unreachable("disjunction handled above");
case ConstraintKind::Conjunction:
llvm_unreachable("conjunction handled above");
case ConstraintKind::SyntacticElement:
llvm_unreachable("syntactic element handled above");
}
if (!skipSecond)
Out << getSecondType()->getString(PO);
if (auto restriction = getRestriction()) {
Out << ' ' << getName(*restriction);
}
if (getKind() == ConstraintKind::ApplicableFunction) {
if (auto trailingClosureMatching = getTrailingClosureMatching()) {
switch (*trailingClosureMatching) {
case TrailingClosureMatching::Forward:
Out << " [forward scan]";
break;
case TrailingClosureMatching::Backward:
Out << " [backward scan]";
break;
}
}
}
if (auto *fix = getFix()) {
Out << ' ';
fix->print(Out);
}
if (Locator && !skipLocator) {
Out << " @ ";
Locator->dump(sm, Out);
}
}
void Constraint::dump(SourceManager *sm) const {
print(llvm::errs(), sm);
llvm::errs() << "\n";
}
void Constraint::dump(ConstraintSystem *CS) const {
// Disable MSVC warning: only for use within the debugger.
#if SWIFT_COMPILER_IS_MSVC
#pragma warning(suppress: 4996)
#endif
dump(&CS->getASTContext().SourceMgr);
}
StringRef swift::constraints::getName(ConversionRestrictionKind kind) {
switch (kind) {
case ConversionRestrictionKind::DeepEquality:
return "[deep equality]";
case ConversionRestrictionKind::Superclass:
return "[superclass]";
case ConversionRestrictionKind::Existential:
return "[existential]";
case ConversionRestrictionKind::MetatypeToExistentialMetatype:
return "[metatype-to-existential-metatype]";
case ConversionRestrictionKind::ExistentialMetatypeToMetatype:
return "[existential-metatype-to-metatype]";
case ConversionRestrictionKind::ValueToOptional:
return "[value-to-optional]";
case ConversionRestrictionKind::OptionalToOptional:
return "[optional-to-optional]";
case ConversionRestrictionKind::ClassMetatypeToAnyObject:
return "[class-metatype-to-object]";
case ConversionRestrictionKind::ExistentialMetatypeToAnyObject:
return "[existential-metatype-to-object]";
case ConversionRestrictionKind::ProtocolMetatypeToProtocolClass:
return "[protocol-metatype-to-object]";
case ConversionRestrictionKind::ArrayToPointer:
return "[array-to-pointer]";
case ConversionRestrictionKind::ArrayToCPointer:
return "[array-to-c-pointer]";
case ConversionRestrictionKind::StringToPointer:
return "[string-to-pointer]";
case ConversionRestrictionKind::InoutToPointer:
return "[inout-to-pointer]";
case ConversionRestrictionKind::InoutToCPointer:
return "[inout-to-c-pointer]";
case ConversionRestrictionKind::PointerToPointer:
return "[pointer-to-pointer]";
case ConversionRestrictionKind::PointerToCPointer:
return "[pointer-to-c-pointer]";
case ConversionRestrictionKind::ArrayUpcast:
return "[array-upcast]";
case ConversionRestrictionKind::DictionaryUpcast:
return "[dictionary-upcast]";
case ConversionRestrictionKind::SetUpcast:
return "[set-upcast]";
case ConversionRestrictionKind::HashableToAnyHashable:
return "[hashable-to-anyhashable]";
case ConversionRestrictionKind::CFTollFreeBridgeToObjC:
return "[cf-toll-free-bridge-to-objc]";
case ConversionRestrictionKind::ObjCTollFreeBridgeToCF:
return "[objc-toll-free-bridge-to-cf]";
case ConversionRestrictionKind::CGFloatToDouble:
return "[CGFloat-to-Double]";
case ConversionRestrictionKind::DoubleToCGFloat:
return "[Double-to-CGFloat]";
}
llvm_unreachable("bad conversion restriction kind");
}
/// Recursively gather the set of type variables referenced by this constraint.
static void
gatherReferencedTypeVars(Constraint *constraint,
SmallPtrSetImpl<TypeVariableType *> &typeVars) {
switch (constraint->getKind()) {
case ConstraintKind::Disjunction:
for (auto nested : constraint->getNestedConstraints())
gatherReferencedTypeVars(nested, typeVars);
return;
case ConstraintKind::Conjunction:
typeVars.insert(constraint->getTypeVariables().begin(),
constraint->getTypeVariables().end());
return;
case ConstraintKind::KeyPath:
case ConstraintKind::KeyPathApplication:
constraint->getThirdType()->getTypeVariables(typeVars);
LLVM_FALLTHROUGH;
case ConstraintKind::ApplicableFunction:
case ConstraintKind::DynamicCallableApplicableFunction:
case ConstraintKind::Bind:
case ConstraintKind::BindParam:
case ConstraintKind::BindToPointerType:
case ConstraintKind::ArgumentConversion:
case ConstraintKind::Conversion:
case ConstraintKind::BridgingConversion:
case ConstraintKind::OperatorArgumentConversion:
case ConstraintKind::CheckedCast:
case ConstraintKind::Equal:
case ConstraintKind::Subtype:
case ConstraintKind::UnresolvedValueMember:
case ConstraintKind::ValueMember:
case ConstraintKind::ValueWitness:
case ConstraintKind::DynamicTypeOf:
case ConstraintKind::EscapableFunctionOf:
case ConstraintKind::OpenedExistentialOf:
case ConstraintKind::OptionalObject:
case ConstraintKind::Defaultable:
case ConstraintKind::SubclassOf:
case ConstraintKind::NonisolatedConformsTo:
case ConstraintKind::ConformsTo:
case ConstraintKind::LiteralConformsTo:
case ConstraintKind::TransitivelyConformsTo:
case ConstraintKind::OneWayEqual:
case ConstraintKind::FallbackType:
case ConstraintKind::UnresolvedMemberChainBase:
case ConstraintKind::PropertyWrapper:
case ConstraintKind::BindTupleOfFunctionParams:
case ConstraintKind::PackElementOf:
case ConstraintKind::ShapeOf:
case ConstraintKind::ExplicitGenericArguments:
case ConstraintKind::SameShape:
case ConstraintKind::MaterializePackExpansion:
case ConstraintKind::LValueObject:
constraint->getFirstType()->getTypeVariables(typeVars);
constraint->getSecondType()->getTypeVariables(typeVars);
break;
case ConstraintKind::BindOverload:
constraint->getFirstType()->getTypeVariables(typeVars);
// Special case: the base type of an overloading binding.
if (auto baseType = constraint->getOverloadChoice().getBaseType()) {
baseType->getTypeVariables(typeVars);
}
break;
case ConstraintKind::SyntacticElement:
typeVars.insert(constraint->getTypeVariables().begin(),
constraint->getTypeVariables().end());
break;
}
}
unsigned Constraint::countResolvedArgumentTypes(ConstraintSystem &cs) const {
auto *argumentFuncType = cs.getAppliedDisjunctionArgumentFunction(this);
if (!argumentFuncType)
return 0;
return llvm::count_if(argumentFuncType->getParams(), [&](const AnyFunctionType::Param arg) {
auto argType = cs.getFixedTypeRecursive(arg.getPlainType(), /*wantRValue=*/true);
return !argType->isTypeVariableOrMember();
});
}
bool Constraint::isExplicitConversion() const {
assert(Kind == ConstraintKind::Disjunction);
if (auto *locator = getLocator())
return isExpr<CoerceExpr>(locator->getAnchor());
return false;
}
Constraint *Constraint::create(ConstraintSystem &cs, ConstraintKind kind,
Type first, Type second,
ConstraintLocator *locator,
ArrayRef<TypeVariableType *> extraTypeVars) {
// Collect type variables.
SmallPtrSet<TypeVariableType *, 4> typeVars;
if (first->hasTypeVariable())
first->getTypeVariables(typeVars);
if (second && second->hasTypeVariable())
second->getTypeVariables(typeVars);
typeVars.insert(extraTypeVars.begin(), extraTypeVars.end());
// Conformance constraints expect an existential on the right-hand side.
assert((kind != ConstraintKind::ConformsTo &&
kind != ConstraintKind::NonisolatedConformsTo &&
kind != ConstraintKind::TransitivelyConformsTo) ||
second->isExistentialType());
// Literal protocol conformances expect a protocol.
assert((kind != ConstraintKind::LiteralConformsTo) ||
second->is<ProtocolType>());
// Create the constraint.
auto size =
totalSizeToAlloc<TypeVariableType *, ConstraintFix *, DeclContext *,
ContextualTypeInfo, OverloadChoice>(
typeVars.size(), /*hasFix=*/0, /*hasDeclContext=*/0,
/*hasContextualTypeInfo=*/0, /*hasOverloadChoice=*/0);
void *mem = cs.getAllocator().Allocate(size, alignof(Constraint));
return ::new (mem) Constraint(kind, first, second, locator, typeVars);
}
Constraint *Constraint::create(ConstraintSystem &cs, ConstraintKind kind,
Type first, Type second, Type third,
ConstraintLocator *locator,
ArrayRef<TypeVariableType *> extraTypeVars) {
// Collect type variables.
SmallPtrSet<TypeVariableType *, 4> typeVars(extraTypeVars.begin(),
extraTypeVars.end());
if (first->hasTypeVariable())
first->getTypeVariables(typeVars);
if (second->hasTypeVariable())
second->getTypeVariables(typeVars);
if (third->hasTypeVariable())
third->getTypeVariables(typeVars);
auto size =
totalSizeToAlloc<TypeVariableType *, ConstraintFix *, DeclContext *,
ContextualTypeInfo, OverloadChoice>(
typeVars.size(), /*hasFix=*/0, /*hasDeclContext=*/0,
/*hasContextualTypeInfo=*/0, /*hasOverloadChoice=*/0);
void *mem = cs.getAllocator().Allocate(size, alignof(Constraint));
return ::new (mem) Constraint(kind,
first, second, third,
locator, typeVars);
}
Constraint *Constraint::createMemberOrOuterDisjunction(
ConstraintSystem &cs, ConstraintKind kind, Type first, Type second,
DeclNameRef member, DeclContext *useDC, FunctionRefInfo functionRefInfo,
ArrayRef<OverloadChoice> outerAlternatives, ConstraintLocator *locator) {
auto memberConstraint = createMember(cs, kind, first, second, member,
useDC, functionRefInfo, locator);
if (outerAlternatives.empty())
return memberConstraint;
SmallVector<Constraint *, 4> constraints;
constraints.push_back(memberConstraint);
memberConstraint->setFavored();
for (auto choice : outerAlternatives) {
constraints.push_back(
Constraint::createBindOverload(cs, first, choice, useDC, /*fix=*/nullptr,
locator));
}
return Constraint::createDisjunction(cs, constraints, locator, ForgetChoice);
}
Constraint *Constraint::createMember(ConstraintSystem &cs, ConstraintKind kind,
Type first, Type second,
DeclNameRef member, DeclContext *useDC,
FunctionRefInfo functionRefInfo,
ConstraintLocator *locator) {
// Collect type variables.
SmallPtrSet<TypeVariableType *, 4> typeVars;
if (first->hasTypeVariable())
first->getTypeVariables(typeVars);
if (second->hasTypeVariable())
second->getTypeVariables(typeVars);
// Create the constraint.
auto size =
totalSizeToAlloc<TypeVariableType *, ConstraintFix *, DeclContext *,
ContextualTypeInfo, OverloadChoice>(
typeVars.size(), /*hasFix=*/0, /*hasDeclContext=*/1,
/*hasContextualTypeInfo=*/0, /*hasOverloadChoice=*/0);
void *mem = cs.getAllocator().Allocate(size, alignof(Constraint));
return new (mem) Constraint(kind, first, second, member, useDC,
functionRefInfo, locator, typeVars);
}
Constraint *Constraint::createValueWitness(
ConstraintSystem &cs, ConstraintKind kind, Type first, Type second,
ValueDecl *requirement, DeclContext *useDC,
FunctionRefInfo functionRefInfo, ConstraintLocator *locator) {
assert(kind == ConstraintKind::ValueWitness);
// Collect type variables.
SmallPtrSet<TypeVariableType *, 4> typeVars;
if (first->hasTypeVariable())
first->getTypeVariables(typeVars);
if (second->hasTypeVariable())
second->getTypeVariables(typeVars);
// Create the constraint.
auto size =
totalSizeToAlloc<TypeVariableType *, ConstraintFix *, DeclContext *,
ContextualTypeInfo, OverloadChoice>(
typeVars.size(), /*hasFix=*/0, /*hasDeclContext=*/1,
/*hasContextualTypeInfo=*/0, /*hasOverloadChoice=*/0);
void *mem = cs.getAllocator().Allocate(size, alignof(Constraint));
return new (mem) Constraint(kind, first, second, requirement, useDC,
functionRefInfo, locator, typeVars);
}
Constraint *Constraint::createBindOverload(ConstraintSystem &cs, Type type,
OverloadChoice choice,
DeclContext *useDC,
ConstraintFix *fix,
ConstraintLocator *locator) {
// Collect type variables.
SmallPtrSet<TypeVariableType *, 4> typeVars;
if (type->hasTypeVariable())
type->getTypeVariables(typeVars);
if (auto baseType = choice.getBaseType()) {
baseType->getTypeVariables(typeVars);
}
// Create the constraint.
auto size =
totalSizeToAlloc<TypeVariableType *, ConstraintFix *, DeclContext *,
ContextualTypeInfo, OverloadChoice>(
typeVars.size(), fix ? 1 : 0, /*hasDeclContext=*/1,
/*hasContextualTypeInfo=*/0, /*hasOverloadChoice=*/1);
void *mem = cs.getAllocator().Allocate(size, alignof(Constraint));
return new (mem) Constraint(type, choice, useDC, fix, locator, typeVars);
}
Constraint *Constraint::createRestricted(ConstraintSystem &cs,
ConstraintKind kind,
ConversionRestrictionKind restriction,
Type first, Type second,
ConstraintLocator *locator) {
// Collect type variables.
SmallPtrSet<TypeVariableType *, 4> typeVars;
if (first->hasTypeVariable())
first->getTypeVariables(typeVars);
if (second->hasTypeVariable())
second->getTypeVariables(typeVars);
// Create the constraint.
auto size =
totalSizeToAlloc<TypeVariableType *, ConstraintFix *, DeclContext *,
ContextualTypeInfo, OverloadChoice>(
typeVars.size(), /*hasFix=*/0, /*hasDeclContext=*/0,
/*hasContextualTypeInfo=*/0, /*hasOverloadChoice=*/0);
void *mem = cs.getAllocator().Allocate(size, alignof(Constraint));
return new (mem) Constraint(kind, restriction, first, second, locator,
typeVars);
}
Constraint *Constraint::createFixed(ConstraintSystem &cs, ConstraintKind kind,
ConstraintFix *fix, Type first, Type second,
ConstraintLocator *locator) {
// Collect type variables.
SmallPtrSet<TypeVariableType *, 4> typeVars;
if (first->hasTypeVariable())
first->getTypeVariables(typeVars);
if (second->hasTypeVariable())
second->getTypeVariables(typeVars);
// Create the constraint.
auto size =
totalSizeToAlloc<TypeVariableType *, ConstraintFix *, DeclContext *,
ContextualTypeInfo, OverloadChoice>(
typeVars.size(), fix ? 1 : 0, /*hasDeclContext=*/0,
/*hasContextualTypeInfo=*/0, /*hasOverloadChoice=*/0);
void *mem = cs.getAllocator().Allocate(size, alignof(Constraint));
return new (mem) Constraint(kind, fix, first, second, locator, typeVars);
}
Constraint *Constraint::createDisjunction(ConstraintSystem &cs,
ArrayRef<Constraint *> constraints,
ConstraintLocator *locator,
RememberChoice_t rememberChoice) {
// Unwrap any disjunctions inside the disjunction constraint; we only allow
// disjunctions at the top level.
SmallPtrSet<TypeVariableType *, 4> typeVars;
bool unwrappedAny = false;
SmallVector<Constraint *, 1> unwrapped;
unsigned index = 0;
for (auto constraint : constraints) {
// Gather type variables from this constraint.
gatherReferencedTypeVars(constraint, typeVars);
// If we have a nested disjunction, unwrap it.
if (constraint->getKind() == ConstraintKind::Disjunction) {
// If we haven't unwrapped anything before, copy all of the constraints
// we skipped.
if (!unwrappedAny) {
unwrapped.append(constraints.begin(), constraints.begin() + index);
unwrappedAny = true;
}
// Add all of the constraints in the disjunction.
unwrapped.append(constraint->getNestedConstraints().begin(),
constraint->getNestedConstraints().end());
} else if (unwrappedAny) {
// Since we unwrapped constraints before, add this constraint.
unwrapped.push_back(constraint);
}
++index;
}
// If we unwrapped anything, our list of constraints is the unwrapped list.
if (unwrappedAny)
constraints = unwrapped;
assert(!constraints.empty() && "Empty disjunction constraint");
// If there is a single constraint, this isn't a disjunction at all.