- Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathPattern.cpp
857 lines (726 loc) · 26.9 KB
/
Pattern.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
//===--- Pattern.cpp - Swift Language Pattern-Matching ASTs ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the Pattern class and subclasses.
//
//===----------------------------------------------------------------------===//
#include"swift/AST/Pattern.h"
#include"swift/AST/ASTContext.h"
#include"swift/AST/ASTVisitor.h"
#include"swift/AST/ASTWalker.h"
#include"swift/AST/Expr.h"
#include"swift/AST/GenericEnvironment.h"
#include"swift/AST/TypeCheckRequests.h"
#include"swift/AST/TypeLoc.h"
#include"swift/AST/TypeRepr.h"
#include"swift/Basic/Assertions.h"
#include"swift/Basic/Statistic.h"
#include"llvm/ADT/APFloat.h"
#include"llvm/Support/raw_ostream.h"
usingnamespaceswift;
#definePATTERN(Id, _) \
static_assert(IsTriviallyDestructible<Id##Pattern>::value, \
"Patterns are BumpPtrAllocated; the d'tor is never called");
#include"swift/AST/PatternNodes.def"
DescriptivePatternKind Pattern::getDescriptiveKind() const {
#defineTRIVIAL_PATTERN_KIND(Kind) \
case PatternKind::Kind: \
return DescriptivePatternKind::Kind
switch (getKind()) {
TRIVIAL_PATTERN_KIND(Paren);
TRIVIAL_PATTERN_KIND(Tuple);
TRIVIAL_PATTERN_KIND(Named);
TRIVIAL_PATTERN_KIND(Any);
TRIVIAL_PATTERN_KIND(Typed);
TRIVIAL_PATTERN_KIND(Is);
TRIVIAL_PATTERN_KIND(EnumElement);
TRIVIAL_PATTERN_KIND(OptionalSome);
TRIVIAL_PATTERN_KIND(Bool);
TRIVIAL_PATTERN_KIND(Expr);
case PatternKind::Binding:
switch (cast<BindingPattern>(this)->getIntroducer()) {
case VarDecl::Introducer::Let:
case VarDecl::Introducer::Borrowing:
return DescriptivePatternKind::Let;
case VarDecl::Introducer::Var:
case VarDecl::Introducer::InOut:
return DescriptivePatternKind::Var;
}
}
#undef TRIVIAL_PATTERN_KIND
llvm_unreachable("bad DescriptivePatternKind");
}
StringRef Pattern::getKindName(PatternKind K) {
switch (K) {
#definePATTERN(Id, Parent) case PatternKind::Id: return #Id;
#include"swift/AST/PatternNodes.def"
}
llvm_unreachable("bad PatternKind");
}
StringRef Pattern::getDescriptivePatternKindName(DescriptivePatternKind K) {
#defineENTRY(Kind, String) \
case DescriptivePatternKind::Kind: \
return String
switch (K) {
ENTRY(Paren, "parenthesized pattern");
ENTRY(Tuple, "tuple pattern");
ENTRY(Named, "pattern variable binding");
ENTRY(Any, "'_' pattern");
ENTRY(Typed, "pattern type annotation");
ENTRY(Is, "prefix 'is' pattern");
ENTRY(EnumElement, "enum case matching pattern");
ENTRY(OptionalSome, "optional pattern");
ENTRY(Bool, "bool matching pattern");
ENTRY(Expr, "expression pattern");
ENTRY(Var, "'var' binding pattern");
ENTRY(Let, "'let' binding pattern");
}
#undef ENTRY
llvm_unreachable("bad DescriptivePatternKind");
}
// Metaprogram to verify that every concrete class implements
// a 'static bool classof(const Pattern*)'.
template <boolfn(const Pattern*)> struct CheckClassOfPattern {
staticconstbool IsImplemented = true;
};
template <> structCheckClassOfPattern<Pattern::classof> {
staticconstbool IsImplemented = false;
};
#definePATTERN(ID, PARENT) \
static_assert(CheckClassOfPattern<ID##Pattern::classof>::IsImplemented, \
#ID "Pattern is missing classof(const Pattern*)");
#include"swift/AST/PatternNodes.def"
// Metaprogram to verify that every concrete class implements
// 'SourceRange getSourceRange()'.
typedefconstchar (&TwoChars)[2];
template<typename Class>
inlinecharcheckSourceRangeType(SourceRange (Class::*)() const);
inline TwoChars checkSourceRangeType(SourceRange (Pattern::*)() const);
/// getSourceRange - Return the full source range of the pattern.
SourceRange Pattern::getSourceRange() const {
switch (getKind()) {
#definePATTERN(ID, PARENT) \
case PatternKind::ID: \
static_assert(sizeof(checkSourceRangeType(&ID##Pattern::getSourceRange)) == 1, \
#ID "Pattern is missing getSourceRange()"); \
return cast<ID##Pattern>(this)->getSourceRange();
#include"swift/AST/PatternNodes.def"
}
llvm_unreachable("pattern type not handled!");
}
voidPattern::setDelayedInterfaceType(Type interfaceTy, DeclContext *dc) {
assert(interfaceTy->hasTypeParameter() && "Not an interface type");
Ty = interfaceTy;
ASTContext &ctx = interfaceTy->getASTContext();
ctx.DelayedPatternContexts[this] = dc;
Bits.Pattern.hasInterfaceType = true;
}
Type Pattern::getType() const {
assert(hasType());
// If this pattern has an interface type, map it into the context type.
if (Bits.Pattern.hasInterfaceType) {
ASTContext &ctx = Ty->getASTContext();
// Retrieve the generic environment to use for the mapping.
auto found = ctx.DelayedPatternContexts.find(this);
assert(found != ctx.DelayedPatternContexts.end());
auto dc = found->second;
if (auto genericEnv = dc->getGenericEnvironmentOfContext()) {
ctx.DelayedPatternContexts.erase(this);
Ty = genericEnv->mapTypeIntoContext(Ty);
const_cast<Pattern*>(this)->Bits.Pattern.hasInterfaceType = false;
}
}
return Ty;
}
/// getLoc - Return the caret location of the pattern.
SourceLoc Pattern::getLoc() const {
switch (getKind()) {
#definePATTERN(ID, PARENT) \
case PatternKind::ID: \
if (&Pattern::getLoc != &ID##Pattern::getLoc) \
return cast<ID##Pattern>(this)->getLoc(); \
break;
#include"swift/AST/PatternNodes.def"
}
returngetStartLoc();
}
voidPattern::collectVariables(SmallVectorImpl<VarDecl *> &variables) const {
forEachVariable([&](VarDecl *VD) { variables.push_back(VD); });
}
VarDecl *Pattern::getSingleVar() const {
auto pattern = getSemanticsProvidingPattern();
if (auto named = dyn_cast<NamedPattern>(pattern))
return named->getDecl();
returnnullptr;
}
namespace {
classWalkToVarDecls : publicASTWalker {
const std::function<void(VarDecl*)> &fn;
public:
WalkToVarDecls(const std::function<void(VarDecl*)> &fn)
: fn(fn) {}
/// Walk everything that's available; there shouldn't be macro expansions
/// that matter anyway.
MacroWalking getMacroWalkingBehavior() constoverride {
return MacroWalking::ArgumentsAndExpansion;
}
PostWalkResult<Pattern *> walkToPatternPost(Pattern *P) override {
// Handle vars.
if (auto *Named = dyn_cast<NamedPattern>(P))
fn(Named->getDecl());
returnAction::Continue(P);
}
// Only walk into an expression insofar as it doesn't open a new scope -
// that is, don't walk into a closure body.
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (isa<ClosureExpr>(E)) {
returnAction::SkipNode(E);
}
returnAction::Continue(E);
}
// Don't walk into anything else.
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
returnAction::SkipNode(S);
}
PreWalkAction walkToTypeReprPre(TypeRepr *T) override {
returnAction::SkipNode();
}
PreWalkAction walkToParameterListPre(ParameterList *PL) override {
returnAction::SkipNode();
}
PreWalkAction walkToDeclPre(Decl *D) override {
returnAction::SkipNode();
}
};
} // end anonymous namespace
/// apply the specified function to all variables referenced in this
/// pattern.
voidPattern::forEachVariable(llvm::function_ref<void(VarDecl *)> fn) const {
switch (getKind()) {
case PatternKind::Any:
case PatternKind::Bool:
return;
case PatternKind::Is:
if (auto SP = cast<IsPattern>(this)->getSubPattern())
SP->forEachVariable(fn);
return;
case PatternKind::Named:
fn(cast<NamedPattern>(this)->getDecl());
return;
case PatternKind::Paren:
case PatternKind::Typed:
case PatternKind::Binding:
returngetSemanticsProvidingPattern()->forEachVariable(fn);
case PatternKind::Tuple:
for (auto elt : cast<TuplePattern>(this)->getElements())
elt.getPattern()->forEachVariable(fn);
return;
case PatternKind::EnumElement:
if (auto SP = cast<EnumElementPattern>(this)->getSubPattern())
SP->forEachVariable(fn);
return;
case PatternKind::OptionalSome:
cast<OptionalSomePattern>(this)->getSubPattern()->forEachVariable(fn);
return;
case PatternKind::Expr:
// An ExprPattern only exists before sema has resolved a refutable pattern
// into a concrete pattern. We have to use an AST Walker to find the
// VarDecls buried down inside of it.
const_cast<Pattern*>(this)->walk(WalkToVarDecls(fn));
return;
}
}
/// apply the specified function to all pattern nodes recursively in
/// this pattern. This is a pre-order traversal.
voidPattern::forEachNode(llvm::function_ref<void(Pattern*)> f) {
f(this);
switch (getKind()) {
// Leaf patterns have no recursion.
case PatternKind::Any:
case PatternKind::Named:
case PatternKind::Expr:// FIXME: expr nodes are not modeled right in general.
case PatternKind::Bool:
return;
case PatternKind::Is:
if (auto SP = cast<IsPattern>(this)->getSubPattern())
SP->forEachNode(f);
return;
case PatternKind::Paren:
return cast<ParenPattern>(this)->getSubPattern()->forEachNode(f);
case PatternKind::Typed:
return cast<TypedPattern>(this)->getSubPattern()->forEachNode(f);
case PatternKind::Binding:
return cast<BindingPattern>(this)->getSubPattern()->forEachNode(f);
case PatternKind::Tuple:
for (auto elt : cast<TuplePattern>(this)->getElements())
elt.getPattern()->forEachNode(f);
return;
case PatternKind::EnumElement: {
auto *OP = cast<EnumElementPattern>(this);
if (OP->hasSubPattern())
OP->getSubPattern()->forEachNode(f);
return;
}
case PatternKind::OptionalSome:
cast<OptionalSomePattern>(this)->getSubPattern()->forEachNode(f);
return;
}
}
boolPattern::hasStorage() const {
bool HasStorage = false;
forEachVariable([&](VarDecl *VD) {
if (VD->hasStorage())
HasStorage = true;
});
return HasStorage;
}
boolPattern::hasAnyMutableBindings() const {
auto HasMutable = false;
forEachVariable([&](VarDecl *VD) {
if (!VD->isLet())
HasMutable = true;
});
return HasMutable;
}
BindingPattern *BindingPattern::createParsed(ASTContext &ctx, SourceLoc loc,
VarDecl::Introducer introducer,
Pattern *sub) {
// Reset the introducer of the all variables in the pattern.
sub->forEachVariable([&](VarDecl *vd) { vd->setIntroducer(introducer); });
returnnew (ctx) BindingPattern(loc, introducer, sub);
}
BindingPattern *BindingPattern::createImplicitCatch(DeclContext *dc,
SourceLoc loc) {
auto &ctx = dc->getASTContext();
auto var = new (ctx) VarDecl(/*IsStatic=*/false, VarDecl::Introducer::Let,
loc, ctx.Id_error, dc);
var->setImplicit();
auto namePattern = new (ctx) NamedPattern(var);
auto varPattern =
new (ctx) BindingPattern(loc, VarDecl::Introducer::Let, namePattern);
varPattern->setImplicit();
return varPattern;
}
OptionalSomePattern *OptionalSomePattern::create(ASTContext &ctx,
Pattern *subPattern,
SourceLoc questionLoc) {
returnnew (ctx) OptionalSomePattern(ctx, subPattern, questionLoc);
}
OptionalSomePattern *OptionalSomePattern::createImplicit(ASTContext &ctx,
Pattern *subPattern) {
auto *P = OptionalSomePattern::create(ctx, subPattern,
/*questionLoc*/SourceLoc());
P->setImplicit();
return P;
}
EnumElementDecl *OptionalSomePattern::getElementDecl() const {
return Ctx.getOptionalSomeDecl();
}
/// Return true if this is a non-resolved ExprPattern which is syntactically
/// irrefutable.
staticboolisIrrefutableExprPattern(const ExprPattern *EP) {
// If the pattern is resolved, it must be irrefutable.
if (EP->isResolved()) returnfalse;
auto expr = EP->getSubExpr();
while (true) {
// Drill into parens.
if (auto parens = dyn_cast<ParenExpr>(expr)) {
expr = parens->getSubExpr();
continue;
}
// A '_' is an untranslated AnyPattern.
if (isa<DiscardAssignmentExpr>(expr))
returntrue;
// Everything else is non-exhaustive.
returnfalse;
}
}
/// Return true if this pattern (or a subpattern) is refutable.
boolPattern::isRefutablePattern() const {
bool foundRefutablePattern = false;
const_cast<Pattern*>(this)->forEachNode([&](Pattern *Node) {
// If this is an always matching 'is' pattern, then it isn't refutable.
if (auto *is = dyn_cast<IsPattern>(Node))
if (is->getCastKind() == CheckedCastKind::Coercion ||
is->getCastKind() == CheckedCastKind::BridgingCoercion)
return;
// If this is an ExprPattern that isn't resolved yet, do some simple
// syntactic checks.
// FIXME: This is unsound, since type checking will turn other more
// complicated patterns into non-refutable forms.
if (auto *ep = dyn_cast<ExprPattern>(Node))
if (isIrrefutableExprPattern(ep))
return;
switch (Node->getKind()) {
#definePATTERN(ID, PARENT) case PatternKind::ID: break;
#defineREFUTABLE_PATTERN(ID, PARENT) \
case PatternKind::ID: foundRefutablePattern = true; break;
#include"swift/AST/PatternNodes.def"
}
});
return foundRefutablePattern;
}
/// Find the name directly bound by this pattern. When used as a
/// tuple element in a function signature, such names become part of
/// the type.
Identifier Pattern::getBoundName() const {
if (auto *NP = dyn_cast<NamedPattern>(getSemanticsProvidingPattern()))
return NP->getBoundName();
returnIdentifier();
}
Identifier NamedPattern::getBoundName() const {
return Var->getName();
}
/// Allocate a new pattern that matches a tuple.
TuplePattern *TuplePattern::create(ASTContext &C, SourceLoc lp,
ArrayRef<TuplePatternElt> elts,
SourceLoc rp) {
#ifndef NDEBUG
if (elts.size() == 1)
assert(!elts[0].getLabel().empty());
#endif
unsigned n = elts.size();
void *buffer = C.Allocate(totalSizeToAlloc<TuplePatternElt>(n),
alignof(TuplePattern));
TuplePattern *pattern = ::new (buffer) TuplePattern(lp, n, rp);
std::uninitialized_copy(elts.begin(), elts.end(),
pattern->getTrailingObjects<TuplePatternElt>());
return pattern;
}
Pattern *TuplePattern::createSimple(ASTContext &C, SourceLoc lp,
ArrayRef<TuplePatternElt> elements,
SourceLoc rp) {
assert(lp.isValid() == rp.isValid());
if (elements.size() == 1 &&
elements[0].getLabel().empty()) {
auto &first = const_cast<TuplePatternElt&>(elements.front());
returnnew (C) ParenPattern(lp, first.getPattern(), rp);
}
returncreate(C, lp, elements, rp);
}
SourceRange TuplePattern::getSourceRange() const {
if (LPLoc.isValid())
return { LPLoc, RPLoc };
auto Fields = getElements();
if (Fields.empty())
return {};
return { Fields.front().getPattern()->getStartLoc(),
Fields.back().getPattern()->getEndLoc() };
}
TypedPattern::TypedPattern(Pattern *pattern, TypeRepr *tr)
: Pattern(PatternKind::Typed), SubPattern(pattern), PatTypeRepr(tr) {
Bits.TypedPattern.IsPropagatedType = false;
}
SourceLoc TypedPattern::getLoc() const {
if (SubPattern->isImplicit() && PatTypeRepr)
return PatTypeRepr->getSourceRange().Start;
return SubPattern->getLoc();
}
SourceRange TypedPattern::getSourceRange() const {
if (isImplicit() || isPropagatedType()) {
// If a TypedPattern is implicit, then its type is definitely implicit, so
// we should ignore its location. On the other hand, the sub-pattern can
// be explicit or implicit.
return SubPattern->getSourceRange();
}
if (!PatTypeRepr)
returnSourceRange();
if (SubPattern->isImplicit())
return PatTypeRepr->getSourceRange();
return { SubPattern->getSourceRange().Start,
PatTypeRepr->getSourceRange().End };
}
IsPattern::IsPattern(SourceLoc IsLoc, TypeExpr *CastTy, Pattern *SubPattern,
CheckedCastKind Kind)
: Pattern(PatternKind::Is), IsLoc(IsLoc), SubPattern(SubPattern),
CastKind(Kind), CastType(CastTy) {
assert(IsLoc.isValid() == CastTy->getLoc().isValid());
}
IsPattern *IsPattern::createImplicit(ASTContext &Ctx, Type castTy,
Pattern *SubPattern,
CheckedCastKind Kind) {
assert(castTy);
auto *CastTE = TypeExpr::createImplicit(castTy, Ctx);
auto *ip = new (Ctx) IsPattern(SourceLoc(), CastTE, SubPattern, Kind);
ip->setImplicit();
return ip;
}
SourceRange IsPattern::getSourceRange() const {
SourceLoc beginLoc = SubPattern ? SubPattern->getSourceRange().Start : IsLoc;
SourceLoc endLoc = (isImplicit() ? beginLoc : CastType->getEndLoc());
return {beginLoc, endLoc};
}
Type IsPattern::getCastType() const { return CastType->getInstanceType(); }
voidIsPattern::setCastType(Type type) {
assert(type);
CastType->setType(MetatypeType::get(type));
}
TypeRepr *IsPattern::getCastTypeRepr() const { return CastType->getTypeRepr(); }
ExprPattern *ExprPattern::createParsed(ASTContext &ctx, Expr *E,
DeclContext *DC) {
returnnew (ctx) ExprPattern(E, DC, /*isResolved*/false);
}
ExprPattern *ExprPattern::createResolved(ASTContext &ctx, Expr *E,
DeclContext *DC) {
returnnew (ctx) ExprPattern(E, DC, /*isResolved*/true);
}
ExprPattern *ExprPattern::createImplicit(ASTContext &ctx, Expr *E,
DeclContext *DC) {
auto *EP = ExprPattern::createResolved(ctx, E, DC);
EP->setImplicit();
return EP;
}
Expr *ExprPattern::getMatchExpr() const {
auto &eval = DC->getASTContext().evaluator;
returnevaluateOrDefault(eval, ExprPatternMatchRequest{this}, std::nullopt)
.getMatchExpr();
}
VarDecl *ExprPattern::getMatchVar() const {
auto &eval = DC->getASTContext().evaluator;
returnevaluateOrDefault(eval, ExprPatternMatchRequest{this}, std::nullopt)
.getMatchVar();
}
voidExprPattern::updateMatchExpr(Expr *e) const {
classFindMatchOperatorDeclRef: publicASTWalker {
public:
ValueOwnership Ownership = ValueOwnership::Default;
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
// See if this is the reference to the ~= operator used.
auto declRef = dyn_cast<DeclRefExpr>(E);
if (!declRef) {
returnAction::Continue(E);
}
auto decl = declRef->getDecl();
auto declName = decl->getName();
if (!declName.isOperator()) {
returnAction::Continue(E);
}
if (!declName.getBaseIdentifier().is("~=")) {
returnAction::Continue(E);
}
// We found a `~=` declref. Get the value ownership from the parameter.
auto fnTy = decl->getInterfaceType()->castTo<AnyFunctionType>();
if (decl->isStatic()) {
fnTy = fnTy->getResult()->castTo<AnyFunctionType>();
}
// Subject value is the right-hand operand to the operator.
assert(fnTy->getParams().size() == 2);
Ownership = fnTy->getParams()[1].getValueOwnership();
// Operators are always normal functions or methods, so their default
// parameter ownership is always borrowing.
if (Ownership == ValueOwnership::Default) {
Ownership = ValueOwnership::Shared;
}
returnAction::Stop();
}
};
FindMatchOperatorDeclRef walker;
e->walk(walker);
MatchExprAndOperandOwnership = {e, walker.Ownership};
}
EnumElementPattern *
EnumElementPattern::createImplicit(Type parentTy, SourceLoc dotLoc,
DeclNameLoc nameLoc, EnumElementDecl *decl,
Pattern *subPattern, DeclContext *DC) {
auto &ctx = DC->getASTContext();
auto *parentExpr = TypeExpr::createImplicit(parentTy, ctx);
auto *P = new (ctx) EnumElementPattern(
parentExpr, dotLoc, nameLoc, decl->createNameRef(), decl, subPattern, DC);
P->setImplicit();
P->setType(parentTy);
return P;
}
SourceLoc EnumElementPattern::getStartLoc() const {
return (ParentType && !ParentType->isImplicit())
? ParentType->getSourceRange().Start
: DotLoc.isValid() ? DotLoc : NameLoc.getBaseNameLoc();
}
SourceLoc EnumElementPattern::getEndLoc() const {
if (SubPattern && SubPattern->getSourceRange().isValid()) {
return SubPattern->getSourceRange().End;
}
return NameLoc.getEndLoc();
}
TypeRepr *EnumElementPattern::getParentTypeRepr() const {
if (!ParentType)
returnnullptr;
return ParentType->getTypeRepr();
}
Type EnumElementPattern::getParentType() const {
if (!ParentType)
returnType();
return ParentType->getInstanceType();
}
voidEnumElementPattern::setParentType(Type type) {
assert(type);
if (ParentType) {
ParentType->setType(MetatypeType::get(type));
} else {
ParentType = TypeExpr::createImplicit(type, type->getASTContext());
}
}
SourceLoc ExprPattern::getLoc() const {
returngetSubExpr()->getLoc();
}
SourceRange ExprPattern::getSourceRange() const {
returngetSubExpr()->getSourceRange();
}
// See swift/Basic/Statistic.h for declaration: this enables tracing Patterns, is
// defined here to avoid too much layering violation / circular linkage
// dependency.
structPatternTraceFormatter : publicUnifiedStatsReporter::TraceFormatter {
voidtraceName(constvoid *Entity, raw_ostream &OS) constoverride {
if (!Entity)
return;
const Pattern *P = static_cast<const Pattern *>(Entity);
if (const NamedPattern *NP = dyn_cast<NamedPattern>(P)) {
OS << NP->getBoundName();
}
}
voidtraceLoc(constvoid *Entity, SourceManager *SM,
clang::SourceManager *CSM, raw_ostream &OS) constoverride {
if (!Entity)
return;
const Pattern *P = static_cast<const Pattern *>(Entity);
P->getSourceRange().print(OS, *SM, false);
}
};
static PatternTraceFormatter TF;
template<>
const UnifiedStatsReporter::TraceFormatter*
FrontendStatsTracer::getTraceFormatter<const Pattern *>() {
return &TF;
}
ContextualPattern ContextualPattern::forPatternBindingDecl(
PatternBindingDecl *pbd, unsigned index) {
returnContextualPattern(
pbd->getPattern(index), /*isTopLevel=*/true, pbd, index);
}
DeclContext *ContextualPattern::getDeclContext() const {
if (auto pbd = getPatternBindingDecl())
return pbd->getDeclContext();
return declOrContext.get<DeclContext *>();
}
PatternBindingDecl *ContextualPattern::getPatternBindingDecl() const {
return declOrContext.dyn_cast<PatternBindingDecl *>();
}
boolContextualPattern::allowsInference() const {
if (auto pbd = getPatternBindingDecl()) {
return pbd->isInitialized(index) ||
pbd->isDefaultInitializableViaPropertyWrapper(index);
}
returntrue;
}
voidswift::simple_display(llvm::raw_ostream &out,
const ContextualPattern &pattern) {
simple_display(out, pattern.getPattern());
}
voidswift::simple_display(llvm::raw_ostream &out, const Pattern *pattern) {
out << "(pattern @ " << pattern << ")";
}
SourceLoc swift::extractNearestSourceLoc(const Pattern *pattern) {
return pattern->getLoc();
}
ValueOwnership
Pattern::getOwnership(
SmallVectorImpl<Pattern *> *mostRestrictiveSubpatterns) const
{
classGetPatternOwnership: publicPatternVisitor<GetPatternOwnership, void> {
public:
ValueOwnership Ownership = ValueOwnership::Shared;
SmallVectorImpl<Pattern *> *RestrictingPatterns = nullptr;
voidincreaseOwnership(ValueOwnership newOwnership, Pattern *p) {
// If the new ownership is stricter than the current ownership, then
// clear the restricting patterns we'd collected and start over with the
// new stricter ownership.
if (newOwnership > Ownership) {
Ownership = newOwnership;
if (RestrictingPatterns) {
RestrictingPatterns->clear();
}
}
if (RestrictingPatterns
&& newOwnership == Ownership
&& Ownership > ValueOwnership::Shared) {
RestrictingPatterns->push_back(p);
}
}
#defineUSE_SUBPATTERN(Kind) \
void visit##Kind##Pattern(Kind##Pattern *pattern) { \
returnvisit(pattern->getSubPattern()); \
}
USE_SUBPATTERN(Paren)
USE_SUBPATTERN(Typed)
USE_SUBPATTERN(Binding)
#undef USE_SUBPATTERN
voidvisitTuplePattern(TuplePattern *p) {
for (auto &element : p->getElements()) {
visit(element.getPattern());
}
}
voidvisitNamedPattern(NamedPattern *p) {
switch (p->getDecl()->getIntroducer()) {
case VarDecl::Introducer::Let:
// `let` defaults to the prevailing ownership of the switch.
break;
case VarDecl::Introducer::Var:
// If the subpattern type is copyable, then we can bind the variable
// by copying without requiring more than a borrow of the original.
if (!p->hasType() || !p->getType()->isNoncopyable()) {
break;
}
// TODO: An explicit `consuming` binding kind consumes regardless of
// type.
// Noncopyable `var` consumes the bound value to move it into
// a new independent variable.
increaseOwnership(ValueOwnership::Owned, p);
break;
case VarDecl::Introducer::InOut:
// `inout` bindings modify the value in-place.
increaseOwnership(ValueOwnership::InOut, p);
break;
case VarDecl::Introducer::Borrowing:
// `borrow` bindings borrow parts of the value in-place.
increaseOwnership(ValueOwnership::Shared, p);
break;
}
}
voidvisitAnyPattern(AnyPattern *p) {
/* no change */
}
voidvisitBoolPattern(BoolPattern *p) {
/* no change */
}
voidvisitIsPattern(IsPattern *p) {
// Casting has to either be possible by borrowing or copying the subject,
// or can't be supported in a pattern match.
/* no change */
}
voidvisitEnumElementPattern(EnumElementPattern *p) {
if (p->hasSubPattern()) {
visit(p->getSubPattern());
}
}
voidvisitOptionalSomePattern(OptionalSomePattern *p) {
visit(p->getSubPattern());
}
voidvisitExprPattern(ExprPattern *p) {
// A `~=` operator has to be able to either borrow or copy the operand,
// or can't be used.
/* no change */
}
};
GetPatternOwnership visitor;
visitor.RestrictingPatterns = mostRestrictiveSubpatterns;
visitor.visit(const_cast<Pattern *>(this));
return visitor.Ownership;
}