file_test.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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/autoupdate.h"
  19. #include "testing/file_test/file_test_base.h"
  20. #include "toolchain/driver/driver.h"
  21. namespace Carbon::Testing {
  22. namespace {
  23. // Adds a file to the fs.
  24. static auto AddFile(llvm::vfs::InMemoryFileSystem& fs, llvm::StringRef path)
  25. -> ErrorOr<Success> {
  26. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file =
  27. llvm::MemoryBuffer::getFile(path);
  28. if (file.getError()) {
  29. return ErrorBuilder() << "Getting `" << path
  30. << "`: " << file.getError().message();
  31. }
  32. if (!fs.addFile(path, /*ModificationTime=*/0, std::move(*file))) {
  33. return ErrorBuilder() << "Duplicate file: `" << path << "`";
  34. }
  35. return Success();
  36. }
  37. struct SharedTestData {
  38. // The toolchain install information.
  39. InstallPaths installation;
  40. // Files in the prelude.
  41. llvm::SmallVector<std::string> prelude_files;
  42. // The installed files that tests can use.
  43. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> file_system =
  44. new llvm::vfs::InMemoryFileSystem();
  45. };
  46. static auto GetSharedTestData(llvm::StringRef exe_path)
  47. -> const SharedTestData* {
  48. static ErrorOr<SharedTestData> data = [&]() -> ErrorOr<SharedTestData> {
  49. SharedTestData data = {.installation =
  50. InstallPaths::MakeForBazelRunfiles(exe_path)};
  51. CARBON_ASSIGN_OR_RETURN(data.prelude_files,
  52. data.installation.ReadPreludeManifest());
  53. for (const auto& file : data.prelude_files) {
  54. CARBON_RETURN_IF_ERROR(AddFile(*data.file_system, file));
  55. }
  56. llvm::SmallVector<std::string> clang_header_files;
  57. CARBON_ASSIGN_OR_RETURN(clang_header_files,
  58. data.installation.ReadClangHeadersManifest());
  59. for (const auto& file : clang_header_files) {
  60. CARBON_RETURN_IF_ERROR(AddFile(*data.file_system, file));
  61. }
  62. return data;
  63. }();
  64. CARBON_CHECK(data.ok(), "{0}", data.error());
  65. return &*data;
  66. }
  67. // Provides common test support for the driver. This is used by file tests in
  68. // component subdirectories.
  69. class ToolchainFileTest : public FileTestBase {
  70. public:
  71. explicit ToolchainFileTest(llvm::StringRef exe_path,
  72. llvm::StringRef test_name);
  73. // Loads files into the VFS and runs the driver.
  74. auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  75. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  76. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  77. llvm::raw_pwrite_stream& error_stream) const
  78. -> ErrorOr<RunResult> override;
  79. // Sets different default flags based on the component being tested.
  80. auto GetDefaultArgs() const -> llvm::SmallVector<std::string> override;
  81. // Returns string replacements to implement `%{key}` -> `value` in arguments.
  82. auto GetArgReplacements() const -> llvm::StringMap<std::string> override {
  83. return {{"core", data_->installation.core_package().native()}};
  84. }
  85. // Generally uses the parent implementation, with special handling for lex.
  86. auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> filenames) const
  87. -> std::optional<RE2> override;
  88. // Generally uses the parent implementation, with special handling for lex.
  89. auto GetLineNumberReplacements(llvm::ArrayRef<llvm::StringRef> filenames)
  90. const -> llvm::SmallVector<LineNumberReplacement> override;
  91. // Generally uses the parent implementation, with special handling for lex and
  92. // driver.
  93. auto DoExtraCheckReplacements(std::string& check_line) const -> void override;
  94. // Do some final tweaks to check line locations.
  95. auto FinalizeCheckLines(CheckLineArray& check_lines, bool is_stderr) const
  96. -> void override;
  97. // Most tests can be run in parallel, but clangd has a global for its logging
  98. // system so we need language-server tests to be run in serial.
  99. auto AllowParallelRun() const -> bool override {
  100. return component_ != "language_server";
  101. }
  102. private:
  103. // The toolchain component subdirectory, such as `lex` or `language_server`.
  104. const llvm::StringRef component_;
  105. // The shared test data.
  106. const SharedTestData* data_;
  107. };
  108. } // namespace
  109. CARBON_FILE_TEST_FACTORY(ToolchainFileTest)
  110. // Returns the toolchain subdirectory being tested.
  111. static auto GetComponent(llvm::StringRef test_name) -> llvm::StringRef {
  112. // This handles cases where the toolchain directory may be copied into a
  113. // repository that doesn't put it at the root.
  114. auto pos = test_name.find("toolchain/");
  115. CARBON_CHECK(pos != llvm::StringRef::npos, "{0}", test_name);
  116. test_name = test_name.drop_front(pos + strlen("toolchain/"));
  117. test_name = test_name.take_front(test_name.find("/"));
  118. return test_name;
  119. }
  120. ToolchainFileTest::ToolchainFileTest(llvm::StringRef exe_path,
  121. llvm::StringRef test_name)
  122. : FileTestBase(test_name),
  123. component_(GetComponent(test_name)),
  124. data_(GetSharedTestData(exe_path)) {}
  125. auto ToolchainFileTest::Run(
  126. const llvm::SmallVector<llvm::StringRef>& test_args,
  127. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  128. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  129. llvm::raw_pwrite_stream& error_stream) const -> ErrorOr<RunResult> {
  130. llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem> overlay_fs =
  131. new llvm::vfs::OverlayFileSystem(data_->file_system);
  132. overlay_fs->pushOverlay(fs);
  133. llvm::SmallVector<llvm::StringRef> filtered_test_args;
  134. if (component_ == "check" || component_ == "lower") {
  135. filtered_test_args.reserve(test_args.size());
  136. bool found_prelude_flag = false;
  137. for (auto arg : test_args) {
  138. bool driver_flag = arg == "--custom-core" || arg == "--no-prelude-import";
  139. // A flag specified by a test prelude to indicate the intention to include
  140. // the full production prelude.
  141. bool full_prelude = arg == "--expect-full-prelude";
  142. if (driver_flag || full_prelude) {
  143. found_prelude_flag = true;
  144. }
  145. if (!full_prelude) {
  146. filtered_test_args.push_back(arg);
  147. }
  148. }
  149. if (!found_prelude_flag) {
  150. return Error(
  151. "Include a prelude from //toolchain/testing/testdata/min_prelude "
  152. "to specify what should be imported into the test.");
  153. }
  154. } else {
  155. filtered_test_args = test_args;
  156. }
  157. Driver driver(overlay_fs, &data_->installation, input_stream, &output_stream,
  158. &error_stream);
  159. auto driver_result = driver.RunCommand(filtered_test_args);
  160. // If any diagnostics have been produced, add a trailing newline to make the
  161. // last diagnostic match intermediate diagnostics (that have a newline
  162. // separator between them). This reduces churn when adding new diagnostics
  163. // to test cases.
  164. if (error_stream.tell() > 0) {
  165. error_stream << '\n';
  166. }
  167. RunResult result{
  168. .success = driver_result.success,
  169. .per_file_success = std::move(driver_result.per_file_success)};
  170. // Drop entries that don't look like a file, and entries corresponding to
  171. // the prelude. Note this can empty out the list.
  172. llvm::erase_if(result.per_file_success,
  173. [&](std::pair<llvm::StringRef, bool> entry) {
  174. return entry.first == "." || entry.first == "-" ||
  175. entry.first.starts_with("not_file") ||
  176. llvm::is_contained(data_->prelude_files, entry.first);
  177. });
  178. if (component_ == "language_server") {
  179. // The language server doesn't always add a suffix newline, so add one for
  180. // tests to be happy.
  181. output_stream << "\n";
  182. }
  183. return result;
  184. }
  185. auto ToolchainFileTest::GetDefaultArgs() const
  186. -> llvm::SmallVector<std::string> {
  187. llvm::SmallVector<std::string> args = {"--include-diagnostic-kind"};
  188. if (component_ == "format") {
  189. args.insert(args.end(), {"format", "%s"});
  190. return args;
  191. } else if (component_ == "language_server") {
  192. args.insert(args.end(), {"language-server"});
  193. return args;
  194. }
  195. args.insert(args.end(), {
  196. "compile",
  197. "--phase=" + component_.str(),
  198. // Use the install path to exclude prelude files.
  199. "--exclude-dump-file-prefix=" +
  200. data_->installation.core_package().native(),
  201. });
  202. if (component_ == "lex") {
  203. args.insert(args.end(), {"--no-prelude-import", "--dump-tokens",
  204. "--omit-file-boundary-tokens"});
  205. } else if (component_ == "parse") {
  206. args.insert(args.end(), {"--no-prelude-import", "--dump-parse-tree"});
  207. } else if (component_ == "check") {
  208. args.insert(args.end(), {"--dump-sem-ir", "--dump-sem-ir-ranges=only"});
  209. } else if (component_ == "lower") {
  210. args.insert(args.end(), {"--dump-llvm-ir", "--target=x86_64-linux-gnu"});
  211. } else if (component_ == "codegen") {
  212. // codegen tests specify flags as needed.
  213. } else {
  214. CARBON_FATAL("Unexpected test component {0}: {1}", component_, test_name());
  215. }
  216. args.push_back("%s");
  217. return args;
  218. }
  219. auto ToolchainFileTest::GetDefaultFileRE(
  220. llvm::ArrayRef<llvm::StringRef> filenames) const -> std::optional<RE2> {
  221. if (component_ == "lex") {
  222. return std::make_optional<RE2>(
  223. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  224. }
  225. return FileTestBase::GetDefaultFileRE(filenames);
  226. }
  227. auto ToolchainFileTest::GetLineNumberReplacements(
  228. llvm::ArrayRef<llvm::StringRef> filenames) const
  229. -> llvm::SmallVector<LineNumberReplacement> {
  230. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  231. if (component_ == "lex") {
  232. replacements.push_back({.has_file = false,
  233. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  234. // The `{{{{` becomes `{{`.
  235. .line_formatv = "{{{{ *}}{0}"});
  236. }
  237. return replacements;
  238. }
  239. // For Clang AST dump lines, we remove references to builtins because they're
  240. // inconsistent between systems and replace the ids since they're inconsistent
  241. // between runs.
  242. static auto DoClangASTCheckReplacements(std::string& check_line) -> void {
  243. static constexpr llvm::StringRef ClangDeclIdRegex = "0x[a-f0-9]+";
  244. static const RE2 is_clang_ast_line_re(
  245. R"(^// CHECK:STDOUT: (TranslationUnitDecl|[ |]*`?\-))");
  246. if (!RE2::PartialMatch(check_line, is_clang_ast_line_re)) {
  247. return;
  248. }
  249. // Filter out references to builtins.
  250. static const RE2 is_builtin_referring_re(
  251. R"(`-BuiltinType |[ ']__[a-zA-Z]|\| `\-PointerType 0x[a-f0-9]+ 'char \*'$)");
  252. if (RE2::PartialMatch(check_line, is_builtin_referring_re)) {
  253. check_line.clear();
  254. return;
  255. }
  256. // Replace the ids.
  257. static const RE2 clang_decl_id_re(llvm::formatv(" {0} ", ClangDeclIdRegex));
  258. static const std::string& clang_decl_id_replacement =
  259. *new std::string(llvm::formatv(" {{{{{0}}} ", ClangDeclIdRegex));
  260. RE2::GlobalReplace(&check_line, clang_decl_id_re, clang_decl_id_replacement);
  261. }
  262. auto ToolchainFileTest::DoExtraCheckReplacements(std::string& check_line) const
  263. -> void {
  264. // The path to the core package appears in various places, such as some check
  265. // diagnostics and debug information produced by lowering, and will differ
  266. // between testing environments, so don't test it.
  267. // TODO: Consider adding a content keyword to name the core package, and
  268. // replace with that instead. Alternatively, consider adding the core
  269. // package to the VFS with a fixed name.
  270. absl::StrReplaceAll({{data_->installation.core_package().native(), "{{.*}}"}},
  271. &check_line);
  272. if (component_ == "driver") {
  273. // TODO: Disable token output, it's not interesting for these tests.
  274. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  275. check_line = "// CHECK:STDOUT: {{.*}}";
  276. }
  277. } else if (component_ == "lex") {
  278. // Both FileStart and FileEnd regularly have locations on CHECK
  279. // comment lines that don't work correctly. The line happens to be correct
  280. // for the FileEnd, but we need to avoid checking the column.
  281. // The column happens to be right for FileStart, but the line is wrong.
  282. static RE2 file_token_re(R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  283. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  284. } else if (component_ == "check") {
  285. DoClangASTCheckReplacements(check_line);
  286. // Reduce instruction numbering sensitivity; this is brittle for
  287. // instruction edits including adding/removing singleton instructions.
  288. static RE2 inst_re(
  289. R"(((?:import_ref [^,]*, |<unexpected>\.)inst)[0-9A-F]+)");
  290. RE2::Replace(&check_line, inst_re, R"(\1{{[0-9A-F]+}})");
  291. // Reduce location sensitivity in imports referring to `Core`; this is
  292. // brittle for small edits, including comment changes.
  293. static RE2 core_loc_re(R"((import_ref Core//[^,]*, loc)\d+_\d+)");
  294. RE2::Replace(&check_line, core_loc_re, R"(\1{{\\d+_\\d+}})");
  295. } else {
  296. FileTestBase::DoExtraCheckReplacements(check_line);
  297. }
  298. }
  299. auto ToolchainFileTest::FinalizeCheckLines(CheckLineArray& check_lines,
  300. bool is_stderr) const -> void {
  301. if (is_stderr) {
  302. static const RE2 is_new_diagnostic_re(R"(.*:\d*:\d*: (error|warning): )");
  303. // If a diagnostic isn't attached to a line, try to position it with its
  304. // first note.
  305. FileTestAutoupdater::CheckLine* diagnostic_without_loc = nullptr;
  306. for (auto& check_line : check_lines) {
  307. bool has_loc = check_line.line_number() != -1;
  308. if (RE2::PartialMatch(check_line.line(), is_new_diagnostic_re)) {
  309. diagnostic_without_loc = has_loc ? nullptr : &check_line;
  310. } else if (has_loc && diagnostic_without_loc) {
  311. diagnostic_without_loc->set_location(check_line.file_number(),
  312. check_line.line_number());
  313. diagnostic_without_loc = nullptr;
  314. }
  315. }
  316. }
  317. }
  318. } // namespace Carbon::Testing
  319. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_