file_test_base.cpp 37 KB

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