file_test.cpp 6.4 KB

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