file_test_base.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. const std::string& filename = file.filename;
  337. if (!filename.ends_with(".h")) {
  338. it = test_args.insert(it, filename);
  339. ++it;
  340. }
  341. }
  342. // Back up once because the for loop will advance.
  343. --it;
  344. break;
  345. }
  346. case 't': {
  347. char* tmpdir = getenv("TEST_TMPDIR");
  348. CARBON_CHECK(tmpdir != nullptr);
  349. it->replace(percent, 2, llvm::formatv("{0}/temp_file", tmpdir));
  350. break;
  351. }
  352. case '{': {
  353. auto end_brace = it->find('}', percent);
  354. if (end_brace == std::string::npos) {
  355. return ErrorBuilder() << "%{ without closing }: " << *it;
  356. }
  357. llvm::StringRef substr(&*(it->begin() + percent + 2),
  358. end_brace - percent - 2);
  359. auto replacement = replacements.find(substr);
  360. if (replacement == replacements.end()) {
  361. return ErrorBuilder()
  362. << "unknown substitution: %{" << substr << "}: " << *it;
  363. }
  364. it->replace(percent, end_brace - percent + 1, replacement->second);
  365. break;
  366. }
  367. default:
  368. return ErrorBuilder() << "%" << c << " is not supported: " << *it;
  369. }
  370. }
  371. return Success();
  372. }
  373. // Processes conflict markers, including tracking of whether code is within a
  374. // conflict marker. Returns true if the line is consumed.
  375. static auto TryConsumeConflictMarker(llvm::StringRef line,
  376. llvm::StringRef line_trimmed,
  377. bool* inside_conflict_marker)
  378. -> ErrorOr<bool> {
  379. bool is_start = line.starts_with("<<<<<<<");
  380. bool is_middle = line.starts_with("=======") || line.starts_with("|||||||");
  381. bool is_end = line.starts_with(">>>>>>>");
  382. // When running the test, any conflict marker is an error.
  383. if (!absl::GetFlag(FLAGS_autoupdate) && (is_start || is_middle || is_end)) {
  384. return ErrorBuilder() << "Conflict marker found:\n" << line;
  385. }
  386. // Autoupdate tracks conflict markers for context, and will discard
  387. // conflicting lines when it can autoupdate them.
  388. if (*inside_conflict_marker) {
  389. if (is_start) {
  390. return ErrorBuilder() << "Unexpected conflict marker inside conflict:\n"
  391. << line;
  392. }
  393. if (is_middle) {
  394. return true;
  395. }
  396. if (is_end) {
  397. *inside_conflict_marker = false;
  398. return true;
  399. }
  400. // Look for CHECK and TIP lines, which can be discarded.
  401. if (line_trimmed.starts_with("// CHECK:STDOUT:") ||
  402. line_trimmed.starts_with("// CHECK:STDERR:") ||
  403. line_trimmed.starts_with("// TIP:")) {
  404. return true;
  405. }
  406. return ErrorBuilder()
  407. << "Autoupdate can't discard non-CHECK lines inside conflicts:\n"
  408. << line;
  409. } else {
  410. if (is_start) {
  411. *inside_conflict_marker = true;
  412. return true;
  413. }
  414. if (is_middle || is_end) {
  415. return ErrorBuilder() << "Unexpected conflict marker outside conflict:\n"
  416. << line;
  417. }
  418. return false;
  419. }
  420. }
  421. // State for file splitting logic: TryConsumeSplit and FinishSplit.
  422. struct SplitState {
  423. auto has_splits() const -> bool { return file_index > 0; }
  424. auto add_content(llvm::StringRef line) -> void {
  425. content.append(line.str());
  426. content.append("\n");
  427. }
  428. // Whether content has been found. Only updated before a file split is found
  429. // (which may be never).
  430. bool found_code_pre_split = false;
  431. // The current file name, considering splits. Empty for the default file.
  432. llvm::StringRef filename = "";
  433. // The accumulated content for the file being built. This may elide some of
  434. // the original content, such as conflict markers.
  435. std::string content;
  436. // The current file index.
  437. int file_index = 0;
  438. };
  439. // Replaces the content keywords.
  440. //
  441. // TEST_NAME is the only content keyword at present, but we do validate that
  442. // other names are reserved.
  443. static auto ReplaceContentKeywords(llvm::StringRef filename,
  444. std::string* content) -> ErrorOr<Success> {
  445. static constexpr llvm::StringLiteral Prefix = "[[@";
  446. auto keyword_pos = content->find(Prefix);
  447. // Return early if not finding anything.
  448. if (keyword_pos == std::string::npos) {
  449. return Success();
  450. }
  451. // Construct the test name by getting the base name without the extension,
  452. // then removing any "fail_" or "todo_" prefixes.
  453. llvm::StringRef test_name = filename;
  454. if (auto last_slash = test_name.rfind("/");
  455. last_slash != llvm::StringRef::npos) {
  456. test_name = test_name.substr(last_slash + 1);
  457. }
  458. if (auto ext_dot = test_name.find("."); ext_dot != llvm::StringRef::npos) {
  459. test_name = test_name.substr(0, ext_dot);
  460. }
  461. // Note this also handles `fail_todo_` and `todo_fail_`.
  462. test_name.consume_front("todo_");
  463. test_name.consume_front("fail_");
  464. test_name.consume_front("todo_");
  465. while (keyword_pos != std::string::npos) {
  466. static constexpr llvm::StringLiteral TestName = "[[@TEST_NAME]]";
  467. auto keyword = llvm::StringRef(*content).substr(keyword_pos);
  468. if (keyword.starts_with(TestName)) {
  469. content->replace(keyword_pos, TestName.size(), test_name);
  470. keyword_pos += test_name.size();
  471. } else if (keyword.starts_with("[[@LINE")) {
  472. // Just move past the prefix to find the next one.
  473. keyword_pos += Prefix.size();
  474. } else {
  475. return ErrorBuilder()
  476. << "Unexpected use of `[[@` at `" << keyword.substr(0, 5) << "`";
  477. }
  478. keyword_pos = content->find(Prefix, keyword_pos);
  479. }
  480. return Success();
  481. }
  482. // Adds a file. Used for both split and unsplit test files.
  483. static auto AddTestFile(llvm::StringRef filename, std::string* content,
  484. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  485. -> ErrorOr<Success> {
  486. CARBON_RETURN_IF_ERROR(ReplaceContentKeywords(filename, content));
  487. test_files->push_back(
  488. {.filename = filename.str(), .content = std::move(*content)});
  489. content->clear();
  490. return Success();
  491. }
  492. // Process file split ("---") lines when found. Returns true if the line is
  493. // consumed.
  494. static auto TryConsumeSplit(
  495. llvm::StringRef line, llvm::StringRef line_trimmed, bool found_autoupdate,
  496. int* line_index, SplitState* split,
  497. llvm::SmallVector<FileTestBase::TestFile>* test_files,
  498. llvm::SmallVector<FileTestLine>* non_check_lines) -> ErrorOr<bool> {
  499. if (!line_trimmed.consume_front("// ---")) {
  500. if (!split->has_splits() && !line_trimmed.starts_with("//") &&
  501. !line_trimmed.empty()) {
  502. split->found_code_pre_split = true;
  503. }
  504. // Add the line to the current file's content (which may not be a split
  505. // file).
  506. split->add_content(line);
  507. return false;
  508. }
  509. if (!found_autoupdate) {
  510. // If there's a split, all output is appended at the end of each file
  511. // before AUTOUPDATE. We may want to change that, but it's not
  512. // necessary to handle right now.
  513. return ErrorBuilder() << "AUTOUPDATE/NOAUTOUPDATE setting must be in "
  514. "the first file.";
  515. }
  516. // On a file split, add the previous file, then start a new one.
  517. if (split->has_splits()) {
  518. CARBON_RETURN_IF_ERROR(
  519. AddTestFile(split->filename, &split->content, test_files));
  520. } else {
  521. split->content.clear();
  522. if (split->found_code_pre_split) {
  523. // For the first split, we make sure there was no content prior.
  524. return ErrorBuilder() << "When using split files, there must be no "
  525. "content before the first split file.";
  526. }
  527. }
  528. ++split->file_index;
  529. split->filename = line_trimmed.trim();
  530. if (split->filename.empty()) {
  531. return ErrorBuilder() << "Missing filename for split.";
  532. }
  533. // The split line is added to non_check_lines for retention in autoupdate, but
  534. // is not added to the test file content.
  535. *line_index = 0;
  536. non_check_lines->push_back(
  537. FileTestLine(split->file_index, *line_index, line));
  538. return true;
  539. }
  540. // Converts a `FileCheck`-style expectation string into a single complete regex
  541. // string by escaping all regex characters outside of the designated `{{...}}`
  542. // regex sequences, and switching those to a normal regex sub-pattern syntax.
  543. static void ConvertExpectationStringToRegex(std::string& str) {
  544. for (int pos = 0; pos < static_cast<int>(str.size());) {
  545. switch (str[pos]) {
  546. case '(':
  547. case ')':
  548. case '[':
  549. case ']':
  550. case '}':
  551. case '.':
  552. case '^':
  553. case '$':
  554. case '*':
  555. case '+':
  556. case '?':
  557. case '|':
  558. case '\\': {
  559. // Escape regex characters.
  560. str.insert(pos, "\\");
  561. pos += 2;
  562. break;
  563. }
  564. case '{': {
  565. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  566. // Single `{`, escape it.
  567. str.insert(pos, "\\");
  568. pos += 2;
  569. break;
  570. }
  571. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  572. str.replace(pos, 2, "(");
  573. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  574. if (str[pos] == '}' && str[pos + 1] == '}') {
  575. str.replace(pos, 2, ")");
  576. ++pos;
  577. break;
  578. }
  579. }
  580. break;
  581. }
  582. default: {
  583. ++pos;
  584. }
  585. }
  586. }
  587. }
  588. // Transforms an expectation on a given line from `FileCheck` syntax into a
  589. // standard regex matcher.
  590. static auto TransformExpectation(int line_index, llvm::StringRef in)
  591. -> ErrorOr<Matcher<std::string>> {
  592. if (in.empty()) {
  593. return Matcher<std::string>{StrEq("")};
  594. }
  595. if (!in.consume_front(" ")) {
  596. return ErrorBuilder() << "Malformated CHECK line: " << in;
  597. }
  598. // Check early if we have a regex component as we can avoid building an
  599. // expensive matcher when not using those.
  600. bool has_regex = in.find("{{") != llvm::StringRef::npos;
  601. // Now scan the string and expand any keywords. Note that this needs to be
  602. // `size_t` to correctly store `npos`.
  603. size_t keyword_pos = in.find("[[");
  604. // If there are neither keywords nor regex sequences, we can match the
  605. // incoming string directly.
  606. if (!has_regex && keyword_pos == llvm::StringRef::npos) {
  607. return Matcher<std::string>{StrEq(in)};
  608. }
  609. std::string str = in.str();
  610. // First expand the keywords.
  611. while (keyword_pos != std::string::npos) {
  612. llvm::StringRef line_keyword_cursor =
  613. llvm::StringRef(str).substr(keyword_pos);
  614. CARBON_CHECK(line_keyword_cursor.consume_front("[["));
  615. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  616. if (!line_keyword_cursor.consume_front(LineKeyword)) {
  617. return ErrorBuilder()
  618. << "Unexpected [[, should be {{\\[\\[}} at `"
  619. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  620. }
  621. // Allow + or - here; consumeInteger handles -.
  622. line_keyword_cursor.consume_front("+");
  623. int offset;
  624. // consumeInteger returns true for errors, not false.
  625. if (line_keyword_cursor.consumeInteger(10, offset) ||
  626. !line_keyword_cursor.consume_front("]]")) {
  627. return ErrorBuilder()
  628. << "Unexpected @LINE offset at `"
  629. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  630. }
  631. std::string int_str = llvm::Twine(line_index + offset).str();
  632. int remove_len = (line_keyword_cursor.data() - str.data()) - keyword_pos;
  633. str.replace(keyword_pos, remove_len, int_str);
  634. keyword_pos += int_str.size();
  635. // Find the next keyword start or the end of the string.
  636. keyword_pos = str.find("[[", keyword_pos);
  637. }
  638. // If there was no regex, we can directly match the adjusted string.
  639. if (!has_regex) {
  640. return Matcher<std::string>{StrEq(str)};
  641. }
  642. // Otherwise, we need to turn the entire string into a regex by escaping
  643. // things outside the regex region and transforming the regex region into a
  644. // normal syntax.
  645. ConvertExpectationStringToRegex(str);
  646. return Matcher<std::string>{MatchesRegex(str)};
  647. }
  648. // Once all content is processed, do any remaining split processing.
  649. static auto FinishSplit(llvm::StringRef test_name, SplitState* split,
  650. llvm::SmallVector<FileTestBase::TestFile>* test_files)
  651. -> ErrorOr<Success> {
  652. if (split->has_splits()) {
  653. return AddTestFile(split->filename, &split->content, test_files);
  654. } else {
  655. // If no file splitting happened, use the main file as the test file.
  656. // There will always be a `/` unless tests are in the repo root.
  657. return AddTestFile(test_name.drop_front(test_name.rfind("/") + 1),
  658. &split->content, test_files);
  659. }
  660. }
  661. // Process CHECK lines when found. Returns true if the line is consumed.
  662. static auto TryConsumeCheck(
  663. int line_index, llvm::StringRef line, llvm::StringRef line_trimmed,
  664. llvm::SmallVector<testing::Matcher<std::string>>* expected_stdout,
  665. llvm::SmallVector<testing::Matcher<std::string>>* expected_stderr)
  666. -> ErrorOr<bool> {
  667. if (!line_trimmed.consume_front("// CHECK")) {
  668. return false;
  669. }
  670. // Don't build expectations when doing an autoupdate. We don't want to
  671. // break the autoupdate on an invalid CHECK line.
  672. if (!absl::GetFlag(FLAGS_autoupdate)) {
  673. llvm::SmallVector<Matcher<std::string>>* expected;
  674. if (line_trimmed.consume_front(":STDOUT:")) {
  675. expected = expected_stdout;
  676. } else if (line_trimmed.consume_front(":STDERR:")) {
  677. expected = expected_stderr;
  678. } else {
  679. return ErrorBuilder() << "Unexpected CHECK in input: " << line.str();
  680. }
  681. CARBON_ASSIGN_OR_RETURN(Matcher<std::string> check_matcher,
  682. TransformExpectation(line_index, line_trimmed));
  683. expected->push_back(check_matcher);
  684. }
  685. return true;
  686. }
  687. // Processes ARGS lines when found. Returns true if the line is consumed.
  688. static auto TryConsumeArgs(llvm::StringRef line, llvm::StringRef line_trimmed,
  689. llvm::SmallVector<std::string>* args)
  690. -> ErrorOr<bool> {
  691. if (!line_trimmed.consume_front("// ARGS: ")) {
  692. return false;
  693. }
  694. if (!args->empty()) {
  695. return ErrorBuilder() << "ARGS was specified multiple times: "
  696. << line.str();
  697. }
  698. // Split the line into arguments.
  699. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  700. llvm::getToken(line_trimmed);
  701. while (!cursor.first.empty()) {
  702. args->push_back(std::string(cursor.first));
  703. cursor = llvm::getToken(cursor.second);
  704. }
  705. return true;
  706. }
  707. // Processes AUTOUPDATE lines when found. Returns true if the line is consumed.
  708. static auto TryConsumeAutoupdate(int line_index, llvm::StringRef line_trimmed,
  709. bool* found_autoupdate,
  710. std::optional<int>* autoupdate_line_number)
  711. -> ErrorOr<bool> {
  712. static constexpr llvm::StringLiteral Autoupdate = "// AUTOUPDATE";
  713. static constexpr llvm::StringLiteral NoAutoupdate = "// NOAUTOUPDATE";
  714. if (line_trimmed != Autoupdate && line_trimmed != NoAutoupdate) {
  715. return false;
  716. }
  717. if (*found_autoupdate) {
  718. return ErrorBuilder() << "Multiple AUTOUPDATE/NOAUTOUPDATE settings found";
  719. }
  720. *found_autoupdate = true;
  721. if (line_trimmed == Autoupdate) {
  722. *autoupdate_line_number = line_index;
  723. }
  724. return true;
  725. }
  726. // Processes SET-* lines when found. Returns true if the line is consumed.
  727. static auto TryConsumeSetFlag(llvm::StringRef line_trimmed,
  728. llvm::StringLiteral flag_name, bool* flag)
  729. -> ErrorOr<bool> {
  730. if (!line_trimmed.consume_front("// ") || line_trimmed != flag_name) {
  731. return false;
  732. }
  733. if (*flag) {
  734. return ErrorBuilder() << flag_name << " was specified multiple times";
  735. }
  736. *flag = true;
  737. return true;
  738. }
  739. auto FileTestBase::ProcessTestFile(TestContext& context) -> ErrorOr<Success> {
  740. // Original file content, and a cursor for walking through it.
  741. llvm::StringRef file_content = context.input_content;
  742. llvm::StringRef cursor = file_content;
  743. // Whether either AUTOUDPATE or NOAUTOUPDATE was found.
  744. bool found_autoupdate = false;
  745. // The index in the current test file. Will be reset on splits.
  746. int line_index = 0;
  747. SplitState split;
  748. // When autoupdating, we track whether we're inside conflict markers.
  749. // Otherwise conflict markers are errors.
  750. bool inside_conflict_marker = false;
  751. while (!cursor.empty()) {
  752. auto [line, next_cursor] = cursor.split("\n");
  753. cursor = next_cursor;
  754. auto line_trimmed = line.ltrim();
  755. bool is_consumed = false;
  756. CARBON_ASSIGN_OR_RETURN(
  757. is_consumed,
  758. TryConsumeConflictMarker(line, line_trimmed, &inside_conflict_marker));
  759. if (is_consumed) {
  760. continue;
  761. }
  762. // At this point, remaining lines are part of the test input.
  763. CARBON_ASSIGN_OR_RETURN(
  764. is_consumed,
  765. TryConsumeSplit(line, line_trimmed, found_autoupdate, &line_index,
  766. &split, &context.test_files, &context.non_check_lines));
  767. if (is_consumed) {
  768. continue;
  769. }
  770. ++line_index;
  771. // TIP lines have no impact on validation.
  772. if (line_trimmed.starts_with("// TIP:")) {
  773. continue;
  774. }
  775. CARBON_ASSIGN_OR_RETURN(
  776. is_consumed,
  777. TryConsumeCheck(line_index, line, line_trimmed,
  778. &context.expected_stdout, &context.expected_stderr));
  779. if (is_consumed) {
  780. continue;
  781. }
  782. // At this point, lines are retained as non-CHECK lines.
  783. context.non_check_lines.push_back(
  784. FileTestLine(split.file_index, line_index, line));
  785. CARBON_ASSIGN_OR_RETURN(
  786. is_consumed, TryConsumeArgs(line, line_trimmed, &context.test_args));
  787. if (is_consumed) {
  788. continue;
  789. }
  790. CARBON_ASSIGN_OR_RETURN(
  791. is_consumed,
  792. TryConsumeAutoupdate(line_index, line_trimmed, &found_autoupdate,
  793. &context.autoupdate_line_number));
  794. if (is_consumed) {
  795. continue;
  796. }
  797. CARBON_ASSIGN_OR_RETURN(
  798. is_consumed,
  799. TryConsumeSetFlag(line_trimmed, "SET-CAPTURE-CONSOLE-OUTPUT",
  800. &context.capture_console_output));
  801. if (is_consumed) {
  802. continue;
  803. }
  804. CARBON_ASSIGN_OR_RETURN(is_consumed,
  805. TryConsumeSetFlag(line_trimmed, "SET-CHECK-SUBSET",
  806. &context.check_subset));
  807. if (is_consumed) {
  808. continue;
  809. }
  810. }
  811. if (!found_autoupdate) {
  812. return Error("Missing AUTOUPDATE/NOAUTOUPDATE setting");
  813. }
  814. context.has_splits = split.has_splits();
  815. CARBON_RETURN_IF_ERROR(FinishSplit(test_name_, &split, &context.test_files));
  816. // Validate AUTOUPDATE-SPLIT use, and remove it from test files if present.
  817. if (context.has_splits) {
  818. constexpr llvm::StringLiteral AutoupdateSplit = "AUTOUPDATE-SPLIT";
  819. for (const auto& test_file :
  820. llvm::ArrayRef(context.test_files).drop_back()) {
  821. if (test_file.filename == AutoupdateSplit) {
  822. return Error("AUTOUPDATE-SPLIT must be the last split");
  823. }
  824. }
  825. if (context.test_files.back().filename == AutoupdateSplit) {
  826. if (!context.autoupdate_line_number) {
  827. return Error("AUTOUPDATE-SPLIT requires AUTOUPDATE");
  828. }
  829. context.autoupdate_split = true;
  830. context.test_files.pop_back();
  831. }
  832. }
  833. // Assume there is always a suffix `\n` in output.
  834. if (!context.expected_stdout.empty()) {
  835. context.expected_stdout.push_back(StrEq(""));
  836. }
  837. if (!context.expected_stderr.empty()) {
  838. context.expected_stderr.push_back(StrEq(""));
  839. }
  840. return Success();
  841. }
  842. // Returns the tests to run.
  843. static auto GetTests() -> llvm::SmallVector<std::string> {
  844. // Prefer a user-specified list if present.
  845. auto specific_tests = absl::GetFlag(FLAGS_file_tests);
  846. if (!specific_tests.empty()) {
  847. return llvm::SmallVector<std::string>(specific_tests.begin(),
  848. specific_tests.end());
  849. }
  850. // Extracts tests from the target file.
  851. CARBON_CHECK(!absl::GetFlag(FLAGS_test_targets_file).empty(),
  852. "Missing --test_targets_file.");
  853. auto content = ReadFile(absl::GetFlag(FLAGS_test_targets_file));
  854. CARBON_CHECK(content.ok(), "{0}", content.error());
  855. llvm::SmallVector<std::string> all_tests;
  856. for (llvm::StringRef file_ref : llvm::split(*content, "\n")) {
  857. if (file_ref.empty()) {
  858. continue;
  859. }
  860. all_tests.push_back(file_ref.str());
  861. }
  862. return all_tests;
  863. }
  864. // Runs autoupdate for the given tests. This is multi-threaded to try to get a
  865. // little extra speed.
  866. static auto RunAutoupdate(llvm::StringRef exe_path,
  867. llvm::ArrayRef<std::string> tests,
  868. FileTestFactory& test_factory) -> int {
  869. llvm::CrashRecoveryContext::Enable();
  870. llvm::DefaultThreadPool pool(
  871. {.ThreadsRequested = absl::GetFlag(FLAGS_threads)});
  872. // Guard access to both `llvm::errs` and `crashed`.
  873. std::mutex mutex;
  874. bool crashed = false;
  875. for (const auto& test_name : tests) {
  876. pool.async([&test_factory, &mutex, &exe_path, &crashed, test_name] {
  877. // If any thread crashed, don't try running more.
  878. {
  879. std::unique_lock<std::mutex> lock(mutex);
  880. if (crashed) {
  881. return;
  882. }
  883. }
  884. // Use a crash recovery context to try to get a stack trace when
  885. // multiple threads may crash in parallel, which otherwise leads to the
  886. // program aborting without printing a stack trace.
  887. llvm::CrashRecoveryContext crc;
  888. crc.DumpStackAndCleanupOnFailure = true;
  889. bool thread_crashed = !crc.RunSafely([&] {
  890. std::unique_ptr<FileTestBase> test(
  891. test_factory.factory_fn(exe_path, &mutex, test_name));
  892. auto result = test->Autoupdate();
  893. std::unique_lock<std::mutex> lock(mutex);
  894. if (result.ok()) {
  895. llvm::errs() << (*result ? "!" : ".");
  896. } else {
  897. llvm::errs() << "\n" << result.error().message() << "\n";
  898. }
  899. });
  900. if (thread_crashed) {
  901. std::unique_lock<std::mutex> lock(mutex);
  902. crashed = true;
  903. }
  904. });
  905. }
  906. pool.wait();
  907. if (crashed) {
  908. // Abort rather than returning so that we don't get a LeakSanitizer report.
  909. // We expect to have leaked memory if one or more of our tests crashed.
  910. std::abort();
  911. }
  912. llvm::errs() << "\nDone!\n";
  913. return EXIT_SUCCESS;
  914. }
  915. // Implements main() within the Carbon::Testing namespace for convenience.
  916. static auto Main(int argc, char** argv) -> int {
  917. Carbon::InitLLVM init_llvm(argc, argv);
  918. testing::InitGoogleTest(&argc, argv);
  919. auto args = absl::ParseCommandLine(argc, argv);
  920. if (args.size() > 1) {
  921. llvm::errs() << "Unexpected arguments:";
  922. for (char* arg : llvm::ArrayRef(args).drop_front()) {
  923. llvm::errs() << " ";
  924. llvm::errs().write_escaped(arg);
  925. }
  926. llvm::errs() << "\n";
  927. return EXIT_FAILURE;
  928. }
  929. std::string exe_path = FindExecutablePath(argv[0]);
  930. // Tests might try to read from stdin. Ensure those reads fail by closing
  931. // stdin and reopening it as /dev/null. Note that STDIN_FILENO doesn't exist
  932. // on Windows, but POSIX requires it to be 0.
  933. if (std::error_code error =
  934. llvm::sys::Process::SafelyCloseFileDescriptor(0)) {
  935. llvm::errs() << "Unable to close standard input: " << error.message()
  936. << "\n";
  937. return EXIT_FAILURE;
  938. }
  939. if (std::error_code error =
  940. llvm::sys::Process::FixupStandardFileDescriptors()) {
  941. llvm::errs() << "Unable to correct standard file descriptors: "
  942. << error.message() << "\n";
  943. return EXIT_FAILURE;
  944. }
  945. if (absl::GetFlag(FLAGS_autoupdate) && absl::GetFlag(FLAGS_dump_output)) {
  946. llvm::errs() << "--autoupdate and --dump_output are mutually exclusive.\n";
  947. return EXIT_FAILURE;
  948. }
  949. llvm::SmallVector<std::string> tests = GetTests();
  950. auto test_factory = GetFileTestFactory();
  951. if (absl::GetFlag(FLAGS_autoupdate)) {
  952. return RunAutoupdate(exe_path, tests, test_factory);
  953. } else if (absl::GetFlag(FLAGS_dump_output)) {
  954. for (const auto& test_name : tests) {
  955. std::unique_ptr<FileTestBase> test(
  956. test_factory.factory_fn(exe_path, nullptr, test_name));
  957. auto result = test->DumpOutput();
  958. if (!result.ok()) {
  959. llvm::errs() << "\n" << result.error().message() << "\n";
  960. }
  961. }
  962. llvm::errs() << "\nDone!\n";
  963. return EXIT_SUCCESS;
  964. } else {
  965. for (llvm::StringRef test_name : tests) {
  966. testing::RegisterTest(
  967. test_factory.name, test_name.data(), nullptr, test_name.data(),
  968. __FILE__, __LINE__,
  969. [&test_factory, &exe_path, test_name = test_name]() {
  970. return test_factory.factory_fn(exe_path, nullptr, test_name);
  971. });
  972. }
  973. return RUN_ALL_TESTS();
  974. }
  975. }
  976. } // namespace Carbon::Testing
  977. auto main(int argc, char** argv) -> int {
  978. return Carbon::Testing::Main(argc, argv);
  979. }