autoupdate.cpp 13 KB

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