Twine.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. //===- Twine.h - Fast Temporary String Concatenation ------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #ifndef LLVM_ADT_TWINE_H
  9. #define LLVM_ADT_TWINE_H
  10. #include "llvm/ADT/SmallVector.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/Support/ErrorHandling.h"
  13. #include <cassert>
  14. #include <cstdint>
  15. #include <string>
  16. namespace llvm {
  17. class formatv_object_base;
  18. class raw_ostream;
  19. /// Twine - A lightweight data structure for efficiently representing the
  20. /// concatenation of temporary values as strings.
  21. ///
  22. /// A Twine is a kind of rope, it represents a concatenated string using a
  23. /// binary-tree, where the string is the preorder of the nodes. Since the
  24. /// Twine can be efficiently rendered into a buffer when its result is used,
  25. /// it avoids the cost of generating temporary values for intermediate string
  26. /// results -- particularly in cases when the Twine result is never
  27. /// required. By explicitly tracking the type of leaf nodes, we can also avoid
  28. /// the creation of temporary strings for conversions operations (such as
  29. /// appending an integer to a string).
  30. ///
  31. /// A Twine is not intended for use directly and should not be stored, its
  32. /// implementation relies on the ability to store pointers to temporary stack
  33. /// objects which may be deallocated at the end of a statement. Twines should
  34. /// only be used accepted as const references in arguments, when an API wishes
  35. /// to accept possibly-concatenated strings.
  36. ///
  37. /// Twines support a special 'null' value, which always concatenates to form
  38. /// itself, and renders as an empty string. This can be returned from APIs to
  39. /// effectively nullify any concatenations performed on the result.
  40. ///
  41. /// \b Implementation
  42. ///
  43. /// Given the nature of a Twine, it is not possible for the Twine's
  44. /// concatenation method to construct interior nodes; the result must be
  45. /// represented inside the returned value. For this reason a Twine object
  46. /// actually holds two values, the left- and right-hand sides of a
  47. /// concatenation. We also have nullary Twine objects, which are effectively
  48. /// sentinel values that represent empty strings.
  49. ///
  50. /// Thus, a Twine can effectively have zero, one, or two children. The \see
  51. /// isNullary(), \see isUnary(), and \see isBinary() predicates exist for
  52. /// testing the number of children.
  53. ///
  54. /// We maintain a number of invariants on Twine objects (FIXME: Why):
  55. /// - Nullary twines are always represented with their Kind on the left-hand
  56. /// side, and the Empty kind on the right-hand side.
  57. /// - Unary twines are always represented with the value on the left-hand
  58. /// side, and the Empty kind on the right-hand side.
  59. /// - If a Twine has another Twine as a child, that child should always be
  60. /// binary (otherwise it could have been folded into the parent).
  61. ///
  62. /// These invariants are check by \see isValid().
  63. ///
  64. /// \b Efficiency Considerations
  65. ///
  66. /// The Twine is designed to yield efficient and small code for common
  67. /// situations. For this reason, the concat() method is inlined so that
  68. /// concatenations of leaf nodes can be optimized into stores directly into a
  69. /// single stack allocated object.
  70. ///
  71. /// In practice, not all compilers can be trusted to optimize concat() fully,
  72. /// so we provide two additional methods (and accompanying operator+
  73. /// overloads) to guarantee that particularly important cases (cstring plus
  74. /// StringRef) codegen as desired.
  75. class Twine {
  76. /// NodeKind - Represent the type of an argument.
  77. enum NodeKind : unsigned char {
  78. /// An empty string; the result of concatenating anything with it is also
  79. /// empty.
  80. NullKind,
  81. /// The empty string.
  82. EmptyKind,
  83. /// A pointer to a Twine instance.
  84. TwineKind,
  85. /// A pointer to a C string instance.
  86. CStringKind,
  87. /// A pointer to an std::string instance.
  88. StdStringKind,
  89. /// A pointer to a StringRef instance.
  90. StringRefKind,
  91. /// A pointer to a SmallString instance.
  92. SmallStringKind,
  93. /// A pointer to a formatv_object_base instance.
  94. FormatvObjectKind,
  95. /// A char value, to render as a character.
  96. CharKind,
  97. /// An unsigned int value, to render as an unsigned decimal integer.
  98. DecUIKind,
  99. /// An int value, to render as a signed decimal integer.
  100. DecIKind,
  101. /// A pointer to an unsigned long value, to render as an unsigned decimal
  102. /// integer.
  103. DecULKind,
  104. /// A pointer to a long value, to render as a signed decimal integer.
  105. DecLKind,
  106. /// A pointer to an unsigned long long value, to render as an unsigned
  107. /// decimal integer.
  108. DecULLKind,
  109. /// A pointer to a long long value, to render as a signed decimal integer.
  110. DecLLKind,
  111. /// A pointer to a uint64_t value, to render as an unsigned hexadecimal
  112. /// integer.
  113. UHexKind
  114. };
  115. union Child
  116. {
  117. const Twine *twine;
  118. const char *cString;
  119. const std::string *stdString;
  120. const StringRef *stringRef;
  121. const SmallVectorImpl<char> *smallString;
  122. const formatv_object_base *formatvObject;
  123. char character;
  124. unsigned int decUI;
  125. int decI;
  126. const unsigned long *decUL;
  127. const long *decL;
  128. const unsigned long long *decULL;
  129. const long long *decLL;
  130. const uint64_t *uHex;
  131. };
  132. /// LHS - The prefix in the concatenation, which may be uninitialized for
  133. /// Null or Empty kinds.
  134. Child LHS;
  135. /// RHS - The suffix in the concatenation, which may be uninitialized for
  136. /// Null or Empty kinds.
  137. Child RHS;
  138. /// LHSKind - The NodeKind of the left hand side, \see getLHSKind().
  139. NodeKind LHSKind = EmptyKind;
  140. /// RHSKind - The NodeKind of the right hand side, \see getRHSKind().
  141. NodeKind RHSKind = EmptyKind;
  142. /// Construct a nullary twine; the kind must be NullKind or EmptyKind.
  143. explicit Twine(NodeKind Kind) : LHSKind(Kind) {
  144. assert(isNullary() && "Invalid kind!");
  145. }
  146. /// Construct a binary twine.
  147. explicit Twine(const Twine &LHS, const Twine &RHS)
  148. : LHSKind(TwineKind), RHSKind(TwineKind) {
  149. this->LHS.twine = &LHS;
  150. this->RHS.twine = &RHS;
  151. assert(isValid() && "Invalid twine!");
  152. }
  153. /// Construct a twine from explicit values.
  154. explicit Twine(Child LHS, NodeKind LHSKind, Child RHS, NodeKind RHSKind)
  155. : LHS(LHS), RHS(RHS), LHSKind(LHSKind), RHSKind(RHSKind) {
  156. assert(isValid() && "Invalid twine!");
  157. }
  158. /// Check for the null twine.
  159. bool isNull() const {
  160. return getLHSKind() == NullKind;
  161. }
  162. /// Check for the empty twine.
  163. bool isEmpty() const {
  164. return getLHSKind() == EmptyKind;
  165. }
  166. /// Check if this is a nullary twine (null or empty).
  167. bool isNullary() const {
  168. return isNull() || isEmpty();
  169. }
  170. /// Check if this is a unary twine.
  171. bool isUnary() const {
  172. return getRHSKind() == EmptyKind && !isNullary();
  173. }
  174. /// Check if this is a binary twine.
  175. bool isBinary() const {
  176. return getLHSKind() != NullKind && getRHSKind() != EmptyKind;
  177. }
  178. /// Check if this is a valid twine (satisfying the invariants on
  179. /// order and number of arguments).
  180. bool isValid() const {
  181. // Nullary twines always have Empty on the RHS.
  182. if (isNullary() && getRHSKind() != EmptyKind)
  183. return false;
  184. // Null should never appear on the RHS.
  185. if (getRHSKind() == NullKind)
  186. return false;
  187. // The RHS cannot be non-empty if the LHS is empty.
  188. if (getRHSKind() != EmptyKind && getLHSKind() == EmptyKind)
  189. return false;
  190. // A twine child should always be binary.
  191. if (getLHSKind() == TwineKind &&
  192. !LHS.twine->isBinary())
  193. return false;
  194. if (getRHSKind() == TwineKind &&
  195. !RHS.twine->isBinary())
  196. return false;
  197. return true;
  198. }
  199. /// Get the NodeKind of the left-hand side.
  200. NodeKind getLHSKind() const { return LHSKind; }
  201. /// Get the NodeKind of the right-hand side.
  202. NodeKind getRHSKind() const { return RHSKind; }
  203. /// Print one child from a twine.
  204. void printOneChild(raw_ostream &OS, Child Ptr, NodeKind Kind) const;
  205. /// Print the representation of one child from a twine.
  206. void printOneChildRepr(raw_ostream &OS, Child Ptr,
  207. NodeKind Kind) const;
  208. public:
  209. /// @name Constructors
  210. /// @{
  211. /// Construct from an empty string.
  212. /*implicit*/ Twine() {
  213. assert(isValid() && "Invalid twine!");
  214. }
  215. Twine(const Twine &) = default;
  216. /// Construct from a C string.
  217. ///
  218. /// We take care here to optimize "" into the empty twine -- this will be
  219. /// optimized out for string constants. This allows Twine arguments have
  220. /// default "" values, without introducing unnecessary string constants.
  221. /*implicit*/ Twine(const char *Str) {
  222. if (Str[0] != '\0') {
  223. LHS.cString = Str;
  224. LHSKind = CStringKind;
  225. } else
  226. LHSKind = EmptyKind;
  227. assert(isValid() && "Invalid twine!");
  228. }
  229. /// Delete the implicit conversion from nullptr as Twine(const char *)
  230. /// cannot take nullptr.
  231. /*implicit*/ Twine(std::nullptr_t) = delete;
  232. /// Construct from an std::string.
  233. /*implicit*/ Twine(const std::string &Str) : LHSKind(StdStringKind) {
  234. LHS.stdString = &Str;
  235. assert(isValid() && "Invalid twine!");
  236. }
  237. /// Construct from a StringRef.
  238. /*implicit*/ Twine(const StringRef &Str) : LHSKind(StringRefKind) {
  239. LHS.stringRef = &Str;
  240. assert(isValid() && "Invalid twine!");
  241. }
  242. /// Construct from a SmallString.
  243. /*implicit*/ Twine(const SmallVectorImpl<char> &Str)
  244. : LHSKind(SmallStringKind) {
  245. LHS.smallString = &Str;
  246. assert(isValid() && "Invalid twine!");
  247. }
  248. /// Construct from a formatv_object_base.
  249. /*implicit*/ Twine(const formatv_object_base &Fmt)
  250. : LHSKind(FormatvObjectKind) {
  251. LHS.formatvObject = &Fmt;
  252. assert(isValid() && "Invalid twine!");
  253. }
  254. /// Construct from a char.
  255. explicit Twine(char Val) : LHSKind(CharKind) {
  256. LHS.character = Val;
  257. }
  258. /// Construct from a signed char.
  259. explicit Twine(signed char Val) : LHSKind(CharKind) {
  260. LHS.character = static_cast<char>(Val);
  261. }
  262. /// Construct from an unsigned char.
  263. explicit Twine(unsigned char Val) : LHSKind(CharKind) {
  264. LHS.character = static_cast<char>(Val);
  265. }
  266. /// Construct a twine to print \p Val as an unsigned decimal integer.
  267. explicit Twine(unsigned Val) : LHSKind(DecUIKind) {
  268. LHS.decUI = Val;
  269. }
  270. /// Construct a twine to print \p Val as a signed decimal integer.
  271. explicit Twine(int Val) : LHSKind(DecIKind) {
  272. LHS.decI = Val;
  273. }
  274. /// Construct a twine to print \p Val as an unsigned decimal integer.
  275. explicit Twine(const unsigned long &Val) : LHSKind(DecULKind) {
  276. LHS.decUL = &Val;
  277. }
  278. /// Construct a twine to print \p Val as a signed decimal integer.
  279. explicit Twine(const long &Val) : LHSKind(DecLKind) {
  280. LHS.decL = &Val;
  281. }
  282. /// Construct a twine to print \p Val as an unsigned decimal integer.
  283. explicit Twine(const unsigned long long &Val) : LHSKind(DecULLKind) {
  284. LHS.decULL = &Val;
  285. }
  286. /// Construct a twine to print \p Val as a signed decimal integer.
  287. explicit Twine(const long long &Val) : LHSKind(DecLLKind) {
  288. LHS.decLL = &Val;
  289. }
  290. // FIXME: Unfortunately, to make sure this is as efficient as possible we
  291. // need extra binary constructors from particular types. We can't rely on
  292. // the compiler to be smart enough to fold operator+()/concat() down to the
  293. // right thing. Yet.
  294. /// Construct as the concatenation of a C string and a StringRef.
  295. /*implicit*/ Twine(const char *LHS, const StringRef &RHS)
  296. : LHSKind(CStringKind), RHSKind(StringRefKind) {
  297. this->LHS.cString = LHS;
  298. this->RHS.stringRef = &RHS;
  299. assert(isValid() && "Invalid twine!");
  300. }
  301. /// Construct as the concatenation of a StringRef and a C string.
  302. /*implicit*/ Twine(const StringRef &LHS, const char *RHS)
  303. : LHSKind(StringRefKind), RHSKind(CStringKind) {
  304. this->LHS.stringRef = &LHS;
  305. this->RHS.cString = RHS;
  306. assert(isValid() && "Invalid twine!");
  307. }
  308. /// Since the intended use of twines is as temporary objects, assignments
  309. /// when concatenating might cause undefined behavior or stack corruptions
  310. Twine &operator=(const Twine &) = delete;
  311. /// Create a 'null' string, which is an empty string that always
  312. /// concatenates to form another empty string.
  313. static Twine createNull() {
  314. return Twine(NullKind);
  315. }
  316. /// @}
  317. /// @name Numeric Conversions
  318. /// @{
  319. // Construct a twine to print \p Val as an unsigned hexadecimal integer.
  320. static Twine utohexstr(const uint64_t &Val) {
  321. Child LHS, RHS;
  322. LHS.uHex = &Val;
  323. RHS.twine = nullptr;
  324. return Twine(LHS, UHexKind, RHS, EmptyKind);
  325. }
  326. /// @}
  327. /// @name Predicate Operations
  328. /// @{
  329. /// Check if this twine is trivially empty; a false return value does not
  330. /// necessarily mean the twine is empty.
  331. bool isTriviallyEmpty() const {
  332. return isNullary();
  333. }
  334. /// Return true if this twine can be dynamically accessed as a single
  335. /// StringRef value with getSingleStringRef().
  336. bool isSingleStringRef() const {
  337. if (getRHSKind() != EmptyKind) return false;
  338. switch (getLHSKind()) {
  339. case EmptyKind:
  340. case CStringKind:
  341. case StdStringKind:
  342. case StringRefKind:
  343. case SmallStringKind:
  344. return true;
  345. default:
  346. return false;
  347. }
  348. }
  349. /// @}
  350. /// @name String Operations
  351. /// @{
  352. Twine concat(const Twine &Suffix) const;
  353. /// @}
  354. /// @name Output & Conversion.
  355. /// @{
  356. /// Return the twine contents as a std::string.
  357. std::string str() const;
  358. /// Append the concatenated string into the given SmallString or SmallVector.
  359. void toVector(SmallVectorImpl<char> &Out) const;
  360. /// This returns the twine as a single StringRef. This method is only valid
  361. /// if isSingleStringRef() is true.
  362. StringRef getSingleStringRef() const {
  363. assert(isSingleStringRef() &&"This cannot be had as a single stringref!");
  364. switch (getLHSKind()) {
  365. default: llvm_unreachable("Out of sync with isSingleStringRef");
  366. case EmptyKind: return StringRef();
  367. case CStringKind: return StringRef(LHS.cString);
  368. case StdStringKind: return StringRef(*LHS.stdString);
  369. case StringRefKind: return *LHS.stringRef;
  370. case SmallStringKind:
  371. return StringRef(LHS.smallString->data(), LHS.smallString->size());
  372. }
  373. }
  374. /// This returns the twine as a single StringRef if it can be
  375. /// represented as such. Otherwise the twine is written into the given
  376. /// SmallVector and a StringRef to the SmallVector's data is returned.
  377. StringRef toStringRef(SmallVectorImpl<char> &Out) const {
  378. if (isSingleStringRef())
  379. return getSingleStringRef();
  380. toVector(Out);
  381. return StringRef(Out.data(), Out.size());
  382. }
  383. /// This returns the twine as a single null terminated StringRef if it
  384. /// can be represented as such. Otherwise the twine is written into the
  385. /// given SmallVector and a StringRef to the SmallVector's data is returned.
  386. ///
  387. /// The returned StringRef's size does not include the null terminator.
  388. StringRef toNullTerminatedStringRef(SmallVectorImpl<char> &Out) const;
  389. /// Write the concatenated string represented by this twine to the
  390. /// stream \p OS.
  391. void print(raw_ostream &OS) const;
  392. /// Dump the concatenated string represented by this twine to stderr.
  393. void dump() const;
  394. /// Write the representation of this twine to the stream \p OS.
  395. void printRepr(raw_ostream &OS) const;
  396. /// Dump the representation of this twine to stderr.
  397. void dumpRepr() const;
  398. /// @}
  399. };
  400. /// @name Twine Inline Implementations
  401. /// @{
  402. inline Twine Twine::concat(const Twine &Suffix) const {
  403. // Concatenation with null is null.
  404. if (isNull() || Suffix.isNull())
  405. return Twine(NullKind);
  406. // Concatenation with empty yields the other side.
  407. if (isEmpty())
  408. return Suffix;
  409. if (Suffix.isEmpty())
  410. return *this;
  411. // Otherwise we need to create a new node, taking care to fold in unary
  412. // twines.
  413. Child NewLHS, NewRHS;
  414. NewLHS.twine = this;
  415. NewRHS.twine = &Suffix;
  416. NodeKind NewLHSKind = TwineKind, NewRHSKind = TwineKind;
  417. if (isUnary()) {
  418. NewLHS = LHS;
  419. NewLHSKind = getLHSKind();
  420. }
  421. if (Suffix.isUnary()) {
  422. NewRHS = Suffix.LHS;
  423. NewRHSKind = Suffix.getLHSKind();
  424. }
  425. return Twine(NewLHS, NewLHSKind, NewRHS, NewRHSKind);
  426. }
  427. inline Twine operator+(const Twine &LHS, const Twine &RHS) {
  428. return LHS.concat(RHS);
  429. }
  430. /// Additional overload to guarantee simplified codegen; this is equivalent to
  431. /// concat().
  432. inline Twine operator+(const char *LHS, const StringRef &RHS) {
  433. return Twine(LHS, RHS);
  434. }
  435. /// Additional overload to guarantee simplified codegen; this is equivalent to
  436. /// concat().
  437. inline Twine operator+(const StringRef &LHS, const char *RHS) {
  438. return Twine(LHS, RHS);
  439. }
  440. inline raw_ostream &operator<<(raw_ostream &OS, const Twine &RHS) {
  441. RHS.print(OS);
  442. return OS;
  443. }
  444. /// @}
  445. } // end namespace llvm
  446. #endif // LLVM_ADT_TWINE_H