driver_test.cpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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. #include "toolchain/driver/driver.h"
  5. #include <gmock/gmock.h>
  6. #include <gtest/gtest.h>
  7. #include <filesystem>
  8. #include <fstream>
  9. #include <utility>
  10. #include "llvm/ADT/ScopeExit.h"
  11. #include "llvm/Object/Binary.h"
  12. #include "llvm/Support/FormatVariadic.h"
  13. #include "testing/base/test_raw_ostream.h"
  14. #include "toolchain/testing/yaml_test_helpers.h"
  15. namespace Carbon {
  16. namespace {
  17. using ::Carbon::Testing::TestRawOstream;
  18. using ::testing::_;
  19. using ::testing::ContainsRegex;
  20. using ::testing::HasSubstr;
  21. using ::testing::StrEq;
  22. namespace Yaml = ::Carbon::Testing::Yaml;
  23. // Reads a file to string.
  24. // TODO: Extract this to a helper and share it with other tests.
  25. static auto ReadFile(std::filesystem::path path) -> std::string {
  26. std::ifstream proto_file(path);
  27. std::stringstream buffer;
  28. buffer << proto_file.rdbuf();
  29. proto_file.close();
  30. return buffer.str();
  31. }
  32. class DriverTest : public testing::Test {
  33. protected:
  34. DriverTest() : driver_(fs_, test_output_stream_, test_error_stream_) {
  35. char* tmpdir_env = getenv("TEST_TMPDIR");
  36. CARBON_CHECK(tmpdir_env != nullptr);
  37. test_tmpdir_ = tmpdir_env;
  38. }
  39. auto CreateTestFile(llvm::StringRef text,
  40. llvm::StringRef file_name = "test_file.carbon")
  41. -> llvm::StringRef {
  42. fs_.addFile(file_name, /*ModificationTime=*/0,
  43. llvm::MemoryBuffer::getMemBuffer(text));
  44. return file_name;
  45. }
  46. // Makes a temp directory and changes the working directory to it. Returns an
  47. // LLVM `scope_exit` that will restore the working directory and remove the
  48. // temporary directory (and everything it contains) when destroyed.
  49. auto ScopedTempWorkingDir() {
  50. // Save our current working directory.
  51. std::error_code ec;
  52. auto original_dir = std::filesystem::current_path(ec);
  53. CARBON_CHECK(!ec) << ec.message();
  54. const auto* unit_test = ::testing::UnitTest::GetInstance();
  55. const auto* test_info = unit_test->current_test_info();
  56. std::filesystem::path test_dir = test_tmpdir_.append(
  57. llvm::formatv("{0}_{1}", test_info->test_suite_name(),
  58. test_info->name())
  59. .str());
  60. std::filesystem::create_directory(test_dir, ec);
  61. CARBON_CHECK(!ec) << "Could not create test working dir '" << test_dir
  62. << "': " << ec.message();
  63. std::filesystem::current_path(test_dir, ec);
  64. CARBON_CHECK(!ec) << "Could not change the current working dir to '"
  65. << test_dir << "': " << ec.message();
  66. return llvm::make_scope_exit([original_dir, test_dir] {
  67. std::error_code ec;
  68. std::filesystem::current_path(original_dir, ec);
  69. CARBON_CHECK(!ec) << "Could not change the current working dir to '"
  70. << original_dir << "': " << ec.message();
  71. std::filesystem::remove_all(test_dir, ec);
  72. CARBON_CHECK(!ec) << "Could not remove the test working dir '" << test_dir
  73. << "': " << ec.message();
  74. });
  75. }
  76. llvm::vfs::InMemoryFileSystem fs_;
  77. TestRawOstream test_output_stream_;
  78. TestRawOstream test_error_stream_;
  79. // Some tests work directly with files in the test temporary directory.
  80. std::filesystem::path test_tmpdir_;
  81. Driver driver_;
  82. };
  83. TEST_F(DriverTest, BadCommandErrors) {
  84. EXPECT_FALSE(driver_.RunCommand({}));
  85. EXPECT_THAT(test_error_stream_.TakeStr(), HasSubstr("ERROR"));
  86. EXPECT_FALSE(driver_.RunCommand({"foo"}));
  87. EXPECT_THAT(test_error_stream_.TakeStr(), HasSubstr("ERROR"));
  88. EXPECT_FALSE(driver_.RunCommand({"foo --bar --baz"}));
  89. EXPECT_THAT(test_error_stream_.TakeStr(), HasSubstr("ERROR"));
  90. }
  91. TEST_F(DriverTest, CompileCommandErrors) {
  92. // No input file. This error message is important so check all of it.
  93. EXPECT_FALSE(driver_.RunCommand({"compile"}));
  94. EXPECT_THAT(
  95. test_error_stream_.TakeStr(),
  96. StrEq("ERROR: Not all required positional arguments were provided. First "
  97. "missing and required positional argument: 'FILE'\n"));
  98. // Invalid output filename. No reliably error message here.
  99. // TODO: Likely want a different filename on Windows.
  100. auto empty_file = CreateTestFile("");
  101. EXPECT_FALSE(
  102. driver_.RunCommand({"compile", "--output=/dev/empty", empty_file}));
  103. EXPECT_THAT(test_error_stream_.TakeStr(),
  104. ContainsRegex("ERROR: .*/dev/empty.*"));
  105. }
  106. TEST_F(DriverTest, DumpTokens) {
  107. auto file = CreateTestFile("Hello World");
  108. EXPECT_TRUE(
  109. driver_.RunCommand({"compile", "--phase=lex", "--dump-tokens", file}));
  110. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  111. // Verify there is output without examining it.
  112. EXPECT_THAT(Yaml::Value::FromText(test_output_stream_.TakeStr()),
  113. Yaml::IsYaml(_));
  114. }
  115. TEST_F(DriverTest, DumpParseTree) {
  116. auto file = CreateTestFile("var v: i32 = 42;");
  117. EXPECT_TRUE(driver_.RunCommand(
  118. {"compile", "--phase=parse", "--dump-parse-tree", file}));
  119. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  120. // Verify there is output without examining it.
  121. EXPECT_THAT(Yaml::Value::FromText(test_output_stream_.TakeStr()),
  122. Yaml::IsYaml(_));
  123. }
  124. TEST_F(DriverTest, StdoutOutput) {
  125. // Use explicit filenames so we can look for those to validate output.
  126. CreateTestFile("fn Main() -> i32 { return 0; }", "test.carbon");
  127. EXPECT_TRUE(driver_.RunCommand({"compile", "--output=-", "test.carbon"}));
  128. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  129. // The default is textual assembly.
  130. EXPECT_THAT(test_output_stream_.TakeStr(), ContainsRegex("Main:"));
  131. EXPECT_TRUE(driver_.RunCommand(
  132. {"compile", "--output=-", "--force-obj-output", "test.carbon"}));
  133. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  134. std::string output = test_output_stream_.TakeStr();
  135. auto result =
  136. llvm::object::createBinary(llvm::MemoryBufferRef(output, "test_output"));
  137. if (auto error = result.takeError()) {
  138. FAIL() << toString(std::move(error));
  139. }
  140. EXPECT_TRUE(result->get()->isObject());
  141. }
  142. TEST_F(DriverTest, FileOutput) {
  143. auto scope = ScopedTempWorkingDir();
  144. // Use explicit filenames as the default output filename is computed from
  145. // this, and we can use this to validate output.
  146. CreateTestFile("fn Main() -> i32 { return 0; }", "test.carbon");
  147. // Object output (the default) uses `.o`.
  148. // TODO: This should actually reflect the platform defaults.
  149. EXPECT_TRUE(driver_.RunCommand({"compile", "test.carbon"}));
  150. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  151. // Ensure we wrote an object file of some form with the correct name.
  152. auto result = llvm::object::createBinary("test.o");
  153. if (auto error = result.takeError()) {
  154. FAIL() << toString(std::move(error));
  155. }
  156. EXPECT_TRUE(result->getBinary()->isObject());
  157. // Assembly output uses `.s`.
  158. // TODO: This should actually reflect the platform defaults.
  159. EXPECT_TRUE(driver_.RunCommand({"compile", "--asm-output", "test.carbon"}));
  160. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  161. // TODO: This may need to be tailored to other assembly formats.
  162. EXPECT_THAT(ReadFile("test.s"), ContainsRegex("Main:"));
  163. }
  164. } // namespace
  165. } // namespace Carbon