forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Expr.cpp
1229 lines (1035 loc) · 40 KB
/
Expr.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
//===--- Expr.cpp - Swift Language Expression ASTs ------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the Expr class and subclasses.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Expr.h"
#include "swift/Basic/Unicode.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Decl.h" // FIXME: Bad dependency
#include "swift/AST/Stmt.h"
#include "swift/AST/AST.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AvailabilitySpec.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/TypeLoc.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/Twine.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Expr methods.
//===----------------------------------------------------------------------===//
// Only allow allocation of Stmts using the allocator in ASTContext.
void *Expr::operator new(size_t Bytes, ASTContext &C,
unsigned Alignment) {
return C.Allocate(Bytes, Alignment);
}
StringRef Expr::getKindName(ExprKind K) {
switch (K) {
#define EXPR(Id, Parent) case ExprKind::Id: return #Id;
#include "swift/AST/ExprNodes.def"
}
llvm_unreachable("bad ExprKind");
}
template <class T> static SourceLoc getStartLocImpl(const T *E);
template <class T> static SourceLoc getEndLocImpl(const T *E);
template <class T> static SourceLoc getLocImpl(const T *E);
// Helper functions to check statically whether a method has been
// overridden from its implementation in Expr. The sort of thing you
// need when you're avoiding v-tables.
namespace {
template <typename ReturnType, typename Class>
constexpr bool isOverriddenFromExpr(ReturnType (Class::*)() const) {
return true;
}
template <typename ReturnType>
constexpr bool isOverriddenFromExpr(ReturnType (Expr::*)() const) {
return false;
}
template <bool IsOverridden> struct Dispatch;
/// Dispatch down to a concrete override.
template <> struct Dispatch<true> {
template <class T> static SourceLoc getStartLoc(const T *E) {
return E->getStartLoc();
}
template <class T> static SourceLoc getEndLoc(const T *E) {
return E->getEndLoc();
}
template <class T> static SourceLoc getLoc(const T *E) {
return E->getLoc();
}
template <class T> static SourceRange getSourceRange(const T *E) {
return E->getSourceRange();
}
};
/// Default implementations for when a method isn't overridden.
template <> struct Dispatch<false> {
template <class T> static SourceLoc getStartLoc(const T *E) {
return E->getSourceRange().Start;
}
template <class T> static SourceLoc getEndLoc(const T *E) {
return E->getSourceRange().End;
}
template <class T> static SourceLoc getLoc(const T *E) {
return getStartLocImpl(E);
}
template <class T> static SourceRange getSourceRange(const T *E) {
return { E->getStartLoc(), E->getEndLoc() };
}
};
}
template <class T> static SourceRange getSourceRangeImpl(const T *E) {
static_assert(isOverriddenFromExpr(&T::getSourceRange) ||
(isOverriddenFromExpr(&T::getStartLoc) &&
isOverriddenFromExpr(&T::getEndLoc)),
"Expr subclass must implement either getSourceRange() "
"or getStartLoc()/getEndLoc()");
return Dispatch<isOverriddenFromExpr(&T::getSourceRange)>::getSourceRange(E);
}
SourceRange Expr::getSourceRange() const {
switch (getKind()) {
#define EXPR(ID, PARENT) \
case ExprKind::ID: return getSourceRangeImpl(cast<ID##Expr>(this));
#include "swift/AST/ExprNodes.def"
}
llvm_unreachable("expression type not handled!");
}
template <class T> static SourceLoc getStartLocImpl(const T *E) {
return Dispatch<isOverriddenFromExpr(&T::getStartLoc)>::getStartLoc(E);
}
SourceLoc Expr::getStartLoc() const {
switch (getKind()) {
#define EXPR(ID, PARENT) \
case ExprKind::ID: return getStartLocImpl(cast<ID##Expr>(this));
#include "swift/AST/ExprNodes.def"
}
llvm_unreachable("expression type not handled!");
}
template <class T> static SourceLoc getEndLocImpl(const T *E) {
return Dispatch<isOverriddenFromExpr(&T::getEndLoc)>::getEndLoc(E);
}
SourceLoc Expr::getEndLoc() const {
switch (getKind()) {
#define EXPR(ID, PARENT) \
case ExprKind::ID: return getEndLocImpl(cast<ID##Expr>(this));
#include "swift/AST/ExprNodes.def"
}
llvm_unreachable("expression type not handled!");
}
template <class T> static SourceLoc getLocImpl(const T *E) {
return Dispatch<isOverriddenFromExpr(&T::getLoc)>::getLoc(E);
}
SourceLoc Expr::getLoc() const {
switch (getKind()) {
#define EXPR(ID, PARENT) \
case ExprKind::ID: return getLocImpl(cast<ID##Expr>(this));
#include "swift/AST/ExprNodes.def"
}
llvm_unreachable("expression type not handled!");
}
Expr *Expr::getSemanticsProvidingExpr() {
if (IdentityExpr *IE = dyn_cast<IdentityExpr>(this))
return IE->getSubExpr()->getSemanticsProvidingExpr();
if (TryExpr *TE = dyn_cast<TryExpr>(this))
return TE->getSubExpr()->getSemanticsProvidingExpr();
if (DefaultValueExpr *DE = dyn_cast<DefaultValueExpr>(this))
return DE->getSubExpr()->getSemanticsProvidingExpr();
return this;
}
Expr *Expr::getValueProvidingExpr() {
Expr *E = getSemanticsProvidingExpr();
if (auto TE = dyn_cast<ForceTryExpr>(this))
return TE->getSubExpr()->getValueProvidingExpr();
// TODO:
// - tuple literal projection, which may become interestingly idiomatic
return E;
}
/// Propagate l-value use information to children.
void Expr::propagateLValueAccessKind(AccessKind accessKind,
bool allowOverwrite) {
/// A visitor class which walks an entire l-value expression.
class PropagateAccessKind
: public ExprVisitor<PropagateAccessKind, void, AccessKind> {
#ifndef NDEBUG
bool AllowOverwrite;
#endif
public:
PropagateAccessKind(bool allowOverwrite)
#ifndef NDEBUG
: AllowOverwrite(allowOverwrite)
#endif
{}
void visit(Expr *E, AccessKind kind) {
assert((AllowOverwrite || !E->hasLValueAccessKind()) &&
"l-value access kind has already been set");
assert(E->getType()->isAssignableType() &&
"setting access kind on non-l-value");
E->setLValueAccessKind(kind);
// Propagate this to sub-expressions.
ASTVisitor::visit(E, kind);
}
#define NON_LVALUE_EXPR(KIND) \
void visit##KIND##Expr(KIND##Expr *, AccessKind accessKind) { \
llvm_unreachable("not an l-value"); \
}
#define LEAF_LVALUE_EXPR(KIND) \
void visit##KIND##Expr(KIND##Expr *E, AccessKind accessKind) {}
#define COMPLETE_PHYSICAL_LVALUE_EXPR(KIND, ACCESSOR) \
void visit##KIND##Expr(KIND##Expr *E, AccessKind accessKind) { \
visit(E->ACCESSOR, accessKind); \
}
#define PARTIAL_PHYSICAL_LVALUE_EXPR(KIND, ACCESSOR) \
void visit##KIND##Expr(KIND##Expr *E, AccessKind accessKind) { \
visit(E->ACCESSOR, getPartialAccessKind(accessKind)); \
}
void visitMemberRefExpr(MemberRefExpr *E, AccessKind accessKind) {
if (!E->getBase()->getType()->isLValueType()) return;
visit(E->getBase(), getBaseAccessKind(E->getMember(), accessKind));
}
void visitSubscriptExpr(SubscriptExpr *E, AccessKind accessKind) {
if (!E->getBase()->getType()->isLValueType()) return;
visit(E->getBase(), getBaseAccessKind(E->getDecl(), accessKind));
}
static AccessKind getPartialAccessKind(AccessKind accessKind) {
return (accessKind == AccessKind::Read
? accessKind : AccessKind::ReadWrite);
}
static AccessKind getBaseAccessKind(ConcreteDeclRef member,
AccessKind accessKind) {
// We assume writes are partial writes, so the result is always
// either Read or ReadWrite.
auto memberDecl = cast<AbstractStorageDecl>(member.getDecl());
// If we're reading and the getter is mutating, or we're writing
// and the setter is mutating, this is readwrite.
if ((accessKind != AccessKind::Write &&
memberDecl->isGetterMutating()) ||
(accessKind != AccessKind::Read &&
!memberDecl->isSetterNonMutating())) {
return AccessKind::ReadWrite;
}
return AccessKind::Read;
}
void visitTupleExpr(TupleExpr *E, AccessKind accessKind) {
for (auto elt : E->getElements()) {
visit(elt, accessKind);
}
}
void visitOpenExistentialExpr(OpenExistentialExpr *E,
AccessKind accessKind) {
bool opaqueValueHadAK = E->getOpaqueValue()->hasLValueAccessKind();
AccessKind oldOpaqueValueAK =
(opaqueValueHadAK ? E->getOpaqueValue()->getLValueAccessKind()
: AccessKind::Read);
visit(E->getSubExpr(), accessKind);
// Propagate the new access kind from the OVE to the original existential
// if we just set or changed it on the OVE.
if (E->getOpaqueValue()->hasLValueAccessKind()) {
auto newOpaqueValueAK = E->getOpaqueValue()->getLValueAccessKind();
if (!opaqueValueHadAK || newOpaqueValueAK != oldOpaqueValueAK)
visit(E->getExistentialValue(), newOpaqueValueAK);
}
}
LEAF_LVALUE_EXPR(DeclRef)
LEAF_LVALUE_EXPR(DiscardAssignment)
LEAF_LVALUE_EXPR(DynamicLookup)
LEAF_LVALUE_EXPR(OpaqueValue)
COMPLETE_PHYSICAL_LVALUE_EXPR(AnyTry, getSubExpr())
PARTIAL_PHYSICAL_LVALUE_EXPR(BindOptional, getSubExpr())
COMPLETE_PHYSICAL_LVALUE_EXPR(DotSyntaxBaseIgnored, getRHS());
PARTIAL_PHYSICAL_LVALUE_EXPR(ForceValue, getSubExpr())
COMPLETE_PHYSICAL_LVALUE_EXPR(Identity, getSubExpr())
PARTIAL_PHYSICAL_LVALUE_EXPR(TupleElement, getBase())
NON_LVALUE_EXPR(Error)
NON_LVALUE_EXPR(Literal)
NON_LVALUE_EXPR(SuperRef)
NON_LVALUE_EXPR(Type)
NON_LVALUE_EXPR(OtherConstructorDeclRef)
NON_LVALUE_EXPR(Collection)
NON_LVALUE_EXPR(CaptureList)
NON_LVALUE_EXPR(AbstractClosure)
NON_LVALUE_EXPR(InOut)
NON_LVALUE_EXPR(DynamicType)
NON_LVALUE_EXPR(RebindSelfInConstructor)
NON_LVALUE_EXPR(Apply)
NON_LVALUE_EXPR(ImplicitConversion)
NON_LVALUE_EXPR(ExplicitCast)
NON_LVALUE_EXPR(OptionalEvaluation)
NON_LVALUE_EXPR(If)
NON_LVALUE_EXPR(Assign)
NON_LVALUE_EXPR(DefaultValue)
NON_LVALUE_EXPR(CodeCompletion)
#define UNCHECKED_EXPR(KIND, BASE) \
NON_LVALUE_EXPR(KIND)
#include "swift/AST/ExprNodes.def"
#undef PHYSICAL_LVALUE_EXPR
#undef LEAF_LVALUE_EXPR
#undef NON_LVALUE_EXPR
};
PropagateAccessKind(allowOverwrite).visit(this, accessKind);
}
/// Enumerate each immediate child expression of this node, invoking the
/// specific functor on it. This ignores statements and other non-expression
/// children.
void Expr::
forEachImmediateChildExpr(const std::function<Expr*(Expr*)> &callback) {
struct ChildWalker : ASTWalker {
const std::function<Expr*(Expr*)> &callback;
Expr *ThisNode;
ChildWalker(const std::function<Expr*(Expr*)> &callback, Expr *ThisNode)
: callback(callback), ThisNode(ThisNode) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
// When looking at the current node, of course we want to enter it. We
// also don't want to enumerate it.
if (E == ThisNode)
return { true, E };
// Otherwise we must be a child of our expression, enumerate it!
return { false, callback(E) };
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
return { false, S };
}
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
return { false, P };
}
bool walkToDeclPre(Decl *D) override { return false; }
bool walkToTypeReprPre(TypeRepr *T) override { return false; }
bool walkToTypeLocPre(TypeLoc &TL) override { return false; }
};
this->walk(ChildWalker(callback, this));
}
/// Enumerate each immediate child expression of this node, invoking the
/// specific functor on it. This ignores statements and other non-expression
/// children.
void Expr::forEachChildExpr(const std::function<Expr*(Expr*)> &callback) {
struct ChildWalker : ASTWalker {
const std::function<Expr*(Expr*)> &callback;
ChildWalker(const std::function<Expr*(Expr*)> &callback)
: callback(callback) {}
std::pair<bool, Expr *> walkToExprPre(Expr *E) override {
// Enumerate the node!
return { true, callback(E) };
}
std::pair<bool, Stmt *> walkToStmtPre(Stmt *S) override {
return { false, S };
}
std::pair<bool, Pattern*> walkToPatternPre(Pattern *P) override {
return { false, P };
}
bool walkToDeclPre(Decl *D) override { return false; }
bool walkToTypeReprPre(TypeRepr *T) override { return false; }
bool walkToTypeLocPre(TypeLoc &TL) override { return false; }
};
this->walk(ChildWalker(callback));
}
Initializer *Expr::findExistingInitializerContext() {
struct FindExistingInitializer : ASTWalker {
Initializer *TheInitializer = nullptr;
std::pair<bool,Expr*> walkToExprPre(Expr *E) override {
assert(!TheInitializer && "continuing to walk after finding context?");
if (auto closure = dyn_cast<AbstractClosureExpr>(E)) {
TheInitializer = cast<Initializer>(closure->getParent());
return { false, nullptr };
}
return { true, E };
}
} finder;
walk(finder);
return finder.TheInitializer;
}
bool Expr::isTypeReference() const {
// If the result isn't a metatype, there's nothing else to do.
if (!getType()->is<AnyMetatypeType>())
return false;
const Expr *expr = this;
do {
// Skip syntax.
expr = expr->getSemanticsProvidingExpr();
// Direct reference to a type.
if (auto declRef = dyn_cast<DeclRefExpr>(expr))
if (isa<TypeDecl>(declRef->getDecl()))
return true;
if (isa<TypeExpr>(expr))
return true;
// A "." expression that refers to a member.
if (auto memberRef = dyn_cast<MemberRefExpr>(expr))
return isa<TypeDecl>(memberRef->getMember().getDecl());
// When the base of a "." expression is ignored, look at the member.
if (auto ignoredDot = dyn_cast<DotSyntaxBaseIgnoredExpr>(expr)) {
expr = ignoredDot->getRHS();
continue;
}
// Anything else is not statically derived.
return false;
} while (true);
}
bool Expr::isStaticallyDerivedMetatype() const {
// The type must first be a type reference.
if (!isTypeReference())
return false;
// Archetypes are never statically derived.
return !getType()->getAs<AnyMetatypeType>()->getInstanceType()
->is<ArchetypeType>();
}
bool Expr::isSuperExpr() const {
const Expr *expr = this;
do {
expr = expr->getSemanticsProvidingExpr();
if (isa<SuperRefExpr>(expr))
return true;
if (auto derivedToBase = dyn_cast<DerivedToBaseExpr>(expr)) {
expr = derivedToBase->getSubExpr();
continue;
}
if (auto metatypeConversion = dyn_cast<MetatypeConversionExpr>(expr)) {
expr = metatypeConversion->getSubExpr();
continue;
}
return false;
} while (true);
}
bool Expr::canAppendCallParentheses() const {
switch (getKind()) {
case ExprKind::Error:
case ExprKind::CodeCompletion:
return false;
case ExprKind::NilLiteral:
case ExprKind::IntegerLiteral:
case ExprKind::FloatLiteral:
case ExprKind::BooleanLiteral:
case ExprKind::StringLiteral:
case ExprKind::InterpolatedStringLiteral:
case ExprKind::MagicIdentifierLiteral:
return true;
case ExprKind::ObjectLiteral:
return true;
case ExprKind::DiscardAssignment:
// Legal but pointless.
return true;
case ExprKind::DeclRef:
return !cast<DeclRefExpr>(this)->getDecl()->getName().isOperator();
case ExprKind::SuperRef:
case ExprKind::Type:
case ExprKind::OtherConstructorDeclRef:
case ExprKind::UnresolvedConstructor:
case ExprKind::DotSyntaxBaseIgnored:
return true;
case ExprKind::OverloadedDeclRef: {
auto *overloadedExpr = cast<OverloadedDeclRefExpr>(this);
if (overloadedExpr->getDecls().empty())
return false;
return !overloadedExpr->getDecls().front()->getName().isOperator();
}
case ExprKind::OverloadedMemberRef:
return true;
case ExprKind::UnresolvedDeclRef:
return cast<UnresolvedDeclRefExpr>(this)->getName().isOperator();
case ExprKind::MemberRef:
case ExprKind::DynamicMemberRef:
case ExprKind::DynamicSubscript:
case ExprKind::UnresolvedSpecialize:
case ExprKind::UnresolvedMember:
case ExprKind::UnresolvedDot:
case ExprKind::UnresolvedSelector:
return true;
case ExprKind::Sequence:
return false;
case ExprKind::Paren:
case ExprKind::DotSelf:
case ExprKind::Tuple:
case ExprKind::Array:
case ExprKind::Dictionary:
case ExprKind::Subscript:
case ExprKind::TupleElement:
return true;
case ExprKind::CaptureList:
case ExprKind::Closure:
case ExprKind::AutoClosure:
return false;
case ExprKind::DynamicType:
return true;
case ExprKind::Try:
case ExprKind::ForceTry:
case ExprKind::OptionalTry:
case ExprKind::InOut:
return false;
case ExprKind::RebindSelfInConstructor:
case ExprKind::OpaqueValue:
case ExprKind::BindOptional:
case ExprKind::OptionalEvaluation:
return false;
case ExprKind::ForceValue:
return true;
case ExprKind::OpenExistential:
return false;
case ExprKind::Call:
case ExprKind::PostfixUnary:
case ExprKind::DotSyntaxCall:
case ExprKind::ConstructorRefCall:
return true;
case ExprKind::PrefixUnary:
case ExprKind::Binary:
return false;
case ExprKind::Load:
case ExprKind::TupleShuffle:
case ExprKind::UnresolvedTypeConversion:
case ExprKind::FunctionConversion:
case ExprKind::CovariantFunctionConversion:
case ExprKind::CovariantReturnConversion:
case ExprKind::MetatypeConversion:
case ExprKind::CollectionUpcastConversion:
case ExprKind::Erasure:
case ExprKind::DerivedToBase:
case ExprKind::ArchetypeToSuper:
case ExprKind::InjectIntoOptional:
case ExprKind::ClassMetatypeToObject:
case ExprKind::ExistentialMetatypeToObject:
case ExprKind::ProtocolMetatypeToObject:
case ExprKind::InOutToPointer:
case ExprKind::ArrayToPointer:
case ExprKind::StringToPointer:
case ExprKind::PointerToPointer:
case ExprKind::LValueToPointer:
case ExprKind::ForeignObjectConversion:
return false;
case ExprKind::ForcedCheckedCast:
case ExprKind::ConditionalCheckedCast:
case ExprKind::Is:
case ExprKind::Coerce:
return false;
case ExprKind::If:
case ExprKind::Assign:
case ExprKind::DefaultValue:
case ExprKind::UnresolvedPattern:
case ExprKind::EditorPlaceholder:
return false;
}
}
llvm::DenseMap<Expr *, Expr *> Expr::getParentMap() {
class RecordingTraversal : public ASTWalker {
public:
llvm::DenseMap<Expr *, Expr *> &ParentMap;
explicit RecordingTraversal(llvm::DenseMap<Expr *, Expr *> &parentMap)
: ParentMap(parentMap) { }
virtual std::pair<bool, Expr *> walkToExprPre(Expr *E) {
if (auto parent = Parent.getAsExpr())
ParentMap[E] = parent;
return { true, E };
}
};
llvm::DenseMap<Expr *, Expr *> parentMap;
RecordingTraversal traversal(parentMap);
walk(traversal);
return parentMap;
}
llvm::DenseMap<Expr *, unsigned> Expr::getDepthMap() {
class RecordingTraversal : public ASTWalker {
public:
llvm::DenseMap<Expr *, unsigned> &DepthMap;
unsigned Depth = 0;
explicit RecordingTraversal(llvm::DenseMap<Expr *, unsigned> &depthMap)
: DepthMap(depthMap) { }
virtual std::pair<bool, Expr *> walkToExprPre(Expr *E) {
DepthMap[E] = Depth;
Depth++;
return { true, E };
}
virtual Expr *walkToExprPost(Expr *E) {
Depth--;
return E;
}
};
llvm::DenseMap<Expr *, unsigned> depthMap;
RecordingTraversal traversal(depthMap);
walk(traversal);
return depthMap;
}
llvm::DenseMap<Expr *, unsigned> Expr::getPreorderIndexMap() {
class RecordingTraversal : public ASTWalker {
public:
llvm::DenseMap<Expr *, unsigned> &IndexMap;
unsigned Index = 0;
explicit RecordingTraversal(llvm::DenseMap<Expr *, unsigned> &indexMap)
: IndexMap(indexMap) { }
virtual std::pair<bool, Expr *> walkToExprPre(Expr *E) {
IndexMap[E] = Index;
Index++;
return { true, E };
}
};
llvm::DenseMap<Expr *, unsigned> indexMap;
RecordingTraversal traversal(indexMap);
walk(traversal);
return indexMap;
}
//===----------------------------------------------------------------------===//
// Support methods for Exprs.
//===----------------------------------------------------------------------===//
static LiteralExpr *shallowCloneImpl(const NilLiteralExpr *E, ASTContext &Ctx) {
return new (Ctx) NilLiteralExpr(E->getLoc());
}
static LiteralExpr *
shallowCloneImpl(const IntegerLiteralExpr *E, ASTContext &Ctx) {
auto res = new (Ctx) IntegerLiteralExpr(E->getDigitsText(),
E->getSourceRange().End);
if (E->isNegative())
res->setNegative(E->getSourceRange().Start);
return res;
}
static LiteralExpr *shallowCloneImpl(const FloatLiteralExpr *E, ASTContext &Ctx) {
auto res = new (Ctx) FloatLiteralExpr(E->getDigitsText(),
E->getSourceRange().End);
if (E->isNegative())
res->setNegative(E->getSourceRange().Start);
return res;
}
static LiteralExpr *
shallowCloneImpl(const BooleanLiteralExpr *E, ASTContext &Ctx) {
return new (Ctx) BooleanLiteralExpr(E->getValue(), E->getLoc());
}
static LiteralExpr *shallowCloneImpl(const StringLiteralExpr *E, ASTContext &Ctx) {
auto res = new (Ctx) StringLiteralExpr(E->getValue(), E->getSourceRange());
res->setEncoding(E->getEncoding());
return res;
}
static LiteralExpr *
shallowCloneImpl(const InterpolatedStringLiteralExpr *E, ASTContext &Ctx) {
auto res = new (Ctx) InterpolatedStringLiteralExpr(E->getLoc(),
const_cast<InterpolatedStringLiteralExpr*>(E)->getSegments());
res->setSemanticExpr(E->getSemanticExpr());
return res;
}
static LiteralExpr *
shallowCloneImpl(const MagicIdentifierLiteralExpr *E, ASTContext &Ctx) {
auto res = new (Ctx) MagicIdentifierLiteralExpr(E->getKind(),
E->getSourceRange().End);
if (res->isString())
res->setStringEncoding(E->getStringEncoding());
return res;
}
static LiteralExpr *
shallowCloneImpl(const ObjectLiteralExpr *E, ASTContext &Ctx) {
auto res = new (Ctx) ObjectLiteralExpr(E->getStartLoc(), E->getName(),
E->getNameLoc(), E->getArg(),
E->getEndLoc());
res->setSemanticExpr(E->getSemanticExpr());
return res;
}
// Make an exact copy of this AST node.
LiteralExpr *LiteralExpr::shallowClone(ASTContext &Ctx) const {
LiteralExpr *Result = nullptr;
switch (getKind()) {
default: llvm_unreachable("Unknown literal type!");
#define DISPATCH_CLONE(KIND) \
case ExprKind::KIND: \
Result = shallowCloneImpl(cast<KIND##Expr>(this), Ctx); \
break;
DISPATCH_CLONE(NilLiteral)
DISPATCH_CLONE(IntegerLiteral)
DISPATCH_CLONE(FloatLiteral)
DISPATCH_CLONE(BooleanLiteral)
DISPATCH_CLONE(StringLiteral)
DISPATCH_CLONE(InterpolatedStringLiteral)
DISPATCH_CLONE(ObjectLiteral)
DISPATCH_CLONE(MagicIdentifierLiteral)
#undef DISPATCH_CLONE
}
Result->setType(getType());
Result->setImplicit(isImplicit());
return Result;
}
static APInt getIntegerLiteralValue(bool IsNegative, StringRef Text,
unsigned BitWidth) {
llvm::APInt Value(BitWidth, 0);
// swift encodes octal differently from C
bool IsCOctal = Text.size() > 1 && Text[0] == '0' && isdigit(Text[1]);
bool Error = Text.getAsInteger(IsCOctal ? 10 : 0, Value);
assert(!Error && "Invalid IntegerLiteral formed"); (void)Error;
if (IsNegative)
Value = -Value;
if (Value.getBitWidth() != BitWidth)
Value = Value.sextOrTrunc(BitWidth);
return Value;
}
APInt IntegerLiteralExpr::getValue(StringRef Text, unsigned BitWidth) {
return getIntegerLiteralValue(/*IsNegative=*/false, Text, BitWidth);
}
APInt IntegerLiteralExpr::getValue() const {
assert(!getType().isNull() && "Semantic analysis has not completed");
assert(!getType()->is<ErrorType>() && "Should have a valid type");
return getIntegerLiteralValue(
isNegative(), getDigitsText(),
getType()->castTo<BuiltinIntegerType>()->getGreatestWidth());
}
static APFloat getFloatLiteralValue(bool IsNegative, StringRef Text,
const llvm::fltSemantics &Semantics) {
APFloat Val(Semantics);
APFloat::opStatus Res =
Val.convertFromString(Text, llvm::APFloat::rmNearestTiesToEven);
assert(Res != APFloat::opInvalidOp && "Sema didn't reject invalid number");
(void)Res;
if (IsNegative) {
auto NegVal = APFloat::getZero(Semantics, /*negative*/ true);
Res = NegVal.subtract(Val, llvm::APFloat::rmNearestTiesToEven);
assert(Res != APFloat::opInvalidOp && "Sema didn't reject invalid number");
(void)Res;
return NegVal;
}
return Val;
}
APFloat FloatLiteralExpr::getValue(StringRef Text,
const llvm::fltSemantics &Semantics) {
return getFloatLiteralValue(/*IsNegative*/false, Text, Semantics);
}
llvm::APFloat FloatLiteralExpr::getValue() const {
assert(!getType().isNull() && "Semantic analysis has not completed");
assert(!getType()->is<ErrorType>() && "Should have a valid type");
return getFloatLiteralValue(isNegative(), getDigitsText(),
getType()->castTo<BuiltinFloatType>()->getAPFloatSemantics());
}
StringLiteralExpr::StringLiteralExpr(StringRef Val, SourceRange Range,
bool Implicit)
: LiteralExpr(ExprKind::StringLiteral, Implicit), Val(Val),
Range(Range) {
StringLiteralExprBits.Encoding = static_cast<unsigned>(UTF8);
StringLiteralExprBits.IsSingleUnicodeScalar =
unicode::isSingleUnicodeScalar(Val);
StringLiteralExprBits.IsSingleExtendedGraphemeCluster =
unicode::isSingleExtendedGraphemeCluster(Val);
}
void DeclRefExpr::setDeclRef(ConcreteDeclRef ref) {
if (auto spec = getSpecInfo())
spec->D = ref;
else
DOrSpecialized = ref;
}
void DeclRefExpr::setSpecialized() {
if (isSpecialized())
return;
ConcreteDeclRef ref = getDeclRef();
void *Mem = ref.getDecl()->getASTContext().Allocate(sizeof(SpecializeInfo),
alignof(SpecializeInfo));
auto Spec = new (Mem) SpecializeInfo;
Spec->D = ref;
DOrSpecialized = Spec;
}
void DeclRefExpr::setGenericArgs(ArrayRef<TypeRepr*> GenericArgs) {
ValueDecl *D = getDecl();
assert(D);
setSpecialized();
getSpecInfo()->GenericArgs = D->getASTContext().AllocateCopy(GenericArgs);
}
ConstructorDecl *OtherConstructorDeclRefExpr::getDecl() const {
return cast_or_null<ConstructorDecl>(Ctor.getDecl());
}
MemberRefExpr::MemberRefExpr(Expr *base, SourceLoc dotLoc,
ConcreteDeclRef member, SourceRange nameRange,
bool Implicit, AccessSemantics semantics)
: Expr(ExprKind::MemberRef, Implicit), Base(base),
Member(member), DotLoc(dotLoc), NameRange(nameRange) {
MemberRefExprBits.Semantics = (unsigned) semantics;
MemberRefExprBits.IsSuper = false;
}
Type OverloadSetRefExpr::getBaseType() const {
if (isa<OverloadedDeclRefExpr>(this))
return Type();
if (auto *DRE = dyn_cast<OverloadedMemberRefExpr>(this)) {
return DRE->getBase()->getType()->getRValueType();
}
llvm_unreachable("Unhandled overloaded set reference expression");
}
bool OverloadSetRefExpr::hasBaseObject() const {
if (Type BaseTy = getBaseType())
return !BaseTy->is<AnyMetatypeType>();
return false;
}
SequenceExpr *SequenceExpr::create(ASTContext &ctx, ArrayRef<Expr*> elements) {
void *Buffer = ctx.Allocate(sizeof(SequenceExpr) +
elements.size() * sizeof(Expr*),
alignof(SequenceExpr));
return ::new(Buffer) SequenceExpr(elements);
}
SourceLoc TupleExpr::getStartLoc() const {
if (LParenLoc.isValid()) return LParenLoc;
if (getNumElements() == 0) return SourceLoc();
return getElement(0)->getStartLoc();
}
SourceLoc TupleExpr::getEndLoc() const {
if (hasTrailingClosure() || RParenLoc.isInvalid()) {
if (getNumElements() == 0) return SourceLoc();
return getElements().back()->getEndLoc();
}
return RParenLoc;
}
TupleExpr::TupleExpr(SourceLoc LParenLoc, ArrayRef<Expr *> SubExprs,
ArrayRef<Identifier> ElementNames,
ArrayRef<SourceLoc> ElementNameLocs,
SourceLoc RParenLoc, bool HasTrailingClosure,
bool Implicit, Type Ty)
: Expr(ExprKind::Tuple, Implicit, Ty),
LParenLoc(LParenLoc), RParenLoc(RParenLoc),
NumElements(SubExprs.size())
{
TupleExprBits.HasTrailingClosure = HasTrailingClosure;
TupleExprBits.HasElementNames = !ElementNames.empty();
TupleExprBits.HasElementNameLocations = !ElementNameLocs.empty();
assert(LParenLoc.isValid() == RParenLoc.isValid() &&
"Mismatched parenthesis location information validity");
assert(ElementNames.empty() || ElementNames.size() == SubExprs.size());
assert(ElementNameLocs.empty() ||
ElementNames.size() == ElementNameLocs.size());
// Copy elements.
memcpy(getElements().data(), SubExprs.data(),
SubExprs.size() * sizeof(Expr *));
// Copy element names, if provided.
if (hasElementNames()) {
memcpy(getElementNamesBuffer().data(), ElementNames.data(),
ElementNames.size() * sizeof(Identifier));
}
// Copy element name locations, if provided.
if (hasElementNameLocs()) {
memcpy(getElementNameLocsBuffer().data(), ElementNameLocs.data(),
ElementNameLocs.size() * sizeof(SourceLoc));
}
}
TupleExpr *TupleExpr::create(ASTContext &ctx,
SourceLoc LParenLoc,
ArrayRef<Expr *> SubExprs,
ArrayRef<Identifier> ElementNames,
ArrayRef<SourceLoc> ElementNameLocs,
SourceLoc RParenLoc, bool HasTrailingClosure,
bool Implicit, Type Ty) {
unsigned size = sizeof(TupleExpr);
size += SubExprs.size() * sizeof(Expr*);
size += ElementNames.size() * sizeof(Identifier);
size += ElementNameLocs.size() * sizeof(SourceLoc);
void *mem = ctx.Allocate(size, alignof(TupleExpr));
return new (mem) TupleExpr(LParenLoc, SubExprs, ElementNames, ElementNameLocs,
RParenLoc, HasTrailingClosure, Implicit, Ty);
}
TupleExpr *TupleExpr::createEmpty(ASTContext &ctx, SourceLoc LParenLoc,
SourceLoc RParenLoc, bool Implicit) {
return create(ctx, LParenLoc, { }, { }, { }, RParenLoc,
/*HasTrailingClosure=*/false, Implicit,
TupleType::getEmpty(ctx));
}
TupleExpr *TupleExpr::createImplicit(ASTContext &ctx, ArrayRef<Expr *> SubExprs,
ArrayRef<Identifier> ElementNames) {
return create(ctx, SourceLoc(), SubExprs, ElementNames, { }, SourceLoc(),
/*HasTrailingClosure=*/false, /*Implicit=*/true, Type());
}
ArrayExpr *ArrayExpr::create(ASTContext &C, SourceLoc LBracketLoc,
ArrayRef<Expr*> Elements,
ArrayRef<SourceLoc> CommaLocs,
SourceLoc RBracketLoc, Type Ty) {
// Copy the element list into the ASTContext.
auto NewElements = C.AllocateCopy(Elements);
auto NewCommas = C.AllocateCopy(CommaLocs);
return new (C) ArrayExpr(LBracketLoc, NewElements, NewCommas, RBracketLoc,Ty);
}
DictionaryExpr *DictionaryExpr::create(ASTContext &C, SourceLoc LBracketLoc,
ArrayRef<Expr*> Elements, SourceLoc RBracketLoc,
Type Ty) {