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