Twine.h revision 37e3fe9ad7d7cb350cbbce0695c68d652d624bb4
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/Support/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      /// A pointer to a uint64_t value, to render as an unsigned decimal
103      /// integer.
104      UDecKind,
105
106      /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
107      /// integer.
108      UHexKind,
109
110      /// A pointer to a uint64_t value, to render as a signed decimal integer.
111      SDecKind
112    };
113
114  private:
115    /// LHS - The prefix in the concatenation, which may be uninitialized for
116    /// Null or Empty kinds.
117    const void *LHS;
118    /// RHS - The suffix in the concatenation, which may be uninitialized for
119    /// Null or Empty kinds.
120    const void *RHS;
121    /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
122    NodeKind LHSKind : 8;
123    /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
124    NodeKind RHSKind : 8;
125
126  private:
127    /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
128    explicit Twine(NodeKind Kind)
129      : LHSKind(Kind), RHSKind(EmptyKind) {
130      assert(isNullary() && "Invalid kind!");
131    }
132
133    /// Construct a binary twine.
134    explicit Twine(const Twine &_LHS, const Twine &_RHS)
135      : LHS(&_LHS), RHS(&_RHS), LHSKind(TwineKind), RHSKind(TwineKind) {
136      assert(isValid() && "Invalid twine!");
137    }
138
139    /// Construct a twine from explicit values.
140    explicit Twine(const void *_LHS, NodeKind _LHSKind,
141                   const void *_RHS, NodeKind _RHSKind)
142      : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
143      assert(isValid() && "Invalid twine!");
144    }
145
146    /// isNull - Check for the null twine.
147    bool isNull() const {
148      return getLHSKind() == NullKind;
149    }
150
151    /// isEmpty - Check for the empty twine.
152    bool isEmpty() const {
153      return getLHSKind() == EmptyKind;
154    }
155
156    /// isNullary - Check if this is a nullary twine (null or empty).
157    bool isNullary() const {
158      return isNull() || isEmpty();
159    }
160
161    /// isUnary - Check if this is a unary twine.
162    bool isUnary() const {
163      return getRHSKind() == EmptyKind && !isNullary();
164    }
165
166    /// isBinary - Check if this is a binary twine.
167    bool isBinary() const {
168      return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
169    }
170
171    /// isValid - Check if this is a valid twine (satisfying the invariants on
172    /// order and number of arguments).
173    bool isValid() const {
174      // Nullary twines always have Empty on the RHS.
175      if (isNullary() && getRHSKind() != EmptyKind)
176        return false;
177
178      // Null should never appear on the RHS.
179      if (getRHSKind() == NullKind)
180        return false;
181
182      // The RHS cannot be non-empty if the LHS is empty.
183      if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
184        return false;
185
186      // A twine child should always be binary.
187      if (getLHSKind() == TwineKind &&
188          !static_cast<const Twine*>(LHS)->isBinary())
189        return false;
190      if (getRHSKind() == TwineKind &&
191          !static_cast<const Twine*>(RHS)->isBinary())
192        return false;
193
194      return true;
195    }
196
197    /// getLHSKind - Get the NodeKind of the left-hand side.
198    NodeKind getLHSKind() const { return LHSKind; }
199
200    /// getRHSKind - Get the NodeKind of the left-hand side.
201    NodeKind getRHSKind() const { return RHSKind; }
202
203    /// printOneChild - Print one child from a twine.
204    void printOneChild(raw_ostream &OS, const void *Ptr, NodeKind Kind) const;
205
206    /// printOneChildRepr - Print the representation of one child from a twine.
207    void printOneChildRepr(raw_ostream &OS, const void *Ptr,
208                           NodeKind Kind) const;
209
210  public:
211    /// @name Constructors
212    /// @{
213
214    /// Construct from an empty string.
215    /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
216      assert(isValid() && "Invalid twine!");
217    }
218
219    /// Construct from a C string.
220    ///
221    /// We take care here to optimize "" into the empty twine -- this will be
222    /// optimized out for string constants. This allows Twine arguments have
223    /// default "" values, without introducing unnecessary string constants.
224    /*implicit*/ Twine(const char *Str)
225      : RHSKind(EmptyKind) {
226      if (Str[0] != '\0') {
227        LHS = Str;
228        LHSKind = CStringKind;
229      } else
230        LHSKind = EmptyKind;
231
232      assert(isValid() && "Invalid twine!");
233    }
234
235    /// Construct from an std::string.
236    /*implicit*/ Twine(const std::string &Str)
237      : LHS(&Str), LHSKind(StdStringKind), RHSKind(EmptyKind) {
238      assert(isValid() && "Invalid twine!");
239    }
240
241    /// Construct from a StringRef.
242    /*implicit*/ Twine(const StringRef &Str)
243      : LHS(&Str), LHSKind(StringRefKind), RHSKind(EmptyKind) {
244      assert(isValid() && "Invalid twine!");
245    }
246
247    // FIXME: Unfortunately, to make sure this is as efficient as possible we
248    // need extra binary constructors from particular types. We can't rely on
249    // the compiler to be smart enough to fold operator+()/concat() down to the
250    // right thing. Yet.
251
252    /// Construct as the concatenation of a C string and a StringRef.
253    /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
254      : LHS(_LHS), RHS(&_RHS), LHSKind(CStringKind), RHSKind(StringRefKind) {
255      assert(isValid() && "Invalid twine!");
256    }
257
258    /// Construct as the concatenation of a StringRef and a C string.
259    /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
260      : LHS(&_LHS), RHS(_RHS), LHSKind(StringRefKind), RHSKind(CStringKind) {
261      assert(isValid() && "Invalid twine!");
262    }
263
264    /// Create a 'null' string, which is an empty string that always
265    /// concatenates to form another empty string.
266    static Twine createNull() {
267      return Twine(NullKind);
268    }
269
270    /// @}
271    /// @name Numeric Conversions
272    /// @{
273
274    /// Construct a twine to print \arg Val as an unsigned decimal integer.
275    static Twine utostr(const uint64_t &Val) {
276      return Twine(&Val, UDecKind, 0, EmptyKind);
277    }
278
279    /// Construct a twine to print \arg Val as a signed decimal integer.
280    static Twine itostr(const int64_t &Val) {
281      return Twine(&Val, SDecKind, 0, EmptyKind);
282    }
283
284    // Construct a twine to print \arg Val as an unsigned hexadecimal integer.
285    static Twine utohexstr(const uint64_t &Val) {
286      return Twine(&Val, UHexKind, 0, EmptyKind);
287    }
288
289    // Construct a twine to print \arg Val as an unsigned hexadecimal
290    // integer. This routine is provided as a convenience to sign extend values
291    // before printing.
292    static Twine itohexstr(const int64_t &Val) {
293      return Twine(&Val, UHexKind, 0, EmptyKind);
294    }
295
296    /// @}
297    /// @name String Operations
298    /// @{
299
300    Twine concat(const Twine &Suffix) const;
301
302    /// @}
303    /// @name Output & Conversion.
304    /// @{
305
306    /// str - Return the twine contents as a std::string.
307    std::string str() const;
308
309    /// toVector - Write the concatenated string into the given SmallString or
310    /// SmallVector.
311    void toVector(SmallVectorImpl<char> &Out) const;
312
313    /// print - Write the concatenated string represented by this twine to the
314    /// stream \arg OS.
315    void print(raw_ostream &OS) const;
316
317    /// dump - Dump the concatenated string represented by this twine to stderr.
318    void dump() const;
319
320    /// print - Write the representation of this twine to the stream \arg OS.
321    void printRepr(raw_ostream &OS) const;
322
323    /// dumpRepr - Dump the representation of this twine to stderr.
324    void dumpRepr() const;
325
326    /// @}
327  };
328
329  /// @name Twine Inline Implementations
330  /// @{
331
332  inline Twine Twine::concat(const Twine &Suffix) const {
333    // Concatenation with null is null.
334    if (isNull() || Suffix.isNull())
335      return Twine(NullKind);
336
337    // Concatenation with empty yields the other side.
338    if (isEmpty())
339      return Suffix;
340    if (Suffix.isEmpty())
341      return *this;
342
343    // Otherwise we need to create a new node, taking care to fold in unary
344    // twines.
345    const void *NewLHS = this, *NewRHS = &Suffix;
346    NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
347    if (isUnary()) {
348      NewLHS = LHS;
349      NewLHSKind = getLHSKind();
350    }
351    if (Suffix.isUnary()) {
352      NewRHS = Suffix.LHS;
353      NewRHSKind = Suffix.getLHSKind();
354    }
355
356    return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
357  }
358
359  inline Twine operator+(const Twine &LHS, const Twine &RHS) {
360    return LHS.concat(RHS);
361  }
362
363  /// Additional overload to guarantee simplified codegen; this is equivalent to
364  /// concat().
365
366  inline Twine operator+(const char *LHS, const StringRef &RHS) {
367    return Twine(LHS, RHS);
368  }
369
370  /// Additional overload to guarantee simplified codegen; this is equivalent to
371  /// concat().
372
373  inline Twine operator+(const StringRef &LHS, const char *RHS) {
374    return Twine(LHS, RHS);
375  }
376
377  inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
378    RHS.print(OS);
379    return OS;
380  }
381
382  /// @}
383}
384
385#endif
386