Solve Visual C++ warning C4805 on getAsInteger<bool>.
[oota-llvm.git] / include / llvm / ADT / StringRef.h
1 //===--- StringRef.h - Constant String Reference Wrapper --------*- C++ -*-===//
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 #ifndef LLVM_ADT_STRINGREF_H
11 #define LLVM_ADT_STRINGREF_H
12
13 #include <algorithm>
14 #include <cassert>
15 #include <cstring>
16 #include <limits>
17 #include <string>
18 #include <utility>
19
20 namespace llvm {
21   template <typename T>
22   class SmallVectorImpl;
23   class APInt;
24   class hash_code;
25   class StringRef;
26
27   /// Helper functions for StringRef::getAsInteger.
28   bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
29                             unsigned long long &Result);
30
31   bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
32
33   /// StringRef - Represent a constant reference to a string, i.e. a character
34   /// array and a length, which need not be null terminated.
35   ///
36   /// This class does not own the string data, it is expected to be used in
37   /// situations where the character data resides in some other buffer, whose
38   /// lifetime extends past that of the StringRef. For this reason, it is not in
39   /// general safe to store a StringRef.
40   class StringRef {
41   public:
42     typedef const char *iterator;
43     typedef const char *const_iterator;
44     static const size_t npos = ~size_t(0);
45     typedef size_t size_type;
46
47   private:
48     /// The start of the string, in an external buffer.
49     const char *Data;
50
51     /// The length of the string.
52     size_t Length;
53
54     // Workaround memcmp issue with null pointers (undefined behavior)
55     // by providing a specialized version
56     static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
57       if (Length == 0) { return 0; }
58       return ::memcmp(Lhs,Rhs,Length);
59     }
60
61   public:
62     /// @name Constructors
63     /// @{
64
65     /// Construct an empty string ref.
66     /*implicit*/ StringRef() : Data(nullptr), Length(0) {}
67
68     /// Construct a string ref from a cstring.
69     /*implicit*/ StringRef(const char *Str)
70       : Data(Str) {
71         assert(Str && "StringRef cannot be built from a NULL argument");
72         Length = ::strlen(Str); // invoking strlen(NULL) is undefined behavior
73       }
74
75     /// Construct a string ref from a pointer and length.
76     /*implicit*/ StringRef(const char *data, size_t length)
77       : Data(data), Length(length) {
78         assert((data || length == 0) &&
79         "StringRef cannot be built from a NULL argument with non-null length");
80       }
81
82     /// Construct a string ref from an std::string.
83     /*implicit*/ StringRef(const std::string &Str)
84       : Data(Str.data()), Length(Str.length()) {}
85
86     /// @}
87     /// @name Iterators
88     /// @{
89
90     iterator begin() const { return Data; }
91
92     iterator end() const { return Data + Length; }
93
94     /// @}
95     /// @name String Operations
96     /// @{
97
98     /// data - Get a pointer to the start of the string (which may not be null
99     /// terminated).
100     const char *data() const { return Data; }
101
102     /// empty - Check if the string is empty.
103     bool empty() const { return Length == 0; }
104
105     /// size - Get the string size.
106     size_t size() const { return Length; }
107
108     /// front - Get the first character in the string.
109     char front() const {
110       assert(!empty());
111       return Data[0];
112     }
113
114     /// back - Get the last character in the string.
115     char back() const {
116       assert(!empty());
117       return Data[Length-1];
118     }
119
120     // copy - Allocate copy in Allocator and return StringRef to it.
121     template <typename Allocator> StringRef copy(Allocator &A) const {
122       char *S = A.template Allocate<char>(Length);
123       std::copy(begin(), end(), S);
124       return StringRef(S, Length);
125     }
126
127     /// equals - Check for string equality, this is more efficient than
128     /// compare() when the relative ordering of inequal strings isn't needed.
129     bool equals(StringRef RHS) const {
130       return (Length == RHS.Length &&
131               compareMemory(Data, RHS.Data, RHS.Length) == 0);
132     }
133
134     /// equals_lower - Check for string equality, ignoring case.
135     bool equals_lower(StringRef RHS) const {
136       return Length == RHS.Length && compare_lower(RHS) == 0;
137     }
138
139     /// compare - Compare two strings; the result is -1, 0, or 1 if this string
140     /// is lexicographically less than, equal to, or greater than the \p RHS.
141     int compare(StringRef RHS) const {
142       // Check the prefix for a mismatch.
143       if (int Res = compareMemory(Data, RHS.Data, std::min(Length, RHS.Length)))
144         return Res < 0 ? -1 : 1;
145
146       // Otherwise the prefixes match, so we only need to check the lengths.
147       if (Length == RHS.Length)
148         return 0;
149       return Length < RHS.Length ? -1 : 1;
150     }
151
152     /// compare_lower - Compare two strings, ignoring case.
153     int compare_lower(StringRef RHS) const;
154
155     /// compare_numeric - Compare two strings, treating sequences of digits as
156     /// numbers.
157     int compare_numeric(StringRef RHS) const;
158
159     /// \brief Determine the edit distance between this string and another
160     /// string.
161     ///
162     /// \param Other the string to compare this string against.
163     ///
164     /// \param AllowReplacements whether to allow character
165     /// replacements (change one character into another) as a single
166     /// operation, rather than as two operations (an insertion and a
167     /// removal).
168     ///
169     /// \param MaxEditDistance If non-zero, the maximum edit distance that
170     /// this routine is allowed to compute. If the edit distance will exceed
171     /// that maximum, returns \c MaxEditDistance+1.
172     ///
173     /// \returns the minimum number of character insertions, removals,
174     /// or (if \p AllowReplacements is \c true) replacements needed to
175     /// transform one of the given strings into the other. If zero,
176     /// the strings are identical.
177     unsigned edit_distance(StringRef Other, bool AllowReplacements = true,
178                            unsigned MaxEditDistance = 0) const;
179
180     /// str - Get the contents as an std::string.
181     std::string str() const {
182       if (!Data) return std::string();
183       return std::string(Data, Length);
184     }
185
186     /// @}
187     /// @name Operator Overloads
188     /// @{
189
190     char operator[](size_t Index) const {
191       assert(Index < Length && "Invalid index!");
192       return Data[Index];
193     }
194
195     /// @}
196     /// @name Type Conversions
197     /// @{
198
199     operator std::string() const {
200       return str();
201     }
202
203     /// @}
204     /// @name String Predicates
205     /// @{
206
207     /// Check if this string starts with the given \p Prefix.
208     bool startswith(StringRef Prefix) const {
209       return Length >= Prefix.Length &&
210              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
211     }
212
213     /// Check if this string starts with the given \p Prefix, ignoring case.
214     bool startswith_lower(StringRef Prefix) const;
215
216     /// Check if this string ends with the given \p Suffix.
217     bool endswith(StringRef Suffix) const {
218       return Length >= Suffix.Length &&
219         compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0;
220     }
221
222     /// Check if this string ends with the given \p Suffix, ignoring case.
223     bool endswith_lower(StringRef Suffix) const;
224
225     /// @}
226     /// @name String Searching
227     /// @{
228
229     /// Search for the first character \p C in the string.
230     ///
231     /// \returns The index of the first occurrence of \p C, or npos if not
232     /// found.
233     size_t find(char C, size_t From = 0) const {
234       for (size_t i = std::min(From, Length), e = Length; i != e; ++i)
235         if (Data[i] == C)
236           return i;
237       return npos;
238     }
239
240     /// Search for the first string \p Str in the string.
241     ///
242     /// \returns The index of the first occurrence of \p Str, or npos if not
243     /// found.
244     size_t find(StringRef Str, size_t From = 0) const;
245
246     /// Search for the last character \p C in the string.
247     ///
248     /// \returns The index of the last occurrence of \p C, or npos if not
249     /// found.
250     size_t rfind(char C, size_t From = npos) const {
251       From = std::min(From, Length);
252       size_t i = From;
253       while (i != 0) {
254         --i;
255         if (Data[i] == C)
256           return i;
257       }
258       return npos;
259     }
260
261     /// Search for the last string \p Str in the string.
262     ///
263     /// \returns The index of the last occurrence of \p Str, or npos if not
264     /// found.
265     size_t rfind(StringRef Str) const;
266
267     /// Find the first character in the string that is \p C, or npos if not
268     /// found. Same as find.
269     size_t find_first_of(char C, size_t From = 0) const {
270       return find(C, From);
271     }
272
273     /// Find the first character in the string that is in \p Chars, or npos if
274     /// not found.
275     ///
276     /// Complexity: O(size() + Chars.size())
277     size_t find_first_of(StringRef Chars, size_t From = 0) const;
278
279     /// Find the first character in the string that is not \p C or npos if not
280     /// found.
281     size_t find_first_not_of(char C, size_t From = 0) const;
282
283     /// Find the first character in the string that is not in the string
284     /// \p Chars, or npos if not found.
285     ///
286     /// Complexity: O(size() + Chars.size())
287     size_t find_first_not_of(StringRef Chars, size_t From = 0) const;
288
289     /// Find the last character in the string that is \p C, or npos if not
290     /// found.
291     size_t find_last_of(char C, size_t From = npos) const {
292       return rfind(C, From);
293     }
294
295     /// Find the last character in the string that is in \p C, or npos if not
296     /// found.
297     ///
298     /// Complexity: O(size() + Chars.size())
299     size_t find_last_of(StringRef Chars, size_t From = npos) const;
300
301     /// Find the last character in the string that is not \p C, or npos if not
302     /// found.
303     size_t find_last_not_of(char C, size_t From = npos) const;
304
305     /// Find the last character in the string that is not in \p Chars, or
306     /// npos if not found.
307     ///
308     /// Complexity: O(size() + Chars.size())
309     size_t find_last_not_of(StringRef Chars, size_t From = npos) const;
310
311     /// @}
312     /// @name Helpful Algorithms
313     /// @{
314
315     /// Return the number of occurrences of \p C in the string.
316     size_t count(char C) const {
317       size_t Count = 0;
318       for (size_t i = 0, e = Length; i != e; ++i)
319         if (Data[i] == C)
320           ++Count;
321       return Count;
322     }
323
324     /// Return the number of non-overlapped occurrences of \p Str in
325     /// the string.
326     size_t count(StringRef Str) const;
327
328     /// Parse the current string as an integer of the specified radix.  If
329     /// \p Radix is specified as zero, this does radix autosensing using
330     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
331     ///
332     /// If the string is invalid or if only a subset of the string is valid,
333     /// this returns true to signify the error.  The string is considered
334     /// erroneous if empty or if it overflows T.
335     template <typename T>
336     typename std::enable_if<std::numeric_limits<T>::is_signed, bool>::type
337     getAsInteger(unsigned Radix, T &Result) const {
338       long long LLVal;
339       if (getAsSignedInteger(*this, Radix, LLVal) ||
340             static_cast<T>(LLVal) != LLVal)
341         return true;
342       Result = LLVal;
343       return false;
344     }
345
346     template <typename T>
347     typename std::enable_if<!std::numeric_limits<T>::is_signed, bool>::type
348     getAsInteger(unsigned Radix, T &Result) const {
349       unsigned long long ULLVal;
350       // The additional cast to unsigned long long is required to avoid the
351       // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
352       // 'unsigned __int64' when instantiating getAsInteger with T = bool.
353       if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
354           static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
355         return true;
356       Result = ULLVal;
357       return false;
358     }
359
360     /// Parse the current string as an integer of the specified \p Radix, or of
361     /// an autosensed radix if the \p Radix given is 0.  The current value in
362     /// \p Result is discarded, and the storage is changed to be wide enough to
363     /// store the parsed integer.
364     ///
365     /// \returns true if the string does not solely consist of a valid
366     /// non-empty number in the appropriate base.
367     ///
368     /// APInt::fromString is superficially similar but assumes the
369     /// string is well-formed in the given radix.
370     bool getAsInteger(unsigned Radix, APInt &Result) const;
371
372     /// @}
373     /// @name String Operations
374     /// @{
375
376     // Convert the given ASCII string to lowercase.
377     std::string lower() const;
378
379     /// Convert the given ASCII string to uppercase.
380     std::string upper() const;
381
382     /// @}
383     /// @name Substring Operations
384     /// @{
385
386     /// Return a reference to the substring from [Start, Start + N).
387     ///
388     /// \param Start The index of the starting character in the substring; if
389     /// the index is npos or greater than the length of the string then the
390     /// empty substring will be returned.
391     ///
392     /// \param N The number of characters to included in the substring. If N
393     /// exceeds the number of characters remaining in the string, the string
394     /// suffix (starting with \p Start) will be returned.
395     StringRef substr(size_t Start, size_t N = npos) const {
396       Start = std::min(Start, Length);
397       return StringRef(Data + Start, std::min(N, Length - Start));
398     }
399
400     /// Return a StringRef equal to 'this' but with the first \p N elements
401     /// dropped.
402     StringRef drop_front(size_t N = 1) const {
403       assert(size() >= N && "Dropping more elements than exist");
404       return substr(N);
405     }
406
407     /// Return a StringRef equal to 'this' but with the last \p N elements
408     /// dropped.
409     StringRef drop_back(size_t N = 1) const {
410       assert(size() >= N && "Dropping more elements than exist");
411       return substr(0, size()-N);
412     }
413
414     /// Return a reference to the substring from [Start, End).
415     ///
416     /// \param Start The index of the starting character in the substring; if
417     /// the index is npos or greater than the length of the string then the
418     /// empty substring will be returned.
419     ///
420     /// \param End The index following the last character to include in the
421     /// substring. If this is npos, or less than \p Start, or exceeds the
422     /// number of characters remaining in the string, the string suffix
423     /// (starting with \p Start) will be returned.
424     StringRef slice(size_t Start, size_t End) const {
425       Start = std::min(Start, Length);
426       End = std::min(std::max(Start, End), Length);
427       return StringRef(Data + Start, End - Start);
428     }
429
430     /// Split into two substrings around the first occurrence of a separator
431     /// character.
432     ///
433     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
434     /// such that (*this == LHS + Separator + RHS) is true and RHS is
435     /// maximal. If \p Separator is not in the string, then the result is a
436     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
437     ///
438     /// \param Separator The character to split on.
439     /// \returns The split substrings.
440     std::pair<StringRef, StringRef> split(char Separator) const {
441       size_t Idx = find(Separator);
442       if (Idx == npos)
443         return std::make_pair(*this, StringRef());
444       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
445     }
446
447     /// Split into two substrings around the first occurrence of a separator
448     /// string.
449     ///
450     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
451     /// such that (*this == LHS + Separator + RHS) is true and RHS is
452     /// maximal. If \p Separator is not in the string, then the result is a
453     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
454     ///
455     /// \param Separator - The string to split on.
456     /// \return - The split substrings.
457     std::pair<StringRef, StringRef> split(StringRef Separator) const {
458       size_t Idx = find(Separator);
459       if (Idx == npos)
460         return std::make_pair(*this, StringRef());
461       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
462     }
463
464     /// Split into substrings around the occurrences of a separator string.
465     ///
466     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
467     /// \p MaxSplit splits are done and consequently <= \p MaxSplit
468     /// elements are added to A.
469     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
470     /// still count when considering \p MaxSplit
471     /// An useful invariant is that
472     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
473     ///
474     /// \param A - Where to put the substrings.
475     /// \param Separator - The string to split on.
476     /// \param MaxSplit - The maximum number of times the string is split.
477     /// \param KeepEmpty - True if empty substring should be added.
478     void split(SmallVectorImpl<StringRef> &A,
479                StringRef Separator, int MaxSplit = -1,
480                bool KeepEmpty = true) const;
481
482     /// Split into two substrings around the last occurrence of a separator
483     /// character.
484     ///
485     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
486     /// such that (*this == LHS + Separator + RHS) is true and RHS is
487     /// minimal. If \p Separator is not in the string, then the result is a
488     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
489     ///
490     /// \param Separator - The character to split on.
491     /// \return - The split substrings.
492     std::pair<StringRef, StringRef> rsplit(char Separator) const {
493       size_t Idx = rfind(Separator);
494       if (Idx == npos)
495         return std::make_pair(*this, StringRef());
496       return std::make_pair(slice(0, Idx), slice(Idx+1, npos));
497     }
498
499     /// Return string with consecutive characters in \p Chars starting from
500     /// the left removed.
501     StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
502       return drop_front(std::min(Length, find_first_not_of(Chars)));
503     }
504
505     /// Return string with consecutive characters in \p Chars starting from
506     /// the right removed.
507     StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
508       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
509     }
510
511     /// Return string with consecutive characters in \p Chars starting from
512     /// the left and right removed.
513     StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
514       return ltrim(Chars).rtrim(Chars);
515     }
516
517     /// @}
518   };
519
520   /// @name StringRef Comparison Operators
521   /// @{
522
523   inline bool operator==(StringRef LHS, StringRef RHS) {
524     return LHS.equals(RHS);
525   }
526
527   inline bool operator!=(StringRef LHS, StringRef RHS) {
528     return !(LHS == RHS);
529   }
530
531   inline bool operator<(StringRef LHS, StringRef RHS) {
532     return LHS.compare(RHS) == -1;
533   }
534
535   inline bool operator<=(StringRef LHS, StringRef RHS) {
536     return LHS.compare(RHS) != 1;
537   }
538
539   inline bool operator>(StringRef LHS, StringRef RHS) {
540     return LHS.compare(RHS) == 1;
541   }
542
543   inline bool operator>=(StringRef LHS, StringRef RHS) {
544     return LHS.compare(RHS) != -1;
545   }
546
547   inline std::string &operator+=(std::string &buffer, StringRef string) {
548     return buffer.append(string.data(), string.size());
549   }
550
551   /// @}
552
553   /// \brief Compute a hash_code for a StringRef.
554   hash_code hash_value(StringRef S);
555
556   // StringRefs can be treated like a POD type.
557   template <typename T> struct isPodLike;
558   template <> struct isPodLike<StringRef> { static const bool value = true; };
559 }
560
561 #endif