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/System/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 /// An unsigned int value reinterpreted as a pointer, to render as an
103 /// unsigned decimal integer.
106 /// An int value reinterpreted as a pointer, to render as a signed
110 /// A pointer to an unsigned long value, to render as an unsigned decimal
114 /// A pointer to a long value, to render as a signed decimal integer.
117 /// A pointer to an unsigned long long value, to render as an unsigned
121 /// A pointer to a long long value, to render as a signed decimal integer.
124 /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
130 /// LHS - The prefix in the concatenation, which may be uninitialized for
131 /// Null or Empty kinds.
133 /// RHS - The suffix in the concatenation, which may be uninitialized for
134 /// Null or Empty kinds.
136 /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
137 unsigned char LHSKind;
138 /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
139 unsigned char RHSKind;
142 /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
143 explicit Twine(NodeKind Kind)
144 : LHSKind(Kind), RHSKind(EmptyKind) {
145 assert(isNullary() && "Invalid kind!");
148 /// Construct a binary twine.
149 explicit Twine(const Twine &_LHS, const Twine &_RHS)
150 : LHS(&_LHS), RHS(&_RHS), LHSKind(TwineKind), RHSKind(TwineKind) {
151 assert(isValid() && "Invalid twine!");
154 /// Construct a twine from explicit values.
155 explicit Twine(const void *_LHS, NodeKind _LHSKind,
156 const void *_RHS, NodeKind _RHSKind)
157 : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
158 assert(isValid() && "Invalid twine!");
161 /// isNull - Check for the null twine.
162 bool isNull() const {
163 return getLHSKind() == NullKind;
166 /// isEmpty - Check for the empty twine.
167 bool isEmpty() const {
168 return getLHSKind() == EmptyKind;
171 /// isNullary - Check if this is a nullary twine (null or empty).
172 bool isNullary() const {
173 return isNull() || isEmpty();
176 /// isUnary - Check if this is a unary twine.
177 bool isUnary() const {
178 return getRHSKind() == EmptyKind && !isNullary();
181 /// isBinary - Check if this is a binary twine.
182 bool isBinary() const {
183 return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
186 /// isValid - Check if this is a valid twine (satisfying the invariants on
187 /// order and number of arguments).
188 bool isValid() const {
189 // Nullary twines always have Empty on the RHS.
190 if (isNullary() && getRHSKind() != EmptyKind)
193 // Null should never appear on the RHS.
194 if (getRHSKind() == NullKind)
197 // The RHS cannot be non-empty if the LHS is empty.
198 if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
201 // A twine child should always be binary.
202 if (getLHSKind() == TwineKind &&
203 !static_cast<const Twine*>(LHS)->isBinary())
205 if (getRHSKind() == TwineKind &&
206 !static_cast<const Twine*>(RHS)->isBinary())
212 /// getLHSKind - Get the NodeKind of the left-hand side.
213 NodeKind getLHSKind() const { return (NodeKind) LHSKind; }
215 /// getRHSKind - Get the NodeKind of the left-hand side.
216 NodeKind getRHSKind() const { return (NodeKind) RHSKind; }
218 /// printOneChild - Print one child from a twine.
219 void printOneChild(raw_ostream &OS, const void *Ptr, NodeKind Kind) const;
221 /// printOneChildRepr - Print the representation of one child from a twine.
222 void printOneChildRepr(raw_ostream &OS, const void *Ptr,
223 NodeKind Kind) const;
226 /// @name Constructors
229 /// Construct from an empty string.
230 /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
231 assert(isValid() && "Invalid twine!");
234 /// Construct from a C string.
236 /// We take care here to optimize "" into the empty twine -- this will be
237 /// optimized out for string constants. This allows Twine arguments have
238 /// default "" values, without introducing unnecessary string constants.
239 /*implicit*/ Twine(const char *Str)
240 : RHSKind(EmptyKind) {
241 if (Str[0] != '\0') {
243 LHSKind = CStringKind;
247 assert(isValid() && "Invalid twine!");
250 /// Construct from an std::string.
251 /*implicit*/ Twine(const std::string &Str)
252 : LHS(&Str), LHSKind(StdStringKind), RHSKind(EmptyKind) {
253 assert(isValid() && "Invalid twine!");
256 /// Construct from a StringRef.
257 /*implicit*/ Twine(const StringRef &Str)
258 : LHS(&Str), LHSKind(StringRefKind), RHSKind(EmptyKind) {
259 assert(isValid() && "Invalid twine!");
262 /// Construct a twine to print \arg Val as an unsigned decimal integer.
263 explicit Twine(unsigned Val)
264 : LHS((void*)(intptr_t)Val), LHSKind(DecUIKind), RHSKind(EmptyKind) {
267 /// Construct a twine to print \arg Val as a signed decimal integer.
268 explicit Twine(int Val)
269 : LHS((void*)(intptr_t)Val), LHSKind(DecIKind), RHSKind(EmptyKind) {
272 /// Construct a twine to print \arg Val as an unsigned decimal integer.
273 explicit Twine(const unsigned long &Val)
274 : LHS(&Val), LHSKind(DecULKind), RHSKind(EmptyKind) {
277 /// Construct a twine to print \arg Val as a signed decimal integer.
278 explicit Twine(const long &Val)
279 : LHS(&Val), LHSKind(DecLKind), RHSKind(EmptyKind) {
282 /// Construct a twine to print \arg Val as an unsigned decimal integer.
283 explicit Twine(const unsigned long long &Val)
284 : LHS(&Val), LHSKind(DecULLKind), RHSKind(EmptyKind) {
287 /// Construct a twine to print \arg Val as a signed decimal integer.
288 explicit Twine(const long long &Val)
289 : LHS(&Val), LHSKind(DecLLKind), RHSKind(EmptyKind) {
292 // FIXME: Unfortunately, to make sure this is as efficient as possible we
293 // need extra binary constructors from particular types. We can't rely on
294 // the compiler to be smart enough to fold operator+()/concat() down to the
297 /// Construct as the concatenation of a C string and a StringRef.
298 /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
299 : LHS(_LHS), RHS(&_RHS), LHSKind(CStringKind), RHSKind(StringRefKind) {
300 assert(isValid() && "Invalid twine!");
303 /// Construct as the concatenation of a StringRef and a C string.
304 /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
305 : LHS(&_LHS), RHS(_RHS), LHSKind(StringRefKind), RHSKind(CStringKind) {
306 assert(isValid() && "Invalid twine!");
309 /// Create a 'null' string, which is an empty string that always
310 /// concatenates to form another empty string.
311 static Twine createNull() {
312 return Twine(NullKind);
316 /// @name Numeric Conversions
319 // Construct a twine to print \arg Val as an unsigned hexadecimal integer.
320 static Twine utohexstr(const uint64_t &Val) {
321 return Twine(&Val, UHexKind, 0, EmptyKind);
325 /// @name Predicate Operations
328 /// isTriviallyEmpty - Check if this twine is trivially empty; a false
329 /// return value does not necessarily mean the twine is empty.
330 bool isTriviallyEmpty() const {
334 /// isSingleStringRef - Return true if this twine can be dynamically
335 /// accessed as a single StringRef value with getSingleStringRef().
336 bool isSingleStringRef() const {
337 if (getRHSKind() != EmptyKind) return false;
339 switch (getLHSKind()) {
351 /// @name String Operations
354 Twine concat(const Twine &Suffix) const;
357 /// @name Output & Conversion.
360 /// str - Return the twine contents as a std::string.
361 std::string str() const;
363 /// toVector - Write the concatenated string into the given SmallString or
365 void toVector(SmallVectorImpl<char> &Out) const;
367 /// getSingleStringRef - This returns the twine as a single StringRef. This
368 /// method is only valid if isSingleStringRef() is true.
369 StringRef getSingleStringRef() const {
370 assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
371 switch (getLHSKind()) {
372 default: assert(0 && "Out of sync with isSingleStringRef");
373 case EmptyKind: return StringRef();
374 case CStringKind: return StringRef((const char*)LHS);
375 case StdStringKind: return StringRef(*(const std::string*)LHS);
376 case StringRefKind: return *(const StringRef*)LHS;
380 /// toStringRef - This returns the twine as a single StringRef if it can be
381 /// represented as such. Otherwise the twine is written into the given
382 /// SmallVector and a StringRef to the SmallVector's data is returned.
383 StringRef toStringRef(SmallVectorImpl<char> &Out) const;
385 /// print - Write the concatenated string represented by this twine to the
387 void print(raw_ostream &OS) const;
389 /// dump - Dump the concatenated string represented by this twine to stderr.
392 /// print - Write the representation of this twine to the stream \arg OS.
393 void printRepr(raw_ostream &OS) const;
395 /// dumpRepr - Dump the representation of this twine to stderr.
396 void dumpRepr() const;
401 /// @name Twine Inline Implementations
404 inline Twine Twine::concat(const Twine &Suffix) const {
405 // Concatenation with null is null.
406 if (isNull() || Suffix.isNull())
407 return Twine(NullKind);
409 // Concatenation with empty yields the other side.
412 if (Suffix.isEmpty())
415 // Otherwise we need to create a new node, taking care to fold in unary
417 const void *NewLHS = this, *NewRHS = &Suffix;
418 NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
421 NewLHSKind = getLHSKind();
423 if (Suffix.isUnary()) {
425 NewRHSKind = Suffix.getLHSKind();
428 return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
431 inline Twine operator+(const Twine &LHS, const Twine &RHS) {
432 return LHS.concat(RHS);
435 /// Additional overload to guarantee simplified codegen; this is equivalent to
438 inline Twine operator+(const char *LHS, const StringRef &RHS) {
439 return Twine(LHS, RHS);
442 /// Additional overload to guarantee simplified codegen; this is equivalent to
445 inline Twine operator+(const StringRef &LHS, const char *RHS) {
446 return Twine(LHS, RHS);
449 inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {