file_test_base.cpp 37 KB

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