gdp-wired 0.45.0 → 0.46.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 (120) hide show
  1. package/README.md +58 -7
  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 +3 -0
  10. package/dist/core/cli.js +204 -38
  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.d.ts +1 -4
  27. package/dist/core/effect.js +1 -15
  28. package/dist/core/exists.d.ts +1 -0
  29. package/dist/core/exists.js +191 -16
  30. package/dist/core/extract-c.d.ts +2 -0
  31. package/dist/core/extract-c.js +169 -22
  32. package/dist/core/extract-check.d.ts +1 -0
  33. package/dist/core/extract-check.js +66 -0
  34. package/dist/core/extract-go-check.d.ts +1 -1
  35. package/dist/core/extract-go-check.js +2 -1
  36. package/dist/core/extract-go.d.ts +1 -0
  37. package/dist/core/extract-go.js +38 -4
  38. package/dist/core/extract-ir.d.ts +1 -0
  39. package/dist/core/extract-ir.js +15 -0
  40. package/dist/core/extract-jvm.d.ts +1 -1
  41. package/dist/core/extract-jvm.js +2 -0
  42. package/dist/core/extract-orm.d.ts +12 -0
  43. package/dist/core/extract-orm.js +244 -0
  44. package/dist/core/extract-print.js +20 -1
  45. package/dist/core/extract-py.d.ts +1 -0
  46. package/dist/core/extract-py.js +1 -1
  47. package/dist/core/extract-read.d.ts +17 -0
  48. package/dist/core/extract-read.js +5 -5
  49. package/dist/core/extract-rs.js +5 -1
  50. package/dist/core/extract-shapes.js +2 -0
  51. package/dist/core/extract-sol.d.ts +10 -1
  52. package/dist/core/extract-sol.js +70 -22
  53. package/dist/core/extract-step.d.ts +151 -1
  54. package/dist/core/extract-step.js +1232 -60
  55. package/dist/core/extract-swift.js +6 -2
  56. package/dist/core/extract.d.ts +8 -0
  57. package/dist/core/extract.js +61 -5
  58. package/dist/core/fiber-run.d.ts +5 -0
  59. package/dist/core/fiber-run.js +18 -0
  60. package/dist/core/infer.d.ts +4 -1
  61. package/dist/core/infer.js +918 -217
  62. package/dist/core/jvm/JavaReader.java +23 -6
  63. package/dist/core/jvm/Jvm.java +3 -0
  64. package/dist/core/jvm/KtReader.java +6 -5
  65. package/dist/core/laws.d.ts +10 -3
  66. package/dist/core/laws.js +193 -14
  67. package/dist/core/machine.d.ts +15 -1
  68. package/dist/core/machine.js +187 -15
  69. package/dist/core/nonterm.js +14 -1
  70. package/dist/core/orm/harness.js +61 -0
  71. package/dist/core/orm-fixtures/schema.prisma +5 -0
  72. package/dist/core/py/harness.py +183 -10
  73. package/dist/core/py/reader.py +234 -40
  74. package/dist/core/reader-fixtures/README.md +28 -0
  75. package/dist/core/reader-fixtures/c-693042.cpp +8 -0
  76. package/dist/core/reader-fixtures/go-685506.go +14 -0
  77. package/dist/core/reader-fixtures/jvm-724362.kt +8 -0
  78. package/dist/core/reader-fixtures/jvm-737430.kt +7 -0
  79. package/dist/core/reader-fixtures/jvm-765282.kt +3 -0
  80. package/dist/core/reader-fixtures/swift-735726.swift +15 -0
  81. package/dist/core/reader-fixtures/swift-735990.swift +15 -0
  82. package/dist/core/reader-fixtures/swift-739158.swift +4 -0
  83. package/dist/core/reader-fixtures/swift-744834.swift +15 -0
  84. package/dist/core/reader-fixtures/swift-746946.swift +31 -0
  85. package/dist/core/reader-fixtures/typescript-673062.ts.txt +2 -0
  86. package/dist/core/relation.d.ts +1 -1
  87. package/dist/core/relation.js +29 -2
  88. package/dist/core/relational.js +4 -2
  89. package/dist/core/rs/src/main.rs +8 -2
  90. package/dist/core/sample-cache.d.ts +8 -0
  91. package/dist/core/sample-cache.js +46 -0
  92. package/dist/core/security.d.ts +38 -0
  93. package/dist/core/security.js +88 -0
  94. package/dist/core/sol/harness.py +57 -4
  95. package/dist/core/sol-concrete.d.ts +23 -0
  96. package/dist/core/sol-concrete.js +195 -0
  97. package/dist/core/solver.js +3 -1
  98. package/dist/core/swift/Sources/gdp-swiftreader/main.swift +50 -7
  99. package/dist/core/system.js +1 -1
  100. package/dist/core/transfer.js +22 -9
  101. package/dist/core/translate.js +39 -10
  102. package/dist/core/watch.js +50 -5
  103. package/dist/interchange/format.js +11 -1
  104. package/dist/kernel/cdcl.d.ts +5 -0
  105. package/dist/kernel/cdcl.js +56 -9
  106. package/dist/kernel/epr.js +108 -26
  107. package/dist/kernel/kernel.d.ts +29 -1
  108. package/dist/kernel/kernel.js +325 -62
  109. package/dist/kernel/model-sequence.d.ts +3 -0
  110. package/dist/kernel/model-sequence.js +34 -0
  111. package/dist/kernel/prove.d.ts +10 -3
  112. package/dist/kernel/prove.js +332 -71
  113. package/dist/kernel/reader.d.ts +3 -0
  114. package/dist/kernel/reader.js +101 -14
  115. package/dist/kernel/share.d.ts +1 -0
  116. package/dist/kernel/share.js +27 -0
  117. package/dist/lean-kernel/emit.js +30 -37
  118. package/dist/lean-kernel/lean-terms.js +5 -0
  119. package/dist/lean-kernel/library.js +10 -10
  120. package/package.json +6 -1
@@ -52,6 +52,46 @@ export function clangDump(file, flags, clang = 'clang', cpp = false, filter) {
52
52
  const defs = run([...lang, ...flags, '-dM', '-E', '/dev/null']), def = (k) => Number(new RegExp(`#define ${k} (\\d+)`).exec(defs)?.[1] ?? 0);
53
53
  return { tu, target: { int: def('__SIZEOF_INT__') * 8, long: def('__SIZEOF_LONG__') * 8, short: def('__SIZEOF_SHORT__') * 8, llong: def('__SIZEOF_LONG_LONG__') * 8, charUnsigned: /#define __CHAR_UNSIGNED__/.test(defs) } };
54
54
  }
55
+ // The values of names a law reads that the code defines as integer constants (a macro, an enum constant, a constexpr
56
+ // variable), folded by clang itself: each the value of an enumerator of a probe that includes the file. A name that
57
+ // isn't one (a field, a float, a string) doesn't compile there and is left out.
58
+ export function constantsOf(file, flags, clang, cpp, names) {
59
+ const fs = node('node:fs'), os = node('node:os'), path = node('node:path'), cp = node('node:child_process');
60
+ let left = [...new Set(names)].filter(n => /^[A-Za-z_]\w*(::[A-Za-z_]\w*)*$/.test(n) && (cpp || !n.includes('::')));
61
+ if (!left.length)
62
+ return {};
63
+ const work = fs.mkdtempSync(`${os.tmpdir()}/gdp-cconst-`), probe = `${work}/probe.${cpp ? 'cpp' : 'c'}`, out = {};
64
+ try {
65
+ for (let round = 0; round < 3 && left.length; round++) {
66
+ fs.writeFileSync(probe, `#include ${JSON.stringify(path.resolve(file))}\n${left.map((n, i) => `enum gdp_k${i}_e ${cpp ? ': long long ' : ''}{ gdp_k${i} = (${n}) };`).join('\n')}\n`);
67
+ let dump = '';
68
+ try {
69
+ dump = cp.execFileSync(clang, [...(cpp ? ['-x', 'c++'] : ['-x', 'c']), ...flags, '-w', '-ferror-limit=0', '-Xclang', '-ast-dump=json', '-Xclang', '-ast-dump-filter=gdp_k', '-fsyntax-only', probe], { encoding: 'utf8', maxBuffer: 1 << 28, stdio: ['ignore', 'pipe', 'pipe'], ...readerRun() });
70
+ }
71
+ catch (e) {
72
+ // (the lines that don't compile: their names left out, the rest tried again)
73
+ const bad = new Set([...String(e.stderr ?? '').matchAll(/probe\.c(?:pp)?:(\d+):\d+: error/g)].map(m => Number(m[1]) - 2));
74
+ if (!bad.size)
75
+ return out;
76
+ left = left.filter((_, i) => !bad.has(i));
77
+ continue;
78
+ }
79
+ for (const m of dump.matchAll(/"kind":\s*"EnumConstantDecl"[^]*?"name":\s*"gdp_k(\d+)"[^]*?"value":\s*"(-?\d+)"/g)) {
80
+ const v = Number(m[2]);
81
+ if (Number.isSafeInteger(v))
82
+ out[left[Number(m[1])]] = v;
83
+ }
84
+ break;
85
+ }
86
+ return out;
87
+ }
88
+ finally {
89
+ try {
90
+ fs.rmSync(work, { recursive: true, force: true });
91
+ }
92
+ catch { /* gone */ }
93
+ }
94
+ }
55
95
  // The project's flags for a file: from a compile_commands.json (its -I, -D, -std, -include and -f options), or given.
56
96
  export function flagsFor(file, compileCommands) {
57
97
  if (!compileCommands)
@@ -101,9 +141,13 @@ function locate(root) {
101
141
  n.$b = at(n.range.begin);
102
142
  n.$e = at(n.range.end);
103
143
  }
104
- else if (k === 'inner')
144
+ // (doc comments, FullComment and its parts, are no code)
145
+ // (a for's absent parts are empty objects, kind-less)
146
+ else if (k === 'inner') {
147
+ n.inner = n.inner.filter(c => !(c.kind ?? '').endsWith('Comment'));
105
148
  for (const c of n.inner)
106
149
  walk(c);
150
+ }
107
151
  }
108
152
  n.$at ??= n.$b;
109
153
  };
@@ -116,7 +160,9 @@ const FAIL = { abort: 'abort()', __assert_rtn: 'an assertion failing', __assert_
116
160
  // (`root`: the project's own files, whose functions are read too: a static inline helper of its header; by default the
117
161
  // file's directory)
118
162
  // (`picks`: an overloaded method's arity, the one read: `functions: ['throttle/1']`)
119
- export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
163
+ // (leave: globals the rule leaves out, an output the code writes for other code, never read into what it keeps)
164
+ // (cut: the file's own functions a call of which the request answers, as another file's)
165
+ export function readC(file, entry, tu, target, cpp = false, root, picks = {}, pickNames = [], leave = [], cut = []) {
120
166
  const path = node('node:path'), fs = node('node:fs');
121
167
  const main = path.resolve(file), base = path.basename(file), dir = `${path.resolve(root ?? main.replace(/\/[^/]*$/, ''))}/`, srcs = new Map();
122
168
  locate(tu);
@@ -136,12 +182,19 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
136
182
  const text = (n) => (n.$b && n.$e && n.$b.file === n.$e.file && own(n) && n.$e.off + n.$e.tok >= n.$b.off ? src(n.$b.file).slice(n.$b.off, n.$e.off + n.$e.tok) || n.kind : n.kind);
137
183
  // The declarations: typedefs, records and enums of every file (a header's types are the file's too), the globals.
138
184
  const typedefs = new Map(), records = new Map(), tags = new Map(), anon = new Map();
139
- const members = new Map(), fieldNode = new Map(), enums = new Map(), cxx = [];
140
- const enumConst = new Map(), globals = new Map(), fields = new Map(), recName = new Map();
185
+ const members = new Map(), fieldNode = new Map(), enums = new Map(), enumById = new Map(), cxx = [];
186
+ const enumConst = new Map(), named = new Map(), globals = new Map(), fields = new Map(), recName = new Map();
141
187
  const declOf = (n) => n.decl ?? (n.inner ?? []).map(declOf).find(Boolean);
142
188
  const visitDecl = (n) => {
143
189
  if (n.kind === 'TypedefDecl' && n.name) {
144
190
  const d = declOf(n);
191
+ // (a typedef of an unnamed enum names it: clang 21 spells it `enum state_t`, desugared to the typedef's own name)
192
+ const en = d?.kind === 'EnumDecl' ? enumById.get(d.id) : undefined;
193
+ if (en && !en.name) {
194
+ for (const q of [n.name, `enum ${n.name}`])
195
+ enums.set(q, en);
196
+ return;
197
+ }
145
198
  typedefs.set(n.name, { qual: n.type.qualType, ...(n.type.desugaredQualType ? { desug: n.type.desugaredQualType } : {}), ...(d && (d.kind === 'RecordDecl' || d.kind === 'CXXRecordDecl') ? { rec: d.id } : {}) });
146
199
  if (d && !recName.has(d.id))
147
200
  recName.set(d.id, n.name);
@@ -178,6 +231,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
178
231
  }
179
232
  }
180
233
  else if (n.kind === 'EnumDecl') {
234
+ enumById.set(n.id, n);
181
235
  if (n.name)
182
236
  for (const q of [n.name, ...(n.$outer ? [`${n.$outer}::${n.name}`] : []), `enum ${n.name}`])
183
237
  enums.set(q, n);
@@ -187,6 +241,8 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
187
241
  const k = c.inner?.length ? fold(c.inner[0]) : undefined;
188
242
  v = k ?? v + 1;
189
243
  enumConst.set(c.id, v);
244
+ if (c.name)
245
+ named.set(c.name, named.has(c.name) && named.get(c.name) !== v ? NaN : v);
190
246
  }
191
247
  }
192
248
  else if (n.kind === 'VarDecl')
@@ -290,7 +346,9 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
290
346
  if (r.tagUsed === 'union')
291
347
  return add(key, { k: 'union', go });
292
348
  const t = add(key, { k: 'struct', own: true, name: go, go, fields: [] });
293
- ttab[t].fields = (r.inner ?? []).filter(f => f.kind === 'FieldDecl').map(f => ({ name: f.name ?? '', t: tyOf(f.type), embedded: false }));
349
+ // (a void * field: a flag where the code only sets it to NULL or not and tests it against NULL, CANopen's CO_FLAG;
350
+ // any other use of it refused where it is)
351
+ ttab[t].fields = (r.inner ?? []).filter(f => f.kind === 'FieldDecl').map(f => { const ft = tyOf(f.type), pt = T(ft); return { name: f.name ?? '', t: pt.k === 'ptr' && T(pt.elem).k === 'void' ? add(`nullflag:${f.type.qualType}`, { k: 'bool', go: f.type.qualType, nullflag: true }) : ft, embedded: false }; });
294
352
  return t;
295
353
  };
296
354
  function tyOf(ty) { return parseT(ty.qualType, ty.desugaredQualType); }
@@ -301,6 +359,12 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
301
359
  const arr = /^(.*?)\s*\[(\d+)\]$/.exec(s);
302
360
  if (arr)
303
361
  return add(`arr:${s}`, { k: 'array', go: s, elem: parseT(arr[1]), len: Number(arr[2]), fixed: true });
362
+ // (an unnamed struct's spelling, `struct (unnamed struct at f.c:3:8)`, is no function type)
363
+ const un0 = /^(struct|union|class) \((?:unnamed|anonymous) (?:struct|union|class) at .*:(\d+):(\d+)\)$/.exec(s);
364
+ if (un0) {
365
+ const id = anon.get(`${un0[2]}:${un0[3]}`);
366
+ return id ? recT(id) : add(`opaque:${s}`, { k: 'opaque', go: s });
367
+ }
304
368
  if (/\(\*\)|\(.*\)$/.test(s))
305
369
  return add(`fn:${s}`, { k: 'func', go: s });
306
370
  if (/\*$/.test(s)) {
@@ -353,6 +417,19 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
353
417
  const enumT = (s) => {
354
418
  const d = enums.get(s), vals = (d?.inner ?? []).filter(c => c.kind === 'EnumConstantDecl').map(c => enumConst.get(c.id) ?? 0);
355
419
  const fixed = d?.fixedUnderlyingType?.qualType, ft = fixed ? T(parseT(fixed)) : undefined;
420
+ // (C++, no fixed type: its values are those of the smallest bit-field holding every enumerator, another one
421
+ // undefined to make, the sanitizer's trap where it is read)
422
+ if (cpp && !ft) {
423
+ const lo = Math.min(0, ...vals), hi = Math.max(0, ...vals);
424
+ let b = 1;
425
+ if (lo < 0)
426
+ while (-(2 ** (b - 1)) > lo || hi > 2 ** (b - 1) - 1)
427
+ b++;
428
+ else
429
+ while (hi > 2 ** b - 1)
430
+ b++;
431
+ return add(`int:${s}`, { k: 'int', go: s, bits: b, signed: lo < 0, ub: true });
432
+ }
356
433
  return intT(s, ft?.bits ?? target.int, ft ? ft.signed : vals.some(v => v < 0));
357
434
  };
358
435
  for (const n of top)
@@ -399,10 +476,71 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
399
476
  overloaded.add(m.name);
400
477
  funcs.set(m.name, m);
401
478
  }
402
- const entryT = entryRec ? recT(entryRec, entry) : refuse(undefined, `no ${cpp ? 'class' : 'struct'} ${entry} in ${base}${cpp ? ' (a class template is outside the subset)' : ''}`);
479
+ // The file's globals as the state (C, the entry the file's stem, no struct of that name): each global its functions
480
+ // read or write a field of one object, `this`, every function of the file a method of it. A global the functions
481
+ // only read that the file doesn't own (extern, volatile, or another file's to write: not static) is the request's:
482
+ // the value each request finds there, set by the check before the call (read once a request).
483
+ const stem = base.replace(/\.[^.]*$/, ''), gmode = !entryRec && !cpp && entry === stem;
484
+ const gfield = new Map(), ginput = new Set(), gnodes = [], fnReads = new Map(), left = new Set();
485
+ if (gmode) {
486
+ const reads = new Set(), writes = new Set(), all = new Set();
487
+ const bare = (n) => ((n.kind === 'ParenExpr' || CAST.has(n.kind) && ['LValueToRValue', 'NoOp'].includes(n.castKind)) && n.inner?.length ? bare(n.inner[0]) : n);
488
+ const root = (n0) => { const n = bare(n0); return n.kind === 'DeclRefExpr' ? n : n.kind === 'MemberExpr' || n.kind === 'ArraySubscriptExpr' ? root(n.inner[0]) : (CAST.has(n.kind) && n.castKind === 'ArrayToPointerDecay') ? root(n.inner[0]) : undefined; };
489
+ const scan = (n) => {
490
+ const w = n.kind === 'BinaryOperator' && n.opcode === '=' || n.kind === 'CompoundAssignOperator' ? root(n.inner[0]) : n.kind === 'UnaryOperator' && ['++', '--', '&'].includes(n.opcode) ? root(n.inner[0]) : undefined;
491
+ const d = w?.referencedDecl;
492
+ if (d?.kind === 'VarDecl' && globals.has(d.id))
493
+ writes.add(d.id);
494
+ if (n.kind === 'DeclRefExpr' && n.referencedDecl?.kind === 'VarDecl' && globals.has(n.referencedDecl.id)) {
495
+ reads.add(n.referencedDecl.id);
496
+ all.add(n.referencedDecl.id);
497
+ }
498
+ for (const c of n.inner ?? [])
499
+ scan(c);
500
+ };
501
+ for (const [name, f] of funcs) {
502
+ const r0 = new Set(reads);
503
+ reads.clear();
504
+ scan(f);
505
+ fnReads.set(name, new Set(reads));
506
+ for (const id of r0)
507
+ reads.add(id);
508
+ }
509
+ // (and the functions each one calls, read through)
510
+ const callees = (f, out = new Set()) => { const w = (n) => { if (n.kind === 'DeclRefExpr' && n.referencedDecl?.kind === 'FunctionDecl' && funcs.has(n.referencedDecl.name) && !out.has(n.referencedDecl.name)) {
511
+ out.add(n.referencedDecl.name);
512
+ w(funcs.get(n.referencedDecl.name));
513
+ } for (const c of n.inner ?? [])
514
+ w(c); }; w(f); return out; };
515
+ for (const [name, f] of funcs)
516
+ for (const g of callees(f))
517
+ for (const id of fnReads.get(g) ?? [])
518
+ fnReads.get(name).add(id);
519
+ for (const [id, g] of globals) {
520
+ if (!all.has(id))
521
+ continue;
522
+ if (leave.includes(g.name)) {
523
+ left.add(id);
524
+ continue;
525
+ }
526
+ const qt = g.type.qualType;
527
+ if (/^const /.test(qt) && !writes.has(id))
528
+ continue;
529
+ if (/\[\]$/.test(qt.trim()))
530
+ refuse(g, `${g.name}: an array of unknown size (its length is another file's)`);
531
+ if (!writes.has(id) && (g.storageClass === 'extern' || /\bvolatile\b/.test(qt) || g.storageClass !== 'static'))
532
+ ginput.add(id);
533
+ gfield.set(id, gnodes.length);
534
+ gnodes.push(g);
535
+ }
536
+ if (!gnodes.length)
537
+ refuse(undefined, `no global of ${base} its functions read or write (the state, when the file keeps it in globals)`);
538
+ }
539
+ const entryT = entryRec ? recT(entryRec, entry) : gmode ? add(`globals:${entry}`, { k: 'struct', own: true, name: entry, go: 'gdp_G', fields: gnodes.map(g => ({ name: g.name, t: tyOf(g.type), embedded: false })) }) : refuse(undefined, `no ${cpp ? 'class' : 'struct'} ${entry} in ${base}${cpp ? ' (a class template is outside the subset)' : ''}${!cpp && entry !== stem ? ` (a file that keeps its state in globals: name ${stem}, its stem)` : ''}`);
540
+ const ptrT = add(`ptr:${entryT}`, { k: 'ptr', go: `${entry} *`, elem: entryT }), self0 = (n) => ({ e: 'id', ...at(n, ptrT), o: 'var', id: 'this', n: 'this' });
403
541
  // An out-parameter (a pointer to an integer or a bool, not the receiver): a pointer to a box of one field, `value`,
404
542
  // *p its field.
405
- const boxed = new Map(), byValue = new Map(), refs = new Set();
543
+ const boxed = new Map(), byValue = new Map(), refs = new Set(), structRefs = new Set();
406
544
  const boxOf = (q) => {
407
545
  // (a const reference to an integer is its value: an input)
408
546
  if (/^const [^*&]*&$/.test(q.type.qualType.trim())) {
@@ -411,6 +549,13 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
411
549
  return v;
412
550
  }
413
551
  const ref = /[^&]&$/.test(q.type.qualType.trim()), t = ref ? parseT(q.type.qualType.trim().slice(0, -1), q.type.desugaredQualType?.trim().replace(/&$/, '')) : tyOf(q.type), pt = ref ? { k: 'ptr', elem: t, go: q.type.qualType } : T(t);
552
+ // (C++: a reference to a struct, the caller's object, read as a pointer to it)
553
+ if (ref && T(t).k === 'struct') {
554
+ const r = add(`ref:${t}`, { k: 'ptr', go: q.type.qualType, elem: t });
555
+ byValue.set(q.id, r);
556
+ structRefs.add(q.id);
557
+ return r;
558
+ }
414
559
  if (pt.k !== 'ptr' || !['int', 'bool'].includes(T(pt.elem).k))
415
560
  return tyOf(q.type);
416
561
  if (ref)
@@ -420,9 +565,10 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
420
565
  return bp;
421
566
  };
422
567
  const THIS = { kind: 'ParmVarDecl', id: 'this', name: 'this', type: { qualType: `${entry} *` } };
423
- const recvOf = (f) => { if (f.$m)
568
+ const recvOf = (f) => { if (gmode)
569
+ return THIS; if (f.$m)
424
570
  return f.storageClass === 'static' ? undefined : THIS; const p = params(f)[0], t = p ? T(tyOf(p.type)) : undefined; return t?.k === 'ptr' && t.elem === entryT ? p : undefined; };
425
- const args0 = (f) => (f.$m ? params(f) : params(f).slice(recvOf(f) ? 1 : 0));
571
+ const args0 = (f) => (f.$m || gmode ? params(f) : params(f).slice(recvOf(f) ? 1 : 0));
426
572
  for (const f of [...funcs.values(), ...ctors])
427
573
  for (const q of args0(f))
428
574
  boxOf(q);
@@ -461,9 +607,30 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
461
607
  return !!n.type && T(tyOf(n.type)).signed === false;
462
608
  };
463
609
  const calleeName = (n) => { const c = strip(n.inner[0]); const d = (c.kind === 'ImplicitCastExpr' ? strip(c.inner[0]) : c).referencedDecl; return d?.kind === 'FunctionDecl' ? d.name : undefined; };
610
+ // (a pointer flag's field, read where a flag is: tested, compared with NULL)
611
+ const flagOf = (n0) => { let n = strip(n0); while (CAST.has(n.kind) && ['BitCast', 'NoOp', 'LValueToRValue'].includes(n.castKind))
612
+ n = strip(n.inner[0]); const f = n.kind === 'MemberExpr' ? fields.get(n.referencedMemberDecl) : undefined; return f && T(T(recT(f.rec)).fields[f.i].t).nullflag ? n : undefined; };
613
+ const isNull = (n0) => { const n = strip(n0); return (CAST.has(n.kind) && (n.castKind === 'NullToPointer' || ((n.castKind === 'IntegralToPointer' || n.castKind === 'BitCast') && isNull(n.inner[0])))) || fold(n) === 0 || n.kind === 'CXXNullPtrLiteralExpr' || n.kind === 'GNUNullExpr'; };
614
+ let flagRead = false;
615
+ const readFlag = (n) => { flagRead = true; try {
616
+ return x(n);
617
+ }
618
+ finally {
619
+ flagRead = false;
620
+ } };
464
621
  // A condition: a boolean as it is; a number compared with 0; a pointer with NULL.
465
622
  const cond = (n0) => {
466
623
  const n = strip(n0);
624
+ const fl = flagOf(n.kind === 'ImplicitCastExpr' && n.castKind === 'PointerToBoolean' ? n.inner[0] : n);
625
+ if (fl)
626
+ return readFlag(fl);
627
+ if (n.kind === 'BinaryOperator' && (n.opcode === '==' || n.opcode === '!=') && (flagOf(n.inner[0]) || flagOf(n.inner[1]))) {
628
+ const [f, o] = flagOf(n.inner[0]) ? [flagOf(n.inner[0]), n.inner[1]] : [flagOf(n.inner[1]), n.inner[0]];
629
+ if (!isNull(o))
630
+ return no(n, `${text(n)}: a pointer flag compared with other than NULL`);
631
+ const v = readFlag(f);
632
+ return n.opcode === '!=' ? v : { e: 'un', ...at(n, boolT), op: '!', x: v };
633
+ }
467
634
  if (n.kind === 'CallExpr' && calleeName(n) === '__builtin_expect')
468
635
  return cond(n.inner[1]);
469
636
  if ((n.kind === 'ImplicitCastExpr' || n.kind === 'CStyleCastExpr') && ['IntegralCast', 'IntegralToBoolean', 'PointerToBoolean'].includes(n.castKind) && isBoolish(n.inner[0]))
@@ -471,7 +638,7 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
471
638
  if (n.kind === 'BinaryOperator' && CMP.has(n.opcode))
472
639
  return { e: 'bin', ...at(n, boolT), op: n.opcode, x: x(n.inner[0]), y: x(n.inner[1]) };
473
640
  if (n.kind === 'BinaryOperator' && (n.opcode === '&&' || n.opcode === '||'))
474
- return { e: 'bin', ...at(n, boolT), op: n.opcode, x: cond(n.inner[0]), y: cond(n.inner[1]) };
641
+ return { e: 'bin', ...at(n, boolT), op: n.opcode, x: cond(n.inner[0]), y: guard(() => cond(n.inner[1])) };
475
642
  if (n.kind === 'UnaryOperator' && n.opcode === '!')
476
643
  return { e: 'un', ...at(n, boolT), op: '!', x: cond(n.inner[0]) };
477
644
  const v = (n.kind === 'ImplicitCastExpr' && (n.castKind === 'IntegralToBoolean' || n.castKind === 'PointerToBoolean')) ? n.inner[0] : n, vt = v.type ? tyOf(v.type) : -1;
@@ -486,8 +653,107 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
486
653
  return { e: 'bin', ...at(n, boolT), op: '!=', x: x(v), y: lit(n, 0, vt) };
487
654
  return no(n, `${text(n)}: a condition of type ${n.type?.qualType}`);
488
655
  };
656
+ // A side effect inside an expression (an assignment, ++ or --, `if (--timer > 0)`): its statement run before the
657
+ // statement it is in, the expression its value; where it runs only on some paths (the right of && or ||, a branch of
658
+ // ?:), refused.
659
+ let pending, guarded = 0, temps = 0;
660
+ const guard = (f) => { guarded++; try {
661
+ return f();
662
+ }
663
+ finally {
664
+ guarded--;
665
+ } };
666
+ const effect = (n, value, before = []) => {
667
+ if (!pending || guarded)
668
+ return no(n, `${text(n)}: ${guarded ? 'a side effect on some paths of an expression (the right of && or ||, a branch of ?:)' : 'a side effect inside an expression (the subset reads it as a statement)'}`);
669
+ pending.push(...before, ...st(n));
670
+ return value();
671
+ };
672
+ const pre = (f) => { const outer = pending, og = guarded; pending = []; guarded = 0; try {
673
+ const v = f();
674
+ return [pending, v];
675
+ }
676
+ finally {
677
+ pending = outer;
678
+ guarded = og;
679
+ } };
680
+ // (a float's value: left out, a value nothing the rule keeps may read; one read into an integer, a condition or a
681
+ // comparison is refused there. Its operands are the code's measurements: an assignment or a call of the file's own
682
+ // inside it is refused, its effect would be lost.)
683
+ // A constant table read at indices (a transition table, a lookup; a const or constexpr array, a class's static one):
684
+ // its entry by cases on the indices, each index outside its dimension undefined behavior, the step's failure (checked
685
+ // before the statement, so the index must be free of side effects and read where the statement surely reads it).
686
+ const table = (n) => {
687
+ const idx = [];
688
+ let b = n;
689
+ while (b.kind === 'ArraySubscriptExpr') {
690
+ idx.unshift(b.inner[1]);
691
+ b = strip(b.inner[0]);
692
+ if (CAST.has(b.kind) && b.castKind === 'ArrayToPointerDecay')
693
+ b = strip(b.inner[0]);
694
+ }
695
+ const d = b.kind === 'DeclRefExpr' ? b.referencedDecl : undefined;
696
+ if (d?.kind !== 'VarDecl' || !globals.has(d.id))
697
+ return undefined;
698
+ const g0 = globals.get(d.id), g = g0.init ? g0 : [...globals.values()].find(v => v.name === g0.name && v.init) ?? g0, qt = g.type.qualType;
699
+ if (!/^(const |constexpr )|\bconst\b/.test(qt) || !g.init)
700
+ return undefined;
701
+ const init = (g.inner ?? []).find(c => !c.kind.endsWith('Attr'));
702
+ if (!init)
703
+ return undefined;
704
+ const t = n.type ? tyOf(n.type) : -1, a = at(n, t);
705
+ // (the table's values, nested by dimension; an entry not given is 0)
706
+ const dims = [...qt.matchAll(/\[(\d+)\]/g)].map(m => Number(m[1]));
707
+ if (dims.length !== idx.length || !['int', 'bool'].includes(T(t).k))
708
+ return no(n, `${text(n)}: a table read other than at every one of its dimensions`);
709
+ const val = (v, path, k) => {
710
+ if (k === dims.length) {
711
+ const f = v ? fold(v) : 0;
712
+ return f ?? NaN;
713
+ }
714
+ const s0 = v ? strip(v) : undefined, kids = s0?.kind === 'InitListExpr' ? (s0.inner ?? []) : [];
715
+ return val(kids[path[k]], path, k + 1);
716
+ };
717
+ if (idx.some(effects))
718
+ return no(n, `${text(n)}: a table read at an index with a side effect`);
719
+ if (!pending || guarded)
720
+ return no(n, `${text(n)}: a table read on some paths of an expression (the right of && or ||, a branch of ?:)`);
721
+ const ix = idx.map(i => x(i)), ty = (i) => (ix[i].t >= 0 ? ix[i].t : intT('int', target.int, true));
722
+ const inRange = ix.map((v, i) => ({ e: 'bin', ...at(idx[i], boolT), op: '&&', x: { e: 'bin', ...at(idx[i], boolT), op: '<=', x: lit(idx[i], 0, ty(i)), y: v }, y: { e: 'bin', ...at(idx[i], boolT), op: '<', x: v, y: lit(idx[i], dims[i], ty(i)) } }));
723
+ pending.push({ s: 'if', p: pos(n), c: { e: 'un', ...at(n, boolT), op: '!', x: inRange.reduce((l, r) => ({ e: 'bin', ...at(n, boolT), op: '&&', x: l, y: r })) }, then: [{ s: 'expr', p: pos(n), x: { e: 'call', ...at(n, -1), builtin: 'panic', a: [], what: `${text(n)}: an index past the table (undefined behavior)` } }] });
724
+ // (by cases: each dimension's index against each of its values, the last value the rest)
725
+ const build = (k, path) => {
726
+ if (k === dims.length) {
727
+ const v = val(init, path, 0);
728
+ if (!Number.isSafeInteger(v))
729
+ return no(n, `${text(n)}: an entry that isn't a constant integer`);
730
+ return T(t).k === 'bool' ? { e: 'lit', ...a, c: { bool: v !== 0 } } : lit(n, v, t);
731
+ }
732
+ let out = build(k + 1, [...path, dims[k] - 1]);
733
+ for (let j = dims[k] - 2; j >= 0; j--)
734
+ out = { e: 'ite', ...a, x: { e: 'bin', ...at(idx[k], boolT), op: '==', x: ix[k], y: lit(idx[k], j, ty(k)) }, y: build(k + 1, [...path, j]), b: out };
735
+ return out;
736
+ };
737
+ return build(0, []);
738
+ };
739
+ let placing = false;
740
+ // (a place in a global left out, or its address)
741
+ // (a field of the entry left out, `leave`, or anything reached through one: an object other code owns, a buffer the
742
+ // code writes for it)
743
+ const leftField = (n) => { const f = fields.get(n.referencedMemberDecl ?? ''); return !!f && f.rec === entryRec && leave.includes(String(n.name)); };
744
+ const leftOut = (n0) => { const n = strip(n0); if (n.kind === 'DeclRefExpr')
745
+ return left.has(n.referencedDecl?.id ?? ''); if (n.kind === 'MemberExpr' && leftField(n))
746
+ return true; if (n.kind === 'MemberExpr' || n.kind === 'ArraySubscriptExpr' || (n.kind === 'UnaryOperator' && n.opcode === '&') || (CAST.has(n.kind) && n.castKind === 'ArrayToPointerDecay'))
747
+ return leftOut(n.inner[0]); return false; };
748
+ const effects = (n) => (n.kind === 'CallExpr' && funcs.has(calleeName(n) ?? '')) || ['CompoundAssignOperator'].includes(n.kind) || (n.kind === 'BinaryOperator' && n.opcode === '=') || (n.kind === 'UnaryOperator' && ['++', '--'].includes(n.opcode)) || (n.inner ?? []).some(effects);
489
749
  const x = (n0) => {
490
750
  const n = strip(n0), t = n.type ? tyOf(n.type) : -1, a = at(n, t), kids = n.inner ?? [];
751
+ const asPlace = placing;
752
+ placing = false;
753
+ if ((left.size || leave.length) && leftOut(n))
754
+ return { e: 'opaque', ...a, why: `${text(n)}: left out (leave: an output for other code, never read into the rule)` };
755
+ if (t >= 0 && T(t).k === 'float' && !asPlace)
756
+ return effects(n) ? no(n, `${text(n)}: a float computed with an effect of the file's own code (floats are left out)`) : { e: 'opaque', ...a, why: `${text(n)}: a float (left out of the rule: a binary fraction that rounds)` };
491
757
  const k = t >= 0 && T(t).k === 'int' ? fold(n) : undefined;
492
758
  if (k !== undefined)
493
759
  return Number.isSafeInteger(k) ? lit(n, k, t) : no(n, `${text(n)}: the constant ${n.kind === 'IntegerLiteral' ? n.value : k} is past 2^53 (the rule's numbers stop there)`);
@@ -506,12 +772,19 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
506
772
  }
507
773
  case 'DeclRefExpr': {
508
774
  const d = n.referencedDecl;
775
+ // (a reference to the caller's struct: the object it points to)
776
+ if (d.kind === 'ParmVarDecl' && structRefs.has(d.id))
777
+ return { e: 'star', ...a, x: { e: 'id', ...a, t: byValue.get(d.id), o: 'var', id: d.id, n: d.name } };
509
778
  if (d.kind === 'ParmVarDecl') {
510
779
  const v = { e: 'id', ...a, ...(boxed.has(d.id) ? { t: boxed.get(d.id) } : {}), o: 'var', id: d.id, n: d.name };
511
780
  return refs.has(d.id) ? { e: 'sel', ...a, k: 'field', x: v, path: [0] } : v;
512
781
  }
513
782
  if (d.kind === 'VarDecl' && /&$/.test(d.type?.qualType ?? ''))
514
783
  return no(n, `${d.name}: a reference held in a local (a second name for a place)`);
784
+ if (d.kind === 'VarDecl' && gfield.has(d.id))
785
+ return { e: 'sel', ...a, k: 'field', x: self0(n), path: [gfield.get(d.id)] };
786
+ if (d.kind === 'VarDecl' && left.has(d.id))
787
+ return { e: 'opaque', ...a, why: `${d.name}: left out (leave: an output for other code, never read into the rule)` };
515
788
  if (d.kind === 'VarDecl')
516
789
  return globals.has(d.id) ? no(n, `${d.name}: a ${globals.get(d.id).storageClass === 'static' ? 'static' : 'global'} variable (state every object shares)`) : { e: 'id', ...a, o: 'var', id: d.id, n: d.name };
517
790
  if (d.kind === 'FunctionDecl')
@@ -520,6 +793,8 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
520
793
  }
521
794
  case 'MemberExpr': {
522
795
  const f = fields.get(n.referencedMemberDecl);
796
+ if (f && !flagRead && !asPlace && T(T(recT(f.rec)).fields[f.i].t).nullflag)
797
+ return no(n, `${text(n)}: a void * read as a pointer (the subset reads one as a flag: set to NULL or not, tested against NULL)`);
523
798
  if (!f)
524
799
  return no(n, `${text(n)}: a member that isn't a field of a struct read here`);
525
800
  if (records.get(f.rec).tagUsed === 'union')
@@ -548,6 +823,10 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
548
823
  return x(inner);
549
824
  if (ck === 'BitCast' && T(t).k === 'ptr' && strip(inner).type && tyOf(strip(inner).type) === t)
550
825
  return x(inner);
826
+ // (a pointer to the state made a void * or another pointer type, given to other code: still a pointer to the
827
+ // state, which that code may change; anything read through it here is refused)
828
+ if (ck === 'BitCast' && T(t).k === 'ptr' && strip(inner).type && T(tyOf(strip(inner).type)).k === 'ptr')
829
+ return x(inner);
551
830
  return no(n, `${text(n)}: a ${ck} conversion${ck === 'IntegralToFloating' || ck.includes('Floating') ? ' (floats are outside the subset)' : ck.includes('Pointer') ? ' (a pointer made from other than the state\'s objects)' : ''}`);
552
831
  }
553
832
  case 'BinaryOperator': {
@@ -569,6 +848,8 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
569
848
  return { e: 'bin', ...a, op: op === '^' ? '^' : op, x: x(l), y: x(r) };
570
849
  if (op === ',')
571
850
  return no(n, 'the comma operator');
851
+ if (op === '=')
852
+ return effect(n, () => x(l));
572
853
  return no(n, `${text(n)}: an assignment inside an expression (the subset reads it as a statement)`);
573
854
  }
574
855
  case 'UnaryOperator': {
@@ -585,9 +866,17 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
585
866
  const r = strip(kids[0]);
586
867
  return r.kind === 'DeclRefExpr' && boxed.has(r.referencedDecl.id) ? { e: 'sel', ...a, k: 'field', x: x(r), path: [0] } : { e: 'star', ...a, x: x(kids[0]) };
587
868
  }
869
+ // (x++ inside an expression: x's value before it, a local; ++x: x after it)
870
+ if (op === '++' || op === '--') {
871
+ if (!n.isPostfix)
872
+ return effect(n, () => x(kids[0]));
873
+ const id = `$t${++temps}`, v = x(kids[0]);
874
+ return effect(n, () => ({ e: 'id', ...a, o: 'var', id, n: id }), [{ s: 'decl', p: pos(n), specs: [{ names: [{ name: id, id, t: tyOf(kids[0].type) }], v: [v] }] }]);
875
+ }
588
876
  return no(n, `${text(n)}: ${op} inside an expression (the subset reads it as a statement)`);
589
877
  }
590
- case 'ConditionalOperator': return { e: 'ite', ...a, x: cond(kids[0]), y: x(kids[1]), b: x(kids[2]) };
878
+ case 'ConditionalOperator': return { e: 'ite', ...a, x: cond(kids[0]), y: guard(() => x(kids[1])), b: guard(() => x(kids[2])) };
879
+ case 'CompoundAssignOperator': return effect(n, () => x(kids[0]));
591
880
  case 'CallExpr': return call(n);
592
881
  case 'CompoundLiteralExpr': return x(kids[0]);
593
882
  case 'InitListExpr': {
@@ -601,6 +890,9 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
601
890
  return { e: 'comp', ...a, elts: kids.flatMap((k, i) => (k.kind === 'ImplicitValueInitExpr' ? [] : [{ field: tt.fields[i].name, v: x(k) }])) };
602
891
  }
603
892
  case 'ArraySubscriptExpr': {
893
+ const tb = table(n);
894
+ if (tb)
895
+ return tb;
604
896
  // An index into an array of the state (its decay to a pointer undone); pointer arithmetic is outside.
605
897
  const b = strip(kids[0]), arr = b.kind === 'ImplicitCastExpr' && b.castKind === 'ArrayToPointerDecay' ? b.inner[0] : undefined;
606
898
  return arr ? { e: 'index', ...a, x: place(arr), i: x(kids[1]) } : no(n, `${text(n)}: an index into a pointer (pointer arithmetic)`);
@@ -613,13 +905,31 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
613
905
  };
614
906
  // A place: a local, a field (through a pointer: ->), *p.
615
907
  const place = (n0) => {
616
- const n = strip(n0);
617
- if (n.kind === 'DeclRefExpr' || n.kind === 'MemberExpr' || n.kind === 'CXXOperatorCallExpr' || (n.kind === 'UnaryOperator' && n.opcode === '*'))
908
+ const n = strip(n0), at0 = () => { const was = placing; placing = true; try {
618
909
  return x(n);
910
+ }
911
+ finally {
912
+ placing = was;
913
+ } };
914
+ if (n.kind === 'DeclRefExpr' || n.kind === 'MemberExpr' || n.kind === 'CXXOperatorCallExpr' || (n.kind === 'UnaryOperator' && n.opcode === '*'))
915
+ return at0();
619
916
  if (n.kind === 'ArraySubscriptExpr')
620
- return x(n);
917
+ return at0();
621
918
  return no(n, `${text(n)}: a place the subset doesn't write`);
622
919
  };
920
+ // Other code called with different constants (CO_isError(em, BUS_OFF), CO_isError(em, HB_CONSUMER)): a question per
921
+ // constant arguments, each its own answer, named by them (CO_isError_x_18: x where an argument isn't a constant).
922
+ const asked = new Map();
923
+ const sig = (args) => args.map(a => { const k = fold(a); return k === undefined || !Number.isSafeInteger(k) ? 'x' : String(k).replace('-', 'm'); }).join('_');
924
+ const scanCalls = (n) => { if (n.kind === 'CallExpr') {
925
+ const nm = calleeName(n);
926
+ if (nm && (!funcs.has(nm) || cut.includes(nm)))
927
+ (asked.get(nm) ?? asked.set(nm, new Set()).get(nm)).add(sig((n.inner ?? []).slice(1)));
928
+ } for (const c of n.inner ?? [])
929
+ scanCalls(c); };
930
+ for (const f of funcs.values())
931
+ scanCalls(f);
932
+ const keyed = (name, args) => ((asked.get(name)?.size ?? 0) > 1 && /\d/.test(sig(args)) ? `${name}_${sig(args)}` : name);
623
933
  const call = (n) => {
624
934
  const t = n.type ? tyOf(n.type) : -1, a = at(n, t), name = calleeName(n), args = (n.inner ?? []).slice(1);
625
935
  if (!name)
@@ -632,13 +942,16 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
632
942
  return no(n, `${name}: the process ends`);
633
943
  if (cpp && (name === 'min' || name === 'max') && args.length === 2)
634
944
  return { e: 'call', ...a, builtin: name, a: args.map(x) };
635
- const f = funcs.get(name);
945
+ // (one of the file's own the caller answers, `answers`: read as other code's, its value the request's)
946
+ const f = cut.includes(name) ? undefined : funcs.get(name);
636
947
  if (f?.$m)
637
948
  return no(n, `${name}: a static method`);
638
949
  // (another file's or a library's function: at the boundary where it is inferred, with its end, where the check
639
950
  // stubs an answered one in a copy of the file)
640
951
  if (!f)
641
- return { e: 'call', ...a, f: { e: 'sel', ...at(n, -1), k: 'qual', pkg: '', n: name, why: `${name}: a function of another file or library (other code)` }, a: args.map(x), ...(n.$e && own(n) ? { end: `${n.$e.line}:${n.$e.col + n.$e.tok}` } : {}) };
952
+ return { e: 'call', ...a, f: { e: 'sel', ...at(n, -1), k: 'qual', pkg: '', n: keyed(name, args), why: `${name}: a function of another file or library (other code)` }, a: args.map(x), ...(n.$e && own(n) ? { end: `${n.$e.line}:${n.$e.col + n.$e.tok}` } : {}) };
953
+ if (gmode)
954
+ return { e: 'call', ...a, f: { e: 'sel', ...at(n, -1), k: 'method', x: self0(n), n: name, mtype: entry, mptr: true }, a: args.map(x) };
642
955
  if (recvOf(f) && args.length)
643
956
  return { e: 'call', ...a, f: { e: 'sel', ...at(n, -1), k: 'method', x: x(args[0]), n: name, mtype: entry, mptr: true }, a: args.slice(1).map(x) };
644
957
  return { e: 'call', ...a, f: { e: 'id', ...at(n, -1), o: 'func', n: name }, a: args.map(x) };
@@ -650,6 +963,12 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
650
963
  const bt = b?.type ? T(tyOf(b.type)) : undefined;
651
964
  if (me.name === 'size' && bt?.fixed)
652
965
  return lit(n, bt.len, t);
966
+ // (another class's method with no body here: other code at the boundary, as a function of another file, its value
967
+ // the request's where it is read; from where the call begins, so the check stubs the whole call)
968
+ if (b && (!m || m.$rec !== entryRec) && m?.name && (!own(m) || (!(m.inner ?? []).some(c => c.kind === 'CompoundStmt') && !cxx.some(k => k.previousDecl === m.id)))) {
969
+ const p0 = n.$b && own(n) ? `${path.basename(n.$b.file)}:${n.$b.line}:${n.$b.col}` : pos(n);
970
+ return { e: 'call', ...at(n, t), p: p0, f: { e: 'sel', ...at(n, -1), k: 'qual', pkg: '', n: m.name, why: `${text(n)}: a method of another class (other code)` }, a: (n.inner ?? []).slice(1).map(x), ...(n.$e && own(n) ? { end: `${n.$e.line}:${n.$e.col + n.$e.tok}` } : {}) };
971
+ }
653
972
  if (!m || m.$rec !== entryRec || !b)
654
973
  return no(n, `${text(n)}: a method of another class (other code)`);
655
974
  if (overloaded.has(m.name) || (picks[m.name] !== undefined && params(m).length !== picks[m.name]))
@@ -669,12 +988,19 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
669
988
  const ends = (b) => { const l = b.at(-1); return !!l && (l.s === 'return' || l.s === 'panic' || (l.s === 'branch' && l.tok === 'break')); };
670
989
  function st(n) {
671
990
  const p = pos(n), kids = n.inner ?? [];
991
+ // (a write into a global left out: its value computed, the write not kept)
992
+ if ((left.size || leave.length) && (n.kind === 'CompoundAssignOperator' || (n.kind === 'BinaryOperator' && n.opcode === '=') || (n.kind === 'UnaryOperator' && ['++', '--'].includes(n.opcode))) && leftOut(kids[0])) {
993
+ if (n.kind === 'UnaryOperator')
994
+ return [];
995
+ const [ps, v] = pre(() => x(kids[1]));
996
+ return [...ps, { s: 'expr', p, x: v }];
997
+ }
672
998
  switch (n.kind) {
673
999
  case 'CompoundStmt': return [{ s: 'block', p, b: ss(kids) }];
674
1000
  case 'NullStmt': return [];
675
1001
  case 'DeclStmt': return kids.flatMap((d) => {
676
1002
  if (d.kind !== 'VarDecl')
677
- return d.kind === 'RecordDecl' || d.kind === 'TypedefDecl' || d.kind === 'EnumDecl' ? [] : sno(d, `a ${d.kind} in a function`);
1003
+ return ['RecordDecl', 'TypedefDecl', 'EnumDecl', 'StaticAssertDecl', 'TypeAliasDecl', 'UsingDecl'].includes(d.kind) ? [] : sno(d, `a ${d.kind} in a function`);
678
1004
  if (d.storageClass === 'static')
679
1005
  return sno(d, `${d.name}: a static local (state every call shares)`);
680
1006
  // std::lock_guard, std::scoped_lock, std::unique_lock of one of the object's mutexes, in the function's own
@@ -689,14 +1015,21 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
689
1015
  const init = d.init ? (d.inner ?? []).find(c => !c.kind.endsWith('Attr')) : undefined;
690
1016
  if (!init)
691
1017
  return [];
692
- return [{ s: 'decl', p, specs: [{ names: [{ name: d.name, id: d.id, t: tyOf(d.type) }], v: [x(init)] }] }];
1018
+ const [ps, v] = pre(() => x(init));
1019
+ return [...ps, { s: 'decl', p, specs: [{ names: [{ name: d.name, id: d.id, t: tyOf(d.type) }], v: [v] }] }];
693
1020
  });
694
- case 'ReturnStmt': return [{ s: 'return', p, r: kids.length ? [x(kids[0])] : [] }];
1021
+ case 'ReturnStmt': {
1022
+ if (!kids.length)
1023
+ return [{ s: 'return', p, r: [] }];
1024
+ const [ps, v] = pre(() => x(kids[0]));
1025
+ return [...ps, { s: 'return', p, r: [v] }];
1026
+ }
695
1027
  case 'IfStmt': {
696
1028
  if (n.hasInitStorage || n.hasVarStorage)
697
1029
  return sno(n, 'an if with a declaration');
698
1030
  const [c, th, el] = kids;
699
- return [{ s: 'if', p, c: cond(c), then: block(th), ...(el ? { else: { s: 'block', p: pos(el), b: block(el) } } : {}) }];
1031
+ const [ps, cc] = pre(() => cond(c));
1032
+ return [...ps, { s: 'if', p, c: cc, then: block(th), ...(el ? { else: { s: 'block', p: pos(el), b: block(el) } } : {}) }];
700
1033
  }
701
1034
  case 'SwitchStmt': return switchC(n);
702
1035
  case 'BreakStmt': return [{ s: 'branch', p, tok: 'break' }];
@@ -706,7 +1039,20 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
706
1039
  case 'CXXForRangeStmt': return sno(n, 'a loop (for over a range)');
707
1040
  case 'WhileStmt':
708
1041
  case 'DoStmt':
709
- case 'ForStmt': return sno(n, `a loop (${n.kind === 'WhileStmt' ? 'while' : n.kind === 'DoStmt' ? 'do' : 'for'})`);
1042
+ case 'ForStmt': {
1043
+ // (an endless loop nothing leaves, an assertion's trap or a wait for the watchdog's reset: the code stops there,
1044
+ // the step's failure)
1045
+ const c0 = n.kind === 'ForStmt' ? (kids[2]?.kind ? kids[2] : undefined) : n.kind === 'DoStmt' ? kids[1] : kids.find(k => k.kind && k.kind !== 'NullStmt' && !k.kind.endsWith('Stmt'));
1046
+ const body = n.kind === 'DoStmt' ? kids[0] : kids.at(-1), leaves = (b) => ['BreakStmt', 'ReturnStmt', 'GotoStmt', 'IndirectGotoStmt'].includes(b.kind) || (b.inner ?? []).some(leaves) || (b.kind === 'CallExpr' && !FAIL[calleeName(b) ?? '']);
1047
+ const k = c0 && c0.kind !== 'NullStmt' ? fold(c0) : n.kind === 'ForStmt' ? 1 : undefined;
1048
+ if (k !== undefined && k !== 0 && body && !leaves(body))
1049
+ return [{ s: 'expr', p, x: { e: 'call', ...at(n, -1), builtin: 'panic', a: [], what: 'an endless loop (the code stops there)' } }];
1050
+ // (do { ... } while (0), a macro's one statement: its body once, where nothing in it breaks or continues it)
1051
+ const exits = (b) => ['BreakStmt', 'ContinueStmt'].includes(b.kind) || (!['WhileStmt', 'DoStmt', 'ForStmt', 'SwitchStmt'].includes(b.kind) && (b.inner ?? []).some(exits));
1052
+ if (n.kind === 'DoStmt' && k === 0 && body && !(body.inner ?? []).some(exits))
1053
+ return block(body);
1054
+ return sno(n, `a loop (${n.kind === 'WhileStmt' ? 'while' : n.kind === 'DoStmt' ? 'do' : 'for'})`);
1055
+ }
710
1056
  case 'GotoStmt':
711
1057
  case 'IndirectGotoStmt': return sno(n, 'goto');
712
1058
  case 'LabelStmt': return sno(n, 'a label (goto)');
@@ -729,10 +1075,19 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
729
1075
  if (n.opcode !== '=')
730
1076
  break;
731
1077
  const [l, r] = kids, rs = strip(r);
1078
+ // (a pointer flag set: NULL its false, a constant other than 0 its true)
1079
+ if (flagOf(l)) {
1080
+ const k = isNull(r) ? 0 : (() => { let v = strip(r); while (CAST.has(v.kind))
1081
+ v = strip(v.inner[0]); return fold(v); })();
1082
+ if (k === undefined)
1083
+ return sno(n, `${text(n)}: a pointer flag set to other than NULL or a constant`);
1084
+ return [{ s: 'assign', p, op: '=', l: [place(l)], r: [{ e: 'lit', ...at(r, boolT), c: { bool: k !== 0 } }] }];
1085
+ }
732
1086
  // a = b = c: b set first, then a to b's value.
733
1087
  if (rs.kind === 'BinaryOperator' && rs.opcode === '=')
734
1088
  return [...st(rs), { s: 'assign', p, op: '=', l: [place(l)], r: [conv2(r, tyOf(l.type), x(rs.inner[0]))] }];
735
- return [{ s: 'assign', p, op: '=', l: [place(l)], r: [x(r)] }];
1089
+ const [ps, rv] = pre(() => x(r));
1090
+ return [...ps, { s: 'assign', p, op: '=', l: [place(l)], r: [rv] }];
736
1091
  }
737
1092
  case 'CompoundAssignOperator': {
738
1093
  const [l, r] = kids, lt = tyOf(l.type), ct = tyOf(n.computeLHSType), op = n.opcode.slice(0, -1);
@@ -758,7 +1113,10 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
758
1113
  return [{ s: 'assign', p, op: '=', l: [place(l)], r: [conv(n, lt, { e: 'bin', ...at(n, it), op: n.opcode[0], x: conv(l, it, x(l)), y: lit(n, 1, it) })] }];
759
1114
  }
760
1115
  case 'CallExpr':
761
- case 'CXXMemberCallExpr': return [{ s: 'expr', p, x: n.kind === 'CallExpr' ? call(n) : memberCall(n) }];
1116
+ case 'CXXMemberCallExpr': {
1117
+ const [ps, cx] = pre(() => (n.kind === 'CallExpr' ? call(n) : memberCall(n)));
1118
+ return [...ps, { s: 'expr', p, x: cx }];
1119
+ }
762
1120
  }
763
1121
  if (n.kind.endsWith('Expr') || n.kind.endsWith('Literal') || n.kind.endsWith('Operator'))
764
1122
  return [{ s: 'expr', p, x: x(n) }];
@@ -809,26 +1167,57 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
809
1167
  delete c.list;
810
1168
  cases.forEach((c, i) => { if (i < cases.length - 1 && !ends(c.b))
811
1169
  c.b.push({ s: 'branch', p: c.p, tok: 'fallthrough' }); });
812
- return [{ s: 'switch', p: pos(n), tag: x(tag), cases }];
1170
+ const [ps, tx] = pre(() => x(tag));
1171
+ return [...ps, { s: 'switch', p: pos(n), tag: tx, cases }];
813
1172
  }
814
1173
  // --- the functions ----------------------------------------------------------------------------------------------------
815
- const out = [], td0 = () => records.get(entryRec);
816
- const fn = (name, f, pre = []) => {
1174
+ const out = [], td0 = () => (gmode ? top.find(n => mine(n)) ?? top[0] : records.get(entryRec));
1175
+ // (the requests: the file's non-static functions, or those named; each given the globals the request gives)
1176
+ const requests = new Set(gmode ? (Object.keys(picks).length || pickNames.length ? pickNames : [...funcs].filter(([, f]) => f.storageClass !== 'static' && mine(f)).map(([n]) => n)) : []);
1177
+ const fn = (name, f, pre0 = []) => {
1178
+ // (a request of the file's globals: each global the request gives set from its argument of that name first)
1179
+ const gin = gmode && requests.has(name) ? gnodes.filter(g => ginput.has(g.id) && fnReads.get(name)?.has(g.id)) : [];
1180
+ for (const q of params(f))
1181
+ if (gin.some(g => g.name === q.name))
1182
+ refuse(q, `${name}: its parameter ${q.name} has a global's name the request gives`);
1183
+ const pre = [...pre0, ...gin.map((g) => ({ s: 'assign', p: pos(f), op: '=', l: [{ e: 'sel', ...at(f, tyOf(g.type)), k: 'field', x: self0(f), path: [gfield.get(g.id)] }], r: [{ e: 'id', ...at(f, tyOf(g.type)), o: 'var', id: `in:${g.id}`, n: g.name }] }))];
817
1184
  const r = recvOf(f), body = f.inner.find(c => c.kind === 'CompoundStmt'), rt = f.kind === 'CXXConstructorDecl' ? parseT('void') : parseT(f.type.qualType.slice(0, retEnd(f.type.qualType)));
818
1185
  for (const c of body.inner ?? [])
819
1186
  topStmts.add(c.id);
820
1187
  return { name, p: pos(f), span: [f.$b?.line ?? 0, f.$e?.line ?? 0],
821
- ...(r ? { recv: { t: tyOf(r.type), ptr: true, type: entry, ...(r.name ? { name: r.name, id: r.id } : {}) } } : {}),
822
- params: args0(f).map(q => ({ ...(q.name ? { name: q.name, id: q.id } : {}), t: boxed.get(q.id) ?? byValue.get(q.id) ?? tyOf(q.type), ts: q.type.qualType })),
1188
+ ...(r ? { recv: { t: gmode ? ptrT : tyOf(r.type), ptr: true, type: entry, ...(r.name ? { name: r.name, id: r.id } : {}) } } : {}),
1189
+ params: [...args0(f).map(q => ({ ...(q.name ? { name: q.name, id: q.id } : {}), t: boxed.get(q.id) ?? byValue.get(q.id) ?? tyOf(q.type), ts: q.type.qualType })), ...gin.map(g => ({ name: g.name, id: `in:${g.id}`, t: tyOf(g.type), ts: g.type.qualType }))],
823
1190
  results: T(rt).k === 'void' ? [] : [{ t: rt }], body: [...pre, ...ss(body.inner ?? [])],
824
1191
  ...(/\.\.\.\)$/.test(f.type.qualType) ? { params: [{ t: -1, variadic: true }] } : {}),
825
1192
  static: f.storageClass === 'static', ...(f.virtual ? { why: `${name}: a virtual method (its dispatch)` } : {}) };
826
1193
  };
1194
+ let ctor;
827
1195
  for (const [name, f] of funcs)
828
1196
  out.push(fn(name, f));
1197
+ // (the globals' start: each one's initializer, where it has one; C's zero where not)
1198
+ if (gmode) {
1199
+ const pre = [];
1200
+ for (const g of gnodes) {
1201
+ const v = g.init ? (g.inner ?? []).find(c => !c.kind.endsWith('Attr')) : undefined, t = tyOf(g.type);
1202
+ const empty = !v || (strip(v).kind === 'InitListExpr' && (strip(v).inner ?? []).every(c => c.kind === 'ImplicitValueInitExpr'));
1203
+ // (C's zero, leaf by leaf: each integer and boolean of it 0, an array a list of zeros already)
1204
+ const zeros = (tt, place) => {
1205
+ const k = T(tt).k;
1206
+ if (k === 'int' || k === 'bool')
1207
+ pre.push({ s: 'assign', p: pos(g), op: '=', l: [place], r: [k === 'int' ? lit(g, 0, tt) : { e: 'lit', ...at(g, tt), c: { bool: false } }] });
1208
+ else if (k === 'struct')
1209
+ T(tt).fields.forEach((f, i) => zeros(f.t, { e: 'sel', ...at(g, f.t), k: 'field', x: place, path: [i] }));
1210
+ };
1211
+ const place = { e: 'sel', ...at(v ?? g, t), k: 'field', x: self0(v ?? g), path: [gfield.get(g.id)] };
1212
+ if (empty)
1213
+ zeros(t, place);
1214
+ else
1215
+ pre.push({ s: 'assign', p: pos(v), op: '=', l: [place], r: [x(v)] });
1216
+ }
1217
+ ctor = { name: '$ctor', p: pos(td0()), span: [0, 0], recv: { t: ptrT, ptr: true, type: entry, name: 'this', id: 'this' }, params: [], results: [], body: pre };
1218
+ }
829
1219
  // The constructor (C++): its member initializers (each field's own in-class one where it has no other), then its body;
830
1220
  // the rule starts where it leaves the object, its parameters the rule's.
831
- let ctor;
832
1221
  if (cpp) {
833
1222
  if (ctors.length > 1)
834
1223
  refuse(ctors[1], `${entry}: ${ctors.length} constructors (the C++ front end reads a class with one)`);
@@ -856,11 +1245,14 @@ export function readC(file, entry, tu, target, cpp = false, root, picks = {}) {
856
1245
  const td = td0();
857
1246
  const pkg = { lang: cpp ? 'cpp' : 'c', package: entry, files: [{ name: base, imports: [] }], funcs: out, types: [{ name: entry, t: entryT, p: pos(td), span: [td.$b?.line ?? 0, td.$e?.line ?? 0] }], consts: [], vars: [], errors: [], ttab, ...(ctor ? { ctor } : {}) };
858
1247
  // (by default: the file's non-static functions taking the struct; a class's public methods)
859
- const methods = out.filter((f, i) => { const n = [...funcs.values()][i]; return f.recv && !f.static && (n.$m ? n.$access === 'public' : mine(n)); }).map(f => f.name);
1248
+ const methods = gmode ? [...requests] : out.filter((f, i) => { const n = [...funcs.values()][i]; return f.recv && !f.static && (n.$m ? n.$access === 'public' : mine(n)); }).map(f => f.name);
860
1249
  // (the class's qualified name, which the harness spells: `this`'s type, as clang prints it)
861
1250
  const thisOf = (n) => (n.kind === 'CXXThisExpr' ? n.type.qualType : (n.inner ?? []).map(thisOf).find(Boolean));
862
1251
  const self = cpp ? cxx.filter(m => m.$rec === entryRec).map(thisOf).find(Boolean)?.replace(/^const /, '').replace(/ \*$/, '') : undefined;
863
- return { pkg, methods, entry, cname: self ?? T(entryT).go };
1252
+ return { pkg, methods, entry, cname: self ?? T(entryT).go, consts: Object.fromEntries([...named].filter(([, v]) => Number.isSafeInteger(v))),
1253
+ ...(gmode ? { globals: { state: gnodes.map(g => g.name), inputs: gnodes.filter(g => ginput.has(g.id)).map(g => g.name), types: Object.fromEntries(gnodes.map(g => [g.name, g.type.qualType])),
1254
+ // (declared only, another file's to define: the check defines it, zero at the start)
1255
+ externs: gnodes.filter(g => ![...globals.values()].some(d => d.name === g.name && (d.storageClass !== 'extern' || d.init))).map(g => g.name) } } : {}) };
864
1256
  }
865
1257
  // Where a function type's result ends: before its parameter list (the last parenthesized group).
866
1258
  function retEnd(s) {