StringRef.h 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- StringRef.h - Constant String Reference Wrapper ----------*- 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_STRINGREF_H
  14. #define LLVM_ADT_STRINGREF_H
  15. #include "llvm/ADT/DenseMapInfo.h"
  16. #include "llvm/ADT/STLFunctionalExtras.h"
  17. #include "llvm/ADT/iterator_range.h"
  18. #include "llvm/Support/Compiler.h"
  19. #include <algorithm>
  20. #include <cassert>
  21. #include <cstddef>
  22. #include <cstring>
  23. #include <limits>
  24. #include <string>
  25. #include <string_view>
  26. #include <type_traits>
  27. #include <utility>
  28. namespace llvm {
  29. class APInt;
  30. class hash_code;
  31. template <typename T> class SmallVectorImpl;
  32. class StringRef;
  33. /// Helper functions for StringRef::getAsInteger.
  34. bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
  35. unsigned long long &Result);
  36. bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
  37. bool consumeUnsignedInteger(StringRef &Str, unsigned Radix,
  38. unsigned long long &Result);
  39. bool consumeSignedInteger(StringRef &Str, unsigned Radix, long long &Result);
  40. /// StringRef - Represent a constant reference to a string, i.e. a character
  41. /// array and a length, which need not be null terminated.
  42. ///
  43. /// This class does not own the string data, it is expected to be used in
  44. /// situations where the character data resides in some other buffer, whose
  45. /// lifetime extends past that of the StringRef. For this reason, it is not in
  46. /// general safe to store a StringRef.
  47. class LLVM_GSL_POINTER StringRef {
  48. public:
  49. static constexpr size_t npos = ~size_t(0);
  50. using iterator = const char *;
  51. using const_iterator = const char *;
  52. using size_type = size_t;
  53. private:
  54. /// The start of the string, in an external buffer.
  55. const char *Data = nullptr;
  56. /// The length of the string.
  57. size_t Length = 0;
  58. // Workaround memcmp issue with null pointers (undefined behavior)
  59. // by providing a specialized version
  60. static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
  61. if (Length == 0) { return 0; }
  62. return ::memcmp(Lhs,Rhs,Length);
  63. }
  64. public:
  65. /// @name Constructors
  66. /// @{
  67. /// Construct an empty string ref.
  68. /*implicit*/ StringRef() = default;
  69. /// Disable conversion from nullptr. This prevents things like
  70. /// if (S == nullptr)
  71. StringRef(std::nullptr_t) = delete;
  72. /// Construct a string ref from a cstring.
  73. /*implicit*/ constexpr StringRef(const char *Str)
  74. : Data(Str), Length(Str ?
  75. // GCC 7 doesn't have constexpr char_traits. Fall back to __builtin_strlen.
  76. #if defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE < 8
  77. __builtin_strlen(Str)
  78. #else
  79. std::char_traits<char>::length(Str)
  80. #endif
  81. : 0) {
  82. }
  83. /// Construct a string ref from a pointer and length.
  84. /*implicit*/ constexpr StringRef(const char *data, size_t length)
  85. : Data(data), Length(length) {}
  86. /// Construct a string ref from an std::string.
  87. /*implicit*/ StringRef(const std::string &Str)
  88. : Data(Str.data()), Length(Str.length()) {}
  89. /// Construct a string ref from an std::string_view.
  90. /*implicit*/ constexpr StringRef(std::string_view Str)
  91. : Data(Str.data()), Length(Str.size()) {}
  92. /// @}
  93. /// @name Iterators
  94. /// @{
  95. iterator begin() const { return Data; }
  96. iterator end() const { return Data + Length; }
  97. const unsigned char *bytes_begin() const {
  98. return reinterpret_cast<const unsigned char *>(begin());
  99. }
  100. const unsigned char *bytes_end() const {
  101. return reinterpret_cast<const unsigned char *>(end());
  102. }
  103. iterator_range<const unsigned char *> bytes() const {
  104. return make_range(bytes_begin(), bytes_end());
  105. }
  106. /// @}
  107. /// @name String Operations
  108. /// @{
  109. /// data - Get a pointer to the start of the string (which may not be null
  110. /// terminated).
  111. [[nodiscard]] const char *data() const { return Data; }
  112. /// empty - Check if the string is empty.
  113. [[nodiscard]] constexpr bool empty() const { return Length == 0; }
  114. /// size - Get the string size.
  115. [[nodiscard]] constexpr size_t size() const { return Length; }
  116. /// front - Get the first character in the string.
  117. [[nodiscard]] char front() const {
  118. assert(!empty());
  119. return Data[0];
  120. }
  121. /// back - Get the last character in the string.
  122. [[nodiscard]] char back() const {
  123. assert(!empty());
  124. return Data[Length-1];
  125. }
  126. // copy - Allocate copy in Allocator and return StringRef to it.
  127. template <typename Allocator>
  128. [[nodiscard]] StringRef copy(Allocator &A) const {
  129. // Don't request a length 0 copy from the allocator.
  130. if (empty())
  131. return StringRef();
  132. char *S = A.template Allocate<char>(Length);
  133. std::copy(begin(), end(), S);
  134. return StringRef(S, Length);
  135. }
  136. /// equals - Check for string equality, this is more efficient than
  137. /// compare() when the relative ordering of inequal strings isn't needed.
  138. [[nodiscard]] bool equals(StringRef RHS) const {
  139. return (Length == RHS.Length &&
  140. compareMemory(Data, RHS.Data, RHS.Length) == 0);
  141. }
  142. /// Check for string equality, ignoring case.
  143. [[nodiscard]] bool equals_insensitive(StringRef RHS) const {
  144. return Length == RHS.Length && compare_insensitive(RHS) == 0;
  145. }
  146. /// compare - Compare two strings; the result is negative, zero, or positive
  147. /// if this string is lexicographically less than, equal to, or greater than
  148. /// the \p RHS.
  149. [[nodiscard]] int compare(StringRef RHS) const {
  150. // Check the prefix for a mismatch.
  151. if (int Res = compareMemory(Data, RHS.Data, std::min(Length, RHS.Length)))
  152. return Res < 0 ? -1 : 1;
  153. // Otherwise the prefixes match, so we only need to check the lengths.
  154. if (Length == RHS.Length)
  155. return 0;
  156. return Length < RHS.Length ? -1 : 1;
  157. }
  158. /// Compare two strings, ignoring case.
  159. [[nodiscard]] int compare_insensitive(StringRef RHS) const;
  160. /// compare_numeric - Compare two strings, treating sequences of digits as
  161. /// numbers.
  162. [[nodiscard]] int compare_numeric(StringRef RHS) const;
  163. /// Determine the edit distance between this string and another
  164. /// string.
  165. ///
  166. /// \param Other the string to compare this string against.
  167. ///
  168. /// \param AllowReplacements whether to allow character
  169. /// replacements (change one character into another) as a single
  170. /// operation, rather than as two operations (an insertion and a
  171. /// removal).
  172. ///
  173. /// \param MaxEditDistance If non-zero, the maximum edit distance that
  174. /// this routine is allowed to compute. If the edit distance will exceed
  175. /// that maximum, returns \c MaxEditDistance+1.
  176. ///
  177. /// \returns the minimum number of character insertions, removals,
  178. /// or (if \p AllowReplacements is \c true) replacements needed to
  179. /// transform one of the given strings into the other. If zero,
  180. /// the strings are identical.
  181. [[nodiscard]] unsigned edit_distance(StringRef Other,
  182. bool AllowReplacements = true,
  183. unsigned MaxEditDistance = 0) const;
  184. [[nodiscard]] unsigned
  185. edit_distance_insensitive(StringRef Other, bool AllowReplacements = true,
  186. unsigned MaxEditDistance = 0) const;
  187. /// str - Get the contents as an std::string.
  188. [[nodiscard]] std::string str() const {
  189. if (!Data) return std::string();
  190. return std::string(Data, Length);
  191. }
  192. /// @}
  193. /// @name Operator Overloads
  194. /// @{
  195. [[nodiscard]] char operator[](size_t Index) const {
  196. assert(Index < Length && "Invalid index!");
  197. return Data[Index];
  198. }
  199. /// Disallow accidental assignment from a temporary std::string.
  200. ///
  201. /// The declaration here is extra complicated so that `stringRef = {}`
  202. /// and `stringRef = "abc"` continue to select the move assignment operator.
  203. template <typename T>
  204. std::enable_if_t<std::is_same<T, std::string>::value, StringRef> &
  205. operator=(T &&Str) = delete;
  206. /// @}
  207. /// @name Type Conversions
  208. /// @{
  209. operator std::string_view() const {
  210. return std::string_view(data(), size());
  211. }
  212. /// @}
  213. /// @name String Predicates
  214. /// @{
  215. /// Check if this string starts with the given \p Prefix.
  216. [[nodiscard]] bool starts_with(StringRef Prefix) const {
  217. return Length >= Prefix.Length &&
  218. compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
  219. }
  220. [[nodiscard]] bool startswith(StringRef Prefix) const {
  221. return starts_with(Prefix);
  222. }
  223. /// Check if this string starts with the given \p Prefix, ignoring case.
  224. [[nodiscard]] bool starts_with_insensitive(StringRef Prefix) const;
  225. [[nodiscard]] bool startswith_insensitive(StringRef Prefix) const {
  226. return starts_with_insensitive(Prefix);
  227. }
  228. /// Check if this string ends with the given \p Suffix.
  229. [[nodiscard]] bool ends_with(StringRef Suffix) const {
  230. return Length >= Suffix.Length &&
  231. compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) ==
  232. 0;
  233. }
  234. [[nodiscard]] bool endswith(StringRef Suffix) const {
  235. return ends_with(Suffix);
  236. }
  237. /// Check if this string ends with the given \p Suffix, ignoring case.
  238. [[nodiscard]] bool ends_with_insensitive(StringRef Suffix) const;
  239. [[nodiscard]] bool endswith_insensitive(StringRef Suffix) const {
  240. return ends_with_insensitive(Suffix);
  241. }
  242. /// @}
  243. /// @name String Searching
  244. /// @{
  245. /// Search for the first character \p C in the string.
  246. ///
  247. /// \returns The index of the first occurrence of \p C, or npos if not
  248. /// found.
  249. [[nodiscard]] size_t find(char C, size_t From = 0) const {
  250. return std::string_view(*this).find(C, From);
  251. }
  252. /// Search for the first character \p C in the string, ignoring case.
  253. ///
  254. /// \returns The index of the first occurrence of \p C, or npos if not
  255. /// found.
  256. [[nodiscard]] size_t find_insensitive(char C, size_t From = 0) const;
  257. /// Search for the first character satisfying the predicate \p F
  258. ///
  259. /// \returns The index of the first character satisfying \p F starting from
  260. /// \p From, or npos if not found.
  261. [[nodiscard]] size_t find_if(function_ref<bool(char)> F,
  262. size_t From = 0) const {
  263. StringRef S = drop_front(From);
  264. while (!S.empty()) {
  265. if (F(S.front()))
  266. return size() - S.size();
  267. S = S.drop_front();
  268. }
  269. return npos;
  270. }
  271. /// Search for the first character not satisfying the predicate \p F
  272. ///
  273. /// \returns The index of the first character not satisfying \p F starting
  274. /// from \p From, or npos if not found.
  275. [[nodiscard]] size_t find_if_not(function_ref<bool(char)> F,
  276. size_t From = 0) const {
  277. return find_if([F](char c) { return !F(c); }, From);
  278. }
  279. /// Search for the first string \p Str in the string.
  280. ///
  281. /// \returns The index of the first occurrence of \p Str, or npos if not
  282. /// found.
  283. [[nodiscard]] size_t find(StringRef Str, size_t From = 0) const;
  284. /// Search for the first string \p Str in the string, ignoring case.
  285. ///
  286. /// \returns The index of the first occurrence of \p Str, or npos if not
  287. /// found.
  288. [[nodiscard]] size_t find_insensitive(StringRef Str, size_t From = 0) const;
  289. /// Search for the last character \p C in the string.
  290. ///
  291. /// \returns The index of the last occurrence of \p C, or npos if not
  292. /// found.
  293. [[nodiscard]] size_t rfind(char C, size_t From = npos) const {
  294. From = std::min(From, Length);
  295. size_t i = From;
  296. while (i != 0) {
  297. --i;
  298. if (Data[i] == C)
  299. return i;
  300. }
  301. return npos;
  302. }
  303. /// Search for the last character \p C in the string, ignoring case.
  304. ///
  305. /// \returns The index of the last occurrence of \p C, or npos if not
  306. /// found.
  307. [[nodiscard]] size_t rfind_insensitive(char C, size_t From = npos) const;
  308. /// Search for the last string \p Str in the string.
  309. ///
  310. /// \returns The index of the last occurrence of \p Str, or npos if not
  311. /// found.
  312. [[nodiscard]] size_t rfind(StringRef Str) const;
  313. /// Search for the last string \p Str in the string, ignoring case.
  314. ///
  315. /// \returns The index of the last occurrence of \p Str, or npos if not
  316. /// found.
  317. [[nodiscard]] size_t rfind_insensitive(StringRef Str) const;
  318. /// Find the first character in the string that is \p C, or npos if not
  319. /// found. Same as find.
  320. [[nodiscard]] size_t find_first_of(char C, size_t From = 0) const {
  321. return find(C, From);
  322. }
  323. /// Find the first character in the string that is in \p Chars, or npos if
  324. /// not found.
  325. ///
  326. /// Complexity: O(size() + Chars.size())
  327. [[nodiscard]] size_t find_first_of(StringRef Chars, size_t From = 0) const;
  328. /// Find the first character in the string that is not \p C or npos if not
  329. /// found.
  330. [[nodiscard]] size_t find_first_not_of(char C, size_t From = 0) const;
  331. /// Find the first character in the string that is not in the string
  332. /// \p Chars, or npos if not found.
  333. ///
  334. /// Complexity: O(size() + Chars.size())
  335. [[nodiscard]] size_t find_first_not_of(StringRef Chars,
  336. size_t From = 0) const;
  337. /// Find the last character in the string that is \p C, or npos if not
  338. /// found.
  339. [[nodiscard]] size_t find_last_of(char C, size_t From = npos) const {
  340. return rfind(C, From);
  341. }
  342. /// Find the last character in the string that is in \p C, or npos if not
  343. /// found.
  344. ///
  345. /// Complexity: O(size() + Chars.size())
  346. [[nodiscard]] size_t find_last_of(StringRef Chars,
  347. size_t From = npos) const;
  348. /// Find the last character in the string that is not \p C, or npos if not
  349. /// found.
  350. [[nodiscard]] size_t find_last_not_of(char C, size_t From = npos) const;
  351. /// Find the last character in the string that is not in \p Chars, or
  352. /// npos if not found.
  353. ///
  354. /// Complexity: O(size() + Chars.size())
  355. [[nodiscard]] size_t find_last_not_of(StringRef Chars,
  356. size_t From = npos) const;
  357. /// Return true if the given string is a substring of *this, and false
  358. /// otherwise.
  359. [[nodiscard]] bool contains(StringRef Other) const {
  360. return find(Other) != npos;
  361. }
  362. /// Return true if the given character is contained in *this, and false
  363. /// otherwise.
  364. [[nodiscard]] bool contains(char C) const {
  365. return find_first_of(C) != npos;
  366. }
  367. /// Return true if the given string is a substring of *this, and false
  368. /// otherwise.
  369. [[nodiscard]] bool contains_insensitive(StringRef Other) const {
  370. return find_insensitive(Other) != npos;
  371. }
  372. /// Return true if the given character is contained in *this, and false
  373. /// otherwise.
  374. [[nodiscard]] bool contains_insensitive(char C) const {
  375. return find_insensitive(C) != npos;
  376. }
  377. /// @}
  378. /// @name Helpful Algorithms
  379. /// @{
  380. /// Return the number of occurrences of \p C in the string.
  381. [[nodiscard]] size_t count(char C) const {
  382. size_t Count = 0;
  383. for (size_t i = 0, e = Length; i != e; ++i)
  384. if (Data[i] == C)
  385. ++Count;
  386. return Count;
  387. }
  388. /// Return the number of non-overlapped occurrences of \p Str in
  389. /// the string.
  390. size_t count(StringRef Str) const;
  391. /// Parse the current string as an integer of the specified radix. If
  392. /// \p Radix is specified as zero, this does radix autosensing using
  393. /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
  394. ///
  395. /// If the string is invalid or if only a subset of the string is valid,
  396. /// this returns true to signify the error. The string is considered
  397. /// erroneous if empty or if it overflows T.
  398. template <typename T> bool getAsInteger(unsigned Radix, T &Result) const {
  399. if constexpr (std::numeric_limits<T>::is_signed) {
  400. long long LLVal;
  401. if (getAsSignedInteger(*this, Radix, LLVal) ||
  402. static_cast<T>(LLVal) != LLVal)
  403. return true;
  404. Result = LLVal;
  405. } else {
  406. unsigned long long ULLVal;
  407. // The additional cast to unsigned long long is required to avoid the
  408. // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
  409. // 'unsigned __int64' when instantiating getAsInteger with T = bool.
  410. if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
  411. static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
  412. return true;
  413. Result = ULLVal;
  414. }
  415. return false;
  416. }
  417. /// Parse the current string as an integer of the specified radix. If
  418. /// \p Radix is specified as zero, this does radix autosensing using
  419. /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
  420. ///
  421. /// If the string does not begin with a number of the specified radix,
  422. /// this returns true to signify the error. The string is considered
  423. /// erroneous if empty or if it overflows T.
  424. /// The portion of the string representing the discovered numeric value
  425. /// is removed from the beginning of the string.
  426. template <typename T> bool consumeInteger(unsigned Radix, T &Result) {
  427. if constexpr (std::numeric_limits<T>::is_signed) {
  428. long long LLVal;
  429. if (consumeSignedInteger(*this, Radix, LLVal) ||
  430. static_cast<long long>(static_cast<T>(LLVal)) != LLVal)
  431. return true;
  432. Result = LLVal;
  433. } else {
  434. unsigned long long ULLVal;
  435. if (consumeUnsignedInteger(*this, Radix, ULLVal) ||
  436. static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
  437. return true;
  438. Result = ULLVal;
  439. }
  440. return false;
  441. }
  442. /// Parse the current string as an integer of the specified \p Radix, or of
  443. /// an autosensed radix if the \p Radix given is 0. The current value in
  444. /// \p Result is discarded, and the storage is changed to be wide enough to
  445. /// store the parsed integer.
  446. ///
  447. /// \returns true if the string does not solely consist of a valid
  448. /// non-empty number in the appropriate base.
  449. ///
  450. /// APInt::fromString is superficially similar but assumes the
  451. /// string is well-formed in the given radix.
  452. bool getAsInteger(unsigned Radix, APInt &Result) const;
  453. /// Parse the current string as an IEEE double-precision floating
  454. /// point value. The string must be a well-formed double.
  455. ///
  456. /// If \p AllowInexact is false, the function will fail if the string
  457. /// cannot be represented exactly. Otherwise, the function only fails
  458. /// in case of an overflow or underflow, or an invalid floating point
  459. /// representation.
  460. bool getAsDouble(double &Result, bool AllowInexact = true) const;
  461. /// @}
  462. /// @name String Operations
  463. /// @{
  464. // Convert the given ASCII string to lowercase.
  465. [[nodiscard]] std::string lower() const;
  466. /// Convert the given ASCII string to uppercase.
  467. [[nodiscard]] std::string upper() const;
  468. /// @}
  469. /// @name Substring Operations
  470. /// @{
  471. /// Return a reference to the substring from [Start, Start + N).
  472. ///
  473. /// \param Start The index of the starting character in the substring; if
  474. /// the index is npos or greater than the length of the string then the
  475. /// empty substring will be returned.
  476. ///
  477. /// \param N The number of characters to included in the substring. If N
  478. /// exceeds the number of characters remaining in the string, the string
  479. /// suffix (starting with \p Start) will be returned.
  480. [[nodiscard]] constexpr StringRef substr(size_t Start,
  481. size_t N = npos) const {
  482. Start = std::min(Start, Length);
  483. return StringRef(Data + Start, std::min(N, Length - Start));
  484. }
  485. /// Return a StringRef equal to 'this' but with only the first \p N
  486. /// elements remaining. If \p N is greater than the length of the
  487. /// string, the entire string is returned.
  488. [[nodiscard]] StringRef take_front(size_t N = 1) const {
  489. if (N >= size())
  490. return *this;
  491. return drop_back(size() - N);
  492. }
  493. /// Return a StringRef equal to 'this' but with only the last \p N
  494. /// elements remaining. If \p N is greater than the length of the
  495. /// string, the entire string is returned.
  496. [[nodiscard]] StringRef take_back(size_t N = 1) const {
  497. if (N >= size())
  498. return *this;
  499. return drop_front(size() - N);
  500. }
  501. /// Return the longest prefix of 'this' such that every character
  502. /// in the prefix satisfies the given predicate.
  503. [[nodiscard]] StringRef take_while(function_ref<bool(char)> F) const {
  504. return substr(0, find_if_not(F));
  505. }
  506. /// Return the longest prefix of 'this' such that no character in
  507. /// the prefix satisfies the given predicate.
  508. [[nodiscard]] StringRef take_until(function_ref<bool(char)> F) const {
  509. return substr(0, find_if(F));
  510. }
  511. /// Return a StringRef equal to 'this' but with the first \p N elements
  512. /// dropped.
  513. [[nodiscard]] StringRef drop_front(size_t N = 1) const {
  514. assert(size() >= N && "Dropping more elements than exist");
  515. return substr(N);
  516. }
  517. /// Return a StringRef equal to 'this' but with the last \p N elements
  518. /// dropped.
  519. [[nodiscard]] StringRef drop_back(size_t N = 1) const {
  520. assert(size() >= N && "Dropping more elements than exist");
  521. return substr(0, size()-N);
  522. }
  523. /// Return a StringRef equal to 'this', but with all characters satisfying
  524. /// the given predicate dropped from the beginning of the string.
  525. [[nodiscard]] StringRef drop_while(function_ref<bool(char)> F) const {
  526. return substr(find_if_not(F));
  527. }
  528. /// Return a StringRef equal to 'this', but with all characters not
  529. /// satisfying the given predicate dropped from the beginning of the string.
  530. [[nodiscard]] StringRef drop_until(function_ref<bool(char)> F) const {
  531. return substr(find_if(F));
  532. }
  533. /// Returns true if this StringRef has the given prefix and removes that
  534. /// prefix.
  535. bool consume_front(StringRef Prefix) {
  536. if (!starts_with(Prefix))
  537. return false;
  538. *this = drop_front(Prefix.size());
  539. return true;
  540. }
  541. /// Returns true if this StringRef has the given prefix, ignoring case,
  542. /// and removes that prefix.
  543. bool consume_front_insensitive(StringRef Prefix) {
  544. if (!startswith_insensitive(Prefix))
  545. return false;
  546. *this = drop_front(Prefix.size());
  547. return true;
  548. }
  549. /// Returns true if this StringRef has the given suffix and removes that
  550. /// suffix.
  551. bool consume_back(StringRef Suffix) {
  552. if (!ends_with(Suffix))
  553. return false;
  554. *this = drop_back(Suffix.size());
  555. return true;
  556. }
  557. /// Returns true if this StringRef has the given suffix, ignoring case,
  558. /// and removes that suffix.
  559. bool consume_back_insensitive(StringRef Suffix) {
  560. if (!endswith_insensitive(Suffix))
  561. return false;
  562. *this = drop_back(Suffix.size());
  563. return true;
  564. }
  565. /// Return a reference to the substring from [Start, End).
  566. ///
  567. /// \param Start The index of the starting character in the substring; if
  568. /// the index is npos or greater than the length of the string then the
  569. /// empty substring will be returned.
  570. ///
  571. /// \param End The index following the last character to include in the
  572. /// substring. If this is npos or exceeds the number of characters
  573. /// remaining in the string, the string suffix (starting with \p Start)
  574. /// will be returned. If this is less than \p Start, an empty string will
  575. /// be returned.
  576. [[nodiscard]] StringRef slice(size_t Start, size_t End) const {
  577. Start = std::min(Start, Length);
  578. End = std::min(std::max(Start, End), Length);
  579. return StringRef(Data + Start, End - Start);
  580. }
  581. /// Split into two substrings around the first occurrence of a separator
  582. /// character.
  583. ///
  584. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  585. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  586. /// maximal. If \p Separator is not in the string, then the result is a
  587. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  588. ///
  589. /// \param Separator The character to split on.
  590. /// \returns The split substrings.
  591. [[nodiscard]] std::pair<StringRef, StringRef> split(char Separator) const {
  592. return split(StringRef(&Separator, 1));
  593. }
  594. /// Split into two substrings around the first occurrence of a separator
  595. /// string.
  596. ///
  597. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  598. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  599. /// maximal. If \p Separator is not in the string, then the result is a
  600. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  601. ///
  602. /// \param Separator - The string to split on.
  603. /// \return - The split substrings.
  604. [[nodiscard]] std::pair<StringRef, StringRef>
  605. split(StringRef Separator) const {
  606. size_t Idx = find(Separator);
  607. if (Idx == npos)
  608. return std::make_pair(*this, StringRef());
  609. return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
  610. }
  611. /// Split into two substrings around the last occurrence of a separator
  612. /// string.
  613. ///
  614. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  615. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  616. /// minimal. If \p Separator is not in the string, then the result is a
  617. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  618. ///
  619. /// \param Separator - The string to split on.
  620. /// \return - The split substrings.
  621. [[nodiscard]] std::pair<StringRef, StringRef>
  622. rsplit(StringRef Separator) const {
  623. size_t Idx = rfind(Separator);
  624. if (Idx == npos)
  625. return std::make_pair(*this, StringRef());
  626. return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
  627. }
  628. /// Split into substrings around the occurrences of a separator string.
  629. ///
  630. /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
  631. /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
  632. /// elements are added to A.
  633. /// If \p KeepEmpty is false, empty strings are not added to \p A. They
  634. /// still count when considering \p MaxSplit
  635. /// An useful invariant is that
  636. /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
  637. ///
  638. /// \param A - Where to put the substrings.
  639. /// \param Separator - The string to split on.
  640. /// \param MaxSplit - The maximum number of times the string is split.
  641. /// \param KeepEmpty - True if empty substring should be added.
  642. void split(SmallVectorImpl<StringRef> &A,
  643. StringRef Separator, int MaxSplit = -1,
  644. bool KeepEmpty = true) const;
  645. /// Split into substrings around the occurrences of a separator character.
  646. ///
  647. /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
  648. /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
  649. /// elements are added to A.
  650. /// If \p KeepEmpty is false, empty strings are not added to \p A. They
  651. /// still count when considering \p MaxSplit
  652. /// An useful invariant is that
  653. /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
  654. ///
  655. /// \param A - Where to put the substrings.
  656. /// \param Separator - The string to split on.
  657. /// \param MaxSplit - The maximum number of times the string is split.
  658. /// \param KeepEmpty - True if empty substring should be added.
  659. void split(SmallVectorImpl<StringRef> &A, char Separator, int MaxSplit = -1,
  660. bool KeepEmpty = true) const;
  661. /// Split into two substrings around the last occurrence of a separator
  662. /// character.
  663. ///
  664. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  665. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  666. /// minimal. If \p Separator is not in the string, then the result is a
  667. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  668. ///
  669. /// \param Separator - The character to split on.
  670. /// \return - The split substrings.
  671. [[nodiscard]] std::pair<StringRef, StringRef> rsplit(char Separator) const {
  672. return rsplit(StringRef(&Separator, 1));
  673. }
  674. /// Return string with consecutive \p Char characters starting from the
  675. /// the left removed.
  676. [[nodiscard]] StringRef ltrim(char Char) const {
  677. return drop_front(std::min(Length, find_first_not_of(Char)));
  678. }
  679. /// Return string with consecutive characters in \p Chars starting from
  680. /// the left removed.
  681. [[nodiscard]] StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
  682. return drop_front(std::min(Length, find_first_not_of(Chars)));
  683. }
  684. /// Return string with consecutive \p Char characters starting from the
  685. /// right removed.
  686. [[nodiscard]] StringRef rtrim(char Char) const {
  687. return drop_back(Length - std::min(Length, find_last_not_of(Char) + 1));
  688. }
  689. /// Return string with consecutive characters in \p Chars starting from
  690. /// the right removed.
  691. [[nodiscard]] StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
  692. return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
  693. }
  694. /// Return string with consecutive \p Char characters starting from the
  695. /// left and right removed.
  696. [[nodiscard]] StringRef trim(char Char) const {
  697. return ltrim(Char).rtrim(Char);
  698. }
  699. /// Return string with consecutive characters in \p Chars starting from
  700. /// the left and right removed.
  701. [[nodiscard]] StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
  702. return ltrim(Chars).rtrim(Chars);
  703. }
  704. /// Detect the line ending style of the string.
  705. ///
  706. /// If the string contains a line ending, return the line ending character
  707. /// sequence that is detected. Otherwise return '\n' for unix line endings.
  708. ///
  709. /// \return - The line ending character sequence.
  710. [[nodiscard]] StringRef detectEOL() const {
  711. size_t Pos = find('\r');
  712. if (Pos == npos) {
  713. // If there is no carriage return, assume unix
  714. return "\n";
  715. }
  716. if (Pos + 1 < Length && Data[Pos + 1] == '\n')
  717. return "\r\n"; // Windows
  718. if (Pos > 0 && Data[Pos - 1] == '\n')
  719. return "\n\r"; // You monster!
  720. return "\r"; // Classic Mac
  721. }
  722. /// @}
  723. };
  724. /// A wrapper around a string literal that serves as a proxy for constructing
  725. /// global tables of StringRefs with the length computed at compile time.
  726. /// In order to avoid the invocation of a global constructor, StringLiteral
  727. /// should *only* be used in a constexpr context, as such:
  728. ///
  729. /// constexpr StringLiteral S("test");
  730. ///
  731. class StringLiteral : public StringRef {
  732. private:
  733. constexpr StringLiteral(const char *Str, size_t N) : StringRef(Str, N) {
  734. }
  735. public:
  736. template <size_t N>
  737. constexpr StringLiteral(const char (&Str)[N])
  738. #if defined(__clang__) && __has_attribute(enable_if)
  739. #pragma clang diagnostic push
  740. #pragma clang diagnostic ignored "-Wgcc-compat"
  741. __attribute((enable_if(__builtin_strlen(Str) == N - 1,
  742. "invalid string literal")))
  743. #pragma clang diagnostic pop
  744. #endif
  745. : StringRef(Str, N - 1) {
  746. }
  747. // Explicit construction for strings like "foo\0bar".
  748. template <size_t N>
  749. static constexpr StringLiteral withInnerNUL(const char (&Str)[N]) {
  750. return StringLiteral(Str, N - 1);
  751. }
  752. };
  753. /// @name StringRef Comparison Operators
  754. /// @{
  755. inline bool operator==(StringRef LHS, StringRef RHS) {
  756. return LHS.equals(RHS);
  757. }
  758. inline bool operator!=(StringRef LHS, StringRef RHS) { return !(LHS == RHS); }
  759. inline bool operator<(StringRef LHS, StringRef RHS) {
  760. return LHS.compare(RHS) < 0;
  761. }
  762. inline bool operator<=(StringRef LHS, StringRef RHS) {
  763. return LHS.compare(RHS) <= 0;
  764. }
  765. inline bool operator>(StringRef LHS, StringRef RHS) {
  766. return LHS.compare(RHS) > 0;
  767. }
  768. inline bool operator>=(StringRef LHS, StringRef RHS) {
  769. return LHS.compare(RHS) >= 0;
  770. }
  771. inline std::string &operator+=(std::string &buffer, StringRef string) {
  772. return buffer.append(string.data(), string.size());
  773. }
  774. /// @}
  775. /// Compute a hash_code for a StringRef.
  776. [[nodiscard]] hash_code hash_value(StringRef S);
  777. // Provide DenseMapInfo for StringRefs.
  778. template <> struct DenseMapInfo<StringRef, void> {
  779. static inline StringRef getEmptyKey() {
  780. return StringRef(
  781. reinterpret_cast<const char *>(~static_cast<uintptr_t>(0)), 0);
  782. }
  783. static inline StringRef getTombstoneKey() {
  784. return StringRef(
  785. reinterpret_cast<const char *>(~static_cast<uintptr_t>(1)), 0);
  786. }
  787. static unsigned getHashValue(StringRef Val);
  788. static bool isEqual(StringRef LHS, StringRef RHS) {
  789. if (RHS.data() == getEmptyKey().data())
  790. return LHS.data() == getEmptyKey().data();
  791. if (RHS.data() == getTombstoneKey().data())
  792. return LHS.data() == getTombstoneKey().data();
  793. return LHS == RHS;
  794. }
  795. };
  796. } // end namespace llvm
  797. #endif // LLVM_ADT_STRINGREF_H
  798. #ifdef __GNUC__
  799. #pragma GCC diagnostic pop
  800. #endif