file_test.cpp 14 KB

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