file_test.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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 <memory>
  8. #include <optional>
  9. #include <string>
  10. #include <utility>
  11. #include "absl/strings/str_replace.h"
  12. #include "common/error.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/SmallVector.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/Support/FormatVariadic.h"
  17. #include "llvm/Support/VirtualFileSystem.h"
  18. #include "testing/file_test/file_test_base.h"
  19. #include "toolchain/driver/driver.h"
  20. namespace Carbon::Testing {
  21. namespace {
  22. // Provides common test support for the driver. This is used by file tests in
  23. // component subdirectories.
  24. class ToolchainFileTest : public FileTestBase {
  25. public:
  26. explicit ToolchainFileTest(llvm::StringRef exe_path,
  27. llvm::StringRef test_name);
  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. // The toolchain component subdirectory, such as `lex` or `language_server`.
  52. const llvm::StringRef component_;
  53. // The toolchain install information.
  54. const InstallPaths installation_;
  55. };
  56. } // namespace
  57. CARBON_FILE_TEST_FACTORY(ToolchainFileTest)
  58. // Returns the toolchain subdirectory being tested.
  59. static auto GetComponent(llvm::StringRef test_name) -> llvm::StringRef {
  60. // This handles cases where the toolchain directory may be copied into a
  61. // repository that doesn't put it at the root.
  62. auto pos = test_name.find("toolchain/");
  63. CARBON_CHECK(pos != llvm::StringRef::npos, "{0}", test_name);
  64. test_name = test_name.drop_front(pos + strlen("toolchain/"));
  65. test_name = test_name.take_front(test_name.find("/"));
  66. return test_name;
  67. }
  68. ToolchainFileTest::ToolchainFileTest(llvm::StringRef exe_path,
  69. llvm::StringRef test_name)
  70. : FileTestBase(test_name),
  71. component_(GetComponent(test_name)),
  72. installation_(InstallPaths::MakeForBazelRunfiles(exe_path)) {}
  73. // Adds a file to the fs.
  74. static auto AddFile(llvm::vfs::InMemoryFileSystem& fs, llvm::StringRef path)
  75. -> ErrorOr<Success> {
  76. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file =
  77. llvm::MemoryBuffer::getFile(path);
  78. if (file.getError()) {
  79. return ErrorBuilder() << "Getting `" << path
  80. << "`: " << file.getError().message();
  81. }
  82. if (!fs.addFile(path, /*ModificationTime=*/0, std::move(*file))) {
  83. return ErrorBuilder() << "Duplicate file: `" << path << "`";
  84. }
  85. return Success();
  86. }
  87. auto ToolchainFileTest::Run(
  88. const llvm::SmallVector<llvm::StringRef>& test_args,
  89. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  90. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  91. llvm::raw_pwrite_stream& error_stream) const -> ErrorOr<RunResult> {
  92. llvm::SmallVector<std::string> prelude_files;
  93. // Lex and parse shouldn't ever access the prelude.
  94. if (component_ != "lex" && component_ != "parse") {
  95. // TODO: Try providing the prelude as an overlay.
  96. CARBON_ASSIGN_OR_RETURN(prelude_files, installation_.ReadPreludeManifest());
  97. for (const auto& file : prelude_files) {
  98. CARBON_RETURN_IF_ERROR(AddFile(*fs, file));
  99. }
  100. }
  101. llvm::SmallVector<llvm::StringRef> filtered_test_args;
  102. if (component_ == "check" || component_ == "lower") {
  103. filtered_test_args.reserve(test_args.size());
  104. bool found_prelude_flag = false;
  105. for (auto arg : test_args) {
  106. bool driver_flag = arg == "--custom-core" || arg == "--no-prelude-import";
  107. // A flag specified by a test prelude to indicate the intention to include
  108. // the full production prelude.
  109. bool full_prelude = arg == "--expect-full-prelude";
  110. if (driver_flag || full_prelude) {
  111. found_prelude_flag = true;
  112. }
  113. if (!full_prelude) {
  114. filtered_test_args.push_back(arg);
  115. }
  116. }
  117. if (!found_prelude_flag) {
  118. // TODO: Enable this error when all check/ and lower/ tests include a
  119. // prelude choice explicitly.
  120. // return Error(
  121. // "Include a prelude from //toolchain/testing/testdata/min_prelude "
  122. // "to specify what should be imported into the test.");
  123. }
  124. } else {
  125. filtered_test_args = test_args;
  126. }
  127. Driver driver(fs, &installation_, input_stream, &output_stream,
  128. &error_stream);
  129. auto driver_result = driver.RunCommand(filtered_test_args);
  130. // If any diagnostics have been produced, add a trailing newline to make the
  131. // last diagnostic match intermediate diagnostics (that have a newline
  132. // separator between them). This reduces churn when adding new diagnostics
  133. // to test cases.
  134. if (error_stream.tell() > 0) {
  135. error_stream << '\n';
  136. }
  137. RunResult result{
  138. .success = driver_result.success,
  139. .per_file_success = std::move(driver_result.per_file_success)};
  140. // Drop entries that don't look like a file, and entries corresponding to
  141. // the prelude. Note this can empty out the list.
  142. llvm::erase_if(result.per_file_success,
  143. [&](std::pair<llvm::StringRef, bool> entry) {
  144. return entry.first == "." || entry.first == "-" ||
  145. entry.first.starts_with("not_file") ||
  146. llvm::is_contained(prelude_files, entry.first);
  147. });
  148. if (component_ == "language_server") {
  149. // The language server doesn't always add a suffix newline, so add one for
  150. // tests to be happy.
  151. output_stream << "\n";
  152. }
  153. return result;
  154. }
  155. auto ToolchainFileTest::GetDefaultArgs() const
  156. -> llvm::SmallVector<std::string> {
  157. llvm::SmallVector<std::string> args = {"--include-diagnostic-kind"};
  158. if (component_ == "format") {
  159. args.insert(args.end(), {"format", "%s"});
  160. return args;
  161. } else if (component_ == "language_server") {
  162. args.insert(args.end(), {"language-server"});
  163. return args;
  164. }
  165. args.insert(args.end(),
  166. {
  167. "compile",
  168. "--phase=" + component_.str(),
  169. // Use the install path to exclude prelude files.
  170. "--exclude-dump-file-prefix=" + installation_.core_package(),
  171. });
  172. if (component_ == "lex") {
  173. args.insert(args.end(), {"--no-prelude-import", "--dump-tokens",
  174. "--omit-file-boundary-tokens"});
  175. } else if (component_ == "parse") {
  176. args.insert(args.end(), {"--no-prelude-import", "--dump-parse-tree"});
  177. } else if (component_ == "check") {
  178. args.insert(args.end(), {"--dump-sem-ir", "--dump-sem-ir-ranges=only"});
  179. } else if (component_ == "lower") {
  180. args.insert(args.end(), {"--dump-llvm-ir", "--target=x86_64-linux-gnu"});
  181. } else if (component_ == "codegen") {
  182. // codegen tests specify flags as needed.
  183. } else {
  184. CARBON_FATAL("Unexpected test component {0}: {1}", component_, test_name());
  185. }
  186. args.push_back("%s");
  187. return args;
  188. }
  189. auto ToolchainFileTest::GetDefaultFileRE(
  190. llvm::ArrayRef<llvm::StringRef> filenames) const -> std::optional<RE2> {
  191. if (component_ == "lex") {
  192. return std::make_optional<RE2>(
  193. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  194. }
  195. return FileTestBase::GetDefaultFileRE(filenames);
  196. }
  197. auto ToolchainFileTest::GetLineNumberReplacements(
  198. llvm::ArrayRef<llvm::StringRef> filenames) const
  199. -> llvm::SmallVector<LineNumberReplacement> {
  200. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  201. if (component_ == "lex") {
  202. replacements.push_back({.has_file = false,
  203. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  204. // The `{{{{` becomes `{{`.
  205. .line_formatv = "{{{{ *}}{0}"});
  206. }
  207. return replacements;
  208. }
  209. auto ToolchainFileTest::DoExtraCheckReplacements(std::string& check_line) const
  210. -> void {
  211. if (component_ == "driver") {
  212. // TODO: Disable token output, it's not interesting for these tests.
  213. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  214. check_line = "// CHECK:STDOUT: {{.*}}";
  215. }
  216. } else if (component_ == "lex") {
  217. // Both FileStart and FileEnd regularly have locations on CHECK
  218. // comment lines that don't work correctly. The line happens to be correct
  219. // for the FileEnd, but we need to avoid checking the column.
  220. // The column happens to be right for FileStart, but the line is wrong.
  221. static RE2 file_token_re(R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  222. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  223. } else if (component_ == "check" || component_ == "lower") {
  224. // The path to the core package appears in some check diagnostics and in
  225. // debug information produced by lowering, and will differ between testing
  226. // environments, so don't test it.
  227. // TODO: Consider adding a content keyword to name the core package, and
  228. // replace with that instead. Alternatively, consider adding the core
  229. // package to the VFS with a fixed name.
  230. absl::StrReplaceAll({{installation_.core_package(), "{{.*}}"}},
  231. &check_line);
  232. } else {
  233. FileTestBase::DoExtraCheckReplacements(check_line);
  234. }
  235. }
  236. } // namespace Carbon::Testing
  237. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_