file_test_base.cpp 26 KB

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