StringRef.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. //===--- StringRef.h - Constant String Reference Wrapper --------*- 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. #ifndef LLVM_ADT_STRINGREF_H
  10. #define LLVM_ADT_STRINGREF_H
  11. #include <algorithm>
  12. #include <cassert>
  13. #include <cstring>
  14. #include <limits>
  15. #include <string>
  16. #include <utility>
  17. namespace llvm {
  18. template <typename T>
  19. class SmallVectorImpl;
  20. class APInt;
  21. class hash_code;
  22. class StringRef;
  23. /// Helper functions for StringRef::getAsInteger.
  24. bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
  25. unsigned long long &Result);
  26. bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
  27. /// StringRef - Represent a constant reference to a string, i.e. a character
  28. /// array and a length, which need not be null terminated.
  29. ///
  30. /// This class does not own the string data, it is expected to be used in
  31. /// situations where the character data resides in some other buffer, whose
  32. /// lifetime extends past that of the StringRef. For this reason, it is not in
  33. /// general safe to store a StringRef.
  34. class StringRef {
  35. public:
  36. typedef const char *iterator;
  37. typedef const char *const_iterator;
  38. static const size_t npos = ~size_t(0);
  39. typedef size_t size_type;
  40. private:
  41. /// The start of the string, in an external buffer.
  42. const char *Data;
  43. /// The length of the string.
  44. size_t Length;
  45. // Workaround memcmp issue with null pointers (undefined behavior)
  46. // by providing a specialized version
  47. static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
  48. if (Length == 0) { return 0; }
  49. return ::memcmp(Lhs,Rhs,Length);
  50. }
  51. public:
  52. /// @name Constructors
  53. /// @{
  54. /// Construct an empty string ref.
  55. /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
  56. StringRef(std::nullptr_t) = delete; // HLSL Change - So we don't accidentally pass `false` again
  57. /// Construct a string ref from a cstring.
  58. /*implicit*/ StringRef(const char *Str)
  59. : Data(Str) {
  60. assert(Str && "StringRef cannot be built from a NULL argument");
  61. Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
  62. }
  63. /// Construct a string ref from a pointer and length.
  64. /*implicit*/ StringRef(const char *data, size_t length)
  65. : Data(data), Length(length) {
  66. assert((data || length == 0) &&
  67. "StringRef cannot be built from a NULL argument with non-null length");
  68. }
  69. /// Construct a string ref from an std::string.
  70. /*implicit*/ StringRef(const std::string &Str)
  71. : Data(Str.data()), Length(Str.length()) {}
  72. /// @}
  73. /// @name Iterators
  74. /// @{
  75. iterator begin() const { return Data; }
  76. iterator end() const { return Data + Length; }
  77. const unsigned char *bytes_begin() const {
  78. return reinterpret_cast<const unsigned char *>(begin());
  79. }
  80. const unsigned char *bytes_end() const {
  81. return reinterpret_cast<const unsigned char *>(end());
  82. }
  83. /// @}
  84. /// @name String Operations
  85. /// @{
  86. /// data - Get a pointer to the start of the string (which may not be null
  87. /// terminated).
  88. const char *data() const { return Data; }
  89. /// empty - Check if the string is empty.
  90. bool empty() const { return Length == 0; }
  91. /// size - Get the string size.
  92. size_t size() const { return Length; }
  93. /// front - Get the first character in the string.
  94. char front() const {
  95. assert(!empty());
  96. return Data[0];
  97. }
  98. /// back - Get the last character in the string.
  99. char back() const {
  100. assert(!empty());
  101. return Data[Length-1];
  102. }
  103. // copy - Allocate copy in Allocator and return StringRef to it.
  104. template <typename Allocator> StringRef copy(Allocator &A) const {
  105. char *S = A.template Allocate<char>(Length);
  106. std::copy(begin(), end(), S);
  107. return StringRef(S, Length);
  108. }
  109. /// equals - Check for string equality, this is more efficient than
  110. /// compare() when the relative ordering of inequal strings isn't needed.
  111. bool equals(StringRef RHS) const {
  112. return (Length == RHS.Length &&
  113. compareMemory(Data, RHS.Data, RHS.Length) == 0);
  114. }
  115. /// equals_lower - Check for string equality, ignoring case.
  116. bool equals_lower(StringRef RHS) const {
  117. return Length == RHS.Length && compare_lower(RHS) == 0;
  118. }
  119. /// compare - Compare two strings; the result is -1, 0, or 1 if this string
  120. /// is lexicographically less than, equal to, or greater than the \p RHS.
  121. int compare(StringRef RHS) const {
  122. // Check the prefix for a mismatch.
  123. if (int Res = compareMemory(Data, RHS.Data, std::min(Length, RHS.Length)))
  124. return Res < 0 ? -1 : 1;
  125. // Otherwise the prefixes match, so we only need to check the lengths.
  126. if (Length == RHS.Length)
  127. return 0;
  128. return Length < RHS.Length ? -1 : 1;
  129. }
  130. /// compare_lower - Compare two strings, ignoring case.
  131. int compare_lower(StringRef RHS) const;
  132. /// compare_numeric - Compare two strings, treating sequences of digits as
  133. /// numbers.
  134. int compare_numeric(StringRef RHS) const;
  135. /// \brief Determine the edit distance between this string and another
  136. /// string.
  137. ///
  138. /// \param Other the string to compare this string against.
  139. ///
  140. /// \param AllowReplacements whether to allow character
  141. /// replacements (change one character into another) as a single
  142. /// operation, rather than as two operations (an insertion and a
  143. /// removal).
  144. ///
  145. /// \param MaxEditDistance If non-zero, the maximum edit distance that
  146. /// this routine is allowed to compute. If the edit distance will exceed
  147. /// that maximum, returns \c MaxEditDistance+1.
  148. ///
  149. /// \returns the minimum number of character insertions, removals,
  150. /// or (if \p AllowReplacements is \c true) replacements needed to
  151. /// transform one of the given strings into the other. If zero,
  152. /// the strings are identical.
  153. unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
  154. unsigned MaxEditDistance = 0) const;
  155. /// str - Get the contents as an std::string.
  156. std::string str() const {
  157. if (!Data) return std::string();
  158. return std::string(Data, Length);
  159. }
  160. /// @}
  161. /// @name Operator Overloads
  162. /// @{
  163. char operator[](size_t Index) const {
  164. assert(Index < Length && "Invalid index!");
  165. return Data[Index];
  166. }
  167. /// @}
  168. /// @name Type Conversions
  169. /// @{
  170. operator std::string() const {
  171. return str();
  172. }
  173. /// @}
  174. /// @name String Predicates
  175. /// @{
  176. /// Check if this string starts with the given \p Prefix.
  177. bool startswith(StringRef Prefix) const {
  178. return Length >= Prefix.Length &&
  179. compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
  180. }
  181. /// Check if this string starts with the given \p Prefix, ignoring case.
  182. bool startswith_lower(StringRef Prefix) const;
  183. /// Check if this string ends with the given \p Suffix.
  184. bool endswith(StringRef Suffix) const {
  185. return Length >= Suffix.Length &&
  186. compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
  187. }
  188. /// Check if this string ends with the given \p Suffix, ignoring case.
  189. bool endswith_lower(StringRef Suffix) const;
  190. /// @}
  191. /// @name String Searching
  192. /// @{
  193. /// Search for the first character \p C in the string.
  194. ///
  195. /// \returns The index of the first occurrence of \p C, or npos if not
  196. /// found.
  197. size_t find(char C, size_t From = 0) const {
  198. size_t FindBegin = std::min(From, Length);
  199. if (FindBegin < Length) { // Avoid calling memchr with nullptr.
  200. // Just forward to memchr, which is faster than a hand-rolled loop.
  201. if (const void *P = ::memchr(Data + FindBegin, C, Length - FindBegin))
  202. return static_cast<const char *>(P) - Data;
  203. }
  204. return npos;
  205. }
  206. /// Search for the first string \p Str in the string.
  207. ///
  208. /// \returns The index of the first occurrence of \p Str, or npos if not
  209. /// found.
  210. size_t find(StringRef Str, size_t From = 0) const;
  211. /// Search for the last character \p C in the string.
  212. ///
  213. /// \returns The index of the last occurrence of \p C, or npos if not
  214. /// found.
  215. size_t rfind(char C, size_t From = npos) const {
  216. From = std::min(From, Length);
  217. size_t i = From;
  218. while (i != 0) {
  219. --i;
  220. if (Data[i] == C)
  221. return i;
  222. }
  223. return npos;
  224. }
  225. /// Search for the last string \p Str in the string.
  226. ///
  227. /// \returns The index of the last occurrence of \p Str, or npos if not
  228. /// found.
  229. size_t rfind(StringRef Str) const;
  230. /// Find the first character in the string that is \p C, or npos if not
  231. /// found. Same as find.
  232. size_t find_first_of(char C, size_t From = 0) const {
  233. return find(C, From);
  234. }
  235. /// Find the first character in the string that is in \p Chars, or npos if
  236. /// not found.
  237. ///
  238. /// Complexity: O(size() + Chars.size())
  239. size_t find_first_of(StringRef Chars, size_t From = 0) const;
  240. /// Find the first character in the string that is not \p C or npos if not
  241. /// found.
  242. size_t find_first_not_of(char C, size_t From = 0) const;
  243. /// Find the first character in the string that is not in the string
  244. /// \p Chars, or npos if not found.
  245. ///
  246. /// Complexity: O(size() + Chars.size())
  247. size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
  248. /// Find the last character in the string that is \p C, or npos if not
  249. /// found.
  250. size_t find_last_of(char C, size_t From = npos) const {
  251. return rfind(C, From);
  252. }
  253. /// Find the last character in the string that is in \p C, or npos if not
  254. /// found.
  255. ///
  256. /// Complexity: O(size() + Chars.size())
  257. size_t find_last_of(StringRef Chars, size_t From = npos) const;
  258. /// Find the last character in the string that is not \p C, or npos if not
  259. /// found.
  260. size_t find_last_not_of(char C, size_t From = npos) const;
  261. /// Find the last character in the string that is not in \p Chars, or
  262. /// npos if not found.
  263. ///
  264. /// Complexity: O(size() + Chars.size())
  265. size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
  266. /// @}
  267. /// @name Helpful Algorithms
  268. /// @{
  269. /// Return the number of occurrences of \p C in the string.
  270. size_t count(char C) const {
  271. size_t Count = 0;
  272. for (size_t i = 0, e = Length; i != e; ++i)
  273. if (Data[i] == C)
  274. ++Count;
  275. return Count;
  276. }
  277. /// Return the number of non-overlapped occurrences of \p Str in
  278. /// the string.
  279. size_t count(StringRef Str) const;
  280. /// Parse the current string as an integer of the specified radix. If
  281. /// \p Radix is specified as zero, this does radix autosensing using
  282. /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
  283. ///
  284. /// If the string is invalid or if only a subset of the string is valid,
  285. /// this returns true to signify the error. The string is considered
  286. /// erroneous if empty or if it overflows T.
  287. template <typename T>
  288. typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
  289. getAsInteger(unsigned Radix, T &Result) const {
  290. long long LLVal;
  291. if (getAsSignedInteger(*this, Radix, LLVal) ||
  292. static_cast<T>(LLVal) != LLVal)
  293. return true;
  294. Result = LLVal;
  295. return false;
  296. }
  297. template <typename T>
  298. typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
  299. getAsInteger(unsigned Radix, T &Result) const {
  300. unsigned long long ULLVal;
  301. // The additional cast to unsigned long long is required to avoid the
  302. // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
  303. // 'unsigned __int64' when instantiating getAsInteger with T = bool.
  304. if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
  305. static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
  306. return true;
  307. Result = ULLVal;
  308. return false;
  309. }
  310. /// Parse the current string as an integer of the specified \p Radix, or of
  311. /// an autosensed radix if the \p Radix given is 0. The current value in
  312. /// \p Result is discarded, and the storage is changed to be wide enough to
  313. /// store the parsed integer.
  314. ///
  315. /// \returns true if the string does not solely consist of a valid
  316. /// non-empty number in the appropriate base.
  317. ///
  318. /// APInt::fromString is superficially similar but assumes the
  319. /// string is well-formed in the given radix.
  320. bool getAsInteger(unsigned Radix, APInt &Result) const;
  321. /// @}
  322. /// @name String Operations
  323. /// @{
  324. // Convert the given ASCII string to lowercase.
  325. std::string lower() const;
  326. /// Convert the given ASCII string to uppercase.
  327. std::string upper() const;
  328. /// @}
  329. /// @name Substring Operations
  330. /// @{
  331. /// Return a reference to the substring from [Start, Start + N).
  332. ///
  333. /// \param Start The index of the starting character in the substring; if
  334. /// the index is npos or greater than the length of the string then the
  335. /// empty substring will be returned.
  336. ///
  337. /// \param N The number of characters to included in the substring. If N
  338. /// exceeds the number of characters remaining in the string, the string
  339. /// suffix (starting with \p Start) will be returned.
  340. StringRef substr(size_t Start, size_t N = npos) const {
  341. Start = std::min(Start, Length);
  342. return StringRef(Data + Start, std::min(N, Length - Start));
  343. }
  344. /// Return a StringRef equal to 'this' but with the first \p N elements
  345. /// dropped.
  346. StringRef drop_front(size_t N = 1) const {
  347. assert(size() >= N && "Dropping more elements than exist");
  348. return substr(N);
  349. }
  350. /// Return a StringRef equal to 'this' but with the last \p N elements
  351. /// dropped.
  352. StringRef drop_back(size_t N = 1) const {
  353. assert(size() >= N && "Dropping more elements than exist");
  354. return substr(0, size()-N);
  355. }
  356. /// Return a reference to the substring from [Start, End).
  357. ///
  358. /// \param Start The index of the starting character in the substring; if
  359. /// the index is npos or greater than the length of the string then the
  360. /// empty substring will be returned.
  361. ///
  362. /// \param End The index following the last character to include in the
  363. /// substring. If this is npos, or less than \p Start, or exceeds the
  364. /// number of characters remaining in the string, the string suffix
  365. /// (starting with \p Start) will be returned.
  366. StringRef slice(size_t Start, size_t End) const {
  367. Start = std::min(Start, Length);
  368. End = std::min(std::max(Start, End), Length);
  369. return StringRef(Data + Start, End - Start);
  370. }
  371. /// Split into two substrings around the first occurrence of a separator
  372. /// character.
  373. ///
  374. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  375. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  376. /// maximal. If \p Separator is not in the string, then the result is a
  377. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  378. ///
  379. /// \param Separator The character to split on.
  380. /// \returns The split substrings.
  381. std::pair<StringRef, StringRef> split(char Separator) const {
  382. size_t Idx = find(Separator);
  383. if (Idx == npos)
  384. return std::make_pair(*this, StringRef());
  385. return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
  386. }
  387. /// Split into two substrings around the first occurrence of a separator
  388. /// string.
  389. ///
  390. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  391. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  392. /// maximal. If \p Separator is not in the string, then the result is a
  393. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  394. ///
  395. /// \param Separator - The string to split on.
  396. /// \return - The split substrings.
  397. std::pair<StringRef, StringRef> split(StringRef Separator) const {
  398. size_t Idx = find(Separator);
  399. if (Idx == npos)
  400. return std::make_pair(*this, StringRef());
  401. return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
  402. }
  403. /// Split into substrings around the occurrences of a separator string.
  404. ///
  405. /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
  406. /// \p MaxSplit splits are done and consequently <= \p MaxSplit
  407. /// elements are added to A.
  408. /// If \p KeepEmpty is false, empty strings are not added to \p A. They
  409. /// still count when considering \p MaxSplit
  410. /// An useful invariant is that
  411. /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
  412. ///
  413. /// \param A - Where to put the substrings.
  414. /// \param Separator - The string to split on.
  415. /// \param MaxSplit - The maximum number of times the string is split.
  416. /// \param KeepEmpty - True if empty substring should be added.
  417. void split(SmallVectorImpl<StringRef> &A,
  418. StringRef Separator, int MaxSplit = -1,
  419. bool KeepEmpty = true) const;
  420. /// Split into two substrings around the last occurrence of a separator
  421. /// character.
  422. ///
  423. /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
  424. /// such that (*this == LHS + Separator + RHS) is true and RHS is
  425. /// minimal. If \p Separator is not in the string, then the result is a
  426. /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
  427. ///
  428. /// \param Separator - The character to split on.
  429. /// \return - The split substrings.
  430. std::pair<StringRef, StringRef> rsplit(char Separator) const {
  431. size_t Idx = rfind(Separator);
  432. if (Idx == npos)
  433. return std::make_pair(*this, StringRef());
  434. return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
  435. }
  436. /// Return string with consecutive characters in \p Chars starting from
  437. /// the left removed.
  438. StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
  439. return drop_front(std::min(Length, find_first_not_of(Chars)));
  440. }
  441. /// Return string with consecutive characters in \p Chars starting from
  442. /// the right removed.
  443. StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
  444. return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
  445. }
  446. /// Return string with consecutive characters in \p Chars starting from
  447. /// the left and right removed.
  448. StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
  449. return ltrim(Chars).rtrim(Chars);
  450. }
  451. /// @}
  452. };
  453. /// @name StringRef Comparison Operators
  454. /// @{
  455. inline bool operator==(StringRef LHS, StringRef RHS) {
  456. return LHS.equals(RHS);
  457. }
  458. inline bool operator!=(StringRef LHS, StringRef RHS) {
  459. return !(LHS == RHS);
  460. }
  461. inline bool operator<(StringRef LHS, StringRef RHS) {
  462. return LHS.compare(RHS) == -1;
  463. }
  464. inline bool operator<=(StringRef LHS, StringRef RHS) {
  465. return LHS.compare(RHS) != 1;
  466. }
  467. inline bool operator>(StringRef LHS, StringRef RHS) {
  468. return LHS.compare(RHS) == 1;
  469. }
  470. inline bool operator>=(StringRef LHS, StringRef RHS) {
  471. return LHS.compare(RHS) != -1;
  472. }
  473. inline std::string &operator+=(std::string &buffer, StringRef string) {
  474. return buffer.append(string.data(), string.size());
  475. }
  476. /// @}
  477. /// \brief Compute a hash_code for a StringRef.
  478. hash_code hash_value(StringRef S);
  479. // StringRefs can be treated like a POD type.
  480. template <typename T> struct isPodLike;
  481. template <> struct isPodLike<StringRef> { static const bool value = true; };
  482. }
  483. // HLSL Change Starts
  484. // StringRef provides an operator string; that trips up the std::pair noexcept specification,
  485. // which (a) enables the moves constructor (because conversion is allowed), but (b)
  486. // misclassifies the the construction as nothrow.
  487. namespace std {
  488. template<>
  489. struct is_nothrow_constructible <std::string, llvm::StringRef>
  490. : std::false_type {
  491. };
  492. template<>
  493. struct is_nothrow_constructible <std::string, llvm::StringRef &>
  494. : std::false_type {
  495. };
  496. template<>
  497. struct is_nothrow_constructible <std::string, const llvm::StringRef &>
  498. : std::false_type {
  499. };
  500. }
  501. // HLSL Change Ends
  502. #endif