blob: abe570f6df4bedf163f2d66bc90869327ac5428b [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"
Chandler Carruth528f0bb2012-03-04 10:55:27 +000013#include "llvm/ADT/Hashing.h"
Kaelyn Uhrain01d53ec2012-02-15 22:13:07 +000014#include "llvm/ADT/edit_distance.h"
Benjamin Kramer250eb002010-08-23 18:16:08 +000015#include <bitset>
Douglas Gregorad6b6da2010-01-07 00:51:54 +000016
Daniel Dunbare6551282009-09-16 22:38:48 +000017using namespace llvm;
18
Daniel Dunbar77696be2009-09-22 03:34:40 +000019// MSVC emits references to this into the translation units which reference it.
20#ifndef _MSC_VER
Daniel Dunbare6551282009-09-16 22:38:48 +000021const size_t StringRef::npos;
Daniel Dunbar77696be2009-09-22 03:34:40 +000022#endif
Chris Lattnercea14382009-09-19 19:47:14 +000023
Benjamin Kramer05872ea2009-11-12 20:36:59 +000024static char ascii_tolower(char x) {
25 if (x >= 'A' && x <= 'Z')
26 return x - 'A' + 'a';
27 return x;
28}
29
Daniel Dunbar589fbb12011-11-06 18:04:43 +000030static char ascii_toupper(char x) {
31 if (x >= 'a' && x <= 'z')
32 return x - 'a' + 'A';
33 return x;
34}
35
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000036static bool ascii_isdigit(char x) {
37 return x >= '0' && x <= '9';
38}
39
Benjamin Kramer05872ea2009-11-12 20:36:59 +000040/// compare_lower - Compare strings, ignoring case.
41int StringRef::compare_lower(StringRef RHS) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +000042 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
Benjamin Kramer0043e352010-08-26 14:21:08 +000043 unsigned char LHC = ascii_tolower(Data[I]);
44 unsigned char RHC = ascii_tolower(RHS.Data[I]);
Benjamin Kramer05872ea2009-11-12 20:36:59 +000045 if (LHC != RHC)
46 return LHC < RHC ? -1 : 1;
47 }
48
49 if (Length == RHS.Length)
Benjamin Kramer0043e352010-08-26 14:21:08 +000050 return 0;
Benjamin Kramer05872ea2009-11-12 20:36:59 +000051 return Length < RHS.Length ? -1 : 1;
52}
53
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000054/// compare_numeric - Compare strings, handle embedded numbers.
55int StringRef::compare_numeric(StringRef RHS) const {
56 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000057 // Check for sequences of digits.
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000058 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000059 // The longer sequence of numbers is considered larger.
60 // This doesn't really handle prefixed zeros well.
61 size_t J;
62 for (J = I + 1; J != E + 1; ++J) {
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000063 bool ld = J < Length && ascii_isdigit(Data[J]);
64 bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
65 if (ld != rd)
66 return rd ? -1 : 1;
67 if (!rd)
68 break;
69 }
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000070 // The two number sequences have the same length (J-I), just memcmp them.
71 if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
72 return Res < 0 ? -1 : 1;
73 // Identical number sequences, continue search after the numbers.
74 I = J - 1;
75 continue;
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000076 }
Jakob Stoklund Olesen7850dd02011-09-30 17:03:55 +000077 if (Data[I] != RHS.Data[I])
78 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000079 }
80 if (Length == RHS.Length)
Benjamin Kramer0043e352010-08-26 14:21:08 +000081 return 0;
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000082 return Length < RHS.Length ? -1 : 1;
83}
84
Douglas Gregor7e54d5b2009-12-31 04:24:34 +000085// Compute the edit distance between the two given strings.
Michael J. Spencer326990f2010-11-26 04:16:08 +000086unsigned StringRef::edit_distance(llvm::StringRef Other,
Douglas Gregor5ee568a2010-10-19 22:13:48 +000087 bool AllowReplacements,
88 unsigned MaxEditDistance) {
Kaelyn Uhrain01d53ec2012-02-15 22:13:07 +000089 return llvm::ComputeEditDistance(
90 llvm::ArrayRef<char>(data(), size()),
91 llvm::ArrayRef<char>(Other.data(), Other.size()),
92 AllowReplacements, MaxEditDistance);
Douglas Gregor441c8b42009-12-30 17:23:44 +000093}
94
Chris Lattner05a32c82009-09-20 01:22:16 +000095//===----------------------------------------------------------------------===//
Daniel Dunbar589fbb12011-11-06 18:04:43 +000096// String Operations
97//===----------------------------------------------------------------------===//
98
99std::string StringRef::lower() const {
100 std::string Result(size(), char());
101 for (size_type i = 0, e = size(); i != e; ++i) {
102 Result[i] = ascii_tolower(Data[i]);
103 }
104 return Result;
105}
106
107std::string StringRef::upper() const {
108 std::string Result(size(), char());
109 for (size_type i = 0, e = size(); i != e; ++i) {
Benjamin Kramera7b966f2011-11-06 20:36:50 +0000110 Result[i] = ascii_toupper(Data[i]);
Daniel Dunbar589fbb12011-11-06 18:04:43 +0000111 }
112 return Result;
113}
114
115//===----------------------------------------------------------------------===//
Chris Lattner05a32c82009-09-20 01:22:16 +0000116// String Searching
117//===----------------------------------------------------------------------===//
118
119
120/// find - Search for the first string \arg Str in the string.
121///
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000122/// \return - The index of the first occurrence of \arg Str, or npos if not
Chris Lattner05a32c82009-09-20 01:22:16 +0000123/// found.
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000124size_t StringRef::find(StringRef Str, size_t From) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000125 size_t N = Str.size();
126 if (N > Length)
127 return npos;
Benjamin Kramer6e6a5582011-10-15 10:08:31 +0000128
129 // For short haystacks or unsupported needles fall back to the naive algorithm
130 if (Length < 16 || N > 255 || N == 0) {
131 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
132 if (substr(i, N).equals(Str))
133 return i;
134 return npos;
135 }
136
Benjamin Kramere7a07192011-10-17 20:49:40 +0000137 if (From >= Length)
138 return npos;
139
Benjamin Kramer6e6a5582011-10-15 10:08:31 +0000140 // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
141 uint8_t BadCharSkip[256];
142 std::memset(BadCharSkip, N, 256);
143 for (unsigned i = 0; i != N-1; ++i)
144 BadCharSkip[(uint8_t)Str[i]] = N-1-i;
145
Benjamin Kramere7a07192011-10-17 20:49:40 +0000146 unsigned Len = Length-From, Pos = From;
Benjamin Kramer6e6a5582011-10-15 10:08:31 +0000147 while (Len >= N) {
148 if (substr(Pos, N).equals(Str)) // See if this is the correct substring.
149 return Pos;
150
151 // Otherwise skip the appropriate number of bytes.
Benjamin Kramere7a07192011-10-17 20:49:40 +0000152 uint8_t Skip = BadCharSkip[(uint8_t)(*this)[Pos+N-1]];
Benjamin Kramer6e6a5582011-10-15 10:08:31 +0000153 Len -= Skip;
154 Pos += Skip;
155 }
156
Chris Lattner05a32c82009-09-20 01:22:16 +0000157 return npos;
158}
159
160/// rfind - Search for the last string \arg Str in the string.
161///
Chris Lattner7a2bdde2011-04-15 05:18:47 +0000162/// \return - The index of the last occurrence of \arg Str, or npos if not
Chris Lattner05a32c82009-09-20 01:22:16 +0000163/// found.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000164size_t StringRef::rfind(StringRef Str) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000165 size_t N = Str.size();
166 if (N > Length)
167 return npos;
168 for (size_t i = Length - N + 1, e = 0; i != e;) {
169 --i;
170 if (substr(i, N).equals(Str))
171 return i;
172 }
173 return npos;
174}
175
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000176/// find_first_of - Find the first character in the string that is in \arg
177/// Chars, or npos if not found.
178///
Benjamin Kramer250eb002010-08-23 18:16:08 +0000179/// Note: O(size() + Chars.size())
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000180StringRef::size_type StringRef::find_first_of(StringRef Chars,
181 size_t From) const {
Benjamin Kramer250eb002010-08-23 18:16:08 +0000182 std::bitset<1 << CHAR_BIT> CharBits;
183 for (size_type i = 0; i != Chars.size(); ++i)
184 CharBits.set((unsigned char)Chars[i]);
185
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000186 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer250eb002010-08-23 18:16:08 +0000187 if (CharBits.test((unsigned char)Data[i]))
Chris Lattner05a32c82009-09-20 01:22:16 +0000188 return i;
189 return npos;
190}
191
192/// find_first_not_of - Find the first character in the string that is not
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000193/// \arg C or npos if not found.
194StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000195 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000196 if (Data[i] != C)
197 return i;
198 return npos;
199}
200
201/// find_first_not_of - Find the first character in the string that is not
202/// in the string \arg Chars, or npos if not found.
203///
Benjamin Kramer250eb002010-08-23 18:16:08 +0000204/// Note: O(size() + Chars.size())
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000205StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
206 size_t From) const {
Benjamin Kramer250eb002010-08-23 18:16:08 +0000207 std::bitset<1 << CHAR_BIT> CharBits;
208 for (size_type i = 0; i != Chars.size(); ++i)
209 CharBits.set((unsigned char)Chars[i]);
210
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000211 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer250eb002010-08-23 18:16:08 +0000212 if (!CharBits.test((unsigned char)Data[i]))
Chris Lattner05a32c82009-09-20 01:22:16 +0000213 return i;
214 return npos;
215}
216
Michael J. Spencer63c133b2010-11-30 23:27:35 +0000217/// find_last_of - Find the last character in the string that is in \arg C,
218/// or npos if not found.
219///
220/// Note: O(size() + Chars.size())
221StringRef::size_type StringRef::find_last_of(StringRef Chars,
222 size_t From) const {
223 std::bitset<1 << CHAR_BIT> CharBits;
224 for (size_type i = 0; i != Chars.size(); ++i)
225 CharBits.set((unsigned char)Chars[i]);
226
227 for (size_type i = min(From, Length) - 1, e = -1; i != e; --i)
228 if (CharBits.test((unsigned char)Data[i]))
229 return i;
230 return npos;
231}
Chris Lattner05a32c82009-09-20 01:22:16 +0000232
Duncan Sandsbf8653f2012-02-21 12:00:25 +0000233void StringRef::split(SmallVectorImpl<StringRef> &A,
234 StringRef Separators, int MaxSplit,
235 bool KeepEmpty) const {
236 StringRef rest = *this;
237
238 // rest.data() is used to distinguish cases like "a," that splits into
239 // "a" + "" and "a" that splits into "a" + 0.
240 for (int splits = 0;
241 rest.data() != NULL && (MaxSplit < 0 || splits < MaxSplit);
242 ++splits) {
243 std::pair<StringRef, StringRef> p = rest.split(Separators);
244
Duncan Sands37b6e5a2012-02-24 09:01:34 +0000245 if (KeepEmpty || p.first.size() != 0)
Duncan Sandsbf8653f2012-02-21 12:00:25 +0000246 A.push_back(p.first);
247 rest = p.second;
248 }
249 // If we have a tail left, add it.
250 if (rest.data() != NULL && (rest.size() != 0 || KeepEmpty))
251 A.push_back(rest);
252}
253
Chris Lattner05a32c82009-09-20 01:22:16 +0000254//===----------------------------------------------------------------------===//
255// Helpful Algorithms
256//===----------------------------------------------------------------------===//
257
258/// count - Return the number of non-overlapped occurrences of \arg Str in
259/// the string.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000260size_t StringRef::count(StringRef Str) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000261 size_t Count = 0;
262 size_t N = Str.size();
263 if (N > Length)
264 return 0;
265 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
266 if (substr(i, N).equals(Str))
267 ++Count;
268 return Count;
269}
270
John McCall1e7ad392010-02-28 09:55:58 +0000271static unsigned GetAutoSenseRadix(StringRef &Str) {
272 if (Str.startswith("0x")) {
273 Str = Str.substr(2);
274 return 16;
275 } else if (Str.startswith("0b")) {
276 Str = Str.substr(2);
277 return 2;
278 } else if (Str.startswith("0")) {
279 return 8;
280 } else {
281 return 10;
282 }
283}
284
285
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000286/// GetAsUnsignedInteger - Workhorse method that converts a integer character
287/// sequence of radix up to 36 to an unsigned long long value.
Michael J. Spencer9130b422012-03-10 23:02:54 +0000288bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
289 unsigned long long &Result) {
Chris Lattnercea14382009-09-19 19:47:14 +0000290 // Autosense radix if not specified.
John McCall1e7ad392010-02-28 09:55:58 +0000291 if (Radix == 0)
292 Radix = GetAutoSenseRadix(Str);
Michael J. Spencer326990f2010-11-26 04:16:08 +0000293
Chris Lattnercea14382009-09-19 19:47:14 +0000294 // Empty strings (after the radix autosense) are invalid.
295 if (Str.empty()) return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000296
Chris Lattnercea14382009-09-19 19:47:14 +0000297 // Parse all the bytes of the string given this radix. Watch for overflow.
298 Result = 0;
299 while (!Str.empty()) {
300 unsigned CharVal;
301 if (Str[0] >= '0' && Str[0] <= '9')
302 CharVal = Str[0]-'0';
303 else if (Str[0] >= 'a' && Str[0] <= 'z')
304 CharVal = Str[0]-'a'+10;
305 else if (Str[0] >= 'A' && Str[0] <= 'Z')
306 CharVal = Str[0]-'A'+10;
307 else
308 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000309
Chris Lattnercea14382009-09-19 19:47:14 +0000310 // If the parsed value is larger than the integer radix, the string is
311 // invalid.
312 if (CharVal >= Radix)
313 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000314
Chris Lattnercea14382009-09-19 19:47:14 +0000315 // Add in this character.
316 unsigned long long PrevResult = Result;
317 Result = Result*Radix+CharVal;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000318
Chris Lattnercea14382009-09-19 19:47:14 +0000319 // Check for overflow.
320 if (Result < PrevResult)
321 return true;
322
323 Str = Str.substr(1);
324 }
Michael J. Spencer326990f2010-11-26 04:16:08 +0000325
Chris Lattnercea14382009-09-19 19:47:14 +0000326 return false;
327}
328
Michael J. Spencer9130b422012-03-10 23:02:54 +0000329bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
330 long long &Result) {
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000331 unsigned long long ULLVal;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000332
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000333 // Handle positive strings first.
Michael J. Spencer9130b422012-03-10 23:02:54 +0000334 if (Str.empty() || Str.front() != '-') {
335 if (getAsUnsignedInteger(Str, Radix, ULLVal) ||
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000336 // Check for value so large it overflows a signed value.
337 (long long)ULLVal < 0)
338 return true;
339 Result = ULLVal;
340 return false;
341 }
Michael J. Spencer326990f2010-11-26 04:16:08 +0000342
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000343 // Get the positive part of the value.
Michael J. Spencer9130b422012-03-10 23:02:54 +0000344 if (getAsUnsignedInteger(Str.substr(1), Radix, ULLVal) ||
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000345 // Reject values so large they'd overflow as negative signed, but allow
346 // "-0". This negates the unsigned so that the negative isn't undefined
347 // on signed overflow.
348 (long long)-ULLVal > 0)
349 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000350
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000351 Result = -ULLVal;
352 return false;
353}
354
John McCall1e7ad392010-02-28 09:55:58 +0000355bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
356 StringRef Str = *this;
357
358 // Autosense radix if not specified.
359 if (Radix == 0)
360 Radix = GetAutoSenseRadix(Str);
361
362 assert(Radix > 1 && Radix <= 36);
Michael J. Spencer326990f2010-11-26 04:16:08 +0000363
John McCall1e7ad392010-02-28 09:55:58 +0000364 // Empty strings (after the radix autosense) are invalid.
365 if (Str.empty()) return true;
366
367 // Skip leading zeroes. This can be a significant improvement if
368 // it means we don't need > 64 bits.
369 while (!Str.empty() && Str.front() == '0')
370 Str = Str.substr(1);
371
372 // If it was nothing but zeroes....
373 if (Str.empty()) {
374 Result = APInt(64, 0);
375 return false;
376 }
377
378 // (Over-)estimate the required number of bits.
379 unsigned Log2Radix = 0;
380 while ((1U << Log2Radix) < Radix) Log2Radix++;
381 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
382
383 unsigned BitWidth = Log2Radix * Str.size();
384 if (BitWidth < Result.getBitWidth())
385 BitWidth = Result.getBitWidth(); // don't shrink the result
386 else
Jay Foad40f8f622010-12-07 08:25:19 +0000387 Result = Result.zext(BitWidth);
John McCall1e7ad392010-02-28 09:55:58 +0000388
389 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
390 if (!IsPowerOf2Radix) {
391 // These must have the same bit-width as Result.
392 RadixAP = APInt(BitWidth, Radix);
393 CharAP = APInt(BitWidth, 0);
394 }
395
396 // Parse all the bytes of the string given this radix.
397 Result = 0;
398 while (!Str.empty()) {
399 unsigned CharVal;
400 if (Str[0] >= '0' && Str[0] <= '9')
401 CharVal = Str[0]-'0';
402 else if (Str[0] >= 'a' && Str[0] <= 'z')
403 CharVal = Str[0]-'a'+10;
404 else if (Str[0] >= 'A' && Str[0] <= 'Z')
405 CharVal = Str[0]-'A'+10;
406 else
407 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000408
John McCall1e7ad392010-02-28 09:55:58 +0000409 // If the parsed value is larger than the integer radix, the string is
410 // invalid.
411 if (CharVal >= Radix)
412 return true;
Michael J. Spencer326990f2010-11-26 04:16:08 +0000413
John McCall1e7ad392010-02-28 09:55:58 +0000414 // Add in this character.
415 if (IsPowerOf2Radix) {
416 Result <<= Log2Radix;
417 Result |= CharVal;
418 } else {
419 Result *= RadixAP;
420 CharAP = CharVal;
421 Result += CharAP;
422 }
423
424 Str = Str.substr(1);
425 }
Michael J. Spencer326990f2010-11-26 04:16:08 +0000426
John McCall1e7ad392010-02-28 09:55:58 +0000427 return false;
428}
Chandler Carruth528f0bb2012-03-04 10:55:27 +0000429
430
431// Implementation of StringRef hashing.
432hash_code llvm::hash_value(StringRef S) {
433 return hash_combine_range(S.begin(), S.end());
434}