test_file.cpp 29 KB

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