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 #include "llvm/ADT/OwningPtr.h" 13 #include "llvm/ADT/Hashing.h" 14 #include "llvm/ADT/edit_distance.h" 15 #include <bitset> 16 17 using namespace llvm; 18 19 // MSVC emits references to this into the translation units which reference it. 20 #ifndef _MSC_VER 21 const size_t StringRef::npos; 22 #endif 23 24 static char ascii_tolower(char x) { 25 if (x >= 'A' && x <= 'Z') 26 return x - 'A' + 'a'; 27 return x; 28 } 29 30 static char ascii_toupper(char x) { 31 if (x >= 'a' && x <= 'z') 32 return x - 'a' + 'A'; 33 return x; 34 } 35 36 static bool ascii_isdigit(char x) { 37 return x >= '0' && x <= '9'; 38 } 39 40 /// compare_lower - Compare strings, ignoring case. 41 int StringRef::compare_lower(StringRef RHS) const { 42 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) { 43 unsigned char LHC = ascii_tolower(Data[I]); 44 unsigned char RHC = ascii_tolower(RHS.Data[I]); 45 if (LHC != RHC) 46 return LHC < RHC ? -1 : 1; 47 } 48 49 if (Length == RHS.Length) 50 return 0; 51 return Length < RHS.Length ? -1 : 1; 52 } 53 54 /// compare_numeric - Compare strings, handle embedded numbers. 55 int StringRef::compare_numeric(StringRef RHS) const { 56 for (size_t I = 0, E = min(Length, RHS.Length); I != E; ++I) { 57 // Check for sequences of digits. 58 if (ascii_isdigit(Data[I]) && ascii_isdigit(RHS.Data[I])) { 59 // 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) { 63 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 } 70 // 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; 76 } 77 if (Data[I] != RHS.Data[I]) 78 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1; 79 } 80 if (Length == RHS.Length) 81 return 0; 82 return Length < RHS.Length ? -1 : 1; 83 } 84 85 // Compute the edit distance between the two given strings. 86 unsigned StringRef::edit_distance(llvm::StringRef Other, 87 bool AllowReplacements, 88 unsigned MaxEditDistance) { 89 return llvm::ComputeEditDistance( 90 llvm::ArrayRef<char>(data(), size()), 91 llvm::ArrayRef<char>(Other.data(), Other.size()), 92 AllowReplacements, MaxEditDistance); 93 } 94 95 //===----------------------------------------------------------------------===// 96 // String Operations 97 //===----------------------------------------------------------------------===// 98 99 std::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 107 std::string StringRef::upper() const { 108 std::string Result(size(), char()); 109 for (size_type i = 0, e = size(); i != e; ++i) { 110 Result[i] = ascii_toupper(Data[i]); 111 } 112 return Result; 113 } 114 115 //===----------------------------------------------------------------------===// 116 // String Searching 117 //===----------------------------------------------------------------------===// 118 119 120 /// find - Search for the first string \arg Str in the string. 121 /// 122 /// \return - The index of the first occurrence of \arg Str, or npos if not 123 /// found. 124 size_t StringRef::find(StringRef Str, size_t From) const { 125 size_t N = Str.size(); 126 if (N > Length) 127 return npos; 128 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 137 if (From >= Length) 138 return npos; 139 140 // 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 146 unsigned Len = Length-From, Pos = From; 147 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. 152 uint8_t Skip = BadCharSkip[(uint8_t)(*this)[Pos+N-1]]; 153 Len -= Skip; 154 Pos += Skip; 155 } 156 157 return npos; 158 } 159 160 /// rfind - Search for the last string \arg Str in the string. 161 /// 162 /// \return - The index of the last occurrence of \arg Str, or npos if not 163 /// found. 164 size_t StringRef::rfind(StringRef Str) const { 165 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 176 /// find_first_of - Find the first character in the string that is in \arg 177 /// Chars, or npos if not found. 178 /// 179 /// Note: O(size() + Chars.size()) 180 StringRef::size_type StringRef::find_first_of(StringRef Chars, 181 size_t From) const { 182 std::bitset<1 << CHAR_BIT> CharBits; 183 for (size_type i = 0; i != Chars.size(); ++i) 184 CharBits.set((unsigned char)Chars[i]); 185 186 for (size_type i = min(From, Length), e = Length; i != e; ++i) 187 if (CharBits.test((unsigned char)Data[i])) 188 return i; 189 return npos; 190 } 191 192 /// find_first_not_of - Find the first character in the string that is not 193 /// \arg C or npos if not found. 194 StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const { 195 for (size_type i = min(From, Length), e = Length; i != e; ++i) 196 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 /// 204 /// Note: O(size() + Chars.size()) 205 StringRef::size_type StringRef::find_first_not_of(StringRef Chars, 206 size_t From) const { 207 std::bitset<1 << CHAR_BIT> CharBits; 208 for (size_type i = 0; i != Chars.size(); ++i) 209 CharBits.set((unsigned char)Chars[i]); 210 211 for (size_type i = min(From, Length), e = Length; i != e; ++i) 212 if (!CharBits.test((unsigned char)Data[i])) 213 return i; 214 return npos; 215 } 216 217 /// 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()) 221 StringRef::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 } 232 233 void 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 245 if (KeepEmpty || p.first.size() != 0) 246 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 254 //===----------------------------------------------------------------------===// 255 // Helpful Algorithms 256 //===----------------------------------------------------------------------===// 257 258 /// count - Return the number of non-overlapped occurrences of \arg Str in 259 /// the string. 260 size_t StringRef::count(StringRef Str) const { 261 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 271 static unsigned GetAutoSenseRadix(StringRef &Str) { 272 if (Str.startswith("0x")) { 273 Str = Str.substr(2); 274 return 16; 275 } 276 277 if (Str.startswith("0b")) { 278 Str = Str.substr(2); 279 return 2; 280 } 281 282 if (Str.startswith("0o")) { 283 Str = Str.substr(2); 284 return 8; 285 } 286 287 if (Str.startswith("0")) 288 return 8; 289 290 return 10; 291 } 292 293 294 /// GetAsUnsignedInteger - Workhorse method that converts a integer character 295 /// sequence of radix up to 36 to an unsigned long long value. 296 bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix, 297 unsigned long long &Result) { 298 // Autosense radix if not specified. 299 if (Radix == 0) 300 Radix = GetAutoSenseRadix(Str); 301 302 // Empty strings (after the radix autosense) are invalid. 303 if (Str.empty()) return true; 304 305 // Parse all the bytes of the string given this radix. Watch for overflow. 306 Result = 0; 307 while (!Str.empty()) { 308 unsigned CharVal; 309 if (Str[0] >= '0' && Str[0] <= '9') 310 CharVal = Str[0]-'0'; 311 else if (Str[0] >= 'a' && Str[0] <= 'z') 312 CharVal = Str[0]-'a'+10; 313 else if (Str[0] >= 'A' && Str[0] <= 'Z') 314 CharVal = Str[0]-'A'+10; 315 else 316 return true; 317 318 // If the parsed value is larger than the integer radix, the string is 319 // invalid. 320 if (CharVal >= Radix) 321 return true; 322 323 // Add in this character. 324 unsigned long long PrevResult = Result; 325 Result = Result*Radix+CharVal; 326 327 // Check for overflow. 328 if (Result < PrevResult) 329 return true; 330 331 Str = Str.substr(1); 332 } 333 334 return false; 335 } 336 337 bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix, 338 long long &Result) { 339 unsigned long long ULLVal; 340 341 // Handle positive strings first. 342 if (Str.empty() || Str.front() != '-') { 343 if (getAsUnsignedInteger(Str, Radix, ULLVal) || 344 // Check for value so large it overflows a signed value. 345 (long long)ULLVal < 0) 346 return true; 347 Result = ULLVal; 348 return false; 349 } 350 351 // Get the positive part of the value. 352 if (getAsUnsignedInteger(Str.substr(1), Radix, ULLVal) || 353 // Reject values so large they'd overflow as negative signed, but allow 354 // "-0". This negates the unsigned so that the negative isn't undefined 355 // on signed overflow. 356 (long long)-ULLVal > 0) 357 return true; 358 359 Result = -ULLVal; 360 return false; 361 } 362 363 bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const { 364 StringRef Str = *this; 365 366 // Autosense radix if not specified. 367 if (Radix == 0) 368 Radix = GetAutoSenseRadix(Str); 369 370 assert(Radix > 1 && Radix <= 36); 371 372 // Empty strings (after the radix autosense) are invalid. 373 if (Str.empty()) return true; 374 375 // Skip leading zeroes. This can be a significant improvement if 376 // it means we don't need > 64 bits. 377 while (!Str.empty() && Str.front() == '0') 378 Str = Str.substr(1); 379 380 // If it was nothing but zeroes.... 381 if (Str.empty()) { 382 Result = APInt(64, 0); 383 return false; 384 } 385 386 // (Over-)estimate the required number of bits. 387 unsigned Log2Radix = 0; 388 while ((1U << Log2Radix) < Radix) Log2Radix++; 389 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix); 390 391 unsigned BitWidth = Log2Radix * Str.size(); 392 if (BitWidth < Result.getBitWidth()) 393 BitWidth = Result.getBitWidth(); // don't shrink the result 394 else if (BitWidth > Result.getBitWidth()) 395 Result = Result.zext(BitWidth); 396 397 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix 398 if (!IsPowerOf2Radix) { 399 // These must have the same bit-width as Result. 400 RadixAP = APInt(BitWidth, Radix); 401 CharAP = APInt(BitWidth, 0); 402 } 403 404 // Parse all the bytes of the string given this radix. 405 Result = 0; 406 while (!Str.empty()) { 407 unsigned CharVal; 408 if (Str[0] >= '0' && Str[0] <= '9') 409 CharVal = Str[0]-'0'; 410 else if (Str[0] >= 'a' && Str[0] <= 'z') 411 CharVal = Str[0]-'a'+10; 412 else if (Str[0] >= 'A' && Str[0] <= 'Z') 413 CharVal = Str[0]-'A'+10; 414 else 415 return true; 416 417 // If the parsed value is larger than the integer radix, the string is 418 // invalid. 419 if (CharVal >= Radix) 420 return true; 421 422 // Add in this character. 423 if (IsPowerOf2Radix) { 424 Result <<= Log2Radix; 425 Result |= CharVal; 426 } else { 427 Result *= RadixAP; 428 CharAP = CharVal; 429 Result += CharAP; 430 } 431 432 Str = Str.substr(1); 433 } 434 435 return false; 436 } 437 438 439 // Implementation of StringRef hashing. 440 hash_code llvm::hash_value(StringRef S) { 441 return hash_combine_range(S.begin(), S.end()); 442 } 443