file_test.cpp 9.5 KB

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