autoupdate.cpp 14 KB

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