gdp-wired 0.31.1 → 0.33.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 +95 -6
- package/dist/core/c/reader.d.ts +86 -0
- package/dist/core/c/reader.js +860 -0
- package/dist/core/check.js +20 -6
- package/dist/core/cli.d.ts +76 -0
- package/dist/core/cli.js +636 -0
- package/dist/core/dsl.d.ts +6 -4
- package/dist/core/dsl.js +30 -16
- 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 +19 -5
- 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.d.ts +4 -0
- package/dist/core/infer.js +1838 -69
- 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 +83 -0
- package/dist/core/laws.js +623 -0
- package/dist/core/machine.d.ts +2 -0
- package/dist/core/machine.js +87 -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/relational.d.ts +49 -0
- package/dist/core/relational.js +345 -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/interchange/check.d.ts +16 -0
- package/dist/interchange/check.js +111 -0
- package/dist/interchange/format.d.ts +150 -0
- package/dist/interchange/format.js +678 -0
- package/dist/kernel/epr.d.ts +40 -0
- package/dist/kernel/epr.js +1882 -0
- package/dist/kernel/kernel.d.ts +45 -1
- package/dist/kernel/kernel.js +138 -13
- package/dist/kernel/prove.d.ts +45 -0
- package/dist/kernel/prove.js +658 -51
- package/dist/lean-kernel/emit.d.ts +17 -2
- package/dist/lean-kernel/emit.js +87 -7
- package/package.json +57 -2
|
@@ -0,0 +1,1166 @@
|
|
|
1
|
+
// The extractor's Go front end (`extractGo`): a struct's methods read through Go's own parser and type checker
|
|
2
|
+
// (core/go/reader.go, go/ast and go/types, run with the Go toolchain), lowered here into the shared step IR and executed
|
|
3
|
+
// by the shared executor (core/extract-step.ts) into the same Model every front end makes, printed, built and checked
|
|
4
|
+
// as that one is (core/extract.ts's fromModel). The lowering decides what Go's types decide (which operation a node is,
|
|
5
|
+
// the width of an integer, a refusal that needs no execution); the executor does what the values decide. Only the
|
|
6
|
+
// reader, the lowering and the check's runner are Go's: the check (core/extract-go-check.ts) builds the package as it
|
|
7
|
+
// ships with a generated harness beside it, drives the methods with the same requests as the rule, and prints every
|
|
8
|
+
// state as JSON for the comparison core/extract-check.ts makes. Nothing here is trusted either.
|
|
9
|
+
//
|
|
10
|
+
// The subset: a named struct of the package and the methods given (pointer or value receivers), the object starting
|
|
11
|
+
// at Go's zero value; fields of integer types (every width, signed and unsigned, named ones such as time.Duration),
|
|
12
|
+
// bool, string, *big.Int (an unbounded integer, nil a state of its own), nested structs (embedded ones too), maps from
|
|
13
|
+
// integers or strings to integers, booleans or structs of them, and slices of integers or booleans as lists; locals,
|
|
14
|
+
// assignments (=, :=, op=, ++, --, tuples), if, switch (with a tag or without, fallthrough, break), early returns,
|
|
15
|
+
// calls of the package's functions and methods (inlined), pointers to the state's objects (an interior pointer &x.f
|
|
16
|
+
// too: a write through one is a write to the object), errors.New and fmt.Errorf (a non-nil error), big.NewInt,
|
|
17
|
+
// new(big.Int) and big.Int's Add, Sub, Mul, Neg, Abs, Set, SetInt64, SetUint64, Cmp, Sign, Int64, IsInt64, the
|
|
18
|
+
// builtins len, append, delete, make, new, min, max and panic, conversions between integer types, a sync.Mutex's
|
|
19
|
+
// Lock with its deferred Unlock (one step is atomic in the rule), a context.Context argument only passed on to the
|
|
20
|
+
// package's own functions, and a pointer to another package's struct as an argument (its exported fields read as
|
|
21
|
+
// inputs, the package read from its source in the repo: core/go/reader.go's foreignPackage).
|
|
22
|
+
//
|
|
23
|
+
// Integers are exactly Go's. A result past its type's range wraps in Go: at 8, 16 and 32 bits the rule takes it modulo
|
|
24
|
+
// 2^n by cases (x + 1 past 2^32 − 1 is 0), as compare/term/c2ari.py takes C's unsigned arithmetic; at 64 bits the rule's
|
|
25
|
+
// numbers stop at ±2^53 (its runtime refuses past them, as for JavaScript's numbers), and a uint64 below 0, which Go
|
|
26
|
+
// would wrap to 2^64 − x, is refused. Division and remainder by a constant truncate toward zero, as Go's do; >> by a
|
|
27
|
+
// constant is a floor division, << a product, both wrapped. An error result that isn't nil, and a panic (explicit, a
|
|
28
|
+
// nil dereference, an index out of range, a write to a nil map), are the rule's refusals; the state must be as it was
|
|
29
|
+
// there (a write before them is refused) unless the caller discards what a failed call wrote (`onError: 'discard'`).
|
|
30
|
+
//
|
|
31
|
+
// Refused, each where it is with why: loops (a range over a map besides: Go's order is random), goroutines, channels,
|
|
32
|
+
// closures, defer (but a mutex's Unlock), recover, floats, strings beyond set and compared, bit operations, package
|
|
33
|
+
// variables (shared by every object), interfaces and type switches, generics, another module's code, a slice under a
|
|
34
|
+
// second name (two slices may share a backing array: append writes into it or not by its capacity), one object in
|
|
35
|
+
// two of the state's places or a pointer the caller gave kept in the state, a map replaced whole, two keys of one map
|
|
36
|
+
// or two writes of one list in one step.
|
|
37
|
+
import * as I from "./extract-ir.js";
|
|
38
|
+
import { Refusal, pathOf } from "./extract-read.js";
|
|
39
|
+
import { fromModel } from "./extract.js";
|
|
40
|
+
import { Stepper, iteTerm, mapWritesOf, phiP, rangeLaws, rangeOf, varTerm } from "./extract-step.js";
|
|
41
|
+
import { checkGo } from "./extract-go-check.js";
|
|
42
|
+
export { proveRule, proveSteps } from "./dsl.js";
|
|
43
|
+
const refuse = (x, what) => { throw new Refusal(typeof x === 'string' ? x : x.p || '?', what); };
|
|
44
|
+
// --- the lowering: Go's JSON into the step IR, what the types decide decided here ------------------------------------
|
|
45
|
+
class Go {
|
|
46
|
+
pkg;
|
|
47
|
+
opts;
|
|
48
|
+
g;
|
|
49
|
+
leaves = [];
|
|
50
|
+
funcs = {};
|
|
51
|
+
constructor(pkg, opts, inf) {
|
|
52
|
+
this.pkg = pkg;
|
|
53
|
+
this.opts = opts;
|
|
54
|
+
const mod = { lang: pkg.lang ?? 'go', file: pkg.files[0]?.name ?? 'go', path: pkg.dir ? `${pkg.dir}/${pkg.files[0]?.name ?? ''}` : '', module: pkg.package, root: pkg.dir ?? '', entries: [], recs: {}, funcs: this.funcs, split: false };
|
|
55
|
+
this.g = new Stepper(mod, { entry: opts.entry, ...(opts.onError ? { onError: opts.onError } : {}) }, inf);
|
|
56
|
+
for (const f of pkg.funcs)
|
|
57
|
+
this.funcs[`${f.recv?.type ?? ''}.${f.name}`] = this.fn(f);
|
|
58
|
+
}
|
|
59
|
+
T(t) { return this.pkg.ttab[t] ?? { k: 'invalid' }; }
|
|
60
|
+
// (another package's types by its name, not the harness's alias for it)
|
|
61
|
+
tname(t) { const x = this.T(t); return x.go?.replace(/\bgdp_(?:\w*_)?(\w+)\./g, '$1.') ?? x.name ?? x.k; }
|
|
62
|
+
intTy(t) { const x = this.T(t); return x.k === 'int' ? { bits: x.untyped ? 64 : x.bits ?? 64, signed: x.signed ?? true, t, name: this.tname(t), ...(x.ub ? { ub: true } : {}) } : undefined; }
|
|
63
|
+
isBig(t) { const x = this.T(t); return x.k === 'ext' && x.pkg === 'math/big' && x.name === 'Int'; }
|
|
64
|
+
isBigPtr(t) { const x = this.T(t); return x.k === 'ptr' && this.isBig(x.elem); }
|
|
65
|
+
isContext(t) { const x = this.T(t); return x.k === 'ext' && x.pkg === 'context' && x.name === 'Context'; }
|
|
66
|
+
isMutex(t) { const x = this.T(t); return x.mutex === true || (x.k === 'ext' && x.pkg === 'sync' && (x.name === 'Mutex' || x.name === 'RWMutex')); }
|
|
67
|
+
stdlib(path) { return !path.split('/')[0].includes('.'); }
|
|
68
|
+
// The scalar sort a field of type t is in the rule, or why it isn't one.
|
|
69
|
+
scalar(t) {
|
|
70
|
+
const x = this.T(t);
|
|
71
|
+
if (x.k === 'int')
|
|
72
|
+
return { k: 'num' };
|
|
73
|
+
if (x.k === 'bool')
|
|
74
|
+
return { k: 'bool' };
|
|
75
|
+
if (x.k === 'string')
|
|
76
|
+
return { k: 'str' };
|
|
77
|
+
if (x.k === 'float')
|
|
78
|
+
return `${this.tname(t)}: a float (a binary fraction that rounds; the subset reads integers)`;
|
|
79
|
+
return `${this.tname(t)}: a value outside the subset`;
|
|
80
|
+
}
|
|
81
|
+
// Why a type is outside the subset, by what it is made of.
|
|
82
|
+
whyType(t, depth = 0) {
|
|
83
|
+
const x = this.T(t);
|
|
84
|
+
if (x.k === 'invalid')
|
|
85
|
+
return "another module's type";
|
|
86
|
+
if (x.k === 'ext' && x.iface)
|
|
87
|
+
return 'an interface';
|
|
88
|
+
if ((x.k === 'ext' || x.name) && x.pkg && !this.stdlib(x.pkg))
|
|
89
|
+
return "another module's type";
|
|
90
|
+
if (x.k === 'ext' && x.pkg === 'time' && x.name === 'Time')
|
|
91
|
+
return "the clock's time (time.Time is outside the subset)";
|
|
92
|
+
if (x.k === 'error' || x.k === 'iface' || x.iface)
|
|
93
|
+
return 'an interface';
|
|
94
|
+
if (x.k === 'func')
|
|
95
|
+
return 'a function';
|
|
96
|
+
if (x.k === 'float')
|
|
97
|
+
return 'a float';
|
|
98
|
+
if (x.k === 'chan')
|
|
99
|
+
return 'a channel';
|
|
100
|
+
if ((x.k === 'ptr' || x.k === 'slice' || x.k === 'array' || x.k === 'map') && depth < 4) {
|
|
101
|
+
for (const i of x.k === 'map' ? [x.key, x.elem] : [x.elem]) {
|
|
102
|
+
const w = this.whyType(i, depth + 1);
|
|
103
|
+
if (w !== 'outside the subset')
|
|
104
|
+
return x.k === 'map' ? `a map of ${w}` : x.k === 'ptr' ? w : `a ${x.k} of ${w}`;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (x.k === 'ext')
|
|
108
|
+
return `${x.go ?? x.name}, a type of the standard library outside the subset`;
|
|
109
|
+
return 'outside the subset';
|
|
110
|
+
}
|
|
111
|
+
methodOf(type, name) { return this.pkg.funcs.find(f => f.recv?.type === type && f.name === name); }
|
|
112
|
+
funcOf(name) { return this.pkg.funcs.find(f => !f.recv && f.name === name); }
|
|
113
|
+
// --- expressions ----------------------------------------------------------------------------------------------------
|
|
114
|
+
no(x, why, more = {}) { return { e: 'no', p: x.p, why, ...more }; }
|
|
115
|
+
// A call of another package's code: at the boundary where it is inferred, its object and arguments lowered (the
|
|
116
|
+
// executor evaluates them, as Go does, and refuses the call where they give it the state).
|
|
117
|
+
// (its result's type, where a scalar: an answer's; its end and its type's name: where the check stubs it)
|
|
118
|
+
ext(x, why, name, recv) {
|
|
119
|
+
const k = this.T(x.t).k, it = this.intTy(x.t), ret = it ? { k: 'int', bits: it.bits, signed: it.signed } : k === 'bool' ? { k: 'bool' } : k === 'string' ? { k: 'str' } : undefined;
|
|
120
|
+
return this.no(x, why, { ext: name, args: (x.a ?? []).map(y => this.x(y)), kw: [], ...(recv ? { recv: this.x(recv) } : {}), ...(ret ? { ret, ty: this.tname(x.t) } : {}), ...(x.end ? { end: x.end } : {}) });
|
|
121
|
+
}
|
|
122
|
+
at(x) { return { p: x.p, text: x.text }; }
|
|
123
|
+
// A value as the type it is assigned to: an untyped constant takes the type; an integer stays itself.
|
|
124
|
+
as(v, t) {
|
|
125
|
+
const ty = this.intTy(t), k = this.T(t).k;
|
|
126
|
+
return ty || k === 'ptr' || k === 'error' ? { e: 'as', p: v.p, x: v, ...(ty ? { ity: ty } : { nil: k === 'ptr' ? 'ptr' : 'err' }) } : v;
|
|
127
|
+
}
|
|
128
|
+
// Go's zero value of a type.
|
|
129
|
+
zero(t, at) {
|
|
130
|
+
const tt = this.T(t);
|
|
131
|
+
if (tt.k === 'int')
|
|
132
|
+
return { e: 'int', p: at.p, v: 0, ity: this.intTy(t) };
|
|
133
|
+
if (tt.k === 'bool')
|
|
134
|
+
return { e: 'bool', p: at.p, v: false };
|
|
135
|
+
if (tt.k === 'string')
|
|
136
|
+
return { e: 'str', p: at.p, v: '' };
|
|
137
|
+
if (tt.k === 'ptr')
|
|
138
|
+
return { e: 'ptr0', p: at.p };
|
|
139
|
+
if (tt.k === 'error')
|
|
140
|
+
return { e: 'errv', p: at.p, is: false };
|
|
141
|
+
if (tt.k === 'struct') {
|
|
142
|
+
return { e: 'struct', p: at.p, ty: String(t), fields: (tt.fields ?? []).map(g => {
|
|
143
|
+
const s = this.scalar(g.t);
|
|
144
|
+
return [g.name, typeof s === 'string' && !['ptr', 'struct', 'error'].includes(this.T(g.t).k) ? { e: 'opaque', p: at.p, why: `${g.name}: ${s}`, firm: true } : this.zero(g.t, at)];
|
|
145
|
+
}) };
|
|
146
|
+
}
|
|
147
|
+
return { e: 'opaque', p: at.p, why: `a value of type ${this.tname(t)} (outside the subset)`, firm: true };
|
|
148
|
+
}
|
|
149
|
+
x(x) {
|
|
150
|
+
const at = this.at(x), c = x.c;
|
|
151
|
+
if (c) {
|
|
152
|
+
if (c.int !== undefined) {
|
|
153
|
+
const ty = this.intTy(x.t);
|
|
154
|
+
if (!ty)
|
|
155
|
+
return this.no(x, this.T(x.t).k === 'float' ? `${x.text}: a float constant (the subset reads integers)` : `${x.text}: an integer constant of type ${this.tname(x.t)}`);
|
|
156
|
+
const v = Number(c.int);
|
|
157
|
+
if (!Number.isSafeInteger(v))
|
|
158
|
+
return this.no(x, `${x.text}: the constant ${c.int} is past 2^53 (the rule's numbers stop there)`);
|
|
159
|
+
return { e: 'int', ...at, v, ity: ty };
|
|
160
|
+
}
|
|
161
|
+
if (c.bool !== undefined)
|
|
162
|
+
return { e: 'bool', ...at, v: c.bool };
|
|
163
|
+
if (c.str !== undefined)
|
|
164
|
+
return { e: 'str', ...at, v: c.str };
|
|
165
|
+
return this.no(x, `${x.text}: ${c.float !== undefined ? 'a float constant (the subset reads integers)' : "a constant the subset doesn't read"}`);
|
|
166
|
+
}
|
|
167
|
+
switch (x.e) {
|
|
168
|
+
case 'id': {
|
|
169
|
+
if (x.o === 'nil')
|
|
170
|
+
return { e: 'nil', ...at };
|
|
171
|
+
if (x.o !== 'var')
|
|
172
|
+
return this.no(x, `${x.text}: a ${x.o} used as a value`);
|
|
173
|
+
if (!x.id?.startsWith('pkg:'))
|
|
174
|
+
return { e: 'var', ...at, n: x.id, why: `${x.n}: a variable the step doesn't set before reading` };
|
|
175
|
+
const v = this.pkg.vars.find(y => `pkg:${y.name}` === x.id), f = v?.init?.f;
|
|
176
|
+
if (v && this.T(v.t).k === 'error' && v.init?.e === 'call' && f?.e === 'sel' && ((f.pkg === 'errors' && f.n === 'New') || (f.pkg === 'fmt' && f.n === 'Errorf')))
|
|
177
|
+
return { e: 'errv', ...at, is: true, note: `${x.n}: an error the package makes once (errors.New): read as an error that isn't nil` };
|
|
178
|
+
return this.no(x, `${x.n}: a package variable (state every object shares)`);
|
|
179
|
+
}
|
|
180
|
+
case 'sel':
|
|
181
|
+
if (x.k === 'field')
|
|
182
|
+
return { e: 'at', ...at, pl: this.place(x) };
|
|
183
|
+
if (x.k === 'qual')
|
|
184
|
+
return this.no(x, x.pkg === 'math' && /^(Max|Min)(Int|Uint)\d*$/.test(x.n) ? `${x.text}: a constant past 2^53` : `${x.text}: ${x.pkg && !this.stdlib(x.pkg) ? "another module's" : 'a package-level'} ${x.o === 'var' ? 'variable' : 'value'} the subset doesn't read`);
|
|
185
|
+
return this.no(x, `${x.text}: a method used as a value`);
|
|
186
|
+
case 'paren': return this.x(x.x);
|
|
187
|
+
case 'call': return this.call(x);
|
|
188
|
+
case 'bin': return { e: x.op === '&&' || x.op === '||' ? 'andalso' : 'binop', ...at, op: x.op, x: this.x(x.x), y: this.x(x.y) };
|
|
189
|
+
case 'un': {
|
|
190
|
+
if (x.op === '&')
|
|
191
|
+
return x.x.e === 'comp' ? { e: 'alloc', ...at, x: this.composite(x.x) } : { e: 'addr', ...at, pl: this.place(x.x), why: `&${x.x.text}: a pointer to a local (the subset's pointers are to the state's objects and to new ones)` };
|
|
192
|
+
return { e: 'unop', ...at, op: x.op, x: this.x(x.x), why: `${x.op}: ${x.op === '^' ? 'a bit operation' : 'outside the subset'}` };
|
|
193
|
+
}
|
|
194
|
+
case 'star': return { e: 'deref', ...at, x: this.x(x.x) };
|
|
195
|
+
case 'comp': return this.composite(x);
|
|
196
|
+
case 'index': {
|
|
197
|
+
const xt = this.T(x.x.t);
|
|
198
|
+
if (xt.k === 'map')
|
|
199
|
+
return this.midx(x);
|
|
200
|
+
if (xt.k === 'slice' || xt.fixed)
|
|
201
|
+
return { e: 'lidx', ...at, s: this.x(x.x), i: this.x(x.i), ty: this.intTy(xt.elem) };
|
|
202
|
+
return this.no(x, `${x.text}: an index into a ${this.tname(x.x.t)}`, { pre: [this.x(x.x), this.x(x.i)] });
|
|
203
|
+
}
|
|
204
|
+
case 'slice': {
|
|
205
|
+
// s[:len(s)-1] of a slice of the state: its last item taken off (put back in s's own place).
|
|
206
|
+
const h = x.hi, ok = !x.lo && !x.three && h?.e === 'bin' && h.op === '-' && h.y?.c?.int === '1' && h.x?.e === 'call' && h.x.builtin === 'len' && h.x.a?.[0]?.text === x.x.text;
|
|
207
|
+
return { e: 'pop', ...at, s: this.x(x.x), ok, why: `${x.text}: a slice of a slice (it shares the backing array: a write through either is seen by both, and append writes into it or not by its capacity)` };
|
|
208
|
+
}
|
|
209
|
+
case 'no': return this.no(x, x.why);
|
|
210
|
+
case 'ite': return { e: 'ite', ...at, c: this.x(x.x), a: this.x(x.y), b: this.x(x.b) };
|
|
211
|
+
case 'funclit': return this.no(x, 'a closure');
|
|
212
|
+
case 'assert': return this.no(x, 'a type assertion (interfaces are outside the subset)');
|
|
213
|
+
case 'inst': return this.no(x, 'a generic function');
|
|
214
|
+
case 'lit': return this.no(x, `${x.text}: a literal of type ${this.tname(x.t)}`);
|
|
215
|
+
}
|
|
216
|
+
return this.no(x, `${x.text}: an expression the subset doesn't read (${x.e})`);
|
|
217
|
+
}
|
|
218
|
+
midx(x) {
|
|
219
|
+
const mt = this.T(x.x.t), vt = this.T(mt.elem);
|
|
220
|
+
const tys = Object.fromEntries((vt.k === 'struct' ? vt.fields : [{ name: 'value', t: mt.elem }]).map(f => [f.name, this.intTy(f.t) ?? null]));
|
|
221
|
+
return { e: 'midx', ...this.at(x), m: this.x(x.x), k: this.x(x.i), tys, sty: String(mt.elem) };
|
|
222
|
+
}
|
|
223
|
+
// A place: a local (and a field path into its struct value), or a field path inside the object a pointer points to.
|
|
224
|
+
place(x) {
|
|
225
|
+
if (x.e === 'id') {
|
|
226
|
+
if (x.n === '_')
|
|
227
|
+
return { e: 'blank', p: x.p };
|
|
228
|
+
if (x.o !== 'var' || x.id?.startsWith('pkg:'))
|
|
229
|
+
return this.no(x, `${x.text}: ${x.id?.startsWith('pkg:') ? 'a package variable (state every object shares)' : 'not a local'}`);
|
|
230
|
+
return { e: 'var', ...this.at(x), n: x.id };
|
|
231
|
+
}
|
|
232
|
+
if (x.e === 'star')
|
|
233
|
+
return { e: 'deref', ...this.at(x), x: this.x(x.x) };
|
|
234
|
+
if (x.e === 'sel' && x.k === 'field') {
|
|
235
|
+
// The field names a selection goes through (its embedded fields first); through a pointer (or an embedded
|
|
236
|
+
// pointer on the way) the place is the pointee's.
|
|
237
|
+
let t = this.T(x.x.t);
|
|
238
|
+
const base = t.k === 'ptr' ? { e: 'deref', ...this.at(x), x: this.x(x.x) } : this.place(x.x);
|
|
239
|
+
if (t.k === 'ptr')
|
|
240
|
+
t = this.T(t.elem);
|
|
241
|
+
let cur = base;
|
|
242
|
+
const path = x.path ?? [];
|
|
243
|
+
for (let i = 0; i < path.length; i++) {
|
|
244
|
+
const f = (t.fields ?? t.xfields)?.[path[i]];
|
|
245
|
+
if (!f)
|
|
246
|
+
return this.no(x, `${x.text}: a field the struct's type doesn't list`);
|
|
247
|
+
cur = { e: 'fld', ...this.at(x), x: cur, f: f.name };
|
|
248
|
+
t = this.T(f.t);
|
|
249
|
+
if (t.k === 'ptr' && i < path.length - 1) {
|
|
250
|
+
t = this.T(t.elem);
|
|
251
|
+
cur = { e: 'deref', ...this.at(x), x: { e: 'at', ...this.at(x), pl: cur, raw: true } };
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return cur;
|
|
255
|
+
}
|
|
256
|
+
return this.no(x, `${x.text}: an assignment to other than a variable, a field or *p`);
|
|
257
|
+
}
|
|
258
|
+
composite(x) {
|
|
259
|
+
const tt = this.T(x.t), at = this.at(x);
|
|
260
|
+
if (tt.k === 'struct') {
|
|
261
|
+
const fields = this.zero(x.t, x).fields;
|
|
262
|
+
(x.elts ?? []).forEach((el, i) => {
|
|
263
|
+
const name = el.field ?? tt.fields?.[i]?.name;
|
|
264
|
+
fields.push(name === undefined ? ['', this.no(x, 'a struct literal with more values than fields')] : [name, this.as(this.x(el.v), tt.fields.find(g => g.name === name).t)]);
|
|
265
|
+
});
|
|
266
|
+
return { e: 'struct', ...at, ty: String(x.t), fields };
|
|
267
|
+
}
|
|
268
|
+
if ((tt.k === 'map' || tt.k === 'slice') && !(x.elts ?? []).length)
|
|
269
|
+
return { e: tt.k === 'map' ? 'newmap' : 'newlist', ...at };
|
|
270
|
+
return this.no(x, `${x.text}: a literal of a ${this.tname(x.t)} (the subset makes structs, and maps and slices empty)`);
|
|
271
|
+
}
|
|
272
|
+
call(x) {
|
|
273
|
+
const f = x.f, at = this.at(x), a = x.a ?? [];
|
|
274
|
+
if (x.conv)
|
|
275
|
+
return { e: 'conv', ...at, x: this.x(a[0]), ity: this.intTy(x.t), why: `${x.text}: a conversion to ${this.tname(x.t)} (the subset converts between integer types)` };
|
|
276
|
+
if (x.builtin)
|
|
277
|
+
return this.builtin(x);
|
|
278
|
+
if (f.e === 'sel' && f.k === 'qual')
|
|
279
|
+
return this.std(x);
|
|
280
|
+
if (f.e === 'sel' && f.k === 'method') {
|
|
281
|
+
// A method promoted from an embedded field: its receiver is that field (through the embedded fields on the way).
|
|
282
|
+
let rt = this.T(f.x.t), base = rt.k === 'ptr' ? rt.elem : f.x.t, emb;
|
|
283
|
+
if ((f.path ?? []).length > 1) {
|
|
284
|
+
let cur = rt.k === 'ptr' ? { e: 'deref', ...at, x: this.x(f.x) } : this.place(f.x), t = this.T(base);
|
|
285
|
+
if (cur.e === 'blank')
|
|
286
|
+
return this.no(x, '_');
|
|
287
|
+
for (const i of f.path.slice(0, -1)) {
|
|
288
|
+
const fd = t.fields?.[i];
|
|
289
|
+
if (!fd)
|
|
290
|
+
return this.no(x, `${x.text}: an embedded field the type doesn't list`, { prepl: cur });
|
|
291
|
+
cur = { e: 'fld', ...at, x: cur, f: fd.name };
|
|
292
|
+
base = fd.t;
|
|
293
|
+
t = this.T(fd.t);
|
|
294
|
+
if (t.k === 'ptr') {
|
|
295
|
+
cur = { e: 'deref', ...at, x: { e: 'at', ...at, pl: cur, raw: true } };
|
|
296
|
+
base = t.elem;
|
|
297
|
+
t = this.T(t.elem);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
emb = cur;
|
|
301
|
+
rt = this.T(base);
|
|
302
|
+
}
|
|
303
|
+
const after = emb ? { prepl: emb } : {};
|
|
304
|
+
if (this.isBig(base))
|
|
305
|
+
return emb ? this.no(x, 'a big.Int method promoted from an embedded field', after) : this.big(x);
|
|
306
|
+
if (this.isMutex(base))
|
|
307
|
+
return emb ? this.no(x, `${x.text}: a mutex's method promoted from an embedded field (lock it by its field's name)`, after) : { e: 'mutex', ...at, op: f.n, pl: this.place(f.x) };
|
|
308
|
+
if (f.mpkg && f.mpkg !== this.pkg.package)
|
|
309
|
+
return emb ? this.no(x, `${x.text}: a method of ${f.mpkg} (another package's code)`, after) : this.ext(x, `${x.text}: a method of ${f.mpkg} (another package's code)`, `${f.mpkg}.${f.n}`, f.x);
|
|
310
|
+
const decl = this.methodOf(f.mtype, f.n);
|
|
311
|
+
if (!decl)
|
|
312
|
+
return this.no(x, `${x.text}: no method ${f.mtype}.${f.n} declared with a body`, after);
|
|
313
|
+
// The receiver: a pointer to the value (its place's address) or a copy of it.
|
|
314
|
+
const recv = emb
|
|
315
|
+
? (f.mptr ? { e: 'addr', ...at, k: 'addr', pl: emb, why: `${x.text}: a pointer method of a local value's embedded field (a pointer to a local)` } : { e: 'recv', p: x.p, k: 'rd', pl: emb })
|
|
316
|
+
: f.mptr
|
|
317
|
+
? (rt.k === 'ptr' ? { e: 'recv', p: x.p, k: 'val0', x: this.x(f.x) } : { e: 'addr', ...at, k: 'addr', pl: this.place(f.x), why: `${f.x.text}.${f.n}(): a pointer method of a local value (its address is a pointer to a local)` })
|
|
318
|
+
: { e: 'recv', p: x.p, k: 'val', x: this.x(f.x) };
|
|
319
|
+
return { e: 'gcall', ...at, fn: `${decl.recv?.type ?? ''}.${decl.name}`, recv, args: this.args(a, decl) };
|
|
320
|
+
}
|
|
321
|
+
if (f.e === 'id' && f.o === 'func') {
|
|
322
|
+
const decl = this.funcOf(f.n);
|
|
323
|
+
if (!decl)
|
|
324
|
+
return this.no(x, `${f.n}: a function with no body here`);
|
|
325
|
+
return { e: 'gcall', ...at, fn: `.${decl.name}`, args: this.args(a, decl) };
|
|
326
|
+
}
|
|
327
|
+
return this.ext(x, `${x.text}: a call of a function value`, x.text, f);
|
|
328
|
+
}
|
|
329
|
+
args(a, decl) { return a.map((y, i) => (decl.params[i] ? this.as(this.x(y), decl.params[i].t) : this.x(y))); }
|
|
330
|
+
builtin(x) {
|
|
331
|
+
const b = x.builtin, a = x.a ?? [], at = this.at(x);
|
|
332
|
+
switch (b) {
|
|
333
|
+
case 'len': {
|
|
334
|
+
const k = this.T(a[0].t).k;
|
|
335
|
+
if (k === 'string' || k === 'slice')
|
|
336
|
+
return { e: 'len', ...at, k: k === 'string' ? 'str' : 'list', x: this.x(a[0]), ity: this.intTy(x.t) };
|
|
337
|
+
return this.no(x, k === 'map' ? 'len of a map (the subset keeps no count of a map\'s keys)' : `len of a ${this.tname(a[0].t)}`);
|
|
338
|
+
}
|
|
339
|
+
case 'append': return a.length !== 2 || x.ell ? this.no(x, 'append of other than one item') : { e: 'append', ...at, s: this.x(a[0]), x: this.x(a[1]), at1: this.at(a[1]) };
|
|
340
|
+
case 'delete': return { e: 'delete', ...at, m: this.x(a[0]), k: this.x(a[1]) };
|
|
341
|
+
case 'make': {
|
|
342
|
+
const k = this.T(x.t).k;
|
|
343
|
+
if (k === 'map' && a.length <= 2)
|
|
344
|
+
return { e: 'newmap', ...at };
|
|
345
|
+
return this.no(x, k === 'slice' ? 'make of a slice (a list starts empty: nil, and grows by append)' : `make of a ${this.tname(x.t)}`);
|
|
346
|
+
}
|
|
347
|
+
case 'new': {
|
|
348
|
+
const et = this.T(x.t).elem;
|
|
349
|
+
return this.isBig(et) ? { e: 'bignew', ...at } : { e: 'alloc', ...at, x: this.zero(et, x) };
|
|
350
|
+
}
|
|
351
|
+
case 'min':
|
|
352
|
+
case 'max': return { e: 'minmax', ...at, op: b, xs: a.map(y => this.x(y)), ity: this.intTy(x.t), why: `${b} of other than integers` };
|
|
353
|
+
case 'panic': return { e: 'panic', ...at, args: a.map(y => this.x(y)), ...(x.what ? { what: x.what } : {}) };
|
|
354
|
+
case 'recover': return this.no(x, 'recover (a panic is a refusal in the subset)');
|
|
355
|
+
case 'cap': return this.no(x, 'cap (a slice\'s capacity decides whether append shares its backing array)');
|
|
356
|
+
case 'copy': return this.no(x, 'copy (between two slices)');
|
|
357
|
+
case 'clear': return this.no(x, 'clear (a map or a slice emptied whole)');
|
|
358
|
+
}
|
|
359
|
+
return this.no(x, `${b}: a builtin the subset doesn't read`);
|
|
360
|
+
}
|
|
361
|
+
std(x) {
|
|
362
|
+
const f = x.f, path = f.pkg ?? '', n = f.n, at = this.at(x);
|
|
363
|
+
if (f.why)
|
|
364
|
+
return this.ext(x, f.why, n);
|
|
365
|
+
if ((path === 'errors' && n === 'New') || (path === 'fmt' && n === 'Errorf')) {
|
|
366
|
+
// An error: not nil. Its arguments are evaluated (they may panic), its text is not compared.
|
|
367
|
+
const pre = (x.a ?? []).flatMap(a => (a.e === 'call' && a.f?.e === 'sel' && a.f.n === 'String' && a.f.k === 'method' && (this.isBigPtr(a.f.x.t) || this.isBig(a.f.x.t)) ? [this.x(a.f.x)] : a.c ? [] : [this.x(a)]));
|
|
368
|
+
return { e: 'errv', ...at, is: true, pre };
|
|
369
|
+
}
|
|
370
|
+
if (path === 'math/big' && n === 'NewInt')
|
|
371
|
+
return { e: 'bignew', ...at, x: this.x(x.a[0]) };
|
|
372
|
+
if (path === 'time' && n === 'Now')
|
|
373
|
+
return this.no(x, 'time.Now(): the clock (the check can\'t set it for the code, and time.Time is outside the subset)');
|
|
374
|
+
if (!this.stdlib(path))
|
|
375
|
+
return this.ext(x, `${x.text}: a function of ${path} (another module's code)`, `${path}.${n}`);
|
|
376
|
+
if (!path)
|
|
377
|
+
return this.no(x, `${x.text}: a call on a value whose type isn't read here (another module's, beyond the packages the code imports)`);
|
|
378
|
+
return this.ext(x, `${x.text}: a function of the standard library the subset doesn't read`, `${path}.${n}`);
|
|
379
|
+
}
|
|
380
|
+
big(x) {
|
|
381
|
+
const f = x.f, n = f.n;
|
|
382
|
+
return { e: 'big', ...this.at(x), op: n, z: this.x(f.x), args: (x.a ?? []).map(y => this.x(y)), ty: { bits: 64, signed: n !== 'Uint64', t: x.t, name: this.tname(x.t) } };
|
|
383
|
+
}
|
|
384
|
+
// --- statements -----------------------------------------------------------------------------------------------------
|
|
385
|
+
body(ss, fn) { return ss.flatMap(s => this.s(s, fn)); }
|
|
386
|
+
s(s, fn) {
|
|
387
|
+
const no = (why) => [{ s: 'no', p: s.p, why }];
|
|
388
|
+
switch (s.s) {
|
|
389
|
+
case 'block': return this.body(s.b, fn);
|
|
390
|
+
case 'empty': return [];
|
|
391
|
+
case 'no': return no(s.why);
|
|
392
|
+
case 'expr': {
|
|
393
|
+
const x = s.x;
|
|
394
|
+
if (x.e === 'call' && x.builtin === 'panic')
|
|
395
|
+
return [{ s: 'panic', p: s.p, args: (x.a ?? []).map(y => this.x(y)), ...(x.what ? { what: x.what } : {}) }];
|
|
396
|
+
return [{ s: 'expr', p: s.p, x: this.x(x) }];
|
|
397
|
+
}
|
|
398
|
+
case 'incdec': return [{ s: 'incdec', p: s.p, op: s.op, to: this.place(s.x) }];
|
|
399
|
+
case 'assign': return [this.assign(s)];
|
|
400
|
+
case 'decl': {
|
|
401
|
+
const out = [];
|
|
402
|
+
for (const sp of s.specs ?? []) {
|
|
403
|
+
if (sp.type)
|
|
404
|
+
return [...out, ...no('a type declared in a function')];
|
|
405
|
+
if (sp.const)
|
|
406
|
+
continue;
|
|
407
|
+
const to = sp.names.map(n => ({ e: 'var', p: s.p, n: n.id, bind: 'always' }));
|
|
408
|
+
if (sp.v.length && sp.v.length !== sp.names.length) {
|
|
409
|
+
out.push({ s: 'assign', p: s.p, to, one: this.x(sp.v[0]), decl: true, why: 'a declaration of several from one value' });
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
sp.names.forEach((n, i) => { const e = sp.v[i]; out.push({ s: 'assign', p: s.p, to: [to[i]], xs: [e ? this.as(this.x(e), n.t) : this.zero(n.t, s)] }); });
|
|
413
|
+
}
|
|
414
|
+
return out;
|
|
415
|
+
}
|
|
416
|
+
case 'if': return [...(s.init ? this.s(s.init, fn) : []), { s: 'if', p: s.p, c: this.x(s.c), then: this.body(s.then, fn), else: s.else ? this.s(s.else, fn) : [], strict: `${s.c.text}: a condition that isn't a boolean`, cp: s.c.p }];
|
|
417
|
+
case 'switch': return [...(s.init ? this.s(s.init, fn) : []), { s: 'switch', p: s.p, ...(s.tag ? { tag: this.x(s.tag) } : {}), cases: s.cases.map(c => ({ p: c.p, ...(c.default ? { default: true } : { list: c.list.map(e => this.x(e)) }), b: this.body(c.b, fn) })) }];
|
|
418
|
+
case 'return': {
|
|
419
|
+
const r = s.r;
|
|
420
|
+
if (r.length === 1 && fn.results.length > 1)
|
|
421
|
+
return [{ s: 'ret', p: s.p, one: this.x(r[0]), why: 'a return of one value from a function of several' }];
|
|
422
|
+
if (!r.length && fn.results.length)
|
|
423
|
+
return [{ s: 'ret', p: s.p, bare: fn.results.map(x => x.id ?? null) }];
|
|
424
|
+
return [{ s: 'ret', p: s.p, xs: r.map((e, i) => this.as(this.x(e), fn.results[i].t)) }];
|
|
425
|
+
}
|
|
426
|
+
case 'branch':
|
|
427
|
+
if (s.tok === 'break' && !s.label)
|
|
428
|
+
return [{ s: 'break', p: s.p }];
|
|
429
|
+
if (s.tok === 'fallthrough')
|
|
430
|
+
return [{ s: 'fallthrough', p: s.p }];
|
|
431
|
+
return no(`${s.tok}${s.label ? ` ${s.label}` : ''} (the subset reads break in a switch; loops and goto are outside it)`);
|
|
432
|
+
case 'defer': {
|
|
433
|
+
// A mutex's Unlock deferred after its Lock: the step is atomic in the rule.
|
|
434
|
+
const x = s.x;
|
|
435
|
+
if (x.e === 'call' && x.f?.e === 'sel' && x.f.k === 'method' && /^(R?Unlock)$/.test(x.f.n) && this.isMutex(this.T(x.f.x.t).k === 'ptr' ? this.T(x.f.x.t).elem : x.f.x.t))
|
|
436
|
+
return [{ s: 'defer', p: s.p, pl: this.place(x.f.x), text: x.text }];
|
|
437
|
+
return no('defer (other than a mutex\'s Unlock after its Lock): it runs at the return, after the results are set');
|
|
438
|
+
}
|
|
439
|
+
case 'for': return no('a loop (for)');
|
|
440
|
+
case 'range': return no(s.x && this.T(s.x.t).k === 'map' ? 'a range over a map (Go\'s iteration order is random, and loops are outside the subset)' : 'a loop (range)');
|
|
441
|
+
case 'go': return no('a goroutine (its steps interleave with others)');
|
|
442
|
+
case 'select':
|
|
443
|
+
case 'send': return no('a channel');
|
|
444
|
+
case 'typeswitch': return no('a type switch (interfaces are outside the subset)');
|
|
445
|
+
case 'labeled': return no('a label');
|
|
446
|
+
}
|
|
447
|
+
return no(`a statement the subset doesn't read (${s.s})`);
|
|
448
|
+
}
|
|
449
|
+
// The targets of an assignment: a local bound (:= of a new name), a map's item, a slice's, or a place.
|
|
450
|
+
target(x, op) {
|
|
451
|
+
if (op === ':=' && x.e === 'id' && x.n !== '_')
|
|
452
|
+
return { e: 'var', ...this.at(x), n: x.id, bind: 'new' };
|
|
453
|
+
if (x.e === 'index') {
|
|
454
|
+
const k = this.T(x.x.t).k;
|
|
455
|
+
if (k === 'map')
|
|
456
|
+
return this.midx(x);
|
|
457
|
+
if (k === 'slice' || this.T(x.x.t).fixed)
|
|
458
|
+
return { e: 'lidx', ...this.at(x), s: this.x(x.x), i: this.x(x.i) };
|
|
459
|
+
return this.no(x, 'an index into other than a map or a slice');
|
|
460
|
+
}
|
|
461
|
+
return this.place(x);
|
|
462
|
+
}
|
|
463
|
+
assign(s) {
|
|
464
|
+
const l = s.l, r = s.r, op = s.op;
|
|
465
|
+
if (op === '=' || op === ':=') {
|
|
466
|
+
const to = l.map(x => this.target(x, op));
|
|
467
|
+
// v, ok := m[k]: the value and whether the map holds the key.
|
|
468
|
+
if (l.length === 2 && r.length === 1 && r[0].e === 'index' && this.T(r[0].x.t).k === 'map')
|
|
469
|
+
return { s: 'assign', p: s.p, to, mapok: this.midx(r[0]) };
|
|
470
|
+
// (Go evaluates the left side's indices and indirections, then the right side, then assigns: the subset reads
|
|
471
|
+
// left sides without effects, so the right side first is the same.)
|
|
472
|
+
if (r.length === 1 && l.length > 1)
|
|
473
|
+
return { s: 'assign', p: s.p, to, one: this.x(r[0]), why: 'an assignment of several from one value' };
|
|
474
|
+
return { s: 'assign', p: s.p, to, xs: r.map((e, i) => this.as(this.x(e), l[i].t)) };
|
|
475
|
+
}
|
|
476
|
+
// x op= y
|
|
477
|
+
const bop = op.slice(0, -1);
|
|
478
|
+
if (l[0].e === 'index' && this.T(l[0].x.t).k === 'map')
|
|
479
|
+
return { s: 'mopset', p: s.p, at: this.midx(l[0]), op: bop, y: this.x(r[0]) };
|
|
480
|
+
if (l[0].e === 'index')
|
|
481
|
+
return { s: 'no', p: s.p, why: `${op} on ${this.T(l[0].x.t).fixed ? 'an array\'s' : 'a slice\'s'} item (the subset sets an item: s[i] = x)` };
|
|
482
|
+
return { s: 'opset', p: s.p, to: this.place(l[0]), op: bop, y: this.x(r[0]) };
|
|
483
|
+
}
|
|
484
|
+
fn(f) {
|
|
485
|
+
// The named results start at their zero values.
|
|
486
|
+
const zeros = f.results.filter(r => r.id).map(r => ({ s: 'assign', p: f.p, to: [{ e: 'var', p: f.p, n: r.id, bind: 'always' }], xs: [this.zero(r.t, f)] }));
|
|
487
|
+
let body;
|
|
488
|
+
const lower = () => this.body(f.body ?? [], f);
|
|
489
|
+
return {
|
|
490
|
+
id: `${f.recv?.type ?? ''}.${f.name}`, name: f.name, p: f.p, span: [f.p.split(':')[0], f.span[0], f.span[1]], params: f.params.map(pa => ({ name: pa.id ?? '', t: { k: 'any' } })), ret: { k: 'any' },
|
|
491
|
+
get body() { return (body ??= [...zeros, ...lower()]); }, decorators: [], ...(f.recv?.id ? { recv: f.recv.id } : {}), results: f.results.length,
|
|
492
|
+
...(f.generic ? { why: `${f.name}: a generic function` } : !f.body ? { late: `${f.name} has no body` } : f.params.some(x => x.variadic) ? { late: `${f.name}: a variadic function` } : {}),
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
// --- the state: the struct's fields as variables, leaf by leaf ------------------------------------------------------
|
|
496
|
+
// Each field of a subset type is a leaf (a variable, or a map or a list); one of another type is left out (the check
|
|
497
|
+
// asks the code not to change it), and reading or writing it is refused where it is.
|
|
498
|
+
buildStruct(t, path, heap) {
|
|
499
|
+
const g = this.g, x = this.T(t), out = new Map();
|
|
500
|
+
for (const f of x.fields ?? []) {
|
|
501
|
+
const fp = [...path, f.name], name = fp.join('_'), ft = this.T(f.t), id = `state:${fp.join('.')}`;
|
|
502
|
+
const leaf = (kind, v, ty) => { this.leaves.push({ name: v.name, path: fp, kind, t: ty, go: this.tname(ty) }); return v; };
|
|
503
|
+
if (ft.k === 'int') {
|
|
504
|
+
const ty = this.intTy(f.t), v = leaf('int', g.newVar(name, { k: 'num' }, 'state'), f.t);
|
|
505
|
+
g.ints.set(v.name, ty);
|
|
506
|
+
out.set(f.name, { t: 'num', e: I.nvar(v.name), ty });
|
|
507
|
+
}
|
|
508
|
+
else if (ft.k === 'bool')
|
|
509
|
+
out.set(f.name, { t: 'bool', e: I.bvar(leaf('bool', g.newVar(name, { k: 'bool' }, 'state'), f.t).name) });
|
|
510
|
+
else if (ft.k === 'string')
|
|
511
|
+
out.set(f.name, { t: 'str', e: { op: 'svar', name: leaf('str', g.newVar(name, { k: 'str' }, 'state'), f.t).name } });
|
|
512
|
+
else if (this.isBigPtr(f.t)) {
|
|
513
|
+
// A *big.Int: its value, and whether it is nil (Go's zero value).
|
|
514
|
+
const v = leaf('big', g.newVar(name, { k: 'num' }, 'state', 'a *big.Int (its value; 0 where it is nil)'), f.t);
|
|
515
|
+
const nil = leaf('bignil', g.newVar(`${name}_nil`, { k: 'bool' }, 'state', `whether ${fp.join('.')} is nil`), f.t);
|
|
516
|
+
heap.set(id, { k: 'big', v: I.nvar(v.name), origin: 'state' });
|
|
517
|
+
g.stateOrigin.set(id, fp.join('.'));
|
|
518
|
+
out.set(f.name, { t: 'ptr', to: phiP(I.bvar(nil.name), { k: 'nil' }, { k: 'obj', id, path: [] }) });
|
|
519
|
+
}
|
|
520
|
+
else if (ft.k === 'struct' && (ft.own || !ft.name))
|
|
521
|
+
out.set(f.name, { t: 'struct', ty: String(f.t), f: this.buildStruct(f.t, fp, heap) });
|
|
522
|
+
else if (ft.k === 'map' && this.mapOK(f.t)) {
|
|
523
|
+
const decl = this.mapDecl(f.t, name);
|
|
524
|
+
const nil = leaf('mapnil', g.newVar(`${decl.name}_nil`, { k: 'bool' }, 'state', `whether ${fp.join('.')} is nil (a nil map holds no key, and a write to it panics)`), f.t);
|
|
525
|
+
this.leaves.push({ name: decl.name, path: fp, kind: 'map', t: f.t, go: this.tname(f.t) });
|
|
526
|
+
heap.set(id, { k: 'map', decl, nil: I.bvar(nil.name), origin: 'state' });
|
|
527
|
+
out.set(f.name, { t: 'map', id });
|
|
528
|
+
}
|
|
529
|
+
else if ((ft.k === 'slice' || ft.fixed) && ['int', 'bool'].includes(this.T(ft.elem).k)) {
|
|
530
|
+
// (a fixed array, C's: a list of its length, never pushed or popped)
|
|
531
|
+
const decl = { name: g.newVar(name, { k: 'num' }, 'state').name, key: 'num', fields: [{ name: '$item', sort: this.T(ft.elem).k === 'int' ? { k: 'num' } : { k: 'bool' }, role: 'state' }], scalar: true, js: 'Map', ...(ft.fixed ? { len: ft.len } : {}) };
|
|
532
|
+
g.lists.push(decl);
|
|
533
|
+
const it = this.intTy(ft.elem);
|
|
534
|
+
if (it)
|
|
535
|
+
g.ints.set(`${decl.name}.$item`, it);
|
|
536
|
+
this.leaves.push({ name: decl.name, path: fp, kind: 'list', t: f.t, go: this.tname(f.t) });
|
|
537
|
+
heap.set(id, { k: 'list', decl, ops: [], origin: 'state' });
|
|
538
|
+
out.set(f.name, { t: 'list', id });
|
|
539
|
+
}
|
|
540
|
+
else {
|
|
541
|
+
out.set(f.name, { t: 'opaque', why: `${fp.join('.')} is a ${this.tname(f.t)}, a field outside the subset (left out of the rule)`, firm: true });
|
|
542
|
+
this.leaves.push({ name: '', path: fp, kind: 'frame', t: f.t, go: this.tname(f.t) });
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
return out;
|
|
546
|
+
}
|
|
547
|
+
mapOK(t) {
|
|
548
|
+
const x = this.T(t), kk = this.T(x.key).k, v = this.T(x.elem);
|
|
549
|
+
if (kk !== 'int' && kk !== 'string')
|
|
550
|
+
return false;
|
|
551
|
+
if (v.k === 'int' || v.k === 'bool')
|
|
552
|
+
return true;
|
|
553
|
+
return v.k === 'struct' && (v.fields ?? []).every(f => ['int', 'bool'].includes(this.T(f.t).k));
|
|
554
|
+
}
|
|
555
|
+
mapDecl(t, name) {
|
|
556
|
+
const x = this.T(t), v = this.T(x.elem), key = this.T(x.key).k === 'int' ? 'num' : 'str';
|
|
557
|
+
const n = this.g.newVar(name, { k: 'num' }, 'state').name;
|
|
558
|
+
const fs = v.k === 'struct' ? v.fields : [{ name: 'value', t: x.elem }];
|
|
559
|
+
const fields = fs.map(f => ({ name: f.name, sort: this.T(f.t).k === 'int' ? { k: 'num' } : { k: 'bool' }, role: 'state' }));
|
|
560
|
+
const decl = { name: n, key, fields, scalar: v.k !== 'struct', js: 'Map' };
|
|
561
|
+
for (const f of fs) {
|
|
562
|
+
const it = this.intTy(f.t);
|
|
563
|
+
if (it)
|
|
564
|
+
this.g.ints.set(`${n}.${f.name}`, it);
|
|
565
|
+
}
|
|
566
|
+
this.g.maps.push(decl);
|
|
567
|
+
return decl;
|
|
568
|
+
}
|
|
569
|
+
// An input of an integer type: a request the code can't be given (past its type's range) is refused where `sel` (the
|
|
570
|
+
// method called) holds, the claim being for the type's values.
|
|
571
|
+
input(x, t, sel) { return this.g.valueOfIn(x, this.intTy(t), sel); }
|
|
572
|
+
// The arguments of a method or a function: each an input (a pointer to a struct of the package a fresh object whose
|
|
573
|
+
// fields read are inputs, a *big.Int one whose value is).
|
|
574
|
+
bindParams(fn, sel, p0) {
|
|
575
|
+
const g = this.g, args = [], params = [];
|
|
576
|
+
let p = p0;
|
|
577
|
+
if (fn.params.some(x => x.variadic))
|
|
578
|
+
refuse(fn, `${fn.name}: a variadic method`);
|
|
579
|
+
for (const pa of fn.params) {
|
|
580
|
+
const name = `${fn.name}_${pa.name ?? 'arg'}`, tt = this.T(pa.t), s = this.scalar(pa.t);
|
|
581
|
+
let v, arg;
|
|
582
|
+
if (typeof s !== 'string') {
|
|
583
|
+
const x = g.newVar(name, s, 'input');
|
|
584
|
+
v = this.input(x, pa.t, sel);
|
|
585
|
+
arg = { k: 'input', name: x.name };
|
|
586
|
+
}
|
|
587
|
+
else if (this.isBigPtr(pa.t)) {
|
|
588
|
+
const x = g.newVar(name, { k: 'num' }, 'input', 'a *big.Int argument (not nil: the claim is for calls that give one)');
|
|
589
|
+
p.heap.set(`in:${x.name}`, { k: 'big', v: I.nvar(x.name), origin: 'input' });
|
|
590
|
+
v = { t: 'ptr', to: { k: 'obj', id: `in:${x.name}`, path: [] } };
|
|
591
|
+
arg = { k: 'input', name: x.name };
|
|
592
|
+
g.notes.add(`${name}: a *big.Int argument, never nil here (the claim is for calls that give one)`);
|
|
593
|
+
}
|
|
594
|
+
else if (tt.k === 'ptr' && ((this.T(tt.elem).k === 'struct' && this.T(tt.elem).own) || this.T(tt.elem).xfields)) {
|
|
595
|
+
// (Another package's struct is read as data the same way: its exported fields, the only ones the package's code
|
|
596
|
+
// can read; its methods stay that package's code, refused where they are called.)
|
|
597
|
+
// A pointer to a struct the caller gives: its fields read are inputs (each made where it is first read).
|
|
598
|
+
const id = `in:${name}`, et = this.T(tt.elem);
|
|
599
|
+
p.heap.set(id, { k: 'rec', ty: String(tt.elem), f: new Map(), origin: 'input', lazy: name });
|
|
600
|
+
const recipes = {};
|
|
601
|
+
for (const fd of et.fields ?? et.xfields ?? []) {
|
|
602
|
+
const fs = this.scalar(fd.t);
|
|
603
|
+
recipes[fd.name] = typeof fs !== 'string' ? { k: fs.k, ty: this.intTy(fd.t) } : this.isBigPtr(fd.t) ? { k: 'big' } : { k: 'no', why: `${fd.name} of the argument: ${fs}` };
|
|
604
|
+
}
|
|
605
|
+
g.lazyIn.set(id, { id: name, fields: [], sel, recipes });
|
|
606
|
+
v = { t: 'ptr', to: { k: 'obj', id, path: [] } };
|
|
607
|
+
arg = { k: 'lazy', prefix: name };
|
|
608
|
+
g.notes.add(`${name}: a *${this.tname(tt.elem)} the caller gives, a fresh one for each call (its fields read are inputs; the claim is for calls that don't pass the object itself)`);
|
|
609
|
+
}
|
|
610
|
+
else if ((tt.k === 'struct' && tt.own) || tt.xfields) {
|
|
611
|
+
// A struct the caller gives by value: the call's own copy, so a value here as a local struct is (no other name
|
|
612
|
+
// reaches it, and writing it changes nothing the caller sees). Each field of a subset type an input (another
|
|
613
|
+
// package's, its exported fields: all its code can set), the others left out, refused where they are read.
|
|
614
|
+
const fields = [], f = new Map();
|
|
615
|
+
for (const fd of tt.fields ?? tt.xfields.filter(x => x.exported)) {
|
|
616
|
+
const fs = this.scalar(fd.t);
|
|
617
|
+
if (typeof fs === 'string') {
|
|
618
|
+
f.set(fd.name, { t: 'opaque', why: `${pa.name}.${fd.name} of the argument: ${fs}`, firm: true });
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
const x = g.newVar(`${name}_${fd.name}`, fs, 'input');
|
|
622
|
+
f.set(fd.name, this.input(x, fd.t, sel));
|
|
623
|
+
fields.push([fd.name, { k: 'input', name: x.name }]);
|
|
624
|
+
}
|
|
625
|
+
v = { t: 'struct', ty: String(pa.t), f };
|
|
626
|
+
arg = { k: 'rec', fields };
|
|
627
|
+
g.notes.add(`${fn.name}(${pa.name ?? '_'}): a ${this.tname(pa.t)} given by value, its fields inputs`);
|
|
628
|
+
}
|
|
629
|
+
else if (this.isContext(pa.t)) {
|
|
630
|
+
// A context.Context: the check gives context.Background(). Exact while the step never reads it: passed on to the
|
|
631
|
+
// package's own functions only (its methods, Done, Err, Value, are another package's code; given to another
|
|
632
|
+
// package's function, it is that function's: both refused where they are).
|
|
633
|
+
v = { t: 'opaque', why: `${pa.name ?? 'the context'}, a context.Context read (the subset only passes one on to the package's own functions)`, firm: true };
|
|
634
|
+
arg = { k: 'lit', value: 'context' };
|
|
635
|
+
g.notes.add(`${fn.name}(${pa.name ?? '_'}): a context.Context, passed on to the package's own functions only (the claim is for any context, the step never reading it)`);
|
|
636
|
+
}
|
|
637
|
+
else
|
|
638
|
+
return refuse(fn, `${fn.name}(${pa.name}): an argument of type ${pa.ts ?? this.tname(pa.t)} (${this.whyType(pa.t)})`);
|
|
639
|
+
if (pa.id)
|
|
640
|
+
p = g.bindLocal(pa.id, v, fn, p);
|
|
641
|
+
args.push(arg);
|
|
642
|
+
params.push({ name: pa.name ?? '', t: pa.t, arg });
|
|
643
|
+
}
|
|
644
|
+
return { p, args, params };
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
// Read with the boundary inferred unless strict (core/extract-step.ts's readStep: each refused run adds what the next
|
|
648
|
+
// infers): Go's check can't stub a call, so a call of another package is left out where nothing reads its value.
|
|
649
|
+
export function readGo(pkg, opts) {
|
|
650
|
+
if (!opts.entry && !opts.strict) {
|
|
651
|
+
// No entry: the package's one struct whose exported methods write it (core/extract-step.ts's writesState).
|
|
652
|
+
const g = new Go(pkg, opts).g, writing = (t) => pkg.funcs.filter(f => f.recv?.type === t && f.body && (pkg.lang === 'c' || pkg.lang === 'cpp' || /^[A-Z]/.test(f.name)) && g.writesState(`${t}.${f.name}`, new Set([g.mod.funcs[`${t}.${f.name}`]?.recv ?? ''])));
|
|
653
|
+
const cands = pkg.types.filter(t => writing(t.name).length);
|
|
654
|
+
if (cands.length !== 1)
|
|
655
|
+
refuse(pkg.files[0]?.name ?? '?', cands.length ? `several structs write their state (${cands.map(t => t.name).join(', ')}): name one (entry)` : 'no struct whose exported methods write it: name the entry');
|
|
656
|
+
const r = readGo(pkg, { ...opts, entry: cands[0].name });
|
|
657
|
+
r.model.notes.unshift(`the entry inferred: ${cands[0].name}, the struct whose exported methods write it`);
|
|
658
|
+
return r;
|
|
659
|
+
}
|
|
660
|
+
if (opts.strict)
|
|
661
|
+
return readGo1(pkg, opts, new Go(pkg, opts));
|
|
662
|
+
const inf = { answers: new Map(), cut: new Map() };
|
|
663
|
+
for (let n = 0;; n++) {
|
|
664
|
+
const go = new Go(pkg, opts, inf);
|
|
665
|
+
try {
|
|
666
|
+
return readGo1(pkg, opts, go);
|
|
667
|
+
}
|
|
668
|
+
catch (e) {
|
|
669
|
+
if (!(e instanceof Refusal))
|
|
670
|
+
throw e;
|
|
671
|
+
const r = n < 256 ? go.g.promote(e) : e;
|
|
672
|
+
if (r)
|
|
673
|
+
throw r;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
function readGo1(pkg, o, go) {
|
|
678
|
+
const g = go.g, opts = { ...o, entry: o.entry ?? refuse(pkg.files[0]?.name ?? '?', 'no entry (strict: name the struct)') };
|
|
679
|
+
const td = pkg.types.find(t => t.name === opts.entry) ?? refuse(pkg.files[0]?.name ?? '?', `no type ${opts.entry} in package ${pkg.package}`);
|
|
680
|
+
const st = go.T(td.t);
|
|
681
|
+
if (st.k !== 'struct')
|
|
682
|
+
refuse(td, `${opts.entry} is a ${st.k === 'float' ? 'float' : st.k} type, not a struct (the subset reads a struct and its methods)`);
|
|
683
|
+
if (st.args?.length || st.generic)
|
|
684
|
+
refuse(td, `${opts.entry} is a generic type (its methods read a type parameter)`);
|
|
685
|
+
if (pkg.funcs.some(f => f.recv?.type === opts.entry && f.generic))
|
|
686
|
+
refuse(td, `${opts.entry} is a generic type (its methods read a type parameter)`);
|
|
687
|
+
// The state: the object, every field of a subset type a leaf.
|
|
688
|
+
const heap = new Map();
|
|
689
|
+
const fields = go.buildStruct(td.t, [], heap);
|
|
690
|
+
heap.set('this', { k: 'rec', ty: String(td.t), f: fields, origin: 'state' });
|
|
691
|
+
for (const [id, o] of heap)
|
|
692
|
+
g.initHeap.set(id, o);
|
|
693
|
+
const stateVars = [...g.vars.values()].filter(v => v.role === 'state');
|
|
694
|
+
// C++'s constructor, run once from the zeroed object: where it leaves each leaf is the rule's start, its parameters
|
|
695
|
+
// the rule's (within their types: the precondition).
|
|
696
|
+
const cparams = [], ctorArgs = [];
|
|
697
|
+
let ctorInit, pre = I.T;
|
|
698
|
+
if (pkg.ctor) {
|
|
699
|
+
const fn = pkg.ctor, n0 = g.refusals.length;
|
|
700
|
+
g.method = fn.name;
|
|
701
|
+
let p = { pc: [], locals: new Map(), heap: new Map(heap), called: [], locks: [], defers: [] };
|
|
702
|
+
for (const pa of fn.params) {
|
|
703
|
+
const s = go.scalar(pa.t), it = go.intTy(pa.t);
|
|
704
|
+
if (typeof s === 'string' || s.k === 'str')
|
|
705
|
+
refuse(fn, `the constructor's ${pa.name ?? 'argument'}: ${typeof s === 'string' ? s : 'a string'}`);
|
|
706
|
+
const v = g.newVar(pa.name ?? 'arg', s, 'param');
|
|
707
|
+
cparams.push(v);
|
|
708
|
+
ctorArgs.push({ name: pa.name ?? '', t: pa.t, arg: { k: 'input', name: v.name } });
|
|
709
|
+
if (it) {
|
|
710
|
+
g.ints.set(v.name, it);
|
|
711
|
+
const [lo, hi] = rangeOf(it);
|
|
712
|
+
if (Number.isFinite(lo))
|
|
713
|
+
pre = I.and(pre, I.cmp('<=', I.num(lo), I.nvar(v.name)));
|
|
714
|
+
if (Number.isFinite(hi))
|
|
715
|
+
pre = I.and(pre, I.cmp('<=', I.nvar(v.name), I.num(hi)));
|
|
716
|
+
}
|
|
717
|
+
if (pa.id)
|
|
718
|
+
p = g.bindLocal(pa.id, it ? { t: 'num', e: I.nvar(v.name), ty: it } : { t: 'bool', e: I.bvar(v.name) }, fn, p);
|
|
719
|
+
}
|
|
720
|
+
p = g.bindLocal('this', { t: 'ptr', to: { k: 'obj', id: 'this', path: [] } }, fn, p);
|
|
721
|
+
const flow = g.block(go.fn(fn).body, p), ends = [...flow.rets.map(([q]) => q), ...(flow.live ? [flow.live] : [])];
|
|
722
|
+
if (g.refusals.length > n0 || !ends.length)
|
|
723
|
+
refuse(fn, 'a constructor that can fail (the rule\'s start is where it leaves the object)');
|
|
724
|
+
const m = materialize(go, g.join(ends, fn), fn);
|
|
725
|
+
if (m.lists.size || m.maps.size)
|
|
726
|
+
refuse(fn, 'a constructor that writes an array (a list starts as zeros)');
|
|
727
|
+
ctorInit = m.leaves;
|
|
728
|
+
}
|
|
729
|
+
// The methods: each an event.
|
|
730
|
+
const all = pkg.funcs.filter(f => f.recv?.type === opts.entry && f.body);
|
|
731
|
+
const chosen = opts.methods ? opts.methods.map(n => all.find(f => f.name === n) ?? refuse(td, `no method ${opts.entry}.${n} with a body`)) : all.filter(f => /^[A-Z]/.test(f.name));
|
|
732
|
+
if (!chosen.length)
|
|
733
|
+
refuse(td, `${opts.entry} has no methods to read`);
|
|
734
|
+
const names = chosen.map(f => f.name), ev = g.newVar('method', { k: 'choice', values: names }, 'input');
|
|
735
|
+
const evL = { op: 'var', name: ev.name, values: names };
|
|
736
|
+
const outputs = [], results = {};
|
|
737
|
+
const finals = [], events = [], methods = [];
|
|
738
|
+
for (const fn of chosen) {
|
|
739
|
+
g.method = fn.name;
|
|
740
|
+
const sel = I.is(evL, fn.name);
|
|
741
|
+
let p = { pc: [sel], locals: new Map(), heap: new Map(heap), called: [], locks: [], defers: [] };
|
|
742
|
+
const bound = go.bindParams(fn, sel, p), args = bound.args, params = bound.params;
|
|
743
|
+
p = bound.p;
|
|
744
|
+
// The receiver.
|
|
745
|
+
if (fn.recv?.id)
|
|
746
|
+
p = g.bindLocal(fn.recv.id, fn.recv.ptr ? { t: 'ptr', to: { k: 'obj', id: 'this', path: [] } } : { t: 'struct', ty: String(td.t), f: fields }, fn, p);
|
|
747
|
+
const errAt = fn.results.length && go.T(fn.results.at(-1).t).k === 'error' ? fn.results.length - 1 : -1;
|
|
748
|
+
const kept = fn.results.filter((_, i) => i !== errAt);
|
|
749
|
+
if (kept.length > 1)
|
|
750
|
+
refuse(fn, `${fn.name} returns ${kept.length} values (a result kept is one value)`);
|
|
751
|
+
const lowered = go.funcs[`${fn.recv?.type ?? ''}.${fn.name}`];
|
|
752
|
+
g.spans.set(`${opts.entry}.${fn.name}`, [fn.p.split(':')[0], fn.span[0], fn.span[1]]);
|
|
753
|
+
const flow = g.block(lowered.body, p);
|
|
754
|
+
if (flow.brk?.length)
|
|
755
|
+
refuse(fn, 'a break outside a switch');
|
|
756
|
+
const rets = [...flow.rets.map(([q, v]) => [q, v.xs]), ...(flow.live ? [[flow.live, []]] : [])];
|
|
757
|
+
// An error returned: a refusal (where it isn't nil), the state as it was there.
|
|
758
|
+
const ok = [];
|
|
759
|
+
for (const [q0, vs] of rets) {
|
|
760
|
+
const q = { ...q0, locks: q0.locks.filter(k => !q0.defers.includes(k)) };
|
|
761
|
+
if (q.locks.length)
|
|
762
|
+
refuse(fn, `${fn.name} returns with a mutex locked`);
|
|
763
|
+
const fails = opts.fails?.[fn.name];
|
|
764
|
+
if (fails !== undefined) {
|
|
765
|
+
// A result the caller states is the failure where it compares so: a refusal there, as an error is.
|
|
766
|
+
const m = /^\s*(==|!=|<=|>=|<|>)\s*(-?\d+|true|false)\s*$/.exec(fails) ?? refuse(fn, `fails: ${JSON.stringify(fails)} (a comparison with a constant: '< 0', '!= 0', '== false')`);
|
|
767
|
+
const r = vs[0] ?? refuse(fn, `${fn.name} returns nothing to compare (fails: ${fails})`);
|
|
768
|
+
const k = m[2] === 'true' || m[2] === 'false' ? { t: 'bool', e: m[2] === 'true' ? I.T : I.F } : { t: 'num', e: I.num(Number(m[2])) };
|
|
769
|
+
// (no failure where the result's bounds and the path's facts exclude it: an item of a uint8_t is never < 0)
|
|
770
|
+
const kv = Number(m[2]), e = r.t === 'num' ? r.e : undefined, op = m[1];
|
|
771
|
+
const [blo, bhi] = e ? g.bounds(e) : [-Infinity, Infinity], atLeast = (b) => blo >= b || g.within(e, b, 'lo', q), atMost = (b) => bhi <= b || g.within(e, b, 'hi', q);
|
|
772
|
+
const never = e !== undefined && Number.isFinite(kv) && (op === '<' ? atLeast(kv) : op === '<=' ? atLeast(kv + 1) : op === '>' ? atMost(kv) : op === '>=' ? atMost(kv - 1) : op === '==' ? atLeast(kv + 1) || atMost(kv - 1) : false);
|
|
773
|
+
const is = never ? I.F : g.binop(op, r, k, fn, q).e;
|
|
774
|
+
g.refuseWhere(q, is, fn, `${fn.name} returning ${fails.trim()} (its failure, as the caller states)`);
|
|
775
|
+
if (!(is.op === 'const' && is.v))
|
|
776
|
+
ok.push([g.assume(q, I.not(is)), vs]);
|
|
777
|
+
}
|
|
778
|
+
else if (errAt >= 0) {
|
|
779
|
+
const e = vs[errAt];
|
|
780
|
+
const is = !e ? I.F : e.t === 'err' ? e.is : e.t === 'nil' ? I.F : refuse(fn, `${fn.name} returns an error of another kind`);
|
|
781
|
+
g.refuseWhere(q, is, fn, 'an error returned');
|
|
782
|
+
if (!(is.op === 'const' && is.v))
|
|
783
|
+
ok.push([g.assume(q, I.not(is)), vs]);
|
|
784
|
+
}
|
|
785
|
+
else
|
|
786
|
+
ok.push([q, vs]);
|
|
787
|
+
}
|
|
788
|
+
if (!ok.length)
|
|
789
|
+
refuse(fn, `${fn.name} always fails`);
|
|
790
|
+
// The kept result: by the path that returned it (a local the join merges).
|
|
791
|
+
const ri = fn.results.findIndex((_, i) => i !== errAt);
|
|
792
|
+
const final = g.join(ok.map(([q, vs]) => (kept.length ? { ...q, locals: new Map(q.locals).set('$ret', vs[ri]) } : q)), fn), acc = final.locals.get('$ret');
|
|
793
|
+
let out;
|
|
794
|
+
if (kept.length) {
|
|
795
|
+
const s = go.scalar(fn.results[ri].t);
|
|
796
|
+
if (typeof s === 'string')
|
|
797
|
+
refuse(fn, `${fn.name} returns ${s}`);
|
|
798
|
+
const x = g.newVar(`${fn.name}_result`, s, 'state', `what ${fn.name} returned, at the step that called it (its default at others)`);
|
|
799
|
+
outputs.push(x.name);
|
|
800
|
+
results[fn.name] = { k: 'scalar', name: x.name };
|
|
801
|
+
const it = go.intTy(fn.results[ri].t);
|
|
802
|
+
if (it)
|
|
803
|
+
g.ints.set(x.name, it);
|
|
804
|
+
out = [x.name, termOf(acc, fn)];
|
|
805
|
+
}
|
|
806
|
+
// An out-parameter (C's `T *out`, a box the caller gives): what the function left in it, beside the result.
|
|
807
|
+
const more = [];
|
|
808
|
+
for (const pa of params) {
|
|
809
|
+
const pt = go.T(pa.t);
|
|
810
|
+
if (pt.k !== 'ptr' || !go.T(pt.elem).box)
|
|
811
|
+
continue;
|
|
812
|
+
const id = `in:${fn.name}_${pa.name}`;
|
|
813
|
+
if (ok.some(([q]) => !q.heap.get(id)?.f?.has('value')))
|
|
814
|
+
refuse(fn, `${fn.name}: *${pa.name} neither set nor read where it returns (the caller's value, unknown to the rule)`);
|
|
815
|
+
const v = final.heap.get(id).f.get('value'), s = go.scalar(go.T(pt.elem).fields[0].t);
|
|
816
|
+
const x = g.newVar(`${fn.name}_${pa.name}`, s, 'state', `what ${fn.name} left in *${pa.name}, at the step that called it (its default at others)`);
|
|
817
|
+
outputs.push(x.name);
|
|
818
|
+
const it = go.intTy(go.T(pt.elem).fields[0].t);
|
|
819
|
+
if (it)
|
|
820
|
+
g.ints.set(x.name, it);
|
|
821
|
+
more.push([x.name, termOf(v, fn)]);
|
|
822
|
+
}
|
|
823
|
+
if (more.length)
|
|
824
|
+
results[fn.name] = { k: 'rec', fields: [...(out ? [['result', out[0]]] : []), ...more.map(([n]) => [n.slice(fn.name.length + 1), n])] };
|
|
825
|
+
finals.push({ sel, ...materialize(go, final, fn), ...(out ? { out } : {}), ...(more.length ? { more } : {}) });
|
|
826
|
+
events.push({ select: { [ev.name]: fn.name }, call: fn.name, args });
|
|
827
|
+
methods.push({ name: fn.name, ptr: !!fn.recv?.ptr, params, results: fn.results.map(r => r.t), err: errAt >= 0 });
|
|
828
|
+
}
|
|
829
|
+
// The lazy inputs' records: the fields read.
|
|
830
|
+
const recOf = (a) => (a.k === 'lazy' ? { k: 'rec', fields: (g.lazyIn.get(`in:${a.prefix}`)?.fields ?? []).map(([f, n]) => [f, { k: 'input', name: n }]) } : a);
|
|
831
|
+
for (const e of events)
|
|
832
|
+
e.args = e.args.map(recOf);
|
|
833
|
+
const answers = [...g.answers.values()].map(a => ({ ...a, ...(g.ints.get(a.inputs.name) ? { range: rangeOf(g.ints.get(a.inputs.name)) } : {}) }));
|
|
834
|
+
if (answers.length)
|
|
835
|
+
for (const e of events)
|
|
836
|
+
e.args.push({ k: 'rec', fields: answers.flatMap(a => [a.inputs.name, ...(a.inputs.none ? [a.inputs.none] : [])]).map(n => [n, { k: 'input', name: n }]) });
|
|
837
|
+
// (and the harness's: it makes the struct with the fields read)
|
|
838
|
+
for (const mt of methods)
|
|
839
|
+
mt.params = mt.params.map(pa => ({ ...pa, arg: recOf(pa.arg) }));
|
|
840
|
+
// The methods together: each variable by the method called.
|
|
841
|
+
const writes = {}, init = {};
|
|
842
|
+
const leafVars = stateVars.filter(v => !g.lists.some(d => d.name === v.name) && !g.maps.some(d => d.name === v.name));
|
|
843
|
+
for (const v of leafVars) {
|
|
844
|
+
init[v.name] = ctorInit?.get(v.name) ?? (v.sort.k === 'num' ? { s: 'num', e: I.num(0) } : v.sort.k === 'bool' ? { s: 'bool', e: v.name.endsWith('_nil') && go.leaves.some(l => l.name === v.name && (l.kind === 'bignil' || l.kind === 'mapnil')) ? I.T : I.F } : { s: 'str', e: { op: 'slit', value: '' } });
|
|
845
|
+
let acc;
|
|
846
|
+
for (let i = finals.length - 1; i >= 0; i--) {
|
|
847
|
+
const t = finals[i].leaves.get(v.name) ?? varTerm(v);
|
|
848
|
+
acc = acc === undefined ? t : iteTerm(finals[i].sel, t, acc);
|
|
849
|
+
}
|
|
850
|
+
if (acc && !I.same(acc.e, varTerm(v).e))
|
|
851
|
+
writes[v.name] = acc;
|
|
852
|
+
}
|
|
853
|
+
for (const o of outputs) {
|
|
854
|
+
const v = g.vars.get(o);
|
|
855
|
+
init[o] = v.sort.k === 'num' ? { s: 'num', e: I.num(0) } : v.sort.k === 'bool' ? { s: 'bool', e: I.F } : { s: 'str', e: { op: 'slit', value: '' } };
|
|
856
|
+
let acc = init[o];
|
|
857
|
+
for (let i = finals.length - 1; i >= 0; i--)
|
|
858
|
+
acc = iteTerm(finals[i].sel, finals[i].out?.[0] === o ? finals[i].out[1] : finals[i].more?.find(([n]) => n === o)?.[1] ?? init[o], acc);
|
|
859
|
+
writes[o] = acc;
|
|
860
|
+
}
|
|
861
|
+
const mapWrites = {};
|
|
862
|
+
for (const d of g.maps) {
|
|
863
|
+
const w = mapWritesOf(g, d, finals.map(f => f.sel), finals.map(f => f.maps.get(d.name)));
|
|
864
|
+
if (w)
|
|
865
|
+
mapWrites[d.name] = w;
|
|
866
|
+
}
|
|
867
|
+
const listWrites = {};
|
|
868
|
+
for (const d of g.lists) {
|
|
869
|
+
const ops = finals.flatMap(f => (f.lists.get(d.name) ?? []).map(o => ({ ...o, when: I.and(f.sel, o.when) })));
|
|
870
|
+
if (ops.length)
|
|
871
|
+
listWrites[d.name] = ops.map(o => (o.op === 'pop' ? o : { ...o, x: termOf(o.x, { p: '' }) }));
|
|
872
|
+
}
|
|
873
|
+
// What the rule reads or writes: the leaves no term mentions are left out (the check asks the code not to change them).
|
|
874
|
+
const used = new Set();
|
|
875
|
+
const mention = (t) => { const r = I.varsOf(t); for (const n of r.vars)
|
|
876
|
+
used.add(n); for (const n of r.maps)
|
|
877
|
+
used.add(n); };
|
|
878
|
+
for (const t of Object.values(writes))
|
|
879
|
+
mention(t.e);
|
|
880
|
+
for (const [n, w] of Object.entries(mapWrites)) {
|
|
881
|
+
used.add(n);
|
|
882
|
+
mention(w.has);
|
|
883
|
+
mention(w.key);
|
|
884
|
+
for (const t of Object.values(w.vals))
|
|
885
|
+
mention(t.e);
|
|
886
|
+
}
|
|
887
|
+
for (const [n, ops] of Object.entries(listWrites)) {
|
|
888
|
+
used.add(n);
|
|
889
|
+
for (const o of ops) {
|
|
890
|
+
mention(o.when);
|
|
891
|
+
if (o.op !== 'pop')
|
|
892
|
+
mention(o.x.e);
|
|
893
|
+
if (o.op === 'set')
|
|
894
|
+
mention(o.i);
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
const refuseB = I.or(...g.refusals);
|
|
898
|
+
mention(refuseB);
|
|
899
|
+
for (const n of Object.keys(writes))
|
|
900
|
+
used.add(n);
|
|
901
|
+
// A map's nil flag and a big.Int's go with their value.
|
|
902
|
+
for (const l of go.leaves) {
|
|
903
|
+
if (l.kind === 'bignil' && used.has(l.name.replace(/_nil$/, '')))
|
|
904
|
+
used.add(l.name);
|
|
905
|
+
if (l.kind === 'big' && used.has(`${l.name}_nil`))
|
|
906
|
+
used.add(l.name);
|
|
907
|
+
if (l.kind === 'mapnil' && used.has(l.name.replace(/_nil$/, '')))
|
|
908
|
+
used.add(l.name);
|
|
909
|
+
if (l.kind === 'map' && used.has(`${l.name}_nil`))
|
|
910
|
+
used.add(l.name);
|
|
911
|
+
if (l.kind === 'list' && used.has(`${l.name}_len`))
|
|
912
|
+
used.add(l.name);
|
|
913
|
+
}
|
|
914
|
+
const keepVar = (v) => used.has(v.name) || outputs.includes(v.name);
|
|
915
|
+
const state = [...leafVars.filter(keepVar), ...outputs.map(o => g.vars.get(o))];
|
|
916
|
+
for (const n of Object.keys(init))
|
|
917
|
+
if (!state.some(v => v.name === n))
|
|
918
|
+
delete init[n];
|
|
919
|
+
const leftOut = leafVars.filter(v => !keepVar(v)).map(v => v.name);
|
|
920
|
+
const maps = g.maps.filter(d => used.has(d.name)), lists = g.lists.filter(d => used.has(d.name));
|
|
921
|
+
for (const l of go.leaves)
|
|
922
|
+
if (l.name && !state.some(v => v.name === l.name) && !maps.some(d => d.name === l.name) && !lists.some(d => d.name === l.name))
|
|
923
|
+
l.kind = 'frame';
|
|
924
|
+
if (leftOut.length)
|
|
925
|
+
g.notes.add(`left out (no method reads or writes them; the check asks the code not to change them): ${leftOut.join(', ')}`);
|
|
926
|
+
for (const l of go.leaves)
|
|
927
|
+
if (l.kind === 'frame' && !l.name)
|
|
928
|
+
g.notes.add(`${l.path.join('.')}: a ${l.go}, outside the subset, left out (no method the rule reads touches it)`);
|
|
929
|
+
// The laws every state of the code keeps: each fixed-width number within its type's range, a nil map holding no key.
|
|
930
|
+
const laws = rangeLaws(state, g.ints);
|
|
931
|
+
// (a fixed array's items within their type's range too: C's; Go's slices have no such law yet)
|
|
932
|
+
for (const d of lists) {
|
|
933
|
+
const it = g.ints.get(`${d.name}.$item`);
|
|
934
|
+
if (d.len === undefined || !it)
|
|
935
|
+
continue;
|
|
936
|
+
const [lo, hi] = rangeOf(it);
|
|
937
|
+
if (Number.isFinite(hi))
|
|
938
|
+
laws.push(`r.law(${JSON.stringify(`${d.name}: each item within its type's range`)}, ({${d.name}}) => forall(k => ${d.name}.at(k).atMost(${hi}).and(${d.name}.at(k).atLeast(${lo}))))`);
|
|
939
|
+
}
|
|
940
|
+
for (const l of go.leaves)
|
|
941
|
+
if (l.kind === 'big' && state.some(v => v.name === l.name))
|
|
942
|
+
laws.push(`r.law(${JSON.stringify(`${l.name}: a nil one holds 0`)}, ({${l.name}, ${l.name}_nil}) => any(${l.name}_nil.not(), ${l.name}.eq(0)))`);
|
|
943
|
+
for (const d of maps)
|
|
944
|
+
laws.push(`r.law(${JSON.stringify(`${d.name}: a nil map holds no key`)}, ({${d.name}, ${d.name}_nil}) => forall(k => any(${d.name}_nil.not(), ${d.name}.at(k).has.not())))`);
|
|
945
|
+
const layout = { k: 'rec', fields: state.filter(v => !outputs.includes(v.name)).map(v => [v.name, { k: 'scalar', name: v.name }]) };
|
|
946
|
+
const model = {
|
|
947
|
+
name: opts.entry, shape: 'class', file: pkg.files[0]?.name ?? 'go', entry: opts.entry,
|
|
948
|
+
params: cparams, inputs: g.inputs, state, maps, init, writes, mapWrites, outputs, ...(lists.length ? { lists, listWrites } : {}),
|
|
949
|
+
refuse: refuseB, pre, layout, events, notes: [...g.notes], hints: g.hints, event: ev.name, results, laws,
|
|
950
|
+
};
|
|
951
|
+
// Unsigned inputs are naturals (the input's kind); a state variable's sort is the printer's to decide (a natural where
|
|
952
|
+
// every write is proven one: a wrap by cases may not be, though it stays within the type, which its law says).
|
|
953
|
+
const unsigned = [...g.ints].filter(([n, ty]) => { const [lo, hi] = rangeOf(ty); return lo === 0 && hi > 0 && (g.inputs.some(v => v.name === n) || cparams.some(v => v.name === n)); }).map(([n]) => n);
|
|
954
|
+
return { ...(pkg.ctor ? { ctor: ctorArgs } : {}), model, edges: g.edges, unsigned, leaves: go.leaves.filter(l => l.kind === 'frame' || state.some(v => v.name === l.name) || maps.some(d => d.name === l.name) || lists.some(d => d.name === l.name)), spans: [...g.spans.values()], entry: opts.entry, methods, ...(answers.length ? { answers } : {}) };
|
|
955
|
+
}
|
|
956
|
+
function termOf(v, at) {
|
|
957
|
+
if (v.t === 'num')
|
|
958
|
+
return { s: 'num', e: v.e };
|
|
959
|
+
if (v.t === 'bool')
|
|
960
|
+
return { s: 'bool', e: v.e };
|
|
961
|
+
if (v.t === 'str')
|
|
962
|
+
return { s: 'str', e: v.e };
|
|
963
|
+
return refuse(at, `${v.t === 'opaque' && v.ask ? v.why : `a ${v.t}`} where the rule keeps a number, a boolean or a string`);
|
|
964
|
+
}
|
|
965
|
+
// The state at a method's end, leaf by leaf (and the maps' and lists' writes), checking that no object of the state
|
|
966
|
+
// is in two of its places.
|
|
967
|
+
function materialize(go, p, at) {
|
|
968
|
+
const g = go.g, leaves = new Map(), maps = new Map(), lists = new Map();
|
|
969
|
+
const self = p.heap.get('this');
|
|
970
|
+
const seen = new Map();
|
|
971
|
+
for (const l of go.leaves) {
|
|
972
|
+
if (l.kind === 'frame' || l.kind === 'bignil' || l.kind === 'mapnil')
|
|
973
|
+
continue;
|
|
974
|
+
let v = { t: 'struct', ty: self.ty, f: self.f };
|
|
975
|
+
for (const s of l.path)
|
|
976
|
+
v = v?.t === 'struct' ? v.f.get(s) : undefined;
|
|
977
|
+
if (!v)
|
|
978
|
+
continue;
|
|
979
|
+
if (l.kind === 'big') {
|
|
980
|
+
if (v.t !== 'ptr' && v.t !== 'nil')
|
|
981
|
+
refuse(at, `${l.path.join('.')} set to other than a *big.Int`);
|
|
982
|
+
const cs = g.cases(v.t === 'nil' ? { k: 'nil' } : v.to);
|
|
983
|
+
let val;
|
|
984
|
+
for (const o of [...cs.objs].reverse()) {
|
|
985
|
+
const obj = p.heap.get(o.id);
|
|
986
|
+
if (obj?.k !== 'big')
|
|
987
|
+
refuse(at, `${l.path.join('.')} points to other than a big.Int`);
|
|
988
|
+
// One object in two places of the state, or one the caller gave: refused (the rule keeps a value per field).
|
|
989
|
+
const prev = seen.get(o.id);
|
|
990
|
+
if (prev && prev !== l.name)
|
|
991
|
+
refuse(at, `${l.path.join('.')} and ${prev} may be one big.Int (one object in two places of the state)`);
|
|
992
|
+
seen.set(o.id, l.name);
|
|
993
|
+
if (obj.origin === 'input')
|
|
994
|
+
refuse(at, `${l.path.join('.')} keeps the *big.Int the caller gave (the caller may change it after the call)`);
|
|
995
|
+
// Where it isn't nil it is one of the objects: the last of them needs no condition.
|
|
996
|
+
val = val === undefined ? obj.v : I.nite(o.c, obj.v, val);
|
|
997
|
+
}
|
|
998
|
+
// Unchanged (nil as it was, the same object with the same value): the variables themselves (a nil one holds 0).
|
|
999
|
+
const same = I.same(cs.nil, I.bvar(`${l.name}_nil`)) && val !== undefined && I.same(val, I.nvar(l.name));
|
|
1000
|
+
leaves.set(l.name, { s: 'num', e: same ? I.nvar(l.name) : val === undefined ? I.num(0) : I.nite(cs.nil, I.num(0), val) });
|
|
1001
|
+
leaves.set(`${l.name}_nil`, { s: 'bool', e: cs.nil });
|
|
1002
|
+
continue;
|
|
1003
|
+
}
|
|
1004
|
+
if (l.kind === 'map') {
|
|
1005
|
+
if (v.t !== 'map')
|
|
1006
|
+
continue;
|
|
1007
|
+
const o = p.heap.get(v.id);
|
|
1008
|
+
leaves.set(`${l.name}_nil`, { s: 'bool', e: o.nil });
|
|
1009
|
+
if (o.w)
|
|
1010
|
+
maps.set(l.name, { key: o.w.key, has: o.w.has, vals: Object.fromEntries([...o.w.vals].map(([f, x]) => [f, termOf(x, at)])) });
|
|
1011
|
+
continue;
|
|
1012
|
+
}
|
|
1013
|
+
if (l.kind === 'list') {
|
|
1014
|
+
if (v.t !== 'list')
|
|
1015
|
+
continue;
|
|
1016
|
+
const o = p.heap.get(v.id);
|
|
1017
|
+
if (o.ops.length)
|
|
1018
|
+
lists.set(l.name, o.ops);
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
leaves.set(l.name, termOf(v, at));
|
|
1022
|
+
}
|
|
1023
|
+
return { leaves, maps, lists };
|
|
1024
|
+
}
|
|
1025
|
+
const proc = globalThis.process;
|
|
1026
|
+
export const node = (id) => { const m = proc?.getBuiltinModule?.(id); if (!m)
|
|
1027
|
+
throw new Error(`the Go front end runs Go through ${id} (Node 20.16 or later, or Bun)`); return m; };
|
|
1028
|
+
// The reader, built once per version of its source (into the system's temporary directory).
|
|
1029
|
+
export function readerBinary() {
|
|
1030
|
+
const fs = node('node:fs'), cp = node('node:child_process'), os = node('node:os'), crypto = node('node:crypto');
|
|
1031
|
+
const dir = new URL('./go/', import.meta.url).pathname;
|
|
1032
|
+
const src = fs.readFileSync(`${dir}reader.go`, 'utf8'), h = crypto.createHash('sha256').update(src).digest('hex').slice(0, 12);
|
|
1033
|
+
const bin = `${os.tmpdir()}/gdp-goreader-${h}`;
|
|
1034
|
+
if (!fs.existsSync(bin))
|
|
1035
|
+
cp.execFileSync('go', ['build', '-o', bin, '.'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: { ...proc?.env, GOFLAGS: '-mod=mod', GOTOOLCHAIN: 'local' } });
|
|
1036
|
+
return bin;
|
|
1037
|
+
}
|
|
1038
|
+
export function readGoPackage(dir) {
|
|
1039
|
+
const cp = node('node:child_process');
|
|
1040
|
+
try {
|
|
1041
|
+
return JSON.parse(cp.execFileSync(readerBinary(), [dir], { encoding: 'utf8', maxBuffer: 1 << 29, stdio: ['ignore', 'pipe', 'pipe'] }));
|
|
1042
|
+
}
|
|
1043
|
+
catch (e) {
|
|
1044
|
+
throw new Refusal(dir, `the Go reader didn't run (${String(e.stderr || e.message).split('\n').filter(Boolean).slice(-2).join(' | ')}): go is needed to extract Go`);
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
export function extractGo(at, opts = {}) {
|
|
1048
|
+
const p = pathOf(at), dir = /\.go$/.test(p) ? p.replace(/\/[^/]*$/, '') || '.' : p;
|
|
1049
|
+
const notes = [];
|
|
1050
|
+
let read, pkg;
|
|
1051
|
+
try {
|
|
1052
|
+
pkg = readGoPackage(dir);
|
|
1053
|
+
pkg.dir = node('node:path').resolve(dir);
|
|
1054
|
+
try {
|
|
1055
|
+
read = readGo(pkg, opts);
|
|
1056
|
+
}
|
|
1057
|
+
catch (e) {
|
|
1058
|
+
if (e instanceof Refusal)
|
|
1059
|
+
capture({ k: 'read', opts, pkg, refusal: { where: e.where, what: e.what } });
|
|
1060
|
+
throw e;
|
|
1061
|
+
}
|
|
1062
|
+
capture({ k: 'read', opts, pkg, read });
|
|
1063
|
+
}
|
|
1064
|
+
catch (e) {
|
|
1065
|
+
if (e instanceof Refusal) {
|
|
1066
|
+
const r = { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
|
|
1067
|
+
snapshot(opts, r);
|
|
1068
|
+
return r;
|
|
1069
|
+
}
|
|
1070
|
+
throw e;
|
|
1071
|
+
}
|
|
1072
|
+
const file = `${read.entry}.go`;
|
|
1073
|
+
const x = fromModel(read.model, file, { ...unsignedDomains(read), ...opts.domains }, notes, (rule, sorts) => checkGo(dir, pkg, read, rule, sorts, opts));
|
|
1074
|
+
snapshot(opts, x);
|
|
1075
|
+
return { ...x, leaves: read.leaves, names: goNames(read) };
|
|
1076
|
+
}
|
|
1077
|
+
// The names of a Go (or C, C++) reading: each leaf of the state by its path (a nil one's flag beside it), the
|
|
1078
|
+
// constructor's and each method's arguments, each answer by its callee's name, each method's result.
|
|
1079
|
+
export function goNames(read) {
|
|
1080
|
+
const out = [], m = read.model;
|
|
1081
|
+
for (const l of read.leaves) {
|
|
1082
|
+
const code = l.path.join('.');
|
|
1083
|
+
if (l.kind === 'map')
|
|
1084
|
+
out.push({ code, rule: l.name, role: 'state', map: { fields: m.maps.find(d => d.name === l.name)?.fields.map(f => f.name) ?? [] } });
|
|
1085
|
+
else if (l.kind === 'bignil' || l.kind === 'mapnil') {
|
|
1086
|
+
const n = out.find(x => x.code === code && x.role === 'state');
|
|
1087
|
+
if (n)
|
|
1088
|
+
n.none = l.name;
|
|
1089
|
+
else
|
|
1090
|
+
out.push({ code, rule: '', role: 'state', none: l.name });
|
|
1091
|
+
}
|
|
1092
|
+
else if (l.kind === 'int' || l.kind === 'bool' || l.kind === 'str' || l.kind === 'big')
|
|
1093
|
+
out.push({ code, rule: l.name, role: 'state' });
|
|
1094
|
+
}
|
|
1095
|
+
const arg = (a, code, role, method) => {
|
|
1096
|
+
if (a.k === 'input')
|
|
1097
|
+
out.push({ code, rule: a.name, role, ...(method ? { method } : {}) });
|
|
1098
|
+
else if (a.k === 'rec')
|
|
1099
|
+
for (const [f, x] of a.fields)
|
|
1100
|
+
arg(x, `${code}.${f}`, role, method);
|
|
1101
|
+
};
|
|
1102
|
+
for (const c of read.ctor ?? [])
|
|
1103
|
+
arg(c.arg, c.name, 'param');
|
|
1104
|
+
for (const mt of read.methods)
|
|
1105
|
+
for (const pa of mt.params)
|
|
1106
|
+
arg(pa.arg, pa.name, 'input', mt.name);
|
|
1107
|
+
for (const a of read.answers ?? [])
|
|
1108
|
+
out.push({ code: a.key, rule: a.inputs.name, role: 'answer', ...(a.inputs.none ? { none: a.inputs.none } : {}) });
|
|
1109
|
+
for (const [method, r] of Object.entries(m.results ?? {})) {
|
|
1110
|
+
if (r.k === 'scalar')
|
|
1111
|
+
out.push({ code: 'result', rule: r.name, role: 'result', method });
|
|
1112
|
+
else if (r.k === 'rec')
|
|
1113
|
+
for (const [f, n] of r.fields)
|
|
1114
|
+
out.push({ code: f === 'result' ? 'result' : f, rule: n, role: 'result', method });
|
|
1115
|
+
}
|
|
1116
|
+
if (m.event)
|
|
1117
|
+
out.push({ code: 'method', rule: m.event, role: 'method' });
|
|
1118
|
+
return out;
|
|
1119
|
+
}
|
|
1120
|
+
// (gen/go-shared: each extraction's rule, notes and refusals appended to $GDP_GO_SNAPSHOT, to compare the Go front end
|
|
1121
|
+
// before and after it moves onto the shared executor)
|
|
1122
|
+
function snapshot(opts, x) {
|
|
1123
|
+
const f = proc?.env?.GDP_GO_SNAPSHOT;
|
|
1124
|
+
if (f)
|
|
1125
|
+
node('node:fs').appendFileSync(f, `${JSON.stringify({ entry: opts.entry, methods: opts.methods ?? null, ok: x.ok, source: x.source ?? null, notes: x.notes, refusals: x.refusals })}\n`);
|
|
1126
|
+
}
|
|
1127
|
+
// (gen/go-port: each reading's input, the reader's JSON, and its output appended to $GDP_GO_CAPTURE, for a differential
|
|
1128
|
+
// test of the port that needs no Go)
|
|
1129
|
+
function capture(x) {
|
|
1130
|
+
const f = proc?.env?.GDP_GO_CAPTURE;
|
|
1131
|
+
if (f)
|
|
1132
|
+
node('node:fs').appendFileSync(f, `${JSON.stringify({ ...x, opts: x.opts ? { ...x.opts, check: undefined } : undefined })}\n`);
|
|
1133
|
+
}
|
|
1134
|
+
// Unsigned numbers are naturals by their type (inputs and state alike); the rule's sorts say so.
|
|
1135
|
+
export function unsignedDomains(r) {
|
|
1136
|
+
const out = {};
|
|
1137
|
+
for (const n of r.unsigned)
|
|
1138
|
+
out[n] = 'nat';
|
|
1139
|
+
return out;
|
|
1140
|
+
}
|
|
1141
|
+
// A function the corpus names (not a struct's method): read as far as the subset goes, for where and why it stops; a
|
|
1142
|
+
// function the subset reads to its end is still not a step (a decision of its arguments, or writes to the caller's
|
|
1143
|
+
// objects): refused so, with what it is.
|
|
1144
|
+
export function probeGoFunc(pkg, name) {
|
|
1145
|
+
const r = probe(pkg, name);
|
|
1146
|
+
capture({ k: 'probe', pkg, name, out: r });
|
|
1147
|
+
return r;
|
|
1148
|
+
}
|
|
1149
|
+
function probe(pkg, name) {
|
|
1150
|
+
const go = new Go(pkg, { entry: '' }), fn = go.funcOf(name);
|
|
1151
|
+
if (!fn)
|
|
1152
|
+
return { where: pkg.files[0]?.name ?? '?', what: `${name}: not a function the package declares with a body` };
|
|
1153
|
+
try {
|
|
1154
|
+
if (fn.generic)
|
|
1155
|
+
refuse(fn, `${name}: a generic function`);
|
|
1156
|
+
const bound = go.bindParams(fn, I.T, { pc: [], locals: new Map(), heap: new Map(), called: [], locks: [], defers: [] });
|
|
1157
|
+
go.g.block(go.funcs[`.${fn.name}`].body, bound.p);
|
|
1158
|
+
}
|
|
1159
|
+
catch (e) {
|
|
1160
|
+
if (e instanceof Refusal)
|
|
1161
|
+
return { where: e.where, what: e.what };
|
|
1162
|
+
throw e;
|
|
1163
|
+
}
|
|
1164
|
+
const writes = fn.params.some(x => go.T(x.t).k === 'ptr');
|
|
1165
|
+
return { where: fn.p, what: `${name}: a function of its arguments${writes ? ' (the objects its pointers give are the caller\'s)' : ''}, not a step of a state the subset reads (a struct and its methods)` };
|
|
1166
|
+
}
|