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