1 //===-- Twine.h - Fast Temporary String Concatenation -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLVM_ADT_TWINE_H
11 #define LLVM_ADT_TWINE_H
13 #include "llvm/ADT/StringRef.h"
19 class SmallVectorImpl;
23 /// Twine - A lightweight data structure for efficiently representing the
24 /// concatenation of temporary values as strings.
26 /// A Twine is a kind of rope, it represents a concatenated string using a
27 /// binary-tree, where the string is the preorder of the nodes. Since the
28 /// Twine can be efficiently rendered into a buffer when its result is used,
29 /// it avoids the cost of generating temporary values for intermediate string
30 /// results -- particularly in cases when the Twine result is never
31 /// required. By explicitly tracking the type of leaf nodes, we can also avoid
32 /// the creation of temporary strings for conversions operations (such as
33 /// appending an integer to a string).
35 /// A Twine is not intended for use directly and should not be stored, its
36 /// implementation relies on the ability to store pointers to temporary stack
37 /// objects which may be deallocated at the end of a statement. Twines should
38 /// only be used accepted as const references in arguments, when an API wishes
39 /// to accept possibly-concatenated strings.
41 /// Twines support a special 'null' value, which always concatenates to form
42 /// itself, and renders as an empty string. This can be returned from APIs to
43 /// effectively nullify any concatenations performed on the result.
45 /// \b Implementation \n
47 /// Given the nature of a Twine, it is not possible for the Twine's
48 /// concatenation method to construct interior nodes; the result must be
49 /// represented inside the returned value. For this reason a Twine object
50 /// actually holds two values, the left- and right-hand sides of a
51 /// concatenation. We also have nullary Twine objects, which are effectively
52 /// sentinel values that represent empty strings.
54 /// Thus, a Twine can effectively have zero, one, or two children. The \see
55 /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
56 /// testing the number of children.
58 /// We maintain a number of invariants on Twine objects (FIXME: Why):
59 /// - Nullary twines are always represented with their Kind on the left-hand
60 /// side, and the Empty kind on the right-hand side.
61 /// - Unary twines are always represented with the value on the left-hand
62 /// side, and the Empty kind on the right-hand side.
63 /// - If a Twine has another Twine as a child, that child should always be
64 /// binary (otherwise it could have been folded into the parent).
66 /// These invariants are check by \see isValid().
68 /// \b Efficiency Considerations \n
70 /// The Twine is designed to yield efficient and small code for common
71 /// situations. For this reason, the concat() method is inlined so that
72 /// concatenations of leaf nodes can be optimized into stores directly into a
73 /// single stack allocated object.
75 /// In practice, not all compilers can be trusted to optimize concat() fully,
76 /// so we provide two additional methods (and accompanying operator+
77 /// overloads) to guarantee that particularly important cases (cstring plus
78 /// StringRef) codegen as desired.
80 /// NodeKind - Represent the type of an argument.
82 /// An empty string; the result of concatenating anything with it is also
89 /// A pointer to a C string instance.
92 /// A pointer to an std::string instance.
95 /// A pointer to a StringRef instance.
98 /// A pointer to a Twine instance.
103 /// LHS - The prefix in the concatenation, which may be uninitialized for
104 /// Null or Empty kinds.
106 /// RHS - The suffix in the concatenation, which may be uninitialized for
107 /// Null or Empty kinds.
109 /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
110 NodeKind LHSKind : 8;
111 /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
112 NodeKind RHSKind : 8;
115 /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
116 explicit Twine(NodeKind Kind)
117 : LHSKind(Kind), RHSKind(EmptyKind) {
118 assert(isNullary() && "Invalid kind!");
121 /// Construct a binary twine.
122 explicit Twine(const Twine &_LHS, const Twine &_RHS)
123 : LHS(&_LHS), RHS(&_RHS), LHSKind(TwineKind), RHSKind(TwineKind) {
124 assert(isValid() && "Invalid twine!");
127 /// Construct a twine from explicit values.
128 explicit Twine(const void *_LHS, NodeKind _LHSKind,
129 const void *_RHS, NodeKind _RHSKind)
130 : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
131 assert(isValid() && "Invalid twine!");
134 /// isNull - Check for the null twine.
135 bool isNull() const {
136 return getLHSKind() == NullKind;
139 /// isEmpty - Check for the empty twine.
140 bool isEmpty() const {
141 return getLHSKind() == EmptyKind;
144 /// isNullary - Check if this is a nullary twine (null or empty).
145 bool isNullary() const {
146 return isNull() || isEmpty();
149 /// isUnary - Check if this is a unary twine.
150 bool isUnary() const {
151 return getRHSKind() == EmptyKind && !isNullary();
154 /// isBinary - Check if this is a binary twine.
155 bool isBinary() const {
156 return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
159 /// isValid - Check if this is a valid twine (satisfying the invariants on
160 /// order and number of arguments).
161 bool isValid() const {
162 // Nullary twines always have Empty on the RHS.
163 if (isNullary() && getRHSKind() != EmptyKind)
166 // Null should never appear on the RHS.
167 if (getRHSKind() == NullKind)
170 // The RHS cannot be non-empty if the LHS is empty.
171 if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
174 // A twine child should always be binary.
175 if (getLHSKind() == TwineKind &&
176 !static_cast<const Twine*>(LHS)->isBinary())
178 if (getRHSKind() == TwineKind &&
179 !static_cast<const Twine*>(RHS)->isBinary())
185 /// getLHSKind - Get the NodeKind of the left-hand side.
186 NodeKind getLHSKind() const { return LHSKind; }
188 /// getRHSKind - Get the NodeKind of the left-hand side.
189 NodeKind getRHSKind() const { return RHSKind; }
191 /// printOneChild - Print one child from a twine.
192 void printOneChild(raw_ostream &OS, const void *Ptr, NodeKind Kind) const;
194 /// printOneChildRepr - Print the representation of one child from a twine.
195 void printOneChildRepr(raw_ostream &OS, const void *Ptr,
196 NodeKind Kind) const;
199 /// @name Constructors
202 /// Construct from an empty string.
203 /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
204 assert(isValid() && "Invalid twine!");
207 /// Construct from a C string.
209 /// We take care here to optimize "" into the empty twine -- this will be
210 /// optimized out for string constants. This allows Twine arguments have
211 /// default "" values, without introducing unnecessary string constants.
212 /*implicit*/ Twine(const char *Str)
213 : RHSKind(EmptyKind) {
214 if (Str[0] != '\0') {
216 LHSKind = CStringKind;
220 assert(isValid() && "Invalid twine!");
223 /// Construct from an std::string.
224 /*implicit*/ Twine(const std::string &Str)
225 : LHS(&Str), LHSKind(StdStringKind), RHSKind(EmptyKind) {
226 assert(isValid() && "Invalid twine!");
229 /// Construct from a StringRef.
230 /*implicit*/ Twine(const StringRef &Str)
231 : LHS(&Str), LHSKind(StringRefKind), RHSKind(EmptyKind) {
232 assert(isValid() && "Invalid twine!");
235 /// Create a 'null' string, which is an empty string that always
236 /// concatenates to form another empty string.
237 static Twine createNull() {
238 return Twine(NullKind);
241 // FIXME: Unfortunately, to make sure this is as efficient as possible we
242 // need extra binary constructors from particular types. We can't rely on
243 // the compiler to be smart enough to fold operator+()/concat() down to the
246 /// Construct as the concatenation of a C string and a StringRef.
247 /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
248 : LHS(_LHS), RHS(&_RHS), LHSKind(CStringKind), RHSKind(StringRefKind) {
249 assert(isValid() && "Invalid twine!");
252 /// Construct as the concatenation of a StringRef and a C string.
253 /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
254 : LHS(&_LHS), RHS(_RHS), LHSKind(StringRefKind), RHSKind(CStringKind) {
255 assert(isValid() && "Invalid twine!");
259 /// @name String Operations
262 Twine concat(const Twine &Suffix) const;
265 /// @name Output & Conversion.
268 /// str - Return the twine contents as a std::string.
269 std::string str() const;
271 /// toVector - Write the concatenated string into the given SmallString or
273 void toVector(SmallVectorImpl<char> &Out) const;
275 /// print - Write the concatenated string represented by this twine to the
277 void print(raw_ostream &OS) const;
279 /// dump - Dump the concatenated string represented by this twine to stderr.
282 /// print - Write the representation of this twine to the stream \arg OS.
283 void printRepr(raw_ostream &OS) const;
285 /// dumpRepr - Dump the representation of this twine to stderr.
286 void dumpRepr() const;
291 /// @name Twine Inline Implementations
294 inline Twine Twine::concat(const Twine &Suffix) const {
295 // Concatenation with null is null.
296 if (isNull() || Suffix.isNull())
297 return Twine(NullKind);
299 // Concatenation with empty yields the other side.
302 if (Suffix.isEmpty())
305 // Otherwise we need to create a new node, taking care to fold in unary
307 const void *NewLHS = this, *NewRHS = &Suffix;
308 NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
311 NewLHSKind = getLHSKind();
313 if (Suffix.isUnary()) {
315 NewRHSKind = Suffix.getLHSKind();
318 return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
321 inline Twine operator+(const Twine &LHS, const Twine &RHS) {
322 return LHS.concat(RHS);
325 /// Additional overload to guarantee simplified codegen; this is equivalent to
328 inline Twine operator+(const char *LHS, const StringRef &RHS) {
329 return Twine(LHS, RHS);
332 /// Additional overload to guarantee simplified codegen; this is equivalent to
335 inline Twine operator+(const StringRef &LHS, const char *RHS) {
336 return Twine(LHS, RHS);
339 inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {