@eagleoutice/flowr 2.15.0 → 2.15.2

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 (30) hide show
  1. package/README.md +14 -14
  2. package/abstract-interpretation/data-frame/dataframe-semantics.js +14 -5
  3. package/dataflow/environments/identifier.d.ts +2 -0
  4. package/dataflow/environments/identifier.js +8 -1
  5. package/dataflow/environments/query-fn-props.d.ts +9 -1
  6. package/dataflow/environments/query-fn-props.js +88 -10
  7. package/dataflow/eval/resolve/alias-tracking.js +4 -4
  8. package/dataflow/eval/resolve/resolve.js +11 -1
  9. package/dataflow/eval/values/general.d.ts +2 -0
  10. package/dataflow/eval/values/general.js +5 -0
  11. package/dataflow/eval/values/sets/set-constants.d.ts +5 -0
  12. package/dataflow/eval/values/sets/set-constants.js +9 -1
  13. package/dataflow/internal/process/functions/call/built-in/built-in-string-template.js +2 -1
  14. package/linter/rules/problematic-inputs.js +1 -1
  15. package/linter/rules/undefined-symbol.js +3 -2
  16. package/package.json +1 -1
  17. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +3 -1
  18. package/project/sigdb/build.js +38 -0
  19. package/project/sigdb/manifest.js +1 -1
  20. package/project/sigdb/reader.d.ts +18 -5
  21. package/project/sigdb/reader.js +121 -19
  22. package/queries/catalog/dice-query/dice-query-executor.js +3 -2
  23. package/queries/catalog/input-sources-query/simple-input-classifier.js +67 -0
  24. package/queries/catalog/slice-query-options.d.ts +10 -4
  25. package/queries/catalog/slice-query-options.js +27 -5
  26. package/queries/catalog/static-slice-query/static-slice-query-executor.d.ts +1 -1
  27. package/queries/catalog/static-slice-query/static-slice-query-executor.js +7 -4
  28. package/queries/query.d.ts +56 -2
  29. package/queries/query.js +66 -1
  30. package/util/version.js +2 -2
@@ -143,11 +143,11 @@ export interface OpenSyncFromOptions extends SigDbOpenOptions, OpenSyncOptions {
143
143
  */
144
144
  export declare class SigDatabase implements PackageSignatureSource {
145
145
  private closed;
146
- /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; FIFO-bounded to cap memory */
146
+ /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; bounded by {@link BlobCacheBudget} */
147
147
  private readonly blobCache;
148
- private static readonly BlobCacheCap;
149
- /** a version's function indices plus its `name -> index` view; FIFO-bounded like {@link blobCache} */
148
+ /** a version's function indices plus its `name -> index` view, keyed by package and version; FIFO-bounded */
150
149
  private readonly versionFnCache;
150
+ private static readonly VersionFnCacheCap;
151
151
  /** which names a package can offer at all, as sorted dictionary ids; filled the first time its blob is read */
152
152
  private readonly nameIdsOfBlob;
153
153
  /** dictionary id per name asked for, so only the names someone actually queried are ever resolved */
@@ -185,7 +185,9 @@ export declare class SigDatabase implements PackageSignatureSource {
185
185
  * nothing is known about the package yet, so this only ever skips work that would have found nothing.
186
186
  */
187
187
  private mayOffer;
188
- /** store `value` under `key`, dropping the oldest entry first once the cache sits at {@link BlobCacheCap} */
188
+ /** drop one decoded blob, for the shared budget to reclaim what it costs (see {@link keepBlob}) */
189
+ dropBlob(blobIdx: number): void;
190
+ /** store `value` under `key`, dropping the oldest entry first once the cache sits at `cap` */
189
191
  private static cache;
190
192
  /** seek to a byte range, read + decode the package blob there (no caching) */
191
193
  private readBlobAt;
@@ -201,8 +203,19 @@ export declare class SigDatabase implements PackageSignatureSource {
201
203
  private blobMeta;
202
204
  lookup(pkg: string, version?: string): LibraryExports | undefined;
203
205
  packagesExporting(name: string): readonly string[];
206
+ /**
207
+ * Whether the newest version of `pkg` exports the name with dictionary id `id`. The same answer
208
+ * {@link lookup}'s `exported` gives, off the function records themselves: asking a package at a time is what
209
+ * {@link packagesExporting} does, and deriving a whole export view per package to read one name out of it is not
210
+ * worth the five arrays and the map it builds.
211
+ */
212
+ private exportsNameId;
204
213
  classOwner(className: string, version?: string): string | undefined;
205
- /** resolve a package version to its blob and the function-record indices of that version (the shared prologue of {@link functions}/{@link functionByName}) */
214
+ /**
215
+ * Resolve a package version to its blob and the function records of that version (the shared prologue of
216
+ * {@link functions}/{@link functionByName}). The blob comes from {@link blob} every time rather than out of
217
+ * {@link versionFnCache}: holding one here would keep it decoded past what {@link BlobCacheBudget} allows.
218
+ */
206
219
  private versionFns;
207
220
  functions(pkg: string, version?: string): DecodedFunction[] | undefined;
208
221
  functionByName(pkg: string, name: string, version?: string): DecodedFunction | undefined;
@@ -36,6 +36,48 @@ function applyDictLine(json, strings) {
36
36
  strings[start + k] = batch[k];
37
37
  }
38
38
  }
39
+ /**
40
+ * Dictionary ids grouped by first character and length, shared per dictionary rather than per reader (the shards of one
41
+ * database read the same array). One `Int32Array` per group, ascending, so a lookup answers what `indexOf` would while
42
+ * comparing a few hundred strings rather than the 1.4 million a scan of the whole dictionary walks.
43
+ */
44
+ const dictionaryBuckets = new WeakMap();
45
+ /** the group `name` belongs to; the empty string has none of its own, which is what `0` stands for */
46
+ function bucketKeyOf(name) {
47
+ return name.length === 0 ? 0 : (name.charCodeAt(0) << 8) | Math.min(name.length, 255);
48
+ }
49
+ /** the id `strings.indexOf(name)` would give, through {@link dictionaryBuckets}; `-1` when the dictionary lacks it */
50
+ function dictionaryIdOf(strings, name) {
51
+ let buckets = dictionaryBuckets.get(strings);
52
+ if (buckets === undefined) {
53
+ /* one pass over the 1.4 million entries: sizing them first meant walking all of them twice and a map
54
+ lookup per entry to know where in its group the next one goes */
55
+ const grouped = new Map();
56
+ for (let i = 0; i < strings.length; i++) {
57
+ const key = bucketKeyOf(strings[i]);
58
+ const group = grouped.get(key);
59
+ if (group === undefined) {
60
+ grouped.set(key, [i]);
61
+ }
62
+ else {
63
+ group.push(i);
64
+ }
65
+ }
66
+ buckets = new Map();
67
+ for (const [key, group] of grouped) {
68
+ buckets.set(key, Int32Array.from(group));
69
+ }
70
+ dictionaryBuckets.set(strings, buckets);
71
+ }
72
+ const bucket = buckets.get(bucketKeyOf(name));
73
+ /* ascending, so the first match is the one a scan from the front would have found */
74
+ for (const id of bucket ?? []) {
75
+ if (strings[id] === name) {
76
+ return id;
77
+ }
78
+ }
79
+ return -1;
80
+ }
39
81
  function readDictSection(buf, strings) {
40
82
  let off = 0;
41
83
  while (off < buf.length) {
@@ -266,17 +308,37 @@ function sourceForPackage(sources, pkg) {
266
308
  }
267
309
  /** the {@link SigDatabase.fd} of a database that has no file behind it (see {@link SigDatabase.fromMemory}) */
268
310
  const NoFile = -1;
311
+ /**
312
+ * One budget for every open bundle, spent in the bytes the blobs take on disk. Per bundle it would not bound
313
+ * anything: how many shards a query set opens is not something the caller picks, and each would claim the
314
+ * budget again. A count would not bound anything either -- one package's blob outweighs a hundred small ones.
315
+ */
316
+ const BlobCacheBudget = 8 * 1024 * 1024;
317
+ /** what every open bundle holds decoded, oldest read first, so the budget is spent across all of them */
318
+ const cachedBlobs = [];
319
+ let cachedBlobBytes = 0;
320
+ /** keep `blob` decoded for `db`, dropping what any bundle read longest ago until all of them fit the budget */
321
+ function keepBlob(db, blobIdx, bytes) {
322
+ while (cachedBlobBytes + bytes > BlobCacheBudget && cachedBlobs.length > 0) {
323
+ const dropped = cachedBlobs.shift();
324
+ /* the bytes are off the list either way: a closed bundle already let its blobs go */
325
+ cachedBlobBytes -= dropped.bytes;
326
+ dropped.db.dropBlob(dropped.blobIdx);
327
+ }
328
+ cachedBlobs.push({ db, blobIdx, bytes });
329
+ cachedBlobBytes += bytes;
330
+ }
269
331
  /**
270
332
  * Fast, partial reader for a single bundle. `open()`/`openSync()` load the string dictionary + `.idx` once, then every
271
333
  * query seeks straight to one package blob; `open()` additionally decompresses a `.br`/`.gz` source into a hash-keyed cache.
272
334
  */
273
335
  class SigDatabase {
274
336
  closed = false;
275
- /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; FIFO-bounded to cap memory */
337
+ /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; bounded by {@link BlobCacheBudget} */
276
338
  blobCache = new Map();
277
- static BlobCacheCap = 2048;
278
- /** a version's function indices plus its `name -> index` view; FIFO-bounded like {@link blobCache} */
339
+ /** a version's function indices plus its `name -> index` view, keyed by package and version; FIFO-bounded */
279
340
  versionFnCache = new Map();
341
+ static VersionFnCacheCap = 2048;
280
342
  /** which names a package can offer at all, as sorted dictionary ids; filled the first time its blob is read */
281
343
  nameIdsOfBlob = new Map();
282
344
  /** dictionary id per name asked for, so only the names someone actually queried are ever resolved */
@@ -364,17 +426,20 @@ class SigDatabase {
364
426
  if (this.fd === NoFile) {
365
427
  return undefined; // an in-memory database starts out with every blob cached
366
428
  }
367
- const blob = this.readBlobAt(this.index.blobs[blobIdx]);
429
+ const range = this.index.blobs[blobIdx];
430
+ const blob = this.readBlobAt(range);
368
431
  if (!this.nameIdsOfBlob.has(blobIdx)) {
369
432
  this.nameIdsOfBlob.set(blobIdx, Int32Array.from(new Set(blob.fns.map(fn => fn[0]))).sort());
370
433
  }
371
- return SigDatabase.cache(this.blobCache, blobIdx, blob);
434
+ keepBlob(this, blobIdx, range[1]);
435
+ this.blobCache.set(blobIdx, blob);
436
+ return blob;
372
437
  }
373
438
  /** the dictionary id of `name`, or `-1` if the dictionary does not hold it, so no package can offer it */
374
439
  nameId(name) {
375
440
  let id = this.nameIds.get(name);
376
441
  if (id === undefined) {
377
- this.nameIds.set(name, id = this.strings.indexOf(name));
442
+ this.nameIds.set(name, id = dictionaryIdOf(this.strings, name));
378
443
  }
379
444
  return id;
380
445
  }
@@ -407,9 +472,13 @@ class SigDatabase {
407
472
  }
408
473
  return false;
409
474
  }
410
- /** store `value` under `key`, dropping the oldest entry first once the cache sits at {@link BlobCacheCap} */
411
- static cache(cache, key, value) {
412
- if (cache.size >= SigDatabase.BlobCacheCap) {
475
+ /** drop one decoded blob, for the shared budget to reclaim what it costs (see {@link keepBlob}) */
476
+ dropBlob(blobIdx) {
477
+ this.blobCache.delete(blobIdx);
478
+ }
479
+ /** store `value` under `key`, dropping the oldest entry first once the cache sits at `cap` */
480
+ static cache(cache, key, value, cap) {
481
+ if (cache.size >= cap) {
413
482
  const oldest = cache.keys().next().value;
414
483
  if (oldest !== undefined) {
415
484
  cache.delete(oldest);
@@ -463,17 +532,37 @@ class SigDatabase {
463
532
  return bm && (0, decode_1.deriveLibraryExports)(this.strings, bm.blob, bm.meta, pkg, version, this.cranBase);
464
533
  }
465
534
  packagesExporting(name) {
466
- if (this.nameId(name) < 0) {
535
+ const id = this.nameId(name);
536
+ if (id < 0) {
467
537
  return [];
468
538
  }
469
539
  const found = [];
470
540
  for (const pkg in this.index.pkgs) {
471
- if (this.mayOffer(pkg, name) && this.lookup(pkg)?.exported.includes(name)) {
541
+ if (this.mayOffer(pkg, name) && this.exportsNameId(pkg, id)) {
472
542
  found.push(pkg);
473
543
  }
474
544
  }
475
545
  return found.sort((a, b) => this.downloads(b) - this.downloads(a) || a.localeCompare(b));
476
546
  }
547
+ /**
548
+ * Whether the newest version of `pkg` exports the name with dictionary id `id`. The same answer
549
+ * {@link lookup}'s `exported` gives, off the function records themselves: asking a package at a time is what
550
+ * {@link packagesExporting} does, and deriving a whole export view per package to read one name out of it is not
551
+ * worth the five arrays and the map it builds.
552
+ */
553
+ exportsNameId(pkg, id) {
554
+ const r = this.versionFns(pkg);
555
+ if (r === undefined) {
556
+ return false;
557
+ }
558
+ for (const i of r.fns.idxs) {
559
+ const fn = r.blob.fns[i];
560
+ if (fn[0] === id && (fn[3] & 1 /* FnProp.Exported */) !== 0) {
561
+ return true;
562
+ }
563
+ }
564
+ return false;
565
+ }
477
566
  classOwner(className, version) {
478
567
  if (version !== undefined) {
479
568
  return classOwnerAtVersion(this, className, version);
@@ -481,7 +570,11 @@ class SigDatabase {
481
570
  this.classIndex ??= classOwnerIndexFor(this, this.packageNames());
482
571
  return this.classIndex.get(className);
483
572
  }
484
- /** resolve a package version to its blob and the function-record indices of that version (the shared prologue of {@link functions}/{@link functionByName}) */
573
+ /**
574
+ * Resolve a package version to its blob and the function records of that version (the shared prologue of
575
+ * {@link functions}/{@link functionByName}). The blob comes from {@link blob} every time rather than out of
576
+ * {@link versionFnCache}: holding one here would keep it decoded past what {@link BlobCacheBudget} allows.
577
+ */
485
578
  versionFns(pkg, version) {
486
579
  const bm = this.blobMeta(pkg);
487
580
  if (!bm) {
@@ -495,17 +588,17 @@ class SigDatabase {
495
588
  const key = `${pkg}\0${ver}`;
496
589
  const cached = this.versionFnCache.get(key);
497
590
  if (cached !== undefined) {
498
- return cached;
591
+ return { blob: bm.blob, fns: cached };
499
592
  }
500
593
  const idxs = (0, decode_1.versionFnIndices)(bm.blob, ver);
501
594
  if (idxs === undefined) {
502
595
  return undefined;
503
596
  }
504
- return SigDatabase.cache(this.versionFnCache, key, { blob: bm.blob, idxs });
597
+ return { blob: bm.blob, fns: SigDatabase.cache(this.versionFnCache, key, { idxs }, SigDatabase.VersionFnCacheCap) };
505
598
  }
506
599
  functions(pkg, version) {
507
600
  const r = this.versionFns(pkg, version);
508
- return r?.idxs.map(i => (0, decode_1.decodeFunction)(this.strings, r.blob, i));
601
+ return r?.fns.idxs.map(i => (0, decode_1.decodeFunction)(this.strings, r.blob, i));
509
602
  }
510
603
  functionByName(pkg, name, version) {
511
604
  if (!this.mayOffer(pkg, name)) {
@@ -515,18 +608,18 @@ class SigDatabase {
515
608
  if (r === undefined) {
516
609
  return undefined;
517
610
  }
518
- if (r.byName === undefined) {
611
+ if (r.fns.byName === undefined) {
519
612
  const byName = new Map();
520
- for (const i of r.idxs) {
613
+ for (const i of r.fns.idxs) {
521
614
  const fn = this.strings[r.blob.fns[i][0]];
522
615
  // first record wins, as the linear scan did
523
616
  if (!byName.has(fn)) {
524
617
  byName.set(fn, i);
525
618
  }
526
619
  }
527
- r.byName = byName;
620
+ r.fns.byName = byName;
528
621
  }
529
- const hit = r.byName.get(name);
622
+ const hit = r.fns.byName.get(name);
530
623
  return hit !== undefined ? (0, decode_1.decodeFunction)(this.strings, r.blob, hit) : undefined;
531
624
  }
532
625
  transitiveCallees(pkg, name, version) {
@@ -585,6 +678,7 @@ class SigDatabase {
585
678
  if (!this.closed) {
586
679
  this.closed = true;
587
680
  this.blobCache.clear();
681
+ this.versionFnCache.clear();
588
682
  this.classIndex = undefined;
589
683
  if (this.fd !== NoFile) {
590
684
  fs_1.default.closeSync(this.fd);
@@ -1024,6 +1118,14 @@ async function verifyShardedDatabase(manifestFile, opts = {}) {
1024
1118
  break;
1025
1119
  }
1026
1120
  }
1121
+ /* a class names itself, its superclasses and its slots out of the same dictionary the rest reads from */
1122
+ for (const c of set.classes(pkg) ?? []) {
1123
+ const strings = [c.name, ...c.supers, ...c.slots.flatMap(slot => [slot.name, slot.type]), c.package];
1124
+ if (strings.some(entry => entry !== undefined && typeof entry !== 'string')) {
1125
+ errors.push(`spot-check: '${pkg}' class decoded with a non-string name/super/slot (dictionary index out of range?)`);
1126
+ break;
1127
+ }
1128
+ }
1027
1129
  spotChecked++;
1028
1130
  }
1029
1131
  // 5. required packages (e.g. base R) are present
@@ -14,8 +14,9 @@ async function executeDiceQuery({ analyzer }, queries) {
14
14
  const results = {};
15
15
  const ast = await analyzer.normalize();
16
16
  const df = await analyzer.dataflow();
17
- for (const query of queries) {
18
- const key = (0, slice_query_options_1.sliceResultKey)(query);
17
+ const keys = (0, slice_query_options_1.sliceResultKeys)(queries, query => `${query.from.join(',')}->${query.to.join(',')}`);
18
+ for (const [at, query] of queries.entries()) {
19
+ const key = keys[at];
19
20
  if (results[key]) {
20
21
  log_1.log.warn(`Duplicate key for dice-query: ${key}, skipping...`);
21
22
  continue;
@@ -428,6 +428,11 @@ class InputClassifier {
428
428
  if (callee !== undefined) {
429
429
  return this.classifyCdsAndReturn(call, { ...callee, id: call.id });
430
430
  }
431
+ // a call of a function the code defines yields whatever that function returns
432
+ const returned = this.classifyDefinitionResult(call);
433
+ if (returned !== undefined) {
434
+ return this.classifyCdsAndReturn(call, returned);
435
+ }
431
436
  // if it is not pure, we cannot classify based on the inputs, in that case we do not know!
432
437
  types.push(input_types_1.InputType.Unknown);
433
438
  }
@@ -466,6 +471,68 @@ class InputClassifier {
466
471
  argTypes.push(input_types_1.InputType.DerivedConstant);
467
472
  return this.classifyCdsAndReturn(call, (0, objects_1.compactRecord)({ id: call.id, types: (0, arrays_1.uniqueArray)(argTypes), trace: input_types_1.InputTraceType.Known, cds }));
468
473
  }
474
+ /**
475
+ * What a call of a function the analyzed code defines yields: what its exit points do, as a function whose
476
+ * body is `system(x)` runs a system command whether the call reads `f(cmd)` or `system(cmd)`. `undefined`
477
+ * when the call names no definition here or when none of them says anything about what it returns.
478
+ */
479
+ classifyDefinitionResult(call) {
480
+ const graph = this.fullDfg ?? this.dfg;
481
+ const acc = new ClassificationAccumulator();
482
+ let known = false;
483
+ for (const fn of this.functionDefinitionsAt(call.id)) {
484
+ const definition = graph.getVertex(fn);
485
+ if (!vertex_1.FunctionDefinitionVertex.is(definition)) {
486
+ continue;
487
+ }
488
+ for (const { nodeId } of definition.exitPoints) {
489
+ for (const value of this.exitValues(nodeId)) {
490
+ const vtx = value === undefined ? undefined : this.dfg.getVertex(value) ?? graph.getVertex(value);
491
+ const classified = vtx ? this.classifyEntry(vtx) : undefined;
492
+ if (classified === undefined) {
493
+ /* an exit flowR cannot place says nothing about the call, so neither can the others */
494
+ return undefined;
495
+ }
496
+ known = true;
497
+ acc.merge(classified);
498
+ }
499
+ }
500
+ }
501
+ if (!known) {
502
+ return undefined;
503
+ }
504
+ const built = acc.build(call.id);
505
+ return built.types.includes(input_types_1.InputType.Unknown) ? undefined : built;
506
+ }
507
+ /**
508
+ * What an exit point hands back, descending through the branches of an `if` (which yields one of them, while
509
+ * {@link classifyFunctionCall} reports the condition it depends on). Yields `undefined` for a construct whose
510
+ * value flowR cannot name, a loop above all, so the caller stops rather than answers with the branches alone.
511
+ */
512
+ *exitValues(id, depth = 0) {
513
+ const vtx = (this.dfg.getVertex(id) ?? (this.fullDfg ?? this.dfg).getVertex(id));
514
+ if (vtx === undefined || !vertex_1.FunctionCallVertex.is(vtx)) {
515
+ yield id;
516
+ return;
517
+ }
518
+ if (vtx.origin.includes(built_in_proc_name_1.BuiltInProcName.WhileLoop) || vtx.origin.includes(built_in_proc_name_1.BuiltInProcName.ForLoop) || vtx.origin.includes(built_in_proc_name_1.BuiltInProcName.RepeatLoop)) {
519
+ yield undefined;
520
+ }
521
+ else if (vtx.origin.includes(built_in_proc_name_1.BuiltInProcName.IfThenElse) && depth <= MaxFunctionResolveDepth) {
522
+ for (const branch of vtx.args.slice(1)) {
523
+ const ref = graph_1.FunctionArgument.isEmpty(branch) ? undefined : graph_1.FunctionArgument.getReference(branch);
524
+ if (ref === undefined) {
525
+ yield undefined;
526
+ }
527
+ else {
528
+ yield* this.exitValues(ref, depth + 1);
529
+ }
530
+ }
531
+ }
532
+ else {
533
+ yield id;
534
+ }
535
+ }
469
536
  /** classifies what a call of a variable (e.g. a shiny reactive `n()`) yields, by what that variable holds */
470
537
  classifyCallee(call) {
471
538
  for (const o of df_helper_1.Dataflow.origin(this.dfg, call.id) ?? []) {
@@ -57,11 +57,17 @@ export declare const SliceQueryOptionsSchema: {
57
57
  readonly reportPackages: Joi.BooleanSchema<boolean>;
58
58
  };
59
59
  /**
60
- * How a slicing query's result is keyed: under the name it was given, else under the query itself so that two
61
- * runs of the same slice are one entry. A name is what keeps a caller from having to parse a serialized query
62
- * back out of the key.
60
+ * How a slicing query's result is keyed: under the name it was given, else under what it slices (`2@x`), which
61
+ * is what a caller looks the result up by. Use {@link sliceResultKeys} for a whole request, as only there can
62
+ * two queries be seen to want the same key.
63
63
  */
64
- export declare function sliceResultKey(query: SliceQueryOptions): string;
64
+ export declare function sliceResultKey<T extends SliceQueryOptions>(query: T, describe: (query: T) => string): string;
65
+ /**
66
+ * The keys a whole request's results are reported under (see {@link sliceResultKey}). Two queries that differ
67
+ * only in their options would want the same key, and only one of them could be reported; those fall back to the
68
+ * serialized query, so nothing is silently merged. Two *identical* queries still share one entry, as they must.
69
+ */
70
+ export declare function sliceResultKeys<T extends SliceQueryOptions>(queries: readonly T[], describe: (query: T) => string): string[];
65
71
  /** Whether a result key is a serialized query rather than the name someone gave the slice. */
66
72
  export declare function isSerializedQuery(key: string): boolean;
67
73
  /**
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.SliceQueryOptionsSchema = void 0;
7
7
  exports.sliceResultKey = sliceResultKey;
8
+ exports.sliceResultKeys = sliceResultKeys;
8
9
  exports.isSerializedQuery = isSerializedQuery;
9
10
  exports.resolveSliceCriteria = resolveSliceCriteria;
10
11
  exports.reconstructSlice = reconstructSlice;
@@ -31,12 +32,33 @@ exports.SliceQueryOptionsSchema = {
31
32
  reportPackages: joi_1.default.boolean().optional().description('Also report the packages the slice calls into, i.e. what this selection needs installed rather than what the whole program loads.')
32
33
  };
33
34
  /**
34
- * How a slicing query's result is keyed: under the name it was given, else under the query itself so that two
35
- * runs of the same slice are one entry. A name is what keeps a caller from having to parse a serialized query
36
- * back out of the key.
35
+ * How a slicing query's result is keyed: under the name it was given, else under what it slices (`2@x`), which
36
+ * is what a caller looks the result up by. Use {@link sliceResultKeys} for a whole request, as only there can
37
+ * two queries be seen to want the same key.
37
38
  */
38
- function sliceResultKey(query) {
39
- return query.name ?? JSON.stringify(query);
39
+ function sliceResultKey(query, describe) {
40
+ return query.name ?? describe(query);
41
+ }
42
+ /**
43
+ * The keys a whole request's results are reported under (see {@link sliceResultKey}). Two queries that differ
44
+ * only in their options would want the same key, and only one of them could be reported; those fall back to the
45
+ * serialized query, so nothing is silently merged. Two *identical* queries still share one entry, as they must.
46
+ */
47
+ function sliceResultKeys(queries, describe) {
48
+ const short = queries.map(q => sliceResultKey(q, describe));
49
+ const claimed = new Map();
50
+ const collided = new Set();
51
+ queries.forEach((query, i) => {
52
+ const serialized = JSON.stringify(query);
53
+ const first = claimed.get(short[i]);
54
+ if (first === undefined) {
55
+ claimed.set(short[i], serialized);
56
+ }
57
+ else if (first !== serialized) {
58
+ collided.add(short[i]);
59
+ }
60
+ });
61
+ return queries.map((query, i) => query.name === undefined && collided.has(short[i]) ? JSON.stringify(query) : short[i]);
40
62
  }
41
63
  /** Whether a result key is a serialized query rather than the name someone gave the slice. */
42
64
  function isSerializedQuery(key) {
@@ -2,7 +2,7 @@ import type { StaticSliceQuery, StaticSliceQueryResult } from './static-slice-qu
2
2
  import type { BasicQueryData } from '../../base-query-format';
3
3
  /**
4
4
  * The key a static slice query's result is reported under: the {@link SliceQueryOptions#name|name} it was given,
5
- * else the query itself, which is what makes two runs of the same slice one entry.
5
+ * else what it slices. Within a request use {@link sliceResultKeys}, which settles two queries wanting one key.
6
6
  */
7
7
  export declare function fingerPrintOfQuery(query: StaticSliceQuery): string;
8
8
  /**
@@ -7,12 +7,14 @@ const slice_query_options_1 = require("../slice-query-options");
7
7
  const log_1 = require("../../../util/log");
8
8
  const slice_direction_1 = require("../../../util/slice-direction");
9
9
  const df_helper_1 = require("../../../dataflow/graph/df-helper");
10
+ /** what a static slice is of, which is what its result is keyed by when it was given no name */
11
+ const slicedBy = (query) => query.criteria.join(',');
10
12
  /**
11
13
  * The key a static slice query's result is reported under: the {@link SliceQueryOptions#name|name} it was given,
12
- * else the query itself, which is what makes two runs of the same slice one entry.
14
+ * else what it slices. Within a request use {@link sliceResultKeys}, which settles two queries wanting one key.
13
15
  */
14
16
  function fingerPrintOfQuery(query) {
15
- return (0, slice_query_options_1.sliceResultKey)(query);
17
+ return (0, slice_query_options_1.sliceResultKey)(query, slicedBy);
16
18
  }
17
19
  /**
18
20
  * Execute static slice queries, catching duplicates with the same fingerprint
@@ -23,8 +25,9 @@ function fingerPrintOfQuery(query) {
23
25
  async function executeStaticSliceQuery({ analyzer }, queries) {
24
26
  const start = Date.now();
25
27
  const results = {};
26
- for (const query of queries) {
27
- const key = fingerPrintOfQuery(query);
28
+ const keys = (0, slice_query_options_1.sliceResultKeys)(queries, slicedBy);
29
+ for (const [at, query] of queries.entries()) {
30
+ const key = keys[at];
28
31
  if (results[key]) {
29
32
  log_1.log.warn(`Duplicate Key for slicing-query: ${key}, skipping...`);
30
33
  }
@@ -1,4 +1,4 @@
1
- import { type CallContextQuery } from './catalog/call-context-query/call-context-query-format';
1
+ import { type CallContextQuery, type CallContextQuerySubKindResult } from './catalog/call-context-query/call-context-query-format';
2
2
  import type { BaseQueryFormat, BaseQueryResult, BasicQueryData } from './base-query-format';
3
3
  import { type VirtualQueryArgumentsWithType } from './virtual-query/virtual-queries';
4
4
  import type { VirtualCompoundConstraint } from './virtual-query/compound-query';
@@ -36,7 +36,7 @@ import type { DoesCallQuery } from './catalog/does-call-query/does-call-query-fo
36
36
  import type { InspectExceptionQuery } from './catalog/inspect-exceptions-query/inspect-exception-query-format';
37
37
  import type { InputSourcesQuery } from './catalog/input-sources-query/input-sources-query-format';
38
38
  import type { ProvenanceQuery } from './catalog/provenance-query/provenance-query-format';
39
- import type { LintingResultCertainty } from '../linter/linter-format';
39
+ import type { LintingResult, LintingResultCertainty } from '../linter/linter-format';
40
40
  import { type DiceQuery } from './catalog/dice-query/dice-query-format';
41
41
  import { type GuessDepVersionsQuery } from './catalog/guess-dep-versions-query/guess-dep-versions-query-format';
42
42
  import { type AbsintQuery } from './catalog/absint-query/absint-query-format';
@@ -391,4 +391,58 @@ export declare function QueriesSchema(): Joi.ArraySchema<any[]>;
391
391
  * Wraps a function that executes a REPL query and, if it fails, checks whether there were any requests to analyze.
392
392
  */
393
393
  export declare function genericWrapReplFailIfNoRequest<T>(fn: () => Promise<T>, output: ReplOutput, analyzer: ReadonlyFlowrAnalysisProvider): Promise<T | undefined>;
394
+ /** What a query reports per key, for the queries that report anything per key. */
395
+ type ResultsOf<Type extends SupportedQueryTypes> = Awaited<QueryResult<Type>> extends {
396
+ readonly results: infer R;
397
+ } ? R : never;
398
+ /** The keys {@link ResultsOf} is indexed by, e.g. the slicing criterion a slice was taken at. */
399
+ type KeyOf<Type extends SupportedQueryTypes> = Extract<keyof ResultsOf<Type>, string>;
400
+ /** What one key of {@link ResultsOf} holds, e.g. one slice with its reconstruction. */
401
+ type ValueOf<Type extends SupportedQueryTypes> = ResultsOf<Type>[KeyOf<Type>];
402
+ /** One call a `call-context` query found, with the kind and subkind it was found under. */
403
+ export interface FoundCall extends CallContextQuerySubKindResult {
404
+ readonly kind: string;
405
+ readonly subkind: string;
406
+ }
407
+ /** One finding a `linter` query reported, with the rule that reported it. */
408
+ export interface FoundLint {
409
+ readonly rule: string;
410
+ readonly result: LintingResult;
411
+ }
412
+ /**
413
+ * Running queries and reading what they reported, without `Object.entries` and the casts it forces. Reading
414
+ * changes nothing: the results keep the shape they are serialized in.
415
+ * @example
416
+ * ```ts
417
+ * const out = await executeQueries({ analyzer }, [{ type: 'static-slice', criteria: ['2@x'] }]);
418
+ * Query.get(out, 'static-slice', '2@x'); // the slice taken at `2@x`
419
+ * Query.first(out, 'static-slice'); // the only slice, when one was asked for
420
+ * for(const [criterion, slice] of Query.entries(out, 'static-slice')) { ... }
421
+ * ```
422
+ */
423
+ export declare const Query: {
424
+ name: string;
425
+ /**
426
+ * Run a single query and answer with what it reported, so a caller asking one thing is handed that one
427
+ * thing instead of a {@link QueryResults} to index into.
428
+ */
429
+ one<Type extends SupportedQueryTypes>(this: void, data: BasicQueryData, query: Extract<Query, {
430
+ type: Type;
431
+ }>): Promise<Awaited<QueryResult<Type>>>;
432
+ /** Every key and result of one query, typed as that query reports them. */
433
+ entries<Base extends SupportedQueryTypes, Type extends Base>(this: void, results: QueryResults<Base>, type: Type): [KeyOf<Type>, ValueOf<Type>][];
434
+ /** Every result of one query, for when the keys are not what you are after. */
435
+ values<Base extends SupportedQueryTypes, Type extends Base>(this: void, results: QueryResults<Base>, type: Type): ValueOf<Type>[];
436
+ /** The result of one query under one key, `undefined` when it reported none. */
437
+ get<Base extends SupportedQueryTypes, Type extends Base>(this: void, results: QueryResults<Base>, type: Type, key: KeyOf<Type>): ValueOf<Type> | undefined;
438
+ /** The one result of a query that was asked for one thing, `undefined` when it reported none. */
439
+ first<Base extends SupportedQueryTypes, Type extends Base>(this: void, results: QueryResults<Base>, type: Type): ValueOf<Type> | undefined;
440
+ /**
441
+ * Every call a `call-context` query found, flat, each carrying the kind and subkind it was found under
442
+ * rather than leaving them as the two levels of record the result nests them in.
443
+ */
444
+ calls(this: void, results: Partial<QueryResults<"call-context">>): FoundCall[];
445
+ /** Every finding a `linter` query reported, flat, each carrying the rule that reported it. */
446
+ lints(this: void, results: Partial<QueryResults<"linter">>): FoundLint[];
447
+ };
394
448
  export {};
package/queries/query.js CHANGED
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.CompoundQuerySchema = exports.SupportedQueries = void 0;
6
+ exports.Query = exports.CompoundQuerySchema = exports.SupportedQueries = void 0;
7
7
  exports.queryWikiPage = queryWikiPage;
8
8
  exports.executeQueriesOfSameType = executeQueriesOfSameType;
9
9
  exports.executeQueries = executeQueries;
@@ -228,4 +228,69 @@ async function genericWrapReplFailIfNoRequest(fn, output, analyzer) {
228
228
  }
229
229
  }
230
230
  }
231
+ /**
232
+ * Running queries and reading what they reported, without `Object.entries` and the casts it forces. Reading
233
+ * changes nothing: the results keep the shape they are serialized in.
234
+ * @example
235
+ * ```ts
236
+ * const out = await executeQueries({ analyzer }, [{ type: 'static-slice', criteria: ['2@x'] }]);
237
+ * Query.get(out, 'static-slice', '2@x'); // the slice taken at `2@x`
238
+ * Query.first(out, 'static-slice'); // the only slice, when one was asked for
239
+ * for(const [criterion, slice] of Query.entries(out, 'static-slice')) { ... }
240
+ * ```
241
+ */
242
+ exports.Query = {
243
+ name: 'Query',
244
+ /**
245
+ * Run a single query and answer with what it reported, so a caller asking one thing is handed that one
246
+ * thing instead of a {@link QueryResults} to index into.
247
+ */
248
+ async one(data, query) {
249
+ const results = await executeQueries(data, [query]);
250
+ return results[query.type];
251
+ },
252
+ /** Every key and result of one query, typed as that query reports them. */
253
+ entries(results, type) {
254
+ const found = results[type];
255
+ return Object.entries(found?.results ?? {});
256
+ },
257
+ /** Every result of one query, for when the keys are not what you are after. */
258
+ values(results, type) {
259
+ return exports.Query.entries(results, type).map(([, value]) => value);
260
+ },
261
+ /** The result of one query under one key, `undefined` when it reported none. */
262
+ get(results, type, key) {
263
+ const found = results[type];
264
+ return found?.results?.[key];
265
+ },
266
+ /** The one result of a query that was asked for one thing, `undefined` when it reported none. */
267
+ first(results, type) {
268
+ return exports.Query.values(results, type)[0];
269
+ },
270
+ /**
271
+ * Every call a `call-context` query found, flat, each carrying the kind and subkind it was found under
272
+ * rather than leaving them as the two levels of record the result nests them in.
273
+ */
274
+ calls(results) {
275
+ const found = [];
276
+ for (const [kind, { subkinds }] of Object.entries(results['call-context']?.kinds ?? {})) {
277
+ for (const [subkind, hits] of Object.entries(subkinds)) {
278
+ for (const hit of hits) {
279
+ found.push({ ...hit, kind, subkind });
280
+ }
281
+ }
282
+ }
283
+ return found;
284
+ },
285
+ /** Every finding a `linter` query reported, flat, each carrying the rule that reported it. */
286
+ lints(results) {
287
+ const found = [];
288
+ for (const [rule, reported] of Object.entries(results['linter']?.results ?? {})) {
289
+ for (const result of reported.results ?? []) {
290
+ found.push({ rule, result });
291
+ }
292
+ }
293
+ return found;
294
+ }
295
+ };
231
296
  //# sourceMappingURL=query.js.map