driver_test.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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_, /*input_stream=*/nullptr,
  38. &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. RawStringOstream test_output_stream_;
  85. RawStringOstream 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. // Pass non-existing file
  106. EXPECT_FALSE(driver_
  107. .RunCommand({"compile", "--dump-mem-usage",
  108. "non-existing-file.carbon"})
  109. .success);
  110. EXPECT_THAT(
  111. test_error_stream_.TakeStr(),
  112. ContainsRegex("No such file or directory[\\n]*non-existing-file.carbon"));
  113. // Flush output stream, because it's ok that it's not empty here.
  114. test_output_stream_.TakeStr();
  115. // Invalid output filename. No reliably error message here.
  116. // TODO: Likely want a different filename on Windows.
  117. auto empty_file = MakeTestFile("");
  118. EXPECT_FALSE(driver_
  119. .RunCommand({"compile", "--no-prelude-import",
  120. "--output=/dev/empty", empty_file})
  121. .success);
  122. EXPECT_THAT(test_error_stream_.TakeStr(),
  123. ContainsRegex("error: .*/dev/empty.*"));
  124. }
  125. TEST_F(DriverTest, DumpTokens) {
  126. auto file = MakeTestFile("Hello World");
  127. EXPECT_TRUE(driver_
  128. .RunCommand({"compile", "--no-prelude-import", "--phase=lex",
  129. "--dump-tokens", file})
  130. .success);
  131. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  132. // Verify there is output without examining it.
  133. EXPECT_THAT(Yaml::Value::FromText(test_output_stream_.TakeStr()),
  134. Yaml::IsYaml(_));
  135. }
  136. TEST_F(DriverTest, DumpParseTree) {
  137. auto file = MakeTestFile("var v: () = ();");
  138. EXPECT_TRUE(driver_
  139. .RunCommand({"compile", "--no-prelude-import",
  140. "--phase=parse", "--dump-parse-tree", file})
  141. .success);
  142. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  143. // Verify there is output without examining it.
  144. EXPECT_THAT(Yaml::Value::FromText(test_output_stream_.TakeStr()),
  145. Yaml::IsYaml(_));
  146. }
  147. TEST_F(DriverTest, StdoutOutput) {
  148. // Use explicit filenames so we can look for those to validate output.
  149. MakeTestFile("fn Main() {}", "test.carbon");
  150. EXPECT_TRUE(driver_
  151. .RunCommand({"compile", "--no-prelude-import", "--output=-",
  152. "test.carbon"})
  153. .success);
  154. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  155. // The default is textual assembly.
  156. EXPECT_THAT(test_output_stream_.TakeStr(), ContainsRegex("Main:"));
  157. EXPECT_TRUE(driver_
  158. .RunCommand({"compile", "--no-prelude-import", "--output=-",
  159. "--force-obj-output", "test.carbon"})
  160. .success);
  161. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  162. std::string output = test_output_stream_.TakeStr();
  163. auto result =
  164. llvm::object::createBinary(llvm::MemoryBufferRef(output, "test_output"));
  165. if (auto error = result.takeError()) {
  166. FAIL() << toString(std::move(error));
  167. }
  168. EXPECT_TRUE(result->get()->isObject());
  169. }
  170. TEST_F(DriverTest, FileOutput) {
  171. auto scope = ScopedTempWorkingDir();
  172. // Use explicit filenames as the default output filename is computed from
  173. // this, and we can use this to validate output.
  174. MakeTestFile("fn Main() {}", "test.carbon");
  175. // Object output (the default) uses `.o`.
  176. // TODO: This should actually reflect the platform defaults.
  177. EXPECT_TRUE(
  178. driver_.RunCommand({"compile", "--no-prelude-import", "test.carbon"})
  179. .success);
  180. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  181. // Ensure we wrote an object file of some form with the correct name.
  182. auto result = llvm::object::createBinary("test.o");
  183. if (auto error = result.takeError()) {
  184. FAIL() << toString(std::move(error));
  185. }
  186. EXPECT_TRUE(result->getBinary()->isObject());
  187. // Assembly output uses `.s`.
  188. // TODO: This should actually reflect the platform defaults.
  189. EXPECT_TRUE(driver_
  190. .RunCommand({"compile", "--no-prelude-import", "--asm-output",
  191. "test.carbon"})
  192. .success);
  193. EXPECT_THAT(test_error_stream_.TakeStr(), StrEq(""));
  194. // TODO: This may need to be tailored to other assembly formats.
  195. EXPECT_THAT(ReadFile("test.s"), ContainsRegex("Main:"));
  196. }
  197. } // namespace
  198. } // namespace Carbon