@eagleoutice/flowr 2.13.2 → 2.13.3

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 (97) hide show
  1. package/README.md +46 -44
  2. package/abstract-interpretation/data-frame/mappers/access-mapper.js +1 -0
  3. package/abstract-interpretation/data-frame/mappers/function-mapper.d.ts +1 -1
  4. package/abstract-interpretation/data-frame/mappers/function-mapper.js +3 -0
  5. package/abstract-interpretation/domains/state-domain-like.d.ts +1 -1
  6. package/config.d.ts +8 -0
  7. package/config.js +9 -1
  8. package/control-flow/control-flow-graph.js +2 -1
  9. package/control-flow/semantic-cfg-guided-visitor.d.ts +1 -1
  10. package/core/steps/all/core/11-normalize-tree-sitter.d.ts +1 -1
  11. package/dataflow/environments/append.d.ts +1 -1
  12. package/dataflow/environments/clone.d.ts +1 -1
  13. package/dataflow/environments/environment.d.ts +28 -4
  14. package/dataflow/environments/environment.js +66 -11
  15. package/dataflow/environments/overwrite.d.ts +1 -1
  16. package/dataflow/eval/resolve/alias-tracking.d.ts +1 -1
  17. package/dataflow/graph/dataflowgraph-builder.d.ts +1 -1
  18. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +1 -1
  19. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +1 -1
  20. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +7 -0
  21. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +51 -0
  22. package/dataflow/internal/process/functions/call/built-in/built-in-eval.d.ts +1 -1
  23. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +1 -1
  24. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.d.ts +1 -1
  25. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +5 -2
  26. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +15 -9
  27. package/dataflow/internal/process/functions/call/built-in/built-in-list.d.ts +1 -1
  28. package/dataflow/internal/process/functions/call/built-in/built-in-quote.d.ts +1 -1
  29. package/dataflow/internal/process/functions/call/built-in/built-in-register-hook.d.ts +1 -1
  30. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-dispatch.d.ts +1 -1
  31. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.d.ts +7 -1
  32. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +9 -2
  33. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.d.ts +1 -1
  34. package/dataflow/internal/process/functions/call/built-in/built-in-stack-env.js +2 -2
  35. package/dataflow/internal/process/functions/call/built-in/built-in-vector.d.ts +1 -1
  36. package/documentation/doc-readme.js +14 -12
  37. package/documentation/doc-util/doc-normalized-ast.d.ts +1 -1
  38. package/documentation/wiki-dataflow-graph.js +4 -24
  39. package/documentation/wiki-query.js +47 -0
  40. package/documentation/wiki-signature-database.js +3 -2
  41. package/linter/rules/dataframe-access-validation.d.ts +1 -1
  42. package/linter/rules/undefined-symbol-util.js +3 -1
  43. package/linter/rules/undefined-symbol.js +3 -4
  44. package/package.json +21 -9
  45. package/project/context/flowr-analyzer-context.d.ts +4 -4
  46. package/project/context/flowr-analyzer-context.js +3 -3
  47. package/project/context/flowr-analyzer-dependencies-context.d.ts +11 -5
  48. package/project/context/flowr-analyzer-dependencies-context.js +8 -3
  49. package/project/context/flowr-analyzer-meta-context.d.ts +1 -0
  50. package/project/dependency-version-space.d.ts +118 -26
  51. package/project/dependency-version-space.js +343 -87
  52. package/project/plugins/file-plugins/files/flowr-description-file.d.ts +4 -0
  53. package/project/plugins/file-plugins/files/flowr-description-file.js +8 -1
  54. package/project/plugins/file-plugins/files/flowr-rda-file.js +27 -25
  55. package/project/plugins/file-plugins/notebooks/flowr-analyzer-rmd-file-plugin.d.ts +1 -1
  56. package/project/plugins/file-plugins/notebooks/flowr-analyzer-sweave-file-plugin.d.ts +1 -1
  57. package/project/plugins/package-version-plugins/flowr-analyzer-meta-description-file-plugin.js +2 -1
  58. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +1 -1
  59. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +4 -4
  60. package/project/plugins/package-version-plugins/package.d.ts +27 -10
  61. package/project/plugins/package-version-plugins/package.js +50 -25
  62. package/project/sigdb/reader.d.ts +26 -16
  63. package/project/sigdb/reader.js +52 -21
  64. package/queries/catalog/dependencies-query/dependencies-query-executor.js +1 -1
  65. package/queries/catalog/dependencies-query/dependencies-query-format.d.ts +2 -2
  66. package/queries/catalog/dependencies-query/dependencies-query-format.js +2 -2
  67. package/queries/catalog/does-call-query/does-call-query-format.d.ts +1 -1
  68. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-executor.js +39 -77
  69. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.d.ts +12 -0
  70. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.js +53 -23
  71. package/queries/catalog/input-sources-query/input-source-functions.d.ts +13 -0
  72. package/queries/catalog/input-sources-query/input-source-functions.js +96 -1
  73. package/queries/catalog/input-sources-query/input-sources-query-executor.js +40 -4
  74. package/queries/catalog/input-sources-query/input-sources-query-format.js +21 -3
  75. package/queries/catalog/input-sources-query/input-types.d.ts +58 -0
  76. package/queries/catalog/input-sources-query/input-types.js +64 -0
  77. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +62 -52
  78. package/queries/catalog/input-sources-query/simple-input-classifier.js +334 -101
  79. package/queries/catalog/project-query/project-query-executor.js +1 -1
  80. package/queries/catalog/signature-query/signature-query-executor.d.ts +7 -1
  81. package/queries/catalog/signature-query/signature-query-executor.js +112 -39
  82. package/queries/catalog/signature-query/signature-query-format.d.ts +5 -1
  83. package/queries/catalog/signature-query/signature-query-format.js +1 -1
  84. package/queries/catalog/signature-query/signature-query-render.js +8 -3
  85. package/r-bridge/lang-4.x/ast/parser/json/format.js +1 -1
  86. package/r-bridge/retriever.d.ts +1 -1
  87. package/search/flowr-search-printer.js +10 -8
  88. package/slicing/static/static-slicer.d.ts +2 -2
  89. package/util/objects.js +6 -4
  90. package/util/r-base-packages.d.ts +2 -0
  91. package/util/r-base-packages.js +3 -0
  92. package/util/r-license.js +1 -4
  93. package/util/r-version.d.ts +12 -0
  94. package/util/r-version.js +16 -0
  95. package/util/range.d.ts +6 -2
  96. package/util/range.js +33 -15
  97. package/util/version.js +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NoDisabledSources = exports.DefaultFixpointIterations = exports.DefaultExplodeLimit = void 0;
3
+ exports.NoDisabledSources = exports.VersionSpace = exports.DefaultFixpointIterations = exports.DefaultExplodeLimit = exports.ProjectPackage = void 0;
4
4
  exports.dateCutoff = dateCutoff;
5
5
  exports.isoDay = isoDay;
6
6
  exports.collectUsage = collectUsage;
@@ -9,7 +9,6 @@ exports.collectTransitiveConstraints = collectTransitiveConstraints;
9
9
  exports.iterateToFixpoint = iterateToFixpoint;
10
10
  exports.enforceArcConsistency = enforceArcConsistency;
11
11
  exports.countRunnableCombinations = countRunnableCombinations;
12
- exports.versionMeetsPartners = versionMeetsPartners;
13
12
  exports.survivingEntries = survivingEntries;
14
13
  exports.timelinePackageKey = timelinePackageKey;
15
14
  exports.orderedCandidatesOf = orderedCandidatesOf;
@@ -35,6 +34,9 @@ const vertex_1 = require("../dataflow/graph/vertex");
35
34
  const graph_1 = require("../dataflow/graph/graph");
36
35
  const df_helper_1 = require("../dataflow/graph/df-helper");
37
36
  const type_1 = require("../r-bridge/lang-4.x/ast/model/type");
37
+ const built_in_s_seven_new_generic_1 = require("../dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic");
38
+ /** the pseudo-package standing for the analyzed project itself, never one of its own dependencies */
39
+ exports.ProjectPackage = 'current';
38
40
  /** default safety cap on how many assignments {@link explodeDependencyVersions} yields */
39
41
  exports.DefaultExplodeLimit = 256;
40
42
  /** the date cutoff (end of the named day/month/year) for a `YYYY.MM.DD` spec, or `undefined` if malformed */
@@ -62,7 +64,7 @@ function makeFnResolver(src, name) {
62
64
  * directives, flattened across every generic), deduplicated.
63
65
  */
64
66
  function projectS3Classes(deps) {
65
- const generics = deps.getDependency('current')?.namespaceInfo?.exportS3Generics;
67
+ const generics = deps.getDependency(exports.ProjectPackage)?.namespaceInfo?.exportS3Generics;
66
68
  return new Set([...(generics?.values() ?? [])].flat());
67
69
  }
68
70
  /** builtins whose string-literal argument names an S3/S4 class in use, and which slot carries it */
@@ -115,6 +117,14 @@ function collectCodeClassUses(graph) {
115
117
  * Mark the package that OWNS a used S3/S4 class as used, from the project's NAMESPACE `S3method`/`exportClasses`
116
118
  * registrations and from class-name literals in the code. The same-named constructor is recorded as a synthetic
117
119
  * use so the version is bounded by its function-export history, not by the pre-NAMESPACE-biased `s3Classes` set.
120
+ *
121
+ * The owner is looked for among the packages already in play (called or declared). A NAMESPACE registration is
122
+ * deliberate wiring, so it may still introduce a package from outside that set, but only for a project that declares
123
+ * no dependencies at all. Class names collide heavily across CRAN: with declared dependencies present, the
124
+ * whole-database {@link PackageSignatureSource.classOwner} answer is decided by database order (attributing `POSIXlt`
125
+ * or `function` to whichever unrelated package comes first), so it is a collision far more often than a hidden
126
+ * dependency, and it costs reading every package in the database. A class-name literal in code is weaker still and
127
+ * may only ever refine a package already in play.
118
128
  */
119
129
  function addClassOwnershipUsage(usage, deps, graph) {
120
130
  const namespaceClasses = projectS3Classes(deps);
@@ -123,18 +133,17 @@ function addClassOwnershipUsage(usage, deps, graph) {
123
133
  return;
124
134
  }
125
135
  const sources = deps.signatureSources();
126
- // a class-name literal in code is weak (names collide across CRAN): it may only refine an existing dependency,
127
- // never introduce one; a NAMESPACE registration is deliberate wiring, so it may introduce the owner
128
- const anchored = new Set([...usage.keys(), ...deps.getDependencies().map(d => d.name)]);
129
- const attribute = (cls, mayIntroduce) => {
130
- for (const src of sources) {
131
- const owner = src.classOwner(cls);
136
+ const declared = deps.declaredPackageNames();
137
+ // `current` is the analyzed project itself, not a dependency (see `defaultTargets`)
138
+ const anchored = new Set([...usage.keys(), ...deps.getDependencies().map(d => d.name), ...declared].filter(n => n !== exports.ProjectPackage));
139
+ const owners = sources.map(src => (0, reader_1.classOwnerIndexFor)(src, anchored));
140
+ const mayIntroduce = declared.length === 0;
141
+ const attribute = (cls, fromNamespace) => {
142
+ for (const [i, src] of sources.entries()) {
143
+ const owner = owners[i].get(cls) ?? (fromNamespace && mayIntroduce ? src.classOwner(cls) : undefined);
132
144
  if (owner === undefined) {
133
145
  continue;
134
146
  }
135
- if (!mayIntroduce && !anchored.has(owner)) {
136
- return;
137
- }
138
147
  let pkgUsage = usage.get(owner);
139
148
  if (pkgUsage === undefined) {
140
149
  pkgUsage = new Map();
@@ -154,6 +163,14 @@ function addClassOwnershipUsage(usage, deps, graph) {
154
163
  attribute(cls, false);
155
164
  }
156
165
  }
166
+ /**
167
+ * Whether an argument was synthesized by flowR rather than written in the code. Such an argument is not evidence of
168
+ * how the package is called, so a signature that lacks its parameter must not reject the version (S7's `new_class`
169
+ * has no `fun` parameter, yet flowR appends one to model the constructor it returns).
170
+ */
171
+ function isSyntheticArgument(arg) {
172
+ return !graph_1.FunctionArgument.isEmpty(arg) && String(arg.nodeId).endsWith(built_in_s_seven_new_generic_1.S7SyntheticFunArgSuffix);
173
+ }
157
174
  /** scan the dataflow graph for every call that resolves (via {@link Dataflow.qualify}) to a package export */
158
175
  function collectUsage(graph, deps) {
159
176
  const usage = new Map();
@@ -178,9 +195,10 @@ function collectUsage(graph, deps) {
178
195
  entry = { named: new Set(), calls: new Map() };
179
196
  pkgUsage.set(fn, entry);
180
197
  }
198
+ const args = vertex.args.some(isSyntheticArgument) ? vertex.args.filter(a => !isSyntheticArgument(a)) : vertex.args;
181
199
  const named = [];
182
200
  let positional = 0;
183
- for (const arg of vertex.args) {
201
+ for (const arg of args) {
184
202
  if (graph_1.FunctionArgument.isNamed(arg)) {
185
203
  entry.named.add(arg.name);
186
204
  named.push(arg.name);
@@ -192,7 +210,7 @@ function collectUsage(graph, deps) {
192
210
  // dedupe by call shape: named names + positional count
193
211
  const key = named.sort().join(',') + '#' + positional;
194
212
  if (!entry.calls.has(key)) {
195
- entry.calls.set(key, [...vertex.args]);
213
+ entry.calls.set(key, [...args]);
196
214
  }
197
215
  }
198
216
  if (deps) {
@@ -237,8 +255,8 @@ function isCompatible(getFn, version, usage, tracked) {
237
255
  }
238
256
  /**
239
257
  * Whether a named argument would bind to a parameter of `decoded` under R's matching (exact, pmatch, or `...`).
240
- * `undefined` (the function is absent) is a no; an empty capture -- a generic like `seq` whose formals became
241
- * `UseMethod`, or a data gap -- is uninformative and treated as accepting (so it never reports a false removal).
258
+ * `undefined` (the function is absent) is a no; an empty capture (a generic like `seq` whose formals became
259
+ * `UseMethod`, or a data gap) is uninformative and treated as accepting (so it never reports a false removal).
242
260
  */
243
261
  function argumentSupported(decoded, arg) {
244
262
  if (decoded === undefined) {
@@ -291,7 +309,7 @@ function addSignatureEvidence(observe, src, getFn, pkg, usage, timeline) {
291
309
  }
292
310
  }
293
311
  }
294
- /** intersection of multiple survivor sets -- versions that survive in every set */
312
+ /** intersection of multiple survivor sets: versions that survive in every set */
295
313
  function intersectSurvivors(survivorSets) {
296
314
  if (survivorSets.length === 0) {
297
315
  return [];
@@ -301,29 +319,77 @@ function intersectSurvivors(survivorSets) {
301
319
  return first.filter(e => restVersions.every(set => set.has(e.ver)));
302
320
  }
303
321
  /**
304
- * The transitive constraints declared packages place on their own dependencies (one level deep). `versionOf` overrides
305
- * which version of each declaring package to read the requirements from -- passing the previous pass's guessed versions
306
- * lets two packages tighten each other (a bounded fixpoint over mutual constraints).
322
+ * Collapse alternative requirements that are all simple lower bounds (or all simple upper bounds) into the single
323
+ * weakest one, which *is* their union: `>= 3.5.0 || >= 4.0.0` is just `>= 3.5.0`. This filters identically and keeps
324
+ * a package with a long release history from reporting a dozen redundant alternatives.
325
+ */
326
+ function collapseAlternatives(ranges) {
327
+ if (ranges.length < 2) {
328
+ return ranges;
329
+ }
330
+ // only single-comparator ranges are comparable this cheaply; anything compound (`>=1.0 <2.0`) keeps its alternatives
331
+ const simple = ranges.map(r => r.set.length === 1 && r.set[0].length === 1 ? r.set[0][0] : undefined);
332
+ if (simple.some(c => c === undefined || (c.operator !== '>=' && c.operator !== '>' && c.operator !== '<=' && c.operator !== '<'))) {
333
+ return ranges;
334
+ }
335
+ const lower = simple.every(c => c?.operator === '>=' || c?.operator === '>');
336
+ const upper = simple.every(c => c?.operator === '<=' || c?.operator === '<');
337
+ if (!lower && !upper) {
338
+ return ranges;
339
+ }
340
+ let best = 0;
341
+ for (let i = 1; i < ranges.length; i++) {
342
+ const cmp = r_version_1.RVersion.compare(simple[i]?.semver.version, simple[best]?.semver.version);
343
+ // the weakest bound wins; at the same version the inclusive one (`>=` over `>`) is the weaker
344
+ if (cmp === 0 ? simple[i]?.operator.length === 2 : (lower ? cmp < 0 : cmp > 0)) {
345
+ best = i;
346
+ }
347
+ }
348
+ return [ranges[best]];
349
+ }
350
+ /**
351
+ * The transitive constraints declared packages place on their own dependencies (one level deep). `versionsOf` gives
352
+ * the versions of each declaring package that are still in play. The requirements are read from all of them, so a
353
+ * constraint only ever filters when *every* one of them declares it (see {@link TransitiveConstraint}). Without it,
354
+ * the single {@link Package.resolvedVersion|resolved version} is used, which is by definition universal.
307
355
  */
308
- function collectTransitiveConstraints(deps, sources, versionOf) {
356
+ function collectTransitiveConstraints(deps, sources, versionsOf) {
309
357
  const out = new Map();
310
358
  for (const pkg of deps.getDependencies()) {
311
- const src = sources.find(s => s.has(pkg.name));
359
+ // merged across sources: a single source may only carry part of the package's history, and a version it lacks
360
+ // would look like "declares nothing" and wrongly turn the requirement into a partial one
361
+ const src = (0, reader_1.sourceForPackage)(sources, pkg.name);
312
362
  if (!src) {
313
363
  continue;
314
364
  }
315
- const version = versionOf?.(pkg.name) ?? pkg.resolvedVersion;
316
- for (const dep of src.dependencies(pkg.name, version) ?? []) {
317
- if (!dep.constraint) {
318
- continue;
319
- }
320
- const range = r_version_1.RRange.parse(dep.constraint);
321
- if (!range) {
322
- continue;
365
+ const known = versionsOf?.(pkg.name);
366
+ // `undefined` asks the source for its own default version, so a package with no candidates still yields its requirements
367
+ const versions = known && known.length > 0 ? known : [pkg.resolvedVersion];
368
+ // per required package: the distinct requirements found, and from how many of `versions` they were read
369
+ const perDep = new Map();
370
+ for (const version of versions) {
371
+ const seen = new Set();
372
+ for (const dep of src.dependencies(pkg.name, version) ?? []) {
373
+ const range = dep.constraint ? r_version_1.RRange.parse(dep.constraint) : undefined;
374
+ if (!range || seen.has(dep.name)) {
375
+ continue;
376
+ }
377
+ seen.add(dep.name);
378
+ let entry = perDep.get(dep.name);
379
+ if (entry === undefined) {
380
+ entry = { ranges: new Map(), declaredBy: 0 };
381
+ perDep.set(dep.name, entry);
382
+ }
383
+ entry.ranges.set(range.raw, range);
384
+ entry.declaredBy++;
323
385
  }
324
- const arr = out.get(dep.name) ?? [];
325
- arr.push({ range, from: `${pkg.name}${version ? ' ' + version : ''}` });
326
- out.set(dep.name, arr);
386
+ }
387
+ const only = versions.length === 1 ? versions[0] : undefined;
388
+ const from = `${pkg.name}${only ? ' ' + only : ''}`;
389
+ for (const [name, entry] of perDep) {
390
+ const arr = out.get(name) ?? [];
391
+ arr.push({ ranges: collapseAlternatives([...entry.ranges.values()]), from, universal: entry.declaredBy === versions.length });
392
+ out.set(name, arr);
327
393
  }
328
394
  }
329
395
  return out;
@@ -334,46 +400,231 @@ exports.DefaultFixpointIterations = 8;
334
400
  function iterateToFixpoint(maxIterations, step) {
335
401
  for (let i = 0; i < maxIterations && step(); i++) { /* repeat until a step makes no change */ }
336
402
  }
337
- /** drop, to a fixpoint, versions no co-guessed dependency can satisfy; returns the blocking partners per package */
338
- function enforceArcConsistency(entries, maxIterations = exports.DefaultFixpointIterations) {
403
+ /**
404
+ * Whether a version's signatures accept how the code calls the package. The verdict depends only on the code and the
405
+ * database, never on the constraints, so it is decided once per version and reused across the fixpoint's passes.
406
+ */
407
+ function makeSignatureFilter(src, pkg, getFn, timeline, usage) {
408
+ if (!src || !usage) {
409
+ return () => true;
410
+ }
411
+ // tracked names appear in some carried version; untracked names must not reject all versions
412
+ const tracked = new Set([...usage.keys()].filter(fn => timeline.some(e => getFn(fn, e.ver) !== undefined)));
413
+ const verdict = new Map();
414
+ return version => {
415
+ let ok = verdict.get(version);
416
+ if (ok === undefined) {
417
+ ok = !src.hasVersion(pkg, version) || isCompatible(getFn, version, usage, tracked);
418
+ verdict.set(version, ok);
419
+ }
420
+ return ok;
421
+ };
422
+ }
423
+ /**
424
+ * The version space of one analysis: the surviving versions of each dependency and the transitive constraints
425
+ * refined to a fixpoint. Holding the shared inputs here keeps the passes to a handful of arguments and lets each
426
+ * package's sigdb key, source and decoded signatures be resolved once. The passes revisit the same versions
427
+ * repeatedly, so that memoization is what makes the fixpoint affordable.
428
+ */
429
+ class VersionSpace {
430
+ deps;
431
+ sources;
432
+ usage;
433
+ cutoff;
434
+ rVersion;
435
+ disabled;
436
+ resolved = new Map();
437
+ constructor({ deps, usage, cutoff, rVersion, disabled = exports.NoDisabledSources }) {
438
+ this.deps = deps;
439
+ this.sources = deps.signatureSources();
440
+ this.usage = usage;
441
+ this.cutoff = cutoff;
442
+ this.rVersion = rVersion;
443
+ this.disabled = disabled;
444
+ }
445
+ /** the sigdb package, source and signature resolver of a target, resolved once */
446
+ resolve(name) {
447
+ let entry = this.resolved.get(name);
448
+ if (entry === undefined) {
449
+ const key = timelinePackageKey(name, this.sources);
450
+ const src = (0, reader_1.sourceForPackage)(this.sources, key);
451
+ const getFn = makeFnResolver(src, key);
452
+ const timeline = src ? versionTimeline(src, key) : [];
453
+ const all = this.usage.get(name);
454
+ // base primitives are captured inconsistently, so their absence from a base package is a data gap, not a removal
455
+ const usage = all && src?.isBaseR(key) ? new Map([...all].filter(([fn]) => !r_base_primitives_generated_1.RBasePrimitives.has(fn))) : all;
456
+ entry = { key, src, getFn, timeline, usage, signatureOk: makeSignatureFilter(src, key, getFn, timeline, usage) };
457
+ this.resolved.set(name, entry);
458
+ }
459
+ return entry;
460
+ }
461
+ /** the versions of `name` surviving every constraint, see {@link survivingEntries} */
462
+ survivors(name, transitive, observe) {
463
+ return survivingEntries(this, name, transitive, observe);
464
+ }
465
+ /**
466
+ * The transitive constraints, refined to a fixpoint: each pass re-reads every declaring package's requirements
467
+ * from the versions of it that survived the previous pass, so two packages can tighten each other. Feeding back
468
+ * the whole surviving set (not one representative version) is what keeps a requirement that only *some* of those
469
+ * versions declare from filtering (see {@link TransitiveConstraint}).
470
+ *
471
+ * The first pass runs with *no* transitive constraint at all, so every later pass can only shrink the surviving
472
+ * sets and thus only tighten the constraints: the refinement is monotone and cannot oscillate, and stopping early
473
+ * at `maxIterations` leaves it on the permissive side rather than at an arbitrary point. A declaring package that
474
+ * is not among the `targets` is not being guessed, so its {@link Package.resolvedVersion} stands in.
475
+ */
476
+ refineTransitive(targets, maxIterations = exports.DefaultFixpointIterations) {
477
+ if (this.disabled.has('transitive')) {
478
+ return collectTransitiveConstraints(this.deps, this.sources);
479
+ }
480
+ let transitive = new Map();
481
+ let previous = '';
482
+ iterateToFixpoint(maxIterations, () => {
483
+ const pass = new Map();
484
+ for (const name of targets) {
485
+ pass.set(name, this.survivors(name, transitive.get(name) ?? []).survivors.map(e => e.ver));
486
+ }
487
+ // the sets only ever shrink, so their sizes and endpoints identify the state
488
+ const signature = Array.from(pass, ([k, v]) => `${k}=${v.length}:${v[0] ?? ''}-${v[v.length - 1] ?? ''}`).sort().join(',');
489
+ if (signature === previous) {
490
+ return false;
491
+ }
492
+ previous = signature;
493
+ transitive = collectTransitiveConstraints(this.deps, this.sources, name => pass.get(name));
494
+ return true;
495
+ });
496
+ return transitive;
497
+ }
498
+ }
499
+ exports.VersionSpace = VersionSpace;
500
+ /** drop, to a fixpoint, the versions of each package that no co-guessed dependency can satisfy */
501
+ function enforceArcConsistency(space, initial, maxIterations = exports.DefaultFixpointIterations) {
502
+ const survivors = new Map(initial);
339
503
  const blockers = new Map();
340
504
  iterateToFixpoint(maxIterations, () => {
341
- const survivorsByName = new Map(entries.map(e => [e.name, e.survivors.map(s => s.ver)]));
505
+ const versionsByName = new Map([...survivors].map(([name, entries]) => [name, entries.map(e => e.ver)]));
342
506
  let changed = false;
343
- for (const e of entries) {
344
- const src = e.src;
507
+ for (const [name, entries] of survivors) {
508
+ const { src, key } = space.resolve(name);
345
509
  if (src === undefined) {
346
510
  continue;
347
511
  }
348
- const kept = e.survivors.filter(v => versionMeetsPartners(src, e.key, v.ver, survivorsByName, e.name, (partner, constraint) => {
349
- const forPkg = blockers.get(e.name) ?? new Map();
512
+ const kept = entries.filter(v => versionMeetsPartners(src, key, v.ver, versionsByName, name, (partner, constraint) => {
513
+ const forPkg = blockers.get(name) ?? new Map();
350
514
  forPkg.set(partner, constraint);
351
- blockers.set(e.name, forPkg);
515
+ blockers.set(name, forPkg);
352
516
  }));
353
- if (kept.length !== e.survivors.length) {
517
+ if (kept.length !== entries.length) {
354
518
  changed = true;
355
- e.survivors = kept;
519
+ survivors.set(name, kept);
356
520
  }
357
521
  }
358
522
  return changed;
359
523
  });
360
- return blockers;
524
+ return { survivors, blockers };
525
+ }
526
+ /** the parseable requirements each surviving version of `f` places on the other packages, resolved once */
527
+ function factorRequirements(space, f) {
528
+ const { src, key } = space.resolve(f.name);
529
+ return f.survivors.map(v => {
530
+ const out = new Map();
531
+ for (const dep of src?.dependencies(key, v) ?? []) {
532
+ const range = dep.constraint ? r_version_1.RRange.parse(dep.constraint) : undefined;
533
+ if (range && !out.has(dep.name)) {
534
+ out.set(dep.name, range);
535
+ }
536
+ }
537
+ return out;
538
+ });
539
+ }
540
+ /** the coupling between two factors, or `undefined` when neither ever constrains the other */
541
+ function coupleFactors(a, b, factors, requirements) {
542
+ const onB = requirements[a].map(r => r.has(factors[b].name));
543
+ const onA = requirements[b].map(r => r.has(factors[a].name));
544
+ if (!onB.some(Boolean) && !onA.some(Boolean)) {
545
+ return undefined;
546
+ }
547
+ // a direction nobody requires is simply absent, not partial: only a direction some but not all versions declare is
548
+ const partial = (side) => side.some(Boolean) && !side.every(Boolean);
549
+ return { a, b, always: !partial(onB) && !partial(onA) };
550
+ }
551
+ /** `ok[i][j]`: version `i` of factor `a` runs with version `j` of factor `b` */
552
+ function compatibilityMatrix(c, factors, requirements) {
553
+ const [fa, fb] = [factors[c.a], factors[c.b]];
554
+ const onB = requirements[c.a].map(r => r.get(fb.name));
555
+ const onA = requirements[c.b].map(r => r.get(fa.name));
556
+ return fa.survivors.map((va, i) => fb.survivors.map((vb, j) => (onB[i] === undefined || r_version_1.RRange.satisfies(vb, onB[i])) && (onA[j] === undefined || r_version_1.RRange.satisfies(va, onA[j]))));
361
557
  }
362
558
  /**
363
- * The runnable-combination count. Everything depends on the shared base/R `hub`, so for each hub version take the
364
- * product of how many versions of every other factor are compatible with it, and sum over the hub. With no hub the
365
- * factors are independent, so it is the plain product. (Constraints between two non-hub factors are not modelled.)
559
+ * The runnable-combination count: how many version tuples satisfy the requirements the factors place on each other.
560
+ * A requirement need not hold for every version of the declaring package (`A 0.2.5` may pin `B` to `0.2.1` while
561
+ * `A 0.3.0` pins it to `0.3.2`), so the two are counted as *coupled* rather than as independent factors: a version
562
+ * of `A` only ever multiplies in the versions of `B` it actually admits.
563
+ *
564
+ * Counting all couplings exactly is #CSP-hard, so they are counted over a spanning forest of the coupling graph,
565
+ * preferring the couplings that always apply. That is exact whenever the graph has no cycle, which covers the common
566
+ * shared-hub shape. A coupling that would close a cycle is dropped and reported as uncounted, leaving the result an
567
+ * upper bound. Only the forest's couplings need their compatibility matrix, so the work stays linear in the factors.
366
568
  */
367
- function countRunnableCombinations(hub, others) {
368
- if (hub === undefined) {
369
- return others.reduce((p, f) => p * f.survivors.length, 1);
569
+ function countRunnableCombinations(space, factors) {
570
+ const requirements = factors.map(f => factorRequirements(space, f));
571
+ const found = [];
572
+ for (let a = 0; a < factors.length; a++) {
573
+ for (let b = a + 1; b < factors.length; b++) {
574
+ const coupling = coupleFactors(a, b, factors, requirements);
575
+ if (coupling) {
576
+ found.push(coupling);
577
+ }
578
+ }
370
579
  }
371
- // each factor version's constraint on the hub, resolved once (it does not depend on which hub version we count against)
372
- const hubRanges = others.map(f => f.survivors.map(v => {
373
- const dep = f.src?.dependencies(f.key, v)?.find(d => d.name === hub.name && d.constraint);
374
- return dep?.constraint ? r_version_1.RRange.parse(dep.constraint) : undefined;
375
- }));
376
- return hub.survivors.reduce((sum, h) => sum + hubRanges.reduce((prod, ranges) => prod * ranges.filter(r => !r || r_version_1.RRange.satisfies(h, r)).length, 1), 0);
580
+ const parent = factors.map((_, i) => i);
581
+ const find = (i) => parent[i] === i ? i : (parent[i] = find(parent[i]));
582
+ const tree = [];
583
+ const couplings = found.sort((x, y) => Number(y.always) - Number(x.always)).map(c => {
584
+ const [ra, rb] = [find(c.a), find(c.b)];
585
+ const counted = ra !== rb;
586
+ if (counted) {
587
+ parent[ra] = rb;
588
+ tree.push({ ...c, ok: compatibilityMatrix(c, factors, requirements) });
589
+ }
590
+ return { a: factors[c.a].name, b: factors[c.b].name, always: c.always, counted };
591
+ });
592
+ return { total: countOverForest(factors, tree), couplings };
593
+ }
594
+ /** the number of assignments satisfying every coupling of a forest, by rooting each tree and folding bottom-up */
595
+ function countOverForest(factors, tree) {
596
+ const neighbours = factors.map(() => []);
597
+ for (const c of tree) {
598
+ neighbours[c.a].push({ to: c.b, ok: c.ok, flipped: false });
599
+ neighbours[c.b].push({ to: c.a, ok: c.ok, flipped: true });
600
+ }
601
+ // weight[i] of a node: how many assignments of its subtree exist with that node fixed to version i
602
+ const visited = factors.map(() => false);
603
+ const subtree = (node, from) => {
604
+ visited[node] = true;
605
+ const weight = factors[node].survivors.map(() => 1);
606
+ for (const edge of neighbours[node]) {
607
+ if (edge.to === from || visited[edge.to]) {
608
+ continue;
609
+ }
610
+ const child = subtree(edge.to, node);
611
+ for (let i = 0; i < weight.length; i++) {
612
+ let sum = 0;
613
+ for (let j = 0; j < child.length; j++) {
614
+ sum += (edge.flipped ? edge.ok[j][i] : edge.ok[i][j]) ? child[j] : 0;
615
+ }
616
+ weight[i] *= sum;
617
+ }
618
+ }
619
+ return weight;
620
+ };
621
+ let total = 1;
622
+ for (let i = 0; i < factors.length; i++) {
623
+ if (!visited[i]) {
624
+ total *= subtree(i, -1).reduce((a, b) => a + b, 0);
625
+ }
626
+ }
627
+ return total;
377
628
  }
378
629
  /** whether every requirement `pkg@ver` places on a co-guessed dependency is met by one of that partner's surviving versions */
379
630
  function versionMeetsPartners(src, pkg, ver, partnerSurvivors, selfName, onReject) {
@@ -397,11 +648,13 @@ function versionMeetsPartners(src, pkg, ver, partnerSurvivors, selfName, onRejec
397
648
  exports.NoDisabledSources = new Set();
398
649
  /**
399
650
  * Filter a version timeline by the declared range, transitive constraints, base-R version bound, and date cutoff,
400
- * emitting each constraint to `observe` (when given) as it is applied -- so the filtering and its explanation cannot
401
- * drift apart. A source in `disabled` is skipped entirely: neither filtered on nor reported as evidence.
651
+ * emitting each constraint to `observe` (when given) as it is applied, so the filtering and its explanation cannot
652
+ * drift apart. A source disabled on `space` is skipped entirely: neither filtered on nor reported as evidence.
402
653
  */
403
- function applyConstraints(timeline, name, declaredRange, declaredConstraints, transitive, base, rVersion, cutoff, observe, disabled = exports.NoDisabledSources) {
404
- let t = [...timeline];
654
+ function applyConstraints(space, name, timeline, inputs, observe) {
655
+ const { disabled, rVersion, cutoff } = space;
656
+ const { declaredRange, declaredConstraints, transitive, base } = inputs;
657
+ let t = timeline.slice();
405
658
  if (!disabled.has('declared')) {
406
659
  for (const c of declaredConstraints) {
407
660
  observe?.({ source: 'declared', origin: 'project metadata', detail: `declared as ${c}`, bound: c });
@@ -410,8 +663,13 @@ function applyConstraints(timeline, name, declaredRange, declaredConstraints, tr
410
663
  }
411
664
  if (!disabled.has('transitive')) {
412
665
  for (const c of transitive) {
413
- observe?.({ source: 'transitive', origin: c.from, detail: `${c.from} requires ${name} ${c.range.raw}`, bound: c.range.raw });
414
- t = t.filter(e => r_version_1.RRange.satisfies(e.ver, c.range));
666
+ const bound = r_version_1.RRange.formatAlternatives(c.ranges);
667
+ // a constraint only some versions of the origin declare cannot filter: another of its versions avoids it
668
+ const detail = c.universal ? `${c.from} requires ${name} ${bound}` : `some versions of ${c.from} require ${name} ${bound}`;
669
+ observe?.({ source: 'transitive', origin: c.from, detail, bound, ...(c.universal ? {} : { partial: true }) });
670
+ if (c.universal) {
671
+ t = t.filter(e => r_version_1.RRange.satisfiesAny(e.ver, c.ranges));
672
+ }
415
673
  }
416
674
  }
417
675
  // a base package's version *is* the R version, so it is bounded by the assumed/declared R (only when that is known)
@@ -423,7 +681,7 @@ function applyConstraints(timeline, name, declaredRange, declaredConstraints, tr
423
681
  if (cutoff && !disabled.has('date')) {
424
682
  observe?.({ source: 'date', origin: isoDay(cutoff), detail: `only releases up to ${isoDay(cutoff)}`, bound: `<=${isoDay(cutoff)}` });
425
683
  // base R is stored undated, so fall back to its R release date; a dated release must predate the cutoff, and an
426
- // undated one is dropped -- except base R older than the release table (kept, as it predates any real cutoff)
684
+ // undated one is dropped, except base R older than the release table (kept, as it predates any real cutoff)
427
685
  t = t.filter(e => {
428
686
  const date = e.date ?? (base ? (0, r_version_1.rReleaseDate)(e.ver) : undefined);
429
687
  return date !== undefined ? date.getTime() <= cutoff.getTime() : base;
@@ -434,39 +692,37 @@ function applyConstraints(timeline, name, declaredRange, declaredConstraints, tr
434
692
  /**
435
693
  * Apply every constraint (declared, transitive, base-R, date, then signature usage) to a package's timeline. When an
436
694
  * `observe` callback is given, emits the provenance of each constraint (including the signature lower bounds).
695
+ * Prefer {@link VersionSpace.survivors}, which is the same call with the shared inputs already bound.
437
696
  */
438
- function survivingEntries(name, src, deps, usage, transitive, cutoff, rVersion, observe, disabled = exports.NoDisabledSources, packageKey = name) {
697
+ function survivingEntries(space, name, transitive, observe) {
698
+ const { deps, disabled } = space;
439
699
  // packageKey: sigdb package (R reuses base, others use themselves)
440
- const getFn = makeFnResolver(src, packageKey);
441
- const declaredRange = disabled.has('declared') ? undefined : deps.inferredVersion(name);
700
+ const { key: packageKey, src, getFn, timeline, usage, signatureOk } = space.resolve(name);
701
+ const declaredRange = disabled.has('declared') ? undefined : deps.inferredRange(name);
442
702
  const declaredConstraints = disabled.has('declared') ? [] : (deps.getDependency(name)?.versionConstraints.map(c => c.raw) ?? []);
443
703
  const effectiveTransitive = disabled.has('transitive') ? [] : transitive;
444
704
  // contradiction is a constraint property, not an empty database
445
705
  const unsatisfiable = constraintsContradict(declaredConstraints, declaredRange, effectiveTransitive);
446
706
  if (!src) {
447
- return { survivors: [], preSignature: [], getFn, declaredRange, declaredConstraints, base: false, unsatisfiable, total: 0 };
707
+ return { survivors: [], preSignature: [], getFn, declaredRange, declaredConstraints, base: false, unsatisfiable, total: 0, declared: 0 };
448
708
  }
449
709
  const base = src.isBaseR(packageKey);
450
- const timeline = versionTimeline(src, packageKey);
451
710
  const total = timeline.length;
711
+ const declared = declaredRange ? timeline.filter(e => r_version_1.RRange.satisfies(e.ver, declaredRange)).length : total;
452
712
  // emit database coverage envelope as outer bounds
453
713
  if (observe && timeline.length > 0 && !disabled.has('available')) {
454
714
  observe({ source: 'available', origin: 'signature database', detail: `data available from ${timeline[0].ver}`, bound: `>=${timeline[0].ver}` });
455
715
  observe({ source: 'available', origin: 'signature database', detail: `data available up to ${timeline[timeline.length - 1].ver}`, bound: `<=${timeline[timeline.length - 1].ver}` });
456
716
  }
457
- const preSignature = applyConstraints(timeline, name, declaredRange, declaredConstraints, effectiveTransitive, base, rVersion, cutoff, observe, disabled);
717
+ const preSignature = applyConstraints(space, name, timeline, { declaredRange, declaredConstraints, transitive: effectiveTransitive, base }, observe);
458
718
  if (!usage || disabled.has('signature')) {
459
- return { survivors: preSignature, preSignature, getFn, declaredRange, declaredConstraints, base, unsatisfiable, total };
719
+ return { survivors: preSignature, preSignature, getFn, declaredRange, declaredConstraints, base, unsatisfiable, total, declared };
460
720
  }
461
- // exclude base primitives from base packages (captured inconsistently, so absence is data gap not removal)
462
- const relevant = base ? new Map([...usage].filter(([fn]) => !r_base_primitives_generated_1.RBasePrimitives.has(fn))) : usage;
463
721
  if (observe) {
464
- addSignatureEvidence(observe, src, getFn, packageKey, relevant, preSignature);
722
+ addSignatureEvidence(observe, src, getFn, packageKey, usage, preSignature);
465
723
  }
466
- // tracked names appear in some carried version; untracked names must not reject all versions
467
- const tracked = new Set([...relevant.keys()].filter(fn => preSignature.some(e => getFn(fn, e.ver) !== undefined)));
468
- const survivors = preSignature.filter(e => !src.hasVersion(packageKey, e.ver) || isCompatible(getFn, e.ver, relevant, tracked));
469
- return { survivors, preSignature, getFn, declaredRange, declaredConstraints, base, unsatisfiable, total };
724
+ const survivors = preSignature.filter(e => signatureOk(e.ver));
725
+ return { survivors, preSignature, getFn, declaredRange, declaredConstraints, base, unsatisfiable, total, declared };
470
726
  }
471
727
  /** the sigdb package a target's version history is drawn from: `R` reuses `base` (their releases coincide), everything else is itself */
472
728
  function timelinePackageKey(name, sources) {
@@ -478,11 +734,12 @@ function constraintsContradict(declaredConstraints, declaredRange, transitive) {
478
734
  if (declaredConstraints.length > 0 && declaredRange === undefined) {
479
735
  return true;
480
736
  }
481
- const ranges = [declaredRange, ...transitive.map(t => t.range)].filter((r) => r !== undefined);
737
+ // only unambiguous requirements can contradict: a constraint with alternatives (or one only some versions declare) always has a way out
738
+ const ranges = [declaredRange, ...transitive.filter(t => t.universal && t.ranges.length === 1).map(t => t.ranges[0])].filter((r) => r !== undefined);
482
739
  if (ranges.length === 0) {
483
740
  return false;
484
741
  }
485
- const combined = r_version_1.RRange.parse(ranges.map(r => r.raw).join(' '));
742
+ const combined = r_version_1.RRange.intersect(ranges);
486
743
  return combined === undefined || (0, semver_1.minVersion)(combined) === null;
487
744
  }
488
745
  /**
@@ -503,7 +760,7 @@ function orderedCandidatesOf(src, name, surviving, prefer, order) {
503
760
  }
504
761
  /** the default explosion targets: every declared and used dependency (excluding `current`, the analyzed package's own namespace) */
505
762
  function defaultTargets(deps, usage) {
506
- return [...new Set([...deps.getDependencies().map(d => d.name), ...usage.keys()])].filter(name => name !== 'current');
763
+ return [...new Set([...deps.getDependencies().map(d => d.name), ...usage.keys()])].filter(name => name !== exports.ProjectPackage);
507
764
  }
508
765
  /** lazily yield concrete version assignments (one version per package) in odometer order over the per-package lists */
509
766
  function* assignmentsOf(perPackage, limit) {
@@ -542,15 +799,14 @@ async function orderedCandidatesFor(analyzer, options) {
542
799
  // bound base packages by R only when genuinely known (a config pin, metadata, or detection); `auto` with nothing detected imposes no R ceiling
543
800
  const rVersion = ctx.rVersionKnown ? (ctx.meta.getRVersion() ?? ctx.resolvedRVersion) : undefined;
544
801
  const usage = collectUsage((await analyzer.dataflow()).graph, deps);
545
- const transitive = collectTransitiveConstraints(deps, sources);
546
- const targets = options.packages && options.packages.length > 0 ? [...options.packages] : defaultTargets(deps, usage);
802
+ const targets = (options.packages && options.packages.length > 0 ? [...options.packages] : defaultTargets(deps, usage)).sort();
803
+ const space = new VersionSpace({ deps, usage, cutoff, rVersion });
804
+ const transitive = space.refineTransitive(targets);
547
805
  const order = options.order ?? 'newest';
548
806
  const out = [];
549
- for (const name of targets.sort()) {
550
- const packageKey = timelinePackageKey(name, sources);
551
- const src = (0, reader_1.sourceForPackage)(sources, packageKey);
552
- const surviving = survivingEntries(name, src, deps, usage.get(name), transitive.get(name) ?? [], cutoff, rVersion, undefined, exports.NoDisabledSources, packageKey);
553
- const oc = orderedCandidatesOf(src, name, surviving, options.prefer?.[name], order);
807
+ for (const name of targets) {
808
+ const surviving = space.survivors(name, transitive.get(name) ?? []);
809
+ const oc = orderedCandidatesOf(space.resolve(name).src, name, surviving, options.prefer?.[name], order);
554
810
  if (oc) {
555
811
  out.push(oc);
556
812
  }
@@ -51,6 +51,10 @@ export declare class FlowrDescriptionFile extends FlowrFile<DeepReadonly<DCF>> {
51
51
  * Returns the parsed suggested packages from the 'Suggests' field in the DESCRIPTION file.
52
52
  */
53
53
  suggests(): Package[] | undefined;
54
+ /**
55
+ * Returns the parsed enhanced packages from the 'Enhances' field in the DESCRIPTION file.
56
+ */
57
+ enhances(): Package[] | undefined;
54
58
  /**
55
59
  * Returns the 'Collate' field from the DESCRIPTION file.
56
60
  */