file_test.cpp 12 KB

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