blob: a862ed2fa9ce6589cf987b972f730583072f77a6 [file] [log] [blame]
Daniel Dunbare6551282009-09-16 22:38:48 +00001//===-- 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
10#include "llvm/ADT/StringRef.h"
John McCall1e7ad392010-02-28 09:55:58 +000011#include "llvm/ADT/APInt.h"
Ted Kremenek13302ec2010-11-07 06:09:02 +000012#include "llvm/ADT/OwningPtr.h"
Benjamin Kramer250eb002010-08-23 18:16:08 +000013#include <bitset>
Douglas Gregorad6b6da2010-01-07 00:51:54 +000014
Daniel Dunbare6551282009-09-16 22:38:48 +000015using namespace llvm;
16
Daniel Dunbar77696be2009-09-22 03:34:40 +000017// MSVC emits references to this into the translation units which reference it.
18#ifndef _MSC_VER
Daniel Dunbare6551282009-09-16 22:38:48 +000019const size_t StringRef::npos;
Daniel Dunbar77696be2009-09-22 03:34:40 +000020#endif
Chris Lattnercea14382009-09-19 19:47:14 +000021
Benjamin Kramer05872ea2009-11-12 20:36:59 +000022static char ascii_tolower(char x) {
23 if (x >= 'A' && x <= 'Z')
24 return x - 'A' + 'a';
25 return x;
26}
27
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000028static bool ascii_isdigit(char x) {
29 return x >= '0' && x <= '9';
30}
31
Benjamin Kramer05872ea2009-11-12 20:36:59 +000032/// compare_lower - Compare strings, ignoring case.
33int StringRef::compare_lower(StringRef RHS) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +000034 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
Benjamin Kramer0043e352010-08-26 14:21:08 +000035 unsigned char LHC = ascii_tolower(Data[I]);
36 unsigned char RHC = ascii_tolower(RHS.Data[I]);
Benjamin Kramer05872ea2009-11-12 20:36:59 +000037 if (LHC != RHC)
38 return LHC < RHC ? -1 : 1;
39 }
40
41 if (Length == RHS.Length)
Benjamin Kramer0043e352010-08-26 14:21:08 +000042 return 0;
Benjamin Kramer05872ea2009-11-12 20:36:59 +000043 return Length < RHS.Length ? -1 : 1;
44}
45
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000046/// compare_numeric - Compare strings, handle embedded numbers.
47int StringRef::compare_numeric(StringRef RHS) const {
48 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000049 // Check for sequences of digits.
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000050 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000051 // The longer sequence of numbers is considered larger.
52 // This doesn't really handle prefixed zeros well.
53 size_t J;
54 for (J = I + 1; J != E + 1; ++J) {
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000055 bool ld = J < Length && ascii_isdigit(Data[J]);
56 bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
57 if (ld != rd)
58 return rd ? -1 : 1;
59 if (!rd)
60 break;
61 }
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000062 // The two number sequences have the same length (J-I), just memcmp them.
63 if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
64 return Res < 0 ? -1 : 1;
65 // Identical number sequences, continue search after the numbers.
66 I = J - 1;
67 continue;
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000068 }
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000069 if (Data[I] != RHS.Data[I])
70 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000071 }
72 if (Length == RHS.Length)
Benjamin Kramer0043e352010-08-26 14:21:08 +000073 return 0;
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000074 return Length < RHS.Length ? -1 : 1;
75}
76
Douglas Gregor7e54d5b2009-12-31 04:24:34 +000077// Compute the edit distance between the two given strings.
Michael J. Spencer326990f2010-11-26 04:16:08 +000078unsigned StringRef::edit_distance(llvm::StringRef Other,
Douglas Gregor5ee568a2010-10-19 22:13:48 +000079 bool AllowReplacements,
80 unsigned MaxEditDistance) {
Douglas Gregor7e54d5b2009-12-31 04:24:34 +000081 // The algorithm implemented below is the "classic"
82 // dynamic-programming algorithm for computing the Levenshtein
83 // distance, which is described here:
84 //
85 // http://en.wikipedia.org/wiki/Levenshtein_distance
86 //
87 // Although the algorithm is typically described using an m x n
88 // array, only two rows are used at a time, so this implemenation
89 // just keeps two separate vectors for those two rows.
Douglas Gregor441c8b42009-12-30 17:23:44 +000090 size_type m = size();
91 size_type n = Other.size();
92
Douglas Gregor2772ea82010-01-07 02:24:06 +000093 const unsigned SmallBufferSize = 64;
94 unsigned SmallBuffer[SmallBufferSize];
Ted Kremenek13302ec2010-11-07 06:09:02 +000095 llvm::OwningArrayPtr<unsigned> Allocated;
Douglas Gregor2772ea82010-01-07 02:24:06 +000096 unsigned *previous = SmallBuffer;
Ted Kremenek13302ec2010-11-07 06:09:02 +000097 if (2*(n + 1) > SmallBufferSize) {
98 previous = new unsigned [2*(n+1)];
99 Allocated.reset(previous);
100 }
Douglas Gregor2772ea82010-01-07 02:24:06 +0000101 unsigned *current = previous + (n + 1);
Michael J. Spencer326990f2010-11-26 04:16:08 +0000102
103 for (unsigned i = 0; i <= n; ++i)
Douglas Gregor441c8b42009-12-30 17:23:44 +0000104 previous[i] = i;
105
Douglas Gregor441c8b42009-12-30 17:23:44 +0000106 for (size_type y = 1; y <= m; ++y) {
Douglas Gregor441c8b42009-12-30 17:23:44 +0000107 current[0] = y;
Douglas Gregor5ee568a2010-10-19 22:13:48 +0000108 unsigned BestThisRow = current[0];
Michael J. Spencer326990f2010-11-26 04:16:08 +0000109
Douglas Gregor441c8b42009-12-30 17:23:44 +0000110 for (size_type x = 1; x <= n; ++x) {
111 if (AllowReplacements) {
112 current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
113 min(current[x-1], previous[x])+1);
114 }
115 else {
116 if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
117 else current[x] = min(current[x-1], previous[x]) + 1;
118 }
Douglas Gregor5ee568a2010-10-19 22:13:48 +0000119 BestThisRow = min(BestThisRow, current[x]);
Douglas Gregor441c8b42009-12-30 17:23:44 +0000120 }
Michael J. Spencer326990f2010-11-26 04:16:08 +0000121
Douglas Gregor5ee568a2010-10-19 22:13:48 +0000122 if (MaxEditDistance && BestThisRow > MaxEditDistance)
123 return MaxEditDistance + 1;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000124
Douglas Gregorad6b6da2010-01-07 00:51:54 +0000125 unsigned *tmp = current;
126 current = previous;
127 previous = tmp;
Douglas Gregor441c8b42009-12-30 17:23:44 +0000128 }
129
Douglas Gregorad6b6da2010-01-07 00:51:54 +0000130 unsigned Result = previous[n];
Douglas Gregorad6b6da2010-01-07 00:51:54 +0000131 return Result;
Douglas Gregor441c8b42009-12-30 17:23:44 +0000132}
133
Chris Lattner05a32c82009-09-20 01:22:16 +0000134//===----------------------------------------------------------------------===//
135// String Searching
136//===----------------------------------------------------------------------===//
137
138
139/// find - Search for the first string \arg Str in the string.
140///
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000141/// \return - The index of the first occurrence of \arg Str, or npos if not
Chris Lattner05a32c82009-09-20 01:22:16 +0000142/// found.
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000143size_t StringRef::find(StringRef Str, size_t From) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000144 size_t N = Str.size();
145 if (N > Length)
146 return npos;
Benjamin Kramer6e6a5582011-10-15 10:08:31 +0000147
148 // For short haystacks or unsupported needles fall back to the naive algorithm
149 if (Length < 16 || N > 255 || N == 0) {
150 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
151 if (substr(i, N).equals(Str))
152 return i;
153 return npos;
154 }
155
156 // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
157 uint8_t BadCharSkip[256];
158 std::memset(BadCharSkip, N, 256);
159 for (unsigned i = 0; i != N-1; ++i)
160 BadCharSkip[(uint8_t)Str[i]] = N-1-i;
161
162 unsigned Len = Length, Pos = min(From, Length);
163 while (Len >= N) {
164 if (substr(Pos, N).equals(Str)) // See if this is the correct substring.
165 return Pos;
166
167 // Otherwise skip the appropriate number of bytes.
168 uint8_t Skip = BadCharSkip[(uint8_t)Data[Pos+N-1]];
169 Len -= Skip;
170 Pos += Skip;
171 }
172
Chris Lattner05a32c82009-09-20 01:22:16 +0000173 return npos;
174}
175
176/// rfind - Search for the last string \arg Str in the string.
177///
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000178/// \return - The index of the last occurrence of \arg Str, or npos if not
Chris Lattner05a32c82009-09-20 01:22:16 +0000179/// found.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000180size_t StringRef::rfind(StringRef Str) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000181 size_t N = Str.size();
182 if (N > Length)
183 return npos;
184 for (size_t i = Length - N + 1, e = 0; i != e;) {
185 --i;
186 if (substr(i, N).equals(Str))
187 return i;
188 }
189 return npos;
190}
191
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000192/// find_first_of - Find the first character in the string that is in \arg
193/// Chars, or npos if not found.
194///
Benjamin Kramer250eb002010-08-23 18:16:08 +0000195/// Note: O(size() + Chars.size())
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000196StringRef::size_type StringRef::find_first_of(StringRef Chars,
197 size_t From) const {
Benjamin Kramer250eb002010-08-23 18:16:08 +0000198 std::bitset<1 << CHAR_BIT> CharBits;
199 for (size_type i = 0; i != Chars.size(); ++i)
200 CharBits.set((unsigned char)Chars[i]);
201
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000202 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer250eb002010-08-23 18:16:08 +0000203 if (CharBits.test((unsigned char)Data[i]))
Chris Lattner05a32c82009-09-20 01:22:16 +0000204 return i;
205 return npos;
206}
207
208/// find_first_not_of - Find the first character in the string that is not
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000209/// \arg C or npos if not found.
210StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000211 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000212 if (Data[i] != C)
213 return i;
214 return npos;
215}
216
217/// find_first_not_of - Find the first character in the string that is not
218/// in the string \arg Chars, or npos if not found.
219///
Benjamin Kramer250eb002010-08-23 18:16:08 +0000220/// Note: O(size() + Chars.size())
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000221StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
222 size_t From) const {
Benjamin Kramer250eb002010-08-23 18:16:08 +0000223 std::bitset<1 << CHAR_BIT> CharBits;
224 for (size_type i = 0; i != Chars.size(); ++i)
225 CharBits.set((unsigned char)Chars[i]);
226
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000227 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer250eb002010-08-23 18:16:08 +0000228 if (!CharBits.test((unsigned char)Data[i]))
Chris Lattner05a32c82009-09-20 01:22:16 +0000229 return i;
230 return npos;
231}
232
Michael J. Spencer63c133b2010-11-30 23:27:35 +0000233/// find_last_of - Find the last character in the string that is in \arg C,
234/// or npos if not found.
235///
236/// Note: O(size() + Chars.size())
237StringRef::size_type StringRef::find_last_of(StringRef Chars,
238 size_t From) const {
239 std::bitset<1 << CHAR_BIT> CharBits;
240 for (size_type i = 0; i != Chars.size(); ++i)
241 CharBits.set((unsigned char)Chars[i]);
242
243 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
244 if (CharBits.test((unsigned char)Data[i]))
245 return i;
246 return npos;
247}
Chris Lattner05a32c82009-09-20 01:22:16 +0000248
249//===----------------------------------------------------------------------===//
250// Helpful Algorithms
251//===----------------------------------------------------------------------===//
252
253/// count - Return the number of non-overlapped occurrences of \arg Str in
254/// the string.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000255size_t StringRef::count(StringRef Str) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000256 size_t Count = 0;
257 size_t N = Str.size();
258 if (N > Length)
259 return 0;
260 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
261 if (substr(i, N).equals(Str))
262 ++Count;
263 return Count;
264}
265
John McCall1e7ad392010-02-28 09:55:58 +0000266static unsigned GetAutoSenseRadix(StringRef &Str) {
267 if (Str.startswith("0x")) {
268 Str = Str.substr(2);
269 return 16;
270 } else if (Str.startswith("0b")) {
271 Str = Str.substr(2);
272 return 2;
273 } else if (Str.startswith("0")) {
274 return 8;
275 } else {
276 return 10;
277 }
278}
279
280
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000281/// GetAsUnsignedInteger - Workhorse method that converts a integer character
282/// sequence of radix up to 36 to an unsigned long long value.
Chris Lattnercea14382009-09-19 19:47:14 +0000283static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
284 unsigned long long &Result) {
285 // Autosense radix if not specified.
John McCall1e7ad392010-02-28 09:55:58 +0000286 if (Radix == 0)
287 Radix = GetAutoSenseRadix(Str);
Michael J. Spencer326990f2010-11-26 04:16:08 +0000288
Chris Lattnercea14382009-09-19 19:47:14 +0000289 // Empty strings (after the radix autosense) are invalid.
290 if (Str.empty()) return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000291
Chris Lattnercea14382009-09-19 19:47:14 +0000292 // Parse all the bytes of the string given this radix. Watch for overflow.
293 Result = 0;
294 while (!Str.empty()) {
295 unsigned CharVal;
296 if (Str[0] >= '0' && Str[0] <= '9')
297 CharVal = Str[0]-'0';
298 else if (Str[0] >= 'a' && Str[0] <= 'z')
299 CharVal = Str[0]-'a'+10;
300 else if (Str[0] >= 'A' && Str[0] <= 'Z')
301 CharVal = Str[0]-'A'+10;
302 else
303 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000304
Chris Lattnercea14382009-09-19 19:47:14 +0000305 // If the parsed value is larger than the integer radix, the string is
306 // invalid.
307 if (CharVal >= Radix)
308 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000309
Chris Lattnercea14382009-09-19 19:47:14 +0000310 // Add in this character.
311 unsigned long long PrevResult = Result;
312 Result = Result*Radix+CharVal;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000313
Chris Lattnercea14382009-09-19 19:47:14 +0000314 // Check for overflow.
315 if (Result < PrevResult)
316 return true;
317
318 Str = Str.substr(1);
319 }
Michael J. Spencer326990f2010-11-26 04:16:08 +0000320
Chris Lattnercea14382009-09-19 19:47:14 +0000321 return false;
322}
323
324bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
325 return GetAsUnsignedInteger(*this, Radix, Result);
326}
327
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000328
329bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
330 unsigned long long ULLVal;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000331
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000332 // Handle positive strings first.
333 if (empty() || front() != '-') {
334 if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
335 // Check for value so large it overflows a signed value.
336 (long long)ULLVal < 0)
337 return true;
338 Result = ULLVal;
339 return false;
340 }
Michael J. Spencer326990f2010-11-26 04:16:08 +0000341
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000342 // Get the positive part of the value.
343 if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
344 // Reject values so large they'd overflow as negative signed, but allow
345 // "-0". This negates the unsigned so that the negative isn't undefined
346 // on signed overflow.
347 (long long)-ULLVal > 0)
348 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000349
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000350 Result = -ULLVal;
351 return false;
352}
353
354bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
355 long long Val;
356 if (getAsInteger(Radix, Val) ||
357 (int)Val != Val)
358 return true;
359 Result = Val;
360 return false;
361}
362
363bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
364 unsigned long long Val;
365 if (getAsInteger(Radix, Val) ||
366 (unsigned)Val != Val)
367 return true;
368 Result = Val;
369 return false;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000370}
John McCall1e7ad392010-02-28 09:55:58 +0000371
372bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
373 StringRef Str = *this;
374
375 // Autosense radix if not specified.
376 if (Radix == 0)
377 Radix = GetAutoSenseRadix(Str);
378
379 assert(Radix > 1 && Radix <= 36);
Michael J. Spencer326990f2010-11-26 04:16:08 +0000380
John McCall1e7ad392010-02-28 09:55:58 +0000381 // Empty strings (after the radix autosense) are invalid.
382 if (Str.empty()) return true;
383
384 // Skip leading zeroes. This can be a significant improvement if
385 // it means we don't need > 64 bits.
386 while (!Str.empty() && Str.front() == '0')
387 Str = Str.substr(1);
388
389 // If it was nothing but zeroes....
390 if (Str.empty()) {
391 Result = APInt(64, 0);
392 return false;
393 }
394
395 // (Over-)estimate the required number of bits.
396 unsigned Log2Radix = 0;
397 while ((1U << Log2Radix) < Radix) Log2Radix++;
398 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
399
400 unsigned BitWidth = Log2Radix * Str.size();
401 if (BitWidth < Result.getBitWidth())
402 BitWidth = Result.getBitWidth(); // don't shrink the result
403 else
Jay Foad40f8f622010-12-07 08:25:19 +0000404 Result = Result.zext(BitWidth);
John McCall1e7ad392010-02-28 09:55:58 +0000405
406 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
407 if (!IsPowerOf2Radix) {
408 // These must have the same bit-width as Result.
409 RadixAP = APInt(BitWidth, Radix);
410 CharAP = APInt(BitWidth, 0);
411 }
412
413 // Parse all the bytes of the string given this radix.
414 Result = 0;
415 while (!Str.empty()) {
416 unsigned CharVal;
417 if (Str[0] >= '0' && Str[0] <= '9')
418 CharVal = Str[0]-'0';
419 else if (Str[0] >= 'a' && Str[0] <= 'z')
420 CharVal = Str[0]-'a'+10;
421 else if (Str[0] >= 'A' && Str[0] <= 'Z')
422 CharVal = Str[0]-'A'+10;
423 else
424 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000425
John McCall1e7ad392010-02-28 09:55:58 +0000426 // If the parsed value is larger than the integer radix, the string is
427 // invalid.
428 if (CharVal >= Radix)
429 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000430
John McCall1e7ad392010-02-28 09:55:58 +0000431 // Add in this character.
432 if (IsPowerOf2Radix) {
433 Result <<= Log2Radix;
434 Result |= CharVal;
435 } else {
436 Result *= RadixAP;
437 CharAP = CharVal;
438 Result += CharAP;
439 }
440
441 Str = Str.substr(1);
442 }
Michael J. Spencer326990f2010-11-26 04:16:08 +0000443
John McCall1e7ad392010-02-28 09:55:58 +0000444 return false;
445}