Repository navigation
Expand file tree
/
Copy pathproofloc.py
More file actions
executable file
·277 lines (235 loc) · 7.92 KB
/
Copy pathproofloc.py
File metadata and controls
executable file
·277 lines (235 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
#!/usr/bin/env python3
import argparse
import re
import json
import sys
from collections import defaultdict
SINGLE_LINE_PROOF_PATTERN = re.compile(
r"""
([ \t]|^)Proof\. # Proof keyword
.* # The actual proof.
[ \t.]Qed\. # End of proof keyword.
""",
re.VERBOSE,
)
PROOF_START_PATTERN = re.compile(r"[ \t^](Proof|Next +Obligation)\.")
PROOF_END_PATTERN = re.compile(r"[ \t^.](Qed|Defined)\.")
CLAIM_NAME_PATTERN = re.compile(
r"""
# first a keyword indicating a claim
(Lemma|Theorem|Corollary|Fact|Remark|Example)
\s+ # whitespace
([^:\s]+) # the identifier (anything up to the first space or colon)
""",
re.VERBOSE,
)
COMMENT_SEPARATOR_PATTERN = re.compile(r"\(\*|\*\)")
def banner(fname):
fill1 = (76 - len(fname)) // 2
fill2 = 76 - len(fname) - fill1
print("%s[ %s ]%s" % ("=" * fill1, fname, "=" * fill2))
def show_line(tag, line_number, line):
print("%3s %4d %s" % (tag, line_number + 1, line), end="")
def silent(tag, line_number, line):
pass
def process_file(fname, annotate=silent):
proofs = []
in_proof = False
in_comment = 0
claim = "???"
discounted_lines = 0
start = -1
with open(fname) as f:
for i, line in enumerate(f):
# strip comments
ranges = [(0, in_comment)]
for m in COMMENT_SEPARATOR_PATTERN.finditer(line):
if m.group(0) == "(*":
in_comment += 1
ranges.append((m.start(), in_comment))
elif m.group(0) == "*)":
in_comment -= 1
ranges.append((m.end(), in_comment))
assert in_comment >= 0
else:
assert False # unreachable unless regex is wrong
ranges.append((len(line), in_comment))
filtered_line = ""
for s, e in zip(ranges, ranges[1:]):
if s[1] == 0:
filtered_line += line[s[0] : e[0]]
else:
filtered_line += " "
name_match = CLAIM_NAME_PATTERN.search(filtered_line)
if name_match is not None:
claim = name_match.group(2)
if in_proof:
if PROOF_END_PATTERN.search(filtered_line):
annotate("###", i, line)
proofs.append(
(fname, start + 1, claim, i - start - 1 - discounted_lines)
)
in_proof = False
claim = "???"
elif not filtered_line.strip():
# empty line or only comment
discounted_lines += 1
annotate(" ", i, line)
else:
annotate(" P ", i, line)
elif SINGLE_LINE_PROOF_PATTERN.search(filtered_line):
annotate("*P*", i, line)
proofs.append((fname, i + 1, claim, 1))
claim = "???"
elif PROOF_START_PATTERN.search(filtered_line):
annotate("***", i, line)
in_proof = True
start = i
discounted_lines = 0
else:
annotate(" ", i, line)
return proofs
def show_histogram(opts, all_proofs):
limit = 0
counts = []
for fname, line, claim, length in reversed(all_proofs):
if length > limit:
limit += opts.bin_size
counts.append(0)
counts[-1] += 1
print(" LOC #Proofs")
print("=" * 19)
for i, count in enumerate(counts):
print(" <= %3d %7d" % ((i + 1) * opts.bin_size, count))
def create_db(opts, all_proofs):
db = {}
db["manual_exceptions"] = opts.long_proofs["manual_exceptions"]
db["legacy_proofs"] = defaultdict(dict)
for fname, line, claim, length in all_proofs:
if fname in db["manual_exceptions"] and claim in db["manual_exceptions"][fname]:
# skip manually approved long proofs
continue
if length >= opts.threshold:
db["legacy_proofs"][fname][claim] = length
print(json.dumps(db, sort_keys=True, indent=4))
def check_proof_lengths(opts, all_proofs):
new_long_proofs = False
known_long_proofs = 0
for fname, line, claim, length in all_proofs:
if length <= opts.threshold:
break
known = False
for category in ["manual_exceptions", "legacy_proofs"]:
if (
fname in opts.long_proofs[category]
and claim in opts.long_proofs[category][fname]
and opts.long_proofs[category][fname][claim] >= length
):
# this is a known long proof of non-increased length
# no need to complain
known = True
if not known:
print(
"Warning: new long proof of %s in %s:%d!" % (claim, fname, line),
file=sys.stderr,
)
new_long_proofs = True
else:
known_long_proofs = known_long_proofs + 1
if known_long_proofs:
print(
"Checked %d proofs in %d files, while skipping %d known long proofs."
% (len(all_proofs), len(opts.input_files), known_long_proofs)
)
else:
print(
"Checked %d proofs in %d files." % (len(all_proofs), len(opts.input_files))
)
return new_long_proofs
def rank_proofs(opts, all_proofs):
print("%12s %s" % ("Proof LOC", "Location (Claim)"))
print("=" * 80)
for fname, line, claim, length in all_proofs:
if (not opts.extract) and length <= opts.threshold:
break
print("%12d %s:%d (%s)" % (length, fname, line, claim))
def parse_args():
parser = argparse.ArgumentParser(description="Proof counting tool")
parser.add_argument(
"input_files", nargs="*", metavar="Rocq-file", help="input Rocq files (*.v)"
)
parser.add_argument(
"-t",
"--threshold",
default=40,
action="store",
type=int,
help="up to which length is a proof is considered ok",
)
parser.add_argument(
"-b",
"--bin-size",
default=None,
action="store",
type=int,
metavar="BIN-SIZE",
help="report length histogram with given bin size",
)
parser.add_argument(
"--extract",
default=False,
action="store_true",
help="simply list all identified proofs",
)
parser.add_argument(
"--annotate",
default=False,
action="store_true",
help="dump the file with proofs marked",
)
parser.add_argument(
"--create-db",
default=False,
action="store_true",
help="create a DB of known long proofs (JSON format)",
)
parser.add_argument(
"--long-proofs",
default=None,
type=argparse.FileType("r"),
metavar="JSON-FILE",
help="JSON DB of known long proofs",
)
parser.add_argument(
"--check",
default=False,
action="store_true",
help="complain and return non-zero exit code if there are new too-long proofs",
)
return parser.parse_args()
def main():
opts = parse_args()
if opts.long_proofs:
opts.long_proofs = json.load(opts.long_proofs)
else:
opts.long_proofs = {"manual_exceptions": {}, "legacy_proofs": {}}
all_proofs = []
annotate = show_line if opts.annotate else silent
for f in opts.input_files:
if opts.annotate:
banner(f)
all_proofs += process_file(f, annotate=annotate)
if opts.annotate:
print("\n")
if not opts.extract:
all_proofs.sort(key=lambda x: x[3], reverse=True)
if opts.bin_size:
show_histogram(opts, all_proofs)
elif opts.create_db:
create_db(opts, all_proofs)
elif opts.check:
sys.exit(check_proof_lengths(opts, all_proofs))
else:
rank_proofs(opts, all_proofs)
if __name__ == "__main__":
main()