-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathTypeCheckConstraints.cpp
2070 lines (1765 loc) · 68.7 KB
/
TypeCheckConstraints.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
//===--- TypeCheckConstraints.cpp - Constraint-based Type Checking --------===//
//
// 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 high-level entry points that use constraint
// systems for type checking, as well as a few miscellaneous helper
// functions that support the constraint system.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeChecker.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/DiagnosticSuppression.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Statistic.h"
#include "swift/Sema/CodeCompletionTypeChecking.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/SolutionResult.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Allocator.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/Format.h"
#include <iterator>
#include <map>
#include <memory>
#include <utility>
#include <tuple>
using namespace swift;
using namespace constraints;
//===----------------------------------------------------------------------===//
// Type variable implementation.
//===----------------------------------------------------------------------===//
#pragma mark Type variable implementation
void TypeVariableType::Implementation::print(llvm::raw_ostream &OS) {
getTypeVariable()->print(OS, PrintOptions());
}
SavedTypeVariableBinding::SavedTypeVariableBinding(TypeVariableType *typeVar)
: TypeVar(typeVar), Options(typeVar->getImpl().getRawOptions()),
ParentOrFixed(typeVar->getImpl().ParentOrFixed) { }
void SavedTypeVariableBinding::restore() {
TypeVar->getImpl().setRawOptions(Options);
TypeVar->getImpl().ParentOrFixed = ParentOrFixed;
}
GenericTypeParamType *
TypeVariableType::Implementation::getGenericParameter() const {
return locator ? locator->getGenericParameter() : nullptr;
}
Optional<ExprKind>
TypeVariableType::Implementation::getAtomicLiteralKind() const {
if (!locator || !locator->directlyAt<LiteralExpr>())
return None;
auto kind = getAsExpr(locator->getAnchor())->getKind();
switch (kind) {
case ExprKind::IntegerLiteral:
case ExprKind::FloatLiteral:
case ExprKind::StringLiteral:
case ExprKind::BooleanLiteral:
case ExprKind::NilLiteral:
return kind;
default:
return None;
}
}
bool TypeVariableType::Implementation::isClosureType() const {
if (!(locator && locator->getAnchor()))
return false;
return isExpr<ClosureExpr>(locator->getAnchor()) && locator->getPath().empty();
}
bool TypeVariableType::Implementation::isClosureParameterType() const {
if (!(locator && locator->getAnchor()))
return false;
return isExpr<ClosureExpr>(locator->getAnchor()) &&
locator->isLastElement<LocatorPathElt::TupleElement>();
}
bool TypeVariableType::Implementation::isClosureResultType() const {
if (!(locator && locator->getAnchor()))
return false;
return isExpr<ClosureExpr>(locator->getAnchor()) &&
locator->isLastElement<LocatorPathElt::ClosureResult>();
}
void *operator new(size_t bytes, ConstraintSystem& cs,
size_t alignment) {
return cs.getAllocator().Allocate(bytes, alignment);
}
bool constraints::computeTupleShuffle(ArrayRef<TupleTypeElt> fromTuple,
ArrayRef<TupleTypeElt> toTuple,
SmallVectorImpl<unsigned> &sources) {
const unsigned unassigned = -1;
SmallVector<bool, 4> consumed(fromTuple.size(), false);
sources.clear();
sources.assign(toTuple.size(), unassigned);
// Match up any named elements.
for (unsigned i = 0, n = toTuple.size(); i != n; ++i) {
const auto &toElt = toTuple[i];
// Skip unnamed elements.
if (!toElt.hasName())
continue;
// Find the corresponding named element.
int matched = -1;
{
int index = 0;
for (auto field : fromTuple) {
if (field.getName() == toElt.getName() && !consumed[index]) {
matched = index;
break;
}
++index;
}
}
if (matched == -1)
continue;
// Record this match.
sources[i] = matched;
consumed[matched] = true;
}
// Resolve any unmatched elements.
unsigned fromNext = 0, fromLast = fromTuple.size();
auto skipToNextAvailableInput = [&] {
while (fromNext != fromLast && consumed[fromNext])
++fromNext;
};
skipToNextAvailableInput();
for (unsigned i = 0, n = toTuple.size(); i != n; ++i) {
// Check whether we already found a value for this element.
if (sources[i] != unassigned)
continue;
// If there aren't any more inputs, we are done.
if (fromNext == fromLast) {
return true;
}
// Otherwise, assign this input to the next output element.
const auto &elt2 = toTuple[i];
assert(!elt2.isVararg());
// Fail if the input element is named and we're trying to match it with
// something with a different label.
if (fromTuple[fromNext].hasName() && elt2.hasName())
return true;
sources[i] = fromNext;
consumed[fromNext] = true;
skipToNextAvailableInput();
}
// Complain if we didn't reach the end of the inputs.
if (fromNext != fromLast) {
return true;
}
// If we got here, we should have claimed all the arguments.
assert(std::find(consumed.begin(), consumed.end(), false) == consumed.end());
return false;
}
Expr *ConstraintLocatorBuilder::trySimplifyToExpr() const {
SmallVector<LocatorPathElt, 4> pathBuffer;
auto anchor = getLocatorParts(pathBuffer);
// Locators are not guaranteed to have an anchor
// if constraint system is used to verify generic
// requirements.
if (!anchor.is<Expr *>())
return nullptr;
ArrayRef<LocatorPathElt> path = pathBuffer;
SourceRange range;
simplifyLocator(anchor, path, range);
return (path.empty() ? getAsExpr(anchor) : nullptr);
}
void ParentConditionalConformance::diagnoseConformanceStack(
DiagnosticEngine &diags, SourceLoc loc,
ArrayRef<ParentConditionalConformance> conformances) {
for (auto history : llvm::reverse(conformances)) {
diags.diagnose(loc, diag::requirement_implied_by_conditional_conformance,
history.ConformingType, history.Protocol);
}
}
namespace {
/// Produce any additional syntactic diagnostics for the body of a function
/// that had a result builder applied.
class FunctionSyntacticDiagnosticWalker : public ASTWalker {
SmallVector<DeclContext *, 4> dcStack;
public:
FunctionSyntacticDiagnosticWalker(DeclContext *dc) { dcStack.push_back(dc); }
std::pair<bool, Expr *> walkToExprPre(Expr *expr) override {
performSyntacticExprDiagnostics(expr, dcStack.back(), /*isExprStmt=*/false);
if (auto closure = dyn_cast<ClosureExpr>(expr)) {
if (closure->isSeparatelyTypeChecked()) {
dcStack.push_back(closure);
return {true, expr};
}
}
return {false, expr};
}
Expr *walkToExprPost(Expr *expr) override {
if (auto closure = dyn_cast<ClosureExpr>(expr)) {
if (closure->isSeparatelyTypeChecked()) {
assert(dcStack.back() == closure);
dcStack.pop_back();
}
}
return expr;
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *stmt) override {
performStmtDiagnostics(stmt, dcStack.back());
return {true, stmt};
}
std::pair<bool, Pattern *> walkToPatternPre(Pattern *pattern) override {
return {false, pattern};
}
bool walkToTypeReprPre(TypeRepr *typeRepr) override { return false; }
bool walkToParameterListPre(ParameterList *params) override { return false; }
};
} // end anonymous namespace
void constraints::performSyntacticDiagnosticsForTarget(
const SolutionApplicationTarget &target, bool isExprStmt) {
auto *dc = target.getDeclContext();
switch (target.kind) {
case SolutionApplicationTarget::Kind::expression: {
// First emit diagnostics for the main expression.
performSyntacticExprDiagnostics(target.getAsExpr(), dc, isExprStmt);
// If this is a for-in statement, we also need to check the where clause if
// present.
if (target.isForEachStmt()) {
if (auto *whereExpr = target.getForEachStmtInfo().whereExpr)
performSyntacticExprDiagnostics(whereExpr, dc, /*isExprStmt*/ false);
}
return;
}
case SolutionApplicationTarget::Kind::function: {
FunctionSyntacticDiagnosticWalker walker(dc);
target.getFunctionBody()->walk(walker);
return;
}
case SolutionApplicationTarget::Kind::stmtCondition:
case SolutionApplicationTarget::Kind::caseLabelItem:
case SolutionApplicationTarget::Kind::patternBinding:
case SolutionApplicationTarget::Kind::uninitializedWrappedVar:
// Nothing to do for these.
return;
}
llvm_unreachable("Unhandled case in switch!");
}
#pragma mark High-level entry points
Type TypeChecker::typeCheckExpression(Expr *&expr, DeclContext *dc,
ContextualTypeInfo contextualInfo,
TypeCheckExprOptions options) {
SolutionApplicationTarget target(
expr, dc, contextualInfo.purpose, contextualInfo.getType(),
options.contains(TypeCheckExprFlags::IsDiscarded));
auto resultTarget = typeCheckExpression(target, options);
if (!resultTarget) {
expr = target.getAsExpr();
return Type();
}
expr = resultTarget->getAsExpr();
return expr->getType();
}
Optional<SolutionApplicationTarget>
TypeChecker::typeCheckExpression(
SolutionApplicationTarget &target,
TypeCheckExprOptions options) {
Expr *expr = target.getAsExpr();
DeclContext *dc = target.getDeclContext();
auto &Context = dc->getASTContext();
FrontendStatsTracer StatsTracer(Context.Stats,
"typecheck-expr", expr);
PrettyStackTraceExpr stackTrace(Context, "type-checking", expr);
// First, pre-check the expression, validating any types that occur in the
// expression and folding sequence expressions.
if (ConstraintSystem::preCheckExpression(
expr, dc, /*replaceInvalidRefsWithErrors=*/true)) {
target.setExpr(expr);
return None;
}
target.setExpr(expr);
// Check whether given expression has a code completion token which requires
// special handling.
if (Context.CompletionCallback &&
typeCheckForCodeCompletion(target, /*needsPrecheck*/false,
[&](const constraints::Solution &S) {
Context.CompletionCallback->sawSolution(S);
}))
return None;
// Construct a constraint system from this expression.
ConstraintSystemOptions csOptions = ConstraintSystemFlags::AllowFixes;
if (DiagnosticSuppression::isEnabled(Context.Diags))
csOptions |= ConstraintSystemFlags::SuppressDiagnostics;
if (options.contains(TypeCheckExprFlags::AllowUnresolvedTypeVariables))
csOptions |= ConstraintSystemFlags::AllowUnresolvedTypeVariables;
if (options.contains(TypeCheckExprFlags::LeaveClosureBodyUnchecked))
csOptions |= ConstraintSystemFlags::LeaveClosureBodyUnchecked;
ConstraintSystem cs(dc, csOptions);
// Tell the constraint system what the contextual type is. This informs
// diagnostics and is a hint for various performance optimizations.
cs.setContextualType(
expr,
target.getExprContextualTypeLoc(),
target.getExprContextualTypePurpose());
// Try to shrink the system by reducing disjunction domains. This
// goes through every sub-expression and generate its own sub-system, to
// try to reduce the domains of those subexpressions.
cs.shrink(expr);
target.setExpr(expr);
// If the client can handle unresolved type variables, leave them in the
// system.
auto allowFreeTypeVariables = FreeTypeVariableBinding::Disallow;
if (options.contains(TypeCheckExprFlags::AllowUnresolvedTypeVariables))
allowFreeTypeVariables = FreeTypeVariableBinding::UnresolvedType;
// Attempt to solve the constraint system.
auto viable = cs.solve(target, allowFreeTypeVariables);
if (!viable) {
target.setExpr(expr);
return None;
}
// If the client allows the solution to have unresolved type expressions,
// check for them now. We cannot apply the solution with unresolved TypeVars,
// because they will leak out into arbitrary places in the resultant AST.
if (options.contains(TypeCheckExprFlags::AllowUnresolvedTypeVariables) &&
(viable->size() != 1 ||
(target.getExprConversionType() &&
target.getExprConversionType()->hasUnresolvedType()))) {
return target;
}
// Apply this solution to the constraint system.
// FIXME: This shouldn't be necessary.
auto &solution = (*viable)[0];
cs.applySolution(solution);
// Apply the solution to the expression.
auto resultTarget = cs.applySolution(solution, target);
if (!resultTarget) {
// Failure already diagnosed, above, as part of applying the solution.
return None;
}
Expr *result = resultTarget->getAsExpr();
// Unless the client has disabled them, perform syntactic checks on the
// expression now.
if (!cs.shouldSuppressDiagnostics()) {
bool isExprStmt = options.contains(TypeCheckExprFlags::IsExprStmt);
performSyntacticDiagnosticsForTarget(*resultTarget, isExprStmt);
}
resultTarget->setExpr(result);
return *resultTarget;
}
Type TypeChecker::typeCheckParameterDefault(Expr *&defaultValue,
DeclContext *DC, Type paramType,
bool isAutoClosure) {
assert(paramType && !paramType->hasError());
return typeCheckExpression(defaultValue, DC, /*contextualInfo=*/
{paramType, isAutoClosure
? CTP_AutoclosureDefaultParameter
: CTP_DefaultParameter});
}
bool TypeChecker::typeCheckBinding(
Pattern *&pattern, Expr *&initializer, DeclContext *DC,
Type patternType, PatternBindingDecl *PBD, unsigned patternNumber) {
SolutionApplicationTarget target =
PBD ? SolutionApplicationTarget::forInitialization(
initializer, DC, patternType, PBD, patternNumber,
/*bindPatternVarsOneWay=*/false)
: SolutionApplicationTarget::forInitialization(
initializer, DC, patternType, pattern,
/*bindPatternVarsOneWay=*/false);
// Type-check the initializer.
auto resultTarget = typeCheckExpression(target);
if (resultTarget) {
initializer = resultTarget->getAsExpr();
pattern = resultTarget->getInitializationPattern();
return false;
}
auto &Context = DC->getASTContext();
initializer = target.getAsExpr();
if (!initializer->getType())
initializer->setType(ErrorType::get(Context));
// Assign error types to the pattern and its variables, to prevent it from
// being referenced by the constraint system.
if (patternType->hasUnresolvedType() ||
patternType->hasUnboundGenericType()) {
pattern->setType(ErrorType::get(Context));
}
pattern->forEachVariable([&](VarDecl *var) {
// Don't change the type of a variable that we've been able to
// compute a type for.
if (var->hasInterfaceType() &&
!var->getType()->hasUnboundGenericType() &&
!var->isInvalid())
return;
var->setInvalid();
});
return true;
}
bool TypeChecker::typeCheckPatternBinding(PatternBindingDecl *PBD,
unsigned patternNumber,
Type patternType) {
Pattern *pattern = PBD->getPattern(patternNumber);
Expr *init = PBD->getInit(patternNumber);
// Enter an initializer context if necessary.
PatternBindingInitializer *initContext = nullptr;
DeclContext *DC = PBD->getDeclContext();
if (!DC->isLocalContext()) {
initContext = cast_or_null<PatternBindingInitializer>(
PBD->getInitContext(patternNumber));
if (initContext)
DC = initContext;
}
// If we weren't given a pattern type, compute one now.
if (!patternType) {
if (pattern->hasType())
patternType = pattern->getType();
else {
auto contextualPattern = ContextualPattern::forRawPattern(pattern, DC);
patternType = typeCheckPattern(contextualPattern);
}
if (patternType->hasError()) {
PBD->setInvalid();
return true;
}
}
bool hadError = TypeChecker::typeCheckBinding(
pattern, init, DC, patternType, PBD, patternNumber);
if (!init) {
PBD->setInvalid();
return true;
}
PBD->setPattern(patternNumber, pattern, initContext);
PBD->setInit(patternNumber, init);
// Bind a property with an opaque return type to the underlying type
// given by the initializer.
if (auto var = pattern->getSingleVar()) {
if (auto opaque = var->getOpaqueResultTypeDecl()) {
if (auto convertedInit = dyn_cast<UnderlyingToOpaqueExpr>(init)) {
auto underlyingType = convertedInit->getSubExpr()->getType()
->mapTypeOutOfContext();
auto underlyingSubs = SubstitutionMap::get(
opaque->getOpaqueInterfaceGenericSignature(),
[&](SubstitutableType *t) -> Type {
if (t->isEqual(opaque->getUnderlyingInterfaceType())) {
return underlyingType;
}
return Type(t);
},
LookUpConformanceInModule(opaque->getModuleContext()));
opaque->setUnderlyingTypeSubstitutions(underlyingSubs);
} else {
var->diagnose(diag::opaque_type_var_no_underlying_type);
}
}
}
if (hadError)
PBD->setInvalid();
PBD->setInitializerChecked(patternNumber);
return hadError;
}
bool TypeChecker::typeCheckForEachBinding(DeclContext *dc, ForEachStmt *stmt) {
auto &Context = dc->getASTContext();
auto failed = [&]() -> bool {
// Invalidate the pattern and the var decl.
stmt->getPattern()->setType(ErrorType::get(Context));
stmt->getPattern()->forEachVariable([&](VarDecl *var) {
if (var->hasInterfaceType() && !var->isInvalid())
return;
var->setInvalid();
});
return true;
};
auto sequenceProto = TypeChecker::getProtocol(
dc->getASTContext(), stmt->getForLoc(),
stmt->getAwaitLoc().isValid() ?
KnownProtocolKind::AsyncSequence : KnownProtocolKind::Sequence);
if (!sequenceProto)
return failed();
// Precheck the sequence.
Expr *sequence = stmt->getSequence();
if (ConstraintSystem::preCheckExpression(
sequence, dc, /*replaceInvalidRefsWithErrors=*/true))
return failed();
stmt->setSequence(sequence);
// Precheck the filtering condition.
if (Expr *whereExpr = stmt->getWhere()) {
if (ConstraintSystem::preCheckExpression(
whereExpr, dc, /*replaceInvalidRefsWithErrors=*/true))
return failed();
stmt->setWhere(whereExpr);
}
auto target = SolutionApplicationTarget::forForEachStmt(
stmt, sequenceProto, dc, /*bindPatternVarsOneWay=*/false);
if (!typeCheckExpression(target))
return failed();
// check to see if the sequence expr is throwing (and async), if so require
// the stmt to have a try loc
if (stmt->getAwaitLoc().isValid()) {
// fetch the sequence out of the statement
// else wise the value is potentially unresolved
auto Ty = stmt->getSequence()->getType();
auto module = dc->getParentModule();
auto conformanceRef = module->lookupConformance(Ty, sequenceProto);
if (conformanceRef.hasEffect(EffectKind::Throws) &&
stmt->getTryLoc().isInvalid()) {
auto &diags = dc->getASTContext().Diags;
diags.diagnose(stmt->getAwaitLoc(), diag::throwing_call_unhandled)
.fixItInsert(stmt->getAwaitLoc(), "try");
return failed();
}
}
return false;
}
bool TypeChecker::typeCheckCondition(Expr *&expr, DeclContext *dc) {
// If this expression is already typechecked and has type Bool, then just
// re-typecheck it.
if (expr->getType() && expr->getType()->isBool()) {
auto resultTy =
TypeChecker::typeCheckExpression(expr, dc);
return !resultTy;
}
auto *boolDecl = dc->getASTContext().getBoolDecl();
if (!boolDecl)
return true;
auto resultTy = TypeChecker::typeCheckExpression(
expr, dc,
/*contextualInfo=*/{boolDecl->getDeclaredInterfaceType(), CTP_Condition});
return !resultTy;
}
/// Find the '~=` operator that can compare an expression inside a pattern to a
/// value of a given type.
bool TypeChecker::typeCheckExprPattern(ExprPattern *EP, DeclContext *DC,
Type rhsType) {
auto &Context = DC->getASTContext();
FrontendStatsTracer StatsTracer(Context.Stats,
"typecheck-expr-pattern", EP);
PrettyStackTracePattern stackTrace(Context, "type-checking", EP);
// Create a 'let' binding to stand in for the RHS value.
auto *matchVar = new (Context) VarDecl(/*IsStatic*/false,
VarDecl::Introducer::Let,
EP->getLoc(),
Context.getIdentifier("$match"),
DC);
matchVar->setInterfaceType(rhsType->mapTypeOutOfContext());
matchVar->setImplicit();
EP->setMatchVar(matchVar);
// Find '~=' operators for the match.
auto matchLookup =
lookupUnqualified(DC->getModuleScopeContext(),
DeclNameRef(Context.Id_MatchOperator),
SourceLoc(), defaultUnqualifiedLookupOptions);
auto &diags = DC->getASTContext().Diags;
if (!matchLookup) {
diags.diagnose(EP->getLoc(), diag::no_match_operator);
return true;
}
SmallVector<ValueDecl*, 4> choices;
for (auto &result : matchLookup) {
choices.push_back(result.getValueDecl());
}
if (choices.empty()) {
diags.diagnose(EP->getLoc(), diag::no_match_operator);
return true;
}
// Build the 'expr ~= var' expression.
// FIXME: Compound name locations.
auto *matchOp =
TypeChecker::buildRefExpr(choices, DC, DeclNameLoc(EP->getLoc()),
/*Implicit=*/true, FunctionRefKind::Compound);
auto *matchVarRef = new (Context) DeclRefExpr(matchVar,
DeclNameLoc(EP->getLoc()),
/*Implicit=*/true);
Expr *matchArgElts[] = {EP->getSubExpr(), matchVarRef};
auto *matchArgs
= TupleExpr::create(Context, EP->getSubExpr()->getSourceRange().Start,
matchArgElts, { }, { },
EP->getSubExpr()->getSourceRange().End,
/*HasTrailingClosure=*/false, /*Implicit=*/true);
Expr *matchCall = new (Context) BinaryExpr(matchOp, matchArgs,
/*Implicit=*/true);
// Check the expression as a condition.
bool hadError = typeCheckCondition(matchCall, DC);
// Save the type-checked expression in the pattern.
EP->setMatchExpr(matchCall);
// Set the type on the pattern.
EP->setType(rhsType);
return hadError;
}
static Type replaceArchetypesWithTypeVariables(ConstraintSystem &cs,
Type t) {
llvm::DenseMap<SubstitutableType *, TypeVariableType *> types;
return t.subst(
[&](SubstitutableType *origType) -> Type {
auto found = types.find(origType);
if (found != types.end())
return found->second;
if (auto archetypeType = dyn_cast<ArchetypeType>(origType)) {
auto root = archetypeType->getRoot();
// We leave opaque types and their nested associated types alone here.
// They're globally available.
if (isa<OpaqueTypeArchetypeType>(root))
return origType;
// For other nested types, fail here so the default logic in subst()
// for nested types applies.
else if (root != archetypeType)
return Type();
auto locator = cs.getConstraintLocator({});
auto replacement = cs.createTypeVariable(locator,
TVO_CanBindToNoEscape);
if (auto superclass = archetypeType->getSuperclass()) {
cs.addConstraint(ConstraintKind::Subtype, replacement,
superclass, locator);
}
for (auto proto : archetypeType->getConformsTo()) {
cs.addConstraint(ConstraintKind::ConformsTo, replacement,
proto->getDeclaredInterfaceType(), locator);
}
types[origType] = replacement;
return replacement;
}
// FIXME: Remove this case
assert(cast<GenericTypeParamType>(origType));
auto locator = cs.getConstraintLocator({});
auto replacement = cs.createTypeVariable(locator,
TVO_CanBindToNoEscape);
types[origType] = replacement;
return replacement;
},
MakeAbstractConformanceForGenericType());
}
bool TypeChecker::typesSatisfyConstraint(Type type1, Type type2,
bool openArchetypes,
ConstraintKind kind, DeclContext *dc,
bool *unwrappedIUO) {
assert(!type1->hasTypeVariable() && !type2->hasTypeVariable() &&
"Unexpected type variable in constraint satisfaction testing");
ConstraintSystem cs(dc, ConstraintSystemOptions());
if (openArchetypes) {
type1 = replaceArchetypesWithTypeVariables(cs, type1);
type2 = replaceArchetypesWithTypeVariables(cs, type2);
}
cs.addConstraint(kind, type1, type2, cs.getConstraintLocator({}));
if (openArchetypes) {
assert(!unwrappedIUO && "FIXME");
SmallVector<Solution, 4> solutions;
return !cs.solve(solutions, FreeTypeVariableBinding::Allow);
}
if (auto solution = cs.solveSingle()) {
if (unwrappedIUO)
*unwrappedIUO = solution->getFixedScore().Data[SK_ForceUnchecked] > 0;
return true;
}
return false;
}
bool TypeChecker::isSubtypeOf(Type type1, Type type2, DeclContext *dc) {
return typesSatisfyConstraint(type1, type2,
/*openArchetypes=*/false,
ConstraintKind::Subtype, dc);
}
bool TypeChecker::isConvertibleTo(Type type1, Type type2, DeclContext *dc,
bool *unwrappedIUO) {
return typesSatisfyConstraint(type1, type2,
/*openArchetypes=*/false,
ConstraintKind::Conversion, dc,
unwrappedIUO);
}
bool TypeChecker::isExplicitlyConvertibleTo(Type type1, Type type2,
DeclContext *dc) {
return (typesSatisfyConstraint(type1, type2,
/*openArchetypes=*/false,
ConstraintKind::Conversion, dc) ||
isObjCBridgedTo(type1, type2, dc));
}
bool TypeChecker::isObjCBridgedTo(Type type1, Type type2, DeclContext *dc,
bool *unwrappedIUO) {
return (typesSatisfyConstraint(type1, type2,
/*openArchetypes=*/false,
ConstraintKind::BridgingConversion,
dc, unwrappedIUO));
}
bool TypeChecker::checkedCastMaySucceed(Type t1, Type t2, DeclContext *dc) {
auto kind = TypeChecker::typeCheckCheckedCast(t1, t2,
CheckedCastContextKind::None, dc,
SourceLoc(), nullptr, SourceRange());
return (kind != CheckedCastKind::Unresolved);
}
Expr *
TypeChecker::addImplicitLoadExpr(ASTContext &Context, Expr *expr,
std::function<Type(Expr *)> getType,
std::function<void(Expr *, Type)> setType) {
class LoadAdder : public ASTWalker {
private:
using GetTypeFn = std::function<Type(Expr *)>;
using SetTypeFn = std::function<void(Expr *, Type)>;
ASTContext &Ctx;
GetTypeFn getType;
SetTypeFn setType;
public:
LoadAdder(ASTContext &ctx, GetTypeFn getType, SetTypeFn setType)
: Ctx(ctx), getType(getType), setType(setType) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
if (isa<ParenExpr>(E) || isa<ForceValueExpr>(E))
return { true, E };
// Since load expression is created by walker,
// it's safe to stop as soon as it encounters first one
// because it would be the one it just created.
if (isa<LoadExpr>(E))
return { false, nullptr };
return { false, createLoadExpr(E) };
}
Expr *walkToExprPost(Expr *E) override {
if (auto *FVE = dyn_cast<ForceValueExpr>(E))
setType(E, getType(FVE->getSubExpr())->getOptionalObjectType());
if (auto *PE = dyn_cast<ParenExpr>(E))
setType(E, ParenType::get(Ctx, getType(PE->getSubExpr())));
return E;
}
private:
LoadExpr *createLoadExpr(Expr *E) {
auto objectType = getType(E)->getRValueType();
auto *LE = new (Ctx) LoadExpr(E, objectType);
setType(LE, objectType);
return LE;
}
};
return expr->walk(LoadAdder(Context, getType, setType));
}
Expr *
TypeChecker::coerceToRValue(ASTContext &Context, Expr *expr,
llvm::function_ref<Type(Expr *)> getType,
llvm::function_ref<void(Expr *, Type)> setType) {
Type exprTy = getType(expr);
// If expr has no type, just assume it's the right expr.
if (!exprTy)
return expr;
// If the type is already materializable, then we're already done.
if (!exprTy->hasLValueType())
return expr;
// Walk into force optionals and coerce the source.
if (auto *FVE = dyn_cast<ForceValueExpr>(expr)) {
auto sub = coerceToRValue(Context, FVE->getSubExpr(), getType, setType);
FVE->setSubExpr(sub);
setType(FVE, getType(sub)->getOptionalObjectType());
return FVE;
}
// Walk into parenthesized expressions to update the subexpression.
if (auto paren = dyn_cast<IdentityExpr>(expr)) {
auto sub = coerceToRValue(Context, paren->getSubExpr(), getType, setType);
paren->setSubExpr(sub);
setType(paren, ParenType::get(Context, getType(sub)));
return paren;
}
// Walk into 'try' and 'try!' expressions to update the subexpression.
if (auto tryExpr = dyn_cast<AnyTryExpr>(expr)) {
auto sub = coerceToRValue(Context, tryExpr->getSubExpr(), getType, setType);
tryExpr->setSubExpr(sub);
if (isa<OptionalTryExpr>(tryExpr) && !getType(sub)->hasError())
setType(tryExpr, OptionalType::get(getType(sub)));
else
setType(tryExpr, getType(sub));
return tryExpr;
}
// Walk into tuples to update the subexpressions.
if (auto tuple = dyn_cast<TupleExpr>(expr)) {
bool anyChanged = false;
for (auto &elt : tuple->getElements()) {
// Materialize the element.
auto oldType = getType(elt);
elt = coerceToRValue(Context, elt, getType, setType);
// If the type changed at all, make a note of it.
if (getType(elt).getPointer() != oldType.getPointer()) {
anyChanged = true;
}
}
// If any of the types changed, rebuild the tuple type.
if (anyChanged) {
SmallVector<TupleTypeElt, 4> elements;
elements.reserve(tuple->getElements().size());
for (unsigned i = 0, n = tuple->getNumElements(); i != n; ++i) {
Type type = getType(tuple->getElement(i));
Identifier name = tuple->getElementName(i);
elements.push_back(TupleTypeElt(type, name));
}
setType(tuple, TupleType::get(elements, Context));
}
return tuple;
}
// Load lvalues.
if (exprTy->is<LValueType>())
return addImplicitLoadExpr(Context, expr, getType, setType);
// Nothing to do.
return expr;
}
//===----------------------------------------------------------------------===//
// Debugging
//===----------------------------------------------------------------------===//
#pragma mark Debugging
void Solution::dump() const {
dump(llvm::errs());
}
void Solution::dump(raw_ostream &out) const {
PrintOptions PO;
PO.PrintTypesForDebugging = true;
SourceManager *sm = &getConstraintSystem().getASTContext().SourceMgr;
out << "Fixed score: " << FixedScore << "\n";
out << "Type variables:\n";
for (auto binding : typeBindings) {
auto &typeVar = binding.first;
out.indent(2);
Type(typeVar).print(out, PO);
out << " as ";
binding.second.print(out, PO);
if (auto *locator = typeVar->getImpl().getLocator()) {
out << " @ ";
locator->dump(sm, out);
}
out << "\n";
}
out << "\n";
out << "Overload choices:\n";
for (auto ovl : overloadChoices) {
out.indent(2);
if (ovl.first)
ovl.first->dump(sm, out);
out << " with ";
auto choice = ovl.second.choice;
switch (choice.getKind()) {
case OverloadChoiceKind::Decl:
case OverloadChoiceKind::DeclViaDynamic:
case OverloadChoiceKind::DeclViaBridge:
case OverloadChoiceKind::DeclViaUnwrappedOptional:
choice.getDecl()->dumpRef(out);
out << " as ";
if (choice.getBaseType())
out << choice.getBaseType()->getString(PO) << ".";
out << choice.getDecl()->getBaseName() << ": "
<< ovl.second.openedType->getString(PO) << "\n";
break;