file_test_base.cpp 31 KB

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