file_test.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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,
  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. llvm::StringRef test_name)
  74. : FileTestBase(test_name),
  75. component_(GetComponent(test_name)),
  76. installation_(InstallPaths::MakeForBazelRunfiles(exe_path)) {}
  77. auto ToolchainFileTest::GetArgReplacements() -> llvm::StringMap<std::string> {
  78. return {{"core_package_dir", installation_.core_package()}};
  79. }
  80. auto ToolchainFileTest::Run(
  81. const llvm::SmallVector<llvm::StringRef>& test_args,
  82. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  83. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  84. llvm::raw_pwrite_stream& error_stream) -> ErrorOr<RunResult> {
  85. CARBON_ASSIGN_OR_RETURN(auto prelude, installation_.ReadPreludeManifest());
  86. if (!is_no_prelude()) {
  87. for (const auto& file : prelude) {
  88. CARBON_RETURN_IF_ERROR(AddFile(*fs, file));
  89. }
  90. }
  91. Driver driver(fs, &installation_, input_stream, &output_stream,
  92. &error_stream);
  93. auto driver_result = driver.RunCommand(test_args);
  94. // If any diagnostics have been produced, add a trailing newline to make the
  95. // last diagnostic match intermediate diagnostics (that have a newline
  96. // separator between them). This reduces churn when adding new diagnostics
  97. // to test cases.
  98. if (error_stream.tell() > 0) {
  99. error_stream << '\n';
  100. }
  101. RunResult result{
  102. .success = driver_result.success,
  103. .per_file_success = std::move(driver_result.per_file_success)};
  104. // Drop entries that don't look like a file, and entries corresponding to
  105. // the prelude. Note this can empty out the list.
  106. llvm::erase_if(result.per_file_success,
  107. [&](std::pair<llvm::StringRef, bool> entry) {
  108. return entry.first == "." || entry.first == "-" ||
  109. entry.first.starts_with("not_file") ||
  110. llvm::is_contained(prelude, entry.first);
  111. });
  112. if (component_ == "language_server") {
  113. // The language server doesn't always add a suffix newline, so add one for
  114. // tests to be happy.
  115. output_stream << "\n";
  116. }
  117. return result;
  118. }
  119. auto ToolchainFileTest::GetDefaultArgs() -> llvm::SmallVector<std::string> {
  120. llvm::SmallVector<std::string> args = {"--include-diagnostic-kind"};
  121. if (component_ == "format") {
  122. args.insert(args.end(), {"format", "%s"});
  123. return args;
  124. } else if (component_ == "language_server") {
  125. args.insert(args.end(), {"language-server"});
  126. return args;
  127. }
  128. args.insert(args.end(), {"compile", "--phase=" + component_.str()});
  129. if (component_ == "lex") {
  130. args.insert(args.end(), {"--dump-tokens", "--omit-file-boundary-tokens"});
  131. } else if (component_ == "parse") {
  132. args.push_back("--dump-parse-tree");
  133. } else if (component_ == "check") {
  134. args.push_back("--dump-sem-ir");
  135. } else if (component_ == "lower") {
  136. args.push_back("--dump-llvm-ir");
  137. } else {
  138. CARBON_FATAL("Unexpected test component {0}: {1}", component_, test_name());
  139. }
  140. // For `lex` and `parse`, we don't need to import the prelude; exclude it to
  141. // focus errors. In other phases we only do this for explicit "no_prelude"
  142. // tests.
  143. if (component_ == "lex" || component_ == "parse" || is_no_prelude()) {
  144. args.push_back("--no-prelude-import");
  145. }
  146. args.insert(
  147. args.end(),
  148. {"--exclude-dump-file-prefix=" + installation_.core_package(), "%s"});
  149. return args;
  150. }
  151. auto ToolchainFileTest::GetDefaultFileRE(
  152. llvm::ArrayRef<llvm::StringRef> filenames) -> std::optional<RE2> {
  153. if (component_ == "lex") {
  154. return std::make_optional<RE2>(
  155. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  156. }
  157. return FileTestBase::GetDefaultFileRE(filenames);
  158. }
  159. auto ToolchainFileTest::GetLineNumberReplacements(
  160. llvm::ArrayRef<llvm::StringRef> filenames)
  161. -> llvm::SmallVector<LineNumberReplacement> {
  162. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  163. if (component_ == "lex") {
  164. replacements.push_back({.has_file = false,
  165. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  166. // The `{{{{` becomes `{{`.
  167. .line_formatv = "{{{{ *}}{0}"});
  168. }
  169. return replacements;
  170. }
  171. auto ToolchainFileTest::DoExtraCheckReplacements(std::string& check_line)
  172. -> void {
  173. if (component_ == "driver") {
  174. // TODO: Disable token output, it's not interesting for these tests.
  175. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  176. check_line = "// CHECK:STDOUT: {{.*}}";
  177. }
  178. } else if (component_ == "lex") {
  179. // Both FileStart and FileEnd regularly have locations on CHECK
  180. // comment lines that don't work correctly. The line happens to be correct
  181. // for the FileEnd, but we need to avoid checking the column.
  182. // The column happens to be right for FileStart, but the line is wrong.
  183. static RE2 file_token_re(R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  184. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  185. } else {
  186. FileTestBase::DoExtraCheckReplacements(check_line);
  187. }
  188. }
  189. auto ToolchainFileTest::AddFile(llvm::vfs::InMemoryFileSystem& fs,
  190. llvm::StringRef path) -> ErrorOr<Success> {
  191. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file =
  192. llvm::MemoryBuffer::getFile(path);
  193. if (file.getError()) {
  194. return ErrorBuilder() << "Getting `" << path
  195. << "`: " << file.getError().message();
  196. }
  197. if (!fs.addFile(path, /*ModificationTime=*/0, std::move(*file))) {
  198. return ErrorBuilder() << "Duplicate file: `" << path << "`";
  199. }
  200. return Success();
  201. }
  202. } // namespace Carbon::Testing
  203. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_