file_test_base.cpp 31 KB

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