forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathExpr.h
6638 lines (5450 loc) · 221 KB
/
Expr.h
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.h - Swift Language Expression ASTs ----------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines the Expr class and subclasses.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_AST_EXPR_H
#define SWIFT_AST_EXPR_H
#include "swift/AST/ArgumentList.h"
#include "swift/AST/Attr.h"
#include "swift/AST/AvailabilityRange.h"
#include "swift/AST/CaptureInfo.h"
#include "swift/AST/ConcreteDeclRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DeclContext.h"
#include "swift/AST/DeclNameLoc.h"
#include "swift/AST/FreestandingMacroExpansion.h"
#include "swift/AST/FunctionRefInfo.h"
#include "swift/AST/ProtocolConformanceRef.h"
#include "swift/AST/ThrownErrorDestination.h"
#include "swift/AST/TypeAlignments.h"
#include "swift/Basic/Debug.h"
#include "swift/Basic/InlineBitfield.h"
#include "llvm/Support/TrailingObjects.h"
#include <optional>
#include <utility>
namespace llvm {
struct fltSemantics;
}
namespace swift {
enum class AccessKind : unsigned char;
class ArchetypeType;
class ASTContext;
class AvailabilitySpec;
class DeclRefTypeRepr;
class Type;
class TypeRepr;
class ValueDecl;
class Decl;
class DeclRefExpr;
class ExistentialArchetypeType;
class ParamDecl;
class Pattern;
class SubscriptDecl;
class Stmt;
class BraceStmt;
class ASTWalker;
class Initializer;
class VarDecl;
class OpaqueValueExpr;
class FuncDecl;
class ConstructorDecl;
class TypeDecl;
class PatternBindingDecl;
class ParameterList;
class EnumElementDecl;
class CallExpr;
class KeyPathExpr;
class CaptureListExpr;
class ThenStmt;
class ReturnStmt;
enum class ExprKind : uint8_t {
#define EXPR(Id, Parent) Id,
#define LAST_EXPR(Id) Last_Expr = Id,
#define EXPR_RANGE(Id, FirstId, LastId) \
First_##Id##Expr = FirstId, Last_##Id##Expr = LastId,
#include "swift/AST/ExprNodes.def"
};
enum : unsigned { NumExprKindBits =
countBitsUsed(static_cast<unsigned>(ExprKind::Last_Expr)) };
/// Discriminates certain kinds of checked cast that have specialized diagnostic
/// and/or code generation peephole behavior.
///
/// This enumeration should not have any semantic effect on the behavior of a
/// well-typed program, since the runtime can perform all casts that are
/// statically accepted.
enum class CheckedCastKind : unsigned {
/// The kind has not been determined yet.
Unresolved,
/// Valid resolved kinds start here.
First_Resolved,
/// The requested cast is an implicit conversion, so this is a coercion.
Coercion = First_Resolved,
/// A checked cast with no known specific behavior.
ValueCast,
// A downcast from an array type to another array type.
ArrayDowncast,
// A downcast from a dictionary type to another dictionary type.
DictionaryDowncast,
// A downcast from a set type to another set type.
SetDowncast,
/// A bridging conversion that always succeeds.
BridgingCoercion,
Last_CheckedCastKind = BridgingCoercion,
};
/// What are the high-level semantics of this access?
enum class AccessSemantics : uint8_t {
/// On a storage reference, this is a direct access to the underlying
/// physical storage, bypassing any observers. The declaration must be
/// a variable with storage.
///
/// On a function reference, this is a non-polymorphic access to a
/// particular implementation.
DirectToStorage,
/// On a storage reference, this is a direct access to the concrete
/// implementation of this storage, bypassing any possibility of override.
DirectToImplementation,
/// This is an ordinary access to a declaration, using whatever
/// polymorphism is expected.
Ordinary,
/// This is an access to the underlying storage through a distributed thunk.
///
/// The declaration must be a 'distributed' computed property used outside
/// of its actor isolation context.
DistributedThunk,
};
/// Expr - Base class for all expressions in swift.
class alignas(8) Expr : public ASTAllocated<Expr> {
Expr(const Expr&) = delete;
void operator=(const Expr&) = delete;
protected:
// clang-format off
union { uint64_t OpaqueBits;
SWIFT_INLINE_BITFIELD_BASE(Expr, bitmax(NumExprKindBits,8)+1,
/// The subclass of Expr that this is.
Kind : bitmax(NumExprKindBits,8),
/// Whether the Expr represents something directly written in source or
/// it was implicitly generated by the type-checker.
Implicit : 1
);
SWIFT_INLINE_BITFIELD_FULL(CollectionExpr, Expr, 64-NumExprBits,
/// True if the type of this collection expr was inferred by the collection
/// fallback type, like [Any].
IsTypeDefaulted : 1,
/// Number of comma source locations.
NumCommas : 32 - 1 - NumExprBits,
/// Number of entries in the collection. If this is a DictionaryExpr,
/// each entry is a Tuple with the key and value pair.
NumSubExprs : 32
);
SWIFT_INLINE_BITFIELD_EMPTY(LiteralExpr, Expr);
SWIFT_INLINE_BITFIELD_EMPTY(IdentityExpr, Expr);
SWIFT_INLINE_BITFIELD(LookupExpr, Expr, 1+1+1,
IsSuper : 1,
IsImplicitlyAsync : 1,
IsImplicitlyThrows : 1
);
SWIFT_INLINE_BITFIELD_EMPTY(DynamicLookupExpr, LookupExpr);
SWIFT_INLINE_BITFIELD_EMPTY(ParenExpr, IdentityExpr);
SWIFT_INLINE_BITFIELD(NumberLiteralExpr, LiteralExpr, 1+1,
IsNegative : 1,
IsExplicitConversion : 1
);
SWIFT_INLINE_BITFIELD(StringLiteralExpr, LiteralExpr, 3+1+1,
Encoding : 3,
IsSingleUnicodeScalar : 1,
IsSingleExtendedGraphemeCluster : 1
);
SWIFT_INLINE_BITFIELD_FULL(InterpolatedStringLiteralExpr, LiteralExpr, 32+20,
: NumPadBits,
InterpolationCount : 20,
LiteralCapacity : 32
);
SWIFT_INLINE_BITFIELD(DeclRefExpr, Expr, 2+3+1+1,
Semantics : 2, // an AccessSemantics
FunctionRefInfo : 3,
IsImplicitlyAsync : 1,
IsImplicitlyThrows : 1
);
SWIFT_INLINE_BITFIELD(UnresolvedDeclRefExpr, Expr, 2+3,
DeclRefKind : 2,
FunctionRefInfo : 3
);
SWIFT_INLINE_BITFIELD(MemberRefExpr, LookupExpr, 2,
Semantics : 2 // an AccessSemantics
);
SWIFT_INLINE_BITFIELD_FULL(TupleElementExpr, Expr, 32,
: NumPadBits,
FieldNo : 32
);
SWIFT_INLINE_BITFIELD_FULL(TupleExpr, Expr, 1+1+32,
/// Whether this tuple has any labels.
HasElementNames : 1,
/// Whether this tuple has label locations.
HasElementNameLocations : 1,
: NumPadBits,
NumElements : 32
);
SWIFT_INLINE_BITFIELD(UnresolvedDotExpr, Expr, 3,
FunctionRefInfo : 3
);
SWIFT_INLINE_BITFIELD_FULL(SubscriptExpr, LookupExpr, 2,
Semantics : 2 // an AccessSemantics
);
SWIFT_INLINE_BITFIELD_EMPTY(DynamicSubscriptExpr, DynamicLookupExpr);
SWIFT_INLINE_BITFIELD_FULL(UnresolvedMemberExpr, Expr, 3,
FunctionRefInfo : 3
);
SWIFT_INLINE_BITFIELD(OverloadSetRefExpr, Expr, 3,
FunctionRefInfo : 3
);
SWIFT_INLINE_BITFIELD(BooleanLiteralExpr, LiteralExpr, 1,
Value : 1
);
SWIFT_INLINE_BITFIELD(MagicIdentifierLiteralExpr, LiteralExpr, 3+1,
Kind : 3,
StringEncoding : 1
);
SWIFT_INLINE_BITFIELD_FULL(ObjectLiteralExpr, LiteralExpr, 3,
LitKind : 3
);
SWIFT_INLINE_BITFIELD(AbstractClosureExpr, Expr, (16-NumExprBits)+16,
: 16 - NumExprBits, // Align and leave room for subclasses
Discriminator : 16
);
SWIFT_INLINE_BITFIELD(AutoClosureExpr, AbstractClosureExpr, 2,
/// If the autoclosure was built for a curry thunk, the thunk kind is
/// stored here.
Kind : 2
);
SWIFT_INLINE_BITFIELD(ClosureExpr, AbstractClosureExpr, 1+1+1+1+1+1+1,
/// True if closure parameters were synthesized from anonymous closure
/// variables.
HasAnonymousClosureVars : 1,
/// True if "self" can be captured implicitly without requiring "self."
/// on each member reference.
ImplicitSelfCapture : 1,
/// True if this @Sendable async closure parameter should implicitly
/// inherit the actor context from where it was formed.
InheritActorContext : 1,
/// True if this closure's actor isolation behavior was determined by an
/// \c \@preconcurrency declaration.
IsolatedByPreconcurrency : 1,
/// True if this is a closure literal that is passed to a sending parameter.
IsPassedToSendingParameter : 1,
/// True if we're in the common case where the GlobalActorAttributeRequest
/// request returned a pair of null pointers.
NoGlobalActorAttribute : 1,
/// Indicates whether this closure literal would require dynamic actor
/// isolation checks when it either specifies or inherits isolation
/// and was passed as an argument to a function that is not fully
/// concurrency checked.
RequiresDynamicIsolationChecking : 1
);
SWIFT_INLINE_BITFIELD_FULL(BindOptionalExpr, Expr, 16,
: NumPadBits,
Depth : 16
);
SWIFT_INLINE_BITFIELD_EMPTY(ImplicitConversionExpr, Expr);
SWIFT_INLINE_BITFIELD_FULL(DestructureTupleExpr, ImplicitConversionExpr, 16,
/// The number of elements in the tuple type being destructured.
NumElements : 16
);
SWIFT_INLINE_BITFIELD(ForceValueExpr, Expr, 1,
ForcedIUO : 1
);
SWIFT_INLINE_BITFIELD(InOutToPointerExpr, ImplicitConversionExpr, 1,
IsNonAccessing : 1
);
SWIFT_INLINE_BITFIELD(ArrayToPointerExpr, ImplicitConversionExpr, 1,
IsNonAccessing : 1
);
SWIFT_INLINE_BITFIELD_FULL(ErasureExpr, ImplicitConversionExpr, 32+20,
: NumPadBits,
NumConformances : 32,
NumArgumentConversions : 20
);
SWIFT_INLINE_BITFIELD_FULL(UnresolvedSpecializeExpr, Expr, 32,
: NumPadBits,
NumUnresolvedParams : 32
);
SWIFT_INLINE_BITFIELD_FULL(CaptureListExpr, Expr, 32,
: NumPadBits,
NumCaptures : 32
);
SWIFT_INLINE_BITFIELD(ApplyExpr, Expr, 1+1+1+1+1,
ThrowsIsSet : 1,
ImplicitlyAsync : 1,
ImplicitlyThrows : 1,
NoAsync : 1,
ShouldApplyDistributedThunk : 1
);
SWIFT_INLINE_BITFIELD_EMPTY(CallExpr, ApplyExpr);
enum { NumCheckedCastKindBits = 4 };
SWIFT_INLINE_BITFIELD(CheckedCastExpr, Expr, NumCheckedCastKindBits,
CastKind : NumCheckedCastKindBits
);
static_assert(unsigned(CheckedCastKind::Last_CheckedCastKind)
< (1 << NumCheckedCastKindBits),
"unable to fit a CheckedCastKind in the given number of bits");
SWIFT_INLINE_BITFIELD_EMPTY(CollectionUpcastConversionExpr, Expr);
SWIFT_INLINE_BITFIELD(ObjCSelectorExpr, Expr, 2,
/// The selector kind.
SelectorKind : 2
);
SWIFT_INLINE_BITFIELD(KeyPathExpr, Expr, 1,
/// Whether this is an ObjC stringified keypath.
IsObjC : 1
);
SWIFT_INLINE_BITFIELD_FULL(SequenceExpr, Expr, 32+1,
: NumPadBits,
NumElements : 32,
IsFolded: 1
);
SWIFT_INLINE_BITFIELD(OpaqueValueExpr, Expr, 1,
IsPlaceholder : 1
);
SWIFT_INLINE_BITFIELD_FULL(TypeJoinExpr, Expr, 32,
: NumPadBits,
NumElements : 32
);
} Bits;
// clang-format on
private:
/// Ty - This is the type of the expression.
Type Ty;
protected:
Expr(ExprKind Kind, bool Implicit, Type Ty = Type()) : Ty(Ty) {
Bits.OpaqueBits = 0;
Bits.Expr.Kind = unsigned(Kind);
Bits.Expr.Implicit = Implicit;
}
public:
/// Return the kind of this expression.
ExprKind getKind() const { return ExprKind(Bits.Expr.Kind); }
/// Retrieve the name of the given expression kind.
///
/// This name should only be used for debugging dumps and other
/// developer aids, and should never be part of a diagnostic or exposed
/// to the user of the compiler in any way.
static StringRef getKindName(ExprKind K);
/// getType - Return the type of this expression.
Type getType() const { return Ty; }
/// setType - Sets the type of this expression.
void setType(Type T);
/// Return the source range of the expression.
SourceRange getSourceRange() const;
/// getStartLoc - Return the location of the start of the expression.
SourceLoc getStartLoc() const;
/// Retrieve the location of the last token of the expression.
SourceLoc getEndLoc() const;
/// getLoc - Return the caret location of this expression.
SourceLoc getLoc() const;
#define SWIFT_FORWARD_SOURCE_LOCS_TO(SUBEXPR) \
SourceLoc getStartLoc() const { return (SUBEXPR)->getStartLoc(); } \
SourceLoc getEndLoc() const { return (SUBEXPR)->getEndLoc(); } \
SourceLoc getLoc() const { return (SUBEXPR)->getLoc(); } \
SourceRange getSourceRange() const { return (SUBEXPR)->getSourceRange(); }
SourceLoc TrailingSemiLoc;
/// getSemanticsProvidingExpr - Find the smallest subexpression
/// which obeys the property that evaluating it is exactly
/// equivalent to evaluating this expression.
///
/// Looks through parentheses. Would not look through something
/// like '(foo(), x:bar(), baz()).x'.
Expr *getSemanticsProvidingExpr();
const Expr *getSemanticsProvidingExpr() const {
return const_cast<Expr *>(this)->getSemanticsProvidingExpr();
}
/// getValueProvidingExpr - Find the smallest subexpression which is
/// responsible for generating the value of this expression.
/// Evaluating the result is not necessarily equivalent to
/// evaluating this expression because of potential missing
/// side-effects (which may influence the returned value).
Expr *getValueProvidingExpr();
const Expr *getValueProvidingExpr() const {
return const_cast<Expr *>(this)->getValueProvidingExpr();
}
/// Find the original expression value, looking through various
/// implicit conversions.
const Expr *findOriginalValue() const;
/// Find the original type of a value, looking through various implicit
/// conversions.
Type findOriginalType() const;
/// If this is a reference to an operator written as a member of a type (or
/// extension thereof), return the underlying operator reference.
DeclRefExpr *getMemberOperatorRef();
/// This recursively walks the AST rooted at this expression.
Expr *walk(ASTWalker &walker);
Expr *walk(ASTWalker &&walker) { return walk(walker); }
/// Enumerate each immediate child expression of this node, invoking the
/// specific functor on it. This ignores statements and other non-expression
/// children.
void forEachImmediateChildExpr(llvm::function_ref<Expr *(Expr *)> callback);
/// Enumerate each expr node within this expression subtree, invoking the
/// specific functor on it. This ignores statements and other non-expression
/// children, and if there is a closure within the expression, this does not
/// walk into the body of it (unless it is single-expression).
void forEachChildExpr(llvm::function_ref<Expr *(Expr *)> callback);
/// Determine whether this expression refers to a type by name.
///
/// This distinguishes static references to types, like Int, from metatype
/// values, "someTy: Any.Type".
bool isTypeReference(
llvm::function_ref<Type(Expr *)> getType = [](Expr *E) -> Type {
return E->getType();
},
llvm::function_ref<Decl *(Expr *)> getDecl = [](Expr *E) -> Decl * {
return nullptr;
}) const;
/// Determine whether this expression refers to a statically-derived metatype.
///
/// This implies `isTypeReference`, but also requires that the referenced type
/// is not an archetype or dependent type.
bool isStaticallyDerivedMetatype(
llvm::function_ref<Type(Expr *)> getType = [](Expr *E) -> Type {
return E->getType();
},
llvm::function_ref<bool(Expr *)> isTypeReference =
[](Expr *E) { return E->isTypeReference(); }) const;
/// isImplicit - Determines whether this expression was implicitly-generated,
/// rather than explicitly written in the AST.
bool isImplicit() const {
return Bits.Expr.Implicit;
}
void setImplicit(bool Implicit = true);
/// Retrieves the declaration that is being referenced by this
/// expression, if any.
ConcreteDeclRef getReferencedDecl(bool stopAtParenExpr = false) const;
/// Determine whether this expression is 'super', possibly converted to
/// a base class.
bool isSuperExpr() const;
/// Returns whether the semantically meaningful content of this expression is
/// an inout expression.
///
/// FIXME(Remove InOutType): This should eventually sub-in for
/// 'E->getType()->is<InOutType>()' in all cases.
bool isSemanticallyInOutExpr() const {
return getSemanticsProvidingExpr()->getKind() == ExprKind::InOut;
}
bool printConstExprValue(llvm::raw_ostream *OS, llvm::function_ref<bool(Expr*)> additionalCheck) const;
bool isSemanticallyConstExpr(llvm::function_ref<bool(Expr*)> additionalCheck = nullptr) const;
/// Returns false if this expression needs to be wrapped in parens when
/// used inside of a any postfix expression, true otherwise.
///
/// \param appendingPostfixOperator if the expression being
/// appended is a postfix operator like '!' or '?'.
bool canAppendPostfixExpression(bool appendingPostfixOperator = false) const;
/// Returns true if this is an infix operator of some sort, including
/// a builtin operator.
bool isInfixOperator() const;
/// Returns true if this is a reference to the implicit self of function.
bool isSelfExprOf(const AbstractFunctionDecl *AFD,
bool sameBase = false) const;
/// If the expression has an argument list, returns it. Otherwise, returns
/// \c nullptr.
ArgumentList *getArgs() const;
/// If the expression has a DeclNameLoc, returns it. Otherwise, returns
/// an nullp DeclNameLoc.
DeclNameLoc getNameLoc() const;
/// Produce a mapping from each subexpression to its parent
/// expression, with the provided expression serving as the root of
/// the parent map.
llvm::DenseMap<Expr *, Expr *> getParentMap();
/// Whether this expression is a valid parent for a given TypeExpr.
bool isValidParentOfTypeExpr(Expr *typeExpr) const;
SWIFT_DEBUG_DUMP;
void dump(raw_ostream &OS, unsigned Indent = 0) const;
void dump(raw_ostream &OS, llvm::function_ref<Type(Expr *)> getType,
llvm::function_ref<Type(TypeRepr *)> getTypeOfTypeRepr,
llvm::function_ref<Type(KeyPathExpr *E, unsigned index)>
getTypeOfKeyPathComponent,
unsigned Indent = 0) const;
void print(ASTPrinter &Printer, const PrintOptions &Opts) const;
};
/// ErrorExpr - Represents a semantically erroneous subexpression in the AST,
/// typically this will have an ErrorType.
class ErrorExpr : public Expr {
SourceRange Range;
Expr *OriginalExpr;
public:
ErrorExpr(SourceRange Range, Type Ty = Type(), Expr *OriginalExpr = nullptr)
: Expr(ExprKind::Error, /*Implicit=*/true, Ty), Range(Range),
OriginalExpr(OriginalExpr) {}
SourceRange getSourceRange() const { return Range; }
Expr *getOriginalExpr() const { return OriginalExpr; }
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::Error;
}
};
/// CodeCompletionExpr - Represents the code completion token in the AST, this
/// can help us preserve the context of the code completion position.
class CodeCompletionExpr : public Expr {
Expr *Base;
SourceLoc Loc;
public:
CodeCompletionExpr(Expr *Base, SourceLoc Loc)
: Expr(ExprKind::CodeCompletion, /*Implicit=*/true, Type()),
Base(Base), Loc(Loc) {}
CodeCompletionExpr(SourceLoc Loc)
: CodeCompletionExpr(/*Base=*/nullptr, Loc) {}
Expr *getBase() const { return Base; }
void setBase(Expr *E) { Base = E; }
SourceLoc getLoc() const { return Loc; }
SourceLoc getStartLoc() const { return Base ? Base->getStartLoc() : Loc; }
SourceLoc getEndLoc() const { return Loc; }
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::CodeCompletion;
}
};
/// LiteralExpr - Common base class between the literals.
class LiteralExpr : public Expr {
// Set by Sema:
ConcreteDeclRef Initializer;
public:
LiteralExpr(ExprKind Kind, bool Implicit) : Expr(Kind, Implicit) {}
static bool classof(const Expr *E) {
return E->getKind() >= ExprKind::First_LiteralExpr &&
E->getKind() <= ExprKind::Last_LiteralExpr;
}
/// Retrieve the initializer that will be used to construct the
/// literal from the result of the initializer.
///
/// Only literals that have no builtin literal conformance will have
/// this initializer, which will be called on the result of the builtin
/// initializer.
ConcreteDeclRef getInitializer() const { return Initializer; }
/// Set the initializer that will be used to construct the literal.
void setInitializer(ConcreteDeclRef initializer) {
Initializer = initializer;
}
/// Get description string for the literal expression.
StringRef getLiteralKindDescription() const;
};
/// BuiltinLiteralExpr - Common base class between all literals
/// that provides BuiltinInitializer
class BuiltinLiteralExpr : public LiteralExpr {
// Set by Seam:
ConcreteDeclRef BuiltinInitializer;
public:
BuiltinLiteralExpr(ExprKind Kind, bool Implicit)
: LiteralExpr(Kind, Implicit) {}
static bool classof(const Expr *E) {
return E->getKind() >= ExprKind::First_BuiltinLiteralExpr &&
E->getKind() <= ExprKind::Last_BuiltinLiteralExpr;
}
/// Retrieve the builtin initializer that will be used to construct the
/// literal.
///
/// Any type-checked literal will have a builtin initializer, which is
/// called first to form a concrete Swift type.
ConcreteDeclRef getBuiltinInitializer() const { return BuiltinInitializer; }
/// Set the builtin initializer that will be used to construct the
/// literal.
void setBuiltinInitializer(ConcreteDeclRef builtinInitializer) {
BuiltinInitializer = builtinInitializer;
}
};
/// The 'nil' literal.
///
class NilLiteralExpr : public LiteralExpr {
SourceLoc Loc;
public:
NilLiteralExpr(SourceLoc Loc, bool Implicit = false)
: LiteralExpr(ExprKind::NilLiteral, Implicit), Loc(Loc) {
}
SourceRange getSourceRange() const {
return Loc;
}
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::NilLiteral;
}
};
/// Abstract base class for numeric literals, potentially with a sign.
class NumberLiteralExpr : public BuiltinLiteralExpr {
/// The value of the literal as an ASTContext-owned string. Underscores must
/// be stripped.
StringRef Val; // Use StringRef instead of APInt or APFloat, which leak.
protected:
SourceLoc MinusLoc;
SourceLoc DigitsLoc;
public:
NumberLiteralExpr(ExprKind Kind, StringRef Val, SourceLoc DigitsLoc,
bool Implicit)
: BuiltinLiteralExpr(Kind, Implicit), Val(Val), DigitsLoc(DigitsLoc) {
Bits.NumberLiteralExpr.IsNegative = false;
Bits.NumberLiteralExpr.IsExplicitConversion = false;
}
bool isNegative() const { return Bits.NumberLiteralExpr.IsNegative; }
void setNegative(SourceLoc Loc) {
MinusLoc = Loc;
Bits.NumberLiteralExpr.IsNegative = true;
}
bool isExplicitConversion() const {
return Bits.NumberLiteralExpr.IsExplicitConversion;
}
void setExplicitConversion(bool isExplicitConversion = true) {
Bits.NumberLiteralExpr.IsExplicitConversion = isExplicitConversion;
}
StringRef getDigitsText() const { return Val; }
SourceRange getSourceRange() const {
if (isNegative())
return { MinusLoc, DigitsLoc };
else
return DigitsLoc;
}
SourceLoc getMinusLoc() const {
return MinusLoc;
}
SourceLoc getDigitsLoc() const {
return DigitsLoc;
}
static bool classof(const Expr *E) {
return E->getKind() >= ExprKind::First_NumberLiteralExpr
&& E->getKind() <= ExprKind::Last_NumberLiteralExpr;
}
};
/// Integer literal with a '+' or '-' sign, like '+4' or '- 2'.
///
/// After semantic analysis assigns types, this is guaranteed to have
/// a BuiltinIntegerType or be a normal type and implicitly be
/// AnyBuiltinIntegerType.
class IntegerLiteralExpr : public NumberLiteralExpr {
public:
IntegerLiteralExpr(StringRef Val, SourceLoc DigitsLoc, bool Implicit = false)
: NumberLiteralExpr(ExprKind::IntegerLiteral,
Val, DigitsLoc, Implicit)
{}
/// Returns a new integer literal expression with the given value.
/// \p C The AST context.
/// \p value The integer value.
/// \return An implicit integer literal expression which evaluates to the value.
static IntegerLiteralExpr *
createFromUnsigned(ASTContext &C, unsigned value, SourceLoc loc);
/// Returns the value of the literal, appropriately constructed in the
/// target type.
APInt getValue() const;
/// Returns the raw value of the literal without any truncation.
APInt getRawValue() const;
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::IntegerLiteral;
}
};
/// FloatLiteralExpr - Floating point literal, like '4.0'. After semantic
/// analysis assigns types, BuiltinTy is guaranteed to only have a
/// BuiltinFloatingPointType.
class FloatLiteralExpr : public NumberLiteralExpr {
/// This is the type of the builtin literal.
Type BuiltinTy;
public:
FloatLiteralExpr(StringRef Val, SourceLoc Loc, bool Implicit = false)
: NumberLiteralExpr(ExprKind::FloatLiteral, Val, Loc, Implicit)
{}
APFloat getValue() const;
static APFloat getValue(StringRef Text, const llvm::fltSemantics &Semantics,
bool Negative);
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::FloatLiteral;
}
Type getBuiltinType() const { return BuiltinTy; }
void setBuiltinType(Type ty) { BuiltinTy = ty; }
};
/// A Boolean literal ('true' or 'false')
///
class BooleanLiteralExpr : public BuiltinLiteralExpr {
SourceLoc Loc;
public:
BooleanLiteralExpr(bool Value, SourceLoc Loc, bool Implicit = false)
: BuiltinLiteralExpr(ExprKind::BooleanLiteral, Implicit), Loc(Loc) {
Bits.BooleanLiteralExpr.Value = Value;
}
/// Retrieve the Boolean value of this literal.
bool getValue() const { return Bits.BooleanLiteralExpr.Value; }
SourceRange getSourceRange() const {
return Loc;
}
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::BooleanLiteral;
}
};
/// StringLiteralExpr - String literal, like '"foo"'.
class StringLiteralExpr : public BuiltinLiteralExpr {
StringRef Val;
SourceRange Range;
public:
/// The encoding that should be used for the string literal.
enum Encoding : unsigned {
/// A UTF-8 string.
UTF8,
/// A single UnicodeScalar, passed as an integer.
OneUnicodeScalar
};
StringLiteralExpr(StringRef Val, SourceRange Range, bool Implicit = false);
StringRef getValue() const { return Val; }
SourceRange getSourceRange() const { return Range; }
/// Determine the encoding that should be used for this string literal.
Encoding getEncoding() const {
return static_cast<Encoding>(Bits.StringLiteralExpr.Encoding);
}
/// Set the encoding that should be used for this string literal.
void setEncoding(Encoding encoding) {
Bits.StringLiteralExpr.Encoding = static_cast<unsigned>(encoding);
}
bool isSingleUnicodeScalar() const {
return Bits.StringLiteralExpr.IsSingleUnicodeScalar;
}
bool isSingleExtendedGraphemeCluster() const {
return Bits.StringLiteralExpr.IsSingleExtendedGraphemeCluster;
}
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::StringLiteral;
}
};
/// Runs a series of statements which use or modify \c SubExpr
/// before it is given to the rest of the expression.
///
/// \c Body should begin with a \c VarDecl; this defines the variable
/// \c TapExpr will initialize at the beginning and read a result
/// from at the end. \c TapExpr creates a separate scope, then
/// assigns the result of \c SubExpr to the variable and runs \c Body
/// in it, returning the value of the variable after the \c Body runs.
///
/// (The design here could be a bit cleaner, particularly where the VarDecl
/// is concerned.)
class TapExpr : public Expr {
Expr *SubExpr;
BraceStmt *Body;
public:
TapExpr(Expr *SubExpr, BraceStmt *Body);
Expr * getSubExpr() const { return SubExpr; }
void setSubExpr(Expr * se) { SubExpr = se; }
/// The variable which will be accessed and possibly modified by
/// the \c Body. This is the first \c ASTNode in the \c Body.
VarDecl * getVar() const;
BraceStmt * getBody() const { return Body; }
void setBody(BraceStmt * b) { Body = b; }
SourceLoc getLoc() const { return SubExpr ? SubExpr->getLoc() : SourceLoc(); }
SourceRange getSourceRange() const;
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::Tap;
}
};
/// InterpolatedStringLiteral - An interpolated string literal.
///
/// An interpolated string literal mixes expressions (which are evaluated and
/// converted into string form) within a string literal.
///
/// \code
/// "[\(min)..\(max)]"
/// \endcode
class InterpolatedStringLiteralExpr : public LiteralExpr {
/// Points at the beginning quote.
SourceLoc Loc;
TapExpr *AppendingExpr;
// Set by Sema:
OpaqueValueExpr *interpolationExpr = nullptr;
ConcreteDeclRef builderInit;
Expr *interpolationCountExpr = nullptr;
Expr *literalCapacityExpr = nullptr;
public:
InterpolatedStringLiteralExpr(SourceLoc Loc,
unsigned LiteralCapacity,
unsigned InterpolationCount,
TapExpr *AppendingExpr)
: LiteralExpr(ExprKind::InterpolatedStringLiteral, /*Implicit=*/false),
Loc(Loc),
AppendingExpr(AppendingExpr) {
Bits.InterpolatedStringLiteralExpr.InterpolationCount = InterpolationCount;
Bits.InterpolatedStringLiteralExpr.LiteralCapacity = LiteralCapacity;
}
// Sets the constructor for the interpolation type.
void setBuilderInit(ConcreteDeclRef decl) { builderInit = decl; }
ConcreteDeclRef getBuilderInit() const { return builderInit; }
/// Sets the OpaqueValueExpr that is passed into AppendingExpr as the SubExpr
/// that the tap operates on.
void setInterpolationExpr(OpaqueValueExpr *expr) { interpolationExpr = expr; }
OpaqueValueExpr *getInterpolationExpr() const { return interpolationExpr; }
/// Store a builtin integer literal expr wrapping getInterpolationCount().
/// This is an arg to builderInit.
void setInterpolationCountExpr(Expr *expr) { interpolationCountExpr = expr; }
Expr *getInterpolationCountExpr() const { return interpolationCountExpr; }
/// Store a builtin integer literal expr wrapping getLiteralCapacity().
/// This is an arg to builderInit.
void setLiteralCapacityExpr(Expr *expr) { literalCapacityExpr = expr; }
Expr *getLiteralCapacityExpr() const { return literalCapacityExpr; }
/// Retrieve the value of the literalCapacity parameter to the
/// initializer.
unsigned getLiteralCapacity() const {
return Bits.InterpolatedStringLiteralExpr.LiteralCapacity;
}
/// Retrieve the value of the interpolationCount parameter to the
/// initializer.
unsigned getInterpolationCount() const {
return Bits.InterpolatedStringLiteralExpr.InterpolationCount;
}
/// A block containing expressions which call
/// \c StringInterpolationProtocol methods to append segments to the
/// string interpolation. The first node in \c Body should be an uninitialized
/// \c VarDecl; the other statements should append to it.
TapExpr * getAppendingExpr() const { return AppendingExpr; }
void setAppendingExpr(TapExpr * AE) { AppendingExpr = AE; }
SourceLoc getStartLoc() const {
return Loc;
}
SourceLoc getEndLoc() const {
// SourceLocs are token based, and the interpolated string is one string
// token, so the range should be (Start == End).
return Loc;
}
/// Call the \c callback with information about each segment in turn.
void forEachSegment(ASTContext &Ctx,
llvm::function_ref<void(bool, CallExpr *)> callback);
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::InterpolatedStringLiteral;
}
};
/// The opaque kind of a RegexLiteralExpr feature, which should only be