aboutsummaryrefslogtreecommitdiff
path: root/icing/text_classifier/lib3/utils/base/statusor.h
blob: 89c94e9f316e481de76125c5569a1f66b3b9763e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
// Copyright (C) 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef ICING_TEXT_CLASSIFIER_LIB3_UTILS_BASE_STATUSOR_H_
#define ICING_TEXT_CLASSIFIER_LIB3_UTILS_BASE_STATUSOR_H_

#include <type_traits>
#include <utility>

#include "icing/text_classifier/lib3/utils/base/logging.h"
#include "icing/text_classifier/lib3/utils/base/macros.h"
#include "icing/text_classifier/lib3/utils/base/status.h"

namespace libtextclassifier3 {

// A StatusOr holds a Status (in the case of an error), or a value T.
template <typename T>
class StatusOr {
 public:
  // Has status UNKNOWN.
  inline StatusOr();

  // Builds from a non-OK status. Crashes if an OK status is specified.
  inline StatusOr(const Status& status);             // NOLINT

  // Builds from the specified value.
  inline StatusOr(const T& value);  // NOLINT
  inline StatusOr(T&& value);       // NOLINT

  // Copy constructor.
  inline StatusOr(const StatusOr& other);
  // Move constructor.
  inline StatusOr(StatusOr&& other);

  // Conversion copy constructor, T must be copy constructible from U.
  template <typename U,
            std::enable_if_t<
                std::conjunction<std::negation<std::is_same<T, U>>,
                                 std::is_constructible<T, const U&>,
                                 std::is_convertible<const U&, T>>::value,
                int> = 0>
  inline StatusOr(const StatusOr<U>& other);  // NOLINT

  // Conversion move constructor, T must by move constructible from U.
  template <
      typename U,
      std::enable_if_t<std::conjunction<std::negation<std::is_same<T, U>>,
                                        std::is_constructible<T, U&&>,
                                        std::is_convertible<U&&, T>>::value,
                       int> = 0>
  inline StatusOr(StatusOr<U>&& other);  // NOLINT

  // Value conversion copy constructor, T must by copy constructible from U.
  template <typename U,
            std::enable_if_t<
                std::conjunction<std::negation<std::is_same<T, U>>,
                                 std::is_constructible<T, const U&>,
                                 std::is_convertible<const U&, T>>::value,
                int> = 0>
  inline StatusOr(const U& value);  // NOLINT

  // Value conversion move constructor, T must by move constructible from U.
  template <
      typename U,
      std::enable_if_t<std::conjunction<std::negation<std::is_same<T, U>>,
                                        std::is_constructible<T, U&&>,
                                        std::is_convertible<U&&, T>>::value,
                       int> = 0>
  inline StatusOr(U&& value);  // NOLINT

  // Assignment operator.
  inline StatusOr& operator=(const StatusOr& other);
  inline StatusOr& operator=(StatusOr&& other);

  // Conversion assignment operator, T must be assignable from U
  template <typename U>
  inline StatusOr& operator=(const StatusOr<U>& other);

  inline ~StatusOr();

  // Accessors.
  inline const Status& status() const& { return status_; }
  inline Status status() && { return std::move(status_); }

  // Shorthand for status().ok().
  inline bool ok() const { return status_.ok(); }

  // Returns value or crashes if ok() is false.
  inline const T& ValueOrDie() const& {
    if (!ok()) {
      TC3_LOG(FATAL) << "Attempting to fetch value of non-OK StatusOr: "
                     << status();
      exit(1);
    }
    return value_;
  }
  inline T& ValueOrDie() & {
    if (!ok()) {
      TC3_LOG(FATAL) << "Attempting to fetch value of non-OK StatusOr: "
                     << status();
      exit(1);
    }
    return value_;
  }
  inline const T&& ValueOrDie() const&& {
    if (!ok()) {
      TC3_LOG(FATAL) << "Attempting to fetch value of non-OK StatusOr: "
                     << status();
      exit(1);
    }
    return std::move(value_);
  }
  inline T&& ValueOrDie() && {
    if (!ok()) {
      TC3_LOG(FATAL) << "Attempting to fetch value of non-OK StatusOr: "
                     << status();
      exit(1);
    }
    return std::move(value_);
  }

  template <typename U>
  friend class StatusOr;

 private:
  Status status_;
  // The members of unions do not require initialization and are not destructed
  // unless specifically called. This allows us to construct instances of
  // StatusOr with only error statuses where T is not default constructible.
  union {
    // value_ is active iff status_.ok()==true
    // WARNING: The destructor of value_ is called ONLY if status_ is OK.
    T value_;
  };
};

// Implementation.

template <typename T>
inline StatusOr<T>::StatusOr() : status_(StatusCode::UNKNOWN, "") {}

template <typename T>
inline StatusOr<T>::StatusOr(const Status& status) : status_(status) {
  if (status.ok()) {
    TC3_LOG(FATAL) << "OkStatus() is not a valid argument to StatusOr";
    exit(1);
  }
}

template <typename T>
inline StatusOr<T>::StatusOr(const T& value) : value_(value) {}

template <typename T>
inline StatusOr<T>::StatusOr(T&& value) : value_(std::move(value)) {}

template <typename T>
inline StatusOr<T>::StatusOr(const StatusOr& other)
    : status_(other.status_), value_(other.value_) {}

template <typename T>
inline StatusOr<T>::StatusOr(StatusOr&& other)
    : status_(other.status_), value_(std::move(other.value_)) {}

template <typename T>
template <
    typename U,
    std::enable_if_t<std::conjunction<std::negation<std::is_same<T, U>>,
                                      std::is_constructible<T, const U&>,
                                      std::is_convertible<const U&, T>>::value,
                     int>>
inline StatusOr<T>::StatusOr(const StatusOr<U>& other)
    : status_(other.status_), value_(other.value_) {}

template <typename T>
template <typename U,
          std::enable_if_t<std::conjunction<std::negation<std::is_same<T, U>>,
                                            std::is_constructible<T, U&&>,
                                            std::is_convertible<U&&, T>>::value,
                           int>>
inline StatusOr<T>::StatusOr(StatusOr<U>&& other)
    : status_(other.status_), value_(std::move(other.value_)) {}

template <typename T>
template <
    typename U,
    std::enable_if_t<std::conjunction<std::negation<std::is_same<T, U>>,
                                      std::is_constructible<T, const U&>,
                                      std::is_convertible<const U&, T>>::value,
                     int>>
inline StatusOr<T>::StatusOr(const U& value) : StatusOr(T(value)) {}

template <typename T>
template <typename U,
          std::enable_if_t<std::conjunction<std::negation<std::is_same<T, U>>,
                                            std::is_constructible<T, U&&>,
                                            std::is_convertible<U&&, T>>::value,
                           int>>
inline StatusOr<T>::StatusOr(U&& value) : StatusOr(T(std::forward<U>(value))) {}

template <typename T>
inline StatusOr<T>& StatusOr<T>::operator=(const StatusOr& other) {
  status_ = other.status_;
  if (status_.ok()) {
    value_ = other.value_;
  }
  return *this;
}

template <typename T>
inline StatusOr<T>& StatusOr<T>::operator=(StatusOr&& other) {
  status_ = other.status_;
  if (status_.ok()) {
    value_ = std::move(other.value_);
  }
  return *this;
}

template <typename T>
inline StatusOr<T>::~StatusOr() {
  if (ok()) {
    value_.~T();
  }
}

template <typename T>
template <typename U>
inline StatusOr<T>& StatusOr<T>::operator=(const StatusOr<U>& other) {
  status_ = other.status_;
  if (status_.ok()) {
    value_ = other.value_;
  }
  return *this;
}

}  // namespace libtextclassifier3

#define TC3_ASSIGN_OR_RETURN(...)                              \
  TC_STATUS_MACROS_IMPL_GET_VARIADIC_(                         \
      (__VA_ARGS__, TC_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_3_, \
       TC_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_2_))             \
  (__VA_ARGS__)

#define TC3_ASSIGN_OR_RETURN_NULL(lhs, rexpr) \
  TC3_ASSIGN_OR_RETURN(lhs, rexpr, nullptr)

#define TC3_ASSIGN_OR_RETURN_FALSE(lhs, rexpr) \
  TC3_ASSIGN_OR_RETURN(lhs, rexpr, false)

#define TC3_ASSIGN_OR_RETURN_0(lhs, rexpr) TC3_ASSIGN_OR_RETURN(lhs, rexpr, 0)

// =================================================================
// == Implementation details, do not rely on anything below here. ==
// =================================================================

// Some builds do not support C++14 fully yet, using C++11 constexpr technique.
constexpr bool HasPossiblyConditionalOperator(const char* lhs, int index) {
  return (index == -1 ? false
                      : (lhs[index] == '?'
                             ? true
                             : HasPossiblyConditionalOperator(lhs, index - 1)));
}

// MSVC incorrectly expands variadic macros, splice together a macro call to
// work around the bug.
#define TC_STATUS_MACROS_IMPL_GET_VARIADIC_HELPER_(_1, _2, _3, NAME, ...) NAME
#define TC_STATUS_MACROS_IMPL_GET_VARIADIC_(args) \
  TC_STATUS_MACROS_IMPL_GET_VARIADIC_HELPER_ args

#define TC_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_2_(lhs, rexpr) \
  TC_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_3_(lhs, rexpr, _)
#define TC_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_3_(lhs, rexpr,                \
                                                  error_expression)          \
  TC_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_(                                   \
      TC_STATUS_MACROS_IMPL_CONCAT_(_status_or_value, __LINE__), lhs, rexpr, \
      error_expression)
#define TC_STATUS_MACROS_IMPL_ASSIGN_OR_RETURN_(statusor, lhs, rexpr,          \
                                                error_expression)              \
  auto statusor = (rexpr);                                                     \
  if (!statusor.ok()) {                                                        \
    ::libtextclassifier3::Status _(std::move(statusor).status());              \
    (void)_; /* error_expression is allowed to not use this variable */        \
    return (error_expression);                                                 \
  }                                                                            \
  {                                                                            \
    static_assert(#lhs[0] != '(' || #lhs[sizeof(#lhs) - 2] != ')' ||           \
                      !HasPossiblyConditionalOperator(#lhs, sizeof(#lhs) - 2), \
                  "Identified potential conditional operator, consider not "   \
                  "using ASSIGN_OR_RETURN");                                   \
  }                                                                            \
  TC_STATUS_MACROS_IMPL_UNPARENTHESIZE_IF_PARENTHESIZED(lhs) =                 \
      std::move(statusor).ValueOrDie()

// Internal helpers for macro expansion.
#define TC_STATUS_MACROS_IMPL_EAT(...)
#define TC_STATUS_MACROS_IMPL_REM(...) __VA_ARGS__
#define TC_STATUS_MACROS_IMPL_EMPTY()

// Internal helpers for emptyness arguments check.
#define TC_STATUS_MACROS_IMPL_IS_EMPTY_INNER(...) \
  TC_STATUS_MACROS_IMPL_IS_EMPTY_INNER_I(__VA_ARGS__, 0, 1)
#define TC_STATUS_MACROS_IMPL_IS_EMPTY_INNER_I(e0, e1, is_empty, ...) is_empty

#define TC_STATUS_MACROS_IMPL_IS_EMPTY(...) \
  TC_STATUS_MACROS_IMPL_IS_EMPTY_I(__VA_ARGS__)
#define TC_STATUS_MACROS_IMPL_IS_EMPTY_I(...) \
  TC_STATUS_MACROS_IMPL_IS_EMPTY_INNER(_, ##__VA_ARGS__)

// Internal helpers for if statement.
#define TC_STATUS_MACROS_IMPL_IF_1(_Then, _Else) _Then
#define TC_STATUS_MACROS_IMPL_IF_0(_Then, _Else) _Else
#define TC_STATUS_MACROS_IMPL_IF(_Cond, _Then, _Else) \
  TC_STATUS_MACROS_IMPL_CONCAT_(TC_STATUS_MACROS_IMPL_IF_, _Cond)(_Then, _Else)

// Expands to 1 if the input is parenthesized. Otherwise expands to 0.
#define TC_STATUS_MACROS_IMPL_IS_PARENTHESIZED(...) \
  TC_STATUS_MACROS_IMPL_IS_EMPTY(TC_STATUS_MACROS_IMPL_EAT __VA_ARGS__)

// If the input is parenthesized, removes the parentheses. Otherwise expands to
// the input unchanged.
#define TC_STATUS_MACROS_IMPL_UNPARENTHESIZE_IF_PARENTHESIZED(...) \
  TC_STATUS_MACROS_IMPL_IF(                                        \
      TC_STATUS_MACROS_IMPL_IS_PARENTHESIZED(__VA_ARGS__),         \
      TC_STATUS_MACROS_IMPL_REM, TC_STATUS_MACROS_IMPL_EMPTY())    \
  __VA_ARGS__

// Internal helper for concatenating macro values.
#define TC_STATUS_MACROS_IMPL_CONCAT_INNER_(x, y) x##y
#define TC_STATUS_MACROS_IMPL_CONCAT_(x, y) \
  TC_STATUS_MACROS_IMPL_CONCAT_INNER_(x, y)

#endif  // ICING_TEXT_CLASSIFIER_LIB3_UTILS_BASE_STATUSOR_H_