driver_test.cpp 8.3 KB

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