2
0

StringRef.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. //===-- StringRef.cpp - Lightweight String References ---------------------===//
  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. #include "llvm/ADT/StringRef.h"
  10. #include "llvm/ADT/APInt.h"
  11. #include "llvm/ADT/Hashing.h"
  12. #include "llvm/ADT/edit_distance.h"
  13. #include <bitset>
  14. using namespace llvm;
  15. // MSVC emits references to this into the translation units which reference it.
  16. #ifndef _MSC_VER
  17. const size_t StringRef::npos;
  18. #endif
  19. static char ascii_tolower(char x) {
  20. if (x >= 'A' && x <= 'Z')
  21. return x - 'A' + 'a';
  22. return x;
  23. }
  24. static char ascii_toupper(char x) {
  25. if (x >= 'a' && x <= 'z')
  26. return x - 'a' + 'A';
  27. return x;
  28. }
  29. static bool ascii_isdigit(char x) {
  30. return x >= '0' && x <= '9';
  31. }
  32. // strncasecmp() is not available on non-POSIX systems, so define an
  33. // alternative function here.
  34. static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) {
  35. for (size_t I = 0; I < Length; ++I) {
  36. unsigned char LHC = ascii_tolower(LHS[I]);
  37. unsigned char RHC = ascii_tolower(RHS[I]);
  38. if (LHC != RHC)
  39. return LHC < RHC ? -1 : 1;
  40. }
  41. return 0;
  42. }
  43. /// compare_lower - Compare strings, ignoring case.
  44. int StringRef::compare_lower(StringRef RHS) const {
  45. if (int Res = ascii_strncasecmp(Data, RHS.Data, std::min(Length, RHS.Length)))
  46. return Res;
  47. if (Length == RHS.Length)
  48. return 0;
  49. return Length < RHS.Length ? -1 : 1;
  50. }
  51. /// Check if this string starts with the given \p Prefix, ignoring case.
  52. bool StringRef::startswith_lower(StringRef Prefix) const {
  53. return Length >= Prefix.Length &&
  54. ascii_strncasecmp(Data, Prefix.Data, Prefix.Length) == 0;
  55. }
  56. /// Check if this string ends with the given \p Suffix, ignoring case.
  57. bool StringRef::endswith_lower(StringRef Suffix) const {
  58. return Length >= Suffix.Length &&
  59. ascii_strncasecmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
  60. }
  61. /// compare_numeric - Compare strings, handle embedded numbers.
  62. int StringRef::compare_numeric(StringRef RHS) const {
  63. for (size_t I = 0, E = std::min(Length, RHS.Length); I != E; ++I) {
  64. // Check for sequences of digits.
  65. if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
  66. // The longer sequence of numbers is considered larger.
  67. // This doesn't really handle prefixed zeros well.
  68. size_t J;
  69. for (J = I + 1; J != E + 1; ++J) {
  70. bool ld = J < Length && ascii_isdigit(Data[J]);
  71. bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
  72. if (ld != rd)
  73. return rd ? -1 : 1;
  74. if (!rd)
  75. break;
  76. }
  77. // The two number sequences have the same length (J-I), just memcmp them.
  78. if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
  79. return Res < 0 ? -1 : 1;
  80. // Identical number sequences, continue search after the numbers.
  81. I = J - 1;
  82. continue;
  83. }
  84. if (Data[I] != RHS.Data[I])
  85. return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
  86. }
  87. if (Length == RHS.Length)
  88. return 0;
  89. return Length < RHS.Length ? -1 : 1;
  90. }
  91. // Compute the edit distance between the two given strings.
  92. unsigned StringRef::edit_distance(llvm::StringRef Other,
  93. bool AllowReplacements,
  94. unsigned MaxEditDistance) const {
  95. return llvm::ComputeEditDistance(
  96. makeArrayRef(data(), size()),
  97. makeArrayRef(Other.data(), Other.size()),
  98. AllowReplacements, MaxEditDistance);
  99. }
  100. //===----------------------------------------------------------------------===//
  101. // String Operations
  102. //===----------------------------------------------------------------------===//
  103. std::string StringRef::lower() const {
  104. std::string Result(size(), char());
  105. for (size_type i = 0, e = size(); i != e; ++i) {
  106. Result[i] = ascii_tolower(Data[i]);
  107. }
  108. return Result;
  109. }
  110. std::string StringRef::upper() const {
  111. std::string Result(size(), char());
  112. for (size_type i = 0, e = size(); i != e; ++i) {
  113. Result[i] = ascii_toupper(Data[i]);
  114. }
  115. return Result;
  116. }
  117. //===----------------------------------------------------------------------===//
  118. // String Searching
  119. //===----------------------------------------------------------------------===//
  120. /// find - Search for the first string \arg Str in the string.
  121. ///
  122. /// \return - The index of the first occurrence of \arg Str, or npos if not
  123. /// found.
  124. size_t StringRef::find(StringRef Str, size_t From) const {
  125. size_t N = Str.size();
  126. if (N > Length)
  127. return npos;
  128. // For short haystacks or unsupported needles fall back to the naive algorithm
  129. if (Length < 16 || N > 255 || N == 0) {
  130. for (size_t e = Length - N + 1, i = std::min(From, e); i != e; ++i)
  131. if (substr(i, N).equals(Str))
  132. return i;
  133. return npos;
  134. }
  135. if (From >= Length)
  136. return npos;
  137. // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
  138. uint8_t BadCharSkip[256];
  139. std::memset(BadCharSkip, N, 256);
  140. for (unsigned i = 0; i != N-1; ++i)
  141. BadCharSkip[(uint8_t)Str[i]] = N-1-i;
  142. unsigned Len = Length-From, Pos = From;
  143. while (Len >= N) {
  144. if (substr(Pos, N).equals(Str)) // See if this is the correct substring.
  145. return Pos;
  146. // Otherwise skip the appropriate number of bytes.
  147. uint8_t Skip = BadCharSkip[(uint8_t)(*this)[Pos+N-1]];
  148. Len -= Skip;
  149. Pos += Skip;
  150. }
  151. return npos;
  152. }
  153. /// rfind - Search for the last string \arg Str in the string.
  154. ///
  155. /// \return - The index of the last occurrence of \arg Str, or npos if not
  156. /// found.
  157. size_t StringRef::rfind(StringRef Str) const {
  158. size_t N = Str.size();
  159. if (N > Length)
  160. return npos;
  161. for (size_t i = Length - N + 1, e = 0; i != e;) {
  162. --i;
  163. if (substr(i, N).equals(Str))
  164. return i;
  165. }
  166. return npos;
  167. }
  168. /// find_first_of - Find the first character in the string that is in \arg
  169. /// Chars, or npos if not found.
  170. ///
  171. /// Note: O(size() + Chars.size())
  172. StringRef::size_type StringRef::find_first_of(StringRef Chars,
  173. size_t From) const {
  174. std::bitset<1 << CHAR_BIT> CharBits;
  175. for (size_type i = 0; i != Chars.size(); ++i)
  176. CharBits.set((unsigned char)Chars[i]);
  177. for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
  178. if (CharBits.test((unsigned char)Data[i]))
  179. return i;
  180. return npos;
  181. }
  182. /// find_first_not_of - Find the first character in the string that is not
  183. /// \arg C or npos if not found.
  184. StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
  185. for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
  186. if (Data[i] != C)
  187. return i;
  188. return npos;
  189. }
  190. /// find_first_not_of - Find the first character in the string that is not
  191. /// in the string \arg Chars, or npos if not found.
  192. ///
  193. /// Note: O(size() + Chars.size())
  194. StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
  195. size_t From) const {
  196. std::bitset<1 << CHAR_BIT> CharBits;
  197. for (size_type i = 0; i != Chars.size(); ++i)
  198. CharBits.set((unsigned char)Chars[i]);
  199. for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
  200. if (!CharBits.test((unsigned char)Data[i]))
  201. return i;
  202. return npos;
  203. }
  204. /// find_last_of - Find the last character in the string that is in \arg C,
  205. /// or npos if not found.
  206. ///
  207. /// Note: O(size() + Chars.size())
  208. StringRef::size_type StringRef::find_last_of(StringRef Chars,
  209. size_t From) const {
  210. std::bitset<1 << CHAR_BIT> CharBits;
  211. for (size_type i = 0; i != Chars.size(); ++i)
  212. CharBits.set((unsigned char)Chars[i]);
  213. for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
  214. if (CharBits.test((unsigned char)Data[i]))
  215. return i;
  216. return npos;
  217. }
  218. /// find_last_not_of - Find the last character in the string that is not
  219. /// \arg C, or npos if not found.
  220. StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const {
  221. for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
  222. if (Data[i] != C)
  223. return i;
  224. return npos;
  225. }
  226. /// find_last_not_of - Find the last character in the string that is not in
  227. /// \arg Chars, or npos if not found.
  228. ///
  229. /// Note: O(size() + Chars.size())
  230. StringRef::size_type StringRef::find_last_not_of(StringRef Chars,
  231. size_t From) const {
  232. std::bitset<1 << CHAR_BIT> CharBits;
  233. for (size_type i = 0, e = Chars.size(); i != e; ++i)
  234. CharBits.set((unsigned char)Chars[i]);
  235. for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
  236. if (!CharBits.test((unsigned char)Data[i]))
  237. return i;
  238. return npos;
  239. }
  240. void StringRef::split(SmallVectorImpl<StringRef> &A,
  241. StringRef Separators, int MaxSplit,
  242. bool KeepEmpty) const {
  243. StringRef rest = *this;
  244. // rest.data() is used to distinguish cases like "a," that splits into
  245. // "a" + "" and "a" that splits into "a" + 0.
  246. for (int splits = 0;
  247. rest.data() != nullptr && (MaxSplit < 0 || splits < MaxSplit);
  248. ++splits) {
  249. std::pair<StringRef, StringRef> p = rest.split(Separators);
  250. if (KeepEmpty || p.first.size() != 0)
  251. A.push_back(p.first);
  252. rest = p.second;
  253. }
  254. // If we have a tail left, add it.
  255. if (rest.data() != nullptr && (rest.size() != 0 || KeepEmpty))
  256. A.push_back(rest);
  257. }
  258. //===----------------------------------------------------------------------===//
  259. // Helpful Algorithms
  260. //===----------------------------------------------------------------------===//
  261. /// count - Return the number of non-overlapped occurrences of \arg Str in
  262. /// the string.
  263. size_t StringRef::count(StringRef Str) const {
  264. size_t Count = 0;
  265. size_t N = Str.size();
  266. if (N > Length)
  267. return 0;
  268. for (size_t i = 0, e = Length - N + 1; i != e; ++i)
  269. if (substr(i, N).equals(Str))
  270. ++Count;
  271. return Count;
  272. }
  273. static unsigned GetAutoSenseRadix(StringRef &Str) {
  274. if (Str.startswith("0x")) {
  275. Str = Str.substr(2);
  276. return 16;
  277. }
  278. if (Str.startswith("0b")) {
  279. Str = Str.substr(2);
  280. return 2;
  281. }
  282. if (Str.startswith("0o")) {
  283. Str = Str.substr(2);
  284. return 8;
  285. }
  286. if (Str.startswith("0"))
  287. return 8;
  288. return 10;
  289. }
  290. /// GetAsUnsignedInteger - Workhorse method that converts a integer character
  291. /// sequence of radix up to 36 to an unsigned long long value.
  292. bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
  293. unsigned long long &Result) {
  294. // Autosense radix if not specified.
  295. if (Radix == 0)
  296. Radix = GetAutoSenseRadix(Str);
  297. // Empty strings (after the radix autosense) are invalid.
  298. if (Str.empty()) return true;
  299. // Parse all the bytes of the string given this radix. Watch for overflow.
  300. Result = 0;
  301. while (!Str.empty()) {
  302. unsigned CharVal;
  303. if (Str[0] >= '0' && Str[0] <= '9')
  304. CharVal = Str[0]-'0';
  305. else if (Str[0] >= 'a' && Str[0] <= 'z')
  306. CharVal = Str[0]-'a'+10;
  307. else if (Str[0] >= 'A' && Str[0] <= 'Z')
  308. CharVal = Str[0]-'A'+10;
  309. else
  310. return true;
  311. // If the parsed value is larger than the integer radix, the string is
  312. // invalid.
  313. if (CharVal >= Radix)
  314. return true;
  315. // Add in this character.
  316. unsigned long long PrevResult = Result;
  317. Result = Result*Radix+CharVal;
  318. // Check for overflow by shifting back and seeing if bits were lost.
  319. if (Result/Radix < PrevResult)
  320. return true;
  321. Str = Str.substr(1);
  322. }
  323. return false;
  324. }
  325. bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
  326. long long &Result) {
  327. unsigned long long ULLVal;
  328. // Handle positive strings first.
  329. if (Str.empty() || Str.front() != '-') {
  330. if (getAsUnsignedInteger(Str, Radix, ULLVal) ||
  331. // Check for value so large it overflows a signed value.
  332. (long long)ULLVal < 0)
  333. return true;
  334. Result = ULLVal;
  335. return false;
  336. }
  337. // Get the positive part of the value.
  338. if (getAsUnsignedInteger(Str.substr(1), Radix, ULLVal) ||
  339. // Reject values so large they'd overflow as negative signed, but allow
  340. // "-0". This negates the unsigned so that the negative isn't undefined
  341. // on signed overflow.
  342. (long long)-ULLVal > 0)
  343. return true;
  344. Result = -ULLVal;
  345. return false;
  346. }
  347. bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
  348. StringRef Str = *this;
  349. // Autosense radix if not specified.
  350. if (Radix == 0)
  351. Radix = GetAutoSenseRadix(Str);
  352. assert(Radix > 1 && Radix <= 36);
  353. // Empty strings (after the radix autosense) are invalid.
  354. if (Str.empty()) return true;
  355. // Skip leading zeroes. This can be a significant improvement if
  356. // it means we don't need > 64 bits.
  357. while (!Str.empty() && Str.front() == '0')
  358. Str = Str.substr(1);
  359. // If it was nothing but zeroes....
  360. if (Str.empty()) {
  361. Result = APInt(64, 0);
  362. return false;
  363. }
  364. // (Over-)estimate the required number of bits.
  365. unsigned Log2Radix = 0;
  366. while ((1U << Log2Radix) < Radix) Log2Radix++;
  367. bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
  368. unsigned BitWidth = Log2Radix * Str.size();
  369. if (BitWidth < Result.getBitWidth())
  370. BitWidth = Result.getBitWidth(); // don't shrink the result
  371. else if (BitWidth > Result.getBitWidth())
  372. Result = Result.zext(BitWidth);
  373. APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
  374. if (!IsPowerOf2Radix) {
  375. // These must have the same bit-width as Result.
  376. RadixAP = APInt(BitWidth, Radix);
  377. CharAP = APInt(BitWidth, 0);
  378. }
  379. // Parse all the bytes of the string given this radix.
  380. Result = 0;
  381. while (!Str.empty()) {
  382. unsigned CharVal;
  383. if (Str[0] >= '0' && Str[0] <= '9')
  384. CharVal = Str[0]-'0';
  385. else if (Str[0] >= 'a' && Str[0] <= 'z')
  386. CharVal = Str[0]-'a'+10;
  387. else if (Str[0] >= 'A' && Str[0] <= 'Z')
  388. CharVal = Str[0]-'A'+10;
  389. else
  390. return true;
  391. // If the parsed value is larger than the integer radix, the string is
  392. // invalid.
  393. if (CharVal >= Radix)
  394. return true;
  395. // Add in this character.
  396. if (IsPowerOf2Radix) {
  397. Result <<= Log2Radix;
  398. Result |= CharVal;
  399. } else {
  400. Result *= RadixAP;
  401. CharAP = CharVal;
  402. Result += CharAP;
  403. }
  404. Str = Str.substr(1);
  405. }
  406. return false;
  407. }
  408. // Implementation of StringRef hashing.
  409. hash_code llvm::hash_value(StringRef S) {
  410. return hash_combine_range(S.begin(), S.end());
  411. }