StringRef.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. //===-- StringRef.cpp - Lightweight String References ---------------------===//
  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. #include "llvm/ADT/StringRef.h"
  9. #include "llvm/ADT/APFloat.h"
  10. #include "llvm/ADT/APInt.h"
  11. #include "llvm/ADT/Hashing.h"
  12. #include "llvm/ADT/StringExtras.h"
  13. #include "llvm/ADT/edit_distance.h"
  14. #include "llvm/Support/Error.h"
  15. #include <bitset>
  16. using namespace llvm;
  17. // MSVC emits references to this into the translation units which reference it.
  18. #ifndef _MSC_VER
  19. constexpr size_t StringRef::npos;
  20. #endif
  21. // strncasecmp() is not available on non-POSIX systems, so define an
  22. // alternative function here.
  23. static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) {
  24. for (size_t I = 0; I < Length; ++I) {
  25. unsigned char LHC = toLower(LHS[I]);
  26. unsigned char RHC = toLower(RHS[I]);
  27. if (LHC != RHC)
  28. return LHC < RHC ? -1 : 1;
  29. }
  30. return 0;
  31. }
  32. int StringRef::compare_insensitive(StringRef RHS) const {
  33. if (int Res = ascii_strncasecmp(Data, RHS.Data, std::min(Length, RHS.Length)))
  34. return Res;
  35. if (Length == RHS.Length)
  36. return 0;
  37. return Length < RHS.Length ? -1 : 1;
  38. }
  39. bool StringRef::startswith_insensitive(StringRef Prefix) const {
  40. return Length >= Prefix.Length &&
  41. ascii_strncasecmp(Data, Prefix.Data, Prefix.Length) == 0;
  42. }
  43. bool StringRef::endswith_insensitive(StringRef Suffix) const {
  44. return Length >= Suffix.Length &&
  45. ascii_strncasecmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
  46. }
  47. size_t StringRef::find_insensitive(char C, size_t From) const {
  48. char L = toLower(C);
  49. return find_if([L](char D) { return toLower(D) == L; }, From);
  50. }
  51. /// compare_numeric - Compare strings, handle embedded numbers.
  52. int StringRef::compare_numeric(StringRef RHS) const {
  53. for (size_t I = 0, E = std::min(Length, RHS.Length); I != E; ++I) {
  54. // Check for sequences of digits.
  55. if (isDigit(Data[I]) && isDigit(RHS.Data[I])) {
  56. // The longer sequence of numbers is considered larger.
  57. // This doesn't really handle prefixed zeros well.
  58. size_t J;
  59. for (J = I + 1; J != E + 1; ++J) {
  60. bool ld = J < Length && isDigit(Data[J]);
  61. bool rd = J < RHS.Length && isDigit(RHS.Data[J]);
  62. if (ld != rd)
  63. return rd ? -1 : 1;
  64. if (!rd)
  65. break;
  66. }
  67. // The two number sequences have the same length (J-I), just memcmp them.
  68. if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
  69. return Res < 0 ? -1 : 1;
  70. // Identical number sequences, continue search after the numbers.
  71. I = J - 1;
  72. continue;
  73. }
  74. if (Data[I] != RHS.Data[I])
  75. return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
  76. }
  77. if (Length == RHS.Length)
  78. return 0;
  79. return Length < RHS.Length ? -1 : 1;
  80. }
  81. // Compute the edit distance between the two given strings.
  82. unsigned StringRef::edit_distance(llvm::StringRef Other,
  83. bool AllowReplacements,
  84. unsigned MaxEditDistance) const {
  85. return llvm::ComputeEditDistance(
  86. makeArrayRef(data(), size()),
  87. makeArrayRef(Other.data(), Other.size()),
  88. AllowReplacements, MaxEditDistance);
  89. }
  90. //===----------------------------------------------------------------------===//
  91. // String Operations
  92. //===----------------------------------------------------------------------===//
  93. std::string StringRef::lower() const {
  94. return std::string(map_iterator(begin(), toLower),
  95. map_iterator(end(), toLower));
  96. }
  97. std::string StringRef::upper() const {
  98. return std::string(map_iterator(begin(), toUpper),
  99. map_iterator(end(), toUpper));
  100. }
  101. //===----------------------------------------------------------------------===//
  102. // String Searching
  103. //===----------------------------------------------------------------------===//
  104. /// find - Search for the first string \arg Str in the string.
  105. ///
  106. /// \return - The index of the first occurrence of \arg Str, or npos if not
  107. /// found.
  108. size_t StringRef::find(StringRef Str, size_t From) const {
  109. if (From > Length)
  110. return npos;
  111. const char *Start = Data + From;
  112. size_t Size = Length - From;
  113. const char *Needle = Str.data();
  114. size_t N = Str.size();
  115. if (N == 0)
  116. return From;
  117. if (Size < N)
  118. return npos;
  119. if (N == 1) {
  120. const char *Ptr = (const char *)::memchr(Start, Needle[0], Size);
  121. return Ptr == nullptr ? npos : Ptr - Data;
  122. }
  123. const char *Stop = Start + (Size - N + 1);
  124. // For short haystacks or unsupported needles fall back to the naive algorithm
  125. if (Size < 16 || N > 255) {
  126. do {
  127. if (std::memcmp(Start, Needle, N) == 0)
  128. return Start - Data;
  129. ++Start;
  130. } while (Start < Stop);
  131. return npos;
  132. }
  133. // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
  134. uint8_t BadCharSkip[256];
  135. std::memset(BadCharSkip, N, 256);
  136. for (unsigned i = 0; i != N-1; ++i)
  137. BadCharSkip[(uint8_t)Str[i]] = N-1-i;
  138. do {
  139. uint8_t Last = Start[N - 1];
  140. if (LLVM_UNLIKELY(Last == (uint8_t)Needle[N - 1]))
  141. if (std::memcmp(Start, Needle, N - 1) == 0)
  142. return Start - Data;
  143. // Otherwise skip the appropriate number of bytes.
  144. Start += BadCharSkip[Last];
  145. } while (Start < Stop);
  146. return npos;
  147. }
  148. size_t StringRef::find_insensitive(StringRef Str, size_t From) const {
  149. StringRef This = substr(From);
  150. while (This.size() >= Str.size()) {
  151. if (This.startswith_insensitive(Str))
  152. return From;
  153. This = This.drop_front();
  154. ++From;
  155. }
  156. return npos;
  157. }
  158. size_t StringRef::rfind_insensitive(char C, size_t From) const {
  159. From = std::min(From, Length);
  160. size_t i = From;
  161. while (i != 0) {
  162. --i;
  163. if (toLower(Data[i]) == toLower(C))
  164. return i;
  165. }
  166. return npos;
  167. }
  168. /// rfind - Search for the last string \arg Str in the string.
  169. ///
  170. /// \return - The index of the last occurrence of \arg Str, or npos if not
  171. /// found.
  172. size_t StringRef::rfind(StringRef Str) const {
  173. size_t N = Str.size();
  174. if (N > Length)
  175. return npos;
  176. for (size_t i = Length - N + 1, e = 0; i != e;) {
  177. --i;
  178. if (substr(i, N).equals(Str))
  179. return i;
  180. }
  181. return npos;
  182. }
  183. size_t StringRef::rfind_insensitive(StringRef Str) const {
  184. size_t N = Str.size();
  185. if (N > Length)
  186. return npos;
  187. for (size_t i = Length - N + 1, e = 0; i != e;) {
  188. --i;
  189. if (substr(i, N).equals_insensitive(Str))
  190. return i;
  191. }
  192. return npos;
  193. }
  194. /// find_first_of - Find the first character in the string that is in \arg
  195. /// Chars, or npos if not found.
  196. ///
  197. /// Note: O(size() + Chars.size())
  198. StringRef::size_type StringRef::find_first_of(StringRef Chars,
  199. size_t From) const {
  200. std::bitset<1 << CHAR_BIT> CharBits;
  201. for (char C : Chars)
  202. CharBits.set((unsigned char)C);
  203. for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
  204. if (CharBits.test((unsigned char)Data[i]))
  205. return i;
  206. return npos;
  207. }
  208. /// find_first_not_of - Find the first character in the string that is not
  209. /// \arg C or npos if not found.
  210. StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
  211. for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
  212. if (Data[i] != C)
  213. return i;
  214. return npos;
  215. }
  216. /// find_first_not_of - Find the first character in the string that is not
  217. /// in the string \arg Chars, or npos if not found.
  218. ///
  219. /// Note: O(size() + Chars.size())
  220. StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
  221. size_t From) const {
  222. std::bitset<1 << CHAR_BIT> CharBits;
  223. for (char C : Chars)
  224. CharBits.set((unsigned char)C);
  225. for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
  226. if (!CharBits.test((unsigned char)Data[i]))
  227. return i;
  228. return npos;
  229. }
  230. /// find_last_of - Find the last character in the string that is in \arg C,
  231. /// or npos if not found.
  232. ///
  233. /// Note: O(size() + Chars.size())
  234. StringRef::size_type StringRef::find_last_of(StringRef Chars,
  235. size_t From) const {
  236. std::bitset<1 << CHAR_BIT> CharBits;
  237. for (char C : Chars)
  238. CharBits.set((unsigned char)C);
  239. for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
  240. if (CharBits.test((unsigned char)Data[i]))
  241. return i;
  242. return npos;
  243. }
  244. /// find_last_not_of - Find the last character in the string that is not
  245. /// \arg C, or npos if not found.
  246. StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const {
  247. for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
  248. if (Data[i] != C)
  249. return i;
  250. return npos;
  251. }
  252. /// find_last_not_of - Find the last character in the string that is not in
  253. /// \arg Chars, or npos if not found.
  254. ///
  255. /// Note: O(size() + Chars.size())
  256. StringRef::size_type StringRef::find_last_not_of(StringRef Chars,
  257. size_t From) const {
  258. std::bitset<1 << CHAR_BIT> CharBits;
  259. for (char C : Chars)
  260. CharBits.set((unsigned char)C);
  261. for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
  262. if (!CharBits.test((unsigned char)Data[i]))
  263. return i;
  264. return npos;
  265. }
  266. void StringRef::split(SmallVectorImpl<StringRef> &A,
  267. StringRef Separator, int MaxSplit,
  268. bool KeepEmpty) const {
  269. StringRef S = *this;
  270. // Count down from MaxSplit. When MaxSplit is -1, this will just split
  271. // "forever". This doesn't support splitting more than 2^31 times
  272. // intentionally; if we ever want that we can make MaxSplit a 64-bit integer
  273. // but that seems unlikely to be useful.
  274. while (MaxSplit-- != 0) {
  275. size_t Idx = S.find(Separator);
  276. if (Idx == npos)
  277. break;
  278. // Push this split.
  279. if (KeepEmpty || Idx > 0)
  280. A.push_back(S.slice(0, Idx));
  281. // Jump forward.
  282. S = S.slice(Idx + Separator.size(), npos);
  283. }
  284. // Push the tail.
  285. if (KeepEmpty || !S.empty())
  286. A.push_back(S);
  287. }
  288. void StringRef::split(SmallVectorImpl<StringRef> &A, char Separator,
  289. int MaxSplit, bool KeepEmpty) const {
  290. StringRef S = *this;
  291. // Count down from MaxSplit. When MaxSplit is -1, this will just split
  292. // "forever". This doesn't support splitting more than 2^31 times
  293. // intentionally; if we ever want that we can make MaxSplit a 64-bit integer
  294. // but that seems unlikely to be useful.
  295. while (MaxSplit-- != 0) {
  296. size_t Idx = S.find(Separator);
  297. if (Idx == npos)
  298. break;
  299. // Push this split.
  300. if (KeepEmpty || Idx > 0)
  301. A.push_back(S.slice(0, Idx));
  302. // Jump forward.
  303. S = S.slice(Idx + 1, npos);
  304. }
  305. // Push the tail.
  306. if (KeepEmpty || !S.empty())
  307. A.push_back(S);
  308. }
  309. //===----------------------------------------------------------------------===//
  310. // Helpful Algorithms
  311. //===----------------------------------------------------------------------===//
  312. /// count - Return the number of non-overlapped occurrences of \arg Str in
  313. /// the string.
  314. size_t StringRef::count(StringRef Str) const {
  315. size_t Count = 0;
  316. size_t N = Str.size();
  317. if (!N || N > Length)
  318. return 0;
  319. for (size_t i = 0, e = Length - N + 1; i < e;) {
  320. if (substr(i, N).equals(Str)) {
  321. ++Count;
  322. i += N;
  323. }
  324. else
  325. ++i;
  326. }
  327. return Count;
  328. }
  329. static unsigned GetAutoSenseRadix(StringRef &Str) {
  330. if (Str.empty())
  331. return 10;
  332. if (Str.startswith("0x") || Str.startswith("0X")) {
  333. Str = Str.substr(2);
  334. return 16;
  335. }
  336. if (Str.startswith("0b") || Str.startswith("0B")) {
  337. Str = Str.substr(2);
  338. return 2;
  339. }
  340. if (Str.startswith("0o")) {
  341. Str = Str.substr(2);
  342. return 8;
  343. }
  344. if (Str[0] == '0' && Str.size() > 1 && isDigit(Str[1])) {
  345. Str = Str.substr(1);
  346. return 8;
  347. }
  348. return 10;
  349. }
  350. bool llvm::consumeUnsignedInteger(StringRef &Str, unsigned Radix,
  351. unsigned long long &Result) {
  352. // Autosense radix if not specified.
  353. if (Radix == 0)
  354. Radix = GetAutoSenseRadix(Str);
  355. // Empty strings (after the radix autosense) are invalid.
  356. if (Str.empty()) return true;
  357. // Parse all the bytes of the string given this radix. Watch for overflow.
  358. StringRef Str2 = Str;
  359. Result = 0;
  360. while (!Str2.empty()) {
  361. unsigned CharVal;
  362. if (Str2[0] >= '0' && Str2[0] <= '9')
  363. CharVal = Str2[0] - '0';
  364. else if (Str2[0] >= 'a' && Str2[0] <= 'z')
  365. CharVal = Str2[0] - 'a' + 10;
  366. else if (Str2[0] >= 'A' && Str2[0] <= 'Z')
  367. CharVal = Str2[0] - 'A' + 10;
  368. else
  369. break;
  370. // If the parsed value is larger than the integer radix, we cannot
  371. // consume any more characters.
  372. if (CharVal >= Radix)
  373. break;
  374. // Add in this character.
  375. unsigned long long PrevResult = Result;
  376. Result = Result * Radix + CharVal;
  377. // Check for overflow by shifting back and seeing if bits were lost.
  378. if (Result / Radix < PrevResult)
  379. return true;
  380. Str2 = Str2.substr(1);
  381. }
  382. // We consider the operation a failure if no characters were consumed
  383. // successfully.
  384. if (Str.size() == Str2.size())
  385. return true;
  386. Str = Str2;
  387. return false;
  388. }
  389. bool llvm::consumeSignedInteger(StringRef &Str, unsigned Radix,
  390. long long &Result) {
  391. unsigned long long ULLVal;
  392. // Handle positive strings first.
  393. if (Str.empty() || Str.front() != '-') {
  394. if (consumeUnsignedInteger(Str, Radix, ULLVal) ||
  395. // Check for value so large it overflows a signed value.
  396. (long long)ULLVal < 0)
  397. return true;
  398. Result = ULLVal;
  399. return false;
  400. }
  401. // Get the positive part of the value.
  402. StringRef Str2 = Str.drop_front(1);
  403. if (consumeUnsignedInteger(Str2, Radix, ULLVal) ||
  404. // Reject values so large they'd overflow as negative signed, but allow
  405. // "-0". This negates the unsigned so that the negative isn't undefined
  406. // on signed overflow.
  407. (long long)-ULLVal > 0)
  408. return true;
  409. Str = Str2;
  410. Result = -ULLVal;
  411. return false;
  412. }
  413. /// GetAsUnsignedInteger - Workhorse method that converts a integer character
  414. /// sequence of radix up to 36 to an unsigned long long value.
  415. bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
  416. unsigned long long &Result) {
  417. if (consumeUnsignedInteger(Str, Radix, Result))
  418. return true;
  419. // For getAsUnsignedInteger, we require the whole string to be consumed or
  420. // else we consider it a failure.
  421. return !Str.empty();
  422. }
  423. bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
  424. long long &Result) {
  425. if (consumeSignedInteger(Str, Radix, Result))
  426. return true;
  427. // For getAsSignedInteger, we require the whole string to be consumed or else
  428. // we consider it a failure.
  429. return !Str.empty();
  430. }
  431. bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
  432. StringRef Str = *this;
  433. // Autosense radix if not specified.
  434. if (Radix == 0)
  435. Radix = GetAutoSenseRadix(Str);
  436. assert(Radix > 1 && Radix <= 36);
  437. // Empty strings (after the radix autosense) are invalid.
  438. if (Str.empty()) return true;
  439. // Skip leading zeroes. This can be a significant improvement if
  440. // it means we don't need > 64 bits.
  441. while (!Str.empty() && Str.front() == '0')
  442. Str = Str.substr(1);
  443. // If it was nothing but zeroes....
  444. if (Str.empty()) {
  445. Result = APInt(64, 0);
  446. return false;
  447. }
  448. // (Over-)estimate the required number of bits.
  449. unsigned Log2Radix = 0;
  450. while ((1U << Log2Radix) < Radix) Log2Radix++;
  451. bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
  452. unsigned BitWidth = Log2Radix * Str.size();
  453. if (BitWidth < Result.getBitWidth())
  454. BitWidth = Result.getBitWidth(); // don't shrink the result
  455. else if (BitWidth > Result.getBitWidth())
  456. Result = Result.zext(BitWidth);
  457. APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
  458. if (!IsPowerOf2Radix) {
  459. // These must have the same bit-width as Result.
  460. RadixAP = APInt(BitWidth, Radix);
  461. CharAP = APInt(BitWidth, 0);
  462. }
  463. // Parse all the bytes of the string given this radix.
  464. Result = 0;
  465. while (!Str.empty()) {
  466. unsigned CharVal;
  467. if (Str[0] >= '0' && Str[0] <= '9')
  468. CharVal = Str[0]-'0';
  469. else if (Str[0] >= 'a' && Str[0] <= 'z')
  470. CharVal = Str[0]-'a'+10;
  471. else if (Str[0] >= 'A' && Str[0] <= 'Z')
  472. CharVal = Str[0]-'A'+10;
  473. else
  474. return true;
  475. // If the parsed value is larger than the integer radix, the string is
  476. // invalid.
  477. if (CharVal >= Radix)
  478. return true;
  479. // Add in this character.
  480. if (IsPowerOf2Radix) {
  481. Result <<= Log2Radix;
  482. Result |= CharVal;
  483. } else {
  484. Result *= RadixAP;
  485. CharAP = CharVal;
  486. Result += CharAP;
  487. }
  488. Str = Str.substr(1);
  489. }
  490. return false;
  491. }
  492. bool StringRef::getAsDouble(double &Result, bool AllowInexact) const {
  493. APFloat F(0.0);
  494. auto StatusOrErr = F.convertFromString(*this, APFloat::rmNearestTiesToEven);
  495. if (errorToBool(StatusOrErr.takeError()))
  496. return true;
  497. APFloat::opStatus Status = *StatusOrErr;
  498. if (Status != APFloat::opOK) {
  499. if (!AllowInexact || !(Status & APFloat::opInexact))
  500. return true;
  501. }
  502. Result = F.convertToDouble();
  503. return false;
  504. }
  505. // Implementation of StringRef hashing.
  506. hash_code llvm::hash_value(StringRef S) {
  507. return hash_combine_range(S.begin(), S.end());
  508. }
  509. unsigned DenseMapInfo<StringRef, void>::getHashValue(StringRef Val) {
  510. assert(Val.data() != getEmptyKey().data() &&
  511. "Cannot hash the empty key!");
  512. assert(Val.data() != getTombstoneKey().data() &&
  513. "Cannot hash the tombstone key!");
  514. return (unsigned)(hash_value(Val));
  515. }