semantics_ir_for_test.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_FOR_TEST_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_FOR_TEST_H_
  6. #include <gmock/gmock.h>
  7. #include <gtest/gtest.h>
  8. #include <sstream>
  9. #include "common/check.h"
  10. #include "llvm/ADT/StringExtras.h"
  11. //#include "toolchain/semantics/nodes/infix_operator.h"
  12. #include "toolchain/semantics/semantics_ir.h"
  13. namespace Carbon::Testing {
  14. // A singleton SemanticsIR instance, used by the test helpers.
  15. //
  16. // This provides a singleton so that calls like PrintTo(Semantics::Declaration)
  17. // have a SemanticsIR to refer back to; PrintTo must be static.
  18. class SemanticsIRForTest {
  19. public:
  20. template <typename NodeT>
  21. static auto GetNode(Semantics::NodeRef node_ref) -> llvm::Optional<NodeT> {
  22. if (node_ref.kind() != NodeT::Kind) {
  23. return llvm::None;
  24. }
  25. return semantics().nodes_.Get<NodeT>(node_ref);
  26. }
  27. static auto semantics() -> const SemanticsIR& {
  28. CARBON_CHECK(g_semantics != llvm::None);
  29. return *g_semantics;
  30. }
  31. static void set_semantics(SemanticsIR semantics) {
  32. CARBON_CHECK(g_semantics == llvm::None)
  33. << "Call clear() before setting again.";
  34. g_semantics = std::move(semantics);
  35. }
  36. static void clear() { g_semantics = llvm::None; }
  37. private:
  38. static llvm::Optional<SemanticsIR> g_semantics;
  39. };
  40. } // namespace Carbon::Testing
  41. namespace Carbon::Semantics {
  42. inline void PrintTo(const NodeRef& node_ref, std::ostream* out) {
  43. llvm::raw_os_ostream wrapped_out(*out);
  44. Carbon::Testing::SemanticsIRForTest::semantics().Print(wrapped_out, node_ref);
  45. }
  46. } // namespace Carbon::Semantics
  47. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_FOR_TEST_H_