file_test.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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 <string>
  7. #include "common/error.h"
  8. #include "llvm/ADT/STLExtras.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/ADT/StringRef.h"
  11. #include "llvm/Support/FormatVariadic.h"
  12. #include "llvm/Support/VirtualFileSystem.h"
  13. #include "testing/file_test/file_test_base.h"
  14. #include "toolchain/driver/driver.h"
  15. namespace Carbon::Testing {
  16. namespace {
  17. // Provides common test support for the driver. This is used by file tests in
  18. // phase subdirectories.
  19. class ToolchainFileTest : public FileTestBase {
  20. public:
  21. explicit ToolchainFileTest(llvm::StringRef exe_path, std::mutex* output_mutex,
  22. llvm::StringRef test_name)
  23. : FileTestBase(output_mutex, test_name),
  24. component_(GetComponent(test_name)),
  25. installation_(InstallPaths::MakeForBazelRunfiles(exe_path)) {}
  26. auto GetArgReplacements() -> llvm::StringMap<std::string> override {
  27. return {{"core_package_dir", installation_.core_package()}};
  28. }
  29. auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  30. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  31. llvm::raw_pwrite_stream& stdout, llvm::raw_pwrite_stream& stderr)
  32. -> ErrorOr<RunResult> override {
  33. CARBON_ASSIGN_OR_RETURN(auto prelude, installation_.ReadPreludeManifest());
  34. if (!is_no_prelude()) {
  35. for (const auto& file : prelude) {
  36. CARBON_RETURN_IF_ERROR(AddFile(*fs, file));
  37. }
  38. }
  39. Driver driver(fs, &installation_, stdout, stderr);
  40. auto driver_result = driver.RunCommand(test_args);
  41. RunResult result{
  42. .success = driver_result.success,
  43. .per_file_success = std::move(driver_result.per_file_success)};
  44. // Drop entries that don't look like a file, and entries corresponding to
  45. // the prelude. Note this can empty out the list.
  46. llvm::erase_if(result.per_file_success,
  47. [&](std::pair<llvm::StringRef, bool> entry) {
  48. return entry.first == "." || entry.first == "-" ||
  49. entry.first.starts_with("not_file") ||
  50. llvm::is_contained(prelude, entry.first);
  51. });
  52. return result;
  53. }
  54. auto GetDefaultArgs() -> llvm::SmallVector<std::string> override {
  55. if (component_ == "format") {
  56. return {"format", "%s"};
  57. }
  58. llvm::SmallVector<std::string> args = {
  59. "compile", "--include-diagnostic-kind", "--phase=" + component_.str()};
  60. if (component_ == "lex") {
  61. args.insert(args.end(), {"--dump-tokens", "--omit-file-boundary-tokens"});
  62. } else if (component_ == "parse") {
  63. args.push_back("--dump-parse-tree");
  64. } else if (component_ == "check") {
  65. args.push_back("--dump-sem-ir");
  66. } else if (component_ == "lower") {
  67. args.push_back("--dump-llvm-ir");
  68. } else {
  69. CARBON_FATAL("Unexpected test component {0}: {1}", component_,
  70. test_name());
  71. }
  72. // For `lex` and `parse`, we don't need to import the prelude; exclude it to
  73. // focus errors. In other phases we only do this for explicit "no_prelude"
  74. // tests.
  75. if (component_ == "lex" || component_ == "parse" || is_no_prelude()) {
  76. args.push_back("--no-prelude-import");
  77. }
  78. args.insert(
  79. args.end(),
  80. {"--exclude-dump-file-prefix=" + installation_.core_package(), "%s"});
  81. return args;
  82. }
  83. auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> filenames)
  84. -> std::optional<RE2> override {
  85. if (component_ == "lex") {
  86. return std::make_optional<RE2>(
  87. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  88. }
  89. return FileTestBase::GetDefaultFileRE(filenames);
  90. }
  91. auto GetLineNumberReplacements(llvm::ArrayRef<llvm::StringRef> filenames)
  92. -> llvm::SmallVector<LineNumberReplacement> override {
  93. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  94. if (component_ == "lex") {
  95. replacements.push_back({.has_file = false,
  96. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  97. // The `{{{{` becomes `{{`.
  98. .line_formatv = "{{{{ *}}{0}"});
  99. }
  100. return replacements;
  101. }
  102. auto DoExtraCheckReplacements(std::string& check_line) -> void override {
  103. if (component_ == "driver") {
  104. // TODO: Disable token output, it's not interesting for these tests.
  105. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  106. check_line = "// CHECK:STDOUT: {{.*}}";
  107. }
  108. } else if (component_ == "lex") {
  109. // Both FileStart and FileEnd regularly have locations on CHECK
  110. // comment lines that don't work correctly. The line happens to be correct
  111. // for the FileEnd, but we need to avoid checking the column.
  112. // The column happens to be right for FileStart, but the line is wrong.
  113. static RE2 file_token_re(
  114. R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  115. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  116. } else {
  117. FileTestBase::DoExtraCheckReplacements(check_line);
  118. }
  119. }
  120. private:
  121. // Adds a file to the fs.
  122. auto AddFile(llvm::vfs::InMemoryFileSystem& fs, llvm::StringRef path)
  123. -> ErrorOr<Success> {
  124. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file =
  125. llvm::MemoryBuffer::getFile(path);
  126. if (file.getError()) {
  127. return ErrorBuilder()
  128. << "Getting `" << path << "`: " << file.getError().message();
  129. }
  130. if (!fs.addFile(path, /*ModificationTime=*/0, std::move(*file))) {
  131. return ErrorBuilder() << "Duplicate file: `" << path << "`";
  132. }
  133. return Success();
  134. }
  135. // Returns the toolchain subdirectory being tested.
  136. static auto GetComponent(llvm::StringRef test_name) -> llvm::StringRef {
  137. // This handles cases where the toolchain directory may be copied into a
  138. // repository that doesn't put it at the root.
  139. auto pos = test_name.find("toolchain/");
  140. CARBON_CHECK(pos != llvm::StringRef::npos, "{0}", test_name);
  141. test_name = test_name.drop_front(pos + strlen("toolchain/"));
  142. test_name = test_name.take_front(test_name.find("/"));
  143. return test_name;
  144. }
  145. auto is_no_prelude() const -> bool {
  146. return test_name().find("/no_prelude/") != llvm::StringRef::npos;
  147. }
  148. const llvm::StringRef component_;
  149. const InstallPaths installation_;
  150. };
  151. } // namespace
  152. CARBON_FILE_TEST_FACTORY(ToolchainFileTest)
  153. } // namespace Carbon::Testing
  154. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_