file_test_base.cpp 42 KB

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