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.
@@ -4,6 +4,7 @@
4
4
  // symbolically (core/extract-read.ts) into a Model: the state's variables, where each sits in the code's own values,
5
5
  // the step's writes, what the code refuses (its throws) and how a request is made of the code.
6
6
  import ts from 'typescript';
7
+ import { standaloneClosure } from "./extract-standalone.js";
7
8
  import * as I from "./extract-ir.js";
8
9
  import { Exec, Retype, memberName, mergeOps, normalize, program, refuse, shapeOf, unparen } from "./extract-read.js";
9
10
  const at0 = (sf) => sf.statements[0] ?? sf;
@@ -432,6 +433,87 @@ function argOf(ex, param, prefix, body) {
432
433
  return { v, events, heap };
433
434
  }
434
435
  const sortOf = (sh, lits) => (sh.k === 'str' && lits.length ? { k: 'choice', values: [...lits, OTHER] } : sh.k === 'num' || sh.k === 'bool' || sh.k === 'choice' || sh.k === 'str' ? sh : (() => { throw new Error('a compound sort'); })());
436
+ // Experimental opt-in: a pure, standalone scalar function. No third-party call or state is synthesized.
437
+ export function readStandalone(code, file, opts) {
438
+ const s = setupOf(code, file, opts.typed, opts.files), fn = findFunction(s.sf, opts.entry);
439
+ if (opts.entry === 'undefined' || opts.entry === '__cov')
440
+ refuse(fn, 'standalone: reserved entry name');
441
+ const bindings = standaloneClosure(s, fn);
442
+ s.spans = [[fn.getStart(), fn.end]];
443
+ const ex = new Exec(s, true), heap = new Map(), args = [];
444
+ const domains = {}, limits = [];
445
+ let p = { pc: [], locals: new Map(), heap, wrote: [], nows: 0 };
446
+ for (const param of fn.parameters) {
447
+ const name = param.name.text, t = s.checker.getTypeAtLocation(param), parts = t.isUnion() ? t.types : [t];
448
+ const missing = parts.filter(x => !!(x.flags & ts.TypeFlags.Undefined)), rest = parts.filter(x => !(x.flags & ts.TypeFlags.Undefined));
449
+ if (parts.some(x => !!(x.flags & ts.TypeFlags.Null)))
450
+ refuse(param, 'standalone: null input is outside the subset');
451
+ const bool = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.BooleanLike));
452
+ const num = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.NumberLike));
453
+ if ((!bool && !num) || (missing.length && !bool))
454
+ refuse(param, 'standalone: only numeric, boolean, or boolean | undefined inputs');
455
+ const x = ex.newVar(name, { k: bool ? 'bool' : 'num' }, 'input');
456
+ let v = Exec.valueOf(x);
457
+ if (num && rest.every(t => !!(t.flags & ts.TypeFlags.NumberLiteral))) {
458
+ const values = [...new Set(rest.map(t => t.value))].sort((a, b) => a - b);
459
+ if (!values.every(Number.isSafeInteger) || values.length > 64)
460
+ refuse(param, 'standalone: numeric literal domain must contain at most 64 safe integers');
461
+ domains[x.name] = values;
462
+ limits.push(I.or(...values.map(n => I.cmp('=', v.e, I.num(n)))));
463
+ }
464
+ if (missing.length) {
465
+ const m = ex.newVar(`${name}_missing`, { k: 'bool' }, 'input');
466
+ v = { t: 'opt', has: I.not(Exec.valueOf(m).e), v };
467
+ args.push({ k: 'maybe-bool', name: x.name, missing: m.name });
468
+ }
469
+ else
470
+ args.push({ k: 'input', name: x.name });
471
+ p = ex.bind(param.name, v, p);
472
+ }
473
+ const sig = s.checker.getSignatureFromDeclaration(fn), rt = s.checker.getReturnTypeOfSignature(sig), parts = rt.isUnion() ? rt.types : [rt];
474
+ if (parts.some(x => !!(x.flags & ts.TypeFlags.Null)))
475
+ refuse(fn, 'standalone: null result is outside the subset');
476
+ const rest = parts.filter(x => !(x.flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)));
477
+ const bool = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.BooleanLike));
478
+ const num = rest.length > 0 && rest.every(x => !!(x.flags & ts.TypeFlags.NumberLike));
479
+ if (!bool && !num)
480
+ refuse(fn, 'standalone: result must be numeric or boolean, optionally undefined');
481
+ const val = ex.newVar(`${opts.entry}_result`, { k: bool ? 'bool' : 'num' }, 'state');
482
+ const absent = ex.newVar(`${opts.entry}_result_missing`, { k: 'bool' }, 'state');
483
+ let outs;
484
+ if (ts.isBlock(fn.body)) {
485
+ const flow = ex.block(fn.body.statements, p);
486
+ outs = [...flow.rets, ...(flow.live ? [[flow.live, { t: 'undef' }]] : [])];
487
+ }
488
+ else {
489
+ const [v, q] = ex.ev(fn.body, p);
490
+ outs = [[q, v]];
491
+ }
492
+ outs = outs.filter(([q]) => ex.feasible(q));
493
+ if (!outs.length)
494
+ refuse(fn, 'standalone: no reachable return');
495
+ const final = joinAll(ex, outs.map(([q, v]) => {
496
+ if ((v.t === 'undef' && v.null) || (v.t === 'opt' && v.null))
497
+ refuse(fn, 'standalone: null result');
498
+ const has = v.t === 'undef' ? I.F : v.t === 'opt' ? v.has : I.T;
499
+ const inner = v.t === 'undef' ? undefined : v.t === 'opt' ? v.v : v;
500
+ const there = inner ? outValue(ex, inner, val, { ...q, pc: [...q.pc, has] }, fn) : Exec.defaultOf(val.sort);
501
+ const sv = { leaves: new Map(), maps: new Map() };
502
+ sv.leaves.set(val.name, ex.mergeScalar(has, there, Exec.defaultOf(val.sort), fn));
503
+ sv.leaves.set(absent.name, { t: 'bool', e: I.not(has) });
504
+ return [q, sv];
505
+ }), fn);
506
+ const model = finish(s, { name: opts.entry, shape: 'functions', file, entry: opts.entry,
507
+ layout: { k: 'rec', fields: [] }, init: { [val.name]: termOf(Exec.defaultOf(val.sort)), [absent.name]: termOf(Exec.defaultOf(absent.sort)) },
508
+ final, refuse: I.or(refusalOf(ex), I.not(I.and(...limits))), pre: I.T, events: [{ select: {}, call: opts.entry, args, names: fn.parameters.map(x => x.name.getText()) }], outputs: [val.name, absent.name] });
509
+ model.standalone = true;
510
+ model.kind = 'a standalone scalar function';
511
+ model.standaloneDomains = domains;
512
+ model.standaloneBindings = bindings;
513
+ model.notes.push('standalone scalar function: separate arguments and optional result; numbers are safe integers, not arbitrary JavaScript numbers', `closed reachable bindings: ${bindings.join(', ')}`, ...Object.entries(domains).map(([n, xs]) => `declared numeric input domain ${n}: ${xs.join(', ')}; other values are outside the claim`));
514
+ model.results = { [opts.entry]: { k: 'maybe', name: val.name, missing: absent.name, null: false } };
515
+ return model;
516
+ }
435
517
  export function readFunctions(code, file, opts) {
436
518
  // Read again while an untyped input turns out to be of another sort than a number.
437
519
  for (let typed = { ...opts.typed };;) {
@@ -0,0 +1,3 @@
1
+ import ts from 'typescript';
2
+ import { type Setup } from './extract-read.js';
3
+ export declare function standaloneClosure(s: Setup, entry: ts.FunctionLikeDeclaration): string[];
@@ -0,0 +1,221 @@
1
+ // The opt-in scalar reader's closed binding boundary. No module code is run here.
2
+ import ts from 'typescript';
3
+ import { refuse, unparen } from "./extract-read.js";
4
+ const reserved = (name) => ['undefined', '__cov', '$join', 'this'].includes(name) || name.startsWith('__gdp');
5
+ export function standaloneClosure(s, entry) {
6
+ const bindings = new Map(), active = new Set(), done = new Set(), reached = new Set();
7
+ const symbol = (id) => s.checker.getSymbolAtLocation(id) ?? refuse(id, 'standalone: unresolved binding');
8
+ const add = (id, decl, order) => {
9
+ if (reserved(id.text))
10
+ refuse(id, ts.isFunctionDeclaration(decl) ? 'standalone: reserved function name' : 'standalone: reserved module binding');
11
+ const sym = symbol(id);
12
+ if (bindings.has(sym))
13
+ refuse(id, 'standalone: duplicate module binding');
14
+ bindings.set(sym, { decl, order });
15
+ };
16
+ // Declarations of functions and types do not run their bodies on module load. Only
17
+ // inert const initializers may accompany them. Value imports and re-exports can run
18
+ // another module and are deliberately not this frontend's boundary.
19
+ for (const [order, st] of s.sf.statements.entries()) {
20
+ if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isEmptyStatement(st))
21
+ continue;
22
+ if (ts.isImportDeclaration(st)) {
23
+ const c = st.importClause;
24
+ if (c?.isTypeOnly || (c && !c.name && c.namedBindings && ts.isNamedImports(c.namedBindings) && c.namedBindings.elements.length > 0 && c.namedBindings.elements.every(x => x.isTypeOnly)))
25
+ continue;
26
+ refuse(st, 'standalone: only erased type imports are supported');
27
+ }
28
+ if (ts.isFunctionDeclaration(st) && st.name) {
29
+ add(st.name, st, order);
30
+ continue;
31
+ }
32
+ if (ts.isFunctionDeclaration(st) && st === entry)
33
+ continue;
34
+ if (ts.isVariableStatement(st) && st.declarationList.flags & ts.NodeFlags.Const) {
35
+ for (const d of st.declarationList.declarations) {
36
+ if (!ts.isIdentifier(d.name) || !d.initializer)
37
+ refuse(d, 'standalone: module constants need a simple binding and initializer');
38
+ add(d.name, d, order);
39
+ }
40
+ continue;
41
+ }
42
+ refuse(st, 'standalone: executable module statement or unsupported declaration');
43
+ }
44
+ const functionOf = (b) => {
45
+ if (ts.isFunctionDeclaration(b.decl))
46
+ return b.decl;
47
+ const e = b.decl.initializer && unparen(b.decl.initializer);
48
+ return e && (ts.isArrowFunction(e) || ts.isFunctionExpression(e)) ? e : undefined;
49
+ };
50
+ const inert = (raw, before) => {
51
+ const e = unparen(raw);
52
+ if (ts.isAsExpression(e) || ts.isTypeAssertionExpression(e) || ts.isSatisfiesExpression(e)) {
53
+ inert(e.expression, before);
54
+ return;
55
+ }
56
+ if (ts.isNumericLiteral(e)) {
57
+ if (!Number.isSafeInteger(Number(e.text)))
58
+ refuse(e, 'standalone: constants must be safe integers');
59
+ return;
60
+ }
61
+ if (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e) || [ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.NullKeyword].includes(e.kind))
62
+ return;
63
+ if (ts.isIdentifier(e)) {
64
+ if (e.text === 'undefined' && !s.checker.getSymbolAtLocation(e)?.valueDeclaration)
65
+ return;
66
+ const b = bindings.get(symbol(e));
67
+ if (!b || b.order >= before.order || functionOf(b))
68
+ refuse(e, 'standalone: constant initializer must reference an earlier inert constant');
69
+ return;
70
+ }
71
+ if (ts.isArrayLiteralExpression(e)) {
72
+ for (const x of e.elements) {
73
+ if (ts.isSpreadElement(x) || ts.isOmittedExpression(x))
74
+ refuse(x, 'standalone: array initializer spread or hole');
75
+ inert(x, before);
76
+ }
77
+ ;
78
+ return;
79
+ }
80
+ if (ts.isPrefixUnaryExpression(e) && [ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.ExclamationToken].includes(e.operator)) {
81
+ inert(e.operand, before);
82
+ return;
83
+ }
84
+ refuse(e, 'standalone: module initializer is not inert');
85
+ };
86
+ for (const b of bindings.values())
87
+ if (ts.isVariableDeclaration(b.decl) && !functionOf(b))
88
+ inert(b.decl.initializer, b);
89
+ const constant = (b, at) => {
90
+ if (active.has(b.decl))
91
+ refuse(at, 'standalone: recursive constant');
92
+ if (done.has(b.decl))
93
+ return;
94
+ if (!ts.isVariableDeclaration(b.decl))
95
+ refuse(at, 'standalone: function used as a value');
96
+ active.add(b.decl);
97
+ expression(b.decl.initializer, new Set());
98
+ active.delete(b.decl);
99
+ done.add(b.decl);
100
+ reached.add(b.decl.name.getText());
101
+ };
102
+ const expression = (raw, locals) => {
103
+ const e = unparen(raw);
104
+ if (ts.isAsExpression(e) || ts.isTypeAssertionExpression(e) || ts.isSatisfiesExpression(e)) {
105
+ expression(e.expression, locals);
106
+ return;
107
+ }
108
+ if (ts.isNumericLiteral(e) || e.kind === ts.SyntaxKind.TrueKeyword || e.kind === ts.SyntaxKind.FalseKeyword)
109
+ return;
110
+ if (ts.isIdentifier(e)) {
111
+ const sym = s.checker.getSymbolAtLocation(e);
112
+ if (e.text === 'undefined' && !sym?.valueDeclaration)
113
+ return;
114
+ if (sym && locals.has(sym))
115
+ return;
116
+ const b = sym && bindings.get(sym);
117
+ if (!b)
118
+ refuse(e, 'standalone: non-input identifier or captured binding');
119
+ if (functionOf(b))
120
+ refuse(e, 'standalone: non-input identifier (function used as a value)');
121
+ constant(b, e);
122
+ return;
123
+ }
124
+ if (ts.isCallExpression(e)) {
125
+ if (e.questionDotToken || !ts.isIdentifier(e.expression))
126
+ refuse(e, 'standalone: only direct closed helper calls are supported');
127
+ const b = bindings.get(symbol(e.expression)), fn = b && functionOf(b);
128
+ if (!fn || locals.has(symbol(e.expression)))
129
+ refuse(e, 'standalone: call is not a closed helper');
130
+ if (e.arguments.length !== fn.parameters.length)
131
+ refuse(e, 'standalone: helper arguments must match its parameters');
132
+ for (const x of e.arguments)
133
+ expression(x, locals);
134
+ functionBody(fn);
135
+ return;
136
+ }
137
+ if (ts.isPrefixUnaryExpression(e) && [ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.ExclamationToken].includes(e.operator)) {
138
+ expression(e.operand, locals);
139
+ return;
140
+ }
141
+ if (ts.isBinaryExpression(e) && [ts.SyntaxKind.PlusToken, ts.SyntaxKind.MinusToken, ts.SyntaxKind.AsteriskToken, ts.SyntaxKind.PercentToken, ts.SyntaxKind.SlashToken, ts.SyntaxKind.LessThanToken, ts.SyntaxKind.LessThanEqualsToken, ts.SyntaxKind.GreaterThanToken, ts.SyntaxKind.GreaterThanEqualsToken, ts.SyntaxKind.EqualsEqualsToken, ts.SyntaxKind.EqualsEqualsEqualsToken, ts.SyntaxKind.ExclamationEqualsToken, ts.SyntaxKind.ExclamationEqualsEqualsToken, ts.SyntaxKind.AmpersandAmpersandToken, ts.SyntaxKind.BarBarToken, ts.SyntaxKind.QuestionQuestionToken].includes(e.operatorToken.kind)) {
142
+ expression(e.left, locals);
143
+ expression(e.right, locals);
144
+ return;
145
+ }
146
+ if (ts.isConditionalExpression(e)) {
147
+ expression(e.condition, locals);
148
+ expression(e.whenTrue, locals);
149
+ expression(e.whenFalse, locals);
150
+ return;
151
+ }
152
+ if (ts.isNonNullExpression(e)) {
153
+ expression(e.expression, locals);
154
+ return;
155
+ }
156
+ refuse(e, 'standalone: effects or unsupported expression');
157
+ };
158
+ const statement = (st, locals) => {
159
+ if (ts.isBlock(st)) {
160
+ st.statements.forEach(x => statement(x, locals));
161
+ return;
162
+ }
163
+ if (ts.isReturnStatement(st)) {
164
+ if (st.expression)
165
+ expression(st.expression, locals);
166
+ return;
167
+ }
168
+ if (ts.isIfStatement(st)) {
169
+ expression(st.expression, locals);
170
+ statement(st.thenStatement, locals);
171
+ if (st.elseStatement)
172
+ statement(st.elseStatement, locals);
173
+ return;
174
+ }
175
+ if (ts.isSwitchStatement(st)) {
176
+ expression(st.expression, locals);
177
+ for (const c of st.caseBlock.clauses) {
178
+ if (ts.isCaseClause(c))
179
+ expression(c.expression, locals);
180
+ c.statements.forEach(x => statement(x, locals));
181
+ }
182
+ return;
183
+ }
184
+ if ((ts.isBreakStatement(st) && !st.label) || ts.isEmptyStatement(st))
185
+ return;
186
+ refuse(st, 'standalone: effects or unsupported statement');
187
+ };
188
+ const functionBody = (fn) => {
189
+ if (active.has(fn))
190
+ refuse(fn, 'standalone: recursion is outside the subset');
191
+ if (done.has(fn))
192
+ return;
193
+ if (!fn.body || fn.asteriskToken || fn.modifiers?.some(m => m.kind === ts.SyntaxKind.AsyncKeyword))
194
+ refuse(fn, 'standalone: async, generator or missing body');
195
+ if ((ts.isFunctionDeclaration(fn) || ts.isFunctionExpression(fn)) && fn.name && reserved(fn.name.text))
196
+ refuse(fn.name, 'standalone: reserved function name');
197
+ const locals = new Set();
198
+ for (const p of fn.parameters) {
199
+ if (!ts.isIdentifier(p.name) || p.dotDotDotToken || p.initializer)
200
+ refuse(p, 'standalone: rest, destructuring and defaults are outside the subset');
201
+ if (reserved(p.name.getText()))
202
+ refuse(p, `standalone: reserved parameter ${p.name.getText()}`);
203
+ const sym = symbol(p.name);
204
+ if (locals.has(sym))
205
+ refuse(p, 'standalone: duplicate parameter binding');
206
+ locals.add(sym);
207
+ }
208
+ active.add(fn);
209
+ if (ts.isBlock(fn.body))
210
+ statement(fn.body, locals);
211
+ else
212
+ expression(fn.body, locals);
213
+ active.delete(fn);
214
+ done.add(fn);
215
+ const b = [...bindings.values()].find(x => functionOf(x) === fn);
216
+ if (b)
217
+ reached.add(b.decl.name.getText());
218
+ };
219
+ functionBody(entry);
220
+ return [...reached].sort();
221
+ }
@@ -14,6 +14,7 @@ export type ExtractOptions = Omit<ReadOptions, 'entry' | 'functions'> & {
14
14
  file?: string;
15
15
  orm?: OrmOptions;
16
16
  shape?: 'class' | 'functions';
17
+ mode?: 'standalone';
17
18
  domains?: Record<string, 'nat' | 'int'>;
18
19
  check?: CheckOptions;
19
20
  };
@@ -42,7 +42,7 @@ import { compileFunction, walk } from "./machine.js";
42
42
  import * as I from "./extract-ir.js";
43
43
  import { PASS } from "./extract-ir.js";
44
44
  import { Refusal, placed, sourceOf, syntaxError, tooDeep } from "./extract-read.js";
45
- import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice } from "./extract-shapes.js";
45
+ import { isFactory, isSlice, readClass, readFactory, readFunctions, readSlice, readStandalone } from "./extract-shapes.js";
46
46
  import { kindOf, mapEmpty, mapKind, natOK, pb, pidx, pk, pnum, pterm, sortsOf } from "./extract-print.js";
47
47
  import { check } from "./extract-check.js";
48
48
  import { extractOrm } from "./extract-orm.js";
@@ -72,6 +72,8 @@ export function namesOf(m) {
72
72
  const arg = (a, at, method) => {
73
73
  if (a.k === 'input')
74
74
  out.push({ code: at, rule: a.name, role: 'input', method });
75
+ else if (a.k === 'maybe-bool')
76
+ out.push({ code: at, rule: a.name, none: a.missing, role: 'input', method });
75
77
  else if (a.k === 'rec')
76
78
  for (const [f, x] of a.fields)
77
79
  arg(x, `${at}.${f}`, method);
@@ -98,17 +100,27 @@ export function extract(at, opts = {}) {
98
100
  try {
99
101
  ;
100
102
  ({ code, file } = sourceOf(at, opts.file, 'input.ts'));
103
+ if (opts.mode !== undefined && opts.mode !== 'standalone')
104
+ throw new Refusal(file, `unsupported extraction mode: ${String(opts.mode)}`);
101
105
  const bad = syntaxError(code, file);
102
106
  if (bad)
103
107
  throw new Refusal(file, bad);
104
108
  if (opts.orm) {
109
+ if (opts.mode === 'standalone')
110
+ throw new Refusal(file, 'standalone mode cannot use ORM');
105
111
  if (typeof at !== 'string' || at.includes('\n') || !/\.[cm]?[jt]sx?$/.test(at))
106
112
  throw new Refusal(file, 'ORM checking requires the original module on disk');
107
113
  return extractOrm(file, code, { ...opts, orm: opts.orm });
108
114
  }
109
115
  const fns = Array.isArray(opts.entry) ? opts.entry : opts.functions;
110
116
  const o = { ...opts, entry: (Array.isArray(opts.entry) ? opts.entry[0] : opts.entry) ?? fns?.[0] ?? '', ...(fns ? { functions: fns } : {}) };
111
- model = o.entry ? readModel(code, file, o, opts.shape) : inferred(code, file, o, opts.shape);
117
+ if (opts.mode === 'standalone') {
118
+ if (!o.entry || Array.isArray(opts.entry) || opts.functions || opts.shape || opts.orm)
119
+ throw new Refusal(file, 'standalone mode needs exactly one named function and no other shape');
120
+ model = readStandalone(code, placed(file), o);
121
+ }
122
+ else
123
+ model = o.entry ? readModel(code, file, o, opts.shape) : inferred(code, file, o, opts.shape);
112
124
  model.file = file;
113
125
  }
114
126
  catch (e) {
@@ -118,6 +130,8 @@ export function extract(at, opts = {}) {
118
130
  return { ok: false, refusals: [{ where: opts.file ?? (typeof at === 'string' && !at.includes('\n') ? at : 'input.ts'), what: 'the source nests too deeply to read' }], notes };
119
131
  throw e;
120
132
  }
133
+ if (model.standalone && Object.entries(model.standaloneDomains ?? {}).some(([n, xs]) => opts.domains?.[n] === 'nat' && xs.some(x => x < 0)))
134
+ return { ok: false, refusals: [{ where: file, what: 'standalone: a natural domain contradicts the declared negative numeric literals' }], notes, model };
121
135
  return { ...fromModel(model, file, opts.domains, notes, (rule, sorts) => check(code, file, model, rule, sorts, { ...opts.check, ...(opts.files ? { files: opts.files } : {}), ...(opts.domains ? { given: opts.domains } : {}) })), names: namesOf(model) };
122
136
  }
123
137
  function readModel(code, file, opts, shape) {
package/dist/core/laws.js CHANGED
@@ -263,6 +263,7 @@ const calendarOf = (opts) => {
263
263
  }
264
264
  };
265
265
  export function buildLaw(x, l, opts = {}) {
266
+ const strictOptional = x.model?.standalone === true;
266
267
  const names = namesWithClock(x), r = x.rule;
267
268
  if (!r)
268
269
  throw new LawError('the extraction has no rule');
@@ -271,7 +272,7 @@ export function buildLaw(x, l, opts = {}) {
271
272
  const e = parse(l.expr);
272
273
  // A first reading finds what the law reads: a request, a result, the failure or the state before make it a step law.
273
274
  const cal = opts.clock === undefined ? undefined : calendarOf(opts);
274
- const probe = { consts: x.consts, b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock, cal };
275
+ const probe = { strictOptional, consts: x.consts, b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock, cal };
275
276
  read(e, probe, names, true);
276
277
  // (a law on a method, the line above it, is a law of its step: the state after it, old(x) before)
277
278
  const step = !!l.method || ['input', 'answer', 'result', 'failed', 'clock', 'method', 'old'].some(k => probe.roles.has(k));
@@ -279,7 +280,7 @@ export function buildLaw(x, l, opts = {}) {
279
280
  if (probe.methods.size > 1)
280
281
  throw new LawError(`it reads the arguments of ${[...probe.methods].join(' and ')}: a law of one step is about one method`);
281
282
  const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
282
- const body0 = (b, a, pins, bits) => read(e, { consts: x.consts, b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock, cal, pins, ...(bits ? { bits } : {}) }, names, false);
283
+ const body0 = (b, a, pins, bits) => read(e, { strictOptional, consts: x.consts, b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock, cal, pins, ...(bits ? { bits } : {}) }, names, false);
283
284
  // (a step law's bit tests: read once to count the keys they take, then at every value of them, the facts implying it)
284
285
  const bitBody = (b, a) => {
285
286
  const count = { ks: [], used: 0, hyps: [] };
@@ -343,7 +344,7 @@ function read(e, c, names, dry) {
343
344
  if (dry) {
344
345
  for (const f of chain)
345
346
  c.keys.set(f.v, new Term({ op: 'const', value: 0 }));
346
- return cond(val(body, c, names, true));
347
+ return cond(val(body, c, names, true), c.strictOptional);
347
348
  }
348
349
  const at = (ks) => {
349
350
  const held = overs.map((o, i) => {
@@ -353,17 +354,17 @@ function read(e, c, names, dry) {
353
354
  c.items.set(chain[i].v, { map: m.at(ks[i]), fields: o.over.n.map.fields });
354
355
  return m.at(ks[i]).has;
355
356
  });
356
- return all(...held).implies(cond(val(body, c, names, false)));
357
+ return all(...held).implies(cond(val(body, c, names, false), c.strictOptional));
357
358
  };
358
359
  return chain.length === 1 ? forall(k => at([k])) : chain.length === 2 ? forall((k, j) => at([k, j])) : forall((k, j, i) => at([k, j, i]));
359
360
  }
360
- return cond(val(e, c, names, dry));
361
+ return cond(val(e, c, names, dry), c.strictOptional);
361
362
  }
362
- const cond = (v) => {
363
+ const cond = (v, strictOptional = false) => {
363
364
  if (v.t === 'cond')
364
365
  return v.v;
365
366
  if (v.t === 'opt' && v.v?.t === 'cond')
366
- return v.v.v;
367
+ return strictOptional ? all(not(v.none), v.v.v) : v.v.v;
367
368
  throw new LawError(`a ${v.t === 'num' ? 'number' : v.t} where a condition is read`);
368
369
  };
369
370
  const num = (v) => {
@@ -432,6 +433,8 @@ function val(e, c, names, dry) {
432
433
  }
433
434
  }
434
435
  const xs = e.xs.map(go);
436
+ if (c.strictOptional && xs.some(v => v.t === 'opt'))
437
+ throw new LawError('arithmetic on an optional standalone value is not supported');
435
438
  if (dry)
436
439
  return DRY;
437
440
  if (e.f === 'abs')
@@ -440,9 +443,11 @@ function val(e, c, names, dry) {
440
443
  }
441
444
  case 'un': {
442
445
  const v = go(e.x);
446
+ if (c.strictOptional && e.op === '-' && v.t === 'opt')
447
+ throw new LawError('arithmetic on an optional standalone value is not supported');
443
448
  if (dry)
444
449
  return v.t === 'cond' ? v : DRY;
445
- return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v)) };
450
+ return e.op === '-' ? { t: 'num', v: num(v).negate() } : { t: 'cond', v: not(cond(v, c.strictOptional)) };
446
451
  }
447
452
  case 'bin': {
448
453
  // (a comparison with x // k on one side, k a positive constant: the same comparison without the division, exact
@@ -453,6 +458,11 @@ function val(e, c, names, dry) {
453
458
  return { t: 'cond', v: businessCompare(e, flip, c, go, dry) };
454
459
  const divk = (x) => (x.k === 'bin' && x.op === '//' && (constOf(x.b) ?? 0) >= 1 ? x : undefined);
455
460
  if (flip[e.op] && (divk(e.b) || divk(e.a))) {
461
+ // Inspect the original numerator before rewriting division into comparisons.
462
+ if (c.strictOptional)
463
+ for (const d of [divk(e.a), divk(e.b)])
464
+ if (d && go(d.a).t === 'opt')
465
+ throw new LawError('arithmetic on an optional standalone value is not supported');
456
466
  const [op, lhs, d] = divk(e.b) ? [e.op, e.a, divk(e.b)] : [flip[e.op], e.b, divk(e.a)];
457
467
  const k = constOf(d.b), ka = { k: 'bin', op: '*', a: { k: 'num', v: k }, b: lhs }, ka1 = { k: 'bin', op: '*', a: { k: 'num', v: k }, b: { k: 'bin', op: '+', a: lhs, b: { k: 'num', v: 1 } } };
458
468
  const le = (a, b) => ({ k: 'bin', op: '<=', a, b }), lt = (a, b) => ({ k: 'bin', op: '<', a, b });
@@ -481,7 +491,9 @@ function val(e, c, names, dry) {
481
491
  if (a.t === 'lit' && a.err && b.t === 'lit' && b.err)
482
492
  throw a.err;
483
493
  if (['&&', '||', '=>'].includes(e.op))
484
- return dry ? { t: 'cond', v: yes } : { t: 'cond', v: e.op === '&&' ? all(cond(a), cond(b)) : e.op === '||' ? any(cond(a), cond(b)) : cond(a).implies(cond(b)) };
494
+ return dry ? { t: 'cond', v: yes } : { t: 'cond', v: e.op === '&&' ? all(cond(a, c.strictOptional), cond(b, c.strictOptional)) : e.op === '||' ? any(cond(a, c.strictOptional), cond(b, c.strictOptional)) : cond(a, c.strictOptional).implies(cond(b, c.strictOptional)) };
495
+ if (c.strictOptional && ['+', '-', '*', '//', '/', '%', '&', '|'].includes(e.op) && [a, b].some(v => v.t === 'opt'))
496
+ throw new LawError('arithmetic on an optional standalone value is not supported');
485
497
  if (dry)
486
498
  return ['+', '-', '*', '//', '/', '%', '&', '|'].includes(e.op) ? DRY : { t: 'cond', v: yes };
487
499
  // x & K and x | K with K a constant (a literal or a constant of the code): K's runs of ones, ((x div 2^lo) mod 2^n)·2^lo
@@ -542,7 +554,7 @@ function val(e, c, names, dry) {
542
554
  throw new LawError(`${e.op} by a positive constant only`);
543
555
  return e.op === '%' ? { t: 'num', v: Int.of(num(a).modBy(k)) } : { t: 'num', v: num(a).divBy(k) };
544
556
  }
545
- return { t: 'cond', v: compare(e.op, a, b, e) };
557
+ return { t: 'cond', v: compare(e.op, a, b, e, c.strictOptional) };
546
558
  }
547
559
  case 'path': return path(e, c, names, dry);
548
560
  case 'forall': return fail('forall ... in ...: at the top of the law only');
@@ -584,13 +596,25 @@ function businessCompare(e, flip, c, go, dry) {
584
596
  // (a path's last name: a choice's value written as one, Outcome.SLOW_ERROR)
585
597
  const lastName = (x) => (x.segs.length ? x.segs.at(-1).f : x.head);
586
598
  const constOf = (x) => (x.k === 'num' ? x.v : x.k === 'un' && x.op === '-' && x.x.k === 'num' ? -x.x.v : undefined);
587
- function compare(op, a, b, e) {
599
+ function compare(op, a, b, e, strictOptional = false) {
588
600
  if (b.t === 'null' || a.t === 'null') {
589
601
  const o = a.t === 'null' ? b : a, none = o.t === 'opt' ? o.none : o.t === 'cell' ? not(o.rec.has) : undefined;
590
602
  if (!none)
591
603
  throw new LawError(`${show(a.t === 'null' ? e.b : e.a)} is never None here (the rule holds no None for it)`);
592
604
  return op === '==' ? none : op === '!=' ? not(none) : fail(`${op} with None`);
593
605
  }
606
+ // A standalone optional value is absent regardless of its hidden scalar payload.
607
+ // Keep the established law language of other frontends unchanged.
608
+ if (strictOptional && (a.t === 'opt' || b.t === 'opt')) {
609
+ const av = a.t === 'opt' ? a.v : a, bv = b.t === 'opt' ? b.v : b;
610
+ const present = all(a.t === 'opt' ? not(a.none) : yes, b.t === 'opt' ? not(b.none) : yes);
611
+ if (op === '==' || op === '!=') {
612
+ const absent = a.t === 'opt' && b.t === 'opt' ? all(a.none, b.none) : no;
613
+ const equal = any(absent, av && bv ? all(present, compare('==', av, bv, e)) : no);
614
+ return op === '==' ? equal : not(equal);
615
+ }
616
+ return av && bv ? all(present, compare(op, av, bv, e)) : no;
617
+ }
594
618
  const un = (v) => (v.t === 'opt' && v.v ? v.v : v);
595
619
  a = un(a);
596
620
  b = un(b);
@@ -5,7 +5,7 @@ edition = "2021"
5
5
  publish = false
6
6
 
7
7
  [dependencies]
8
- syn = {version = "2", features = ["full"]}
8
+ syn = {version = "2", features = ["full", "visit"]}
9
9
  proc-macro2 = {version = "1", features = ["span-locations"]}
10
10
  quote = "1"
11
11
  serde_json = "1"