driver_test.cpp 8.4 KB

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