Twine.h revision 326990f1eb7ff005adabe46a1f982eff8835813e
1//===-- Twine.h - Fast Temporary String Concatenation -----------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef LLVM_ADT_TWINE_H
11#define LLVM_ADT_TWINE_H
12
13#include "llvm/ADT/StringRef.h"
14#include "llvm/System/DataTypes.h"
15#include <cassert>
16#include <string>
17
18namespace llvm {
19  template <typename T>
20  class SmallVectorImpl;
21  class StringRef;
22  class raw_ostream;
23
24  /// Twine - A lightweight data structure for efficiently representing the
25  /// concatenation of temporary values as strings.
26  ///
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).
35  ///
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.
41  ///
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.
45  ///
46  /// \b Implementation \n
47  ///
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.
54  ///
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.
58  ///
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).
66  ///
67  /// These invariants are check by \see isValid().
68  ///
69  /// \b Efficiency Considerations \n
70  ///
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.
75  ///
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.
80  class Twine {
81    /// NodeKind - Represent the type of an argument.
82    enum NodeKind {
83      /// An empty string; the result of concatenating anything with it is also
84      /// empty.
85      NullKind,
86
87      /// The empty string.
88      EmptyKind,
89
90      /// A pointer to a Twine instance.
91      TwineKind,
92
93      /// A pointer to a C string instance.
94      CStringKind,
95
96      /// A pointer to an std::string instance.
97      StdStringKind,
98
99      /// A pointer to a StringRef instance.
100      StringRefKind,
101
102      /// An unsigned int value reinterpreted as a pointer, to render as an
103      /// unsigned decimal integer.
104      DecUIKind,
105
106      /// An int value reinterpreted as a pointer, to render as a signed
107      /// decimal integer.
108      DecIKind,
109
110      /// A pointer to an unsigned long value, to render as an unsigned decimal
111      /// integer.
112      DecULKind,
113
114      /// A pointer to a long value, to render as a signed decimal integer.
115      DecLKind,
116
117      /// A pointer to an unsigned long long value, to render as an unsigned
118      /// decimal integer.
119      DecULLKind,
120
121      /// A pointer to a long long value, to render as a signed decimal integer.
122      DecLLKind,
123
124      /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
125      /// integer.
126      UHexKind
127    };
128
129  private:
130    /// LHS - The prefix in the concatenation, which may be uninitialized for
131    /// Null or Empty kinds.
132    const void *LHS;
133    /// RHS - The suffix in the concatenation, which may be uninitialized for
134    /// Null or Empty kinds.
135    const void *RHS;
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;
140
141  private:
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!");
146    }
147
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!");
152    }
153
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!");
159    }
160
161    /// isNull - Check for the null twine.
162    bool isNull() const {
163      return getLHSKind() == NullKind;
164    }
165
166    /// isEmpty - Check for the empty twine.
167    bool isEmpty() const {
168      return getLHSKind() == EmptyKind;
169    }
170
171    /// isNullary - Check if this is a nullary twine (null or empty).
172    bool isNullary() const {
173      return isNull() || isEmpty();
174    }
175
176    /// isUnary - Check if this is a unary twine.
177    bool isUnary() const {
178      return getRHSKind() == EmptyKind && !isNullary();
179    }
180
181    /// isBinary - Check if this is a binary twine.
182    bool isBinary() const {
183      return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
184    }
185
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)
191        return false;
192
193      // Null should never appear on the RHS.
194      if (getRHSKind() == NullKind)
195        return false;
196
197      // The RHS cannot be non-empty if the LHS is empty.
198      if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
199        return false;
200
201      // A twine child should always be binary.
202      if (getLHSKind() == TwineKind &&
203          !static_cast<const Twine*>(LHS)->isBinary())
204        return false;
205      if (getRHSKind() == TwineKind &&
206          !static_cast<const Twine*>(RHS)->isBinary())
207        return false;
208
209      return true;
210    }
211
212    /// getLHSKind - Get the NodeKind of the left-hand side.
213    NodeKind getLHSKind() const { return (NodeKind) LHSKind; }
214
215    /// getRHSKind - Get the NodeKind of the left-hand side.
216    NodeKind getRHSKind() const { return (NodeKind) RHSKind; }
217
218    /// printOneChild - Print one child from a twine.
219    void printOneChild(raw_ostream &OS, const void *Ptr, NodeKind Kind) const;
220
221    /// printOneChildRepr - Print the representation of one child from a twine.
222    void printOneChildRepr(raw_ostream &OS, const void *Ptr,
223                           NodeKind Kind) const;
224
225  public:
226    /// @name Constructors
227    /// @{
228
229    /// Construct from an empty string.
230    /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
231      assert(isValid() && "Invalid twine!");
232    }
233
234    /// Construct from a C string.
235    ///
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') {
242        LHS = Str;
243        LHSKind = CStringKind;
244      } else
245        LHSKind = EmptyKind;
246
247      assert(isValid() && "Invalid twine!");
248    }
249
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!");
254    }
255
256    /// Construct from a StringRef.
257    /*implicit*/ Twine(const StringRef &Str)
258      : LHS(&Str), LHSKind(StringRefKind), RHSKind(EmptyKind) {
259      assert(isValid() && "Invalid twine!");
260    }
261
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) {
265    }
266
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) {
270    }
271
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) {
275    }
276
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) {
280    }
281
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) {
285    }
286
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) {
290    }
291
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
295    // right thing. Yet.
296
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!");
301    }
302
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!");
307    }
308
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);
313    }
314
315    /// @}
316    /// @name Numeric Conversions
317    /// @{
318
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);
322    }
323
324    /// @}
325    /// @name Predicate Operations
326    /// @{
327
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 {
331      return isNullary();
332    }
333
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;
338
339      switch (getLHSKind()) {
340      case EmptyKind:
341      case CStringKind:
342      case StdStringKind:
343      case StringRefKind:
344        return true;
345      default:
346        return false;
347      }
348    }
349
350    /// @}
351    /// @name String Operations
352    /// @{
353
354    Twine concat(const Twine &Suffix) const;
355
356    /// @}
357    /// @name Output & Conversion.
358    /// @{
359
360    /// str - Return the twine contents as a std::string.
361    std::string str() const;
362
363    /// toVector - Write the concatenated string into the given SmallString or
364    /// SmallVector.
365    void toVector(SmallVectorImpl<char> &Out) const;
366
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;
377      }
378    }
379
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;
384
385    /// print - Write the concatenated string represented by this twine to the
386    /// stream \arg OS.
387    void print(raw_ostream &OS) const;
388
389    /// dump - Dump the concatenated string represented by this twine to stderr.
390    void dump() const;
391
392    /// print - Write the representation of this twine to the stream \arg OS.
393    void printRepr(raw_ostream &OS) const;
394
395    /// dumpRepr - Dump the representation of this twine to stderr.
396    void dumpRepr() const;
397
398    /// @}
399  };
400
401  /// @name Twine Inline Implementations
402  /// @{
403
404  inline Twine Twine::concat(const Twine &Suffix) const {
405    // Concatenation with null is null.
406    if (isNull() || Suffix.isNull())
407      return Twine(NullKind);
408
409    // Concatenation with empty yields the other side.
410    if (isEmpty())
411      return Suffix;
412    if (Suffix.isEmpty())
413      return *this;
414
415    // Otherwise we need to create a new node, taking care to fold in unary
416    // twines.
417    const void *NewLHS = this, *NewRHS = &Suffix;
418    NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
419    if (isUnary()) {
420      NewLHS = LHS;
421      NewLHSKind = getLHSKind();
422    }
423    if (Suffix.isUnary()) {
424      NewRHS = Suffix.LHS;
425      NewRHSKind = Suffix.getLHSKind();
426    }
427
428    return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
429  }
430
431  inline Twine operator+(const Twine &LHS, const Twine &RHS) {
432    return LHS.concat(RHS);
433  }
434
435  /// Additional overload to guarantee simplified codegen; this is equivalent to
436  /// concat().
437
438  inline Twine operator+(const char *LHS, const StringRef &RHS) {
439    return Twine(LHS, RHS);
440  }
441
442  /// Additional overload to guarantee simplified codegen; this is equivalent to
443  /// concat().
444
445  inline Twine operator+(const StringRef &LHS, const char *RHS) {
446    return Twine(LHS, RHS);
447  }
448
449  inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
450    RHS.print(OS);
451    return OS;
452  }
453
454  /// @}
455}
456
457#endif
458