file_test_base.cpp 29 KB

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