blob: ca0f518a88b6273b13ca47ee41886aa1ccda7331 [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"
Douglas Gregorad6b6da2010-01-07 00:51:54 +000012
Daniel Dunbare6551282009-09-16 22:38:48 +000013using namespace llvm;
14
Daniel Dunbar77696be2009-09-22 03:34:40 +000015// MSVC emits references to this into the translation units which reference it.
16#ifndef _MSC_VER
Daniel Dunbare6551282009-09-16 22:38:48 +000017const size_t StringRef::npos;
Daniel Dunbar77696be2009-09-22 03:34:40 +000018#endif
Chris Lattnercea14382009-09-19 19:47:14 +000019
Benjamin Kramer05872ea2009-11-12 20:36:59 +000020static char ascii_tolower(char x) {
21 if (x >= 'A' && x <= 'Z')
22 return x - 'A' + 'a';
23 return x;
24}
25
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000026static bool ascii_isdigit(char x) {
27 return x >= '0' && x <= '9';
28}
29
Benjamin Kramer05872ea2009-11-12 20:36:59 +000030/// compare_lower - Compare strings, ignoring case.
31int StringRef::compare_lower(StringRef RHS) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +000032 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
Benjamin Kramer05872ea2009-11-12 20:36:59 +000033 char LHC = ascii_tolower(Data[I]);
34 char RHC = ascii_tolower(RHS.Data[I]);
35 if (LHC != RHC)
36 return LHC < RHC ? -1 : 1;
37 }
38
39 if (Length == RHS.Length)
40 return 0;
41 return Length < RHS.Length ? -1 : 1;
42}
43
Jakob Stoklund Olesen160a3bf2010-05-26 21:47:28 +000044/// compare_numeric - Compare strings, handle embedded numbers.
45int StringRef::compare_numeric(StringRef RHS) const {
46 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
47 if (Data[I] == RHS.Data[I])
48 continue;
49 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) {
50 // The longer sequence of numbers is larger. This doesn't really handle
51 // prefixed zeros well.
52 for (size_t J = I+1; J != E+1; ++J) {
53 bool ld = J < Length && ascii_isdigit(Data[J]);
54 bool rd = J < RHS.Length && ascii_isdigit(RHS.Data[J]);
55 if (ld != rd)
56 return rd ? -1 : 1;
57 if (!rd)
58 break;
59 }
60 }
61 return Data[I] < RHS.Data[I] ? -1 : 1;
62 }
63 if (Length == RHS.Length)
64 return 0;
65 return Length < RHS.Length ? -1 : 1;
66}
67
Douglas Gregor7e54d5b2009-12-31 04:24:34 +000068// Compute the edit distance between the two given strings.
Douglas Gregor441c8b42009-12-30 17:23:44 +000069unsigned StringRef::edit_distance(llvm::StringRef Other,
70 bool AllowReplacements) {
Douglas Gregor7e54d5b2009-12-31 04:24:34 +000071 // The algorithm implemented below is the "classic"
72 // dynamic-programming algorithm for computing the Levenshtein
73 // distance, which is described here:
74 //
75 // http://en.wikipedia.org/wiki/Levenshtein_distance
76 //
77 // Although the algorithm is typically described using an m x n
78 // array, only two rows are used at a time, so this implemenation
79 // just keeps two separate vectors for those two rows.
Douglas Gregor441c8b42009-12-30 17:23:44 +000080 size_type m = size();
81 size_type n = Other.size();
82
Douglas Gregor2772ea82010-01-07 02:24:06 +000083 const unsigned SmallBufferSize = 64;
84 unsigned SmallBuffer[SmallBufferSize];
85 unsigned *Allocated = 0;
86 unsigned *previous = SmallBuffer;
87 if (2*(n + 1) > SmallBufferSize)
88 Allocated = previous = new unsigned [2*(n+1)];
89 unsigned *current = previous + (n + 1);
Douglas Gregorad6b6da2010-01-07 00:51:54 +000090
91 for (unsigned i = 0; i <= n; ++i)
Douglas Gregor441c8b42009-12-30 17:23:44 +000092 previous[i] = i;
93
Douglas Gregor441c8b42009-12-30 17:23:44 +000094 for (size_type y = 1; y <= m; ++y) {
Douglas Gregor441c8b42009-12-30 17:23:44 +000095 current[0] = y;
96 for (size_type x = 1; x <= n; ++x) {
97 if (AllowReplacements) {
98 current[x] = min(previous[x-1] + ((*this)[y-1] == Other[x-1]? 0u:1u),
99 min(current[x-1], previous[x])+1);
100 }
101 else {
102 if ((*this)[y-1] == Other[x-1]) current[x] = previous[x-1];
103 else current[x] = min(current[x-1], previous[x]) + 1;
104 }
105 }
Douglas Gregorad6b6da2010-01-07 00:51:54 +0000106
107 unsigned *tmp = current;
108 current = previous;
109 previous = tmp;
Douglas Gregor441c8b42009-12-30 17:23:44 +0000110 }
111
Douglas Gregorad6b6da2010-01-07 00:51:54 +0000112 unsigned Result = previous[n];
Douglas Gregor2772ea82010-01-07 02:24:06 +0000113 delete [] Allocated;
Douglas Gregorad6b6da2010-01-07 00:51:54 +0000114
115 return Result;
Douglas Gregor441c8b42009-12-30 17:23:44 +0000116}
117
Chris Lattner05a32c82009-09-20 01:22:16 +0000118//===----------------------------------------------------------------------===//
119// String Searching
120//===----------------------------------------------------------------------===//
121
122
123/// find - Search for the first string \arg Str in the string.
124///
125/// \return - The index of the first occurence of \arg Str, or npos if not
126/// found.
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000127size_t StringRef::find(StringRef Str, size_t From) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000128 size_t N = Str.size();
129 if (N > Length)
130 return npos;
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000131 for (size_t e = Length - N + 1, i = min(From, e); i != e; ++i)
Chris Lattner05a32c82009-09-20 01:22:16 +0000132 if (substr(i, N).equals(Str))
133 return i;
134 return npos;
135}
136
137/// rfind - Search for the last string \arg Str in the string.
138///
139/// \return - The index of the last occurence of \arg Str, or npos if not
140/// found.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000141size_t StringRef::rfind(StringRef Str) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000142 size_t N = Str.size();
143 if (N > Length)
144 return npos;
145 for (size_t i = Length - N + 1, e = 0; i != e;) {
146 --i;
147 if (substr(i, N).equals(Str))
148 return i;
149 }
150 return npos;
151}
152
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000153/// find_first_of - Find the first character in the string that is in \arg
154/// Chars, or npos if not found.
155///
156/// Note: O(size() * Chars.size())
157StringRef::size_type StringRef::find_first_of(StringRef Chars,
158 size_t From) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000159 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Chris Lattner05a32c82009-09-20 01:22:16 +0000160 if (Chars.find(Data[i]) != npos)
161 return i;
162 return npos;
163}
164
165/// find_first_not_of - Find the first character in the string that is not
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000166/// \arg C or npos if not found.
167StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000168 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Daniel Dunbar64066bd2009-11-11 00:28:53 +0000169 if (Data[i] != C)
170 return i;
171 return npos;
172}
173
174/// find_first_not_of - Find the first character in the string that is not
175/// in the string \arg Chars, or npos if not found.
176///
177/// Note: O(size() * Chars.size())
178StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
179 size_t From) const {
Daniel Dunbar58ce7ac2009-11-19 18:53:18 +0000180 for (size_type i = min(From, Length), e = Length; i != e; ++i)
Chris Lattner05a32c82009-09-20 01:22:16 +0000181 if (Chars.find(Data[i]) == npos)
182 return i;
183 return npos;
184}
185
186
187//===----------------------------------------------------------------------===//
188// Helpful Algorithms
189//===----------------------------------------------------------------------===//
190
191/// count - Return the number of non-overlapped occurrences of \arg Str in
192/// the string.
Daniel Dunbar2928c832009-11-06 10:58:06 +0000193size_t StringRef::count(StringRef Str) const {
Chris Lattner05a32c82009-09-20 01:22:16 +0000194 size_t Count = 0;
195 size_t N = Str.size();
196 if (N > Length)
197 return 0;
198 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
199 if (substr(i, N).equals(Str))
200 ++Count;
201 return Count;
202}
203
John McCall1e7ad392010-02-28 09:55:58 +0000204static unsigned GetAutoSenseRadix(StringRef &Str) {
205 if (Str.startswith("0x")) {
206 Str = Str.substr(2);
207 return 16;
208 } else if (Str.startswith("0b")) {
209 Str = Str.substr(2);
210 return 2;
211 } else if (Str.startswith("0")) {
212 return 8;
213 } else {
214 return 10;
215 }
216}
217
218
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000219/// GetAsUnsignedInteger - Workhorse method that converts a integer character
220/// sequence of radix up to 36 to an unsigned long long value.
Chris Lattnercea14382009-09-19 19:47:14 +0000221static bool GetAsUnsignedInteger(StringRef Str, unsigned Radix,
222 unsigned long long &Result) {
223 // Autosense radix if not specified.
John McCall1e7ad392010-02-28 09:55:58 +0000224 if (Radix == 0)
225 Radix = GetAutoSenseRadix(Str);
Chris Lattnercea14382009-09-19 19:47:14 +0000226
227 // Empty strings (after the radix autosense) are invalid.
228 if (Str.empty()) return true;
229
230 // Parse all the bytes of the string given this radix. Watch for overflow.
231 Result = 0;
232 while (!Str.empty()) {
233 unsigned CharVal;
234 if (Str[0] >= '0' && Str[0] <= '9')
235 CharVal = Str[0]-'0';
236 else if (Str[0] >= 'a' && Str[0] <= 'z')
237 CharVal = Str[0]-'a'+10;
238 else if (Str[0] >= 'A' && Str[0] <= 'Z')
239 CharVal = Str[0]-'A'+10;
240 else
241 return true;
242
243 // If the parsed value is larger than the integer radix, the string is
244 // invalid.
245 if (CharVal >= Radix)
246 return true;
247
248 // Add in this character.
249 unsigned long long PrevResult = Result;
250 Result = Result*Radix+CharVal;
251
252 // Check for overflow.
253 if (Result < PrevResult)
254 return true;
255
256 Str = Str.substr(1);
257 }
258
259 return false;
260}
261
262bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
263 return GetAsUnsignedInteger(*this, Radix, Result);
264}
265
Chris Lattner63c6b7d2009-09-19 23:58:48 +0000266
267bool StringRef::getAsInteger(unsigned Radix, long long &Result) const {
268 unsigned long long ULLVal;
269
270 // Handle positive strings first.
271 if (empty() || front() != '-') {
272 if (GetAsUnsignedInteger(*this, Radix, ULLVal) ||
273 // Check for value so large it overflows a signed value.
274 (long long)ULLVal < 0)
275 return true;
276 Result = ULLVal;
277 return false;
278 }
279
280 // Get the positive part of the value.
281 if (GetAsUnsignedInteger(substr(1), Radix, ULLVal) ||
282 // Reject values so large they'd overflow as negative signed, but allow
283 // "-0". This negates the unsigned so that the negative isn't undefined
284 // on signed overflow.
285 (long long)-ULLVal > 0)
286 return true;
287
288 Result = -ULLVal;
289 return false;
290}
291
292bool StringRef::getAsInteger(unsigned Radix, int &Result) const {
293 long long Val;
294 if (getAsInteger(Radix, Val) ||
295 (int)Val != Val)
296 return true;
297 Result = Val;
298 return false;
299}
300
301bool StringRef::getAsInteger(unsigned Radix, unsigned &Result) const {
302 unsigned long long Val;
303 if (getAsInteger(Radix, Val) ||
304 (unsigned)Val != Val)
305 return true;
306 Result = Val;
307 return false;
308}
John McCall1e7ad392010-02-28 09:55:58 +0000309
310bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
311 StringRef Str = *this;
312
313 // Autosense radix if not specified.
314 if (Radix == 0)
315 Radix = GetAutoSenseRadix(Str);
316
317 assert(Radix > 1 && Radix <= 36);
318
319 // Empty strings (after the radix autosense) are invalid.
320 if (Str.empty()) return true;
321
322 // Skip leading zeroes. This can be a significant improvement if
323 // it means we don't need > 64 bits.
324 while (!Str.empty() && Str.front() == '0')
325 Str = Str.substr(1);
326
327 // If it was nothing but zeroes....
328 if (Str.empty()) {
329 Result = APInt(64, 0);
330 return false;
331 }
332
333 // (Over-)estimate the required number of bits.
334 unsigned Log2Radix = 0;
335 while ((1U << Log2Radix) < Radix) Log2Radix++;
336 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
337
338 unsigned BitWidth = Log2Radix * Str.size();
339 if (BitWidth < Result.getBitWidth())
340 BitWidth = Result.getBitWidth(); // don't shrink the result
341 else
342 Result.zext(BitWidth);
343
344 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
345 if (!IsPowerOf2Radix) {
346 // These must have the same bit-width as Result.
347 RadixAP = APInt(BitWidth, Radix);
348 CharAP = APInt(BitWidth, 0);
349 }
350
351 // Parse all the bytes of the string given this radix.
352 Result = 0;
353 while (!Str.empty()) {
354 unsigned CharVal;
355 if (Str[0] >= '0' && Str[0] <= '9')
356 CharVal = Str[0]-'0';
357 else if (Str[0] >= 'a' && Str[0] <= 'z')
358 CharVal = Str[0]-'a'+10;
359 else if (Str[0] >= 'A' && Str[0] <= 'Z')
360 CharVal = Str[0]-'A'+10;
361 else
362 return true;
363
364 // If the parsed value is larger than the integer radix, the string is
365 // invalid.
366 if (CharVal >= Radix)
367 return true;
368
369 // Add in this character.
370 if (IsPowerOf2Radix) {
371 Result <<= Log2Radix;
372 Result |= CharVal;
373 } else {
374 Result *= RadixAP;
375 CharAP = CharVal;
376 Result += CharAP;
377 }
378
379 Str = Str.substr(1);
380 }
381
382 return false;
383}