bison_wrap.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 EXECUTABLE_SEMANTICS_SYNTAX_BISON_WRAP_H_
  5. #define EXECUTABLE_SEMANTICS_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. BisonWrap& operator=(T&& rhs) {
  17. val = std::move(rhs);
  18. return *this;
  19. }
  20. // Support transparent conversion to the wrapped type.
  21. operator T() { return Release(); }
  22. // Deliberately releases the contained value. Errors if not initialized.
  23. // Called directly in parser.ypp when releasing pairs.
  24. auto Release() -> T {
  25. CHECK(val.has_value());
  26. T ret = std::move(*val);
  27. val.reset();
  28. return ret;
  29. }
  30. private:
  31. std::optional<T> val;
  32. };
  33. } // namespace Carbon
  34. #endif // EXECUTABLE_SEMANTICS_SYNTAX_BISON_WRAP_H_