destructive_gen_data.py 8.28 KB
Newer Older
Michael Sammler's avatar
Michael Sammler committed
1
2
3
4
5
#!/usr/bin/env python3
import sys
import re
import json
import subprocess
Michael Sammler's avatar
Michael Sammler committed
6
7
8
import shutil
import os
import random
Michael Sammler's avatar
Michael Sammler committed
9
10

annotation_re = re.compile(r"( ?)\[\[rc::([A-Za-z_]+)\s*\((.*?)\)\s*\]\]", re.DOTALL)
Michael Sammler's avatar
Michael Sammler committed
11
annotation_block_re = re.compile(r"\[\[rc::([A-Za-z_]+)\s*\]\]")
Michael Sammler's avatar
Michael Sammler committed
12
inline_re = re.compile("rc_([A-Za-z_]*)")
Michael Sammler's avatar
Michael Sammler committed
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
comment_re = re.compile("//\s*@\s*rc::([A-Za-z_]*)")

ANNOT_TYPE = {
    "manual_proof": "annot",
    "context": "annot",
    "annot_args": "spec",
    "import": "annot",
    "require": "annot",
    "inlined": "annot",
    "tagged_union": "annot",
    "union_tag": "annot",
    "unfold_int": "annot",
    "refined_by": "annot",
    "ptr_type": "annot",
    "field": "annot",
    "size": "annot",
    "global": "annot",
    "constraints": "annot",
    "parameters": "spec",
    "args": "spec",
    "requires": "spec",
    "ensures": "spec",
    "exists": "spec",
    "returns": "spec",
    "loopexists": "annot",
    "inv_vars": "annot",
    "block": "annot",
Michael Sammler's avatar
Michael Sammler committed
40
41
    "tactics": "pure",
    "lemmas": "pure",
Michael Sammler's avatar
Michael Sammler committed
42
43
44
45
46
47
48
    "unfold": "rule",
    "unfold_once": "rule",
    "unlock": "rule",
    "share": "rule",
    "to_uninit": "rule",
    "uninit_strengthen_align": "rule",
}
Michael Sammler's avatar
Michael Sammler committed
49
50

def print_stats(annots, loc):
Michael Sammler's avatar
Michael Sammler committed
51
52
53
    # print(json.dumps(annots, indent=2))
    types = {}
    total = 0
Michael Sammler's avatar
Michael Sammler committed
54
    for k,v in annots.items():
Michael Sammler's avatar
Michael Sammler committed
55
56
57
58
59
60
        if k not in ANNOT_TYPE:
            print('unknown annotation: ' + k)
            exit(1)
        t = ANNOT_TYPE[k]
        types[t] = types.get(t, 0)
        types[t] += v
Michael Sammler's avatar
Michael Sammler committed
61
        if k != "import" and k != "inlined" and k != "require":
Michael Sammler's avatar
Michael Sammler committed
62
63
            total += v
    types["LoC"] = loc - total
Michael Sammler's avatar
Michael Sammler committed
64
65
    types["annot"] = types.get("annot", 0) + types.get("rule", 0)
    types.pop('rule', None)
Michael Sammler's avatar
Michael Sammler committed
66
    print(json.dumps(types, indent=2))
Michael Sammler's avatar
Michael Sammler committed
67
    return types
Michael Sammler's avatar
Michael Sammler committed
68

Michael Sammler's avatar
Michael Sammler committed
69
70
71
72
def parse_file(f):
    per_file = {}
    for match in annotation_re.finditer(f):
        num_lines = len(match.group(3).strip().split('\n'))
Michael Sammler's avatar
Michael Sammler committed
73
74
75
76
77
78
79
80
81
82
83
84
        name = match.group(2)
        if name == "exists" and match.group(1) != "":
            name = "loopexists"

        per_file[name] = per_file.get(name, 0)
        per_file[name] += num_lines

    for match in annotation_block_re.finditer(f):
        num_lines = 1

        per_file[match.group(1)] = per_file.get(match.group(1), 0)
        per_file[match.group(1)] += num_lines
Michael Sammler's avatar
Michael Sammler committed
85
86
87
88

    for match in inline_re.finditer(f):
        num_lines = 1

Michael Sammler's avatar
Michael Sammler committed
89
90
91
92
93
94
95
96
        per_file[match.group(1)] = per_file.get(match.group(1), 0)
        per_file[match.group(1)] += num_lines

    for match in comment_re.finditer(f):
        num_lines = 1

        per_file[match.group(1)] = per_file.get(match.group(1), 0)
        per_file[match.group(1)] += num_lines
Michael Sammler's avatar
Michael Sammler committed
97
98
99

    return per_file

Michael Sammler's avatar
Michael Sammler committed
100
101
102
def compute_annots(FILES):
    total = {}
    o = subprocess.check_output(["tokei", "--output=json", "--files"] + FILES)
103
104
    print(o)
    inner = json.loads(o)
Michael Sammler's avatar
Michael Sammler committed
105
    if "CHeader" not in inner:
106
        inner["CHeader"] = { "code": 0, "reports": []}
Michael Sammler's avatar
Michael Sammler committed
107
108
    lines_total = inner["C"]["code"] + inner["CHeader"]["code"]
    lines_per_file = {}
109
110
    for s in inner["C"]["reports"] + inner["CHeader"]["reports"]:
        lines_per_file[s["name"]] = s["stats"]["code"]
Michael Sammler's avatar
Michael Sammler committed
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

    # count annotations
    for f in FILES:
        if f.endswith(".v"):
            continue
        print(f)
        with open(f, 'r') as content_file:
            per_file = parse_file(content_file.read())

        print_stats(per_file, lines_per_file[f])

        for k,v in per_file.items():
            total[k] = total.get(k, 0)
            total[k] += v


    total = print_stats(total, lines_total)
    if "Coq" in inner:
        total["pure"] = total.get("pure", 0) + inner["Coq"]["code"]
    # count lemmas and quantifier instantiations
    total["exists"] = 0
    total["sideconds"] = 0
    total["unsolvedsideconds"] = 0
    total["rules"] = 0
    results = []

    for f in FILES:
        if not f.endswith(".c"):
            continue
        proofsdir = os.path.join(os.path.dirname(f), "proofs", os.path.basename(f)[:-2])
        print(proofsdir)
        tmpname = f + ".statstmp"
        shutil.copyfile(f, tmpname)
        with open(f, "a") as fd:
            fd.write("//@rc::import enable_debug from refinedc.typing.automation\n")
            fd.write(f"//@rc::inlined Definition marker_{random.randint(0, 1000)} := tt.\n")

        subprocess.check_output(["dune", "exec", "--", "refinedc", "check", "--no-build", f])

        o = subprocess.check_output(["dune", "build", "--display", "short"],
                                    cwd=proofsdir, stderr=subprocess.STDOUT).split(b"\n")
        current = None
Michael Sammler's avatar
Michael Sammler committed
153

Michael Sammler's avatar
Michael Sammler committed
154
155
156
157
158
        for line in o:
            if b"coqc " in line:
                if current is not None:
                    results.append(current)
                    current = None
Michael Sammler's avatar
Michael Sammler committed
159

Michael Sammler's avatar
Michael Sammler committed
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
                name = line.decode("utf8")
                if proofsdir in name:
                    print(name)
                    current = { "name" : name,
                                "exists": 0, "sideconds": 0, "unsolvedsideconds": 0, "rules": 0 }
            if current is None:
                continue
            if line == b"EVAR":
                current["exists"] += 1
                total["exists"] += 1
            if line == b"SIDECOND":
                current["sideconds"] += 1
                total["sideconds"] += 1
            if line == b"UNSOLVEDSIDECOND":
                current["unsolvedsideconds"] += 1
                total["unsolvedsideconds"] += 1
            if line == b"EXTENSIBLE":
                current["rules"] += 1
                total["rules"] += 1
        if current is not None:
            results.append(current)
            current = None
Michael Sammler's avatar
Michael Sammler committed
182

Michael Sammler's avatar
Michael Sammler committed
183
184
185
        # print((json.dumps(results, indent=2)))
        # print((json.dumps(total, indent=2)))
        shutil.move(tmpname, f)
Michael Sammler's avatar
Michael Sammler committed
186

Michael Sammler's avatar
Michael Sammler committed
187
188
189
190
    print("total:")
    # print_stats(total, lines_total)
    print(json.dumps(total, indent=2))
    return total
Michael Sammler's avatar
Michael Sammler committed
191

Michael Sammler's avatar
Michael Sammler committed
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
stats = [ {
    "name": "#1",
    "progs": [ {
        "name": "Singly linked list",
        "abs": "wand, alloc",
        "stats": compute_annots(["tutorial/t03_list.c"])
    }, {
        "name": "Queue",
        "abs": "list segments, alloc",
        "stats": compute_annots(["examples/queue.c"])
    }, {
        "name": "Binary search",
        "abs": "arrays, func. ptr.",
        "stats": compute_annots(["examples/binary_search.c",
                                 "examples/proofs/binary_search/binary_search_extra.v"])
    } ]
}, {
    "name": "#2",
    "progs": [ {
        "name": "Thread-safe allocator",
        "abs": "wand, padded, spinlock",
        "stats": compute_annots(["tutorial/t04_alloc.c", "tutorial/alloc.h", "tutorial/alloc_internal.h"])
    }, {
        "name": "Page allocator",
        "abs": "padded",
        "stats": compute_annots(["examples/malloc1.c"])
    } ]
}, {
    "name": "#3",
    "progs": [ {
        "name": "Binary search tree (layered)",
        "abs": "wand, alloc",
        "stats": compute_annots(["tutorial/t08_tree.c", "tutorial/proofs/t08_tree/t08_tree_extra.v"])
    }, {
        "name": "Binary search tree (direct)",
        "abs": "wand, alloc",
        "stats": compute_annots(["tutorial/t11_tree_set.c"])
    } ]
}, {
    "name": "#4",
    "progs": [ {
        "name": "Linear probing hashmap",
        "abs": "unions, arrays, alloc",
        "stats": compute_annots(["examples/mutable_map.c", "examples/proofs/mutable_map/mutable_map_extra.v"])
    } ]
}, {
    "name": "#5",
    "progs": [ {
        "name": "Hafnium's mpool allocator",
        "abs": "wand, padded, spinlock",
        "stats": compute_annots(["examples/mpool.c"])
    } ]
}, {
    "name": "#6",
    "progs": [ {
        "name": "Spinlock",
        "abs": "atomic Boolean",
        "stats": compute_annots(["examples/spinlock.c", "examples/include/spinlock.h"])
    }, {
        "name": "One-time barrier",
        "abs": "atomic Boolean",
        "stats": compute_annots(["examples/latch.c", "examples/include/latch.h"])
    } ]
} ]
Michael Sammler's avatar
Michael Sammler committed
256

Michael Sammler's avatar
Michael Sammler committed
257
258
259
260
261
262
263
264
# Add 6 to spinlock for the 6 non-trivial lines in examples/proofs/spinlock/spinlock_proof.v
#   Typeclasses Transparent spinlock spinlocked_ex spinlock_token spinlocked_ex_token.
#   iApply fupd_typed_stmt.
#   iMod (own_alloc (● GSet ∅)) as (γ) "Hown"; [ by apply auth_auth_valid |].
#   iAssert (spinlock_token γ []) with "[Hown]" as "?"; [ by iExists _; iFrame |].
#   iModIntro.
#   liInst Hevar γ.
stats[5]["progs"][0]["stats"]["annot"] += 6
Michael Sammler's avatar
Michael Sammler committed
265

Michael Sammler's avatar
Michael Sammler committed
266
print(json.dumps(stats, indent=2))
267
with open('data.json', 'w') as f:
Michael Sammler's avatar
Michael Sammler committed
268
    json.dump(stats, f, indent=2)