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"
14 #include "llvm/Support/DataTypes.h"
20 class SmallVectorImpl;
24 /// Twine - A lightweight data structure for efficiently representing the
25 /// concatenation of temporary values as strings.
27 /// A Twine is a kind of rope, it represents a concatenated string using a
28 /// binary-tree, where the string is the preorder of the nodes. Since the
29 /// Twine can be efficiently rendered into a buffer when its result is used,
30 /// it avoids the cost of generating temporary values for intermediate string
31 /// results -- particularly in cases when the Twine result is never
32 /// required. By explicitly tracking the type of leaf nodes, we can also avoid
33 /// the creation of temporary strings for conversions operations (such as
34 /// appending an integer to a string).
36 /// A Twine is not intended for use directly and should not be stored, its
37 /// implementation relies on the ability to store pointers to temporary stack
38 /// objects which may be deallocated at the end of a statement. Twines should
39 /// only be used accepted as const references in arguments, when an API wishes
40 /// to accept possibly-concatenated strings.
42 /// Twines support a special 'null' value, which always concatenates to form
43 /// itself, and renders as an empty string. This can be returned from APIs to
44 /// effectively nullify any concatenations performed on the result.
46 /// \b Implementation \n
48 /// Given the nature of a Twine, it is not possible for the Twine's
49 /// concatenation method to construct interior nodes; the result must be
50 /// represented inside the returned value. For this reason a Twine object
51 /// actually holds two values, the left- and right-hand sides of a
52 /// concatenation. We also have nullary Twine objects, which are effectively
53 /// sentinel values that represent empty strings.
55 /// Thus, a Twine can effectively have zero, one, or two children. The \see
56 /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
57 /// testing the number of children.
59 /// We maintain a number of invariants on Twine objects (FIXME: Why):
60 /// - Nullary twines are always represented with their Kind on the left-hand
61 /// side, and the Empty kind on the right-hand side.
62 /// - Unary twines are always represented with the value on the left-hand
63 /// side, and the Empty kind on the right-hand side.
64 /// - If a Twine has another Twine as a child, that child should always be
65 /// binary (otherwise it could have been folded into the parent).
67 /// These invariants are check by \see isValid().
69 /// \b Efficiency Considerations \n
71 /// The Twine is designed to yield efficient and small code for common
72 /// situations. For this reason, the concat() method is inlined so that
73 /// concatenations of leaf nodes can be optimized into stores directly into a
74 /// single stack allocated object.
76 /// In practice, not all compilers can be trusted to optimize concat() fully,
77 /// so we provide two additional methods (and accompanying operator+
78 /// overloads) to guarantee that particularly important cases (cstring plus
79 /// StringRef) codegen as desired.
81 /// NodeKind - Represent the type of an argument.
83 /// An empty string; the result of concatenating anything with it is also
90 /// A pointer to a Twine instance.
93 /// A pointer to a C string instance.
96 /// A pointer to an std::string instance.
99 /// A pointer to a StringRef instance.
102 /// A pointer to a uint64_t value, to render as an unsigned decimal
106 /// A pointer to a uint64_t value, to render as a signed decimal integer.
109 /// A pointer to a uint64_t value, to render as an unsigned decimal
113 /// A pointer to a uint64_t value, to render as a signed decimal integer.
116 /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
122 /// LHS - The prefix in the concatenation, which may be uninitialized for
123 /// Null or Empty kinds.
125 /// RHS - The suffix in the concatenation, which may be uninitialized for
126 /// Null or Empty kinds.
128 /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
129 NodeKind LHSKind : 8;
130 /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
131 NodeKind RHSKind : 8;
134 /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
135 explicit Twine(NodeKind Kind)
136 : LHSKind(Kind), RHSKind(EmptyKind) {
137 assert(isNullary() && "Invalid kind!");
140 /// Construct a binary twine.
141 explicit Twine(const Twine &_LHS, const Twine &_RHS)
142 : LHS(&_LHS), RHS(&_RHS), LHSKind(TwineKind), RHSKind(TwineKind) {
143 assert(isValid() && "Invalid twine!");
146 /// Construct a twine from explicit values.
147 explicit Twine(const void *_LHS, NodeKind _LHSKind,
148 const void *_RHS, NodeKind _RHSKind)
149 : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
150 assert(isValid() && "Invalid twine!");
153 /// isNull - Check for the null twine.
154 bool isNull() const {
155 return getLHSKind() == NullKind;
158 /// isEmpty - Check for the empty twine.
159 bool isEmpty() const {
160 return getLHSKind() == EmptyKind;
163 /// isNullary - Check if this is a nullary twine (null or empty).
164 bool isNullary() const {
165 return isNull() || isEmpty();
168 /// isUnary - Check if this is a unary twine.
169 bool isUnary() const {
170 return getRHSKind() == EmptyKind && !isNullary();
173 /// isBinary - Check if this is a binary twine.
174 bool isBinary() const {
175 return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
178 /// isValid - Check if this is a valid twine (satisfying the invariants on
179 /// order and number of arguments).
180 bool isValid() const {
181 // Nullary twines always have Empty on the RHS.
182 if (isNullary() && getRHSKind() != EmptyKind)
185 // Null should never appear on the RHS.
186 if (getRHSKind() == NullKind)
189 // The RHS cannot be non-empty if the LHS is empty.
190 if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
193 // A twine child should always be binary.
194 if (getLHSKind() == TwineKind &&
195 !static_cast<const Twine*>(LHS)->isBinary())
197 if (getRHSKind() == TwineKind &&
198 !static_cast<const Twine*>(RHS)->isBinary())
204 /// getLHSKind - Get the NodeKind of the left-hand side.
205 NodeKind getLHSKind() const { return LHSKind; }
207 /// getRHSKind - Get the NodeKind of the left-hand side.
208 NodeKind getRHSKind() const { return RHSKind; }
210 /// printOneChild - Print one child from a twine.
211 void printOneChild(raw_ostream &OS, const void *Ptr, NodeKind Kind) const;
213 /// printOneChildRepr - Print the representation of one child from a twine.
214 void printOneChildRepr(raw_ostream &OS, const void *Ptr,
215 NodeKind Kind) const;
218 /// @name Constructors
221 /// Construct from an empty string.
222 /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
223 assert(isValid() && "Invalid twine!");
226 /// Construct from a C string.
228 /// We take care here to optimize "" into the empty twine -- this will be
229 /// optimized out for string constants. This allows Twine arguments have
230 /// default "" values, without introducing unnecessary string constants.
231 /*implicit*/ Twine(const char *Str)
232 : RHSKind(EmptyKind) {
233 if (Str[0] != '\0') {
235 LHSKind = CStringKind;
239 assert(isValid() && "Invalid twine!");
242 /// Construct from an std::string.
243 /*implicit*/ Twine(const std::string &Str)
244 : LHS(&Str), LHSKind(StdStringKind), RHSKind(EmptyKind) {
245 assert(isValid() && "Invalid twine!");
248 /// Construct from a StringRef.
249 /*implicit*/ Twine(const StringRef &Str)
250 : LHS(&Str), LHSKind(StringRefKind), RHSKind(EmptyKind) {
251 assert(isValid() && "Invalid twine!");
254 /// Construct a twine to print \arg Val as an unsigned decimal integer.
255 explicit Twine(const uint32_t &Val)
256 : LHS(&Val), LHSKind(UDec32Kind), RHSKind(EmptyKind) {
259 /// Construct a twine to print \arg Val as a signed decimal integer.
260 explicit Twine(const int32_t &Val)
261 : LHS(&Val), LHSKind(SDec32Kind), RHSKind(EmptyKind) {
264 /// Construct a twine to print \arg Val as an unsigned decimal integer.
265 explicit Twine(const uint64_t &Val)
266 : LHS(&Val), LHSKind(UDec64Kind), RHSKind(EmptyKind) {
269 /// Construct a twine to print \arg Val as a signed decimal integer.
270 explicit Twine(const int64_t &Val)
271 : LHS(&Val), LHSKind(SDec64Kind), RHSKind(EmptyKind) {
274 // FIXME: Unfortunately, to make sure this is as efficient as possible we
275 // need extra binary constructors from particular types. We can't rely on
276 // the compiler to be smart enough to fold operator+()/concat() down to the
279 /// Construct as the concatenation of a C string and a StringRef.
280 /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
281 : LHS(_LHS), RHS(&_RHS), LHSKind(CStringKind), RHSKind(StringRefKind) {
282 assert(isValid() && "Invalid twine!");
285 /// Construct as the concatenation of a StringRef and a C string.
286 /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
287 : LHS(&_LHS), RHS(_RHS), LHSKind(StringRefKind), RHSKind(CStringKind) {
288 assert(isValid() && "Invalid twine!");
291 /// Create a 'null' string, which is an empty string that always
292 /// concatenates to form another empty string.
293 static Twine createNull() {
294 return Twine(NullKind);
298 /// @name Numeric Conversions
301 // Construct a twine to print \arg Val as an unsigned hexadecimal integer.
302 static Twine utohexstr(const uint64_t &Val) {
303 return Twine(&Val, UHexKind, 0, EmptyKind);
307 /// @name String Operations
310 Twine concat(const Twine &Suffix) const;
313 /// @name Output & Conversion.
316 /// str - Return the twine contents as a std::string.
317 std::string str() const;
319 /// toVector - Write the concatenated string into the given SmallString or
321 void toVector(SmallVectorImpl<char> &Out) const;
323 /// print - Write the concatenated string represented by this twine to the
325 void print(raw_ostream &OS) const;
327 /// dump - Dump the concatenated string represented by this twine to stderr.
330 /// print - Write the representation of this twine to the stream \arg OS.
331 void printRepr(raw_ostream &OS) const;
333 /// dumpRepr - Dump the representation of this twine to stderr.
334 void dumpRepr() const;
339 /// @name Twine Inline Implementations
342 inline Twine Twine::concat(const Twine &Suffix) const {
343 // Concatenation with null is null.
344 if (isNull() || Suffix.isNull())
345 return Twine(NullKind);
347 // Concatenation with empty yields the other side.
350 if (Suffix.isEmpty())
353 // Otherwise we need to create a new node, taking care to fold in unary
355 const void *NewLHS = this, *NewRHS = &Suffix;
356 NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
359 NewLHSKind = getLHSKind();
361 if (Suffix.isUnary()) {
363 NewRHSKind = Suffix.getLHSKind();
366 return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
369 inline Twine operator+(const Twine &LHS, const Twine &RHS) {
370 return LHS.concat(RHS);
373 /// Additional overload to guarantee simplified codegen; this is equivalent to
376 inline Twine operator+(const char *LHS, const StringRef &RHS) {
377 return Twine(LHS, RHS);
380 /// Additional overload to guarantee simplified codegen; this is equivalent to
383 inline Twine operator+(const StringRef &LHS, const char *RHS) {
384 return Twine(LHS, RHS);
387 inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {