driver_test.cpp 7.3 KB

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