file_test_base.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861
  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 <filesystem>
  6. #include <fstream>
  7. #include <optional>
  8. #include <string>
  9. #include <utility>
  10. #include "absl/flags/flag.h"
  11. #include "absl/flags/parse.h"
  12. #include "common/check.h"
  13. #include "common/error.h"
  14. #include "common/init_llvm.h"
  15. #include "gmock/gmock.h"
  16. #include "llvm/ADT/StringExtras.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Support/FormatVariadic.h"
  19. #include "llvm/Support/MemoryBuffer.h"
  20. #include "llvm/Support/PrettyStackTrace.h"
  21. #include "llvm/Support/Process.h"
  22. #include "llvm/Support/ThreadPool.h"
  23. #include "testing/file_test/autoupdate.h"
  24. ABSL_FLAG(std::vector<std::string>, file_tests, {},
  25. "A comma-separated list of repo-relative names of test files. "
  26. "Overrides test_targets_file.");
  27. ABSL_FLAG(std::string, test_targets_file, "",
  28. "A path to a file containing repo-relative names of test files.");
  29. ABSL_FLAG(bool, autoupdate, false,
  30. "Instead of verifying files match test output, autoupdate files "
  31. "based on test output.");
  32. ABSL_FLAG(unsigned int, threads, 0,
  33. "Number of threads to use when autoupdating tests, or 0 to "
  34. "automatically determine a thread count.");
  35. ABSL_FLAG(bool, dump_output, false,
  36. "Instead of verifying files match test output, directly dump output "
  37. "to stderr.");
  38. namespace Carbon::Testing {
  39. using ::testing::Matcher;
  40. using ::testing::MatchesRegex;
  41. using ::testing::StrEq;
  42. // Reads a file to string.
  43. static auto ReadFile(std::string_view path) -> std::string {
  44. std::ifstream proto_file(path);
  45. std::stringstream buffer;
  46. buffer << proto_file.rdbuf();
  47. proto_file.close();
  48. return buffer.str();
  49. }
  50. // Splits outputs to string_view because gtest handles string_view by default.
  51. static auto SplitOutput(llvm::StringRef output)
  52. -> llvm::SmallVector<std::string_view> {
  53. if (output.empty()) {
  54. return {};
  55. }
  56. llvm::SmallVector<llvm::StringRef> lines;
  57. llvm::StringRef(output).split(lines, "\n");
  58. return llvm::SmallVector<std::string_view>(lines.begin(), lines.end());
  59. }
  60. // Verify that the success and `fail_` prefix use correspond. Separately handle
  61. // both cases for clearer test failures.
  62. static auto CompareFailPrefix(llvm::StringRef filename, bool success) -> void {
  63. if (success) {
  64. EXPECT_FALSE(filename.starts_with("fail_"))
  65. << "`" << filename
  66. << "` succeeded; if this is correct, add a `fail_` prefix.";
  67. } else {
  68. EXPECT_TRUE(filename.starts_with("fail_"))
  69. << "`" << filename
  70. << "` failed; if this is correct, remove the `fail_` prefix.";
  71. }
  72. }
  73. // Runs a test and compares output. This keeps output split by line so that
  74. // issues are a little easier to identify by the different line.
  75. auto FileTestBase::TestBody() -> void {
  76. std::string test_command;
  77. std::optional<llvm::PrettyStackTraceString> stack_trace_entry;
  78. // If we're being run from bazel, provide some assistance for understanding
  79. // and reproducing failures.
  80. const char* target = getenv("TEST_TARGET");
  81. if (target) {
  82. constexpr const char* CommandFormat =
  83. "bazel {0} {1} --test_arg=--file_tests={2}";
  84. test_command = llvm::formatv(CommandFormat, "test", target, test_name_);
  85. // Add a crash trace entry with the run command.
  86. stack_trace_entry.emplace(test_command.c_str());
  87. // This advice overrides the --file_tests flag provided by the file_test
  88. // rule.
  89. llvm::errs() << "\nTo test this file alone, run:\n " << test_command
  90. << "\n\nTo view output, run:\n "
  91. << llvm::formatv(CommandFormat, "run", target, test_name_)
  92. << " --test_arg=--dump_output\n\n";
  93. }
  94. TestContext context;
  95. auto run_result = ProcessTestFileAndRun(context);
  96. ASSERT_TRUE(run_result.ok()) << run_result.error();
  97. ValidateRun();
  98. auto test_filename = std::filesystem::path(test_name_.str()).filename();
  99. // Check success/failure against `fail_` prefixes.
  100. if (context.run_result.per_file_success.empty()) {
  101. CompareFailPrefix(test_filename.string(), context.run_result.success);
  102. } else {
  103. bool require_overall_failure = false;
  104. for (const auto& [filename, success] :
  105. context.run_result.per_file_success) {
  106. CompareFailPrefix(filename, success);
  107. if (!success) {
  108. require_overall_failure = true;
  109. }
  110. }
  111. if (require_overall_failure) {
  112. EXPECT_FALSE(context.run_result.success)
  113. << "There is a per-file failure expectation, so the overall result "
  114. "should have been a failure.";
  115. } else {
  116. // Individual files all succeeded, so the prefix is enforced on the main
  117. // test file.
  118. CompareFailPrefix(test_filename.string(), context.run_result.success);
  119. }
  120. }
  121. // Check results. Include a reminder of the autoupdate command for any
  122. // stdout/stderr differences.
  123. std::string update_message;
  124. if (target && context.autoupdate_line_number) {
  125. update_message = llvm::formatv(
  126. "If these differences are expected, try the autoupdater:\n"
  127. "\tbazel run {0} -- --autoupdate --file_tests={1}",
  128. target, test_name_);
  129. } else {
  130. update_message =
  131. "If these differences are expected, content must be updated manually.";
  132. }
  133. SCOPED_TRACE(update_message);
  134. if (context.check_subset) {
  135. EXPECT_THAT(SplitOutput(context.stdout),
  136. IsSupersetOf(context.expected_stdout));
  137. EXPECT_THAT(SplitOutput(context.stderr),
  138. IsSupersetOf(context.expected_stderr));
  139. } else {
  140. EXPECT_THAT(SplitOutput(context.stdout),
  141. ElementsAreArray(context.expected_stdout));
  142. EXPECT_THAT(SplitOutput(context.stderr),
  143. ElementsAreArray(context.expected_stderr));
  144. }
  145. // If there are no other test failures, check if autoupdate would make
  146. // changes. We don't do this when there _are_ failures because the
  147. // SCOPED_TRACE already contains the autoupdate reminder.
  148. if (!HasFailure() && RunAutoupdater(context, /*dry_run=*/true)) {
  149. ADD_FAILURE() << "Autoupdate would make changes to the file content.";
  150. }
  151. }
  152. auto FileTestBase::RunAutoupdater(const TestContext& context, bool dry_run)
  153. -> bool {
  154. if (!context.autoupdate_line_number) {
  155. return false;
  156. }
  157. llvm::SmallVector<llvm::StringRef> filenames;
  158. filenames.reserve(context.non_check_lines.size());
  159. if (context.has_splits) {
  160. // There are splits, so we provide an empty name for the first file.
  161. filenames.push_back({});
  162. }
  163. for (const auto& file : context.test_files) {
  164. filenames.push_back(file.filename);
  165. }
  166. llvm::ArrayRef expected_filenames = filenames;
  167. if (filenames.size() > 1) {
  168. expected_filenames = expected_filenames.drop_front();
  169. }
  170. return FileTestAutoupdater(
  171. std::filesystem::absolute(test_name_.str()), context.input_content,
  172. filenames, *context.autoupdate_line_number,
  173. context.non_check_lines, context.stdout, context.stderr,
  174. GetDefaultFileRE(expected_filenames),
  175. GetLineNumberReplacements(expected_filenames),
  176. [&](std::string& line) { DoExtraCheckReplacements(line); })
  177. .Run(dry_run);
  178. }
  179. auto FileTestBase::Autoupdate() -> ErrorOr<bool> {
  180. // Add a crash trace entry mentioning which file we're updating.
  181. std::string stack_trace_string =
  182. llvm::formatv("performing autoupdate for {0}", test_name_);
  183. llvm::PrettyStackTraceString stack_trace_entry(stack_trace_string.c_str());
  184. TestContext context;
  185. auto run_result = ProcessTestFileAndRun(context);
  186. if (!run_result.ok()) {
  187. return ErrorBuilder() << "Error updating " << test_name_ << ": "
  188. << run_result.error();
  189. }
  190. return RunAutoupdater(context, /*dry_run=*/false);
  191. }
  192. auto FileTestBase::DumpOutput() -> ErrorOr<Success> {
  193. TestContext context;
  194. std::string banner(79, '=');
  195. banner.append("\n");
  196. llvm::errs() << banner << "= " << test_name_ << "\n";
  197. auto run_result = ProcessTestFileAndRun(context);
  198. if (!run_result.ok()) {
  199. return ErrorBuilder() << "Error updating " << test_name_ << ": "
  200. << run_result.error();
  201. }
  202. llvm::errs() << banner << "= stderr\n"
  203. << banner << context.stderr << banner << "= stdout\n"
  204. << banner << context.stdout << banner << "= Exit with success: "
  205. << (context.run_result.success ? "true" : "false") << "\n"
  206. << banner;
  207. return Success();
  208. }
  209. auto FileTestBase::GetLineNumberReplacements(
  210. llvm::ArrayRef<llvm::StringRef> filenames)
  211. -> llvm::SmallVector<LineNumberReplacement> {
  212. return {{.has_file = true,
  213. .re = std::make_shared<RE2>(
  214. llvm::formatv(R"(({0}):(\d+))", llvm::join(filenames, "|"))),
  215. .line_formatv = R"({0})"}};
  216. }
  217. auto FileTestBase::ProcessTestFileAndRun(TestContext& context)
  218. -> ErrorOr<Success> {
  219. // Store the file so that test_files can use references to content.
  220. context.input_content = ReadFile(test_name_);
  221. // Load expected output.
  222. CARBON_RETURN_IF_ERROR(ProcessTestFile(context));
  223. // Process arguments.
  224. if (context.test_args.empty()) {
  225. context.test_args = GetDefaultArgs();
  226. }
  227. CARBON_RETURN_IF_ERROR(
  228. DoArgReplacements(context.test_args, context.test_files));
  229. // Create the files in-memory.
  230. llvm::vfs::InMemoryFileSystem fs;
  231. for (const auto& test_file : context.test_files) {
  232. if (!fs.addFile(test_file.filename, /*ModificationTime=*/0,
  233. llvm::MemoryBuffer::getMemBuffer(
  234. test_file.content, test_file.filename,
  235. /*RequiresNullTerminator=*/false))) {
  236. return ErrorBuilder() << "File is repeated: " << test_file.filename;
  237. }
  238. }
  239. // Convert the arguments to StringRef and const char* to match the
  240. // expectations of PrettyStackTraceProgram and Run.
  241. llvm::SmallVector<llvm::StringRef> test_args_ref;
  242. llvm::SmallVector<const char*> test_argv_for_stack_trace;
  243. test_args_ref.reserve(context.test_args.size());
  244. test_argv_for_stack_trace.reserve(context.test_args.size() + 1);
  245. for (const auto& arg : context.test_args) {
  246. test_args_ref.push_back(arg);
  247. test_argv_for_stack_trace.push_back(arg.c_str());
  248. }
  249. // Add a trailing null so that this is a proper argv.
  250. test_argv_for_stack_trace.push_back(nullptr);
  251. // Add a stack trace entry for the test invocation.
  252. llvm::PrettyStackTraceProgram stack_trace_entry(
  253. test_argv_for_stack_trace.size() - 1, test_argv_for_stack_trace.data());
  254. // Capture trace streaming, but only when in debug mode.
  255. llvm::raw_svector_ostream stdout(context.stdout);
  256. llvm::raw_svector_ostream stderr(context.stderr);
  257. CARBON_ASSIGN_OR_RETURN(context.run_result,
  258. Run(test_args_ref, fs, stdout, stderr));
  259. return Success();
  260. }
  261. auto FileTestBase::DoArgReplacements(
  262. llvm::SmallVector<std::string>& test_args,
  263. const llvm::SmallVector<TestFile>& test_files) -> ErrorOr<Success> {
  264. for (auto* it = test_args.begin(); it != test_args.end(); ++it) {
  265. auto percent = it->find("%");
  266. if (percent == std::string::npos) {
  267. continue;
  268. }
  269. if (percent + 1 >= it->size()) {
  270. return ErrorBuilder() << "% is not allowed on its own: " << *it;
  271. }
  272. char c = (*it)[percent + 1];
  273. switch (c) {
  274. case 's': {
  275. if (*it != "%s") {
  276. return ErrorBuilder() << "%s must be the full argument: " << *it;
  277. }
  278. it = test_args.erase(it);
  279. for (const auto& file : test_files) {
  280. it = test_args.insert(it, file.filename);
  281. ++it;
  282. }
  283. // Back up once because the for loop will advance.
  284. --it;
  285. break;
  286. }
  287. case 't': {
  288. char* tmpdir = getenv("TEST_TMPDIR");
  289. CARBON_CHECK(tmpdir != nullptr);
  290. it->replace(percent, 2, llvm::formatv("{0}/temp_file", tmpdir));
  291. break;
  292. }
  293. default:
  294. return ErrorBuilder() << "%" << c << " is not supported: " << *it;
  295. }
  296. }
  297. return Success();
  298. }
  299. // Processes conflict markers, including tracking of whether code is within a
  300. // conflict marker. Returns true if the line is consumed.
  301. static auto TryConsumeConflictMarker(llvm::StringRef line,
  302. llvm::StringRef line_trimmed,
  303. bool* inside_conflict_marker)
  304. -> ErrorOr<bool> {
  305. bool is_start = line.starts_with("<<<<<<<");
  306. bool is_middle = line.starts_with("=======") || line.starts_with("|||||||");
  307. bool is_end = line.starts_with(">>>>>>>");
  308. // When running the test, any conflict marker is an error.
  309. if (!absl::GetFlag(FLAGS_autoupdate) && (is_start || is_middle || is_end)) {
  310. return ErrorBuilder() << "Conflict marker found:\n" << line;
  311. }
  312. // Autoupdate tracks conflict markers for context, and will discard
  313. // conflicting lines when it can autoupdate them.
  314. if (*inside_conflict_marker) {
  315. if (is_start) {
  316. return ErrorBuilder() << "Unexpected conflict marker inside conflict:\n"
  317. << line;
  318. }
  319. if (is_middle) {
  320. return true;
  321. }
  322. if (is_end) {
  323. *inside_conflict_marker = false;
  324. return true;
  325. }
  326. // Look for CHECK lines, which can be discarded.
  327. if (line_trimmed.starts_with("// CHECK:STDOUT:") ||
  328. line_trimmed.starts_with("// CHECK:STDERR:")) {
  329. return true;
  330. }
  331. return ErrorBuilder()
  332. << "Autoupdate can't discard non-CHECK lines inside conflicts:\n"
  333. << line;
  334. } else {
  335. if (is_start) {
  336. *inside_conflict_marker = true;
  337. return true;
  338. }
  339. if (is_middle || is_end) {
  340. return ErrorBuilder() << "Unexpected conflict marker outside conflict:\n"
  341. << line;
  342. }
  343. return false;
  344. }
  345. }
  346. // State for file splitting logic: TryConsumeSplit and FinishSplit.
  347. struct SplitState {
  348. auto has_splits() const -> bool { return file_index > 0; }
  349. auto add_content(llvm::StringRef line) -> void {
  350. content.append(line);
  351. content.append("\n");
  352. }
  353. // Whether content has been found. Only updated before a file split is found
  354. // (which may be never).
  355. bool found_code_pre_split = false;
  356. // The current file name, considering splits. Empty for the default file.
  357. llvm::StringRef filename = "";
  358. // The accumulated content for the file being built. This may elide some of
  359. // the original content, such as conflict markers.
  360. std::string content;
  361. // The current file index.
  362. int file_index = 0;
  363. };
  364. // Adds a file. Used for both split and unsplit test files.
  365. static auto AddTestFile(llvm::StringRef filename, std::string* content,
  366. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  367. -> void {
  368. test_files->push_back(
  369. {.filename = filename.str(), .content = std::move(*content)});
  370. content->clear();
  371. }
  372. // Process file split ("---") lines when found. Returns true if the line is
  373. // consumed.
  374. static auto TryConsumeSplit(
  375. llvm::StringRef line, llvm::StringRef line_trimmed, bool found_autoupdate,
  376. int* line_index, SplitState* split,
  377. llvm::SmallVector<FileTestBase::TestFile>* test_files,
  378. llvm::SmallVector<FileTestLine>* non_check_lines) -> ErrorOr<bool> {
  379. if (!line_trimmed.consume_front("// ---")) {
  380. if (!split->has_splits() && !line_trimmed.starts_with("//") &&
  381. !line_trimmed.empty()) {
  382. split->found_code_pre_split = true;
  383. }
  384. // Add the line to the current file's content (which may not be a split
  385. // file).
  386. split->add_content(line);
  387. return false;
  388. }
  389. if (!found_autoupdate) {
  390. // If there's a split, all output is appended at the end of each file
  391. // before AUTOUPDATE. We may want to change that, but it's not
  392. // necessary to handle right now.
  393. return ErrorBuilder() << "AUTOUPDATE/NOAUTOUPDATE setting must be in "
  394. "the first file.";
  395. }
  396. // On a file split, add the previous file, then start a new one.
  397. if (split->has_splits()) {
  398. AddTestFile(split->filename, &split->content, test_files);
  399. } else {
  400. split->content.clear();
  401. if (split->found_code_pre_split) {
  402. // For the first split, we make sure there was no content prior.
  403. return ErrorBuilder() << "When using split files, there must be no "
  404. "content before the first split file.";
  405. }
  406. }
  407. ++split->file_index;
  408. split->filename = line_trimmed.trim();
  409. if (split->filename.empty()) {
  410. return ErrorBuilder() << "Missing filename for split.";
  411. }
  412. // The split line is added to non_check_lines for retention in autoupdate, but
  413. // is not added to the test file content.
  414. *line_index = 0;
  415. non_check_lines->push_back(
  416. FileTestLine(split->file_index, *line_index, line));
  417. return true;
  418. }
  419. // Transforms an expectation on a given line from `FileCheck` syntax into a
  420. // standard regex matcher.
  421. static auto TransformExpectation(int line_index, llvm::StringRef in)
  422. -> ErrorOr<Matcher<std::string>> {
  423. if (in.empty()) {
  424. return Matcher<std::string>{StrEq("")};
  425. }
  426. if (in[0] != ' ') {
  427. return ErrorBuilder() << "Malformated CHECK line: " << in;
  428. }
  429. std::string str = in.substr(1).str();
  430. for (int pos = 0; pos < static_cast<int>(str.size());) {
  431. switch (str[pos]) {
  432. case '(':
  433. case ')':
  434. case ']':
  435. case '}':
  436. case '.':
  437. case '^':
  438. case '$':
  439. case '*':
  440. case '+':
  441. case '?':
  442. case '|':
  443. case '\\': {
  444. // Escape regex characters.
  445. str.insert(pos, "\\");
  446. pos += 2;
  447. break;
  448. }
  449. case '[': {
  450. llvm::StringRef line_keyword_cursor = llvm::StringRef(str).substr(pos);
  451. if (line_keyword_cursor.consume_front("[[")) {
  452. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  453. if (line_keyword_cursor.consume_front(LineKeyword)) {
  454. // Allow + or - here; consumeInteger handles -.
  455. line_keyword_cursor.consume_front("+");
  456. int offset;
  457. // consumeInteger returns true for errors, not false.
  458. if (line_keyword_cursor.consumeInteger(10, offset) ||
  459. !line_keyword_cursor.consume_front("]]")) {
  460. return ErrorBuilder()
  461. << "Unexpected @LINE offset at `"
  462. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  463. }
  464. std::string int_str = llvm::Twine(line_index + offset).str();
  465. int remove_len = (line_keyword_cursor.data() - str.data()) - pos;
  466. str.replace(pos, remove_len, int_str);
  467. pos += int_str.size();
  468. } else {
  469. return ErrorBuilder()
  470. << "Unexpected [[, should be {{\\[\\[}} at `"
  471. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  472. }
  473. } else {
  474. // Escape the `[`.
  475. str.insert(pos, "\\");
  476. pos += 2;
  477. }
  478. break;
  479. }
  480. case '{': {
  481. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  482. // Single `{`, escape it.
  483. str.insert(pos, "\\");
  484. pos += 2;
  485. } else {
  486. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  487. str.replace(pos, 2, "(");
  488. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  489. if (str[pos] == '}' && str[pos + 1] == '}') {
  490. str.replace(pos, 2, ")");
  491. ++pos;
  492. break;
  493. }
  494. }
  495. }
  496. break;
  497. }
  498. default: {
  499. ++pos;
  500. }
  501. }
  502. }
  503. return Matcher<std::string>{MatchesRegex(str)};
  504. }
  505. // Once all content is processed, do any remaining split processing.
  506. static auto FinishSplit(llvm::StringRef test_name, SplitState* split,
  507. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  508. -> void {
  509. if (split->has_splits()) {
  510. AddTestFile(split->filename, &split->content, test_files);
  511. } else {
  512. // If no file splitting happened, use the main file as the test file.
  513. // There will always be a `/` unless tests are in the repo root.
  514. AddTestFile(test_name.drop_front(test_name.rfind("/") + 1), &split->content,
  515. test_files);
  516. }
  517. }
  518. // Process CHECK lines when found. Returns true if the line is consumed.
  519. static auto TryConsumeCheck(
  520. int line_index, llvm::StringRef line, llvm::StringRef line_trimmed,
  521. llvm::SmallVector<testing::Matcher<std::string>>* expected_stdout,
  522. llvm::SmallVector<testing::Matcher<std::string>>* expected_stderr)
  523. -> ErrorOr<bool> {
  524. if (!line_trimmed.consume_front("// CHECK")) {
  525. return false;
  526. }
  527. // Don't build expectations when doing an autoupdate. We don't want to
  528. // break the autoupdate on an invalid CHECK line.
  529. if (!absl::GetFlag(FLAGS_autoupdate)) {
  530. llvm::SmallVector<Matcher<std::string>>* expected;
  531. if (line_trimmed.consume_front(":STDOUT:")) {
  532. expected = expected_stdout;
  533. } else if (line_trimmed.consume_front(":STDERR:")) {
  534. expected = expected_stderr;
  535. } else {
  536. return ErrorBuilder() << "Unexpected CHECK in input: " << line.str();
  537. }
  538. CARBON_ASSIGN_OR_RETURN(Matcher<std::string> check_matcher,
  539. TransformExpectation(line_index, line_trimmed));
  540. expected->push_back(check_matcher);
  541. }
  542. return true;
  543. }
  544. // Processes ARGS lines when found. Returns true if the line is consumed.
  545. static auto TryConsumeArgs(llvm::StringRef line, llvm::StringRef line_trimmed,
  546. llvm::SmallVector<std::string>* args)
  547. -> ErrorOr<bool> {
  548. if (!line_trimmed.consume_front("// ARGS: ")) {
  549. return false;
  550. }
  551. if (!args->empty()) {
  552. return ErrorBuilder() << "ARGS was specified multiple times: "
  553. << line.str();
  554. }
  555. // Split the line into arguments.
  556. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  557. llvm::getToken(line_trimmed);
  558. while (!cursor.first.empty()) {
  559. args->push_back(std::string(cursor.first));
  560. cursor = llvm::getToken(cursor.second);
  561. }
  562. return true;
  563. }
  564. // Processes AUTOUPDATE lines when found. Returns true if the line is consumed.
  565. static auto TryConsumeAutoupdate(int line_index, llvm::StringRef line_trimmed,
  566. bool* found_autoupdate,
  567. std::optional<int>* autoupdate_line_number)
  568. -> ErrorOr<bool> {
  569. static constexpr llvm::StringLiteral Autoupdate = "// AUTOUPDATE";
  570. static constexpr llvm::StringLiteral NoAutoupdate = "// NOAUTOUPDATE";
  571. if (line_trimmed != Autoupdate && line_trimmed != NoAutoupdate) {
  572. return false;
  573. }
  574. if (*found_autoupdate) {
  575. return ErrorBuilder() << "Multiple AUTOUPDATE/NOAUTOUPDATE settings found";
  576. }
  577. *found_autoupdate = true;
  578. if (line_trimmed == Autoupdate) {
  579. *autoupdate_line_number = line_index;
  580. }
  581. return true;
  582. }
  583. // Processes SET-CHECK-SUBSET lines when found. Returns true if the line is
  584. // consumed.
  585. static auto TryConsumeSetCheckSubset(llvm::StringRef line_trimmed,
  586. bool* check_subset) -> ErrorOr<bool> {
  587. if (line_trimmed != "// SET-CHECK-SUBSET") {
  588. return false;
  589. }
  590. if (*check_subset) {
  591. return ErrorBuilder() << "SET-CHECK-SUBSET was specified multiple times";
  592. }
  593. *check_subset = true;
  594. return true;
  595. }
  596. auto FileTestBase::ProcessTestFile(TestContext& context) -> ErrorOr<Success> {
  597. // Original file content, and a cursor for walking through it.
  598. llvm::StringRef file_content = context.input_content;
  599. llvm::StringRef cursor = file_content;
  600. // Whether either AUTOUDPATE or NOAUTOUPDATE was found.
  601. bool found_autoupdate = false;
  602. // The index in the current test file. Will be reset on splits.
  603. int line_index = 0;
  604. SplitState split;
  605. // When autoupdating, we track whether we're inside conflict markers.
  606. // Otherwise conflict markers are errors.
  607. bool inside_conflict_marker = false;
  608. while (!cursor.empty()) {
  609. auto [line, next_cursor] = cursor.split("\n");
  610. cursor = next_cursor;
  611. auto line_trimmed = line.ltrim();
  612. bool is_consumed = false;
  613. CARBON_ASSIGN_OR_RETURN(
  614. is_consumed,
  615. TryConsumeConflictMarker(line, line_trimmed, &inside_conflict_marker));
  616. if (is_consumed) {
  617. continue;
  618. }
  619. // At this point, remaining lines are part of the test input.
  620. CARBON_ASSIGN_OR_RETURN(
  621. is_consumed,
  622. TryConsumeSplit(line, line_trimmed, found_autoupdate, &line_index,
  623. &split, &context.test_files, &context.non_check_lines));
  624. if (is_consumed) {
  625. continue;
  626. }
  627. ++line_index;
  628. CARBON_ASSIGN_OR_RETURN(
  629. is_consumed,
  630. TryConsumeCheck(line_index, line, line_trimmed,
  631. &context.expected_stdout, &context.expected_stderr));
  632. if (is_consumed) {
  633. continue;
  634. }
  635. // At this point, lines are retained as non-CHECK lines.
  636. context.non_check_lines.push_back(
  637. FileTestLine(split.file_index, line_index, line));
  638. CARBON_ASSIGN_OR_RETURN(
  639. is_consumed, TryConsumeArgs(line, line_trimmed, &context.test_args));
  640. if (is_consumed) {
  641. continue;
  642. }
  643. CARBON_ASSIGN_OR_RETURN(
  644. is_consumed,
  645. TryConsumeAutoupdate(line_index, line_trimmed, &found_autoupdate,
  646. &context.autoupdate_line_number));
  647. if (is_consumed) {
  648. continue;
  649. }
  650. CARBON_ASSIGN_OR_RETURN(
  651. is_consumed,
  652. TryConsumeSetCheckSubset(line_trimmed, &context.check_subset));
  653. if (is_consumed) {
  654. continue;
  655. }
  656. }
  657. if (!found_autoupdate) {
  658. return ErrorBuilder() << "Missing AUTOUPDATE/NOAUTOUPDATE setting";
  659. }
  660. context.has_splits = split.has_splits();
  661. FinishSplit(test_name_, &split, &context.test_files);
  662. // Assume there is always a suffix `\n` in output.
  663. if (!context.expected_stdout.empty()) {
  664. context.expected_stdout.push_back(StrEq(""));
  665. }
  666. if (!context.expected_stderr.empty()) {
  667. context.expected_stderr.push_back(StrEq(""));
  668. }
  669. return Success();
  670. }
  671. // Returns the tests to run.
  672. static auto GetTests() -> llvm::SmallVector<std::string> {
  673. // Prefer a user-specified list if present.
  674. auto specific_tests = absl::GetFlag(FLAGS_file_tests);
  675. if (!specific_tests.empty()) {
  676. return llvm::SmallVector<std::string>(specific_tests.begin(),
  677. specific_tests.end());
  678. }
  679. // Extracts tests from the target file.
  680. CARBON_CHECK(!absl::GetFlag(FLAGS_test_targets_file).empty())
  681. << "Missing --test_targets_file.";
  682. auto content = ReadFile(absl::GetFlag(FLAGS_test_targets_file));
  683. llvm::SmallVector<std::string> all_tests;
  684. for (llvm::StringRef file_ref : llvm::split(content, "\n")) {
  685. if (file_ref.empty()) {
  686. continue;
  687. }
  688. all_tests.push_back(file_ref.str());
  689. }
  690. return all_tests;
  691. }
  692. // Implements main() within the Carbon::Testing namespace for convenience.
  693. static auto Main(int argc, char** argv) -> int {
  694. Carbon::InitLLVM init_llvm(argc, argv);
  695. testing::InitGoogleTest(&argc, argv);
  696. auto args = absl::ParseCommandLine(argc, argv);
  697. if (args.size() > 1) {
  698. llvm::errs() << "Unexpected arguments:";
  699. for (char* arg : llvm::ArrayRef(args).drop_front()) {
  700. llvm::errs() << " ";
  701. llvm::errs().write_escaped(arg);
  702. }
  703. llvm::errs() << "\n";
  704. return EXIT_FAILURE;
  705. }
  706. // Tests might try to read from stdin. Ensure those reads fail by closing
  707. // stdin and reopening it as /dev/null. Note that STDIN_FILENO doesn't exist
  708. // on Windows, but POSIX requires it to be 0.
  709. if (std::error_code error =
  710. llvm::sys::Process::SafelyCloseFileDescriptor(0)) {
  711. llvm::errs() << "Unable to close standard input: " << error.message()
  712. << "\n";
  713. return EXIT_FAILURE;
  714. }
  715. if (std::error_code error =
  716. llvm::sys::Process::FixupStandardFileDescriptors()) {
  717. llvm::errs() << "Unable to correct standard file descriptors: "
  718. << error.message() << "\n";
  719. return EXIT_FAILURE;
  720. }
  721. if (absl::GetFlag(FLAGS_autoupdate) && absl::GetFlag(FLAGS_dump_output)) {
  722. llvm::errs() << "--autoupdate and --dump_output are mutually exclusive.\n";
  723. return EXIT_FAILURE;
  724. }
  725. llvm::SmallVector<std::string> tests = GetTests();
  726. auto test_factory = GetFileTestFactory();
  727. if (absl::GetFlag(FLAGS_autoupdate)) {
  728. llvm::DefaultThreadPool pool(
  729. {.ThreadsRequested = absl::GetFlag(FLAGS_threads)});
  730. std::mutex errs_mutex;
  731. for (const auto& test_name : tests) {
  732. pool.async([&test_factory, &errs_mutex, test_name] {
  733. std::unique_ptr<FileTestBase> test(test_factory.factory_fn(test_name));
  734. auto result = test->Autoupdate();
  735. // Guard access to llvm::errs, which is not thread-safe.
  736. std::unique_lock<std::mutex> lock(errs_mutex);
  737. if (result.ok()) {
  738. llvm::errs() << (*result ? "!" : ".");
  739. } else {
  740. llvm::errs() << "\n" << result.error().message() << "\n";
  741. }
  742. });
  743. }
  744. pool.wait();
  745. llvm::errs() << "\nDone!\n";
  746. return EXIT_SUCCESS;
  747. } else if (absl::GetFlag(FLAGS_dump_output)) {
  748. for (const auto& test_name : tests) {
  749. std::unique_ptr<FileTestBase> test(test_factory.factory_fn(test_name));
  750. auto result = test->DumpOutput();
  751. if (!result.ok()) {
  752. llvm::errs() << "\n" << result.error().message() << "\n";
  753. }
  754. }
  755. llvm::errs() << "\nDone!\n";
  756. return EXIT_SUCCESS;
  757. } else {
  758. for (llvm::StringRef test_name : tests) {
  759. testing::RegisterTest(test_factory.name, test_name.data(), nullptr,
  760. test_name.data(), __FILE__, __LINE__,
  761. [&test_factory, test_name = test_name]() {
  762. return test_factory.factory_fn(test_name);
  763. });
  764. }
  765. return RUN_ALL_TESTS();
  766. }
  767. }
  768. } // namespace Carbon::Testing
  769. auto main(int argc, char** argv) -> int {
  770. return Carbon::Testing::Main(argc, argv);
  771. }