Twine.h 18 KB

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