StringRef.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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/OwningPtr.h"
  12. #include <bitset>
  13. using namespace llvm;
  14. // MSVC emits references to this into the translation units which reference it.
  15. #ifndef _MSC_VER
  16. const size_t StringRef::npos;
  17. #endif
  18. static char ascii_tolower(char x) {
  19. if (x >= 'A' && x <= 'Z')
  20. return x - 'A' + 'a';
  21. return x;
  22. }
  23. static bool ascii_isdigit(char x) {
  24. return x >= '0' && x <= '9';
  25. }
  26. /// compare_lower - Compare strings, ignoring case.
  27. int StringRef::compare_lower(StringRef RHS) const {
  28. for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
  29. unsigned char LHC = ascii_tolower(Data[I]);
  30. unsigned char RHC = ascii_tolower(RHS.Data[I]);
  31. if (LHC != RHC)
  32. return LHC < RHC ? -1 : 1;
  33. }
  34. if (Length == RHS.Length)
  35. return 0;
  36. return Length < RHS.Length ? -1 : 1;
  37. }
  38. /// compare_numeric - Compare strings, handle embedded numbers.
  39. int StringRef::compare_numeric(StringRef RHS) const {
  40. for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
  41. if (Data[I] == RHS.Data[I])
  42. continue;
  43. if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
  44. // The longer sequence of numbers is larger. This doesn't really handle
  45. // prefixed zeros well.
  46. for (size_t J = I+1; J != E+1; ++J) {
  47. bool ld = J < Length && ascii_isdigit(Data[J]);
  48. bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
  49. if (ld != rd)
  50. return rd ? -1 : 1;
  51. if (!rd)
  52. break;
  53. }
  54. }
  55. return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
  56. }
  57. if (Length == RHS.Length)
  58. return 0;
  59. return Length < RHS.Length ? -1 : 1;
  60. }
  61. // Compute the edit distance between the two given strings.
  62. unsigned StringRef::edit_distance(llvm::StringRef Other,
  63. bool AllowReplacements,
  64. unsigned MaxEditDistance) {
  65. // The algorithm implemented below is the "classic"
  66. // dynamic-programming algorithm for computing the Levenshtein
  67. // distance, which is described here:
  68. //
  69. // http://en.wikipedia.org/wiki/Levenshtein_distance
  70. //
  71. // Although the algorithm is typically described using an m x n
  72. // array, only two rows are used at a time, so this implemenation
  73. // just keeps two separate vectors for those two rows.
  74. size_type m = size();
  75. size_type n = Other.size();
  76. const unsigned SmallBufferSize = 64;
  77. unsigned SmallBuffer[SmallBufferSize];
  78. llvm::OwningArrayPtr<unsigned> Allocated;
  79. unsigned *previous = SmallBuffer;
  80. if (2*(n + 1) > SmallBufferSize) {
  81. previous = new unsigned [2*(n+1)];
  82. Allocated.reset(previous);
  83. }
  84. unsigned *current = previous + (n + 1);
  85. for (unsigned i = 0; i <= n; ++i)
  86. previous[i] = i;
  87. for (size_type y = 1; y <= m; ++y) {
  88. current[0] = y;
  89. unsigned BestThisRow = current[0];
  90. for (size_type x = 1; x <= n; ++x) {
  91. if (AllowReplacements) {
  92. current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
  93. min(current[x-1], previous[x])+1);
  94. }
  95. else {
  96. if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
  97. else current[x] = min(current[x-1], previous[x]) + 1;
  98. }
  99. BestThisRow = min(BestThisRow, current[x]);
  100. }
  101. if (MaxEditDistance && BestThisRow > MaxEditDistance)
  102. return MaxEditDistance + 1;
  103. unsigned *tmp = current;
  104. current = previous;
  105. previous = tmp;
  106. }
  107. unsigned Result = previous[n];
  108. return Result;
  109. }
  110. //===----------------------------------------------------------------------===//
  111. // String Searching
  112. //===----------------------------------------------------------------------===//
  113. /// find - Search for the first string \arg Str in the string.
  114. ///
  115. /// \return - The index of the first occurrence of \arg Str, or npos if not
  116. /// found.
  117. size_t StringRef::find(StringRef Str, size_t From) const {
  118. size_t N = Str.size();
  119. if (N > Length)
  120. return npos;
  121. for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
  122. if (substr(i, N).equals(Str))
  123. return i;
  124. return npos;
  125. }
  126. /// rfind - Search for the last string \arg Str in the string.
  127. ///
  128. /// \return - The index of the last occurrence of \arg Str, or npos if not
  129. /// found.
  130. size_t StringRef::rfind(StringRef Str) const {
  131. size_t N = Str.size();
  132. if (N > Length)
  133. return npos;
  134. for (size_t i = Length - N + 1, e = 0; i != e;) {
  135. --i;
  136. if (substr(i, N).equals(Str))
  137. return i;
  138. }
  139. return npos;
  140. }
  141. /// find_first_of - Find the first character in the string that is in \arg
  142. /// Chars, or npos if not found.
  143. ///
  144. /// Note: O(size() + Chars.size())
  145. StringRef::size_type StringRef::find_first_of(StringRef Chars,
  146. size_t From) const {
  147. std::bitset<1 << CHAR_BIT> CharBits;
  148. for (size_type i = 0; i != Chars.size(); ++i)
  149. CharBits.set((unsigned char)Chars[i]);
  150. for (size_type i = min(From, Length), e = Length; i != e; ++i)
  151. if (CharBits.test((unsigned char)Data[i]))
  152. return i;
  153. return npos;
  154. }
  155. /// find_first_not_of - Find the first character in the string that is not
  156. /// \arg C or npos if not found.
  157. StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
  158. for (size_type i = min(From, Length), e = Length; i != e; ++i)
  159. if (Data[i] != C)
  160. return i;
  161. return npos;
  162. }
  163. /// find_first_not_of - Find the first character in the string that is not
  164. /// in the string \arg Chars, or npos if not found.
  165. ///
  166. /// Note: O(size() + Chars.size())
  167. StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
  168. size_t From) const {
  169. std::bitset<1 << CHAR_BIT> CharBits;
  170. for (size_type i = 0; i != Chars.size(); ++i)
  171. CharBits.set((unsigned char)Chars[i]);
  172. for (size_type i = min(From, Length), e = Length; i != e; ++i)
  173. if (!CharBits.test((unsigned char)Data[i]))
  174. return i;
  175. return npos;
  176. }
  177. /// find_last_of - Find the last character in the string that is in \arg C,
  178. /// or npos if not found.
  179. ///
  180. /// Note: O(size() + Chars.size())
  181. StringRef::size_type StringRef::find_last_of(StringRef Chars,
  182. size_t From) const {
  183. std::bitset<1 << CHAR_BIT> CharBits;
  184. for (size_type i = 0; i != Chars.size(); ++i)
  185. CharBits.set((unsigned char)Chars[i]);
  186. for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
  187. if (CharBits.test((unsigned char)Data[i]))
  188. return i;
  189. return npos;
  190. }
  191. //===----------------------------------------------------------------------===//
  192. // Helpful Algorithms
  193. //===----------------------------------------------------------------------===//
  194. /// count - Return the number of non-overlapped occurrences of \arg Str in
  195. /// the string.
  196. size_t StringRef::count(StringRef Str) const {
  197. size_t Count = 0;
  198. size_t N = Str.size();
  199. if (N > Length)
  200. return 0;
  201. for (size_t i = 0, e = Length - N + 1; i != e; ++i)
  202. if (substr(i, N).equals(Str))
  203. ++Count;
  204. return Count;
  205. }
  206. static unsigned GetAutoSenseRadix(StringRef &Str) {
  207. if (Str.startswith("0x")) {
  208. Str = Str.substr(2);
  209. return 16;
  210. } else if (Str.startswith("0b")) {
  211. Str = Str.substr(2);
  212. return 2;
  213. } else if (Str.startswith("0")) {
  214. return 8;
  215. } else {
  216. return 10;
  217. }
  218. }
  219. /// GetAsUnsignedInteger - Workhorse method that converts a integer character
  220. /// sequence of radix up to 36 to an unsigned long long value.
  221. static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
  222. unsigned long long &Result) {
  223. // Autosense radix if not specified.
  224. if (Radix == 0)
  225. Radix = GetAutoSenseRadix(Str);
  226. // Empty strings (after the radix autosense) are invalid.
  227. if (Str.empty()) return true;
  228. // Parse all the bytes of the string given this radix. Watch for overflow.
  229. Result = 0;
  230. while (!Str.empty()) {
  231. unsigned CharVal;
  232. if (Str[0] >= '0' && Str[0] <= '9')
  233. CharVal = Str[0]-'0';
  234. else if (Str[0] >= 'a' && Str[0] <= 'z')
  235. CharVal = Str[0]-'a'+10;
  236. else if (Str[0] >= 'A' && Str[0] <= 'Z')
  237. CharVal = Str[0]-'A'+10;
  238. else
  239. return true;
  240. // If the parsed value is larger than the integer radix, the string is
  241. // invalid.
  242. if (CharVal >= Radix)
  243. return true;
  244. // Add in this character.
  245. unsigned long long PrevResult = Result;
  246. Result = Result*Radix+CharVal;
  247. // Check for overflow.
  248. if (Result < PrevResult)
  249. return true;
  250. Str = Str.substr(1);
  251. }
  252. return false;
  253. }
  254. bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
  255. return GetAsUnsignedInteger(*this, Radix, Result);
  256. }
  257. bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
  258. unsigned long long ULLVal;
  259. // Handle positive strings first.
  260. if (empty() || front() != '-') {
  261. if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
  262. // Check for value so large it overflows a signed value.
  263. (long long)ULLVal < 0)
  264. return true;
  265. Result = ULLVal;
  266. return false;
  267. }
  268. // Get the positive part of the value.
  269. if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
  270. // Reject values so large they'd overflow as negative signed, but allow
  271. // "-0". This negates the unsigned so that the negative isn't undefined
  272. // on signed overflow.
  273. (long long)-ULLVal > 0)
  274. return true;
  275. Result = -ULLVal;
  276. return false;
  277. }
  278. bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
  279. long long Val;
  280. if (getAsInteger(Radix, Val) ||
  281. (int)Val != Val)
  282. return true;
  283. Result = Val;
  284. return false;
  285. }
  286. bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
  287. unsigned long long Val;
  288. if (getAsInteger(Radix, Val) ||
  289. (unsigned)Val != Val)
  290. return true;
  291. Result = Val;
  292. return false;
  293. }
  294. bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
  295. StringRef Str = *this;
  296. // Autosense radix if not specified.
  297. if (Radix == 0)
  298. Radix = GetAutoSenseRadix(Str);
  299. assert(Radix > 1 && Radix <= 36);
  300. // Empty strings (after the radix autosense) are invalid.
  301. if (Str.empty()) return true;
  302. // Skip leading zeroes. This can be a significant improvement if
  303. // it means we don't need > 64 bits.
  304. while (!Str.empty() && Str.front() == '0')
  305. Str = Str.substr(1);
  306. // If it was nothing but zeroes....
  307. if (Str.empty()) {
  308. Result = APInt(64, 0);
  309. return false;
  310. }
  311. // (Over-)estimate the required number of bits.
  312. unsigned Log2Radix = 0;
  313. while ((1U << Log2Radix) < Radix) Log2Radix++;
  314. bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
  315. unsigned BitWidth = Log2Radix * Str.size();
  316. if (BitWidth < Result.getBitWidth())
  317. BitWidth = Result.getBitWidth(); // don't shrink the result
  318. else
  319. Result = Result.zext(BitWidth);
  320. APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
  321. if (!IsPowerOf2Radix) {
  322. // These must have the same bit-width as Result.
  323. RadixAP = APInt(BitWidth, Radix);
  324. CharAP = APInt(BitWidth, 0);
  325. }
  326. // Parse all the bytes of the string given this radix.
  327. Result = 0;
  328. while (!Str.empty()) {
  329. unsigned CharVal;
  330. if (Str[0] >= '0' && Str[0] <= '9')
  331. CharVal = Str[0]-'0';
  332. else if (Str[0] >= 'a' && Str[0] <= 'z')
  333. CharVal = Str[0]-'a'+10;
  334. else if (Str[0] >= 'A' && Str[0] <= 'Z')
  335. CharVal = Str[0]-'A'+10;
  336. else
  337. return true;
  338. // If the parsed value is larger than the integer radix, the string is
  339. // invalid.
  340. if (CharVal >= Radix)
  341. return true;
  342. // Add in this character.
  343. if (IsPowerOf2Radix) {
  344. Result <<= Log2Radix;
  345. Result |= CharVal;
  346. } else {
  347. Result *= RadixAP;
  348. CharAP = CharVal;
  349. Result += CharAP;
  350. }
  351. Str = Str.substr(1);
  352. }
  353. return false;
  354. }