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