-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
CSSimplify.cpp
1918 lines (1614 loc) · 69.3 KB
/
CSSimplify.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
//===--- CSSimplify.cpp - Constraint Simplification -----------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements simplifications of constraints within the constraint
// system.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
using namespace swift;
using namespace constraints;
static bool hasMandatoryTupleLabels(const ConstraintLocatorBuilder &locator) {
if (Expr *e = locator.trySimplifyToExpr())
return hasMandatoryTupleLabels(e);
return false;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchTupleTypes(TupleType *tuple1, TupleType *tuple2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
unsigned subFlags = flags | TMF_GenerateConstraints;
// Equality and subtyping have fairly strict requirements on tuple matching,
// requiring element names to either match up or be disjoint.
if (kind < TypeMatchKind::Conversion) {
if (tuple1->getFields().size() != tuple2->getFields().size()) {
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
Failure::TupleSizeMismatch, tuple1, tuple2);
}
return SolutionKind::Error;
}
for (unsigned i = 0, n = tuple1->getFields().size(); i != n; ++i) {
const auto &elt1 = tuple1->getFields()[i];
const auto &elt2 = tuple2->getFields()[i];
// If the names don't match, we may have a conflict.
if (elt1.getName() != elt2.getName()) {
// Same-type requirements require exact name matches.
if (kind == TypeMatchKind::SameType) {
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(
locator.withPathElement(
LocatorPathElt::getNamedTupleElement(i))),
Failure::TupleNameMismatch, tuple1, tuple2);
}
return SolutionKind::Error;
}
// For subtyping constraints, just make sure that this name isn't
// used at some other position.
if (!elt2.getName().empty()) {
int matched = tuple1->getNamedElementId(elt2.getName());
if (matched != -1) {
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(
locator.withPathElement(
LocatorPathElt::getNamedTupleElement(i))),
Failure::TupleNamePositionMismatch, tuple1, tuple2);
}
return SolutionKind::Error;
}
}
}
// Variadic bit must match.
if (elt1.isVararg() != elt2.isVararg()) {
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(
locator.withPathElement(
LocatorPathElt::getNamedTupleElement(i))),
Failure::TupleVariadicMismatch, tuple1, tuple2);
}
return SolutionKind::Error;
}
// Compare the element types.
switch (matchTypes(elt1.getType(), elt2.getType(), kind, subFlags,
locator.withPathElement(
LocatorPathElt::getTupleElement(i)))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
return SolutionKind::Solved;
}
assert(kind == TypeMatchKind::Conversion);
// Compute the element shuffles for conversions.
SmallVector<int, 16> sources;
SmallVector<unsigned, 4> variadicArguments;
if (computeTupleShuffle(tuple1, tuple2, sources, variadicArguments,
::hasMandatoryTupleLabels(locator))) {
// FIXME: Record why the tuple shuffle couldn't be computed.
if (shouldRecordFailures()) {
if (tuple1->getNumElements() != tuple2->getNumElements()) {
recordFailure(getConstraintLocator(locator),
Failure::TupleSizeMismatch, tuple1, tuple2);
}
}
return SolutionKind::Error;
}
// Check each of the elements.
bool hasVarArg = false;
for (unsigned idx2 = 0, n = sources.size(); idx2 != n; ++idx2) {
// Default-initialization always allowed for conversions.
if (sources[idx2] == TupleShuffleExpr::DefaultInitialize) {
continue;
}
// Variadic arguments handled below.
if (sources[idx2] == TupleShuffleExpr::FirstVariadic) {
hasVarArg = true;
continue;
}
assert(sources[idx2] >= 0);
unsigned idx1 = sources[idx2];
// Match up the types.
const auto &elt1 = tuple1->getFields()[idx1];
const auto &elt2 = tuple2->getFields()[idx2];
switch (matchTypes(elt1.getType(), elt2.getType(),
TypeMatchKind::Conversion, subFlags,
locator.withPathElement(
LocatorPathElt::getTupleElement(idx1)))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
// If we have variadic arguments to check, do so now.
if (hasVarArg) {
const auto &elt2 = tuple2->getFields().back();
auto eltType2 = elt2.getVarargBaseTy();
for (unsigned idx1 : variadicArguments) {
switch (matchTypes(tuple1->getElementType(idx1),
eltType2, TypeMatchKind::Conversion, subFlags,
locator.withPathElement(
LocatorPathElt::getTupleElement(idx1)))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
}
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchScalarToTupleTypes(Type type1, TupleType *tuple2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
int scalarFieldIdx = tuple2->getFieldForScalarInit();
assert(scalarFieldIdx >= 0 && "Invalid tuple for scalar-to-tuple");
const auto &elt = tuple2->getFields()[scalarFieldIdx];
auto scalarFieldTy = elt.isVararg()? elt.getVarargBaseTy() : elt.getType();
return matchTypes(type1, scalarFieldTy, kind, flags,
locator.withPathElement(ConstraintLocator::ScalarToTuple));
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchTupleToScalarTypes(TupleType *tuple1, Type type2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
assert(tuple1->getNumElements() == 1 && "Wrong number of elements");
assert(!tuple1->getFields()[0].isVararg() && "Should not be variadic");
return matchTypes(tuple1->getElementType(0),
type2, kind, flags,
locator.withPathElement(
LocatorPathElt::getTupleElement(0)));
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchFunctionTypes(FunctionType *func1, FunctionType *func2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
// An [auto_closure] function type can be a subtype of a
// non-[auto_closure] function type.
if (func1->isAutoClosure() != func2->isAutoClosure()) {
if (func2->isAutoClosure() || kind < TypeMatchKind::TrivialSubtype) {
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
Failure::FunctionAutoclosureMismatch, func1, func2);
}
return SolutionKind::Error;
}
}
// A [noreturn] function type can be a subtype of a non-[noreturn] function
// type.
if (func1->isNoReturn() != func2->isNoReturn()) {
if (func2->isNoReturn() || kind < TypeMatchKind::SameType) {
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
Failure::FunctionNoReturnMismatch, func1, func2);
}
return SolutionKind::Error;
}
}
// Determine how we match up the input/result types.
TypeMatchKind subKind;
switch (kind) {
case TypeMatchKind::BindType:
case TypeMatchKind::SameType:
case TypeMatchKind::TrivialSubtype:
subKind = kind;
break;
case TypeMatchKind::Subtype:
subKind = TypeMatchKind::TrivialSubtype;
break;
case TypeMatchKind::Conversion:
subKind = TypeMatchKind::Subtype;
break;
}
unsigned subFlags = flags | TMF_GenerateConstraints;
// Input types can be contravariant (or equal).
SolutionKind result = matchTypes(func2->getInput(), func1->getInput(),
subKind, subFlags,
locator.withPathElement(
ConstraintLocator::FunctionArgument));
if (result == SolutionKind::Error)
return SolutionKind::Error;
// Result type can be covariant (or equal).
switch (matchTypes(func1->getResult(), func2->getResult(), subKind,
subFlags,
locator.withPathElement(
ConstraintLocator::FunctionResult))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
result = SolutionKind::Solved;
break;
case SolutionKind::Unsolved:
result = SolutionKind::Unsolved;
break;
}
return result;
}
/// \brief Map a failed type-matching kind to a failure kind, generically.
static Failure::FailureKind getRelationalFailureKind(TypeMatchKind kind) {
switch (kind) {
case TypeMatchKind::BindType:
case TypeMatchKind::SameType:
return Failure::TypesNotEqual;
case TypeMatchKind::TrivialSubtype:
return Failure::TypesNotTrivialSubtypes;
case TypeMatchKind::Subtype:
return Failure::TypesNotSubtypes;
case TypeMatchKind::Conversion:
return Failure::TypesNotConvertible;
}
llvm_unreachable("unhandled type matching kind");
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchSuperclassTypes(Type type1, Type type2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
auto classDecl2 = type2->getClassOrBoundGenericClass();
bool done = false;
for (auto super1 = TC.getSuperClassOf(type1);
!done && super1;
super1 = TC.getSuperClassOf(super1)) {
if (super1->getClassOrBoundGenericClass() != classDecl2)
continue;
return matchTypes(super1, type2, TypeMatchKind::SameType,
TMF_GenerateConstraints, locator);
}
// Record this failure.
// FIXME: Specialize diagnostic.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
getRelationalFailureKind(kind), type1, type2);
}
return SolutionKind::Error;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchDeepEqualityTypes(Type type1, Type type2,
ConstraintLocatorBuilder locator) {
// Handle nominal types that are not directly generic.
if (auto nominal1 = type1->getAs<NominalType>()) {
auto nominal2 = type2->castTo<NominalType>();
assert((bool)nominal1->getParent() == (bool)nominal2->getParent() &&
"Mismatched parents of nominal types");
if (!nominal1->getParent())
return SolutionKind::Solved;
// Match up the parents, exactly.
return matchTypes(nominal1->getParent(), nominal2->getParent(),
TypeMatchKind::SameType, TMF_GenerateConstraints,
locator.withPathElement(ConstraintLocator::ParentType));
}
auto bound1 = type1->castTo<BoundGenericType>();
auto bound2 = type2->castTo<BoundGenericType>();
// Match up the parents, exactly, if there are parents.
assert((bool)bound1->getParent() == (bool)bound2->getParent() &&
"Mismatched parents of bound generics");
if (bound1->getParent()) {
switch (matchTypes(bound1->getParent(), bound2->getParent(),
TypeMatchKind::SameType, TMF_GenerateConstraints,
locator.withPathElement(ConstraintLocator::ParentType))){
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
// Match up the generic arguments, exactly.
auto args1 = bound1->getGenericArgs();
auto args2 = bound2->getGenericArgs();
assert(args1.size() == args2.size() && "Mismatched generic args");
for (unsigned i = 0, n = args1.size(); i != n; ++i) {
switch (matchTypes(args1[i], args2[i], TypeMatchKind::SameType,
TMF_GenerateConstraints,
locator.withPathElement(
LocatorPathElt::getGenericArgument(i)))) {
case SolutionKind::Error:
return SolutionKind::Error;
case SolutionKind::Solved:
case SolutionKind::Unsolved:
break;
}
}
return SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchExistentialTypes(Type type1, Type type2,
TypeMatchKind kind, unsigned flags,
ConstraintLocatorBuilder locator) {
SmallVector<ProtocolDecl *, 4> protocols;
bool existential = type2->isExistentialType(protocols);
assert(existential && "Bogus existential match");
(void)existential;
for (auto proto : protocols) {
switch (simplifyConformsToConstraint(type1, proto, locator, false)) {
case SolutionKind::Solved:
break;
case SolutionKind::Unsolved:
// Add the constraint.
addConstraint(ConstraintKind::ConformsTo, type1,
proto->getDeclaredType());
break;
case SolutionKind::Error:
return SolutionKind::Error;
}
}
return SolutionKind::Solved;
}
/// \brief Map a type-matching kind to a constraint kind.
static ConstraintKind getConstraintKind(TypeMatchKind kind) {
switch (kind) {
case TypeMatchKind::BindType:
return ConstraintKind::Bind;
case TypeMatchKind::SameType:
return ConstraintKind::Equal;
case TypeMatchKind::TrivialSubtype:
return ConstraintKind::TrivialSubtype;
case TypeMatchKind::Subtype:
return ConstraintKind::Subtype;
case TypeMatchKind::Conversion:
return ConstraintKind::Conversion;
}
llvm_unreachable("unhandled type matching kind");
}
/// Determine whether we should attempt a user-defined conversion.
static bool shouldTryUserConversion(ConstraintSystem &cs, Type type) {
// If this isn't a type that can have user-defined conversions, there's
// nothing to do.
if (!type->getNominalOrBoundGenericNominal() && !type->is<ArchetypeType>())
return false;
// If there are no user-defined conversions, there's nothing to do.
// FIXME: lame name!
auto &ctx = cs.getASTContext();
auto name = ctx.getIdentifier("__conversion");
return static_cast<bool>(cs.lookupMember(type, name));
}
/// If the given type has user-defined conversions, introduce new
/// relational constraint between the result of performing the user-defined
/// conversion and an arbitrary other type.
static ConstraintSystem::SolutionKind
tryUserConversion(ConstraintSystem &cs, Type type, ConstraintKind kind,
Type otherType, ConstraintLocatorBuilder locator) {
assert(kind != ConstraintKind::Construction &&
kind != ConstraintKind::Conversion &&
"Construction/conversion constraints create potential cycles");
// If this isn't a type that can have user-defined conversions, there's
// nothing to do.
if (!type->getNominalOrBoundGenericNominal() && !type->is<ArchetypeType>())
return ConstraintSystem::SolutionKind::Unsolved;
// If there are no user-defined conversions, there's nothing to do.
// FIXME: lame name!
auto &ctx = cs.getASTContext();
auto name = ctx.getIdentifier("__conversion");
if (!cs.lookupMember(type, name))
return ConstraintSystem::SolutionKind::Unsolved;
auto memberLocator = cs.getConstraintLocator(
locator.withPathElement(
ConstraintLocator::ConversionMember));
auto inputTV = cs.createTypeVariable(
cs.getConstraintLocator(memberLocator,
ConstraintLocator::FunctionArgument),
/*options=*/0);
auto outputTV = cs.createTypeVariable(
cs.getConstraintLocator(memberLocator,
ConstraintLocator::FunctionResult),
/*options=*/0);
// The conversion function will have function type TI -> TO, for fresh
// type variables TI and TO.
cs.addValueMemberConstraint(type, name,
FunctionType::get(inputTV, outputTV, ctx),
memberLocator);
// A conversion function must accept an empty parameter list ().
// Note: This should never fail, because the declaration checker
// should ensure that conversions have no non-defaulted parameters.
cs.addConstraint(ConstraintKind::Conversion, TupleType::getEmpty(ctx),
inputTV, cs.getConstraintLocator(locator));
// Relate the output of the conversion function to the other type, using
// the provided constraint kind.
// If the type we're converting to is existential, we can also have an
// existential conversion here, so introduce a disjunction.
auto resultLocator = cs.getConstraintLocator(
locator.withPathElement(
ConstraintLocator::ConversionResult));
if (otherType->isExistentialType()) {
Constraint *constraints[2] = {
Constraint::create(cs, kind, outputTV, otherType, Identifier(),
resultLocator),
Constraint::createRestricted(cs, ConstraintKind::Conversion,
ConversionRestrictionKind::Existential,
outputTV, otherType, resultLocator)
};
cs.addConstraint(Constraint::createDisjunction(cs, constraints,
resultLocator));
} else {
cs.addConstraint(kind, outputTV, otherType, resultLocator);
}
// We're adding a user-defined conversion.
cs.increaseScore(SK_UserConversion);
return ConstraintSystem::SolutionKind::Solved;
}
ConstraintSystem::SolutionKind
ConstraintSystem::matchTypes(Type type1, Type type2, TypeMatchKind kind,
unsigned flags,
ConstraintLocatorBuilder locator) {
// If we have type variables that have been bound to fixed types, look through
// to the fixed type.
TypeVariableType *typeVar1;
type1 = getFixedTypeRecursive(type1, typeVar1,
kind == TypeMatchKind::SameType);
auto desugar1 = type1->getDesugaredType();
TypeVariableType *typeVar2;
type2 = getFixedTypeRecursive(type2, typeVar2,
kind == TypeMatchKind::SameType);
auto desugar2 = type2->getDesugaredType();
// If the types are obviously equivalent, we're done.
if (desugar1 == desugar2)
return SolutionKind::Solved;
// If either (or both) types are type variables, unify the type variables.
if (typeVar1 || typeVar2) {
switch (kind) {
case TypeMatchKind::BindType:
case TypeMatchKind::SameType: {
if (typeVar1 && typeVar2) {
auto rep1 = getRepresentative(typeVar1);
auto rep2 = getRepresentative(typeVar2);
if (rep1 == rep2) {
// We already merged these two types, so this constraint is
// trivially solved.
return SolutionKind::Solved;
}
// If exactly one of the type variables can bind to an lvalue, we
// can't merge these two type variables.
if (rep1->getImpl().canBindToLValue()
!= rep2->getImpl().canBindToLValue()) {
if (flags & TMF_GenerateConstraints) {
// Add a new constraint between these types. We consider the current
// type-matching problem to the "solved" by this addition, because
// this new constraint will be solved at a later point.
// Obviously, this must not happen at the top level, or the algorithm
// would not terminate.
addConstraint(getConstraintKind(kind), rep1, rep2,
getConstraintLocator(locator));
return SolutionKind::Solved;
}
return SolutionKind::Unsolved;
}
// Merge the equivalence classes corresponding to these two variables.
mergeEquivalenceClasses(rep1, rep2);
return SolutionKind::Solved;
}
// Provide a fixed type for the type variable.
bool wantRvalue = kind == TypeMatchKind::SameType;
if (typeVar1) {
// If we want an rvalue, get the rvalue.
if (wantRvalue)
type2 = type2->getRValueType();
// If the left-hand type variable cannot bind to an lvalue,
// but we still have an lvalue, fail.
if (!typeVar1->getImpl().canBindToLValue()) {
if (type2->is<LValueType>()) {
if (false && shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
Failure::IsForbiddenLValue, type1, type2);
}
return SolutionKind::Error;
}
// Okay. Bind below.
}
assignFixedType(typeVar1, type2);
return SolutionKind::Solved;
}
// If we want an rvalue, get the rvalue.
if (wantRvalue)
type1 = type1->getRValueType();
if (!typeVar2->getImpl().canBindToLValue()) {
if (type1->is<LValueType>()) {
if (false && shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
Failure::IsForbiddenLValue, type1, type2);
}
return SolutionKind::Error;
}
// Okay. Bind below.
}
assignFixedType(typeVar2, type1);
return SolutionKind::Solved;
}
case TypeMatchKind::TrivialSubtype:
case TypeMatchKind::Subtype:
case TypeMatchKind::Conversion:
if (flags & TMF_GenerateConstraints) {
// Add a new constraint between these types. We consider the current
// type-matching problem to the "solved" by this addition, because
// this new constraint will be solved at a later point.
// Obviously, this must not happen at the top level, or the algorithm
// would not terminate.
addConstraint(getConstraintKind(kind), type1, type2,
getConstraintLocator(locator));
return SolutionKind::Solved;
}
// We couldn't solve this constraint. If only one of the types is a type
// variable, perhaps we can do something with it below.
if (typeVar1 && typeVar2)
return typeVar1 == typeVar2? SolutionKind::Solved
: SolutionKind::Unsolved;
break;
}
}
llvm::SmallVector<ConversionRestrictionKind, 4> potentialConversions;
bool concrete = !typeVar1 && !typeVar2;
// Decompose parallel structure.
unsigned subFlags = flags | TMF_GenerateConstraints;
if (desugar1->getKind() == desugar2->getKind()) {
switch (desugar1->getKind()) {
#define SUGARED_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("Type has not been desugared completely");
#define ARTIFICIAL_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
llvm_unreachable("artificial type in constraint");
#define BUILTIN_TYPE(id, parent) case TypeKind::id:
#define TYPE(id, parent)
#include "swift/AST/TypeNodes.def"
case TypeKind::Module:
if (desugar1 == desugar2) {
return SolutionKind::Solved;
}
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
getRelationalFailureKind(kind), type1, type2);
}
return SolutionKind::Error;
case TypeKind::Error:
return SolutionKind::Error;
case TypeKind::GenericTypeParam:
case TypeKind::DependentMember:
llvm_unreachable("unmapped dependent type in type checker");
case TypeKind::TypeVariable:
case TypeKind::Archetype:
// Nothing to do here; handle type variables and archetypes below.
break;
case TypeKind::Tuple: {
// Try the tuple-to-tuple conversion.
potentialConversions.push_back(ConversionRestrictionKind::TupleToTuple);
break;
}
case TypeKind::Enum:
case TypeKind::Struct:
case TypeKind::Class: {
auto nominal1 = cast<NominalType>(desugar1);
auto nominal2 = cast<NominalType>(desugar2);
if (nominal1->getDecl() == nominal2->getDecl()) {
potentialConversions.push_back(ConversionRestrictionKind::DeepEquality);
}
break;
}
case TypeKind::Protocol:
// Nothing to do here; try existential and user-defined conversions below.
break;
case TypeKind::MetaType: {
auto meta1 = cast<MetaTypeType>(desugar1);
auto meta2 = cast<MetaTypeType>(desugar2);
// metatype<B> < metatype<A> if A < B and both A and B are classes.
TypeMatchKind subKind = TypeMatchKind::SameType;
if (kind != TypeMatchKind::SameType &&
(meta1->getInstanceType()->mayHaveSuperclass() ||
meta2->getInstanceType()->getClassOrBoundGenericClass()))
subKind = std::min(kind, TypeMatchKind::Subtype);
return matchTypes(meta1->getInstanceType(), meta2->getInstanceType(),
subKind, subFlags,
locator.withPathElement(
ConstraintLocator::InstanceType));
}
case TypeKind::Function: {
auto func1 = cast<FunctionType>(desugar1);
auto func2 = cast<FunctionType>(desugar2);
return matchFunctionTypes(func1, func2, kind, flags, locator);
}
case TypeKind::PolymorphicFunction:
case TypeKind::GenericFunction:
llvm_unreachable("Polymorphic function type should have been opened");
case TypeKind::Array: {
auto array1 = cast<ArrayType>(desugar1);
auto array2 = cast<ArrayType>(desugar2);
return matchTypes(array1->getBaseType(), array2->getBaseType(),
TypeMatchKind::SameType, subFlags,
locator.withPathElement(
ConstraintLocator::ArrayElementType));
}
case TypeKind::ProtocolComposition:
// Existential types handled below.
break;
case TypeKind::LValue: {
auto lvalue1 = cast<LValueType>(desugar1);
auto lvalue2 = cast<LValueType>(desugar2);
if (lvalue1->getQualifiers() != lvalue2->getQualifiers() &&
!(kind >= TypeMatchKind::TrivialSubtype &&
lvalue1->getQualifiers() < lvalue2->getQualifiers())) {
// Record this failure.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
Failure::LValueQualifiers, type1, type2);
}
return SolutionKind::Error;
}
return matchTypes(lvalue1->getObjectType(), lvalue2->getObjectType(),
TypeMatchKind::SameType, subFlags,
locator.withPathElement(
ConstraintLocator::ArrayElementType));
}
case TypeKind::UnboundGeneric:
llvm_unreachable("Unbound generic type should have been opened");
case TypeKind::BoundGenericClass:
case TypeKind::BoundGenericEnum:
case TypeKind::BoundGenericStruct: {
auto bound1 = cast<BoundGenericType>(desugar1);
auto bound2 = cast<BoundGenericType>(desugar2);
if (bound1->getDecl() == bound2->getDecl()) {
potentialConversions.push_back(ConversionRestrictionKind::DeepEquality);
}
break;
}
}
}
// FIXME: Materialization
if (concrete && kind >= TypeMatchKind::TrivialSubtype) {
auto tuple1 = type1->getAs<TupleType>();
auto tuple2 = type2->getAs<TupleType>();
// Detect when the source and destination are both permit scalar
// conversions, but the source has a name and the destination does not have
// the same name.
bool tuplesWithMismatchedNames = false;
if (tuple1 && tuple2) {
int scalar1 = tuple1->getFieldForScalarInit();
int scalar2 = tuple2->getFieldForScalarInit();
if (scalar1 >= 0 && scalar2 >= 0) {
auto name1 = tuple1->getFields()[scalar1].getName();
auto name2 = tuple2->getFields()[scalar2].getName();
tuplesWithMismatchedNames = !name1.empty() && name1 != name2;
}
}
if (tuple2 && !tuplesWithMismatchedNames) {
// A scalar type is a trivial subtype of a one-element, non-variadic tuple
// containing a single element if the scalar type is a subtype of
// the type of that tuple's element.
//
// A scalar type can be converted to a tuple so long as there is at
// most one non-defaulted element.
if ((tuple2->getFields().size() == 1 &&
!tuple2->getFields()[0].isVararg()) ||
(kind >= TypeMatchKind::Conversion &&
tuple2->getFieldForScalarInit() >= 0)) {
potentialConversions.push_back(
ConversionRestrictionKind::ScalarToTuple);
// FIXME: Prohibits some user-defined conversions for tuples.
goto commit_to_conversions;
}
}
if (tuple1 && !tuplesWithMismatchedNames) {
// A single-element tuple can be a trivial subtype of a scalar.
if (tuple1->getFields().size() == 1 &&
!tuple1->getFields()[0].isVararg()) {
potentialConversions.push_back(
ConversionRestrictionKind::TupleToScalar);
}
}
// Subclass-to-superclass conversion.
if (type1->mayHaveSuperclass() && type2->mayHaveSuperclass() &&
type2->getClassOrBoundGenericClass() &&
type1->getClassOrBoundGenericClass()
!= type2->getClassOrBoundGenericClass()) {
potentialConversions.push_back(ConversionRestrictionKind::Superclass);
}
}
if (concrete && kind >= TypeMatchKind::Conversion) {
// An lvalue of type T1 can be converted to a value of type T2 so long as
// T1 is convertible to T2 (by loading the value).
if (auto lvalue1 = type1->getAs<LValueType>()) {
if (lvalue1->getQualifiers().isImplicit()) {
potentialConversions.push_back(
ConversionRestrictionKind::LValueToRValue);
}
}
// An expression can be converted to an auto-closure function type, creating
// an implicit closure.
if (auto function2 = type2->getAs<FunctionType>()) {
if (function2->isAutoClosure()) {
return matchTypes(type1, function2->getResult(), kind, subFlags,
locator.withPathElement(ConstraintLocator::Load));
}
}
}
// For a subtyping relation involving two existential types or subtyping of
// a class existential type, or a conversion from any type to an
// existential type, check whether the first type conforms to each of the
// protocols in the second type.
if (type2->isExistentialType() &&
(kind >= TypeMatchKind::Conversion ||
(kind == TypeMatchKind::Subtype &&
(type1->isExistentialType() || type2->isClassExistentialType())))) {
potentialConversions.push_back(ConversionRestrictionKind::Existential);
}
// A value of type T can be converted to type U? if T is convertible to U.
// A value of type T? can be converted to type U? if T is convertible to U.
{
BoundGenericType *boundGenericType2;
if (concrete && kind >= TypeMatchKind::Conversion &&
(boundGenericType2 = type2->getAs<BoundGenericType>())) {
if (boundGenericType2->getDecl() == TC.Context.getOptionalDecl()) {
assert(boundGenericType2->getGenericArgs().size() == 1);
BoundGenericType *boundGenericType1
= type1->getAs<BoundGenericType>();
if (boundGenericType1
&& boundGenericType1->getDecl() == TC.Context.getOptionalDecl()) {
assert(boundGenericType1->getGenericArgs().size() == 1);
potentialConversions.push_back(
ConversionRestrictionKind::OptionalToOptional);
}
potentialConversions.push_back(
ConversionRestrictionKind::ValueToOptional);
}
}
}
// A nominal type can be converted to another type via a user-defined
// conversion function.
if (concrete && kind >= TypeMatchKind::Conversion &&
shouldTryUserConversion(*this, type1)) {
potentialConversions.push_back(ConversionRestrictionKind::User);
}
commit_to_conversions:
// When we hit this point, we're committed to the set of potential
// conversions recorded thus far.
//
//
// FIXME: One should only jump to this label in the case where we want to
// cut off other potential conversions because we know none of them apply.
// Gradually, those gotos should go away as we can handle more kinds of
// conversions via disjunction constraints.
if (potentialConversions.empty()) {
// If one of the types is a type variable, we leave this unsolved.
if (typeVar1 || typeVar2)
return SolutionKind::Unsolved;
// If we are supposed to record failures, do so.
if (shouldRecordFailures()) {
recordFailure(getConstraintLocator(locator),
getRelationalFailureKind(kind), type1, type2);
}
return SolutionKind::Error;
}
// Where there is more than one potential conversion, create a disjunction
// so that we'll explore all of the options.
if (potentialConversions.size() > 1) {
auto fixedLocator = getConstraintLocator(locator);
SmallVector<Constraint *, 2> constraints;
for (auto potential : potentialConversions) {
// Determine the constraint kind. For a deep equality constraint, only
// perform equality.
auto constraintKind = getConstraintKind(kind);
if (potential == ConversionRestrictionKind::DeepEquality)
constraintKind = ConstraintKind::Equal;
constraints.push_back(
Constraint::createRestricted(*this, constraintKind, potential,
type1, type2, fixedLocator));
}
addConstraint(Constraint::createDisjunction(*this, constraints,
fixedLocator));
return SolutionKind::Solved;
}
// For a single potential conversion, directly recurse, so that we
// don't allocate a new constraint or constraint locator.
switch (potentialConversions[0]) {
case ConversionRestrictionKind::TupleToTuple:
return matchTupleTypes(type1->castTo<TupleType>(),
type2->castTo<TupleType>(),
kind, flags, locator);
case ConversionRestrictionKind::ScalarToTuple:
return matchScalarToTupleTypes(type1, type2->castTo<TupleType>(), kind,
subFlags, locator);
case ConversionRestrictionKind::TupleToScalar:
return matchTupleToScalarTypes(type1->castTo<TupleType>(), type2,
kind, subFlags, locator);
case ConversionRestrictionKind::DeepEquality:
return matchDeepEqualityTypes(type1, type2, locator);
case ConversionRestrictionKind::Superclass:
return matchSuperclassTypes(type1, type2, kind, flags, locator);
case ConversionRestrictionKind::LValueToRValue:
return matchTypes(type1->getRValueType(), type2, kind, subFlags, locator);
case ConversionRestrictionKind::Existential:
return matchExistentialTypes(type1, type2, kind, flags, locator);
case ConversionRestrictionKind::ValueToOptional: {
auto boundGenericType2 = type2->castTo<BoundGenericType>();
(void)boundGenericType2;
assert(boundGenericType2->getDecl() == TC.Context.getOptionalDecl());