-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathCSSyntacticElement.cpp
2754 lines (2266 loc) · 94.1 KB
/
CSSyntacticElement.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
//===--- CSSyntacticElement.cpp - Syntactic Element Constraints -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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 SyntacticElement constraint generation and solution
// application, which is used to type-check the bodies of closures. It provides
// part of the implementation of the ConstraintSystem class.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeChecker.h"
#include "TypeCheckAvailability.h"
#include "swift/Basic/Assertions.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
using namespace swift;
using namespace swift::constraints;
void ConstraintSystem::setTargetFor(SyntacticElementTargetKey key,
SyntacticElementTarget target) {
bool inserted = targets.insert({key, target}).second;
ASSERT(inserted);
if (solverState)
recordChange(SolverTrail::Change::RecordedTarget(key));
}
void ConstraintSystem::removeTargetFor(SyntacticElementTargetKey key) {
bool erased = targets.erase(key);
ASSERT(erased);
}
std::optional<SyntacticElementTarget>
ConstraintSystem::getTargetFor(SyntacticElementTargetKey key) const {
auto known = targets.find(key);
if (known == targets.end())
return std::nullopt;
return known->second;
}
std::optional<SyntacticElementTarget>
Solution::getTargetFor(SyntacticElementTargetKey key) const {
auto known = targets.find(key);
if (known == targets.end())
return std::nullopt;
return known->second;
}
namespace {
// Produce an implicit empty tuple expression.
Expr *getVoidExpr(ASTContext &ctx, SourceLoc contextLoc = SourceLoc()) {
auto *voidExpr = TupleExpr::createEmpty(ctx,
/*LParenLoc=*/contextLoc,
/*RParenLoc=*/contextLoc,
/*Implicit=*/true);
voidExpr->setType(ctx.TheEmptyTupleType);
return voidExpr;
}
/// Find any type variable references inside of an AST node.
class TypeVariableRefFinder : public ASTWalker {
/// A stack of all closures the walker encountered so far.
SmallVector<DeclContext *> ClosureDCs;
ConstraintSystem &CS;
ASTNode Parent;
llvm::SmallPtrSetImpl<TypeVariableType *> &ReferencedVars;
public:
TypeVariableRefFinder(
ConstraintSystem &cs, ASTNode parent, ContextualTypeInfo context,
llvm::SmallPtrSetImpl<TypeVariableType *> &referencedVars)
: CS(cs), Parent(parent), ReferencedVars(referencedVars) {
if (auto ty = context.getType())
inferVariables(ty);
if (auto *closure = getAsExpr<ClosureExpr>(Parent))
ClosureDCs.push_back(closure);
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *expr) override {
if (auto *closure = dyn_cast<ClosureExpr>(expr)) {
ClosureDCs.push_back(closure);
}
if (auto *joinExpr = dyn_cast<TypeJoinExpr>(expr)) {
// If this join is over a known type, let's
// analyze it too because it can contain type
// variables.
if (!joinExpr->getVar())
inferVariables(joinExpr->getType());
}
if (auto *DRE = dyn_cast<DeclRefExpr>(expr)) {
auto *decl = DRE->getDecl();
if (auto type = CS.getTypeIfAvailable(decl)) {
auto &ctx = CS.getASTContext();
// If this is not one of the closure parameters which
// is inferrable from the body, let's replace type
// variables with errors to avoid bringing external
// information to the element component.
if (type->hasTypeVariable() &&
!(isa<ParamDecl>(decl) || decl->getName() == ctx.Id_builderSelf)) {
// If there are type variables left in the simplified version,
// it means that this is an invalid external declaration
// relative to this element's context.
if (CS.simplifyType(type)->hasTypeVariable()) {
auto transformedTy = type.transformRec([&](Type type) -> std::optional<Type> {
if (type->is<TypeVariableType>()) {
return Type(ErrorType::get(CS.getASTContext()));
}
return std::nullopt;
});
CS.setType(decl, transformedTy);
return Action::Continue(expr);
}
}
inferVariables(type);
return Action::Continue(expr);
}
auto var = dyn_cast<VarDecl>(decl);
if (!var)
return Action::Continue(expr);
if (auto *wrappedVar = var->getOriginalWrappedProperty()) {
// If there is no type it means that the body of the
// closure hasn't been resolved yet, so we can
// just skip it and wait for \c applyPropertyWrapperToParameter
// to assign types.
if (wrappedVar->hasImplicitPropertyWrapper())
return Action::Continue(expr);
auto outermostWrapperAttr =
wrappedVar->getOutermostAttachedPropertyWrapper();
// If the attribute doesn't have a type it could only mean
// that the declaration was incorrect.
if (!CS.hasType(outermostWrapperAttr->getTypeExpr()))
return Action::Continue(expr);
auto wrapperType =
CS.simplifyType(CS.getType(outermostWrapperAttr->getTypeExpr()));
if (var->getName().hasDollarPrefix()) {
// $<name> is the projected value var
CS.setType(var, computeProjectedValueType(wrappedVar, wrapperType));
} else {
// _<name> is the wrapper var
CS.setType(var, wrapperType);
}
return Action::Continue(expr);
}
// If there is no type recorded yet, let's check whether
// it is a placeholder variable implicitly generated by the
// compiler.
if (auto *PB = var->getParentPatternBinding()) {
if (auto placeholderTy = isPlaceholderVar(PB)) {
auto openedTy = CS.replaceInferableTypesWithTypeVars(
placeholderTy, CS.getConstraintLocator(expr));
inferVariables(openedTy);
CS.setType(var, openedTy);
}
}
}
// If closure appears inside of a pack expansion, the elements
// that reference pack elements have to bring expansion's shape
// type in scope to make sure that the shapes match.
if (auto *packElement = getAsExpr<PackElementExpr>(expr)) {
if (auto *outerExpansion = CS.getPackElementExpansion(packElement)) {
auto *expansionTy = CS.simplifyType(CS.getType(outerExpansion))
->castTo<PackExpansionType>();
expansionTy->getCountType()->getTypeVariables(ReferencedVars);
}
}
return Action::Continue(expr);
}
PostWalkResult<Expr *> walkToExprPost(Expr *expr) override {
if (isa<ClosureExpr>(expr)) {
ClosureDCs.pop_back();
}
return Action::Continue(expr);
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *stmt) override {
// Return statements have to reference outside result type
// since all of them are joined by it if it's not specified
// explicitly.
if (isa<ReturnStmt>(stmt)) {
if (auto *closure = getAsExpr<ClosureExpr>(Parent)) {
// Return is only viable if it belongs to a parent closure.
if (currentClosureDC() == closure)
inferVariables(CS.getClosureType(closure)->getResult());
}
}
return Action::Continue(stmt);
}
PreWalkAction walkToDeclPre(Decl *D) override {
/// Decls get type-checked separately, except for PatternBindingDecls,
/// whose initializers we want to walk into.
return Action::VisitNodeIf(isa<PatternBindingDecl>(D));
}
private:
DeclContext *currentClosureDC() const {
return ClosureDCs.empty() ? nullptr : ClosureDCs.back();
}
void inferVariables(Type type) {
type = type->getWithoutSpecifierType();
// Record the type variable itself because it has to
// be in scope even when already bound.
if (auto *typeVar = type->getAs<TypeVariableType>()) {
ReferencedVars.insert(typeVar);
// It is possible that contextual type of a parameter/result
// has been assigned to e.g. an anonymous or named argument
// early, to facilitate closure type checking. Such a
// type can have type variables inside e.g.
//
// func test<T>(_: (UnsafePointer<T>) -> Void) {}
//
// test { ptr in
// ...
// }
//
// Type variable representing `ptr` in the body of
// this closure would be bound to `UnsafePointer<$T>`
// in this case, where `$T` is a type variable for a
// generic parameter `T`.
type = CS.getFixedTypeRecursive(typeVar, /*wantRValue=*/false);
if (type->isEqual(typeVar))
return;
}
// Desugar type before collecting type variables, otherwise
// we can bring in scope unrelated type variables passed
// into the closure (via parameter/result) from contextual type.
// For example `Typealias<$T, $U>.Context` which desugars into
// `_Context<$U>` would bring in `$T` that could be inferrable
// only after the body of the closure is solved.
type = type->getCanonicalType();
// Don't walk into the opaque archetypes because they are not
// transparent in this context - `some P` could reference a
// type variables as substitutions which are visible only to
// the outer context.
if (type->is<OpaqueTypeArchetypeType>())
return;
if (type->hasTypeVariable()) {
SmallPtrSet<TypeVariableType *, 4> typeVars;
type->getTypeVariables(typeVars);
// Some of the type variables could be non-representative, so
// we need to recurse into `inferTypeVariables` to property
// handle them.
for (auto *typeVar : typeVars)
inferVariables(typeVar);
}
}
};
// MARK: Constraint generation
/// Check whether it makes sense to convert this element into a constraint.
static bool isViableElement(ASTNode element,
bool isForSingleValueStmtCompletion,
ConstraintSystem &cs) {
if (auto *decl = element.dyn_cast<Decl *>()) {
// - Ignore variable declarations, they are handled by pattern bindings;
if (isa<VarDecl>(decl))
return false;
}
if (auto *stmt = element.dyn_cast<Stmt *>()) {
if (auto *braceStmt = dyn_cast<BraceStmt>(stmt)) {
// Empty brace statements are not viable because they do not require
// inference.
if (braceStmt->empty())
return false;
// Skip if we're doing completion for a SingleValueStmtExpr, and have a
// brace that doesn't involve a single expression, and doesn't have a
// code completion token, as it won't contribute to the type of the
// SingleValueStmtExpr.
if (isForSingleValueStmtCompletion &&
!SingleValueStmtExpr::hasResult(braceStmt) &&
!cs.containsIDEInspectionTarget(braceStmt)) {
return false;
}
}
}
return true;
}
using ElementInfo = std::tuple<ASTNode, ContextualTypeInfo,
/*isDiscarded=*/bool, ConstraintLocator *>;
static void createConjunction(ConstraintSystem &cs, DeclContext *dc,
ArrayRef<ElementInfo> elements,
ConstraintLocator *locator, bool isIsolated,
ArrayRef<TypeVariableType *> extraTypeVars) {
SmallVector<Constraint *, 4> constraints;
SmallVector<TypeVariableType *, 2> referencedVars;
referencedVars.append(extraTypeVars.begin(), extraTypeVars.end());
if (locator->directlyAt<ClosureExpr>()) {
auto *closure = castToExpr<ClosureExpr>(locator->getAnchor());
// Conjunction associated with the body of the closure has to
// reference a type variable representing closure type,
// otherwise it would get disconnected from its contextual type.
referencedVars.push_back(cs.getType(closure)->castTo<TypeVariableType>());
// Result builder could be generic but attribute allows its use
// in "unbound" form (i.e. `@Builder` where `Builder` is defined
// as `struct Builder<T>`). Generic parameters of such a result
// builder type are inferable from context, namely from `build*`
// calls injected by the transform, and are not always resolved at
// the time conjunction is created.
//
// Conjunction needs to reference all the type variables associated
// with result builder just like parameters and result type of
// the closure in order to stay connected to its context.
if (auto builder = cs.getAppliedResultBuilderTransform(closure)) {
SmallPtrSet<TypeVariableType *, 4> builderVars;
builder->builderType->getTypeVariables(builderVars);
referencedVars.append(builderVars.begin(), builderVars.end());
}
// Body of the closure is always isolated from its context, only
// its individual elements are allowed access to type information
// from the outside e.g. parameters/result type.
isIsolated = true;
}
if (locator->isForSingleValueStmtConjunction()) {
auto *SVE = castToExpr<SingleValueStmtExpr>(locator->getAnchor());
referencedVars.push_back(cs.getType(SVE)->castTo<TypeVariableType>());
// Single value statement conjunctions are always isolated, as we want to
// solve the branches independently of the rest of the system.
isIsolated = true;
}
if (locator->directlyAt<TapExpr>()) {
// Body of the interpolation is always isolated from its context, only
// its individual elements are allowed access to type information
// from the outside e.g. external declaration references.
isIsolated = true;
}
TypeVarRefCollector paramCollector(cs, dc, locator);
// Whether we're doing completion, and the conjunction is for a
// SingleValueStmtExpr, or one of its braces.
const auto isForSingleValueStmtCompletion =
cs.isForCodeCompletion() &&
locator->isForSingleValueStmtConjunctionOrBrace();
for (const auto &entry : elements) {
ASTNode element = std::get<0>(entry);
ContextualTypeInfo context = std::get<1>(entry);
bool isDiscarded = std::get<2>(entry);
ConstraintLocator *elementLoc = std::get<3>(entry);
if (!isViableElement(element, isForSingleValueStmtCompletion, cs))
continue;
// If this conjunction going to represent a body of a closure,
// let's collect references to not yet resolved outer
// closure parameters.
if (isIsolated)
element.walk(paramCollector);
constraints.push_back(Constraint::createSyntacticElement(
cs, element, context, elementLoc, isDiscarded));
}
// It's possible that there are no viable elements in the body,
// because e.g. whole body is an `#if` statement or it only has
// declarations that are checked during solution application.
// In such cases, let's avoid creating a conjunction.
if (constraints.empty())
return;
for (auto *externalVar : paramCollector.getTypeVars())
referencedVars.push_back(externalVar);
cs.addUnsolvedConstraint(Constraint::createConjunction(
cs, constraints, isIsolated, locator, referencedVars));
}
ElementInfo makeElement(ASTNode node, ConstraintLocator *locator,
ContextualTypeInfo context = ContextualTypeInfo(),
bool isDiscarded = false) {
return std::make_tuple(node, context, isDiscarded, locator);
}
ElementInfo makeJoinElement(ConstraintSystem &cs, TypeJoinExpr *join,
ConstraintLocator *locator) {
return makeElement(
join, cs.getConstraintLocator(locator,
{LocatorPathElt::SyntacticElement(join)}));
}
struct SyntacticElementContext
: public llvm::PointerUnion<AbstractFunctionDecl *, AbstractClosureExpr *,
SingleValueStmtExpr *, ExprPattern *, TapExpr *,
CaptureListExpr *> {
// Inherit the constructors from PointerUnion.
using PointerUnion::PointerUnion;
/// A join that should be applied to the elements of a SingleValueStmtExpr.
NullablePtr<TypeJoinExpr> ElementJoin;
static SyntacticElementContext forTapExpr(TapExpr *tap) { return {tap}; }
static SyntacticElementContext forFunctionRef(AnyFunctionRef ref) {
if (auto *decl = ref.getAbstractFunctionDecl()) {
return {decl};
}
return {ref.getAbstractClosureExpr()};
}
static SyntacticElementContext forClosure(ClosureExpr *closure) {
return {closure};
}
static SyntacticElementContext forFunction(AbstractFunctionDecl *func) {
return {func};
}
static SyntacticElementContext forCaptureList(CaptureListExpr *CLE) {
return {CLE};
}
static SyntacticElementContext
forSingleValueStmtExpr(SingleValueStmtExpr *SVE,
TypeJoinExpr *Join = nullptr) {
auto context = SyntacticElementContext{SVE};
context.ElementJoin = Join;
return context;
}
static SyntacticElementContext forExprPattern(ExprPattern *EP) {
return SyntacticElementContext{EP};
}
DeclContext *getAsDeclContext() const {
if (auto *fn = this->dyn_cast<AbstractFunctionDecl *>()) {
return fn;
} else if (auto *closure = this->dyn_cast<AbstractClosureExpr *>()) {
return closure;
} else if (auto *SVE = dyn_cast<SingleValueStmtExpr *>()) {
return SVE->getDeclContext();
} else if (auto *EP = dyn_cast<ExprPattern *>()) {
return EP->getDeclContext();
} else if (auto *tap = this->dyn_cast<TapExpr *>()) {
return tap->getVar()->getDeclContext();
} else if (auto *CLE = this->dyn_cast<CaptureListExpr *>()) {
// The capture list is part of the closure's parent context.
return CLE->getClosureBody()->getParent();
} else {
llvm_unreachable("unsupported kind");
}
}
NullablePtr<ClosureExpr> getAsClosureExpr() const {
return dyn_cast_or_null<ClosureExpr>(
this->dyn_cast<AbstractClosureExpr *>());
}
NullablePtr<AbstractClosureExpr> getAsAbstractClosureExpr() const {
return this->dyn_cast<AbstractClosureExpr *>();
}
NullablePtr<AbstractFunctionDecl> getAsAbstractFunctionDecl() const {
return this->dyn_cast<AbstractFunctionDecl *>();
}
NullablePtr<SingleValueStmtExpr> getAsSingleValueStmtExpr() const {
return this->dyn_cast<SingleValueStmtExpr *>();
}
std::optional<AnyFunctionRef> getAsAnyFunctionRef() const {
if (auto *fn = this->dyn_cast<AbstractFunctionDecl *>()) {
return {fn};
} else if (auto *closure = this->dyn_cast<AbstractClosureExpr *>()) {
return {closure};
} else {
return std::nullopt;
}
}
Stmt *getStmt() const {
if (auto *fn = this->dyn_cast<AbstractFunctionDecl *>()) {
return fn->getBody();
} else if (auto *closure = this->dyn_cast<AbstractClosureExpr *>()) {
return closure->getBody();
} else if (auto *SVE = dyn_cast<SingleValueStmtExpr *>()) {
return SVE->getStmt();
} else if (auto *tap = this->dyn_cast<TapExpr *>()) {
return tap->getBody();
} else {
llvm_unreachable("unsupported kind");
}
}
bool isSingleExpressionClosure(ConstraintSystem &cs) const {
if (auto ref = getAsAnyFunctionRef()) {
if (cs.getAppliedResultBuilderTransform(*ref))
return false;
if (auto *closure = ref->getAbstractClosureExpr())
return closure->hasSingleExpressionBody();
}
return false;
}
};
/// Statement visitor that generates constraints for a given closure body.
class SyntacticElementConstraintGenerator
: public StmtVisitor<SyntacticElementConstraintGenerator, void> {
friend StmtVisitor<SyntacticElementConstraintGenerator, void>;
ConstraintSystem &cs;
SyntacticElementContext context;
ConstraintLocator *locator;
std::optional<llvm::SaveAndRestore<DeclContext *>> DCScope;
/// Whether a conjunction was generated.
bool generatedConjunction = false;
public:
/// Whether an error was encountered while generating constraints.
bool hadError = false;
SyntacticElementConstraintGenerator(ConstraintSystem &cs,
SyntacticElementContext context,
ConstraintLocator *locator)
: cs(cs), context(context), locator(locator) {
// Capture list bindings in multi-statement closures get solved as part of
// the closure's conjunction, which has the DeclContext set to the closure.
// This is wrong for captures though, which are semantically bound outside
// of the closure body. So we need to re-adjust their DeclContext here for
// constraint generation. The constraint system's DeclContext will be wrong
// for solving, but CSGen should ensure that constraints carry the correct
// DeclContext.
if (context.is<CaptureListExpr *>())
DCScope.emplace(cs.DC, context.getAsDeclContext());
}
void createConjunction(ArrayRef<ElementInfo> elements,
ConstraintLocator *locator, bool isIsolated = false,
ArrayRef<TypeVariableType *> extraTypeVars = {}) {
assert(!generatedConjunction && "Already generated conjunction");
generatedConjunction = true;
// Inject a join if we have one.
SmallVector<ElementInfo, 4> scratch;
if (auto *join = context.ElementJoin.getPtrOrNull()) {
scratch.append(elements.begin(), elements.end());
scratch.push_back(makeJoinElement(cs, join, locator));
elements = scratch;
}
::createConjunction(cs, context.getAsDeclContext(), elements, locator,
isIsolated, extraTypeVars);
}
void visitExprPattern(ExprPattern *EP) {
auto target = SyntacticElementTarget::forExprPattern(EP);
if (cs.preCheckTarget(target)) {
hadError = true;
return;
}
cs.setType(EP->getMatchVar(), cs.getType(EP));
if (cs.generateConstraints(target)) {
hadError = true;
return;
}
cs.setTargetFor(EP, target);
cs.setExprPatternFor(EP->getSubExpr(), EP);
}
void visitPattern(Pattern *pattern, ContextualTypeInfo contextInfo) {
if (context.is<ExprPattern *>()) {
// This is for an ExprPattern conjunction, go ahead and generate
// constraints for the match expression.
visitExprPattern(cast<ExprPattern>(pattern));
return;
}
auto parentElement =
locator->getLastElementAs<LocatorPathElt::SyntacticElement>();
if (!parentElement) {
hadError = true;
return;
}
if (auto *stmt = parentElement->getElement().dyn_cast<Stmt *>()) {
if (isa<ForEachStmt>(stmt)) {
visitForEachPattern(pattern, cast<ForEachStmt>(stmt));
return;
}
if (isa<CaseStmt>(stmt)) {
visitCaseItemPattern(pattern, contextInfo);
return;
}
}
llvm_unreachable("Unsupported pattern");
}
void visitCaseItem(CaseLabelItem *caseItem, ContextualTypeInfo contextInfo) {
assert(contextInfo.purpose == CTP_CaseStmt);
auto *DC = context.getAsDeclContext();
auto &ctx = DC->getASTContext();
// Resolve the pattern.
auto *pattern = caseItem->getPattern();
if (!caseItem->isPatternResolved()) {
pattern = TypeChecker::resolvePattern(pattern, context.getAsDeclContext(),
/*isStmtCondition=*/false);
if (!pattern) {
hadError = true;
return;
}
caseItem->setPattern(pattern, /*resolved=*/true);
}
// Let's generate constraints for pattern + where clause.
// The assumption is that this shouldn't be too complex
// to handle, but if it turns out to be false, this could
// always be converted into a conjunction.
// Generate constraints for pattern.
visitPattern(pattern, contextInfo);
auto *guardExpr = caseItem->getGuardExpr();
// Generate constraints for `where` clause (if any).
if (guardExpr) {
SyntacticElementTarget guardTarget(
guardExpr, DC, CTP_Condition, ctx.getBoolType(), /*discarded*/ false);
if (cs.generateConstraints(guardTarget)) {
hadError = true;
return;
}
guardExpr = guardTarget.getAsExpr();
cs.setTargetFor(guardExpr, guardTarget);
}
// Save information about case item so it could be referenced during
// solution application.
cs.setCaseLabelItemInfo(caseItem, {pattern, guardExpr});
}
private:
/// This method handles both pattern and the sequence expression
/// associated with `for-in` loop because types in this situation
/// flow in both directions:
///
/// - From pattern to sequence, informing its element type e.g.
/// `for i: Int8 in 0 ..< 8`
///
/// - From sequence to pattern, when pattern has no type information.
void visitForEachPattern(Pattern *pattern, ForEachStmt *forEachStmt) {
auto target = SyntacticElementTarget::forForEachPreamble(
forEachStmt, context.getAsDeclContext());
if (cs.generateConstraints(target)) {
hadError = true;
return;
}
// After successful constraint generation, let's record
// syntactic element target with all relevant information.
cs.setTargetFor(forEachStmt, target);
}
void visitCaseItemPattern(Pattern *pattern, ContextualTypeInfo context) {
Type patternType = cs.generateConstraints(
pattern, locator, /*bindPatternVarsOneWay=*/false,
/*patternBinding=*/nullptr, /*patternIndex=*/0);
if (!patternType) {
hadError = true;
return;
}
// Convert the contextual type to the pattern, which establishes the
// bindings.
auto *loc = cs.getConstraintLocator(
locator, {LocatorPathElt::PatternMatch(pattern),
LocatorPathElt::ContextualType(context.purpose)});
cs.addConstraint(ConstraintKind::Equal, context.getType(), patternType,
loc);
// For any pattern variable that has a parent variable (i.e., another
// pattern variable with the same name in the same case), require that
// the types be equivalent.
pattern->forEachNode([&](Pattern *pattern) {
auto namedPattern = dyn_cast<NamedPattern>(pattern);
if (!namedPattern)
return;
auto var = namedPattern->getDecl();
if (auto parentVar = var->getParentVarDecl()) {
cs.addConstraint(
ConstraintKind::Equal, cs.getType(parentVar), cs.getType(var),
cs.getConstraintLocator(
locator, LocatorPathElt::PatternMatch(namedPattern)));
}
});
}
void visitPatternBinding(PatternBindingDecl *patternBinding,
SmallVectorImpl<ElementInfo> &patterns) {
auto *baseLoc = cs.getConstraintLocator(
locator, LocatorPathElt::SyntacticElement(patternBinding));
for (unsigned index : range(patternBinding->getNumPatternEntries())) {
if (patternBinding->isInitializerChecked(index))
continue;
auto *pattern = TypeChecker::resolvePattern(
patternBinding->getPattern(index), patternBinding->getDeclContext(),
/*isStmtCondition=*/true);
if (!pattern) {
hadError = true;
return;
}
// Reset binding to point to the resolved pattern. This is required
// before calling `forPatternBindingDecl`.
patternBinding->setPattern(index, pattern);
patterns.push_back(makeElement(
patternBinding,
cs.getConstraintLocator(
baseLoc, LocatorPathElt::PatternBindingElement(index))));
}
}
std::optional<SyntacticElementTarget>
getTargetForPattern(PatternBindingDecl *patternBinding, unsigned index,
Type patternType) {
auto hasPropertyWrapper = [&](Pattern *pattern) -> bool {
if (auto *singleVar = pattern->getSingleVar())
return singleVar->hasAttachedPropertyWrapper();
return false;
};
auto *pattern = patternBinding->getPattern(index);
auto *init = patternBinding->getInit(index);
if (!init && patternBinding->isDefaultInitializable(index) &&
pattern->hasStorage()) {
init = TypeChecker::buildDefaultInitializer(patternType);
}
// A property wrapper initializer (either user-defined
// or a synthesized one) has to be pre-checked before use.
//
// This is not a problem in top-level code because pattern
// bindings go through `typeCheckExpression` which does
// pre-check automatically and result builders do not allow
// declaring local wrapped variables (yet).
if (hasPropertyWrapper(pattern)) {
auto target = SyntacticElementTarget::forInitialization(
init, patternType, patternBinding, index,
/*bindPatternVarsOneWay=*/false);
if (ConstraintSystem::preCheckTarget(target))
return std::nullopt;
return target;
}
if (init) {
return SyntacticElementTarget::forInitialization(
init, patternType, patternBinding, index,
/*bindPatternVarsOneWay=*/false);
}
return SyntacticElementTarget::forUninitializedVar(patternBinding, index,
patternType);
}
void visitPatternBindingElement(PatternBindingDecl *patternBinding) {
assert(locator->isLastElement<LocatorPathElt::PatternBindingElement>());
auto index =
locator->castLastElementTo<LocatorPathElt::PatternBindingElement>()
.getIndex();
if (patternBinding->isInitializerChecked(index))
return;
auto contextualPattern =
ContextualPattern::forPatternBindingDecl(patternBinding, index);
Type patternType = TypeChecker::typeCheckPattern(contextualPattern);
// Fail early if pattern couldn't be type-checked.
if (!patternType || patternType->hasError()) {
hadError = true;
return;
}
auto target = getTargetForPattern(patternBinding, index, patternType);
if (!target) {
hadError = true;
return;
}
// Keep track of this binding entry.
cs.setTargetFor({patternBinding, index}, *target);
if (isPlaceholderVar(patternBinding))
return;
if (cs.generateConstraints(*target)) {
hadError = true;
return;
}
}
void visitDecl(Decl *decl) {
if (!context.isSingleExpressionClosure(cs)) {
if (auto patternBinding = dyn_cast<PatternBindingDecl>(decl)) {
if (locator->isLastElement<LocatorPathElt::PatternBindingElement>())
visitPatternBindingElement(patternBinding);
else
llvm_unreachable("cannot visit pattern binding directly");
return;
}
}
// Ignore variable declarations, because they're always handled within
// their enclosing pattern bindings.
if (isa<VarDecl>(decl))
return;
// Other declarations will be handled at application time.
}
// These statements don't require any type-checking.
void visitBreakStmt(BreakStmt *breakStmt) {}
void visitContinueStmt(ContinueStmt *continueStmt) {}
void visitDeferStmt(DeferStmt *deferStmt) {}
void visitFallthroughStmt(FallthroughStmt *fallthroughStmt) {}
void visitFailStmt(FailStmt *fail) {}
void visitStmtCondition(LabeledConditionalStmt *S,
SmallVectorImpl<ElementInfo> &elements,
ConstraintLocator *locator) {
auto *condLocator =
cs.getConstraintLocator(locator, ConstraintLocator::Condition);
for (auto &condition : S->getCond())
elements.push_back(makeElement(&condition, condLocator));
}
void visitIfStmt(IfStmt *ifStmt) {
SmallVector<ElementInfo, 4> elements;
// Condition
visitStmtCondition(ifStmt, elements, locator);
// Then Branch
{
auto *thenLoc = cs.getConstraintLocator(
locator, LocatorPathElt::TernaryBranch(/*then=*/true));
elements.push_back(makeElement(ifStmt->getThenStmt(), thenLoc));
}
// Else Branch (if any).
if (auto *elseStmt = ifStmt->getElseStmt()) {
auto *elseLoc = cs.getConstraintLocator(
locator, LocatorPathElt::TernaryBranch(/*then=*/false));
elements.push_back(makeElement(elseStmt, elseLoc));
}
createConjunction(elements, locator);
}
void visitGuardStmt(GuardStmt *guardStmt) {
SmallVector<ElementInfo, 4> elements;
visitStmtCondition(guardStmt, elements, locator);
elements.push_back(makeElement(guardStmt->getBody(), locator));
createConjunction(elements, locator);
}
void visitWhileStmt(WhileStmt *whileStmt) {
SmallVector<ElementInfo, 4> elements;
visitStmtCondition(whileStmt, elements, locator);
elements.push_back(makeElement(whileStmt->getBody(), locator));
createConjunction(elements, locator);
}
void visitDoStmt(DoStmt *doStmt) {
visitBraceStmt(doStmt->getBody());
}
void visitRepeatWhileStmt(RepeatWhileStmt *repeatWhileStmt) {
createConjunction({makeElement(repeatWhileStmt->getCond(),
cs.getConstraintLocator(
locator, ConstraintLocator::Condition),
getContextForCondition()),
makeElement(repeatWhileStmt->getBody(), locator)},
locator);
}
void visitPoundAssertStmt(PoundAssertStmt *poundAssertStmt) {
createConjunction({makeElement(poundAssertStmt->getCondition(),
cs.getConstraintLocator(
locator, ConstraintLocator::Condition),
getContextForCondition())},
locator);
}
void visitThrowStmt(ThrowStmt *throwStmt) {
// Look up the catch node for this "throw" to determine the error type.
auto dc = context.getAsDeclContext();
auto module = dc->getParentModule();
auto throwLoc = throwStmt->getThrowLoc();
Type errorType;
if (auto catchNode = ASTScope::lookupCatchNode(module, throwLoc))
errorType = cs.getExplicitCaughtErrorType(catchNode);
if (!errorType) {
if (!cs.getASTContext().getErrorDecl()) {
hadError = true;
return;
}
errorType = cs.getASTContext().getErrorExistentialType();
}
auto *errorExpr = throwStmt->getSubExpr();
createConjunction(
{makeElement(errorExpr,
cs.getConstraintLocator(
locator, LocatorPathElt::SyntacticElement(errorExpr)),
{errorType, CTP_ThrowStmt})},
locator);
}
void visitDiscardStmt(DiscardStmt *discardStmt) {
auto *fn = discardStmt->getInnermostMethodContext();
if (!fn) {
hadError = true;
return;
}
auto nominalType =