llvm-project
128 строк · 4.0 Кб
1#!/usr/bin/env python3
2
3"""Replaces absolute line numbers in lit-tests with relative line numbers.
4
5Writing line numbers like 152 in 'RUN: or CHECK:' makes tests hard to maintain:
6inserting lines in the middle of the test means updating all the line numbers.
7
8Encoding them relative to the current line helps, and tools support it:
9Lit will substitute %(line+2) with the actual line number
10FileCheck supports [[@LINE+2]]
11
12This tool takes a regex which captures a line number, and a list of test files.
13It searches for line numbers in the files and replaces them with a relative
14line number reference.
15"""
16
17USAGE = """Example usage:
18find -type f clang/test/CodeCompletion | grep -v /Inputs/ | \\
19xargs relative_lines.py --dry-run --verbose --near=100 \\
20--pattern='-code-completion-at[ =]%s:(\d+)' \\
21--pattern='requires fix-it: {(\d+):\d+-(\d+):\d+}'
22"""
23
24import argparse
25import re
26import sys
27
28
29def b(x):
30return bytes(x, encoding="utf-8")
31
32
33parser = argparse.ArgumentParser(
34prog="relative_lines",
35description=__doc__,
36epilog=USAGE,
37formatter_class=argparse.RawTextHelpFormatter,
38)
39parser.add_argument(
40"--near", type=int, default=20, help="maximum line distance to make relative"
41)
42parser.add_argument(
43"--partial",
44action="store_true",
45default=False,
46help="apply replacements to files even if others failed",
47)
48parser.add_argument(
49"--pattern",
50default=[],
51action="append",
52type=lambda x: re.compile(b(x)),
53help="regex to match, with line numbers captured in ().",
54)
55parser.add_argument(
56"--verbose", action="store_true", default=False, help="print matches applied"
57)
58parser.add_argument(
59"--dry-run",
60action="store_true",
61default=False,
62help="don't apply replacements. Best with --verbose.",
63)
64parser.add_argument("files", nargs="+")
65args = parser.parse_args()
66
67for file in args.files:
68try:
69contents = open(file, "rb").read()
70except UnicodeDecodeError as e:
71print(f"{file}: not valid UTF-8 - {e}", file=sys.stderr)
72failures = 0
73
74def line_number(offset):
75return 1 + contents[:offset].count(b"\n")
76
77def replace_one(capture, line, offset):
78"""Text to replace a capture group, e.g. 42 => %(line+1)"""
79try:
80target = int(capture)
81except ValueError:
82print(f"{file}:{line}: matched non-number '{capture}'", file=sys.stderr)
83return capture
84
85if args.near > 0 and abs(target - line) > args.near:
86print(
87f"{file}:{line}: target line {target} is farther than {args.near}",
88file=sys.stderr,
89)
90return capture
91if target > line:
92delta = "+" + str(target - line)
93elif target < line:
94delta = "-" + str(line - target)
95else:
96delta = ""
97
98prefix = contents[:offset].rsplit(b"\n")[-1]
99is_lit = b"RUN" in prefix or b"DEFINE" in prefix
100text = ("%(line{0})" if is_lit else "[[@LINE{0}]]").format(delta)
101if args.verbose:
102print(f"{file}:{line}: {0} ==> {text}")
103return b(text)
104
105def replace_match(m):
106"""Text to replace a whole match, e.g. --at=42:3 => --at=%(line+2):3"""
107line = 1 + contents[: m.start()].count(b"\n")
108result = b""
109pos = m.start()
110for index, capture in enumerate(m.groups()):
111index += 1 # re groups are conventionally 1-indexed
112result += contents[pos : m.start(index)]
113replacement = replace_one(capture, line, m.start(index))
114result += replacement
115if replacement == capture:
116global failures
117failures += 1
118pos = m.end(index)
119result += contents[pos : m.end()]
120return result
121
122for pattern in args.pattern:
123contents = re.sub(pattern, replace_match, contents)
124if failures > 0 and not args.partial:
125print(f"{file}: leaving unchanged (some failed, --partial not given)")
126continue
127if not args.dry_run:
128open(file, "wb").write(contents)
129