driver_test.cpp 7.9 KB

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