bison_wrap.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_EXPLORER_SYNTAX_BISON_WRAP_H_
  5. #define CARBON_EXPLORER_SYNTAX_BISON_WRAP_H_
  6. #include <optional>
  7. #include "common/check.h"
  8. namespace Carbon {
  9. // Bison requires that types be default initializable for use with its variant
  10. // semantics. This wraps arbitrary types to support a default constructor, while
  11. // still requiring they be properly initialized.
  12. template <typename T>
  13. class BisonWrap {
  14. public:
  15. // Assigning a value initializes the wrapper.
  16. auto operator=(T&& rhs) -> BisonWrap& {
  17. val_ = std::move(rhs);
  18. return *this;
  19. }
  20. // Support transparent conversion to the wrapped type.
  21. // NOLINTNEXTLINE(google-explicit-constructor)
  22. operator T() { return Release(); }
  23. // Access the contained object, which must already have been set.
  24. auto Unwrap() & -> T& { return *val_; }
  25. // Deliberately releases the contained value. Errors if not initialized.
  26. // Called directly in parser.ypp when releasing pairs.
  27. auto Release() -> T {
  28. CARBON_CHECK(val_.has_value());
  29. T ret = std::move(*val_);
  30. val_.reset();
  31. return ret;
  32. }
  33. private:
  34. std::optional<T> val_;
  35. };
  36. } // namespace Carbon
  37. #endif // CARBON_EXPLORER_SYNTAX_BISON_WRAP_H_