driver_test.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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/gtest_main.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. protected:
  35. DriverTest()
  36. : installation_(
  37. InstallPaths::MakeForBazelRunfiles(Testing::GetTestExePath())),
  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) << 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 '" << 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 '"
  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) << "Could not change the current working dir to '"
  74. << original_dir << "': " << ec.message();
  75. std::filesystem::remove_all(test_dir, ec);
  76. CARBON_CHECK(!ec) << "Could not remove the test working dir '" << test_dir
  77. << "': " << ec.message();
  78. });
  79. }
  80. llvm::vfs::InMemoryFileSystem fs_;
  81. const InstallPaths installation_;
  82. TestRawOstream test_output_stream_;
  83. TestRawOstream test_error_stream_;
  84. // Some tests work directly with files in the test temporary directory.
  85. std::filesystem::path test_tmpdir_;
  86. Driver driver_;
  87. };
  88. TEST_F(DriverTest, BadCommandErrors) {
  89. EXPECT_FALSE(driver_.RunCommand({}).success);
  90. EXPECT_THAT(test_error_stream_.TakeStr(), HasSubstr("ERROR"));
  91. EXPECT_FALSE(driver_.RunCommand({"foo"}).success);
  92. EXPECT_THAT(test_error_stream_.TakeStr(), HasSubstr("ERROR"));
  93. EXPECT_FALSE(driver_.RunCommand({"foo --bar --baz"}).success);
  94. EXPECT_THAT(test_error_stream_.TakeStr(), HasSubstr("ERROR"));
  95. }
  96. TEST_F(DriverTest, CompileCommandErrors) {
  97. // No input file. This error message is important so check all of it.
  98. EXPECT_FALSE(driver_.RunCommand({"compile"}).success);
  99. EXPECT_THAT(
  100. test_error_stream_.TakeStr(),
  101. StrEq("ERROR: Not all required positional arguments were provided. First "
  102. "missing and required positional argument: 'FILE'\n"));
  103. // Invalid output filename. No reliably error message here.
  104. // TODO: Likely want a different filename on Windows.
  105. auto empty_file = MakeTestFile("");
  106. EXPECT_FALSE(driver_
  107. .RunCommand({"compile", "--no-prelude-import",
  108. "--output=/dev/empty", empty_file})
  109. .success);
  110. EXPECT_THAT(test_error_stream_.TakeStr(),
  111. ContainsRegex("ERROR: .*/dev/empty.*"));
  112. }
  113. TEST_F(DriverTest, DumpTokens) {
  114. auto file = MakeTestFile("Hello World");
  115. EXPECT_TRUE(driver_
  116. .RunCommand({"compile", "--no-prelude-import", "--phase=lex",
  117. "--dump-tokens", file})
  118. .success);
  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, DumpParseTree) {
  125. auto file = MakeTestFile("var v: () = ();");
  126. EXPECT_TRUE(driver_
  127. .RunCommand({"compile", "--no-prelude-import",
  128. "--phase=parse", "--dump-parse-tree", file})
  129. .success);
  130. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  131. // Verify there is output without examining it.
  132. EXPECT_THAT(Yaml::Value::FromText(test_output_stream_.TakeStr()),
  133. Yaml::IsYaml(_));
  134. }
  135. TEST_F(DriverTest, StdoutOutput) {
  136. // Use explicit filenames so we can look for those to validate output.
  137. MakeTestFile("fn Main() {}", "test.carbon");
  138. EXPECT_TRUE(driver_
  139. .RunCommand({"compile", "--no-prelude-import", "--output=-",
  140. "test.carbon"})
  141. .success);
  142. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  143. // The default is textual assembly.
  144. EXPECT_THAT(test_output_stream_.TakeStr(), ContainsRegex("Main:"));
  145. EXPECT_TRUE(driver_
  146. .RunCommand({"compile", "--no-prelude-import", "--output=-",
  147. "--force-obj-output", "test.carbon"})
  148. .success);
  149. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  150. std::string output = test_output_stream_.TakeStr();
  151. auto result =
  152. llvm::object::createBinary(llvm::MemoryBufferRef(output, "test_output"));
  153. if (auto error = result.takeError()) {
  154. FAIL() << toString(std::move(error));
  155. }
  156. EXPECT_TRUE(result->get()->isObject());
  157. }
  158. TEST_F(DriverTest, FileOutput) {
  159. auto scope = ScopedTempWorkingDir();
  160. // Use explicit filenames as the default output filename is computed from
  161. // this, and we can use this to validate output.
  162. MakeTestFile("fn Main() {}", "test.carbon");
  163. // Object output (the default) uses `.o`.
  164. // TODO: This should actually reflect the platform defaults.
  165. EXPECT_TRUE(
  166. driver_.RunCommand({"compile", "--no-prelude-import", "test.carbon"})
  167. .success);
  168. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  169. // Ensure we wrote an object file of some form with the correct name.
  170. auto result = llvm::object::createBinary("test.o");
  171. if (auto error = result.takeError()) {
  172. FAIL() << toString(std::move(error));
  173. }
  174. EXPECT_TRUE(result->getBinary()->isObject());
  175. // Assembly output uses `.s`.
  176. // TODO: This should actually reflect the platform defaults.
  177. EXPECT_TRUE(driver_
  178. .RunCommand({"compile", "--no-prelude-import", "--asm-output",
  179. "test.carbon"})
  180. .success);
  181. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  182. // TODO: This may need to be tailored to other assembly formats.
  183. EXPECT_THAT(ReadFile("test.s"), ContainsRegex("Main:"));
  184. }
  185. } // namespace
  186. } // namespace Carbon