bison_wrap.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. // Deliberately releases the contained value. Errors if not initialized.
  24. // Called directly in parser.ypp when releasing pairs.
  25. auto Release() -> T {
  26. CARBON_CHECK(val_.has_value());
  27. T ret = std::move(*val_);
  28. val_.reset();
  29. return ret;
  30. }
  31. private:
  32. std::optional<T> val_;
  33. };
  34. } // namespace Carbon
  35. #endif // CARBON_EXPLORER_SYNTAX_BISON_WRAP_H_