file_test.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. #ifndef CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_
  5. #define CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_
  6. #include <string>
  7. #include "common/error.h"
  8. #include "llvm/ADT/STLExtras.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/Support/FormatVariadic.h"
  12. #include "llvm/Support/VirtualFileSystem.h"
  13. #include "testing/file_test/file_test_base.h"
  14. #include "toolchain/driver/driver.h"
  15. namespace Carbon::Testing {
  16. namespace {
  17. // Provides common test support for the driver. This is used by file tests in
  18. // component subdirectories.
  19. class ToolchainFileTest : public FileTestBase {
  20. public:
  21. explicit ToolchainFileTest(llvm::StringRef exe_path, std::mutex* output_mutex,
  22. llvm::StringRef test_name);
  23. // Adds a replacement for `core_package_dir`.
  24. auto GetArgReplacements() -> llvm::StringMap<std::string> override;
  25. // Loads files into the VFS and runs the driver.
  26. auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  27. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  28. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  29. llvm::raw_pwrite_stream& error_stream)
  30. -> ErrorOr<RunResult> override;
  31. // Sets different default flags based on the component being tested.
  32. auto GetDefaultArgs() -> llvm::SmallVector<std::string> override;
  33. // Generally uses the parent implementation, with special handling for lex.
  34. auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> filenames)
  35. -> std::optional<RE2> override;
  36. // Generally uses the parent implementation, with special handling for lex.
  37. auto GetLineNumberReplacements(llvm::ArrayRef<llvm::StringRef> filenames)
  38. -> llvm::SmallVector<LineNumberReplacement> override;
  39. // Generally uses the parent implementation, with special handling for lex and
  40. // driver.
  41. auto DoExtraCheckReplacements(std::string& check_line) -> void override;
  42. // Most tests can be run in parallel, but clangd has a global for its logging
  43. // system so we need language-server tests to be run in serial.
  44. auto AllowParallelRun() const -> bool override {
  45. return component_ != "language_server";
  46. }
  47. private:
  48. // Adds a file to the fs.
  49. auto AddFile(llvm::vfs::InMemoryFileSystem& fs, llvm::StringRef path)
  50. -> ErrorOr<Success>;
  51. // Controls whether `Run()` includes the prelude.
  52. auto is_no_prelude() const -> bool {
  53. return test_name().find("/no_prelude/") != llvm::StringRef::npos;
  54. }
  55. // The toolchain component subdirectory, such as `lex` or `language_server`.
  56. const llvm::StringRef component_;
  57. // The toolchain install information.
  58. const InstallPaths installation_;
  59. };
  60. } // namespace
  61. CARBON_FILE_TEST_FACTORY(ToolchainFileTest)
  62. // Returns the toolchain subdirectory being tested.
  63. static auto GetComponent(llvm::StringRef test_name) -> llvm::StringRef {
  64. // This handles cases where the toolchain directory may be copied into a
  65. // repository that doesn't put it at the root.
  66. auto pos = test_name.find("toolchain/");
  67. CARBON_CHECK(pos != llvm::StringRef::npos, "{0}", test_name);
  68. test_name = test_name.drop_front(pos + strlen("toolchain/"));
  69. test_name = test_name.take_front(test_name.find("/"));
  70. return test_name;
  71. }
  72. ToolchainFileTest::ToolchainFileTest(llvm::StringRef exe_path,
  73. std::mutex* output_mutex,
  74. llvm::StringRef test_name)
  75. : FileTestBase(output_mutex, test_name),
  76. component_(GetComponent(test_name)),
  77. installation_(InstallPaths::MakeForBazelRunfiles(exe_path)) {}
  78. auto ToolchainFileTest::GetArgReplacements() -> llvm::StringMap<std::string> {
  79. return {{"core_package_dir", installation_.core_package()}};
  80. }
  81. auto ToolchainFileTest::Run(
  82. const llvm::SmallVector<llvm::StringRef>& test_args,
  83. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  84. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  85. llvm::raw_pwrite_stream& error_stream) -> ErrorOr<RunResult> {
  86. CARBON_ASSIGN_OR_RETURN(auto prelude, installation_.ReadPreludeManifest());
  87. if (!is_no_prelude()) {
  88. for (const auto& file : prelude) {
  89. CARBON_RETURN_IF_ERROR(AddFile(*fs, file));
  90. }
  91. }
  92. Driver driver(fs, &installation_, input_stream, &output_stream,
  93. &error_stream);
  94. auto driver_result = driver.RunCommand(test_args);
  95. // If any diagnostics have been produced, add a trailing newline to make the
  96. // last diagnostic match intermediate diagnostics (that have a newline
  97. // separator between them). This reduces churn when adding new diagnostics
  98. // to test cases.
  99. if (error_stream.tell() > 0) {
  100. error_stream << '\n';
  101. }
  102. RunResult result{
  103. .success = driver_result.success,
  104. .per_file_success = std::move(driver_result.per_file_success)};
  105. // Drop entries that don't look like a file, and entries corresponding to
  106. // the prelude. Note this can empty out the list.
  107. llvm::erase_if(result.per_file_success,
  108. [&](std::pair<llvm::StringRef, bool> entry) {
  109. return entry.first == "." || entry.first == "-" ||
  110. entry.first.starts_with("not_file") ||
  111. llvm::is_contained(prelude, entry.first);
  112. });
  113. if (component_ == "language_server") {
  114. // The language server doesn't always add a suffix newline, so add one for
  115. // tests to be happy.
  116. output_stream << "\n";
  117. }
  118. return result;
  119. }
  120. auto ToolchainFileTest::GetDefaultArgs() -> llvm::SmallVector<std::string> {
  121. llvm::SmallVector<std::string> args = {"--include-diagnostic-kind"};
  122. if (component_ == "format") {
  123. args.insert(args.end(), {"format", "%s"});
  124. return args;
  125. } else if (component_ == "language_server") {
  126. args.insert(args.end(), {"language-server"});
  127. return args;
  128. }
  129. args.insert(args.end(), {"compile", "--phase=" + component_.str()});
  130. if (component_ == "lex") {
  131. args.insert(args.end(), {"--dump-tokens", "--omit-file-boundary-tokens"});
  132. } else if (component_ == "parse") {
  133. args.push_back("--dump-parse-tree");
  134. } else if (component_ == "check") {
  135. args.push_back("--dump-sem-ir");
  136. } else if (component_ == "lower") {
  137. args.push_back("--dump-llvm-ir");
  138. } else {
  139. CARBON_FATAL("Unexpected test component {0}: {1}", component_, test_name());
  140. }
  141. // For `lex` and `parse`, we don't need to import the prelude; exclude it to
  142. // focus errors. In other phases we only do this for explicit "no_prelude"
  143. // tests.
  144. if (component_ == "lex" || component_ == "parse" || is_no_prelude()) {
  145. args.push_back("--no-prelude-import");
  146. }
  147. args.insert(
  148. args.end(),
  149. {"--exclude-dump-file-prefix=" + installation_.core_package(), "%s"});
  150. return args;
  151. }
  152. auto ToolchainFileTest::GetDefaultFileRE(
  153. llvm::ArrayRef<llvm::StringRef> filenames) -> std::optional<RE2> {
  154. if (component_ == "lex") {
  155. return std::make_optional<RE2>(
  156. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  157. }
  158. return FileTestBase::GetDefaultFileRE(filenames);
  159. }
  160. auto ToolchainFileTest::GetLineNumberReplacements(
  161. llvm::ArrayRef<llvm::StringRef> filenames)
  162. -> llvm::SmallVector<LineNumberReplacement> {
  163. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  164. if (component_ == "lex") {
  165. replacements.push_back({.has_file = false,
  166. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  167. // The `{{{{` becomes `{{`.
  168. .line_formatv = "{{{{ *}}{0}"});
  169. }
  170. return replacements;
  171. }
  172. auto ToolchainFileTest::DoExtraCheckReplacements(std::string& check_line)
  173. -> void {
  174. if (component_ == "driver") {
  175. // TODO: Disable token output, it's not interesting for these tests.
  176. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  177. check_line = "// CHECK:STDOUT: {{.*}}";
  178. }
  179. } else if (component_ == "lex") {
  180. // Both FileStart and FileEnd regularly have locations on CHECK
  181. // comment lines that don't work correctly. The line happens to be correct
  182. // for the FileEnd, but we need to avoid checking the column.
  183. // The column happens to be right for FileStart, but the line is wrong.
  184. static RE2 file_token_re(R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  185. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  186. } else {
  187. FileTestBase::DoExtraCheckReplacements(check_line);
  188. }
  189. }
  190. auto ToolchainFileTest::AddFile(llvm::vfs::InMemoryFileSystem& fs,
  191. llvm::StringRef path) -> ErrorOr<Success> {
  192. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file =
  193. llvm::MemoryBuffer::getFile(path);
  194. if (file.getError()) {
  195. return ErrorBuilder() << "Getting `" << path
  196. << "`: " << file.getError().message();
  197. }
  198. if (!fs.addFile(path, /*ModificationTime=*/0, std::move(*file))) {
  199. return ErrorBuilder() << "Duplicate file: `" << path << "`";
  200. }
  201. return Success();
  202. }
  203. } // namespace Carbon::Testing
  204. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_