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 right hand side, \see getRHSKind().
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     /// Since the intended use of twines is as temporary objects, assignments
00186     /// when concatenating might cause undefined behavior or stack corruptions
00187     Twine &operator=(const Twine &Other) LLVM_DELETED_FUNCTION;
00188 
00189     /// isNull - Check for the null twine.
00190     bool isNull() const {
00191       return getLHSKind() == NullKind;
00192     }
00193 
00194     /// isEmpty - Check for the empty twine.
00195     bool isEmpty() const {
00196       return getLHSKind() == EmptyKind;
00197     }
00198 
00199     /// isNullary - Check if this is a nullary twine (null or empty).
00200     bool isNullary() const {
00201       return isNull() || isEmpty();
00202     }
00203 
00204     /// isUnary - Check if this is a unary twine.
00205     bool isUnary() const {
00206       return getRHSKind() == EmptyKind && !isNullary();
00207     }
00208 
00209     /// isBinary - Check if this is a binary twine.
00210     bool isBinary() const {
00211       return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
00212     }
00213 
00214     /// isValid - Check if this is a valid twine (satisfying the invariants on
00215     /// order and number of arguments).
00216     bool isValid() const {
00217       // Nullary twines always have Empty on the RHS.
00218       if (isNullary() && getRHSKind() != EmptyKind)
00219         return false;
00220 
00221       // Null should never appear on the RHS.
00222       if (getRHSKind() == NullKind)
00223         return false;
00224 
00225       // The RHS cannot be non-empty if the LHS is empty.
00226       if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
00227         return false;
00228 
00229       // A twine child should always be binary.
00230       if (getLHSKind() == TwineKind &&
00231           !LHS.twine->isBinary())
00232         return false;
00233       if (getRHSKind() == TwineKind &&
00234           !RHS.twine->isBinary())
00235         return false;
00236 
00237       return true;
00238     }
00239 
00240     /// getLHSKind - Get the NodeKind of the left-hand side.
00241     NodeKind getLHSKind() const { return (NodeKind) LHSKind; }
00242 
00243     /// getRHSKind - Get the NodeKind of the right-hand side.
00244     NodeKind getRHSKind() const { return (NodeKind) RHSKind; }
00245 
00246     /// printOneChild - Print one child from a twine.
00247     void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
00248 
00249     /// printOneChildRepr - Print the representation of one child from a twine.
00250     void printOneChildRepr(raw_ostream &OS, Child Ptr,
00251                            NodeKind Kind) const;
00252 
00253   public:
00254     /// @name Constructors
00255     /// @{
00256 
00257     /// Construct from an empty string.
00258     /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
00259       assert(isValid() && "Invalid twine!");
00260     }
00261 
00262     /// Construct from a C string.
00263     ///
00264     /// We take care here to optimize "" into the empty twine -- this will be
00265     /// optimized out for string constants. This allows Twine arguments have
00266     /// default "" values, without introducing unnecessary string constants.
00267     /*implicit*/ Twine(const char *Str)
00268       : RHSKind(EmptyKind) {
00269       if (Str[0] != '\0') {
00270         LHS.cString = Str;
00271         LHSKind = CStringKind;
00272       } else
00273         LHSKind = EmptyKind;
00274 
00275       assert(isValid() && "Invalid twine!");
00276     }
00277 
00278     /// Construct from an std::string.
00279     /*implicit*/ Twine(const std::string &Str)
00280       : LHSKind(StdStringKind), RHSKind(EmptyKind) {
00281       LHS.stdString = &Str;
00282       assert(isValid() && "Invalid twine!");
00283     }
00284 
00285     /// Construct from a StringRef.
00286     /*implicit*/ Twine(const StringRef &Str)
00287       : LHSKind(StringRefKind), RHSKind(EmptyKind) {
00288       LHS.stringRef = &Str;
00289       assert(isValid() && "Invalid twine!");
00290     }
00291 
00292     /// Construct from a char.
00293     explicit Twine(char Val)
00294       : LHSKind(CharKind), RHSKind(EmptyKind) {
00295       LHS.character = Val;
00296     }
00297 
00298     /// Construct from a signed char.
00299     explicit Twine(signed char Val)
00300       : LHSKind(CharKind), RHSKind(EmptyKind) {
00301       LHS.character = static_cast<char>(Val);
00302     }
00303 
00304     /// Construct from an unsigned char.
00305     explicit Twine(unsigned char Val)
00306       : LHSKind(CharKind), RHSKind(EmptyKind) {
00307       LHS.character = static_cast<char>(Val);
00308     }
00309 
00310     /// Construct a twine to print \p Val as an unsigned decimal integer.
00311     explicit Twine(unsigned Val)
00312       : LHSKind(DecUIKind), RHSKind(EmptyKind) {
00313       LHS.decUI = Val;
00314     }
00315 
00316     /// Construct a twine to print \p Val as a signed decimal integer.
00317     explicit Twine(int Val)
00318       : LHSKind(DecIKind), RHSKind(EmptyKind) {
00319       LHS.decI = Val;
00320     }
00321 
00322     /// Construct a twine to print \p Val as an unsigned decimal integer.
00323     explicit Twine(const unsigned long &Val)
00324       : LHSKind(DecULKind), RHSKind(EmptyKind) {
00325       LHS.decUL = &Val;
00326     }
00327 
00328     /// Construct a twine to print \p Val as a signed decimal integer.
00329     explicit Twine(const long &Val)
00330       : LHSKind(DecLKind), RHSKind(EmptyKind) {
00331       LHS.decL = &Val;
00332     }
00333 
00334     /// Construct a twine to print \p Val as an unsigned decimal integer.
00335     explicit Twine(const unsigned long long &Val)
00336       : LHSKind(DecULLKind), RHSKind(EmptyKind) {
00337       LHS.decULL = &Val;
00338     }
00339 
00340     /// Construct a twine to print \p Val as a signed decimal integer.
00341     explicit Twine(const long long &Val)
00342       : LHSKind(DecLLKind), RHSKind(EmptyKind) {
00343       LHS.decLL = &Val;
00344     }
00345 
00346     // FIXME: Unfortunately, to make sure this is as efficient as possible we
00347     // need extra binary constructors from particular types. We can't rely on
00348     // the compiler to be smart enough to fold operator+()/concat() down to the
00349     // right thing. Yet.
00350 
00351     /// Construct as the concatenation of a C string and a StringRef.
00352     /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
00353       : LHSKind(CStringKind), RHSKind(StringRefKind) {
00354       LHS.cString = _LHS;
00355       RHS.stringRef = &_RHS;
00356       assert(isValid() && "Invalid twine!");
00357     }
00358 
00359     /// Construct as the concatenation of a StringRef and a C string.
00360     /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
00361       : LHSKind(StringRefKind), RHSKind(CStringKind) {
00362       LHS.stringRef = &_LHS;
00363       RHS.cString = _RHS;
00364       assert(isValid() && "Invalid twine!");
00365     }
00366 
00367     /// Create a 'null' string, which is an empty string that always
00368     /// concatenates to form another empty string.
00369     static Twine createNull() {
00370       return Twine(NullKind);
00371     }
00372 
00373     /// @}
00374     /// @name Numeric Conversions
00375     /// @{
00376 
00377     // Construct a twine to print \p Val as an unsigned hexadecimal integer.
00378     static Twine utohexstr(const uint64_t &Val) {
00379       Child LHS, RHS;
00380       LHS.uHex = &Val;
00381       RHS.twine = nullptr;
00382       return Twine(LHS, UHexKind, RHS, EmptyKind);
00383     }
00384 
00385     /// @}
00386     /// @name Predicate Operations
00387     /// @{
00388 
00389     /// isTriviallyEmpty - Check if this twine is trivially empty; a false
00390     /// return value does not necessarily mean the twine is empty.
00391     bool isTriviallyEmpty() const {
00392       return isNullary();
00393     }
00394 
00395     /// isSingleStringRef - Return true if this twine can be dynamically
00396     /// accessed as a single StringRef value with getSingleStringRef().
00397     bool isSingleStringRef() const {
00398       if (getRHSKind() != EmptyKind) return false;
00399 
00400       switch (getLHSKind()) {
00401       case EmptyKind:
00402       case CStringKind:
00403       case StdStringKind:
00404       case StringRefKind:
00405         return true;
00406       default:
00407         return false;
00408       }
00409     }
00410 
00411     /// @}
00412     /// @name String Operations
00413     /// @{
00414 
00415     Twine concat(const Twine &Suffix) const;
00416 
00417     /// @}
00418     /// @name Output & Conversion.
00419     /// @{
00420 
00421     /// str - Return the twine contents as a std::string.
00422     std::string str() const;
00423 
00424     /// toVector - Write the concatenated string into the given SmallString or
00425     /// SmallVector.
00426     void toVector(SmallVectorImpl<char> &Out) const;
00427 
00428     /// getSingleStringRef - This returns the twine as a single StringRef.  This
00429     /// method is only valid if isSingleStringRef() is true.
00430     StringRef getSingleStringRef() const {
00431       assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
00432       switch (getLHSKind()) {
00433       default: llvm_unreachable("Out of sync with isSingleStringRef");
00434       case EmptyKind:      return StringRef();
00435       case CStringKind:    return StringRef(LHS.cString);
00436       case StdStringKind:  return StringRef(*LHS.stdString);
00437       case StringRefKind:  return *LHS.stringRef;
00438       }
00439     }
00440 
00441     /// toStringRef - This returns the twine as a single StringRef if it can be
00442     /// represented as such. Otherwise the twine is written into the given
00443     /// SmallVector and a StringRef to the SmallVector's data is returned.
00444     StringRef toStringRef(SmallVectorImpl<char> &Out) const;
00445 
00446     /// toNullTerminatedStringRef - This returns the twine as a single null
00447     /// terminated StringRef if it can be represented as such. Otherwise the
00448     /// twine is written into the given SmallVector and a StringRef to the
00449     /// SmallVector's data is returned.
00450     ///
00451     /// The returned StringRef's size does not include the null terminator.
00452     StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
00453 
00454     /// Write the concatenated string represented by this twine to the
00455     /// stream \p OS.
00456     void print(raw_ostream &OS) const;
00457 
00458     /// Dump the concatenated string represented by this twine to stderr.
00459     void dump() const;
00460 
00461     /// Write the representation of this twine to the stream \p OS.
00462     void printRepr(raw_ostream &OS) const;
00463 
00464     /// Dump the representation of this twine to stderr.
00465     void dumpRepr() const;
00466 
00467     /// @}
00468   };
00469 
00470   /// @name Twine Inline Implementations
00471   /// @{
00472 
00473   inline Twine Twine::concat(const Twine &Suffix) const {
00474     // Concatenation with null is null.
00475     if (isNull() || Suffix.isNull())
00476       return Twine(NullKind);
00477 
00478     // Concatenation with empty yields the other side.
00479     if (isEmpty())
00480       return Suffix;
00481     if (Suffix.isEmpty())
00482       return *this;
00483 
00484     // Otherwise we need to create a new node, taking care to fold in unary
00485     // twines.
00486     Child NewLHS, NewRHS;
00487     NewLHS.twine = this;
00488     NewRHS.twine = &Suffix;
00489     NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
00490     if (isUnary()) {
00491       NewLHS = LHS;
00492       NewLHSKind = getLHSKind();
00493     }
00494     if (Suffix.isUnary()) {
00495       NewRHS = Suffix.LHS;
00496       NewRHSKind = Suffix.getLHSKind();
00497     }
00498 
00499     return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
00500   }
00501 
00502   inline Twine operator+(const Twine &LHS, const Twine &RHS) {
00503     return LHS.concat(RHS);
00504   }
00505 
00506   /// Additional overload to guarantee simplified codegen; this is equivalent to
00507   /// concat().
00508 
00509   inline Twine operator+(const char *LHS, const StringRef &RHS) {
00510     return Twine(LHS, RHS);
00511   }
00512 
00513   /// Additional overload to guarantee simplified codegen; this is equivalent to
00514   /// concat().
00515 
00516   inline Twine operator+(const StringRef &LHS, const char *RHS) {
00517     return Twine(LHS, RHS);
00518   }
00519 
00520   inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
00521     RHS.print(OS);
00522     return OS;
00523   }
00524 
00525   /// @}
00526 }
00527 
00528 #endif