file_test_base.cpp 41 KB

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