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 char value reinterpreted as a pointer, to render as a character.
105 /// An unsigned int value reinterpreted as a pointer, to render as an
106 /// unsigned decimal integer.
109 /// An int value reinterpreted as a pointer, to render as a signed
113 /// A pointer to an unsigned long value, to render as an unsigned decimal
117 /// A pointer to a long value, to render as a signed decimal integer.
120 /// A pointer to an unsigned long long value, to render as an unsigned
124 /// A pointer to a long long value, to render as a signed decimal integer.
127 /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
136 const std::string *stdString;
137 const StringRef *stringRef;
141 const unsigned long *decUL;
143 const unsigned long long *decULL;
144 const long long *decLL;
145 const uint64_t *uHex;
149 /// LHS - The prefix in the concatenation, which may be uninitialized for
150 /// Null or Empty kinds.
152 /// RHS - The suffix in the concatenation, which may be uninitialized for
153 /// Null or Empty kinds.
155 // enums stored as unsigned chars to save on space while some compilers
156 // don't support specifying the backing type for an enum
157 /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
158 unsigned char LHSKind;
159 /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
160 unsigned char RHSKind;
163 /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
164 explicit Twine(NodeKind Kind)
165 : LHSKind(Kind), RHSKind(EmptyKind) {
166 assert(isNullary() && "Invalid kind!");
169 /// Construct a binary twine.
170 explicit Twine(const Twine &_LHS, const Twine &_RHS)
171 : LHSKind(TwineKind), RHSKind(TwineKind) {
174 assert(isValid() && "Invalid twine!");
177 /// Construct a twine from explicit values.
178 explicit Twine(Child _LHS, NodeKind _LHSKind,
179 Child _RHS, NodeKind _RHSKind)
180 : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
181 assert(isValid() && "Invalid twine!");
184 /// isNull - Check for the null twine.
185 bool isNull() const {
186 return getLHSKind() == NullKind;
189 /// isEmpty - Check for the empty twine.
190 bool isEmpty() const {
191 return getLHSKind() == EmptyKind;
194 /// isNullary - Check if this is a nullary twine (null or empty).
195 bool isNullary() const {
196 return isNull() || isEmpty();
199 /// isUnary - Check if this is a unary twine.
200 bool isUnary() const {
201 return getRHSKind() == EmptyKind && !isNullary();
204 /// isBinary - Check if this is a binary twine.
205 bool isBinary() const {
206 return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
209 /// isValid - Check if this is a valid twine (satisfying the invariants on
210 /// order and number of arguments).
211 bool isValid() const {
212 // Nullary twines always have Empty on the RHS.
213 if (isNullary() && getRHSKind() != EmptyKind)
216 // Null should never appear on the RHS.
217 if (getRHSKind() == NullKind)
220 // The RHS cannot be non-empty if the LHS is empty.
221 if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
224 // A twine child should always be binary.
225 if (getLHSKind() == TwineKind &&
226 !LHS.twine->isBinary())
228 if (getRHSKind() == TwineKind &&
229 !RHS.twine->isBinary())
235 /// getLHSKind - Get the NodeKind of the left-hand side.
236 NodeKind getLHSKind() const { return (NodeKind) LHSKind; }
238 /// getRHSKind - Get the NodeKind of the left-hand side.
239 NodeKind getRHSKind() const { return (NodeKind) RHSKind; }
241 /// printOneChild - Print one child from a twine.
242 void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
244 /// printOneChildRepr - Print the representation of one child from a twine.
245 void printOneChildRepr(raw_ostream &OS, Child Ptr,
246 NodeKind Kind) const;
249 /// @name Constructors
252 /// Construct from an empty string.
253 /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
254 assert(isValid() && "Invalid twine!");
257 /// Construct from a C string.
259 /// We take care here to optimize "" into the empty twine -- this will be
260 /// optimized out for string constants. This allows Twine arguments have
261 /// default "" values, without introducing unnecessary string constants.
262 /*implicit*/ Twine(const char *Str)
263 : RHSKind(EmptyKind) {
264 if (Str[0] != '\0') {
266 LHSKind = CStringKind;
270 assert(isValid() && "Invalid twine!");
273 /// Construct from an std::string.
274 /*implicit*/ Twine(const std::string &Str)
275 : LHSKind(StdStringKind), RHSKind(EmptyKind) {
276 LHS.stdString = &Str;
277 assert(isValid() && "Invalid twine!");
280 /// Construct from a StringRef.
281 /*implicit*/ Twine(const StringRef &Str)
282 : LHSKind(StringRefKind), RHSKind(EmptyKind) {
283 LHS.stringRef = &Str;
284 assert(isValid() && "Invalid twine!");
287 /// Construct from a char.
288 explicit Twine(char Val)
289 : LHSKind(CharKind), RHSKind(EmptyKind) {
293 /// Construct from a signed char.
294 explicit Twine(signed char Val)
295 : LHSKind(CharKind), RHSKind(EmptyKind) {
296 LHS.character = static_cast<char>(Val);
299 /// Construct from an unsigned char.
300 explicit Twine(unsigned char Val)
301 : LHSKind(CharKind), RHSKind(EmptyKind) {
302 LHS.character = static_cast<char>(Val);
305 /// Construct a twine to print \arg Val as an unsigned decimal integer.
306 explicit Twine(unsigned Val)
307 : LHSKind(DecUIKind), RHSKind(EmptyKind) {
311 /// Construct a twine to print \arg Val as a signed decimal integer.
312 explicit Twine(int Val)
313 : LHSKind(DecIKind), RHSKind(EmptyKind) {
317 /// Construct a twine to print \arg Val as an unsigned decimal integer.
318 explicit Twine(const unsigned long &Val)
319 : LHSKind(DecULKind), RHSKind(EmptyKind) {
323 /// Construct a twine to print \arg Val as a signed decimal integer.
324 explicit Twine(const long &Val)
325 : LHSKind(DecLKind), RHSKind(EmptyKind) {
329 /// Construct a twine to print \arg Val as an unsigned decimal integer.
330 explicit Twine(const unsigned long long &Val)
331 : LHSKind(DecULLKind), RHSKind(EmptyKind) {
335 /// Construct a twine to print \arg Val as a signed decimal integer.
336 explicit Twine(const long long &Val)
337 : LHSKind(DecLLKind), RHSKind(EmptyKind) {
341 // FIXME: Unfortunately, to make sure this is as efficient as possible we
342 // need extra binary constructors from particular types. We can't rely on
343 // the compiler to be smart enough to fold operator+()/concat() down to the
346 /// Construct as the concatenation of a C string and a StringRef.
347 /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
348 : LHSKind(CStringKind), RHSKind(StringRefKind) {
350 RHS.stringRef = &_RHS;
351 assert(isValid() && "Invalid twine!");
354 /// Construct as the concatenation of a StringRef and a C string.
355 /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
356 : LHSKind(StringRefKind), RHSKind(CStringKind) {
357 LHS.stringRef = &_LHS;
359 assert(isValid() && "Invalid twine!");
362 /// Create a 'null' string, which is an empty string that always
363 /// concatenates to form another empty string.
364 static Twine createNull() {
365 return Twine(NullKind);
369 /// @name Numeric Conversions
372 // Construct a twine to print \arg Val as an unsigned hexadecimal integer.
373 static Twine utohexstr(const uint64_t &Val) {
377 return Twine(LHS, UHexKind, RHS, EmptyKind);
381 /// @name Predicate Operations
384 /// isTriviallyEmpty - Check if this twine is trivially empty; a false
385 /// return value does not necessarily mean the twine is empty.
386 bool isTriviallyEmpty() const {
390 /// isSingleStringRef - Return true if this twine can be dynamically
391 /// accessed as a single StringRef value with getSingleStringRef().
392 bool isSingleStringRef() const {
393 if (getRHSKind() != EmptyKind) return false;
395 switch (getLHSKind()) {
407 /// @name String Operations
410 Twine concat(const Twine &Suffix) const;
413 /// @name Output & Conversion.
416 /// str - Return the twine contents as a std::string.
417 std::string str() const;
419 /// toVector - Write the concatenated string into the given SmallString or
421 void toVector(SmallVectorImpl<char> &Out) const;
423 /// getSingleStringRef - This returns the twine as a single StringRef. This
424 /// method is only valid if isSingleStringRef() is true.
425 StringRef getSingleStringRef() const {
426 assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
427 switch (getLHSKind()) {
428 default: assert(0 && "Out of sync with isSingleStringRef");
429 case EmptyKind: return StringRef();
430 case CStringKind: return StringRef(LHS.cString);
431 case StdStringKind: return StringRef(*LHS.stdString);
432 case StringRefKind: return *LHS.stringRef;
436 /// toStringRef - This returns the twine as a single StringRef if it can be
437 /// represented as such. Otherwise the twine is written into the given
438 /// SmallVector and a StringRef to the SmallVector's data is returned.
439 StringRef toStringRef(SmallVectorImpl<char> &Out) const;
441 /// toNullTerminatedStringRef - This returns the twine as a single null
442 /// terminated StringRef if it can be represented as such. Otherwise the
443 /// twine is written into the given SmallVector and a StringRef to the
444 /// SmallVector's data is returned.
446 /// The returned StringRef's size does not include the null terminator.
447 StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
449 /// print - Write the concatenated string represented by this twine to the
451 void print(raw_ostream &OS) const;
453 /// dump - Dump the concatenated string represented by this twine to stderr.
456 /// print - Write the representation of this twine to the stream \arg OS.
457 void printRepr(raw_ostream &OS) const;
459 /// dumpRepr - Dump the representation of this twine to stderr.
460 void dumpRepr() const;
465 /// @name Twine Inline Implementations
468 inline Twine Twine::concat(const Twine &Suffix) const {
469 // Concatenation with null is null.
470 if (isNull() || Suffix.isNull())
471 return Twine(NullKind);
473 // Concatenation with empty yields the other side.
476 if (Suffix.isEmpty())
479 // Otherwise we need to create a new node, taking care to fold in unary
481 Child NewLHS, NewRHS;
483 NewRHS.twine = &Suffix;
484 NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
487 NewLHSKind = getLHSKind();
489 if (Suffix.isUnary()) {
491 NewRHSKind = Suffix.getLHSKind();
494 return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
497 inline Twine operator+(const Twine &LHS, const Twine &RHS) {
498 return LHS.concat(RHS);
501 /// Additional overload to guarantee simplified codegen; this is equivalent to
504 inline Twine operator+(const char *LHS, const StringRef &RHS) {
505 return Twine(LHS, RHS);
508 /// Additional overload to guarantee simplified codegen; this is equivalent to
511 inline Twine operator+(const StringRef &LHS, const char *RHS) {
512 return Twine(LHS, RHS);
515 inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {