file_test_base.cpp 33 KB

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