LLVM 22.0.0git
fallible_iterator.h
Go to the documentation of this file.
1//===--- fallible_iterator.h - Wrapper for fallible iterators ---*- 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_FALLIBLE_ITERATOR_H
10#define LLVM_ADT_FALLIBLE_ITERATOR_H
11
14#include "llvm/Support/Error.h"
15
16#include <type_traits>
17
18namespace llvm {
19
20/// A wrapper class for fallible iterators.
21///
22/// The fallible_iterator template wraps an underlying iterator-like class
23/// whose increment and decrement operations are replaced with fallible versions
24/// like:
25///
26/// @code{.cpp}
27/// Error inc();
28/// Error dec();
29/// @endcode
30///
31/// It produces an interface that is (mostly) compatible with a traditional
32/// c++ iterator, including ++ and -- operators that do not fail.
33///
34/// Instances of the wrapper are constructed with an instance of the
35/// underlying iterator and (for non-end iterators) a reference to an Error
36/// instance. If the underlying increment/decrement operations fail, the Error
37/// is returned via this reference, and the resulting iterator value set to an
38/// end-of-range sentinel value. This enables the following loop idiom:
39///
40/// @code{.cpp}
41/// class Archive { // E.g. Potentially malformed on-disk archive
42/// public:
43/// fallible_iterator<ArchiveChildItr> children_begin(Error &Err);
44/// fallible_iterator<ArchiveChildItr> children_end();
45/// iterator_range<fallible_iterator<ArchiveChildItr>>
46/// children(Error &Err) {
47/// return make_range(children_begin(Err), children_end());
48/// //...
49/// };
50///
51/// void walk(Archive &A) {
52/// Error Err = Error::success();
53/// for (auto &C : A.children(Err)) {
54/// // Loop body only entered when increment succeeds.
55/// }
56/// if (Err) {
57/// // handle error.
58/// }
59/// }
60/// @endcode
61///
62/// The wrapper marks the referenced Error as unchecked after each increment
63/// and/or decrement operation, and clears the unchecked flag when a non-end
64/// value is compared against end (since, by the increment invariant, not being
65/// an end value proves that there was no error, and is equivalent to checking
66/// that the Error is success). This allows early exits from the loop body
67/// without requiring redundant error checks.
68template <typename Underlying> class fallible_iterator {
69private:
70 template <typename T, typename U = decltype(std::declval<T>().operator->())>
71 using enable_if_struct_deref_supported =
72 std::enable_if_t<!std::is_void_v<U>, U>;
73
74public:
75 /// Construct a fallible iterator that *cannot* be used as an end-of-range
76 /// value.
77 ///
78 /// A value created by this method can be dereferenced, incremented,
79 /// decremented and compared, providing the underlying type supports it.
80 ///
81 /// The error that is passed in will be initially marked as checked, so if the
82 /// iterator is not used at all the Error need not be checked.
83 static fallible_iterator itr(Underlying I, Error &Err) {
84 (void)!!Err;
85 return fallible_iterator(std::move(I), &Err);
86 }
87
88 /// Construct a fallible iterator that can be used as an end-of-range value.
89 ///
90 /// A value created by this method can be dereferenced (if the underlying
91 /// value points at a valid value) and compared, but not incremented or
92 /// decremented.
93 static fallible_iterator end(Underlying I) {
94 return fallible_iterator(std::move(I), nullptr);
95 }
96
97 /// Forward dereference to the underlying iterator.
98 decltype(auto) operator*() { return *I; }
99
100 /// Forward const dereference to the underlying iterator.
101 decltype(auto) operator*() const { return *I; }
102
103 /// Forward structure dereference to the underlying iterator (if the
104 /// underlying iterator supports it).
105 template <typename T = Underlying>
106 enable_if_struct_deref_supported<T> operator->() {
107 return I.operator->();
108 }
109
110 /// Forward const structure dereference to the underlying iterator (if the
111 /// underlying iterator supports it).
112 template <typename T = Underlying>
113 enable_if_struct_deref_supported<const T> operator->() const {
114 return I.operator->();
115 }
116
117 /// Increment the fallible iterator.
118 ///
119 /// If the underlying 'inc' operation fails, this will set the Error value
120 /// and update this iterator value to point to end-of-range.
121 ///
122 /// The Error value is marked as needing checking, regardless of whether the
123 /// 'inc' operation succeeds or fails.
124 fallible_iterator &operator++() {
125 assert(getErrPtr() && "Cannot increment end iterator");
126 if (auto Err = I.inc())
127 handleError(std::move(Err));
128 else
129 resetCheckedFlag();
130 return *this;
131 }
132
133 /// Decrement the fallible iterator.
134 ///
135 /// If the underlying 'dec' operation fails, this will set the Error value
136 /// and update this iterator value to point to end-of-range.
137 ///
138 /// The Error value is marked as needing checking, regardless of whether the
139 /// 'dec' operation succeeds or fails.
140 fallible_iterator &operator--() {
141 assert(getErrPtr() && "Cannot decrement end iterator");
142 if (auto Err = I.dec())
143 handleError(std::move(Err));
144 else
145 resetCheckedFlag();
146 return *this;
147 }
148
149 /// Compare fallible iterators for equality.
150 ///
151 /// Returns true if both LHS and RHS are end-of-range values, or if both are
152 /// non-end-of-range values whose underlying iterator values compare equal.
153 ///
154 /// If this is a comparison between an end-of-range iterator and a
155 /// non-end-of-range iterator, then the Error (referenced by the
156 /// non-end-of-range value) is marked as checked: Since all
157 /// increment/decrement operations result in an end-of-range value, comparing
158 /// false against end-of-range is equivalent to checking that the Error value
159 /// is success. This flag management enables early returns from loop bodies
160 /// without redundant Error checks.
161 friend bool operator==(const fallible_iterator &LHS,
162 const fallible_iterator &RHS) {
163 // If both iterators are in the end state they compare
164 // equal, regardless of whether either is valid.
165 if (LHS.isEnd() && RHS.isEnd())
166 return true;
167
168 assert(LHS.isValid() && RHS.isValid() &&
169 "Invalid iterators can only be compared against end");
170
171 bool Equal = LHS.I == RHS.I;
172
173 // If the iterators differ and this is a comparison against end then mark
174 // the Error as checked.
175 if (!Equal) {
176 if (LHS.isEnd())
177 (void)!!*RHS.getErrPtr();
178 else
179 (void)!!*LHS.getErrPtr();
180 }
181
182 return Equal;
183 }
184
185 /// Compare fallible iterators for inequality.
186 ///
187 /// See notes for operator==.
188 friend bool operator!=(const fallible_iterator &LHS,
189 const fallible_iterator &RHS) {
190 return !(LHS == RHS);
191 }
192
193private:
194 fallible_iterator(Underlying I, Error *Err)
195 : I(std::move(I)), ErrState(Err, false) {}
196
197 Error *getErrPtr() const { return ErrState.getPointer(); }
198
199 bool isEnd() const { return getErrPtr() == nullptr; }
200
201 bool isValid() const { return !ErrState.getInt(); }
202
203 void handleError(Error Err) {
204 *getErrPtr() = std::move(Err);
205 ErrState.setPointer(nullptr);
206 ErrState.setInt(true);
207 }
208
209 void resetCheckedFlag() {
210 *getErrPtr() = Error::success();
211 }
212
213 Underlying I;
214 mutable PointerIntPair<Error *, 1> ErrState;
215};
216
217/// Convenience wrapper to make a fallible_iterator value from an instance
218/// of an underlying iterator and an Error reference.
219template <typename Underlying>
223
224/// Convenience wrapper to make a fallible_iterator end value from an instance
225/// of an underlying iterator.
226template <typename Underlying>
230
231template <typename Underlying>
233make_fallible_range(Underlying I, Underlying E, Error &Err) {
234 return make_range(make_fallible_itr(std::move(I), Err),
235 make_fallible_end(std::move(E)));
236}
237
238} // end namespace llvm
239
240#endif // LLVM_ADT_FALLIBLE_ITERATOR_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define I(x, y, z)
Definition MD5.cpp:58
This file defines the PointerIntPair class.
Value * RHS
Value * LHS
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
A wrapper class for fallible iterators.
static fallible_iterator end(Underlying I)
Construct a fallible iterator that can be used as an end-of-range value.
friend bool operator!=(const fallible_iterator &LHS, const fallible_iterator &RHS)
Compare fallible iterators for inequality.
static fallible_iterator itr(Underlying I, Error &Err)
Construct a fallible iterator that cannot be used as an end-of-range value.
fallible_iterator & operator--()
Decrement the fallible iterator.
friend bool operator==(const fallible_iterator &LHS, const fallible_iterator &RHS)
Compare fallible iterators for equality.
fallible_iterator & operator++()
Increment the fallible iterator.
enable_if_struct_deref_supported< const T > operator->() const
Forward const structure dereference to the underlying iterator (if the underlying iterator supports i...
enable_if_struct_deref_supported< T > operator->()
Forward structure dereference to the underlying iterator (if the underlying iterator supports it).
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
constexpr std::underlying_type_t< E > Underlying(E Val)
Check that Val is in range for E, and return Val cast to E's underlying type.
This is an optimization pass for GlobalISel generic memory operations.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
fallible_iterator< Underlying > make_fallible_itr(Underlying I, Error &Err)
Convenience wrapper to make a fallible_iterator value from an instance of an underlying iterator and ...
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
fallible_iterator< Underlying > make_fallible_end(Underlying E)
Convenience wrapper to make a fallible_iterator end value from an instance of an underlying iterator.
iterator_range< fallible_iterator< Underlying > > make_fallible_range(Underlying I, Underlying E, Error &Err)
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1847
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:851