file_test_base.cpp 28 KB

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