1 //===- StringRef.h - Constant String Reference Wrapper ----------*- C++ -*-===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef LLVM_ADT_STRINGREF_H
10 #define LLVM_ADT_STRINGREF_H
11 
12 #include "llvm/ADT/DenseMapInfo.h"
13 #include "llvm/ADT/STLFunctionalExtras.h"
14 #include "llvm/ADT/iterator_range.h"
15 #include "llvm/Support/Compiler.h"
16 #include <algorithm>
17 #include <cassert>
18 #include <cstddef>
19 #include <cstring>
20 #include <limits>
21 #include <string>
22 #include <string_view>
23 #include <type_traits>
24 #include <utility>
25 
26 namespace llvm {
27 
28   class APInt;
29   class hash_code;
30   template <typename T> class SmallVectorImpl;
31   class StringRef;
32 
33   /// Helper functions for StringRef::getAsInteger.
34   bool getAsUnsignedInteger(StringRef Str, unsigned Radix,
35                             unsigned long long &Result);
36 
37   bool getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result);
38 
39   bool consumeUnsignedInteger(StringRef &Str, unsigned Radix,
40                               unsigned long long &Result);
41   bool consumeSignedInteger(StringRef &Str, unsigned Radix, long long &Result);
42 
43   /// StringRef - Represent a constant reference to a string, i.e. a character
44   /// array and a length, which need not be null terminated.
45   ///
46   /// This class does not own the string data, it is expected to be used in
47   /// situations where the character data resides in some other buffer, whose
48   /// lifetime extends past that of the StringRef. For this reason, it is not in
49   /// general safe to store a StringRef.
50   class LLVM_GSL_POINTER StringRef {
51   public:
52     static constexpr size_t npos = ~size_t(0);
53 
54     using iterator = const char *;
55     using const_iterator = const char *;
56     using size_type = size_t;
57 
58   private:
59     /// The start of the string, in an external buffer.
60     const char *Data = nullptr;
61 
62     /// The length of the string.
63     size_t Length = 0;
64 
65     // Workaround memcmp issue with null pointers (undefined behavior)
66     // by providing a specialized version
compareMemory(const char * Lhs,const char * Rhs,size_t Length)67     static int compareMemory(const char *Lhs, const char *Rhs, size_t Length) {
68       if (Length == 0) { return 0; }
69       return ::memcmp(Lhs,Rhs,Length);
70     }
71 
72   public:
73     /// @name Constructors
74     /// @{
75 
76     /// Construct an empty string ref.
77     /*implicit*/ StringRef() = default;
78 
79     /// Disable conversion from nullptr.  This prevents things like
80     /// if (S == nullptr)
81     StringRef(std::nullptr_t) = delete;
82 
83     /// Construct a string ref from a cstring.
StringRef(const char * Str)84     /*implicit*/ constexpr StringRef(const char *Str)
85         : Data(Str), Length(Str ?
86     // GCC 7 doesn't have constexpr char_traits. Fall back to __builtin_strlen.
87 #if defined(_GLIBCXX_RELEASE) && _GLIBCXX_RELEASE < 8
88                                 __builtin_strlen(Str)
89 #else
90                                 std::char_traits<char>::length(Str)
91 #endif
92                                 : 0) {
93     }
94 
95     /// Construct a string ref from a pointer and length.
StringRef(const char * data,size_t length)96     /*implicit*/ constexpr StringRef(const char *data, size_t length)
97         : Data(data), Length(length) {}
98 
99     /// Construct a string ref from an std::string.
StringRef(const std::string & Str)100     /*implicit*/ StringRef(const std::string &Str)
101       : Data(Str.data()), Length(Str.length()) {}
102 
103     /// Construct a string ref from an std::string_view.
StringRef(std::string_view Str)104     /*implicit*/ constexpr StringRef(std::string_view Str)
105         : Data(Str.data()), Length(Str.size()) {}
106 
107     /// @}
108     /// @name Iterators
109     /// @{
110 
begin()111     iterator begin() const { return Data; }
112 
end()113     iterator end() const { return Data + Length; }
114 
bytes_begin()115     const unsigned char *bytes_begin() const {
116       return reinterpret_cast<const unsigned char *>(begin());
117     }
bytes_end()118     const unsigned char *bytes_end() const {
119       return reinterpret_cast<const unsigned char *>(end());
120     }
bytes()121     iterator_range<const unsigned char *> bytes() const {
122       return make_range(bytes_begin(), bytes_end());
123     }
124 
125     /// @}
126     /// @name String Operations
127     /// @{
128 
129     /// data - Get a pointer to the start of the string (which may not be null
130     /// terminated).
data()131     [[nodiscard]] constexpr const char *data() const { return Data; }
132 
133     /// empty - Check if the string is empty.
empty()134     [[nodiscard]] constexpr bool empty() const { return Length == 0; }
135 
136     /// size - Get the string size.
size()137     [[nodiscard]] constexpr size_t size() const { return Length; }
138 
139     /// front - Get the first character in the string.
front()140     [[nodiscard]] char front() const {
141       assert(!empty());
142       return Data[0];
143     }
144 
145     /// back - Get the last character in the string.
back()146     [[nodiscard]] char back() const {
147       assert(!empty());
148       return Data[Length-1];
149     }
150 
151     // copy - Allocate copy in Allocator and return StringRef to it.
152     template <typename Allocator>
copy(Allocator & A)153     [[nodiscard]] StringRef copy(Allocator &A) const {
154       // Don't request a length 0 copy from the allocator.
155       if (empty())
156         return StringRef();
157       char *S = A.template Allocate<char>(Length);
158       std::copy(begin(), end(), S);
159       return StringRef(S, Length);
160     }
161 
162     /// equals - Check for string equality, this is more efficient than
163     /// compare() when the relative ordering of inequal strings isn't needed.
equals(StringRef RHS)164     [[nodiscard]] bool equals(StringRef RHS) const {
165       return (Length == RHS.Length &&
166               compareMemory(Data, RHS.Data, RHS.Length) == 0);
167     }
168 
169     /// Check for string equality, ignoring case.
equals_insensitive(StringRef RHS)170     [[nodiscard]] bool equals_insensitive(StringRef RHS) const {
171       return Length == RHS.Length && compare_insensitive(RHS) == 0;
172     }
173 
174     /// compare - Compare two strings; the result is negative, zero, or positive
175     /// if this string is lexicographically less than, equal to, or greater than
176     /// the \p RHS.
compare(StringRef RHS)177     [[nodiscard]] int compare(StringRef RHS) const {
178       // Check the prefix for a mismatch.
179       if (int Res = compareMemory(Data, RHS.Data, std::min(Length, RHS.Length)))
180         return Res < 0 ? -1 : 1;
181 
182       // Otherwise the prefixes match, so we only need to check the lengths.
183       if (Length == RHS.Length)
184         return 0;
185       return Length < RHS.Length ? -1 : 1;
186     }
187 
188     /// Compare two strings, ignoring case.
189     [[nodiscard]] int compare_insensitive(StringRef RHS) const;
190 
191     /// compare_numeric - Compare two strings, treating sequences of digits as
192     /// numbers.
193     [[nodiscard]] int compare_numeric(StringRef RHS) const;
194 
195     /// Determine the edit distance between this string and another
196     /// string.
197     ///
198     /// \param Other the string to compare this string against.
199     ///
200     /// \param AllowReplacements whether to allow character
201     /// replacements (change one character into another) as a single
202     /// operation, rather than as two operations (an insertion and a
203     /// removal).
204     ///
205     /// \param MaxEditDistance If non-zero, the maximum edit distance that
206     /// this routine is allowed to compute. If the edit distance will exceed
207     /// that maximum, returns \c MaxEditDistance+1.
208     ///
209     /// \returns the minimum number of character insertions, removals,
210     /// or (if \p AllowReplacements is \c true) replacements needed to
211     /// transform one of the given strings into the other. If zero,
212     /// the strings are identical.
213     [[nodiscard]] unsigned edit_distance(StringRef Other,
214                                          bool AllowReplacements = true,
215                                          unsigned MaxEditDistance = 0) const;
216 
217     [[nodiscard]] unsigned
218     edit_distance_insensitive(StringRef Other, bool AllowReplacements = true,
219                               unsigned MaxEditDistance = 0) const;
220 
221     /// str - Get the contents as an std::string.
str()222     [[nodiscard]] std::string str() const {
223       if (!Data) return std::string();
224       return std::string(Data, Length);
225     }
226 
227     /// @}
228     /// @name Operator Overloads
229     /// @{
230 
231     [[nodiscard]] char operator[](size_t Index) const {
232       assert(Index < Length && "Invalid index!");
233       return Data[Index];
234     }
235 
236     /// Disallow accidental assignment from a temporary std::string.
237     ///
238     /// The declaration here is extra complicated so that `stringRef = {}`
239     /// and `stringRef = "abc"` continue to select the move assignment operator.
240     template <typename T>
241     std::enable_if_t<std::is_same<T, std::string>::value, StringRef> &
242     operator=(T &&Str) = delete;
243 
244     /// @}
245     /// @name Type Conversions
246     /// @{
247 
string_view()248     constexpr operator std::string_view() const {
249       return std::string_view(data(), size());
250     }
251 
252     /// @}
253     /// @name String Predicates
254     /// @{
255 
256     /// Check if this string starts with the given \p Prefix.
starts_with(StringRef Prefix)257     [[nodiscard]] bool starts_with(StringRef Prefix) const {
258       return Length >= Prefix.Length &&
259              compareMemory(Data, Prefix.Data, Prefix.Length) == 0;
260     }
starts_with(char Prefix)261     [[nodiscard]] bool starts_with(char Prefix) const {
262       return !empty() && front() == Prefix;
263     }
264 
265     /// Check if this string starts with the given \p Prefix, ignoring case.
266     [[nodiscard]] bool starts_with_insensitive(StringRef Prefix) const;
267 
268     /// Check if this string ends with the given \p Suffix.
ends_with(StringRef Suffix)269     [[nodiscard]] bool ends_with(StringRef Suffix) const {
270       return Length >= Suffix.Length &&
271              compareMemory(end() - Suffix.Length, Suffix.Data, Suffix.Length) ==
272                  0;
273     }
ends_with(char Suffix)274     [[nodiscard]] bool ends_with(char Suffix) const {
275       return !empty() && back() == Suffix;
276     }
277 
278     /// Check if this string ends with the given \p Suffix, ignoring case.
279     [[nodiscard]] bool ends_with_insensitive(StringRef Suffix) const;
280 
281     /// @}
282     /// @name String Searching
283     /// @{
284 
285     /// Search for the first character \p C in the string.
286     ///
287     /// \returns The index of the first occurrence of \p C, or npos if not
288     /// found.
289     [[nodiscard]] size_t find(char C, size_t From = 0) const {
290       return std::string_view(*this).find(C, From);
291     }
292 
293     /// Search for the first character \p C in the string, ignoring case.
294     ///
295     /// \returns The index of the first occurrence of \p C, or npos if not
296     /// found.
297     [[nodiscard]] size_t find_insensitive(char C, size_t From = 0) const;
298 
299     /// Search for the first character satisfying the predicate \p F
300     ///
301     /// \returns The index of the first character satisfying \p F starting from
302     /// \p From, or npos if not found.
303     [[nodiscard]] size_t find_if(function_ref<bool(char)> F,
304                                  size_t From = 0) const {
305       StringRef S = drop_front(From);
306       while (!S.empty()) {
307         if (F(S.front()))
308           return size() - S.size();
309         S = S.drop_front();
310       }
311       return npos;
312     }
313 
314     /// Search for the first character not satisfying the predicate \p F
315     ///
316     /// \returns The index of the first character not satisfying \p F starting
317     /// from \p From, or npos if not found.
318     [[nodiscard]] size_t find_if_not(function_ref<bool(char)> F,
319                                      size_t From = 0) const {
320       return find_if([F](char c) { return !F(c); }, From);
321     }
322 
323     /// Search for the first string \p Str in the string.
324     ///
325     /// \returns The index of the first occurrence of \p Str, or npos if not
326     /// found.
327     [[nodiscard]] size_t find(StringRef Str, size_t From = 0) const;
328 
329     /// Search for the first string \p Str in the string, ignoring case.
330     ///
331     /// \returns The index of the first occurrence of \p Str, or npos if not
332     /// found.
333     [[nodiscard]] size_t find_insensitive(StringRef Str, size_t From = 0) const;
334 
335     /// Search for the last character \p C in the string.
336     ///
337     /// \returns The index of the last occurrence of \p C, or npos if not
338     /// found.
339     [[nodiscard]] size_t rfind(char C, size_t From = npos) const {
340       size_t I = std::min(From, Length);
341       while (I) {
342         --I;
343         if (Data[I] == C)
344           return I;
345       }
346       return npos;
347     }
348 
349     /// Search for the last character \p C in the string, ignoring case.
350     ///
351     /// \returns The index of the last occurrence of \p C, or npos if not
352     /// found.
353     [[nodiscard]] size_t rfind_insensitive(char C, size_t From = npos) const;
354 
355     /// Search for the last string \p Str in the string.
356     ///
357     /// \returns The index of the last occurrence of \p Str, or npos if not
358     /// found.
359     [[nodiscard]] size_t rfind(StringRef Str) const;
360 
361     /// Search for the last string \p Str in the string, ignoring case.
362     ///
363     /// \returns The index of the last occurrence of \p Str, or npos if not
364     /// found.
365     [[nodiscard]] size_t rfind_insensitive(StringRef Str) const;
366 
367     /// Find the first character in the string that is \p C, or npos if not
368     /// found. Same as find.
369     [[nodiscard]] size_t find_first_of(char C, size_t From = 0) const {
370       return find(C, From);
371     }
372 
373     /// Find the first character in the string that is in \p Chars, or npos if
374     /// not found.
375     ///
376     /// Complexity: O(size() + Chars.size())
377     [[nodiscard]] size_t find_first_of(StringRef Chars, size_t From = 0) const;
378 
379     /// Find the first character in the string that is not \p C or npos if not
380     /// found.
381     [[nodiscard]] size_t find_first_not_of(char C, size_t From = 0) const;
382 
383     /// Find the first character in the string that is not in the string
384     /// \p Chars, or npos if not found.
385     ///
386     /// Complexity: O(size() + Chars.size())
387     [[nodiscard]] size_t find_first_not_of(StringRef Chars,
388                                            size_t From = 0) const;
389 
390     /// Find the last character in the string that is \p C, or npos if not
391     /// found.
392     [[nodiscard]] size_t find_last_of(char C, size_t From = npos) const {
393       return rfind(C, From);
394     }
395 
396     /// Find the last character in the string that is in \p C, or npos if not
397     /// found.
398     ///
399     /// Complexity: O(size() + Chars.size())
400     [[nodiscard]] size_t find_last_of(StringRef Chars,
401                                       size_t From = npos) const;
402 
403     /// Find the last character in the string that is not \p C, or npos if not
404     /// found.
405     [[nodiscard]] size_t find_last_not_of(char C, size_t From = npos) const;
406 
407     /// Find the last character in the string that is not in \p Chars, or
408     /// npos if not found.
409     ///
410     /// Complexity: O(size() + Chars.size())
411     [[nodiscard]] size_t find_last_not_of(StringRef Chars,
412                                           size_t From = npos) const;
413 
414     /// Return true if the given string is a substring of *this, and false
415     /// otherwise.
contains(StringRef Other)416     [[nodiscard]] bool contains(StringRef Other) const {
417       return find(Other) != npos;
418     }
419 
420     /// Return true if the given character is contained in *this, and false
421     /// otherwise.
contains(char C)422     [[nodiscard]] bool contains(char C) const {
423       return find_first_of(C) != npos;
424     }
425 
426     /// Return true if the given string is a substring of *this, and false
427     /// otherwise.
contains_insensitive(StringRef Other)428     [[nodiscard]] bool contains_insensitive(StringRef Other) const {
429       return find_insensitive(Other) != npos;
430     }
431 
432     /// Return true if the given character is contained in *this, and false
433     /// otherwise.
contains_insensitive(char C)434     [[nodiscard]] bool contains_insensitive(char C) const {
435       return find_insensitive(C) != npos;
436     }
437 
438     /// @}
439     /// @name Helpful Algorithms
440     /// @{
441 
442     /// Return the number of occurrences of \p C in the string.
count(char C)443     [[nodiscard]] size_t count(char C) const {
444       size_t Count = 0;
445       for (size_t I = 0; I != Length; ++I)
446         if (Data[I] == C)
447           ++Count;
448       return Count;
449     }
450 
451     /// Return the number of non-overlapped occurrences of \p Str in
452     /// the string.
453     size_t count(StringRef Str) const;
454 
455     /// Parse the current string as an integer of the specified radix.  If
456     /// \p Radix is specified as zero, this does radix autosensing using
457     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
458     ///
459     /// If the string is invalid or if only a subset of the string is valid,
460     /// this returns true to signify the error.  The string is considered
461     /// erroneous if empty or if it overflows T.
getAsInteger(unsigned Radix,T & Result)462     template <typename T> bool getAsInteger(unsigned Radix, T &Result) const {
463       if constexpr (std::numeric_limits<T>::is_signed) {
464         long long LLVal;
465         if (getAsSignedInteger(*this, Radix, LLVal) ||
466             static_cast<T>(LLVal) != LLVal)
467           return true;
468         Result = LLVal;
469       } else {
470         unsigned long long ULLVal;
471         // The additional cast to unsigned long long is required to avoid the
472         // Visual C++ warning C4805: '!=' : unsafe mix of type 'bool' and type
473         // 'unsigned __int64' when instantiating getAsInteger with T = bool.
474         if (getAsUnsignedInteger(*this, Radix, ULLVal) ||
475             static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
476           return true;
477         Result = ULLVal;
478       }
479       return false;
480     }
481 
482     /// Parse the current string as an integer of the specified radix.  If
483     /// \p Radix is specified as zero, this does radix autosensing using
484     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
485     ///
486     /// If the string does not begin with a number of the specified radix,
487     /// this returns true to signify the error. The string is considered
488     /// erroneous if empty or if it overflows T.
489     /// The portion of the string representing the discovered numeric value
490     /// is removed from the beginning of the string.
consumeInteger(unsigned Radix,T & Result)491     template <typename T> bool consumeInteger(unsigned Radix, T &Result) {
492       if constexpr (std::numeric_limits<T>::is_signed) {
493         long long LLVal;
494         if (consumeSignedInteger(*this, Radix, LLVal) ||
495             static_cast<long long>(static_cast<T>(LLVal)) != LLVal)
496           return true;
497         Result = LLVal;
498       } else {
499         unsigned long long ULLVal;
500         if (consumeUnsignedInteger(*this, Radix, ULLVal) ||
501             static_cast<unsigned long long>(static_cast<T>(ULLVal)) != ULLVal)
502           return true;
503         Result = ULLVal;
504       }
505       return false;
506     }
507 
508     /// Parse the current string as an integer of the specified \p Radix, or of
509     /// an autosensed radix if the \p Radix given is 0.  The current value in
510     /// \p Result is discarded, and the storage is changed to be wide enough to
511     /// store the parsed integer.
512     ///
513     /// \returns true if the string does not solely consist of a valid
514     /// non-empty number in the appropriate base.
515     ///
516     /// APInt::fromString is superficially similar but assumes the
517     /// string is well-formed in the given radix.
518     bool getAsInteger(unsigned Radix, APInt &Result) const;
519 
520     /// Parse the current string as an integer of the specified \p Radix.  If
521     /// \p Radix is specified as zero, this does radix autosensing using
522     /// extended C rules: 0 is octal, 0x is hex, 0b is binary.
523     ///
524     /// If the string does not begin with a number of the specified radix,
525     /// this returns true to signify the error. The string is considered
526     /// erroneous if empty.
527     /// The portion of the string representing the discovered numeric value
528     /// is removed from the beginning of the string.
529     bool consumeInteger(unsigned Radix, APInt &Result);
530 
531     /// Parse the current string as an IEEE double-precision floating
532     /// point value.  The string must be a well-formed double.
533     ///
534     /// If \p AllowInexact is false, the function will fail if the string
535     /// cannot be represented exactly.  Otherwise, the function only fails
536     /// in case of an overflow or underflow, or an invalid floating point
537     /// representation.
538     bool getAsDouble(double &Result, bool AllowInexact = true) const;
539 
540     /// @}
541     /// @name String Operations
542     /// @{
543 
544     // Convert the given ASCII string to lowercase.
545     [[nodiscard]] std::string lower() const;
546 
547     /// Convert the given ASCII string to uppercase.
548     [[nodiscard]] std::string upper() const;
549 
550     /// @}
551     /// @name Substring Operations
552     /// @{
553 
554     /// Return a reference to the substring from [Start, Start + N).
555     ///
556     /// \param Start The index of the starting character in the substring; if
557     /// the index is npos or greater than the length of the string then the
558     /// empty substring will be returned.
559     ///
560     /// \param N The number of characters to included in the substring. If N
561     /// exceeds the number of characters remaining in the string, the string
562     /// suffix (starting with \p Start) will be returned.
563     [[nodiscard]] constexpr StringRef substr(size_t Start,
564                                              size_t N = npos) const {
565       Start = std::min(Start, Length);
566       return StringRef(Data + Start, std::min(N, Length - Start));
567     }
568 
569     /// Return a StringRef equal to 'this' but with only the first \p N
570     /// elements remaining.  If \p N is greater than the length of the
571     /// string, the entire string is returned.
572     [[nodiscard]] StringRef take_front(size_t N = 1) const {
573       if (N >= size())
574         return *this;
575       return drop_back(size() - N);
576     }
577 
578     /// Return a StringRef equal to 'this' but with only the last \p N
579     /// elements remaining.  If \p N is greater than the length of the
580     /// string, the entire string is returned.
581     [[nodiscard]] StringRef take_back(size_t N = 1) const {
582       if (N >= size())
583         return *this;
584       return drop_front(size() - N);
585     }
586 
587     /// Return the longest prefix of 'this' such that every character
588     /// in the prefix satisfies the given predicate.
take_while(function_ref<bool (char)> F)589     [[nodiscard]] StringRef take_while(function_ref<bool(char)> F) const {
590       return substr(0, find_if_not(F));
591     }
592 
593     /// Return the longest prefix of 'this' such that no character in
594     /// the prefix satisfies the given predicate.
take_until(function_ref<bool (char)> F)595     [[nodiscard]] StringRef take_until(function_ref<bool(char)> F) const {
596       return substr(0, find_if(F));
597     }
598 
599     /// Return a StringRef equal to 'this' but with the first \p N elements
600     /// dropped.
601     [[nodiscard]] StringRef drop_front(size_t N = 1) const {
602       assert(size() >= N && "Dropping more elements than exist");
603       return substr(N);
604     }
605 
606     /// Return a StringRef equal to 'this' but with the last \p N elements
607     /// dropped.
608     [[nodiscard]] StringRef drop_back(size_t N = 1) const {
609       assert(size() >= N && "Dropping more elements than exist");
610       return substr(0, size()-N);
611     }
612 
613     /// Return a StringRef equal to 'this', but with all characters satisfying
614     /// the given predicate dropped from the beginning of the string.
drop_while(function_ref<bool (char)> F)615     [[nodiscard]] StringRef drop_while(function_ref<bool(char)> F) const {
616       return substr(find_if_not(F));
617     }
618 
619     /// Return a StringRef equal to 'this', but with all characters not
620     /// satisfying the given predicate dropped from the beginning of the string.
drop_until(function_ref<bool (char)> F)621     [[nodiscard]] StringRef drop_until(function_ref<bool(char)> F) const {
622       return substr(find_if(F));
623     }
624 
625     /// Returns true if this StringRef has the given prefix and removes that
626     /// prefix.
consume_front(StringRef Prefix)627     bool consume_front(StringRef Prefix) {
628       if (!starts_with(Prefix))
629         return false;
630 
631       *this = substr(Prefix.size());
632       return true;
633     }
634 
635     /// Returns true if this StringRef has the given prefix, ignoring case,
636     /// and removes that prefix.
consume_front_insensitive(StringRef Prefix)637     bool consume_front_insensitive(StringRef Prefix) {
638       if (!starts_with_insensitive(Prefix))
639         return false;
640 
641       *this = substr(Prefix.size());
642       return true;
643     }
644 
645     /// Returns true if this StringRef has the given suffix and removes that
646     /// suffix.
consume_back(StringRef Suffix)647     bool consume_back(StringRef Suffix) {
648       if (!ends_with(Suffix))
649         return false;
650 
651       *this = substr(0, size() - Suffix.size());
652       return true;
653     }
654 
655     /// Returns true if this StringRef has the given suffix, ignoring case,
656     /// and removes that suffix.
consume_back_insensitive(StringRef Suffix)657     bool consume_back_insensitive(StringRef Suffix) {
658       if (!ends_with_insensitive(Suffix))
659         return false;
660 
661       *this = substr(0, size() - Suffix.size());
662       return true;
663     }
664 
665     /// Return a reference to the substring from [Start, End).
666     ///
667     /// \param Start The index of the starting character in the substring; if
668     /// the index is npos or greater than the length of the string then the
669     /// empty substring will be returned.
670     ///
671     /// \param End The index following the last character to include in the
672     /// substring. If this is npos or exceeds the number of characters
673     /// remaining in the string, the string suffix (starting with \p Start)
674     /// will be returned. If this is less than \p Start, an empty string will
675     /// be returned.
slice(size_t Start,size_t End)676     [[nodiscard]] StringRef slice(size_t Start, size_t End) const {
677       Start = std::min(Start, Length);
678       End = std::clamp(End, Start, Length);
679       return StringRef(Data + Start, End - Start);
680     }
681 
682     /// Split into two substrings around the first occurrence of a separator
683     /// character.
684     ///
685     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
686     /// such that (*this == LHS + Separator + RHS) is true and RHS is
687     /// maximal. If \p Separator is not in the string, then the result is a
688     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
689     ///
690     /// \param Separator The character to split on.
691     /// \returns The split substrings.
split(char Separator)692     [[nodiscard]] std::pair<StringRef, StringRef> split(char Separator) const {
693       return split(StringRef(&Separator, 1));
694     }
695 
696     /// Split into two substrings around the first occurrence of a separator
697     /// string.
698     ///
699     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
700     /// such that (*this == LHS + Separator + RHS) is true and RHS is
701     /// maximal. If \p Separator is not in the string, then the result is a
702     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
703     ///
704     /// \param Separator - The string to split on.
705     /// \return - The split substrings.
706     [[nodiscard]] std::pair<StringRef, StringRef>
split(StringRef Separator)707     split(StringRef Separator) const {
708       size_t Idx = find(Separator);
709       if (Idx == npos)
710         return std::make_pair(*this, StringRef());
711       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
712     }
713 
714     /// Split into two substrings around the last occurrence of a separator
715     /// string.
716     ///
717     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
718     /// such that (*this == LHS + Separator + RHS) is true and RHS is
719     /// minimal. If \p Separator is not in the string, then the result is a
720     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
721     ///
722     /// \param Separator - The string to split on.
723     /// \return - The split substrings.
724     [[nodiscard]] std::pair<StringRef, StringRef>
rsplit(StringRef Separator)725     rsplit(StringRef Separator) const {
726       size_t Idx = rfind(Separator);
727       if (Idx == npos)
728         return std::make_pair(*this, StringRef());
729       return std::make_pair(slice(0, Idx), slice(Idx + Separator.size(), npos));
730     }
731 
732     /// Split into substrings around the occurrences of a separator string.
733     ///
734     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
735     /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
736     /// elements are added to A.
737     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
738     /// still count when considering \p MaxSplit
739     /// An useful invariant is that
740     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
741     ///
742     /// \param A - Where to put the substrings.
743     /// \param Separator - The string to split on.
744     /// \param MaxSplit - The maximum number of times the string is split.
745     /// \param KeepEmpty - True if empty substring should be added.
746     void split(SmallVectorImpl<StringRef> &A,
747                StringRef Separator, int MaxSplit = -1,
748                bool KeepEmpty = true) const;
749 
750     /// Split into substrings around the occurrences of a separator character.
751     ///
752     /// Each substring is stored in \p A. If \p MaxSplit is >= 0, at most
753     /// \p MaxSplit splits are done and consequently <= \p MaxSplit + 1
754     /// elements are added to A.
755     /// If \p KeepEmpty is false, empty strings are not added to \p A. They
756     /// still count when considering \p MaxSplit
757     /// An useful invariant is that
758     /// Separator.join(A) == *this if MaxSplit == -1 and KeepEmpty == true
759     ///
760     /// \param A - Where to put the substrings.
761     /// \param Separator - The string to split on.
762     /// \param MaxSplit - The maximum number of times the string is split.
763     /// \param KeepEmpty - True if empty substring should be added.
764     void split(SmallVectorImpl<StringRef> &A, char Separator, int MaxSplit = -1,
765                bool KeepEmpty = true) const;
766 
767     /// Split into two substrings around the last occurrence of a separator
768     /// character.
769     ///
770     /// If \p Separator is in the string, then the result is a pair (LHS, RHS)
771     /// such that (*this == LHS + Separator + RHS) is true and RHS is
772     /// minimal. If \p Separator is not in the string, then the result is a
773     /// pair (LHS, RHS) where (*this == LHS) and (RHS == "").
774     ///
775     /// \param Separator - The character to split on.
776     /// \return - The split substrings.
rsplit(char Separator)777     [[nodiscard]] std::pair<StringRef, StringRef> rsplit(char Separator) const {
778       return rsplit(StringRef(&Separator, 1));
779     }
780 
781     /// Return string with consecutive \p Char characters starting from the
782     /// the left removed.
ltrim(char Char)783     [[nodiscard]] StringRef ltrim(char Char) const {
784       return drop_front(std::min(Length, find_first_not_of(Char)));
785     }
786 
787     /// Return string with consecutive characters in \p Chars starting from
788     /// the left removed.
789     [[nodiscard]] StringRef ltrim(StringRef Chars = " \t\n\v\f\r") const {
790       return drop_front(std::min(Length, find_first_not_of(Chars)));
791     }
792 
793     /// Return string with consecutive \p Char characters starting from the
794     /// right removed.
rtrim(char Char)795     [[nodiscard]] StringRef rtrim(char Char) const {
796       return drop_back(Length - std::min(Length, find_last_not_of(Char) + 1));
797     }
798 
799     /// Return string with consecutive characters in \p Chars starting from
800     /// the right removed.
801     [[nodiscard]] StringRef rtrim(StringRef Chars = " \t\n\v\f\r") const {
802       return drop_back(Length - std::min(Length, find_last_not_of(Chars) + 1));
803     }
804 
805     /// Return string with consecutive \p Char characters starting from the
806     /// left and right removed.
trim(char Char)807     [[nodiscard]] StringRef trim(char Char) const {
808       return ltrim(Char).rtrim(Char);
809     }
810 
811     /// Return string with consecutive characters in \p Chars starting from
812     /// the left and right removed.
813     [[nodiscard]] StringRef trim(StringRef Chars = " \t\n\v\f\r") const {
814       return ltrim(Chars).rtrim(Chars);
815     }
816 
817     /// Detect the line ending style of the string.
818     ///
819     /// If the string contains a line ending, return the line ending character
820     /// sequence that is detected. Otherwise return '\n' for unix line endings.
821     ///
822     /// \return - The line ending character sequence.
detectEOL()823     [[nodiscard]] StringRef detectEOL() const {
824       size_t Pos = find('\r');
825       if (Pos == npos) {
826         // If there is no carriage return, assume unix
827         return "\n";
828       }
829       if (Pos + 1 < Length && Data[Pos + 1] == '\n')
830         return "\r\n"; // Windows
831       if (Pos > 0 && Data[Pos - 1] == '\n')
832         return "\n\r"; // You monster!
833       return "\r";     // Classic Mac
834     }
835     /// @}
836   };
837 
838   /// A wrapper around a string literal that serves as a proxy for constructing
839   /// global tables of StringRefs with the length computed at compile time.
840   /// In order to avoid the invocation of a global constructor, StringLiteral
841   /// should *only* be used in a constexpr context, as such:
842   ///
843   /// constexpr StringLiteral S("test");
844   ///
845   class StringLiteral : public StringRef {
846   private:
StringLiteral(const char * Str,size_t N)847     constexpr StringLiteral(const char *Str, size_t N) : StringRef(Str, N) {
848     }
849 
850   public:
851     template <size_t N>
StringLiteral(const char (& Str)[N])852     constexpr StringLiteral(const char (&Str)[N])
853 #if defined(__clang__) && __has_attribute(enable_if)
854 #pragma clang diagnostic push
855 #pragma clang diagnostic ignored "-Wgcc-compat"
856         __attribute((enable_if(__builtin_strlen(Str) == N - 1,
857                                "invalid string literal")))
858 #pragma clang diagnostic pop
859 #endif
860         : StringRef(Str, N - 1) {
861     }
862 
863     // Explicit construction for strings like "foo\0bar".
864     template <size_t N>
withInnerNUL(const char (& Str)[N])865     static constexpr StringLiteral withInnerNUL(const char (&Str)[N]) {
866       return StringLiteral(Str, N - 1);
867     }
868   };
869 
870   /// @name StringRef Comparison Operators
871   /// @{
872 
873   inline bool operator==(StringRef LHS, StringRef RHS) {
874     if (LHS.size() != RHS.size())
875       return false;
876     if (LHS.empty())
877       return true;
878     return ::memcmp(LHS.data(), RHS.data(), LHS.size()) == 0;
879   }
880 
881   inline bool operator!=(StringRef LHS, StringRef RHS) { return !(LHS == RHS); }
882 
883   inline bool operator<(StringRef LHS, StringRef RHS) {
884     return LHS.compare(RHS) < 0;
885   }
886 
887   inline bool operator<=(StringRef LHS, StringRef RHS) {
888     return LHS.compare(RHS) <= 0;
889   }
890 
891   inline bool operator>(StringRef LHS, StringRef RHS) {
892     return LHS.compare(RHS) > 0;
893   }
894 
895   inline bool operator>=(StringRef LHS, StringRef RHS) {
896     return LHS.compare(RHS) >= 0;
897   }
898 
899   inline std::string &operator+=(std::string &buffer, StringRef string) {
900     return buffer.append(string.data(), string.size());
901   }
902 
903   /// @}
904 
905   /// Compute a hash_code for a StringRef.
906   [[nodiscard]] hash_code hash_value(StringRef S);
907 
908   // Provide DenseMapInfo for StringRefs.
909   template <> struct DenseMapInfo<StringRef, void> {
910     static inline StringRef getEmptyKey() {
911       return StringRef(
912           reinterpret_cast<const char *>(~static_cast<uintptr_t>(0)), 0);
913     }
914 
915     static inline StringRef getTombstoneKey() {
916       return StringRef(
917           reinterpret_cast<const char *>(~static_cast<uintptr_t>(1)), 0);
918     }
919 
920     static unsigned getHashValue(StringRef Val);
921 
922     static bool isEqual(StringRef LHS, StringRef RHS) {
923       if (RHS.data() == getEmptyKey().data())
924         return LHS.data() == getEmptyKey().data();
925       if (RHS.data() == getTombstoneKey().data())
926         return LHS.data() == getTombstoneKey().data();
927       return LHS == RHS;
928     }
929   };
930 
931 } // end namespace llvm
932 
933 #endif // LLVM_ADT_STRINGREF_H
934