gdp-wired 0.31.1 → 0.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/cli.d.ts +66 -0
- package/dist/core/cli.js +582 -0
- package/dist/core/dsl.d.ts +4 -2
- package/dist/core/dsl.js +22 -12
- package/dist/core/effect.d.ts +6 -4
- package/dist/core/effect.js +48 -10
- package/dist/core/ex/harness.exs +177 -0
- package/dist/core/ex/json.exs +46 -0
- package/dist/core/ex/reader.exs +462 -0
- package/dist/core/exists.d.ts +3 -0
- package/dist/core/exists.js +3 -1
- package/dist/core/extract-c.d.ts +35 -0
- package/dist/core/extract-c.js +424 -0
- package/dist/core/extract-check.js +27 -6
- package/dist/core/extract-ex.d.ts +16 -0
- package/dist/core/extract-ex.js +33 -0
- package/dist/core/extract-go-check.d.ts +28 -0
- package/dist/core/extract-go-check.js +639 -0
- package/dist/core/extract-go.d.ts +231 -0
- package/dist/core/extract-go.js +1166 -0
- package/dist/core/extract-jvm.d.ts +23 -0
- package/dist/core/extract-jvm.js +220 -0
- package/dist/core/extract-print.js +17 -7
- package/dist/core/extract-py.d.ts +15 -0
- package/dist/core/extract-py.js +31 -0
- package/dist/core/extract-rb.d.ts +17 -0
- package/dist/core/extract-rb.js +31 -0
- package/dist/core/extract-read.d.ts +20 -0
- package/dist/core/extract-read.js +46 -6
- package/dist/core/extract-rs.d.ts +12 -0
- package/dist/core/extract-rs.js +306 -0
- package/dist/core/extract-shapes.d.ts +2 -0
- package/dist/core/extract-shapes.js +6 -5
- package/dist/core/extract-step.d.ts +806 -0
- package/dist/core/extract-step.js +4141 -0
- package/dist/core/extract-swift.d.ts +27 -0
- package/dist/core/extract-swift.js +484 -0
- package/dist/core/extract-xstate.d.ts +10 -3
- package/dist/core/extract-xstate.js +50 -4
- package/dist/core/extract.d.ts +22 -3
- package/dist/core/extract.js +107 -18
- package/dist/core/go/go.mod +3 -0
- package/dist/core/go/reader.go +901 -0
- package/dist/core/infer.js +1770 -52
- package/dist/core/jvm/Harness.java +361 -0
- package/dist/core/jvm/JavaReader.java +825 -0
- package/dist/core/jvm/Jvm.java +332 -0
- package/dist/core/jvm/KtReader.java +960 -0
- package/dist/core/jvm/Rt.java +10 -0
- package/dist/core/laws.d.ts +66 -0
- package/dist/core/laws.js +522 -0
- package/dist/core/py/harness.py +328 -0
- package/dist/core/py/reader.py +447 -0
- package/dist/core/rb/harness.rb +233 -0
- package/dist/core/rb/reader.rb +375 -0
- package/dist/core/rs/Cargo.lock +108 -0
- package/dist/core/rs/Cargo.toml +14 -0
- package/dist/core/rs/src/main.rs +681 -0
- package/dist/core/swift/Harness.swift +124 -0
- package/dist/core/swift/Main.swift +34 -0
- package/dist/core/swift/Package.swift +13 -0
- package/dist/core/swift/Sources/gdp-swiftreader/main.swift +1341 -0
- package/dist/kernel/epr.d.ts +35 -0
- package/dist/kernel/epr.js +1676 -0
- package/dist/kernel/prove.d.ts +44 -0
- package/dist/kernel/prove.js +657 -50
- package/dist/lean-kernel/emit.d.ts +1 -0
- package/dist/lean-kernel/emit.js +21 -4
- package/package.json +53 -2
|
@@ -0,0 +1,4141 @@
|
|
|
1
|
+
// The extractor's shared step IR and its executor: one structure for every language read through a native reader.
|
|
2
|
+
// A reader (core/py/reader.py: Python's own `ast`) lowers a module into the IR below, as JSON; this file executes the
|
|
3
|
+
// steps symbolically into the Model core/extract-read.ts defines (the TypeScript and Go front ends' own), and
|
|
4
|
+
// core/extract.ts's fromModel prints, builds and checks it. The check is core/extract-check.ts's `drive`: the code's
|
|
5
|
+
// side is a harness in the code's own language (core/py/harness.py) spoken to in JSON lines, which makes the object,
|
|
6
|
+
// sets it to a state, calls it with the rule's requests and prints every state. Nothing here is trusted: the rule is
|
|
7
|
+
// adopted only where the run of both agrees, and what the subset doesn't read is refused where a step reaches it.
|
|
8
|
+
//
|
|
9
|
+
// Where a language's semantics differ, the IR says so with explicit operations (the reader chooses them): an integer
|
|
10
|
+
// type's width and what it does past its range (`int`: none for an unbounded one, Python's; wrap, trap or ub for
|
|
11
|
+
// fixed ones, a later reader's), division's rounding (floor for Python's // and %, trunc for C's, Go's and Rust's),
|
|
12
|
+
// truthiness (`truthy`), a missing value (`none`, `opt`), a failure (`fail`: an exception, a panic, an error value,
|
|
13
|
+
// each the step's refusal or, with failures: 'kept', its result).
|
|
14
|
+
//
|
|
15
|
+
// The code's boundary, inferred unless `strict` (research/langs/DESIGN.md, "The boundary inferred"), each statement
|
|
16
|
+
// printed in the notes and enforced by the check; what the caller states wins:
|
|
17
|
+
// answers: a call of other code whose result is an input of the request (the check stubs it with that input).
|
|
18
|
+
// Inferred where its value is read, over its declared result type;
|
|
19
|
+
// skip: a call left out (logging, an alert, a context manager): its value is kept only where nothing the rule
|
|
20
|
+
// keeps reads it, and the check runs it as it is. Inferred where nothing reads it;
|
|
21
|
+
// stores: an object of other code held as a key-value store (a cache client): its get and set methods read and
|
|
22
|
+
// write a map of the state, one per key template; its expiry, eviction and replication are left out, and the
|
|
23
|
+
// check gives the code a store that keeps what is set. Inferred for an injected dependency called by a key.
|
|
24
|
+
// Other code given a reference to the rule's state is refused unless stated; the module's own functions the subset
|
|
25
|
+
// can't read, writing none of the state, are taken as other code; `gdp: skip | answer [type] | strict` comments say
|
|
26
|
+
// it in the code.
|
|
27
|
+
import * as I from "./extract-ir.js";
|
|
28
|
+
import { Refusal, mergeOps, mergeWrites } from "./extract-read.js";
|
|
29
|
+
import { fromModel } from "./extract.js";
|
|
30
|
+
import { nonneg } from "./extract-print.js";
|
|
31
|
+
import { Outside, constantsOf, draw, drive } from "./extract-check.js";
|
|
32
|
+
const where = (x) => x.p || '?';
|
|
33
|
+
const refuse = (x, what) => { throw new Refusal(typeof x === 'string' ? x : where(x), what); };
|
|
34
|
+
const RESERVED = new Set(['rule', 'nat', 'int', 'bool', 'when', 'min', 'max', 'all', 'any', 'not', 'yes', 'no', 'lit', 'str', 'record', 'oneOf', 'intern', 'Int', 'forall']);
|
|
35
|
+
const keyV = (v) => JSON.stringify(v, (_, x) => (x instanceof Map ? [...x.entries()] : x));
|
|
36
|
+
const LANG = { go: 'Go', rust: 'Rust', python: 'Python', c: 'C', cpp: 'C++', ruby: 'Ruby', elixir: 'Elixir', java: 'Java', kotlin: 'Kotlin' };
|
|
37
|
+
const tyName = (ty) => (ty ? (ty.bits ? `${ty.signed ? 'i' : 'u'}${ty.bits}` : ty.signed ? 'an Instant' : 'a Duration') : 'the number');
|
|
38
|
+
const constOf = (v) => (v.t === 'num' && v.e.op === 'const' ? v.e.v : undefined);
|
|
39
|
+
// The sorts a type string names (an answer's): int, float, bool, str, a choice of quoted strings, each `| None`.
|
|
40
|
+
function sortOfText(s, at) {
|
|
41
|
+
const parts = s.split('|').map(x => x.trim()).filter(Boolean), none = parts.includes('None'), rest = parts.filter(x => x !== 'None');
|
|
42
|
+
const one = () => {
|
|
43
|
+
if (rest.length && rest.every(x => /^['"].*['"]$/.test(x)))
|
|
44
|
+
return { k: 'choice', values: rest.map(x => x.slice(1, -1)) };
|
|
45
|
+
if (rest.length !== 1)
|
|
46
|
+
return refuse(at, `the answer type ${JSON.stringify(s)} (int, float, bool, str or quoted strings, each with | None)`);
|
|
47
|
+
const k = rest[0];
|
|
48
|
+
if (k === 'int' || k === 'float' || k === 'bool' || k === 'str')
|
|
49
|
+
return { k };
|
|
50
|
+
// (a fixed width, a compiled language's: u32, i64, usize, uint8, int32)
|
|
51
|
+
const w = /^(u|i|uint|int)(8|16|32|64|128|size)$/.exec(k);
|
|
52
|
+
if (w)
|
|
53
|
+
return { k: 'int', bits: w[2] === 'size' ? 64 : Number(w[2]), signed: !w[1].startsWith('u') };
|
|
54
|
+
return refuse(at, `the answer type ${JSON.stringify(s)} (int, float, bool, str or quoted strings, each with | None)`);
|
|
55
|
+
};
|
|
56
|
+
const t = one();
|
|
57
|
+
return { t: none ? { k: 'opt', of: t } : t };
|
|
58
|
+
}
|
|
59
|
+
const TAG_DECO = /(?:^|\.)gdp[._]?(skip|answer|strict)$/i;
|
|
60
|
+
// A type an answer takes: a scalar, or one with None.
|
|
61
|
+
const answerable = (t) => { const i = t.k === 'opt' ? t.of : t; return i.k === 'int' || i.k === 'float' || i.k === 'bool' || i.k === 'str' || i.k === 'choice'; };
|
|
62
|
+
const typeText = (t) => (t.k === 'opt' ? `${typeText(t.of)} | None` : t.k === 'choice' ? t.values.map(v => JSON.stringify(v)).join(' | ') : t.k);
|
|
63
|
+
// A store's method by its name: one that reads, writes or deletes a key (async_, _cache and camel case aside).
|
|
64
|
+
const KEYED = Object.fromEntries([
|
|
65
|
+
...['get', 'getcache', 'find', 'findbyid', 'fetch', 'load', 'lookup', 'read'].map(n => [n, 'get']),
|
|
66
|
+
...['set', 'setcache', 'put', 'save', 'store', 'write', 'upsert'].map(n => [n, 'set']),
|
|
67
|
+
...['delete', 'deletecache', 'remove', 'deletebyid', 'del', 'evict', 'invalidate'].map(n => [n, 'delete'])
|
|
68
|
+
]);
|
|
69
|
+
const keyShape = (m) => KEYED[m.replace(/^async_?|_?async$/gi, '').replace(/[_-]/g, '').toLowerCase()];
|
|
70
|
+
// --- the executor ---------------------------------------------------------------------------------------------------
|
|
71
|
+
export class Stepper {
|
|
72
|
+
mod;
|
|
73
|
+
opts;
|
|
74
|
+
inf;
|
|
75
|
+
vars = new Map();
|
|
76
|
+
inputs = [];
|
|
77
|
+
params = [];
|
|
78
|
+
notes = new Set();
|
|
79
|
+
refusals = [];
|
|
80
|
+
fails = [];
|
|
81
|
+
failPaths = [];
|
|
82
|
+
maps = [];
|
|
83
|
+
answers = new Map();
|
|
84
|
+
arms = new Set();
|
|
85
|
+
hints = new WeakMap();
|
|
86
|
+
lazy = new Map();
|
|
87
|
+
initHeap = new Map();
|
|
88
|
+
storeMaps = new Map();
|
|
89
|
+
frames = [];
|
|
90
|
+
fieldNames = new Set();
|
|
91
|
+
frozen = new Set();
|
|
92
|
+
// Each fixed-width variable's type (a number read from it overflows as the type does), and its range.
|
|
93
|
+
ints = new Map();
|
|
94
|
+
paramsOut = [];
|
|
95
|
+
now;
|
|
96
|
+
madeAt;
|
|
97
|
+
method = '';
|
|
98
|
+
fresh = 0;
|
|
99
|
+
init = false;
|
|
100
|
+
// (inf: the boundary inferred so far, where the reading infers one; none: only what the caller states)
|
|
101
|
+
constructor(mod, opts, inf) {
|
|
102
|
+
this.mod = mod;
|
|
103
|
+
this.opts = opts;
|
|
104
|
+
this.inf = inf;
|
|
105
|
+
}
|
|
106
|
+
rec(name, at) { return this.mod.recs[name] ?? refuse(at, `${name}: a type the reader didn't read`); }
|
|
107
|
+
newVar(name, sort, role, note) {
|
|
108
|
+
let n = name.replace(/^[_@]+/, '').replace(/\?/g, '_p').replace(/!/g, '').replace(/[^\w$]/g, '_') || 'x';
|
|
109
|
+
if (/^\d/.test(n))
|
|
110
|
+
n = `_${n}`;
|
|
111
|
+
// (a constructor's argument named as a field it sets: the field keeps the name, the argument is the initial one)
|
|
112
|
+
if (role === 'param' && this.fieldNames.has(n))
|
|
113
|
+
n = `${n}0`;
|
|
114
|
+
while (this.vars.has(n) || RESERVED.has(n))
|
|
115
|
+
n = `${n}_`;
|
|
116
|
+
const v = { name: n, sort, role, ...(note ? { note } : {}) };
|
|
117
|
+
this.vars.set(n, v);
|
|
118
|
+
if (role === 'input')
|
|
119
|
+
this.inputs.push(v);
|
|
120
|
+
if (role === 'param')
|
|
121
|
+
this.params.push(v);
|
|
122
|
+
return v;
|
|
123
|
+
}
|
|
124
|
+
valueOf(v) {
|
|
125
|
+
const ty = this.ints.get(v.name);
|
|
126
|
+
return v.sort.k === 'num' ? { t: 'num', e: I.nvar(v.name), ...(ty ? { ty } : {}) } : v.sort.k === 'bool' ? { t: 'bool', e: I.bvar(v.name) } : v.sort.k === 'choice' ? { t: 'choice', e: { op: 'var', name: v.name, values: v.sort.values } } : { t: 'str', e: { op: 'svar', name: v.name } };
|
|
127
|
+
}
|
|
128
|
+
// A scalar sort, or why the type isn't one.
|
|
129
|
+
scalar(t) {
|
|
130
|
+
return t.k === 'int' || t.k === 'float' ? { k: 'num' } : t.k === 'bool' ? { k: 'bool' } : t.k === 'str' ? { k: 'str' } : t.k === 'choice' ? { k: 'choice', values: t.values } : undefined;
|
|
131
|
+
}
|
|
132
|
+
why(t) {
|
|
133
|
+
if (t.k === 'opaque')
|
|
134
|
+
return t.why;
|
|
135
|
+
if (t.k === 'any')
|
|
136
|
+
return 'a value of no type the code states';
|
|
137
|
+
if (t.k === 'list')
|
|
138
|
+
return 'a list (lists are outside the Python subset)';
|
|
139
|
+
if (t.k === 'map')
|
|
140
|
+
return 'a dict';
|
|
141
|
+
return t.k;
|
|
142
|
+
}
|
|
143
|
+
// An input of a type: its variables, the value, and how the harness makes it.
|
|
144
|
+
input(name, t, at, p, role = 'input') {
|
|
145
|
+
const s = this.scalar(t);
|
|
146
|
+
if (s) {
|
|
147
|
+
const v = this.newVar(name, s, role);
|
|
148
|
+
this.typed(v, t, role);
|
|
149
|
+
return [this.valueOf(v), { k: 'in', name: v.name, z: zeroRaw(s), ...(t.k === 'float' ? { float: true } : {}), ...(t.k === 'choice' && t.sym ? { sym: true } : {}) }];
|
|
150
|
+
}
|
|
151
|
+
if (t.k === 'opt') {
|
|
152
|
+
if (t.of.k === 'rec') {
|
|
153
|
+
const none = this.newVar(`${name}_none`, { k: 'bool' }, role, `whether ${name} is None`);
|
|
154
|
+
const [v, a] = this.input(name, t.of, at, p, role);
|
|
155
|
+
return [{ t: 'opt', has: I.not(I.bvar(none.name)), v }, { k: 'opt', none: none.name, v: a }];
|
|
156
|
+
}
|
|
157
|
+
const inner = this.scalar(t.of);
|
|
158
|
+
if (!inner)
|
|
159
|
+
return refuse(at, `${name}: an optional ${this.why(t.of)}`);
|
|
160
|
+
const v = this.newVar(name, inner, role, `0 where ${name} is None`), none = this.newVar(`${name}_none`, { k: 'bool' }, role, `whether ${name} is None`);
|
|
161
|
+
this.typed(v, t.of, role);
|
|
162
|
+
return [{ t: 'opt', has: I.not(I.bvar(none.name)), v: this.valueOf(v) }, { k: 'opt', none: none.name, v: { k: 'in', name: v.name, z: zeroRaw(inner), ...(t.of.k === 'float' ? { float: true } : {}) } }];
|
|
163
|
+
}
|
|
164
|
+
if (t.k === 'none')
|
|
165
|
+
return [{ t: 'none' }, { k: 'dflt' }];
|
|
166
|
+
if (t.k === 'rec' && role === 'input') {
|
|
167
|
+
// An object the caller gives: its fields read are inputs, each made where it is first read.
|
|
168
|
+
const id = `in:${name}:${this.fresh++}`, args = [];
|
|
169
|
+
p.heap.set(id, { k: 'rec', ty: t.name, f: new Map(), origin: 'input', lazy: name });
|
|
170
|
+
this.lazy.set(id, { prefix: name, ty: t.name, args, vals: new Map() });
|
|
171
|
+
return [{ t: 'ref', id }, { k: 'rec', cls: t.name, f: args }];
|
|
172
|
+
}
|
|
173
|
+
// A value of another type: kept only where nothing the rule keeps reads it (the harness gives an inert one).
|
|
174
|
+
return [{ t: 'opaque', why: `${name}: ${this.why(t)}` }, { k: 'inert' }];
|
|
175
|
+
}
|
|
176
|
+
// A fixed-width integer variable: its type, and (for a request) a value outside it refused: the claim is for the
|
|
177
|
+
// type's values.
|
|
178
|
+
intTy(t) { return t.k === 'int' && t.bits !== undefined ? { bits: t.bits, signed: t.signed ?? true } : undefined; }
|
|
179
|
+
typed(v, t, role, sel = this.sel) {
|
|
180
|
+
const ty = 'k' in t ? this.intTy(t) : t;
|
|
181
|
+
if (!ty)
|
|
182
|
+
return;
|
|
183
|
+
this.ints.set(v.name, ty);
|
|
184
|
+
const [lo, hi] = rangeOf(ty);
|
|
185
|
+
if (role === 'state')
|
|
186
|
+
return;
|
|
187
|
+
const x = I.nvar(v.name);
|
|
188
|
+
// (a constructor's argument outside its type: no object is made with one, the rule's precondition says so)
|
|
189
|
+
if (role === 'param') {
|
|
190
|
+
const out = I.or(...(Number.isFinite(lo) ? [I.cmp('<', x, I.num(lo))] : []), ...(Number.isFinite(hi) ? [I.cmp('<', I.num(hi), x)] : []));
|
|
191
|
+
if (!(out.op === 'const' && !out.v))
|
|
192
|
+
this.paramsOut.push(out);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (Number.isFinite(hi))
|
|
196
|
+
this.refusals.push(I.and(sel, I.cmp('<', I.num(hi), x)));
|
|
197
|
+
if (Number.isFinite(lo) && lo < 0)
|
|
198
|
+
this.refusals.push(I.and(sel, I.cmp('<', x, I.num(lo))));
|
|
199
|
+
else if (!ty.signed)
|
|
200
|
+
this.refusals.push(I.and(sel, I.cmp('<', x, I.num(0))));
|
|
201
|
+
}
|
|
202
|
+
sel = I.T;
|
|
203
|
+
// The clock: one input a step.
|
|
204
|
+
clock(at, p) {
|
|
205
|
+
if (p.called.includes('$now'))
|
|
206
|
+
return refuse(at, 'the clock read twice in one step (the subset reads it once a step)');
|
|
207
|
+
// (in the constructor, the time the object is made: a param)
|
|
208
|
+
if (this.init) {
|
|
209
|
+
this.madeAt ??= this.newVar('made_at', { k: 'num' }, 'param', 'Date.now() (here time.time()): the time the object is made');
|
|
210
|
+
return [{ t: 'num', e: I.nvar(this.madeAt.name) }, { ...p, called: [...p.called, '$now'] }];
|
|
211
|
+
}
|
|
212
|
+
this.now ??= this.newVar('now', { k: 'num' }, 'input', 'Date.now() (here the clock, time.time()): the time of the request, an input');
|
|
213
|
+
return [{ t: 'num', e: I.nvar(this.now.name) }, { ...p, called: [...p.called, '$now'] }];
|
|
214
|
+
}
|
|
215
|
+
// --- paths ----------------------------------------------------------------------------------------------------------
|
|
216
|
+
cond(p) { return I.and(...p.pc); }
|
|
217
|
+
// (a negated disjunction as its negated parts, so a later test of one of them is decided)
|
|
218
|
+
assume(p, c) { if (this.mod.split === false)
|
|
219
|
+
return c.op === 'const' && c.v ? p : { ...p, pc: [...p.pc, c] }; const cs = c.op === 'not' && c.x.op === 'or' ? c.x.xs.map(I.not) : c.op === 'and' ? c.xs : [c]; const kept = cs.filter(x => !(x.op === 'const' && x.v)); return kept.length ? { ...p, pc: [...p.pc, ...kept] } : p; }
|
|
220
|
+
// A failure of the code where c holds on this path (an exception raised): the step's refusal, or its result.
|
|
221
|
+
fail(p, c, at, what) {
|
|
222
|
+
const w = I.and(this.cond(p), c);
|
|
223
|
+
if (w.op === 'const' && !w.v)
|
|
224
|
+
return;
|
|
225
|
+
if (this.init) {
|
|
226
|
+
this.fails.push(w);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
// (a crash, Swift's trap: the process ends, so nothing sees what the step wrote before it; the check's harness keeps
|
|
230
|
+
// the state as it was)
|
|
231
|
+
const crash = !!at.crash;
|
|
232
|
+
// Failures kept with what the step wrote before them (the caller sees both): the path goes on to the step's end.
|
|
233
|
+
if (this.opts.failures === 'kept' && this.opts.onError !== 'discard') {
|
|
234
|
+
if (crash && this.changed(p))
|
|
235
|
+
refuse(at, `${what} after the state is written: a crash, after which the state is as it was (onError: 'discard' says so of every failure)`);
|
|
236
|
+
this.failPaths.push(this.assume(p, c));
|
|
237
|
+
this.fails.push(w);
|
|
238
|
+
this.notes.add(`${this.method}: ${what} (${at.p}) is the step's failure, kept as its result (with what the step wrote before it)`);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
if (!crash)
|
|
242
|
+
this.unwritten(p, at, what);
|
|
243
|
+
this.fails.push(w);
|
|
244
|
+
this.notes.add(`${this.method}: ${what} (${at.p}) is ${this.opts.failures === 'kept' ? 'the step\'s failure, kept as its result' : 'the step\'s refusal'}`);
|
|
245
|
+
}
|
|
246
|
+
// A failure after the step wrote the state: refused, but where the caller drops what a failed call wrote.
|
|
247
|
+
unwritten(p, at, what) { if (this.opts.onError !== 'discard' && this.changed(p))
|
|
248
|
+
refuse(at, `${what} after the state is written (the caller would see the object changed and the call failed; with onError: 'discard' the caller is taken to drop what a failed call wrote)`); }
|
|
249
|
+
changed(p) {
|
|
250
|
+
for (const [id, o] of p.heap) {
|
|
251
|
+
const i = this.initHeap.get(id);
|
|
252
|
+
if (!i || ('origin' in o && o.origin !== 'state'))
|
|
253
|
+
continue;
|
|
254
|
+
if (o.k === 'map' ? !!o.w || (!!o.nil && I.keyOf(o.nil) !== I.keyOf(i.nil)) : o.k === 'list' ? o.ops.length > 0 : keyV(o) !== keyV(i))
|
|
255
|
+
return true;
|
|
256
|
+
}
|
|
257
|
+
return false;
|
|
258
|
+
}
|
|
259
|
+
join(ps, at) {
|
|
260
|
+
if (!ps.length)
|
|
261
|
+
return undefined;
|
|
262
|
+
let acc = ps.at(-1);
|
|
263
|
+
for (let i = ps.length - 2; i >= 0; i--)
|
|
264
|
+
acc = this.merge(ps[i], acc, at);
|
|
265
|
+
return acc;
|
|
266
|
+
}
|
|
267
|
+
merge(a, b, at) {
|
|
268
|
+
let k = 0;
|
|
269
|
+
while (k < a.pc.length && k < b.pc.length && I.same(a.pc[k], b.pc[k]))
|
|
270
|
+
k++;
|
|
271
|
+
const c = I.and(...a.pc.slice(k)), pc = a.pc.slice(0, k);
|
|
272
|
+
if (c.op === 'const')
|
|
273
|
+
return c.v ? { ...a, pc } : { ...b, pc };
|
|
274
|
+
if (a.locks.join() !== b.locks.join())
|
|
275
|
+
refuse(at, 'a mutex locked on one path and not on another');
|
|
276
|
+
const locals = new Map();
|
|
277
|
+
for (const [n, x] of a.locals) {
|
|
278
|
+
const y = b.locals.get(n);
|
|
279
|
+
if (y) {
|
|
280
|
+
try {
|
|
281
|
+
locals.set(n, this.ite(c, x, y, at));
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
if (!(e instanceof Refusal) || firm(x) || firm(y))
|
|
285
|
+
throw e;
|
|
286
|
+
locals.set(n, { t: 'opaque', why: e.what });
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const heap = new Map();
|
|
291
|
+
for (const [id, x] of a.heap) {
|
|
292
|
+
const y = b.heap.get(id);
|
|
293
|
+
heap.set(id, y ? this.mergeObj(c, x, y, at) : x);
|
|
294
|
+
}
|
|
295
|
+
for (const [id, y] of b.heap)
|
|
296
|
+
if (!heap.has(id))
|
|
297
|
+
heap.set(id, y);
|
|
298
|
+
return { pc, locals, heap, called: [...new Set([...a.called, ...b.called])], locks: a.locks, defers: [...new Set([...a.defers, ...b.defers])] };
|
|
299
|
+
}
|
|
300
|
+
mergeObj(c, a, b, at) {
|
|
301
|
+
if (a === b)
|
|
302
|
+
return a;
|
|
303
|
+
if (a.k === 'big' && b.k === 'big')
|
|
304
|
+
return { ...a, v: I.nite(c, a.v, b.v) };
|
|
305
|
+
if (a.k === 'rec' && b.k === 'rec') {
|
|
306
|
+
const f = new Map();
|
|
307
|
+
for (const [n, x] of a.f) {
|
|
308
|
+
const y = b.f.get(n);
|
|
309
|
+
f.set(n, y ? this.ite(c, x, y, at) : x);
|
|
310
|
+
}
|
|
311
|
+
for (const [n, y] of b.f)
|
|
312
|
+
if (!f.has(n))
|
|
313
|
+
f.set(n, y);
|
|
314
|
+
return { ...a, f, moved: a.moved || b.moved };
|
|
315
|
+
}
|
|
316
|
+
if (a.k === 'map' && b.k === 'map') {
|
|
317
|
+
const w = mergeWrites(c, a.w, b.w, key => this.baseCell(a.decl, key), (c2, x, y) => this.ite(c2, x, y, at));
|
|
318
|
+
return { ...a, ...(a.nil ? { nil: I.bite(c, a.nil, b.nil) } : {}), ...(w ? { w } : {}) };
|
|
319
|
+
}
|
|
320
|
+
if (a.k === 'list' && b.k === 'list')
|
|
321
|
+
return { ...a, ops: mergeOps(c, a.ops, b.ops) };
|
|
322
|
+
if (a.k === 'store' && b.k === 'store')
|
|
323
|
+
return a;
|
|
324
|
+
return refuse(at, 'an object of two kinds by a condition');
|
|
325
|
+
}
|
|
326
|
+
// A value by cases.
|
|
327
|
+
ite(c, a, b, at) {
|
|
328
|
+
if (c.op === 'const')
|
|
329
|
+
return c.v ? a : b;
|
|
330
|
+
if (a === b)
|
|
331
|
+
return a;
|
|
332
|
+
// (a number keeps its type)
|
|
333
|
+
if (a.t === 'num' && b.t === 'num')
|
|
334
|
+
return { t: 'num', e: I.nite(c, a.e, b.e), ...(a.ty ? { ty: a.ty } : {}) };
|
|
335
|
+
if (firm(a) || firm(b))
|
|
336
|
+
return this.iteFirm(c, a, b, at);
|
|
337
|
+
if (keyV(a) === keyV(b))
|
|
338
|
+
return a;
|
|
339
|
+
if (a.t === 'opaque')
|
|
340
|
+
return a;
|
|
341
|
+
if (b.t === 'opaque')
|
|
342
|
+
return b;
|
|
343
|
+
if (a.t === 'bool' && b.t === 'bool')
|
|
344
|
+
return { t: 'bool', e: I.bite(c, a.e, b.e) };
|
|
345
|
+
if (a.t === 'str' && b.t === 'str')
|
|
346
|
+
return { t: 'str', e: I.kite(c, a.e, b.e) };
|
|
347
|
+
if (a.t === 'choice' && b.t === 'choice')
|
|
348
|
+
return { t: 'choice', e: I.lite(c, a.e, b.e) };
|
|
349
|
+
if (a.t === 'choice' && b.t === 'str' && b.e.op === 'slit')
|
|
350
|
+
return this.ite(c, a, { t: 'choice', e: I.llit(b.e.value, lvalues(a.e)) }, at);
|
|
351
|
+
if (b.t === 'choice' && a.t === 'str' && a.e.op === 'slit')
|
|
352
|
+
return this.ite(c, { t: 'choice', e: I.llit(a.e.value, lvalues(b.e)) }, b, at);
|
|
353
|
+
if (a.t === 'none' && b.t === 'none')
|
|
354
|
+
return a;
|
|
355
|
+
if (a.t === 'none')
|
|
356
|
+
return b.t === 'opt' ? { t: 'opt', has: I.and(I.not(c), b.has), v: b.v } : { t: 'opt', has: I.not(c), v: b };
|
|
357
|
+
if (b.t === 'none')
|
|
358
|
+
return a.t === 'opt' ? { t: 'opt', has: I.and(c, a.has), v: a.v } : { t: 'opt', has: c, v: a };
|
|
359
|
+
if (a.t === 'opt' || b.t === 'opt') {
|
|
360
|
+
const oa = a.t === 'opt' ? a : { has: I.T, v: a }, ob = b.t === 'opt' ? b : { has: I.T, v: b };
|
|
361
|
+
return { t: 'opt', has: I.bite(c, oa.has, ob.has), v: this.ite(c, oa.v, ob.v, at) };
|
|
362
|
+
}
|
|
363
|
+
if (a.t === 'res' && b.t === 'res') {
|
|
364
|
+
// (an Err's value, and an Ok's error, are no value: the other side's is taken)
|
|
365
|
+
const no = (x) => x.op === 'const' && !x.v, yes = (x) => x.op === 'const' && x.v;
|
|
366
|
+
return { t: 'res', ok: I.bite(c, a.ok, b.ok), v: no(a.ok) ? b.v : no(b.ok) ? a.v : this.ite(c, a.v, b.v, at), e: yes(a.ok) ? b.e : yes(b.ok) ? a.e : this.ite(c, a.e, b.e, at) };
|
|
367
|
+
}
|
|
368
|
+
if (a.t === 'tuple' && b.t === 'tuple' && a.xs.length === b.xs.length)
|
|
369
|
+
return { t: 'tuple', xs: a.xs.map((x, i) => this.ite(c, x, b.xs[i], at)) };
|
|
370
|
+
if (a.t === 'ref' && b.t === 'ref')
|
|
371
|
+
return refuse(at, 'one of two objects by a condition');
|
|
372
|
+
return refuse(at, `a value that is a ${a.t} on one path and a ${b.t} on another`);
|
|
373
|
+
}
|
|
374
|
+
// Pointers, records by value, error values, nil, maps and lists: Go's merge (a firm value with another refused).
|
|
375
|
+
iteFirm(c, a, b, at) {
|
|
376
|
+
if (a.t === 'err' && b.t === 'err')
|
|
377
|
+
return { t: 'err', is: I.bite(c, a.is, b.is) };
|
|
378
|
+
const asPtr = (v) => (v.t === 'ptr' ? v.to : v.t === 'nil' ? { k: 'nil' } : undefined);
|
|
379
|
+
if ((a.t === 'ptr' || a.t === 'nil') && (b.t === 'ptr' || b.t === 'nil'))
|
|
380
|
+
return { t: 'ptr', to: phiP(c, asPtr(a), asPtr(b)) };
|
|
381
|
+
if ((a.t === 'err' && b.t === 'nil') || (a.t === 'nil' && b.t === 'err'))
|
|
382
|
+
return { t: 'err', is: I.bite(c, a.t === 'err' ? a.is : I.F, b.t === 'err' ? b.is : I.F) };
|
|
383
|
+
if (a.t === 'struct' && b.t === 'struct') {
|
|
384
|
+
const f = new Map();
|
|
385
|
+
for (const [n, x] of a.f)
|
|
386
|
+
f.set(n, this.ite(c, x, b.f.get(n), at));
|
|
387
|
+
return { t: 'struct', ty: a.ty, f };
|
|
388
|
+
}
|
|
389
|
+
if ((a.t === 'map' && b.t === 'map') || (a.t === 'list' && b.t === 'list')) {
|
|
390
|
+
if (a.id === b.id)
|
|
391
|
+
return a;
|
|
392
|
+
return refuse(at, 'one of two maps or slices by a condition');
|
|
393
|
+
}
|
|
394
|
+
if (a.t === 'opaque' && b.t === 'opaque' && a.why === b.why)
|
|
395
|
+
return a;
|
|
396
|
+
if (keyV(a) === keyV(b))
|
|
397
|
+
return a;
|
|
398
|
+
return refuse(at, `a value that is a ${a.t} on one path and a ${b.t} on another`);
|
|
399
|
+
}
|
|
400
|
+
baseCell(d, key) {
|
|
401
|
+
const vals = new Map(d.fields.map(f => [f.name, f.sort.k === 'num' ? { t: 'num', e: { op: 'cell', map: d.name, key, field: f.name } } : f.sort.k === 'choice' ? { t: 'choice', e: { op: 'cell', map: d.name, key, field: f.name, values: f.sort.values } } : { t: 'bool', e: { op: 'cell', map: d.name, key, field: f.name } }]));
|
|
402
|
+
return { has: { op: 'cell', map: d.name, key, field: 'has' }, vals };
|
|
403
|
+
}
|
|
404
|
+
// A value that may be None, read where the path has decided which (after `if x is None: return`).
|
|
405
|
+
narrow(v, p) {
|
|
406
|
+
if (v.t !== 'opt')
|
|
407
|
+
return v;
|
|
408
|
+
const c = this.cond(p);
|
|
409
|
+
if (I.and(c, I.not(v.has)).op === 'const')
|
|
410
|
+
return this.narrow(v.v, p);
|
|
411
|
+
if (I.and(c, v.has).op === 'const')
|
|
412
|
+
return { t: 'none' };
|
|
413
|
+
return v;
|
|
414
|
+
}
|
|
415
|
+
// --- conversions ----------------------------------------------------------------------------------------------------
|
|
416
|
+
// Python's truthiness, made explicit: a later reader's `if` reads a boolean only.
|
|
417
|
+
truthy(v, at, p) {
|
|
418
|
+
if (this.mod.truth === 'nil-false')
|
|
419
|
+
return v.t === 'bool' ? v.e : v.t === 'none' ? I.F : v.t === 'opt' ? I.and(v.has, this.truthy(v.v, at, p)) : v.t === 'opaque' ? refuse(at, `${at.text ?? ''}: the truth of ${v.why}`) : I.T;
|
|
420
|
+
switch (v.t) {
|
|
421
|
+
case 'bool': return v.e;
|
|
422
|
+
case 'num': return I.not(I.cmp('=', v.e, I.num(0)));
|
|
423
|
+
case 'str': return I.not(I.keq(v.e, { op: 'slit', value: '' }));
|
|
424
|
+
case 'choice': return lvalues(v.e).includes('') ? I.not(I.is(v.e, '')) : I.T;
|
|
425
|
+
case 'none': return I.F;
|
|
426
|
+
case 'opt': return I.and(v.has, this.truthy(v.v, at, p));
|
|
427
|
+
case 'ref': {
|
|
428
|
+
// An object is true unless its class (or a base) defines __bool__ or __len__; a dict's truth is whether it is
|
|
429
|
+
// empty, which the subset doesn't read.
|
|
430
|
+
const o = (p?.heap ?? this.initHeap).get(v.id);
|
|
431
|
+
if (o?.k === 'store')
|
|
432
|
+
return I.T;
|
|
433
|
+
if (o?.k === 'rec' && this.plainTruth(o.ty))
|
|
434
|
+
return I.T;
|
|
435
|
+
return refuse(at, `${at.text ?? ''}: the truth of ${o?.k === 'map' ? 'a dict (whether it is empty)' : 'an object whose class may define __bool__ or __len__'}`);
|
|
436
|
+
}
|
|
437
|
+
case 'cell':
|
|
438
|
+
case 'fmt':
|
|
439
|
+
case 'fn':
|
|
440
|
+
case 'cls':
|
|
441
|
+
case 'lock': return I.T;
|
|
442
|
+
case 'builtin':
|
|
443
|
+
case 'ext':
|
|
444
|
+
case 'lib':
|
|
445
|
+
case 'opaque':
|
|
446
|
+
case 'sattr':
|
|
447
|
+
case 'tuple':
|
|
448
|
+
case 'res':
|
|
449
|
+
case 'ptr':
|
|
450
|
+
case 'struct':
|
|
451
|
+
case 'err':
|
|
452
|
+
case 'nil':
|
|
453
|
+
case 'map':
|
|
454
|
+
case 'list':
|
|
455
|
+
case 'push':
|
|
456
|
+
case 'pop': break;
|
|
457
|
+
}
|
|
458
|
+
return refuse(at, `${at.text ?? ''}: the truth of ${v.t === 'opaque' ? v.why : `a ${v.t}`}`);
|
|
459
|
+
}
|
|
460
|
+
plainTruth(ty) {
|
|
461
|
+
const r = this.mod.recs[ty];
|
|
462
|
+
return !!r && !('__bool__' in r.methods) && !('__len__' in r.methods) && !r.kinds.includes('typeddict') && !r.kinds.some(k => k.startsWith('outside-base:'));
|
|
463
|
+
}
|
|
464
|
+
// A number, where the code reads one (a failure where it is None: Python raises a TypeError).
|
|
465
|
+
numOf(v, at, p) {
|
|
466
|
+
if (v.t === 'num')
|
|
467
|
+
return v.e;
|
|
468
|
+
if (v.t === 'opt') {
|
|
469
|
+
this.fail(p, I.not(v.has), at, `${at.text ?? 'a value'} is None where a number is read (a TypeError)`);
|
|
470
|
+
return this.numOf(v.v, at, p);
|
|
471
|
+
}
|
|
472
|
+
if (v.t === 'none') {
|
|
473
|
+
this.fail(p, I.T, at, `${at.text ?? 'a value'} is None where a number is read (a TypeError)`);
|
|
474
|
+
return I.num(0);
|
|
475
|
+
}
|
|
476
|
+
if (v.t === 'bool')
|
|
477
|
+
return refuse(at, `${at.text}: a boolean read as a number`);
|
|
478
|
+
return refuse(at, `${at.text ?? ''}: ${v.t === 'opaque' ? v.why : `a ${v.t} where a number is read`}`);
|
|
479
|
+
}
|
|
480
|
+
keyOf(v, at) {
|
|
481
|
+
if (v.t === 'num')
|
|
482
|
+
return { op: 'num', e: v.e };
|
|
483
|
+
if (v.t === 'str')
|
|
484
|
+
return v.e;
|
|
485
|
+
if (v.t === 'choice' && v.e.op === 'lit')
|
|
486
|
+
return { op: 'slit', value: v.e.value };
|
|
487
|
+
return refuse(at, `${at.text ?? ''}: a key of ${v.t === 'opaque' ? v.why : `a ${v.t}`} (a map's keys are integers or strings)`);
|
|
488
|
+
}
|
|
489
|
+
// --- the program ----------------------------------------------------------------------------------------------------
|
|
490
|
+
func(id, at) { return this.mod.funcs[id] ?? refuse(at, `${id}: no function the reader read`); }
|
|
491
|
+
// A function or a method inlined: its parameters bound, its body run, its returns joined.
|
|
492
|
+
callFunc(f, self, args, kw, at, p0, awaited, caps) {
|
|
493
|
+
if (f.async && !awaited)
|
|
494
|
+
return refuse(at, `${f.name}: a coroutine made and not awaited`);
|
|
495
|
+
if (this.frames.includes(f.id))
|
|
496
|
+
return refuse(at, `${f.name}: a recursive call`);
|
|
497
|
+
for (const d of f.decorators) {
|
|
498
|
+
// (a law's decorator or annotation, @gdp_law("..."), states a law for core/laws.ts: nothing the method does)
|
|
499
|
+
if (['staticmethod', 'classmethod', 'property', 'override', 'typing.override', 'abstractmethod'].includes(d.name) || (this.inf && TAG_DECO.test(d.name)) || /(?:^|\.)gdp[._]?law$/i.test(d.name))
|
|
500
|
+
continue;
|
|
501
|
+
if (this.skipped([d.name, d.text]))
|
|
502
|
+
this.notes.add(`@${d.text} on ${f.name}: taken as transparent (skip)`);
|
|
503
|
+
else if (this.inf && this.tagAt(d.p)?.k !== 'strict')
|
|
504
|
+
this.notes.add(`@${d.text} on ${f.name}: taken as transparent (inferred: the check runs the method as decorated)`);
|
|
505
|
+
else
|
|
506
|
+
refuse(d, `@${d.text}: a decorator (one of other code changes what the method does; skip it to take it as transparent)`);
|
|
507
|
+
}
|
|
508
|
+
this.arm(f.body);
|
|
509
|
+
const locals = new Map();
|
|
510
|
+
const ps = f.params.filter(x => !x.star);
|
|
511
|
+
let i = 0, q = p0;
|
|
512
|
+
for (const pa of ps) {
|
|
513
|
+
let v;
|
|
514
|
+
if (pa.cap)
|
|
515
|
+
v = caps?.get(pa.name) ?? refuse(at, `${f.name}: ${pa.name} not captured`);
|
|
516
|
+
else if (pa.self && !f.static)
|
|
517
|
+
v = self ?? (i < args.length ? args[i++] : refuse(at, `${f.name}: a method called without its object`));
|
|
518
|
+
else if (!pa.kw && i < args.length)
|
|
519
|
+
v = args[i++];
|
|
520
|
+
else {
|
|
521
|
+
const k = kw.find(([n]) => n === pa.name);
|
|
522
|
+
if (k)
|
|
523
|
+
v = k[1];
|
|
524
|
+
}
|
|
525
|
+
if (!v && pa.dflt) {
|
|
526
|
+
const [d, q2] = this.ev(pa.dflt, q);
|
|
527
|
+
v = d;
|
|
528
|
+
q = q2;
|
|
529
|
+
}
|
|
530
|
+
if (!v)
|
|
531
|
+
return refuse(at, `${f.name}(${pa.name}): an argument not given`);
|
|
532
|
+
locals.set(pa.name, v);
|
|
533
|
+
}
|
|
534
|
+
if (i < args.length || kw.some(([n]) => !ps.some(x => x.name === n))) {
|
|
535
|
+
if (f.params.some(x => x.star))
|
|
536
|
+
return refuse(at, `${f.name}: *args or **kwargs given`);
|
|
537
|
+
return refuse(at, `${f.name}: more arguments than it takes`);
|
|
538
|
+
}
|
|
539
|
+
const saved = q.locals;
|
|
540
|
+
this.frames.push(f.id);
|
|
541
|
+
let flow;
|
|
542
|
+
try {
|
|
543
|
+
flow = this.block(f.body, { ...q, locals });
|
|
544
|
+
}
|
|
545
|
+
catch (e) {
|
|
546
|
+
if (e instanceof Refusal && this.inf)
|
|
547
|
+
(e.frames ??= []).push({ id: f.id, roots: [...locals].filter(([, v]) => this.stateRef(v, q)).map(([n]) => n) });
|
|
548
|
+
throw e;
|
|
549
|
+
}
|
|
550
|
+
finally {
|
|
551
|
+
this.frames.pop();
|
|
552
|
+
}
|
|
553
|
+
const rets = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'none' }]] : [])];
|
|
554
|
+
if (!rets.length)
|
|
555
|
+
return [{ t: 'none' }, { ...q, pc: [...q.pc, I.F], locals: saved }];
|
|
556
|
+
const joined = this.join(rets.map(([r, v]) => ({ ...r, locals: new Map([['$ret', v]]) })), at);
|
|
557
|
+
return [joined.locals.get('$ret'), { ...joined, locals: saved }];
|
|
558
|
+
}
|
|
559
|
+
// A branch arm the step runs: its first statement's line, counted by the harness's line events.
|
|
560
|
+
arm(ss) { const s0 = ss.find(x => x.s !== 'import' && !/:0:\d+$/.test(x.p)); if (s0) {
|
|
561
|
+
const m = /^(.*):(\d+):\d+$/.exec(s0.p);
|
|
562
|
+
if (m)
|
|
563
|
+
this.arms.add(`${m[1]}:${m[2]}`);
|
|
564
|
+
} }
|
|
565
|
+
// --- statements -----------------------------------------------------------------------------------------------------
|
|
566
|
+
block(ss, p) {
|
|
567
|
+
let live = p, ft;
|
|
568
|
+
const rets = [], brk = [];
|
|
569
|
+
for (const s of ss) {
|
|
570
|
+
if (!live)
|
|
571
|
+
break;
|
|
572
|
+
if (s.s === 'fallthrough') {
|
|
573
|
+
ft = live;
|
|
574
|
+
live = undefined;
|
|
575
|
+
break;
|
|
576
|
+
}
|
|
577
|
+
const f = this.stmt(s, live);
|
|
578
|
+
rets.push(...f.rets);
|
|
579
|
+
if (f.brk)
|
|
580
|
+
brk.push(...f.brk);
|
|
581
|
+
live = f.live;
|
|
582
|
+
}
|
|
583
|
+
return { ...(live ? { live } : {}), rets, ...(brk.length ? { brk } : {}), ...(ft ? { ft } : {}) };
|
|
584
|
+
}
|
|
585
|
+
stmt(s, p) {
|
|
586
|
+
switch (s.s) {
|
|
587
|
+
case 'expr': {
|
|
588
|
+
const [, q] = this.ev(s.x, p);
|
|
589
|
+
return { live: q, rets: [] };
|
|
590
|
+
}
|
|
591
|
+
case 'set': {
|
|
592
|
+
// A local the subset can't compute, from an expression with no calls (nothing it could change): kept as a value
|
|
593
|
+
// refused wherever the rule would read it.
|
|
594
|
+
let r;
|
|
595
|
+
try {
|
|
596
|
+
r = this.ev(s.x, p);
|
|
597
|
+
}
|
|
598
|
+
catch (e) {
|
|
599
|
+
if (!(e instanceof Refusal) || s.to.e !== 'var' || !callFree(s.x))
|
|
600
|
+
throw e;
|
|
601
|
+
r = [{ t: 'opaque', why: `${e.where}: ${e.what}` }, p];
|
|
602
|
+
}
|
|
603
|
+
return { live: this.assign(s.to, r[0], s, r[1], s.t), rets: [] };
|
|
604
|
+
}
|
|
605
|
+
case 'if': {
|
|
606
|
+
const [cv, q] = this.ev(s.c, p);
|
|
607
|
+
const c = s.strict ? (cv.t === 'bool' ? cv.e : refuse({ p: s.cp }, s.strict)) : this.truthy(cv, s.c, q);
|
|
608
|
+
if (!(c.op === 'const' && !c.v))
|
|
609
|
+
this.arm(s.then);
|
|
610
|
+
if (!(c.op === 'const' && c.v))
|
|
611
|
+
this.arm(s.else);
|
|
612
|
+
const t = c.op === 'const' && !c.v ? undefined : this.block(s.then, this.assume(q, c));
|
|
613
|
+
const e = c.op === 'const' && c.v ? undefined : this.block(s.else, this.assume(q, I.not(c)));
|
|
614
|
+
const lives = [t?.live, e?.live].filter((x) => !!x);
|
|
615
|
+
const live = this.join(lives, s), brk = [...(t?.brk ?? []), ...(e?.brk ?? [])];
|
|
616
|
+
return { ...(live ? { live } : {}), rets: [...(t?.rets ?? []), ...(e?.rets ?? [])], ...(brk.length ? { brk } : {}) };
|
|
617
|
+
}
|
|
618
|
+
case 'ret': {
|
|
619
|
+
if (s.xs || s.one || s.bare) {
|
|
620
|
+
// (Go's: each result, one call's several, or the named results)
|
|
621
|
+
let vs = [], q = p;
|
|
622
|
+
if (s.one) {
|
|
623
|
+
const [v, q2] = this.ev(s.one, q);
|
|
624
|
+
if (v.t !== 'tuple')
|
|
625
|
+
return refuse(s, String(s.why));
|
|
626
|
+
vs = v.xs;
|
|
627
|
+
q = q2;
|
|
628
|
+
}
|
|
629
|
+
else if (s.bare)
|
|
630
|
+
for (const id of s.bare)
|
|
631
|
+
vs.push((id ? q.locals.get(id) : undefined) ?? refuse(s, 'a bare return of an unnamed result'));
|
|
632
|
+
else
|
|
633
|
+
for (const e of s.xs) {
|
|
634
|
+
const [v, q2] = this.ev(e, q);
|
|
635
|
+
vs.push(v);
|
|
636
|
+
q = q2;
|
|
637
|
+
}
|
|
638
|
+
return { rets: [[q, { t: 'tuple', xs: vs }]] };
|
|
639
|
+
}
|
|
640
|
+
if (!s.x)
|
|
641
|
+
return { rets: [[p, { t: 'none' }]] };
|
|
642
|
+
const [v, q] = this.ev(s.x, p);
|
|
643
|
+
return { rets: [[q, v]] };
|
|
644
|
+
}
|
|
645
|
+
case 'fail':
|
|
646
|
+
this.fail(p, I.T, s, String(s.why));
|
|
647
|
+
return { rets: [] };
|
|
648
|
+
case 'with': {
|
|
649
|
+
let q = p;
|
|
650
|
+
for (const it of s.items) {
|
|
651
|
+
if (it.as)
|
|
652
|
+
refuse(s, 'with ... as (a context manager\'s value)');
|
|
653
|
+
if (it.x.e === 'call' && this.skipped(this.calleeNames(it.x))) {
|
|
654
|
+
this.notes.add(`with ${it.x.text} (${it.x.p}): a context manager taken as transparent (skip)`);
|
|
655
|
+
continue;
|
|
656
|
+
}
|
|
657
|
+
const [v, q2] = this.ev(it.x, q);
|
|
658
|
+
q = q2;
|
|
659
|
+
if (v.t === 'opaque' && v.ask) {
|
|
660
|
+
this.notes.add(`with ${it.x.text} (${it.x.p}): a context manager of other code taken as transparent (inferred: the check runs it)`);
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
if (v.t !== 'lock')
|
|
664
|
+
refuse(it.x, `with ${it.x.text}: a context manager (the subset reads a lock's, which makes the step atomic)`);
|
|
665
|
+
this.notes.add(`${this.method}: the lock held (${it.x.p}): the step is atomic`);
|
|
666
|
+
}
|
|
667
|
+
return this.block(s.body, q);
|
|
668
|
+
}
|
|
669
|
+
case 'del': {
|
|
670
|
+
const t = s.x;
|
|
671
|
+
if (t.e !== 'idx')
|
|
672
|
+
return refuse(s, `del ${t.text}: of other than a dict's item`);
|
|
673
|
+
const [m, q] = this.ev(t.x, p), [k, q2] = this.ev(t.i, q);
|
|
674
|
+
return { live: this.mapDel(m, this.keyOf(k, t), t, q2, true), rets: [] };
|
|
675
|
+
}
|
|
676
|
+
case 'import': {
|
|
677
|
+
const locals = new Map(p.locals);
|
|
678
|
+
for (const [n, x] of Object.entries(s.names))
|
|
679
|
+
locals.set(n, { t: 'ext', q: x.name ? `${x.mod}.${x.name}` : x.mod, text: n, patch: { mod: x.mod, ...(x.name ? { path: [x.name] } : {}) }, ...(x.ret ? { ret: x.ret } : {}) });
|
|
680
|
+
return { live: { ...p, locals }, rets: [] };
|
|
681
|
+
}
|
|
682
|
+
case 'no': return refuse(s, String(s.why));
|
|
683
|
+
case 'panic': {
|
|
684
|
+
let q = p;
|
|
685
|
+
for (const a of s.args)
|
|
686
|
+
q = this.ev(a, q)[1];
|
|
687
|
+
this.refuseWhere(q, I.T, s, s.what ?? 'a panic');
|
|
688
|
+
return { rets: [] };
|
|
689
|
+
}
|
|
690
|
+
case 'incdec': {
|
|
691
|
+
const [pl, q] = this.place(s.to, p), [v, q2] = this.read(pl, s, q);
|
|
692
|
+
if (v.t !== 'num')
|
|
693
|
+
return refuse(s, `${s.op} of a ${v.t}`);
|
|
694
|
+
return { live: this.write(pl, this.arith(s.op === '++' ? '+' : '-', v, { t: 'num', e: I.num(1), ty: v.ty }, s, q2), s, q2), rets: [] };
|
|
695
|
+
}
|
|
696
|
+
case 'opset': {
|
|
697
|
+
const [pl, q] = this.place(s.to, p), [x, q2] = this.read(pl, s, q), [y, q3] = this.ev(s.y, q2);
|
|
698
|
+
return { live: this.write(pl, this.binop(String(s.op), x, y, s, q3), s, q3), rets: [] };
|
|
699
|
+
}
|
|
700
|
+
case 'mopset': {
|
|
701
|
+
const at = s.at, [m, q] = this.ev(at.m, p), [k, q2] = this.ev(at.k, q), cell = this.mapRead(m, k, at, q2), [y, q3] = this.ev(s.y, q2);
|
|
702
|
+
return { live: this.mapWrite(m, k, this.binop(String(s.op), cell.v, y, s, q3), at, q3), rets: [] };
|
|
703
|
+
}
|
|
704
|
+
case 'assign': return { live: this.assignGo(s, p), rets: [] };
|
|
705
|
+
case 'switch': return this.switchGo(s, p);
|
|
706
|
+
case 'break': return { rets: [], brk: [p] };
|
|
707
|
+
case 'defer': {
|
|
708
|
+
const key = this.lockKey(s.pl, p);
|
|
709
|
+
if (!p.locks.includes(key))
|
|
710
|
+
refuse(s, `defer ${s.text} without its Lock first`);
|
|
711
|
+
return { live: { ...p, defers: [...p.defers, key] }, rets: [] };
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
return refuse(s, `a statement the subset doesn't read (${s.s})`);
|
|
715
|
+
}
|
|
716
|
+
// An assignment: to a local, to a field of an object, to a dict's item, or to a tuple of those.
|
|
717
|
+
assign(to, v, at, p, t) {
|
|
718
|
+
if (to.e === 'lock' || to.e === 'ref')
|
|
719
|
+
return this.assign(to.x, v, at, p, t);
|
|
720
|
+
switch (to.e) {
|
|
721
|
+
case 'var': {
|
|
722
|
+
let x = v;
|
|
723
|
+
if (t && x.t === 'str' && t.k === 'choice' && x.e.op === 'slit')
|
|
724
|
+
x = { t: 'choice', e: I.llit(x.e.value, t.values) };
|
|
725
|
+
if (t && x.t === 'opaque' && this.scalar(t) === undefined) { } // (kept opaque)
|
|
726
|
+
if (this.init && (to.n === 'self'))
|
|
727
|
+
refuse(at, 'self rebound');
|
|
728
|
+
return { ...p, locals: new Map(p.locals).set(String(to.n), x) };
|
|
729
|
+
}
|
|
730
|
+
case 'tuple': {
|
|
731
|
+
const xs = to.xs;
|
|
732
|
+
if (v.t === 'opaque' && xs.every(y => y.e === 'var')) {
|
|
733
|
+
let q = p;
|
|
734
|
+
for (const y of xs)
|
|
735
|
+
q = this.assign(y, v, at, q);
|
|
736
|
+
return q;
|
|
737
|
+
}
|
|
738
|
+
if (v.t !== 'tuple' || v.xs.length !== xs.length)
|
|
739
|
+
return refuse(at, `${xs.length} names given ${v.t === 'tuple' ? `${v.xs.length} values` : `a ${v.t === 'opaque' ? v.why : v.t}`}`);
|
|
740
|
+
let q = p;
|
|
741
|
+
xs.forEach((x, i) => { q = this.assign(x, v.xs[i], at, q); });
|
|
742
|
+
return q;
|
|
743
|
+
}
|
|
744
|
+
case 'get': {
|
|
745
|
+
const [o, q] = this.ev(to.x, p);
|
|
746
|
+
return this.setField(o, String(to.f), v, to, q, t);
|
|
747
|
+
}
|
|
748
|
+
case 'idx': {
|
|
749
|
+
const [m, q] = this.ev(to.x, p), [k, q2] = this.ev(to.i, q);
|
|
750
|
+
return this.mapSet(m, this.keyOf(k, to.i), v, to, q2);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
return refuse(at, `${to.text ?? to.e}: ${to.e === 'no' ? String(to.why) : 'an assignment the subset doesn\'t read'}`);
|
|
754
|
+
}
|
|
755
|
+
setField(o, f, v, at, p, t) {
|
|
756
|
+
if (o.t === 'opt') {
|
|
757
|
+
this.fail(p, I.not(o.has), at, `${at.text}: a field of None set (an AttributeError)`);
|
|
758
|
+
return this.setField(o.v, f, v, at, this.assume(p, o.has), t);
|
|
759
|
+
}
|
|
760
|
+
if (o.t === 'cell') {
|
|
761
|
+
const m = p.heap.get(o.map);
|
|
762
|
+
const vals = this.cellOf(m, o.key, p, at);
|
|
763
|
+
if (!vals.vals.has(f))
|
|
764
|
+
return refuse(at, `${at.text}: no field ${f} in the map's records`);
|
|
765
|
+
return this.writeCell(o.map, m, o.key, vals.has, new Map(vals.vals).set(f, this.fit(v, m.decl.fields.find(x => x.name === f), at)), at, p);
|
|
766
|
+
}
|
|
767
|
+
if (o.t !== 'ref')
|
|
768
|
+
return refuse(at, `${at.text}: a field set on ${o.t === 'opaque' ? o.why : `a ${o.t}`}`);
|
|
769
|
+
const obj = p.heap.get(o.id);
|
|
770
|
+
if (obj?.k !== 'rec')
|
|
771
|
+
return refuse(at, `${at.text}: a field set on other than an object`);
|
|
772
|
+
if (obj.origin === 'input')
|
|
773
|
+
return refuse(at, `${at.text}: writes an object the caller gave (the caller's, not the state)`);
|
|
774
|
+
if (obj.moved)
|
|
775
|
+
return refuse(at, `${at.text}: writes an object already put in a map (one object in two places)`);
|
|
776
|
+
if (obj.origin === 'state' && !this.init && !obj.f.has(f))
|
|
777
|
+
return refuse(at, `${at.text}: a field the constructor doesn't set (the state's fields are the constructor's)`);
|
|
778
|
+
const old = obj.f.get(f);
|
|
779
|
+
if (old?.t === 'opaque' && obj.origin === 'state' && !this.init)
|
|
780
|
+
return refuse(at, `${at.text}: writes ${old.why}`);
|
|
781
|
+
if (o.id === 'this' && this.frozen.has(f) && !this.init)
|
|
782
|
+
return refuse(at, `${at.text}: writes a field the constructor sets to None (of no type the code states)`);
|
|
783
|
+
if (this.init && t)
|
|
784
|
+
this.declared.set(`${o.id}.${f}`, t);
|
|
785
|
+
// (a literal written to a field of a choice is the choice's)
|
|
786
|
+
const ft = this.declared.get(`${o.id}.${f}`) ?? this.mod.recs[obj.ty]?.fields.find(x => x.name === f)?.t, ct = ft?.k === 'opt' ? ft.of : ft;
|
|
787
|
+
if (ct?.k === 'choice' && v.t === 'str' && v.e.op === 'slit' && ct.values.includes(v.e.value))
|
|
788
|
+
v = { t: 'choice', e: I.llit(v.e.value, ct.values) };
|
|
789
|
+
const heap = new Map(p.heap).set(o.id, { ...obj, f: new Map(obj.f).set(f, v) });
|
|
790
|
+
return { ...p, heap };
|
|
791
|
+
}
|
|
792
|
+
declared = new Map();
|
|
793
|
+
// A value as a cell's field holds it (a string literal of a choice field as the choice).
|
|
794
|
+
fit(v, f, at) {
|
|
795
|
+
if (f.sort.k === 'choice' && v.t === 'str' && v.e.op === 'slit') {
|
|
796
|
+
if (!f.sort.values.includes(v.e.value))
|
|
797
|
+
refuse(at, `${JSON.stringify(v.e.value)} is not one of ${f.name}'s literals`);
|
|
798
|
+
return { t: 'choice', e: I.llit(v.e.value, f.sort.values) };
|
|
799
|
+
}
|
|
800
|
+
if (f.sort.k === 'num' && v.t !== 'num')
|
|
801
|
+
return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} set where a number is held`);
|
|
802
|
+
if (f.sort.k === 'bool' && v.t !== 'bool')
|
|
803
|
+
return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} set where a boolean is held`);
|
|
804
|
+
return v;
|
|
805
|
+
}
|
|
806
|
+
// --- maps -----------------------------------------------------------------------------------------------------------
|
|
807
|
+
mapObj(m, at, p) {
|
|
808
|
+
if (m.t !== 'ref')
|
|
809
|
+
return refuse(at, `${at.text}: an item of ${m.t === 'opaque' ? m.why : `a ${m.t}`}`);
|
|
810
|
+
const o = p.heap.get(m.id);
|
|
811
|
+
if (o?.k !== 'map')
|
|
812
|
+
return refuse(at, `${at.text}: an item of other than a dict`);
|
|
813
|
+
if (o.origin === 'input')
|
|
814
|
+
return refuse(at, `${at.text}: a dict the caller gave`);
|
|
815
|
+
return [m.id, o];
|
|
816
|
+
}
|
|
817
|
+
cellOf(o, key, _p, _at) {
|
|
818
|
+
const base = this.baseCell(o.decl, key);
|
|
819
|
+
if (!o.w)
|
|
820
|
+
return base;
|
|
821
|
+
const same = I.keq(key, o.w.key);
|
|
822
|
+
return { has: I.bite(same, o.w.has, base.has), vals: new Map([...base.vals].map(([f, v]) => [f, this.ite(same, o.w.vals.get(f), v, _at)])) };
|
|
823
|
+
}
|
|
824
|
+
writeCell(id, o, key, has, vals, at, p) {
|
|
825
|
+
if (o.w && !I.same(o.w.key, key))
|
|
826
|
+
return refuse(at, `${at.text}: a second key of one map written in one step (the subset writes one a step)`);
|
|
827
|
+
return { ...p, heap: new Map(p.heap).set(id, { ...o, w: { key, has, vals } }) };
|
|
828
|
+
}
|
|
829
|
+
mapGet(m, k, at, p, missing) {
|
|
830
|
+
const [id, o] = this.mapObj(m, at, p);
|
|
831
|
+
void id;
|
|
832
|
+
const c = this.cellOf(o, k, p, at);
|
|
833
|
+
const value = () => (o.decl.scalar ? c.vals.get('value') : { t: 'cell', map: id, key: k });
|
|
834
|
+
if (missing === 'fail') {
|
|
835
|
+
this.fail(p, I.not(c.has), at, `${at.text}: a key the dict doesn't hold (a KeyError)`);
|
|
836
|
+
return [value(), this.assume(p, c.has)];
|
|
837
|
+
}
|
|
838
|
+
if (missing === 'none')
|
|
839
|
+
return [o.decl.scalar ? { t: 'opt', has: c.has, v: value() } : { t: 'opt', has: c.has, v: value() }, p];
|
|
840
|
+
return [this.ite(c.has, value(), missing, at), p];
|
|
841
|
+
}
|
|
842
|
+
mapSet(m, k, v, at, p) {
|
|
843
|
+
const [id, o] = this.mapObj(m, at, p);
|
|
844
|
+
if (o.decl.scalar)
|
|
845
|
+
return this.writeCell(id, o, k, I.T, new Map([['value', this.fit(v, o.decl.fields[0], at)]]), at, p);
|
|
846
|
+
// A record put in: a fresh one (made here), its fields copied into the cell, the object no longer written apart.
|
|
847
|
+
if (v.t === 'cell' && v.map === id && I.same(v.key, k))
|
|
848
|
+
return p;
|
|
849
|
+
if (v.t !== 'ref')
|
|
850
|
+
return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} put in a dict of records`);
|
|
851
|
+
const r = p.heap.get(v.id);
|
|
852
|
+
if (r?.k !== 'rec' || r.origin !== 'fresh')
|
|
853
|
+
return refuse(at, `${at.text}: an object put in a dict that isn't made here (one object in two places)`);
|
|
854
|
+
const vals = new Map();
|
|
855
|
+
for (const f of o.decl.fields)
|
|
856
|
+
vals.set(f.name, this.fit(r.f.get(f.name) ?? refuse(at, `${at.text}: the record has no ${f.name}`), f, at));
|
|
857
|
+
const q = this.writeCell(id, o, k, I.T, vals, at, p);
|
|
858
|
+
return { ...q, heap: new Map(q.heap).set(v.id, { ...r, moved: true }) };
|
|
859
|
+
}
|
|
860
|
+
mapDel(m, k, at, p, strict) {
|
|
861
|
+
const [id, o] = this.mapObj(m, at, p), c = this.cellOf(o, k, p, at);
|
|
862
|
+
if (strict)
|
|
863
|
+
this.fail(p, I.not(c.has), at, `${at.text}: a key the dict doesn't hold deleted (a KeyError)`);
|
|
864
|
+
return this.writeCell(id, o, k, I.F, new Map([...c.vals].map(([f, v]) => [f, (v.t === 'num' ? { t: 'num', e: I.num(0) } : v.t === 'bool' ? { t: 'bool', e: I.F } : v.t === 'choice' ? { t: 'choice', e: I.llit(lvalues(v.e)[0], lvalues(v.e)) } : v)])), at, strict ? this.assume(p, c.has) : p);
|
|
865
|
+
}
|
|
866
|
+
mapDeclOf(name, t, at) {
|
|
867
|
+
if (t.k !== 'map')
|
|
868
|
+
return refuse(at, `${name}: ${this.why(t)}`);
|
|
869
|
+
const key = t.key.k === 'int' ? 'num' : t.key.k === 'str' ? 'str' : refuse(at, `${name}: a dict keyed by ${this.why(t.key)} (keys are integers or strings)`);
|
|
870
|
+
const cell = (n, ft) => { const s = this.scalar(ft); if (!s || s.k === 'str')
|
|
871
|
+
return refuse(at, `${name}: a dict of ${s?.k === 'str' ? 'strings' : this.why(ft)} (a cell holds integers, booleans and literals)`); return { name: n, sort: s, role: 'state' }; };
|
|
872
|
+
let fields, scalar = true;
|
|
873
|
+
if (t.val.k === 'rec') {
|
|
874
|
+
const r = this.rec(t.val.name, at);
|
|
875
|
+
fields = r.fields.map(f => cell(f.name, f.t));
|
|
876
|
+
scalar = false;
|
|
877
|
+
}
|
|
878
|
+
else
|
|
879
|
+
fields = [cell('value', t.val)];
|
|
880
|
+
const v = this.newVar(name, { k: 'num' }, 'state');
|
|
881
|
+
const d = { name: v.name, key, fields, scalar, js: 'Map' };
|
|
882
|
+
this.maps.push(d);
|
|
883
|
+
return d;
|
|
884
|
+
}
|
|
885
|
+
// --- stores ---------------------------------------------------------------------------------------------------------
|
|
886
|
+
storeMap(store, tpl, kn, at, p) {
|
|
887
|
+
const key = `${store}\u0000${tpl}`;
|
|
888
|
+
let sm = this.storeMaps.get(key);
|
|
889
|
+
if (!sm) {
|
|
890
|
+
for (const other of [...this.storeMaps.values()].filter(x => x.store === store))
|
|
891
|
+
if (!disjoint(other.tpl, tpl))
|
|
892
|
+
refuse(at, `${store}: the key templates ${JSON.stringify(other.tpl)} and ${JSON.stringify(tpl)} may name one key`);
|
|
893
|
+
const decl = this.storeDecl(store);
|
|
894
|
+
const val = decl.value === 'int' ? { k: 'int' } : decl.value === 'str' ? { k: 'str' } : { k: 'float' };
|
|
895
|
+
const name = `${store}_${tpl.replace(/\{\}/g, '').replace(/[^A-Za-z0-9]+/g, '_').replace(/^_|_$/g, '')}`;
|
|
896
|
+
const d = this.mapDeclOf(name, { k: 'map', key: { k: kn ? 'int' : 'str' }, val }, at);
|
|
897
|
+
const id = `store:${key}`;
|
|
898
|
+
sm = { store, tpl, id, decl: d };
|
|
899
|
+
this.storeMaps.set(key, sm);
|
|
900
|
+
this.initHeap.set(id, { k: 'map', decl: d, val, origin: 'state' });
|
|
901
|
+
this.notes.add(`${store}: a store (${this.opts.stores?.[store] ? 'stated' : 'inferred: an injected dependency, read and written by a key'}): ${JSON.stringify(tpl)} keys held as ${d.name}, its expiry and eviction left out`);
|
|
902
|
+
}
|
|
903
|
+
if (!p.heap.has(sm.id))
|
|
904
|
+
p.heap.set(sm.id, this.initHeap.get(sm.id));
|
|
905
|
+
return [sm.id, p.heap.get(sm.id)];
|
|
906
|
+
}
|
|
907
|
+
storeKey(v, at) {
|
|
908
|
+
if (v.t === 'fmt')
|
|
909
|
+
return { tpl: v.tpl, k: v.k, kn: v.k.op === 'num' };
|
|
910
|
+
if (v.t === 'str')
|
|
911
|
+
return { tpl: '{}', k: v.e, kn: false };
|
|
912
|
+
return refuse(at, `${at.text}: a store's key of ${v.t === 'opaque' ? v.why : `a ${v.t}`} (a string, or a format with one hole)`);
|
|
913
|
+
}
|
|
914
|
+
storeAsync = {};
|
|
915
|
+
// A store's declaration: the caller's, with the methods inference reads as its get, set and delete added.
|
|
916
|
+
storeDecls = new Map();
|
|
917
|
+
// (an injected dependency's type: its methods' declared results)
|
|
918
|
+
storeTypes = new Map();
|
|
919
|
+
// (the stores whose keys the rule holds: stated, or an injected dependency the class calls a key's method on)
|
|
920
|
+
storeKeyed = new Set();
|
|
921
|
+
injectedFields = [];
|
|
922
|
+
// (the injected dependencies and stores: their type, whether the rule holds keys of theirs, whether the caller stated them)
|
|
923
|
+
deps = [];
|
|
924
|
+
// A constructor argument held as an injected dependency (a store): one its reader marks so, or one of no scalar type
|
|
925
|
+
// (another module's class, a protocol, none stated) the class keeps in a field and calls methods on.
|
|
926
|
+
injected(pa, init, r) {
|
|
927
|
+
if (!this.inf)
|
|
928
|
+
return undefined;
|
|
929
|
+
const t = pa.t.k === 'opt' ? pa.t.of : pa.t;
|
|
930
|
+
if (!pa.inject && (this.scalar(t) || ['lock', 'none', 'map', 'list'].includes(t.k) || (t.k === 'rec' && this.mod.recs[t.name]?.own && !this.mod.recs[t.name].kinds.includes('protocol')) || pa.dflt))
|
|
931
|
+
return undefined;
|
|
932
|
+
const fields = [];
|
|
933
|
+
deep(init.body, st => { const to = st.to, v = st.x; if (st.s === 'set' && to?.e === 'get' && to.x.e === 'var' && to.x.n === 'self' && v?.e === 'var' && v.n === pa.name)
|
|
934
|
+
fields.push(String(to.f)); });
|
|
935
|
+
const ms = this.callsOn(r, fields);
|
|
936
|
+
if (!pa.inject && !ms.length)
|
|
937
|
+
return undefined;
|
|
938
|
+
return { keyed: ms.some(m => !!keyShape(m)), ...(t.k === 'rec' ? { ty: t.name } : {}) };
|
|
939
|
+
}
|
|
940
|
+
// The methods the class's code calls on its fields named (self.f.m(...), or through a reader of one: self.f().m()).
|
|
941
|
+
callsOn(r, fields) {
|
|
942
|
+
const ms = [], self = (x) => x?.e === 'var' && x.n === 'self';
|
|
943
|
+
const field = (x) => {
|
|
944
|
+
if (x?.e === 'get' && self(x.x))
|
|
945
|
+
return String(x.f);
|
|
946
|
+
const g = x?.e === 'call' && !x.args.length ? x.f : undefined, body = g?.e === 'get' && self(g.x) ? this.mod.funcs[r.methods[String(g.f)] ?? '']?.body : undefined;
|
|
947
|
+
return body?.length === 1 && body[0].s === 'ret' ? field(body[0].x) : undefined;
|
|
948
|
+
};
|
|
949
|
+
for (const id of Object.values(r.methods))
|
|
950
|
+
if (id && this.mod.funcs[id])
|
|
951
|
+
deep(this.mod.funcs[id].body, o => { const f = o.f; if (o.e === 'call' && f?.e === 'get' && fields.includes(field(f.x) ?? ''))
|
|
952
|
+
ms.push(String(f.f)); });
|
|
953
|
+
return ms;
|
|
954
|
+
}
|
|
955
|
+
storeDecl(store) {
|
|
956
|
+
let d = this.storeDecls.get(store);
|
|
957
|
+
if (!d) {
|
|
958
|
+
d = { ...this.opts.stores?.[store] };
|
|
959
|
+
this.storeDecls.set(store, d);
|
|
960
|
+
}
|
|
961
|
+
return d;
|
|
962
|
+
}
|
|
963
|
+
storeCall(store, m, args, kw, at, p, awaited) {
|
|
964
|
+
const d = this.storeDecl(store), all = [...args, ...kw.map(([, v]) => v)];
|
|
965
|
+
// (other code given the rule's state may change it: refused unless the caller states it, the tag on its line)
|
|
966
|
+
const given = (vs) => { if (!this.tagAt(at.p) && vs.some(v => this.stateRef(v, p)))
|
|
967
|
+
refuse(at, `${at.text}: ${store}.${m} is given the rule's state, which other code may change (if it doesn't, a \`gdp: skip\` comment on its line says so)`); };
|
|
968
|
+
const arg = (n, i) => kw.find(([k]) => k === n)?.[1] ?? args[i] ?? refuse(at, `${at.text}: the store's ${n} not given`);
|
|
969
|
+
const has = (n, i) => kw.some(([k]) => k === n) || args.length > i;
|
|
970
|
+
let kind = (d.get ?? ['get', 'async_get_cache', 'get_cache']).includes(m) ? 'get' : (d.set ?? ['set', 'async_set_cache', 'set_cache']).includes(m) ? 'set' : (d.delete ?? ['delete', 'delete_cache', 'async_delete_cache']).includes(m) ? 'delete' : undefined;
|
|
971
|
+
if (!kind && this.inf) {
|
|
972
|
+
// (inferred: a method named as a key's get, set or delete, given a key that is a string or a format)
|
|
973
|
+
const k = keyShape(m), key = kw.find(([n]) => n === 'key')?.[1] ?? args[0];
|
|
974
|
+
if (k && key && (key.t === 'str' || key.t === 'fmt') && (k !== 'set' || has('value', 1))) {
|
|
975
|
+
kind = k;
|
|
976
|
+
(d[k] ??= []).push(m);
|
|
977
|
+
this.notes.add(`${store}.${m}: read as the store's ${k} by a key (inferred from its name)`);
|
|
978
|
+
}
|
|
979
|
+
else {
|
|
980
|
+
// (another method: an answer, or left out; of a store, one that may change what it holds, unless stated)
|
|
981
|
+
if (this.storeKeyed.has(store) && !this.tagAt(at.p))
|
|
982
|
+
return refuse(at, `${at.text}: ${m}, a method of the store not stated as its get, set or delete (one that may change what it holds: state it, stores: {${store}: {get, set, delete}}, or skip it)`);
|
|
983
|
+
given(all);
|
|
984
|
+
const ty = this.storeTypes.get(store), ret = ty ? this.mod.recs[ty]?.rets?.[m] : undefined;
|
|
985
|
+
const out = this.boundary({ ...at, args: [], kw: [] }, { key: `${store}.${m}`, name: `${store}.${m}`, patch: { store, path: [m] }, ...(ret ? { ret } : {}), args: false, refusal: `${at.text}: ${m}, a method of the store not stated as its get, set or delete` }, p, awaited);
|
|
986
|
+
// (left out: the check's store does nothing for it; the claim assumes it returns and changes nothing the rule keeps)
|
|
987
|
+
if (out[0].t === 'opaque' && out[0].ask) {
|
|
988
|
+
if (!(d.skip ??= []).includes(m)) {
|
|
989
|
+
d.skip.push(m);
|
|
990
|
+
this.notes.add(`${store}.${m}: assumes it returns and changes nothing the rule keeps (left out: the check's ${store} does nothing for it)`);
|
|
991
|
+
}
|
|
992
|
+
(this.storeAsync[store] ??= {})[m] = awaited;
|
|
993
|
+
}
|
|
994
|
+
return out;
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
if (!kind)
|
|
998
|
+
return refuse(at, `${at.text}: ${m}, a method of the store not stated as its get, set or delete`);
|
|
999
|
+
const was = (this.storeAsync[store] ??= {})[m];
|
|
1000
|
+
if (was !== undefined && was !== awaited)
|
|
1001
|
+
return refuse(at, `${at.text}: the store's ${m} awaited at one call and not at another`);
|
|
1002
|
+
this.storeAsync[store][m] = awaited;
|
|
1003
|
+
// (a key's operation takes its key, and a set its value: any other argument given the rule's state is refused)
|
|
1004
|
+
const keyV = arg('key', 0), valV = kind === 'set' ? arg('value', 1) : undefined;
|
|
1005
|
+
given(all.filter(v => v !== keyV && v !== valV));
|
|
1006
|
+
const { tpl, k, kn } = this.storeKey(keyV, at);
|
|
1007
|
+
const [id, o] = this.storeMap(store, tpl, kn, at, p);
|
|
1008
|
+
if (kind === 'get')
|
|
1009
|
+
return this.mapGet({ t: 'ref', id }, k, at, p, 'none');
|
|
1010
|
+
if (kind === 'delete')
|
|
1011
|
+
return [{ t: 'none' }, this.mapDel({ t: 'ref', id }, k, at, p, false)];
|
|
1012
|
+
const v = arg('value', 1);
|
|
1013
|
+
if (o.val.k === 'str' ? v.t !== 'str' : v.t !== 'num')
|
|
1014
|
+
return refuse(at, `${at.text}: a ${v.t === 'opaque' ? v.why : v.t} set in a store of ${o.val.k === 'float' ? 'numbers' : o.val.k}`);
|
|
1015
|
+
if (o.val.k === 'str')
|
|
1016
|
+
return refuse(at, `${at.text}: a store of strings (its cells hold numbers)`);
|
|
1017
|
+
return [{ t: 'none' }, this.mapSet({ t: 'ref', id }, k, v, at, p)];
|
|
1018
|
+
}
|
|
1019
|
+
// --- the boundary the caller states ---------------------------------------------------------------------------------
|
|
1020
|
+
calleeNames(x) {
|
|
1021
|
+
const f = x.f;
|
|
1022
|
+
const out = [];
|
|
1023
|
+
if (typeof f.text === 'string')
|
|
1024
|
+
out.push(f.text);
|
|
1025
|
+
if (typeof f.q === 'string')
|
|
1026
|
+
out.push(f.q);
|
|
1027
|
+
if (f.e === 'get')
|
|
1028
|
+
out.push(String(f.f));
|
|
1029
|
+
if (f.e === 'fn')
|
|
1030
|
+
out.push(String(f.id));
|
|
1031
|
+
if (f.e === 'var')
|
|
1032
|
+
out.push(String(f.n));
|
|
1033
|
+
return out;
|
|
1034
|
+
}
|
|
1035
|
+
match(list, names) {
|
|
1036
|
+
return list?.find(e => names.some(n => n === e || n.startsWith(`${e}.`) || n.endsWith(`.${e}`) || n.endsWith(`.${e.replace(/^self\./, '')}`)));
|
|
1037
|
+
}
|
|
1038
|
+
skipped(names) { return !!this.match(this.opts.skip, names); }
|
|
1039
|
+
// A call answered by the request: its result an input (one a step), the check stubbing the callee with it. Its type
|
|
1040
|
+
// is the caller's (a type string), a tag's, or the callee's declared one (inferred: `how` says which).
|
|
1041
|
+
answer(key, names, patch, at, p, awaited, type = this.opts.answers[key], how = 'stated') {
|
|
1042
|
+
if (!patch && !at.end)
|
|
1043
|
+
return refuse(at, `${at.text}: an answered call the check can't stub`);
|
|
1044
|
+
if (this.mod.stubs === false)
|
|
1045
|
+
return refuse(at, `${at.text}: answered (${how}), but the ${LANG[this.mod.lang] ?? this.mod.lang} check can't stub a call yet`);
|
|
1046
|
+
if (p.called.includes(key))
|
|
1047
|
+
return refuse(at, `${at.text}: ${key} called twice in one step (an answer is one a step)`);
|
|
1048
|
+
const q = { ...p, called: [...p.called, key] };
|
|
1049
|
+
// (where it is called: a compiled language's check stubs it there, its source rewritten)
|
|
1050
|
+
const site = { p: at.p, ...(at.end ? { end: at.end } : {}), ...(at.span ? { span: at.span } : {}) };
|
|
1051
|
+
let a = this.answers.get(key);
|
|
1052
|
+
const short = key.split(/\.|::/).pop();
|
|
1053
|
+
if (!a) {
|
|
1054
|
+
const t = typeof type === 'string' ? sortOfText(type, at.p).t : type, text = typeof type === 'string' ? type : typeText(type);
|
|
1055
|
+
const inner = t.k === 'opt' ? t.of : t, s = this.scalar(inner);
|
|
1056
|
+
const v = this.newVar(short, s, 'input', how === 'stated' ? `what ${names[0]} returns (stated: answers)` : `what ${names[0]} returns (${how}: any ${text})`);
|
|
1057
|
+
const none = t.k === 'opt' ? this.newVar(`${short}_none`, { k: 'bool' }, 'input', `whether ${names[0]} returns None`).name : undefined;
|
|
1058
|
+
// (a result of a fixed width: within it, the claim is for the values its type holds)
|
|
1059
|
+
const fit = !!this.intTy(inner);
|
|
1060
|
+
if (fit)
|
|
1061
|
+
this.typed(v, inner, 'input');
|
|
1062
|
+
a = { key, patch: patch ?? {}, async: awaited, inputs: { name: v.name, ...(none ? { none } : {}), ...(inner.k === 'float' ? { float: true } : {}) }, sort: text, ...(how === 'stated' ? {} : { how }), ...(fit ? { fit } : {}), at: [], ...(at.ty ? { ty: at.ty } : {}) };
|
|
1063
|
+
this.answers.set(key, a);
|
|
1064
|
+
this.notes.add(how === 'stated' ? `${names[0]} (${at.p}): answered by the request (stated), its arguments not read` : `${names[0]} (${at.p}): answered by the request (${how}: its value is read; assumes ${names[0]} may return any ${text}), its arguments not read`);
|
|
1065
|
+
}
|
|
1066
|
+
else if (a.async !== awaited)
|
|
1067
|
+
return refuse(at, `${at.text}: ${key} awaited at one call and not at another`);
|
|
1068
|
+
// (a callee whose declared result is a fixed-width integer, the reader's `ity`: an answer is within it where it is read)
|
|
1069
|
+
if (at.ity && this.vars.get(a.inputs.name).sort.k === 'num')
|
|
1070
|
+
this.typed(this.vars.get(a.inputs.name), at.ity, 'input', I.and(this.sel, this.cond(p)));
|
|
1071
|
+
if (!a.at.some(x => x.p === site.p))
|
|
1072
|
+
a.at.push(site);
|
|
1073
|
+
const vv = this.valueOf(this.vars.get(a.inputs.name));
|
|
1074
|
+
return [a.inputs.none ? { t: 'opt', has: I.not(I.bvar(a.inputs.none)), v: vv } : vv, q];
|
|
1075
|
+
}
|
|
1076
|
+
// --- the boundary inferred ---------------------------------------------------------------------------------------
|
|
1077
|
+
// A call of code the subset doesn't read (another module's, an injected dependency's, or the module's own function
|
|
1078
|
+
// cut): tagged, else inferred. Its arguments are evaluated (the code does). Given a reference to the rule's state,
|
|
1079
|
+
// other code may change it: refused unless the caller states it. Its value read (a run refused where it is): the next
|
|
1080
|
+
// run answers it by the request, over its declared type; else it is left out, kept only where nothing reads it.
|
|
1081
|
+
pend = new Map();
|
|
1082
|
+
entryIds = new Set();
|
|
1083
|
+
boundary(x, b, p, awaited) {
|
|
1084
|
+
const tag = this.tagAt(x.p) ?? b.tag;
|
|
1085
|
+
if (tag?.k === 'strict')
|
|
1086
|
+
return refuse(x, b.refusal);
|
|
1087
|
+
const [vals, q] = b.args === false ? [[], p] : this.argVals(x, p);
|
|
1088
|
+
// (a call a reader doesn't lower: the names its arguments mention, where the reader says; else taken as given it)
|
|
1089
|
+
const given = b.args === false && x.e === 'no' && !b.recv ? x.names?.some(n => { const v = q.locals.get(n); return !v || this.stateRef(v, q); }) ?? true : [b.recv, ...vals].some(v => v && this.stateRef(v, q));
|
|
1090
|
+
if (given && !tag && (!b.own || this.writesState(b.own, this.rootsOf(this.func(b.own, x), b.recv, vals, q))))
|
|
1091
|
+
return refuse(x, `${b.refusal}; it is given the rule's state, which ${b.own ? 'its code' : 'other code'} may change (if it doesn't, state it: skip: [${JSON.stringify(b.key.split('.').pop())}], or a \`gdp: skip\` comment on its line)`);
|
|
1092
|
+
const t = tag?.k === 'answer' ? (tag.arg ? tag.arg : b.ret && answerable(b.ret) ? b.ret : refuse(x, `${x.text}: tagged gdp: answer, and ${b.name} declares no type an answer takes: give it (gdp: answer float)`)) : this.inf.answers.get(b.key);
|
|
1093
|
+
if (t)
|
|
1094
|
+
return this.answer(b.key, [b.name], b.patch, x, q, awaited, t, tag ? 'tagged' : 'inferred');
|
|
1095
|
+
const why = `${x.text ?? b.name}: the value of ${b.name}, other code left out`;
|
|
1096
|
+
this.pend.set(why, { ...b, why, at: x.p, ...(x.end ? { end: x.end } : {}) });
|
|
1097
|
+
this.notes.add(`${b.name} (${x.p}): left out (${tag ? 'tagged: gdp: skip' : 'inferred: nothing the rule keeps reads its value'}), run as it is by the check`);
|
|
1098
|
+
return [{ t: 'opaque', why, ask: b.key }, q];
|
|
1099
|
+
}
|
|
1100
|
+
argVals(x, p) {
|
|
1101
|
+
let q = p;
|
|
1102
|
+
const out = [];
|
|
1103
|
+
for (const a of [...(x.args ?? []), ...(x.kw ?? []).map(([, v]) => v)]) {
|
|
1104
|
+
try {
|
|
1105
|
+
const [v, q2] = this.ev(a, q);
|
|
1106
|
+
out.push(v);
|
|
1107
|
+
q = q2;
|
|
1108
|
+
}
|
|
1109
|
+
catch (e) {
|
|
1110
|
+
if (!(e instanceof Refusal) || !foreign(a))
|
|
1111
|
+
throw e;
|
|
1112
|
+
out.push({ t: 'opaque', why: e.what });
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return [out, q];
|
|
1116
|
+
}
|
|
1117
|
+
// A value that is (or holds) a reference to the rule's state: the object, its nested objects, maps, lists, stores.
|
|
1118
|
+
stateRef(v, p) {
|
|
1119
|
+
const st = (id) => { const o = p.heap.get(id); return id === 'this' || (o?.k === 'store' ? this.storeKeyed.has(o.name) : !!o && 'origin' in o && o.origin === 'state'); };
|
|
1120
|
+
if (v.t === 'ref' || v.t === 'map' || v.t === 'list')
|
|
1121
|
+
return st(v.id);
|
|
1122
|
+
if (v.t === 'cell')
|
|
1123
|
+
return st(v.map);
|
|
1124
|
+
if (v.t === 'ptr')
|
|
1125
|
+
return this.cases(v.to).objs.some(c => st(c.id));
|
|
1126
|
+
if (v.t === 'opt')
|
|
1127
|
+
return this.stateRef(v.v, p);
|
|
1128
|
+
if (v.t === 'tuple' || v.t === 'struct')
|
|
1129
|
+
return [...(v.t === 'tuple' ? v.xs : v.f.values())].some(y => this.stateRef(y, p));
|
|
1130
|
+
const by = v.t === 'fn' ? v.self : v.t === 'ext' ? v.recv : undefined;
|
|
1131
|
+
return !!by && this.stateRef(by, p);
|
|
1132
|
+
}
|
|
1133
|
+
// The parameters of a function a call gives the rule's state (its receiver, its arguments).
|
|
1134
|
+
rootsOf(fn, recv, args, p) {
|
|
1135
|
+
const out = new Set(), ps = fn.params.filter(x => !x.star);
|
|
1136
|
+
let i = 0;
|
|
1137
|
+
for (const pa of ps) {
|
|
1138
|
+
const v = pa.self && !fn.static ? recv : args[i++];
|
|
1139
|
+
if (v && this.stateRef(v, p))
|
|
1140
|
+
out.add(pa.name);
|
|
1141
|
+
}
|
|
1142
|
+
return out;
|
|
1143
|
+
}
|
|
1144
|
+
// Whether a function may write the state its `roots` (parameters, then locals aliasing them) reach, read from the IR
|
|
1145
|
+
// alone: a write through one, a call of other code given one, a method called on one, or a statement or expression
|
|
1146
|
+
// the subset doesn't read. The module's own functions it calls are read the same way.
|
|
1147
|
+
writesState(id, roots, seen = new Set()) {
|
|
1148
|
+
if (!roots.size)
|
|
1149
|
+
return false;
|
|
1150
|
+
const key = `${id}(${[...roots].sort().join()})`;
|
|
1151
|
+
if (seen.has(key))
|
|
1152
|
+
return false;
|
|
1153
|
+
seen.add(key);
|
|
1154
|
+
const fn = this.mod.funcs[id];
|
|
1155
|
+
if (!fn)
|
|
1156
|
+
return true;
|
|
1157
|
+
const rs = new Set(roots);
|
|
1158
|
+
const mentions = (x) => deep(x, o => o.e === 'var' && rs.has(String(o.n)));
|
|
1159
|
+
const isVar = (x) => !!x && typeof x === 'object' && x.e === 'var';
|
|
1160
|
+
const targets = (s) => [s.to, ...(s.l ?? []), s.pl, s.at?.m, s.s === 'del' ? s.x : undefined].filter(Boolean);
|
|
1161
|
+
// (aliases first: a local set from a root's parts is one)
|
|
1162
|
+
for (let grew = true; grew;) {
|
|
1163
|
+
grew = false;
|
|
1164
|
+
deep(fn.body, st => { if ((st.s === 'set' || st.s === 'assign') && mentions(st.x ?? st.r))
|
|
1165
|
+
for (const t of targets(st))
|
|
1166
|
+
for (const y of t.e === 'tuple' ? t.xs : [t])
|
|
1167
|
+
if (isVar(y) && !rs.has(String(y.n))) {
|
|
1168
|
+
rs.add(String(y.n));
|
|
1169
|
+
grew = true;
|
|
1170
|
+
} });
|
|
1171
|
+
}
|
|
1172
|
+
const own = (f) => {
|
|
1173
|
+
if (f.e === 'fn')
|
|
1174
|
+
return this.mod.funcs[String(f.id)];
|
|
1175
|
+
if (f.e === 'get' && isVar(f.x) && rs.has(String(f.x.n))) {
|
|
1176
|
+
const r = Object.values(this.mod.recs).find(r => r.own && Object.values(r.methods).includes(fn.id));
|
|
1177
|
+
const mid = r?.methods[String(f.f)];
|
|
1178
|
+
return mid ? this.mod.funcs[mid] : undefined;
|
|
1179
|
+
}
|
|
1180
|
+
return undefined;
|
|
1181
|
+
};
|
|
1182
|
+
const calls = (c) => {
|
|
1183
|
+
const f = c.f, args = [...(c.args ?? [])], kw = c.kw ?? [];
|
|
1184
|
+
const target = f && own(f);
|
|
1185
|
+
if (!target)
|
|
1186
|
+
return (f?.e === 'get' && mentions(f.x)) || args.some(mentions) || kw.some(([, a]) => mentions(a));
|
|
1187
|
+
const sub = new Set(), ps = target.params.filter(x => !x.star);
|
|
1188
|
+
let i = 0;
|
|
1189
|
+
for (const pa of ps) {
|
|
1190
|
+
if (pa.self && !target.static) {
|
|
1191
|
+
if (f.e === 'get')
|
|
1192
|
+
sub.add(pa.name);
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
const a = args[i++] ?? kw.find(([n]) => n === pa.name)?.[1];
|
|
1196
|
+
if (a && mentions(a))
|
|
1197
|
+
sub.add(pa.name);
|
|
1198
|
+
}
|
|
1199
|
+
return this.writesState(target.id, sub, seen);
|
|
1200
|
+
};
|
|
1201
|
+
// (a statement or expression the subset doesn't read: where its reader names what it mentions, by those)
|
|
1202
|
+
return deep(fn.body, o => ((o.s === 'no' || o.e === 'no') && (!o.names || o.names.some(n => rs.has(n)))) || (o.e === 'rmw' && mentions(o)) ||
|
|
1203
|
+
(!!o.s && ['set', 'assign', 'del', 'incdec', 'opset', 'mopset'].includes(o.s) && targets(o).some(t => !isVar(t) && mentions(t))) || (o.e === 'call' && calls(o)));
|
|
1204
|
+
}
|
|
1205
|
+
// The `gdp:` comments of the file read (skip, answer [type], strict), by line: on a call's line, they state its
|
|
1206
|
+
// boundary; on a function's line (or the line above it), every call of it. A decorator or annotation named
|
|
1207
|
+
// gdp.skip, gdp_skip or GdpSkip (answer, strict) states it for the function too.
|
|
1208
|
+
tagLines = new Map();
|
|
1209
|
+
tagAt(at) {
|
|
1210
|
+
const m = this.inf && /^(.*):(\d+):\d+$/.exec(at);
|
|
1211
|
+
if (!m)
|
|
1212
|
+
return undefined;
|
|
1213
|
+
let lines = this.tagLines.get(m[1]);
|
|
1214
|
+
if (!lines) {
|
|
1215
|
+
lines = new Map();
|
|
1216
|
+
const src = sourceOf(this.mod, m[1]) ?? '';
|
|
1217
|
+
src.split('\n').forEach((l, i) => { const t = /(?:#|\/\/|--|%)\s*gdp:\s*(skip|answer|strict)\b[ \t]*([^#\n]*)$/.exec(l); if (t)
|
|
1218
|
+
lines.set(i + 1, { k: t[1], arg: t[2].trim() }); });
|
|
1219
|
+
this.tagLines.set(m[1], lines);
|
|
1220
|
+
}
|
|
1221
|
+
return lines.get(Number(m[2]));
|
|
1222
|
+
}
|
|
1223
|
+
fnTag(fn) {
|
|
1224
|
+
for (const d of fn.decorators) {
|
|
1225
|
+
const m = TAG_DECO.exec(d.name);
|
|
1226
|
+
if (m)
|
|
1227
|
+
return { k: m[1].toLowerCase(), arg: /\(\s*['"](.*)['"]\s*\)/.exec(d.text)?.[1] ?? '' };
|
|
1228
|
+
}
|
|
1229
|
+
const [file, line] = fn.span;
|
|
1230
|
+
return this.tagAt(`${file}:${line}:1`) ?? this.tagAt(`${file}:${line - 1}:1`);
|
|
1231
|
+
}
|
|
1232
|
+
// The module's own function called where the boundary is: its patch for the check (a method of the object: on it).
|
|
1233
|
+
ownPatch(fn, self) {
|
|
1234
|
+
if (!fn.cls)
|
|
1235
|
+
return { mod: this.mod.module, path: [fn.id] };
|
|
1236
|
+
if (self?.t === 'ref' && self.id === 'this')
|
|
1237
|
+
return { self: fn.name };
|
|
1238
|
+
const r = Object.values(this.mod.recs).find(r => r.methods[fn.name] === fn.id);
|
|
1239
|
+
return r ? { mod: r.module, path: [r.short, fn.name] } : undefined;
|
|
1240
|
+
}
|
|
1241
|
+
ownCut(fn, self, x) {
|
|
1242
|
+
const tag = this.fnTag(fn), lineTag = this.tagAt(x.p);
|
|
1243
|
+
if (!this.inf || tag?.k === 'strict' || lineTag?.k === 'strict' || !(this.inf.cut.has(fn.id) || tag || lineTag))
|
|
1244
|
+
return undefined;
|
|
1245
|
+
const why = this.inf.cut.get(fn.id);
|
|
1246
|
+
if (why)
|
|
1247
|
+
this.notes.add(`${fn.name}: the module's own code, outside the subset (${why}), and writing none of the rule's state: taken as other code where it is called (inferred)`);
|
|
1248
|
+
return { key: fn.id, name: fn.name, patch: this.ownPatch(fn, self), ret: fn.ret, own: fn.id, recv: self, tag, refusal: `${x.text}: ${fn.name}` };
|
|
1249
|
+
}
|
|
1250
|
+
// A refused run: what the next one infers, or the refusal (with the statement that would accept it). A value of
|
|
1251
|
+
// other code read is answered by its declared type (where the check can stub it); else the module's own function the
|
|
1252
|
+
// refusal is in (the innermost but the entries) is cut where it writes none of the rule's state.
|
|
1253
|
+
promote(e) {
|
|
1254
|
+
let best;
|
|
1255
|
+
for (const [why, pd] of this.pend)
|
|
1256
|
+
if (e.what.includes(why) && (!best || why.length > best.why.length))
|
|
1257
|
+
best = pd;
|
|
1258
|
+
let hint = '';
|
|
1259
|
+
if (best) {
|
|
1260
|
+
const t = best.ret && answerable(best.ret) ? best.ret : undefined;
|
|
1261
|
+
if (t && (best.patch || best.end) && this.mod.stubs !== false) {
|
|
1262
|
+
this.inf.answers.set(best.key, t);
|
|
1263
|
+
return undefined;
|
|
1264
|
+
}
|
|
1265
|
+
const short = JSON.stringify(best.key.split('.').pop()), cant = this.mod.stubs === false ? `the ${LANG[this.mod.lang] ?? this.mod.lang} check can't stub a call yet` : !best.patch && !best.end ? 'the check can\'t stub it' : '';
|
|
1266
|
+
hint = `${best.refusal.replace(/ \(answer it, skip it, or read that module\)$/, '')} (${best.at}), whose value is read, and ${cant || (!best.ret || best.ret.k === 'any' ? 'it declares no type' : `it returns ${best.ret.k === 'rec' ? `an object (${this.mod.recs[best.ret.name]?.short ?? best.ret.name})` : this.why(best.ret)}`)}: ${cant ? 'read its code, or keep its value unread' : `state what it returns (answers: {${short}: 'int'}, or a \`gdp: answer int\` comment on its line)`}`;
|
|
1267
|
+
}
|
|
1268
|
+
for (const id of e.frames ?? []) {
|
|
1269
|
+
const fn = this.mod.funcs[id.id];
|
|
1270
|
+
if (!fn || this.inf.cut.has(id.id) || this.entryIds.has(id.id) || this.fnTag(fn)?.k === 'strict' || this.writesState(id.id, new Set(id.roots)))
|
|
1271
|
+
continue;
|
|
1272
|
+
this.inf.cut.set(id.id, `${e.where}: ${e.what}`);
|
|
1273
|
+
return undefined;
|
|
1274
|
+
}
|
|
1275
|
+
return hint ? new Refusal(e.where, `${e.what}; ${hint}`) : e;
|
|
1276
|
+
}
|
|
1277
|
+
// --- expressions ----------------------------------------------------------------------------------------------------
|
|
1278
|
+
ev(x, p, awaited = false) {
|
|
1279
|
+
switch (x.e) {
|
|
1280
|
+
case 'int': {
|
|
1281
|
+
const ty = x.ity ?? (x.ty ? this.intTy(x.ty) : undefined);
|
|
1282
|
+
return [{ t: 'num', e: I.num(Number(x.v)), ...(ty ? { ty } : {}) }, p];
|
|
1283
|
+
}
|
|
1284
|
+
case 'unit': return [{ t: 'none' }, p];
|
|
1285
|
+
case 'opaque': return [{ t: 'opaque', why: String(x.why), ...(x.firm ? { firm: true } : {}) }, p];
|
|
1286
|
+
case 'ref':
|
|
1287
|
+
case 'lock': return this.ev(x.x, p);
|
|
1288
|
+
case 'copy': {
|
|
1289
|
+
const [v, q] = this.ev(x.x, p);
|
|
1290
|
+
return this.copy(v, q, x);
|
|
1291
|
+
}
|
|
1292
|
+
case 'cast': return this.cast(x, p);
|
|
1293
|
+
case 'clock': return this.clock(x, p);
|
|
1294
|
+
case 'some': {
|
|
1295
|
+
const [v, q] = this.ev(x.x, p);
|
|
1296
|
+
return [{ t: 'opt', has: I.T, v }, q];
|
|
1297
|
+
}
|
|
1298
|
+
case 'ok':
|
|
1299
|
+
case 'err': {
|
|
1300
|
+
const [v, q] = this.ev(x.x, p);
|
|
1301
|
+
return [{ t: 'res', ok: x.e === 'ok' ? I.T : I.F, v: x.e === 'ok' ? v : { t: 'none' }, e: x.e === 'err' ? v : { t: 'none' } }, q];
|
|
1302
|
+
}
|
|
1303
|
+
case 'is': {
|
|
1304
|
+
const [v, q] = this.ev(x.x, p);
|
|
1305
|
+
return [{ t: 'bool', e: this.isOf(v, String(x.k), x) }, q];
|
|
1306
|
+
}
|
|
1307
|
+
case 'unwrap': {
|
|
1308
|
+
const [v, q] = this.ev(x.x, p);
|
|
1309
|
+
return [this.inner(v, String(x.k), x), q];
|
|
1310
|
+
}
|
|
1311
|
+
case 'expect': {
|
|
1312
|
+
const [v, q] = this.ev(x.x, p);
|
|
1313
|
+
const good = this.isOf(v, 'good', x);
|
|
1314
|
+
this.fail(q, I.not(good), x, `${x.text}: unwrap of ${v.t === 'res' ? 'an Err' : 'None'} (a panic)`);
|
|
1315
|
+
return [this.inner(v, 'good', x), this.assume(q, good)];
|
|
1316
|
+
}
|
|
1317
|
+
case 'opt_or': {
|
|
1318
|
+
const [v, q] = this.ev(x.x, p);
|
|
1319
|
+
const good = this.isOf(v, 'good', x), val = this.inner(v, 'good', x);
|
|
1320
|
+
const [d, q2] = x.d.e === 'zero' ? [zeroLike(val), q] : this.ev(x.d, q);
|
|
1321
|
+
return [this.ite(good, val, d, x), q2];
|
|
1322
|
+
}
|
|
1323
|
+
// The bad case of a value `?` returns: an Err with its error, or None.
|
|
1324
|
+
case 'bad': {
|
|
1325
|
+
const [v, q] = this.ev(x.x, p);
|
|
1326
|
+
return [v.t === 'res' ? { t: 'res', ok: I.F, v: { t: 'none' }, e: v.e } : { t: 'none' }, q];
|
|
1327
|
+
}
|
|
1328
|
+
case 'res_ok': {
|
|
1329
|
+
const [v, q] = this.ev(x.x, p);
|
|
1330
|
+
return [v.t === 'res' ? { t: 'opt', has: v.ok, v: v.v } : v, q];
|
|
1331
|
+
}
|
|
1332
|
+
case 'variant': return [{ t: 'choice', e: I.llit(String(x.v), x.values) }, p];
|
|
1333
|
+
case 'closure': {
|
|
1334
|
+
const caps = new Map();
|
|
1335
|
+
for (const n of x.caps) {
|
|
1336
|
+
const v = p.locals.get(n);
|
|
1337
|
+
if (v)
|
|
1338
|
+
caps.set(n, v);
|
|
1339
|
+
}
|
|
1340
|
+
return [{ t: 'fn', id: String(x.id), caps }, p];
|
|
1341
|
+
}
|
|
1342
|
+
case 'new': {
|
|
1343
|
+
let q = p;
|
|
1344
|
+
const f = new Map();
|
|
1345
|
+
for (const [n, y] of x.fields) {
|
|
1346
|
+
const [v, q2] = this.ev(y, q);
|
|
1347
|
+
f.set(n, v);
|
|
1348
|
+
q = q2;
|
|
1349
|
+
}
|
|
1350
|
+
const r = this.rec(String(x.rec), x);
|
|
1351
|
+
for (const fd of r.fields)
|
|
1352
|
+
if (!f.has(fd.name))
|
|
1353
|
+
return refuse(x, `${x.text}: ${fd.name} not given`);
|
|
1354
|
+
for (const fd of r.fields) {
|
|
1355
|
+
const v = f.get(fd.name);
|
|
1356
|
+
if (fd.t.k === 'choice' && v.t === 'str' && v.e.op === 'slit')
|
|
1357
|
+
f.set(fd.name, { t: 'choice', e: I.llit(v.e.value, fd.t.values) });
|
|
1358
|
+
const ty = this.intTy(fd.t);
|
|
1359
|
+
if (ty && v.t === 'num' && !v.ty)
|
|
1360
|
+
f.set(fd.name, { ...v, ty });
|
|
1361
|
+
}
|
|
1362
|
+
const id = `fresh:${this.fresh++}`;
|
|
1363
|
+
return [{ t: 'ref', id }, { ...q, heap: new Map(q.heap).set(id, { k: 'rec', ty: String(x.rec), f, origin: 'fresh' }) }];
|
|
1364
|
+
}
|
|
1365
|
+
// An immutable update (Elixir's %{s | f: v}): a fresh copy of the record, the fields given set in it.
|
|
1366
|
+
case 'upd': {
|
|
1367
|
+
const [o, q] = this.ev(x.x, p);
|
|
1368
|
+
let [c, q2] = this.copy(o, q, x);
|
|
1369
|
+
for (const [f, y] of x.fields) {
|
|
1370
|
+
const [v, q3] = this.ev(y, q2);
|
|
1371
|
+
q2 = this.setField(c, f, v, x, q3);
|
|
1372
|
+
}
|
|
1373
|
+
return [c, q2];
|
|
1374
|
+
}
|
|
1375
|
+
case 'rmw': return this.rmw(x, p);
|
|
1376
|
+
case 'bool': return [{ t: 'bool', e: x.v ? I.T : I.F }, p];
|
|
1377
|
+
case 'str': return [{ t: 'str', e: { op: 'slit', value: String(x.v) } }, p];
|
|
1378
|
+
case 'none': return [{ t: 'none' }, p];
|
|
1379
|
+
case 'var': {
|
|
1380
|
+
const v = p.locals.get(String(x.n));
|
|
1381
|
+
if (!v)
|
|
1382
|
+
return refuse(x, x.why ?? `${String(x.n)}: a variable read before it is set`);
|
|
1383
|
+
return [this.narrow(v, p), p];
|
|
1384
|
+
}
|
|
1385
|
+
case 'fn': return [{ t: 'fn', id: String(x.id) }, p];
|
|
1386
|
+
case 'cls': return [{ t: 'cls', rec: String(x.rec), ...(x.patch ? { patch: x.patch } : {}) }, p];
|
|
1387
|
+
case 'builtin': return [{ t: 'builtin', n: String(x.n) }, p];
|
|
1388
|
+
case 'lib': return [{ t: 'lib', q: String(x.q) }, p];
|
|
1389
|
+
case 'ext': return [{ t: 'ext', q: String(x.q), text: String(x.text), ...(x.patch ? { patch: x.patch } : {}), ...(x.ret ? { ret: x.ret } : {}) }, p];
|
|
1390
|
+
case 'no': {
|
|
1391
|
+
// (a call of other code a reader doesn't lower, `ext` its name: at the boundary, where it is inferred)
|
|
1392
|
+
if (x.ext && !x.pre && !x.prepl) {
|
|
1393
|
+
const names = [x.ext], ans = this.match(Object.keys(this.opts.answers ?? {}), names), patch = x.patch;
|
|
1394
|
+
if (ans)
|
|
1395
|
+
return this.answer(ans, names, patch, x, x.args ? this.argsRead(x, p) : p, false);
|
|
1396
|
+
if (this.skipped(names)) {
|
|
1397
|
+
this.notes.add(`${names[0]} (${x.p}): left out (stated: skip), run as it is by the check`);
|
|
1398
|
+
return [{ t: 'opaque', why: `${names[0]}: the value of a call left out (skip)` }, x.args ? this.argsRead(x, p) : p];
|
|
1399
|
+
}
|
|
1400
|
+
let q = p, recv;
|
|
1401
|
+
if (x.recv && this.inf)
|
|
1402
|
+
[recv, q] = this.ev(x.recv, q);
|
|
1403
|
+
if (this.inf)
|
|
1404
|
+
return this.boundary(x, { key: names[0], name: names[0], refusal: String(x.why), ...(x.args ? {} : { args: false }), ...(recv ? { recv } : {}), ...(x.ret ? { ret: x.ret } : {}), ...(patch ? { patch } : {}) }, q, false);
|
|
1405
|
+
}
|
|
1406
|
+
let q = p;
|
|
1407
|
+
for (const y of x.pre ?? [])
|
|
1408
|
+
q = this.ev(y, q)[1];
|
|
1409
|
+
if (x.prepl)
|
|
1410
|
+
this.place(x.prepl, q);
|
|
1411
|
+
return refuse(x, String(x.why));
|
|
1412
|
+
}
|
|
1413
|
+
case 'nil': return [{ t: 'nil' }, p];
|
|
1414
|
+
case 'ptr0': return [{ t: 'ptr', to: { k: 'nil' } }, p];
|
|
1415
|
+
case 'errv': {
|
|
1416
|
+
let q = p;
|
|
1417
|
+
for (const y of x.pre ?? [])
|
|
1418
|
+
q = this.ev(y, q)[1];
|
|
1419
|
+
if (x.note)
|
|
1420
|
+
this.notes.add(x.note);
|
|
1421
|
+
return [{ t: 'err', is: x.is ? I.T : I.F }, q];
|
|
1422
|
+
}
|
|
1423
|
+
case 'struct': {
|
|
1424
|
+
let q = p;
|
|
1425
|
+
const f = new Map();
|
|
1426
|
+
for (const [n, y] of x.fields) {
|
|
1427
|
+
const [v, q2] = this.ev(y, q);
|
|
1428
|
+
f.set(n, v);
|
|
1429
|
+
q = q2;
|
|
1430
|
+
}
|
|
1431
|
+
return [{ t: 'struct', ty: String(x.ty), f }, q];
|
|
1432
|
+
}
|
|
1433
|
+
case 'at': {
|
|
1434
|
+
const [pl, q] = this.place(x.pl, p);
|
|
1435
|
+
if (pl.k === 'blank')
|
|
1436
|
+
return refuse(x, '_');
|
|
1437
|
+
const [v, q2] = this.read(pl, x, q);
|
|
1438
|
+
if (v.t === 'opaque' && !x.raw)
|
|
1439
|
+
return refuse(x, v.why);
|
|
1440
|
+
return [v, q2];
|
|
1441
|
+
}
|
|
1442
|
+
case 'deref': {
|
|
1443
|
+
const [v, q] = this.ev(x.x, p);
|
|
1444
|
+
return this.deref(v, [], x, q);
|
|
1445
|
+
}
|
|
1446
|
+
case 'as': {
|
|
1447
|
+
const [v, q] = this.ev(x.x, p);
|
|
1448
|
+
if (v.t === 'num' && x.ity)
|
|
1449
|
+
return [{ ...v, ty: x.ity }, q];
|
|
1450
|
+
if (v.t === 'nil' && x.nil)
|
|
1451
|
+
return [x.nil === 'ptr' ? { t: 'ptr', to: { k: 'nil' } } : { t: 'err', is: I.F }, q];
|
|
1452
|
+
return [v, q];
|
|
1453
|
+
}
|
|
1454
|
+
case 'conv': {
|
|
1455
|
+
const [v, q] = this.ev(x.x, p), ty = x.ity;
|
|
1456
|
+
if (ty && v.t === 'num')
|
|
1457
|
+
return [{ t: 'num', e: this.wrap(v.e, ty.ub ? { bits: ty.bits, signed: ty.signed, name: ty.name, t: ty.t } : ty, x, q), ty }, q];
|
|
1458
|
+
return refuse(x, v.t === 'opaque' && v.ask ? `${String(x.why)}: of ${v.why}` : String(x.why));
|
|
1459
|
+
}
|
|
1460
|
+
case 'binop': {
|
|
1461
|
+
const [a, q] = this.ev(x.x, p), [b, q2] = this.ev(x.y, q);
|
|
1462
|
+
return [this.binop(String(x.op), a, b, x, q2), q2];
|
|
1463
|
+
}
|
|
1464
|
+
case 'andalso': {
|
|
1465
|
+
// The right side runs only where the left doesn't decide: its failures and effects only there.
|
|
1466
|
+
const and = x.op === '&&', [a, q] = this.ev(x.x, p), ab = this.boolv(a, x.x), c = and ? ab : I.not(ab);
|
|
1467
|
+
const [b, q2] = this.ev(x.y, this.assume(q, c)), bb = this.boolv(b, x.y);
|
|
1468
|
+
return [{ t: 'bool', e: and ? I.and(ab, bb) : I.or(ab, bb) }, q2.heap === q.heap ? q : this.merge({ ...q2, pc: [...q.pc, c] }, q, x)];
|
|
1469
|
+
}
|
|
1470
|
+
case 'unop': {
|
|
1471
|
+
const [a, q] = this.ev(x.x, p), op = String(x.op);
|
|
1472
|
+
if (op === '!')
|
|
1473
|
+
return [{ t: 'bool', e: I.not(this.boolv(a, x)) }, q];
|
|
1474
|
+
if (op === '-') {
|
|
1475
|
+
if (a.t !== 'num')
|
|
1476
|
+
return refuse(x, `- of a ${a.t}`);
|
|
1477
|
+
return [{ t: 'num', e: this.wrap(I.neg(a.e), a.ty, x, q), ty: a.ty }, q];
|
|
1478
|
+
}
|
|
1479
|
+
if (op === '+')
|
|
1480
|
+
return [a, q];
|
|
1481
|
+
return refuse(x, String(x.why));
|
|
1482
|
+
}
|
|
1483
|
+
case 'addr': {
|
|
1484
|
+
const [pl, q] = this.place(x.pl, p);
|
|
1485
|
+
if (pl.k === 'heap' && pl.ptr.t === 'ptr')
|
|
1486
|
+
return [{ t: 'ptr', to: this.shift(pl.ptr.to, pl.path) }, this.nonNil(pl.ptr.to, x, q, 'a nil dereference')[1]];
|
|
1487
|
+
return refuse(x, String(x.why));
|
|
1488
|
+
}
|
|
1489
|
+
case 'alloc': {
|
|
1490
|
+
const [v, q] = this.ev(x.x, p), id = `new:${++this.fresh}`;
|
|
1491
|
+
if (v.t !== 'struct')
|
|
1492
|
+
return refuse({ p: '' }, 'new of other than a struct');
|
|
1493
|
+
return [{ t: 'ptr', to: { k: 'obj', id, path: [] } }, { ...q, heap: new Map(q.heap).set(id, { k: 'rec', ty: v.ty, f: new Map(v.f), origin: 'fresh' }) }];
|
|
1494
|
+
}
|
|
1495
|
+
case 'bignew': {
|
|
1496
|
+
if (!x.x)
|
|
1497
|
+
return this.newBig(I.num(0), p);
|
|
1498
|
+
const [v, q] = this.ev(x.x, p);
|
|
1499
|
+
return this.newBig(this.numv(v, x), q);
|
|
1500
|
+
}
|
|
1501
|
+
case 'big': return this.bigCall(x, p);
|
|
1502
|
+
case 'mutex': return this.lockCall(x, p);
|
|
1503
|
+
case 'gcall': {
|
|
1504
|
+
const fn = this.func(String(x.fn), x), r = x.recv;
|
|
1505
|
+
let q = p, recv;
|
|
1506
|
+
if (r?.e === 'addr')
|
|
1507
|
+
[recv, q] = this.ev(r, q);
|
|
1508
|
+
else if (r?.k === 'rd') {
|
|
1509
|
+
const [pl, q2] = this.place(r.pl, q);
|
|
1510
|
+
[recv, q] = this.read(pl, x, q2);
|
|
1511
|
+
}
|
|
1512
|
+
else if (r) {
|
|
1513
|
+
const [v, q2] = this.ev(r.x, q);
|
|
1514
|
+
q = q2;
|
|
1515
|
+
if (r.k === 'val' && v.t === 'ptr')
|
|
1516
|
+
[recv, q] = this.deref(v, [], x, q);
|
|
1517
|
+
else
|
|
1518
|
+
recv = v;
|
|
1519
|
+
}
|
|
1520
|
+
const args = [];
|
|
1521
|
+
for (const a of x.args) {
|
|
1522
|
+
const [v, q2] = this.ev(a, q);
|
|
1523
|
+
args.push(v);
|
|
1524
|
+
q = q2;
|
|
1525
|
+
}
|
|
1526
|
+
return this.inline(fn, recv, args, x, q);
|
|
1527
|
+
}
|
|
1528
|
+
case 'len': {
|
|
1529
|
+
const [s, q] = this.ev(x.x, p);
|
|
1530
|
+
if (x.k === 'str') {
|
|
1531
|
+
if (s.t !== 'str')
|
|
1532
|
+
refuse(x, 'len of a non-string');
|
|
1533
|
+
return [{ t: 'num', e: I.num(0), ty: x.ity, slen: s.e }, q];
|
|
1534
|
+
}
|
|
1535
|
+
return [{ t: 'num', e: this.listLen(s, x, q), ty: x.ity }, q];
|
|
1536
|
+
}
|
|
1537
|
+
case 'append': {
|
|
1538
|
+
const [s, q] = this.ev(x.s, p), [v, q2] = this.ev(x.x, q);
|
|
1539
|
+
if (s.t !== 'list')
|
|
1540
|
+
return refuse(x, 'append to other than a slice of the state');
|
|
1541
|
+
if (v.t === 'num' && v.slen)
|
|
1542
|
+
return refuse(x.at1, 'len of a string read other than against 0');
|
|
1543
|
+
return [{ t: 'push', id: s.id, x: v }, q2];
|
|
1544
|
+
}
|
|
1545
|
+
case 'delete': {
|
|
1546
|
+
const [m, q] = this.ev(x.m, p), [k, q2] = this.ev(x.k, q);
|
|
1547
|
+
return [{ t: 'tuple', xs: [] }, this.mapDelete(m, k, x, q2)];
|
|
1548
|
+
}
|
|
1549
|
+
case 'newmap': return [{ t: 'map', id: 'new-map' }, p];
|
|
1550
|
+
case 'newlist': return [{ t: 'list', id: 'new-list' }, p];
|
|
1551
|
+
case 'minmax': {
|
|
1552
|
+
let q = p;
|
|
1553
|
+
const vs = [];
|
|
1554
|
+
for (const y of x.xs) {
|
|
1555
|
+
const [v, q2] = this.ev(y, q);
|
|
1556
|
+
vs.push(v);
|
|
1557
|
+
q = q2;
|
|
1558
|
+
}
|
|
1559
|
+
let e = this.numv(vs[0], x);
|
|
1560
|
+
for (const v of vs.slice(1))
|
|
1561
|
+
e = x.op === 'min' ? I.nmin(e, this.numv(v, x)) : I.nmax(e, this.numv(v, x));
|
|
1562
|
+
return [{ t: 'num', e, ty: x.ity ?? refuse(x, String(x.why)) }, q];
|
|
1563
|
+
}
|
|
1564
|
+
case 'panic': {
|
|
1565
|
+
let q = p;
|
|
1566
|
+
for (const a of x.args)
|
|
1567
|
+
q = this.ev(a, q)[1];
|
|
1568
|
+
this.refuseWhere(q, I.T, x, x.what ?? 'a panic');
|
|
1569
|
+
return [{ t: 'tuple', xs: [] }, { ...q, pc: [...q.pc, I.F] }];
|
|
1570
|
+
}
|
|
1571
|
+
case 'midx': {
|
|
1572
|
+
const [b, q] = this.ev(x.m, p), [i, q2] = this.ev(x.k, q);
|
|
1573
|
+
return [this.mapRead(b, i, x, q2).v, q2];
|
|
1574
|
+
}
|
|
1575
|
+
case 'lidx': {
|
|
1576
|
+
const [b, q] = this.ev(x.s, p), [i, q2] = this.ev(x.i, q);
|
|
1577
|
+
return this.listGet(b, i, x, q2);
|
|
1578
|
+
}
|
|
1579
|
+
case 'pop': {
|
|
1580
|
+
const [s, q] = this.ev(x.s, p);
|
|
1581
|
+
if (s.t === 'list' && x.ok) {
|
|
1582
|
+
const len = this.listLen(s, x, q);
|
|
1583
|
+
this.refuseWhere(q, I.cmp('<', len, I.num(1)), x, 'a slice out of range (a panic: s[:len(s)-1] of an empty s)');
|
|
1584
|
+
return [{ t: 'pop', id: s.id }, this.assume(q, I.cmp('<=', I.num(1), len))];
|
|
1585
|
+
}
|
|
1586
|
+
return refuse(x, String(x.why));
|
|
1587
|
+
}
|
|
1588
|
+
case 'await': {
|
|
1589
|
+
const inner = x.x;
|
|
1590
|
+
if (inner.e !== 'call')
|
|
1591
|
+
return refuse(x, `await ${inner.text ?? ''}: an await of other than a call`);
|
|
1592
|
+
return this.ev(inner, p, true);
|
|
1593
|
+
}
|
|
1594
|
+
case 'get': return this.get(x, p);
|
|
1595
|
+
case 'idx': {
|
|
1596
|
+
const [m, q] = this.ev(x.x, p), [k, q2] = this.ev(x.i, q);
|
|
1597
|
+
if (m.t === 'opaque')
|
|
1598
|
+
return [m, q2];
|
|
1599
|
+
return this.mapGet(m, this.keyOf(k, x.i), x, q2, 'fail');
|
|
1600
|
+
}
|
|
1601
|
+
case 'neg': {
|
|
1602
|
+
const [v, q] = this.ev(x.x, p);
|
|
1603
|
+
if (v.t === 'opaque')
|
|
1604
|
+
return [v, q];
|
|
1605
|
+
return [{ t: 'num', e: I.neg(this.numOf(v, x, q)) }, q];
|
|
1606
|
+
}
|
|
1607
|
+
case 'not': {
|
|
1608
|
+
const [v, q] = this.ev(x.x, p);
|
|
1609
|
+
if (v.t === 'opaque')
|
|
1610
|
+
return [v, q];
|
|
1611
|
+
if (x.strict && v.t !== 'bool')
|
|
1612
|
+
return refuse(x, `${x.text ?? '!'}: a bitwise not`);
|
|
1613
|
+
return [{ t: 'bool', e: I.not(this.truthy(v, x, q)) }, q];
|
|
1614
|
+
}
|
|
1615
|
+
case 'bin': return this.bin(x, p);
|
|
1616
|
+
case 'cmp': return this.compare(x, p);
|
|
1617
|
+
case 'and':
|
|
1618
|
+
case 'or': return this.boolOp(x, p);
|
|
1619
|
+
case 'ite': {
|
|
1620
|
+
const [cv, q] = this.ev(x.c, p);
|
|
1621
|
+
if (cv.t === 'opaque')
|
|
1622
|
+
return [cv, q];
|
|
1623
|
+
const c = this.truthy(cv, x.c, q);
|
|
1624
|
+
if (c.op === 'const')
|
|
1625
|
+
return this.ev((c.v ? x.a : x.b), q);
|
|
1626
|
+
const [a, qa] = this.ev(x.a, this.assume(q, c)), [b, qb] = this.ev(x.b, this.assume(q, I.not(c)));
|
|
1627
|
+
return [this.ite(c, a, b, x), this.merge(qa, qb, x)];
|
|
1628
|
+
}
|
|
1629
|
+
case 'tuple': {
|
|
1630
|
+
let q = p;
|
|
1631
|
+
const xs = [];
|
|
1632
|
+
for (const y of x.xs) {
|
|
1633
|
+
const [v, q2] = this.ev(y, q);
|
|
1634
|
+
xs.push(v);
|
|
1635
|
+
q = q2;
|
|
1636
|
+
}
|
|
1637
|
+
return [{ t: 'tuple', xs }, q];
|
|
1638
|
+
}
|
|
1639
|
+
case 'fstr': return this.fstr(x, p);
|
|
1640
|
+
case 'dict': {
|
|
1641
|
+
if (x.keys.length)
|
|
1642
|
+
return refuse(x, `${x.text ?? 'a dict literal'}: a dict literal with items (a record is made by its class)`);
|
|
1643
|
+
return [{ t: 'opaque', why: '{} (an empty dict, a map only where a field declares its type)' }, p];
|
|
1644
|
+
}
|
|
1645
|
+
case 'list': return refuse(x, 'a list literal (lists are outside the Python subset)');
|
|
1646
|
+
case 'call': return this.call(x, p, awaited);
|
|
1647
|
+
}
|
|
1648
|
+
return refuse(x, `${x.text ?? x.e}: an expression the subset doesn't read`);
|
|
1649
|
+
}
|
|
1650
|
+
// A value read by value (Rust's copies and moves): an object copied whole into a fresh one, a map's record too.
|
|
1651
|
+
copy(v, p, at) {
|
|
1652
|
+
if (v.t === 'cell') {
|
|
1653
|
+
const m = p.heap.get(v.map), c = this.cellOf(m, v.key, p, at);
|
|
1654
|
+
const id = `fresh:${this.fresh++}`;
|
|
1655
|
+
return [{ t: 'ref', id }, { ...p, heap: new Map(p.heap).set(id, { k: 'rec', ty: m.val.name, f: new Map(c.vals), origin: 'fresh' }) }];
|
|
1656
|
+
}
|
|
1657
|
+
if (v.t === 'opt') {
|
|
1658
|
+
const [w, q] = this.copy(v.v, p, at);
|
|
1659
|
+
return [{ ...v, v: w }, q];
|
|
1660
|
+
}
|
|
1661
|
+
if (v.t !== 'ref')
|
|
1662
|
+
return [v, p];
|
|
1663
|
+
const o = p.heap.get(v.id);
|
|
1664
|
+
if (o?.k !== 'rec')
|
|
1665
|
+
return o?.k === 'map' ? refuse(at, `${at.text ?? ''}: a map copied whole`) : [v, p];
|
|
1666
|
+
let q = p;
|
|
1667
|
+
const f = new Map();
|
|
1668
|
+
for (const [n, w] of o.f) {
|
|
1669
|
+
const [c, q2] = this.copy(w, q, at);
|
|
1670
|
+
f.set(n, c);
|
|
1671
|
+
q = q2;
|
|
1672
|
+
}
|
|
1673
|
+
const id = `fresh:${this.fresh++}`;
|
|
1674
|
+
return [{ t: 'ref', id }, { ...q, heap: new Map(q.heap).set(id, { k: 'rec', ty: o.ty, f, origin: 'fresh', ...(o.lazy && o.origin === 'input' ? {} : {}) }) }];
|
|
1675
|
+
}
|
|
1676
|
+
// Which of its cases a value is: Some / None, Ok / Err, good (Some or Ok) / bad.
|
|
1677
|
+
isOf(v, k, at) {
|
|
1678
|
+
if (v.t === 'opt')
|
|
1679
|
+
return k === 'some' || k === 'good' ? v.has : k === 'none' || k === 'bad' ? I.not(v.has) : refuse(at, `${at.text ?? ''}: an Option tested as ${k}`);
|
|
1680
|
+
if (v.t === 'none')
|
|
1681
|
+
return k === 'none' || k === 'bad' ? I.T : k === 'some' || k === 'good' ? I.F : refuse(at, `${at.text ?? ''}: None tested as ${k}`);
|
|
1682
|
+
if (v.t === 'res')
|
|
1683
|
+
return k === 'ok' || k === 'good' ? v.ok : k === 'err' || k === 'bad' ? I.not(v.ok) : refuse(at, `${at.text ?? ''}: a Result tested as ${k}`);
|
|
1684
|
+
if (v.t === 'opaque')
|
|
1685
|
+
return refuse(at, `${at.text ?? ''}: ${v.why}`);
|
|
1686
|
+
return k === 'some' || k === 'good' ? I.T : k === 'none' || k === 'bad' ? I.F : refuse(at, `${at.text ?? ''}: a ${v.t} tested as ${k}`);
|
|
1687
|
+
}
|
|
1688
|
+
inner(v, k, at) {
|
|
1689
|
+
if (v.t === 'opt')
|
|
1690
|
+
return v.v;
|
|
1691
|
+
if (v.t === 'res')
|
|
1692
|
+
return k === 'err' ? v.e : v.v;
|
|
1693
|
+
if (v.t === 'none')
|
|
1694
|
+
return { t: 'none' };
|
|
1695
|
+
if (v.t === 'opaque')
|
|
1696
|
+
return v;
|
|
1697
|
+
return k === 'err' ? refuse(at, `${at.text ?? ''}: the Err of a value that is no Result`) : v;
|
|
1698
|
+
}
|
|
1699
|
+
// An atomic's operation on the field it is: read, written, or both (one step is one call).
|
|
1700
|
+
rmw(x, p) {
|
|
1701
|
+
const place = x.place, op = String(x.op), args = x.args;
|
|
1702
|
+
const [cur, q] = this.ev(place, p);
|
|
1703
|
+
if (cur.t !== 'num' && cur.t !== 'bool')
|
|
1704
|
+
return refuse(x, `${x.text}: an atomic of ${cur.t === 'opaque' ? cur.why : `a ${cur.t}`}`);
|
|
1705
|
+
this.notes.add(`${x.text} (${x.p}): an atomic read and written as the field it is (each request one step: the claim is for calls that don't interleave)`);
|
|
1706
|
+
const argv = [];
|
|
1707
|
+
let q2 = q;
|
|
1708
|
+
for (const a of args) {
|
|
1709
|
+
const [v, q3] = this.ev(a, q2);
|
|
1710
|
+
argv.push(v);
|
|
1711
|
+
q2 = q3;
|
|
1712
|
+
}
|
|
1713
|
+
const wrap = (e) => { const ty = cur.t === 'num' ? cur.ty : undefined; return ty ? { t: 'num', e: this.wrap(e, ty, x, q2), ty } : { t: 'num', e }; };
|
|
1714
|
+
const set = (v) => this.assign(place, v, x, q2);
|
|
1715
|
+
switch (op) {
|
|
1716
|
+
case 'load': return [cur, q2];
|
|
1717
|
+
case 'store': return [{ t: 'none' }, set(argv[0])];
|
|
1718
|
+
case 'swap': return [cur, set(argv[0])];
|
|
1719
|
+
case 'fetch_add':
|
|
1720
|
+
case 'fetch_sub': return [cur, set(wrap(op === 'fetch_add' ? I.add(this.numOf(cur, x, q2), this.numOf(argv[0], x, q2)) : I.sub(this.numOf(cur, x, q2), this.numOf(argv[0], x, q2))))];
|
|
1721
|
+
case 'fetch_max':
|
|
1722
|
+
case 'fetch_min': return [cur, set({ ...cur, e: op === 'fetch_max' ? I.nmax(this.numOf(cur, x, q2), this.numOf(argv[0], x, q2)) : I.nmin(this.numOf(cur, x, q2), this.numOf(argv[0], x, q2)) })];
|
|
1723
|
+
case 'compare_exchange':
|
|
1724
|
+
case 'compare_exchange_weak': {
|
|
1725
|
+
const c = this.equal(cur, argv[0], x, q2);
|
|
1726
|
+
if (op === 'compare_exchange_weak')
|
|
1727
|
+
this.notes.add(`${x.text}: compare_exchange_weak read as compare_exchange (it may fail spuriously: the claim is for calls where it doesn't)`);
|
|
1728
|
+
return [{ t: 'res', ok: c, v: cur, e: cur }, set(this.ite(c, argv[1], cur, x))];
|
|
1729
|
+
}
|
|
1730
|
+
}
|
|
1731
|
+
return refuse(x, `${x.text}: an atomic's ${op}`);
|
|
1732
|
+
}
|
|
1733
|
+
get(x, p) {
|
|
1734
|
+
const [o, q] = this.ev(x.x, p), f = String(x.f);
|
|
1735
|
+
switch (o.t) {
|
|
1736
|
+
case 'opaque':
|
|
1737
|
+
if (o.sattr)
|
|
1738
|
+
return this.storeAttr(o.sattr.store, `${o.sattr.path}.${f}`, x, q);
|
|
1739
|
+
return [{ t: 'opaque', why: o.why, ...(o.ask ? { ask: o.ask } : {}) }, q];
|
|
1740
|
+
case 'ext': return [{ t: 'ext', q: `${o.q}.${f}`, text: `${o.text}.${f}`, ...(o.patch?.path ? { patch: { ...o.patch, path: [...o.patch.path, f] } } : {}) }, q];
|
|
1741
|
+
case 'none':
|
|
1742
|
+
this.fail(q, I.T, x, `${x.text}: a field of None (an AttributeError)`);
|
|
1743
|
+
return [{ t: 'opaque', why: 'unreachable' }, { ...q, pc: [...q.pc, I.F] }];
|
|
1744
|
+
case 'opt': {
|
|
1745
|
+
this.fail(q, I.not(o.has), x, `${x.text}: a field of None (an AttributeError)`);
|
|
1746
|
+
const [v2, q3] = this.get({ ...x, x: { e: 'var', n: '$v', p: x.p } }, { ...this.assume(q, o.has), locals: new Map(q.locals).set('$v', o.v) });
|
|
1747
|
+
return [v2, { ...q3, locals: q.locals }];
|
|
1748
|
+
}
|
|
1749
|
+
case 'sattr':
|
|
1750
|
+
case 'ref': break;
|
|
1751
|
+
case 'cell': {
|
|
1752
|
+
const m = q.heap.get(o.map), c = this.cellOf(m, o.key, q, x);
|
|
1753
|
+
return [c.vals.get(f) ?? refuse(x, `${x.text}: no field ${f}`), q];
|
|
1754
|
+
}
|
|
1755
|
+
case 'cls': {
|
|
1756
|
+
const r = this.rec(o.rec, x), mid = r.methods[f];
|
|
1757
|
+
if (mid)
|
|
1758
|
+
return [{ t: 'fn', id: mid }, q];
|
|
1759
|
+
return [{ t: 'ext', q: `${o.rec}.${f}`, text: x.text ?? f, ...(o.patch?.path ? { patch: { ...o.patch, path: [...o.patch.path, f] } } : {}), ...(r.rets?.[f] ? { ret: r.rets[f] } : {}) }, q];
|
|
1760
|
+
}
|
|
1761
|
+
case 'bool':
|
|
1762
|
+
case 'builtin':
|
|
1763
|
+
case 'choice':
|
|
1764
|
+
case 'fmt':
|
|
1765
|
+
case 'fn':
|
|
1766
|
+
case 'lib':
|
|
1767
|
+
case 'lock':
|
|
1768
|
+
case 'num':
|
|
1769
|
+
case 'str':
|
|
1770
|
+
case 'tuple':
|
|
1771
|
+
case 'res':
|
|
1772
|
+
case 'ptr':
|
|
1773
|
+
case 'struct':
|
|
1774
|
+
case 'err':
|
|
1775
|
+
case 'nil':
|
|
1776
|
+
case 'map':
|
|
1777
|
+
case 'list':
|
|
1778
|
+
case 'push':
|
|
1779
|
+
case 'pop': return refuse(x, `${x.text}: a field of a ${o.t}`);
|
|
1780
|
+
}
|
|
1781
|
+
if (o.t === 'sattr')
|
|
1782
|
+
return this.storeAttr(o.store, o.path ? `${o.path}.${f}` : f, x, q);
|
|
1783
|
+
const obj = q.heap.get(o.id);
|
|
1784
|
+
if (obj?.k === 'store')
|
|
1785
|
+
return this.storeAttr(obj.name, f, x, q);
|
|
1786
|
+
if (obj?.k !== 'rec')
|
|
1787
|
+
return refuse(x, `${x.text}: a field of other than an object`);
|
|
1788
|
+
const r = this.rec(obj.ty, x);
|
|
1789
|
+
const v = obj.f.get(f);
|
|
1790
|
+
if (v)
|
|
1791
|
+
return [v, q];
|
|
1792
|
+
const mid = r.methods[f];
|
|
1793
|
+
if (mid !== undefined) {
|
|
1794
|
+
if (mid === null)
|
|
1795
|
+
return this.inf ? [{ t: 'ext', q: `${r.name}.${f}`, text: x.text ?? f, patch: { mod: r.module, path: [r.short, f] }, recv: o, ...(r.rets?.[f] ? { ret: r.rets[f] } : {}) }, q] : refuse(x, `${x.text}: a method of another module's class`);
|
|
1796
|
+
const fn = this.func(mid, x);
|
|
1797
|
+
if (fn.decorators.some(d => d.name === 'property'))
|
|
1798
|
+
return this.callFunc(fn, o, [], [], x, q, false);
|
|
1799
|
+
return [{ t: 'fn', id: mid, self: fn.static ? undefined : o }, q];
|
|
1800
|
+
}
|
|
1801
|
+
if (obj.lazy)
|
|
1802
|
+
return this.lazyField(o.id, obj, f, x, q);
|
|
1803
|
+
return refuse(x, `${x.text}: no field ${f} (the object's fields are those its constructor sets)`);
|
|
1804
|
+
}
|
|
1805
|
+
// A field of an object the caller gives, made an input where it is first read.
|
|
1806
|
+
lazyField(id, obj, f, x, p) {
|
|
1807
|
+
const r = this.rec(obj.ty, x), fd = r.fields.find(g => g.name === f);
|
|
1808
|
+
if (!fd)
|
|
1809
|
+
return refuse(x, `${x.text}: ${f}, a field ${r.short} doesn't declare`);
|
|
1810
|
+
const li = this.lazy.get(id);
|
|
1811
|
+
const had = li.vals.get(f);
|
|
1812
|
+
if (had) {
|
|
1813
|
+
p.heap.set(id, { ...obj, f: new Map(obj.f).set(f, had) });
|
|
1814
|
+
return [had, p];
|
|
1815
|
+
}
|
|
1816
|
+
const [v, a] = this.input(`${li.prefix}_${f}`, fd.t, x, p);
|
|
1817
|
+
li.args.push([f, a]);
|
|
1818
|
+
li.vals.set(f, v);
|
|
1819
|
+
p.heap.set(id, { ...obj, f: new Map(obj.f).set(f, v) });
|
|
1820
|
+
return [v, p];
|
|
1821
|
+
}
|
|
1822
|
+
storeAttr(store, path, x, p) {
|
|
1823
|
+
const attrs = this.storeDecl(store).attrs ?? {};
|
|
1824
|
+
if (path in attrs) {
|
|
1825
|
+
const v = attrs[path];
|
|
1826
|
+
this.notes.add(`${store}.${path} is ${JSON.stringify(v)} (stated)`);
|
|
1827
|
+
return [v === null ? { t: 'none' } : typeof v === 'boolean' ? { t: 'bool', e: v ? I.T : I.F } : typeof v === 'number' ? { t: 'num', e: I.num(v) } : { t: 'str', e: { op: 'slit', value: v } }, p];
|
|
1828
|
+
}
|
|
1829
|
+
if (Object.keys(attrs).some(k => k.startsWith(`${path}.`)))
|
|
1830
|
+
return [{ t: 'sattr', store, path }, p];
|
|
1831
|
+
return [{ t: 'opaque', why: `${x.text}: an attribute of the store not stated${this.inf ? ` (where the rule reads it, state its value: stores: {${store}: {attrs: {${JSON.stringify(path)}: null}}})` : ''}`, ...(this.inf ? { sattr: { store, path } } : {}) }, p];
|
|
1832
|
+
}
|
|
1833
|
+
bin(x, p) {
|
|
1834
|
+
const op = String(x.op);
|
|
1835
|
+
if (x.ovf)
|
|
1836
|
+
return this.fixed(x, p);
|
|
1837
|
+
if (op === '/')
|
|
1838
|
+
return refuse(x, `${x.text}: a true division (a float; the subset reads math.floor or math.ceil of x / k, int(x / k), or x // k)`);
|
|
1839
|
+
const [a, q] = this.ev(x.x, p), [b, q2] = this.ev(x.y, q);
|
|
1840
|
+
if (a.t === 'opaque' || b.t === 'opaque')
|
|
1841
|
+
return [a.t === 'opaque' ? a : b, q2];
|
|
1842
|
+
if ((a.t === 'str' || a.t === 'fmt') && op === '+')
|
|
1843
|
+
return [{ t: 'opaque', why: `${x.text}: strings joined` }, q2];
|
|
1844
|
+
if (a.t === 'str' && op === '%')
|
|
1845
|
+
return [{ t: 'opaque', why: `${x.text}: a string formatted` }, q2];
|
|
1846
|
+
const na = this.numOf(a, x, q2), nb = this.numOf(b, x, q2);
|
|
1847
|
+
switch (op) {
|
|
1848
|
+
case '+': return [{ t: 'num', e: I.add(na, nb) }, q2];
|
|
1849
|
+
case '-': return [{ t: 'num', e: I.sub(na, nb) }, q2];
|
|
1850
|
+
case '*': return [{ t: 'num', e: I.mul(na, nb) }, q2];
|
|
1851
|
+
case '//':
|
|
1852
|
+
case '%': {
|
|
1853
|
+
const k = constOf(b);
|
|
1854
|
+
if (k === undefined)
|
|
1855
|
+
return refuse(x, `${x.text}: a division by a value that isn't a constant`);
|
|
1856
|
+
if (k === 0) {
|
|
1857
|
+
this.fail(q2, I.T, x, `${x.text}: a division by zero (a ZeroDivisionError)`);
|
|
1858
|
+
return [{ t: 'num', e: I.num(0) }, { ...q2, pc: [...q2.pc, I.F] }];
|
|
1859
|
+
}
|
|
1860
|
+
const fl = this.floorDiv(na, k);
|
|
1861
|
+
return [{ t: 'num', e: op === '//' ? fl : I.sub(na, I.mulk(k, fl)) }, q2];
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
return refuse(x, `${x.text}: ${op}`);
|
|
1865
|
+
}
|
|
1866
|
+
// Arithmetic with an overflow the reader states (Rust's, later C's): the result's type is its operands', and what
|
|
1867
|
+
// happens past its range is the operation's: a trap (a panic: the step's failure), a wrap (modulo 2^bits), a
|
|
1868
|
+
// saturation, or an Option (checked). Division and remainder truncate toward zero; by zero they trap.
|
|
1869
|
+
fixed(x, p) {
|
|
1870
|
+
const op = String(x.op), ovf = String(x.ovf);
|
|
1871
|
+
const [a, q] = this.ev(x.x, p), [b, q2] = this.ev(x.y, q);
|
|
1872
|
+
if (a.t === 'opaque' || b.t === 'opaque')
|
|
1873
|
+
return [a.t === 'opaque' ? a : b, q2];
|
|
1874
|
+
const na = this.numOf(a, x, q2), nb = this.numOf(b, x, q2);
|
|
1875
|
+
const ty = (a.t === 'num' ? a.ty : undefined) ?? (b.t === 'num' ? b.ty : undefined) ?? (ovf === 'sat0' || ovf === 'checked0' ? { bits: 0, signed: false } : undefined);
|
|
1876
|
+
let e;
|
|
1877
|
+
if (op === '+')
|
|
1878
|
+
e = I.add(na, nb);
|
|
1879
|
+
else if (op === '-')
|
|
1880
|
+
e = I.sub(na, nb);
|
|
1881
|
+
else if (op === '*')
|
|
1882
|
+
e = I.mul(na, nb);
|
|
1883
|
+
else if (op === '/' || op === '%') {
|
|
1884
|
+
const k = constOf(b);
|
|
1885
|
+
if (k === undefined)
|
|
1886
|
+
return refuse(x, `${x.text}: a division by a value that isn't a constant`);
|
|
1887
|
+
if (k === 0) {
|
|
1888
|
+
this.fail(q2, I.T, x, `${x.text}: a division by zero (a panic)`);
|
|
1889
|
+
return [{ t: 'num', e: I.num(0), ...(ty ? { ty } : {}) }, { ...q2, pc: [...q2.pc, I.F] }];
|
|
1890
|
+
}
|
|
1891
|
+
e = op === '/' ? (k < 0 ? I.neg(this.quot(na, -k)) : this.quot(na, k)) : this.rem(na, Math.abs(k));
|
|
1892
|
+
}
|
|
1893
|
+
else
|
|
1894
|
+
return refuse(x, `${x.text}: ${op}`);
|
|
1895
|
+
const out = (n) => ({ t: 'num', e: n, ...(ty ? { ty } : {}) });
|
|
1896
|
+
const [lo, hi] = ty ? rangeOf(ty) : [-Infinity, Infinity], [below, above] = this.past(e, lo, hi, q2);
|
|
1897
|
+
switch (ovf) {
|
|
1898
|
+
case 'trap':
|
|
1899
|
+
this.fail(q2, I.or(below, above), x, `${x.text}: past ${tyName(ty)}'s range (${typeof x.trap === 'string' ? x.trap : `a panic: attempt to ${op === '+' ? 'add' : op === '-' ? 'subtract' : op === '*' ? 'multiply' : 'divide'} with overflow`})`);
|
|
1900
|
+
return [out(e), this.assume(q2, I.not(I.or(below, above)))];
|
|
1901
|
+
case 'sat': return [out(Number.isFinite(lo) || Number.isFinite(hi) ? I.nite(below, I.num(lo), I.nite(above, I.num(hi), e)) : e), q2];
|
|
1902
|
+
case 'sat0': return [out(I.nmax(e, I.num(0))), q2];
|
|
1903
|
+
case 'checked': return [{ t: 'opt', has: I.not(I.or(below, above)), v: out(e) }, q2];
|
|
1904
|
+
case 'checked0': return [{ t: 'opt', has: I.cmp('<=', I.num(0), e), v: out(e) }, q2];
|
|
1905
|
+
case 'wrap': return [out(ty ? this.wrap(e, ty, x, q2) : e), q2];
|
|
1906
|
+
}
|
|
1907
|
+
return refuse(x, `${x.text}: an overflow mode ${ovf}`);
|
|
1908
|
+
}
|
|
1909
|
+
// `x as T`: an integer into another width (wrapped where it may not fit), a C-like enum's discriminant, a bool's 0 or 1.
|
|
1910
|
+
cast(x, p) {
|
|
1911
|
+
const [v, q] = this.ev(x.x, p), t = x.ty, ty = this.intTy(t);
|
|
1912
|
+
if (v.t === 'opaque')
|
|
1913
|
+
return [v, q];
|
|
1914
|
+
let e;
|
|
1915
|
+
if (v.t === 'num')
|
|
1916
|
+
e = v.e;
|
|
1917
|
+
else if (v.t === 'bool')
|
|
1918
|
+
e = I.nite(v.e, I.num(1), I.num(0));
|
|
1919
|
+
else if (v.t === 'choice') {
|
|
1920
|
+
const vals = lvalues(v.e), discs = x.x.discs ?? this.discsOf(vals);
|
|
1921
|
+
e = vals.reduceRight((acc, val, i) => I.nite(I.is(v.e, val), I.num(discs[i] ?? i), acc), I.num(0));
|
|
1922
|
+
}
|
|
1923
|
+
else
|
|
1924
|
+
return refuse(x, `${x.text}: a ${v.t} cast`);
|
|
1925
|
+
if (!ty)
|
|
1926
|
+
return [{ t: 'num', e }, q];
|
|
1927
|
+
const from = v.t === 'num' ? v.ty : { bits: 8, signed: false };
|
|
1928
|
+
const [lo, hi] = rangeOf(ty), [flo, fhi] = from ? rangeOf(from) : [-Infinity, Infinity];
|
|
1929
|
+
if (flo >= lo && fhi <= hi)
|
|
1930
|
+
return [{ t: 'num', e, ty }, q];
|
|
1931
|
+
// (a narrowing cast of a value of a wider type: within the target's range by its bounds and the path's facts, or
|
|
1932
|
+
// refused where it isn't)
|
|
1933
|
+
const out = I.or(...this.past(e, lo, hi, q));
|
|
1934
|
+
if (!(out.op === 'const' && !out.v)) {
|
|
1935
|
+
this.refusals.push(I.and(this.cond(q), out));
|
|
1936
|
+
this.notes.add(`${x.text} (${x.p}): a narrowing cast, refused where the value doesn't fit (it truncates)`);
|
|
1937
|
+
}
|
|
1938
|
+
return [{ t: 'num', e, ty }, this.assume(q, I.not(out))];
|
|
1939
|
+
}
|
|
1940
|
+
discsOf(values) { for (const e of Object.values(this.mod.enums ?? {}))
|
|
1941
|
+
if (e.values.join() === values.join())
|
|
1942
|
+
return e.discs; return values.map((_, i) => i); }
|
|
1943
|
+
// ⌊a / k⌋ for a constant k (≠ 0): Python's // (and its float floor division at whole values).
|
|
1944
|
+
floorDiv(a, k) { return k > 0 ? I.divk(k, a) : I.divk(-k, I.neg(a)); }
|
|
1945
|
+
compare(x, p) {
|
|
1946
|
+
const op = String(x.op);
|
|
1947
|
+
const [a, q] = this.ev(x.x, p), [b, q2] = this.ev(x.y, q);
|
|
1948
|
+
const out = (e) => [{ t: 'bool', e }, q2];
|
|
1949
|
+
if (a.t === 'opaque' || b.t === 'opaque')
|
|
1950
|
+
return [a.t === 'opaque' ? a : b, q2];
|
|
1951
|
+
if (op === 'is' || op === 'is not') {
|
|
1952
|
+
const isNone = (v) => (v.t === 'none' ? I.T : v.t === 'opt' ? I.not(v.has) : I.F);
|
|
1953
|
+
if (b.t !== 'none' && a.t !== 'none')
|
|
1954
|
+
return refuse(x, `${x.text}: an identity test of other than None`);
|
|
1955
|
+
const e = b.t === 'none' ? isNone(a) : isNone(b);
|
|
1956
|
+
return out(op === 'is' ? e : I.not(e));
|
|
1957
|
+
}
|
|
1958
|
+
if (op === 'in' || op === 'not in') {
|
|
1959
|
+
let e;
|
|
1960
|
+
if (b.t === 'tuple')
|
|
1961
|
+
e = I.or(...b.xs.map(y => this.equal(a, y, x, q2)));
|
|
1962
|
+
else {
|
|
1963
|
+
const [, o] = this.mapObj(b, x, q2);
|
|
1964
|
+
e = this.cellOf(o, this.keyOf(a, x.x), q2, x).has;
|
|
1965
|
+
}
|
|
1966
|
+
return out(op === 'in' ? e : I.not(e));
|
|
1967
|
+
}
|
|
1968
|
+
if (op === '==' || op === '!=') {
|
|
1969
|
+
const e = this.equal(a, b, x, q2);
|
|
1970
|
+
return out(op === '==' ? e : I.not(e));
|
|
1971
|
+
}
|
|
1972
|
+
if (a.t === 'str' || b.t === 'str' || a.t === 'choice' || b.t === 'choice')
|
|
1973
|
+
return refuse(x, `${x.text}: strings ordered (the subset compares them for equality)`);
|
|
1974
|
+
const na = this.numOf(a, x, q2), nb = this.numOf(b, x, q2);
|
|
1975
|
+
return out(op === '<' ? I.cmp('<', na, nb) : op === '<=' ? I.cmp('<=', na, nb) : op === '>' ? I.cmp('<', nb, na) : I.cmp('<=', nb, na));
|
|
1976
|
+
}
|
|
1977
|
+
equal(a, b, at, p) {
|
|
1978
|
+
if (a.t === 'none' || b.t === 'none') {
|
|
1979
|
+
const o = a.t === 'none' ? b : a;
|
|
1980
|
+
return o.t === 'none' ? I.T : o.t === 'opt' ? I.not(o.has) : I.F;
|
|
1981
|
+
}
|
|
1982
|
+
if (a.t === 'opt')
|
|
1983
|
+
return I.and(a.has, this.equal(a.v, b, at, p));
|
|
1984
|
+
if (b.t === 'opt')
|
|
1985
|
+
return I.and(b.has, this.equal(a, b.v, at, p));
|
|
1986
|
+
if (a.t === 'num' && b.t === 'num')
|
|
1987
|
+
return I.cmp('=', a.e, b.e);
|
|
1988
|
+
if (a.t === 'bool' && b.t === 'bool')
|
|
1989
|
+
return I.bite(a.e, b.e, I.not(b.e));
|
|
1990
|
+
if (a.t === 'str' && b.t === 'str')
|
|
1991
|
+
return I.keq(a.e, b.e);
|
|
1992
|
+
if (a.t === 'choice' && b.t === 'choice')
|
|
1993
|
+
return I.leq(a.e, b.e);
|
|
1994
|
+
if (a.t === 'choice' && b.t === 'str' && b.e.op === 'slit')
|
|
1995
|
+
return I.is(a.e, b.e.value);
|
|
1996
|
+
if (b.t === 'choice' && a.t === 'str' && a.e.op === 'slit')
|
|
1997
|
+
return I.is(b.e, a.e.value);
|
|
1998
|
+
if ((a.t === 'num' && b.t === 'str') || (a.t === 'str' && b.t === 'num'))
|
|
1999
|
+
return I.F;
|
|
2000
|
+
return refuse(at, `${at.text}: ${a.t} == ${b.t}`);
|
|
2001
|
+
}
|
|
2002
|
+
// and / or: Python's give one of their operands (the first falsy, or the last; the first truthy, or the last).
|
|
2003
|
+
boolOp(x, p) {
|
|
2004
|
+
const xs = x.xs, isAnd = x.e === 'and';
|
|
2005
|
+
const go = (i, q) => {
|
|
2006
|
+
const [v, q1] = this.ev(xs[i], q);
|
|
2007
|
+
if (i === xs.length - 1 || v.t === 'opaque')
|
|
2008
|
+
return [v, q1];
|
|
2009
|
+
const c = this.truthy(v, xs[i], q1);
|
|
2010
|
+
const stop = isAnd ? I.not(c) : c;
|
|
2011
|
+
if (stop.op === 'const' && stop.v)
|
|
2012
|
+
return [v, q1];
|
|
2013
|
+
const [rest, q2] = go(i + 1, this.assume(q1, I.not(stop)));
|
|
2014
|
+
if (stop.op === 'const')
|
|
2015
|
+
return [rest, q2];
|
|
2016
|
+
// (the operand kept where it stops: an optional value is its value where it is truthy)
|
|
2017
|
+
const kept = !isAnd && v.t === 'opt' ? v.v : v;
|
|
2018
|
+
return [this.ite(stop, kept, rest, x), this.merge(this.assume(q1, stop), q2, x)];
|
|
2019
|
+
};
|
|
2020
|
+
return go(0, p);
|
|
2021
|
+
}
|
|
2022
|
+
// An f-string: with one hole between literal text, a key a store reads by (its template); else a value kept only
|
|
2023
|
+
// where nothing reads it.
|
|
2024
|
+
fstr(x, p) {
|
|
2025
|
+
const parts = x.parts;
|
|
2026
|
+
let q = p, tpl = '', hole, n = 0, opaque = false, ask;
|
|
2027
|
+
for (const part of parts) {
|
|
2028
|
+
if (typeof part === 'string') {
|
|
2029
|
+
tpl += part.replace(/\{\}/g, '{ }');
|
|
2030
|
+
continue;
|
|
2031
|
+
}
|
|
2032
|
+
const [v, q2] = this.ev(part.x, q);
|
|
2033
|
+
q = q2;
|
|
2034
|
+
n++;
|
|
2035
|
+
if (v.t === 'opaque' && v.ask)
|
|
2036
|
+
ask ??= v;
|
|
2037
|
+
if (!part.plain || n > 1 || !(v.t === 'str' || (v.t === 'num' && part.plain))) {
|
|
2038
|
+
opaque = true;
|
|
2039
|
+
continue;
|
|
2040
|
+
}
|
|
2041
|
+
hole = v.t === 'str' ? v.e : { op: 'num', e: v.e };
|
|
2042
|
+
tpl += '{}';
|
|
2043
|
+
}
|
|
2044
|
+
if (ask?.t === 'opaque')
|
|
2045
|
+
return [{ t: 'opaque', why: `${x.text}: a formatted string (${ask.why})`, ask: ask.ask }, q];
|
|
2046
|
+
if (opaque || !hole)
|
|
2047
|
+
return [{ t: 'opaque', why: `${x.text}: a formatted string` }, q];
|
|
2048
|
+
return [{ t: 'fmt', tpl, k: hole }, q];
|
|
2049
|
+
}
|
|
2050
|
+
call(x, p, awaited) {
|
|
2051
|
+
const fx = x.f, names = this.calleeNames(x), args0 = x.args, kw0 = x.kw;
|
|
2052
|
+
// The boundary first: an answered call, then a skipped one (neither's arguments read).
|
|
2053
|
+
const ans = this.match(Object.keys(this.opts.answers ?? {}), names);
|
|
2054
|
+
if (ans) {
|
|
2055
|
+
let patch;
|
|
2056
|
+
if (fx.e === 'fn')
|
|
2057
|
+
patch = { mod: this.mod.module, path: [String(fx.id)] };
|
|
2058
|
+
else if (fx.e === 'get' && fx.x.e === 'var' && fx.x.n === 'self')
|
|
2059
|
+
patch = { self: String(fx.f) };
|
|
2060
|
+
else if (fx.e === 'get') {
|
|
2061
|
+
// A method of an object the caller gives, of another module's class: the class's method stubbed.
|
|
2062
|
+
const [o] = this.ev(fx.x, p), obj = o.t === 'ref' ? p.heap.get(o.id) : undefined;
|
|
2063
|
+
if (obj?.k === 'rec') {
|
|
2064
|
+
const r = this.rec(obj.ty, x);
|
|
2065
|
+
patch = { mod: r.module, path: [r.short, String(fx.f)] };
|
|
2066
|
+
}
|
|
2067
|
+
else {
|
|
2068
|
+
const [v] = this.ev(fx, p);
|
|
2069
|
+
if (v.t === 'ext' || v.t === 'cls')
|
|
2070
|
+
patch = v.patch;
|
|
2071
|
+
}
|
|
2072
|
+
}
|
|
2073
|
+
else {
|
|
2074
|
+
const [o] = this.ev(fx, p);
|
|
2075
|
+
if (o.t === 'ext' || o.t === 'cls')
|
|
2076
|
+
patch = o.patch;
|
|
2077
|
+
}
|
|
2078
|
+
return this.answer(ans, names, patch, x, this.argsRead(x, p), awaited);
|
|
2079
|
+
}
|
|
2080
|
+
if (this.skipped(names)) {
|
|
2081
|
+
this.notes.add(`${names[0]} (${x.p}): left out (stated: skip), run as it is by the check`);
|
|
2082
|
+
return [{ t: 'opaque', why: `${x.text}: the value of a call left out (skip)` }, this.argsRead(x, p)];
|
|
2083
|
+
}
|
|
2084
|
+
// The callee and its object.
|
|
2085
|
+
let f, q = p;
|
|
2086
|
+
if (fx.e === 'get') {
|
|
2087
|
+
const [o, q1] = this.ev(fx.x, q);
|
|
2088
|
+
q = q1;
|
|
2089
|
+
if (o.t === 'ref' && q.heap.get(o.id)?.k === 'map')
|
|
2090
|
+
return this.dictCall(o, String(fx.f), x, q);
|
|
2091
|
+
if (o.t === 'ref' && q.heap.get(o.id)?.k === 'store')
|
|
2092
|
+
return this.evArgs(x, q, (args, kw, q2) => this.storeCall(q.heap.get(o.id).name, String(fx.f), args, kw, x, q2, awaited));
|
|
2093
|
+
if (o.t === 'sattr')
|
|
2094
|
+
return refuse(x, `${x.text}: a method of the store's ${o.path} (not stated)`);
|
|
2095
|
+
[f, q] = this.get(fx, q);
|
|
2096
|
+
if (o.t === 'opaque' && f.t === 'opaque')
|
|
2097
|
+
return this.inf ? this.boundary(x, { key: names[0] ?? String(x.text), name: names[0] ?? String(x.text), refusal: `${x.text}: a call on ${o.why}` }, q, awaited) : refuse(x, `${x.text}: a call on ${o.why}`);
|
|
2098
|
+
}
|
|
2099
|
+
else
|
|
2100
|
+
[f, q] = this.ev(fx, q);
|
|
2101
|
+
switch (f.t) {
|
|
2102
|
+
case 'fn': {
|
|
2103
|
+
const fn = this.func(f.id, x);
|
|
2104
|
+
if (fn.generic)
|
|
2105
|
+
return refuse(x, `${fn.name}: a generic function`);
|
|
2106
|
+
const cut = this.ownCut(fn, f.self, x);
|
|
2107
|
+
if (cut)
|
|
2108
|
+
return this.boundary(x, cut, q, !!fn.async);
|
|
2109
|
+
try {
|
|
2110
|
+
return this.evArgs(x, q, (args, kw, q2) => this.callFunc(fn, f.self, args, kw, x, q2, awaited || !fn.async, f.caps));
|
|
2111
|
+
}
|
|
2112
|
+
catch (e) {
|
|
2113
|
+
// (refused before its body runs, an argument or the call itself: the function is where it may be cut)
|
|
2114
|
+
if (e instanceof Refusal && this.inf && !e.frames?.length)
|
|
2115
|
+
e.frames = [{ id: fn.id, roots: f.self && this.stateRef(f.self, q) ? fn.params.filter(x => x.self).map(x => x.name) : [] }];
|
|
2116
|
+
throw e;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
case 'cls': {
|
|
2120
|
+
// (another module's class made: other code, at the boundary)
|
|
2121
|
+
const r = this.inf ? this.mod.recs[f.rec] : undefined;
|
|
2122
|
+
if (r && !r.own)
|
|
2123
|
+
return this.boundary(x, { key: f.rec, name: names[0] ?? r.short, ...(f.patch ? { patch: f.patch } : {}), ret: { k: 'rec', name: f.rec }, refusal: `${x.text}: ${r.short} made (the subset makes the module's own dataclasses)` }, q, awaited);
|
|
2124
|
+
return this.evArgs(x, q, (args, kw, q2) => this.construct(f.rec, args, kw, x, q2));
|
|
2125
|
+
}
|
|
2126
|
+
case 'builtin': return this.builtin(f.n, x, q);
|
|
2127
|
+
case 'lib': return this.lib(f.q, x, q);
|
|
2128
|
+
case 'ext': {
|
|
2129
|
+
const refusal = `${x.text}: ${f.q}, other code (answer it, skip it, or read that module)`;
|
|
2130
|
+
return this.inf ? this.boundary(x, { key: f.q, name: /\s/.test(names[0] ?? ' ') ? f.q : names[0], ...(f.patch ? { patch: f.patch } : {}), ...(f.ret ? { ret: f.ret } : {}), ...(f.recv ? { recv: f.recv } : {}), refusal }, q, awaited) : refuse(x, refusal);
|
|
2131
|
+
}
|
|
2132
|
+
case 'opaque': return this.inf ? this.boundary(x, { key: names[0] ?? String(x.text), name: names[0] ?? String(x.text), refusal: `${x.text}: a call of ${f.why}` }, q, awaited) : refuse(x, `${x.text}: a call of ${f.why}`);
|
|
2133
|
+
case 'bool':
|
|
2134
|
+
case 'cell':
|
|
2135
|
+
case 'choice':
|
|
2136
|
+
case 'fmt':
|
|
2137
|
+
case 'lock':
|
|
2138
|
+
case 'none':
|
|
2139
|
+
case 'num':
|
|
2140
|
+
case 'opt':
|
|
2141
|
+
case 'ref':
|
|
2142
|
+
case 'sattr':
|
|
2143
|
+
case 'str':
|
|
2144
|
+
case 'tuple':
|
|
2145
|
+
case 'res':
|
|
2146
|
+
case 'ptr':
|
|
2147
|
+
case 'struct':
|
|
2148
|
+
case 'err':
|
|
2149
|
+
case 'nil':
|
|
2150
|
+
case 'map':
|
|
2151
|
+
case 'list':
|
|
2152
|
+
case 'push':
|
|
2153
|
+
case 'pop': break;
|
|
2154
|
+
}
|
|
2155
|
+
void args0;
|
|
2156
|
+
void kw0;
|
|
2157
|
+
return refuse(x, `${x.text}: a call of a ${f.t}`);
|
|
2158
|
+
}
|
|
2159
|
+
// The arguments of a call left to the boundary, read as far as the subset goes: the code evaluates them, so the fields
|
|
2160
|
+
// they read are inputs the check gives. An argument outside the subset that reaches none of the module's code and
|
|
2161
|
+
// not the object itself (other code's calls on other values) is taken as changing nothing of the state.
|
|
2162
|
+
argsRead(x, p) { return this.argVals(x, p)[1]; }
|
|
2163
|
+
evArgs(x, p, k) {
|
|
2164
|
+
let q = p;
|
|
2165
|
+
const args = [], kw = [];
|
|
2166
|
+
for (const a of x.args) {
|
|
2167
|
+
const [v, q2] = this.ev(a, q);
|
|
2168
|
+
args.push(v);
|
|
2169
|
+
q = q2;
|
|
2170
|
+
}
|
|
2171
|
+
for (const [n, a] of x.kw) {
|
|
2172
|
+
const [v, q2] = this.ev(a, q);
|
|
2173
|
+
kw.push([n, v]);
|
|
2174
|
+
q = q2;
|
|
2175
|
+
}
|
|
2176
|
+
return k(args, kw, q);
|
|
2177
|
+
}
|
|
2178
|
+
dictCall(m, name, x, p) {
|
|
2179
|
+
return this.evArgs(x, p, (args, kw, q) => {
|
|
2180
|
+
if (kw.length)
|
|
2181
|
+
return refuse(x, `${x.text}: a dict's method given keywords`);
|
|
2182
|
+
const key = () => this.keyOf(args[0] ?? refuse(x, `${x.text}: no key`), x.args[0]);
|
|
2183
|
+
if (name === 'contains_key')
|
|
2184
|
+
return [{ t: 'bool', e: this.cellOf(this.mapObj(m, x, q)[1], key(), q, x).has }, q];
|
|
2185
|
+
if (name === 'insert') {
|
|
2186
|
+
const k = key(), [old, q2] = this.mapGet(m, k, x, q, 'none');
|
|
2187
|
+
return [old, this.mapSet(m, k, args[1] ?? refuse(x, `${x.text}: no value`), x, q2)];
|
|
2188
|
+
}
|
|
2189
|
+
if (name === 'remove') {
|
|
2190
|
+
const k = key(), [old, q2] = this.mapGet(m, k, x, q, 'none');
|
|
2191
|
+
return [old, this.mapDel(m, k, x, q2, false)];
|
|
2192
|
+
}
|
|
2193
|
+
if (name === 'get_mut') {
|
|
2194
|
+
const k = key(), [, o] = this.mapObj(m, x, q);
|
|
2195
|
+
if (o.decl.scalar)
|
|
2196
|
+
return refuse(x, `${x.text}: a reference to a map's number (the subset writes one through m.insert)`);
|
|
2197
|
+
return this.mapGet(m, k, x, q, 'none');
|
|
2198
|
+
}
|
|
2199
|
+
if (name === 'get')
|
|
2200
|
+
return args.length > 1 ? this.mapGet(m, key(), x, q, args[1]) : this.mapGet(m, key(), x, q, 'none');
|
|
2201
|
+
if (name === 'pop') {
|
|
2202
|
+
const k = key();
|
|
2203
|
+
const [v, q2] = args.length > 1 ? this.mapGet(m, k, x, q, args[1]) : this.mapGet(m, k, x, q, 'fail');
|
|
2204
|
+
return [v, this.mapDel(m, k, x, q2, false)];
|
|
2205
|
+
}
|
|
2206
|
+
return refuse(x, `${x.text}: dict.${name} (the subset reads get, pop, [k], in and del)`);
|
|
2207
|
+
});
|
|
2208
|
+
}
|
|
2209
|
+
construct(rec, args, kw, x, p) {
|
|
2210
|
+
const r = this.rec(rec, x);
|
|
2211
|
+
if (!r.kinds.includes('dataclass') || !r.own)
|
|
2212
|
+
return refuse(x, `${x.text}: ${r.short} made (the subset makes the module's own dataclasses)`);
|
|
2213
|
+
if (r.methods.__init__ || r.methods.__post_init__)
|
|
2214
|
+
return refuse(x, `${x.text}: ${r.short} has its own __init__ or __post_init__`);
|
|
2215
|
+
const f = new Map();
|
|
2216
|
+
let i = 0, q = p;
|
|
2217
|
+
for (const fd of r.fields) {
|
|
2218
|
+
let v = i < args.length ? args[i++] : kw.find(([n]) => n === fd.name)?.[1];
|
|
2219
|
+
if (!v && fd.dflt) {
|
|
2220
|
+
const [d, q2] = this.ev(fd.dflt, q);
|
|
2221
|
+
v = d;
|
|
2222
|
+
q = q2;
|
|
2223
|
+
}
|
|
2224
|
+
if (!v)
|
|
2225
|
+
return refuse(x, `${x.text}: ${fd.name} not given`);
|
|
2226
|
+
if (fd.t.k === 'choice' && v.t === 'str' && v.e.op === 'slit')
|
|
2227
|
+
v = { t: 'choice', e: I.llit(v.e.value, fd.t.values) };
|
|
2228
|
+
f.set(fd.name, v);
|
|
2229
|
+
}
|
|
2230
|
+
const id = `fresh:${this.fresh++}`;
|
|
2231
|
+
return [{ t: 'ref', id }, { ...q, heap: new Map(q.heap).set(id, { k: 'rec', ty: rec, f, origin: 'fresh' }) }];
|
|
2232
|
+
}
|
|
2233
|
+
builtin(n, x, p) {
|
|
2234
|
+
const a0 = x.args[0];
|
|
2235
|
+
// int(x / k): truncated toward zero.
|
|
2236
|
+
if (n === 'int' && a0?.e === 'bin' && a0.op === '/')
|
|
2237
|
+
return this.quotient(a0, p, 'trunc');
|
|
2238
|
+
return this.evArgs(x, p, (args, kw, q) => {
|
|
2239
|
+
if (kw.length)
|
|
2240
|
+
return refuse(x, `${x.text}: ${n} given keywords`);
|
|
2241
|
+
if (args.some(a => a.t === 'opaque') && ['str', 'repr', 'len', 'isinstance', 'round', 'int', 'float', 'bool'].includes(n)) {
|
|
2242
|
+
const ask = args.find(a => a.t === 'opaque' && a.ask);
|
|
2243
|
+
return [{ t: 'opaque', why: `${x.text}: of a value outside the subset${ask ? ` (${ask.why})` : ''}`, ...(ask ? { ask: ask.ask } : {}) }, q];
|
|
2244
|
+
}
|
|
2245
|
+
const v = args[0];
|
|
2246
|
+
switch (n) {
|
|
2247
|
+
case 'min':
|
|
2248
|
+
case 'max': {
|
|
2249
|
+
if (args.length < 2)
|
|
2250
|
+
return refuse(x, `${x.text}: ${n} of an iterable`);
|
|
2251
|
+
const ns = args.map(a => this.numOf(a, x, q));
|
|
2252
|
+
const ty = args.map(v => (v.t === 'num' ? v.ty : undefined)).find(Boolean);
|
|
2253
|
+
return [{ t: 'num', e: ns.slice(1).reduce((acc, y) => (n === 'min' ? I.nmin(acc, y) : I.nmax(acc, y)), ns[0]), ...(ty ? { ty } : {}) }, q];
|
|
2254
|
+
}
|
|
2255
|
+
case 'abs': {
|
|
2256
|
+
const e = this.numOf(v, x, q);
|
|
2257
|
+
return [{ t: 'num', e: I.nite(I.cmp('<', e, I.num(0)), I.neg(e), e) }, q];
|
|
2258
|
+
}
|
|
2259
|
+
case 'int':
|
|
2260
|
+
case 'float':
|
|
2261
|
+
if (v?.t === 'str')
|
|
2262
|
+
return refuse(x, `${x.text}: a string parsed`);
|
|
2263
|
+
if (v?.t === 'bool')
|
|
2264
|
+
return [{ t: 'num', e: I.nite(v.e, I.num(1), I.num(0)) }, q];
|
|
2265
|
+
return [{ t: 'num', e: this.numOf(v ?? { t: 'num', e: I.num(0) }, x, q) }, q];
|
|
2266
|
+
case 'bool': return [{ t: 'bool', e: v ? this.truthy(v, x) : I.F }, q];
|
|
2267
|
+
case 'str':
|
|
2268
|
+
if (v?.t === 'str')
|
|
2269
|
+
return [v, q];
|
|
2270
|
+
return [{ t: 'opaque', why: `${x.text}: a value made a string` }, q];
|
|
2271
|
+
case 'repr': return [{ t: 'opaque', why: `${x.text}: a repr` }, q];
|
|
2272
|
+
}
|
|
2273
|
+
return refuse(x, `${x.text}: ${n}() (a builtin outside the subset)`);
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
quotient(d, p, round) {
|
|
2277
|
+
const [a, q] = this.ev(d.x, p), [b, q2] = this.ev(d.y, q), k = constOf(b);
|
|
2278
|
+
if (k === undefined)
|
|
2279
|
+
return refuse(d, `${d.text}: a division by a value that isn't a constant`);
|
|
2280
|
+
if (k === 0) {
|
|
2281
|
+
this.fail(q2, I.T, d, `${d.text}: a division by zero (a ZeroDivisionError)`);
|
|
2282
|
+
return [{ t: 'num', e: I.num(0) }, { ...q2, pc: [...q2.pc, I.F] }];
|
|
2283
|
+
}
|
|
2284
|
+
const n = this.numOf(a, d, q2), fl = this.floorDiv(n, k), ce = I.neg(this.floorDiv(I.neg(n), k));
|
|
2285
|
+
const lt = k > 0 ? I.cmp('<', n, I.num(0)) : I.cmp('<', I.num(0), n);
|
|
2286
|
+
return [{ t: 'num', e: round === 'floor' ? fl : round === 'ceil' ? ce : I.nite(lt, ce, fl) }, q2];
|
|
2287
|
+
}
|
|
2288
|
+
lib(q0, x, p) {
|
|
2289
|
+
const a0 = x.args[0];
|
|
2290
|
+
if ((q0 === 'math.floor' || q0 === 'math.ceil') && a0?.e === 'bin' && a0.op === '/')
|
|
2291
|
+
return this.quotient(a0, p, q0 === 'math.floor' ? 'floor' : 'ceil');
|
|
2292
|
+
if (q0 === 'time.time' || q0 === 'time.monotonic' || q0 === 'time.perf_counter') {
|
|
2293
|
+
this.notes.add(`${q0}() is the request's time (an input, read once a step, at whole seconds: the claim is for those)`);
|
|
2294
|
+
return this.clock(x, p);
|
|
2295
|
+
}
|
|
2296
|
+
if (q0 === 'threading.Lock' || q0 === 'threading.RLock' || q0 === 'asyncio.Lock')
|
|
2297
|
+
return [{ t: 'lock' }, p];
|
|
2298
|
+
return this.evArgs(x, p, (args, _kw, q) => {
|
|
2299
|
+
const v = args[0];
|
|
2300
|
+
if (v?.t === 'opaque')
|
|
2301
|
+
return [v, q];
|
|
2302
|
+
if (q0 === 'math.floor' || q0 === 'math.ceil')
|
|
2303
|
+
return [{ t: 'num', e: this.numOf(v, x, q) }, q];
|
|
2304
|
+
// Whole numbers are finite: isfinite holds, isnan and isinf don't (a float here is a whole value).
|
|
2305
|
+
if (q0 === 'math.isfinite') {
|
|
2306
|
+
this.numOf(v, x, q);
|
|
2307
|
+
return [{ t: 'bool', e: I.T }, q];
|
|
2308
|
+
}
|
|
2309
|
+
if (q0 === 'math.isnan' || q0 === 'math.isinf') {
|
|
2310
|
+
this.numOf(v, x, q);
|
|
2311
|
+
return [{ t: 'bool', e: I.F }, q];
|
|
2312
|
+
}
|
|
2313
|
+
return refuse(x, `${x.text}: ${q0}`);
|
|
2314
|
+
});
|
|
2315
|
+
}
|
|
2316
|
+
// --- pointers into the state, value records, lists, error values and locks (Go's lowering's; C's and Rust's next) --
|
|
2317
|
+
// A pointer is by cases on the objects it may be (an interior one, &x.f, a path into it), or nil; a record held by
|
|
2318
|
+
// value is copied where it is assigned; an error value is nil or not; a list of the state is pushed, popped or set
|
|
2319
|
+
// once a step; a lock held until the deferred unlock at the return. Each failure is where it is (refuseWhere: the
|
|
2320
|
+
// step's refusal, the state as it was there), and each refusal text is the reader's own.
|
|
2321
|
+
edges = [];
|
|
2322
|
+
lists = [];
|
|
2323
|
+
spans = new Map();
|
|
2324
|
+
stateOrigin = new Map();
|
|
2325
|
+
lazyIn = new Map();
|
|
2326
|
+
// A failure where c holds on this path, refused (the step's refusal); `state` false: one the code goes on past and
|
|
2327
|
+
// the rule's numbers stop at (an edge, counted apart by the check).
|
|
2328
|
+
refuseWhere(p, c, at, what, state = true) {
|
|
2329
|
+
const w = I.and(this.cond(p), c);
|
|
2330
|
+
if (w.op === 'const' && !w.v)
|
|
2331
|
+
return;
|
|
2332
|
+
if (state)
|
|
2333
|
+
this.unwritten(p, at, what);
|
|
2334
|
+
this.refusals.push(w);
|
|
2335
|
+
if (!state)
|
|
2336
|
+
this.edges.push(w);
|
|
2337
|
+
}
|
|
2338
|
+
// The cases a pointer is: each object (with the condition it is that one), and the condition it is nil.
|
|
2339
|
+
cases(p, c = I.T) {
|
|
2340
|
+
if (p.k === 'nil')
|
|
2341
|
+
return { nil: c, objs: [] };
|
|
2342
|
+
if (p.k === 'obj')
|
|
2343
|
+
return { nil: I.F, objs: [{ c, id: p.id, path: p.path }] };
|
|
2344
|
+
const a = this.cases(p.a, I.and(c, p.c)), b = this.cases(p.b, I.and(c, I.not(p.c)));
|
|
2345
|
+
return { nil: I.or(a.nil, b.nil), objs: [...a.objs, ...b.objs] };
|
|
2346
|
+
}
|
|
2347
|
+
// A pointer's cases, a failure (what) where it may be nil, and the path where it isn't.
|
|
2348
|
+
nonNil(to, at, p, what) { const cs = this.cases(to); this.refuseWhere(p, cs.nil, at, what); return [cs, this.assume(p, I.not(cs.nil))]; }
|
|
2349
|
+
shift(p, path) { return p.k === 'nil' ? p : p.k === 'obj' ? { ...p, path: [...p.path, ...path] } : { ...p, a: this.shift(p.a, path), b: this.shift(p.b, path) }; }
|
|
2350
|
+
readObj(o, path, at, p, id) {
|
|
2351
|
+
if (o.k === 'big') {
|
|
2352
|
+
if (path.length)
|
|
2353
|
+
refuse(at, 'a field of a big.Int');
|
|
2354
|
+
return refuse(at, 'a big.Int read as a value (it is used through its pointer)');
|
|
2355
|
+
}
|
|
2356
|
+
if (o.k !== 'rec')
|
|
2357
|
+
return refuse(at, 'a field of other than a struct');
|
|
2358
|
+
let v = { t: 'struct', ty: o.ty, f: o.f };
|
|
2359
|
+
for (const seg of path) {
|
|
2360
|
+
if (v.t !== 'struct')
|
|
2361
|
+
return refuse(at, `.${seg} of other than a struct`);
|
|
2362
|
+
v = v.f.get(seg) ?? this.lazyFieldIn(id, seg, p, at);
|
|
2363
|
+
}
|
|
2364
|
+
return v;
|
|
2365
|
+
}
|
|
2366
|
+
writeObj(o, path, x, at) {
|
|
2367
|
+
if (o.k !== 'rec')
|
|
2368
|
+
return refuse(at, 'a write into other than a struct');
|
|
2369
|
+
if (!path.length) {
|
|
2370
|
+
if (x.t !== 'struct')
|
|
2371
|
+
return refuse(at, 'a struct set to other than a struct');
|
|
2372
|
+
return { ...o, f: new Map(x.f) };
|
|
2373
|
+
}
|
|
2374
|
+
const set = (fs, segs) => {
|
|
2375
|
+
const seg = segs[0], rest = segs.slice(1), out = new Map(fs);
|
|
2376
|
+
if (!rest.length) {
|
|
2377
|
+
const old = fs.get(seg);
|
|
2378
|
+
if (old?.t === 'opaque')
|
|
2379
|
+
refuse(at, `writes ${old.why}`);
|
|
2380
|
+
out.set(seg, x);
|
|
2381
|
+
return out;
|
|
2382
|
+
}
|
|
2383
|
+
const inner = fs.get(seg);
|
|
2384
|
+
if (inner?.t !== 'struct')
|
|
2385
|
+
return refuse(at, `.${seg} of other than a struct`);
|
|
2386
|
+
out.set(seg, { ...inner, f: set(inner.f, rest) });
|
|
2387
|
+
return out;
|
|
2388
|
+
};
|
|
2389
|
+
return { ...o, f: set(o.f, path) };
|
|
2390
|
+
}
|
|
2391
|
+
// A field of a record the caller gives, made an input where it is first read (by the reader's recipe for it).
|
|
2392
|
+
lazyFieldIn(id, f, p, at) {
|
|
2393
|
+
const li = this.lazyIn.get(id), r = li?.recipes[f];
|
|
2394
|
+
if (!li || !r)
|
|
2395
|
+
return refuse(at, `no field ${f}`);
|
|
2396
|
+
if (r.k === 'no')
|
|
2397
|
+
return refuse(at, r.why);
|
|
2398
|
+
let g;
|
|
2399
|
+
if (r.k === 'big') {
|
|
2400
|
+
const v = this.newVar(`${li.id}_${f}`, { k: 'num' }, 'input', 'a *big.Int argument (not nil: the claim is for calls that give one)');
|
|
2401
|
+
li.fields.push([f, v.name]);
|
|
2402
|
+
p.heap.set(`in:${v.name}`, { k: 'big', v: I.nvar(v.name), origin: 'input' });
|
|
2403
|
+
g = { t: 'ptr', to: { k: 'obj', id: `in:${v.name}`, path: [] } };
|
|
2404
|
+
}
|
|
2405
|
+
else {
|
|
2406
|
+
const v = this.newVar(`${li.id}_${f}`, { k: r.k }, 'input');
|
|
2407
|
+
li.fields.push([f, v.name]);
|
|
2408
|
+
g = this.valueOfIn(v, r.ty, li.sel);
|
|
2409
|
+
}
|
|
2410
|
+
;
|
|
2411
|
+
p.heap.get(id).f.set(f, g);
|
|
2412
|
+
return g;
|
|
2413
|
+
}
|
|
2414
|
+
// An input's value, its type's range kept (a request outside it refused where sel holds: the claim is for its values).
|
|
2415
|
+
valueOfIn(v, ty, sel) {
|
|
2416
|
+
if (ty)
|
|
2417
|
+
this.typed(v, ty, 'input', sel);
|
|
2418
|
+
return v.sort.k === 'num' ? { t: 'num', e: I.nvar(v.name), ty: ty ?? { bits: 64, signed: true } } : this.valueOf(v);
|
|
2419
|
+
}
|
|
2420
|
+
// *x read: by cases on the objects x may point to; nil fails.
|
|
2421
|
+
deref(v, path, at, p) {
|
|
2422
|
+
if (v.t === 'nil') {
|
|
2423
|
+
this.refuseWhere(p, I.T, at, 'a nil dereference');
|
|
2424
|
+
return [{ t: 'opaque', why: 'unreachable', firm: true }, { ...p, pc: [...p.pc, I.F] }];
|
|
2425
|
+
}
|
|
2426
|
+
if (v.t !== 'ptr')
|
|
2427
|
+
return refuse(at, `a dereference of a ${v.t}`);
|
|
2428
|
+
const [cs, q] = this.nonNil(v.to, at, p, `a nil dereference (${at.p})`);
|
|
2429
|
+
if (!cs.objs.length)
|
|
2430
|
+
return [{ t: 'opaque', why: 'unreachable', firm: true }, q];
|
|
2431
|
+
let out;
|
|
2432
|
+
for (const o of [...cs.objs].reverse()) {
|
|
2433
|
+
const x = this.readObj(q.heap.get(o.id), [...o.path, ...path], at, q, o.id);
|
|
2434
|
+
out = out ? this.ite(o.c, x, out, at) : x;
|
|
2435
|
+
}
|
|
2436
|
+
return [out, q];
|
|
2437
|
+
}
|
|
2438
|
+
// A write through a pointer: to each object it may be, where it is that one.
|
|
2439
|
+
writeThrough(v, path, x, at, p) {
|
|
2440
|
+
if (v.t !== 'ptr')
|
|
2441
|
+
return refuse(at, `a write through a ${v.t}`);
|
|
2442
|
+
const [cs, q] = this.nonNil(v.to, at, p, 'a nil dereference'), heap = new Map(q.heap);
|
|
2443
|
+
for (const o of cs.objs) {
|
|
2444
|
+
const obj = heap.get(o.id), pa = [...o.path, ...path];
|
|
2445
|
+
heap.set(o.id, this.writeObj(obj, pa, this.ite(o.c, x, this.readObj(obj, pa, at, q, o.id), at), at));
|
|
2446
|
+
}
|
|
2447
|
+
return { ...q, heap };
|
|
2448
|
+
}
|
|
2449
|
+
// A place: a local (and a path into its record), or a path inside the object a pointer is.
|
|
2450
|
+
place(x, p) {
|
|
2451
|
+
switch (x.e) {
|
|
2452
|
+
case 'blank': return [{ k: 'blank' }, p];
|
|
2453
|
+
case 'var': return [{ k: 'local', id: String(x.n), path: [] }, p];
|
|
2454
|
+
case 'deref': {
|
|
2455
|
+
const [v, q] = this.ev(x.x, p);
|
|
2456
|
+
return [{ k: 'heap', ptr: v, path: [] }, q];
|
|
2457
|
+
}
|
|
2458
|
+
case 'fld': {
|
|
2459
|
+
const [b, q] = this.place(x.x, p);
|
|
2460
|
+
if (b.k === 'blank')
|
|
2461
|
+
return refuse(x, 'a field of _');
|
|
2462
|
+
return [{ ...b, path: [...b.path, String(x.f)] }, q];
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
return refuse(x, x.why ?? `${x.text}: an assignment to other than a variable, a field or *p`);
|
|
2466
|
+
}
|
|
2467
|
+
read(pl, at, p) {
|
|
2468
|
+
if (pl.k === 'blank')
|
|
2469
|
+
return refuse(at, '_ read');
|
|
2470
|
+
if (pl.k === 'heap')
|
|
2471
|
+
return this.deref(pl.ptr, pl.path, at, p);
|
|
2472
|
+
let v = p.locals.get(pl.id) ?? refuse(at, `${at.text ?? ''}: a variable read before it is set`);
|
|
2473
|
+
for (const s of pl.path) {
|
|
2474
|
+
if (v.t !== 'struct')
|
|
2475
|
+
refuse(at, `.${s} of other than a struct`);
|
|
2476
|
+
v = v.f.get(s) ?? refuse(at, `no field ${s}`);
|
|
2477
|
+
}
|
|
2478
|
+
return [v, p];
|
|
2479
|
+
}
|
|
2480
|
+
write(pl, x, at, p) {
|
|
2481
|
+
if (pl.k === 'blank')
|
|
2482
|
+
return p;
|
|
2483
|
+
this.secondName(x, at);
|
|
2484
|
+
if (pl.k === 'heap') {
|
|
2485
|
+
this.keepsInState(pl, x, at, p);
|
|
2486
|
+
return this.writeThrough(pl.ptr, pl.path, x, at, p);
|
|
2487
|
+
}
|
|
2488
|
+
if (!pl.path.length)
|
|
2489
|
+
return { ...p, locals: new Map(p.locals).set(pl.id, x) };
|
|
2490
|
+
const set = (v, segs) => {
|
|
2491
|
+
const s = segs[0], rest = segs.slice(1);
|
|
2492
|
+
if (v.t !== 'struct')
|
|
2493
|
+
return refuse(at, `.${s} of other than a struct`);
|
|
2494
|
+
return { ...v, f: new Map(v.f).set(s, rest.length ? set(v.f.get(s), rest) : x) };
|
|
2495
|
+
};
|
|
2496
|
+
return { ...p, locals: new Map(p.locals).set(pl.id, set(p.locals.get(pl.id) ?? refuse(at, 'a field of a variable not set'), pl.path)) };
|
|
2497
|
+
}
|
|
2498
|
+
// A list or a map under a second name: refused (two slices may share a backing array; a map is a reference).
|
|
2499
|
+
secondName(x, at) {
|
|
2500
|
+
if (x.t === 'list')
|
|
2501
|
+
refuse(at, 'a slice given a second name (two slices may share a backing array: append writes into it or not by its capacity)');
|
|
2502
|
+
if (x.t === 'map')
|
|
2503
|
+
refuse(at, 'a map given a second name (a map is a reference: a write through either is a write to both)');
|
|
2504
|
+
}
|
|
2505
|
+
// A pointer stored into the state: to a fresh object only (one the state holds would be in two places; one the
|
|
2506
|
+
// caller gave the caller's to change after the call).
|
|
2507
|
+
keepsInState(pl, x, at, p) {
|
|
2508
|
+
if (x.t !== 'ptr')
|
|
2509
|
+
return;
|
|
2510
|
+
const into = this.cases(pl.ptr.t === 'ptr' ? pl.ptr.to : { k: 'nil' });
|
|
2511
|
+
if (!into.objs.some(o => p.heap.get(o.id)?.origin === 'state'))
|
|
2512
|
+
return;
|
|
2513
|
+
for (const o of this.cases(x.to).objs) {
|
|
2514
|
+
const origin = p.heap.get(o.id)?.origin;
|
|
2515
|
+
if (origin === 'input')
|
|
2516
|
+
refuse(at, 'the state keeps a pointer the caller gave (the caller may change its object after the call)');
|
|
2517
|
+
if (origin === 'state')
|
|
2518
|
+
refuse(at, `the state's ${this.stateOrigin.get(o.id) ?? 'object'} put in a second place of the state (one object in two places)`);
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
bindLocal(id, v, at, p) {
|
|
2522
|
+
if (v.t === 'list' || v.t === 'map' || v.t === 'push' || v.t === 'pop')
|
|
2523
|
+
this.secondName(v.t === 'push' || v.t === 'pop' ? { t: 'list', id: v.id } : v, at);
|
|
2524
|
+
if (v.t === 'num' && v.slen)
|
|
2525
|
+
refuse(at, 'len of a string kept (it is read only against 0)');
|
|
2526
|
+
return { ...p, locals: new Map(p.locals).set(id, v) };
|
|
2527
|
+
}
|
|
2528
|
+
numv(v, at) {
|
|
2529
|
+
if (v.t !== 'num')
|
|
2530
|
+
return refuse(at, `${at.text ?? ''}: a ${v.t} where a number is read`);
|
|
2531
|
+
if (v.slen)
|
|
2532
|
+
return refuse(at, 'len of a string read other than against 0 (strings are set and compared in the subset)');
|
|
2533
|
+
return v.e;
|
|
2534
|
+
}
|
|
2535
|
+
boolv(v, at) { if (v.t !== 'bool')
|
|
2536
|
+
return refuse(at, `${at.text ?? ''}: a ${v.t} where a condition is read`); return v.e; }
|
|
2537
|
+
// A binary operation of the reader's language with fixed-width integers (Go's): comparisons, arithmetic wrapped.
|
|
2538
|
+
binop(op, a, b, x, p) {
|
|
2539
|
+
if (op === '==' || op === '!=') {
|
|
2540
|
+
const e = this.eq(a, b, x, p);
|
|
2541
|
+
return { t: 'bool', e: op === '==' ? e : I.not(e) };
|
|
2542
|
+
}
|
|
2543
|
+
// len(s) of a string against 0: whether it is empty.
|
|
2544
|
+
const sl = (v, k) => (v.t === 'num' && v.slen && k.t === 'num' && !k.slen && k.e.op === 'const' && k.e.v === 0 ? v.slen : undefined);
|
|
2545
|
+
const flip = { '<': '>', '<=': '>=', '>': '<', '>=': '<=' };
|
|
2546
|
+
if (['<', '<=', '>', '>='].includes(op) && (sl(a, b) || sl(b, a))) {
|
|
2547
|
+
const s = (sl(a, b) ?? sl(b, a)), empty = I.keq(s, { op: 'slit', value: '' }), o = sl(a, b) ? op : flip[op];
|
|
2548
|
+
return { t: 'bool', e: o === '<=' ? empty : o === '>' ? I.not(empty) : o === '>=' ? I.T : I.F };
|
|
2549
|
+
}
|
|
2550
|
+
if (['<', '<=', '>', '>='].includes(op)) {
|
|
2551
|
+
if (a.t === 'str' || b.t === 'str')
|
|
2552
|
+
return refuse(x, 'strings ordered (strings are set and compared in the subset)');
|
|
2553
|
+
// x.Cmp(y) against 0, read as the comparison of x and y.
|
|
2554
|
+
const cmpOf = (v, k) => (v.t === 'num' && v.cmp && k.t === 'num' && k.e.op === 'const' && k.e.v === 0 ? v.cmp : undefined);
|
|
2555
|
+
const ca = cmpOf(a, b), cb = cmpOf(b, a);
|
|
2556
|
+
let l, r, o = op;
|
|
2557
|
+
if (ca)
|
|
2558
|
+
[l, r] = ca;
|
|
2559
|
+
else if (cb) {
|
|
2560
|
+
[l, r] = cb;
|
|
2561
|
+
o = flip[op];
|
|
2562
|
+
}
|
|
2563
|
+
else {
|
|
2564
|
+
l = this.numv(a, x);
|
|
2565
|
+
r = this.numv(b, x);
|
|
2566
|
+
}
|
|
2567
|
+
return { t: 'bool', e: o === '<' ? I.cmp('<', l, r) : o === '<=' ? I.cmp('<=', l, r) : o === '>' ? I.cmp('<', r, l) : I.cmp('<=', r, l) };
|
|
2568
|
+
}
|
|
2569
|
+
if (['+', '-', '*', '/', '%', '<<', '>>'].includes(op)) {
|
|
2570
|
+
if (a.t === 'str')
|
|
2571
|
+
return refuse(x, 'strings joined (strings are set and compared in the subset)');
|
|
2572
|
+
return this.arith(op, a, b, x, p);
|
|
2573
|
+
}
|
|
2574
|
+
return refuse(x, `${op}: a bit operation (outside the subset)`);
|
|
2575
|
+
}
|
|
2576
|
+
eq(a, b, x, p) {
|
|
2577
|
+
if (a.t === 'map' && b.t === 'nil' && p)
|
|
2578
|
+
return this.mapAt(a, x, p).nil;
|
|
2579
|
+
if (a.t === 'nil' && b.t === 'map' && p)
|
|
2580
|
+
return this.mapAt(b, x, p).nil;
|
|
2581
|
+
if (a.t === 'num' && b.t === 'num')
|
|
2582
|
+
return I.cmp('=', this.numv(a, x), this.numv(b, x));
|
|
2583
|
+
if (a.t === 'bool' && b.t === 'bool')
|
|
2584
|
+
return I.or(I.and(a.e, b.e), I.and(I.not(a.e), I.not(b.e)));
|
|
2585
|
+
if (a.t === 'str' && b.t === 'str')
|
|
2586
|
+
return I.keq(a.e, b.e);
|
|
2587
|
+
if (a.t === 'err' && b.t === 'nil')
|
|
2588
|
+
return I.not(a.is);
|
|
2589
|
+
if (a.t === 'nil' && b.t === 'err')
|
|
2590
|
+
return I.not(b.is);
|
|
2591
|
+
if (a.t === 'err' && b.t === 'err')
|
|
2592
|
+
return refuse(x, 'two errors compared (an error is nil or not in the subset)');
|
|
2593
|
+
if ((a.t === 'ptr' || a.t === 'nil') && (b.t === 'ptr' || b.t === 'nil')) {
|
|
2594
|
+
if (a.t === 'nil' && b.t === 'nil')
|
|
2595
|
+
return I.T;
|
|
2596
|
+
if (b.t === 'nil')
|
|
2597
|
+
return this.cases(a.to).nil;
|
|
2598
|
+
if (a.t === 'nil')
|
|
2599
|
+
return this.cases(b.to).nil;
|
|
2600
|
+
// Two pointers: the same object (and place), or both nil.
|
|
2601
|
+
const ca = this.cases(a.to), cb = this.cases(b.to);
|
|
2602
|
+
return I.or(I.and(ca.nil, cb.nil), ...ca.objs.flatMap(o => cb.objs.filter(q => q.id === o.id && q.path.join() === o.path.join()).map(q => I.and(o.c, q.c))));
|
|
2603
|
+
}
|
|
2604
|
+
if ((a.t === 'list' || a.t === 'map') && b.t === 'nil')
|
|
2605
|
+
return refuse(x, `a ${a.t === 'list' ? 'slice' : 'map'} compared with nil (nil and empty are one ${a.t === 'list' ? 'list' : 'map'} in the subset)`);
|
|
2606
|
+
return refuse(x, `${a.t === 'opaque' && a.ask ? a.why : `a ${a.t}`} compared with a ${b.t}`);
|
|
2607
|
+
}
|
|
2608
|
+
// Integer arithmetic at the type's width: the exact result, wrapped as the type wraps it (or refused, at 64 bits).
|
|
2609
|
+
arith(op, a, b, x, p) {
|
|
2610
|
+
if (a.t !== 'num' || b.t !== 'num')
|
|
2611
|
+
return refuse(x, `${op} of a ${a.t} and a ${b.t}`);
|
|
2612
|
+
this.numv(a, x);
|
|
2613
|
+
this.numv(b, x);
|
|
2614
|
+
const ty = a.ty?.name !== undefined ? a.ty : b.ty;
|
|
2615
|
+
let e;
|
|
2616
|
+
switch (op) {
|
|
2617
|
+
case '+':
|
|
2618
|
+
e = I.add(a.e, b.e);
|
|
2619
|
+
break;
|
|
2620
|
+
case '-':
|
|
2621
|
+
e = I.sub(a.e, b.e);
|
|
2622
|
+
break;
|
|
2623
|
+
case '*':
|
|
2624
|
+
e = I.mul(a.e, b.e);
|
|
2625
|
+
break;
|
|
2626
|
+
case '/':
|
|
2627
|
+
case '%': {
|
|
2628
|
+
if (b.e.op !== 'const')
|
|
2629
|
+
return refuse(x, `${op} by other than a constant`);
|
|
2630
|
+
if (b.e.v === 0) {
|
|
2631
|
+
this.refuseWhere(p, I.T, x, 'a division by zero');
|
|
2632
|
+
return { t: 'num', e: I.num(0), ty };
|
|
2633
|
+
}
|
|
2634
|
+
const k = Math.abs(b.e.v), q = this.quot(a.e, k);
|
|
2635
|
+
e = op === '/' ? (b.e.v < 0 ? I.neg(q) : q) : this.rem(a.e, k);
|
|
2636
|
+
break;
|
|
2637
|
+
}
|
|
2638
|
+
case '>>':
|
|
2639
|
+
if (b.e.op !== 'const' || b.e.v < 0)
|
|
2640
|
+
return refuse(x, '>> by other than a constant');
|
|
2641
|
+
if (b.e.v >= 53)
|
|
2642
|
+
return refuse(x, `>> ${b.e.v} (past the rule's 2^53)`);
|
|
2643
|
+
e = I.divk(2 ** b.e.v, a.e);
|
|
2644
|
+
break;
|
|
2645
|
+
case '<<':
|
|
2646
|
+
if (b.e.op !== 'const' || b.e.v < 0)
|
|
2647
|
+
return refuse(x, '<< by other than a constant');
|
|
2648
|
+
if (b.e.v >= 53)
|
|
2649
|
+
return refuse(x, `<< ${b.e.v} (past the rule's 2^53)`);
|
|
2650
|
+
if (ty.ub)
|
|
2651
|
+
this.refuseWhere(p, I.cmp('<', a.e, I.num(0)), x, `${x.text ? `${x.text}: ` : ''}a negative value shifted left (undefined behavior)`);
|
|
2652
|
+
e = I.mulk(2 ** b.e.v, a.e);
|
|
2653
|
+
break;
|
|
2654
|
+
default: return refuse(x, `${op}: outside the subset`);
|
|
2655
|
+
}
|
|
2656
|
+
return { t: 'num', e: this.wrap(e, ty, x, p), ty };
|
|
2657
|
+
}
|
|
2658
|
+
// a / k and a % k truncated toward zero (the remainder takes the dividend's sign), for a constant k > 0: one case
|
|
2659
|
+
// where a's bounds say it is at least 0.
|
|
2660
|
+
quot(a, k) { return this.bounds(a)[0] >= 0 ? I.divk(k, a) : I.nite(I.cmp('<=', I.num(0), a), I.divk(k, a), I.neg(I.divk(k, I.neg(a)))); }
|
|
2661
|
+
// (0 − r, not −r: the printer's remainder is a natural's, which Int subtracts from)
|
|
2662
|
+
rem(a, k) { return this.bounds(a)[0] >= 0 ? I.modk(k, a) : I.nite(I.cmp('<=', I.num(0), a), I.modk(k, a), I.sub(I.num(0), I.modk(k, I.neg(a)))); }
|
|
2663
|
+
// The bounds a term's value is within, from its variables' types (a cell's too) and its constants.
|
|
2664
|
+
bounds(e) {
|
|
2665
|
+
const r = (n) => { const ty = this.ints.get(n); return ty ? rangeOf(ty) : [-Infinity, Infinity]; };
|
|
2666
|
+
switch (e.op) {
|
|
2667
|
+
case 'const': return [e.v, e.v];
|
|
2668
|
+
case 'var': return r(e.name);
|
|
2669
|
+
case 'cell': return r(`${e.map}.${e.field}`);
|
|
2670
|
+
case 'add': {
|
|
2671
|
+
const a = this.bounds(e.a), b = this.bounds(e.b);
|
|
2672
|
+
return [a[0] + b[0], a[1] + b[1]];
|
|
2673
|
+
}
|
|
2674
|
+
case 'sub': {
|
|
2675
|
+
const a = this.bounds(e.a), b = this.bounds(e.b);
|
|
2676
|
+
return [a[0] - b[1], a[1] - b[0]];
|
|
2677
|
+
}
|
|
2678
|
+
case 'neg': {
|
|
2679
|
+
const a = this.bounds(e.a);
|
|
2680
|
+
return [-a[1], -a[0]];
|
|
2681
|
+
}
|
|
2682
|
+
case 'mulk': {
|
|
2683
|
+
const a = this.bounds(e.a);
|
|
2684
|
+
return e.k >= 0 ? [e.k * a[0], e.k * a[1]] : [e.k * a[1], e.k * a[0]];
|
|
2685
|
+
}
|
|
2686
|
+
case 'mul': {
|
|
2687
|
+
const a = this.bounds(e.a), b = this.bounds(e.b), xs = [a[0] * b[0], a[0] * b[1], a[1] * b[0], a[1] * b[1]].map(v => (Number.isNaN(v) ? 0 : v));
|
|
2688
|
+
return [Math.min(...xs), Math.max(...xs)];
|
|
2689
|
+
}
|
|
2690
|
+
case 'min': {
|
|
2691
|
+
const a = this.bounds(e.a), b = this.bounds(e.b);
|
|
2692
|
+
return [Math.min(a[0], b[0]), Math.min(a[1], b[1])];
|
|
2693
|
+
}
|
|
2694
|
+
case 'max': {
|
|
2695
|
+
const a = this.bounds(e.a), b = this.bounds(e.b);
|
|
2696
|
+
return [Math.max(a[0], b[0]), Math.max(a[1], b[1])];
|
|
2697
|
+
}
|
|
2698
|
+
case 'divk': {
|
|
2699
|
+
const a = this.bounds(e.a);
|
|
2700
|
+
return [Math.floor(a[0] / e.k), Math.floor(a[1] / e.k)];
|
|
2701
|
+
}
|
|
2702
|
+
case 'modk': return [0, e.k - 1];
|
|
2703
|
+
case 'ite': {
|
|
2704
|
+
const a = this.bounds(e.a), b = this.bounds(e.b);
|
|
2705
|
+
return [Math.min(a[0], b[0]), Math.max(a[1], b[1])];
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
// A result past its type's range: at 8, 16 and 32 bits modulo 2^n by cases (none where the bounds of the term or the
|
|
2710
|
+
// path's facts keep it within); at 64 bits the rule's numbers stop at ±2^53, and an unsigned one below 0 is refused.
|
|
2711
|
+
wrap(e, ty, x, p) {
|
|
2712
|
+
if (ty.bits === 0)
|
|
2713
|
+
return e;
|
|
2714
|
+
if (ty.ub) {
|
|
2715
|
+
const out = I.or(...this.past(e, ...rangeOf(ty), p));
|
|
2716
|
+
if (!(out.op === 'const' && !out.v)) {
|
|
2717
|
+
this.refuseWhere(p, out, x, `${x.text ? `${x.text}: ` : ''}past ${ty.name ?? tyName(ty)}'s range (signed overflow: undefined behavior)`);
|
|
2718
|
+
this.notes.add(`${ty.name ?? tyName(ty)}: a result past its range is refused (signed overflow is undefined behavior in ${LANG[this.mod.lang] ?? this.mod.lang})`);
|
|
2719
|
+
}
|
|
2720
|
+
return e;
|
|
2721
|
+
}
|
|
2722
|
+
const [lo, hi] = rangeOf(ty), [blo0, bhi0] = this.bounds(e);
|
|
2723
|
+
if (blo0 >= lo && bhi0 <= hi)
|
|
2724
|
+
return e;
|
|
2725
|
+
const blo = blo0 >= lo || this.within(e, lo, 'lo', p) ? Math.max(blo0, lo) : blo0, bhi = bhi0 <= hi || this.within(e, hi, 'hi', p) ? Math.min(bhi0, hi) : bhi0;
|
|
2726
|
+
if (blo >= lo && bhi <= hi)
|
|
2727
|
+
return e;
|
|
2728
|
+
const name = ty.name ?? tyName(ty), lang = LANG[this.mod.lang] ?? this.mod.lang;
|
|
2729
|
+
if (ty.bits >= 64) {
|
|
2730
|
+
if (!ty.signed && blo < 0) {
|
|
2731
|
+
this.refuseWhere(p, I.cmp('<', e, I.num(0)), x, `a ${name} below 0 (${lang} wraps it to 2^64 − x, past the rule's numbers)`, false);
|
|
2732
|
+
this.notes.add(`${name}: a result below 0 is refused (${lang} would wrap it past 2^53)`);
|
|
2733
|
+
}
|
|
2734
|
+
return e;
|
|
2735
|
+
}
|
|
2736
|
+
const m = 2 ** ty.bits, k0 = Math.floor((blo - lo) / m), k1 = Math.floor((bhi - lo) / m);
|
|
2737
|
+
this.notes.add(`${name}: a result past its range wraps modulo 2^${ty.bits}, as ${lang}'s does`);
|
|
2738
|
+
if (Number.isFinite(k0) && Number.isFinite(k1) && k1 - k0 <= 3) {
|
|
2739
|
+
// By cases from the bottom: e at least lo + k·2^n takes e − k·2^n.
|
|
2740
|
+
const less = (k) => (k >= 0 ? I.sub(e, I.num(k * m)) : I.add(e, I.num(-k * m)));
|
|
2741
|
+
let acc = less(k0);
|
|
2742
|
+
for (let k = k0 + 1; k <= k1; k++)
|
|
2743
|
+
acc = I.nite(I.cmp('<=', I.num(lo + k * m), e), less(k), acc);
|
|
2744
|
+
return acc;
|
|
2745
|
+
}
|
|
2746
|
+
// Many times over (a conversion from a wider type, a product): e − 2^n·⌊(e − lo)/2^n⌋.
|
|
2747
|
+
return I.sub(e, I.mulk(m, I.divk(m, I.add(e, I.num(-lo)))));
|
|
2748
|
+
}
|
|
2749
|
+
// Where e may be past [lo, hi] on the path: below and above, each false where the term's bounds or the path's facts
|
|
2750
|
+
// keep it within.
|
|
2751
|
+
past(e, lo, hi, p) {
|
|
2752
|
+
const [blo, bhi] = this.bounds(e);
|
|
2753
|
+
return [!Number.isFinite(lo) || blo >= lo || this.within(e, lo, 'lo', p) ? I.F : I.cmp('<', e, I.num(lo)), !Number.isFinite(hi) || bhi <= hi || this.within(e, hi, 'hi', p) ? I.F : I.cmp('<', I.num(hi), e)];
|
|
2754
|
+
}
|
|
2755
|
+
// Whether e is at least lo (or at most hi) on the path: its conditions and its variables' ranges as facts.
|
|
2756
|
+
within(e, b, side, p) {
|
|
2757
|
+
if (!Number.isFinite(b))
|
|
2758
|
+
return false;
|
|
2759
|
+
const facts = [...p.pc];
|
|
2760
|
+
for (const n of I.varsOf(e).vars) {
|
|
2761
|
+
const ty = this.ints.get(n);
|
|
2762
|
+
if (ty) {
|
|
2763
|
+
const r = rangeOf(ty);
|
|
2764
|
+
if (Number.isFinite(r[0]))
|
|
2765
|
+
facts.push(I.cmp('<=', I.num(r[0]), I.nvar(n)));
|
|
2766
|
+
if (Number.isFinite(r[1]))
|
|
2767
|
+
facts.push(I.cmp('<=', I.nvar(n), I.num(r[1])));
|
|
2768
|
+
}
|
|
2769
|
+
}
|
|
2770
|
+
return nonneg(side === 'lo' ? I.sub(e, I.num(b)) : I.sub(I.num(b), e), { m: { refuse: I.F, pre: I.T }, sorts: new Map(), atoms: facts });
|
|
2771
|
+
}
|
|
2772
|
+
// --- maps with a nil state, lists, big integers, locks --------------------------------------------------------------
|
|
2773
|
+
mapAt(m, at, p) {
|
|
2774
|
+
if (m.t !== 'map' || !p.heap.has(m.id))
|
|
2775
|
+
return refuse(at, `${at.text}: a map other than the state's`);
|
|
2776
|
+
return p.heap.get(m.id);
|
|
2777
|
+
}
|
|
2778
|
+
mkey(k, d, at) {
|
|
2779
|
+
if (d.key === 'num') {
|
|
2780
|
+
if (k.t !== 'num')
|
|
2781
|
+
refuse(at, 'a map key of the wrong kind');
|
|
2782
|
+
return { op: 'num', e: k.e };
|
|
2783
|
+
}
|
|
2784
|
+
if (k.t !== 'str')
|
|
2785
|
+
return refuse(at, 'a map key of the wrong kind');
|
|
2786
|
+
return k.e;
|
|
2787
|
+
}
|
|
2788
|
+
// A map's value at a key: its type's zero where the map doesn't hold it.
|
|
2789
|
+
mapRead(m, k, at, p) {
|
|
2790
|
+
const o = this.mapAt(m, at, p), cell = this.cellOf(o, this.mkey(k, o.decl, at), p, at), tys = at.tys;
|
|
2791
|
+
const vals = new Map([...cell.vals].map(([f, v]) => {
|
|
2792
|
+
const it = tys[f], typed = v.t === 'num' && it ? { ...v, ty: it } : v;
|
|
2793
|
+
return [f, this.ite(cell.has, typed, typed.t === 'num' ? { ...typed, e: I.num(0) } : typed.t === 'bool' ? { t: 'bool', e: I.F } : typed, at)];
|
|
2794
|
+
}));
|
|
2795
|
+
return { v: o.decl.scalar ? vals.get('value') : { t: 'struct', ty: String(at.sty), f: new Map(vals) }, has: cell.has };
|
|
2796
|
+
}
|
|
2797
|
+
mapWrite(m, k, v, at, p) {
|
|
2798
|
+
const o = this.mapAt(m, at, p), key = this.mkey(k, o.decl, at);
|
|
2799
|
+
if (o.origin !== 'state')
|
|
2800
|
+
return refuse(at, 'a write to a map other than the state\'s');
|
|
2801
|
+
this.refuseWhere(p, o.nil, at, 'a write to a nil map (a panic)');
|
|
2802
|
+
const q = this.assume(p, I.not(o.nil));
|
|
2803
|
+
if (o.w && !I.same(o.w.key, key))
|
|
2804
|
+
return refuse(at, `writes ${o.decl.name} at a second key in one step`);
|
|
2805
|
+
const vals = new Map(o.decl.scalar ? [['value', v]] : o.decl.fields.map(f => [f.name, v.f?.get(f.name) ?? refuse(at, 'a map value of the wrong kind')]));
|
|
2806
|
+
return { ...q, heap: new Map(q.heap).set(m.id, { ...o, w: { key, has: I.T, vals } }) };
|
|
2807
|
+
}
|
|
2808
|
+
mapDelete(m, k, at, p) {
|
|
2809
|
+
const o = this.mapAt(m, at, p), key = this.mkey(k, o.decl, at);
|
|
2810
|
+
if (o.w && !I.same(o.w.key, key))
|
|
2811
|
+
return refuse(at, `writes ${o.decl.name} at a second key in one step`);
|
|
2812
|
+
const vals = new Map(o.decl.fields.map(f => [f.name, f.sort.k === 'num' ? { t: 'num', e: I.num(0), ty: { bits: 64, signed: true } } : { t: 'bool', e: I.F }]));
|
|
2813
|
+
return { ...p, heap: new Map(p.heap).set(m.id, { ...o, w: { key, has: I.F, vals } }) };
|
|
2814
|
+
}
|
|
2815
|
+
// A map field set to a new empty map where it is nil (the lazy start Go code makes): its nil flag cleared.
|
|
2816
|
+
mapAssign(x, v, p) {
|
|
2817
|
+
if (v.t !== 'map' || v.id !== 'new-map')
|
|
2818
|
+
return refuse(x, 'a map given a second name (a map is a reference: a write through either is a write to both)');
|
|
2819
|
+
const [pl, q] = this.place(x, p);
|
|
2820
|
+
if (pl.k === 'blank')
|
|
2821
|
+
return q;
|
|
2822
|
+
const [cur, q2] = this.read(pl, x, q);
|
|
2823
|
+
if (cur.t !== 'map')
|
|
2824
|
+
return refuse(x, 'a new map kept other than in a map field of the state');
|
|
2825
|
+
const o = this.mapAt(cur, x, q2), nil = o.nil;
|
|
2826
|
+
if (!(nil.op === 'const' && nil.v) && !q2.pc.some(c => I.same(c, nil)))
|
|
2827
|
+
return refuse(x, `${o.decl.name} replaced whole (the subset sets a map once, where it is nil)`);
|
|
2828
|
+
return { ...q2, heap: new Map(q2.heap).set(cur.id, { ...o, nil: I.F }) };
|
|
2829
|
+
}
|
|
2830
|
+
listObj(s, at, p) {
|
|
2831
|
+
if (s.t !== 'list' || !p.heap.has(s.id))
|
|
2832
|
+
return refuse(at, `${at.text}: a slice other than the state's`);
|
|
2833
|
+
return p.heap.get(s.id);
|
|
2834
|
+
}
|
|
2835
|
+
listLen(s, at, p) {
|
|
2836
|
+
const o = this.listObj(s, at, p);
|
|
2837
|
+
if (o.ops.length)
|
|
2838
|
+
return refuse(at, `${o.decl.name} read after it is written in one step`);
|
|
2839
|
+
return o.decl.len !== undefined ? I.num(o.decl.len) : I.nvar(`${o.decl.name}_len`);
|
|
2840
|
+
}
|
|
2841
|
+
inside(s, i, at, p) {
|
|
2842
|
+
const o = this.listObj(s, at, p), idx = this.numv(i, at), len = this.listLen(s, at, p), inside = I.and(I.cmp('<=', I.num(0), idx), I.cmp('<', idx, len));
|
|
2843
|
+
this.refuseWhere(p, I.not(inside), at, o.decl.len !== undefined ? `an index outside [0, ${o.decl.len}) (undefined behavior)` : 'an index out of range (a panic)');
|
|
2844
|
+
return [o, idx, inside];
|
|
2845
|
+
}
|
|
2846
|
+
listGet(s, i, at, p) {
|
|
2847
|
+
const [o, idx, inside] = this.inside(s, i, at, p), e = { op: 'cell', map: o.decl.name, key: { op: 'num', e: idx }, field: '$item' };
|
|
2848
|
+
return [o.decl.fields[0].sort.k === 'num' ? { t: 'num', e: e, ty: at.ty } : { t: 'bool', e: e }, this.assume(p, inside)];
|
|
2849
|
+
}
|
|
2850
|
+
listSet(s, i, v, at, p) {
|
|
2851
|
+
const [o, idx, inside] = this.inside(s, i, at, p), q = this.assume(p, inside);
|
|
2852
|
+
if (o.decl.len !== undefined && o.ops.length)
|
|
2853
|
+
return refuse(at, `a second write to ${o.decl.name} in one step`);
|
|
2854
|
+
return { ...q, heap: new Map(q.heap).set(s.id, { ...o, ops: [{ op: 'set', i: idx, x: v, when: I.T }] }) };
|
|
2855
|
+
}
|
|
2856
|
+
// s = append(s, x) and s = s[:len(s)-1] in s's own place; any other list put there is refused.
|
|
2857
|
+
listAssign(x, v, p) {
|
|
2858
|
+
const [pl, q] = this.place(x, p);
|
|
2859
|
+
if (pl.k === 'blank')
|
|
2860
|
+
return q;
|
|
2861
|
+
const [cur, q2] = this.read(pl, x, q);
|
|
2862
|
+
if ((v.t !== 'push' && v.t !== 'pop') || cur.t !== 'list' || v.id !== cur.id)
|
|
2863
|
+
return refuse(x, 'a slice given a second name, or replaced whole (two slices may share a backing array: append writes into it or not by its capacity)');
|
|
2864
|
+
const o = this.listObj(cur, x, q2);
|
|
2865
|
+
if (o.ops.length)
|
|
2866
|
+
return refuse(x, `a second write to ${o.decl.name} in one step`);
|
|
2867
|
+
const it = o.decl.fields[0].sort.k;
|
|
2868
|
+
if (v.t === 'push' && ((it === 'num' && v.x.t !== 'num') || (it === 'bool' && v.x.t !== 'bool')))
|
|
2869
|
+
return refuse(x, 'an item of the wrong kind appended');
|
|
2870
|
+
return { ...q2, heap: new Map(q2.heap).set(cur.id, { ...o, ops: [v.t === 'push' ? { op: 'push', x: v.x, when: I.T } : { op: 'pop', when: I.T }] }) };
|
|
2871
|
+
}
|
|
2872
|
+
newBig(v, p) {
|
|
2873
|
+
const id = `new:${++this.fresh}`;
|
|
2874
|
+
return [{ t: 'ptr', to: { k: 'obj', id, path: [] } }, { ...p, heap: new Map(p.heap).set(id, { k: 'big', v, origin: 'fresh' }) }];
|
|
2875
|
+
}
|
|
2876
|
+
// A big integer's value through a pointer (by cases; nil fails).
|
|
2877
|
+
bigVal(v, at, p) {
|
|
2878
|
+
if (v.t !== 'ptr')
|
|
2879
|
+
return refuse(at, `${at.text}: a big.Int read through a ${v.t}`);
|
|
2880
|
+
const [cs, q] = this.nonNil(v.to, at, p, `a nil *big.Int (${at.text})`);
|
|
2881
|
+
let out;
|
|
2882
|
+
for (const o of [...cs.objs].reverse()) {
|
|
2883
|
+
const obj = q.heap.get(o.id);
|
|
2884
|
+
if (obj?.k !== 'big' || o.path.length)
|
|
2885
|
+
return refuse(at, 'a big.Int pointer to other than a big.Int');
|
|
2886
|
+
out = out === undefined ? obj.v : I.nite(o.c, obj.v, out);
|
|
2887
|
+
}
|
|
2888
|
+
return [out ?? I.num(0), q];
|
|
2889
|
+
}
|
|
2890
|
+
bigCall(x, p) {
|
|
2891
|
+
const n = String(x.op), zx = x.z, ax = x.args, ty = x.ty;
|
|
2892
|
+
const [z, q0] = this.ev(zx, p);
|
|
2893
|
+
const as = [];
|
|
2894
|
+
let q = q0;
|
|
2895
|
+
for (const a of ax) {
|
|
2896
|
+
const [v, q2] = this.ev(a, q);
|
|
2897
|
+
as.push(v);
|
|
2898
|
+
q = q2;
|
|
2899
|
+
}
|
|
2900
|
+
const vals = [];
|
|
2901
|
+
const ints = (k) => { for (let i = 0; i < k; i++) {
|
|
2902
|
+
const a = as[i];
|
|
2903
|
+
if (a.t === 'num')
|
|
2904
|
+
vals.push(a.e);
|
|
2905
|
+
else {
|
|
2906
|
+
const [v, q2] = this.bigVal(a, ax[i], q);
|
|
2907
|
+
vals.push(v);
|
|
2908
|
+
q = q2;
|
|
2909
|
+
}
|
|
2910
|
+
} };
|
|
2911
|
+
// z = e, z the receiver (its object written where z points), and z returned.
|
|
2912
|
+
const set = (e) => {
|
|
2913
|
+
const [, q2] = this.bigVal(z, zx, q);
|
|
2914
|
+
const heap = new Map(q2.heap);
|
|
2915
|
+
for (const o of this.cases(z.to).objs) {
|
|
2916
|
+
const obj = heap.get(o.id);
|
|
2917
|
+
heap.set(o.id, { ...obj, v: I.nite(o.c, e, obj.v) });
|
|
2918
|
+
}
|
|
2919
|
+
return [z, { ...q2, heap }];
|
|
2920
|
+
};
|
|
2921
|
+
const sign = (l, r) => I.nite(I.cmp('<', l, r), I.num(-1), I.nite(I.cmp('=', l, r), I.num(0), I.num(1)));
|
|
2922
|
+
switch (n) {
|
|
2923
|
+
case 'Add':
|
|
2924
|
+
ints(2);
|
|
2925
|
+
return set(I.add(vals[0], vals[1]));
|
|
2926
|
+
case 'Sub':
|
|
2927
|
+
ints(2);
|
|
2928
|
+
return set(I.sub(vals[0], vals[1]));
|
|
2929
|
+
case 'Mul':
|
|
2930
|
+
ints(2);
|
|
2931
|
+
return set(I.mul(vals[0], vals[1]));
|
|
2932
|
+
case 'Neg':
|
|
2933
|
+
ints(1);
|
|
2934
|
+
return set(I.neg(vals[0]));
|
|
2935
|
+
case 'Abs':
|
|
2936
|
+
ints(1);
|
|
2937
|
+
return set(I.nmax(vals[0], I.neg(vals[0])));
|
|
2938
|
+
case 'Set':
|
|
2939
|
+
ints(1);
|
|
2940
|
+
return set(vals[0]);
|
|
2941
|
+
case 'SetInt64':
|
|
2942
|
+
case 'SetUint64': return set(this.numv(as[0], x));
|
|
2943
|
+
case 'Cmp':
|
|
2944
|
+
case 'CmpAbs': {
|
|
2945
|
+
const [a, q2] = this.bigVal(z, zx, q);
|
|
2946
|
+
q = q2;
|
|
2947
|
+
ints(1);
|
|
2948
|
+
const l = n === 'Cmp' ? a : I.nmax(a, I.neg(a)), r = n === 'Cmp' ? vals[0] : I.nmax(vals[0], I.neg(vals[0]));
|
|
2949
|
+
return [{ t: 'num', e: sign(l, r), ty, cmp: [l, r] }, q];
|
|
2950
|
+
}
|
|
2951
|
+
case 'Sign': {
|
|
2952
|
+
const [a, q2] = this.bigVal(z, zx, q);
|
|
2953
|
+
return [{ t: 'num', e: sign(a, I.num(0)), ty, cmp: [a, I.num(0)] }, q2];
|
|
2954
|
+
}
|
|
2955
|
+
case 'Int64':
|
|
2956
|
+
case 'Uint64': {
|
|
2957
|
+
const [a, q2] = this.bigVal(z, zx, q);
|
|
2958
|
+
if (n === 'Uint64')
|
|
2959
|
+
this.refuseWhere(q2, I.cmp('<', a, I.num(0)), x, 'Uint64 of a big.Int below 0 (undefined: Go returns its low bits)', false);
|
|
2960
|
+
return [{ t: 'num', e: a, ty }, q2];
|
|
2961
|
+
}
|
|
2962
|
+
case 'IsInt64': {
|
|
2963
|
+
const [, q2] = this.bigVal(z, zx, q);
|
|
2964
|
+
return [{ t: 'bool', e: I.T }, q2];
|
|
2965
|
+
}
|
|
2966
|
+
case 'String': return refuse(x, 'a big.Int as a string (outside an error\'s text)');
|
|
2967
|
+
}
|
|
2968
|
+
return refuse(x, `${x.text}: big.Int's ${n} (outside the subset)`);
|
|
2969
|
+
}
|
|
2970
|
+
// A lock's key: the place it is (of the object, or a local).
|
|
2971
|
+
lockKey(x, p) {
|
|
2972
|
+
const [pl] = this.place(x, p);
|
|
2973
|
+
if (pl.k === 'local')
|
|
2974
|
+
return `local:${pl.id}.${pl.path.join('.')}`;
|
|
2975
|
+
if (pl.k === 'heap' && pl.ptr.t === 'ptr' && pl.ptr.to.k === 'obj')
|
|
2976
|
+
return `${pl.ptr.to.id}.${[...pl.ptr.to.path, ...pl.path].join('.')}`;
|
|
2977
|
+
return refuse(x, 'a mutex not of the object');
|
|
2978
|
+
}
|
|
2979
|
+
lockCall(x, p) {
|
|
2980
|
+
const n = String(x.op), key = this.lockKey(x.pl, p);
|
|
2981
|
+
if (n === 'Lock' || n === 'RLock') {
|
|
2982
|
+
if (p.locks.includes(key))
|
|
2983
|
+
refuse(x, `${x.text}: the mutex is locked again in the same step (a deadlock)`);
|
|
2984
|
+
return [{ t: 'tuple', xs: [] }, { ...p, locks: [...p.locks, key] }];
|
|
2985
|
+
}
|
|
2986
|
+
if (n === 'Unlock' || n === 'RUnlock') {
|
|
2987
|
+
if (!p.locks.includes(key))
|
|
2988
|
+
refuse(x, `${x.text}: an unlock of a mutex not locked (a panic)`);
|
|
2989
|
+
return [{ t: 'tuple', xs: [] }, { ...p, locks: p.locks.filter(k => k !== key) }];
|
|
2990
|
+
}
|
|
2991
|
+
return refuse(x, `${x.text}: a mutex's ${n}`);
|
|
2992
|
+
}
|
|
2993
|
+
// A function of the module inlined, its receiver and arguments bound by id (Go's): its returns joined, each result
|
|
2994
|
+
// by the path that returned it, the locks it deferred released at each.
|
|
2995
|
+
inline(fn, recv, args, at, p) {
|
|
2996
|
+
if (fn.why)
|
|
2997
|
+
return refuse(at, fn.why);
|
|
2998
|
+
if (this.frames.includes(fn.id))
|
|
2999
|
+
return refuse(at, `${fn.name}: a recursive call`);
|
|
3000
|
+
if (fn.late)
|
|
3001
|
+
return refuse(at, fn.late);
|
|
3002
|
+
this.spans.set(fn.id, fn.span);
|
|
3003
|
+
let q = { ...p, locals: new Map(p.locals), defers: [] };
|
|
3004
|
+
if (fn.recv && recv)
|
|
3005
|
+
q = this.bindLocal(fn.recv, recv, at, q);
|
|
3006
|
+
fn.params.forEach((pa, i) => { if (pa.name)
|
|
3007
|
+
q = this.bindLocal(pa.name, args[i], at, q); });
|
|
3008
|
+
this.frames.push(fn.id);
|
|
3009
|
+
let flow;
|
|
3010
|
+
try {
|
|
3011
|
+
flow = this.block(fn.body, q);
|
|
3012
|
+
}
|
|
3013
|
+
finally {
|
|
3014
|
+
this.frames.pop();
|
|
3015
|
+
}
|
|
3016
|
+
if (flow.brk?.length)
|
|
3017
|
+
refuse(at, `${fn.name}: a break outside a switch`);
|
|
3018
|
+
const rets = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'tuple', xs: [] }]] : [])];
|
|
3019
|
+
if (flow.live && fn.results)
|
|
3020
|
+
refuse(at, `${fn.name}: a path with no return`);
|
|
3021
|
+
if (!rets.length)
|
|
3022
|
+
return [{ t: 'opaque', why: 'no return', firm: true }, { ...p, pc: [...p.pc, I.F] }];
|
|
3023
|
+
const joined = this.join(rets.map(([r, v]) => ({ ...r, locks: r.locks.filter(k => !r.defers.includes(k)), defers: p.defers, locals: new Map([...r.locals, ...v.xs.map((x, i) => [`$ret${i}`, x])]) })), at);
|
|
3024
|
+
const vals = Array.from({ length: fn.results ?? 0 }, (_, i) => joined.locals.get(`$ret${i}`));
|
|
3025
|
+
return [vals.length === 1 ? vals[0] : { t: 'tuple', xs: vals }, { ...joined, locals: new Map(p.locals), defers: p.defers }];
|
|
3026
|
+
}
|
|
3027
|
+
// An assignment of Go's: each value evaluated (or one of several results, or a map's item and whether it is held),
|
|
3028
|
+
// then each target in order: a local bound, a map's item, a list's, a list or a map put back in its place, a place.
|
|
3029
|
+
assignGo(s, p) {
|
|
3030
|
+
const to = s.to;
|
|
3031
|
+
if (s.mapok) {
|
|
3032
|
+
const at = s.mapok, [m, q] = this.ev(at.m, p), [k, q2] = this.ev(at.k, q), cell = this.mapRead(m, k, at, q2);
|
|
3033
|
+
return this.assignTo(to, [cell.v, { t: 'bool', e: cell.has }], q2);
|
|
3034
|
+
}
|
|
3035
|
+
if (s.one) {
|
|
3036
|
+
const [v, q] = this.ev(s.one, p);
|
|
3037
|
+
// (the results of a call left out: each one its value, kept only where nothing reads it)
|
|
3038
|
+
if (v.t === 'opaque' && v.ask)
|
|
3039
|
+
return s.decl ? to.reduce((q2, x) => this.bindLocal(String(x.n), v, s, q2), q) : this.assignTo(to, to.map(() => v), q);
|
|
3040
|
+
if (v.t !== 'tuple' || (!s.decl && v.xs.length !== to.length))
|
|
3041
|
+
return refuse(s, String(s.why));
|
|
3042
|
+
return s.decl ? to.reduce((q2, x, i) => this.bindLocal(String(x.n), v.xs[i], s, q2), q) : this.assignTo(to, v.xs, q);
|
|
3043
|
+
}
|
|
3044
|
+
let q = p;
|
|
3045
|
+
const vals = [];
|
|
3046
|
+
for (const e of s.xs) {
|
|
3047
|
+
const [v, q2] = this.ev(e, q);
|
|
3048
|
+
vals.push(v);
|
|
3049
|
+
q = q2;
|
|
3050
|
+
}
|
|
3051
|
+
return this.assignTo(to, vals, q);
|
|
3052
|
+
}
|
|
3053
|
+
assignTo(l, vals, p) {
|
|
3054
|
+
let q = p;
|
|
3055
|
+
l.forEach((x, i) => {
|
|
3056
|
+
const v = vals[i];
|
|
3057
|
+
if (x.bind && !(x.bind === 'new' && q.locals.has(String(x.n)))) {
|
|
3058
|
+
q = this.bindLocal(String(x.n), v, x, q);
|
|
3059
|
+
return;
|
|
3060
|
+
}
|
|
3061
|
+
if (x.e === 'midx') {
|
|
3062
|
+
const [m, q2] = this.ev(x.m, q), [k, q3] = this.ev(x.k, q2);
|
|
3063
|
+
q = this.mapWrite(m, k, v, x, q3);
|
|
3064
|
+
return;
|
|
3065
|
+
}
|
|
3066
|
+
if (x.e === 'lidx') {
|
|
3067
|
+
const [sv, q2] = this.ev(x.s, q), [k, q3] = this.ev(x.i, q2);
|
|
3068
|
+
q = this.listSet(sv, k, v, x, q3);
|
|
3069
|
+
return;
|
|
3070
|
+
}
|
|
3071
|
+
if (x.e === 'no')
|
|
3072
|
+
return refuse(x, String(x.why));
|
|
3073
|
+
if (v.t === 'list' || v.t === 'push' || v.t === 'pop') {
|
|
3074
|
+
q = this.listAssign(x, v, q);
|
|
3075
|
+
return;
|
|
3076
|
+
}
|
|
3077
|
+
if (v.t === 'map') {
|
|
3078
|
+
q = this.mapAssign(x, v, q);
|
|
3079
|
+
return;
|
|
3080
|
+
}
|
|
3081
|
+
const [pl, q2] = this.place(x, q);
|
|
3082
|
+
q = this.write(pl, v, x, q2);
|
|
3083
|
+
});
|
|
3084
|
+
return q;
|
|
3085
|
+
}
|
|
3086
|
+
// A switch: each case's condition (none before it matched; the default's, none matched), evaluated in order; a case
|
|
3087
|
+
// carried into the next by fallthrough, a break out of it joined after.
|
|
3088
|
+
switchGo(s, p) {
|
|
3089
|
+
let q = p, tag;
|
|
3090
|
+
if (s.tag) {
|
|
3091
|
+
const [v, q2] = this.ev(s.tag, q);
|
|
3092
|
+
tag = v;
|
|
3093
|
+
q = q2;
|
|
3094
|
+
}
|
|
3095
|
+
const cases = s.cases, conds = [];
|
|
3096
|
+
let none = I.T;
|
|
3097
|
+
for (const c of cases) {
|
|
3098
|
+
if (c.default) {
|
|
3099
|
+
conds.push(I.F);
|
|
3100
|
+
continue;
|
|
3101
|
+
}
|
|
3102
|
+
let any = I.F;
|
|
3103
|
+
for (const e of c.list) {
|
|
3104
|
+
const [v, q2] = this.ev(e, q);
|
|
3105
|
+
q = q2;
|
|
3106
|
+
any = I.or(any, tag ? this.eq(tag, v, e, q) : v.t === 'bool' ? v.e : refuse(e, 'a case that isn\'t a condition'));
|
|
3107
|
+
}
|
|
3108
|
+
conds.push(I.and(none, any));
|
|
3109
|
+
none = I.and(none, I.not(any));
|
|
3110
|
+
}
|
|
3111
|
+
const di = cases.findIndex(c => c.default);
|
|
3112
|
+
if (di >= 0)
|
|
3113
|
+
conds[di] = none;
|
|
3114
|
+
const lives = [], rets = [];
|
|
3115
|
+
let carried;
|
|
3116
|
+
cases.forEach((c, i) => {
|
|
3117
|
+
const entry = conds[i].op === 'const' && !conds[i].v ? undefined : this.assume(q, conds[i]);
|
|
3118
|
+
let into = this.join([...(entry ? [entry] : []), ...(carried ? [carried] : [])], c);
|
|
3119
|
+
// (entered and carried into: the join keeps that one or the other got here, which a later join reads)
|
|
3120
|
+
if (entry && carried && into) {
|
|
3121
|
+
let k = 0;
|
|
3122
|
+
while (k < entry.pc.length && k < carried.pc.length && I.same(entry.pc[k], carried.pc[k]))
|
|
3123
|
+
k++;
|
|
3124
|
+
into = this.assume(into, I.or(I.and(...entry.pc.slice(k)), I.and(...carried.pc.slice(k))));
|
|
3125
|
+
}
|
|
3126
|
+
carried = undefined;
|
|
3127
|
+
if (!into)
|
|
3128
|
+
return;
|
|
3129
|
+
const f = this.block(c.b, into);
|
|
3130
|
+
if (f.live)
|
|
3131
|
+
lives.push(f.live);
|
|
3132
|
+
rets.push(...f.rets);
|
|
3133
|
+
if (f.brk?.length)
|
|
3134
|
+
lives.push(this.join(f.brk, c));
|
|
3135
|
+
if (f.ft) {
|
|
3136
|
+
if (i === cases.length - 1)
|
|
3137
|
+
refuse(c, 'fallthrough out of the last case');
|
|
3138
|
+
carried = f.ft;
|
|
3139
|
+
}
|
|
3140
|
+
});
|
|
3141
|
+
if (di < 0)
|
|
3142
|
+
lives.push(this.assume(q, none));
|
|
3143
|
+
const live = this.join(lives, s);
|
|
3144
|
+
return { ...(live ? { live } : {}), rets };
|
|
3145
|
+
}
|
|
3146
|
+
}
|
|
3147
|
+
// A pointer by a condition (one case where both are the same).
|
|
3148
|
+
export const phiP = (c, a, b) => (c.op === 'const' ? (c.v ? a : b) : JSON.stringify(a) === JSON.stringify(b) ? a : { k: 'phi', c, a, b });
|
|
3149
|
+
// The values a merge keeps exact (Go's): refused, not made opaque, where two paths make them different.
|
|
3150
|
+
const firm = (v) => ['ptr', 'struct', 'err', 'nil', 'map', 'list', 'push', 'pop'].includes(v.t) || (v.t === 'opaque' && !!v.firm);
|
|
3151
|
+
// An expression that calls nothing (so evaluating it changes nothing).
|
|
3152
|
+
// Whether some node of an IR tree (an object, depth first) is one f says yes to.
|
|
3153
|
+
const deep = (x, f) => !!x && typeof x === 'object' && (!!f(x) || Object.values(x).some(y => deep(y, f)));
|
|
3154
|
+
const callFree = (x) => !deep(x, o => o.e === 'call' || o.e === 'await' || o.e === 'no');
|
|
3155
|
+
// An expression that reaches none of the module's own code and not `self`.
|
|
3156
|
+
const foreign = (x) => !deep(x, o => o.e === 'fn' || (o.e === 'var' && o.n === 'self'));
|
|
3157
|
+
// Two key templates name disjoint keys: they differ at some position of their fixed prefixes or of their fixed
|
|
3158
|
+
// suffixes (a hole's value can be any string, so only those parts tell keys apart).
|
|
3159
|
+
export function disjoint(a, b) {
|
|
3160
|
+
if (a === b)
|
|
3161
|
+
return false;
|
|
3162
|
+
const [pa, sa] = split(a), [pb, sb] = split(b);
|
|
3163
|
+
for (let i = 0; i < Math.min(pa.length, pb.length); i++)
|
|
3164
|
+
if (pa[i] !== pb[i])
|
|
3165
|
+
return true;
|
|
3166
|
+
for (let i = 1; i <= Math.min(sa.length, sb.length); i++)
|
|
3167
|
+
if (sa[sa.length - i] !== sb[sb.length - i])
|
|
3168
|
+
return true;
|
|
3169
|
+
return false;
|
|
3170
|
+
}
|
|
3171
|
+
const split = (t) => { const i = t.indexOf('{}'); return i < 0 ? [t, t] : [t.slice(0, i), t.slice(i + 2)]; };
|
|
3172
|
+
// --- a module's step: the class (or the functions) read into the Model -------------------------------------------------
|
|
3173
|
+
// What a refutation (or any request of the rule) assumes of the boundary inferred: each answer inferred or tagged
|
|
3174
|
+
// that it gives a value, as "assumes `callee` may return v". A refutation that assumes none is the code's own.
|
|
3175
|
+
export function assumed(x, request) {
|
|
3176
|
+
const out = [];
|
|
3177
|
+
for (const a of x.read?.answers ?? []) {
|
|
3178
|
+
if (!a.how || !request || !(a.inputs.name in request))
|
|
3179
|
+
continue;
|
|
3180
|
+
// (an integer of the prover's is a pair: x − x$neg; a boolean 0 or 1)
|
|
3181
|
+
const none = a.inputs.none && (request[a.inputs.none] === true || request[a.inputs.none] === 1), v = request[a.inputs.name], neg = request[`${a.inputs.name}$neg`];
|
|
3182
|
+
const shown = none ? 'None' : /^bool\b/.test(a.sort) ? String(v === true || v === 1) : typeof v === 'number' ? String(v - (typeof neg === 'number' ? neg : 0)) : JSON.stringify(v);
|
|
3183
|
+
out.push(`assumes \`${a.key.split('.').pop()}\` may return ${shown} (${a.how}: any ${a.sort})`);
|
|
3184
|
+
}
|
|
3185
|
+
return out;
|
|
3186
|
+
}
|
|
3187
|
+
// The text of a file a position names (its name as the reader wrote it: absolute, under the root, or beside the file).
|
|
3188
|
+
export function sourceOf(mod, file) {
|
|
3189
|
+
const fs = node('node:fs'), dir = mod.path.replace(/\/[^/]*$/, '');
|
|
3190
|
+
for (const f of [file.startsWith('/') ? file : '', mod.path.endsWith(`/${file}`) ? mod.path : '', `${mod.root}/${file}`, `${dir}/${file}`])
|
|
3191
|
+
if (f)
|
|
3192
|
+
try {
|
|
3193
|
+
return fs.readFileSync(f, 'utf8');
|
|
3194
|
+
}
|
|
3195
|
+
catch { /* the next */ }
|
|
3196
|
+
return undefined;
|
|
3197
|
+
}
|
|
3198
|
+
// The stubbing of a compiled language's check: each answered call's text (from its position to its end) replaced in
|
|
3199
|
+
// its file by the harness's stub for that answer (in the code's language). Every file a call is answered in,
|
|
3200
|
+
// rewritten, by its name in the positions; a call with no end (a reader that doesn't say) is a refusal of the check.
|
|
3201
|
+
export function stubbed(read, text, stub) {
|
|
3202
|
+
const edits = new Map(), starts = new Map();
|
|
3203
|
+
for (const [i, a] of (read.answers ?? []).entries()) {
|
|
3204
|
+
for (const s of a.at ?? []) {
|
|
3205
|
+
// (its place: offsets where the reader gives them, a JVM reader's; else from its position to its end)
|
|
3206
|
+
const m = /^(.*):(\d+):(\d+)$/.exec(s.p), e = s.end && /^(\d+):(\d+)$/.exec(s.end);
|
|
3207
|
+
if (!m || (!e && !s.span))
|
|
3208
|
+
throw new Refusal(s.p, `${a.key}: an answered call whose end the reader doesn't give (the check can't stub it)`);
|
|
3209
|
+
const [from, to] = s.span ?? [lineCol(m[1], Number(m[2]), Number(m[3])), lineCol(m[1], Number(e[1]), Number(e[2]))];
|
|
3210
|
+
(edits.get(m[1]) ?? edits.set(m[1], []).get(m[1])).push([from, to, stub(a, i, (text(m[1]) ?? '').slice(from, to))]);
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
function lineCol(f, l, c) {
|
|
3214
|
+
let ls = starts.get(f);
|
|
3215
|
+
if (!ls) {
|
|
3216
|
+
const t = text(f) ?? '';
|
|
3217
|
+
ls = [0];
|
|
3218
|
+
for (let k = 0; k < t.length; k++)
|
|
3219
|
+
if (t[k] === '\n')
|
|
3220
|
+
ls.push(k + 1);
|
|
3221
|
+
starts.set(f, ls);
|
|
3222
|
+
}
|
|
3223
|
+
return (ls[l - 1] ?? 0) + c - 1;
|
|
3224
|
+
}
|
|
3225
|
+
const out = new Map();
|
|
3226
|
+
for (const [f, es] of edits) {
|
|
3227
|
+
let t = text(f) ?? '';
|
|
3228
|
+
for (const [a, b, r] of es.sort((x, y) => y[0] - x[0]))
|
|
3229
|
+
t = t.slice(0, a) + r + t.slice(b);
|
|
3230
|
+
out.set(f, t);
|
|
3231
|
+
}
|
|
3232
|
+
return out;
|
|
3233
|
+
}
|
|
3234
|
+
// The names a reader is asked for (none: the module's classes, for the entry inferred).
|
|
3235
|
+
export const entryNames = (opts) => (opts.entry === undefined ? [] : Array.isArray(opts.entry) ? opts.entry : [opts.entry]);
|
|
3236
|
+
// The module read into the rule. Unless strict, the boundary is inferred: each run that refuses where the subset's
|
|
3237
|
+
// inference can go on (a value of other code read, the module's own code outside the subset) adds what the next run
|
|
3238
|
+
// infers, until one reads (or refuses with what the caller would state to accept it).
|
|
3239
|
+
export function readStep(mod, opts) {
|
|
3240
|
+
if (opts.strict)
|
|
3241
|
+
return readOnce(mod, opts, new Stepper(mod, opts));
|
|
3242
|
+
const inf = { answers: new Map(), cut: new Map() };
|
|
3243
|
+
for (let n = 0;; n++) {
|
|
3244
|
+
const g = new Stepper(mod, opts, inf);
|
|
3245
|
+
try {
|
|
3246
|
+
return readOnce(mod, opts, g);
|
|
3247
|
+
}
|
|
3248
|
+
catch (e) {
|
|
3249
|
+
if (!(e instanceof Refusal))
|
|
3250
|
+
throw e;
|
|
3251
|
+
const r = n < 256 ? g.promote(e) : e;
|
|
3252
|
+
if (r)
|
|
3253
|
+
throw r;
|
|
3254
|
+
}
|
|
3255
|
+
}
|
|
3256
|
+
}
|
|
3257
|
+
function readOnce(mod, opts, g) {
|
|
3258
|
+
if (mod.error)
|
|
3259
|
+
refuse(mod.file ?? mod.root ?? '?', mod.error);
|
|
3260
|
+
const kept = opts.failures === 'kept', carried = kept && opts.onError !== 'discard';
|
|
3261
|
+
let entries = mod.entries;
|
|
3262
|
+
for (const e of entries)
|
|
3263
|
+
if (e.k === 'missing')
|
|
3264
|
+
refuse(mod.file, `no class or function ${e.name} in ${mod.file}`);
|
|
3265
|
+
// No entry: the module's one class whose public methods write its state, and those methods.
|
|
3266
|
+
let writing;
|
|
3267
|
+
if (!entryNames(opts).length) {
|
|
3268
|
+
if (!g.inf)
|
|
3269
|
+
refuse(mod.file, 'no entry (strict: name the class or the functions)');
|
|
3270
|
+
const pub = (r) => Object.keys(r.methods).filter(m => !m.startsWith('_') && r.methods[m] && g.writesState(r.methods[m], new Set(g.mod.funcs[r.methods[m]]?.params.filter(x => x.self).map(x => x.name) ?? [])));
|
|
3271
|
+
const cands = entries.filter((e) => e.k === 'class' && pub(g.rec(e.rec, { p: mod.file })).length > 0);
|
|
3272
|
+
if (cands.length !== 1)
|
|
3273
|
+
refuse(mod.file, cands.length ? `several classes write their state (${cands.map(e => g.rec(e.rec, { p: mod.file }).short).join(', ')}): name one (entry)` : 'no class whose public methods write its state: name the entry (a class, or functions)');
|
|
3274
|
+
entries = cands;
|
|
3275
|
+
writing = pub(g.rec(cands[0].rec, { p: mod.file }));
|
|
3276
|
+
g.notes.add(`the entry inferred: ${g.rec(cands[0].rec, { p: mod.file }).short}, the class whose public methods write its state${opts.methods ? '' : ` (${writing.join(', ')}; the others read it)`}`);
|
|
3277
|
+
}
|
|
3278
|
+
const cls = entries.length === 1 && entries[0].k === 'class' ? entries[0].rec : undefined;
|
|
3279
|
+
if (!cls && entries.some(e => e.k === 'class'))
|
|
3280
|
+
refuse(mod.file, 'a class read with other entries (one class, or functions)');
|
|
3281
|
+
const leaves = [], ctor = [];
|
|
3282
|
+
const at = { p: `${mod.file}:1:1` };
|
|
3283
|
+
// --- the state: the object as its constructor makes it -----------------------------------------------------------
|
|
3284
|
+
const stateOf = new Map(); // each leaf's value at the start (terms over the params)
|
|
3285
|
+
let pre = I.T;
|
|
3286
|
+
const tree = [];
|
|
3287
|
+
if (cls) {
|
|
3288
|
+
const r = g.rec(cls, at);
|
|
3289
|
+
if (!r.own)
|
|
3290
|
+
refuse(at, `${r.short}: a class of another module`);
|
|
3291
|
+
const fresh = { pc: [], locals: new Map(), heap: new Map([['this', { k: 'rec', ty: cls, f: new Map(), origin: 'state' }]]), called: [], locks: [], defers: [] };
|
|
3292
|
+
g.init = true;
|
|
3293
|
+
g.method = '__init__';
|
|
3294
|
+
const r0 = g.refusals.length;
|
|
3295
|
+
let made;
|
|
3296
|
+
const initId = r.methods.__init__;
|
|
3297
|
+
if (initId)
|
|
3298
|
+
g.entryIds.add(initId);
|
|
3299
|
+
if (r.kinds.some(k => k.startsWith('generic:')))
|
|
3300
|
+
refuse(r, `${r.short}: a generic type (its methods read a type parameter)`);
|
|
3301
|
+
const rustNew = mod.lang === 'rust' ? r.methods.new : undefined;
|
|
3302
|
+
if (rustNew)
|
|
3303
|
+
g.entryIds.add(rustNew);
|
|
3304
|
+
if (mod.lang === 'rust' && rustNew) {
|
|
3305
|
+
// Rust: the object is what `new` returns, its arguments the rule's params (named after the fields' names).
|
|
3306
|
+
for (const f of r.fields)
|
|
3307
|
+
g.fieldNames.add(f.name);
|
|
3308
|
+
const fn = g.func(rustNew, at);
|
|
3309
|
+
const args = [];
|
|
3310
|
+
let p = fresh;
|
|
3311
|
+
for (const pa of fn.params.filter(x => !x.self)) {
|
|
3312
|
+
const [v, a] = g.input(pa.name, pa.t, fn, p, 'param');
|
|
3313
|
+
if (a.k === 'inert')
|
|
3314
|
+
refuse(fn, `${r.short}::new(${pa.name}): an argument of ${g.why(pa.t)}`);
|
|
3315
|
+
args.push(v);
|
|
3316
|
+
ctor.push([pa.name, a]);
|
|
3317
|
+
}
|
|
3318
|
+
const [out, p2] = g.callFunc(fn, undefined, args, [], { e: 'call', p: fn.p, text: `${r.short}::new()` }, p, true);
|
|
3319
|
+
const obj = out.t === 'ref' ? p2.heap.get(out.id) : undefined;
|
|
3320
|
+
if (obj?.k !== 'rec' || obj.ty !== cls)
|
|
3321
|
+
refuse(fn, `${r.short}::new returns ${out.t === 'ref' ? 'another object' : `a ${out.t}`} (the subset reads a new() that returns Self)`);
|
|
3322
|
+
made = { ...p2, heap: new Map(p2.heap).set('this', { ...obj, origin: 'state' }) };
|
|
3323
|
+
if (ctor.length)
|
|
3324
|
+
g.notes.add(`${r.short} made by ${r.short}::new: its arguments are the rule's params`);
|
|
3325
|
+
}
|
|
3326
|
+
else if (mod.lang === 'rust') {
|
|
3327
|
+
if (!r.kinds.includes('default'))
|
|
3328
|
+
refuse(r, `${r.short}: no new() and no derived Default (the subset makes the object by one of them)`);
|
|
3329
|
+
const f = new Map();
|
|
3330
|
+
for (const fd of r.fields)
|
|
3331
|
+
f.set(fd.name, defaultOf(fd.t, at));
|
|
3332
|
+
made = { ...fresh, heap: new Map(fresh.heap).set('this', { k: 'rec', ty: cls, f, origin: 'state' }) };
|
|
3333
|
+
g.notes.add(`${r.short}: made by its derived Default`);
|
|
3334
|
+
}
|
|
3335
|
+
else if (initId) {
|
|
3336
|
+
const fn = g.func(initId, at);
|
|
3337
|
+
// The fields it sets (named first: the state's names are the fields').
|
|
3338
|
+
const scan = (ss) => { for (const st of ss) {
|
|
3339
|
+
const to = st.to;
|
|
3340
|
+
if (st.s === 'set' && to?.e === 'get' && to.x.e === 'var' && to.x.n === 'self')
|
|
3341
|
+
g.fieldNames.add(String(to.f));
|
|
3342
|
+
if (st.s === 'if') {
|
|
3343
|
+
scan(st.then);
|
|
3344
|
+
scan(st.else);
|
|
3345
|
+
}
|
|
3346
|
+
if (st.s === 'with')
|
|
3347
|
+
scan(st.body);
|
|
3348
|
+
} };
|
|
3349
|
+
scan(fn.body);
|
|
3350
|
+
const args = [], kw = [];
|
|
3351
|
+
let p = fresh;
|
|
3352
|
+
// (a keyword argument given as one)
|
|
3353
|
+
const give = (pa, v) => { if (pa.kw)
|
|
3354
|
+
kw.push([pa.name, v]);
|
|
3355
|
+
else
|
|
3356
|
+
args.push(v); };
|
|
3357
|
+
for (const pa of fn.params.filter(x => !x.self && !x.star)) {
|
|
3358
|
+
const dep = opts.stores?.[pa.name] ? undefined : g.injected(pa, fn, r);
|
|
3359
|
+
if (opts.stores?.[pa.name] || dep) {
|
|
3360
|
+
const id = `store:${pa.name}`;
|
|
3361
|
+
p.heap.set(id, { k: 'store', name: pa.name });
|
|
3362
|
+
g.initHeap.set(id, { k: 'store', name: pa.name });
|
|
3363
|
+
give(pa, { t: 'ref', id });
|
|
3364
|
+
ctor.push([pa.name, { k: 'store', name: pa.name }]);
|
|
3365
|
+
if (!dep || dep.keyed)
|
|
3366
|
+
g.storeKeyed.add(pa.name);
|
|
3367
|
+
const pt = pa.t.k === 'opt' ? pa.t.of : pa.t;
|
|
3368
|
+
g.deps.push({ name: pa.name, ...(pt.k === 'rec' ? { ty: pt.name } : {}), keyed: !dep || dep.keyed, stated: !dep });
|
|
3369
|
+
if (dep?.ty)
|
|
3370
|
+
g.storeTypes.set(pa.name, dep.ty);
|
|
3371
|
+
if (dep)
|
|
3372
|
+
g.notes.add(`${r.short}(${pa.name}): an injected dependency (inferred: ${pa.inject ? 'marked so' : `of ${dep.ty ? g.mod.recs[dep.ty]?.short ?? dep.ty : 'no stated type'}, its methods called`}), the check giving one that ${dep.keyed ? 'keeps what is set' : 'answers its calls'}`);
|
|
3373
|
+
continue;
|
|
3374
|
+
}
|
|
3375
|
+
if (pa.dflt && !g.scalar(pa.t.k === 'opt' ? pa.t.of : pa.t)) {
|
|
3376
|
+
ctor.push([pa.name, { k: 'dflt' }]);
|
|
3377
|
+
const [d, p2] = g.ev(pa.dflt, p);
|
|
3378
|
+
give(pa, d);
|
|
3379
|
+
p = p2;
|
|
3380
|
+
continue;
|
|
3381
|
+
}
|
|
3382
|
+
const [v, a] = g.input(pa.name, pa.t, fn, p, 'param');
|
|
3383
|
+
if (a.k === 'inert')
|
|
3384
|
+
refuse(fn, `${r.short}(${pa.name}): a constructor argument of ${g.why(pa.t)} (state it as a store, or give it a default)`);
|
|
3385
|
+
give(pa, v);
|
|
3386
|
+
ctor.push([pa.name, a]);
|
|
3387
|
+
}
|
|
3388
|
+
const [, p2] = g.callFunc(fn, { t: 'ref', id: 'this' }, args, kw, { e: 'call', p: fn.p, text: `${r.short}()` }, p, false);
|
|
3389
|
+
made = p2;
|
|
3390
|
+
if (ctor.length)
|
|
3391
|
+
g.notes.add(`${r.short} made by its constructor: its arguments are the rule's params`);
|
|
3392
|
+
}
|
|
3393
|
+
else if (r.kinds.includes('dataclass')) {
|
|
3394
|
+
const f = new Map();
|
|
3395
|
+
let p = fresh;
|
|
3396
|
+
for (const fd of r.fields) {
|
|
3397
|
+
if (fd.dflt) {
|
|
3398
|
+
const [d, p2] = g.ev(fd.dflt, p);
|
|
3399
|
+
f.set(fd.name, d);
|
|
3400
|
+
p = p2;
|
|
3401
|
+
g.declared.set(`this.${fd.name}`, fd.t);
|
|
3402
|
+
continue;
|
|
3403
|
+
}
|
|
3404
|
+
const [v, a] = g.input(fd.name, fd.t, { p: r.p }, p, 'param');
|
|
3405
|
+
if (a.k === 'inert')
|
|
3406
|
+
refuse(r, `${r.short}.${fd.name}: a field of ${g.why(fd.t)}`);
|
|
3407
|
+
f.set(fd.name, v);
|
|
3408
|
+
ctor.push([fd.name, a]);
|
|
3409
|
+
g.declared.set(`this.${fd.name}`, fd.t);
|
|
3410
|
+
}
|
|
3411
|
+
if (r.methods.__post_init__)
|
|
3412
|
+
refuse(r, `${r.short}: __post_init__`);
|
|
3413
|
+
made = { ...p, heap: new Map(p.heap).set('this', { k: 'rec', ty: cls, f, origin: 'state' }) };
|
|
3414
|
+
g.notes.add(`${r.short}: a dataclass, made with its fields' defaults (the claim is for objects made so) and the others as params`);
|
|
3415
|
+
}
|
|
3416
|
+
else
|
|
3417
|
+
made = fresh;
|
|
3418
|
+
// (what the constructor refuses, a narrowing cast's value that doesn't fit, is the precondition's)
|
|
3419
|
+
pre = I.and(I.not(I.or(...g.fails)), I.not(I.or(...g.paramsOut)), I.not(I.or(...g.refusals.splice(r0))));
|
|
3420
|
+
g.fails = [];
|
|
3421
|
+
g.init = false;
|
|
3422
|
+
// (a field a framework injects, @Autowired or @Inject on it: the store the check gives, named by the field)
|
|
3423
|
+
for (const fd of g.inf ? r.fields.filter(f => f.inject && !made.heap.get('this').f.has(f.name)) : []) {
|
|
3424
|
+
const id = `store:${fd.name}`, o = { k: 'store', name: fd.name };
|
|
3425
|
+
made.heap.set(id, o);
|
|
3426
|
+
g.initHeap.set(id, o);
|
|
3427
|
+
g.injectedFields.push(fd.name);
|
|
3428
|
+
made.heap.get('this').f.set(fd.name, { t: 'ref', id });
|
|
3429
|
+
if (fd.t.k === 'rec')
|
|
3430
|
+
g.storeTypes.set(fd.name, fd.t.name);
|
|
3431
|
+
const keyed = g.callsOn(r, [fd.name]).some(m => !!keyShape(m));
|
|
3432
|
+
if (keyed)
|
|
3433
|
+
g.storeKeyed.add(fd.name);
|
|
3434
|
+
g.deps.push({ name: fd.name, ...(fd.t.k === 'rec' ? { ty: fd.t.name } : {}), keyed, stated: false });
|
|
3435
|
+
g.notes.add(`${r.short}.${fd.name}: an injected dependency (marked so), the check giving one`);
|
|
3436
|
+
}
|
|
3437
|
+
// (two injected dependencies are taken as two objects: where they are of one type and the rule holds keys of one,
|
|
3438
|
+
// the code may be given one object for both, which the rule would take as two; refused unless both are stated)
|
|
3439
|
+
for (const [i, a] of g.deps.entries())
|
|
3440
|
+
for (const b of g.deps.slice(i + 1)) {
|
|
3441
|
+
if (a.ty === b.ty && (a.keyed || b.keyed) && !(a.stated && b.stated))
|
|
3442
|
+
refuse(r, `${r.short}(${a.name}, ${b.name}): two injected dependencies of one type (${a.ty ? g.mod.recs[a.ty]?.short ?? a.ty : 'none stated'}), the rule holding keys of ${a.keyed ? a.name : b.name}: the code may be given one object for both, which the rule would take as two (state both stores, stores: {${a.name}: {}, ${b.name}: {}}, to take them as distinct)`);
|
|
3443
|
+
}
|
|
3444
|
+
if (g.deps.length > 1)
|
|
3445
|
+
g.notes.add(`${r.short}: assumes its injected dependencies ${g.deps.map(d => d.name).join(', ')} are distinct objects (each with what it holds)`);
|
|
3446
|
+
const self = made.heap.get('this');
|
|
3447
|
+
for (const [f, v] of self.f) {
|
|
3448
|
+
const t = g.declared.get(`this.${f}`) ?? r.fields.find(x => x.name === f)?.t;
|
|
3449
|
+
tree.push({ path: [f], v, ...(t && t.k !== 'any' ? { t } : {}) });
|
|
3450
|
+
}
|
|
3451
|
+
for (const fd of r.fields)
|
|
3452
|
+
if (!self.f.has(fd.name) && !r.kinds.includes('dataclass'))
|
|
3453
|
+
g.notes.add(`${r.short}.${fd.name}: declared on the class but not set by its constructor (left out)`);
|
|
3454
|
+
// Each field a leaf: a variable (two for an optional one), a nested object's own, a map, a store, or left out.
|
|
3455
|
+
const heap = new Map();
|
|
3456
|
+
const fields = new Map();
|
|
3457
|
+
const build = (path, v, t, into, initPath) => {
|
|
3458
|
+
const name = path.join('_'), f = path.at(-1), decl = t ?? undefined;
|
|
3459
|
+
const scalarT = decl && decl.k !== 'opt' ? decl : undefined;
|
|
3460
|
+
const leaf = (kind, vr, float) => { leaves.push({ name: vr.name, path, kind, ...(float ? { float: true } : {}) }); return vr; };
|
|
3461
|
+
const isFloat = (decl?.k === 'float') || (decl?.k === 'opt' && decl.of.k === 'float');
|
|
3462
|
+
if (v.t === 'num' || v.t === 'bool' || v.t === 'str' || v.t === 'choice' || (v.t === 'none' && decl?.k === 'opt') || v.t === 'opt') {
|
|
3463
|
+
const inner = decl?.k === 'opt' ? decl.of : scalarT;
|
|
3464
|
+
const sort = inner && g.scalar(inner) ? g.scalar(inner) : v.t === 'num' ? { k: 'num' } : v.t === 'bool' ? { k: 'bool' } : v.t === 'str' ? { k: 'str' } : v.t === 'choice' ? { k: 'choice', values: lvalues(v.e) } : v.t === 'opt' && g.scalar({ k: v.v.t === 'num' ? 'int' : v.v.t === 'bool' ? 'bool' : 'str' }) ? (v.v.t === 'num' ? { k: 'num' } : v.v.t === 'bool' ? { k: 'bool' } : { k: 'str' }) : refuse(at, `${path.join('.')}: a field of no scalar type`);
|
|
3465
|
+
if (v.t === 'str' && sort.k === 'choice' && v.e.op === 'slit')
|
|
3466
|
+
v = { t: 'choice', e: I.llit(v.e.value, sort.values) };
|
|
3467
|
+
const optional = v.t === 'none' || v.t === 'opt' || decl?.k === 'opt';
|
|
3468
|
+
const vr = leaf(sort.k === 'num' ? 'num' : sort.k, g.newVar(name, sort, 'state'), isFloat);
|
|
3469
|
+
if (inner)
|
|
3470
|
+
g.typed(vr, inner, 'state');
|
|
3471
|
+
const lf = leaves[leaves.length - 1];
|
|
3472
|
+
if (decl)
|
|
3473
|
+
lf.t = decl;
|
|
3474
|
+
let cur = g.valueOf(vr);
|
|
3475
|
+
if (optional) {
|
|
3476
|
+
const nv = leaf('none', g.newVar(`${name}_none`, { k: 'bool' }, 'state', `whether ${path.join('.')} is None`));
|
|
3477
|
+
const has = I.not(I.bvar(nv.name));
|
|
3478
|
+
stateOf.set(nv.name, { t: 'bool', e: v.t === 'none' ? I.T : v.t === 'opt' ? I.not(v.has) : I.F });
|
|
3479
|
+
stateOf.set(vr.name, v.t === 'none' ? zeroOf(sort) : v.t === 'opt' ? v.v : v);
|
|
3480
|
+
cur = { t: 'opt', has, v: cur };
|
|
3481
|
+
}
|
|
3482
|
+
else
|
|
3483
|
+
stateOf.set(vr.name, v);
|
|
3484
|
+
into.set(f, cur);
|
|
3485
|
+
return;
|
|
3486
|
+
}
|
|
3487
|
+
if (v.t === 'ref') {
|
|
3488
|
+
const o = initPath.heap.get(v.id);
|
|
3489
|
+
if (o?.k === 'store') {
|
|
3490
|
+
into.set(f, v);
|
|
3491
|
+
heap.set(v.id, o);
|
|
3492
|
+
return;
|
|
3493
|
+
}
|
|
3494
|
+
if (o?.k === 'rec') {
|
|
3495
|
+
const sub = new Map(), id = `state:${path.join('.')}`;
|
|
3496
|
+
for (const [ff, vv] of o.f)
|
|
3497
|
+
build([...path, ff], vv, g.mod.recs[o.ty]?.fields.find(x => x.name === ff)?.t, sub, initPath);
|
|
3498
|
+
heap.set(id, { k: 'rec', ty: o.ty, f: sub, origin: 'state' });
|
|
3499
|
+
leaves.push({ name: '', path, kind: 'frame', cls: o.ty });
|
|
3500
|
+
into.set(f, { t: 'ref', id });
|
|
3501
|
+
return;
|
|
3502
|
+
}
|
|
3503
|
+
}
|
|
3504
|
+
if (v.t === 'opaque' && decl?.k === 'map' && /\{\}/.test(v.why)) {
|
|
3505
|
+
const d = g.mapDeclOf(name, decl, at), id = `state:${path.join('.')}`;
|
|
3506
|
+
const vt = decl.val;
|
|
3507
|
+
heap.set(id, { k: 'map', decl: d, val: vt, origin: 'state' });
|
|
3508
|
+
leaves.push({ name: d.name, path, kind: 'map', key: d.key, ...(vt.k === 'rec' ? { cls: vt.name, fields: d.fields.map(x => ({ name: x.name, ...(g.mod.recs[vt.name].fields.find(y => y.name === x.name)?.t.k === 'float' ? { float: true } : {}) })) } : vt.k === 'float' ? { float: true } : {}) });
|
|
3509
|
+
into.set(f, { t: 'ref', id });
|
|
3510
|
+
return;
|
|
3511
|
+
}
|
|
3512
|
+
if (v.t === 'lock') {
|
|
3513
|
+
into.set(f, v);
|
|
3514
|
+
return;
|
|
3515
|
+
}
|
|
3516
|
+
// A field the constructor sets to None, of no declared type: a constant (a method setting it is refused).
|
|
3517
|
+
if (v.t === 'none') {
|
|
3518
|
+
into.set(f, v);
|
|
3519
|
+
g.frozen.add(path.join('.'));
|
|
3520
|
+
leaves.push({ name: '', path, kind: 'frame' });
|
|
3521
|
+
return;
|
|
3522
|
+
}
|
|
3523
|
+
into.set(f, { t: 'opaque', why: `${path.join('.')}: ${v.t === 'opaque' ? v.why : `a ${v.t}`}, a field outside the subset (left out of the rule)` });
|
|
3524
|
+
leaves.push({ name: '', path, kind: 'frame' });
|
|
3525
|
+
};
|
|
3526
|
+
for (const { path, v, t } of tree)
|
|
3527
|
+
build(path, v, t, fields, made);
|
|
3528
|
+
heap.set('this', { k: 'rec', ty: cls, f: fields, origin: 'state' });
|
|
3529
|
+
for (const [id, o] of heap)
|
|
3530
|
+
g.initHeap.set(id, o);
|
|
3531
|
+
}
|
|
3532
|
+
// --- the requests: each method (or function) one -------------------------------------------------------------------
|
|
3533
|
+
const r = cls ? g.rec(cls, at) : undefined;
|
|
3534
|
+
const chosen = cls
|
|
3535
|
+
? (opts.methods ?? writing ?? Object.keys(r.methods).filter(m => !m.startsWith('_') && r.methods[m])).map(m => (r.methods[m] ? g.func(r.methods[m], at) : refuse(at, `no method ${r.short}.${m} in ${mod.file}`)))
|
|
3536
|
+
: entries.map(e => g.func(e.id, at));
|
|
3537
|
+
if (!chosen.length)
|
|
3538
|
+
refuse(at, `${cls ? r.short : 'the entry'} has no methods to read`);
|
|
3539
|
+
for (const f of chosen)
|
|
3540
|
+
g.entryIds.add(f.id);
|
|
3541
|
+
for (const f of chosen)
|
|
3542
|
+
if (f.decorators.some(d => d.name === 'property'))
|
|
3543
|
+
refuse(f, `${f.name}: a property (read, not called)`);
|
|
3544
|
+
const names = chosen.map(f => f.name);
|
|
3545
|
+
const ev = names.length > 1 ? g.newVar('method', { k: 'choice', values: names }, 'input') : undefined;
|
|
3546
|
+
const evL = ev ? { op: 'var', name: ev.name, values: names } : undefined;
|
|
3547
|
+
const events = [], argsOf = {};
|
|
3548
|
+
const finals = [];
|
|
3549
|
+
for (const fn of chosen) {
|
|
3550
|
+
g.method = fn.name;
|
|
3551
|
+
const sel = evL ? I.is(evL, fn.name) : I.T;
|
|
3552
|
+
g.sel = sel;
|
|
3553
|
+
let p = { pc: [sel], locals: new Map(), heap: new Map(g.initHeap), called: [], locks: [], defers: [] };
|
|
3554
|
+
const args = [], pargs = [];
|
|
3555
|
+
if (fn.recv === 'value')
|
|
3556
|
+
refuse(fn, `${fn.name}: a method that takes self by value (it consumes the object)`);
|
|
3557
|
+
if (fn.generic)
|
|
3558
|
+
refuse(fn, `${fn.name}: a generic method`);
|
|
3559
|
+
for (const pa of fn.params.filter(x => !x.self && !x.star)) {
|
|
3560
|
+
const [v, a] = g.input(`${names.length > 1 ? `${fn.name}_` : ''}${pa.name}`, pa.t, fn, p);
|
|
3561
|
+
args.push(v);
|
|
3562
|
+
pargs.push([pa.name, a]);
|
|
3563
|
+
}
|
|
3564
|
+
g.fails = [];
|
|
3565
|
+
g.failPaths = [];
|
|
3566
|
+
let [out, q] = g.callFunc(fn, cls ? { t: 'ref', id: 'this' } : undefined, args, [], { e: 'call', p: fn.p, text: fn.name }, p, fn.async ?? false);
|
|
3567
|
+
// A Result returned: its Err is the step's failure (Rust's error results, later Go's and Elixir's), its Ok the value.
|
|
3568
|
+
if (out.t === 'res') {
|
|
3569
|
+
g.fail(q, I.not(out.ok), fn, `${fn.name} returns an Err`);
|
|
3570
|
+
q = g.assume(q, out.ok);
|
|
3571
|
+
out = out.v;
|
|
3572
|
+
}
|
|
3573
|
+
p = g.failPaths.length ? g.join([q, ...g.failPaths], fn) : q;
|
|
3574
|
+
finals.push({ sel, path: p, out, fails: g.fails });
|
|
3575
|
+
argsOf[fn.name] = pargs;
|
|
3576
|
+
}
|
|
3577
|
+
// --- the methods together: each leaf by the method called ---------------------------------------------------------
|
|
3578
|
+
const state = [], init = {}, writes = {}, mapWrites = {}, outputs = [];
|
|
3579
|
+
const stateLeaves = leaves.filter(l => l.kind !== 'frame' && l.kind !== 'map');
|
|
3580
|
+
const failedOf = (f) => I.or(...f.fails);
|
|
3581
|
+
const anyFail = (f) => I.and(f.sel, failedOf(f));
|
|
3582
|
+
const termOf = (v, at2) => {
|
|
3583
|
+
if (v.t === 'num')
|
|
3584
|
+
return { s: 'num', e: v.e };
|
|
3585
|
+
if (v.t === 'bool')
|
|
3586
|
+
return { s: 'bool', e: v.e };
|
|
3587
|
+
if (v.t === 'str')
|
|
3588
|
+
return { s: 'str', e: v.e };
|
|
3589
|
+
if (v.t === 'choice')
|
|
3590
|
+
return { s: 'choice', e: v.e };
|
|
3591
|
+
return refuse(at2, `a ${v.t === 'opaque' ? v.why : v.t} where the state holds a scalar`);
|
|
3592
|
+
};
|
|
3593
|
+
// The value of each leaf at a path's end (the object's fields, nested ones through their objects).
|
|
3594
|
+
const leafAt = (path, l, at2) => {
|
|
3595
|
+
let o = path.heap.get('this');
|
|
3596
|
+
for (const seg of l.path.slice(0, -1)) {
|
|
3597
|
+
const v = o.f.get(seg);
|
|
3598
|
+
if (v?.t !== 'ref')
|
|
3599
|
+
return refuse(at2, `${l.path.join('.')}: a nested object replaced by a ${v?.t}`);
|
|
3600
|
+
o = path.heap.get(v.id);
|
|
3601
|
+
}
|
|
3602
|
+
const f = l.kind === 'none' ? l.path.at(-1) : l.path.at(-1);
|
|
3603
|
+
const v = o.f.get(f) ?? refuse(at2, `${l.path.join('.')} unset`);
|
|
3604
|
+
const s = g.vars.get(l.name).sort;
|
|
3605
|
+
if (l.kind === 'none')
|
|
3606
|
+
return { s: 'bool', e: v.t === 'none' ? I.T : v.t === 'opt' ? I.not(v.has) : I.F };
|
|
3607
|
+
// (None holds its sort's zero: the value read where the field is Some, the zero elsewhere)
|
|
3608
|
+
const z = zeroOf(s), inOpt = (w) => (v.t !== 'opt' ? w : w.t === 'num' && z.t === 'num' ? { t: 'num', e: I.nite(v.has, w.e, z.e) } : w.t === 'bool' && z.t === 'bool' ? { t: 'bool', e: I.bite(v.has, w.e, z.e) } : w.t === 'str' && z.t === 'str' ? { t: 'str', e: I.kite(v.has, w.e, z.e) } : w.t === 'choice' && z.t === 'choice' ? { t: 'choice', e: I.lite(v.has, w.e, z.e) } : w);
|
|
3609
|
+
const val = v.t === 'opt' ? inOpt(v.v) : v.t === 'none' ? z : v;
|
|
3610
|
+
return termOf(val.t === 'str' && s.k === 'choice' && val.e.op === 'slit' ? { t: 'choice', e: I.llit(val.e.value, s.values) } : val, at2);
|
|
3611
|
+
};
|
|
3612
|
+
for (const l of stateLeaves) {
|
|
3613
|
+
const v = g.vars.get(l.name);
|
|
3614
|
+
state.push(v);
|
|
3615
|
+
init[v.name] = termOf(stateOf.get(v.name), at);
|
|
3616
|
+
let acc;
|
|
3617
|
+
for (let i = finals.length - 1; i >= 0; i--) {
|
|
3618
|
+
const f = finals[i];
|
|
3619
|
+
let t = leafAt(f.path, l, { p: chosen[i].p });
|
|
3620
|
+
if (kept && !carried)
|
|
3621
|
+
t = iteTerm(failedOf(f), varTerm(v), t);
|
|
3622
|
+
acc = acc === undefined ? t : iteTerm(f.sel, t, acc);
|
|
3623
|
+
}
|
|
3624
|
+
if (acc && !I.same(acc.e, varTerm(v).e))
|
|
3625
|
+
writes[v.name] = acc;
|
|
3626
|
+
}
|
|
3627
|
+
// A one-object check: no object in two places of the state.
|
|
3628
|
+
for (const f of finals) {
|
|
3629
|
+
const seen = new Set();
|
|
3630
|
+
const visit = (o, path) => { for (const [k, v] of o.f)
|
|
3631
|
+
if (v.t === 'ref') {
|
|
3632
|
+
if (seen.has(v.id))
|
|
3633
|
+
refuse(chosen[0].p, `${path}.${k}: one object in two places of the state`);
|
|
3634
|
+
seen.add(v.id);
|
|
3635
|
+
const x = f.path.heap.get(v.id);
|
|
3636
|
+
if (x?.k === 'rec')
|
|
3637
|
+
visit(x, `${path}.${k}`);
|
|
3638
|
+
} };
|
|
3639
|
+
const self = f.path.heap.get('this');
|
|
3640
|
+
if (self?.k === 'rec')
|
|
3641
|
+
visit(self, 'self');
|
|
3642
|
+
}
|
|
3643
|
+
// The maps (and the stores' maps).
|
|
3644
|
+
for (const d of g.maps) {
|
|
3645
|
+
const id = [...g.initHeap].find(([, o]) => o.k === 'map' && o.decl === d)?.[0];
|
|
3646
|
+
if (!id)
|
|
3647
|
+
continue;
|
|
3648
|
+
const ws = finals.map(f => { const w0 = f.path.heap.get(id)?.w; return w0 && { key: w0.key, has: w0.has, vals: Object.fromEntries([...w0.vals].map(([f2, v]) => [f2, termOf(v, at)])) }; });
|
|
3649
|
+
// (a failure kept, the cell as it was there)
|
|
3650
|
+
const w = mapWritesOf(g, d, finals.map(f => f.sel), ws, (i, w2, base) => { if (!kept || carried)
|
|
3651
|
+
return w2; const fl = failedOf(finals[i]), b = base(w2.key); return { key: w2.key, has: I.bite(fl, b.has, w2.has), vals: Object.fromEntries(Object.entries(w2.vals).map(([f, t]) => [f, iteTerm(fl, b.vals[f], t)])) }; });
|
|
3652
|
+
if (w)
|
|
3653
|
+
mapWrites[d.name] = w;
|
|
3654
|
+
}
|
|
3655
|
+
// What each method returns, and whether it failed: the step's result.
|
|
3656
|
+
const results = {}, resultKinds = {};
|
|
3657
|
+
let failedVar;
|
|
3658
|
+
if (kept) {
|
|
3659
|
+
failedVar = g.newVar('failed', { k: 'bool' }, 'state', 'whether the step failed (an exception raised): the state is as it was');
|
|
3660
|
+
}
|
|
3661
|
+
for (const [i, f] of finals.entries()) {
|
|
3662
|
+
const fn = chosen[i];
|
|
3663
|
+
const out = f.out;
|
|
3664
|
+
let kind = 'none', rv, rn;
|
|
3665
|
+
// (a result of other code left out by inference: the step's result is kept, so its value is read)
|
|
3666
|
+
const asked = out.t === 'opaque' ? out : out.t === 'opt' && out.v.t === 'opaque' ? out.v : undefined;
|
|
3667
|
+
if (asked?.ask)
|
|
3668
|
+
refuse(fn, `${fn.name} returns ${asked.why} (a result the rule keeps)`);
|
|
3669
|
+
if (out.t === 'num' || out.t === 'bool' || out.t === 'str' || out.t === 'choice' || out.t === 'opt') {
|
|
3670
|
+
const inner = out.t === 'opt' ? out.v : out;
|
|
3671
|
+
if (inner.t === 'num' || inner.t === 'bool' || inner.t === 'str' || inner.t === 'choice') {
|
|
3672
|
+
const sort = inner.t === 'num' ? { k: 'num' } : inner.t === 'bool' ? { k: 'bool' } : inner.t === 'str' ? { k: 'str' } : { k: 'choice', values: lvalues(inner.e) };
|
|
3673
|
+
rv = g.newVar(`${fn.name}_result`, sort, 'state', `what ${fn.name} returned, at the step that called it (its default at others)`);
|
|
3674
|
+
// (a kept result of a fixed-width type within its range: a law, as a field's is)
|
|
3675
|
+
const rt = g.intTy(fn.ret?.k === 'opt' || fn.ret?.k === 'res' ? fn.ret.of : fn.ret ?? { k: 'any' });
|
|
3676
|
+
if (rt)
|
|
3677
|
+
g.ints.set(rv.name, rt);
|
|
3678
|
+
if (out.t === 'opt') {
|
|
3679
|
+
rn = g.newVar(`${fn.name}_result_none`, { k: 'bool' }, 'state', `whether ${fn.name} returned None`);
|
|
3680
|
+
kind = 'maybe';
|
|
3681
|
+
}
|
|
3682
|
+
else
|
|
3683
|
+
kind = 'scalar';
|
|
3684
|
+
}
|
|
3685
|
+
}
|
|
3686
|
+
else if (out.t !== 'none')
|
|
3687
|
+
g.notes.add(`${fn.name} returns ${out.t === 'opaque' ? out.why : `a ${out.t}`}: not kept`);
|
|
3688
|
+
resultKinds[fn.name] = kind;
|
|
3689
|
+
const fields = [];
|
|
3690
|
+
if (failedVar)
|
|
3691
|
+
fields.push(['failed', failedVar.name]);
|
|
3692
|
+
if (rv) {
|
|
3693
|
+
fields.push(['value', rv.name]);
|
|
3694
|
+
outputs.push(rv.name);
|
|
3695
|
+
state.push(rv);
|
|
3696
|
+
init[rv.name] = termOf(zeroOf(rv.sort), at);
|
|
3697
|
+
}
|
|
3698
|
+
if (rn) {
|
|
3699
|
+
fields.push(['none', rn.name]);
|
|
3700
|
+
outputs.push(rn.name);
|
|
3701
|
+
state.push(rn);
|
|
3702
|
+
init[rn.name] = { s: 'bool', e: I.F };
|
|
3703
|
+
}
|
|
3704
|
+
if (fields.length === 1 && !failedVar && rv && !rn)
|
|
3705
|
+
results[fn.name] = { k: 'scalar', name: rv.name };
|
|
3706
|
+
else if (fields.length)
|
|
3707
|
+
results[fn.name] = { k: 'rec', fields };
|
|
3708
|
+
f.rv = rv;
|
|
3709
|
+
f.rn = rn;
|
|
3710
|
+
}
|
|
3711
|
+
for (const o of outputs) {
|
|
3712
|
+
const v = g.vars.get(o);
|
|
3713
|
+
let acc = init[o];
|
|
3714
|
+
for (let i = finals.length - 1; i >= 0; i--) {
|
|
3715
|
+
const f = finals[i];
|
|
3716
|
+
const out = f.out;
|
|
3717
|
+
let t = init[o];
|
|
3718
|
+
// (a result that is None holds its sort's zero, as the check reads the code's)
|
|
3719
|
+
if (f.rv?.name === o)
|
|
3720
|
+
t = termOf(out.t === 'opt' ? g.ite(out.has, out.v, zeroLike(out.v), chosen[i]) : out, chosen[i]);
|
|
3721
|
+
if (f.rn?.name === o)
|
|
3722
|
+
t = { s: 'bool', e: out.t === 'opt' ? I.not(out.has) : I.F };
|
|
3723
|
+
if (kept && (f.rv?.name === o || f.rn?.name === o))
|
|
3724
|
+
t = iteTerm(failedOf(f), init[o], t);
|
|
3725
|
+
acc = iteTerm(f.sel, t, acc);
|
|
3726
|
+
}
|
|
3727
|
+
writes[o] = acc;
|
|
3728
|
+
void v;
|
|
3729
|
+
}
|
|
3730
|
+
if (failedVar) {
|
|
3731
|
+
outputs.push(failedVar.name);
|
|
3732
|
+
state.push(failedVar);
|
|
3733
|
+
init[failedVar.name] = { s: 'bool', e: I.F };
|
|
3734
|
+
writes[failedVar.name] = { s: 'bool', e: I.or(...finals.map(anyFail)) };
|
|
3735
|
+
}
|
|
3736
|
+
const refuseB = I.or(...g.refusals, ...(kept ? [] : finals.map(anyFail)));
|
|
3737
|
+
// Inputs no term reads are still the request's (the check builds the arguments from them).
|
|
3738
|
+
const maps = g.maps.filter(d => [...g.initHeap.values()].some(o => o.k === 'map' && o.decl === d));
|
|
3739
|
+
const stores = Object.fromEntries([...new Set([...Object.keys(opts.stores ?? {}), ...g.storeDecls.keys()])].map(n => [n, { ...g.storeDecl(n), async: g.storeAsync[n] ?? {} }]));
|
|
3740
|
+
for (const sm of g.storeMaps.values())
|
|
3741
|
+
leaves.push({ name: sm.decl.name, path: [], kind: 'map', key: sm.decl.key, store: sm.store, tpl: sm.tpl, ...(stores[sm.store]?.value !== 'int' ? { float: true } : {}) });
|
|
3742
|
+
const layout = { k: 'rec', fields: state.filter(v => !outputs.includes(v.name)).map(v => [v.name, { k: 'scalar', name: v.name }]) };
|
|
3743
|
+
for (const fn of chosen) {
|
|
3744
|
+
const used = new Set();
|
|
3745
|
+
const walk = (a) => { if (a.k === 'in')
|
|
3746
|
+
used.add(a.name);
|
|
3747
|
+
else if (a.k === 'opt') {
|
|
3748
|
+
used.add(a.none);
|
|
3749
|
+
walk(a.v);
|
|
3750
|
+
}
|
|
3751
|
+
else if (a.k === 'rec')
|
|
3752
|
+
a.f.forEach(([, x]) => walk(x)); };
|
|
3753
|
+
argsOf[fn.name].forEach(([, a]) => walk(a));
|
|
3754
|
+
for (const a of g.answers.values()) {
|
|
3755
|
+
used.add(a.inputs.name);
|
|
3756
|
+
if (a.inputs.none)
|
|
3757
|
+
used.add(a.inputs.none);
|
|
3758
|
+
}
|
|
3759
|
+
if (g.now)
|
|
3760
|
+
used.add(g.now.name);
|
|
3761
|
+
events.push({ select: ev ? { [ev.name]: fn.name } : {}, call: fn.name, args: [{ k: 'rec', fields: [...used].map(n => [n, { k: 'input', name: n }]) }] });
|
|
3762
|
+
}
|
|
3763
|
+
const laws = [];
|
|
3764
|
+
// A fixed-width field within its type's range (every state of the code is).
|
|
3765
|
+
laws.push(...rangeLaws(state, g.ints));
|
|
3766
|
+
for (const l of leaves)
|
|
3767
|
+
if (l.kind === 'none') {
|
|
3768
|
+
const base = l.name.replace(/_none$/, '');
|
|
3769
|
+
if (g.vars.get(base)?.sort.k === 'num')
|
|
3770
|
+
laws.push(`r.law(${JSON.stringify(`${base}: a None one holds 0`)}, ({${base}, ${l.name}}) => any(${l.name}.not(), ${base}.eq(0)))`);
|
|
3771
|
+
}
|
|
3772
|
+
if (g.now) {
|
|
3773
|
+
const n = g.vars.get(g.now.name);
|
|
3774
|
+
n.note = 'Date.now() (here time.time()): the time of the request, an input';
|
|
3775
|
+
}
|
|
3776
|
+
const left = leaves.filter(l => l.kind === 'frame' && !l.cls).map(l => l.path.join('.'));
|
|
3777
|
+
if (left.length)
|
|
3778
|
+
g.notes.add(`left out (outside the subset; the methods read don't touch them): ${left.join(', ')}`);
|
|
3779
|
+
// Inputs no term reads are left out of the rule (the harness gives them their sort's zero, or None).
|
|
3780
|
+
const read = new Set();
|
|
3781
|
+
const mention = (t) => { for (const n of I.varsOf(t).vars)
|
|
3782
|
+
read.add(n); };
|
|
3783
|
+
for (const t of [...Object.values(writes), ...Object.values(init)])
|
|
3784
|
+
mention(t.e);
|
|
3785
|
+
for (const w of Object.values(mapWrites)) {
|
|
3786
|
+
mention(w.has);
|
|
3787
|
+
mention(w.key);
|
|
3788
|
+
for (const t of Object.values(w.vals))
|
|
3789
|
+
mention(t.e);
|
|
3790
|
+
}
|
|
3791
|
+
mention(refuseB);
|
|
3792
|
+
mention(pre);
|
|
3793
|
+
const unread = g.inputs.filter(v => !read.has(v.name) && v.name !== ev?.name);
|
|
3794
|
+
if (unread.length)
|
|
3795
|
+
g.notes.add(`read by the code but by no term of the rule (given their sort's zero, or None, by the check): ${unread.map(v => v.name).join(', ')}`);
|
|
3796
|
+
const inputs = g.inputs.filter(v => !unread.includes(v));
|
|
3797
|
+
for (const e of events) {
|
|
3798
|
+
const a = e.args[0];
|
|
3799
|
+
a.fields = a.fields.filter(([n]) => !unread.some(v => v.name === n));
|
|
3800
|
+
}
|
|
3801
|
+
// A start that divides (a constructor's `limit / 2`): each quotient of the params a param of its own, which the
|
|
3802
|
+
// precondition fixes (k·q ≤ a < k·q + k) and the check computes from the others (a start reads the params alone,
|
|
3803
|
+
// and a quotient is no term over them).
|
|
3804
|
+
const pnames = new Set(g.params.map(v => v.name)), qs = new Map();
|
|
3805
|
+
const ok = (a) => { const r = I.varsOf(a); return !r.maps.size && [...r.vars].every(n => pnames.has(n)); };
|
|
3806
|
+
const qOf = (k, a) => {
|
|
3807
|
+
const key = I.keyOf({ k, a });
|
|
3808
|
+
let q = qs.get(key);
|
|
3809
|
+
if (!q) {
|
|
3810
|
+
q = g.newVar(`${[...I.varsOf(a).vars][0] ?? 'q'}_div${k}`, { k: 'num' }, 'param', `⌊${k === 1 ? '' : 'the start\'s dividend / '}${k}⌋ of the params (fixed by the precondition: a start divides)`);
|
|
3811
|
+
q.derived = { op: 'divk', k, a };
|
|
3812
|
+
qs.set(key, q);
|
|
3813
|
+
pre = I.and(pre, I.cmp('<=', I.mulk(k, I.nvar(q.name)), a), I.cmp('<', a, I.add(I.mulk(k, I.nvar(q.name)), I.num(k))));
|
|
3814
|
+
}
|
|
3815
|
+
return I.nvar(q.name);
|
|
3816
|
+
};
|
|
3817
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
3818
|
+
const lift = (t) => {
|
|
3819
|
+
if (Array.isArray(t))
|
|
3820
|
+
return t.map(lift);
|
|
3821
|
+
if (!t || typeof t !== 'object')
|
|
3822
|
+
return t;
|
|
3823
|
+
if ((t.op === 'divk' || t.op === 'modk') && t.k > 1) {
|
|
3824
|
+
const a = lift(t.a);
|
|
3825
|
+
if (ok(a))
|
|
3826
|
+
return t.op === 'divk' ? qOf(t.k, a) : I.sub(a, I.mulk(t.k, qOf(t.k, a)));
|
|
3827
|
+
}
|
|
3828
|
+
return Object.fromEntries(Object.entries(t).map(([k, v]) => [k, lift(v)]));
|
|
3829
|
+
};
|
|
3830
|
+
for (const [n, t] of Object.entries(init))
|
|
3831
|
+
init[n] = lift(t);
|
|
3832
|
+
pre = lift(pre);
|
|
3833
|
+
const model = {
|
|
3834
|
+
kind: cls ? 'a class and its methods' : names.length > 1 ? 'functions, each a request' : 'a function, each call a request',
|
|
3835
|
+
name: cls ? g.rec(cls, at).short : names.length === 1 ? names[0] : mod.module.split('.').pop(), shape: 'class', file: mod.file, entry: cls ? g.rec(cls, at).short : names.join(', '),
|
|
3836
|
+
params: g.params, inputs, state, maps, init, writes, mapWrites, outputs,
|
|
3837
|
+
refuse: refuseB, pre, layout, events, notes: [...g.notes], hints: g.hints, ...(ev ? { event: ev.name } : {}), results, laws,
|
|
3838
|
+
};
|
|
3839
|
+
return { ints: Object.fromEntries(g.ints), ...(g.madeAt ? { madeAt: g.madeAt.name } : {}), model, leaves, args: argsOf, answers: [...g.answers.values()], ctor, kept, arms: [...g.arms].map(a => { const i = a.lastIndexOf(':'); return [a.slice(0, i), Number(a.slice(i + 1))]; }), ...(cls ? { cls } : {}), stores, results: resultKinds, ...(g.injectedFields.length ? { inject: g.injectedFields } : {}) };
|
|
3840
|
+
}
|
|
3841
|
+
// A type's range (64 bits and wider: the rule's numbers stop at ±2^53 before the type's do, and are refused there).
|
|
3842
|
+
export const rangeOf = (ty) => (ty.bits === 0 || ty.bits >= 64 ? (ty.signed ? [-Infinity, Infinity] : [0, Infinity]) : ty.signed ? [-(2 ** (ty.bits - 1)), 2 ** (ty.bits - 1) - 1] : [0, 2 ** ty.bits - 1]);
|
|
3843
|
+
// A value of the same kind as v, its zero (unwrap_or_default).
|
|
3844
|
+
const zeroLike = (v) => (v.t === 'num' ? { t: 'num', e: I.num(0), ...(v.ty ? { ty: v.ty } : {}) } : v.t === 'bool' ? { t: 'bool', e: I.F } : v.t === 'str' ? { t: 'str', e: { op: 'slit', value: '' } } : v.t === 'choice' ? { t: 'choice', e: I.llit(lvalues(v.e)[0], lvalues(v.e)) } : { t: 'opaque', why: 'a default of no scalar kind' });
|
|
3845
|
+
// A derived Default's value of a type (a Rust field's): 0, false, "", None, the first variant.
|
|
3846
|
+
const defaultOf = (t, at) => {
|
|
3847
|
+
if (t.k === 'int' || t.k === 'float')
|
|
3848
|
+
return { t: 'num', e: I.num(0) };
|
|
3849
|
+
if (t.k === 'bool')
|
|
3850
|
+
return { t: 'bool', e: I.F };
|
|
3851
|
+
if (t.k === 'str')
|
|
3852
|
+
return { t: 'str', e: { op: 'slit', value: '' } };
|
|
3853
|
+
if (t.k === 'opt')
|
|
3854
|
+
return { t: 'none' };
|
|
3855
|
+
return refuse(at, `a Default of ${t.k} (the subset makes numbers, booleans, strings and Options)`);
|
|
3856
|
+
};
|
|
3857
|
+
// A choice term's values (an ite's are its branches').
|
|
3858
|
+
const lvalues = (e) => (e.op === 'ite' ? lvalues(e.a) : e.values);
|
|
3859
|
+
const zeroRaw = (s) => (s.k === 'num' ? 0 : s.k === 'bool' ? false : s.k === 'choice' ? s.values[0] : '');
|
|
3860
|
+
const zeroOf = (s) => (s.k === 'num' ? { t: 'num', e: I.num(0) } : s.k === 'bool' ? { t: 'bool', e: I.F } : s.k === 'choice' ? { t: 'choice', e: I.llit(s.values[0], s.values) } : { t: 'str', e: { op: 'slit', value: '' } });
|
|
3861
|
+
export function mapWritesOf(g, d, sels, ws, fix = (_, w) => w) {
|
|
3862
|
+
if (!ws.some(Boolean))
|
|
3863
|
+
return undefined;
|
|
3864
|
+
const key0 = ws.find(Boolean).key, base = (k) => { const c = g.baseCell(d, k); return { key: k, has: c.has, vals: Object.fromEntries([...c.vals].map(([f, v]) => [f, { s: v.t === 'num' ? 'num' : v.t === 'choice' ? 'choice' : 'bool', e: v.e }])) }; };
|
|
3865
|
+
let acc;
|
|
3866
|
+
for (let i = sels.length - 1; i >= 0; i--) {
|
|
3867
|
+
const w = ws[i] ? fix(i, ws[i], base) : base(acc?.key ?? key0), c = sels[i];
|
|
3868
|
+
acc = acc === undefined ? w : { key: I.kite(c, w.key, acc.key), has: I.bite(c, w.has, acc.has), vals: Object.fromEntries(Object.entries(w.vals).map(([f, t]) => [f, iteTerm(c, t, acc.vals[f])])) };
|
|
3869
|
+
}
|
|
3870
|
+
return acc;
|
|
3871
|
+
}
|
|
3872
|
+
// Each fixed-width variable within its type's range: a law every state of the code keeps.
|
|
3873
|
+
export const rangeLaws = (state, ints) => state.flatMap(v => {
|
|
3874
|
+
const ty = ints.get(v.name), law = (b) => [`r.law(${JSON.stringify(`${v.name} within its type's range`)}, ({${v.name}}) => ${v.name}.${b})`];
|
|
3875
|
+
if (!ty || v.sort.k !== 'num')
|
|
3876
|
+
return [];
|
|
3877
|
+
const [lo, hi] = rangeOf(ty);
|
|
3878
|
+
return Number.isFinite(hi) ? law(`atMost(${hi}).and(${v.name}.atLeast(${lo}))`) : lo === 0 ? law('atLeast(0)') : [];
|
|
3879
|
+
});
|
|
3880
|
+
export const varTerm = (v) => (v.sort.k === 'num' ? { s: 'num', e: I.nvar(v.name) } : v.sort.k === 'bool' ? { s: 'bool', e: I.bvar(v.name) } : v.sort.k === 'choice' ? { s: 'choice', e: { op: 'var', name: v.name, values: v.sort.values } } : { s: 'str', e: { op: 'svar', name: v.name } });
|
|
3881
|
+
export function iteTerm(c, a, b) {
|
|
3882
|
+
if (a.s === 'num' && b.s === 'num')
|
|
3883
|
+
return { s: 'num', e: I.nite(c, a.e, b.e) };
|
|
3884
|
+
if (a.s === 'bool' && b.s === 'bool')
|
|
3885
|
+
return { s: 'bool', e: I.bite(c, a.e, b.e) };
|
|
3886
|
+
if (a.s === 'choice' && b.s === 'choice')
|
|
3887
|
+
return { s: 'choice', e: I.lite(c, a.e, b.e) };
|
|
3888
|
+
if (a.s === 'str' && b.s === 'str')
|
|
3889
|
+
return { s: 'str', e: I.kite(c, a.e, b.e) };
|
|
3890
|
+
throw new Refusal('?', 'a leaf of two sorts');
|
|
3891
|
+
}
|
|
3892
|
+
const proc = globalThis.process;
|
|
3893
|
+
export const node = (id) => { const m = proc?.getBuiltinModule?.(id); if (!m)
|
|
3894
|
+
throw new Error(`the extractor runs the code's toolchain through ${id} (Node 20.16 or later, or Bun)`); return m; };
|
|
3895
|
+
export function checkStep(h, read, r, sorts, opts) {
|
|
3896
|
+
const o = opts.check ?? {}, m = read.model, bound = o.bound ?? 12;
|
|
3897
|
+
const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os');
|
|
3898
|
+
const work = fs.mkdtempSync(`${os.tmpdir()}/gdp-stepcheck-`);
|
|
3899
|
+
let child, wi = -1, ro = -1;
|
|
3900
|
+
const empty = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0, runMs: 0 };
|
|
3901
|
+
try {
|
|
3902
|
+
if (h.error)
|
|
3903
|
+
return { ...empty, mismatch: h.error };
|
|
3904
|
+
cp.execFileSync('mkfifo', [`${work}/in`, `${work}/out`], {});
|
|
3905
|
+
child = cp.spawn(h.cmd, [...h.args, `${work}/in`, `${work}/out`], { stdio: ['ignore', 'ignore', 'inherit'], env: { ...proc?.env, ...h.env } });
|
|
3906
|
+
wi = fs.openSync(`${work}/in`, 'w');
|
|
3907
|
+
ro = fs.openSync(`${work}/out`, 'r');
|
|
3908
|
+
const buf = new Uint8Array(1 << 20), dec = new TextDecoder();
|
|
3909
|
+
let pend = '';
|
|
3910
|
+
const line = () => {
|
|
3911
|
+
for (;;) {
|
|
3912
|
+
const k = pend.indexOf('\n');
|
|
3913
|
+
if (k >= 0) {
|
|
3914
|
+
const l = pend.slice(0, k);
|
|
3915
|
+
pend = pend.slice(k + 1);
|
|
3916
|
+
return l;
|
|
3917
|
+
}
|
|
3918
|
+
const n = fs.readSync(ro, buf, 0, buf.length, null);
|
|
3919
|
+
if (n === 0)
|
|
3920
|
+
return undefined;
|
|
3921
|
+
pend += dec.decode(buf.subarray(0, n), { stream: true });
|
|
3922
|
+
}
|
|
3923
|
+
};
|
|
3924
|
+
const ask = (cmd) => {
|
|
3925
|
+
fs.writeSync(wi, `${JSON.stringify(cmd)}\n`);
|
|
3926
|
+
const l = line();
|
|
3927
|
+
if (l === undefined)
|
|
3928
|
+
throw new Error('the harness stopped');
|
|
3929
|
+
return JSON.parse(l);
|
|
3930
|
+
};
|
|
3931
|
+
const hi = ask({ op: 'hello', ...h.hello, leaves: read.leaves, ctor: read.ctor, answers: read.answers, kept: read.kept, cls: read.cls ?? null, stores: read.stores, arms: read.arms, discard: opts.onError === 'discard', ...(read.inject ? { inject: read.inject } : {}) });
|
|
3932
|
+
if (hi.error)
|
|
3933
|
+
return { ...empty, mismatch: `the code doesn't load with the check's harness: ${JSON.stringify(hi.error)}` };
|
|
3934
|
+
const num = (x, at) => { const n = Number(x); if (typeof x === 'string' && Number.isSafeInteger(n) && String(n) === x)
|
|
3935
|
+
return n; throw new Outside(`${at} is ${String(x)}`); };
|
|
3936
|
+
const toSnap = (s) => {
|
|
3937
|
+
const leaves = {}, maps = {};
|
|
3938
|
+
for (const v of m.state)
|
|
3939
|
+
if (!m.outputs.includes(v.name))
|
|
3940
|
+
leaves[v.name] = v.sort.k === 'num' ? num(s[v.name], v.name) : s[v.name];
|
|
3941
|
+
for (const d of m.maps)
|
|
3942
|
+
maps[d.name] = Object.fromEntries(Object.entries((s[d.name] ?? {})).map(([k, c]) => [k, Object.fromEntries(d.fields.map(f => [f.name, f.sort.k === 'num' ? num(c[f.name], `${d.name}[${k}].${f.name}`) : c[f.name]]))]));
|
|
3943
|
+
return { leaves, maps };
|
|
3944
|
+
};
|
|
3945
|
+
const j = (x) => (typeof x === 'number' ? String(x) : x);
|
|
3946
|
+
const snapJson = (s) => ({ ...Object.fromEntries(Object.entries(s.leaves).map(([k, v]) => [k, j(v)])), ...Object.fromEntries(Object.entries(s.maps).map(([k, cells]) => [k, Object.fromEntries(Object.entries(cells).map(([key, c]) => [key, Object.fromEntries(Object.entries(c).map(([f, x]) => [f, j(x)]))]))])) });
|
|
3947
|
+
const build = (a, inputs) => (a.k === 'in' ? { in: inputs[a.name] ?? a.z ?? 0, ...(a.float ? { float: true } : {}), ...(a.sym ? { sym: true } : {}) } : a.k === 'opt' ? (inputs[a.none] === true ? { none: true } : build(a.v, inputs)) : a.k === 'rec' ? (a.f.length ? { rec: a.cls, f: Object.fromEntries(a.f.map(([f, x]) => [f, build(x, inputs)])) } : { inert: true }) : a.k === 'inert' ? { inert: true } : a.k === 'store' ? { store: a.name } : { dflt: true });
|
|
3948
|
+
const ctorArgs = (params) => read.ctor.map(([n, a]) => [n, build(a, params)]);
|
|
3949
|
+
let now = 0, inputsNow = {};
|
|
3950
|
+
// (an answer outside its type is no value the callee returns: the request is outside what the check compares)
|
|
3951
|
+
const answersOf = () => Object.fromEntries(read.answers.map(a => {
|
|
3952
|
+
const v = inputsNow[a.inputs.name] ?? 0, ty = read.ints[a.inputs.name], n = Number(v);
|
|
3953
|
+
if (a.fit && ty && !(a.inputs.none && inputsNow[a.inputs.none] === true)) {
|
|
3954
|
+
const [lo, hi] = rangeOf(ty);
|
|
3955
|
+
if (n < lo || n > hi)
|
|
3956
|
+
throw new Outside(`${a.key} answers ${String(v)}, outside its type`);
|
|
3957
|
+
}
|
|
3958
|
+
return [a.key, a.inputs.none && inputsNow[a.inputs.none] === true ? { none: true } : { in: v, ...(a.inputs.float ? { float: true } : {}) }];
|
|
3959
|
+
}));
|
|
3960
|
+
let coverage;
|
|
3961
|
+
const r0 = performance.now();
|
|
3962
|
+
const side = {
|
|
3963
|
+
make: params => { const res = ask({ op: 'new', a: ctorArgs(params), now: read.madeAt ? params[read.madeAt] : 0 }); return res.err !== undefined ? { ok: false, error: JSON.stringify(res.err) } : { ok: true, value: res.id }; },
|
|
3964
|
+
at: (s, params) => { const res = ask({ op: 'at', a: ctorArgs(params), now: read.madeAt ? params[read.madeAt] : 0, state: snapJson(s) }); return res.bad ? undefined : res.id; },
|
|
3965
|
+
snapOf: self => { const res = ask({ op: 'get', id: self }); if (res.error)
|
|
3966
|
+
throw new Error(JSON.stringify(res.error)); return toSnap(res.state); },
|
|
3967
|
+
call: (self, e, args) => {
|
|
3968
|
+
const res = ask({ op: 'call', id: self, m: e.call, a: args, now, answers: answersOf() });
|
|
3969
|
+
if (res.frame)
|
|
3970
|
+
throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
|
|
3971
|
+
if (res.bad !== undefined)
|
|
3972
|
+
return { ok: false, error: `the code can't be given it (${res.bad})` };
|
|
3973
|
+
const kind = read.results[e.call] ?? 'none', failed = res.err !== undefined;
|
|
3974
|
+
if (failed && !read.kept)
|
|
3975
|
+
return { ok: false, error: `raised: ${res.err}` };
|
|
3976
|
+
const value = (x) => { const t = x; if (t && typeof t === 'object') {
|
|
3977
|
+
if (t.n !== undefined)
|
|
3978
|
+
return num(t.n, `${e.call}'s result`);
|
|
3979
|
+
if (t.s !== undefined)
|
|
3980
|
+
return t.s;
|
|
3981
|
+
return `<${t.o}>`;
|
|
3982
|
+
} return x; };
|
|
3983
|
+
const out = res.out;
|
|
3984
|
+
const rk = m.results?.[e.call];
|
|
3985
|
+
if (!rk)
|
|
3986
|
+
return { ok: true, value: undefined };
|
|
3987
|
+
if (rk.k === 'scalar')
|
|
3988
|
+
return { ok: true, value: value(out) };
|
|
3989
|
+
const o = {};
|
|
3990
|
+
for (const [f] of rk.fields) {
|
|
3991
|
+
if (f === 'failed')
|
|
3992
|
+
o.failed = failed;
|
|
3993
|
+
if (f === 'value') {
|
|
3994
|
+
const rv = m.state.find(v => v.name === rk.fields.find(x => x[0] === 'value')[1]);
|
|
3995
|
+
o.value = failed || out === null || out === undefined ? (rv.sort.k === 'num' ? 0 : rv.sort.k === 'bool' ? false : rv.sort.k === 'choice' ? rv.sort.values[0] : '') : value(out);
|
|
3996
|
+
}
|
|
3997
|
+
if (f === 'none')
|
|
3998
|
+
o.none = !failed && (out === null || out === undefined) && kind === 'maybe';
|
|
3999
|
+
}
|
|
4000
|
+
return { ok: true, value: o };
|
|
4001
|
+
},
|
|
4002
|
+
args: (inputs, e) => { inputsNow = inputs; return (read.args[e.call] ?? []).map(([n, a]) => [n, build(a, inputs)]); },
|
|
4003
|
+
setNow: n => { now = n; },
|
|
4004
|
+
coverage: () => (coverage ??= closeAndCount()),
|
|
4005
|
+
drawSnap: rand => {
|
|
4006
|
+
const leaves = {}, maps = {};
|
|
4007
|
+
const consts = constantsOf(m), strs = ['a', 'b', 'c', ''];
|
|
4008
|
+
for (const v of m.state) {
|
|
4009
|
+
if (m.outputs.includes(v.name))
|
|
4010
|
+
continue;
|
|
4011
|
+
let x = draw(v.sort, sorts, v.name, rand, consts, bound, strs);
|
|
4012
|
+
if (typeof x === 'number' && sorts.get(v.name) === 'nat' && x < 0)
|
|
4013
|
+
x = -x;
|
|
4014
|
+
if (typeof x === 'number' && Math.abs(x) > Number.MAX_SAFE_INTEGER / 4)
|
|
4015
|
+
x = rand(bound);
|
|
4016
|
+
leaves[v.name] = x;
|
|
4017
|
+
}
|
|
4018
|
+
for (const l of read.leaves)
|
|
4019
|
+
if (l.kind === 'none' && leaves[l.name] === true)
|
|
4020
|
+
leaves[l.name.replace(/_none$/, '')] = g0(m, l.name.replace(/_none$/, ''));
|
|
4021
|
+
for (const d of m.maps) {
|
|
4022
|
+
const cells = {};
|
|
4023
|
+
for (let i = rand(4); i > 0; i--) {
|
|
4024
|
+
const key = d.key === 'str' ? strs[rand(3)] : String(rand(4));
|
|
4025
|
+
cells[key] = Object.fromEntries(d.fields.map(f => { let x = draw(f.sort, sorts, `${d.name}.${f.name}`, rand, consts, bound, strs); if (typeof x === 'number' && sorts.get(`${d.name}.${f.name}`) === 'nat')
|
|
4026
|
+
x = Math.abs(x); return [f.name, x]; }));
|
|
4027
|
+
}
|
|
4028
|
+
maps[d.name] = cells;
|
|
4029
|
+
}
|
|
4030
|
+
return { leaves, maps };
|
|
4031
|
+
},
|
|
4032
|
+
normalize: s => { for (const l of read.leaves)
|
|
4033
|
+
if (l.kind === 'none' && s.leaves[l.name] === true)
|
|
4034
|
+
s.leaves[l.name.replace(/_none$/, '')] = g0(m, l.name.replace(/_none$/, '')); return s; },
|
|
4035
|
+
};
|
|
4036
|
+
function closeAndCount() {
|
|
4037
|
+
const res = ask({ op: 'coverage' });
|
|
4038
|
+
fs.closeSync(wi);
|
|
4039
|
+
wi = -1;
|
|
4040
|
+
const hit = new Set((res.hit ?? []).map(([f, l]) => `${f}:${l}`));
|
|
4041
|
+
const arms = read.arms.map(([f, l]) => `${f}:${l}`);
|
|
4042
|
+
return { arms: arms.length, hit: arms.filter(a => hit.has(a)).length, missed: arms.filter(a => !hit.has(a)).map(a => `the arm at ${a}`) };
|
|
4043
|
+
}
|
|
4044
|
+
const ev = drive(m, r, sorts, side, o);
|
|
4045
|
+
return { ...ev, runMs: Math.round(performance.now() - r0) };
|
|
4046
|
+
}
|
|
4047
|
+
catch (x) {
|
|
4048
|
+
return { ...empty, mismatch: `the check's harness: ${x.message}` };
|
|
4049
|
+
}
|
|
4050
|
+
finally {
|
|
4051
|
+
if (wi >= 0)
|
|
4052
|
+
try {
|
|
4053
|
+
fs.closeSync(wi);
|
|
4054
|
+
}
|
|
4055
|
+
catch { /* closed */ }
|
|
4056
|
+
if (ro >= 0)
|
|
4057
|
+
try {
|
|
4058
|
+
fs.closeSync(ro);
|
|
4059
|
+
}
|
|
4060
|
+
catch { /* closed */ }
|
|
4061
|
+
try {
|
|
4062
|
+
child?.kill();
|
|
4063
|
+
}
|
|
4064
|
+
catch { /* gone */ }
|
|
4065
|
+
try {
|
|
4066
|
+
fs.rmSync(work, { recursive: true, force: true });
|
|
4067
|
+
}
|
|
4068
|
+
catch { /* gone */ }
|
|
4069
|
+
}
|
|
4070
|
+
}
|
|
4071
|
+
// The value a None leaf holds in the rule (its sort's zero).
|
|
4072
|
+
const g0 = (m, name) => { const v = m.state.find(x => x.name === name); return v?.sort.k === 'num' ? 0 : v?.sort.k === 'bool' ? false : v?.sort.k === 'choice' ? v.sort.values[0] : ''; };
|
|
4073
|
+
// A front end's whole run: the module read, the model printed and built, the code run beside it.
|
|
4074
|
+
export function extractStep(mod, h, opts) {
|
|
4075
|
+
const notes = [];
|
|
4076
|
+
let read;
|
|
4077
|
+
try {
|
|
4078
|
+
read = readStep(mod, opts);
|
|
4079
|
+
}
|
|
4080
|
+
catch (e) {
|
|
4081
|
+
if (e instanceof Refusal)
|
|
4082
|
+
return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
|
|
4083
|
+
throw e;
|
|
4084
|
+
}
|
|
4085
|
+
const unsigned = Object.fromEntries([...read.model.inputs, ...read.model.params].filter(v => read.ints[v.name] && !read.ints[v.name].signed).map(v => [v.name, 'nat']));
|
|
4086
|
+
const x = fromModel(read.model, mod.file, { ...unsigned, ...opts.domains }, notes, (rule, sorts) => checkStep(h(read), read, rule, sorts, opts));
|
|
4087
|
+
return { ...x, read, names: stepNames(read) };
|
|
4088
|
+
}
|
|
4089
|
+
// The names of a reading: each leaf of the state by its path, the constructor's and each method's arguments (an object
|
|
4090
|
+
// the caller gives by its fields), each answer by its callee's qualified name, each method's result, the failure.
|
|
4091
|
+
export function stepNames(read) {
|
|
4092
|
+
const out = [], m = read.model, at = (code) => out.find(n => n.code === code && n.role === 'state');
|
|
4093
|
+
for (const l of read.leaves) {
|
|
4094
|
+
const code = l.path.join('.');
|
|
4095
|
+
if (l.kind === 'map')
|
|
4096
|
+
out.push({ code: l.store ?? code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [], ...(l.store ? { store: l.store, tpl: l.tpl ?? '{}' } : {}) } });
|
|
4097
|
+
else if (l.kind === 'none') {
|
|
4098
|
+
const n = at(code);
|
|
4099
|
+
if (n)
|
|
4100
|
+
n.none = l.name;
|
|
4101
|
+
else
|
|
4102
|
+
out.push({ code, rule: '', role: 'state', none: l.name });
|
|
4103
|
+
}
|
|
4104
|
+
else if (l.kind !== 'frame')
|
|
4105
|
+
out.push({ code, rule: l.name, role: 'state' });
|
|
4106
|
+
}
|
|
4107
|
+
const arg = (a, code, role, method) => {
|
|
4108
|
+
const k = method ? { method } : {};
|
|
4109
|
+
if (a.k === 'in')
|
|
4110
|
+
out.push({ code, rule: a.name, role, ...k });
|
|
4111
|
+
else if (a.k === 'opt') {
|
|
4112
|
+
const n = out.length;
|
|
4113
|
+
arg(a.v, code, role, method);
|
|
4114
|
+
if (out[n]?.code === code)
|
|
4115
|
+
out[n].none = a.none;
|
|
4116
|
+
else
|
|
4117
|
+
out.push({ code, rule: '', role, none: a.none, ...k });
|
|
4118
|
+
}
|
|
4119
|
+
else if (a.k === 'rec')
|
|
4120
|
+
for (const [f, x] of a.f)
|
|
4121
|
+
arg(x, `${code}.${f}`, role, method);
|
|
4122
|
+
};
|
|
4123
|
+
for (const [code, a] of read.ctor)
|
|
4124
|
+
arg(a, code, 'param');
|
|
4125
|
+
for (const [method, as] of Object.entries(read.args))
|
|
4126
|
+
for (const [code, a] of as)
|
|
4127
|
+
arg(a, code, 'input', method);
|
|
4128
|
+
for (const a of read.answers)
|
|
4129
|
+
out.push({ code: a.key, rule: a.inputs.name, role: 'answer', ...(a.inputs.none ? { none: a.inputs.none } : {}) });
|
|
4130
|
+
const vars = new Set([...m.state, ...m.inputs].map(v => v.name));
|
|
4131
|
+
for (const [method, k] of Object.entries(read.results))
|
|
4132
|
+
if (k !== 'none')
|
|
4133
|
+
out.push({ code: 'result', rule: `${method}_result`, role: 'result', method, ...(k === 'maybe' ? { none: `${method}_result_none` } : {}) });
|
|
4134
|
+
if (vars.has('failed'))
|
|
4135
|
+
out.push({ code: 'failed', rule: 'failed', role: 'failed' });
|
|
4136
|
+
if (vars.has('now'))
|
|
4137
|
+
out.push({ code: 'now', rule: 'now', role: 'clock' });
|
|
4138
|
+
if (m.event)
|
|
4139
|
+
out.push({ code: 'method', rule: m.event, role: 'method' });
|
|
4140
|
+
return out;
|
|
4141
|
+
}
|