vile / scheme / testdata / check_hashtables.py
167 lines · 155 sloc · 6.93 KB · 76646891b77a3d5c6af4a1e42b122cd61dc1654b
Raw
1"""Independent manual hashtable check: operations against dict and finite graph classes.
2
3Run: python3 scheme/testdata/check_hashtables.py /path/to/vile [report.json]
4These are manual CLI/property probes, not additional V _test.v cases.
5"""
6import itertools, json, pathlib, random, subprocess, sys
7from fractions import Fraction
8
9if len(sys.argv) not in (2, 3):
10 raise SystemExit('usage: check_hashtables.py VILE_BINARY [REPORT_JSON]')
11binary = str(pathlib.Path(sys.argv[1]).resolve())
12rng = random.Random(613)
13checks = 0
14
15def run(expressions, expected, count_operations=True):
16 global checks
17 command = [binary, '-s']
18 for expression in expressions:
19 command.extend(['-e', expression])
20 result = subprocess.run(command, capture_output=True, text=True, timeout=40)
21 assert result.returncode == 0 and not result.stderr, (result.stderr, expressions)
22 assert result.stdout.splitlines() == expected, (result.stdout.splitlines(), expected, expressions)
23 if count_operations:
24 checks += len(expected)
25
26modes = {
27 'eq': '(make-eq-hashtable)',
28 'eqv': '(make-eqv-hashtable)',
29 'collision': '(make-hashtable (lambda (x) 0) =)',
30 'structural': '(make-hashtable equal-hash equal?)',
31 'casefold': '(make-hashtable string-ci-hash string-ci=?)',
32}
33for mode, constructor in modes.items():
34 data = {}
35 commands, expected = [f'(define h {constructor})'], []
36 def key(i):
37 if mode == 'structural':
38 return f'(list (vector {i}) (list {i + 1}))'
39 if mode == 'casefold':
40 text = f'Key{i}'
41 return '"' + ''.join(c.upper() if rng.randrange(2) else c.lower() for c in text) + '"'
42 return str(i)
43 for step in range(350):
44 operation = rng.choice(['set', 'ref', 'contains', 'delete', 'update', 'copy', 'clear'])
45 i = rng.randrange(-18, 19)
46 k = key(i)
47 if operation == 'set':
48 value = rng.randrange(-10000, 10000)
49 commands.append(f'(hashtable-set! h {k} {value}) (hashtable-size h)')
50 data[i] = value
51 expected.append(str(len(data)))
52 elif operation == 'ref':
53 commands.append(f'(hashtable-ref h {k} 77777)')
54 expected.append(str(data.get(i, 77777)))
55 elif operation == 'contains':
56 commands.append(f'(hashtable-contains? h {k})')
57 expected.append('#t' if i in data else '#f')
58 elif operation == 'delete':
59 commands.append(f'(hashtable-delete! h {k}) (hashtable-size h)')
60 data.pop(i, None)
61 expected.append(str(len(data)))
62 elif operation == 'update':
63 commands.append(f'(hashtable-update! h {k} (lambda (x) (+ x 1)) 100) (hashtable-ref h {k} #f)')
64 data[i] = data.get(i, 100) + 1
65 expected.append(str(data[i]))
66 elif operation == 'copy':
67 commands.append(f'(define frozen (hashtable-copy h)) (define changed (hashtable-copy frozen #t)) (hashtable-set! changed {k} -999) (list (hashtable-size frozen) (hashtable-ref frozen {k} 77777))')
68 expected.append(f'({len(data)} {data.get(i, 77777)})')
69 else:
70 commands.append('(hashtable-clear! h 4) (hashtable-size h)')
71 data.clear()
72 expected.append('0')
73 run(commands, expected)
74
75# Independent coinductive classes of finite pair graphs. Pointer layout and
76# number of graph nodes must not enter the structural hash result.
77graphs = []
78for size in range(1, 4):
79 for labels in itertools.product([0, 1], repeat=size):
80 for tails in itertools.product(range(-1, size), repeat=size):
81 graphs.append((labels, tails))
82
83commands = []
84for labels, tails in graphs:
85 bindings = ' '.join(f'(n{i} (cons {label} (list)))' for i, label in enumerate(labels))
86 links = ' '.join(f'(set-cdr! n{i} n{tail})' for i, tail in enumerate(tails) if tail >= 0)
87 commands.append(f'(let ({bindings}) {links} (equal-hash n0))')
88command = [binary, '-s']
89for program in commands:
90 command.extend(['-e', program])
91result = subprocess.run(command, capture_output=True, text=True, timeout=40)
92assert result.returncode == 0 and not result.stderr, result.stderr
93hashes = list(map(int, result.stdout.splitlines()))
94assert len(hashes) == len(graphs)
95
96def equal(a, b):
97 pending, seen = [(0, 0)], set()
98 while pending:
99 x, y = pending.pop()
100 if (x, y) in seen:
101 continue
102 seen.add((x, y))
103 if a[0][x] != b[0][y]:
104 return False
105 ax, by = a[1][x], b[1][y]
106 if ax == -1 or by == -1:
107 if ax != by:
108 return False
109 else:
110 pending.append((ax, by))
111 return True
112
113equivalent_pairs = 0
114for i, graph in enumerate(graphs):
115 for j in range(i, len(graphs)):
116 if equal(graph, graphs[j]):
117 assert hashes[i] == hashes[j], (graph, graphs[j], hashes[i], hashes[j])
118 equivalent_pairs += 1
119# Independent exact-number hash oracle. Keep these separate from the original
120# operation count and the finite-graph property checks in the report.
121MASK = (1 <<64) -1
122OFFSET =14695981039346656037
123PRIME =1099511628211
124WORD_LIMIT =2048
125
126def hash_word(state, value):
127 for shift in range(0,64,8):
128 state = ((state ^ ((value >>shift) &255)) *PRIME) &MASK
129 return state
130
131def hash_component(state, value):
132 magnitude =abs(value)
133 words =(magnitude.bit_length() +31) //32
134 state =hash_word(hash_word(state, int(value <0)), words)
135 for index in range(min(words,WORD_LIMIT)):
136 state =hash_word(state, (magnitude >> (32 *index)) &0xffffffff)
137 if words >WORD_LIMIT:
138 state =hash_word(state,0x424947435554)
139 return state
140
141def exact_hash(value):
142 state =hash_word(OFFSET,0x4558414354)
143 state =hash_component(state,value.numerator)
144 state =hash_component(state,value.denominator)
145 return state &0x7fffffffffffffff
146
147numeric =[]
148for value in [0,1,-1,(1 <<31)-1,1 <<31,(1 <<32)-1,1 <<32,(1 <<63)-1,
149 -(1 <<63),1 <<63,-(1 <<63)-1,(1 <<64)-1,1 <<64, -(1 <<200)+17]:
150 numeric.append((Fraction(value),str(value)))
151for bits in [65,97,130,200,511,1024,4097]:
152 value =(1 <<bits) +rng.getrandbits(bits-1)
153 for signed in [value,-value]:
154 numeric.append((Fraction(signed),str(signed)))
155 denominator =rng.randrange(3,100000,2)
156 numeric.append((Fraction(signed,denominator),f'{signed}/{denominator}'))
157for shift in [WORD_LIMIT *32+128,WORD_LIMIT *32+512]:
158 numeric.append((Fraction(1 <<shift),f'(expt 2 {shift})'))
159 numeric.append((Fraction((1 <<shift) +(1 << (WORD_LIMIT *32+64))),
160 f'(+ (expt 2 {shift}) (expt 2 {WORD_LIMIT *32+64}))'))
161run([f'(equal-hash {program})' for _,program in numeric],
162 [str(exact_hash(value)) for value,_ in numeric],count_operations=False)
163report ={'operation_checks':checks,'finite_graph_hashes':len(graphs),
164 'coinductively_equal_pairs':equivalent_pairs,'numeric_hash_oracle_checks':len(numeric)}
165if len(sys.argv) == 3:
166 pathlib.Path(sys.argv[2]).write_text(json.dumps(report, indent=2) + chr(10))
167print(json.dumps(report))
168