file_test_base.cpp 25 KB

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