Optional.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. //===- Optional.h - Simple variant for passing optional values --*- 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. // This file provides Optional, a template class modeled in the spirit of
  10. // OCaml's 'opt' variant. The idea is to strongly type whether or not
  11. // a value can be optional.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_ADT_OPTIONAL_H
  15. #define LLVM_ADT_OPTIONAL_H
  16. #include "llvm/ADT/Hashing.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/STLForwardCompat.h"
  19. #include "llvm/Support/Compiler.h"
  20. #include "llvm/Support/type_traits.h"
  21. #include <cassert>
  22. #include <memory>
  23. #include <new>
  24. #include <utility>
  25. namespace llvm {
  26. class raw_ostream;
  27. namespace optional_detail {
  28. /// Storage for any type.
  29. //
  30. // The specialization condition intentionally uses
  31. // llvm::is_trivially_copy_constructible instead of
  32. // std::is_trivially_copy_constructible. GCC versions prior to 7.4 may
  33. // instantiate the copy constructor of `T` when
  34. // std::is_trivially_copy_constructible is instantiated. This causes
  35. // compilation to fail if we query the trivially copy constructible property of
  36. // a class which is not copy constructible.
  37. //
  38. // The current implementation of OptionalStorage insists that in order to use
  39. // the trivial specialization, the value_type must be trivially copy
  40. // constructible and trivially copy assignable due to =default implementations
  41. // of the copy/move constructor/assignment. It does not follow that this is
  42. // necessarily the case std::is_trivially_copyable is true (hence the expanded
  43. // specialization condition).
  44. //
  45. // The move constructible / assignable conditions emulate the remaining behavior
  46. // of std::is_trivially_copyable.
  47. template <typename T, bool = (llvm::is_trivially_copy_constructible<T>::value &&
  48. std::is_trivially_copy_assignable<T>::value &&
  49. (std::is_trivially_move_constructible<T>::value ||
  50. !std::is_move_constructible<T>::value) &&
  51. (std::is_trivially_move_assignable<T>::value ||
  52. !std::is_move_assignable<T>::value))>
  53. class OptionalStorage {
  54. union {
  55. char empty;
  56. T value;
  57. };
  58. bool hasVal;
  59. public:
  60. ~OptionalStorage() { reset(); }
  61. constexpr OptionalStorage() noexcept : empty(), hasVal(false) {}
  62. constexpr OptionalStorage(OptionalStorage const &other) : OptionalStorage() {
  63. if (other.hasValue()) {
  64. emplace(other.value);
  65. }
  66. }
  67. constexpr OptionalStorage(OptionalStorage &&other) : OptionalStorage() {
  68. if (other.hasValue()) {
  69. emplace(std::move(other.value));
  70. }
  71. }
  72. template <class... Args>
  73. constexpr explicit OptionalStorage(in_place_t, Args &&... args)
  74. : value(std::forward<Args>(args)...), hasVal(true) {}
  75. void reset() noexcept {
  76. if (hasVal) {
  77. value.~T();
  78. hasVal = false;
  79. }
  80. }
  81. constexpr bool hasValue() const noexcept { return hasVal; }
  82. T &getValue() LLVM_LVALUE_FUNCTION noexcept {
  83. assert(hasVal);
  84. return value;
  85. }
  86. constexpr T const &getValue() const LLVM_LVALUE_FUNCTION noexcept {
  87. assert(hasVal);
  88. return value;
  89. }
  90. #if LLVM_HAS_RVALUE_REFERENCE_THIS
  91. T &&getValue() && noexcept {
  92. assert(hasVal);
  93. return std::move(value);
  94. }
  95. #endif
  96. template <class... Args> void emplace(Args &&... args) {
  97. reset();
  98. ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
  99. hasVal = true;
  100. }
  101. OptionalStorage &operator=(T const &y) {
  102. if (hasValue()) {
  103. value = y;
  104. } else {
  105. ::new ((void *)std::addressof(value)) T(y);
  106. hasVal = true;
  107. }
  108. return *this;
  109. }
  110. OptionalStorage &operator=(T &&y) {
  111. if (hasValue()) {
  112. value = std::move(y);
  113. } else {
  114. ::new ((void *)std::addressof(value)) T(std::move(y));
  115. hasVal = true;
  116. }
  117. return *this;
  118. }
  119. OptionalStorage &operator=(OptionalStorage const &other) {
  120. if (other.hasValue()) {
  121. if (hasValue()) {
  122. value = other.value;
  123. } else {
  124. ::new ((void *)std::addressof(value)) T(other.value);
  125. hasVal = true;
  126. }
  127. } else {
  128. reset();
  129. }
  130. return *this;
  131. }
  132. OptionalStorage &operator=(OptionalStorage &&other) {
  133. if (other.hasValue()) {
  134. if (hasValue()) {
  135. value = std::move(other.value);
  136. } else {
  137. ::new ((void *)std::addressof(value)) T(std::move(other.value));
  138. hasVal = true;
  139. }
  140. } else {
  141. reset();
  142. }
  143. return *this;
  144. }
  145. };
  146. template <typename T> class OptionalStorage<T, true> {
  147. union {
  148. char empty;
  149. T value;
  150. };
  151. bool hasVal = false;
  152. public:
  153. ~OptionalStorage() = default;
  154. constexpr OptionalStorage() noexcept : empty{} {}
  155. constexpr OptionalStorage(OptionalStorage const &other) = default;
  156. constexpr OptionalStorage(OptionalStorage &&other) = default;
  157. OptionalStorage &operator=(OptionalStorage const &other) = default;
  158. OptionalStorage &operator=(OptionalStorage &&other) = default;
  159. template <class... Args>
  160. constexpr explicit OptionalStorage(in_place_t, Args &&... args)
  161. : value(std::forward<Args>(args)...), hasVal(true) {}
  162. void reset() noexcept {
  163. if (hasVal) {
  164. value.~T();
  165. hasVal = false;
  166. }
  167. }
  168. constexpr bool hasValue() const noexcept { return hasVal; }
  169. T &getValue() LLVM_LVALUE_FUNCTION noexcept {
  170. assert(hasVal);
  171. return value;
  172. }
  173. constexpr T const &getValue() const LLVM_LVALUE_FUNCTION noexcept {
  174. assert(hasVal);
  175. return value;
  176. }
  177. #if LLVM_HAS_RVALUE_REFERENCE_THIS
  178. T &&getValue() && noexcept {
  179. assert(hasVal);
  180. return std::move(value);
  181. }
  182. #endif
  183. template <class... Args> void emplace(Args &&... args) {
  184. reset();
  185. ::new ((void *)std::addressof(value)) T(std::forward<Args>(args)...);
  186. hasVal = true;
  187. }
  188. OptionalStorage &operator=(T const &y) {
  189. if (hasValue()) {
  190. value = y;
  191. } else {
  192. ::new ((void *)std::addressof(value)) T(y);
  193. hasVal = true;
  194. }
  195. return *this;
  196. }
  197. OptionalStorage &operator=(T &&y) {
  198. if (hasValue()) {
  199. value = std::move(y);
  200. } else {
  201. ::new ((void *)std::addressof(value)) T(std::move(y));
  202. hasVal = true;
  203. }
  204. return *this;
  205. }
  206. };
  207. } // namespace optional_detail
  208. template <typename T> class Optional {
  209. optional_detail::OptionalStorage<T> Storage;
  210. public:
  211. using value_type = T;
  212. constexpr Optional() {}
  213. constexpr Optional(NoneType) {}
  214. constexpr Optional(const T &y) : Storage(in_place, y) {}
  215. constexpr Optional(const Optional &O) = default;
  216. constexpr Optional(T &&y) : Storage(in_place, std::move(y)) {}
  217. constexpr Optional(Optional &&O) = default;
  218. template <typename... ArgTypes>
  219. constexpr Optional(in_place_t, ArgTypes &&...Args)
  220. : Storage(in_place, std::forward<ArgTypes>(Args)...) {}
  221. Optional &operator=(T &&y) {
  222. Storage = std::move(y);
  223. return *this;
  224. }
  225. Optional &operator=(Optional &&O) = default;
  226. /// Create a new object by constructing it in place with the given arguments.
  227. template <typename... ArgTypes> void emplace(ArgTypes &&... Args) {
  228. Storage.emplace(std::forward<ArgTypes>(Args)...);
  229. }
  230. static constexpr Optional create(const T *y) {
  231. return y ? Optional(*y) : Optional();
  232. }
  233. Optional &operator=(const T &y) {
  234. Storage = y;
  235. return *this;
  236. }
  237. Optional &operator=(const Optional &O) = default;
  238. void reset() { Storage.reset(); }
  239. constexpr const T *getPointer() const { return &Storage.getValue(); }
  240. T *getPointer() { return &Storage.getValue(); }
  241. constexpr const T &getValue() const LLVM_LVALUE_FUNCTION {
  242. return Storage.getValue();
  243. }
  244. T &getValue() LLVM_LVALUE_FUNCTION { return Storage.getValue(); }
  245. constexpr explicit operator bool() const { return hasValue(); }
  246. constexpr bool hasValue() const { return Storage.hasValue(); }
  247. constexpr const T *operator->() const { return getPointer(); }
  248. T *operator->() { return getPointer(); }
  249. constexpr const T &operator*() const LLVM_LVALUE_FUNCTION {
  250. return getValue();
  251. }
  252. T &operator*() LLVM_LVALUE_FUNCTION { return getValue(); }
  253. template <typename U>
  254. constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION {
  255. return hasValue() ? getValue() : std::forward<U>(value);
  256. }
  257. /// Apply a function to the value if present; otherwise return None.
  258. template <class Function>
  259. auto map(const Function &F) const LLVM_LVALUE_FUNCTION
  260. -> Optional<decltype(F(getValue()))> {
  261. if (*this) return F(getValue());
  262. return None;
  263. }
  264. #if LLVM_HAS_RVALUE_REFERENCE_THIS
  265. T &&getValue() && { return std::move(Storage.getValue()); }
  266. T &&operator*() && { return std::move(Storage.getValue()); }
  267. template <typename U>
  268. T getValueOr(U &&value) && {
  269. return hasValue() ? std::move(getValue()) : std::forward<U>(value);
  270. }
  271. /// Apply a function to the value if present; otherwise return None.
  272. template <class Function>
  273. auto map(const Function &F) &&
  274. -> Optional<decltype(F(std::move(*this).getValue()))> {
  275. if (*this) return F(std::move(*this).getValue());
  276. return None;
  277. }
  278. #endif
  279. };
  280. template <class T> llvm::hash_code hash_value(const Optional<T> &O) {
  281. return O ? hash_combine(true, *O) : hash_value(false);
  282. }
  283. template <typename T, typename U>
  284. constexpr bool operator==(const Optional<T> &X, const Optional<U> &Y) {
  285. if (X && Y)
  286. return *X == *Y;
  287. return X.hasValue() == Y.hasValue();
  288. }
  289. template <typename T, typename U>
  290. constexpr bool operator!=(const Optional<T> &X, const Optional<U> &Y) {
  291. return !(X == Y);
  292. }
  293. template <typename T, typename U>
  294. constexpr bool operator<(const Optional<T> &X, const Optional<U> &Y) {
  295. if (X && Y)
  296. return *X < *Y;
  297. return X.hasValue() < Y.hasValue();
  298. }
  299. template <typename T, typename U>
  300. constexpr bool operator<=(const Optional<T> &X, const Optional<U> &Y) {
  301. return !(Y < X);
  302. }
  303. template <typename T, typename U>
  304. constexpr bool operator>(const Optional<T> &X, const Optional<U> &Y) {
  305. return Y < X;
  306. }
  307. template <typename T, typename U>
  308. constexpr bool operator>=(const Optional<T> &X, const Optional<U> &Y) {
  309. return !(X < Y);
  310. }
  311. template <typename T>
  312. constexpr bool operator==(const Optional<T> &X, NoneType) {
  313. return !X;
  314. }
  315. template <typename T>
  316. constexpr bool operator==(NoneType, const Optional<T> &X) {
  317. return X == None;
  318. }
  319. template <typename T>
  320. constexpr bool operator!=(const Optional<T> &X, NoneType) {
  321. return !(X == None);
  322. }
  323. template <typename T>
  324. constexpr bool operator!=(NoneType, const Optional<T> &X) {
  325. return X != None;
  326. }
  327. template <typename T> constexpr bool operator<(const Optional<T> &, NoneType) {
  328. return false;
  329. }
  330. template <typename T> constexpr bool operator<(NoneType, const Optional<T> &X) {
  331. return X.hasValue();
  332. }
  333. template <typename T>
  334. constexpr bool operator<=(const Optional<T> &X, NoneType) {
  335. return !(None < X);
  336. }
  337. template <typename T>
  338. constexpr bool operator<=(NoneType, const Optional<T> &X) {
  339. return !(X < None);
  340. }
  341. template <typename T> constexpr bool operator>(const Optional<T> &X, NoneType) {
  342. return None < X;
  343. }
  344. template <typename T> constexpr bool operator>(NoneType, const Optional<T> &X) {
  345. return X < None;
  346. }
  347. template <typename T>
  348. constexpr bool operator>=(const Optional<T> &X, NoneType) {
  349. return None <= X;
  350. }
  351. template <typename T>
  352. constexpr bool operator>=(NoneType, const Optional<T> &X) {
  353. return X <= None;
  354. }
  355. template <typename T>
  356. constexpr bool operator==(const Optional<T> &X, const T &Y) {
  357. return X && *X == Y;
  358. }
  359. template <typename T>
  360. constexpr bool operator==(const T &X, const Optional<T> &Y) {
  361. return Y && X == *Y;
  362. }
  363. template <typename T>
  364. constexpr bool operator!=(const Optional<T> &X, const T &Y) {
  365. return !(X == Y);
  366. }
  367. template <typename T>
  368. constexpr bool operator!=(const T &X, const Optional<T> &Y) {
  369. return !(X == Y);
  370. }
  371. template <typename T>
  372. constexpr bool operator<(const Optional<T> &X, const T &Y) {
  373. return !X || *X < Y;
  374. }
  375. template <typename T>
  376. constexpr bool operator<(const T &X, const Optional<T> &Y) {
  377. return Y && X < *Y;
  378. }
  379. template <typename T>
  380. constexpr bool operator<=(const Optional<T> &X, const T &Y) {
  381. return !(Y < X);
  382. }
  383. template <typename T>
  384. constexpr bool operator<=(const T &X, const Optional<T> &Y) {
  385. return !(Y < X);
  386. }
  387. template <typename T>
  388. constexpr bool operator>(const Optional<T> &X, const T &Y) {
  389. return Y < X;
  390. }
  391. template <typename T>
  392. constexpr bool operator>(const T &X, const Optional<T> &Y) {
  393. return Y < X;
  394. }
  395. template <typename T>
  396. constexpr bool operator>=(const Optional<T> &X, const T &Y) {
  397. return !(X < Y);
  398. }
  399. template <typename T>
  400. constexpr bool operator>=(const T &X, const Optional<T> &Y) {
  401. return !(X < Y);
  402. }
  403. raw_ostream &operator<<(raw_ostream &OS, NoneType);
  404. template <typename T, typename = decltype(std::declval<raw_ostream &>()
  405. << std::declval<const T &>())>
  406. raw_ostream &operator<<(raw_ostream &OS, const Optional<T> &O) {
  407. if (O)
  408. OS << *O;
  409. else
  410. OS << None;
  411. return OS;
  412. }
  413. } // end namespace llvm
  414. #endif // LLVM_ADT_OPTIONAL_H