LLVM API Documentation

Twine.h
Go to the documentation of this file.
00001 //===-- Twine.h - Fast Temporary String Concatenation -----------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #ifndef LLVM_ADT_TWINE_H
00011 #define LLVM_ADT_TWINE_H
00012 
00013 #include "llvm/ADT/StringRef.h"
00014 #include "llvm/Support/DataTypes.h"
00015 #include "llvm/Support/ErrorHandling.h"
00016 #include <cassert>
00017 #include <string>
00018 
00019 namespace llvm {
00020   template <typename T>
00021   class SmallVectorImpl;
00022   class StringRef;
00023   class raw_ostream;
00024 
00025   /// Twine - A lightweight data structure for efficiently representing the
00026   /// concatenation of temporary values as strings.
00027   ///
00028   /// A Twine is a kind of rope, it represents a concatenated string using a
00029   /// binary-tree, where the string is the preorder of the nodes. Since the
00030   /// Twine can be efficiently rendered into a buffer when its result is used,
00031   /// it avoids the cost of generating temporary values for intermediate string
00032   /// results -- particularly in cases when the Twine result is never
00033   /// required. By explicitly tracking the type of leaf nodes, we can also avoid
00034   /// the creation of temporary strings for conversions operations (such as
00035   /// appending an integer to a string).
00036   ///
00037   /// A Twine is not intended for use directly and should not be stored, its
00038   /// implementation relies on the ability to store pointers to temporary stack
00039   /// objects which may be deallocated at the end of a statement. Twines should
00040   /// only be used accepted as const references in arguments, when an API wishes
00041   /// to accept possibly-concatenated strings.
00042   ///
00043   /// Twines support a special 'null' value, which always concatenates to form
00044   /// itself, and renders as an empty string. This can be returned from APIs to
00045   /// effectively nullify any concatenations performed on the result.
00046   ///
00047   /// \b Implementation
00048   ///
00049   /// Given the nature of a Twine, it is not possible for the Twine's
00050   /// concatenation method to construct interior nodes; the result must be
00051   /// represented inside the returned value. For this reason a Twine object
00052   /// actually holds two values, the left- and right-hand sides of a
00053   /// concatenation. We also have nullary Twine objects, which are effectively
00054   /// sentinel values that represent empty strings.
00055   ///
00056   /// Thus, a Twine can effectively have zero, one, or two children. The \see
00057   /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
00058   /// testing the number of children.
00059   ///
00060   /// We maintain a number of invariants on Twine objects (FIXME: Why):
00061   ///  - Nullary twines are always represented with their Kind on the left-hand
00062   ///    side, and the Empty kind on the right-hand side.
00063   ///  - Unary twines are always represented with the value on the left-hand
00064   ///    side, and the Empty kind on the right-hand side.
00065   ///  - If a Twine has another Twine as a child, that child should always be
00066   ///    binary (otherwise it could have been folded into the parent).
00067   ///
00068   /// These invariants are check by \see isValid().
00069   ///
00070   /// \b Efficiency Considerations
00071   ///
00072   /// The Twine is designed to yield efficient and small code for common
00073   /// situations. For this reason, the concat() method is inlined so that
00074   /// concatenations of leaf nodes can be optimized into stores directly into a
00075   /// single stack allocated object.
00076   ///
00077   /// In practice, not all compilers can be trusted to optimize concat() fully,
00078   /// so we provide two additional methods (and accompanying operator+
00079   /// overloads) to guarantee that particularly important cases (cstring plus
00080   /// StringRef) codegen as desired.
00081   class Twine {
00082     /// NodeKind - Represent the type of an argument.
00083     enum NodeKind {
00084       /// An empty string; the result of concatenating anything with it is also
00085       /// empty.
00086       NullKind,
00087 
00088       /// The empty string.
00089       EmptyKind,
00090 
00091       /// A pointer to a Twine instance.
00092       TwineKind,
00093 
00094       /// A pointer to a C string instance.
00095       CStringKind,
00096 
00097       /// A pointer to an std::string instance.
00098       StdStringKind,
00099 
00100       /// A pointer to a StringRef instance.
00101       StringRefKind,
00102 
00103       /// A char value reinterpreted as a pointer, to render as a character.
00104       CharKind,
00105 
00106       /// An unsigned int value reinterpreted as a pointer, to render as an
00107       /// unsigned decimal integer.
00108       DecUIKind,
00109 
00110       /// An int value reinterpreted as a pointer, to render as a signed
00111       /// decimal integer.
00112       DecIKind,
00113 
00114       /// A pointer to an unsigned long value, to render as an unsigned decimal
00115       /// integer.
00116       DecULKind,
00117 
00118       /// A pointer to a long value, to render as a signed decimal integer.
00119       DecLKind,
00120 
00121       /// A pointer to an unsigned long long value, to render as an unsigned
00122       /// decimal integer.
00123       DecULLKind,
00124 
00125       /// A pointer to a long long value, to render as a signed decimal integer.
00126       DecLLKind,
00127 
00128       /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
00129       /// integer.
00130       UHexKind
00131     };
00132 
00133     union Child
00134     {
00135       const Twine *twine;
00136       const char *cString;
00137       const std::string *stdString;
00138       const StringRef *stringRef;
00139       char character;
00140       unsigned int decUI;
00141       int decI;
00142       const unsigned long *decUL;
00143       const long *decL;
00144       const unsigned long long *decULL;
00145       const long long *decLL;
00146       const uint64_t *uHex;
00147     };
00148 
00149   private:
00150     /// LHS - The prefix in the concatenation, which may be uninitialized for
00151     /// Null or Empty kinds.
00152     Child LHS;
00153     /// RHS - The suffix in the concatenation, which may be uninitialized for
00154     /// Null or Empty kinds.
00155     Child RHS;
00156     // enums stored as unsigned chars to save on space while some compilers
00157     // don't support specifying the backing type for an enum
00158     /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
00159     unsigned char LHSKind;
00160     /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
00161     unsigned char RHSKind;
00162 
00163   private:
00164     /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
00165     explicit Twine(NodeKind Kind)
00166       : LHSKind(Kind), RHSKind(EmptyKind) {
00167       assert(isNullary() && "Invalid kind!");
00168     }
00169 
00170     /// Construct a binary twine.
00171     explicit Twine(const Twine &_LHS, const Twine &_RHS)
00172       : LHSKind(TwineKind), RHSKind(TwineKind) {
00173       LHS.twine = &_LHS;
00174       RHS.twine = &_RHS;
00175       assert(isValid() && "Invalid twine!");
00176     }
00177 
00178     /// Construct a twine from explicit values.
00179     explicit Twine(Child _LHS, NodeKind _LHSKind,
00180                    Child _RHS, NodeKind _RHSKind)
00181       : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
00182       assert(isValid() && "Invalid twine!");
00183     }
00184 
00185     /// isNull - Check for the null twine.
00186     bool isNull() const {
00187       return getLHSKind() == NullKind;
00188     }
00189 
00190     /// isEmpty - Check for the empty twine.
00191     bool isEmpty() const {
00192       return getLHSKind() == EmptyKind;
00193     }
00194 
00195     /// isNullary - Check if this is a nullary twine (null or empty).
00196     bool isNullary() const {
00197       return isNull() || isEmpty();
00198     }
00199 
00200     /// isUnary - Check if this is a unary twine.
00201     bool isUnary() const {
00202       return getRHSKind() == EmptyKind && !isNullary();
00203     }
00204 
00205     /// isBinary - Check if this is a binary twine.
00206     bool isBinary() const {
00207       return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
00208     }
00209 
00210     /// isValid - Check if this is a valid twine (satisfying the invariants on
00211     /// order and number of arguments).
00212     bool isValid() const {
00213       // Nullary twines always have Empty on the RHS.
00214       if (isNullary() && getRHSKind() != EmptyKind)
00215         return false;
00216 
00217       // Null should never appear on the RHS.
00218       if (getRHSKind() == NullKind)
00219         return false;
00220 
00221       // The RHS cannot be non-empty if the LHS is empty.
00222       if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
00223         return false;
00224 
00225       // A twine child should always be binary.
00226       if (getLHSKind() == TwineKind &&
00227           !LHS.twine->isBinary())
00228         return false;
00229       if (getRHSKind() == TwineKind &&
00230           !RHS.twine->isBinary())
00231         return false;
00232 
00233       return true;
00234     }
00235 
00236     /// getLHSKind - Get the NodeKind of the left-hand side.
00237     NodeKind getLHSKind() const { return (NodeKind) LHSKind; }
00238 
00239     /// getRHSKind - Get the NodeKind of the right-hand side.
00240     NodeKind getRHSKind() const { return (NodeKind) RHSKind; }
00241 
00242     /// printOneChild - Print one child from a twine.
00243     void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
00244 
00245     /// printOneChildRepr - Print the representation of one child from a twine.
00246     void printOneChildRepr(raw_ostream &OS, Child Ptr,
00247                            NodeKind Kind) const;
00248 
00249   public:
00250     /// @name Constructors
00251     /// @{
00252 
00253     /// Construct from an empty string.
00254     /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
00255       assert(isValid() && "Invalid twine!");
00256     }
00257 
00258     /// Construct from a C string.
00259     ///
00260     /// We take care here to optimize "" into the empty twine -- this will be
00261     /// optimized out for string constants. This allows Twine arguments have
00262     /// default "" values, without introducing unnecessary string constants.
00263     /*implicit*/ Twine(const char *Str)
00264       : RHSKind(EmptyKind) {
00265       if (Str[0] != '\0') {
00266         LHS.cString = Str;
00267         LHSKind = CStringKind;
00268       } else
00269         LHSKind = EmptyKind;
00270 
00271       assert(isValid() && "Invalid twine!");
00272     }
00273 
00274     /// Construct from an std::string.
00275     /*implicit*/ Twine(const std::string &Str)
00276       : LHSKind(StdStringKind), RHSKind(EmptyKind) {
00277       LHS.stdString = &Str;
00278       assert(isValid() && "Invalid twine!");
00279     }
00280 
00281     /// Construct from a StringRef.
00282     /*implicit*/ Twine(const StringRef &Str)
00283       : LHSKind(StringRefKind), RHSKind(EmptyKind) {
00284       LHS.stringRef = &Str;
00285       assert(isValid() && "Invalid twine!");
00286     }
00287 
00288     /// Construct from a char.
00289     explicit Twine(char Val)
00290       : LHSKind(CharKind), RHSKind(EmptyKind) {
00291       LHS.character = Val;
00292     }
00293 
00294     /// Construct from a signed char.
00295     explicit Twine(signed char Val)
00296       : LHSKind(CharKind), RHSKind(EmptyKind) {
00297       LHS.character = static_cast<char>(Val);
00298     }
00299 
00300     /// Construct from an unsigned char.
00301     explicit Twine(unsigned char Val)
00302       : LHSKind(CharKind), RHSKind(EmptyKind) {
00303       LHS.character = static_cast<char>(Val);
00304     }
00305 
00306     /// Construct a twine to print \p Val as an unsigned decimal integer.
00307     explicit Twine(unsigned Val)
00308       : LHSKind(DecUIKind), RHSKind(EmptyKind) {
00309       LHS.decUI = Val;
00310     }
00311 
00312     /// Construct a twine to print \p Val as a signed decimal integer.
00313     explicit Twine(int Val)
00314       : LHSKind(DecIKind), RHSKind(EmptyKind) {
00315       LHS.decI = Val;
00316     }
00317 
00318     /// Construct a twine to print \p Val as an unsigned decimal integer.
00319     explicit Twine(const unsigned long &Val)
00320       : LHSKind(DecULKind), RHSKind(EmptyKind) {
00321       LHS.decUL = &Val;
00322     }
00323 
00324     /// Construct a twine to print \p Val as a signed decimal integer.
00325     explicit Twine(const long &Val)
00326       : LHSKind(DecLKind), RHSKind(EmptyKind) {
00327       LHS.decL = &Val;
00328     }
00329 
00330     /// Construct a twine to print \p Val as an unsigned decimal integer.
00331     explicit Twine(const unsigned long long &Val)
00332       : LHSKind(DecULLKind), RHSKind(EmptyKind) {
00333       LHS.decULL = &Val;
00334     }
00335 
00336     /// Construct a twine to print \p Val as a signed decimal integer.
00337     explicit Twine(const long long &Val)
00338       : LHSKind(DecLLKind), RHSKind(EmptyKind) {
00339       LHS.decLL = &Val;
00340     }
00341 
00342     // FIXME: Unfortunately, to make sure this is as efficient as possible we
00343     // need extra binary constructors from particular types. We can't rely on
00344     // the compiler to be smart enough to fold operator+()/concat() down to the
00345     // right thing. Yet.
00346 
00347     /// Construct as the concatenation of a C string and a StringRef.
00348     /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
00349       : LHSKind(CStringKind), RHSKind(StringRefKind) {
00350       LHS.cString = _LHS;
00351       RHS.stringRef = &_RHS;
00352       assert(isValid() && "Invalid twine!");
00353     }
00354 
00355     /// Construct as the concatenation of a StringRef and a C string.
00356     /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
00357       : LHSKind(StringRefKind), RHSKind(CStringKind) {
00358       LHS.stringRef = &_LHS;
00359       RHS.cString = _RHS;
00360       assert(isValid() && "Invalid twine!");
00361     }
00362 
00363     /// Create a 'null' string, which is an empty string that always
00364     /// concatenates to form another empty string.
00365     static Twine createNull() {
00366       return Twine(NullKind);
00367     }
00368 
00369     /// @}
00370     /// @name Numeric Conversions
00371     /// @{
00372 
00373     // Construct a twine to print \p Val as an unsigned hexadecimal integer.
00374     static Twine utohexstr(const uint64_t &Val) {
00375       Child LHS, RHS;
00376       LHS.uHex = &Val;
00377       RHS.twine = nullptr;
00378       return Twine(LHS, UHexKind, RHS, EmptyKind);
00379     }
00380 
00381     /// @}
00382     /// @name Predicate Operations
00383     /// @{
00384 
00385     /// isTriviallyEmpty - Check if this twine is trivially empty; a false
00386     /// return value does not necessarily mean the twine is empty.
00387     bool isTriviallyEmpty() const {
00388       return isNullary();
00389     }
00390 
00391     /// isSingleStringRef - Return true if this twine can be dynamically
00392     /// accessed as a single StringRef value with getSingleStringRef().
00393     bool isSingleStringRef() const {
00394       if (getRHSKind() != EmptyKind) return false;
00395 
00396       switch (getLHSKind()) {
00397       case EmptyKind:
00398       case CStringKind:
00399       case StdStringKind:
00400       case StringRefKind:
00401         return true;
00402       default:
00403         return false;
00404       }
00405     }
00406 
00407     /// @}
00408     /// @name String Operations
00409     /// @{
00410 
00411     Twine concat(const Twine &Suffix) const;
00412 
00413     /// @}
00414     /// @name Output & Conversion.
00415     /// @{
00416 
00417     /// str - Return the twine contents as a std::string.
00418     std::string str() const;
00419 
00420     /// toVector - Write the concatenated string into the given SmallString or
00421     /// SmallVector.
00422     void toVector(SmallVectorImpl<char> &Out) const;
00423 
00424     /// getSingleStringRef - This returns the twine as a single StringRef.  This
00425     /// method is only valid if isSingleStringRef() is true.
00426     StringRef getSingleStringRef() const {
00427       assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
00428       switch (getLHSKind()) {
00429       default: llvm_unreachable("Out of sync with isSingleStringRef");
00430       case EmptyKind:      return StringRef();
00431       case CStringKind:    return StringRef(LHS.cString);
00432       case StdStringKind:  return StringRef(*LHS.stdString);
00433       case StringRefKind:  return *LHS.stringRef;
00434       }
00435     }
00436 
00437     /// toStringRef - This returns the twine as a single StringRef if it can be
00438     /// represented as such. Otherwise the twine is written into the given
00439     /// SmallVector and a StringRef to the SmallVector's data is returned.
00440     StringRef toStringRef(SmallVectorImpl<char> &Out) const;
00441 
00442     /// toNullTerminatedStringRef - This returns the twine as a single null
00443     /// terminated StringRef if it can be represented as such. Otherwise the
00444     /// twine is written into the given SmallVector and a StringRef to the
00445     /// SmallVector's data is returned.
00446     ///
00447     /// The returned StringRef's size does not include the null terminator.
00448     StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
00449 
00450     /// Write the concatenated string represented by this twine to the
00451     /// stream \p OS.
00452     void print(raw_ostream &OS) const;
00453 
00454     /// Dump the concatenated string represented by this twine to stderr.
00455     void dump() const;
00456 
00457     /// Write the representation of this twine to the stream \p OS.
00458     void printRepr(raw_ostream &OS) const;
00459 
00460     /// Dump the representation of this twine to stderr.
00461     void dumpRepr() const;
00462 
00463     /// @}
00464   };
00465 
00466   /// @name Twine Inline Implementations
00467   /// @{
00468 
00469   inline Twine Twine::concat(const Twine &Suffix) const {
00470     // Concatenation with null is null.
00471     if (isNull() || Suffix.isNull())
00472       return Twine(NullKind);
00473 
00474     // Concatenation with empty yields the other side.
00475     if (isEmpty())
00476       return Suffix;
00477     if (Suffix.isEmpty())
00478       return *this;
00479 
00480     // Otherwise we need to create a new node, taking care to fold in unary
00481     // twines.
00482     Child NewLHS, NewRHS;
00483     NewLHS.twine = this;
00484     NewRHS.twine = &Suffix;
00485     NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
00486     if (isUnary()) {
00487       NewLHS = LHS;
00488       NewLHSKind = getLHSKind();
00489     }
00490     if (Suffix.isUnary()) {
00491       NewRHS = Suffix.LHS;
00492       NewRHSKind = Suffix.getLHSKind();
00493     }
00494 
00495     return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
00496   }
00497 
00498   inline Twine operator+(const Twine &LHS, const Twine &RHS) {
00499     return LHS.concat(RHS);
00500   }
00501 
00502   /// Additional overload to guarantee simplified codegen; this is equivalent to
00503   /// concat().
00504 
00505   inline Twine operator+(const char *LHS, const StringRef &RHS) {
00506     return Twine(LHS, RHS);
00507   }
00508 
00509   /// Additional overload to guarantee simplified codegen; this is equivalent to
00510   /// concat().
00511 
00512   inline Twine operator+(const StringRef &LHS, const char *RHS) {
00513     return Twine(LHS, RHS);
00514   }
00515 
00516   inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
00517     RHS.print(OS);
00518     return OS;
00519   }
00520 
00521   /// @}
00522 }
00523 
00524 #endif