gdp-wired 0.32.0 → 0.33.1

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,4 +1,5 @@
1
- import type { Extraction } from './extract.js';
1
+ import type { Extraction, Name } from './extract.js';
2
+ import { type TwoRunLaw } from './relational.js';
2
3
  export type LawText = {
3
4
  name: string;
4
5
  expr: string;
@@ -60,7 +61,23 @@ type X = {
60
61
  v: string;
61
62
  over: X;
62
63
  body: X;
64
+ } | {
65
+ k: 'dur';
66
+ v: number;
67
+ text: string;
63
68
  };
69
+ export declare function duration(text: string, clock?: 's' | 'ms'): number;
64
70
  export declare function parse(s: string): X;
65
- export declare function buildLaw(x: Extraction, l: LawText): Built;
71
+ export declare function namesWithClock(x: Extraction): Name[];
72
+ export declare function buildLaw(x: Extraction, l: LawText, opts?: {
73
+ clock?: number;
74
+ }): Built;
75
+ export type Cite = {
76
+ law: string;
77
+ text: string;
78
+ where: string;
79
+ };
80
+ export declare function citesIn(text: string, where?: string): Cite[];
81
+ export declare const isTwoRuns: (expr: string) => boolean;
82
+ export declare function buildTwoRuns(x: Extraction, l: LawText, others?: Record<string, Extraction>): TwoRunLaw;
66
83
  export {};
package/dist/core/laws.js CHANGED
@@ -24,6 +24,7 @@
24
24
  // forall k in budgets: budgets[k].spent <= budgets[k].limit every key the map holds (at the top of the law)
25
25
  // mode == "closed", outcome == SLOW_ERROR, mode == :closed a choice by its value
26
26
  import { Choice, Int, Str, Term, all, any, forall, no, not, yes } from "./dsl.js";
27
+ import { agreement, isolation, noninterference } from "./relational.js";
27
28
  export class LawError extends Error {
28
29
  }
29
30
  // --- reading the code's text -------------------------------------------------------------------------------------------
@@ -61,6 +62,30 @@ function tokens(s) {
61
62
  throw new LawError(`can't read ${JSON.stringify(s.slice(at).trim())}`);
62
63
  return out;
63
64
  }
65
+ // Durations, as many seconds: linear over the clock (a day is 86,400 s: the request's time counts seconds, with no
66
+ // time zone, leap second or daylight saving). A month, a year, a business day or the end of a day isn't a fixed number
67
+ // of seconds, so a law reading one is refused: state it in days.
68
+ const SECONDS = { ms: 0.001, millisecond: 0.001, milliseconds: 0.001, second: 1, seconds: 1, sec: 1, secs: 1, minute: 60, minutes: 60, min: 60, mins: 60,
69
+ hour: 3600, hours: 3600, day: 86_400, days: 86_400, week: 604_800, weeks: 604_800 };
70
+ const NOT_LINEAR = /^(months?|years?|quarters?|business|working|weekdays?|fortnights?)$/i;
71
+ function seconds(unit) {
72
+ const u = unit.toLowerCase();
73
+ if (NOT_LINEAR.test(u))
74
+ throw new LawError(`${unit}: not a fixed number of seconds (a month or a year has several lengths, a business day depends on the calendar): state it in days, hours or seconds`);
75
+ return SECONDS[u];
76
+ }
77
+ // A duration in the clock's units ('s': time.time(), 'ms': Date.now()): duration('30 days') is 2,592,000.
78
+ export function duration(text, clock = 's') {
79
+ const m = /^\s*(\d+)\s*(?:calendar\s+)?([A-Za-z]+)(?:\s+days?)?\s*$/.exec(text);
80
+ if (!m)
81
+ throw new LawError(`${text}: a duration is a whole number and a unit (30 days, 15 minutes)`);
82
+ if (!Object.hasOwn(SECONDS, m[2].toLowerCase()) && !NOT_LINEAR.test(m[2]))
83
+ throw new LawError(`${m[2]}: a unit of ${Object.keys(SECONDS).join(', ')}`);
84
+ const v = Number(m[1]) * seconds(m[2]) * (clock === 'ms' ? 1000 : 1);
85
+ if (!Number.isInteger(v))
86
+ throw new LawError(`${text}: not a whole number of the clock's units`);
87
+ return v;
88
+ }
64
89
  export function parse(s) {
65
90
  const t = tokens(s);
66
91
  let i = 0;
@@ -119,6 +144,14 @@ export function parse(s) {
119
144
  if (/^\d/.test(x)) {
120
145
  if (x.includes('.') && !/\.0+$/.test(x))
121
146
  throw new LawError(`${x}: a number that isn't whole`);
147
+ // (a duration: 30 days, 15 minutes, in seconds until the clock's unit is known)
148
+ const u = peek()?.toLowerCase(), calendar = u === 'calendar' && /^days?$/i.test(t[i + 1] ?? '');
149
+ if (u && (calendar || Object.hasOwn(SECONDS, u) || NOT_LINEAR.test(u))) {
150
+ eat();
151
+ if (calendar)
152
+ eat();
153
+ return { k: 'dur', v: Number(x) * seconds(calendar ? 'days' : u), text: `${x} ${u}${calendar ? ' days' : ''}` };
154
+ }
122
155
  return { k: 'num', v: Number(x) };
123
156
  }
124
157
  if (/^f?["'`]/.test(x))
@@ -198,15 +231,21 @@ export function parse(s) {
198
231
  return e;
199
232
  }
200
233
  // The law a text states, built on the extraction's rule through its names.
201
- export function buildLaw(x, l) {
202
- const names = x.names ?? [], r = x.rule;
234
+ // The extraction's names, with the request's time as `now` where the rule reads it and no name says so (a TypeScript
235
+ // class's Date.now()).
236
+ export function namesWithClock(x) {
237
+ const ns = x.names ?? [], ins = x.rule?.parts?.inputs.map(([n]) => n) ?? [];
238
+ return ns.some(n => n.role === 'clock') || !ins.includes('now') || ns.some(n => n.code === 'now') ? ns : [...ns, { code: 'now', rule: 'now', role: 'clock' }];
239
+ }
240
+ export function buildLaw(x, l, opts = {}) {
241
+ const names = namesWithClock(x), r = x.rule;
203
242
  if (!r)
204
243
  throw new LawError('the extraction has no rule');
205
244
  if (!l.expr)
206
245
  throw new LawError(`${l.name}: a law is stated as <name>: <expr>`);
207
246
  const e = parse(l.expr);
208
247
  // A first reading finds what the law reads: a request, a result, the failure or the state before make it a step law.
209
- const probe = { b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set() };
248
+ const probe = { b: {}, a: {}, step: true, method: l.method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock };
210
249
  read(e, probe, names, true);
211
250
  // (a law on a method, the line above it, is a law of its step: the state after it, old(x) before)
212
251
  const step = !!l.method || ['input', 'answer', 'result', 'failed', 'clock', 'method', 'old'].some(k => probe.roles.has(k));
@@ -214,7 +253,7 @@ export function buildLaw(x, l) {
214
253
  if (probe.methods.size > 1)
215
254
  throw new LawError(`it reads the arguments of ${[...probe.methods].join(' and ')}: a law of one step is about one method`);
216
255
  const gate = step && method && names.some(n => n.role === 'method') ? method : undefined;
217
- const body = (b, a) => read(e, { b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set() }, names, false);
256
+ const body = (b, a) => read(e, { b, a, step, method, keys: new Map(), roles: new Set(), methods: new Set(), clock: opts.clock }, names, false);
218
257
  if (!step)
219
258
  return { kind: 'law', law: r.law(l.name, (env) => body(env, env)) };
220
259
  const mname = names.find(n => n.role === 'method')?.rule;
@@ -259,6 +298,12 @@ function val(e, c, names, dry) {
259
298
  const go = (x) => val(x, c, names, dry);
260
299
  switch (e.k) {
261
300
  case 'num': return { t: 'num', v: Int.of(e.v) };
301
+ case 'dur':
302
+ if (c.clock === undefined)
303
+ throw new LawError(`${e.text}: the clock's unit isn't known here (clock = "s" or "ms" in gdp.toml)`);
304
+ if (!Number.isInteger(e.v * c.clock))
305
+ throw new LawError(`${e.text}: not a whole number of the clock's units`);
306
+ return { t: 'num', v: Int.of(e.v * c.clock) };
262
307
  case 'bool': return { t: 'cond', v: e.v ? yes : no };
263
308
  case 'null': return { t: 'null' };
264
309
  case 'str':
@@ -520,3 +565,59 @@ function storeKey(m, k, c, names, dry) {
520
565
  throw new LawError(`${m.n.code}[${tpl}]: its keys are ${m.maps.map(x => JSON.stringify(x.map.tpl.replace('{}', '<key>'))).join(', ')}`);
521
566
  return [{ t: 'map', n: hit, maps: [hit] }, val(holes[0], c, names, dry)];
522
567
  }
568
+ const CITE = /(?:#|\/\/|--|%|\/\*|^\s*\*)\s*gdp:\s*cite\s+([^:]+?)\s*:\s*(.+?)\s*(?:\*\/)?\s*$/;
569
+ export function citesIn(text, where = '') {
570
+ return text.split('\n').flatMap((l, i) => { const m = CITE.exec(l); return m ? [{ law: m[1].trim(), text: m[2], where: `${where}:${i + 1}` }] : []; });
571
+ }
572
+ // --- laws about two runs -------------------------------------------------------------------------------------------------
573
+ // Three forms of a stated law (core/relational.ts), over the code's names:
574
+ // <secret>[, ...] never reaches <visible>[, ...] noninterference: the secret arguments (or params, answers) never
575
+ // change the visible fields or results, nor which calls fail
576
+ // isolated by <owner> [seeing <name>[, ...]] isolation: what the caller whose <owner> argument is B sees (the
577
+ // maps' cells at B, the results of B's calls, B's failures) is the
578
+ // same whatever the other callers do; by default every map, result
579
+ // agrees with <Entry> [on <name>[, ...]] a migration: this rule and <Entry> (another rule of the same
580
+ // target) keep the same fields after the same calls, fail alike
581
+ const TWO = [/^(.+?)\s+never\s+reach(?:es)?\s+(.+)$/i, /^isolated\s+by\s+([\w.]+)(?:\s+seeing\s+(.+))?$/i, /^agrees\s+with\s+([\w.]+)(?:\s+on\s+(.+))?$/i];
582
+ export const isTwoRuns = (expr) => TWO.some(re => re.test(expr.trim()));
583
+ const list = (s) => (s ? s.split(/\s*,\s*|\s+and\s+/).map(x => x.trim()).filter(Boolean) : []);
584
+ export function buildTwoRuns(x, l, others = {}) {
585
+ const names = namesWithClock(x), e = l.expr.trim(), r = x.rule;
586
+ if (!r)
587
+ throw new LawError('the extraction has no rule');
588
+ const known = () => [...new Set(names.filter(n => n.rule).map(n => n.code))].join(', ');
589
+ const ruleNames = (ns, code, roles, what) => {
590
+ const hit = ns.filter(n => n.code.replace(/^@/, '') === code.replace(/^(self|this)\./, '') && roles.includes(n.role));
591
+ if (!hit.length)
592
+ throw new LawError(`no ${code} ${what} (its names: ${known()})`);
593
+ return [...new Set(hit.flatMap(n => [n.rule, ...(n.none ? [n.none] : [])]).filter(Boolean))];
594
+ };
595
+ const STATE = ['state', 'result', 'failed'];
596
+ let m = TWO[0].exec(e);
597
+ if (m) {
598
+ const secret = list(m[1]).flatMap(c => ruleNames(names, c, ['input', 'param', 'answer', 'clock'], 'among the arguments, params or answered calls'));
599
+ const visible = list(m[2]).flatMap(c => ruleNames(names, c, STATE, 'among the fields and results'));
600
+ return { ...noninterference(r, { secret, visible, name: l.name }), name: l.name };
601
+ }
602
+ if ((m = TWO[1].exec(e))) {
603
+ const owners = names.filter(n => n.role === 'input' && n.code === m[1] && n.rule);
604
+ if (!owners.length)
605
+ throw new LawError(`no argument ${m[1]} (its names: ${known()})`);
606
+ const method = names.find(n => n.role === 'method')?.rule, methods = new Set(owners.map(n => n.method));
607
+ const key = (v) => (v instanceof Term ? v : v instanceof Int ? v.pos : v.id);
608
+ // (a call is B's where its method takes the owner argument and it is B; with one rule input for every method, that)
609
+ const owner = (env, b) => any(...owners.map(n => all(key(env[n.rule]).eq(b), ...(method && methods.size && n.method ? [env[method].is(n.method)] : []))));
610
+ const seen = m[2] ? list(m[2]).flatMap(c => ruleNames(names, c, STATE, 'among the fields and results')) : undefined;
611
+ const maps = new Set(names.filter(n => n.map).map(n => n.rule));
612
+ const sees = seen?.filter(n => maps.has(n)), results = seen ? seen.filter(n => !maps.has(n)) : names.filter(n => n.role === 'result' || n.role === 'failed').flatMap(n => [n.rule, ...(n.none ? [n.none] : [])]).filter(Boolean);
613
+ return { ...isolation(r, { owner, ...(sees ? { sees } : {}), results: [...new Set(results)], name: l.name }), name: l.name };
614
+ }
615
+ if ((m = TWO[2].exec(e))) {
616
+ const o = others[m[1]];
617
+ if (!o?.rule)
618
+ throw new LawError(`no rule ${m[1]} read beside this one (${Object.keys(others).join(', ') || 'none'}): agrees with names another class of the same target`);
619
+ const visible = m[2] ? list(m[2]).flatMap(c => { const mine = ruleNames(names, c, STATE, 'among the fields and results'); ruleNames(o.names ?? [], c, STATE, `in ${m[1]}`); return mine; }) : undefined;
620
+ return { ...agreement(o.rule, r, { ...(visible ? { visible } : {}), name: l.name }), name: l.name };
621
+ }
622
+ throw new LawError('not a law about two runs');
623
+ }
@@ -205,6 +205,8 @@ export declare const pairE: (a: E, b: E) => E;
205
205
  export declare const argsKey: (args: E[]) => E;
206
206
  export declare function pairedArgs(key: E, n: number): E[] | undefined;
207
207
  export declare function evalC(c: C, env: Env, st: State, m: Machine): boolean;
208
+ export declare function compileE(e: E, m: Machine): (env: Env, st: State) => number;
209
+ export declare function compileC(c: C, m: Machine): (env: Env, st: State) => boolean;
208
210
  export declare function carriedView(m: Machine, st: State, input: Request, rename?: (map: string) => string): State;
209
211
  export declare const numbersOf: (input: Request) => Record<string, number>;
210
212
  export declare function interpret(m: Machine): {
@@ -293,6 +293,93 @@ export function evalC(c, env, st, m) {
293
293
  }
294
294
  }
295
295
  }
296
+ // evalE and evalC compiled once to closures over (env, state): the same values and the same errors, in the same order
297
+ // (a read reads the machine's functions as they are when it runs, which a table swap changes; a quantified condition and
298
+ // a function of several arguments go through evalC and evalE). For a term read at many rows (the engine's views).
299
+ export function compileE(e, m) {
300
+ switch (e.op) {
301
+ case 'var': {
302
+ const name = e.name;
303
+ return (env, st) => { const v = env[name] ?? st.scalars[name]; if (v === undefined)
304
+ throw new Error(`no value for ${name}`); return v; };
305
+ }
306
+ case 'const': {
307
+ const v = e.value;
308
+ return () => v;
309
+ }
310
+ case 'add': {
311
+ const a = compileE(e.a, m), b = compileE(e.b, m);
312
+ return (env, st) => exact(a(env, st) + b(env, st));
313
+ }
314
+ case 'sub': {
315
+ const a = compileE(e.a, m), b = compileE(e.b, m);
316
+ return (env, st) => Math.max(0, a(env, st) - b(env, st));
317
+ }
318
+ case 'mul': {
319
+ const k = e.k, a = compileE(e.a, m);
320
+ return (env, st) => exact(k * a(env, st));
321
+ }
322
+ case 'prod': {
323
+ const a = compileE(e.a, m), b = compileE(e.b, m);
324
+ return (env, st) => exact(a(env, st) * b(env, st));
325
+ }
326
+ case 'min': {
327
+ const a = compileE(e.a, m), b = compileE(e.b, m);
328
+ return (env, st) => Math.min(a(env, st), b(env, st));
329
+ }
330
+ case 'max': {
331
+ const a = compileE(e.a, m), b = compileE(e.b, m);
332
+ return (env, st) => Math.max(a(env, st), b(env, st));
333
+ }
334
+ case 'if': {
335
+ const c = compileC(e.c, m), t = compileE(e.then, m), f = compileE(e.else, m);
336
+ return (env, st) => (c(env, st) ? t(env, st) : f(env, st));
337
+ }
338
+ case 'get': {
339
+ const map = e.map, key = compileE(e.key, m);
340
+ return (env, st) => {
341
+ const fn = m.fns?.[map];
342
+ if (fn?.call && pairedArgs(e.key, fn.arity))
343
+ return evalE(e, env, st, m);
344
+ const k = key(env, st);
345
+ return fn ? naturalIn(fnOf(fn)(k), `${map}(${k})`) : st.maps[map].get(k) ?? st.defaults?.[map] ?? m.maps[map];
346
+ };
347
+ }
348
+ }
349
+ }
350
+ export function compileC(c, m) {
351
+ switch (c.op) {
352
+ case '<': {
353
+ const a = compileE(c.a, m), b = compileE(c.b, m);
354
+ return (env, st) => a(env, st) < b(env, st);
355
+ }
356
+ case '<=': {
357
+ const a = compileE(c.a, m), b = compileE(c.b, m);
358
+ return (env, st) => a(env, st) <= b(env, st);
359
+ }
360
+ case '=': {
361
+ const a = compileE(c.a, m), b = compileE(c.b, m);
362
+ return (env, st) => a(env, st) === b(env, st);
363
+ }
364
+ case 'and': {
365
+ const xs = c.xs.map(y => compileC(y, m));
366
+ return (env, st) => xs.every(x => x(env, st));
367
+ }
368
+ case 'or': {
369
+ const xs = c.xs.map(y => compileC(y, m));
370
+ return (env, st) => xs.some(x => x(env, st));
371
+ }
372
+ case 'not': {
373
+ const x = compileC(c.x, m);
374
+ return (env, st) => !x(env, st);
375
+ }
376
+ case 'flag': {
377
+ const name = `?${c.name}`;
378
+ return env => env[name] === 1;
379
+ }
380
+ case 'all': return (env, st) => evalC(c, env, st, m);
381
+ }
382
+ }
296
383
  // A write at every key: its value at each key the maps it reads hold a cell at, and its new default past them.
297
384
  // With the key in key terms, every key up to the last breakpoint is computed (the stretches between breakpoints hold the
298
385
  // same value, which need not be the default), and past it the value is the new default.
@@ -0,0 +1,49 @@
1
+ import { type Cond, Rule, Term, type StepLaw, type Verdict, type ProveOptions } from './dsl.js';
2
+ import type { Law } from './machine.js';
3
+ import { type Document, type Json } from '../interchange/format.js';
4
+ export type AnyRule = Rule<any, any, any, any, any, any, any, any>;
5
+ type Env = Record<string, unknown>;
6
+ export type TwoRunsOptions = {
7
+ name?: string;
8
+ shared?: string[];
9
+ stays?: (env: Env) => Cond;
10
+ given?: (env: Env) => Cond;
11
+ refusals?: 'same' | 'assumed';
12
+ };
13
+ export declare function twoRuns(a: AnyRule, b?: AnyRule, opts?: TwoRunsOptions): AnyRule;
14
+ export type TwoRunLaw = {
15
+ name: string;
16
+ rule: AnyRule;
17
+ laws: Law[];
18
+ stepLaws: StepLaw[];
19
+ helpers: Law[];
20
+ sides: [AnyRule, AnyRule];
21
+ shared: string[];
22
+ };
23
+ export declare function noninterference(r: AnyRule, o: {
24
+ secret: string[];
25
+ visible?: string[];
26
+ name?: string;
27
+ refusals?: 'same' | 'assumed';
28
+ }): TwoRunLaw;
29
+ export declare function isolation(r: AnyRule, o: {
30
+ owner: string | ((env: Env, tenant: Term) => Cond);
31
+ sees?: string[];
32
+ results?: string[];
33
+ tenant?: string;
34
+ name?: string;
35
+ refusals?: 'same' | 'assumed';
36
+ }): TwoRunLaw;
37
+ export declare function agreement(old: AnyRule, next: AnyRule, o?: {
38
+ visible?: string[];
39
+ name?: string;
40
+ refusals?: 'same' | 'assumed';
41
+ }): TwoRunLaw;
42
+ export declare function lift(l: Law, r: AnyRule, prefix: 'a_' | 'b_', shared: string[]): Law;
43
+ export declare function proveTwoRuns(l: TwoRunLaw, opts?: ProveOptions & {
44
+ invariants?: [Law[], Law[]] | Law[];
45
+ }): Verdict & {
46
+ given: Law[];
47
+ };
48
+ export declare function certify(r: AnyRule, laws: Law[], stepLaws?: StepLaw[], meta?: Json): Document | undefined;
49
+ export {};