gdp-wired 0.45.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.
Files changed (126) hide show
  1. package/README.md +61 -8
  2. package/dist/core/bitsets.d.ts +2 -0
  3. package/dist/core/bitsets.js +23 -0
  4. package/dist/core/bmc.js +6 -2
  5. package/dist/core/c/reader.d.ts +9 -1
  6. package/dist/core/c/reader.js +423 -31
  7. package/dist/core/calendar.d.ts +29 -0
  8. package/dist/core/calendar.js +82 -0
  9. package/dist/core/cli.d.ts +4 -0
  10. package/dist/core/cli.js +206 -40
  11. package/dist/core/compose.js +3 -1
  12. package/dist/core/counts.d.ts +4 -1
  13. package/dist/core/counts.js +314 -85
  14. package/dist/core/cycles.js +8 -1
  15. package/dist/core/cyclic.d.ts +1 -0
  16. package/dist/core/cyclic.js +13 -7
  17. package/dist/core/data-synth.d.ts +3 -0
  18. package/dist/core/data-synth.js +252 -0
  19. package/dist/core/data.d.ts +2 -1
  20. package/dist/core/data.js +223 -24
  21. package/dist/core/discover.js +3 -1
  22. package/dist/core/draft.d.ts +19 -0
  23. package/dist/core/draft.js +53 -0
  24. package/dist/core/dsl.d.ts +37 -3
  25. package/dist/core/dsl.js +167 -26
  26. package/dist/core/effect-schema.d.ts +90 -0
  27. package/dist/core/effect-schema.js +500 -0
  28. package/dist/core/effect.d.ts +4 -11
  29. package/dist/core/effect.js +3 -79
  30. package/dist/core/exists.d.ts +1 -0
  31. package/dist/core/exists.js +191 -16
  32. package/dist/core/extract-c.d.ts +2 -0
  33. package/dist/core/extract-c.js +169 -22
  34. package/dist/core/extract-check.d.ts +1 -0
  35. package/dist/core/extract-check.js +97 -6
  36. package/dist/core/extract-go-check.d.ts +1 -1
  37. package/dist/core/extract-go-check.js +26 -5
  38. package/dist/core/extract-go.d.ts +8 -0
  39. package/dist/core/extract-go.js +67 -6
  40. package/dist/core/extract-ir.d.ts +1 -0
  41. package/dist/core/extract-ir.js +15 -0
  42. package/dist/core/extract-jvm.d.ts +1 -1
  43. package/dist/core/extract-jvm.js +2 -0
  44. package/dist/core/extract-orm.d.ts +12 -0
  45. package/dist/core/extract-orm.js +244 -0
  46. package/dist/core/extract-print.js +20 -1
  47. package/dist/core/extract-py.d.ts +1 -0
  48. package/dist/core/extract-py.js +1 -1
  49. package/dist/core/extract-read.d.ts +26 -1
  50. package/dist/core/extract-read.js +14 -7
  51. package/dist/core/extract-rs.js +63 -15
  52. package/dist/core/extract-shapes.d.ts +1 -0
  53. package/dist/core/extract-shapes.js +84 -0
  54. package/dist/core/extract-sol.d.ts +10 -1
  55. package/dist/core/extract-sol.js +70 -22
  56. package/dist/core/extract-standalone.d.ts +3 -0
  57. package/dist/core/extract-standalone.js +221 -0
  58. package/dist/core/extract-step.d.ts +151 -1
  59. package/dist/core/extract-step.js +1232 -60
  60. package/dist/core/extract-swift.js +6 -2
  61. package/dist/core/extract.d.ts +9 -0
  62. package/dist/core/extract.js +77 -7
  63. package/dist/core/fiber-run.d.ts +5 -0
  64. package/dist/core/fiber-run.js +18 -0
  65. package/dist/core/infer.d.ts +4 -1
  66. package/dist/core/infer.js +918 -217
  67. package/dist/core/jvm/JavaReader.java +23 -6
  68. package/dist/core/jvm/Jvm.java +3 -0
  69. package/dist/core/jvm/KtReader.java +6 -5
  70. package/dist/core/laws.d.ts +10 -3
  71. package/dist/core/laws.js +226 -23
  72. package/dist/core/machine.d.ts +15 -1
  73. package/dist/core/machine.js +187 -15
  74. package/dist/core/nonterm.js +14 -1
  75. package/dist/core/orm/harness.js +61 -0
  76. package/dist/core/orm-fixtures/schema.prisma +5 -0
  77. package/dist/core/py/harness.py +183 -10
  78. package/dist/core/py/reader.py +234 -40
  79. package/dist/core/reader-fixtures/README.md +28 -0
  80. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  81. package/dist/core/reader-fixtures/go-685506.go +14 -0
  82. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  83. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  84. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  85. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  86. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  87. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  88. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  89. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  90. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  91. package/dist/core/relation.d.ts +1 -1
  92. package/dist/core/relation.js +29 -2
  93. package/dist/core/relational.js +4 -2
  94. package/dist/core/rs/Cargo.toml +1 -1
  95. package/dist/core/rs/src/main.rs +466 -11
  96. package/dist/core/sample-cache.d.ts +8 -0
  97. package/dist/core/sample-cache.js +46 -0
  98. package/dist/core/security.d.ts +38 -0
  99. package/dist/core/security.js +88 -0
  100. package/dist/core/sol/harness.py +57 -4
  101. package/dist/core/sol-concrete.d.ts +23 -0
  102. package/dist/core/sol-concrete.js +195 -0
  103. package/dist/core/solver.js +3 -1
  104. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  105. package/dist/core/system.js +1 -1
  106. package/dist/core/transfer.js +22 -9
  107. package/dist/core/translate.js +39 -10
  108. package/dist/core/watch.js +50 -5
  109. package/dist/interchange/format.js +11 -1
  110. package/dist/kernel/cdcl.d.ts +5 -0
  111. package/dist/kernel/cdcl.js +56 -9
  112. package/dist/kernel/epr.js +108 -26
  113. package/dist/kernel/kernel.d.ts +29 -1
  114. package/dist/kernel/kernel.js +325 -62
  115. package/dist/kernel/model-sequence.d.ts +3 -0
  116. package/dist/kernel/model-sequence.js +34 -0
  117. package/dist/kernel/prove.d.ts +10 -3
  118. package/dist/kernel/prove.js +332 -71
  119. package/dist/kernel/reader.d.ts +3 -0
  120. package/dist/kernel/reader.js +101 -14
  121. package/dist/kernel/share.d.ts +1 -0
  122. package/dist/kernel/share.js +27 -0
  123. package/dist/lean-kernel/emit.js +30 -37
  124. package/dist/lean-kernel/lean-terms.js +5 -0
  125. package/dist/lean-kernel/library.js +10 -10
  126. package/package.json +6 -1
@@ -27,7 +27,9 @@ import { fromModel } from "./extract.js";
27
27
  import { evalC, interpret, seeded } from "./machine.js";
28
28
  import { allowed, watch } from "./watch.js";
29
29
  import { kindOfVar } from "./extract-check.js";
30
+ import { substN } from "./extract-ir.js";
30
31
  import { Refusal, pathOf, readerRun, statedRefusal } from "./extract-read.js";
32
+ import { concreteSolidity, SolidityHarnessRefusal } from "./sol-concrete.js";
31
33
  const refuse = (where, what) => { throw new Refusal(where, what); };
32
34
  import { asset, checkStep, node, readStep, stepNames } from "./extract-step.js";
33
35
  export { proveRule, proveSteps } from "./dsl.js";
@@ -36,10 +38,10 @@ export const MOD = 'W256$';
36
38
  const CHECK_W = 2 ** 52;
37
39
  const U256 = { k: 'int', bits: 256, signed: false, mod: MOD };
38
40
  const env = () => globalThis.process?.env ?? {};
39
- export function compile(file, o) {
41
+ export function compile(file, o, extra = {}) {
40
42
  const cp = node('node:child_process'), fs = node('node:fs'), path = node('node:path');
41
43
  const root = path.resolve(o.root ?? path.dirname(file)), rel = path.relative(root, path.resolve(file));
42
- const input = { language: 'Solidity', sources: { [rel]: { content: fs.readFileSync(file, 'utf8') } },
44
+ const input = { language: 'Solidity', sources: { ...Object.fromEntries(Object.entries(extra).map(([p, content]) => [p, { content }])), [rel]: { content: fs.readFileSync(file, 'utf8') } },
43
45
  settings: { remappings: o.remappings ?? [], optimizer: { enabled: false }, outputSelection: { '*': { '': ['ast'], '*': ['abi', 'evm.bytecode.object', 'evm.deployedBytecode.object', 'evm.methodIdentifiers', 'storageLayout'] } } } };
44
46
  let out;
45
47
  const solc = o.solc ?? env().GDP_SOLC ?? 'solc';
@@ -61,7 +63,7 @@ export function compile(file, o) {
61
63
  ast.set(s.id, s.ast);
62
64
  paths.set(s.id, p);
63
65
  const abs = p === rel ? path.resolve(file) : [path.resolve(root, p), path.resolve(root, 'node_modules', p)].find(x => fs.existsSync(x));
64
- text.set(s.id, abs ? fs.readFileSync(abs, 'utf8') : '');
66
+ text.set(s.id, extra[p] ?? (abs ? fs.readFileSync(abs, 'utf8') : ''));
65
67
  }
66
68
  return { main, ast, text, paths, contracts: j.contracts };
67
69
  }
@@ -73,6 +75,7 @@ class Lower {
73
75
  funcs = {};
74
76
  fields = [];
75
77
  consts = new Map();
78
+ ctorParams = new Map();
76
79
  minW = 2;
77
80
  addrBits = 0;
78
81
  get ADDR() { return { k: 'int', bits: this.addrBits, signed: false }; }
@@ -161,7 +164,7 @@ class Lower {
161
164
  return { k: 'map', key: k.k === 'int' && k.mod ? { k: 'int' } : k, val };
162
165
  }
163
166
  // The contract: its linearized bases, state, functions.
164
- module(name) {
167
+ module(name, selected) {
165
168
  const contracts = [...this.defs.values()].filter(d => d.nodeType === 'ContractDefinition');
166
169
  const main = this.c.ast.get(this.c.main);
167
170
  const own = contracts.filter(d => main && main.nodes.includes(d));
@@ -201,11 +204,11 @@ class Lower {
201
204
  if (f.kind === 'constructor')
202
205
  continue;
203
206
  const id = this.fnId(f);
204
- if (this.funcs[id])
207
+ if (fns[id])
205
208
  continue;
206
209
  const pub = f.visibility === 'public' || f.visibility === 'external';
207
210
  const name = f.kind === 'receive' ? 'receive' : f.kind === 'fallback' ? 'fallback' : f.name;
208
- if (pub && f.stateMutability !== 'view' && f.stateMutability !== 'pure') {
211
+ if (pub && (selected ? selected.includes(name) : f.stateMutability !== 'view' && f.stateMutability !== 'pure')) {
209
212
  if (methods[name])
210
213
  this.no(f, `${name}: an overloaded external function (the subset reads one of a name)`);
211
214
  methods[name] = `entry:${id}`;
@@ -392,6 +395,35 @@ class Lower {
392
395
  this.cur = { entry: true, payable: top?.stateMutability === 'payable', rets: [], tmp: 0 };
393
396
  if (this.cur.payable)
394
397
  this.ether = true;
398
+ // Bind constructor arguments derived-first, then execute bodies base-first. Each parameter has a fresh local:
399
+ // a base's `n` must neither read an unbound derived `n` nor overwrite it when the base mutates its own argument.
400
+ const used = new Set([...this.defs.values()].map(d => d.name).filter((n) => typeof n === 'string'));
401
+ const callsCode = (a) => {
402
+ if (Array.isArray(a))
403
+ return a.some(callsCode);
404
+ if (!a || typeof a !== 'object')
405
+ return false;
406
+ const n = a;
407
+ return n.nodeType === 'FunctionCall' && n.kind !== 'typeConversion' || Object.values(n).some(v => v && typeof v === 'object' && callsCode(v));
408
+ };
409
+ for (const c of this.lin) {
410
+ const cf = ctorOf(c);
411
+ for (const [i, pa] of (cf?.parameters.parameters ?? []).entries()) {
412
+ const a = c === k ? undefined : given.get(c.id)?.[i];
413
+ if (c !== k && !a)
414
+ this.no(cf, `${c.name}'s constructor given no ${pa.name}`);
415
+ if (a && callsCode(a))
416
+ this.no(a, 'a constructor argument calling code (its initialization order is not supported)');
417
+ const x = a ? this.ex(a) : { e: 'var', n: pa.name, p: this.at(pa) };
418
+ let name = `gdp$ctor$${pa.id}`;
419
+ while (used.has(name))
420
+ name += '_';
421
+ used.add(name);
422
+ const to = { e: 'var', n: name, p: this.at(pa) };
423
+ body.push({ s: 'set', p: this.at(pa), to, x, t: this.ty(pa.typeDescriptions.typeString, pa) });
424
+ this.ctorParams.set(pa.id, to);
425
+ }
426
+ }
395
427
  for (const c of [...this.lin].reverse()) {
396
428
  for (const n of c.nodes) {
397
429
  if (n.nodeType !== 'VariableDeclaration' || n.constant)
@@ -404,9 +436,6 @@ class Lower {
404
436
  const cf = ctorOf(c);
405
437
  if (!cf)
406
438
  continue;
407
- if (c !== k)
408
- cf.parameters.parameters.forEach((pa, i) => { const a = given.get(c.id)?.[i]; if (!a)
409
- this.no(cf, `${c.name}'s constructor given no ${pa.name}`); body.push({ s: 'set', p: this.at(cf), to: { e: 'var', n: pa.name, p: this.at(cf) }, x: this.ex(a) }); });
410
439
  body.push(...this.withModifiers(cf, (cf.modifiers ?? []).filter(m => this.defs.get(m.modifierName.referencedDeclaration)?.nodeType === 'ModifierDefinition'), 0));
411
440
  }
412
441
  if (this.ether)
@@ -421,6 +450,7 @@ class Lower {
421
450
  const params = [{ name: 'self', t: { k: 'rec', name: k.name }, self: true }, { name: MOD, t: { k: 'int' } }, { name: 'msg.sender', t: this.ADDR }, ...(this.cur.payable ? [{ name: 'msg.value', t: U256 }] : [])];
422
451
  for (const pa of (top?.parameters.parameters ?? []))
423
452
  params.push({ name: pa.name, t: this.ty(pa.typeDescriptions.typeString, pa) });
453
+ this.ctorParams.clear();
424
454
  return { id: '__init__', name: '__init__', p, span: [p, 0, 0], params, ret: { k: 'none' }, body, decorators: [] };
425
455
  }
426
456
  // --- statements ------------------------------------------------------------------------------------------------------
@@ -539,7 +569,7 @@ class Lower {
539
569
  const f = this.fieldOf(n);
540
570
  if (f)
541
571
  return f.t.k === 'opaque' ? (/string|bytes/.test(f.sol) ? undefined : this.no(n, f.t.why)) : self(f.name, p);
542
- return { e: 'var', n: n.name, p };
572
+ return this.ctorParams.get(n.referencedDeclaration) ?? { e: 'var', n: n.name, p };
543
573
  }
544
574
  if (n.nodeType === 'IndexAccess') {
545
575
  if (this.nestedOf(n)) {
@@ -602,6 +632,8 @@ class Lower {
602
632
  return this.no(n, `${n.name} alone`);
603
633
  if (this.consts.has(n.referencedDeclaration))
604
634
  return this.consts.get(n.referencedDeclaration);
635
+ if (this.ctorParams.has(n.referencedDeclaration))
636
+ return this.ctorParams.get(n.referencedDeclaration);
605
637
  const f = this.fieldOf(n);
606
638
  if (f)
607
639
  return f.t.k === 'opaque' ? { e: 'opaque', p, why: `${n.name}: ${f.t.why}` } : self(f.name, p);
@@ -793,11 +825,18 @@ const hasReturn = (ss) => ss.some(s => s.s === 'ret' || (s.s === 'if' && (hasRet
793
825
  const abiType = (ts) => (ts.startsWith('address') ? 'address' : ts.startsWith('enum ') ? 'uint8' : ts.startsWith('contract ') ? 'address' : ts.replace(/ (storage|memory|calldata).*$/, ''));
794
826
  // --- the front end ---------------------------------------------------------------------------------------------------
795
827
  export function readSolidity(file, o = {}, reenter = false, compiled) {
796
- const c = compiled ?? compile(file, o);
828
+ const c = compiled ?? concreteSolidity(file, o, compile(file, o), compile);
797
829
  const L = new Lower(c, file, reenter);
798
- const entry = typeof o.entry === 'string' ? o.entry : undefined;
799
- const { mod, meta } = L.module(entry);
800
- return { mod, meta, c };
830
+ const entry = c.harness?.entry ?? (typeof o.entry === 'string' ? o.entry : undefined);
831
+ try {
832
+ const { mod, meta } = L.module(entry, o.methods ?? c.harnessMethods);
833
+ return { mod, meta, c };
834
+ }
835
+ catch (e) {
836
+ if (e instanceof Refusal && c.harness)
837
+ throw new SolidityHarnessRefusal(e, c.harness);
838
+ throw e;
839
+ }
801
840
  }
802
841
  export function extractSolidity(at, opts = {}) {
803
842
  const file = pathOf(at);
@@ -807,10 +846,11 @@ export function extractSolidity(at, opts = {}) {
807
846
  }
808
847
  catch (e) {
809
848
  if (e instanceof Refusal)
810
- return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: [] };
849
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes: e instanceof SolidityHarnessRefusal ? e.harness.notes : [], ...(e instanceof SolidityHarnessRefusal ? { harness: e.harness } : {}) };
811
850
  throw e;
812
851
  }
813
852
  const { mod, meta, c } = r;
853
+ const info = c.harness ? { harness: c.harness } : {};
814
854
  const out = c.contracts[meta.source]?.[meta.contract];
815
855
  const harness = (read) => {
816
856
  read.arms.length = 0;
@@ -831,16 +871,21 @@ export function extractSolidity(at, opts = {}) {
831
871
  const havoc = Object.fromEntries(meta.fields.filter(f => meta.nested.includes(f.name)).map(f => [f.name, f.t.val.k === 'bool' ? 'bool' : 'int']));
832
872
  const o = { ...opts, methods, share: opts.share ?? true, strict: true, onError: 'discard', entry: meta.contract, check: { probes: 'writes', ...opts.check }, answers: { ...havoc, ...opts.answers } };
833
873
  // extractStep's run, the width's param fixed for the check's own draws (2^52: the proof is for every width)
834
- const notes = [];
874
+ const notes = [...c.harness?.notes ?? []];
835
875
  let read;
836
876
  try {
837
877
  read = readStep(mod, o);
838
878
  }
839
879
  catch (e) {
840
880
  if (e instanceof Refusal)
841
- return { ok: false, refusals: [{ where: e.where, what: e.what }], notes };
881
+ return { ok: false, refusals: [{ where: e.where, what: e.what }], notes, ...info };
842
882
  throw e;
843
883
  }
884
+ // Constructor argument bounds name the state width; before an object exists that is its initial parameter.
885
+ // Keep the bound, but bind it in the parameter-only precondition rather than leaving a state reference there.
886
+ const widthInit = read.model.init[MOD];
887
+ if (widthInit?.s === 'num')
888
+ read.model.pre = substN(read.model.pre, MOD, widthInit.e);
844
889
  const w = read.model.params.find(v => v.name.startsWith(MOD));
845
890
  if (w)
846
891
  w.derived = { op: 'const', v: CHECK_W };
@@ -852,11 +897,11 @@ export function extractSolidity(at, opts = {}) {
852
897
  const unsigned = Object.fromEntries([...read.model.inputs, ...read.model.params].filter(v => read.ints[v.name] && !read.ints[v.name].signed).map(v => [v.name, 'nat']));
853
898
  const x = fromModel(read.model, mod.file, { ...unsigned, ...o.domains }, notes, (rule, sorts) => checkStep(harness(read), read, rule, sorts, o));
854
899
  if (!x.ok)
855
- return { ...x, read, names: stepNames(read) };
900
+ return { ...x, ...info, read, names: stepNames(read) };
856
901
  // (a run that breaks a law, from the prover at any width: replayed on the code at the check's before it is shown)
857
902
  if (!meta.calls || opts.reentrant === false) {
858
903
  const rp = replayer({ rule: x.rule, sorts: x.sorts, model: read.model, names: stepNames(read), leaves: read.leaves, hello: harness(read).hello.sol, ctor: read.ctor, replay: compileReplay(opts), opts });
859
- return { ...x, read, names: stepNames(read), replay: (run, law) => rp(run, law) };
904
+ return { ...x, ...info, read, names: stepNames(read), replay: (run, law) => rp(run, law) };
860
905
  }
861
906
  // The rule the laws are proven of: every call into other code a point where any of the contract's calls may run.
862
907
  let re, rread;
@@ -866,14 +911,17 @@ export function extractSolidity(at, opts = {}) {
866
911
  }
867
912
  catch (e) {
868
913
  if (e instanceof Refusal)
869
- return { ok: false, refusals: [{ where: e.where, what: `re-entrancy: ${e.what}` }], notes: [...x.notes] };
914
+ return { ok: false, refusals: [{ where: e.where, what: `re-entrancy: ${e.what}` }], notes: [...x.notes], ...info };
870
915
  throw e;
871
916
  }
917
+ const reWidthInit = rread.model.init[MOD];
918
+ if (reWidthInit?.s === 'num')
919
+ rread.model.pre = substN(rread.model.pre, MOD, reWidthInit.e);
872
920
  const rw = rread.model.params.find(v => v.name.startsWith(MOD));
873
921
  if (rw)
874
922
  rw.derived = { op: 'const', v: CHECK_W };
875
923
  rread.model.notes.push(...boundaryNotes(meta), `re-entrancy: each call into other code (${re.meta.resumes.map(r => r.replace(/\$resume$/, '')).join(', ')}) is two steps, any of the contract's calls between them (a callee that calls back); a law about the state holds where no call is pending (pending$ == 0)`);
876
- const rnotes = [];
924
+ const rnotes = [...c.harness?.notes ?? []];
877
925
  // The check of the re-entrant rule: its own random runs (calls inside calls, by any address) replayed on the code,
878
926
  // every address an Agent that makes the run's calls from inside the call it receives.
879
927
  let replays;
@@ -903,7 +951,7 @@ export function extractSolidity(at, opts = {}) {
903
951
  });
904
952
  if (rx.ok)
905
953
  rx.notes.push(`re-entrancy: checked by ${runs.runs} runs of the rule replayed on the code (${runs.txs} transactions, ${runs.nested} calls made from inside another, ${runs.steps} steps), an Agent at every address making each call from inside the one it receives`);
906
- return { ...rx, read: rread, names: stepNames(rread), quiet: 'pending$', ...(replays ? { replay: (run, law) => replays(run, law) } : {}) };
954
+ return { ...rx, ...info, read: rread, names: stepNames(rread), quiet: 'pending$', ...(replays ? { replay: (run, law) => replays(run, law) } : {}) };
907
955
  }
908
956
  function compileReplay(o) {
909
957
  const c = compile(asset('sol/Replay.sol'), { ...o, root: asset('sol/') });
@@ -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
+ }