file_test.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. return Error(
  143. "Include a prelude from //toolchain/testing/testdata/min_prelude "
  144. "to specify what should be imported into the test.");
  145. }
  146. } else {
  147. filtered_test_args = test_args;
  148. }
  149. Driver driver(overlay_fs, &data_->installation, input_stream, &output_stream,
  150. &error_stream);
  151. auto driver_result = driver.RunCommand(filtered_test_args);
  152. // If any diagnostics have been produced, add a trailing newline to make the
  153. // last diagnostic match intermediate diagnostics (that have a newline
  154. // separator between them). This reduces churn when adding new diagnostics
  155. // to test cases.
  156. if (error_stream.tell() > 0) {
  157. error_stream << '\n';
  158. }
  159. RunResult result{
  160. .success = driver_result.success,
  161. .per_file_success = std::move(driver_result.per_file_success)};
  162. // Drop entries that don't look like a file, and entries corresponding to
  163. // the prelude. Note this can empty out the list.
  164. llvm::erase_if(result.per_file_success,
  165. [&](std::pair<llvm::StringRef, bool> entry) {
  166. return entry.first == "." || entry.first == "-" ||
  167. entry.first.starts_with("not_file") ||
  168. llvm::is_contained(data_->prelude_files, entry.first);
  169. });
  170. if (component_ == "language_server") {
  171. // The language server doesn't always add a suffix newline, so add one for
  172. // tests to be happy.
  173. output_stream << "\n";
  174. }
  175. return result;
  176. }
  177. auto ToolchainFileTest::GetDefaultArgs() const
  178. -> llvm::SmallVector<std::string> {
  179. llvm::SmallVector<std::string> args = {"--include-diagnostic-kind"};
  180. if (component_ == "format") {
  181. args.insert(args.end(), {"format", "%s"});
  182. return args;
  183. } else if (component_ == "language_server") {
  184. args.insert(args.end(), {"language-server"});
  185. return args;
  186. }
  187. args.insert(args.end(), {
  188. "compile",
  189. "--phase=" + component_.str(),
  190. // Use the install path to exclude prelude files.
  191. "--exclude-dump-file-prefix=" +
  192. data_->installation.core_package(),
  193. });
  194. if (component_ == "lex") {
  195. args.insert(args.end(), {"--no-prelude-import", "--dump-tokens",
  196. "--omit-file-boundary-tokens"});
  197. } else if (component_ == "parse") {
  198. args.insert(args.end(), {"--no-prelude-import", "--dump-parse-tree"});
  199. } else if (component_ == "check") {
  200. args.insert(args.end(), {"--dump-sem-ir", "--dump-sem-ir-ranges=only"});
  201. } else if (component_ == "lower") {
  202. args.insert(args.end(), {"--dump-llvm-ir", "--target=x86_64-linux-gnu"});
  203. } else if (component_ == "codegen") {
  204. // codegen tests specify flags as needed.
  205. } else {
  206. CARBON_FATAL("Unexpected test component {0}: {1}", component_, test_name());
  207. }
  208. args.push_back("%s");
  209. return args;
  210. }
  211. auto ToolchainFileTest::GetDefaultFileRE(
  212. llvm::ArrayRef<llvm::StringRef> filenames) const -> std::optional<RE2> {
  213. if (component_ == "lex") {
  214. return std::make_optional<RE2>(
  215. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  216. }
  217. return FileTestBase::GetDefaultFileRE(filenames);
  218. }
  219. auto ToolchainFileTest::GetLineNumberReplacements(
  220. llvm::ArrayRef<llvm::StringRef> filenames) const
  221. -> llvm::SmallVector<LineNumberReplacement> {
  222. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  223. if (component_ == "lex") {
  224. replacements.push_back({.has_file = false,
  225. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  226. // The `{{{{` becomes `{{`.
  227. .line_formatv = "{{{{ *}}{0}"});
  228. }
  229. return replacements;
  230. }
  231. auto ToolchainFileTest::DoExtraCheckReplacements(std::string& check_line) const
  232. -> void {
  233. if (component_ == "driver") {
  234. // TODO: Disable token output, it's not interesting for these tests.
  235. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  236. check_line = "// CHECK:STDOUT: {{.*}}";
  237. }
  238. } else if (component_ == "lex") {
  239. // Both FileStart and FileEnd regularly have locations on CHECK
  240. // comment lines that don't work correctly. The line happens to be correct
  241. // for the FileEnd, but we need to avoid checking the column.
  242. // The column happens to be right for FileStart, but the line is wrong.
  243. static RE2 file_token_re(R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  244. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  245. } else if (component_ == "check" || component_ == "lower") {
  246. // The path to the core package appears in some check diagnostics and in
  247. // debug information produced by lowering, and will differ between testing
  248. // environments, so don't test it.
  249. // TODO: Consider adding a content keyword to name the core package, and
  250. // replace with that instead. Alternatively, consider adding the core
  251. // package to the VFS with a fixed name.
  252. absl::StrReplaceAll({{data_->installation.core_package(), "{{.*}}"}},
  253. &check_line);
  254. } else {
  255. FileTestBase::DoExtraCheckReplacements(check_line);
  256. }
  257. }
  258. } // namespace Carbon::Testing
  259. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_