autoupdate.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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/autoupdate.h"
  5. #include <fstream>
  6. #include <string>
  7. #include <utility>
  8. #include "absl/strings/str_replace.h"
  9. #include "absl/strings/string_view.h"
  10. #include "common/check.h"
  11. #include "common/ostream.h"
  12. #include "common/raw_string_ostream.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/Support/FormatVariadic.h"
  16. namespace Carbon::Testing {
  17. // Converts a matched line number to an int, trimming whitespace. Returns 0 if
  18. // there is no line number, to assist early placement.
  19. static auto ParseLineNumber(absl::string_view matched_line_number) -> int {
  20. llvm::StringRef trimmed = matched_line_number;
  21. trimmed = trimmed.trim();
  22. if (trimmed.empty()) {
  23. return 0;
  24. }
  25. // NOLINTNEXTLINE(google-runtime-int): API requirement.
  26. long long val;
  27. CARBON_CHECK(!llvm::getAsSignedInteger(trimmed, 10, val), "{0}",
  28. matched_line_number);
  29. return val;
  30. }
  31. FileTestAutoupdater::FileAndLineNumber::FileAndLineNumber(
  32. const LineNumberReplacement* replacement, int file_number,
  33. absl::string_view line_number)
  34. : replacement(replacement),
  35. file_number(file_number),
  36. line_number(ParseLineNumber(line_number)) {}
  37. auto FileTestAutoupdater::CheckLine::RemapLineNumbers(
  38. const llvm::DenseMap<std::pair<int, int>, int>& output_line_remap,
  39. const llvm::SmallVector<int>& new_last_line_numbers) -> void {
  40. // Only need to do remappings when there's a line number replacement.
  41. if (!replacement_) {
  42. return;
  43. }
  44. // Use a cursor for the line so that we can't keep matching the same
  45. // content, which may occur when we keep a literal line number.
  46. int line_offset = 0;
  47. while (true) {
  48. // Rebuild the cursor each time because we're editing the line, which
  49. // could cause a reallocation.
  50. absl::string_view line_cursor = line_;
  51. line_cursor.remove_prefix(line_offset);
  52. // Look for a line number to replace. There may be multiple, so we
  53. // repeatedly check.
  54. absl::string_view matched_line_number;
  55. if (replacement_->has_file) {
  56. RE2::PartialMatch(line_cursor, *replacement_->re, nullptr,
  57. &matched_line_number);
  58. } else {
  59. RE2::PartialMatch(line_cursor, *replacement_->re, &matched_line_number);
  60. }
  61. if (matched_line_number.empty()) {
  62. return;
  63. }
  64. // Update the cursor offset from the match.
  65. line_offset = matched_line_number.begin() - line_.c_str();
  66. // Calculate the new line number (possibly with new CHECK lines added, or
  67. // some removed).
  68. int old_line_number = ParseLineNumber(matched_line_number);
  69. int new_line_number = -1;
  70. if (auto remapped =
  71. output_line_remap.find({file_number(), old_line_number});
  72. remapped != output_line_remap.end()) {
  73. // Map old non-check lines to their new line numbers.
  74. new_line_number = remapped->second;
  75. } else {
  76. // We assume unmapped references point to the end-of-file.
  77. new_line_number = new_last_line_numbers[file_number()];
  78. }
  79. std::string replacement;
  80. if (output_file_number_ == file_number()) {
  81. int offset = new_line_number - output_line_number_;
  82. // Update the line offset in the CHECK line.
  83. const char* offset_prefix = offset < 0 ? "" : "+";
  84. replacement = llvm::formatv(
  85. replacement_->line_formatv.c_str(),
  86. llvm::formatv("[[@LINE{0}{1}]]", offset_prefix, offset));
  87. } else {
  88. // If the CHECK was written to a different file from the file that it
  89. // refers to, leave behind an absolute line reference rather than a
  90. // cross-file offset.
  91. replacement =
  92. llvm::formatv(replacement_->line_formatv.c_str(), new_line_number);
  93. }
  94. line_.replace(matched_line_number.data() - line_.data(),
  95. matched_line_number.size(), replacement);
  96. }
  97. }
  98. auto FileTestAutoupdater::GetFileAndLineNumber(
  99. const llvm::DenseMap<llvm::StringRef, int>& file_to_number_map,
  100. int default_file_number, const std::string& check_line)
  101. -> FileAndLineNumber {
  102. for (const auto& replacement : line_number_replacements_) {
  103. if (replacement.has_file) {
  104. absl::string_view filename;
  105. absl::string_view line_number;
  106. if (RE2::PartialMatch(check_line, *replacement.re, &filename,
  107. &line_number)) {
  108. if (auto it = file_to_number_map.find(filename);
  109. it != file_to_number_map.end()) {
  110. return FileAndLineNumber(&replacement, it->second, line_number);
  111. } else {
  112. return FileAndLineNumber(default_file_number);
  113. }
  114. }
  115. } else {
  116. // There's no file association, so we only look at the line, and assume
  117. // it refers to the default file.
  118. absl::string_view line_number;
  119. if (RE2::PartialMatch(check_line, *replacement.re, &line_number)) {
  120. return FileAndLineNumber(&replacement, default_file_number,
  121. line_number);
  122. }
  123. }
  124. }
  125. return FileAndLineNumber(default_file_number);
  126. }
  127. auto FileTestAutoupdater::BuildCheckLines(llvm::StringRef output,
  128. const char* label) -> CheckLines {
  129. if (output.empty()) {
  130. return CheckLines({});
  131. }
  132. // Prepare to look for filenames in lines.
  133. llvm::DenseMap<llvm::StringRef, int> file_to_number_map;
  134. for (auto [number, name] : llvm::enumerate(filenames_)) {
  135. file_to_number_map.insert({name, number});
  136. }
  137. // %t substitution means we may see TEST_TMPDIR in output.
  138. char* tmpdir_env = getenv("TEST_TMPDIR");
  139. CARBON_CHECK(tmpdir_env != nullptr);
  140. llvm::StringRef tmpdir = tmpdir_env;
  141. llvm::SmallVector<llvm::StringRef> lines(llvm::split(output, '\n'));
  142. // It's typical that output ends with a newline, but we don't want to add a
  143. // blank CHECK for it.
  144. if (lines.back().empty()) {
  145. lines.pop_back();
  146. }
  147. // The default file number for when no specific file is found.
  148. int default_file_number = 0;
  149. llvm::SmallVector<CheckLine> check_lines;
  150. for (const auto& line : lines) {
  151. // This code is relatively hot in our testing, and because when testing it
  152. // isn't run with an optimizer we benefit from making it use simple
  153. // constructs. For this reason, we avoid `llvm::formatv` and similar tools.
  154. std::string check_line;
  155. check_line.reserve(line.size() + strlen(label) + strlen("// CHECK:: "));
  156. check_line.append("// CHECK:");
  157. check_line.append(label);
  158. check_line.append(":");
  159. if (!line.empty()) {
  160. check_line.append(" ");
  161. check_line.append(line);
  162. }
  163. // \r and \t are invisible characters worth marking.
  164. // {{ and [[ are autoupdate syntax which we need to escape.
  165. check_line = absl::StrReplaceAll(check_line, {{"\r", R"({{\r}})"},
  166. {"\t", R"({{\t}})"},
  167. {"{{", R"({{\{\{}})"},
  168. {"[[", R"({{\[\[}})"}});
  169. // Add an empty regex to call out end-of-line whitespace.
  170. if (check_line.ends_with(' ')) {
  171. check_line.append("{{}}");
  172. }
  173. // Ignore TEST_TMPDIR in output.
  174. if (auto pos = check_line.find(tmpdir); pos != std::string::npos) {
  175. check_line.replace(pos, tmpdir.size(), "{{.+}}");
  176. }
  177. do_extra_check_replacements_(check_line);
  178. if (default_file_re_) {
  179. absl::string_view filename;
  180. if (RE2::PartialMatch(line, *default_file_re_, &filename)) {
  181. auto it = file_to_number_map.find(filename);
  182. CARBON_CHECK(it != file_to_number_map.end(),
  183. "default_file_re had unexpected match in '{0}' (`{1}`)",
  184. line, default_file_re_->pattern());
  185. default_file_number = it->second;
  186. }
  187. }
  188. auto file_and_line = GetFileAndLineNumber(file_to_number_map,
  189. default_file_number, check_line);
  190. check_lines.push_back(CheckLine(file_and_line, check_line));
  191. }
  192. return CheckLines(check_lines);
  193. }
  194. auto FileTestAutoupdater::AddRemappedNonCheckLine() -> void {
  195. new_lines_.push_back(non_check_line_);
  196. CARBON_CHECK(output_line_remap_
  197. .insert({{non_check_line_->file_number(),
  198. non_check_line_->line_number()},
  199. ++output_line_number_})
  200. .second);
  201. }
  202. auto FileTestAutoupdater::AddTips() -> void {
  203. CARBON_CHECK(tips_.empty(), "Should only add tips once");
  204. tips_.reserve(4);
  205. // This puts commands on a single line so that they can be easily copied.
  206. tips_.emplace_back("// TIP: To test this file alone, run:");
  207. tips_.emplace_back("// TIP: " + test_command_);
  208. tips_.emplace_back("// TIP: To dump output, run:");
  209. tips_.emplace_back("// TIP: " + dump_command_);
  210. for (const auto& tip : tips_) {
  211. new_lines_.push_back(&tip);
  212. ++output_line_number_;
  213. }
  214. }
  215. auto FileTestAutoupdater::ShouldAddCheckLine(const CheckLines& check_lines,
  216. bool to_file_end) const -> bool {
  217. return !autoupdate_split_ && check_lines.cursor != check_lines.lines.end() &&
  218. (check_lines.cursor->file_number() < output_file_number_ ||
  219. (check_lines.cursor->file_number() == output_file_number_ &&
  220. (to_file_end || check_lines.cursor->line_number() <=
  221. non_check_line_->line_number())));
  222. }
  223. auto FileTestAutoupdater::AddCheckLines(CheckLines& check_lines,
  224. bool to_file_end) -> void {
  225. for (; ShouldAddCheckLine(check_lines, to_file_end); ++check_lines.cursor) {
  226. new_lines_.push_back(check_lines.cursor);
  227. check_lines.cursor->SetOutputLine(
  228. to_file_end ? "" : non_check_line_->indent(), output_file_number_,
  229. ++output_line_number_);
  230. }
  231. }
  232. auto FileTestAutoupdater::FinishFile(bool is_last_file) -> void {
  233. bool include_stdout = any_attached_stdout_lines_ || is_last_file;
  234. // At the end of each file, print any remaining lines which are associated
  235. // with the file.
  236. if (ShouldAddCheckLine(stderr_, /*to_file_end=*/true) ||
  237. (include_stdout && ShouldAddCheckLine(stdout_, /*to_file_end=*/true))) {
  238. // Ensure there's a blank line before any trailing CHECKs.
  239. if (!new_lines_.empty() && !new_lines_.back()->is_blank()) {
  240. new_lines_.push_back(&blank_line_);
  241. ++output_line_number_;
  242. }
  243. AddCheckLines(stderr_, /*to_file_end=*/true);
  244. if (include_stdout) {
  245. AddCheckLines(stdout_, /*to_file_end=*/true);
  246. }
  247. }
  248. new_last_line_numbers_.push_back(output_line_number_);
  249. }
  250. auto FileTestAutoupdater::StartSplitFile() -> void {
  251. // Advance the file.
  252. ++output_file_number_;
  253. output_line_number_ = 0;
  254. CARBON_CHECK(output_file_number_ == non_check_line_->file_number(),
  255. "Non-sequential file: {0}", non_check_line_->file_number());
  256. // Each following file has precisely one split line.
  257. CARBON_CHECK(non_check_line_->line_number() < 1,
  258. "Expected a split line, got {0}", *non_check_line_);
  259. // The split line is ignored when calculating line counts.
  260. new_lines_.push_back(non_check_line_);
  261. // Add any file-specific but line-unattached STDOUT messages here. STDERR is
  262. // handled through the main loop because it's before the next line.
  263. if (any_attached_stdout_lines_) {
  264. AddCheckLines(stdout_, /*to_file_end=*/false);
  265. }
  266. ++non_check_line_;
  267. }
  268. auto FileTestAutoupdater::Run(bool dry_run) -> bool {
  269. // Print everything until the autoupdate line.
  270. while (non_check_line_->line_number() != autoupdate_line_number_) {
  271. CARBON_CHECK(non_check_line_ != non_check_lines_.end() &&
  272. non_check_line_->file_number() == 0,
  273. "Missed autoupdate?");
  274. AddRemappedNonCheckLine();
  275. ++non_check_line_;
  276. }
  277. // Add the AUTOUPDATE line along with any early STDERR lines, so that the
  278. // initial batch of CHECK lines have STDERR before STDOUT. This also ensures
  279. // we don't insert a blank line before the STDERR checks if there are no more
  280. // lines after AUTOUPDATE.
  281. AddRemappedNonCheckLine();
  282. AddTips();
  283. if (!autoupdate_split_) {
  284. AddCheckLines(stderr_, /*to_file_end=*/false);
  285. if (any_attached_stdout_lines_) {
  286. AddCheckLines(stdout_, /*to_file_end=*/false);
  287. }
  288. }
  289. ++non_check_line_;
  290. // Loop through remaining content.
  291. while (non_check_line_ != non_check_lines_.end()) {
  292. if (output_file_number_ < non_check_line_->file_number()) {
  293. FinishFile(/*is_last_file=*/false);
  294. StartSplitFile();
  295. if (autoupdate_split_ &&
  296. output_file_number_ == static_cast<int>(filenames_.size())) {
  297. break;
  298. }
  299. continue;
  300. }
  301. // STDERR check lines are placed before the line they refer to, or as
  302. // early as possible if they don't refer to a line. Include all STDERR
  303. // lines until we find one that wants to go later in the file.
  304. AddCheckLines(stderr_, /*to_file_end=*/false);
  305. AddRemappedNonCheckLine();
  306. // STDOUT check lines are placed after the line they refer to, or at the
  307. // end of the file if none of them refers to a line.
  308. if (any_attached_stdout_lines_) {
  309. AddCheckLines(stdout_, /*to_file_end=*/false);
  310. }
  311. ++non_check_line_;
  312. }
  313. // When autoupdate_split_ was true, this will result in all check lines (and
  314. // only check lines) being added to the split by FinishFile. We don't use
  315. // autoupdate_split_ past this point.
  316. autoupdate_split_ = false;
  317. FinishFile(/*is_last_file=*/true);
  318. for (auto& check_line : stdout_.lines) {
  319. check_line.RemapLineNumbers(output_line_remap_, new_last_line_numbers_);
  320. }
  321. for (auto& check_line : stderr_.lines) {
  322. check_line.RemapLineNumbers(output_line_remap_, new_last_line_numbers_);
  323. }
  324. // Generate the autoupdated file.
  325. RawStringOstream new_content_stream;
  326. for (const auto& line : new_lines_) {
  327. new_content_stream << *line << '\n';
  328. }
  329. std::string new_content = new_content_stream.TakeStr();
  330. // Update the file on disk if needed.
  331. if (new_content == input_content_) {
  332. return false;
  333. }
  334. if (!dry_run) {
  335. std::ofstream out(file_test_path_);
  336. out << new_content;
  337. }
  338. return true;
  339. }
  340. } // namespace Carbon::Testing