file_test.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  32. llvm::raw_pwrite_stream& error_stream)
  33. -> ErrorOr<RunResult> override {
  34. CARBON_ASSIGN_OR_RETURN(auto prelude, installation_.ReadPreludeManifest());
  35. if (!is_no_prelude()) {
  36. for (const auto& file : prelude) {
  37. CARBON_RETURN_IF_ERROR(AddFile(*fs, file));
  38. }
  39. }
  40. Driver driver({.fs = fs,
  41. .installation = &installation_,
  42. .input_stream = input_stream,
  43. .output_stream = &output_stream,
  44. .error_stream = &error_stream});
  45. auto driver_result = driver.RunCommand(test_args);
  46. // If any diagnostics have been produced, add a trailing newline to make the
  47. // last diagnostic match intermediate diagnostics (that have a newline
  48. // separator between them). This reduces churn when adding new diagnostics
  49. // to test cases.
  50. if (error_stream.tell() > 0) {
  51. error_stream << '\n';
  52. }
  53. RunResult result{
  54. .success = driver_result.success,
  55. .per_file_success = std::move(driver_result.per_file_success)};
  56. // Drop entries that don't look like a file, and entries corresponding to
  57. // the prelude. Note this can empty out the list.
  58. llvm::erase_if(result.per_file_success,
  59. [&](std::pair<llvm::StringRef, bool> entry) {
  60. return entry.first == "." || entry.first == "-" ||
  61. entry.first.starts_with("not_file") ||
  62. llvm::is_contained(prelude, entry.first);
  63. });
  64. return result;
  65. }
  66. auto GetDefaultArgs() -> llvm::SmallVector<std::string> override {
  67. if (component_ == "format") {
  68. return {"format", "%s"};
  69. }
  70. llvm::SmallVector<std::string> args = {
  71. "compile", "--include-diagnostic-kind", "--phase=" + component_.str()};
  72. if (component_ == "lex") {
  73. args.insert(args.end(), {"--dump-tokens", "--omit-file-boundary-tokens"});
  74. } else if (component_ == "parse") {
  75. args.push_back("--dump-parse-tree");
  76. } else if (component_ == "check") {
  77. args.push_back("--dump-sem-ir");
  78. } else if (component_ == "lower") {
  79. args.push_back("--dump-llvm-ir");
  80. } else {
  81. CARBON_FATAL("Unexpected test component {0}: {1}", component_,
  82. test_name());
  83. }
  84. // For `lex` and `parse`, we don't need to import the prelude; exclude it to
  85. // focus errors. In other phases we only do this for explicit "no_prelude"
  86. // tests.
  87. if (component_ == "lex" || component_ == "parse" || is_no_prelude()) {
  88. args.push_back("--no-prelude-import");
  89. }
  90. args.insert(
  91. args.end(),
  92. {"--exclude-dump-file-prefix=" + installation_.core_package(), "%s"});
  93. return args;
  94. }
  95. auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> filenames)
  96. -> std::optional<RE2> override {
  97. if (component_ == "lex") {
  98. return std::make_optional<RE2>(
  99. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  100. }
  101. return FileTestBase::GetDefaultFileRE(filenames);
  102. }
  103. auto GetLineNumberReplacements(llvm::ArrayRef<llvm::StringRef> filenames)
  104. -> llvm::SmallVector<LineNumberReplacement> override {
  105. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  106. if (component_ == "lex") {
  107. replacements.push_back({.has_file = false,
  108. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  109. // The `{{{{` becomes `{{`.
  110. .line_formatv = "{{{{ *}}{0}"});
  111. }
  112. return replacements;
  113. }
  114. auto DoExtraCheckReplacements(std::string& check_line) -> void override {
  115. if (component_ == "driver") {
  116. // TODO: Disable token output, it's not interesting for these tests.
  117. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  118. check_line = "// CHECK:STDOUT: {{.*}}";
  119. }
  120. } else if (component_ == "lex") {
  121. // Both FileStart and FileEnd regularly have locations on CHECK
  122. // comment lines that don't work correctly. The line happens to be correct
  123. // for the FileEnd, but we need to avoid checking the column.
  124. // The column happens to be right for FileStart, but the line is wrong.
  125. static RE2 file_token_re(
  126. R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  127. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  128. } else {
  129. FileTestBase::DoExtraCheckReplacements(check_line);
  130. }
  131. }
  132. private:
  133. // Adds a file to the fs.
  134. auto AddFile(llvm::vfs::InMemoryFileSystem& fs, llvm::StringRef path)
  135. -> ErrorOr<Success> {
  136. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file =
  137. llvm::MemoryBuffer::getFile(path);
  138. if (file.getError()) {
  139. return ErrorBuilder()
  140. << "Getting `" << path << "`: " << file.getError().message();
  141. }
  142. if (!fs.addFile(path, /*ModificationTime=*/0, std::move(*file))) {
  143. return ErrorBuilder() << "Duplicate file: `" << path << "`";
  144. }
  145. return Success();
  146. }
  147. // Returns the toolchain subdirectory being tested.
  148. static auto GetComponent(llvm::StringRef test_name) -> llvm::StringRef {
  149. // This handles cases where the toolchain directory may be copied into a
  150. // repository that doesn't put it at the root.
  151. auto pos = test_name.find("toolchain/");
  152. CARBON_CHECK(pos != llvm::StringRef::npos, "{0}", test_name);
  153. test_name = test_name.drop_front(pos + strlen("toolchain/"));
  154. test_name = test_name.take_front(test_name.find("/"));
  155. return test_name;
  156. }
  157. auto is_no_prelude() const -> bool {
  158. return test_name().find("/no_prelude/") != llvm::StringRef::npos;
  159. }
  160. const llvm::StringRef component_;
  161. const InstallPaths installation_;
  162. };
  163. } // namespace
  164. CARBON_FILE_TEST_FACTORY(ToolchainFileTest)
  165. } // namespace Carbon::Testing
  166. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_