@eagleoutice/flowr 2.17.10 → 2.17.12

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 (29) hide show
  1. package/abstract-interpretation/branch-paths-interpreter.js +12 -1
  2. package/benchmark/slicer.js +3 -1
  3. package/dataflow/environments/default-builtin-config/database-access.d.ts +1 -1
  4. package/dataflow/environments/default-builtin-config/database-access.js +3 -0
  5. package/dataflow/environments/default-builtin-config/index.d.ts +1 -1
  6. package/dataflow/extractor.js +8 -4
  7. package/dataflow/fn/argument-roles.js +17 -4
  8. package/dataflow/fn/guards/group-method-guards.js +13 -5
  9. package/dataflow/fn/strict-function.js +6 -2
  10. package/dataflow/graph/df-helper.d.ts +5 -0
  11. package/dataflow/graph/df-helper.js +22 -0
  12. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +135 -10
  13. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +2 -1
  14. package/dataflow/internal/program-order.d.ts +9 -0
  15. package/dataflow/internal/program-order.js +38 -2
  16. package/linter/linter-rules.d.ts +1 -0
  17. package/linter/rules/problematic-inputs.d.ts +3 -0
  18. package/linter/rules/problematic-inputs.js +12 -9
  19. package/linter/rules/undefined-symbol.js +3 -2
  20. package/package.json +5 -2
  21. package/project/sigdb/export-keys.d.ts +9 -0
  22. package/project/sigdb/export-keys.js +121 -0
  23. package/project/sigdb/reader.d.ts +7 -9
  24. package/project/sigdb/reader.js +24 -42
  25. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +0 -4
  26. package/queries/catalog/input-sources-query/simple-input-classifier.js +136 -38
  27. package/util/flowr-version.d.ts +1 -1
  28. package/util/flowr-version.js +2 -2
  29. package/util/mermaid/mermaid.js +1 -1
@@ -4,6 +4,10 @@ exports.ProgramOrder = void 0;
4
4
  const model_1 = require("../../r-bridge/lang-4.x/ast/model/model");
5
5
  const info_1 = require("../info");
6
6
  const edge_1 = require("../graph/edge");
7
+ const r_function_definition_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
8
+ const r_expression_list_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
9
+ const vertex_1 = require("../graph/vertex");
10
+ const built_in_proc_name_1 = require("../environments/built-in-proc-name");
7
11
  /**
8
12
  * Program order of top-level code outside loops and quotes: it runs once, so its definitions are not there yet for the statements before.
9
13
  * @helper dataflow
@@ -12,14 +16,22 @@ exports.ProgramOrder = {
12
16
  name: 'ProgramOrder',
13
17
  /** The top-level statement holding `id` if the program runs it once, in program order, `undefined` otherwise. */
14
18
  runsOnceAt(id, graph) {
19
+ return graph.getVertex(id)?.cds?.some(cd => info_1.ControlDependency.isIterated(cd, graph.idMap)) ? undefined : exports.ProgramOrder.runsWithin(id, graph);
20
+ },
21
+ /** The top-level statement holding `id` if it is top-level code outside quotes, also within a loop, whose every round ends before the next statement runs, `undefined` otherwise. */
22
+ runsWithin(id, graph) {
15
23
  const idMap = graph.idMap;
16
24
  const node = idMap?.get(id);
17
- if (idMap === undefined || node === undefined || !graph.isRoot(id)
18
- || graph.getVertex(id)?.cds?.some(cd => info_1.ControlDependency.isIterated(cd, idMap)) || graph.isQuoted(id)) {
25
+ if (idMap === undefined || node === undefined || !graph.isRoot(id) || graph.isQuoted(id)) {
19
26
  return undefined;
20
27
  }
21
28
  return model_1.RNode.topLevelStatement(node, idMap);
22
29
  },
30
+ /** Whether all of `id` is done before `later` starts: both are top-level code (see {@link ProgramOrder.runsWithin}), `later` in a later statement. */
31
+ runsBefore(id, later, graph) {
32
+ const at = exports.ProgramOrder.runsWithin(id, graph);
33
+ return at !== undefined && exports.ProgramOrder.runsWithin(later, graph) !== undefined && statementsAfter(later, at, graph) > 0;
34
+ },
23
35
  /** How many top-level statements of the same file after `statement` the top-level definition at `definition` is made, `0` for any other. */
24
36
  offset(definition, statement, graph) {
25
37
  return graph.isRoot(definition) ? statementsAfter(definition, statement, graph) : 0;
@@ -28,6 +40,30 @@ exports.ProgramOrder = {
28
40
  definedLater(definition, statement, graph) {
29
41
  return statementsAfter(definition, statement, graph) > 0;
30
42
  },
43
+ /**
44
+ * Whether the definition at `definition` is made only after `id` ran as the body of a function runs: both are directly in that body, the definition in a later statement of it,
45
+ * and each run of the function has a frame of its own. What a promise or an exit hook defers runs later.
46
+ */
47
+ boundLaterInBody(definition, id, graph) {
48
+ const idMap = graph.idMap;
49
+ const fn = idMap === undefined ? undefined : model_1.RNode.strictlyEnclosingFunction(id, idMap);
50
+ const body = fn === undefined ? undefined : idMap?.get(fn);
51
+ if (idMap === undefined || !r_function_definition_1.RFunctionDefinition.is(body) || !r_expression_list_1.RExpressionList.is(body.body) || model_1.RNode.strictlyEnclosingFunction(definition, idMap) !== fn
52
+ || graph.isQuoted(id) || graph.getVertex(id)?.cds?.some(cd => cd.byPromise)) {
53
+ return false;
54
+ }
55
+ const statementOf = (node) => {
56
+ for (; node !== undefined && node.info.parent !== body.body.info.id; node = node.info.parent === undefined ? undefined : idMap.get(node.info.parent)) {
57
+ if (vertex_1.DfgVertex.hasOrigin(graph.getVertex(node.info.id), built_in_proc_name_1.BuiltInProcName.RegisterHook)) {
58
+ return undefined;
59
+ }
60
+ }
61
+ return node;
62
+ };
63
+ const at = statementOf(idMap.get(id));
64
+ const made = statementOf(idMap.get(definition));
65
+ return at !== undefined && made !== undefined && made.info.index > at.info.index;
66
+ },
31
67
  /** For code the program runs once after `statement`, which surely makes the definition `write`: what that code reads no longer sees the definitions made before `statement`. */
32
68
  replaceEarlier(write, statement, graph, readsEarlier) {
33
69
  const before = (id) => exports.ProgramOrder.runsOnceAt(id, graph) !== undefined && exports.ProgramOrder.offset(id, statement, graph) < 0;
@@ -264,6 +264,7 @@ export declare const LintingRules: {
264
264
  readonly certainty: import("./linter-format").LintingRuleCertainty.BestEffort;
265
265
  readonly defaultConfig: (ctx: import("../project/context/flowr-analyzer-context").ReadOnlyFlowrAnalyzerContext) => {
266
266
  consider: readonly import("./rules/problematic-inputs").ConsiderSpec[];
267
+ reportConstantCommands: false;
267
268
  pipeCommandFunctions: readonly import("./rules/problematic-inputs").PipeCommandFunctionSpec[];
268
269
  };
269
270
  };
@@ -25,6 +25,8 @@ export interface ProblematicInputsResult extends LintingResult {
25
25
  }
26
26
  export interface ProblematicInputsConfig extends MergeableRecord {
27
27
  consider?: string | string[] | ConsiderSpec | ConsiderSpec[];
28
+ /** report a considered call without {@link ConsiderSpec.allowedInputTypes} even if it only receives constants (`system("ls")`), off by default */
29
+ reportConstantCommands?: boolean;
28
30
  inputFns?: InputClassifierConfig;
29
31
  pipeCommandFunctions?: PipeCommandFunctionSpec | PipeCommandFunctionSpec[];
30
32
  }
@@ -44,6 +46,7 @@ export declare const PROBLEMATIC_INPUTS: {
44
46
  readonly certainty: LintingRuleCertainty.BestEffort;
45
47
  readonly defaultConfig: (ctx: ReadOnlyFlowrAnalyzerContext) => {
46
48
  consider: readonly ConsiderSpec[];
49
+ reportConstantCommands: false;
47
50
  pipeCommandFunctions: readonly PipeCommandFunctionSpec[];
48
51
  };
49
52
  };
@@ -16,6 +16,8 @@ const identifier_1 = require("../../dataflow/environments/identifier");
16
16
  const strings_1 = require("../../util/text/strings");
17
17
  const query_fn_props_1 = require("../../dataflow/environments/query-fn-props");
18
18
  const resolve_argument_1 = require("../../dataflow/eval/resolve/resolve-argument");
19
+ const node_value_1 = require("../../dataflow/eval/resolve/node-value");
20
+ const resolve_helper_1 = require("../../dataflow/environments/resolve-helper");
19
21
  /** what runs a command, and what evaluates code beyond looking up a name (`get`) or calling a function it is handed (`do.call`) */
20
22
  function defaultConsider(index) {
21
23
  const evaluates = index.with(built_in_props_1.SemanticCallTag.Eval).filter(n => ((index.propsOf(n) ?? 0) & built_in_props_1.CallProp.Pure) === 0 && !index.get(n)?.sig?.some(([, p]) => (p & built_in_props_1.ArgProp.Callee) !== 0));
@@ -82,18 +84,18 @@ function isProblematicForAllowed(sources, evalValues, allowedTypes, allowedValue
82
84
  return false;
83
85
  }
84
86
  /** A path starting with `|` runs a command, so anything but a constant path, user input included, may start one. */
85
- function getPipeCommandValue(sources, allowedValues, disallowedValues) {
86
- for (const s of sources) {
87
- if (typeof s.value !== 'string' || !s.value.startsWith('|')) {
87
+ function getPipeCommandValue(values, allowedValues, disallowedValues) {
88
+ for (const value of values) {
89
+ if (typeof value !== 'string' || !value.startsWith('|')) {
88
90
  continue;
89
91
  }
90
- if (allowedValues !== undefined && allowedValues.test(s.value)) {
92
+ if (allowedValues !== undefined && allowedValues.test(value)) {
91
93
  continue;
92
94
  }
93
- if (disallowedValues !== undefined && !disallowedValues.test(s.value)) {
95
+ if (disallowedValues !== undefined && !disallowedValues.test(value)) {
94
96
  continue;
95
97
  }
96
- return s.value;
98
+ return value;
97
99
  }
98
100
  return undefined;
99
101
  }
@@ -141,7 +143,8 @@ exports.PROBLEMATIC_INPUTS = {
141
143
  const own = res[criterion] ?? [];
142
144
  /* a file argument that is an input itself (`pdf(readline())`) only shows as a source of the call */
143
145
  const sources = target === nid || own.some(s => s.id === target) ? own : own.concat((res[call] ?? []).filter(s => s.id === target));
144
- const pipeCommand = pipeSpec === undefined ? undefined : getPipeCommandValue(sources, pipeSpec.allowedValues, pipeSpec.disallowedValues);
146
+ /* a constant path is one of the values it may hold (`if(a) "|lpr" else "a.pdf"`), not only the one all of them agree on */
147
+ const pipeCommand = pipeSpec === undefined ? undefined : getPipeCommandValue([...sources.map(s => s.value), ...node_value_1.NodeValue.knownStringsOf(target, resolve_helper_1.Resolve.info(df.graph, data.inspectContext()))], pipeSpec.allowedValues, pipeSpec.disallowedValues);
145
148
  const evalValues = [];
146
149
  if (consider?.resolveSourceArgs) {
147
150
  for (const source of sources) {
@@ -151,7 +154,7 @@ exports.PROBLEMATIC_INPUTS = {
151
154
  }
152
155
  }
153
156
  }
154
- if (pipeCommand !== undefined || isProblematicForAllowed(sources, evalValues, consider?.allowedInputTypes ?? (pipeSpec !== undefined || sources.some(s => s.types.includes(simple_input_classifier_1.InputType.TempFile)) ? tempFileAccept : []), consider?.allowedValues, consider?.disallowedValues)) {
157
+ if (pipeCommand !== undefined || isProblematicForAllowed(sources, evalValues, consider?.allowedInputTypes ?? (!config.reportConstantCommands || pipeSpec !== undefined || sources.some(s => s.types.includes(simple_input_classifier_1.InputType.TempFile)) ? tempFileAccept : []), consider?.allowedValues, consider?.disallowedValues)) {
155
158
  seen.add(nid);
156
159
  const uncertain = pipeCommand === undefined && hasUnknownSource(sources);
157
160
  results.push({
@@ -184,7 +187,7 @@ exports.PROBLEMATIC_INPUTS = {
184
187
  description: 'Finds dynamic calls (e.g. eval, system) with non-constant inputs, and graphics-device calls (pdf, postscript) where a filename starts with \'|\' indicating a pipe command injection.',
185
188
  tags: [linter_tags_1.LintingRuleTag.Security, linter_tags_1.LintingRuleTag.Smell, linter_tags_1.LintingRuleTag.Readability, linter_tags_1.LintingRuleTag.Performance],
186
189
  certainty: linter_format_1.LintingRuleCertainty.BestEffort,
187
- defaultConfig: ctx => ({ consider: ctx.env.deriveFromIndex(defaultConsider), pipeCommandFunctions: defaultPipeCommandFunctions })
190
+ defaultConfig: ctx => ({ consider: ctx.env.deriveFromIndex(defaultConsider), reportConstantCommands: false, pipeCommandFunctions: defaultPipeCommandFunctions })
188
191
  }
189
192
  };
190
193
  //# sourceMappingURL=problematic-inputs.js.map
@@ -133,7 +133,7 @@ exports.UNDEFINED_SYMBOL = {
133
133
  const isExportedByLoadedPackage = (0, defaultmap_1.memoize)((name) => loadedPackages.some(p => p.has(name)) || isDatasetOfLoadedPackage(name) || [...importedByLoaded].some(p => exportsOf(p).has(name)));
134
134
  // hint an unloaded package that exports `name` (e.g. `ggplot` -> `ggplot2`), from the package database
135
135
  const attached = new Set(r_base_packages_1.AttachedBasePackages);
136
- const hintPackagesFor = (name) => deps.packagesExporting(name).filter(p => !attached.has(p)).slice(0, MaxHintPackages);
136
+ const hintPackagesFor = (0, defaultmap_1.memoize)((name) => deps.packagesExporting(name).filter(p => !attached.has(p)).slice(0, MaxHintPackages));
137
137
  /** shared resolution logic for a name used either as a function call or a variable */
138
138
  function check(node, name, namespace, kind) {
139
139
  const id = node.info.id;
@@ -177,7 +177,8 @@ exports.UNDEFINED_SYMBOL = {
177
177
  if (loc === undefined) {
178
178
  return undefined;
179
179
  }
180
- const availableInPackages = namespace === undefined ? hintPackagesFor(name) : [];
180
+ /* the database records no data sets, so only a called name has packages worth hinting at */
181
+ const availableInPackages = namespace === undefined && kind === 'function' ? hintPackagesFor(name) : [];
181
182
  return { certainty: linter_format_1.LintingResultCertainty.Uncertain, name, kind, involvedId: id, loc, ...(availableInPackages.length > 0 ? { availableInPackages } : {}) };
182
183
  }
183
184
  /** the symbol to check if the config asks for it: a called function, or a plain symbol read */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eagleoutice/flowr",
3
- "version": "2.17.10",
3
+ "version": "2.17.12",
4
4
  "description": "Static Dataflow Analyzer and Program Slicer for the R Programming Language",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -34,7 +34,10 @@
34
34
  "undici": "^7.30.1"
35
35
  },
36
36
  "glob": "^14.0.2",
37
- "minimatch": "^11.0.1"
37
+ "minimatch": "^11.0.1",
38
+ "typedoc": {
39
+ "minimatch": "^10.2.5"
40
+ }
38
41
  },
39
42
  "dependencies": {
40
43
  "@davisvaughan/tree-sitter-r": "^1.2.0",
@@ -0,0 +1,9 @@
1
+ export interface ExportKeys {
2
+ /** the ordinals of the packages exporting the name with dictionary id `id`, ascending */
3
+ ordinalsOf(id: number): number[];
4
+ }
5
+ /**
6
+ * The export index of a bundle of `packages` packages: the one persisted for `bundleFile` when there is one, otherwise
7
+ * derived from `pairs` (computed on demand) and persisted for the next process. Without a file, kept in memory only.
8
+ */
9
+ export declare function exportKeysFor(bundleFile: string | undefined, packages: number, pairs: () => Iterable<readonly [id: number, ordinal: number]>): ExportKeys;
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.exportKeysFor = exportKeysFor;
7
+ /**
8
+ * The reverse index of a bundle, `dictionary id of a name -> the packages exporting it`, kept as one sorted run of numbers
9
+ * (`id * {@link OrdinalStride} + package ordinal`) so a lookup is a binary search. Deriving it decodes every package, so
10
+ * {@link ExportKeys.persist|persisting} it next to the bundle lets later processes answer from a few ranged reads.
11
+ */
12
+ const fs_1 = __importDefault(require("fs"));
13
+ const decompress_1 = require("./decompress");
14
+ /** the ordinals of a bundle's packages stay below this, so a key keeps the name id and the ordinal apart exactly */
15
+ const OrdinalStride = 2 ** 21;
16
+ const KeyBytes = Float64Array.BYTES_PER_ELEMENT;
17
+ /** the file extension of the persisted index, appended to the plain bundle */
18
+ const ExportKeysExt = '.exports';
19
+ /** the index over `keys`, which {@link buildKeys} sorted */
20
+ function inMemory(keys) {
21
+ return { ordinalsOf: id => collect(keys.length, at => keys[at], id) };
22
+ }
23
+ /** the sorted keys of the `[name id, package ordinal]` pairs, each pair once */
24
+ function buildKeys(pairs) {
25
+ const keys = Float64Array.from(pairs, ([id, ordinal]) => id * OrdinalStride + ordinal).sort();
26
+ let unique = 0;
27
+ for (let i = 0; i < keys.length; i++) {
28
+ if (i === 0 || keys[i] !== keys[i - 1]) {
29
+ keys[unique++] = keys[i];
30
+ }
31
+ }
32
+ return keys.slice(0, unique);
33
+ }
34
+ /** the ordinals of the keys of `id`, off a sorted run read through `keyAt` */
35
+ function collect(count, keyAt, id) {
36
+ let lo = 0, hi = count;
37
+ while (lo < hi) {
38
+ const mid = (lo + hi) >> 1;
39
+ if (keyAt(mid) < id * OrdinalStride) {
40
+ lo = mid + 1;
41
+ }
42
+ else {
43
+ hi = mid;
44
+ }
45
+ }
46
+ const ordinals = [];
47
+ for (let key = lo < count ? keyAt(lo) : Infinity; key < (id + 1) * OrdinalStride; key = ++lo < count ? keyAt(lo) : Infinity) {
48
+ ordinals.push(key % OrdinalStride);
49
+ }
50
+ return ordinals;
51
+ }
52
+ const StampKeys = 2;
53
+ /** the persisted index at `file` when it exists and was derived for `stamp`, answering by ranged reads */
54
+ function readPersisted(file, stamp) {
55
+ let size;
56
+ try {
57
+ size = fs_1.default.statSync(file).size;
58
+ }
59
+ catch {
60
+ return undefined;
61
+ }
62
+ const head = Buffer.allocUnsafe(KeyBytes);
63
+ const at = (fd, i) => (fs_1.default.readSync(fd, head, 0, KeyBytes, i * KeyBytes), head.readDoubleLE(0));
64
+ const count = size / KeyBytes - StampKeys;
65
+ const fd = fs_1.default.openSync(file, 'r');
66
+ try {
67
+ if (!Number.isInteger(count) || count < 0 || stamp.some((s, i) => at(fd, i) !== s)) {
68
+ return undefined;
69
+ }
70
+ }
71
+ finally {
72
+ fs_1.default.closeSync(fd);
73
+ }
74
+ return {
75
+ ordinalsOf: id => {
76
+ const reading = fs_1.default.openSync(file, 'r');
77
+ try {
78
+ return collect(count, i => at(reading, i + StampKeys), id);
79
+ }
80
+ finally {
81
+ fs_1.default.closeSync(reading);
82
+ }
83
+ }
84
+ };
85
+ }
86
+ /** write the index next to the bundle, not failing the query when the directory does not let us */
87
+ function persist(file, stamp, keys) {
88
+ const tmp = (0, decompress_1.uniqueTempPath)(file, 'tmp');
89
+ try {
90
+ const out = new Float64Array(keys.length + StampKeys);
91
+ out.set(stamp);
92
+ out.set(keys, StampKeys);
93
+ fs_1.default.writeFileSync(tmp, new Uint8Array(out.buffer));
94
+ (0, decompress_1.moveIntoPlace)(tmp, file);
95
+ }
96
+ catch {
97
+ /* read-only location: the index then lives for this process only */
98
+ }
99
+ finally {
100
+ fs_1.default.rmSync(tmp, { force: true });
101
+ }
102
+ }
103
+ /**
104
+ * The export index of a bundle of `packages` packages: the one persisted for `bundleFile` when there is one, otherwise
105
+ * derived from `pairs` (computed on demand) and persisted for the next process. Without a file, kept in memory only.
106
+ */
107
+ function exportKeysFor(bundleFile, packages, pairs) {
108
+ const file = bundleFile === undefined ? undefined : bundleFile + ExportKeysExt;
109
+ const stamp = bundleFile === undefined ? undefined : [packages, fs_1.default.statSync(bundleFile).mtimeMs];
110
+ const persisted = file === undefined || stamp === undefined ? undefined : readPersisted(file, stamp);
111
+ if (persisted !== undefined) {
112
+ return persisted;
113
+ }
114
+ const keys = buildKeys(pairs());
115
+ if (file === undefined || stamp === undefined) {
116
+ return inMemory(keys);
117
+ }
118
+ persist(file, stamp, keys);
119
+ return readPersisted(file, stamp) ?? inMemory(keys);
120
+ }
121
+ //# sourceMappingURL=export-keys.js.map
@@ -200,6 +200,10 @@ export declare class SigDatabase extends HistorySource implements PackageSignatu
200
200
  */
201
201
  private readonly outlines;
202
202
  private readonly fd;
203
+ /** the plain bundle file, `undefined` for an in-memory one */
204
+ private readonly file;
205
+ /** what {@link packagesExporting} reads, derived (or read from where an earlier process left it) on the first call */
206
+ private exportKeys;
203
207
  /** the dictionary, or how to load it: a bundle asked only for the versions it holds never needs its names */
204
208
  private dictionary;
205
209
  readonly index: SigDbIndex;
@@ -232,11 +236,6 @@ export declare class SigDatabase extends HistorySource implements PackageSignatu
232
236
  * nothing is known about the package yet, so this only ever skips work that would have found nothing.
233
237
  */
234
238
  private mayOffer;
235
- /**
236
- * Whether `pkg` may offer the name with dictionary id `id`, deciding from the raw bytes of a blob not decoded yet: every `[id,` they hold may
237
- * start a function record, so their ids are a superset of the names the package has, kept for {@link mayOffer} as {@link nameIdsOfBlob}.
238
- */
239
- private mayHoldNameId;
240
239
  /** drop one decoded blob, for the shared budget to reclaim what it costs (see {@link keepBlob}) */
241
240
  dropBlob(blobIdx: number): void;
242
241
  /** store `value` under `key`, dropping the oldest entry first once the cache sits at `cap` */
@@ -259,12 +258,11 @@ export declare class SigDatabase extends HistorySource implements PackageSignatu
259
258
  lookup(pkg: BrandedNamespace, version?: string): LibraryExports | undefined;
260
259
  packagesExporting(name: BrandedIdentifier): readonly BrandedNamespace[];
261
260
  /**
262
- * Whether the newest version of `pkg` exports the name with dictionary id `id`. The same answer
263
- * {@link lookup}'s `exported` gives, off the function records themselves: asking a package at a time is what
264
- * {@link packagesExporting} does, and deriving a whole export view per package to read one name out of it is not
261
+ * Every `[name id, package ordinal]` the newest version of a package exports, the same answer {@link lookup}'s `exported` gives
262
+ * off the function records themselves: deriving a whole export view per package to read the names out of it is not
265
263
  * worth the five arrays and the map it builds.
266
264
  */
267
- private exportsNameId;
265
+ private exportedPairs;
268
266
  /**
269
267
  * Resolve a package version to its blob and the function records of that version (the shared prologue of
270
268
  * {@link functions}/{@link functionByName}). The blob comes from {@link blob} every time rather than out of
@@ -24,6 +24,7 @@ const decode_1 = require("./decode");
24
24
  const decompress_1 = require("./decompress");
25
25
  const codec_1 = require("./codec");
26
26
  const dict_1 = require("./dict");
27
+ const export_keys_1 = require("./export-keys");
27
28
  const hash_1 = require("./hash");
28
29
  const manifest_1 = require("./manifest");
29
30
  const arrays_1 = require("../../util/collections/arrays");
@@ -407,14 +408,19 @@ class SigDatabase extends HistorySource {
407
408
  */
408
409
  outlines = new Map();
409
410
  fd;
411
+ /** the plain bundle file, `undefined` for an in-memory one */
412
+ file;
413
+ /** what {@link packagesExporting} reads, derived (or read from where an earlier process left it) on the first call */
414
+ exportKeys;
410
415
  /** the dictionary, or how to load it: a bundle asked only for the versions it holds never needs its names */
411
416
  dictionary;
412
417
  index;
413
418
  content;
414
419
  cranBase;
415
- constructor(fd, strings, index, content, cranBase) {
420
+ constructor(fd, file, strings, index, content, cranBase) {
416
421
  super();
417
422
  this.fd = fd;
423
+ this.file = file;
418
424
  this.dictionary = strings;
419
425
  this.index = index;
420
426
  this.content = content;
@@ -423,7 +429,7 @@ class SigDatabase extends HistorySource {
423
429
  /** Use an already-built {@link SigDb} directly, no file involved: its blobs start out in the cache, so a test needs only {@link SigDbBuilder} plus this. */
424
430
  static fromMemory(db) {
425
431
  const index = { byteCount: 0, dict: [0, 0], blobs: [], pkgs: db.pkgs, meta: db.meta };
426
- const source = new SigDatabase(NoFile, dict_1.SigDict.of(db.strings), index, db.content, db.cranBase ?? schema_1.DefaultCranBase);
432
+ const source = new SigDatabase(NoFile, undefined, dict_1.SigDict.of(db.strings), index, db.content, db.cranBase ?? schema_1.DefaultCranBase);
427
433
  db.blobs.forEach((blob, i) => source.blobCache.set(i, { blob }));
428
434
  return source;
429
435
  }
@@ -453,7 +459,7 @@ class SigDatabase extends HistorySource {
453
459
  }
454
460
  }
455
461
  const cranBase = header?.cranBase ?? schema_1.DefaultCranBase;
456
- return new SigDatabase(fd, strings, index, header?.content, cranBase);
462
+ return new SigDatabase(fd, plainFile, strings, index, header?.content, cranBase);
457
463
  }
458
464
  /** open a `.sigs.ndjson`, `.br` or `.gz`; compressed sources are decompressed into a hash-keyed cache once */
459
465
  static async open(source, opts = {}) {
@@ -546,32 +552,6 @@ class SigDatabase extends HistorySource {
546
552
  }
547
553
  return false;
548
554
  }
549
- /**
550
- * Whether `pkg` may offer the name with dictionary id `id`, deciding from the raw bytes of a blob not decoded yet: every `[id,` they hold may
551
- * start a function record, so their ids are a superset of the names the package has, kept for {@link mayOffer} as {@link nameIdsOfBlob}.
552
- */
553
- mayHoldNameId(pkg, name) {
554
- const blobIdx = this.index.pkgs[pkg];
555
- if (blobIdx === undefined || this.fd === NoFile || this.blobCache.has(blobIdx) || this.nameIdsOfBlob.has(blobIdx)) {
556
- return true;
557
- }
558
- const [start, bytes] = this.index.blobs[blobIdx];
559
- const buf = Buffer.allocUnsafe(bytes);
560
- fs_1.default.readSync(this.fd, buf, 0, bytes, start);
561
- const ids = new Set();
562
- for (let at = buf.indexOf(91); at >= 0; at = buf.indexOf(91, at + 1)) {
563
- let num = 0;
564
- let end = at + 1;
565
- for (; end < bytes && buf[end] >= 48 && buf[end] <= 57; end++) {
566
- num = num * 10 + buf[end] - 48;
567
- }
568
- if (end > at + 1 && buf[end] === 44) {
569
- ids.add(num);
570
- }
571
- }
572
- this.nameIdsOfBlob.set(blobIdx, Int32Array.from(ids).sort());
573
- return this.mayOffer(pkg, name);
574
- }
575
555
  /** drop one decoded blob, for the shared budget to reclaim what it costs (see {@link keepBlob}) */
576
556
  dropBlob(blobIdx) {
577
557
  this.blobCache.delete(blobIdx);
@@ -652,23 +632,25 @@ class SigDatabase extends HistorySource {
652
632
  if (id < 0) {
653
633
  return [];
654
634
  }
655
- const found = [];
656
- for (const pkg in this.index.pkgs) {
657
- if (this.mayHoldNameId(pkg, name) && this.mayOffer(pkg, name) && this.exportsNameId(pkg, id)) {
658
- found.push(pkg);
659
- }
660
- }
661
- return found.sort((a, b) => this.downloads(b) - this.downloads(a) || (0, strings_1.compareByCodeUnit)(a, b));
635
+ const names = Object.keys(this.index.pkgs);
636
+ this.exportKeys ??= (0, export_keys_1.exportKeysFor)(this.file, names.length, () => this.exportedPairs(names));
637
+ return this.exportKeys.ordinalsOf(id).map(ordinal => names[ordinal]).sort((a, b) => this.downloads(b) - this.downloads(a) || (0, strings_1.compareByCodeUnit)(a, b));
662
638
  }
663
639
  /**
664
- * Whether the newest version of `pkg` exports the name with dictionary id `id`. The same answer
665
- * {@link lookup}'s `exported` gives, off the function records themselves: asking a package at a time is what
666
- * {@link packagesExporting} does, and deriving a whole export view per package to read one name out of it is not
640
+ * Every `[name id, package ordinal]` the newest version of a package exports, the same answer {@link lookup}'s `exported` gives
641
+ * off the function records themselves: deriving a whole export view per package to read the names out of it is not
667
642
  * worth the five arrays and the map it builds.
668
643
  */
669
- exportsNameId(pkg, id) {
670
- const r = this.versionFns(pkg);
671
- return r?.fns.idxs.some(i => r.blob.fns[i][0] === id && (r.blob.fns[i][3] & 1 /* FnProp.Exported */) !== 0) ?? false;
644
+ *exportedPairs(names) {
645
+ for (const [ordinal, pkg] of names.entries()) {
646
+ const r = this.versionFns(pkg);
647
+ for (const i of r?.fns.idxs ?? []) {
648
+ const fn = r?.blob.fns[i];
649
+ if (fn !== undefined && (fn[3] & 1 /* FnProp.Exported */) !== 0) {
650
+ yield [fn[0], ordinal];
651
+ }
652
+ }
653
+ }
672
654
  }
673
655
  /**
674
656
  * Resolve a package version to its blob and the function records of that version (the shared prologue of
@@ -87,10 +87,6 @@ export interface InputSource extends MergeableRecord {
87
87
  }
88
88
  /** The input sources of a criterion, each classified with an {@link InputSource} object. */
89
89
  export type InputSources = InputSource[];
90
- /**
91
- * This is either an {@link NodeId|id} of a known functions all of that category (e.g., you can issue a dependencies query before and then pass all
92
- * identified ids to this query here).
93
- */
94
90
  export type InputClassifierFunctionIdentifiers = readonly (Identifier | NodeId)[];
95
91
  /** For the specifications of `pure` etc. please have a look at {@link InputClassifierFunctionIdentifiers}. */
96
92
  export interface InputClassifierConfig<Functions extends InputClassifierFunctionIdentifiers | FlowrSearchLike = readonly Identifier[] | FlowrSearchLike> extends Partial<Record<InputType, Functions>> {