test_file.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  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/test_file.h"
  5. #include <fstream>
  6. #include <optional>
  7. #include <string>
  8. #include <utility>
  9. #include "common/check.h"
  10. #include "common/error.h"
  11. #include "common/find.h"
  12. #include "common/raw_string_ostream.h"
  13. #include "common/set.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/Support/JSON.h"
  16. #include "testing/base/file_helpers.h"
  17. #include "testing/file_test/line.h"
  18. namespace Carbon::Testing {
  19. using ::testing::Matcher;
  20. using ::testing::MatchesRegex;
  21. using ::testing::StrEq;
  22. // Processes conflict markers, including tracking of whether code is within a
  23. // conflict marker. Returns true if the line is consumed.
  24. static auto TryConsumeConflictMarker(bool running_autoupdate,
  25. llvm::StringRef line,
  26. llvm::StringRef line_trimmed,
  27. bool& inside_conflict_marker)
  28. -> ErrorOr<bool> {
  29. bool is_start = line.starts_with("<<<<<<<");
  30. bool is_middle = line.starts_with("=======") || line.starts_with("|||||||");
  31. bool is_end = line.starts_with(">>>>>>>");
  32. // When running the test, any conflict marker is an error.
  33. if (!running_autoupdate && (is_start || is_middle || is_end)) {
  34. return ErrorBuilder() << "Conflict marker found:\n" << line;
  35. }
  36. // Autoupdate tracks conflict markers for context, and will discard
  37. // conflicting lines when it can autoupdate them.
  38. if (inside_conflict_marker) {
  39. if (is_start) {
  40. return ErrorBuilder() << "Unexpected conflict marker inside conflict:\n"
  41. << line;
  42. }
  43. if (is_middle) {
  44. return true;
  45. }
  46. if (is_end) {
  47. inside_conflict_marker = false;
  48. return true;
  49. }
  50. // Look for CHECK and TIP lines, which can be discarded.
  51. if (line_trimmed.starts_with("// CHECK:STDOUT:") ||
  52. line_trimmed.starts_with("// CHECK:STDERR:") ||
  53. line_trimmed.starts_with("// TIP:")) {
  54. return true;
  55. }
  56. return ErrorBuilder()
  57. << "Autoupdate can't discard non-CHECK lines inside conflicts:\n"
  58. << line;
  59. } else {
  60. if (is_start) {
  61. inside_conflict_marker = true;
  62. return true;
  63. }
  64. if (is_middle || is_end) {
  65. return ErrorBuilder() << "Unexpected conflict marker outside conflict:\n"
  66. << line;
  67. }
  68. return false;
  69. }
  70. }
  71. // State for file splitting logic: TryConsumeSplit and FinishSplit.
  72. struct SplitState {
  73. auto has_splits() const -> bool { return file_index > 0; }
  74. auto add_content(llvm::StringRef line) -> void {
  75. content.append(line.str());
  76. content.append("\n");
  77. }
  78. // Whether content has been found. Only updated before a file split is found
  79. // (which may be never).
  80. bool found_code_pre_split = false;
  81. // The current file name, considering splits. Empty for the default file.
  82. llvm::StringRef filename = "";
  83. // The accumulated content for the file being built. This may elide some of
  84. // the original content, such as conflict markers.
  85. std::string content;
  86. // The current file index.
  87. int file_index = 0;
  88. };
  89. // Given a `file:/<filename>` URI, returns the filename.
  90. static auto ExtractFilePathFromUri(llvm::StringRef uri)
  91. -> ErrorOr<llvm::StringRef> {
  92. static constexpr llvm::StringRef FilePrefix = "file:/";
  93. if (!uri.starts_with(FilePrefix)) {
  94. return ErrorBuilder() << "uri `" << uri << "` is not a file uri";
  95. }
  96. return uri.drop_front(FilePrefix.size());
  97. }
  98. // When `FROM_FILE_SPLIT` is used in path `textDocument.text`, populate the
  99. // value from the split matching the `uri`. Only used for
  100. // `textDocument/didOpen`.
  101. static auto AutoFillDidOpenParams(llvm::json::Object& params,
  102. llvm::ArrayRef<TestFile::Split> splits)
  103. -> ErrorOr<Success> {
  104. auto* text_document = params.getObject("textDocument");
  105. if (text_document == nullptr) {
  106. return Success();
  107. }
  108. auto attr_it = text_document->find("text");
  109. if (attr_it == text_document->end() || attr_it->second != "FROM_FILE_SPLIT") {
  110. return Success();
  111. }
  112. auto uri = text_document->getString("uri");
  113. if (!uri) {
  114. return Error("missing uri in params.textDocument");
  115. }
  116. CARBON_ASSIGN_OR_RETURN(auto file_path, ExtractFilePathFromUri(*uri));
  117. const auto* split = FindIfOrNull(splits, [&](const TestFile::Split& split) {
  118. return split.filename == file_path;
  119. });
  120. if (!split) {
  121. return ErrorBuilder() << "No split found for uri: " << *uri;
  122. }
  123. attr_it->second = split->content;
  124. return Success();
  125. }
  126. // Reformats `[[@LSP:` and similar keyword as an LSP call with headers.
  127. static auto ReplaceLspKeywordAt(std::string& content, size_t keyword_pos,
  128. int& lsp_call_id,
  129. llvm::ArrayRef<TestFile::Split> splits)
  130. -> ErrorOr<size_t> {
  131. llvm::StringRef content_at_keyword =
  132. llvm::StringRef(content).substr(keyword_pos);
  133. auto [keyword, body_start] = content_at_keyword.split(":");
  134. if (body_start.empty()) {
  135. return ErrorBuilder() << "Missing `:` for `"
  136. << content_at_keyword.take_front(10) << "`";
  137. }
  138. // Whether the first param is a method or id.
  139. llvm::StringRef method_or_id_label = "method";
  140. // Whether to attach the `lsp_call_id`.
  141. bool use_call_id = false;
  142. // The JSON label for extra content.
  143. llvm::StringRef extra_content_label;
  144. if (keyword == "[[@LSP-CALL") {
  145. use_call_id = true;
  146. extra_content_label = "params";
  147. } else if (keyword == "[[@LSP-NOTIFY") {
  148. extra_content_label = "params";
  149. } else if (keyword == "[[@LSP-REPLY") {
  150. method_or_id_label = "id";
  151. extra_content_label = "result";
  152. } else if (keyword != "[[@LSP") {
  153. return ErrorBuilder() << "Unrecognized @LSP keyword at `"
  154. << keyword.take_front(10) << "`";
  155. }
  156. static constexpr llvm::StringLiteral LspEnd = "]]";
  157. auto body_end = body_start.find(LspEnd);
  158. if (body_end == std::string::npos) {
  159. return ErrorBuilder() << "Missing `" << LspEnd << "` after `" << keyword
  160. << "`";
  161. }
  162. llvm::StringRef body = body_start.take_front(body_end);
  163. auto [method_or_id, extra_content] = body.split(":");
  164. llvm::json::Value parsed_extra_content = nullptr;
  165. if (!extra_content.empty()) {
  166. std::string extra_content_as_object =
  167. llvm::formatv("{{{0}}", extra_content);
  168. auto parse_result = llvm::json::parse(extra_content_as_object);
  169. if (auto err = parse_result.takeError()) {
  170. return ErrorBuilder() << "Error parsing extra content: " << err;
  171. }
  172. parsed_extra_content = std::move(*parse_result);
  173. CARBON_CHECK(parsed_extra_content.kind() == llvm::json::Value::Object);
  174. if (extra_content_label == "params" &&
  175. method_or_id == "textDocument/didOpen") {
  176. CARBON_RETURN_IF_ERROR(
  177. AutoFillDidOpenParams(*parsed_extra_content.getAsObject(), splits));
  178. }
  179. }
  180. // Form the JSON.
  181. RawStringOstream buffer;
  182. llvm::json::OStream json(buffer);
  183. json.object([&] {
  184. json.attribute("jsonrpc", "2.0");
  185. json.attribute(method_or_id_label, method_or_id);
  186. if (use_call_id) {
  187. json.attribute("id", ++lsp_call_id);
  188. }
  189. if (parsed_extra_content != nullptr) {
  190. if (!extra_content_label.empty()) {
  191. json.attribute(extra_content_label, parsed_extra_content);
  192. } else {
  193. for (const auto& [key, value] : *parsed_extra_content.getAsObject()) {
  194. json.attribute(key, value);
  195. }
  196. }
  197. }
  198. });
  199. // Add the Content-Length header. The `2` accounts for extra newlines.
  200. int content_length = buffer.size() + 2;
  201. auto json_with_header = llvm::formatv("Content-Length: {0}\n\n{1}\n",
  202. content_length, buffer.TakeStr())
  203. .str();
  204. int keyword_len =
  205. (body_start.data() + body_end + LspEnd.size()) - keyword.data();
  206. content.replace(keyword_pos, keyword_len, json_with_header);
  207. return keyword_pos + json_with_header.size();
  208. }
  209. // Replaces the keyword at the given position. Returns the position to start a
  210. // find for the next keyword.
  211. static auto ReplaceContentKeywordAt(std::string& content, size_t keyword_pos,
  212. llvm::StringRef test_name, int& lsp_call_id,
  213. llvm::ArrayRef<TestFile::Split> splits)
  214. -> ErrorOr<size_t> {
  215. auto keyword = llvm::StringRef(content).substr(keyword_pos);
  216. // Line replacements aren't handled here.
  217. static constexpr llvm::StringLiteral Line = "[[@LINE";
  218. if (keyword.starts_with(Line)) {
  219. // Just move past the prefix to find the next one.
  220. return keyword_pos + Line.size();
  221. }
  222. // Replaced with the actual test name.
  223. static constexpr llvm::StringLiteral TestName = "[[@TEST_NAME]]";
  224. if (keyword.starts_with(TestName)) {
  225. content.replace(keyword_pos, TestName.size(), test_name);
  226. return keyword_pos + test_name.size();
  227. }
  228. if (keyword.starts_with("[[@LSP")) {
  229. return ReplaceLspKeywordAt(content, keyword_pos, lsp_call_id, splits);
  230. }
  231. return ErrorBuilder() << "Unexpected use of `[[@` at `"
  232. << keyword.substr(0, 5) << "`";
  233. }
  234. // Replaces the content keywords.
  235. //
  236. // TEST_NAME is the only content keyword at present, but we do validate that
  237. // other names are reserved.
  238. static auto ReplaceContentKeywords(llvm::StringRef filename,
  239. std::string& content,
  240. llvm::ArrayRef<TestFile::Split> splits)
  241. -> ErrorOr<Success> {
  242. static constexpr llvm::StringLiteral Prefix = "[[@";
  243. auto keyword_pos = content.find(Prefix);
  244. // Return early if not finding anything.
  245. if (keyword_pos == std::string::npos) {
  246. return Success();
  247. }
  248. // Construct the test name by getting the base name without the extension,
  249. // then removing any "fail_" or "todo_" prefixes.
  250. llvm::StringRef test_name = filename;
  251. if (auto last_slash = test_name.rfind("/");
  252. last_slash != llvm::StringRef::npos) {
  253. test_name = test_name.substr(last_slash + 1);
  254. }
  255. if (auto ext_dot = test_name.find("."); ext_dot != llvm::StringRef::npos) {
  256. test_name = test_name.substr(0, ext_dot);
  257. }
  258. // Note this also handles `fail_todo_` and `todo_fail_`.
  259. test_name.consume_front("todo_");
  260. test_name.consume_front("fail_");
  261. test_name.consume_front("todo_");
  262. // A counter for LSP calls.
  263. int lsp_call_id = 0;
  264. while (keyword_pos != std::string::npos) {
  265. CARBON_ASSIGN_OR_RETURN(
  266. auto keyword_end,
  267. ReplaceContentKeywordAt(content, keyword_pos, test_name, lsp_call_id,
  268. splits));
  269. keyword_pos = content.find(Prefix, keyword_end);
  270. }
  271. return Success();
  272. }
  273. // Adds a file. Used for both split and unsplit test files.
  274. static auto AddSplit(llvm::StringRef filename, std::string& content,
  275. llvm::SmallVector<TestFile::Split>& file_splits)
  276. -> ErrorOr<Success> {
  277. CARBON_RETURN_IF_ERROR(
  278. ReplaceContentKeywords(filename, content, file_splits));
  279. file_splits.push_back(
  280. {.filename = filename.str(), .content = std::move(content)});
  281. content.clear();
  282. return Success();
  283. }
  284. // Process file split ("---") lines when found. Returns true if the line is
  285. // consumed. `non_check_lines` is only provided for the main file, and will be
  286. // null for includes.
  287. static auto TryConsumeSplit(llvm::StringRef line, llvm::StringRef line_trimmed,
  288. bool missing_autoupdate, int& line_index,
  289. SplitState& split,
  290. llvm::SmallVector<TestFile::Split>& file_splits,
  291. llvm::SmallVector<FileTestLine>* non_check_lines)
  292. -> ErrorOr<bool> {
  293. if (!line_trimmed.consume_front("// ---")) {
  294. if (!split.has_splits() && !line_trimmed.starts_with("//") &&
  295. !line_trimmed.empty()) {
  296. split.found_code_pre_split = true;
  297. }
  298. // Add the line to the current file's content (which may not be a split
  299. // file).
  300. split.add_content(line);
  301. return false;
  302. }
  303. if (missing_autoupdate) {
  304. // If there's a split, all output is appended at the end of each file
  305. // before AUTOUPDATE. We may want to change that, but it's not
  306. // necessary to handle right now.
  307. return Error(
  308. "AUTOUPDATE/NOAUTOUPDATE setting must be in "
  309. "the first file.");
  310. }
  311. // On a file split, add the previous file, then start a new one.
  312. if (split.has_splits()) {
  313. CARBON_RETURN_IF_ERROR(
  314. AddSplit(split.filename, split.content, file_splits));
  315. } else {
  316. split.content.clear();
  317. if (split.found_code_pre_split) {
  318. // For the first split, we make sure there was no content prior.
  319. return Error(
  320. "When using split files, there must be no content before the first "
  321. "split file.");
  322. }
  323. }
  324. ++split.file_index;
  325. split.filename = line_trimmed.trim();
  326. if (split.filename.empty()) {
  327. return Error("Missing filename for split.");
  328. }
  329. // The split line is added to non_check_lines for retention in autoupdate, but
  330. // is not added to the test file content.
  331. line_index = 0;
  332. if (non_check_lines) {
  333. non_check_lines->push_back(
  334. FileTestLine(split.file_index, line_index, line));
  335. }
  336. return true;
  337. }
  338. // Converts a `FileCheck`-style expectation string into a single complete regex
  339. // string by escaping all regex characters outside of the designated `{{...}}`
  340. // regex sequences, and switching those to a normal regex sub-pattern syntax.
  341. static auto ConvertExpectationStringToRegex(std::string& str) -> void {
  342. for (int pos = 0; pos < static_cast<int>(str.size());) {
  343. switch (str[pos]) {
  344. case '(':
  345. case ')':
  346. case '[':
  347. case ']':
  348. case '}':
  349. case '.':
  350. case '^':
  351. case '$':
  352. case '*':
  353. case '+':
  354. case '?':
  355. case '|':
  356. case '\\': {
  357. // Escape regex characters.
  358. str.insert(pos, "\\");
  359. pos += 2;
  360. break;
  361. }
  362. case '{': {
  363. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  364. // Single `{`, escape it.
  365. str.insert(pos, "\\");
  366. pos += 2;
  367. break;
  368. }
  369. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  370. str.replace(pos, 2, "(");
  371. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  372. if (str[pos] == '}' && str[pos + 1] == '}') {
  373. str.replace(pos, 2, ")");
  374. ++pos;
  375. break;
  376. }
  377. }
  378. break;
  379. }
  380. default: {
  381. ++pos;
  382. }
  383. }
  384. }
  385. }
  386. // Transforms an expectation on a given line from `FileCheck` syntax into a
  387. // standard regex matcher.
  388. static auto TransformExpectation(int line_index, llvm::StringRef in)
  389. -> ErrorOr<Matcher<std::string>> {
  390. if (in.empty()) {
  391. return Matcher<std::string>{StrEq("")};
  392. }
  393. if (!in.consume_front(" ")) {
  394. return ErrorBuilder() << "Malformated CHECK line: " << in;
  395. }
  396. // Check early if we have a regex component as we can avoid building an
  397. // expensive matcher when not using those.
  398. bool has_regex = in.find("{{") != llvm::StringRef::npos;
  399. // Now scan the string and expand any keywords. Note that this needs to be
  400. // `size_t` to correctly store `npos`.
  401. size_t keyword_pos = in.find("[[");
  402. // If there are neither keywords nor regex sequences, we can match the
  403. // incoming string directly.
  404. if (!has_regex && keyword_pos == llvm::StringRef::npos) {
  405. return Matcher<std::string>{StrEq(in)};
  406. }
  407. std::string str = in.str();
  408. // First expand the keywords.
  409. while (keyword_pos != std::string::npos) {
  410. llvm::StringRef line_keyword_cursor =
  411. llvm::StringRef(str).substr(keyword_pos);
  412. CARBON_CHECK(line_keyword_cursor.consume_front("[["));
  413. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  414. if (!line_keyword_cursor.consume_front(LineKeyword)) {
  415. return ErrorBuilder()
  416. << "Unexpected [[, should be {{\\[\\[}} at `"
  417. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  418. }
  419. // Allow + or - here; consumeInteger handles -.
  420. line_keyword_cursor.consume_front("+");
  421. int offset;
  422. // consumeInteger returns true for errors, not false.
  423. if (line_keyword_cursor.consumeInteger(10, offset) ||
  424. !line_keyword_cursor.consume_front("]]")) {
  425. return ErrorBuilder()
  426. << "Unexpected @LINE offset at `"
  427. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  428. }
  429. std::string int_str = llvm::Twine(line_index + offset).str();
  430. int remove_len = (line_keyword_cursor.data() - str.data()) - keyword_pos;
  431. str.replace(keyword_pos, remove_len, int_str);
  432. keyword_pos += int_str.size();
  433. // Find the next keyword start or the end of the string.
  434. keyword_pos = str.find("[[", keyword_pos);
  435. }
  436. // If there was no regex, we can directly match the adjusted string.
  437. if (!has_regex) {
  438. return Matcher<std::string>{StrEq(str)};
  439. }
  440. // Otherwise, we need to turn the entire string into a regex by escaping
  441. // things outside the regex region and transforming the regex region into a
  442. // normal syntax.
  443. ConvertExpectationStringToRegex(str);
  444. return Matcher<std::string>{MatchesRegex(str)};
  445. }
  446. // Once all content is processed, do any remaining split processing.
  447. static auto FinishSplit(llvm::StringRef filename, bool is_include_file,
  448. SplitState& split,
  449. llvm::SmallVector<TestFile::Split>& file_splits)
  450. -> ErrorOr<Success> {
  451. if (split.has_splits()) {
  452. return AddSplit(split.filename, split.content, file_splits);
  453. } else {
  454. // If no file splitting happened, use the main file as the test file.
  455. // There will always be a `/` unless tests are in the repo root.
  456. std::string split_name = std::filesystem::path(filename.str()).filename();
  457. if (is_include_file) {
  458. split_name.insert(0, "include_files/");
  459. }
  460. return AddSplit(split_name, split.content, file_splits);
  461. }
  462. }
  463. // Process CHECK lines when found. Returns true if the line is consumed.
  464. // `expected_stdout` and `expected_stderr` are null in included files, where
  465. // it's an error to use `CHECK`.
  466. static auto TryConsumeCheck(
  467. bool running_autoupdate, int line_index, llvm::StringRef line,
  468. llvm::StringRef line_trimmed,
  469. llvm::SmallVector<testing::Matcher<std::string>>* expected_stdout,
  470. llvm::SmallVector<testing::Matcher<std::string>>* expected_stderr)
  471. -> ErrorOr<bool> {
  472. if (!line_trimmed.consume_front("// CHECK")) {
  473. return false;
  474. }
  475. if (!expected_stdout) {
  476. return ErrorBuilder() << "Included files can't add CHECKs: "
  477. << line_trimmed;
  478. }
  479. // Don't build expectations when doing an autoupdate. We don't want to
  480. // break the autoupdate on an invalid CHECK line.
  481. if (!running_autoupdate) {
  482. llvm::SmallVector<Matcher<std::string>>* expected;
  483. if (line_trimmed.consume_front(":STDOUT:")) {
  484. expected = expected_stdout;
  485. } else if (line_trimmed.consume_front(":STDERR:")) {
  486. expected = expected_stderr;
  487. } else {
  488. return ErrorBuilder() << "Unexpected CHECK in input: " << line.str();
  489. }
  490. CARBON_ASSIGN_OR_RETURN(Matcher<std::string> check_matcher,
  491. TransformExpectation(line_index, line_trimmed));
  492. expected->push_back(check_matcher);
  493. }
  494. return true;
  495. }
  496. // Processes ARGS and EXTRA-ARGS lines when found. Returns true if the line is
  497. // consumed.
  498. static auto TryConsumeArgs(llvm::StringRef line, llvm::StringRef line_trimmed,
  499. llvm::SmallVector<std::string>& args)
  500. -> ErrorOr<bool> {
  501. if (!line_trimmed.consume_front("// ARGS: ")) {
  502. return false;
  503. }
  504. if (!args.empty()) {
  505. return ErrorBuilder() << "ARGS specified multiple times: " << line.str();
  506. }
  507. // Split the line into arguments.
  508. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  509. llvm::getToken(line_trimmed);
  510. while (!cursor.first.empty()) {
  511. args.push_back(std::string(cursor.first));
  512. cursor = llvm::getToken(cursor.second);
  513. }
  514. return true;
  515. }
  516. static auto TryConsumeExtraArgs(llvm::StringRef line_trimmed,
  517. llvm::SmallVector<std::string>& extra_args)
  518. -> ErrorOr<bool> {
  519. if (!line_trimmed.consume_front("// EXTRA-ARGS: ")) {
  520. return false;
  521. }
  522. // Split the line into arguments.
  523. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  524. llvm::getToken(line_trimmed);
  525. while (!cursor.first.empty()) {
  526. extra_args.push_back(std::string(cursor.first));
  527. cursor = llvm::getToken(cursor.second);
  528. }
  529. return true;
  530. }
  531. static auto TryConsumeIncludeFile(llvm::StringRef line_trimmed,
  532. llvm::SmallVector<std::string>& include_files)
  533. -> ErrorOr<bool> {
  534. if (!line_trimmed.consume_front("// INCLUDE-FILE: ")) {
  535. return false;
  536. }
  537. include_files.push_back(line_trimmed.str());
  538. return true;
  539. }
  540. // Processes AUTOUPDATE lines when found. Returns true if the line is consumed.
  541. // `found_autoupdate` and `autoupdate_line_number` are only provided for the
  542. // main file; it's an error to have autoupdate in included files.
  543. static auto TryConsumeAutoupdate(int line_index, llvm::StringRef line_trimmed,
  544. bool* found_autoupdate,
  545. std::optional<int>* autoupdate_line_number)
  546. -> ErrorOr<bool> {
  547. static constexpr llvm::StringLiteral Autoupdate = "// AUTOUPDATE";
  548. static constexpr llvm::StringLiteral NoAutoupdate = "// NOAUTOUPDATE";
  549. if (line_trimmed != Autoupdate && line_trimmed != NoAutoupdate) {
  550. return false;
  551. }
  552. if (!found_autoupdate) {
  553. return ErrorBuilder() << "Included files can't control autoupdate: "
  554. << line_trimmed;
  555. }
  556. if (*found_autoupdate) {
  557. return Error("Multiple AUTOUPDATE/NOAUTOUPDATE settings found");
  558. }
  559. *found_autoupdate = true;
  560. if (line_trimmed == Autoupdate) {
  561. *autoupdate_line_number = line_index;
  562. }
  563. return true;
  564. }
  565. // Processes SET-* lines when found. Returns true if the line is consumed.
  566. // If `flag` is null, we're in an included file where the flag can't be set.
  567. static auto TryConsumeSetFlag(llvm::StringRef line_trimmed,
  568. llvm::StringLiteral flag_name, bool* flag)
  569. -> ErrorOr<bool> {
  570. if (!line_trimmed.consume_front("// ") || line_trimmed != flag_name) {
  571. return false;
  572. }
  573. if (!flag) {
  574. return ErrorBuilder() << "Included files can't set flag: " << line_trimmed;
  575. }
  576. if (*flag) {
  577. return ErrorBuilder() << flag_name << " was specified multiple times";
  578. }
  579. *flag = true;
  580. return true;
  581. }
  582. // Process content for either the main file (with `test_file` and
  583. // `found_autoupdate` provided) or an included file (with those arguments null).
  584. //
  585. // - `found_autoupdate` is set to true when either `AUTOUPDATE` or
  586. // `NOAUTOUPDATE` are found.
  587. // - `args` is set from `ARGS`.
  588. // - `extra_args` accumulates `EXTRA-ARGS`.
  589. // - `splits` accumulates split form for the test (`// --- <filename>`, or the
  590. // full file named as `filename` when there are no splits in the file).
  591. // - `include_files` accumulates `INCLUDE-FILE`.
  592. static auto ProcessFileContent(llvm::StringRef filename,
  593. llvm::StringRef content_cursor,
  594. bool running_autoupdate, TestFile* test_file,
  595. bool* found_autoupdate,
  596. llvm::SmallVector<std::string>& args,
  597. llvm::SmallVector<std::string>& extra_args,
  598. llvm::SmallVector<TestFile::Split>& splits,
  599. llvm::SmallVector<std::string>& include_files)
  600. -> ErrorOr<Success> {
  601. // The index in the current test file. Will be reset on splits.
  602. int line_index = 0;
  603. // When autoupdating, we track whether we're inside conflict markers.
  604. // Otherwise conflict markers are errors.
  605. bool inside_conflict_marker = false;
  606. SplitState split_state;
  607. while (!content_cursor.empty()) {
  608. auto [line, next_cursor] = content_cursor.split("\n");
  609. content_cursor = next_cursor;
  610. auto line_trimmed = line.ltrim();
  611. bool is_consumed = false;
  612. CARBON_ASSIGN_OR_RETURN(
  613. is_consumed,
  614. TryConsumeConflictMarker(running_autoupdate, line, line_trimmed,
  615. inside_conflict_marker));
  616. if (is_consumed) {
  617. continue;
  618. }
  619. // At this point, remaining lines are part of the test input.
  620. // We need to consume a split, but the main file has a little more handling.
  621. bool missing_autoupdate = false;
  622. llvm::SmallVector<FileTestLine>* non_check_lines = nullptr;
  623. if (test_file) {
  624. missing_autoupdate = !*found_autoupdate;
  625. non_check_lines = &test_file->non_check_lines;
  626. }
  627. CARBON_ASSIGN_OR_RETURN(
  628. is_consumed,
  629. TryConsumeSplit(line, line_trimmed, missing_autoupdate, line_index,
  630. split_state, splits, non_check_lines));
  631. if (is_consumed) {
  632. continue;
  633. }
  634. ++line_index;
  635. // TIP lines have no impact on validation.
  636. if (line_trimmed.starts_with("// TIP:")) {
  637. continue;
  638. }
  639. CARBON_ASSIGN_OR_RETURN(
  640. is_consumed,
  641. TryConsumeCheck(running_autoupdate, line_index, line, line_trimmed,
  642. test_file ? &test_file->expected_stdout : nullptr,
  643. test_file ? &test_file->expected_stderr : nullptr));
  644. if (is_consumed) {
  645. continue;
  646. }
  647. if (test_file) {
  648. // At this point, lines are retained as non-CHECK lines.
  649. test_file->non_check_lines.push_back(
  650. FileTestLine(split_state.file_index, line_index, line));
  651. }
  652. CARBON_ASSIGN_OR_RETURN(is_consumed,
  653. TryConsumeArgs(line, line_trimmed, args));
  654. if (is_consumed) {
  655. continue;
  656. }
  657. CARBON_ASSIGN_OR_RETURN(is_consumed,
  658. TryConsumeExtraArgs(line_trimmed, extra_args));
  659. if (is_consumed) {
  660. continue;
  661. }
  662. CARBON_ASSIGN_OR_RETURN(is_consumed,
  663. TryConsumeIncludeFile(line_trimmed, include_files));
  664. if (is_consumed) {
  665. continue;
  666. }
  667. CARBON_ASSIGN_OR_RETURN(
  668. is_consumed,
  669. TryConsumeAutoupdate(
  670. line_index, line_trimmed, found_autoupdate,
  671. test_file ? &test_file->autoupdate_line_number : nullptr));
  672. if (is_consumed) {
  673. continue;
  674. }
  675. CARBON_ASSIGN_OR_RETURN(
  676. is_consumed,
  677. TryConsumeSetFlag(
  678. line_trimmed, "SET-CAPTURE-CONSOLE-OUTPUT",
  679. test_file ? &test_file->capture_console_output : nullptr));
  680. if (is_consumed) {
  681. continue;
  682. }
  683. CARBON_ASSIGN_OR_RETURN(
  684. is_consumed,
  685. TryConsumeSetFlag(line_trimmed, "SET-CHECK-SUBSET",
  686. test_file ? &test_file->check_subset : nullptr));
  687. if (is_consumed) {
  688. continue;
  689. }
  690. }
  691. CARBON_RETURN_IF_ERROR(FinishSplit(filename, /*is_include_file=*/!test_file,
  692. split_state, splits));
  693. if (test_file) {
  694. test_file->has_splits = split_state.has_splits();
  695. }
  696. return Success();
  697. }
  698. auto ProcessTestFile(llvm::StringRef test_name, bool running_autoupdate)
  699. -> ErrorOr<TestFile> {
  700. TestFile test_file;
  701. // Store the original content, to avoid a read when autoupdating.
  702. CARBON_ASSIGN_OR_RETURN(test_file.input_content, ReadFile(test_name.str()));
  703. // Whether either AUTOUDPATE or NOAUTOUPDATE was found.
  704. bool found_autoupdate = false;
  705. // INCLUDE-FILE uses, accumulated across both the main file and any includes
  706. // (recursively).
  707. llvm::SmallVector<std::string> include_files;
  708. // Process the main file.
  709. CARBON_RETURN_IF_ERROR(ProcessFileContent(
  710. test_name, test_file.input_content, running_autoupdate, &test_file,
  711. &found_autoupdate, test_file.test_args, test_file.extra_args,
  712. test_file.file_splits, include_files));
  713. if (!found_autoupdate) {
  714. return ErrorBuilder() << "Missing AUTOUPDATE/NOAUTOUPDATE setting: "
  715. << test_name;
  716. }
  717. constexpr llvm::StringLiteral AutoupdateSplit = "AUTOUPDATE-SPLIT";
  718. // Validate AUTOUPDATE-SPLIT use, and remove it from test files if present.
  719. if (test_file.has_splits) {
  720. for (const auto& test_file :
  721. llvm::ArrayRef(test_file.file_splits).drop_back()) {
  722. if (test_file.filename == AutoupdateSplit) {
  723. return Error("AUTOUPDATE-SPLIT must be the last split");
  724. }
  725. }
  726. if (test_file.file_splits.back().filename == AutoupdateSplit) {
  727. if (!test_file.autoupdate_line_number) {
  728. return Error("AUTOUPDATE-SPLIT requires AUTOUPDATE");
  729. }
  730. test_file.autoupdate_split = true;
  731. test_file.file_splits.pop_back();
  732. }
  733. }
  734. // Assume there is always a suffix `\n` in output.
  735. if (!test_file.expected_stdout.empty()) {
  736. test_file.expected_stdout.push_back(StrEq(""));
  737. }
  738. if (!test_file.expected_stderr.empty()) {
  739. test_file.expected_stderr.push_back(StrEq(""));
  740. }
  741. // Process includes. This can add entries to `include_files`.
  742. Set<std::string> processed_includes;
  743. for (size_t i = 0; i < include_files.size(); ++i) {
  744. const auto& filename = include_files[i];
  745. if (!processed_includes.Insert(filename).is_inserted()) {
  746. // Ignore repeated includes, mainly so that included files can include the
  747. // same file (i.e., repeated indirectly).
  748. continue;
  749. }
  750. CARBON_ASSIGN_OR_RETURN(std::string content, ReadFile(filename));
  751. // Note autoupdate never touches included files.
  752. CARBON_RETURN_IF_ERROR(ProcessFileContent(
  753. filename, content, /*running_autoupdate=*/false,
  754. /*test_file=*/nullptr,
  755. /*found_autoupdate=*/nullptr, test_file.test_args, test_file.extra_args,
  756. test_file.include_file_splits, include_files));
  757. }
  758. for (const auto& split : test_file.include_file_splits) {
  759. if (split.filename == AutoupdateSplit) {
  760. return Error("AUTOUPDATE-SPLIT is disallowed in included files");
  761. }
  762. }
  763. return std::move(test_file);
  764. }
  765. } // namespace Carbon::Testing