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