file_test.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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/file_test_base.h"
  19. #include "toolchain/driver/driver.h"
  20. namespace Carbon::Testing {
  21. namespace {
  22. // Provides common test support for the driver. This is used by file tests in
  23. // component subdirectories.
  24. class ToolchainFileTest : public FileTestBase {
  25. public:
  26. explicit ToolchainFileTest(llvm::StringRef exe_path,
  27. llvm::StringRef test_name);
  28. // Adds a replacement for `core_package_dir`.
  29. auto GetArgReplacements() const -> llvm::StringMap<std::string> override;
  30. // Loads files into the VFS and runs the driver.
  31. auto Run(const llvm::SmallVector<llvm::StringRef>& test_args,
  32. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  33. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  34. llvm::raw_pwrite_stream& error_stream) const
  35. -> ErrorOr<RunResult> override;
  36. // Sets different default flags based on the component being tested.
  37. auto GetDefaultArgs() const -> llvm::SmallVector<std::string> override;
  38. // Generally uses the parent implementation, with special handling for lex.
  39. auto GetDefaultFileRE(llvm::ArrayRef<llvm::StringRef> filenames) const
  40. -> std::optional<RE2> override;
  41. // Generally uses the parent implementation, with special handling for lex.
  42. auto GetLineNumberReplacements(llvm::ArrayRef<llvm::StringRef> filenames)
  43. const -> llvm::SmallVector<LineNumberReplacement> override;
  44. // Generally uses the parent implementation, with special handling for lex and
  45. // driver.
  46. auto DoExtraCheckReplacements(std::string& check_line) const -> void override;
  47. // Most tests can be run in parallel, but clangd has a global for its logging
  48. // system so we need language-server tests to be run in serial.
  49. auto AllowParallelRun() const -> bool override {
  50. return component_ != "language_server";
  51. }
  52. private:
  53. // The prelude mode. For lex and parse, it's always `None`; we exclude it in
  54. // order to focus errors. For check and lowering, it's set through
  55. // `min_prelude` and `no_prelude` subdirectories.
  56. enum Prelude {
  57. Default,
  58. Min,
  59. None,
  60. };
  61. auto prelude() const -> Prelude {
  62. if (component_ == "lex" || component_ == "parse" ||
  63. test_name().find("/no_prelude/") != llvm::StringRef::npos) {
  64. return Prelude::None;
  65. }
  66. if (test_name().find("/min_prelude/") != llvm::StringRef::npos) {
  67. return Prelude::Min;
  68. }
  69. return Prelude::Default;
  70. }
  71. // The toolchain component subdirectory, such as `lex` or `language_server`.
  72. const llvm::StringRef component_;
  73. // The toolchain install information.
  74. const InstallPaths installation_;
  75. };
  76. } // namespace
  77. CARBON_FILE_TEST_FACTORY(ToolchainFileTest)
  78. // Returns the toolchain subdirectory being tested.
  79. static auto GetComponent(llvm::StringRef test_name) -> llvm::StringRef {
  80. // This handles cases where the toolchain directory may be copied into a
  81. // repository that doesn't put it at the root.
  82. auto pos = test_name.find("toolchain/");
  83. CARBON_CHECK(pos != llvm::StringRef::npos, "{0}", test_name);
  84. test_name = test_name.drop_front(pos + strlen("toolchain/"));
  85. test_name = test_name.take_front(test_name.find("/"));
  86. return test_name;
  87. }
  88. ToolchainFileTest::ToolchainFileTest(llvm::StringRef exe_path,
  89. llvm::StringRef test_name)
  90. : FileTestBase(test_name),
  91. component_(GetComponent(test_name)),
  92. installation_(InstallPaths::MakeForBazelRunfiles(exe_path)) {}
  93. auto ToolchainFileTest::GetArgReplacements() const
  94. -> llvm::StringMap<std::string> {
  95. return {{"core_package_dir", installation_.core_package()}};
  96. }
  97. // Adds a file to the fs.
  98. static auto AddFile(llvm::vfs::InMemoryFileSystem& fs, llvm::StringRef path)
  99. -> ErrorOr<Success> {
  100. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> file =
  101. llvm::MemoryBuffer::getFile(path);
  102. if (file.getError()) {
  103. return ErrorBuilder() << "Getting `" << path
  104. << "`: " << file.getError().message();
  105. }
  106. if (!fs.addFile(path, /*ModificationTime=*/0, std::move(*file))) {
  107. return ErrorBuilder() << "Duplicate file: `" << path << "`";
  108. }
  109. return Success();
  110. }
  111. auto ToolchainFileTest::Run(
  112. const llvm::SmallVector<llvm::StringRef>& test_args,
  113. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>& fs,
  114. FILE* input_stream, llvm::raw_pwrite_stream& output_stream,
  115. llvm::raw_pwrite_stream& error_stream) const -> ErrorOr<RunResult> {
  116. CARBON_ASSIGN_OR_RETURN(auto prelude_files,
  117. installation_.ReadPreludeManifest());
  118. if (prelude() == Prelude::Default) {
  119. for (const auto& file : prelude_files) {
  120. CARBON_RETURN_IF_ERROR(AddFile(*fs, file));
  121. }
  122. }
  123. Driver driver(fs, &installation_, input_stream, &output_stream,
  124. &error_stream);
  125. auto driver_result = driver.RunCommand(test_args);
  126. // If any diagnostics have been produced, add a trailing newline to make the
  127. // last diagnostic match intermediate diagnostics (that have a newline
  128. // separator between them). This reduces churn when adding new diagnostics
  129. // to test cases.
  130. if (error_stream.tell() > 0) {
  131. error_stream << '\n';
  132. }
  133. RunResult result{
  134. .success = driver_result.success,
  135. .per_file_success = std::move(driver_result.per_file_success)};
  136. // Drop entries that don't look like a file, and entries corresponding to
  137. // the prelude. Note this can empty out the list.
  138. llvm::erase_if(result.per_file_success,
  139. [&](std::pair<llvm::StringRef, bool> entry) {
  140. return entry.first == "." || entry.first == "-" ||
  141. entry.first.starts_with("not_file") ||
  142. llvm::is_contained(prelude_files, entry.first);
  143. });
  144. if (component_ == "language_server") {
  145. // The language server doesn't always add a suffix newline, so add one for
  146. // tests to be happy.
  147. output_stream << "\n";
  148. }
  149. return result;
  150. }
  151. auto ToolchainFileTest::GetDefaultArgs() const
  152. -> llvm::SmallVector<std::string> {
  153. llvm::SmallVector<std::string> args = {"--include-diagnostic-kind"};
  154. if (component_ == "format") {
  155. args.insert(args.end(), {"format", "%s"});
  156. return args;
  157. } else if (component_ == "language_server") {
  158. args.insert(args.end(), {"language-server"});
  159. return args;
  160. }
  161. args.insert(args.end(), {"compile", "--phase=" + component_.str()});
  162. if (component_ == "lex") {
  163. args.insert(args.end(), {"--dump-tokens", "--omit-file-boundary-tokens"});
  164. } else if (component_ == "parse") {
  165. args.push_back("--dump-parse-tree");
  166. } else if (component_ == "check") {
  167. args.push_back("--dump-sem-ir");
  168. } else if (component_ == "lower") {
  169. args.push_back("--dump-llvm-ir");
  170. } else {
  171. CARBON_FATAL("Unexpected test component {0}: {1}", component_, test_name());
  172. }
  173. switch (prelude()) {
  174. case Prelude::Default:
  175. // Use the install path to exclude prelude files.
  176. args.push_back("--exclude-dump-file-prefix=" +
  177. installation_.core_package());
  178. break;
  179. case Prelude::Min:
  180. // Included files all show up under the `include_files/` prefix, so
  181. // exclude min_prelude files that way.
  182. args.insert(args.end(), {"--custom-core",
  183. "--exclude-dump-file-prefix=include_files/"});
  184. break;
  185. case Prelude::None:
  186. args.push_back("--no-prelude-import");
  187. break;
  188. }
  189. args.push_back("%s");
  190. return args;
  191. }
  192. auto ToolchainFileTest::GetDefaultFileRE(
  193. llvm::ArrayRef<llvm::StringRef> filenames) const -> std::optional<RE2> {
  194. if (component_ == "lex") {
  195. return std::make_optional<RE2>(
  196. llvm::formatv(R"(^- filename: ({0})$)", llvm::join(filenames, "|")));
  197. }
  198. return FileTestBase::GetDefaultFileRE(filenames);
  199. }
  200. auto ToolchainFileTest::GetLineNumberReplacements(
  201. llvm::ArrayRef<llvm::StringRef> filenames) const
  202. -> llvm::SmallVector<LineNumberReplacement> {
  203. auto replacements = FileTestBase::GetLineNumberReplacements(filenames);
  204. if (component_ == "lex") {
  205. replacements.push_back({.has_file = false,
  206. .re = std::make_shared<RE2>(R"(line: (\s*\d+))"),
  207. // The `{{{{` becomes `{{`.
  208. .line_formatv = "{{{{ *}}{0}"});
  209. }
  210. return replacements;
  211. }
  212. auto ToolchainFileTest::DoExtraCheckReplacements(std::string& check_line) const
  213. -> void {
  214. if (component_ == "driver") {
  215. // TODO: Disable token output, it's not interesting for these tests.
  216. if (llvm::StringRef(check_line).starts_with("// CHECK:STDOUT: {")) {
  217. check_line = "// CHECK:STDOUT: {{.*}}";
  218. }
  219. } else if (component_ == "lex") {
  220. // Both FileStart and FileEnd regularly have locations on CHECK
  221. // comment lines that don't work correctly. The line happens to be correct
  222. // for the FileEnd, but we need to avoid checking the column.
  223. // The column happens to be right for FileStart, but the line is wrong.
  224. static RE2 file_token_re(R"((FileEnd.*column: |FileStart.*line: )( *\d+))");
  225. RE2::Replace(&check_line, file_token_re, R"(\1{{ *\\d+}})");
  226. } else if (component_ == "check") {
  227. // The path to the core package appears in some check diagnostics, and will
  228. // differ between testing environments, so don't test it.
  229. // TODO: Consider adding a content keyword to name the core package, and
  230. // replace with that instead. Alternatively, consider adding the core
  231. // package to the VFS with a fixed name.
  232. absl::StrReplaceAll({{installation_.core_package(), "{{.*}}"}},
  233. &check_line);
  234. } else {
  235. FileTestBase::DoExtraCheckReplacements(check_line);
  236. }
  237. }
  238. } // namespace Carbon::Testing
  239. #endif // CARBON_TOOLCHAIN_DRIVER_DRIVER_FILE_TEST_BASE_H_