file_test_base.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. #include "testing/file_test/file_test_base.h"
  5. #include <gmock/gmock.h>
  6. #include <filesystem>
  7. #include <optional>
  8. #include <string>
  9. #include <utility>
  10. #include "absl/flags/flag.h"
  11. #include "absl/flags/parse.h"
  12. #include "common/check.h"
  13. #include "common/error.h"
  14. #include "common/exe_path.h"
  15. #include "common/init_llvm.h"
  16. #include "common/raw_string_ostream.h"
  17. #include "llvm/ADT/ScopeExit.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/Support/CrashRecoveryContext.h"
  21. #include "llvm/Support/FormatVariadic.h"
  22. #include "llvm/Support/MemoryBuffer.h"
  23. #include "llvm/Support/PrettyStackTrace.h"
  24. #include "llvm/Support/Process.h"
  25. #include "llvm/Support/ThreadPool.h"
  26. #include "testing/base/file_helpers.h"
  27. #include "testing/file_test/autoupdate.h"
  28. ABSL_FLAG(std::vector<std::string>, file_tests, {},
  29. "A comma-separated list of repo-relative names of test files. "
  30. "Overrides test_targets_file.");
  31. ABSL_FLAG(std::string, test_targets_file, "",
  32. "A path to a file containing repo-relative names of test files.");
  33. ABSL_FLAG(bool, autoupdate, false,
  34. "Instead of verifying files match test output, autoupdate files "
  35. "based on test output.");
  36. ABSL_FLAG(unsigned int, threads, 0,
  37. "Number of threads to use when autoupdating tests, or 0 to "
  38. "automatically determine a thread count.");
  39. ABSL_FLAG(bool, dump_output, false,
  40. "Instead of verifying files match test output, directly dump output "
  41. "to stderr.");
  42. namespace Carbon::Testing {
  43. // While these are marked as "internal" APIs, they seem to work and be pretty
  44. // widely used for their exact documented behavior.
  45. using ::testing::internal::CaptureStderr;
  46. using ::testing::internal::CaptureStdout;
  47. using ::testing::internal::GetCapturedStderr;
  48. using ::testing::internal::GetCapturedStdout;
  49. using ::testing::Matcher;
  50. using ::testing::MatchesRegex;
  51. using ::testing::StrEq;
  52. static constexpr llvm::StringLiteral StdinFilename = "STDIN";
  53. // Splits outputs to string_view because gtest handles string_view by default.
  54. static auto SplitOutput(llvm::StringRef output)
  55. -> llvm::SmallVector<std::string_view> {
  56. if (output.empty()) {
  57. return {};
  58. }
  59. llvm::SmallVector<llvm::StringRef> lines;
  60. llvm::StringRef(output).split(lines, "\n");
  61. return llvm::SmallVector<std::string_view>(lines.begin(), lines.end());
  62. }
  63. // Verify that the success and `fail_` prefix use correspond. Separately handle
  64. // both cases for clearer test failures.
  65. static auto CompareFailPrefix(llvm::StringRef filename, bool success) -> void {
  66. if (success) {
  67. EXPECT_FALSE(filename.starts_with("fail_"))
  68. << "`" << filename
  69. << "` succeeded; if success is expected, remove the `fail_` "
  70. "prefix.";
  71. } else {
  72. EXPECT_TRUE(filename.starts_with("fail_"))
  73. << "`" << filename
  74. << "` failed; if failure is expected, add the `fail_` prefix.";
  75. }
  76. }
  77. // Modes for GetBazelCommand.
  78. enum class BazelMode : uint8_t {
  79. Autoupdate,
  80. Dump,
  81. Test,
  82. };
  83. // Returns the requested bazel command string for the given execution mode.
  84. static auto GetBazelCommand(BazelMode mode, llvm::StringRef test_name)
  85. -> std::string {
  86. RawStringOstream args;
  87. const char* target = getenv("TEST_TARGET");
  88. args << "bazel " << ((mode == BazelMode::Test) ? "test" : "run") << " "
  89. << (target ? target : "<target>") << " ";
  90. switch (mode) {
  91. case BazelMode::Autoupdate:
  92. args << "-- --autoupdate ";
  93. break;
  94. case BazelMode::Dump:
  95. args << "-- --dump_output ";
  96. break;
  97. case BazelMode::Test:
  98. args << "--test_arg=";
  99. break;
  100. }
  101. args << "--file_tests=";
  102. args << test_name;
  103. return args.TakeStr();
  104. }
  105. // Runs a test and compares output. This keeps output split by line so that
  106. // issues are a little easier to identify by the different line.
  107. auto FileTestBase::TestBody() -> void {
  108. // Add a crash trace entry with the single-file test command.
  109. std::string test_command = GetBazelCommand(BazelMode::Test, test_name_);
  110. llvm::PrettyStackTraceString stack_trace_entry(test_command.c_str());
  111. llvm::errs() << "\nTo test this file alone, run:\n " << test_command
  112. << "\n\n";
  113. TestContext context;
  114. auto run_result = ProcessTestFileAndRun(context);
  115. ASSERT_TRUE(run_result.ok()) << run_result.error();
  116. ValidateRun();
  117. auto test_filename = std::filesystem::path(test_name_.str()).filename();
  118. // Check success/failure against `fail_` prefixes.
  119. if (context.run_result.per_file_success.empty()) {
  120. CompareFailPrefix(test_filename.string(), context.run_result.success);
  121. } else {
  122. bool require_overall_failure = false;
  123. for (const auto& [filename, success] :
  124. context.run_result.per_file_success) {
  125. CompareFailPrefix(filename, success);
  126. if (!success) {
  127. require_overall_failure = true;
  128. }
  129. }
  130. if (require_overall_failure) {
  131. EXPECT_FALSE(context.run_result.success)
  132. << "There is a per-file failure expectation, so the overall result "
  133. "should have been a failure.";
  134. } else {
  135. // Individual files all succeeded, so the prefix is enforced on the main
  136. // test file.
  137. CompareFailPrefix(test_filename.string(), context.run_result.success);
  138. }
  139. }
  140. // Check results. Include a reminder of the autoupdate command for any
  141. // stdout/stderr differences.
  142. std::string update_message;
  143. if (context.autoupdate_line_number) {
  144. update_message = llvm::formatv(
  145. "If these differences are expected, try the autoupdater:\n {0}",
  146. GetBazelCommand(BazelMode::Autoupdate, test_name_));
  147. } else {
  148. update_message =
  149. "If these differences are expected, content must be updated manually.";
  150. }
  151. SCOPED_TRACE(update_message);
  152. if (context.check_subset) {
  153. EXPECT_THAT(SplitOutput(context.actual_stdout),
  154. IsSupersetOf(context.expected_stdout));
  155. EXPECT_THAT(SplitOutput(context.actual_stderr),
  156. IsSupersetOf(context.expected_stderr));
  157. } else {
  158. EXPECT_THAT(SplitOutput(context.actual_stdout),
  159. ElementsAreArray(context.expected_stdout));
  160. EXPECT_THAT(SplitOutput(context.actual_stderr),
  161. ElementsAreArray(context.expected_stderr));
  162. }
  163. // If there are no other test failures, check if autoupdate would make
  164. // changes. We don't do this when there _are_ failures because the
  165. // SCOPED_TRACE already contains the autoupdate reminder.
  166. if (!HasFailure() && RunAutoupdater(context, /*dry_run=*/true)) {
  167. ADD_FAILURE() << "Autoupdate would make changes to the file content.";
  168. }
  169. }
  170. auto FileTestBase::RunAutoupdater(const TestContext& context, bool dry_run)
  171. -> bool {
  172. if (!context.autoupdate_line_number) {
  173. return false;
  174. }
  175. llvm::SmallVector<llvm::StringRef> filenames;
  176. filenames.reserve(context.non_check_lines.size());
  177. if (context.has_splits) {
  178. // There are splits, so we provide an empty name for the first file.
  179. filenames.push_back({});
  180. }
  181. for (const auto& file : context.test_files) {
  182. filenames.push_back(file.filename);
  183. }
  184. llvm::ArrayRef expected_filenames = filenames;
  185. if (filenames.size() > 1) {
  186. expected_filenames = expected_filenames.drop_front();
  187. }
  188. return FileTestAutoupdater(
  189. std::filesystem::absolute(test_name_.str()),
  190. GetBazelCommand(BazelMode::Test, test_name_),
  191. GetBazelCommand(BazelMode::Dump, test_name_),
  192. context.input_content, filenames, *context.autoupdate_line_number,
  193. context.autoupdate_split, context.non_check_lines,
  194. context.actual_stdout, context.actual_stderr,
  195. GetDefaultFileRE(expected_filenames),
  196. GetLineNumberReplacements(expected_filenames),
  197. [&](std::string& line) { DoExtraCheckReplacements(line); })
  198. .Run(dry_run);
  199. }
  200. auto FileTestBase::Autoupdate() -> ErrorOr<bool> {
  201. // Add a crash trace entry mentioning which file we're updating.
  202. std::string stack_trace_string =
  203. llvm::formatv("performing autoupdate for {0}", test_name_);
  204. llvm::PrettyStackTraceString stack_trace_entry(stack_trace_string.c_str());
  205. TestContext context;
  206. auto run_result = ProcessTestFileAndRun(context);
  207. if (!run_result.ok()) {
  208. return ErrorBuilder() << "Error updating " << test_name_ << ": "
  209. << run_result.error();
  210. }
  211. return RunAutoupdater(context, /*dry_run=*/false);
  212. }
  213. auto FileTestBase::DumpOutput() -> ErrorOr<Success> {
  214. TestContext context;
  215. context.dump_output = true;
  216. std::string banner(79, '=');
  217. banner.append("\n");
  218. llvm::errs() << banner << "= " << test_name_ << "\n";
  219. auto run_result = ProcessTestFileAndRun(context);
  220. if (!run_result.ok()) {
  221. return ErrorBuilder() << "Error updating " << test_name_ << ": "
  222. << run_result.error();
  223. }
  224. llvm::errs() << banner << context.actual_stdout << banner
  225. << "= Exit with success: "
  226. << (context.run_result.success ? "true" : "false") << "\n"
  227. << banner;
  228. return Success();
  229. }
  230. auto FileTestBase::GetLineNumberReplacements(
  231. llvm::ArrayRef<llvm::StringRef> filenames)
  232. -> llvm::SmallVector<LineNumberReplacement> {
  233. return {{.has_file = true,
  234. .re = std::make_shared<RE2>(
  235. llvm::formatv(R"(({0}):(\d+)?)", llvm::join(filenames, "|"))),
  236. .line_formatv = R"({0})"}};
  237. }
  238. auto FileTestBase::ProcessTestFileAndRun(TestContext& context)
  239. -> ErrorOr<Success> {
  240. // Store the file so that test_files can use references to content.
  241. CARBON_ASSIGN_OR_RETURN(context.input_content, ReadFile(test_name_.str()));
  242. // Load expected output.
  243. CARBON_RETURN_IF_ERROR(ProcessTestFile(context));
  244. // Process arguments.
  245. if (context.test_args.empty()) {
  246. context.test_args = GetDefaultArgs();
  247. context.test_args.append(context.extra_args);
  248. }
  249. CARBON_RETURN_IF_ERROR(
  250. DoArgReplacements(context.test_args, context.test_files));
  251. // stdin needs to exist on-disk for compatibility. We'll use a pointer for it.
  252. FILE* input_stream = nullptr;
  253. auto erase_input_on_exit = llvm::make_scope_exit([&input_stream]() {
  254. if (input_stream) {
  255. // fclose should delete the tmpfile.
  256. fclose(input_stream);
  257. input_stream = nullptr;
  258. }
  259. });
  260. // Create the files in-memory.
  261. llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> fs =
  262. new llvm::vfs::InMemoryFileSystem;
  263. for (const auto& test_file : context.test_files) {
  264. if (test_file.filename == StdinFilename) {
  265. input_stream = tmpfile();
  266. fwrite(test_file.content.c_str(), sizeof(char), test_file.content.size(),
  267. input_stream);
  268. rewind(input_stream);
  269. } else if (!fs->addFile(test_file.filename, /*ModificationTime=*/0,
  270. llvm::MemoryBuffer::getMemBuffer(
  271. test_file.content, test_file.filename,
  272. /*RequiresNullTerminator=*/false))) {
  273. return ErrorBuilder() << "File is repeated: " << test_file.filename;
  274. }
  275. }
  276. // Convert the arguments to StringRef and const char* to match the
  277. // expectations of PrettyStackTraceProgram and Run.
  278. llvm::SmallVector<llvm::StringRef> test_args_ref;
  279. llvm::SmallVector<const char*> test_argv_for_stack_trace;
  280. test_args_ref.reserve(context.test_args.size());
  281. test_argv_for_stack_trace.reserve(context.test_args.size() + 1);
  282. for (const auto& arg : context.test_args) {
  283. test_args_ref.push_back(arg);
  284. test_argv_for_stack_trace.push_back(arg.c_str());
  285. }
  286. // Add a trailing null so that this is a proper argv.
  287. test_argv_for_stack_trace.push_back(nullptr);
  288. // Add a stack trace entry for the test invocation.
  289. llvm::PrettyStackTraceProgram stack_trace_entry(
  290. test_argv_for_stack_trace.size() - 1, test_argv_for_stack_trace.data());
  291. // Execution must be serialized for either serial tests or console output.
  292. std::unique_lock<std::mutex> output_lock;
  293. if (output_mutex_ &&
  294. (context.capture_console_output || !AllowParallelRun())) {
  295. output_lock = std::unique_lock<std::mutex>(*output_mutex_);
  296. }
  297. // Conditionally capture console output. We use a scope exit to ensure the
  298. // captures terminate even on run failures.
  299. if (context.capture_console_output) {
  300. CaptureStderr();
  301. CaptureStdout();
  302. }
  303. auto add_output_on_exit = llvm::make_scope_exit([&]() {
  304. if (context.capture_console_output) {
  305. // No need to flush stderr.
  306. llvm::outs().flush();
  307. context.actual_stdout += GetCapturedStdout();
  308. context.actual_stderr += GetCapturedStderr();
  309. }
  310. });
  311. // Prepare string streams to capture output. In order to address casting
  312. // constraints, we split calls to Run as a ternary based on whether we want to
  313. // capture output.
  314. llvm::raw_svector_ostream output_stream(context.actual_stdout);
  315. llvm::raw_svector_ostream error_stream(context.actual_stderr);
  316. CARBON_ASSIGN_OR_RETURN(
  317. context.run_result,
  318. context.dump_output
  319. ? Run(test_args_ref, fs, input_stream, llvm::outs(), llvm::errs())
  320. : Run(test_args_ref, fs, input_stream, output_stream, error_stream));
  321. return Success();
  322. }
  323. auto FileTestBase::DoArgReplacements(
  324. llvm::SmallVector<std::string>& test_args,
  325. const llvm::SmallVector<TestFile>& test_files) -> ErrorOr<Success> {
  326. auto replacements = GetArgReplacements();
  327. for (auto* it = test_args.begin(); it != test_args.end(); ++it) {
  328. auto percent = it->find("%");
  329. if (percent == std::string::npos) {
  330. continue;
  331. }
  332. if (percent + 1 >= it->size()) {
  333. return ErrorBuilder() << "% is not allowed on its own: " << *it;
  334. }
  335. char c = (*it)[percent + 1];
  336. switch (c) {
  337. case 's': {
  338. if (*it != "%s") {
  339. return ErrorBuilder() << "%s must be the full argument: " << *it;
  340. }
  341. it = test_args.erase(it);
  342. for (const auto& file : test_files) {
  343. const std::string& filename = file.filename;
  344. if (filename == StdinFilename || filename.ends_with(".h")) {
  345. continue;
  346. }
  347. it = test_args.insert(it, filename);
  348. ++it;
  349. }
  350. // Back up once because the for loop will advance.
  351. --it;
  352. break;
  353. }
  354. case 't': {
  355. char* tmpdir = getenv("TEST_TMPDIR");
  356. CARBON_CHECK(tmpdir != nullptr);
  357. it->replace(percent, 2, llvm::formatv("{0}/temp_file", tmpdir));
  358. break;
  359. }
  360. case '{': {
  361. auto end_brace = it->find('}', percent);
  362. if (end_brace == std::string::npos) {
  363. return ErrorBuilder() << "%{ without closing }: " << *it;
  364. }
  365. llvm::StringRef substr(&*(it->begin() + percent + 2),
  366. end_brace - percent - 2);
  367. auto replacement = replacements.find(substr);
  368. if (replacement == replacements.end()) {
  369. return ErrorBuilder()
  370. << "unknown substitution: %{" << substr << "}: " << *it;
  371. }
  372. it->replace(percent, end_brace - percent + 1, replacement->second);
  373. break;
  374. }
  375. default:
  376. return ErrorBuilder() << "%" << c << " is not supported: " << *it;
  377. }
  378. }
  379. return Success();
  380. }
  381. // Processes conflict markers, including tracking of whether code is within a
  382. // conflict marker. Returns true if the line is consumed.
  383. static auto TryConsumeConflictMarker(llvm::StringRef line,
  384. llvm::StringRef line_trimmed,
  385. bool* inside_conflict_marker)
  386. -> ErrorOr<bool> {
  387. bool is_start = line.starts_with("<<<<<<<");
  388. bool is_middle = line.starts_with("=======") || line.starts_with("|||||||");
  389. bool is_end = line.starts_with(">>>>>>>");
  390. // When running the test, any conflict marker is an error.
  391. if (!absl::GetFlag(FLAGS_autoupdate) && (is_start || is_middle || is_end)) {
  392. return ErrorBuilder() << "Conflict marker found:\n" << line;
  393. }
  394. // Autoupdate tracks conflict markers for context, and will discard
  395. // conflicting lines when it can autoupdate them.
  396. if (*inside_conflict_marker) {
  397. if (is_start) {
  398. return ErrorBuilder() << "Unexpected conflict marker inside conflict:\n"
  399. << line;
  400. }
  401. if (is_middle) {
  402. return true;
  403. }
  404. if (is_end) {
  405. *inside_conflict_marker = false;
  406. return true;
  407. }
  408. // Look for CHECK and TIP lines, which can be discarded.
  409. if (line_trimmed.starts_with("// CHECK:STDOUT:") ||
  410. line_trimmed.starts_with("// CHECK:STDERR:") ||
  411. line_trimmed.starts_with("// TIP:")) {
  412. return true;
  413. }
  414. return ErrorBuilder()
  415. << "Autoupdate can't discard non-CHECK lines inside conflicts:\n"
  416. << line;
  417. } else {
  418. if (is_start) {
  419. *inside_conflict_marker = true;
  420. return true;
  421. }
  422. if (is_middle || is_end) {
  423. return ErrorBuilder() << "Unexpected conflict marker outside conflict:\n"
  424. << line;
  425. }
  426. return false;
  427. }
  428. }
  429. // State for file splitting logic: TryConsumeSplit and FinishSplit.
  430. struct SplitState {
  431. auto has_splits() const -> bool { return file_index > 0; }
  432. auto add_content(llvm::StringRef line) -> void {
  433. content.append(line.str());
  434. content.append("\n");
  435. }
  436. // Whether content has been found. Only updated before a file split is found
  437. // (which may be never).
  438. bool found_code_pre_split = false;
  439. // The current file name, considering splits. Empty for the default file.
  440. llvm::StringRef filename = "";
  441. // The accumulated content for the file being built. This may elide some of
  442. // the original content, such as conflict markers.
  443. std::string content;
  444. // The current file index.
  445. int file_index = 0;
  446. };
  447. // Reformats `[[@LSP:` and similar keyword as an LSP call with headers.
  448. static auto ReplaceLspKeywordAt(std::string* content, size_t keyword_pos,
  449. int& lsp_call_id) -> ErrorOr<size_t> {
  450. llvm::StringRef content_at_keyword =
  451. llvm::StringRef(*content).substr(keyword_pos);
  452. auto [keyword, body_start] = content_at_keyword.split(":");
  453. if (body_start.empty()) {
  454. return ErrorBuilder() << "Missing `:` for `"
  455. << content_at_keyword.take_front(10) << "`";
  456. }
  457. // Whether the first param is a method or id.
  458. llvm::StringRef method_or_id_label = "method";
  459. // Whether to attach the `lsp_call_id`.
  460. bool use_call_id = false;
  461. // The JSON label for extra content.
  462. llvm::StringRef extra_content_label;
  463. if (keyword == "[[@LSP-CALL") {
  464. use_call_id = true;
  465. extra_content_label = "params";
  466. } else if (keyword == "[[@LSP-NOTIFY") {
  467. extra_content_label = "params";
  468. } else if (keyword == "[[@LSP-REPLY") {
  469. method_or_id_label = "id";
  470. extra_content_label = "result";
  471. } else if (keyword != "[[@LSP") {
  472. return ErrorBuilder() << "Unrecognized @LSP keyword at `"
  473. << keyword.take_front(10) << "`";
  474. }
  475. static constexpr llvm::StringLiteral LspEnd = "]]";
  476. auto body_end = body_start.find(LspEnd);
  477. if (body_end == std::string::npos) {
  478. return ErrorBuilder() << "Missing `" << LspEnd << "` after `" << keyword
  479. << "`";
  480. }
  481. llvm::StringRef body = body_start.take_front(body_end);
  482. auto [method_or_id, extra_content] = body.split(":");
  483. // Form the JSON.
  484. std::string json = llvm::formatv(R"({{"jsonrpc": "2.0", "{0}": "{1}")",
  485. method_or_id_label, method_or_id);
  486. if (use_call_id) {
  487. // Omit quotes on the ID because we know it's an integer.
  488. json += llvm::formatv(R"(, "id": {0})", ++lsp_call_id);
  489. }
  490. if (!extra_content.empty()) {
  491. json += ",";
  492. if (extra_content_label.empty()) {
  493. if (!extra_content.starts_with("\n")) {
  494. json += " ";
  495. }
  496. json += extra_content;
  497. } else {
  498. json += llvm::formatv(R"( "{0}": {{{1}})", extra_content_label,
  499. extra_content);
  500. }
  501. }
  502. json += "}";
  503. // Add the Content-Length header. The `2` accounts for extra newlines.
  504. auto json_with_header =
  505. llvm::formatv("Content-Length: {0}\n\n{1}\n", json.size() + 2, json)
  506. .str();
  507. int keyword_len =
  508. (body_start.data() + body_end + LspEnd.size()) - keyword.data();
  509. content->replace(keyword_pos, keyword_len, json_with_header);
  510. return keyword_pos + json_with_header.size();
  511. }
  512. // Replaces the keyword at the given position. Returns the position to start a
  513. // find for the next keyword.
  514. static auto ReplaceContentKeywordAt(std::string* content, size_t keyword_pos,
  515. llvm::StringRef test_name, int& lsp_call_id)
  516. -> ErrorOr<size_t> {
  517. auto keyword = llvm::StringRef(*content).substr(keyword_pos);
  518. // Line replacements aren't handled here.
  519. static constexpr llvm::StringLiteral Line = "[[@LINE";
  520. if (keyword.starts_with(Line)) {
  521. // Just move past the prefix to find the next one.
  522. return keyword_pos + Line.size();
  523. }
  524. // Replaced with the actual test name.
  525. static constexpr llvm::StringLiteral TestName = "[[@TEST_NAME]]";
  526. if (keyword.starts_with(TestName)) {
  527. content->replace(keyword_pos, TestName.size(), test_name);
  528. return keyword_pos + test_name.size();
  529. }
  530. if (keyword.starts_with("[[@LSP")) {
  531. return ReplaceLspKeywordAt(content, keyword_pos, lsp_call_id);
  532. }
  533. return ErrorBuilder() << "Unexpected use of `[[@` at `"
  534. << keyword.substr(0, 5) << "`";
  535. }
  536. // Replaces the content keywords.
  537. //
  538. // TEST_NAME is the only content keyword at present, but we do validate that
  539. // other names are reserved.
  540. static auto ReplaceContentKeywords(llvm::StringRef filename,
  541. std::string* content) -> ErrorOr<Success> {
  542. static constexpr llvm::StringLiteral Prefix = "[[@";
  543. auto keyword_pos = content->find(Prefix);
  544. // Return early if not finding anything.
  545. if (keyword_pos == std::string::npos) {
  546. return Success();
  547. }
  548. // Construct the test name by getting the base name without the extension,
  549. // then removing any "fail_" or "todo_" prefixes.
  550. llvm::StringRef test_name = filename;
  551. if (auto last_slash = test_name.rfind("/");
  552. last_slash != llvm::StringRef::npos) {
  553. test_name = test_name.substr(last_slash + 1);
  554. }
  555. if (auto ext_dot = test_name.find("."); ext_dot != llvm::StringRef::npos) {
  556. test_name = test_name.substr(0, ext_dot);
  557. }
  558. // Note this also handles `fail_todo_` and `todo_fail_`.
  559. test_name.consume_front("todo_");
  560. test_name.consume_front("fail_");
  561. test_name.consume_front("todo_");
  562. // A counter for LSP calls.
  563. int lsp_call_id = 0;
  564. while (keyword_pos != std::string::npos) {
  565. CARBON_ASSIGN_OR_RETURN(
  566. auto keyword_end,
  567. ReplaceContentKeywordAt(content, keyword_pos, test_name, lsp_call_id));
  568. keyword_pos = content->find(Prefix, keyword_end);
  569. }
  570. return Success();
  571. }
  572. // Adds a file. Used for both split and unsplit test files.
  573. static auto AddTestFile(llvm::StringRef filename, std::string* content,
  574. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  575. -> ErrorOr<Success> {
  576. CARBON_RETURN_IF_ERROR(ReplaceContentKeywords(filename, content));
  577. test_files->push_back(
  578. {.filename = filename.str(), .content = std::move(*content)});
  579. content->clear();
  580. return Success();
  581. }
  582. // Process file split ("---") lines when found. Returns true if the line is
  583. // consumed.
  584. static auto TryConsumeSplit(
  585. llvm::StringRef line, llvm::StringRef line_trimmed, bool found_autoupdate,
  586. int* line_index, SplitState* split,
  587. llvm::SmallVector<FileTestBase::TestFile>* test_files,
  588. llvm::SmallVector<FileTestLine>* non_check_lines) -> ErrorOr<bool> {
  589. if (!line_trimmed.consume_front("// ---")) {
  590. if (!split->has_splits() && !line_trimmed.starts_with("//") &&
  591. !line_trimmed.empty()) {
  592. split->found_code_pre_split = true;
  593. }
  594. // Add the line to the current file's content (which may not be a split
  595. // file).
  596. split->add_content(line);
  597. return false;
  598. }
  599. if (!found_autoupdate) {
  600. // If there's a split, all output is appended at the end of each file
  601. // before AUTOUPDATE. We may want to change that, but it's not
  602. // necessary to handle right now.
  603. return ErrorBuilder() << "AUTOUPDATE/NOAUTOUPDATE setting must be in "
  604. "the first file.";
  605. }
  606. // On a file split, add the previous file, then start a new one.
  607. if (split->has_splits()) {
  608. CARBON_RETURN_IF_ERROR(
  609. AddTestFile(split->filename, &split->content, test_files));
  610. } else {
  611. split->content.clear();
  612. if (split->found_code_pre_split) {
  613. // For the first split, we make sure there was no content prior.
  614. return ErrorBuilder() << "When using split files, there must be no "
  615. "content before the first split file.";
  616. }
  617. }
  618. ++split->file_index;
  619. split->filename = line_trimmed.trim();
  620. if (split->filename.empty()) {
  621. return ErrorBuilder() << "Missing filename for split.";
  622. }
  623. // The split line is added to non_check_lines for retention in autoupdate, but
  624. // is not added to the test file content.
  625. *line_index = 0;
  626. non_check_lines->push_back(
  627. FileTestLine(split->file_index, *line_index, line));
  628. return true;
  629. }
  630. // Converts a `FileCheck`-style expectation string into a single complete regex
  631. // string by escaping all regex characters outside of the designated `{{...}}`
  632. // regex sequences, and switching those to a normal regex sub-pattern syntax.
  633. static void ConvertExpectationStringToRegex(std::string& str) {
  634. for (int pos = 0; pos < static_cast<int>(str.size());) {
  635. switch (str[pos]) {
  636. case '(':
  637. case ')':
  638. case '[':
  639. case ']':
  640. case '}':
  641. case '.':
  642. case '^':
  643. case '$':
  644. case '*':
  645. case '+':
  646. case '?':
  647. case '|':
  648. case '\\': {
  649. // Escape regex characters.
  650. str.insert(pos, "\\");
  651. pos += 2;
  652. break;
  653. }
  654. case '{': {
  655. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  656. // Single `{`, escape it.
  657. str.insert(pos, "\\");
  658. pos += 2;
  659. break;
  660. }
  661. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  662. str.replace(pos, 2, "(");
  663. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  664. if (str[pos] == '}' && str[pos + 1] == '}') {
  665. str.replace(pos, 2, ")");
  666. ++pos;
  667. break;
  668. }
  669. }
  670. break;
  671. }
  672. default: {
  673. ++pos;
  674. }
  675. }
  676. }
  677. }
  678. // Transforms an expectation on a given line from `FileCheck` syntax into a
  679. // standard regex matcher.
  680. static auto TransformExpectation(int line_index, llvm::StringRef in)
  681. -> ErrorOr<Matcher<std::string>> {
  682. if (in.empty()) {
  683. return Matcher<std::string>{StrEq("")};
  684. }
  685. if (!in.consume_front(" ")) {
  686. return ErrorBuilder() << "Malformated CHECK line: " << in;
  687. }
  688. // Check early if we have a regex component as we can avoid building an
  689. // expensive matcher when not using those.
  690. bool has_regex = in.find("{{") != llvm::StringRef::npos;
  691. // Now scan the string and expand any keywords. Note that this needs to be
  692. // `size_t` to correctly store `npos`.
  693. size_t keyword_pos = in.find("[[");
  694. // If there are neither keywords nor regex sequences, we can match the
  695. // incoming string directly.
  696. if (!has_regex && keyword_pos == llvm::StringRef::npos) {
  697. return Matcher<std::string>{StrEq(in)};
  698. }
  699. std::string str = in.str();
  700. // First expand the keywords.
  701. while (keyword_pos != std::string::npos) {
  702. llvm::StringRef line_keyword_cursor =
  703. llvm::StringRef(str).substr(keyword_pos);
  704. CARBON_CHECK(line_keyword_cursor.consume_front("[["));
  705. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  706. if (!line_keyword_cursor.consume_front(LineKeyword)) {
  707. return ErrorBuilder()
  708. << "Unexpected [[, should be {{\\[\\[}} at `"
  709. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  710. }
  711. // Allow + or - here; consumeInteger handles -.
  712. line_keyword_cursor.consume_front("+");
  713. int offset;
  714. // consumeInteger returns true for errors, not false.
  715. if (line_keyword_cursor.consumeInteger(10, offset) ||
  716. !line_keyword_cursor.consume_front("]]")) {
  717. return ErrorBuilder()
  718. << "Unexpected @LINE offset at `"
  719. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  720. }
  721. std::string int_str = llvm::Twine(line_index + offset).str();
  722. int remove_len = (line_keyword_cursor.data() - str.data()) - keyword_pos;
  723. str.replace(keyword_pos, remove_len, int_str);
  724. keyword_pos += int_str.size();
  725. // Find the next keyword start or the end of the string.
  726. keyword_pos = str.find("[[", keyword_pos);
  727. }
  728. // If there was no regex, we can directly match the adjusted string.
  729. if (!has_regex) {
  730. return Matcher<std::string>{StrEq(str)};
  731. }
  732. // Otherwise, we need to turn the entire string into a regex by escaping
  733. // things outside the regex region and transforming the regex region into a
  734. // normal syntax.
  735. ConvertExpectationStringToRegex(str);
  736. return Matcher<std::string>{MatchesRegex(str)};
  737. }
  738. // Once all content is processed, do any remaining split processing.
  739. static auto FinishSplit(llvm::StringRef test_name, SplitState* split,
  740. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  741. -> ErrorOr<Success> {
  742. if (split->has_splits()) {
  743. return AddTestFile(split->filename, &split->content, test_files);
  744. } else {
  745. // If no file splitting happened, use the main file as the test file.
  746. // There will always be a `/` unless tests are in the repo root.
  747. return AddTestFile(test_name.drop_front(test_name.rfind("/") + 1),
  748. &split->content, test_files);
  749. }
  750. }
  751. // Process CHECK lines when found. Returns true if the line is consumed.
  752. static auto TryConsumeCheck(
  753. int line_index, llvm::StringRef line, llvm::StringRef line_trimmed,
  754. llvm::SmallVector<testing::Matcher<std::string>>* expected_stdout,
  755. llvm::SmallVector<testing::Matcher<std::string>>* expected_stderr)
  756. -> ErrorOr<bool> {
  757. if (!line_trimmed.consume_front("// CHECK")) {
  758. return false;
  759. }
  760. // Don't build expectations when doing an autoupdate. We don't want to
  761. // break the autoupdate on an invalid CHECK line.
  762. if (!absl::GetFlag(FLAGS_autoupdate)) {
  763. llvm::SmallVector<Matcher<std::string>>* expected;
  764. if (line_trimmed.consume_front(":STDOUT:")) {
  765. expected = expected_stdout;
  766. } else if (line_trimmed.consume_front(":STDERR:")) {
  767. expected = expected_stderr;
  768. } else {
  769. return ErrorBuilder() << "Unexpected CHECK in input: " << line.str();
  770. }
  771. CARBON_ASSIGN_OR_RETURN(Matcher<std::string> check_matcher,
  772. TransformExpectation(line_index, line_trimmed));
  773. expected->push_back(check_matcher);
  774. }
  775. return true;
  776. }
  777. // Processes ARGS and EXTRA-ARGS lines when found. Returns true if the line is
  778. // consumed.
  779. static auto TryConsumeArgs(llvm::StringRef line, llvm::StringRef line_trimmed,
  780. llvm::SmallVector<std::string>* args,
  781. llvm::SmallVector<std::string>* extra_args)
  782. -> ErrorOr<bool> {
  783. llvm::SmallVector<std::string>* arg_list = nullptr;
  784. if (line_trimmed.consume_front("// ARGS: ")) {
  785. arg_list = args;
  786. } else if (line_trimmed.consume_front("// EXTRA-ARGS: ")) {
  787. arg_list = extra_args;
  788. } else {
  789. return false;
  790. }
  791. if (!args->empty() || !extra_args->empty()) {
  792. return ErrorBuilder() << "ARGS / EXTRA-ARGS specified multiple times: "
  793. << line.str();
  794. }
  795. // Split the line into arguments.
  796. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  797. llvm::getToken(line_trimmed);
  798. while (!cursor.first.empty()) {
  799. arg_list->push_back(std::string(cursor.first));
  800. cursor = llvm::getToken(cursor.second);
  801. }
  802. return true;
  803. }
  804. // Processes AUTOUPDATE lines when found. Returns true if the line is consumed.
  805. static auto TryConsumeAutoupdate(int line_index, llvm::StringRef line_trimmed,
  806. bool* found_autoupdate,
  807. std::optional<int>* autoupdate_line_number)
  808. -> ErrorOr<bool> {
  809. static constexpr llvm::StringLiteral Autoupdate = "// AUTOUPDATE";
  810. static constexpr llvm::StringLiteral NoAutoupdate = "// NOAUTOUPDATE";
  811. if (line_trimmed != Autoupdate && line_trimmed != NoAutoupdate) {
  812. return false;
  813. }
  814. if (*found_autoupdate) {
  815. return ErrorBuilder() << "Multiple AUTOUPDATE/NOAUTOUPDATE settings found";
  816. }
  817. *found_autoupdate = true;
  818. if (line_trimmed == Autoupdate) {
  819. *autoupdate_line_number = line_index;
  820. }
  821. return true;
  822. }
  823. // Processes SET-* lines when found. Returns true if the line is consumed.
  824. static auto TryConsumeSetFlag(llvm::StringRef line_trimmed,
  825. llvm::StringLiteral flag_name, bool* flag)
  826. -> ErrorOr<bool> {
  827. if (!line_trimmed.consume_front("// ") || line_trimmed != flag_name) {
  828. return false;
  829. }
  830. if (*flag) {
  831. return ErrorBuilder() << flag_name << " was specified multiple times";
  832. }
  833. *flag = true;
  834. return true;
  835. }
  836. auto FileTestBase::ProcessTestFile(TestContext& context) -> ErrorOr<Success> {
  837. // Original file content, and a cursor for walking through it.
  838. llvm::StringRef file_content = context.input_content;
  839. llvm::StringRef cursor = file_content;
  840. // Whether either AUTOUDPATE or NOAUTOUPDATE was found.
  841. bool found_autoupdate = false;
  842. // The index in the current test file. Will be reset on splits.
  843. int line_index = 0;
  844. SplitState split;
  845. // When autoupdating, we track whether we're inside conflict markers.
  846. // Otherwise conflict markers are errors.
  847. bool inside_conflict_marker = false;
  848. while (!cursor.empty()) {
  849. auto [line, next_cursor] = cursor.split("\n");
  850. cursor = next_cursor;
  851. auto line_trimmed = line.ltrim();
  852. bool is_consumed = false;
  853. CARBON_ASSIGN_OR_RETURN(
  854. is_consumed,
  855. TryConsumeConflictMarker(line, line_trimmed, &inside_conflict_marker));
  856. if (is_consumed) {
  857. continue;
  858. }
  859. // At this point, remaining lines are part of the test input.
  860. CARBON_ASSIGN_OR_RETURN(
  861. is_consumed,
  862. TryConsumeSplit(line, line_trimmed, found_autoupdate, &line_index,
  863. &split, &context.test_files, &context.non_check_lines));
  864. if (is_consumed) {
  865. continue;
  866. }
  867. ++line_index;
  868. // TIP lines have no impact on validation.
  869. if (line_trimmed.starts_with("// TIP:")) {
  870. continue;
  871. }
  872. CARBON_ASSIGN_OR_RETURN(
  873. is_consumed,
  874. TryConsumeCheck(line_index, line, line_trimmed,
  875. &context.expected_stdout, &context.expected_stderr));
  876. if (is_consumed) {
  877. continue;
  878. }
  879. // At this point, lines are retained as non-CHECK lines.
  880. context.non_check_lines.push_back(
  881. FileTestLine(split.file_index, line_index, line));
  882. CARBON_ASSIGN_OR_RETURN(
  883. is_consumed, TryConsumeArgs(line, line_trimmed, &context.test_args,
  884. &context.extra_args));
  885. if (is_consumed) {
  886. continue;
  887. }
  888. CARBON_ASSIGN_OR_RETURN(
  889. is_consumed,
  890. TryConsumeAutoupdate(line_index, line_trimmed, &found_autoupdate,
  891. &context.autoupdate_line_number));
  892. if (is_consumed) {
  893. continue;
  894. }
  895. CARBON_ASSIGN_OR_RETURN(
  896. is_consumed,
  897. TryConsumeSetFlag(line_trimmed, "SET-CAPTURE-CONSOLE-OUTPUT",
  898. &context.capture_console_output));
  899. if (is_consumed) {
  900. continue;
  901. }
  902. CARBON_ASSIGN_OR_RETURN(is_consumed,
  903. TryConsumeSetFlag(line_trimmed, "SET-CHECK-SUBSET",
  904. &context.check_subset));
  905. if (is_consumed) {
  906. continue;
  907. }
  908. }
  909. if (!found_autoupdate) {
  910. return Error("Missing AUTOUPDATE/NOAUTOUPDATE setting");
  911. }
  912. context.has_splits = split.has_splits();
  913. CARBON_RETURN_IF_ERROR(FinishSplit(test_name_, &split, &context.test_files));
  914. // Validate AUTOUPDATE-SPLIT use, and remove it from test files if present.
  915. if (context.has_splits) {
  916. constexpr llvm::StringLiteral AutoupdateSplit = "AUTOUPDATE-SPLIT";
  917. for (const auto& test_file :
  918. llvm::ArrayRef(context.test_files).drop_back()) {
  919. if (test_file.filename == AutoupdateSplit) {
  920. return Error("AUTOUPDATE-SPLIT must be the last split");
  921. }
  922. }
  923. if (context.test_files.back().filename == AutoupdateSplit) {
  924. if (!context.autoupdate_line_number) {
  925. return Error("AUTOUPDATE-SPLIT requires AUTOUPDATE");
  926. }
  927. context.autoupdate_split = true;
  928. context.test_files.pop_back();
  929. }
  930. }
  931. // Assume there is always a suffix `\n` in output.
  932. if (!context.expected_stdout.empty()) {
  933. context.expected_stdout.push_back(StrEq(""));
  934. }
  935. if (!context.expected_stderr.empty()) {
  936. context.expected_stderr.push_back(StrEq(""));
  937. }
  938. return Success();
  939. }
  940. // Returns the tests to run.
  941. static auto GetTests() -> llvm::SmallVector<std::string> {
  942. // Prefer a user-specified list if present.
  943. auto specific_tests = absl::GetFlag(FLAGS_file_tests);
  944. if (!specific_tests.empty()) {
  945. return llvm::SmallVector<std::string>(specific_tests.begin(),
  946. specific_tests.end());
  947. }
  948. // Extracts tests from the target file.
  949. CARBON_CHECK(!absl::GetFlag(FLAGS_test_targets_file).empty(),
  950. "Missing --test_targets_file.");
  951. auto content = ReadFile(absl::GetFlag(FLAGS_test_targets_file));
  952. CARBON_CHECK(content.ok(), "{0}", content.error());
  953. llvm::SmallVector<std::string> all_tests;
  954. for (llvm::StringRef file_ref : llvm::split(*content, "\n")) {
  955. if (file_ref.empty()) {
  956. continue;
  957. }
  958. all_tests.push_back(file_ref.str());
  959. }
  960. return all_tests;
  961. }
  962. // Runs autoupdate for the given tests. This is multi-threaded to try to get a
  963. // little extra speed.
  964. static auto RunAutoupdate(llvm::StringRef exe_path,
  965. llvm::ArrayRef<std::string> tests,
  966. FileTestFactory& test_factory) -> int {
  967. llvm::CrashRecoveryContext::Enable();
  968. llvm::DefaultThreadPool pool(
  969. {.ThreadsRequested = absl::GetFlag(FLAGS_threads)});
  970. // Guard access to both `llvm::errs` and `crashed`.
  971. std::mutex mutex;
  972. bool crashed = false;
  973. for (const auto& test_name : tests) {
  974. pool.async([&test_factory, &mutex, &exe_path, &crashed, test_name] {
  975. // If any thread crashed, don't try running more.
  976. {
  977. std::unique_lock<std::mutex> lock(mutex);
  978. if (crashed) {
  979. return;
  980. }
  981. }
  982. // Use a crash recovery context to try to get a stack trace when
  983. // multiple threads may crash in parallel, which otherwise leads to the
  984. // program aborting without printing a stack trace.
  985. llvm::CrashRecoveryContext crc;
  986. crc.DumpStackAndCleanupOnFailure = true;
  987. bool thread_crashed = !crc.RunSafely([&] {
  988. std::unique_ptr<FileTestBase> test(
  989. test_factory.factory_fn(exe_path, &mutex, test_name));
  990. auto result = test->Autoupdate();
  991. std::unique_lock<std::mutex> lock(mutex);
  992. if (result.ok()) {
  993. llvm::errs() << (*result ? "!" : ".");
  994. } else {
  995. llvm::errs() << "\n" << result.error().message() << "\n";
  996. }
  997. });
  998. if (thread_crashed) {
  999. std::unique_lock<std::mutex> lock(mutex);
  1000. crashed = true;
  1001. }
  1002. });
  1003. }
  1004. pool.wait();
  1005. if (crashed) {
  1006. // Abort rather than returning so that we don't get a LeakSanitizer report.
  1007. // We expect to have leaked memory if one or more of our tests crashed.
  1008. std::abort();
  1009. }
  1010. llvm::errs() << "\nDone!\n";
  1011. return EXIT_SUCCESS;
  1012. }
  1013. // Implements main() within the Carbon::Testing namespace for convenience.
  1014. static auto Main(int argc, char** argv) -> int {
  1015. Carbon::InitLLVM init_llvm(argc, argv);
  1016. testing::InitGoogleTest(&argc, argv);
  1017. auto args = absl::ParseCommandLine(argc, argv);
  1018. if (args.size() > 1) {
  1019. llvm::errs() << "Unexpected arguments:";
  1020. for (char* arg : llvm::ArrayRef(args).drop_front()) {
  1021. llvm::errs() << " ";
  1022. llvm::errs().write_escaped(arg);
  1023. }
  1024. llvm::errs() << "\n";
  1025. return EXIT_FAILURE;
  1026. }
  1027. std::string exe_path = FindExecutablePath(argv[0]);
  1028. // Tests might try to read from stdin. Ensure those reads fail by closing
  1029. // stdin and reopening it as /dev/null. Note that STDIN_FILENO doesn't exist
  1030. // on Windows, but POSIX requires it to be 0.
  1031. if (std::error_code error =
  1032. llvm::sys::Process::SafelyCloseFileDescriptor(0)) {
  1033. llvm::errs() << "Unable to close standard input: " << error.message()
  1034. << "\n";
  1035. return EXIT_FAILURE;
  1036. }
  1037. if (std::error_code error =
  1038. llvm::sys::Process::FixupStandardFileDescriptors()) {
  1039. llvm::errs() << "Unable to correct standard file descriptors: "
  1040. << error.message() << "\n";
  1041. return EXIT_FAILURE;
  1042. }
  1043. if (absl::GetFlag(FLAGS_autoupdate) && absl::GetFlag(FLAGS_dump_output)) {
  1044. llvm::errs() << "--autoupdate and --dump_output are mutually exclusive.\n";
  1045. return EXIT_FAILURE;
  1046. }
  1047. llvm::SmallVector<std::string> tests = GetTests();
  1048. auto test_factory = GetFileTestFactory();
  1049. if (absl::GetFlag(FLAGS_autoupdate)) {
  1050. return RunAutoupdate(exe_path, tests, test_factory);
  1051. } else if (absl::GetFlag(FLAGS_dump_output)) {
  1052. for (const auto& test_name : tests) {
  1053. std::unique_ptr<FileTestBase> test(
  1054. test_factory.factory_fn(exe_path, nullptr, test_name));
  1055. auto result = test->DumpOutput();
  1056. if (!result.ok()) {
  1057. llvm::errs() << "\n" << result.error().message() << "\n";
  1058. }
  1059. }
  1060. llvm::errs() << "\nDone!\n";
  1061. return EXIT_SUCCESS;
  1062. } else {
  1063. for (const std::string& test_name : tests) {
  1064. testing::RegisterTest(
  1065. test_factory.name, test_name.c_str(), nullptr, test_name.c_str(),
  1066. __FILE__, __LINE__,
  1067. [&test_factory, &exe_path, test_name = test_name]() {
  1068. return test_factory.factory_fn(exe_path, nullptr, test_name);
  1069. });
  1070. }
  1071. return RUN_ALL_TESTS();
  1072. }
  1073. }
  1074. } // namespace Carbon::Testing
  1075. auto main(int argc, char** argv) -> int {
  1076. return Carbon::Testing::Main(argc, argv);
  1077. }