Home | History | Annotate | Download | only in ADT
      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 
     18 namespace 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 char value reinterpreted as a pointer, to render as a character.
    103       CharKind,
    104 
    105       /// An unsigned int value reinterpreted as a pointer, to render as an
    106       /// unsigned decimal integer.
    107       DecUIKind,
    108 
    109       /// An int value reinterpreted as a pointer, to render as a signed
    110       /// decimal integer.
    111       DecIKind,
    112 
    113       /// A pointer to an unsigned long value, to render as an unsigned decimal
    114       /// integer.
    115       DecULKind,
    116 
    117       /// A pointer to a long value, to render as a signed decimal integer.
    118       DecLKind,
    119 
    120       /// A pointer to an unsigned long long value, to render as an unsigned
    121       /// decimal integer.
    122       DecULLKind,
    123 
    124       /// A pointer to a long long value, to render as a signed decimal integer.
    125       DecLLKind,
    126 
    127       /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
    128       /// integer.
    129       UHexKind
    130     };
    131 
    132     union Child
    133     {
    134       const Twine *twine;
    135       const char *cString;
    136       const std::string *stdString;
    137       const StringRef *stringRef;
    138       char character;
    139       unsigned int decUI;
    140       int decI;
    141       const unsigned long *decUL;
    142       const long *decL;
    143       const unsigned long long *decULL;
    144       const long long *decLL;
    145       const uint64_t *uHex;
    146     };
    147 
    148   private:
    149     /// LHS - The prefix in the concatenation, which may be uninitialized for
    150     /// Null or Empty kinds.
    151     Child LHS;
    152     /// RHS - The suffix in the concatenation, which may be uninitialized for
    153     /// Null or Empty kinds.
    154     Child RHS;
    155     // enums stored as unsigned chars to save on space while some compilers
    156     // don't support specifying the backing type for an enum
    157     /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
    158     unsigned char LHSKind;
    159     /// RHSKind - The NodeKind of the left hand side, \see getLHSKind().
    160     unsigned char RHSKind;
    161 
    162   private:
    163     /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
    164     explicit Twine(NodeKind Kind)
    165       : LHSKind(Kind), RHSKind(EmptyKind) {
    166       assert(isNullary() && "Invalid kind!");
    167     }
    168 
    169     /// Construct a binary twine.
    170     explicit Twine(const Twine &_LHS, const Twine &_RHS)
    171       : LHSKind(TwineKind), RHSKind(TwineKind) {
    172       LHS.twine = &_LHS;
    173       RHS.twine = &_RHS;
    174       assert(isValid() && "Invalid twine!");
    175     }
    176 
    177     /// Construct a twine from explicit values.
    178     explicit Twine(Child _LHS, NodeKind _LHSKind,
    179                    Child _RHS, NodeKind _RHSKind)
    180       : LHS(_LHS), RHS(_RHS), LHSKind(_LHSKind), RHSKind(_RHSKind) {
    181       assert(isValid() && "Invalid twine!");
    182     }
    183 
    184     /// isNull - Check for the null twine.
    185     bool isNull() const {
    186       return getLHSKind() == NullKind;
    187     }
    188 
    189     /// isEmpty - Check for the empty twine.
    190     bool isEmpty() const {
    191       return getLHSKind() == EmptyKind;
    192     }
    193 
    194     /// isNullary - Check if this is a nullary twine (null or empty).
    195     bool isNullary() const {
    196       return isNull() || isEmpty();
    197     }
    198 
    199     /// isUnary - Check if this is a unary twine.
    200     bool isUnary() const {
    201       return getRHSKind() == EmptyKind && !isNullary();
    202     }
    203 
    204     /// isBinary - Check if this is a binary twine.
    205     bool isBinary() const {
    206       return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
    207     }
    208 
    209     /// isValid - Check if this is a valid twine (satisfying the invariants on
    210     /// order and number of arguments).
    211     bool isValid() const {
    212       // Nullary twines always have Empty on the RHS.
    213       if (isNullary() && getRHSKind() != EmptyKind)
    214         return false;
    215 
    216       // Null should never appear on the RHS.
    217       if (getRHSKind() == NullKind)
    218         return false;
    219 
    220       // The RHS cannot be non-empty if the LHS is empty.
    221       if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
    222         return false;
    223 
    224       // A twine child should always be binary.
    225       if (getLHSKind() == TwineKind &&
    226           !LHS.twine->isBinary())
    227         return false;
    228       if (getRHSKind() == TwineKind &&
    229           !RHS.twine->isBinary())
    230         return false;
    231 
    232       return true;
    233     }
    234 
    235     /// getLHSKind - Get the NodeKind of the left-hand side.
    236     NodeKind getLHSKind() const { return (NodeKind) LHSKind; }
    237 
    238     /// getRHSKind - Get the NodeKind of the left-hand side.
    239     NodeKind getRHSKind() const { return (NodeKind) RHSKind; }
    240 
    241     /// printOneChild - Print one child from a twine.
    242     void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
    243 
    244     /// printOneChildRepr - Print the representation of one child from a twine.
    245     void printOneChildRepr(raw_ostream &OS, Child Ptr,
    246                            NodeKind Kind) const;
    247 
    248   public:
    249     /// @name Constructors
    250     /// @{
    251 
    252     /// Construct from an empty string.
    253     /*implicit*/ Twine() : LHSKind(EmptyKind), RHSKind(EmptyKind) {
    254       assert(isValid() && "Invalid twine!");
    255     }
    256 
    257     /// Construct from a C string.
    258     ///
    259     /// We take care here to optimize "" into the empty twine -- this will be
    260     /// optimized out for string constants. This allows Twine arguments have
    261     /// default "" values, without introducing unnecessary string constants.
    262     /*implicit*/ Twine(const char *Str)
    263       : RHSKind(EmptyKind) {
    264       if (Str[0] != '\0') {
    265         LHS.cString = Str;
    266         LHSKind = CStringKind;
    267       } else
    268         LHSKind = EmptyKind;
    269 
    270       assert(isValid() && "Invalid twine!");
    271     }
    272 
    273     /// Construct from an std::string.
    274     /*implicit*/ Twine(const std::string &Str)
    275       : LHSKind(StdStringKind), RHSKind(EmptyKind) {
    276       LHS.stdString = &Str;
    277       assert(isValid() && "Invalid twine!");
    278     }
    279 
    280     /// Construct from a StringRef.
    281     /*implicit*/ Twine(const StringRef &Str)
    282       : LHSKind(StringRefKind), RHSKind(EmptyKind) {
    283       LHS.stringRef = &Str;
    284       assert(isValid() && "Invalid twine!");
    285     }
    286 
    287     /// Construct from a char.
    288     explicit Twine(char Val)
    289       : LHSKind(CharKind), RHSKind(EmptyKind) {
    290       LHS.character = Val;
    291     }
    292 
    293     /// Construct from a signed char.
    294     explicit Twine(signed char Val)
    295       : LHSKind(CharKind), RHSKind(EmptyKind) {
    296       LHS.character = static_cast<char>(Val);
    297     }
    298 
    299     /// Construct from an unsigned char.
    300     explicit Twine(unsigned char Val)
    301       : LHSKind(CharKind), RHSKind(EmptyKind) {
    302       LHS.character = static_cast<char>(Val);
    303     }
    304 
    305     /// Construct a twine to print \arg Val as an unsigned decimal integer.
    306     explicit Twine(unsigned Val)
    307       : LHSKind(DecUIKind), RHSKind(EmptyKind) {
    308       LHS.decUI = Val;
    309     }
    310 
    311     /// Construct a twine to print \arg Val as a signed decimal integer.
    312     explicit Twine(int Val)
    313       : LHSKind(DecIKind), RHSKind(EmptyKind) {
    314       LHS.decI = Val;
    315     }
    316 
    317     /// Construct a twine to print \arg Val as an unsigned decimal integer.
    318     explicit Twine(const unsigned long &Val)
    319       : LHSKind(DecULKind), RHSKind(EmptyKind) {
    320       LHS.decUL = &Val;
    321     }
    322 
    323     /// Construct a twine to print \arg Val as a signed decimal integer.
    324     explicit Twine(const long &Val)
    325       : LHSKind(DecLKind), RHSKind(EmptyKind) {
    326       LHS.decL = &Val;
    327     }
    328 
    329     /// Construct a twine to print \arg Val as an unsigned decimal integer.
    330     explicit Twine(const unsigned long long &Val)
    331       : LHSKind(DecULLKind), RHSKind(EmptyKind) {
    332       LHS.decULL = &Val;
    333     }
    334 
    335     /// Construct a twine to print \arg Val as a signed decimal integer.
    336     explicit Twine(const long long &Val)
    337       : LHSKind(DecLLKind), RHSKind(EmptyKind) {
    338       LHS.decLL = &Val;
    339     }
    340 
    341     // FIXME: Unfortunately, to make sure this is as efficient as possible we
    342     // need extra binary constructors from particular types. We can't rely on
    343     // the compiler to be smart enough to fold operator+()/concat() down to the
    344     // right thing. Yet.
    345 
    346     /// Construct as the concatenation of a C string and a StringRef.
    347     /*implicit*/ Twine(const char *_LHS, const StringRef &_RHS)
    348       : LHSKind(CStringKind), RHSKind(StringRefKind) {
    349       LHS.cString = _LHS;
    350       RHS.stringRef = &_RHS;
    351       assert(isValid() && "Invalid twine!");
    352     }
    353 
    354     /// Construct as the concatenation of a StringRef and a C string.
    355     /*implicit*/ Twine(const StringRef &_LHS, const char *_RHS)
    356       : LHSKind(StringRefKind), RHSKind(CStringKind) {
    357       LHS.stringRef = &_LHS;
    358       RHS.cString = _RHS;
    359       assert(isValid() && "Invalid twine!");
    360     }
    361 
    362     /// Create a 'null' string, which is an empty string that always
    363     /// concatenates to form another empty string.
    364     static Twine createNull() {
    365       return Twine(NullKind);
    366     }
    367 
    368     /// @}
    369     /// @name Numeric Conversions
    370     /// @{
    371 
    372     // Construct a twine to print \arg Val as an unsigned hexadecimal integer.
    373     static Twine utohexstr(const uint64_t &Val) {
    374       Child LHS, RHS;
    375       LHS.uHex = &Val;
    376       RHS.twine = 0;
    377       return Twine(LHS, UHexKind, RHS, EmptyKind);
    378     }
    379 
    380     /// @}
    381     /// @name Predicate Operations
    382     /// @{
    383 
    384     /// isTriviallyEmpty - Check if this twine is trivially empty; a false
    385     /// return value does not necessarily mean the twine is empty.
    386     bool isTriviallyEmpty() const {
    387       return isNullary();
    388     }
    389 
    390     /// isSingleStringRef - Return true if this twine can be dynamically
    391     /// accessed as a single StringRef value with getSingleStringRef().
    392     bool isSingleStringRef() const {
    393       if (getRHSKind() != EmptyKind) return false;
    394 
    395       switch (getLHSKind()) {
    396       case EmptyKind:
    397       case CStringKind:
    398       case StdStringKind:
    399       case StringRefKind:
    400         return true;
    401       default:
    402         return false;
    403       }
    404     }
    405 
    406     /// @}
    407     /// @name String Operations
    408     /// @{
    409 
    410     Twine concat(const Twine &Suffix) const;
    411 
    412     /// @}
    413     /// @name Output & Conversion.
    414     /// @{
    415 
    416     /// str - Return the twine contents as a std::string.
    417     std::string str() const;
    418 
    419     /// toVector - Write the concatenated string into the given SmallString or
    420     /// SmallVector.
    421     void toVector(SmallVectorImpl<char> &Out) const;
    422 
    423     /// getSingleStringRef - This returns the twine as a single StringRef.  This
    424     /// method is only valid if isSingleStringRef() is true.
    425     StringRef getSingleStringRef() const {
    426       assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
    427       switch (getLHSKind()) {
    428       default: assert(0 && "Out of sync with isSingleStringRef");
    429       case EmptyKind:      return StringRef();
    430       case CStringKind:    return StringRef(LHS.cString);
    431       case StdStringKind:  return StringRef(*LHS.stdString);
    432       case StringRefKind:  return *LHS.stringRef;
    433       }
    434     }
    435 
    436     /// toStringRef - This returns the twine as a single StringRef if it can be
    437     /// represented as such. Otherwise the twine is written into the given
    438     /// SmallVector and a StringRef to the SmallVector's data is returned.
    439     StringRef toStringRef(SmallVectorImpl<char> &Out) const;
    440 
    441     /// toNullTerminatedStringRef - This returns the twine as a single null
    442     /// terminated StringRef if it can be represented as such. Otherwise the
    443     /// twine is written into the given SmallVector and a StringRef to the
    444     /// SmallVector's data is returned.
    445     ///
    446     /// The returned StringRef's size does not include the null terminator.
    447     StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
    448 
    449     /// print - Write the concatenated string represented by this twine to the
    450     /// stream \arg OS.
    451     void print(raw_ostream &OS) const;
    452 
    453     /// dump - Dump the concatenated string represented by this twine to stderr.
    454     void dump() const;
    455 
    456     /// print - Write the representation of this twine to the stream \arg OS.
    457     void printRepr(raw_ostream &OS) const;
    458 
    459     /// dumpRepr - Dump the representation of this twine to stderr.
    460     void dumpRepr() const;
    461 
    462     /// @}
    463   };
    464 
    465   /// @name Twine Inline Implementations
    466   /// @{
    467 
    468   inline Twine Twine::concat(const Twine &Suffix) const {
    469     // Concatenation with null is null.
    470     if (isNull() || Suffix.isNull())
    471       return Twine(NullKind);
    472 
    473     // Concatenation with empty yields the other side.
    474     if (isEmpty())
    475       return Suffix;
    476     if (Suffix.isEmpty())
    477       return *this;
    478 
    479     // Otherwise we need to create a new node, taking care to fold in unary
    480     // twines.
    481     Child NewLHS, NewRHS;
    482     NewLHS.twine = this;
    483     NewRHS.twine = &Suffix;
    484     NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
    485     if (isUnary()) {
    486       NewLHS = LHS;
    487       NewLHSKind = getLHSKind();
    488     }
    489     if (Suffix.isUnary()) {
    490       NewRHS = Suffix.LHS;
    491       NewRHSKind = Suffix.getLHSKind();
    492     }
    493 
    494     return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
    495   }
    496 
    497   inline Twine operator+(const Twine &LHS, const Twine &RHS) {
    498     return LHS.concat(RHS);
    499   }
    500 
    501   /// Additional overload to guarantee simplified codegen; this is equivalent to
    502   /// concat().
    503 
    504   inline Twine operator+(const char *LHS, const StringRef &RHS) {
    505     return Twine(LHS, RHS);
    506   }
    507 
    508   /// Additional overload to guarantee simplified codegen; this is equivalent to
    509   /// concat().
    510 
    511   inline Twine operator+(const StringRef &LHS, const char *RHS) {
    512     return Twine(LHS, RHS);
    513   }
    514 
    515   inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
    516     RHS.print(OS);
    517     return OS;
    518   }
    519 
    520   /// @}
    521 }
    522 
    523 #endif
    524