blob: 4bafc4ec7181920e6df1aa0ed59bec15caa7e3ff [file] [log] [blame]
Daniel Dunbar44981682009-09-16 22:38:48 +00001//===-- StringRef.cpp - Lightweight String References ---------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Daniel Dunbar44981682009-09-16 22:38:48 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/ADT/StringRef.h"
Zachary Turner8bd42a12017-02-14 19:06:37 +000010#include "llvm/ADT/APFloat.h"
John McCall512b6502010-02-28 09:55:58 +000011#include "llvm/ADT/APInt.h"
Chandler Carruthca99ad32012-03-04 10:55:27 +000012#include "llvm/ADT/Hashing.h"
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000013#include "llvm/ADT/StringExtras.h"
Kaelyn Uhrain7a9ccf42012-02-15 22:13:07 +000014#include "llvm/ADT/edit_distance.h"
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +000015#include <bitset>
Douglas Gregor09470e62010-01-07 00:51:54 +000016
Daniel Dunbar44981682009-09-16 22:38:48 +000017using namespace llvm;
18
Daniel Dunbarc827d9e2009-09-22 03:34:40 +000019// MSVC emits references to this into the translation units which reference it.
20#ifndef _MSC_VER
Daniel Dunbar44981682009-09-16 22:38:48 +000021const size_t StringRef::npos;
Daniel Dunbarc827d9e2009-09-22 03:34:40 +000022#endif
Chris Lattner68ee7002009-09-19 19:47:14 +000023
Rui Ueyama00e24e42013-10-30 18:32:26 +000024// strncasecmp() is not available on non-POSIX systems, so define an
25// alternative function here.
26static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) {
27 for (size_t I = 0; I < Length; ++I) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000028 unsigned char LHC = toLower(LHS[I]);
29 unsigned char RHC = toLower(RHS[I]);
Benjamin Kramer68e49452009-11-12 20:36:59 +000030 if (LHC != RHC)
31 return LHC < RHC ? -1 : 1;
32 }
Rui Ueyama00e24e42013-10-30 18:32:26 +000033 return 0;
34}
Benjamin Kramer68e49452009-11-12 20:36:59 +000035
Rui Ueyama00e24e42013-10-30 18:32:26 +000036/// compare_lower - Compare strings, ignoring case.
37int StringRef::compare_lower(StringRef RHS) const {
Craig Topper3ced27c2014-08-21 04:31:10 +000038 if (int Res = ascii_strncasecmp(Data, RHS.Data, std::min(Length, RHS.Length)))
Rui Ueyama00e24e42013-10-30 18:32:26 +000039 return Res;
Benjamin Kramer68e49452009-11-12 20:36:59 +000040 if (Length == RHS.Length)
Benjamin Kramerb04d4af2010-08-26 14:21:08 +000041 return 0;
Benjamin Kramer68e49452009-11-12 20:36:59 +000042 return Length < RHS.Length ? -1 : 1;
43}
44
Rui Ueyama00e24e42013-10-30 18:32:26 +000045/// Check if this string starts with the given \p Prefix, ignoring case.
46bool StringRef::startswith_lower(StringRef Prefix) const {
47 return Length >= Prefix.Length &&
48 ascii_strncasecmp(Data, Prefix.Data, Prefix.Length) == 0;
49}
50
51/// Check if this string ends with the given \p Suffix, ignoring case.
52bool StringRef::endswith_lower(StringRef Suffix) const {
53 return Length >= Suffix.Length &&
54 ascii_strncasecmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
55}
56
Zachary Turner17412b02016-11-12 17:17:12 +000057size_t StringRef::find_lower(char C, size_t From) const {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000058 char L = toLower(C);
59 return find_if([L](char D) { return toLower(D) == L; }, From);
Zachary Turner17412b02016-11-12 17:17:12 +000060}
61
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000062/// compare_numeric - Compare strings, handle embedded numbers.
63int StringRef::compare_numeric(StringRef RHS) const {
Craig Topper3ced27c2014-08-21 04:31:10 +000064 for (size_t I = 0, E = std::min(Length, RHS.Length); I != E; ++I) {
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000065 // Check for sequences of digits.
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000066 if (isDigit(Data[I]) && isDigit(RHS.Data[I])) {
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000067 // The longer sequence of numbers is considered larger.
68 // This doesn't really handle prefixed zeros well.
69 size_t J;
70 for (J = I + 1; J != E + 1; ++J) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +000071 bool ld = J < Length && isDigit(Data[J]);
72 bool rd = J < RHS.Length && isDigit(RHS.Data[J]);
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000073 if (ld != rd)
74 return rd ? -1 : 1;
75 if (!rd)
76 break;
77 }
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000078 // The two number sequences have the same length (J-I), just memcmp them.
79 if (int Res = compareMemory(Data + I, RHS.Data + I, J - I))
80 return Res < 0 ? -1 : 1;
81 // Identical number sequences, continue search after the numbers.
82 I = J - 1;
83 continue;
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000084 }
Jakob Stoklund Olesenc874e2d2011-09-30 17:03:55 +000085 if (Data[I] != RHS.Data[I])
86 return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1;
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000087 }
88 if (Length == RHS.Length)
Benjamin Kramerb04d4af2010-08-26 14:21:08 +000089 return 0;
Jakob Stoklund Olesend1d7ed62010-05-26 21:47:28 +000090 return Length < RHS.Length ? -1 : 1;
91}
92
Douglas Gregor5639af42009-12-31 04:24:34 +000093// Compute the edit distance between the two given strings.
Michael J. Spencerf13f4422010-11-26 04:16:08 +000094unsigned StringRef::edit_distance(llvm::StringRef Other,
Douglas Gregor21afc3b2010-10-19 22:13:48 +000095 bool AllowReplacements,
Dmitri Gribenko292c9202013-08-24 01:50:41 +000096 unsigned MaxEditDistance) const {
Kaelyn Uhrain7a9ccf42012-02-15 22:13:07 +000097 return llvm::ComputeEditDistance(
Craig Toppere1d12942014-08-27 05:25:25 +000098 makeArrayRef(data(), size()),
99 makeArrayRef(Other.data(), Other.size()),
Kaelyn Uhrain7a9ccf42012-02-15 22:13:07 +0000100 AllowReplacements, MaxEditDistance);
Douglas Gregor165882c2009-12-30 17:23:44 +0000101}
102
Chris Lattner372a8ae2009-09-20 01:22:16 +0000103//===----------------------------------------------------------------------===//
Daniel Dunbar3fa528d2011-11-06 18:04:43 +0000104// String Operations
105//===----------------------------------------------------------------------===//
106
107std::string StringRef::lower() const {
108 std::string Result(size(), char());
109 for (size_type i = 0, e = size(); i != e; ++i) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000110 Result[i] = toLower(Data[i]);
Daniel Dunbar3fa528d2011-11-06 18:04:43 +0000111 }
112 return Result;
113}
114
115std::string StringRef::upper() const {
116 std::string Result(size(), char());
117 for (size_type i = 0, e = size(); i != e; ++i) {
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000118 Result[i] = toUpper(Data[i]);
Daniel Dunbar3fa528d2011-11-06 18:04:43 +0000119 }
120 return Result;
121}
122
123//===----------------------------------------------------------------------===//
Chris Lattner372a8ae2009-09-20 01:22:16 +0000124// String Searching
125//===----------------------------------------------------------------------===//
126
127
128/// find - Search for the first string \arg Str in the string.
129///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000130/// \return - The index of the first occurrence of \arg Str, or npos if not
Chris Lattner372a8ae2009-09-20 01:22:16 +0000131/// found.
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000132size_t StringRef::find(StringRef Str, size_t From) const {
Chandler Carruth233edd22015-09-10 11:17:49 +0000133 if (From > Length)
Chris Lattner372a8ae2009-09-20 01:22:16 +0000134 return npos;
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000135
Chandler Carruthecbe6192016-12-11 07:46:21 +0000136 const char *Start = Data + From;
137 size_t Size = Length - From;
138
Chandler Carruth233edd22015-09-10 11:17:49 +0000139 const char *Needle = Str.data();
140 size_t N = Str.size();
141 if (N == 0)
142 return From;
Chandler Carruth233edd22015-09-10 11:17:49 +0000143 if (Size < N)
144 return npos;
Chandler Carruthecbe6192016-12-11 07:46:21 +0000145 if (N == 1) {
146 const char *Ptr = (const char *)::memchr(Start, Needle[0], Size);
147 return Ptr == nullptr ? npos : Ptr - Data;
148 }
Chandler Carruth233edd22015-09-10 11:17:49 +0000149
Chandler Carruth233edd22015-09-10 11:17:49 +0000150 const char *Stop = Start + (Size - N + 1);
151
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000152 // For short haystacks or unsupported needles fall back to the naive algorithm
Chandler Carruth233edd22015-09-10 11:17:49 +0000153 if (Size < 16 || N > 255) {
154 do {
155 if (std::memcmp(Start, Needle, N) == 0)
156 return Start - Data;
157 ++Start;
158 } while (Start < Stop);
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000159 return npos;
160 }
161
162 // Build the bad char heuristic table, with uint8_t to reduce cache thrashing.
163 uint8_t BadCharSkip[256];
164 std::memset(BadCharSkip, N, 256);
165 for (unsigned i = 0; i != N-1; ++i)
166 BadCharSkip[(uint8_t)Str[i]] = N-1-i;
167
Chandler Carruth233edd22015-09-10 11:17:49 +0000168 do {
Chandler Carruthecbe6192016-12-11 07:46:21 +0000169 uint8_t Last = Start[N - 1];
170 if (LLVM_UNLIKELY(Last == (uint8_t)Needle[N - 1]))
171 if (std::memcmp(Start, Needle, N - 1) == 0)
172 return Start - Data;
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000173
174 // Otherwise skip the appropriate number of bytes.
Chandler Carruthecbe6192016-12-11 07:46:21 +0000175 Start += BadCharSkip[Last];
Chandler Carruth233edd22015-09-10 11:17:49 +0000176 } while (Start < Stop);
Benjamin Kramer4d681d72011-10-15 10:08:31 +0000177
Chris Lattner372a8ae2009-09-20 01:22:16 +0000178 return npos;
179}
180
Zachary Turner17412b02016-11-12 17:17:12 +0000181size_t StringRef::find_lower(StringRef Str, size_t From) const {
182 StringRef This = substr(From);
183 while (This.size() >= Str.size()) {
184 if (This.startswith_lower(Str))
185 return From;
186 This = This.drop_front();
187 ++From;
188 }
189 return npos;
190}
191
192size_t StringRef::rfind_lower(char C, size_t From) const {
193 From = std::min(From, Length);
194 size_t i = From;
195 while (i != 0) {
196 --i;
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000197 if (toLower(Data[i]) == toLower(C))
Zachary Turner17412b02016-11-12 17:17:12 +0000198 return i;
199 }
200 return npos;
201}
202
Chris Lattner372a8ae2009-09-20 01:22:16 +0000203/// rfind - Search for the last string \arg Str in the string.
204///
Chris Lattner0ab5e2c2011-04-15 05:18:47 +0000205/// \return - The index of the last occurrence of \arg Str, or npos if not
Chris Lattner372a8ae2009-09-20 01:22:16 +0000206/// found.
Daniel Dunbarad36e8a2009-11-06 10:58:06 +0000207size_t StringRef::rfind(StringRef Str) const {
Chris Lattner372a8ae2009-09-20 01:22:16 +0000208 size_t N = Str.size();
209 if (N > Length)
210 return npos;
211 for (size_t i = Length - N + 1, e = 0; i != e;) {
212 --i;
213 if (substr(i, N).equals(Str))
214 return i;
215 }
216 return npos;
217}
218
Zachary Turner17412b02016-11-12 17:17:12 +0000219size_t StringRef::rfind_lower(StringRef Str) const {
220 size_t N = Str.size();
221 if (N > Length)
222 return npos;
223 for (size_t i = Length - N + 1, e = 0; i != e;) {
224 --i;
225 if (substr(i, N).equals_lower(Str))
226 return i;
227 }
228 return npos;
229}
230
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000231/// find_first_of - Find the first character in the string that is in \arg
232/// Chars, or npos if not found.
233///
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000234/// Note: O(size() + Chars.size())
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000235StringRef::size_type StringRef::find_first_of(StringRef Chars,
236 size_t From) const {
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000237 std::bitset<1 << CHAR_BIT> CharBits;
238 for (size_type i = 0; i != Chars.size(); ++i)
239 CharBits.set((unsigned char)Chars[i]);
240
Craig Topper3ced27c2014-08-21 04:31:10 +0000241 for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000242 if (CharBits.test((unsigned char)Data[i]))
Chris Lattner372a8ae2009-09-20 01:22:16 +0000243 return i;
244 return npos;
245}
246
247/// find_first_not_of - Find the first character in the string that is not
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000248/// \arg C or npos if not found.
249StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const {
Craig Topper3ced27c2014-08-21 04:31:10 +0000250 for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000251 if (Data[i] != C)
252 return i;
253 return npos;
254}
255
256/// find_first_not_of - Find the first character in the string that is not
257/// in the string \arg Chars, or npos if not found.
258///
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000259/// Note: O(size() + Chars.size())
Daniel Dunbar9806e4a2009-11-11 00:28:53 +0000260StringRef::size_type StringRef::find_first_not_of(StringRef Chars,
261 size_t From) const {
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000262 std::bitset<1 << CHAR_BIT> CharBits;
263 for (size_type i = 0; i != Chars.size(); ++i)
264 CharBits.set((unsigned char)Chars[i]);
265
Craig Topper3ced27c2014-08-21 04:31:10 +0000266 for (size_type i = std::min(From, Length), e = Length; i != e; ++i)
Benjamin Kramer08fd2cf2010-08-23 18:16:08 +0000267 if (!CharBits.test((unsigned char)Data[i]))
Chris Lattner372a8ae2009-09-20 01:22:16 +0000268 return i;
269 return npos;
270}
271
Michael J. Spencere1d3603d2010-11-30 23:27:35 +0000272/// find_last_of - Find the last character in the string that is in \arg C,
273/// or npos if not found.
274///
275/// Note: O(size() + Chars.size())
276StringRef::size_type StringRef::find_last_of(StringRef Chars,
277 size_t From) const {
278 std::bitset<1 << CHAR_BIT> CharBits;
279 for (size_type i = 0; i != Chars.size(); ++i)
280 CharBits.set((unsigned char)Chars[i]);
281
Craig Topper3ced27c2014-08-21 04:31:10 +0000282 for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
Michael J. Spencere1d3603d2010-11-30 23:27:35 +0000283 if (CharBits.test((unsigned char)Data[i]))
284 return i;
285 return npos;
286}
Chris Lattner372a8ae2009-09-20 01:22:16 +0000287
Michael J. Spencer93303812012-05-11 22:08:50 +0000288/// find_last_not_of - Find the last character in the string that is not
289/// \arg C, or npos if not found.
290StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const {
Craig Topper3ced27c2014-08-21 04:31:10 +0000291 for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
Michael J. Spencer93303812012-05-11 22:08:50 +0000292 if (Data[i] != C)
293 return i;
294 return npos;
295}
296
297/// find_last_not_of - Find the last character in the string that is not in
298/// \arg Chars, or npos if not found.
299///
300/// Note: O(size() + Chars.size())
301StringRef::size_type StringRef::find_last_not_of(StringRef Chars,
302 size_t From) const {
303 std::bitset<1 << CHAR_BIT> CharBits;
304 for (size_type i = 0, e = Chars.size(); i != e; ++i)
305 CharBits.set((unsigned char)Chars[i]);
306
Craig Topper3ced27c2014-08-21 04:31:10 +0000307 for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i)
Michael J. Spencer93303812012-05-11 22:08:50 +0000308 if (!CharBits.test((unsigned char)Data[i]))
309 return i;
310 return npos;
311}
312
Duncan Sands8570b292012-02-21 12:00:25 +0000313void StringRef::split(SmallVectorImpl<StringRef> &A,
Chandler Carruth4425c912015-09-10 07:51:37 +0000314 StringRef Separator, int MaxSplit,
Duncan Sands8570b292012-02-21 12:00:25 +0000315 bool KeepEmpty) const {
Chandler Carruth4425c912015-09-10 07:51:37 +0000316 StringRef S = *this;
Duncan Sands8570b292012-02-21 12:00:25 +0000317
Chandler Carruth4425c912015-09-10 07:51:37 +0000318 // Count down from MaxSplit. When MaxSplit is -1, this will just split
319 // "forever". This doesn't support splitting more than 2^31 times
320 // intentionally; if we ever want that we can make MaxSplit a 64-bit integer
321 // but that seems unlikely to be useful.
322 while (MaxSplit-- != 0) {
323 size_t Idx = S.find(Separator);
324 if (Idx == npos)
325 break;
Duncan Sands8570b292012-02-21 12:00:25 +0000326
Chandler Carruth4425c912015-09-10 07:51:37 +0000327 // Push this split.
328 if (KeepEmpty || Idx > 0)
329 A.push_back(S.slice(0, Idx));
330
331 // Jump forward.
332 S = S.slice(Idx + Separator.size(), npos);
Duncan Sands8570b292012-02-21 12:00:25 +0000333 }
Chandler Carruth4425c912015-09-10 07:51:37 +0000334
335 // Push the tail.
336 if (KeepEmpty || !S.empty())
337 A.push_back(S);
Duncan Sands8570b292012-02-21 12:00:25 +0000338}
339
Chandler Carruth47712172015-09-10 06:07:03 +0000340void StringRef::split(SmallVectorImpl<StringRef> &A, char Separator,
341 int MaxSplit, bool KeepEmpty) const {
Chandler Carruth4425c912015-09-10 07:51:37 +0000342 StringRef S = *this;
Chandler Carruth47712172015-09-10 06:07:03 +0000343
Chandler Carruth4425c912015-09-10 07:51:37 +0000344 // Count down from MaxSplit. When MaxSplit is -1, this will just split
345 // "forever". This doesn't support splitting more than 2^31 times
346 // intentionally; if we ever want that we can make MaxSplit a 64-bit integer
347 // but that seems unlikely to be useful.
348 while (MaxSplit-- != 0) {
349 size_t Idx = S.find(Separator);
350 if (Idx == npos)
351 break;
Chandler Carruth47712172015-09-10 06:07:03 +0000352
Chandler Carruth4425c912015-09-10 07:51:37 +0000353 // Push this split.
354 if (KeepEmpty || Idx > 0)
355 A.push_back(S.slice(0, Idx));
356
357 // Jump forward.
358 S = S.slice(Idx + 1, npos);
Chandler Carruth47712172015-09-10 06:07:03 +0000359 }
Chandler Carruth4425c912015-09-10 07:51:37 +0000360
361 // Push the tail.
362 if (KeepEmpty || !S.empty())
363 A.push_back(S);
Chandler Carruth47712172015-09-10 06:07:03 +0000364}
365
Chris Lattner372a8ae2009-09-20 01:22:16 +0000366//===----------------------------------------------------------------------===//
367// Helpful Algorithms
368//===----------------------------------------------------------------------===//
369
370/// count - Return the number of non-overlapped occurrences of \arg Str in
371/// the string.
Daniel Dunbarad36e8a2009-11-06 10:58:06 +0000372size_t StringRef::count(StringRef Str) const {
Chris Lattner372a8ae2009-09-20 01:22:16 +0000373 size_t Count = 0;
374 size_t N = Str.size();
375 if (N > Length)
376 return 0;
377 for (size_t i = 0, e = Length - N + 1; i != e; ++i)
378 if (substr(i, N).equals(Str))
379 ++Count;
380 return Count;
381}
382
John McCall512b6502010-02-28 09:55:58 +0000383static unsigned GetAutoSenseRadix(StringRef &Str) {
Zachary Turnerd5d57632016-09-22 15:55:05 +0000384 if (Str.empty())
385 return 10;
386
Colin LeMahieu01431462016-03-18 18:22:07 +0000387 if (Str.startswith("0x") || Str.startswith("0X")) {
John McCall512b6502010-02-28 09:55:58 +0000388 Str = Str.substr(2);
389 return 16;
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000390 }
Fangrui Songf78650a2018-07-30 19:41:25 +0000391
Colin LeMahieu01431462016-03-18 18:22:07 +0000392 if (Str.startswith("0b") || Str.startswith("0B")) {
John McCall512b6502010-02-28 09:55:58 +0000393 Str = Str.substr(2);
394 return 2;
John McCall512b6502010-02-28 09:55:58 +0000395 }
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000396
397 if (Str.startswith("0o")) {
398 Str = Str.substr(2);
399 return 8;
400 }
401
Francis Visoiu Mistrih26d6fc12017-11-28 14:22:27 +0000402 if (Str[0] == '0' && Str.size() > 1 && isDigit(Str[1])) {
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000403 Str = Str.substr(1);
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000404 return 8;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000405 }
406
Chris Lattner0a1bafe2012-04-21 22:03:05 +0000407 return 10;
John McCall512b6502010-02-28 09:55:58 +0000408}
409
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000410bool llvm::consumeUnsignedInteger(StringRef &Str, unsigned Radix,
411 unsigned long long &Result) {
Chris Lattner68ee7002009-09-19 19:47:14 +0000412 // Autosense radix if not specified.
John McCall512b6502010-02-28 09:55:58 +0000413 if (Radix == 0)
414 Radix = GetAutoSenseRadix(Str);
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000415
Chris Lattner68ee7002009-09-19 19:47:14 +0000416 // Empty strings (after the radix autosense) are invalid.
417 if (Str.empty()) return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000418
Chris Lattner68ee7002009-09-19 19:47:14 +0000419 // Parse all the bytes of the string given this radix. Watch for overflow.
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000420 StringRef Str2 = Str;
Chris Lattner68ee7002009-09-19 19:47:14 +0000421 Result = 0;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000422 while (!Str2.empty()) {
Chris Lattner68ee7002009-09-19 19:47:14 +0000423 unsigned CharVal;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000424 if (Str2[0] >= '0' && Str2[0] <= '9')
425 CharVal = Str2[0] - '0';
426 else if (Str2[0] >= 'a' && Str2[0] <= 'z')
427 CharVal = Str2[0] - 'a' + 10;
428 else if (Str2[0] >= 'A' && Str2[0] <= 'Z')
429 CharVal = Str2[0] - 'A' + 10;
Chris Lattner68ee7002009-09-19 19:47:14 +0000430 else
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000431 break;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000432
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000433 // If the parsed value is larger than the integer radix, we cannot
434 // consume any more characters.
Chris Lattner68ee7002009-09-19 19:47:14 +0000435 if (CharVal >= Radix)
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000436 break;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000437
Chris Lattner68ee7002009-09-19 19:47:14 +0000438 // Add in this character.
439 unsigned long long PrevResult = Result;
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000440 Result = Result * Radix + CharVal;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000441
Nick Kledzik35c79da2012-10-02 20:01:48 +0000442 // Check for overflow by shifting back and seeing if bits were lost.
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000443 if (Result / Radix < PrevResult)
Chris Lattner68ee7002009-09-19 19:47:14 +0000444 return true;
445
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000446 Str2 = Str2.substr(1);
Chris Lattner68ee7002009-09-19 19:47:14 +0000447 }
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000448
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000449 // We consider the operation a failure if no characters were consumed
450 // successfully.
451 if (Str.size() == Str2.size())
452 return true;
453
454 Str = Str2;
Chris Lattner68ee7002009-09-19 19:47:14 +0000455 return false;
456}
457
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000458bool llvm::consumeSignedInteger(StringRef &Str, unsigned Radix,
459 long long &Result) {
Chris Lattner84c15272009-09-19 23:58:48 +0000460 unsigned long long ULLVal;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000461
Chris Lattner84c15272009-09-19 23:58:48 +0000462 // Handle positive strings first.
Michael J. Spencercfa95f62012-03-10 23:02:54 +0000463 if (Str.empty() || Str.front() != '-') {
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000464 if (consumeUnsignedInteger(Str, Radix, ULLVal) ||
Chris Lattner84c15272009-09-19 23:58:48 +0000465 // Check for value so large it overflows a signed value.
466 (long long)ULLVal < 0)
467 return true;
468 Result = ULLVal;
469 return false;
470 }
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000471
Chris Lattner84c15272009-09-19 23:58:48 +0000472 // Get the positive part of the value.
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000473 StringRef Str2 = Str.drop_front(1);
474 if (consumeUnsignedInteger(Str2, Radix, ULLVal) ||
Chris Lattner84c15272009-09-19 23:58:48 +0000475 // Reject values so large they'd overflow as negative signed, but allow
476 // "-0". This negates the unsigned so that the negative isn't undefined
477 // on signed overflow.
478 (long long)-ULLVal > 0)
479 return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000480
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000481 Str = Str2;
Chris Lattner84c15272009-09-19 23:58:48 +0000482 Result = -ULLVal;
483 return false;
484}
485
Zachary Turner65fd2fc2016-09-22 15:05:19 +0000486/// GetAsUnsignedInteger - Workhorse method that converts a integer character
487/// sequence of radix up to 36 to an unsigned long long value.
488bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix,
489 unsigned long long &Result) {
490 if (consumeUnsignedInteger(Str, Radix, Result))
491 return true;
492
493 // For getAsUnsignedInteger, we require the whole string to be consumed or
494 // else we consider it a failure.
495 return !Str.empty();
496}
497
498bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix,
499 long long &Result) {
500 if (consumeSignedInteger(Str, Radix, Result))
501 return true;
502
503 // For getAsSignedInteger, we require the whole string to be consumed or else
504 // we consider it a failure.
505 return !Str.empty();
506}
507
John McCall512b6502010-02-28 09:55:58 +0000508bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const {
509 StringRef Str = *this;
510
511 // Autosense radix if not specified.
512 if (Radix == 0)
513 Radix = GetAutoSenseRadix(Str);
514
515 assert(Radix > 1 && Radix <= 36);
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000516
John McCall512b6502010-02-28 09:55:58 +0000517 // Empty strings (after the radix autosense) are invalid.
518 if (Str.empty()) return true;
519
520 // Skip leading zeroes. This can be a significant improvement if
521 // it means we don't need > 64 bits.
522 while (!Str.empty() && Str.front() == '0')
523 Str = Str.substr(1);
524
525 // If it was nothing but zeroes....
526 if (Str.empty()) {
527 Result = APInt(64, 0);
528 return false;
529 }
530
531 // (Over-)estimate the required number of bits.
532 unsigned Log2Radix = 0;
533 while ((1U << Log2Radix) < Radix) Log2Radix++;
534 bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix);
535
536 unsigned BitWidth = Log2Radix * Str.size();
537 if (BitWidth < Result.getBitWidth())
538 BitWidth = Result.getBitWidth(); // don't shrink the result
Chris Lattner5e146662012-04-23 00:27:54 +0000539 else if (BitWidth > Result.getBitWidth())
Jay Foad583abbc2010-12-07 08:25:19 +0000540 Result = Result.zext(BitWidth);
John McCall512b6502010-02-28 09:55:58 +0000541
542 APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix
543 if (!IsPowerOf2Radix) {
544 // These must have the same bit-width as Result.
545 RadixAP = APInt(BitWidth, Radix);
546 CharAP = APInt(BitWidth, 0);
547 }
548
549 // Parse all the bytes of the string given this radix.
550 Result = 0;
551 while (!Str.empty()) {
552 unsigned CharVal;
553 if (Str[0] >= '0' && Str[0] <= '9')
554 CharVal = Str[0]-'0';
555 else if (Str[0] >= 'a' && Str[0] <= 'z')
556 CharVal = Str[0]-'a'+10;
557 else if (Str[0] >= 'A' && Str[0] <= 'Z')
558 CharVal = Str[0]-'A'+10;
559 else
560 return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000561
John McCall512b6502010-02-28 09:55:58 +0000562 // If the parsed value is larger than the integer radix, the string is
563 // invalid.
564 if (CharVal >= Radix)
565 return true;
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000566
John McCall512b6502010-02-28 09:55:58 +0000567 // Add in this character.
568 if (IsPowerOf2Radix) {
569 Result <<= Log2Radix;
570 Result |= CharVal;
571 } else {
572 Result *= RadixAP;
573 CharAP = CharVal;
574 Result += CharAP;
575 }
576
577 Str = Str.substr(1);
578 }
Michael J. Spencerf13f4422010-11-26 04:16:08 +0000579
John McCall512b6502010-02-28 09:55:58 +0000580 return false;
581}
Chandler Carruthca99ad32012-03-04 10:55:27 +0000582
Zachary Turner8bd42a12017-02-14 19:06:37 +0000583bool StringRef::getAsDouble(double &Result, bool AllowInexact) const {
584 APFloat F(0.0);
585 APFloat::opStatus Status =
586 F.convertFromString(*this, APFloat::rmNearestTiesToEven);
587 if (Status != APFloat::opOK) {
Serguei Katkov768d6dd2017-12-19 04:27:39 +0000588 if (!AllowInexact || !(Status & APFloat::opInexact))
Zachary Turner8bd42a12017-02-14 19:06:37 +0000589 return true;
590 }
591
592 Result = F.convertToDouble();
593 return false;
594}
Chandler Carruthca99ad32012-03-04 10:55:27 +0000595
596// Implementation of StringRef hashing.
597hash_code llvm::hash_value(StringRef S) {
598 return hash_combine_range(S.begin(), S.end());
599}