File size: 10,906 Bytes
2789d27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
//! Lean 4 integer semantics for the lean2zig converter (Lean-Workbook / OProofs subset).
//! Every value is an i128. Naturals are non-negative i128; the type only decides which operator
//! (`sub`/`monus`) the converter emits. Overflow and undecided searches never fail a vector: they set a
//! flag, `skipped()` reports it, and the test skips that vector.
const std = @import("std");

/// Vectors tried per theorem, and per theorem with a loop (quantifier or finite sum) in it.
pub const tries: usize = 1500;
pub const tries_heavy: usize = 240;
/// Upper end of an unbounded natural variable's draw range.
pub const top: i128 = 1 << 24;
/// Longest finite range a quantifier or a sum may walk; longer ones skip the vector.
pub const span_cap: i128 = 4096;

threadlocal var overflowed: bool = false;
threadlocal var undecided: bool = false;

pub fn begin() void {
    overflowed = false;
    undecided = false;
}
threadlocal var skip_count: usize = 0;

pub fn skipped() bool {
    if (overflowed or undecided) {
        skip_count += 1;
        return true;
    }
    return false;
}
/// Marks the current vector as not decided (a truncated search ran out). Returns true so it can sit in a bool expression.
pub fn giveUp() bool {
    undecided = true;
    return true;
}
fn overflow() i128 {
    overflowed = true;
    return 0;
}

pub fn add(a: i128, b: i128) i128 {
    const r = @addWithOverflow(a, b);
    return if (r[1] != 0) overflow() else r[0];
}
pub fn sub(a: i128, b: i128) i128 {
    const r = @subWithOverflow(a, b);
    return if (r[1] != 0) overflow() else r[0];
}
pub fn mul(a: i128, b: i128) i128 {
    const r = @mulWithOverflow(a, b);
    return if (r[1] != 0) overflow() else r[0];
}
pub fn neg(a: i128) i128 {
    return sub(0, a);
}
/// Natural-number subtraction: truncates at 0.
pub fn monus(a: i128, b: i128) i128 {
    return if (a < b) 0 else sub(a, b);
}
/// Int.emod / Nat.mod: x % 0 = x, otherwise the remainder in [0, |b|).
pub fn mod(a: i128, b: i128) i128 {
    if (b == 0) return a;
    if (b == std.math.minInt(i128) or a == std.math.minInt(i128)) return overflow();
    return @mod(a, if (b < 0) -b else b);
}
/// Int.ediv / Nat.div: x / 0 = 0, otherwise the quotient matching `mod`.
pub fn div(a: i128, b: i128) i128 {
    if (b == 0) return 0;
    if (b == std.math.minInt(i128) or a == std.math.minInt(i128)) return overflow();
    return @divExact(a - mod(a, b), b);
}
pub fn pow(b: i128, e: i128) i128 {
    if (e < 0) return overflow();
    if (e == 0) return 1;
    if (b == 0 or b == 1) return b;
    if (b == -1) return if (@mod(e, 2) == 0) 1 else -1;
    if (e > 127) return overflow();
    var r: i128 = 1;
    var i: i128 = 0;
    while (i < e) : (i += 1) r = mul(r, b);
    return r;
}
pub fn abs(a: i128) i128 {
    return if (a < 0) neg(a) else a;
}
/// Int.toNat.
pub fn toNat(a: i128) i128 {
    return if (a < 0) 0 else a;
}
pub fn gcd(a: i128, b: i128) i128 {
    const ua = abs(a);
    const ub = abs(b);
    if (ua == 0 and ub == 0) return 0;
    if (ua <= std.math.maxInt(u64) and ub <= std.math.maxInt(u64)) return std.math.gcd(@as(u64, @intCast(ua)), @as(u64, @intCast(ub)));
    var x = ua;
    var y = ub;
    while (y != 0) {
        const t = @mod(x, y);
        x = y;
        y = t;
    }
    return x;
}
pub fn lcm(a: i128, b: i128) i128 {
    if (a == 0 or b == 0) return 0;
    return mul(div(abs(a), gcd(a, b)), abs(b));
}
pub fn choose(n: i128, k: i128) i128 {
    if (n < 0 or k < 0 or k > n) return 0;
    const m = @min(k, n - k);
    var r: i128 = 1;
    var i: i128 = 1;
    while (i <= m) : (i += 1) {
        r = div(mul(r, n - m + i), i);
        if (overflowed) return 0;
    }
    return r;
}
pub fn factorial(n: i128) i128 {
    if (n < 0) return overflow();
    if (n > 40) return overflow();
    var r: i128 = 1;
    var i: i128 = 2;
    while (i <= n) : (i += 1) r = mul(r, i);
    return r;
}
pub fn fib(n: i128) i128 {
    if (n < 0 or n > 180) return overflow();
    var a: i128 = 0;
    var b: i128 = 1;
    var i: i128 = 0;
    while (i < n) : (i += 1) {
        const t = add(a, b);
        a = b;
        b = t;
    }
    return a;
}
pub fn isqrt(n: i128) i128 {
    if (n <= 0) return 0;
    var r: i128 = @intFromFloat(@sqrt(@as(f64, @floatFromInt(n))));
    while (r * r > n) r -= 1;
    while ((r + 1) * (r + 1) <= n) r += 1;
    return r;
}
pub fn isPrime(n: i128) bool {
    if (n < 2) return false;
    if (n > 10_000_000_000) return giveUp();
    const m: u64 = @intCast(n);
    if (m < 4) return true;
    if (m % 2 == 0) return false;
    var d: u64 = 3;
    while (d * d <= m) : (d += 2) {
        if (m % d == 0) return false;
    }
    return true;
}
/// Nat.totient, by trial-division factorisation.
pub fn totient(n: i128) i128 {
    if (n <= 0) return 0;
    if (n > 10_000_000_000) return overflow();
    var m: u64 = @intCast(n);
    var r: u64 = m;
    var p: u64 = 2;
    while (p * p <= m) : (p += 1) {
        if (m % p == 0) {
            while (m % p == 0) m /= p;
            r -= r / p;
        }
    }
    if (m > 1) r -= r / m;
    return r;
}
/// a ∣ b (Nat or Int): 0 ∣ b only when b = 0.
pub fn dvd(a: i128, b: i128) bool {
    if (a == 0) return b == 0;
    return mod(b, a) == 0;
}
/// a ≡ b [ZMOD n] and a ≡ b [MOD n].
pub fn modeq(a: i128, b: i128, n: i128) bool {
    return mod(a, n) == mod(b, n);
}
/// True when lo..hi is short enough to walk; otherwise marks the vector undecided.
pub fn spanOk(lo: i128, hi: i128) bool {
    if (hi < lo) return true;
    if (hi - lo > span_cap) return !giveUp();
    return true;
}

/// Deterministic generator: edge values, values at the range ends, then small, medium and large draws.
pub const Rng = struct {
    state: u64,

    const edges = [_]i128{ 0, 1, -1, 2, -2, 3, 4, 5, 7, -3, 6, 8, 9, 10, 11, 12, 13, 16, 17, 19, 23, 31, 64, 97, 100, 101, 127, 256, 1000, 1009 };

    pub fn init(seed: u64) Rng {
        return .{ .state = seed *% 0x9E3779B97F4A7C15 +% 0x1234567 };
    }
    fn next(self: *Rng) u64 {
        self.state +%= 0x9E3779B97F4A7C15;
        var z = self.state;
        z = (z ^ (z >> 30)) *% 0xBF58476D1CE4E5B9;
        z = (z ^ (z >> 27)) *% 0x94D049BB133111EB;
        return z ^ (z >> 31);
    }
    fn window(self: *Rng, lo: i128, hi: i128, wlo: i128, whi: i128) i128 {
        var a = @max(lo, wlo);
        var b = @min(hi, whi);
        if (a > b) {
            if (hi < wlo) {
                a = @max(lo, hi - (whi - wlo));
                b = hi;
            } else {
                a = lo;
                b = @min(hi, lo + (whi - wlo));
            }
        }
        const span: u64 = @intCast(@min(b - a + 1, std.math.maxInt(u32)));
        return a + @as(i128, self.next() % span);
    }
    /// A value in lo..hi, or null when the range is empty.
    pub fn pick(self: *Rng, lo: i128, hi: i128) ?i128 {
        if (lo > hi) return null;
        switch (self.next() % 10) {
            0, 1, 2 => {
                const e = edges[self.next() % edges.len];
                if (e >= lo and e <= hi) return e;
                return self.window(lo, hi, -20, 30);
            },
            3 => {
                const d: i128 = @intCast(self.next() % 3);
                return if (self.next() & 1 == 0) @min(hi, lo + d) else @max(lo, hi - d);
            },
            4, 5, 6 => return self.window(lo, hi, -20, 30),
            7, 8 => return self.window(lo, hi, -1000, 1000),
            else => return self.window(lo, hi, -1_000_000, 1_000_000),
        }
    }
};

/// Vector source: first an exhaustive grid of small values over the free variables (so equalities with small solutions are
/// found), then edge-weighted random draws. Each loop iteration draws its variables in order with `pick`.
pub const Source = struct {
    rng: Rng,
    base: u64,
    grid_total: usize,
    total: usize,
    step: usize = 0,
    slot: usize = 0,

    /// k = number of free variables; heavy statements (loops inside) skip the grid and run fewer random vectors.
    pub fn init(seed: u64, k: usize, heavy: bool) Source {
        // Largest base whose k-th power stays within the grid budget; no grid for loop-heavy statements or many variables.
        var base: u64 = 128;
        var grid: usize = 1;
        while (base >= 3) : (base -= if (base > 24) 8 else 1) {
            grid = 1;
            for (0..k) |_| grid = std.math.mul(usize, grid, base) catch 1 << 40;
            if (grid <= 12000) break;
            grid = 1;
        }
        if (heavy or base < 3 or grid > 12000) grid = 0;
        return .{ .rng = Rng.init(seed), .base = base, .grid_total = grid, .total = grid + if (heavy) tries_heavy else tries };
    }
    /// Starts the next vector; false when the budget is spent.
    pub fn next(self: *Source) bool {
        if (self.step >= self.total) return false;
        self.step += 1;
        self.slot = 0;
        begin();
        return true;
    }
    /// The next free variable's value, within lo..hi, or null if no value of this vector fits.
    pub fn pick(self: *Source, lo: i128, hi: i128) ?i128 {
        const s = self.slot;
        self.slot += 1;
        if (self.step <= self.grid_total) {
            var idx = self.step - 1;
            for (0..s) |_| idx /= self.base;
            const v = @max(lo, -@as(i128, self.base / 2)) + @as(i128, idx % self.base);
            return if (v > hi) null else v;
        }
        return self.rng.pick(lo, hi);
    }
};

/// Collects up to 16 distinct admitted vectors, to check a theorem was exercised.
pub fn Tally(comptime n: usize) type {
    return struct {
        seen: [16][n]i128 = undefined,
        count: usize = 0,

        const Self = @This();
        pub fn init() Self {
            skip_count = 0;
            return .{};
        }
        pub fn record(self: *Self, v: [n]i128) void {
            if (self.count == 16) return;
            for (self.seen[0..self.count]) |s| {
                if (std.mem.eql(i128, &s, &v)) return;
            }
            self.seen[self.count] = v;
            self.count += 1;
        }
        /// Counts the vector unless it was skipped (overflow or undecided search); fails when the conclusion is false.
        pub fn admit(self: *Self, ok: bool, v: [n]i128) error{TestUnexpectedResult}!void {
            if (skipped()) return;
            self.record(v);
            if (!ok) return error.TestUnexpectedResult;
        }
        /// At least k distinct vectors were admitted. NoVector: none was, TooFewVectors: some, OnlySkipped: skips (overflow or
        /// an undecided search) outnumbered admissions.
        pub fn require(self: *const Self, k: usize) error{ TooFewVectors, NoVector, OnlySkipped }!void {
            if (self.count >= k) return;
            if (skip_count > 0 and skip_count >= self.count) return error.OnlySkipped;
            if (self.count == 0) return error.NoVector;
            return error.TooFewVectors;
        }
    };
}