file_test_base.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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. // Reformats `[[@LSP:` and similar keyword as an LSP call with headers.
  462. static auto ReplaceLspKeywordAt(std::string* content, size_t keyword_pos,
  463. int& lsp_call_id) -> ErrorOr<size_t> {
  464. llvm::StringRef content_at_keyword =
  465. llvm::StringRef(*content).substr(keyword_pos);
  466. auto [keyword, body_start] = content_at_keyword.split(":");
  467. if (body_start.empty()) {
  468. return ErrorBuilder() << "Missing `:` for `"
  469. << content_at_keyword.take_front(10) << "`";
  470. }
  471. // Whether the first param is a method or id.
  472. llvm::StringRef method_or_id_label = "method";
  473. // Whether to attach the `lsp_call_id`.
  474. bool use_call_id = false;
  475. // The JSON label for extra content.
  476. llvm::StringRef extra_content_label;
  477. if (keyword == "[[@LSP-CALL") {
  478. use_call_id = true;
  479. extra_content_label = "params";
  480. } else if (keyword == "[[@LSP-NOTIFY") {
  481. extra_content_label = "params";
  482. } else if (keyword == "[[@LSP-REPLY") {
  483. method_or_id_label = "id";
  484. extra_content_label = "result";
  485. } else if (keyword != "[[@LSP") {
  486. return ErrorBuilder() << "Unrecognized @LSP keyword at `"
  487. << keyword.take_front(10) << "`";
  488. }
  489. static constexpr llvm::StringLiteral LspEnd = "]]";
  490. auto body_end = body_start.find(LspEnd);
  491. if (body_end == std::string::npos) {
  492. return ErrorBuilder() << "Missing `" << LspEnd << "` after `" << keyword
  493. << "`";
  494. }
  495. llvm::StringRef body = body_start.take_front(body_end);
  496. auto [method_or_id, extra_content] = body.split(":");
  497. // Form the JSON.
  498. std::string json = llvm::formatv(R"({{"jsonrpc": "2.0", "{0}": "{1}")",
  499. method_or_id_label, method_or_id);
  500. if (use_call_id) {
  501. // Omit quotes on the ID because we know it's an integer.
  502. json += llvm::formatv(R"(, "id": {0})", ++lsp_call_id);
  503. }
  504. if (!extra_content.empty()) {
  505. json += ",";
  506. if (extra_content_label.empty()) {
  507. if (!extra_content.starts_with("\n")) {
  508. json += " ";
  509. }
  510. json += extra_content;
  511. } else {
  512. json += llvm::formatv(R"( "{0}": {{{1}})", extra_content_label,
  513. extra_content);
  514. }
  515. }
  516. json += "}";
  517. // Add the Content-Length header. The `2` accounts for extra newlines.
  518. auto json_with_header =
  519. llvm::formatv("Content-Length: {0}\n\n{1}\n", json.size() + 2, json)
  520. .str();
  521. int keyword_len =
  522. (body_start.data() + body_end + LspEnd.size()) - keyword.data();
  523. content->replace(keyword_pos, keyword_len, json_with_header);
  524. return keyword_pos + json_with_header.size();
  525. }
  526. // Replaces the keyword at the given position. Returns the position to start a
  527. // find for the next keyword.
  528. static auto ReplaceContentKeywordAt(std::string* content, size_t keyword_pos,
  529. llvm::StringRef test_name, int& lsp_call_id)
  530. -> ErrorOr<size_t> {
  531. auto keyword = llvm::StringRef(*content).substr(keyword_pos);
  532. // Line replacements aren't handled here.
  533. static constexpr llvm::StringLiteral Line = "[[@LINE";
  534. if (keyword.starts_with(Line)) {
  535. // Just move past the prefix to find the next one.
  536. return keyword_pos + Line.size();
  537. }
  538. // Replaced with the actual test name.
  539. static constexpr llvm::StringLiteral TestName = "[[@TEST_NAME]]";
  540. if (keyword.starts_with(TestName)) {
  541. content->replace(keyword_pos, TestName.size(), test_name);
  542. return keyword_pos + test_name.size();
  543. }
  544. if (keyword.starts_with("[[@LSP")) {
  545. return ReplaceLspKeywordAt(content, keyword_pos, lsp_call_id);
  546. }
  547. return ErrorBuilder() << "Unexpected use of `[[@` at `"
  548. << keyword.substr(0, 5) << "`";
  549. }
  550. // Replaces the content keywords.
  551. //
  552. // TEST_NAME is the only content keyword at present, but we do validate that
  553. // other names are reserved.
  554. static auto ReplaceContentKeywords(llvm::StringRef filename,
  555. std::string* content) -> ErrorOr<Success> {
  556. static constexpr llvm::StringLiteral Prefix = "[[@";
  557. auto keyword_pos = content->find(Prefix);
  558. // Return early if not finding anything.
  559. if (keyword_pos == std::string::npos) {
  560. return Success();
  561. }
  562. // Construct the test name by getting the base name without the extension,
  563. // then removing any "fail_" or "todo_" prefixes.
  564. llvm::StringRef test_name = filename;
  565. if (auto last_slash = test_name.rfind("/");
  566. last_slash != llvm::StringRef::npos) {
  567. test_name = test_name.substr(last_slash + 1);
  568. }
  569. if (auto ext_dot = test_name.find("."); ext_dot != llvm::StringRef::npos) {
  570. test_name = test_name.substr(0, ext_dot);
  571. }
  572. // Note this also handles `fail_todo_` and `todo_fail_`.
  573. test_name.consume_front("todo_");
  574. test_name.consume_front("fail_");
  575. test_name.consume_front("todo_");
  576. // A counter for LSP calls.
  577. int lsp_call_id = 0;
  578. while (keyword_pos != std::string::npos) {
  579. CARBON_ASSIGN_OR_RETURN(
  580. auto keyword_end,
  581. ReplaceContentKeywordAt(content, keyword_pos, test_name, lsp_call_id));
  582. keyword_pos = content->find(Prefix, keyword_end);
  583. }
  584. return Success();
  585. }
  586. // Adds a file. Used for both split and unsplit test files.
  587. static auto AddTestFile(llvm::StringRef filename, std::string* content,
  588. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  589. -> ErrorOr<Success> {
  590. CARBON_RETURN_IF_ERROR(ReplaceContentKeywords(filename, content));
  591. test_files->push_back(
  592. {.filename = filename.str(), .content = std::move(*content)});
  593. content->clear();
  594. return Success();
  595. }
  596. // Process file split ("---") lines when found. Returns true if the line is
  597. // consumed.
  598. static auto TryConsumeSplit(
  599. llvm::StringRef line, llvm::StringRef line_trimmed, bool found_autoupdate,
  600. int* line_index, SplitState* split,
  601. llvm::SmallVector<FileTestBase::TestFile>* test_files,
  602. llvm::SmallVector<FileTestLine>* non_check_lines) -> ErrorOr<bool> {
  603. if (!line_trimmed.consume_front("// ---")) {
  604. if (!split->has_splits() && !line_trimmed.starts_with("//") &&
  605. !line_trimmed.empty()) {
  606. split->found_code_pre_split = true;
  607. }
  608. // Add the line to the current file's content (which may not be a split
  609. // file).
  610. split->add_content(line);
  611. return false;
  612. }
  613. if (!found_autoupdate) {
  614. // If there's a split, all output is appended at the end of each file
  615. // before AUTOUPDATE. We may want to change that, but it's not
  616. // necessary to handle right now.
  617. return ErrorBuilder() << "AUTOUPDATE/NOAUTOUPDATE setting must be in "
  618. "the first file.";
  619. }
  620. // On a file split, add the previous file, then start a new one.
  621. if (split->has_splits()) {
  622. CARBON_RETURN_IF_ERROR(
  623. AddTestFile(split->filename, &split->content, test_files));
  624. } else {
  625. split->content.clear();
  626. if (split->found_code_pre_split) {
  627. // For the first split, we make sure there was no content prior.
  628. return ErrorBuilder() << "When using split files, there must be no "
  629. "content before the first split file.";
  630. }
  631. }
  632. ++split->file_index;
  633. split->filename = line_trimmed.trim();
  634. if (split->filename.empty()) {
  635. return ErrorBuilder() << "Missing filename for split.";
  636. }
  637. // The split line is added to non_check_lines for retention in autoupdate, but
  638. // is not added to the test file content.
  639. *line_index = 0;
  640. non_check_lines->push_back(
  641. FileTestLine(split->file_index, *line_index, line));
  642. return true;
  643. }
  644. // Converts a `FileCheck`-style expectation string into a single complete regex
  645. // string by escaping all regex characters outside of the designated `{{...}}`
  646. // regex sequences, and switching those to a normal regex sub-pattern syntax.
  647. static void ConvertExpectationStringToRegex(std::string& str) {
  648. for (int pos = 0; pos < static_cast<int>(str.size());) {
  649. switch (str[pos]) {
  650. case '(':
  651. case ')':
  652. case '[':
  653. case ']':
  654. case '}':
  655. case '.':
  656. case '^':
  657. case '$':
  658. case '*':
  659. case '+':
  660. case '?':
  661. case '|':
  662. case '\\': {
  663. // Escape regex characters.
  664. str.insert(pos, "\\");
  665. pos += 2;
  666. break;
  667. }
  668. case '{': {
  669. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  670. // Single `{`, escape it.
  671. str.insert(pos, "\\");
  672. pos += 2;
  673. break;
  674. }
  675. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  676. str.replace(pos, 2, "(");
  677. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  678. if (str[pos] == '}' && str[pos + 1] == '}') {
  679. str.replace(pos, 2, ")");
  680. ++pos;
  681. break;
  682. }
  683. }
  684. break;
  685. }
  686. default: {
  687. ++pos;
  688. }
  689. }
  690. }
  691. }
  692. // Transforms an expectation on a given line from `FileCheck` syntax into a
  693. // standard regex matcher.
  694. static auto TransformExpectation(int line_index, llvm::StringRef in)
  695. -> ErrorOr<Matcher<std::string>> {
  696. if (in.empty()) {
  697. return Matcher<std::string>{StrEq("")};
  698. }
  699. if (!in.consume_front(" ")) {
  700. return ErrorBuilder() << "Malformated CHECK line: " << in;
  701. }
  702. // Check early if we have a regex component as we can avoid building an
  703. // expensive matcher when not using those.
  704. bool has_regex = in.find("{{") != llvm::StringRef::npos;
  705. // Now scan the string and expand any keywords. Note that this needs to be
  706. // `size_t` to correctly store `npos`.
  707. size_t keyword_pos = in.find("[[");
  708. // If there are neither keywords nor regex sequences, we can match the
  709. // incoming string directly.
  710. if (!has_regex && keyword_pos == llvm::StringRef::npos) {
  711. return Matcher<std::string>{StrEq(in)};
  712. }
  713. std::string str = in.str();
  714. // First expand the keywords.
  715. while (keyword_pos != std::string::npos) {
  716. llvm::StringRef line_keyword_cursor =
  717. llvm::StringRef(str).substr(keyword_pos);
  718. CARBON_CHECK(line_keyword_cursor.consume_front("[["));
  719. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  720. if (!line_keyword_cursor.consume_front(LineKeyword)) {
  721. return ErrorBuilder()
  722. << "Unexpected [[, should be {{\\[\\[}} at `"
  723. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  724. }
  725. // Allow + or - here; consumeInteger handles -.
  726. line_keyword_cursor.consume_front("+");
  727. int offset;
  728. // consumeInteger returns true for errors, not false.
  729. if (line_keyword_cursor.consumeInteger(10, offset) ||
  730. !line_keyword_cursor.consume_front("]]")) {
  731. return ErrorBuilder()
  732. << "Unexpected @LINE offset at `"
  733. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  734. }
  735. std::string int_str = llvm::Twine(line_index + offset).str();
  736. int remove_len = (line_keyword_cursor.data() - str.data()) - keyword_pos;
  737. str.replace(keyword_pos, remove_len, int_str);
  738. keyword_pos += int_str.size();
  739. // Find the next keyword start or the end of the string.
  740. keyword_pos = str.find("[[", keyword_pos);
  741. }
  742. // If there was no regex, we can directly match the adjusted string.
  743. if (!has_regex) {
  744. return Matcher<std::string>{StrEq(str)};
  745. }
  746. // Otherwise, we need to turn the entire string into a regex by escaping
  747. // things outside the regex region and transforming the regex region into a
  748. // normal syntax.
  749. ConvertExpectationStringToRegex(str);
  750. return Matcher<std::string>{MatchesRegex(str)};
  751. }
  752. // Once all content is processed, do any remaining split processing.
  753. static auto FinishSplit(llvm::StringRef test_name, SplitState* split,
  754. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  755. -> ErrorOr<Success> {
  756. if (split->has_splits()) {
  757. return AddTestFile(split->filename, &split->content, test_files);
  758. } else {
  759. // If no file splitting happened, use the main file as the test file.
  760. // There will always be a `/` unless tests are in the repo root.
  761. return AddTestFile(test_name.drop_front(test_name.rfind("/") + 1),
  762. &split->content, test_files);
  763. }
  764. }
  765. // Process CHECK lines when found. Returns true if the line is consumed.
  766. static auto TryConsumeCheck(
  767. int line_index, llvm::StringRef line, llvm::StringRef line_trimmed,
  768. llvm::SmallVector<testing::Matcher<std::string>>* expected_stdout,
  769. llvm::SmallVector<testing::Matcher<std::string>>* expected_stderr)
  770. -> ErrorOr<bool> {
  771. if (!line_trimmed.consume_front("// CHECK")) {
  772. return false;
  773. }
  774. // Don't build expectations when doing an autoupdate. We don't want to
  775. // break the autoupdate on an invalid CHECK line.
  776. if (!absl::GetFlag(FLAGS_autoupdate)) {
  777. llvm::SmallVector<Matcher<std::string>>* expected;
  778. if (line_trimmed.consume_front(":STDOUT:")) {
  779. expected = expected_stdout;
  780. } else if (line_trimmed.consume_front(":STDERR:")) {
  781. expected = expected_stderr;
  782. } else {
  783. return ErrorBuilder() << "Unexpected CHECK in input: " << line.str();
  784. }
  785. CARBON_ASSIGN_OR_RETURN(Matcher<std::string> check_matcher,
  786. TransformExpectation(line_index, line_trimmed));
  787. expected->push_back(check_matcher);
  788. }
  789. return true;
  790. }
  791. // Processes ARGS and EXTRA-ARGS lines when found. Returns true if the line is
  792. // consumed.
  793. static auto TryConsumeArgs(llvm::StringRef line, llvm::StringRef line_trimmed,
  794. llvm::SmallVector<std::string>* args,
  795. llvm::SmallVector<std::string>* extra_args)
  796. -> ErrorOr<bool> {
  797. llvm::SmallVector<std::string>* arg_list = nullptr;
  798. if (line_trimmed.consume_front("// ARGS: ")) {
  799. arg_list = args;
  800. } else if (line_trimmed.consume_front("// EXTRA-ARGS: ")) {
  801. arg_list = extra_args;
  802. } else {
  803. return false;
  804. }
  805. if (!args->empty() || !extra_args->empty()) {
  806. return ErrorBuilder() << "ARGS / EXTRA-ARGS specified multiple times: "
  807. << line.str();
  808. }
  809. // Split the line into arguments.
  810. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  811. llvm::getToken(line_trimmed);
  812. while (!cursor.first.empty()) {
  813. arg_list->push_back(std::string(cursor.first));
  814. cursor = llvm::getToken(cursor.second);
  815. }
  816. return true;
  817. }
  818. // Processes AUTOUPDATE lines when found. Returns true if the line is consumed.
  819. static auto TryConsumeAutoupdate(int line_index, llvm::StringRef line_trimmed,
  820. bool* found_autoupdate,
  821. std::optional<int>* autoupdate_line_number)
  822. -> ErrorOr<bool> {
  823. static constexpr llvm::StringLiteral Autoupdate = "// AUTOUPDATE";
  824. static constexpr llvm::StringLiteral NoAutoupdate = "// NOAUTOUPDATE";
  825. if (line_trimmed != Autoupdate && line_trimmed != NoAutoupdate) {
  826. return false;
  827. }
  828. if (*found_autoupdate) {
  829. return ErrorBuilder() << "Multiple AUTOUPDATE/NOAUTOUPDATE settings found";
  830. }
  831. *found_autoupdate = true;
  832. if (line_trimmed == Autoupdate) {
  833. *autoupdate_line_number = line_index;
  834. }
  835. return true;
  836. }
  837. // Processes SET-* lines when found. Returns true if the line is consumed.
  838. static auto TryConsumeSetFlag(llvm::StringRef line_trimmed,
  839. llvm::StringLiteral flag_name, bool* flag)
  840. -> ErrorOr<bool> {
  841. if (!line_trimmed.consume_front("// ") || line_trimmed != flag_name) {
  842. return false;
  843. }
  844. if (*flag) {
  845. return ErrorBuilder() << flag_name << " was specified multiple times";
  846. }
  847. *flag = true;
  848. return true;
  849. }
  850. auto FileTestBase::ProcessTestFile(TestContext& context) -> ErrorOr<Success> {
  851. // Original file content, and a cursor for walking through it.
  852. llvm::StringRef file_content = context.input_content;
  853. llvm::StringRef cursor = file_content;
  854. // Whether either AUTOUDPATE or NOAUTOUPDATE was found.
  855. bool found_autoupdate = false;
  856. // The index in the current test file. Will be reset on splits.
  857. int line_index = 0;
  858. SplitState split;
  859. // When autoupdating, we track whether we're inside conflict markers.
  860. // Otherwise conflict markers are errors.
  861. bool inside_conflict_marker = false;
  862. while (!cursor.empty()) {
  863. auto [line, next_cursor] = cursor.split("\n");
  864. cursor = next_cursor;
  865. auto line_trimmed = line.ltrim();
  866. bool is_consumed = false;
  867. CARBON_ASSIGN_OR_RETURN(
  868. is_consumed,
  869. TryConsumeConflictMarker(line, line_trimmed, &inside_conflict_marker));
  870. if (is_consumed) {
  871. continue;
  872. }
  873. // At this point, remaining lines are part of the test input.
  874. CARBON_ASSIGN_OR_RETURN(
  875. is_consumed,
  876. TryConsumeSplit(line, line_trimmed, found_autoupdate, &line_index,
  877. &split, &context.test_files, &context.non_check_lines));
  878. if (is_consumed) {
  879. continue;
  880. }
  881. ++line_index;
  882. // TIP lines have no impact on validation.
  883. if (line_trimmed.starts_with("// TIP:")) {
  884. continue;
  885. }
  886. CARBON_ASSIGN_OR_RETURN(
  887. is_consumed,
  888. TryConsumeCheck(line_index, line, line_trimmed,
  889. &context.expected_stdout, &context.expected_stderr));
  890. if (is_consumed) {
  891. continue;
  892. }
  893. // At this point, lines are retained as non-CHECK lines.
  894. context.non_check_lines.push_back(
  895. FileTestLine(split.file_index, line_index, line));
  896. CARBON_ASSIGN_OR_RETURN(
  897. is_consumed, TryConsumeArgs(line, line_trimmed, &context.test_args,
  898. &context.extra_args));
  899. if (is_consumed) {
  900. continue;
  901. }
  902. CARBON_ASSIGN_OR_RETURN(
  903. is_consumed,
  904. TryConsumeAutoupdate(line_index, line_trimmed, &found_autoupdate,
  905. &context.autoupdate_line_number));
  906. if (is_consumed) {
  907. continue;
  908. }
  909. CARBON_ASSIGN_OR_RETURN(
  910. is_consumed,
  911. TryConsumeSetFlag(line_trimmed, "SET-CAPTURE-CONSOLE-OUTPUT",
  912. &context.capture_console_output));
  913. if (is_consumed) {
  914. continue;
  915. }
  916. CARBON_ASSIGN_OR_RETURN(is_consumed,
  917. TryConsumeSetFlag(line_trimmed, "SET-CHECK-SUBSET",
  918. &context.check_subset));
  919. if (is_consumed) {
  920. continue;
  921. }
  922. }
  923. if (!found_autoupdate) {
  924. return Error("Missing AUTOUPDATE/NOAUTOUPDATE setting");
  925. }
  926. context.has_splits = split.has_splits();
  927. CARBON_RETURN_IF_ERROR(FinishSplit(test_name_, &split, &context.test_files));
  928. // Validate AUTOUPDATE-SPLIT use, and remove it from test files if present.
  929. if (context.has_splits) {
  930. constexpr llvm::StringLiteral AutoupdateSplit = "AUTOUPDATE-SPLIT";
  931. for (const auto& test_file :
  932. llvm::ArrayRef(context.test_files).drop_back()) {
  933. if (test_file.filename == AutoupdateSplit) {
  934. return Error("AUTOUPDATE-SPLIT must be the last split");
  935. }
  936. }
  937. if (context.test_files.back().filename == AutoupdateSplit) {
  938. if (!context.autoupdate_line_number) {
  939. return Error("AUTOUPDATE-SPLIT requires AUTOUPDATE");
  940. }
  941. context.autoupdate_split = true;
  942. context.test_files.pop_back();
  943. }
  944. }
  945. // Assume there is always a suffix `\n` in output.
  946. if (!context.expected_stdout.empty()) {
  947. context.expected_stdout.push_back(StrEq(""));
  948. }
  949. if (!context.expected_stderr.empty()) {
  950. context.expected_stderr.push_back(StrEq(""));
  951. }
  952. return Success();
  953. }
  954. // Returns the tests to run.
  955. static auto GetTests() -> llvm::SmallVector<std::string> {
  956. // Prefer a user-specified list if present.
  957. auto specific_tests = absl::GetFlag(FLAGS_file_tests);
  958. if (!specific_tests.empty()) {
  959. return llvm::SmallVector<std::string>(specific_tests.begin(),
  960. specific_tests.end());
  961. }
  962. // Extracts tests from the target file.
  963. CARBON_CHECK(!absl::GetFlag(FLAGS_test_targets_file).empty(),
  964. "Missing --test_targets_file.");
  965. auto content = ReadFile(absl::GetFlag(FLAGS_test_targets_file));
  966. CARBON_CHECK(content.ok(), "{0}", content.error());
  967. llvm::SmallVector<std::string> all_tests;
  968. for (llvm::StringRef file_ref : llvm::split(*content, "\n")) {
  969. if (file_ref.empty()) {
  970. continue;
  971. }
  972. all_tests.push_back(file_ref.str());
  973. }
  974. return all_tests;
  975. }
  976. // Runs autoupdate for the given tests. This is multi-threaded to try to get a
  977. // little extra speed.
  978. static auto RunAutoupdate(llvm::StringRef exe_path,
  979. llvm::ArrayRef<std::string> tests,
  980. FileTestFactory& test_factory) -> int {
  981. llvm::CrashRecoveryContext::Enable();
  982. llvm::DefaultThreadPool pool(
  983. {.ThreadsRequested = absl::GetFlag(FLAGS_threads)});
  984. // Guard access to both `llvm::errs` and `crashed`.
  985. std::mutex mutex;
  986. bool crashed = false;
  987. for (const auto& test_name : tests) {
  988. pool.async([&test_factory, &mutex, &exe_path, &crashed, test_name] {
  989. // If any thread crashed, don't try running more.
  990. {
  991. std::unique_lock<std::mutex> lock(mutex);
  992. if (crashed) {
  993. return;
  994. }
  995. }
  996. // Use a crash recovery context to try to get a stack trace when
  997. // multiple threads may crash in parallel, which otherwise leads to the
  998. // program aborting without printing a stack trace.
  999. llvm::CrashRecoveryContext crc;
  1000. crc.DumpStackAndCleanupOnFailure = true;
  1001. bool thread_crashed = !crc.RunSafely([&] {
  1002. std::unique_ptr<FileTestBase> test(
  1003. test_factory.factory_fn(exe_path, &mutex, test_name));
  1004. auto result = test->Autoupdate();
  1005. std::unique_lock<std::mutex> lock(mutex);
  1006. if (result.ok()) {
  1007. llvm::errs() << (*result ? "!" : ".");
  1008. } else {
  1009. llvm::errs() << "\n" << result.error().message() << "\n";
  1010. }
  1011. });
  1012. if (thread_crashed) {
  1013. std::unique_lock<std::mutex> lock(mutex);
  1014. crashed = true;
  1015. }
  1016. });
  1017. }
  1018. pool.wait();
  1019. if (crashed) {
  1020. // Abort rather than returning so that we don't get a LeakSanitizer report.
  1021. // We expect to have leaked memory if one or more of our tests crashed.
  1022. std::abort();
  1023. }
  1024. llvm::errs() << "\nDone!\n";
  1025. return EXIT_SUCCESS;
  1026. }
  1027. // Implements main() within the Carbon::Testing namespace for convenience.
  1028. static auto Main(int argc, char** argv) -> int {
  1029. Carbon::InitLLVM init_llvm(argc, argv);
  1030. testing::InitGoogleTest(&argc, argv);
  1031. auto args = absl::ParseCommandLine(argc, argv);
  1032. if (args.size() > 1) {
  1033. llvm::errs() << "Unexpected arguments:";
  1034. for (char* arg : llvm::ArrayRef(args).drop_front()) {
  1035. llvm::errs() << " ";
  1036. llvm::errs().write_escaped(arg);
  1037. }
  1038. llvm::errs() << "\n";
  1039. return EXIT_FAILURE;
  1040. }
  1041. std::string exe_path = FindExecutablePath(argv[0]);
  1042. // Tests might try to read from stdin. Ensure those reads fail by closing
  1043. // stdin and reopening it as /dev/null. Note that STDIN_FILENO doesn't exist
  1044. // on Windows, but POSIX requires it to be 0.
  1045. if (std::error_code error =
  1046. llvm::sys::Process::SafelyCloseFileDescriptor(0)) {
  1047. llvm::errs() << "Unable to close standard input: " << error.message()
  1048. << "\n";
  1049. return EXIT_FAILURE;
  1050. }
  1051. if (std::error_code error =
  1052. llvm::sys::Process::FixupStandardFileDescriptors()) {
  1053. llvm::errs() << "Unable to correct standard file descriptors: "
  1054. << error.message() << "\n";
  1055. return EXIT_FAILURE;
  1056. }
  1057. if (absl::GetFlag(FLAGS_autoupdate) && absl::GetFlag(FLAGS_dump_output)) {
  1058. llvm::errs() << "--autoupdate and --dump_output are mutually exclusive.\n";
  1059. return EXIT_FAILURE;
  1060. }
  1061. llvm::SmallVector<std::string> tests = GetTests();
  1062. auto test_factory = GetFileTestFactory();
  1063. if (absl::GetFlag(FLAGS_autoupdate)) {
  1064. return RunAutoupdate(exe_path, tests, test_factory);
  1065. } else if (absl::GetFlag(FLAGS_dump_output)) {
  1066. for (const auto& test_name : tests) {
  1067. std::unique_ptr<FileTestBase> test(
  1068. test_factory.factory_fn(exe_path, nullptr, test_name));
  1069. auto result = test->DumpOutput();
  1070. if (!result.ok()) {
  1071. llvm::errs() << "\n" << result.error().message() << "\n";
  1072. }
  1073. }
  1074. llvm::errs() << "\nDone!\n";
  1075. return EXIT_SUCCESS;
  1076. } else {
  1077. for (const std::string& test_name : tests) {
  1078. testing::RegisterTest(
  1079. test_factory.name, test_name.c_str(), nullptr, test_name.c_str(),
  1080. __FILE__, __LINE__,
  1081. [&test_factory, &exe_path, test_name = test_name]() {
  1082. return test_factory.factory_fn(exe_path, nullptr, test_name);
  1083. });
  1084. }
  1085. return RUN_ALL_TESTS();
  1086. }
  1087. }
  1088. } // namespace Carbon::Testing
  1089. auto main(int argc, char** argv) -> int {
  1090. return Carbon::Testing::Main(argc, argv);
  1091. }