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