Add StringRef::compare_numeric and use it to sort TableGen register records.
[oota-llvm.git] / lib / Support / StringRef.cpp
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
10 #include "llvm/ADT/StringRef.h"
11 #include "llvm/ADT/APInt.h"
12
13 using namespace llvm;
14
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
20 static char ascii_tolower(char x) {
21   if (x >= 'A' && x <= 'Z')
22     return x - 'A' + 'a';
23   return x;
24 }
25
26 static bool ascii_isdigit(char x) {
27   return x >= '0' && x <= '9';
28 }
29
30 /// compare_lower - Compare strings, ignoring case.
31 int StringRef::compare_lower(StringRef RHS) const {
32   for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) {
33     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
44 /// compare_numeric - Compare strings, handle embedded numbers.
45 int 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
68 // Compute the edit distance between the two given strings.
69 unsigned StringRef::edit_distance(llvm::StringRef Other, 
70                                   bool AllowReplacements) {
71   // 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.
80   size_type m = size();
81   size_type n = Other.size();
82
83   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);
90   
91   for (unsigned i = 0; i <= n; ++i) 
92     previous[i] = i;
93
94   for (size_type y = 1; y <= m; ++y) {
95     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     }
106     
107     unsigned *tmp = current;
108     current = previous;
109     previous = tmp;
110   }
111
112   unsigned Result = previous[n];
113   delete [] Allocated;
114   
115   return Result;
116 }
117
118 //===----------------------------------------------------------------------===//
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.
127 size_t StringRef::find(StringRef Str, size_t From) const {
128   size_t N = Str.size();
129   if (N > Length)
130     return npos;
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
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.
141 size_t StringRef::rfind(StringRef Str) const {
142   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
153 /// 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())
157 StringRef::size_type StringRef::find_first_of(StringRef Chars,
158                                               size_t From) const {
159   for (size_type i = min(From, Length), e = Length; i != e; ++i)
160     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
166 /// \arg C or npos if not found.
167 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
168   for (size_type i = min(From, Length), e = Length; i != e; ++i)
169     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())
178 StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
179                                                   size_t From) const {
180   for (size_type i = min(From, Length), e = Length; i != e; ++i)
181     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.
193 size_t StringRef::count(StringRef Str) const {
194   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
204 static 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
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   
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
262 bool StringRef::getAsInteger(unsigned Radix, unsigned long long &Result) const {
263   return GetAsUnsignedInteger(*this, Radix, Result);
264 }
265
266
267 bool 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
292 bool 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
301 bool 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 }  
309
310 bool 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 }