driver_test.cpp 8.1 KB

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