autoupdate.cpp 14 KB

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