gdp-wired 0.46.0 → 0.47.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.
@@ -1066,67 +1066,5 @@ export function conforms(r, svc, opts) {
1066
1066
  }
1067
1067
  return { checked };
1068
1068
  }
1069
- // A Schema's kind (its type side, 3.x or 4.x): a struct a record, string literals a choice, a tagged union of structs a
1070
- // variant on `_tag`, integers int (nat where at least 0), Boolean, String, `X | null` and optional fields a maybe, a
1071
- // Schema.Class its fields. A number that may be fractional, and any other Schema, is refused with the path to it.
1072
- // 3.x's AST nodes by 4.x's names:
1073
- const TAGS = { NumberKeyword: 'Number', BooleanKeyword: 'Boolean', StringKeyword: 'String', TypeLiteral: 'Objects', UndefinedKeyword: 'Undefined' };
1074
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1075
- export function fromSchema(schema) {
1076
- const fail = (path, what) => { throw new Error(`fromSchema: ${path || 'the schema'} is ${what}`); };
1077
- const tagOf = (a) => TAGS[a?._tag] ?? a?._tag;
1078
- const ann = (a, id) => { const k = Object.getOwnPropertySymbols(a.annotations ?? {}).find(x => x.description === id); return k ? a.annotations[k] : undefined; };
1079
- const base = (a) => (a._tag === 'Refinement' ? base(a.from) : a);
1080
- // An integer: 4.x's checks on Number (isInt, a minimum), 3.x's Refinements down to NumberKeyword (Int, a JSON Schema minimum).
1081
- const num = (a, path) => {
1082
- let int = false, min = -Infinity;
1083
- for (let x = a; x; x = x._tag === 'Refinement' ? x.from : undefined) {
1084
- const js = ann(x, 'effect/annotation/JSONSchema');
1085
- for (const c of [...(x.checks ?? []).map((c) => c.annotations ?? {}).map((an) => ({ int: an.representation?.id === 'effect/schema/isInt' || an.arbitraryConstraint?.number?.isInteger, min: an.arbitraryConstraint?.minimum })),
1086
- { int: js?.type === 'integer' || ann(x, 'effect/annotation/SchemaId')?.description === 'effect/SchemaId/Int', min: js?.minimum }]) {
1087
- int ||= !!c.int;
1088
- if (typeof c.min === 'number')
1089
- min = Math.max(min, c.min);
1090
- }
1091
- }
1092
- return int ? (min >= 0 ? dsl.nat : dsl.int) : fail(path, 'a number that may be fractional (an integer schema, Schema.Int, is read)');
1093
- };
1094
- const props = (a) => a.propertySignatures;
1095
- const go = (a, path) => {
1096
- const tag = tagOf(a);
1097
- if (tag === 'Transformation')
1098
- return go(a.to, path);
1099
- if (tag === 'Number' || (tag === 'Refinement' && tagOf(base(a)) === 'Number'))
1100
- return num(a, path);
1101
- if (tag === 'Refinement')
1102
- return go(a.from, path);
1103
- if (tag === 'Boolean')
1104
- return dsl.bool;
1105
- if (tag === 'String')
1106
- return dsl.str();
1107
- if (tag === 'Literal')
1108
- return typeof a.literal === 'string' ? dsl.oneOf(a.literal) : fail(path, `the literal ${String(a.literal)} (string literals are read)`);
1109
- if (tag === 'Objects') {
1110
- if (a.indexSignatures?.length)
1111
- fail(path, 'a record with an index signature');
1112
- return dsl.record(fieldsOf(a, path, false));
1113
- }
1114
- if (tag !== 'Union')
1115
- return fail(path, `a ${a?._tag} schema (structs, literals, tagged unions, integers, booleans and strings are read)`);
1116
- const types = a.types, missing = types.filter(t => ['Null', 'Undefined'].includes(tagOf(t)) || (t._tag === 'Literal' && t.literal === null)), rest = types.filter(t => !missing.includes(t));
1117
- const caseOf = (t) => { const p = tagOf(t) === 'Objects' ? props(t).find(x => x.name === '_tag') : undefined; return p?.type._tag === 'Literal' && typeof p.type.literal === 'string' ? p.type.literal : undefined; };
1118
- if (missing.length && rest.length === 1)
1119
- return dsl.maybe(go(rest[0], path));
1120
- if (rest.every(t => t._tag === 'Literal' && typeof t.literal === 'string'))
1121
- return dsl.oneOf(...rest.map(t => t.literal));
1122
- if (!missing.length && rest.every(caseOf))
1123
- return dsl.variant(Object.fromEntries(rest.map(t => [caseOf(t), fieldsOf(t, path, true)])), { tag: '_tag' });
1124
- return fail(path, 'a union other than of string literals, of structs tagged by _tag, or with null');
1125
- };
1126
- const fieldsOf = (a, path, tagged) => Object.fromEntries(props(a).filter(p => !(tagged && p.name === '_tag')).map(p => {
1127
- const k = go(p.type, `${path ? `${path}.` : ''}${String(p.name)}`);
1128
- return [String(p.name), (p.isOptional || p.context?.isOptional) && !('of' in k) ? dsl.maybe(k) : k];
1129
- }));
1130
- const ast = schema.ast;
1131
- return schema.fields && tagOf(ast) !== 'Objects' ? dsl.record(Object.fromEntries(Object.entries(schema.fields).map(([f, x]) => [f, go(x.ast, f)]))) : go(ast, '');
1132
- }
1069
+ // The decoded Schema frontend is independent of service extraction and keeps Effect optional.
1070
+ export { fromSchema, SchemaError, SchemaKind } from "./effect-schema.js";
@@ -400,7 +400,7 @@ export function check(code, file, m, r, sorts, opts = {}) {
400
400
  return retried(() => checkOnce(code, file, m, r, sorts, opts), noEvidence);
401
401
  }
402
402
  function checkOnce(code, file, m, r, sorts, opts) {
403
- const isClass = m.shape === 'class', fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
403
+ const isClass = m.shape === 'class', standalone = !!m.standalone, fns = m.shape === 'class' ? [m.entry] : [...new Set(m.events.map(e => e.call))];
404
404
  let answers = {};
405
405
  // (the modules whose functions the class calls: each export answers its input, or nothing, by the callee's name)
406
406
  const ans = (path) => () => { const n = Object.keys(m.answers ?? {}).find(k => m.answers[k] === path); return n === undefined ? undefined : answers[n]; };
@@ -444,6 +444,8 @@ function checkOnce(code, file, m, r, sorts, opts) {
444
444
  at: (snap, params) => (box.call('$at', undefined, [valueOf(snap, m.layout, m, evalAt(params), box.ctx), ctorValues(params)]).ok ? box.ctx.__r.value : (() => { throw new Error(`could not make the object: ${box.ctx.__r.error}`); })()),
445
445
  snapOf: (self, params) => snapOf(stateOf(self), m.layout, m, evalAt(params)),
446
446
  call: (self, e, args) => {
447
+ if (standalone)
448
+ return box.call(e.call, undefined, args);
447
449
  for (const f of new Set(Object.values(m.answers ?? {})))
448
450
  if (!f.startsWith('import:'))
449
451
  self[f] = answering(f);
@@ -459,7 +461,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
459
461
  args: (inputs, e) => {
460
462
  answers = inputs;
461
463
  const dateIn = (n) => { const x = m.inputs.find(v => v.name === n); return x?.sort.k === 'num' && x.sort.date ? vmOf().runInContext(`new Date(${Number(inputs[n])})`, box.ctx) : inputs[n]; };
462
- const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
464
+ const build = (a) => (a.k === 'input' ? dateIn(a.name) : a.k === 'maybe-bool' ? (inputs[a.missing] ? undefined : inputs[a.name]) : a.k === 'lit' ? a.value : a.k === 'rec' ? Object.fromEntries(a.fields.map(([f, x]) => [f, build(x)])) : a.k === 'lazy'
463
465
  ? Object.fromEntries([...m.inputs].filter(v => m.lazy?.get(v.name)?.prefix === a.prefix).map(v => [m.lazy.get(v.name).field, inputs[v.name]]))
464
466
  : undefined);
465
467
  return e.args.map(build);
@@ -490,7 +492,7 @@ function checkOnce(code, file, m, r, sorts, opts) {
490
492
  // (through its side) and of the rule, and compared.
491
493
  export function drive(m, r, sorts, code, opts = {}) {
492
494
  const t0 = performance.now(), rand = seeded((opts.seed ?? 7) >>> 0 || 1), bound = opts.bound ?? 12;
493
- const isClass = m.shape === 'class';
495
+ const isClass = m.shape === 'class', standalone = !!m.standalone;
494
496
  const interp = r.interpreter(), gen = r.compiled(), machine = r.machine;
495
497
  const ev = { runs: 0, requests: 0, fromStates: 0, probes: { conditions: 0, witnesses: 0, steps: 0 }, refusedBoth: 0, outside: 0, edge: 0, compiledAgreed: 0, coverage: { arms: 0, hit: 0, missed: [] }, ms: 0 };
496
498
  const consts = constantsOf(m), strs = stringsOf(m);
@@ -518,7 +520,8 @@ export function drive(m, r, sorts, code, opts = {}) {
518
520
  }
519
521
  const keys = Object.values(st.maps).flatMap(c => Object.keys(c));
520
522
  // An input given as a natural (domains) is drawn as one: the claim is for those, as the user said.
521
- const x = draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
523
+ const finite = m.standaloneDomains?.[v.name];
524
+ const x = finite ? finite[rand(finite.length)] : draw(v.sort, sorts, v.name, rand, near, bound, [...strs, ...keys]);
522
525
  inputs[v.name] = code.input ? code.input(v, x, rand) : opts.given?.[v.name] === 'nat' && typeof x === 'number' ? Math.abs(x) : x;
523
526
  }
524
527
  // (a list the request carries: up to 4 items, mostly, each field drawn by its sort)
@@ -530,6 +533,10 @@ export function drive(m, r, sorts, code, opts = {}) {
530
533
  const used = new Set();
531
534
  const walk = (a) => { if (a.k === 'input')
532
535
  used.add(a.name);
536
+ else if (a.k === 'maybe-bool') {
537
+ used.add(a.name);
538
+ used.add(a.missing);
539
+ }
533
540
  else if (a.k === 'rec')
534
541
  a.fields.forEach(([, x]) => walk(x));
535
542
  else if (a.k === 'lazy')
@@ -546,6 +553,13 @@ export function drive(m, r, sorts, code, opts = {}) {
546
553
  // Steps the code and the rule from one state; undefined when they agree (the next state on both sides is returned
547
554
  // through `next`), else the difference.
548
555
  const step = (params, ps, side, st, inputs, e, next, where) => {
556
+ // A source type's finite numeric domain is part of the standalone claim, not
557
+ // behavior the source is alleged to reject. Never execute an out-of-domain probe.
558
+ if (m.standalone && Object.entries(m.standaloneDomains ?? {}).some(([name, values]) => !values.includes(inputs[name]))) {
559
+ ev.outside++;
560
+ next.stop = true;
561
+ return undefined;
562
+ }
549
563
  const args = code.args(inputs, e), raw = ruleInputs(inputs, e);
550
564
  if (m.folds)
551
565
  carry(m, raw, inputs, side.snap, params, r.decode(st));
@@ -555,7 +569,18 @@ export function drive(m, r, sorts, code, opts = {}) {
555
569
  // The code.
556
570
  let res;
557
571
  try {
558
- if (isClass) {
572
+ if (standalone) {
573
+ const c = code.call(undefined, e, args);
574
+ if (!c.ok && c.outside) {
575
+ next.stop = true;
576
+ ev.outside++;
577
+ return undefined;
578
+ }
579
+ // Result fields in a prover witness are not state held by a pure
580
+ // function. Compare the returned value below, never carry those fields.
581
+ res = c.ok ? { snap: { leaves: {}, maps: {} }, out: c.value } : { refused: c.error };
582
+ }
583
+ else if (isClass) {
559
584
  const self = side.self, c = code.call(self, e, args);
560
585
  if (!c.ok && c.outside) {
561
586
  next.stop = true;
@@ -656,7 +681,7 @@ export function drive(m, r, sorts, code, opts = {}) {
656
681
  const ruleSide = ruleSnap(r, m, rule.st, sorts), diff = sameSnap(res.snap, ruleSide);
657
682
  if (diff)
658
683
  return `${where}: ${req} ${from}: ${diff}`;
659
- if (isClass) {
684
+ if (isClass || standalone) {
660
685
  // The method's result, as the rule keeps it: a value, a record's fields, or a value and whether it is missing.
661
686
  const rk = m.results?.[e.call], d = r.decode(rule.st);
662
687
  const bad = (what) => `${where}: ${req} ${from}: ${e.call} returns ${JSON.stringify(res.out)}, ${what}`;
@@ -7,6 +7,8 @@ import { node } from "./extract-go.js";
7
7
  function harness(pkg, read, m, discard) {
8
8
  const T = (t) => pkg.ttab[t] ?? { k: 'invalid' };
9
9
  const imports = new Set(['bufio', 'encoding/json', 'fmt', 'os', 'reflect', 'strconv', 'math/big']);
10
+ if (read.clocks?.length)
11
+ imports.add('time');
10
12
  const qual = (t) => { const x = T(t); if (x.pkg && !x.own && x.pkg !== '')
11
13
  imports.add(x.pkg); };
12
14
  const acc = (path) => `o.${path.join('.')}`;
@@ -120,12 +122,17 @@ import (
120
122
  ${[...imports].sort().map(p => `\t${p.split('/')[0].includes('.') ? `${p.replace(/[^A-Za-z0-9]/g, '_').replace(/^/, 'gdp_')} ` : ''}${JSON.stringify(p)}`).join('\n')}
121
123
  )
122
124
 
125
+ ${read.clocks?.length ? `// Only the time source is substituted; Unix/UnixMilli run in Go unchanged.
126
+ var gdpNow int64
127
+ func gdpTimeNow(_ func() time.Time) time.Time { return time.UnixMilli(gdpNow) }
128
+ ` : ''}
123
129
  type gdpStep struct {
124
130
  M string \`json:"m"\`
125
131
  A []json.RawMessage \`json:"a"\`
126
132
  }
127
133
  type gdpCmd struct {
128
134
  Op string \`json:"op"\`
135
+ Now int64 \`json:"now"\`
129
136
  ID int \`json:"id"\`
130
137
  State map[string]json.RawMessage \`json:"state"\`
131
138
  M string \`json:"m"\`
@@ -280,7 +287,7 @@ func GdpHarnessMain(in, out string) {
280
287
  case "get":
281
288
  res = map[string]any{"state": gdpGet(objs[c.ID])}
282
289
  case "call":
283
- ${read.answers?.length ? 'gdpAnswers = c.Answers\n\t\t\t' : ''}res = gdpRun(objs[c.ID], gdpStep{M: c.M, A: c.A})
290
+ ${read.clocks?.length ? 'gdpNow = c.Now\n\t\t\t' : ''}${read.answers?.length ? 'gdpAnswers = c.Answers\n\t\t\t' : ''}res = gdpRun(objs[c.ID], gdpStep{M: c.M, A: c.A})
284
291
  }
285
292
  b, _ := json.Marshal(res)
286
293
  wr.Write(b)
@@ -332,7 +339,18 @@ export function checkGo(dir, pkg, read, r, sorts, gopts) {
332
339
  }
333
340
  // (each answered call rewritten to the harness's answer in a copy of its file, the build told by an overlay)
334
341
  const over = {};
335
- for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, _i, t) => `gdpAnswer[${a.ty}](${JSON.stringify(a.key)}, ${t.slice(0, t.indexOf('('))}, ${t.slice(t.indexOf('(') + 1)}`)) {
342
+ const answers = read.answers ?? [], clocks = read.clocks ?? [];
343
+ // Go positions count UTF-8 bytes; explicit stub spans count JS code units.
344
+ const byteSpan = (p, end) => {
345
+ const m = /^(.*):(\d+):(\d+)$/.exec(p), lines = fs.readFileSync(`${dir}/${m[1]}`, 'utf8').split('\n');
346
+ const offset = (line, column) => lines.slice(0, line - 1).reduce((n, s) => n + s.length + 1, 0) + new TextDecoder('utf-8', { fatal: true }).decode(new TextEncoder().encode(lines[line - 1]).slice(0, column - 1)).length;
347
+ const e = end.split(':').map(Number);
348
+ return [offset(Number(m[2]), Number(m[3])), offset(e[0], e[1])];
349
+ };
350
+ const clockSites = clocks.map(c => ({ key: 'Go wall clock', at: [{ p: c.p, span: byteSpan(c.p, c.end) }] }));
351
+ // A Unicode clock prefix also moves any answer later on the same line.
352
+ const answerSites = !clocks.length ? answers : answers.map(a => ({ ...a, at: a.at?.map(s => s.span || !s.end ? s : { ...s, span: byteSpan(s.p, s.end) }) }));
353
+ for (const [f, t] of stubbed({ ...read, answers: [...answerSites, ...clockSites] }, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, i, t) => i >= answers.length ? `gdpTimeNow(${clocks[i - answers.length].callee})` : `gdpAnswer[${a.ty}](${JSON.stringify(a.key)}, ${t.slice(0, t.indexOf('('))}, ${t.slice(t.indexOf('(') + 1)}`)) {
336
354
  const o = node('node:path').resolve(dir, f);
337
355
  fs.writeFileSync(`${work}/${f}`, t);
338
356
  over[o] = over[node('node:fs').realpathSync(o)] = `${work}/${f}`;
@@ -481,6 +499,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
481
499
  return s;
482
500
  };
483
501
  let coverage;
502
+ let now = 0;
484
503
  const r0 = performance.now();
485
504
  const side = {
486
505
  // (a constructor's arguments, C++'s: the rule's parameters)
@@ -495,7 +514,7 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
495
514
  answers = Object.fromEntries(read.answers.map(a => { const x = v[a.inputs.name] ?? 0; if (a.fit && a.range && (Number(x) < a.range[0] || Number(x) > a.range[1]))
496
515
  throw new Outside(`${a.key} answers ${String(x)}, outside its type`); return [a.key, a.inputs.none && v[a.inputs.none] === true ? { none: true } : { in: x }]; }));
497
516
  }
498
- const res = ask({ op: 'call', id: self, m: e.call, a: args, ...(answers ? { answers } : {}) });
517
+ const res = ask({ op: 'call', id: self, m: e.call, now, a: args, ...(answers ? { answers } : {}) });
499
518
  if (res.frame)
500
519
  throw new Error(`the code changes ${res.frame}, a field the rule leaves out`);
501
520
  if (res.bad)
@@ -505,7 +524,8 @@ export function speak(work, bin, env, pkg, read, r, sorts, opts, count) {
505
524
  return { ok: true, value: typeof res.out === 'string' && /^-?\d+$/.test(res.out) && m.results?.[e.call] && m.state.find(v => v.name === m.results[e.call].name)?.sort.k === 'num' ? Number(res.out) : res.out };
506
525
  },
507
526
  args: (inputs, e) => e.args.map(a => argJson(a, inputs)),
508
- setNow: () => { },
527
+ setNow: n => { if (!Number.isSafeInteger(n))
528
+ throw new Outside('Go clock outside the exact integer range'); now = n; },
509
529
  coverage: () => (coverage ??= closeAndCount()),
510
530
  input: (v, x, rand) => { const y = rand(8) === 0 ? x : fit(x, v.name, rand); return typeof y === 'number' && y < 0 && sorts.get(v.name) === 'nat' ? -y : y; },
511
531
  drawSnap: rand => {
@@ -86,6 +86,7 @@ export type GX = {
86
86
  v: GX;
87
87
  }[];
88
88
  i?: GX;
89
+ end?: string;
89
90
  };
90
91
  export type GS = {
91
92
  s: string;
@@ -191,7 +192,13 @@ export type GoOptions = {
191
192
  answers?: Record<string, string>;
192
193
  skip?: string[];
193
194
  };
195
+ export type GoClock = {
196
+ p: string;
197
+ end: string;
198
+ callee: string;
199
+ };
194
200
  export type GoRead = {
201
+ clocks?: GoClock[];
195
202
  answers?: (Answer & {
196
203
  range?: [number, number];
197
204
  })[];
@@ -9,7 +9,8 @@
9
9
  //
10
10
  // The subset: a named struct of the package and the methods given (pointer or value receivers), the object starting
11
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
12
+ // bool, string, direct time.Now().UnixMilli()/Unix() projections (one millisecond request tick; the check replaces
13
+ // only Now, not the native projection), *big.Int (an unbounded integer, nil a state of its own), nested structs, maps from
13
14
  // integers or strings to integers, booleans or structs of them, and slices of integers or booleans as lists; locals,
14
15
  // assignments (=, :=, op=, ++, --, tuples), if, switch (with a tag or without, fallthrough, break), early returns,
15
16
  // calls of the package's functions and methods (inlined), pointers to the state's objects (an interior pointer &x.f
@@ -47,6 +48,7 @@ class Go {
47
48
  opts;
48
49
  g;
49
50
  leaves = [];
51
+ clocks = new Map();
50
52
  funcs = {};
51
53
  constructor(pkg, opts, inf) {
52
54
  this.pkg = pkg;
@@ -283,6 +285,17 @@ class Go {
283
285
  if (f.e === 'sel' && f.k === 'qual')
284
286
  return this.std(x);
285
287
  if (f.e === 'sel' && f.k === 'method') {
288
+ // Keep Time opaque: only a direct Now projection is a scalar. Preserve
289
+ // the native projection in the check; substitute just its clock source.
290
+ const now = f.x;
291
+ if ((!this.pkg.lang || this.pkg.lang === 'go') && f.mpkg === 'time' && (f.n === 'Unix' || f.n === 'UnixMilli') && !a.length &&
292
+ now?.e === 'call' && !now.a?.length && now.f?.e === 'sel' && now.f.k === 'qual' && now.f.pkg === 'time' && now.f.n === 'Now') {
293
+ if (!now.end)
294
+ return this.no(x, 'time.Now(): the reader did not provide a clock source span');
295
+ this.clocks.set(now.p, { p: now.p, end: now.end, callee: now.f.text });
296
+ const clock = { e: 'clock', ...at };
297
+ return f.n === 'UnixMilli' ? clock : { e: 'bin', ...at, op: '//', x: clock, y: { e: 'int', p: x.p, v: 1000 } };
298
+ }
286
299
  // A method promoted from an embedded field: its receiver is that field (through the embedded fields on the way).
287
300
  let rt = this.T(f.x.t), base = rt.k === 'ptr' ? rt.elem : f.x.t, emb;
288
301
  if ((f.path ?? []).length > 1) {
@@ -868,6 +881,18 @@ function readGo1(pkg, o, go) {
868
881
  if (answers.length)
869
882
  for (const e of events)
870
883
  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 }]) });
884
+ // An answered outer call must not swallow a clock substitution or reuse its offsets.
885
+ for (const clock of go.clocks.values())
886
+ for (const answer of answers)
887
+ for (const site of answer.at ?? []) {
888
+ const c = /^(.*):(\d+):(\d+)$/.exec(clock.p), a = /^(.*):(\d+):(\d+)$/.exec(site.p);
889
+ if (!c || !a || c[1] !== a[1] || !site.end)
890
+ continue;
891
+ const cs = c.slice(2).map(Number), as = a.slice(2).map(Number), ce = clock.end.split(':').map(Number), ae = site.end.split(':').map(Number);
892
+ const before = (x, y) => x[0] < y[0] || (x[0] === y[0] && x[1] < y[1]);
893
+ if (before(cs, ae) && before(as, ce))
894
+ refuse(clock.p, 'a clock read inside an answered call (overlapping source substitutions)');
895
+ }
871
896
  // (and the harness's: it makes the struct with the fields read)
872
897
  for (const mt of methods)
873
898
  mt.params = mt.params.map(pa => ({ ...pa, arg: recOf(pa.arg) }));
@@ -977,6 +1002,8 @@ function readGo1(pkg, o, go) {
977
1002
  for (const d of maps)
978
1003
  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())))`);
979
1004
  const layout = { k: 'rec', fields: state.filter(v => !outputs.includes(v.name)).map(v => [v.name, { k: 'scalar', name: v.name }]) };
1005
+ if (g.now)
1006
+ g.notes.add('Go wall clock: UnixMilli and Unix projections use one millisecond request tick; multiple reads assume the step stays within that tick. General time.Time values and finer projections remain outside the subset.');
980
1007
  const model = {
981
1008
  name: opts.entry, shape: 'class', file: pkg.files[0]?.name ?? 'go', entry: opts.entry,
982
1009
  params: cparams, inputs: g.inputs, state, maps, init, writes, mapWrites, outputs, ...(lists.length ? { lists, listWrites } : {}),
@@ -985,7 +1012,7 @@ function readGo1(pkg, o, go) {
985
1012
  // Unsigned inputs are naturals (the input's kind); a state variable's sort is the printer's to decide (a natural where
986
1013
  // every write is proven one: a wrap by cases may not be, though it stays within the type, which its law says).
987
1014
  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);
988
- return { ...(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 } : {}) };
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 } : {}) };
989
1016
  }
990
1017
  function termOf(v, at) {
991
1018
  // (none: a path that ends without the value, which a reader of malformed source may join in)
@@ -93,6 +93,10 @@ export type Term = {
93
93
  export type Arg = {
94
94
  k: 'input';
95
95
  name: string;
96
+ } | {
97
+ k: 'maybe-bool';
98
+ name: string;
99
+ missing: string;
96
100
  } | {
97
101
  k: 'lit';
98
102
  value: string;
@@ -150,6 +154,9 @@ export type Model = {
150
154
  shape: 'reducer' | 'functions' | 'class';
151
155
  file: string;
152
156
  entry: string;
157
+ standalone?: true;
158
+ standaloneDomains?: Record<string, number[]>;
159
+ standaloneBindings?: string[];
153
160
  params: Var[];
154
161
  inputs: Var[];
155
162
  state: Var[];
@@ -398,12 +405,13 @@ export type Setup = {
398
405
  };
399
406
  export declare class Exec {
400
407
  readonly s: Setup;
408
+ private readonly standalone;
401
409
  throws: {
402
410
  pc: B[];
403
411
  }[];
404
412
  private depth;
405
413
  private ids;
406
- constructor(s: Setup);
414
+ constructor(s: Setup, standalone?: boolean);
407
415
  fresh(base: string): string;
408
416
  newVar(base: string, sort: Sort, role: Var['role'], note?: string): Var;
409
417
  id(prefix: string): string;
@@ -208,11 +208,13 @@ export function shapeOf(t, checker, at, inner) {
208
208
  const keySort = (s, at) => (s.k === 'num' ? 'num' : s.k === 'str' || s.k === 'choice' ? 'str' : refuse(at, 'a map keyed by other than numbers or strings'));
209
209
  export class Exec {
210
210
  s;
211
+ standalone;
211
212
  throws = [];
212
213
  depth = 0;
213
214
  ids = 0;
214
- constructor(s) {
215
+ constructor(s, standalone = false) {
215
216
  this.s = s;
217
+ this.standalone = standalone;
216
218
  }
217
219
  fresh(base) {
218
220
  const clean = base.replace(/^#/, '').replace(/[^A-Za-z0-9_]/g, '_').replace(/^(\d)/, '_$1') || 'x';
@@ -526,13 +528,14 @@ export class Exec {
526
528
  // where it is there.
527
529
  narrow(e, pt, pe) {
528
530
  const strip = (x) => (ts.isParenthesizedExpression(x) ? strip(x.expression) : x);
529
- let x = strip(e), present = true;
531
+ let x = strip(e), present = true, absenceTest = false;
530
532
  if (ts.isPrefixUnaryExpression(x) && x.operator === ts.SyntaxKind.ExclamationToken) {
531
533
  x = strip(x.operand);
532
534
  present = false;
533
535
  }
534
536
  else if (ts.isBinaryExpression(x) && (x.right.kind === ts.SyntaxKind.UndefinedKeyword || (ts.isIdentifier(x.right) && x.right.text === 'undefined') || x.right.kind === ts.SyntaxKind.NullKeyword)) {
535
537
  const op = x.operatorToken.kind;
538
+ absenceTest = true;
536
539
  if (op === ts.SyntaxKind.EqualsEqualsEqualsToken || op === ts.SyntaxKind.EqualsEqualsToken)
537
540
  present = false;
538
541
  else if (op !== ts.SyntaxKind.ExclamationEqualsEqualsToken && op !== ts.SyntaxKind.ExclamationEqualsToken)
@@ -545,6 +548,10 @@ export class Exec {
545
548
  if (v?.t !== 'opt')
546
549
  return [pt, pe];
547
550
  const set = (p, there) => ({ ...p, locals: new Map(p.locals).set(x.text, there ? v.v : { t: 'undef' }) });
551
+ // A falsy optional scalar can be present (false or 0), not just absent.
552
+ // Preserve the opt value on that arm; only an explicit absence comparison narrows both arms.
553
+ if (this.standalone && !absenceTest)
554
+ return present ? [set(pt, true), pe] : [pt, set(pe, true)];
548
555
  return present ? [set(pt, true), set(pe, false)] : [set(pt, false), set(pe, true)];
549
556
  }
550
557
  bind(name, v, p) {
@@ -129,7 +129,7 @@ function toJson(t, x) {
129
129
  return `json!(match ${x} { ${t.values.map(v => `${t.enum}::${v} => ${JSON.stringify(v)}`).join(', ')} })`;
130
130
  return 'json!(null)';
131
131
  }
132
- function harnessCode(mod, read, cls) {
132
+ function harnessCode(mod, read, cls, name) {
133
133
  const leaves = read.leaves.filter(l => l.kind !== 'frame' && l.kind !== 'map');
134
134
  if (read.leaves.some(l => l.kind === 'map'))
135
135
  throw new Refusal(mod.file, 'a map in the state: the Rust harness reads none yet');
@@ -162,17 +162,15 @@ function harnessCode(mod, read, cls) {
162
162
  const f = cls ? fn(cls.methods[m]) : fn(m);
163
163
  const ps = f.params.filter(p => !p.self);
164
164
  const args = ps.map((p, i) => { const rs = p.rs ?? ''; const v = fromJson(p.t, `(&a[${i}][1])`, mod); return /^&\s*mut/.test(rs) ? `&mut ${v}` : rs.startsWith('&') ? `&${v}` : v; });
165
- const target = cls ? `o.${m}(${args.join(', ')})` : `${m}(${args.join(', ')})`;
165
+ const target = cls ? `o.${m}(${args.join(', ')})` : `super::${m}(${args.join(', ')})`;
166
166
  const ret = f.ret;
167
167
  const out = ret.k === 'res' ? `match r { Ok(v) => { let _ = &v; Ok(${ret.of.k === 'none' ? 'json!(null)' : tagged(ret.of, 'v')}) } Err(_) => Err("an Err".to_string()) }` : ret.k === 'opt' ? `Ok(match r { Some(v) => ${tagged(ret.of, 'v')}, None => json!(null) })` : ret.k === 'none' ? 'Ok(json!(null))' : `Ok(${tagged(ret, 'r')})`;
168
168
  return `${JSON.stringify(m)} => { let r = ${target}; ${out} }`;
169
169
  });
170
- const clsMod = cls?.module ?? 'crate';
171
- void clsMod;
172
170
  return `
173
171
  #[cfg(test)]
174
172
  #[allow(unused, clippy::all)]
175
- pub(crate) mod __gdp_harness {
173
+ pub(crate) mod ${name} {
176
174
  use super::*;
177
175
  use serde_json::{json, Value};
178
176
  use std::io::{BufRead, Write};
@@ -260,25 +258,59 @@ function harnessFor(dir, mod, read, opts) {
260
258
  if (!/\[dev-dependencies(\.serde_json)?\][^[]*serde_json/s.test(toml))
261
259
  toml += '\n[dev-dependencies.serde_json]\nversion = "1"\n';
262
260
  fs.writeFileSync(`${work}/Cargo.toml`, toml);
263
- const file = cls ? String(cls.file) : String(mod.fmods ? mod.path.slice(mod.root.length + 1) : mod.path.slice(mod.root.length + 1));
261
+ const file = cls ? String(cls.file) : mod.path.slice(mod.root.length + 1);
264
262
  const modPath = cls?.module ?? mod.fmods?.[Object.keys(read.args)[0]] ?? 'crate';
263
+ if (!cls && Object.keys(read.args).some(id => mod.fmods?.[id] !== modPath || mod.funcs[id]?.span?.[0] !== file)) {
264
+ throw new Refusal(mod.file, 'Rust native replay requires function entries in one known file/module');
265
+ }
265
266
  // The clock: Instant::now() read through the harness (the request's time), the code's own calls rewritten first.
266
267
  const lib = fs.existsSync(`${work}/src/lib.rs`) ? 'src/lib.rs' : 'src/main.rs';
267
268
  const walk = (d) => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => { const x = e; return x.isDirectory() ? walk(`${d}/${x.name}`) : x.name.endsWith('.rs') ? [`${d}/${x.name}`] : []; });
269
+ // Allocate bridges once on the unmodified Rust copy, before the chosen names
270
+ // become references in rewritten calls. Placement is still queried afterwards.
271
+ const bridges = JSON.parse(cp.execFileSync(rsReader(opts.cargo), [JSON.stringify({ root: work, harness_bridges: { file: lib } })], { encoding: 'utf8', maxBuffer: 1 << 20, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() }));
272
+ if (bridges.error)
273
+ throw new Refusal(mod.file, bridges.error);
274
+ const { now: nowName, answer: answerName } = bridges;
275
+ if (typeof nowName !== 'string' || !/^__gdp_now(?:_[1-9][0-9]*)?$/.test(nowName) ||
276
+ typeof answerName !== 'string' || !/^__gdp_answer(?:_[1-9][0-9]*)?$/.test(answerName)) {
277
+ throw new Refusal(mod.file, 'Rust native replay has no validated root bridge names');
278
+ }
268
279
  // (each answered call rewritten to the harness's answer, from the crate's own text, before the clock's; the call
269
280
  // kept in a branch never taken, so the answer is of the type the call is, which a binding needn't write)
270
- for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, _, call) => `(if false { ${call} } else { crate::__gdp_answer(${JSON.stringify(a.key)}) })`))
281
+ for (const [f, t] of stubbed(read, f => fs.readFileSync(`${dir}/${f}`, 'utf8'), (a, _, call) => `(if false { ${call} } else { crate::${answerName}(${JSON.stringify(a.key)}) })`))
271
282
  fs.writeFileSync(`${work}/${f}`, t);
272
283
  for (const f of walk(`${work}/src`)) {
273
284
  const s = fs.readFileSync(f, 'utf8');
274
- const t = s.replace(/\b(?:std::time::)?Instant::now\(\)/g, 'crate::__gdp_now()');
285
+ const t = s.replace(/\b(?:std::time::)?Instant::now\(\)/g, `crate::${nowName}()`);
275
286
  if (t !== s)
276
287
  fs.writeFileSync(f, t);
277
288
  }
278
- // (the lines of the code itself in the files the harness is appended to: an error past them is the harness's)
289
+ // Query the parser after rewrites: original offsets are stale after stubs
290
+ // or clock substitutions. Append for file modules; insert before the exact
291
+ // closing brace for inline modules, keeping private-field access in scope.
279
292
  const own = new Map([file, lib].map(f => [f, fs.readFileSync(`${work}/${f}`, 'utf8').split('\n').length]));
280
- fs.writeFileSync(`${work}/${file}`, fs.readFileSync(`${work}/${file}`, 'utf8') + harnessCode(mod, read, cls));
281
- fs.writeFileSync(`${work}/${lib}`, `${fs.readFileSync(`${work}/${lib}`, 'utf8')}\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn __gdp_now() -> std::time::Instant { ${modPath}::__gdp_harness::now() }\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn __gdp_answer<T: ${modPath}::__gdp_harness::GdpAns>(k: &str) -> T { ${modPath}::__gdp_harness::answer(k) }\n`);
293
+ const site = JSON.parse(cp.execFileSync(rsReader(opts.cargo), [JSON.stringify({ root: work, harness_scope: { file, module: modPath } })], { encoding: 'utf8', maxBuffer: 1 << 20, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() }));
294
+ if (site.error || site.inline_end === undefined)
295
+ throw new Refusal(mod.file, site.error ?? 'Rust native replay has no placement metadata');
296
+ const harnessName = site.harness_name;
297
+ if (typeof harnessName !== 'string' || !/^__gdp_harness(?:_[1-9][0-9]*)?$/.test(harnessName)) {
298
+ throw new Refusal(mod.file, 'Rust native replay has no validated helper module name');
299
+ }
300
+ const source = fs.readFileSync(`${work}/${file}`, 'utf8');
301
+ let prefix = source, suffix = '';
302
+ if (site.inline_end !== null) {
303
+ const bytes = new TextEncoder().encode(source), at = site.inline_end;
304
+ if (!Number.isSafeInteger(at) || at < 0 || at >= bytes.length || bytes[at] !== 125 || source.startsWith('\uFEFF') || /^#![^[]/.test(source)) {
305
+ throw new Refusal(mod.file, 'Rust native replay has an unsupported inline-module byte position');
306
+ }
307
+ const decoder = new TextDecoder('utf-8', { fatal: true });
308
+ prefix = decoder.decode(bytes.slice(0, at));
309
+ suffix = decoder.decode(bytes.slice(at));
310
+ }
311
+ const code = harnessCode(mod, read, cls, harnessName), insertedAt = prefix.split('\n').length, addedLines = code.split('\n').length - 1;
312
+ fs.writeFileSync(`${work}/${file}`, prefix + code + suffix);
313
+ fs.writeFileSync(`${work}/${lib}`, `${fs.readFileSync(`${work}/${lib}`, 'utf8')}\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn ${nowName}() -> std::time::Instant { ${modPath}::${harnessName}::now() }\n#[cfg(test)]\n#[allow(unused)]\npub(crate) fn ${answerName}<T: ${modPath}::${harnessName}::GdpAns>(k: &str) -> T { ${modPath}::${harnessName}::answer(k) }\n`);
282
314
  const target = `${os.tmpdir()}/gdp-rscheck-target`;
283
315
  const built = buildCheck('cargo', () => cp.execFileSync(opts.cargo ?? 'cargo', ['test', '--lib', '--no-run', '--message-format=json', '--target-dir', target], { cwd: work, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28, env: { ...proc?.env }, timeout: compileLimit(), killSignal: 'SIGKILL' }), e => String(e.stdout ?? '').split('\n').flatMap(l => { try {
284
316
  const j = JSON.parse(l);
@@ -286,8 +318,20 @@ function harnessFor(dir, mod, read, opts) {
286
318
  }
287
319
  catch {
288
320
  return [];
289
- } }), l => { const m = /--> ([^\s:]+\.rs):(\d+):\d+/.exec(l); if (!m)
290
- return false; const n = own.get(m[1]); return n === undefined || Number(m[2]) <= n; });
321
+ } }), l => {
322
+ const m = /--> ([^\s:]+\.rs):(\d+):\d+/.exec(l);
323
+ if (!m)
324
+ return false;
325
+ let line = Number(m[2]);
326
+ if (m[1] === file) {
327
+ if (line > insertedAt && line < insertedAt + addedLines)
328
+ return false;
329
+ if (line >= insertedAt + addedLines)
330
+ line -= addedLines;
331
+ }
332
+ const n = own.get(m[1]);
333
+ return n === undefined || line <= n;
334
+ });
291
335
  if (!('ok' in built))
292
336
  return { cmd: 'false', args: [], hello: {}, error: built.why, kind: built.kind };
293
337
  const msgs = built.ok;
@@ -302,7 +346,7 @@ function harnessFor(dir, mod, read, opts) {
302
346
  return { cmd: 'false', args: [], hello: {}, error: 'the test build gave no executable', kind: 'harness' };
303
347
  read.model.notes.push('Rust: the code is checked in a debug build (overflow checks on); its branch arms are not counted (no instrumentation yet)');
304
348
  read.arms.length = 0;
305
- const test = `${modPath === 'crate' ? '' : `${modPath.replace(/^crate::/, '')}::`}__gdp_harness::__gdp_harness_main`;
349
+ const test = `${modPath === 'crate' ? '' : `${modPath.replace(/^crate::/, '')}::`}${harnessName}::__gdp_harness_main`;
306
350
  return { cmd: exe, args: [test, '--exact', '--nocapture', '--test-threads=1'], hello: {} };
307
351
  }
308
352
  catch (e) {
@@ -10,6 +10,7 @@ export type ReadOptions = {
10
10
  init?: unknown;
11
11
  };
12
12
  export declare function setupOf(code: string, file: string, typed?: Record<string, Sort>, files?: Record<string, string>): Setup;
13
+ export declare function readStandalone(code: string, file: string, opts: ReadOptions): Model;
13
14
  export declare function readFunctions(code: string, file: string, opts: ReadOptions): Model;
14
15
  export declare function readClass(code: string, file: string, opts: ReadOptions): Model;
15
16
  export type Result = {