gdp-wired 0.55.1 → 0.56.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.
@@ -1,7 +1,7 @@
1
1
  import type { B } from './extract-ir.js';
2
2
  import { type Arg, type Model, type FileURL } from './extract-read.js';
3
3
  import { type Extraction, type Name } from './extract.js';
4
- import { type Answer } from './extract-step.js';
4
+ import { type Answer, type SafetySite } from './extract-step.js';
5
5
  import { type GoCheckOptions, type GoLeaf } from './extract-go-check.js';
6
6
  export { minimizeRun, minimizeRunDetailed, proveRule, proveSteps } from './dsl.js';
7
7
  export type TT = {
@@ -87,6 +87,12 @@ export type GX = {
87
87
  }[];
88
88
  i?: GX;
89
89
  end?: string;
90
+ site?: SafetySite;
91
+ sites?: SafetySite[];
92
+ checkedType?: number;
93
+ dims?: number[];
94
+ vals?: number[];
95
+ indices?: GX[];
90
96
  };
91
97
  export type GS = {
92
98
  s: string;
@@ -145,10 +151,12 @@ export type GoFunc = {
145
151
  params: GoParam[];
146
152
  results: GoParam[];
147
153
  body?: GS[];
154
+ safetySites?: SafetySite[];
148
155
  };
149
156
  export type GoPkg = {
150
157
  dir?: string;
151
158
  lang?: string;
159
+ safety?: true;
152
160
  ctor?: GoFunc;
153
161
  package: string;
154
162
  files: {
@@ -189,6 +197,7 @@ export type GoOptions = {
189
197
  check?: GoCheckOptions;
190
198
  fails?: Record<string, string>;
191
199
  strict?: boolean;
200
+ safety?: boolean;
192
201
  answers?: Record<string, string>;
193
202
  skip?: string[];
194
203
  };
@@ -198,6 +207,11 @@ export type GoClock = {
198
207
  callee: string;
199
208
  };
200
209
  export type GoRead = {
210
+ safety?: {
211
+ sites: (SafetySite & {
212
+ condition: B;
213
+ })[];
214
+ };
201
215
  clocks?: GoClock[];
202
216
  answers?: (Answer & {
203
217
  range?: [number, number];
@@ -55,6 +55,8 @@ class Go {
55
55
  this.opts = opts;
56
56
  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 };
57
57
  this.g = new Stepper(mod, { entry: opts.entry, ...(opts.onError ? { onError: opts.onError } : {}), ...(opts.answers ? { answers: opts.answers } : {}), ...(opts.skip ? { skip: opts.skip } : {}) }, inf);
58
+ if (opts.safety)
59
+ this.g.safety = new Map();
58
60
  for (const f of pkg.funcs)
59
61
  this.funcs[`${f.recv?.type ?? ''}.${f.name}`] = this.fn(f);
60
62
  }
@@ -121,7 +123,10 @@ class Go {
121
123
  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;
122
124
  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 } : {}) });
123
125
  }
124
- at(x) { return { p: x.p, text: x.text }; }
126
+ at(x) {
127
+ const ity = this.opts.safety && x.checkedType !== undefined ? this.intTy(x.checkedType) ?? refuse(x, 'missing integer operation type in C safety source') : undefined;
128
+ return { p: x.p, text: x.text, ...(this.opts.safety && x.site ? { site: x.site } : {}), ...(ity ? { ity } : {}) };
129
+ }
125
130
  // A value as the type it is assigned to: an untyped constant takes the type; an integer stays itself.
126
131
  as(v, t) {
127
132
  const ty = this.intTy(t), k = this.T(t).k;
@@ -208,6 +213,7 @@ class Go {
208
213
  return { e: 'lidx', ...at, s: this.x(x.x), i: this.x(x.i), ty: this.intTy(xt.elem) };
209
214
  return this.no(x, `${x.text}: an index into a ${this.tname(x.x.t)}`, { pre: [this.x(x.x), this.x(x.i)] });
210
215
  }
216
+ case 'table': return { e: 'table', ...at, sites: x.sites, dims: x.dims, vals: x.vals, indices: (x.indices ?? []).map(y => this.x(y)), ity: this.intTy(x.t), isBool: this.T(x.t).k === 'bool' };
211
217
  case 'slice': {
212
218
  // s[:len(s)-1] of a slice of the state: its last item taken off (put back in s's own place).
213
219
  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;
@@ -685,6 +691,18 @@ class Go {
685
691
  // Read with the boundary inferred unless strict (core/extract-step.ts's readStep: each refused run adds what the next
686
692
  // infers): Go's check can't stub a call, so a call of another package is left out where nothing reads its value.
687
693
  export function readGo(pkg, opts) {
694
+ if (opts.safety) {
695
+ const at = pkg.files[0]?.name ?? '?';
696
+ if (!pkg.safety || pkg.lang !== 'c')
697
+ refuse(at, 'C safety requires the checked source reader');
698
+ if (Object.keys(opts.answers ?? {}).length || opts.skip?.length || Object.keys(opts.domains ?? {}).length)
699
+ refuse(at, 'safety does not allow inferred boundaries or custom domains');
700
+ if (opts.onError === 'discard')
701
+ refuse(at, 'C safety does not allow discarding state writes on failure');
702
+ return readGo1(pkg, { ...opts, onError: 'refuse' }, new Go(pkg, { ...opts, onError: 'refuse' }));
703
+ }
704
+ if (pkg.safety)
705
+ refuse(pkg.files[0]?.name ?? '?', 'checked C source requires safety lowering');
688
706
  if (!opts.entry && !opts.strict) {
689
707
  // No entry: the package's one struct whose exported methods write it (core/extract-step.ts's writesState).
690
708
  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 ?? ''])));
@@ -756,7 +774,30 @@ function readGo1(pkg, o, go) {
756
774
  p = g.bindLocal(pa.id, it ? { t: 'num', e: I.nvar(v.name), ty: it } : { t: 'bool', e: I.bvar(v.name) }, fn, p);
757
775
  }
758
776
  p = g.bindLocal('this', { t: 'ptr', to: { k: 'obj', id: 'this', path: [] } }, fn, p);
777
+ const ctorCut = g.safety ? new Set() : undefined, ctorDead = g.safety ? new Set() : undefined;
778
+ if (g.safety) {
779
+ if (fn.safetySites === undefined)
780
+ refuse(fn, 'missing pre-lowering C safety site inventory on initializer');
781
+ g.safetyCutSites = ctorCut;
782
+ g.safetyDeadSites = ctorDead;
783
+ }
759
784
  const flow = g.block(go.fn(fn).body, p), ends = [...flow.rets.map(([q]) => q), ...(flow.live ? [flow.live] : [])];
785
+ if (g.safety) {
786
+ const expected = new Set((fn.safetySites ?? []).map(s => `${s.kind}:${s.where}`));
787
+ for (const s of fn.safetySites ?? []) {
788
+ const key = `${s.kind}:${s.where}`;
789
+ if (!ctorCut.has(key) && !ctorDead.has(key))
790
+ refuse(fn, `unaccounted C safety initializer site (${s.kind} at ${s.where})`);
791
+ }
792
+ for (const k of ctorCut)
793
+ if (!expected.has(k))
794
+ refuse(fn, `uninventoried C safety initializer cut (${k})`);
795
+ if ([...g.safety.values()].some(s => !(s.condition.op === 'const' && !s.condition.v)))
796
+ refuse(fn, 'a constructor with a possible C safety fault');
797
+ g.safety.clear();
798
+ g.safetyCutSites = undefined;
799
+ g.safetyDeadSites = undefined;
800
+ }
760
801
  if (g.refusals.length > n0 || !ends.length)
761
802
  refuse(fn, 'a constructor that can fail (the rule\'s start is where it leaves the object)');
762
803
  const m = materialize(go, g.join(ends, fn), fn);
@@ -780,6 +821,7 @@ function readGo1(pkg, o, go) {
780
821
  g.method = fn.name;
781
822
  const sel = I.is(evL, fn.name);
782
823
  let p = { pc: [sel], locals: new Map(), heap: new Map(heap), called: [], locks: [], defers: [] };
824
+ const beforeInput = g.refusals.length;
783
825
  const bound = go.bindParams(fn, sel, p), args = bound.args, params = bound.params;
784
826
  p = bound.p;
785
827
  // (an out-parameter a path leaves as the caller gave it: what the caller gave, an input, read at the start)
@@ -788,6 +830,8 @@ function readGo1(pkg, o, go) {
788
830
  if (pt.k === 'ptr' && go.T(pt.elem).box && (go.T(pt.elem).fields ?? []).length === 1 && boxKept(lowered0(fn), pa.id))
789
831
  g.lazyFieldIn(`in:${fn.name}_${pa.name ?? 'arg'}`, 'value', p, fn);
790
832
  }
833
+ if (g.safety)
834
+ p = g.assume(p, I.not(I.or(...g.refusals.slice(beforeInput))));
791
835
  // The receiver.
792
836
  if (fn.recv?.id)
793
837
  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);
@@ -797,13 +841,45 @@ function readGo1(pkg, o, go) {
797
841
  refuse(fn, `${fn.name} returns ${kept.length} values (a result kept is one value)`);
798
842
  const lowered = lowered0(fn);
799
843
  g.spans.set(`${opts.entry}.${fn.name}`, [fn.p.split(':')[0], fn.span[0], fn.span[1]]);
844
+ const methodCut = g.safety ? new Set() : undefined, methodDead = g.safety ? new Set() : undefined;
845
+ if (g.safety) {
846
+ if (fn.safetySites === undefined)
847
+ refuse(fn, 'missing pre-lowering C safety site inventory');
848
+ g.safetyCutSites = methodCut;
849
+ g.safetyDeadSites = methodDead;
850
+ }
851
+ const beforeBody = g.refusals.length;
800
852
  const flow = g.block(lowered.body, p);
853
+ if (g.safety) {
854
+ g.safetyCutSites = undefined;
855
+ g.safetyDeadSites = undefined;
856
+ const expected = new Set(fn.safetySites.map(s => `${s.kind}:${s.where}`));
857
+ for (const s of fn.safetySites) {
858
+ const key = `${s.kind}:${s.where}`;
859
+ if (!methodCut.has(key) && !methodDead.has(key))
860
+ refuse(fn, `unaccounted C safety source site (${s.kind} at ${s.where})`);
861
+ g.registerSafety(s);
862
+ }
863
+ for (const k of methodCut)
864
+ if (!expected.has(k))
865
+ refuse(fn, `uninventoried C safety cut (${k})`);
866
+ }
867
+ if (g.safety && g.refusals.length !== beforeBody)
868
+ refuse(fn, 'an untracked refusal on a C safety source path');
869
+ if (g.safety && flow.live && fn.results.length) {
870
+ const c = g.cond(flow.live);
871
+ if (!(c.op === 'const' && !c.v))
872
+ refuse(fn, 'a non-void C method with a reachable fallthrough');
873
+ }
801
874
  if (flow.brk?.length)
802
875
  refuse(fn, 'a break outside a switch');
803
876
  const rets = [...flow.rets.map(([q, v]) => [q, v.xs]), ...(flow.live ? [[flow.live, []]] : [])];
804
877
  // An error returned: a refusal (where it isn't nil), the state as it was there.
805
878
  const ok = [];
806
879
  for (const [q0, vs] of rets) {
880
+ const prefix = g.cond(q0);
881
+ if (g.safety && prefix.op === 'const' && !prefix.v)
882
+ continue;
807
883
  const q = { ...q0, locks: q0.locks.filter(k => !q0.defers.includes(k)) };
808
884
  if (q.locks.length)
809
885
  refuse(fn, `${fn.name} returns with a mutex locked`);
@@ -812,6 +888,8 @@ function readGo1(pkg, o, go) {
812
888
  // A result the caller states is the failure where it compares so: a refusal there, as an error is.
813
889
  const m = /^\s*(==|!=|<=|>=|<|>)\s*(-?\d+|true|false)\s*$/.exec(fails) ?? refuse(fn, `fails: ${JSON.stringify(fails)} (a comparison with a constant: '< 0', '!= 0', '== false')`);
814
890
  const r = vs[0] ?? refuse(fn, `${fn.name} returns nothing to compare (fails: ${fails})`);
891
+ if (g.safety && !['true', 'false'].includes(m[2]) && !Number.isSafeInteger(Number(m[2])))
892
+ refuse(fn, 'an inexact configured failure constant');
815
893
  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])) };
816
894
  // (no failure where the result's bounds and the path's facts exclude it: an item of a uint8_t is never < 0)
817
895
  const kv = Number(m[2]), e = r.t === 'num' ? r.e : undefined, op = m[1];
@@ -832,8 +910,25 @@ function readGo1(pkg, o, go) {
832
910
  else
833
911
  ok.push([q, vs]);
834
912
  }
835
- if (!ok.length)
836
- refuse(fn, `${fn.name} always fails`);
913
+ if (!ok.length) {
914
+ if (!g.safety)
915
+ refuse(fn, `${fn.name} always fails`);
916
+ // This method still exists as an event: a fault can be its only exit.
917
+ // Its normal slot values are immaterial on faults (the monitor stutters).
918
+ const vs = fn.results.map(r => go.T(r.t).k === 'bool' ? { t: 'bool', e: I.F } : { t: 'num', e: I.num(0), ty: go.intTy(r.t) });
919
+ const dummy = g.assume(p, I.F);
920
+ for (const pa of params) {
921
+ const pt = go.T(pa.t);
922
+ if (pt.k !== 'ptr' || !go.T(pt.elem).box)
923
+ continue;
924
+ const id = `in:${fn.name}_${pa.name}`, obj = dummy.heap.get(id);
925
+ if (obj?.k === 'rec' && !obj.f.has('value')) {
926
+ const et = go.T(pt.elem).fields[0].t;
927
+ dummy.heap.set(id, { ...obj, f: new Map(obj.f).set('value', go.T(et).k === 'bool' ? { t: 'bool', e: I.F } : { t: 'num', e: I.num(0), ty: go.intTy(et) }) });
928
+ }
929
+ }
930
+ ok.push([dummy, vs]);
931
+ }
837
932
  // The kept result: by the path that returned it (a local the join merges).
838
933
  const ri = fn.results.findIndex((_, i) => i !== errAt);
839
934
  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');
@@ -955,6 +1050,9 @@ function readGo1(pkg, o, go) {
955
1050
  }
956
1051
  const refuseB = I.or(...g.refusals);
957
1052
  mention(refuseB);
1053
+ const safety = g.safety ? { sites: [...g.safety.values()] } : undefined;
1054
+ for (const s of safety?.sites ?? [])
1055
+ mention(s.condition);
958
1056
  for (const n of Object.keys(writes))
959
1057
  used.add(n);
960
1058
  // A map's nil flag and a big.Int's go with their value.
@@ -1012,7 +1110,7 @@ function readGo1(pkg, o, go) {
1012
1110
  // Unsigned inputs are naturals (the input's kind); a state variable's sort is the printer's to decide (a natural where
1013
1111
  // every write is proven one: a wrap by cases may not be, though it stays within the type, which its law says).
1014
1112
  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);
1015
- return { ...(g.now ? { clocks: [...go.clocks.values()] } : {}), ...(pkg.ctor ? { ctor: ctorArgs } : {}), ...(g.leftOut.size ? { leftOut: [...g.leftOut] } : {}), 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 } : {}) };
1113
+ return { ...(safety ? { safety } : {}), ...(g.now ? { clocks: [...go.clocks.values()] } : {}), ...(pkg.ctor ? { ctor: ctorArgs } : {}), ...(g.leftOut.size ? { leftOut: [...g.leftOut] } : {}), 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 } : {}) };
1016
1114
  }
1017
1115
  function termOf(v, at) {
1018
1116
  // (none: a path that ends without the value, which a reader of malformed source may join in)
@@ -370,7 +370,8 @@ function pn(e, P, ctx, mode, recv = false) {
370
370
  const prod = `${f(e.a, true)}.mul(${f(e.b, false)})`;
371
371
  return nat ? prod : `Int.of(${prod})`;
372
372
  }
373
- return `${pn(e.a, P, ctx, 'nat', true)}.mul(${pn(e.b, P, ctx, 'nat')})`;
373
+ const prod = `${pn(e.a, P, ctx, 'nat', true)}.mul(${pn(e.b, P, ctx, 'nat')})`;
374
+ return !nat && recv ? `Int.of(${prod})` : prod;
374
375
  case 'min': return nat ? `min(${A(e.a)}, ${A(e.b)})` : `${R(e.a)}.min(${A(e.b)})`;
375
376
  case 'max':
376
377
  if (nat) {
@@ -389,7 +390,8 @@ function pn(e, P, ctx, mode, recv = false) {
389
390
  // where the dividend is at least 0.
390
391
  if (!natOK(e.a, ctx) && !nonneg(e.a, ctx))
391
392
  throw new Refusal(P.m.file, 'x % k where x may be negative (JavaScript\'s remainder takes the sign of x)');
392
- return `${pn(e.a, P, ctx, natOK(e.a, ctx) ? 'nat' : 'int', true)}.modBy(${e.k})`;
393
+ const rem = `${pn(e.a, P, ctx, natOK(e.a, ctx) ? 'nat' : 'int', true)}.modBy(${e.k})`;
394
+ return !nat && recv ? `Int.of(${rem})` : rem;
393
395
  case 'ite': {
394
396
  const d = decided(e.c, ctx);
395
397
  if (d !== undefined)
@@ -246,6 +246,7 @@ type V = {
246
246
  cmp?: [N, N];
247
247
  slen?: K;
248
248
  bits?: Bits;
249
+ range?: [number, number];
249
250
  } | {
250
251
  t: 'bool';
251
252
  e: B;
@@ -614,6 +615,10 @@ type Pend = Bound & {
614
615
  at: string;
615
616
  end?: string;
616
617
  };
618
+ export type SafetySite = {
619
+ where: string;
620
+ kind: 'bounds' | 'overflow' | 'division';
621
+ };
617
622
  export declare class Stepper {
618
623
  readonly mod: SModule;
619
624
  readonly opts: StepOptions;
@@ -623,6 +628,16 @@ export declare class Stepper {
623
628
  readonly params: Var[];
624
629
  readonly notes: Set<string>;
625
630
  readonly refusals: B[];
631
+ safety?: Map<string, SafetySite & {
632
+ condition: B;
633
+ }>;
634
+ safetyCutSites?: Set<string>;
635
+ safetyDeadSites?: Set<string>;
636
+ registerSafety(site: SafetySite): (SafetySite & {
637
+ condition: B;
638
+ }) | undefined;
639
+ markSafetyDead(node: unknown, seenFns?: Set<string>): void;
640
+ safetyCut(p: Path, at: SX, kind: SafetySite['kind'], bad: B): Path;
626
641
  fails: B[];
627
642
  failPaths: Path[];
628
643
  readonly maps: MapDecl[];
@@ -1074,6 +1089,13 @@ export declare class Stepper {
1074
1089
  eq(a: V, b: V, x: {
1075
1090
  p: string;
1076
1091
  }, p?: Path): B;
1092
+ safetyRange(ty: IntTy | undefined, at: SX): [number, number];
1093
+ safetyBounds(v: Extract<V, {
1094
+ t: 'num';
1095
+ }>, at: SX): [number, number];
1096
+ safetyModulo(e: N, m: number, lo?: number): N;
1097
+ safetyWrapUnsigned(e: N, lo: bigint, hi: bigint, mod: number): N;
1098
+ safetyArith(op: string, a: V, b: V, at: SX, p: Path): [V, Path];
1077
1099
  arith(op: string, a: V, b: V, x: {
1078
1100
  p: string;
1079
1101
  }, p: Path): V;