test_file.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  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. Returns
  127. // the position to start a find for the next keyword.
  128. static auto ReplaceLspKeywordAt(std::string& content, size_t keyword_pos,
  129. int& lsp_call_id,
  130. llvm::ArrayRef<TestFile::Split> splits)
  131. -> ErrorOr<size_t> {
  132. llvm::StringRef content_at_keyword =
  133. llvm::StringRef(content).substr(keyword_pos);
  134. auto [keyword, body_start] = content_at_keyword.split(":");
  135. if (keyword.size() == content_at_keyword.size()) {
  136. return ErrorBuilder() << "Missing `:` for `"
  137. << content_at_keyword.take_front(10) << "`";
  138. }
  139. // Whether the first param is a method or id.
  140. llvm::StringRef method_or_id_label = "method";
  141. // Whether to attach the `lsp_call_id`.
  142. bool use_call_id = false;
  143. // The JSON label for extra content.
  144. llvm::StringRef extra_content_label;
  145. if (keyword == "[[@LSP-CALL") {
  146. use_call_id = true;
  147. extra_content_label = "params";
  148. } else if (keyword == "[[@LSP-NOTIFY") {
  149. extra_content_label = "params";
  150. } else if (keyword == "[[@LSP-REPLY") {
  151. method_or_id_label = "id";
  152. extra_content_label = "result";
  153. } else if (keyword != "[[@LSP") {
  154. return ErrorBuilder() << "Unrecognized @LSP keyword at `"
  155. << keyword.take_front(10) << "`";
  156. }
  157. static constexpr llvm::StringLiteral LspEnd = "]]";
  158. auto [body, rest] = body_start.split("]]");
  159. if (body.size() == body_start.size()) {
  160. return ErrorBuilder() << "Missing `" << LspEnd << "` after `" << keyword
  161. << "`";
  162. }
  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. size_t keyword_len = rest.data() - keyword.data();
  205. content.replace(keyword_pos, keyword_len, json_with_header);
  206. return keyword_pos + json_with_header.size();
  207. }
  208. // Replaces `[[@0xAB]]` with the raw byte with value 0xAB. Returns the position
  209. // to start a find for the next keyword.
  210. static auto ReplaceRawByteKeywordAt(std::string& content, size_t keyword_pos)
  211. -> ErrorOr<size_t> {
  212. llvm::StringRef content_at_keyword =
  213. llvm::StringRef(content).substr(keyword_pos);
  214. auto [keyword, rest] = content_at_keyword.split("]]");
  215. if (keyword.size() == content_at_keyword.size()) {
  216. return ErrorBuilder() << "Missing `]]` after " << keyword.take_front(10)
  217. << "`";
  218. }
  219. unsigned char byte_value;
  220. if (keyword.substr(std::size("[[@0x") - 1).getAsInteger(16, byte_value)) {
  221. return ErrorBuilder() << "Invalid raw byte specifier `"
  222. << keyword.take_front(10) << "`";
  223. }
  224. content.replace(keyword_pos, keyword.size() + 2, 1, byte_value);
  225. return keyword_pos + 1;
  226. }
  227. // Replaces the keyword at the given position. Returns the position to start a
  228. // find for the next keyword.
  229. static auto ReplaceContentKeywordAt(std::string& content, size_t keyword_pos,
  230. llvm::StringRef test_name, int& lsp_call_id,
  231. llvm::ArrayRef<TestFile::Split> splits)
  232. -> ErrorOr<size_t> {
  233. auto keyword = llvm::StringRef(content).substr(keyword_pos);
  234. // Line replacements aren't handled here.
  235. static constexpr llvm::StringLiteral Line = "[[@LINE";
  236. if (keyword.starts_with(Line)) {
  237. // Just move past the prefix to find the next one.
  238. return keyword_pos + Line.size();
  239. }
  240. // Replaced with the actual test name.
  241. static constexpr llvm::StringLiteral TestName = "[[@TEST_NAME]]";
  242. if (keyword.starts_with(TestName)) {
  243. content.replace(keyword_pos, TestName.size(), test_name);
  244. return keyword_pos + test_name.size();
  245. }
  246. if (keyword.starts_with("[[@LSP")) {
  247. return ReplaceLspKeywordAt(content, keyword_pos, lsp_call_id, splits);
  248. }
  249. if (keyword.starts_with("[[@0x")) {
  250. return ReplaceRawByteKeywordAt(content, keyword_pos);
  251. }
  252. return ErrorBuilder() << "Unexpected use of `[[@` at `"
  253. << keyword.substr(0, 5) << "`";
  254. }
  255. // Replaces the content keywords.
  256. //
  257. // This handles content keywords such as [[@TEST_NAME]] and [[@LSP*]]. Unknown
  258. // content keywords are diagnosed.
  259. static auto ReplaceContentKeywords(llvm::StringRef filename,
  260. std::string& content,
  261. llvm::ArrayRef<TestFile::Split> splits)
  262. -> ErrorOr<Success> {
  263. static constexpr llvm::StringLiteral Prefix = "[[@";
  264. auto keyword_pos = content.find(Prefix);
  265. // Return early if not finding anything.
  266. if (keyword_pos == std::string::npos) {
  267. return Success();
  268. }
  269. // Construct the test name by getting the base name without the extension,
  270. // then removing any "fail_" or "todo_" prefixes.
  271. llvm::StringRef test_name = filename;
  272. if (auto last_slash = test_name.rfind("/");
  273. last_slash != llvm::StringRef::npos) {
  274. test_name = test_name.substr(last_slash + 1);
  275. }
  276. if (auto ext_dot = test_name.find("."); ext_dot != llvm::StringRef::npos) {
  277. test_name = test_name.substr(0, ext_dot);
  278. }
  279. // Note this also handles `fail_todo_` and `todo_fail_`.
  280. test_name.consume_front("todo_");
  281. test_name.consume_front("fail_");
  282. test_name.consume_front("todo_");
  283. // A counter for LSP calls.
  284. int lsp_call_id = 0;
  285. while (keyword_pos != std::string::npos) {
  286. CARBON_ASSIGN_OR_RETURN(
  287. auto keyword_end,
  288. ReplaceContentKeywordAt(content, keyword_pos, test_name, lsp_call_id,
  289. splits));
  290. keyword_pos = content.find(Prefix, keyword_end);
  291. }
  292. return Success();
  293. }
  294. // Adds a file. Used for both split and unsplit test files.
  295. static auto AddSplit(llvm::StringRef filename, std::string& content,
  296. llvm::SmallVector<TestFile::Split>& file_splits)
  297. -> ErrorOr<Success> {
  298. CARBON_RETURN_IF_ERROR(
  299. ReplaceContentKeywords(filename, content, file_splits));
  300. file_splits.push_back(
  301. {.filename = filename.str(), .content = std::move(content)});
  302. content.clear();
  303. return Success();
  304. }
  305. // Process file split ("---") lines when found. Returns true if the line is
  306. // consumed. `non_check_lines` is only provided for the main file, and will be
  307. // null for includes.
  308. static auto TryConsumeSplit(llvm::StringRef line, llvm::StringRef line_trimmed,
  309. bool missing_autoupdate, int& line_index,
  310. SplitState& split,
  311. llvm::SmallVector<TestFile::Split>& file_splits,
  312. llvm::SmallVector<FileTestLine>* non_check_lines)
  313. -> ErrorOr<bool> {
  314. if (!line_trimmed.consume_front("// ---")) {
  315. if (!split.has_splits() && !line_trimmed.starts_with("//") &&
  316. !line_trimmed.empty()) {
  317. split.found_code_pre_split = true;
  318. }
  319. // Add the line to the current file's content (which may not be a split
  320. // file).
  321. split.add_content(line);
  322. return false;
  323. }
  324. if (missing_autoupdate) {
  325. // If there's a split, all output is appended at the end of each file
  326. // before AUTOUPDATE. We may want to change that, but it's not
  327. // necessary to handle right now.
  328. return Error(
  329. "AUTOUPDATE/NOAUTOUPDATE setting must be in "
  330. "the first file.");
  331. }
  332. // On a file split, add the previous file, then start a new one.
  333. if (split.has_splits()) {
  334. CARBON_RETURN_IF_ERROR(
  335. AddSplit(split.filename, split.content, file_splits));
  336. } else {
  337. split.content.clear();
  338. if (split.found_code_pre_split) {
  339. // For the first split, we make sure there was no content prior.
  340. return Error(
  341. "When using split files, there must be no content before the first "
  342. "split file.");
  343. }
  344. }
  345. ++split.file_index;
  346. split.filename = line_trimmed.trim();
  347. if (split.filename.empty()) {
  348. return Error("Missing filename for split.");
  349. }
  350. // The split line is added to non_check_lines for retention in autoupdate, but
  351. // is not added to the test file content.
  352. line_index = 0;
  353. if (non_check_lines) {
  354. non_check_lines->push_back(
  355. FileTestLine(split.file_index, line_index, line));
  356. }
  357. return true;
  358. }
  359. // Converts a `FileCheck`-style expectation string into a single complete regex
  360. // string by escaping all regex characters outside of the designated `{{...}}`
  361. // regex sequences, and switching those to a normal regex sub-pattern syntax.
  362. static auto ConvertExpectationStringToRegex(std::string& str) -> void {
  363. for (int pos = 0; pos < static_cast<int>(str.size());) {
  364. switch (str[pos]) {
  365. case '(':
  366. case ')':
  367. case '[':
  368. case ']':
  369. case '}':
  370. case '.':
  371. case '^':
  372. case '$':
  373. case '*':
  374. case '+':
  375. case '?':
  376. case '|':
  377. case '\\': {
  378. // Escape regex characters.
  379. str.insert(pos, "\\");
  380. pos += 2;
  381. break;
  382. }
  383. case '{': {
  384. if (pos + 1 == static_cast<int>(str.size()) || str[pos + 1] != '{') {
  385. // Single `{`, escape it.
  386. str.insert(pos, "\\");
  387. pos += 2;
  388. break;
  389. }
  390. // Replace the `{{...}}` regex syntax with standard `(...)` syntax.
  391. str.replace(pos, 2, "(");
  392. for (++pos; pos < static_cast<int>(str.size() - 1); ++pos) {
  393. if (str[pos] == '}' && str[pos + 1] == '}') {
  394. str.replace(pos, 2, ")");
  395. ++pos;
  396. break;
  397. }
  398. }
  399. break;
  400. }
  401. default: {
  402. ++pos;
  403. }
  404. }
  405. }
  406. }
  407. // Transforms an expectation on a given line from `FileCheck` syntax into a
  408. // standard regex matcher.
  409. static auto TransformExpectation(int line_index, llvm::StringRef in)
  410. -> ErrorOr<Matcher<std::string>> {
  411. if (in.empty()) {
  412. return Matcher<std::string>{StrEq("")};
  413. }
  414. if (!in.consume_front(" ")) {
  415. return ErrorBuilder() << "Malformated CHECK line: " << in;
  416. }
  417. // Check early if we have a regex component as we can avoid building an
  418. // expensive matcher when not using those.
  419. bool has_regex = in.find("{{") != llvm::StringRef::npos;
  420. // Now scan the string and expand any keywords. Note that this needs to be
  421. // `size_t` to correctly store `npos`.
  422. size_t keyword_pos = in.find("[[");
  423. // If there are neither keywords nor regex sequences, we can match the
  424. // incoming string directly.
  425. if (!has_regex && keyword_pos == llvm::StringRef::npos) {
  426. return Matcher<std::string>{StrEq(in)};
  427. }
  428. std::string str = in.str();
  429. // First expand the keywords.
  430. while (keyword_pos != std::string::npos) {
  431. llvm::StringRef line_keyword_cursor =
  432. llvm::StringRef(str).substr(keyword_pos);
  433. CARBON_CHECK(line_keyword_cursor.consume_front("[["));
  434. static constexpr llvm::StringLiteral LineKeyword = "@LINE";
  435. if (!line_keyword_cursor.consume_front(LineKeyword)) {
  436. return ErrorBuilder()
  437. << "Unexpected [[, should be {{\\[\\[}} at `"
  438. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  439. }
  440. // Allow + or - here; consumeInteger handles -.
  441. line_keyword_cursor.consume_front("+");
  442. int offset;
  443. // consumeInteger returns true for errors, not false.
  444. if (line_keyword_cursor.consumeInteger(10, offset) ||
  445. !line_keyword_cursor.consume_front("]]")) {
  446. return ErrorBuilder()
  447. << "Unexpected @LINE offset at `"
  448. << line_keyword_cursor.substr(0, 5) << "` in: " << in;
  449. }
  450. std::string int_str = llvm::Twine(line_index + offset).str();
  451. int remove_len = (line_keyword_cursor.data() - str.data()) - keyword_pos;
  452. str.replace(keyword_pos, remove_len, int_str);
  453. keyword_pos += int_str.size();
  454. // Find the next keyword start or the end of the string.
  455. keyword_pos = str.find("[[", keyword_pos);
  456. }
  457. // If there was no regex, we can directly match the adjusted string.
  458. if (!has_regex) {
  459. return Matcher<std::string>{StrEq(str)};
  460. }
  461. // Otherwise, we need to turn the entire string into a regex by escaping
  462. // things outside the regex region and transforming the regex region into a
  463. // normal syntax.
  464. ConvertExpectationStringToRegex(str);
  465. return Matcher<std::string>{MatchesRegex(str)};
  466. }
  467. // Once all content is processed, do any remaining split processing.
  468. static auto FinishSplit(llvm::StringRef filename, bool is_include_file,
  469. SplitState& split,
  470. llvm::SmallVector<TestFile::Split>& file_splits)
  471. -> ErrorOr<Success> {
  472. if (split.has_splits()) {
  473. return AddSplit(split.filename, split.content, file_splits);
  474. } else {
  475. // If no file splitting happened, use the main file as the test file.
  476. // There will always be a `/` unless tests are in the repo root.
  477. std::string split_name = std::filesystem::path(filename.str()).filename();
  478. if (is_include_file) {
  479. split_name.insert(0, "include_files/");
  480. }
  481. return AddSplit(split_name, split.content, file_splits);
  482. }
  483. }
  484. // Process CHECK lines when found. Returns true if the line is consumed.
  485. // `expected_stdout` and `expected_stderr` are null in included files, where
  486. // it's an error to use `CHECK`.
  487. static auto TryConsumeCheck(
  488. bool running_autoupdate, int line_index, llvm::StringRef line,
  489. llvm::StringRef line_trimmed,
  490. llvm::SmallVector<testing::Matcher<std::string>>* expected_stdout,
  491. llvm::SmallVector<testing::Matcher<std::string>>* expected_stderr)
  492. -> ErrorOr<bool> {
  493. if (!line_trimmed.consume_front("// CHECK")) {
  494. return false;
  495. }
  496. if (!expected_stdout) {
  497. return ErrorBuilder() << "Included files can't add CHECKs: "
  498. << line_trimmed;
  499. }
  500. // Don't build expectations when doing an autoupdate. We don't want to
  501. // break the autoupdate on an invalid CHECK line.
  502. if (!running_autoupdate) {
  503. llvm::SmallVector<Matcher<std::string>>* expected;
  504. if (line_trimmed.consume_front(":STDOUT:")) {
  505. expected = expected_stdout;
  506. } else if (line_trimmed.consume_front(":STDERR:")) {
  507. expected = expected_stderr;
  508. } else {
  509. return ErrorBuilder() << "Unexpected CHECK in input: " << line.str();
  510. }
  511. CARBON_ASSIGN_OR_RETURN(Matcher<std::string> check_matcher,
  512. TransformExpectation(line_index, line_trimmed));
  513. expected->push_back(check_matcher);
  514. }
  515. return true;
  516. }
  517. // Processes ARGS and EXTRA-ARGS lines when found. Returns true if the line is
  518. // consumed.
  519. static auto TryConsumeArgs(llvm::StringRef line, llvm::StringRef line_trimmed,
  520. llvm::SmallVector<std::string>& args)
  521. -> ErrorOr<bool> {
  522. if (!line_trimmed.consume_front("// ARGS: ")) {
  523. return false;
  524. }
  525. if (!args.empty()) {
  526. return ErrorBuilder() << "ARGS specified multiple times: " << line.str();
  527. }
  528. // Split the line into arguments.
  529. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  530. llvm::getToken(line_trimmed);
  531. while (!cursor.first.empty()) {
  532. args.push_back(std::string(cursor.first));
  533. cursor = llvm::getToken(cursor.second);
  534. }
  535. return true;
  536. }
  537. static auto TryConsumeExtraArgs(llvm::StringRef line_trimmed,
  538. llvm::SmallVector<std::string>& extra_args)
  539. -> ErrorOr<bool> {
  540. if (!line_trimmed.consume_front("// EXTRA-ARGS: ")) {
  541. return false;
  542. }
  543. // Split the line into arguments.
  544. std::pair<llvm::StringRef, llvm::StringRef> cursor =
  545. llvm::getToken(line_trimmed);
  546. while (!cursor.first.empty()) {
  547. extra_args.push_back(std::string(cursor.first));
  548. cursor = llvm::getToken(cursor.second);
  549. }
  550. return true;
  551. }
  552. static auto TryConsumeIncludeFile(llvm::StringRef line_trimmed,
  553. llvm::SmallVector<std::string>& include_files)
  554. -> ErrorOr<bool> {
  555. if (!line_trimmed.consume_front("// INCLUDE-FILE: ")) {
  556. return false;
  557. }
  558. include_files.push_back(line_trimmed.str());
  559. return true;
  560. }
  561. // Processes AUTOUPDATE lines when found. Returns true if the line is consumed.
  562. // `found_autoupdate` and `autoupdate_line_number` are only provided for the
  563. // main file; it's an error to have autoupdate in included files.
  564. static auto TryConsumeAutoupdate(int line_index, llvm::StringRef line_trimmed,
  565. bool* found_autoupdate,
  566. std::optional<int>* autoupdate_line_number)
  567. -> ErrorOr<bool> {
  568. static constexpr llvm::StringLiteral Autoupdate = "// AUTOUPDATE";
  569. static constexpr llvm::StringLiteral NoAutoupdate = "// NOAUTOUPDATE";
  570. if (line_trimmed != Autoupdate && line_trimmed != NoAutoupdate) {
  571. return false;
  572. }
  573. if (!found_autoupdate) {
  574. return ErrorBuilder() << "Included files can't control autoupdate: "
  575. << line_trimmed;
  576. }
  577. if (*found_autoupdate) {
  578. return Error("Multiple AUTOUPDATE/NOAUTOUPDATE settings found");
  579. }
  580. *found_autoupdate = true;
  581. if (line_trimmed == Autoupdate) {
  582. *autoupdate_line_number = line_index;
  583. }
  584. return true;
  585. }
  586. // Processes SET-* lines when found. Returns true if the line is consumed.
  587. // If `flag` is null, we're in an included file where the flag can't be set.
  588. static auto TryConsumeSetFlag(llvm::StringRef line_trimmed,
  589. llvm::StringLiteral flag_name, bool* flag)
  590. -> ErrorOr<bool> {
  591. if (!line_trimmed.consume_front("// ") || line_trimmed != flag_name) {
  592. return false;
  593. }
  594. if (!flag) {
  595. return ErrorBuilder() << "Included files can't set flag: " << line_trimmed;
  596. }
  597. if (*flag) {
  598. return ErrorBuilder() << flag_name << " was specified multiple times";
  599. }
  600. *flag = true;
  601. return true;
  602. }
  603. // Process content for either the main file (with `test_file` and
  604. // `found_autoupdate` provided) or an included file (with those arguments null).
  605. //
  606. // - `found_autoupdate` is set to true when either `AUTOUPDATE` or
  607. // `NOAUTOUPDATE` are found.
  608. // - `args` is set from `ARGS`.
  609. // - `extra_args` accumulates `EXTRA-ARGS`.
  610. // - `splits` accumulates split form for the test (`// --- <filename>`, or the
  611. // full file named as `filename` when there are no splits in the file).
  612. // - `include_files` accumulates `INCLUDE-FILE`.
  613. static auto ProcessFileContent(llvm::StringRef filename,
  614. llvm::StringRef content_cursor,
  615. bool running_autoupdate, TestFile* test_file,
  616. bool* found_autoupdate,
  617. llvm::SmallVector<std::string>& args,
  618. llvm::SmallVector<std::string>& extra_args,
  619. llvm::SmallVector<TestFile::Split>& splits,
  620. llvm::SmallVector<std::string>& include_files)
  621. -> ErrorOr<Success> {
  622. // The index in the current test file. Will be reset on splits.
  623. int line_index = 0;
  624. // When autoupdating, we track whether we're inside conflict markers.
  625. // Otherwise conflict markers are errors.
  626. bool inside_conflict_marker = false;
  627. SplitState split_state;
  628. while (!content_cursor.empty()) {
  629. auto [line, next_cursor] = content_cursor.split("\n");
  630. content_cursor = next_cursor;
  631. auto line_trimmed = line.ltrim();
  632. bool is_consumed = false;
  633. CARBON_ASSIGN_OR_RETURN(
  634. is_consumed,
  635. TryConsumeConflictMarker(running_autoupdate, line, line_trimmed,
  636. inside_conflict_marker));
  637. if (is_consumed) {
  638. continue;
  639. }
  640. // At this point, remaining lines are part of the test input.
  641. // We need to consume a split, but the main file has a little more handling.
  642. bool missing_autoupdate = false;
  643. llvm::SmallVector<FileTestLine>* non_check_lines = nullptr;
  644. if (test_file) {
  645. missing_autoupdate = !*found_autoupdate;
  646. non_check_lines = &test_file->non_check_lines;
  647. }
  648. CARBON_ASSIGN_OR_RETURN(
  649. is_consumed,
  650. TryConsumeSplit(line, line_trimmed, missing_autoupdate, line_index,
  651. split_state, splits, non_check_lines));
  652. if (is_consumed) {
  653. continue;
  654. }
  655. ++line_index;
  656. // TIP lines have no impact on validation.
  657. if (line_trimmed.starts_with("// TIP:")) {
  658. continue;
  659. }
  660. CARBON_ASSIGN_OR_RETURN(
  661. is_consumed,
  662. TryConsumeCheck(running_autoupdate, line_index, line, line_trimmed,
  663. test_file ? &test_file->expected_stdout : nullptr,
  664. test_file ? &test_file->expected_stderr : nullptr));
  665. if (is_consumed) {
  666. continue;
  667. }
  668. if (test_file) {
  669. // At this point, lines are retained as non-CHECK lines.
  670. test_file->non_check_lines.push_back(
  671. FileTestLine(split_state.file_index, line_index, line));
  672. }
  673. CARBON_ASSIGN_OR_RETURN(is_consumed,
  674. TryConsumeArgs(line, line_trimmed, args));
  675. if (is_consumed) {
  676. continue;
  677. }
  678. CARBON_ASSIGN_OR_RETURN(is_consumed,
  679. TryConsumeExtraArgs(line_trimmed, extra_args));
  680. if (is_consumed) {
  681. continue;
  682. }
  683. CARBON_ASSIGN_OR_RETURN(is_consumed,
  684. TryConsumeIncludeFile(line_trimmed, include_files));
  685. if (is_consumed) {
  686. continue;
  687. }
  688. CARBON_ASSIGN_OR_RETURN(
  689. is_consumed,
  690. TryConsumeAutoupdate(
  691. line_index, line_trimmed, found_autoupdate,
  692. test_file ? &test_file->autoupdate_line_number : nullptr));
  693. if (is_consumed) {
  694. continue;
  695. }
  696. CARBON_ASSIGN_OR_RETURN(
  697. is_consumed,
  698. TryConsumeSetFlag(
  699. line_trimmed, "SET-CAPTURE-CONSOLE-OUTPUT",
  700. test_file ? &test_file->capture_console_output : nullptr));
  701. if (is_consumed) {
  702. continue;
  703. }
  704. CARBON_ASSIGN_OR_RETURN(
  705. is_consumed,
  706. TryConsumeSetFlag(line_trimmed, "SET-CHECK-SUBSET",
  707. test_file ? &test_file->check_subset : nullptr));
  708. if (is_consumed) {
  709. continue;
  710. }
  711. }
  712. CARBON_RETURN_IF_ERROR(FinishSplit(filename, /*is_include_file=*/!test_file,
  713. split_state, splits));
  714. if (test_file) {
  715. test_file->has_splits = split_state.has_splits();
  716. }
  717. return Success();
  718. }
  719. auto ProcessTestFile(llvm::StringRef test_name, bool running_autoupdate)
  720. -> ErrorOr<TestFile> {
  721. TestFile test_file;
  722. // Store the original content, to avoid a read when autoupdating.
  723. CARBON_ASSIGN_OR_RETURN(test_file.input_content, ReadFile(test_name.str()));
  724. // Whether either AUTOUDPATE or NOAUTOUPDATE was found.
  725. bool found_autoupdate = false;
  726. // INCLUDE-FILE uses, accumulated across both the main file and any includes
  727. // (recursively).
  728. llvm::SmallVector<std::string> include_files;
  729. // Store the main file's `EXTRA-ARGS` so that they can be put after any that
  730. // come from `INCLUDE-FILE`.
  731. llvm::SmallVector<std::string> main_extra_args;
  732. // Process the main file.
  733. CARBON_RETURN_IF_ERROR(ProcessFileContent(
  734. test_name, test_file.input_content, running_autoupdate, &test_file,
  735. &found_autoupdate, test_file.test_args, main_extra_args,
  736. test_file.file_splits, include_files));
  737. if (!found_autoupdate) {
  738. return ErrorBuilder() << "Missing AUTOUPDATE/NOAUTOUPDATE setting";
  739. }
  740. constexpr llvm::StringLiteral AutoupdateSplit = "AUTOUPDATE-SPLIT";
  741. // Validate AUTOUPDATE-SPLIT use, and remove it from test files if present.
  742. if (test_file.has_splits) {
  743. for (const auto& test_file :
  744. llvm::ArrayRef(test_file.file_splits).drop_back()) {
  745. if (test_file.filename == AutoupdateSplit) {
  746. return Error("AUTOUPDATE-SPLIT must be the last split");
  747. }
  748. }
  749. if (test_file.file_splits.back().filename == AutoupdateSplit) {
  750. if (!test_file.autoupdate_line_number) {
  751. return Error("AUTOUPDATE-SPLIT requires AUTOUPDATE");
  752. }
  753. test_file.autoupdate_split = true;
  754. test_file.file_splits.pop_back();
  755. }
  756. }
  757. // Assume there is always a suffix `\n` in output.
  758. if (!test_file.expected_stdout.empty()) {
  759. test_file.expected_stdout.push_back(StrEq(""));
  760. }
  761. if (!test_file.expected_stderr.empty()) {
  762. test_file.expected_stderr.push_back(StrEq(""));
  763. }
  764. // Process includes. This can add entries to `include_files`.
  765. Set<std::string> processed_includes;
  766. for (size_t i = 0; i < include_files.size(); ++i) {
  767. const auto& filename = include_files[i];
  768. if (!processed_includes.Insert(filename).is_inserted()) {
  769. // Ignore repeated includes, mainly so that included files can include the
  770. // same file (i.e., repeated indirectly).
  771. continue;
  772. }
  773. CARBON_ASSIGN_OR_RETURN(std::string content, ReadFile(filename));
  774. // Note autoupdate never touches included files.
  775. CARBON_RETURN_IF_ERROR(ProcessFileContent(
  776. filename, content, /*running_autoupdate=*/false,
  777. /*test_file=*/nullptr,
  778. /*found_autoupdate=*/nullptr, test_file.test_args, test_file.extra_args,
  779. test_file.include_file_splits, include_files));
  780. }
  781. for (const auto& split : test_file.include_file_splits) {
  782. if (split.filename == AutoupdateSplit) {
  783. return Error("AUTOUPDATE-SPLIT is disallowed in included files");
  784. }
  785. }
  786. // Copy over `EXTRA-ARGS` from the main file (after includes).
  787. test_file.extra_args.append(main_extra_args);
  788. return std::move(test_file);
  789. }
  790. } // namespace Carbon::Testing