@eagleoutice/flowr 2.15.3 → 2.15.5

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.
package/config.d.ts CHANGED
@@ -158,6 +158,8 @@ export interface FlowrConfig {
158
158
  readonly loadProjectDependencies: boolean;
159
159
  readonly eagerlyLoad: boolean;
160
160
  readonly eagerlyLoadExports: boolean;
161
+ /** How many MiB of decoded package blobs every open bundle may hold together; a bigger budget re-reads and re-parses less, a smaller one keeps less in memory (default `16`). */
162
+ readonly blobCacheBudgetMb?: number;
161
163
  /**
162
164
  * R version assumed when resolving versioned (base-R) exports: a pin, or `"auto"` to detect the installed R
163
165
  * (falling back to {@link DefaultAssumedRVersion} if none, e.g. tree-sitter). See {@link resolveAssumedRVersion}.
package/config.js CHANGED
@@ -292,7 +292,7 @@ exports.FlowrConfig = {
292
292
  variables: VariableResolve.Alias,
293
293
  evalStrings: true,
294
294
  trackEnvironments: true,
295
- sigdb: { enabled: true, loadProjectDependencies: true, eagerlyLoad: false, eagerlyLoadExports: false, assumedRVersion: 'auto', linkBaseR: false, linkDescriptionDependencies: false, linkBaseRCalls: false, linkPackageCalls: false, warmInBackground: false, additionalPaths: [], autoSync: false, versionSelection: VersionSelection.Newest, versionOverrides: {}, installedLibrary: { enabled: false, paths: [], useEnvironment: true, useProjectLibrary: true, maxDepth: 3, packages: [] } },
295
+ sigdb: { enabled: true, loadProjectDependencies: true, eagerlyLoad: false, eagerlyLoadExports: false, blobCacheBudgetMb: 16, assumedRVersion: 'auto', linkBaseR: false, linkDescriptionDependencies: false, linkBaseRCalls: false, linkPackageCalls: false, warmInBackground: false, additionalPaths: [], autoSync: false, versionSelection: VersionSelection.Newest, versionOverrides: {}, installedLibrary: { enabled: false, paths: [], useEnvironment: true, useProjectLibrary: true, maxDepth: 3, packages: [] } },
296
296
  versionManagement: { linkedVersionGroups: [] },
297
297
  resolveSource: {
298
298
  dropPaths: DropPathsOption.No,
@@ -441,6 +441,7 @@ exports.FlowrConfig = {
441
441
  maxDepth: joi_1.default.number().optional().description('How far to descend into the nested layout of a project-local library (default 3).'),
442
442
  packages: joi_1.default.array().items(joi_1.default.string()).optional().description('Only recover packages whose name matches one of these regular expressions; empty means any.')
443
443
  }).optional().description('Recovering packages no signature database knows from the copy installed on this machine.'),
444
+ blobCacheBudgetMb: joi_1.default.number().min(0).optional().description('How many MiB of decoded package blobs every open bundle may hold together (default 16).'),
444
445
  versionSelection: joi_1.default.string().valid(...Object.values(VersionSelection)).optional().description('When a project constrains a dependency, resolve to the newest (default), oldest, or system-installed version satisfying it; system needs R and falls back to newest. Base-R packages always resolve against the assumed R version.'),
445
446
  versionOverrides: joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.string()).optional().description('Force an exact version for specific packages (name -> version), overriding both the project constraint and the versionSelection policy (default {}).')
446
447
  }).description('Resolving library exports from a signature database.'),
@@ -1,7 +1,8 @@
1
1
  import type { BuiltInMemory } from './built-in';
2
- import type { IdentifierDefinition } from './identifier';
2
+ import type { BrandedIdentifier, IdentifierDefinition } from './identifier';
3
3
  import { Identifier } from './identifier';
4
4
  import type { ControlDependency } from '../info';
5
+ import { Frame, MemoryView, WritableMemory } from './frame-memory';
5
6
  import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id';
6
7
  /** A single entry/scope within an {@link REnvironmentInformation} */
7
8
  export interface IEnvironment {
@@ -10,7 +11,7 @@ export interface IEnvironment {
10
11
  /** Lexical parent of the environment, if any (can be manipulated by R code) */
11
12
  parent: IEnvironment;
12
13
  /** Maps to exactly one definition of an identifier if the source is known, otherwise to a list of all possible definitions */
13
- memory: BuiltInMemory;
14
+ memory: MemoryView;
14
15
  /** Built-in environment that must not change; only for the top-most envs. */
15
16
  builtInEnv?: true | undefined;
16
17
  }
@@ -26,7 +27,7 @@ interface Jsonified {
26
27
  id: NodeId;
27
28
  parent: Jsonified | undefined;
28
29
  builtInEnv?: true;
29
- memory: BuiltInMemory;
30
+ memory: ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]>;
30
31
  n?: string;
31
32
  t?: EnvType;
32
33
  globalEnv?: true;
@@ -43,26 +44,33 @@ export declare class Environment implements IEnvironment {
43
44
  /** if created by a closure, the node id of that closure */
44
45
  private c?;
45
46
  parent: Environment;
46
- memory: BuiltInMemory;
47
+ /** the frame this environment's names live in, shared with every other snapshot of it */
48
+ private frame;
49
+ /** the version of {@link frame} this environment sees */
50
+ private fv;
51
+ private view?;
52
+ private writable?;
47
53
  cache?: Map<Identifier, IdentifierDefinition[]>;
54
+ /** what a resolution found below this frame, by target and name; only frames nothing writes keep one */
55
+ tailCache?: Map<string, readonly IdentifierDefinition[] | undefined>;
48
56
  builtInEnv?: true;
49
- /** {@link memory} is shared with a clone; writing needs {@link writableMemory} to unshare it first */
57
+ /** {@link memory} may be seen by another snapshot, so a write has to take a version of its own first */
50
58
  private sharedMemory?;
51
59
  /** {@link parent} is shared with the environment this was cloned from; writing through it needs {@link writableParent} */
52
60
  private sharedParent?;
53
61
  /** marks the global environment (`.GlobalEnv`); attached packages (see {@link EnvType}) live below it */
54
62
  globalEnv?: true;
55
63
  /** What the lexical frame this stands in for held when its closure was created; `<<-` binds lexically, so defining super needs this. */
56
- superMemory?: BuiltInMemory;
64
+ superMemory?: MemoryView;
57
65
  /** What the configuration states about packages R does not attach on startup, by package; only the built-in env carries it (see {@link statedIn}). */
58
66
  namespaces?: ReadonlyMap<string, BuiltInMemory>;
59
- constructor(parent: Environment, isBuiltInDefault?: true | undefined, memory?: BuiltInMemory);
67
+ constructor(parent: Environment, isBuiltInDefault?: true | undefined, frame?: Frame, version?: number);
60
68
  /** Marks this as an attached-package layer (see {@link EnvType}) for package `name`. */
61
69
  asLibrary(name: string, type: EnvType): this;
62
70
  /** Marks this as the global environment (`.GlobalEnv`); see {@link globalEnv}. */
63
71
  asGlobal(): this;
64
72
  /** Records the lexical frame this one stands in for; see {@link superMemory}. */
65
- standsInFor(memory: BuiltInMemory): this;
73
+ standsInFor(memory: MemoryView): this;
66
74
  /** please only use if you know what you are doing */
67
75
  setClosureNodeId(nodeId: NodeId): void;
68
76
  /** Provides the closure linked to this environment. */
@@ -72,11 +80,18 @@ export declare class Environment implements IEnvironment {
72
80
  * and lets it materialize one frame at a time here, since a removal usually reaches only a frame or two.
73
81
  */
74
82
  get writableParent(): Environment;
75
- /**
76
- * This environment's {@link memory}, ready to be written to; every in-place write must go through this rather
77
- * than {@link memory} directly, since {@link clone} shares the map and only the first writer copies it.
78
- */
79
- get writableMemory(): BuiltInMemory;
83
+ /** What the frame binds at the version this sees; a snapshot, not a copy. */
84
+ get memory(): MemoryView;
85
+ /** Whether `other` holds the very bindings this does. */
86
+ sameMemoryAs(other: Environment): boolean;
87
+ /** What `name` holds here. {@link memory}'s answer without the view, for the chain walks of name resolution. */
88
+ lookup(name: BrandedIdentifier): IdentifierDefinition[] | undefined;
89
+ /** the bindings as a plain map where one is at hand, so a merge copies map from map */
90
+ private get copyableMemory();
91
+ /** Takes `map` as the bindings, sharing it until something writes. */
92
+ adoptMap(map: ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]>): void;
93
+ /** {@link memory} ready to be written to; every write goes through this, so the first takes a version of its own. */
94
+ get writableMemory(): WritableMemory;
80
95
  /**
81
96
  * Clones this environment, sharing {@link memory} until either side writes to it (see {@link writableMemory}); cloning
82
97
  * is therefore independent of how many definitions a frame holds, which matters for packages with thousands of them.
@@ -12,6 +12,7 @@ const identifier_1 = require("./identifier");
12
12
  const assert_1 = require("../../util/assert");
13
13
  const info_1 = require("../info");
14
14
  const append_1 = require("./append");
15
+ const frame_memory_1 = require("./frame-memory");
15
16
  const log_1 = require("../../util/log");
16
17
  var EnvType;
17
18
  (function (EnvType) {
@@ -37,10 +38,17 @@ class Environment {
37
38
  /** if created by a closure, the node id of that closure */
38
39
  c;
39
40
  parent;
40
- memory;
41
+ /** the frame this environment's names live in, shared with every other snapshot of it */
42
+ frame;
43
+ /** the version of {@link frame} this environment sees */
44
+ fv;
45
+ view;
46
+ writable;
41
47
  cache;
48
+ /** what a resolution found below this frame, by target and name; only frames nothing writes keep one */
49
+ tailCache;
42
50
  builtInEnv;
43
- /** {@link memory} is shared with a clone; writing needs {@link writableMemory} to unshare it first */
51
+ /** {@link memory} may be seen by another snapshot, so a write has to take a version of its own first */
44
52
  sharedMemory;
45
53
  /** {@link parent} is shared with the environment this was cloned from; writing through it needs {@link writableParent} */
46
54
  sharedParent;
@@ -50,11 +58,15 @@ class Environment {
50
58
  superMemory;
51
59
  /** What the configuration states about packages R does not attach on startup, by package; only the built-in env carries it (see {@link statedIn}). */
52
60
  namespaces;
53
- constructor(parent, isBuiltInDefault = undefined, memory) {
61
+ constructor(parent, isBuiltInDefault = undefined, frame, version) {
54
62
  this.id = isBuiltInDefault ? 0 : environmentIdCounter++;
55
63
  this.parent = parent;
56
- /* a clone hands its own (then shared) memory in, so the fresh map a new frame needs is not allocated to be dropped */
57
- this.memory = memory ?? new Map();
64
+ this.frame = frame ?? frame_memory_1.Frame.empty();
65
+ this.fv = version ?? this.frame.version;
66
+ if (frame === undefined) {
67
+ /* the shared empty frame, so the first write forks it */
68
+ this.sharedMemory = true;
69
+ }
58
70
  // do not store if not needed!
59
71
  if (isBuiltInDefault) {
60
72
  this.builtInEnv = isBuiltInDefault;
@@ -97,16 +109,43 @@ class Environment {
97
109
  }
98
110
  return this.parent;
99
111
  }
100
- /**
101
- * This environment's {@link memory}, ready to be written to; every in-place write must go through this rather
102
- * than {@link memory} directly, since {@link clone} shares the map and only the first writer copies it.
103
- */
112
+ /** What the frame binds at the version this sees; a snapshot, not a copy. */
113
+ get memory() {
114
+ return this.view ??= new frame_memory_1.MemoryView(this.frame, this.fv);
115
+ }
116
+ /** Whether `other` holds the very bindings this does. */
117
+ sameMemoryAs(other) {
118
+ return this === other || (this.frame === other.frame && this.fv === other.fv);
119
+ }
120
+ /** What `name` holds here. {@link memory}'s answer without the view, for the chain walks of name resolution. */
121
+ lookup(name) {
122
+ const frame = this.frame;
123
+ return this.fv === frame.version ? frame.live.get(name) : frame.get(name, this.fv);
124
+ }
125
+ /** the bindings as a plain map where one is at hand, so a merge copies map from map */
126
+ get copyableMemory() {
127
+ return this.frame.settledAt(this.fv) ?? this.memory;
128
+ }
129
+ /** Takes `map` as the bindings, sharing it until something writes. */
130
+ adoptMap(map) {
131
+ this.frame = frame_memory_1.Frame.of(map);
132
+ this.fv = this.frame.version;
133
+ this.view = undefined;
134
+ this.writable = undefined;
135
+ /* the map belongs to whoever handed it over, so the first write forks */
136
+ this.sharedMemory = true;
137
+ }
138
+ /** {@link memory} ready to be written to; every write goes through this, so the first takes a version of its own. */
104
139
  get writableMemory() {
140
+ this.tailCache = undefined;
105
141
  if (this.sharedMemory) {
106
- this.memory = new Map(this.memory);
142
+ this.frame = this.frame.forWrite(this.fv);
143
+ this.fv = this.frame.nextVersion();
107
144
  this.sharedMemory = undefined;
145
+ this.view = undefined;
146
+ this.writable = undefined;
108
147
  }
109
- return this.memory;
148
+ return this.writable ??= new frame_memory_1.WritableMemory(this.frame, this.fv);
110
149
  }
111
150
  /**
112
151
  * Clones this environment, sharing {@link memory} until either side writes to it (see {@link writableMemory}); cloning
@@ -116,7 +155,7 @@ class Environment {
116
155
  if (this.builtInEnv) {
117
156
  return this; // do not clone the built-in environment
118
157
  }
119
- const clone = new Environment(this.parent, this.builtInEnv, this.memory);
158
+ const clone = new Environment(this.parent, this.builtInEnv, this.frame, this.fv);
120
159
  clone.c = this.c;
121
160
  clone.n = this.n;
122
161
  clone.t = this.t;
@@ -163,7 +202,7 @@ class Environment {
163
202
  this.writableMemory.set(name, [definition]);
164
203
  }
165
204
  else {
166
- const existing = this.memory.get(name);
205
+ const existing = this.lookup(name);
167
206
  const inGraphDefinition = definition;
168
207
  if (existing !== undefined &&
169
208
  inGraphDefinition.cds === undefined) {
@@ -227,7 +266,7 @@ class Environment {
227
266
  do {
228
267
  /* `<<-` binds in the closest enclosing frame that holds the name, which for an emptied frame is what
229
268
  * it stood in for when the closure was created (see {@link superMemory}) */
230
- if (current.memory.has(name) || current.superMemory?.has(name)) {
269
+ if (current.lookup(name) !== undefined || current.superMemory?.has(name)) {
231
270
  current.writableMemory.set(name, [definition]);
232
271
  found = true;
233
272
  break;
@@ -257,7 +296,7 @@ class Environment {
257
296
  if (shortcut !== undefined) {
258
297
  return shortcut;
259
298
  }
260
- const map = new Map(this.memory);
299
+ const map = new Map(this.copyableMemory);
261
300
  for (const [key, values] of other.memory) {
262
301
  const hasMaybe = applyCds === undefined ? values.length === 0 || values.some(v => v.cds !== undefined) : true;
263
302
  if (hasMaybe) {
@@ -295,7 +334,7 @@ class Environment {
295
334
  out.t = this.t;
296
335
  out.globalEnv = this.globalEnv;
297
336
  out.superMemory = this.superMemory ?? other.superMemory;
298
- out.memory = map;
337
+ out.adoptMap(map);
299
338
  return out;
300
339
  }
301
340
  /** Adds all writes of `other` to this environment (`other`'s operations *might* happen). Always recurses parents. */
@@ -307,7 +346,7 @@ class Environment {
307
346
  if (shortcut !== undefined) {
308
347
  return shortcut;
309
348
  }
310
- const map = new Map(this.memory);
349
+ const map = new Map(this.copyableMemory);
311
350
  for (const [key, value] of other.memory) {
312
351
  const old = map.get(key);
313
352
  if (old) {
@@ -323,7 +362,7 @@ class Environment {
323
362
  out.t = this.t;
324
363
  out.globalEnv = this.globalEnv;
325
364
  out.superMemory = this.superMemory ?? other.superMemory;
326
- out.memory = map;
365
+ out.adoptMap(map);
327
366
  return out;
328
367
  }
329
368
  /**
@@ -376,7 +415,7 @@ class Environment {
376
415
  byName.set(layer.n, cloned);
377
416
  order.push(cloned);
378
417
  }
379
- else if (existing.memory !== layer.memory) {
418
+ else if (!existing.sameMemoryAs(layer)) {
380
419
  for (const [name, value] of layer.memory) {
381
420
  const old = existing.memory.get(name);
382
421
  if (old !== value) {
@@ -397,7 +436,7 @@ class Environment {
397
436
  this.writableParent.remove(id);
398
437
  return this;
399
438
  }
400
- const definition = this.memory.get(name);
439
+ const definition = this.lookup(name);
401
440
  let cont = true;
402
441
  if (definition !== undefined) {
403
442
  this.writableMemory.delete(name);
@@ -425,11 +464,11 @@ class Environment {
425
464
  id: this.id,
426
465
  parent: this.parent,
427
466
  builtInEnv: this.builtInEnv,
428
- memory: this.memory,
467
+ memory: new Map(this.memory),
429
468
  } : {
430
469
  id: this.id,
431
470
  parent: this.parent,
432
- memory: this.memory,
471
+ memory: new Map(this.memory),
433
472
  // markers needed to rebuild the search path after a round-trip (undefined values are dropped by JSON.stringify)
434
473
  n: this.n,
435
474
  t: this.t,
@@ -543,7 +582,7 @@ function layersEndWith(layers, tail) {
543
582
  }
544
583
  for (let i = 0; i < tail.length; i++) {
545
584
  const l = layers[offset + i], t = tail[i];
546
- if (l !== t && (l.t !== t.t || l.n !== t.n || l.memory !== t.memory)) {
585
+ if (l !== t && (l.t !== t.t || l.n !== t.n || !l.sameMemoryAs(t))) {
547
586
  return false;
548
587
  }
549
588
  }
@@ -0,0 +1,103 @@
1
+ /**
2
+ * One environment frame's bindings, shared by every snapshot of it: a snapshot is the frame plus a version, not a
3
+ * copy. Copying instead cost a whole map per snapshot, and a call vertex keeps one, so a scope with thousands of
4
+ * definitions retained memory in the square of them. The newest version is answered from a plain map, an older one
5
+ * from what the writes recorded.
6
+ * @module
7
+ */
8
+ import type { BrandedIdentifier, IdentifierDefinition } from './identifier';
9
+ /**
10
+ * One frame's bindings across its versions. A frame {@link Frame.of|taken from a map} is frozen: one state, never
11
+ * written, versioned only once {@link forWrite} forks it -- the built-in environment and the package layers.
12
+ */
13
+ export declare class Frame {
14
+ /** the bindings at {@link version} and no other, so read it only after checking the version, as {@link get} does */
15
+ readonly live: Map<BrandedIdentifier, IdentifierDefinition[]>;
16
+ /** whether {@link live} is this frame's own to write, see {@link Frame.of} */
17
+ private readonly frozen;
18
+ /** what each *rewritten* name held per version, for older snapshots; built on the first rewrite, as most see none */
19
+ private history;
20
+ /** when each name still on its first binding came in; a write-once name needs no more, and most are */
21
+ private bornAt;
22
+ /** the last past version walked out into a map, so re-reading that snapshot skips the walk; one slot only */
23
+ private walked;
24
+ /** the newest version written here, counting this frame's writes alone; only a snapshot at it may extend the frame */
25
+ version: number;
26
+ private constructor();
27
+ /** A frame holding what `map` holds, frozen: only read through here, a write forks rather than reaching back. */
28
+ static of(map: ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]>): Frame;
29
+ /** A frame holding nothing, the same one every time, so an environment that defines nothing allocates nothing. */
30
+ static empty(): Frame;
31
+ /** What `name` held at `version`. One lookup for the newest version, small enough for V8 to inline. */
32
+ get(name: BrandedIdentifier, version: number): IdentifierDefinition[] | undefined;
33
+ /** What `name` held at a version written past since. */
34
+ private bound;
35
+ /** Whether `name` was bound at `version`. */
36
+ has(name: BrandedIdentifier, version: number): boolean;
37
+ /** The names `version` binds. */
38
+ keys(version: number): MapIterator<BrandedIdentifier>;
39
+ /** What `version` binds, without the names. */
40
+ values(version: number): MapIterator<IdentifierDefinition[]>;
41
+ /** How many names `version` binds. */
42
+ size(version: number): number;
43
+ /** What `version` binds, name by name. */
44
+ entries(version: number): MapIterator<[BrandedIdentifier, IdentifierDefinition[]]>;
45
+ /**
46
+ * `version` as a map, `undefined` when it has to be walked out. A frame that never rewrote or took on a name has
47
+ * held the same bindings throughout, so {@link live} answers for any version of it.
48
+ */
49
+ settledAt(version: number): ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]> | undefined;
50
+ /** `version` walked out into a map, kept in the {@link walked} slot. */
51
+ private materialize;
52
+ /** What `version` bound; the rewritten names come first, since one dropped since is no longer in {@link live}. */
53
+ private recorded;
54
+ /** The frame a snapshot at `version` writes to: this one if it holds the newest version, a fork otherwise. */
55
+ forWrite(version: number): Frame;
56
+ /** The version the next write goes to; only a frame {@link forWrite} just returned may hand one out. */
57
+ nextVersion(): number;
58
+ /** Binds `name` at `version`, `undefined` removing it. Only the newest version may be written; snapshots hold the rest. */
59
+ set(name: BrandedIdentifier, defs: IdentifierDefinition[] | undefined, version: number): void;
60
+ }
61
+ /** One environment's view of its {@link Frame}, as a {@link ReadonlyMap} so the old readers of the map still work. */
62
+ export declare class MemoryView implements ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]> {
63
+ readonly frame: Frame;
64
+ readonly version: number;
65
+ constructor(frame: Frame, version: number);
66
+ get(name: BrandedIdentifier): IdentifierDefinition[] | undefined;
67
+ has(name: BrandedIdentifier): boolean;
68
+ get size(): number;
69
+ entries(): MapIterator<[BrandedIdentifier, IdentifierDefinition[]]>;
70
+ [Symbol.iterator](): MapIterator<[BrandedIdentifier, IdentifierDefinition[]]>;
71
+ keys(): MapIterator<BrandedIdentifier>;
72
+ values(): MapIterator<IdentifierDefinition[]>;
73
+ forEach(fn: (defs: IdentifierDefinition[], name: BrandedIdentifier, map: ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]>) => void, thisArg?: unknown): void;
74
+ }
75
+ /** The write end of a {@link Frame} at one version, standing in for the map writers used to get. */
76
+ export declare class WritableMemory {
77
+ private readonly frame;
78
+ private readonly version;
79
+ constructor(frame: Frame, version: number);
80
+ set(name: BrandedIdentifier, defs: IdentifierDefinition[]): void;
81
+ delete(name: BrandedIdentifier): void;
82
+ get(name: BrandedIdentifier): IdentifierDefinition[] | undefined;
83
+ has(name: BrandedIdentifier): boolean;
84
+ }
85
+ /**
86
+ * The bindings of an attached package, built one name at a time. An attach used to materialize a definition per
87
+ * export, and a script attaching a handful of packages carries hundreds of thousands of them for the few dozen
88
+ * names it ever mentions. Here the export list is all that is held until a lookup asks for one.
89
+ */
90
+ export declare class LazyBindings implements ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]> {
91
+ private readonly names;
92
+ private readonly bind;
93
+ private readonly built;
94
+ constructor(names: ReadonlySet<BrandedIdentifier>, bind: (name: BrandedIdentifier) => IdentifierDefinition[]);
95
+ get(name: BrandedIdentifier): IdentifierDefinition[] | undefined;
96
+ has(name: BrandedIdentifier): boolean;
97
+ get size(): number;
98
+ keys(): MapIterator<BrandedIdentifier>;
99
+ entries(): MapIterator<[BrandedIdentifier, IdentifierDefinition[]]>;
100
+ [Symbol.iterator](): MapIterator<[BrandedIdentifier, IdentifierDefinition[]]>;
101
+ values(): MapIterator<IdentifierDefinition[]>;
102
+ forEach(fn: (defs: IdentifierDefinition[], name: BrandedIdentifier, map: ReadonlyMap<BrandedIdentifier, IdentifierDefinition[]>) => void, thisArg?: unknown): void;
103
+ }
@@ -0,0 +1,293 @@
1
+ "use strict";
2
+ /**
3
+ * One environment frame's bindings, shared by every snapshot of it: a snapshot is the frame plus a version, not a
4
+ * copy. Copying instead cost a whole map per snapshot, and a call vertex keeps one, so a scope with thousands of
5
+ * definitions retained memory in the square of them. The newest version is answered from a plain map, an older one
6
+ * from what the writes recorded.
7
+ * @module
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.LazyBindings = exports.WritableMemory = exports.MemoryView = exports.Frame = void 0;
11
+ const assert_1 = require("../../util/assert");
12
+ /** the index in `history` of what the greatest version at most `version` bound, `-1` if unbound then */
13
+ function at(history, version) {
14
+ let low = 0;
15
+ let high = (history.length >> 1) - 1;
16
+ while (low <= high) {
17
+ const mid = (low + high) >> 1;
18
+ if (history[mid << 1] <= version) {
19
+ low = mid + 1;
20
+ }
21
+ else {
22
+ high = mid - 1;
23
+ }
24
+ }
25
+ return high < 0 ? -1 : (high << 1) + 1;
26
+ }
27
+ /**
28
+ * One frame's bindings across its versions. A frame {@link Frame.of|taken from a map} is frozen: one state, never
29
+ * written, versioned only once {@link forWrite} forks it -- the built-in environment and the package layers.
30
+ */
31
+ class Frame {
32
+ /** the bindings at {@link version} and no other, so read it only after checking the version, as {@link get} does */
33
+ live;
34
+ /** whether {@link live} is this frame's own to write, see {@link Frame.of} */
35
+ frozen;
36
+ /** what each *rewritten* name held per version, for older snapshots; built on the first rewrite, as most see none */
37
+ history;
38
+ /** when each name still on its first binding came in; a write-once name needs no more, and most are */
39
+ bornAt;
40
+ /** the last past version walked out into a map, so re-reading that snapshot skips the walk; one slot only */
41
+ walked;
42
+ /** the newest version written here, counting this frame's writes alone; only a snapshot at it may extend the frame */
43
+ version = 0;
44
+ constructor(live, frozen) {
45
+ this.live = live;
46
+ this.frozen = frozen;
47
+ }
48
+ /** A frame holding what `map` holds, frozen: only read through here, a write forks rather than reaching back. */
49
+ static of(map) {
50
+ return new Frame(map, true);
51
+ }
52
+ /** A frame holding nothing, the same one every time, so an environment that defines nothing allocates nothing. */
53
+ static empty() {
54
+ return EmptyFrame;
55
+ }
56
+ /** What `name` held at `version`. One lookup for the newest version, small enough for V8 to inline. */
57
+ get(name, version) {
58
+ return version === this.version ? this.live.get(name) : this.bound(name, version);
59
+ }
60
+ /** What `name` held at a version written past since. */
61
+ bound(name, version) {
62
+ const history = this.history?.get(name);
63
+ if (history !== undefined) {
64
+ const index = at(history, version);
65
+ return index < 0 ? undefined : history[index];
66
+ }
67
+ const born = this.bornAt?.get(name);
68
+ /* never rewritten, so it still holds what it held then -- unless it came in after then */
69
+ return born !== undefined && born > version ? undefined : this.live.get(name);
70
+ }
71
+ /** Whether `name` was bound at `version`. */
72
+ has(name, version) {
73
+ return (version === this.version ? this.live.get(name) : this.bound(name, version)) !== undefined;
74
+ }
75
+ /** The names `version` binds. */
76
+ keys(version) {
77
+ return (this.settledAt(version) ?? this.materialize(version)).keys();
78
+ }
79
+ /** What `version` binds, without the names. */
80
+ values(version) {
81
+ return (this.settledAt(version) ?? this.materialize(version)).values();
82
+ }
83
+ /** How many names `version` binds. */
84
+ size(version) {
85
+ return (this.settledAt(version) ?? this.materialize(version)).size;
86
+ }
87
+ /** What `version` binds, name by name. */
88
+ entries(version) {
89
+ return (this.settledAt(version) ?? this.materialize(version)).entries();
90
+ }
91
+ /**
92
+ * `version` as a map, `undefined` when it has to be walked out. A frame that never rewrote or took on a name has
93
+ * held the same bindings throughout, so {@link live} answers for any version of it.
94
+ */
95
+ settledAt(version) {
96
+ if (version === this.version || (this.history === undefined && this.bornAt === undefined)) {
97
+ return this.live;
98
+ }
99
+ const walked = this.walked;
100
+ return walked !== undefined && walked.version === version ? walked.bindings : undefined;
101
+ }
102
+ /** `version` walked out into a map, kept in the {@link walked} slot. */
103
+ materialize(version) {
104
+ const bindings = new Map(this.recorded(version));
105
+ this.walked = { version, bindings };
106
+ return bindings;
107
+ }
108
+ /** What `version` bound; the rewritten names come first, since one dropped since is no longer in {@link live}. */
109
+ *recorded(version) {
110
+ const history = this.history;
111
+ if (history !== undefined) {
112
+ for (const name of history.keys()) {
113
+ const defs = this.bound(name, version);
114
+ if (defs !== undefined) {
115
+ yield [name, defs];
116
+ }
117
+ }
118
+ }
119
+ for (const [name, defs] of this.live) {
120
+ if (history?.has(name)) {
121
+ continue;
122
+ }
123
+ const born = this.bornAt?.get(name);
124
+ if (born === undefined || born <= version) {
125
+ yield [name, defs];
126
+ }
127
+ }
128
+ }
129
+ /** The frame a snapshot at `version` writes to: this one if it holds the newest version, a fork otherwise. */
130
+ forWrite(version) {
131
+ if (!this.frozen && version === this.version) {
132
+ return this;
133
+ }
134
+ return new Frame(new Map(this.settledAt(version) ?? this.materialize(version)), false);
135
+ }
136
+ /** The version the next write goes to; only a frame {@link forWrite} just returned may hand one out. */
137
+ nextVersion() {
138
+ (0, assert_1.guard)(!this.frozen, 'a frozen frame hands out no version, fork it with forWrite first');
139
+ return ++this.version;
140
+ }
141
+ /** Binds `name` at `version`, `undefined` removing it. Only the newest version may be written; snapshots hold the rest. */
142
+ set(name, defs, version) {
143
+ const live = this.live;
144
+ (0, assert_1.guard)(!this.frozen && version === this.version, () => `cannot write version ${version} of a frame standing at ${this.version}`);
145
+ const history = this.history?.get(name);
146
+ if (history !== undefined) {
147
+ if (history[history.length - 2] === version) {
148
+ history[history.length - 1] = defs;
149
+ }
150
+ else {
151
+ history.push(version, defs);
152
+ }
153
+ }
154
+ else {
155
+ const before = live.get(name);
156
+ const born = this.bornAt?.get(name);
157
+ if (before === undefined && born === undefined) {
158
+ /* never held here, so when it came in is all an older snapshot needs */
159
+ (this.bornAt ??= new Map()).set(name, version);
160
+ }
161
+ else {
162
+ /* record what it is replacing before the write buries it */
163
+ this.bornAt?.delete(name);
164
+ (this.history ??= new Map()).set(name, [born ?? 0, before, version, defs]);
165
+ }
166
+ }
167
+ if (defs === undefined) {
168
+ live.delete(name);
169
+ }
170
+ else {
171
+ live.set(name, defs);
172
+ }
173
+ }
174
+ }
175
+ exports.Frame = Frame;
176
+ /** what every environment starts out on, until a write forks it one of its own */
177
+ const EmptyFrame = Frame.of(new Map());
178
+ /** One environment's view of its {@link Frame}, as a {@link ReadonlyMap} so the old readers of the map still work. */
179
+ class MemoryView {
180
+ frame;
181
+ version;
182
+ constructor(frame, version) {
183
+ this.frame = frame;
184
+ this.version = version;
185
+ }
186
+ get(name) {
187
+ return this.frame.get(name, this.version);
188
+ }
189
+ has(name) {
190
+ return this.frame.has(name, this.version);
191
+ }
192
+ get size() {
193
+ return this.frame.size(this.version);
194
+ }
195
+ entries() {
196
+ return this.frame.entries(this.version);
197
+ }
198
+ [Symbol.iterator]() {
199
+ return this.frame.entries(this.version);
200
+ }
201
+ keys() {
202
+ return this.frame.keys(this.version);
203
+ }
204
+ values() {
205
+ return this.frame.values(this.version);
206
+ }
207
+ forEach(fn, thisArg) {
208
+ const settled = this.frame.settledAt(this.version);
209
+ if (settled !== undefined) {
210
+ settled.forEach(fn, thisArg);
211
+ return;
212
+ }
213
+ for (const [name, defs] of this.frame.entries(this.version)) {
214
+ fn.call(thisArg, defs, name, this);
215
+ }
216
+ }
217
+ }
218
+ exports.MemoryView = MemoryView;
219
+ /** The write end of a {@link Frame} at one version, standing in for the map writers used to get. */
220
+ class WritableMemory {
221
+ frame;
222
+ version;
223
+ constructor(frame, version) {
224
+ this.frame = frame;
225
+ this.version = version;
226
+ }
227
+ set(name, defs) {
228
+ this.frame.set(name, defs, this.version);
229
+ }
230
+ delete(name) {
231
+ this.frame.set(name, undefined, this.version);
232
+ }
233
+ get(name) {
234
+ return this.frame.get(name, this.version);
235
+ }
236
+ has(name) {
237
+ return this.frame.has(name, this.version);
238
+ }
239
+ }
240
+ exports.WritableMemory = WritableMemory;
241
+ /**
242
+ * The bindings of an attached package, built one name at a time. An attach used to materialize a definition per
243
+ * export, and a script attaching a handful of packages carries hundreds of thousands of them for the few dozen
244
+ * names it ever mentions. Here the export list is all that is held until a lookup asks for one.
245
+ */
246
+ class LazyBindings {
247
+ names;
248
+ bind;
249
+ built = new Map();
250
+ constructor(names, bind) {
251
+ this.names = names;
252
+ this.bind = bind;
253
+ }
254
+ get(name) {
255
+ if (!this.names.has(name)) {
256
+ return undefined;
257
+ }
258
+ let defs = this.built.get(name);
259
+ if (defs === undefined) {
260
+ this.built.set(name, defs = this.bind(name));
261
+ }
262
+ return defs;
263
+ }
264
+ has(name) {
265
+ return this.names.has(name);
266
+ }
267
+ get size() {
268
+ return this.names.size;
269
+ }
270
+ keys() {
271
+ return this.names.keys();
272
+ }
273
+ *entries() {
274
+ for (const name of this.names) {
275
+ yield [name, this.get(name)];
276
+ }
277
+ }
278
+ [Symbol.iterator]() {
279
+ return this.entries();
280
+ }
281
+ *values() {
282
+ for (const [, defs] of this.entries()) {
283
+ yield defs;
284
+ }
285
+ }
286
+ forEach(fn, thisArg) {
287
+ for (const [name, defs] of this.entries()) {
288
+ fn.call(thisArg, defs, name, this);
289
+ }
290
+ }
291
+ }
292
+ exports.LazyBindings = LazyBindings;
293
+ //# sourceMappingURL=frame-memory.js.map
@@ -10,6 +10,8 @@ const identifier_1 = require("./identifier");
10
10
  const info_1 = require("../info");
11
11
  const built_in_s_seven_dispatch_1 = require("../internal/process/functions/call/built-in/built-in-s-seven-dispatch");
12
12
  const node_id_1 = require("../../r-bridge/lang-4.x/ast/model/processing/node-id");
13
+ /** how many answers a frozen layer memoizes before it starts over, so the memo cannot grow without bound */
14
+ const TailCacheCap = 4096;
13
15
  /** A namespaced lookup only sees its matching layer; a bare lookup skips loaded-but-unattached namespaces (`requireNamespace`). */
14
16
  function layerSkipped(layer, ns) {
15
17
  if (ns !== undefined) {
@@ -85,11 +87,24 @@ function resolveByTargetType(id, environment, target) {
85
87
  /* `current` can already be the built-in environment itself (e.g. `get(x, envir=baseenv())`);
86
88
  * it has no parent to walk to, so resolve directly instead of entering the loop below. */
87
89
  if (current.builtInEnv) {
88
- return current.memory.get(name);
90
+ return current.lookup(name);
89
91
  }
90
92
  let definitions = undefined;
91
93
  const wantedType = TargetTypePredicate[target];
94
+ /* the attached packages below the code's own frames are a dozen layers deep and nothing writes them, so the
95
+ * walk through them is done once per name and target instead of once per resolution */
96
+ const flatten = ns === undefined && internal !== false && typeof id === 'string'
97
+ && target !== identifier_1.ReferenceType.S3MethodPrefix && target !== identifier_1.ReferenceType.S7MethodPrefix;
98
+ const key = flatten ? `${target}\u0000${name}` : '';
99
+ let flattenAt;
92
100
  do {
101
+ if (flatten && flattenAt === undefined && definitions === undefined && (current.t !== undefined || current.builtInEnv)) {
102
+ const cached = current.tailCache?.get(key);
103
+ if (cached !== undefined || current.tailCache?.has(key)) {
104
+ return cached;
105
+ }
106
+ flattenAt = current;
107
+ }
93
108
  if (layerSkipped(current, ns)) {
94
109
  current = current.parent;
95
110
  continue;
@@ -104,7 +119,7 @@ function resolveByTargetType(id, environment, target) {
104
119
  .toArray();
105
120
  }
106
121
  else {
107
- definition = current.memory.get(name);
122
+ definition = current.lookup(name);
108
123
  if (internal === false) {
109
124
  definition = definition?.filter(({ name }) => name === undefined || !identifier_1.Identifier.accessesInternal(name));
110
125
  }
@@ -125,6 +140,9 @@ function resolveByTargetType(id, environment, target) {
125
140
  }
126
141
  }
127
142
  if (allOk) {
143
+ if (flattenAt !== undefined) {
144
+ (flattenAt.tailCache ??= new Map()).set(key, definition);
145
+ }
128
146
  return definition;
129
147
  }
130
148
  /* never alias the environment's own array, it is appended to below */
@@ -142,12 +160,19 @@ function resolveByTargetType(id, environment, target) {
142
160
  } while (!current.builtInEnv);
143
161
  /* the built-in layer is handed over as it is, except to a value position: `filter(df, c > 2)` means the
144
162
  column `c`, never `base::c`, and only with nothing left does `ownDefinitions` have its say */
145
- const known = statedIn(current, name, ns) ?? current.memory.get(name);
163
+ const known = statedIn(current, name, ns) ?? current.lookup(name);
146
164
  const builtIns = target === identifier_1.ReferenceType.NonFunction ? known?.filter(wantedType) : known;
147
- if (definitions) {
148
- return builtIns === undefined || builtIns.length === 0 ? definitions : definitions.concat(builtIns);
165
+ const result = definitions
166
+ ? (builtIns === undefined || builtIns.length === 0 ? definitions : definitions.concat(builtIns))
167
+ : (builtIns === undefined || builtIns.length > 0 ? builtIns : undefined);
168
+ if (flattenAt !== undefined) {
169
+ const memo = flattenAt.tailCache ??= new Map();
170
+ if (memo.size >= TailCacheCap) {
171
+ memo.clear();
172
+ }
173
+ memo.set(key, result);
149
174
  }
150
- return builtIns === undefined || builtIns.length > 0 ? builtIns : undefined;
175
+ return result;
151
176
  }
152
177
  /**
153
178
  * The more performant version of {@link resolveByName} when the target type is unknown.
@@ -168,7 +193,7 @@ function resolveByNameAnyType(id, environment) {
168
193
  const internal = identifier_1.Identifier.accessesInternal(id);
169
194
  /* `current` can already be the built-in environment itself */
170
195
  if (current.builtInEnv) {
171
- const ret = current.memory.get(name);
196
+ const ret = current.lookup(name);
172
197
  if (ret && cacheable) {
173
198
  current.cache ??= new Map();
174
199
  current.cache.set(id, ret);
@@ -181,7 +206,7 @@ function resolveByNameAnyType(id, environment) {
181
206
  current = current.parent;
182
207
  continue;
183
208
  }
184
- let definition = current.memory.get(name);
209
+ let definition = current.lookup(name);
185
210
  if (definition) {
186
211
  if (internal === false) {
187
212
  definition = definition.filter(({ name }) => name === undefined || !identifier_1.Identifier.accessesInternal(name));
@@ -204,7 +229,7 @@ function resolveByNameAnyType(id, environment) {
204
229
  }
205
230
  current = current.parent;
206
231
  } while (!current.builtInEnv);
207
- const builtIns = statedIn(current, name, ns) ?? current.memory.get(name);
232
+ const builtIns = statedIn(current, name, ns) ?? current.lookup(name);
208
233
  let ret;
209
234
  if (definitions) {
210
235
  ret = builtIns === undefined ? definitions : definitions.concat(builtIns);
@@ -608,7 +608,7 @@ function envFromJson(json) {
608
608
  }
609
609
  const obj = new environment_1.Environment(parent, json.builtInEnv);
610
610
  obj.id = json.id;
611
- obj.memory = memory;
611
+ obj.adoptMap(memory);
612
612
  const env = obj;
613
613
  env.n = json.n;
614
614
  env.t = json.t;
@@ -22,6 +22,7 @@ const logger_1 = require("../../../../../logger");
22
22
  const r_string_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-string");
23
23
  const type_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/type");
24
24
  const make_argument_1 = require("../argument/make-argument");
25
+ const frame_memory_1 = require("../../../../../environments/frame-memory");
25
26
  const identifier_1 = require("../../../../../environments/identifier");
26
27
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
27
28
  const environment_1 = require("../../../../../environments/environment");
@@ -350,6 +351,17 @@ function selectExports(callables, spec) {
350
351
  }
351
352
  return callables.filter(c => !spec.exclude?.has(c)).map(c => ({ exported: c, as: c }));
352
353
  }
354
+ /**
355
+ * What a package's attached layer binds, built per name on the first lookup. An attach names thousands of exports
356
+ * and a script mentions a few dozen, so the definitions are only made for the ones something asks about.
357
+ */
358
+ function lazyExports(pack, exports, ctx, definedAt) {
359
+ const byName = new Map();
360
+ for (const exp of exports) {
361
+ byName.set(identifier_1.Identifier.getName(identifier_1.Identifier.make(exp.as, pack)), exp);
362
+ }
363
+ return new frame_memory_1.LazyBindings(new Set(byName.keys()), name => [exportDefinition(pack, byName.get(name), ctx, definedAt)]);
364
+ }
353
365
  /**
354
366
  * The identifier definition binding a package export (or its alias) to its built-in function-definition.
355
367
  * The identity stays the plain export (so a call still materializes its `built-in:pkg:fn` vertex); whatever the configuration states about that name (processor, config, eval handler) rides along on top.
@@ -392,15 +404,15 @@ function attachDependencyToEnvironment(dependency, envInfo, ctx, spec = {}, defi
392
404
  // a subset import restricts the attached exports, so no imports layer is materialized
393
405
  if (spec.namespaceOnly || (spec.include !== undefined && !spec.all)) {
394
406
  const layerType = spec.namespaceOnly ? environment_1.EnvType.LoadedNamespace : environment_1.EnvType.Namespace;
395
- const layer = new environment_1.Environment(envInfo.current).asLibrary(pack, layerType)
396
- .defineAll(exports.map(exp => exportDefinition(pack, exp, ctx, definedAt)));
407
+ const layer = new environment_1.Environment(envInfo.current).asLibrary(pack, layerType);
408
+ layer.adoptMap(lazyExports(pack, exports, ctx, definedAt));
397
409
  return { level: envInfo.level, current: environment_1.REnvironment.attachAt(envInfo.current, layer, layer, spec.pos) };
398
410
  }
399
411
  // full attach: imports layer at the bottom, namespace (exports) layer on top
400
412
  let importsEnv = new environment_1.Environment(envInfo.current).asLibrary(pack, environment_1.EnvType.Imports);
401
413
  importsEnv = recImports(importsEnv, dependency.namespaceInfo, ctx, new Set());
402
- const namespaceEnv = new environment_1.Environment(importsEnv).asLibrary(pack, environment_1.EnvType.Namespace)
403
- .defineAll(exports.map(exp => exportDefinition(pack, exp, ctx, definedAt)));
414
+ const namespaceEnv = new environment_1.Environment(importsEnv).asLibrary(pack, environment_1.EnvType.Namespace);
415
+ namespaceEnv.adoptMap(lazyExports(pack, exports, ctx, definedAt));
404
416
  const attached = { level: envInfo.level, current: environment_1.REnvironment.attachAt(envInfo.current, namespaceEnv, importsEnv, spec.pos) };
405
417
  /* whatever R puts on the search path with it, `pack` first so a dependency cycle stays finite (the guard above stops it) */
406
418
  return (0, attached_packages_1.attachedAlongside)(pack, ctx.deps.signatureSources()).reduce((env, alongside) => {
@@ -567,7 +579,7 @@ function attachStatedDefinitions(pack, envInfo, ctx, spec, as, loadedAt, cds) {
567
579
  }
568
580
  const layer = new environment_1.Environment(envInfo.current)
569
581
  .asLibrary(pack, as ?? (spec.namespaceOnly ? environment_1.EnvType.LoadedNamespace : environment_1.EnvType.Namespace));
570
- layer.memory = memory;
582
+ layer.adoptMap(memory);
571
583
  return { level: envInfo.level, current: environment_1.REnvironment.attachAt(envInfo.current, layer, layer, spec.pos) };
572
584
  }
573
585
  /**
@@ -161,11 +161,18 @@ function* escapeTargetFrames(fdef) {
161
161
  * dominated by the built-ins it holds, so filtering each frame once per pass saves the bulk of the work.
162
162
  */
163
163
  function escapedDefinitions() {
164
+ /* keyed by frame and then by version: one frame answers differently at each, so the version has to be part of it */
164
165
  const perFrame = new Map();
165
166
  return (_id, fdef) => {
166
167
  const defs = [];
167
168
  for (const e of escapeTargetFrames(fdef)) {
168
- let escaped = perFrame.get(e.memory);
169
+ const { frame, version } = e.memory;
170
+ let byVersion = perFrame.get(frame);
171
+ if (byVersion === undefined) {
172
+ byVersion = new Map();
173
+ perFrame.set(frame, byVersion);
174
+ }
175
+ let escaped = byVersion.get(version);
169
176
  if (escaped === undefined) {
170
177
  /* a package frame holds thousands of entries and keeps none of them, so this walks them in place
171
178
  * rather than through a spread/flatMap/filter/map chain that allocates an array per step */
@@ -178,7 +185,7 @@ function escapedDefinitions() {
178
185
  }
179
186
  }
180
187
  escaped = collected;
181
- perFrame.set(e.memory, escaped);
188
+ byVersion.set(version, escaped);
182
189
  }
183
190
  for (const d of escaped) {
184
191
  defs.push(d);
@@ -242,16 +249,23 @@ function propagateTransitivePackages(graph, environment, ctx) {
242
249
  /** Maps each escaped definition's node id to its full (name-carrying) definition. */
243
250
  function escapedDefinitionMap(graph) {
244
251
  const map = new Map();
245
- const seen = new Set();
252
+ /* a frame answers differently at each version, so a visit is only a repeat when both match */
253
+ const seen = new Map();
246
254
  for (const [, vertex] of graph.vertices(true)) {
247
255
  if (!vertex_1.FunctionDefinitionVertex.is(vertex)) {
248
256
  continue;
249
257
  }
250
258
  for (const e of escapeTargetFrames(vertex)) {
251
- if (seen.has(e.memory)) {
259
+ const { frame, version } = e.memory;
260
+ let versions = seen.get(frame);
261
+ if (versions === undefined) {
262
+ versions = new Set();
263
+ seen.set(frame, versions);
264
+ }
265
+ else if (versions.has(version)) {
252
266
  continue; // a frame shared with an already-visited definition contributes the same entries
253
267
  }
254
- seen.add(e.memory);
268
+ versions.add(version);
255
269
  for (const definitions of e.memory.values()) {
256
270
  for (const def of definitions) {
257
271
  if (!node_id_1.NodeId.isBuiltIn(def.nodeId) && def.name !== undefined) {
@@ -11,6 +11,7 @@ const vertex_1 = require("../../dataflow/graph/vertex");
11
11
  const identify_link_to_last_call_relation_1 = require("../../queries/catalog/call-context-query/identify-link-to-last-call-relation");
12
12
  const input_source_functions_1 = require("../../queries/catalog/input-sources-query/input-source-functions");
13
13
  const simple_input_classifier_1 = require("../../queries/catalog/input-sources-query/simple-input-classifier");
14
+ const edge_1 = require("../../dataflow/graph/edge");
14
15
  const model_1 = require("../../r-bridge/lang-4.x/ast/model/model");
15
16
  const flowr_search_builder_1 = require("../../search/flowr-search-builder");
16
17
  const parse_1 = require("../../slicing/criterion/parse");
@@ -35,6 +36,8 @@ var UnescapedArgumentCategory;
35
36
  /** Functions generating/running JavaScript code, e.g. `shinyjs::runjs` */
36
37
  UnescapedArgumentCategory["JavaScript"] = "javascript";
37
38
  })(UnescapedArgumentCategory || (exports.UnescapedArgumentCategory = UnescapedArgumentCategory = {}));
39
+ /** how many vertices {@link readsParameter} may visit before it gives up on finding one */
40
+ const ParameterSearchLimit = 256;
38
41
  /** Maximum depth to descent to find unescaped part of argument */
39
42
  const MaxDescentDepth = 5;
40
43
  /** Input types that are considered to be safe */
@@ -111,6 +114,36 @@ function mapInputSourceToArgs(call, sources) {
111
114
  }
112
115
  return result;
113
116
  }
117
+ /**
118
+ * Whether anything `start` reads is a parameter of an enclosing function. What the call sites happen to pass says
119
+ * nothing here: the function escapes its parameter, and it is one call away from being handed anything at all.
120
+ */
121
+ function readsParameter(graph, start, sanitizers) {
122
+ const seen = new Set([start]);
123
+ const queue = [start];
124
+ while (queue.length > 0) {
125
+ const id = queue.pop();
126
+ if (graph.idMap?.get(id)?.info.role === "param-n" /* RoleInParent.ParameterName */) {
127
+ return true;
128
+ }
129
+ const vertex = graph.getVertex(id);
130
+ /* what a sanitizer hands back is escaped, whatever it read to get there */
131
+ if (vertex_1.FunctionCallVertex.is(vertex) && sanitizers.has(identifier_1.Identifier.getName(vertex.name))) {
132
+ continue;
133
+ }
134
+ if (seen.size > ParameterSearchLimit) {
135
+ return false;
136
+ }
137
+ for (const [to, edge] of graph.outgoingEdges(id) ?? graph_1.NoEdges) {
138
+ /* only what the value is built from, never the calls it is an argument of */
139
+ if (!seen.has(to) && edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Reads | edge_1.EdgeType.DefinedBy | edge_1.EdgeType.Returns)) {
140
+ seen.add(to);
141
+ queue.push(to);
142
+ }
143
+ }
144
+ }
145
+ return false;
146
+ }
114
147
  function isAcceptedInput(source, config) {
115
148
  return source.types.every(type => config.acceptedInputs.includes(type));
116
149
  }
@@ -121,6 +154,7 @@ function isCertainlyCritical(source, config) {
121
154
  * Gets all unescaped sources for the critical target calls of the given category
122
155
  */
123
156
  async function getUnescapedSources(category, targets, config, data, graph) {
157
+ const sanitizerNames = new Set((config.categories[category].sanitizers ?? []).map(call => identifier_1.Identifier.getName(call)));
124
158
  const sanitizers = (config.categories[category].sanitizers ?? []).map(call => ({ call }));
125
159
  const queryConfig = { narrowing: [...(0, input_source_functions_1.narrowingFunctions)(), ...sanitizers] };
126
160
  const found = new Map();
@@ -137,14 +171,20 @@ async function getUnescapedSources(category, targets, config, data, graph) {
137
171
  }
138
172
  for (const [arg, source] of mapInputSourceToArgs(call, classified[parse_1.SlicingCriterion.fromId(entry.call)] ?? [])) {
139
173
  const vertex = graph.getVertex(arg);
140
- if ((entry.only !== undefined && !entry.only.has(arg)) || isAcceptedInput(source, config)) {
174
+ /* a call passing a constant today makes the argument constant, but the function still escapes its
175
+ parameter, and it is one call away from being handed anything */
176
+ const viaParameter = isAcceptedInput(source, config)
177
+ && source.types.length > 0 && source.types.every(t => t === simple_input_classifier_1.InputType.Constant || t === simple_input_classifier_1.InputType.DerivedConstant)
178
+ && readsParameter(graph, arg, sanitizerNames);
179
+ if ((entry.only !== undefined && !entry.only.has(arg)) || (isAcceptedInput(source, config) && !viaParameter)) {
141
180
  continue;
142
181
  }
143
- else if (entry.depth < config.maxDecentDepth && source.trace === simple_input_classifier_1.InputTraceType.Known && vertex_1.FunctionCallVertex.is(vertex) && !vertex_1.FunctionCallVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Access)) {
182
+ else if (entry.depth < config.maxDecentDepth && (source.trace === simple_input_classifier_1.InputTraceType.Known || viaParameter) && vertex_1.FunctionCallVertex.is(vertex) && !vertex_1.FunctionCallVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Access)) {
144
183
  next.push({ target: entry.target, call: arg, only: undefined, depth: entry.depth + 1 });
145
184
  }
146
185
  else {
147
- found.set(entry.target, [...(found.get(entry.target) ?? []), { ...source, id: arg }]);
186
+ const types = viaParameter ? [...source.types, simple_input_classifier_1.InputType.Parameter] : source.types;
187
+ found.set(entry.target, [...(found.get(entry.target) ?? []), { ...source, id: arg, types }]);
148
188
  }
149
189
  }
150
190
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eagleoutice/flowr",
3
- "version": "2.15.3",
3
+ "version": "2.15.5",
4
4
  "description": "Static Dataflow Analyzer and Program Slicer for the R Programming Language",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -23,9 +23,9 @@ class FlowrAnalyzerEnvironmentContext {
23
23
  const builtInsConfig = ctx.config.semantics.environment.overwriteBuiltIns;
24
24
  const builtIns = (0, built_in_config_1.getBuiltInDefinitions)(builtInsConfig.definitions, builtInsConfig.loadDefaults);
25
25
  this.builtInEnv = new environment_1.Environment(undefined, true);
26
- this.builtInEnv.memory = builtIns.builtInMemory;
26
+ this.builtInEnv.adoptMap(builtIns.builtInMemory);
27
27
  this.emptyBuiltInEnv = new environment_1.Environment(undefined, true);
28
- this.emptyBuiltInEnv.memory = builtIns.emptyBuiltInMemory;
28
+ this.emptyBuiltInEnv.adoptMap(builtIns.emptyBuiltInMemory);
29
29
  this.stated = builtIns.packageMemory;
30
30
  /* `pkg::fn` resolves whether or not the package is attached, so the built-in env answers for it */
31
31
  this.builtInEnv.namespaces = builtIns.packageMemory;
@@ -217,6 +217,10 @@ class FlowrAnalyzerPackageVersionsSigDbPlugin extends flowr_analyzer_package_ver
217
217
  this.resetAssembled(); // reload on (re)registration so config/source changes take effect (shared bundles are reused)
218
218
  this.analyzerCtx = ctx;
219
219
  if ((0, config_1.isSigDbEnabled)(ctx.config)) {
220
+ const budgetMb = ctx.config.solver.sigdb.blobCacheBudgetMb;
221
+ if (budgetMb !== undefined) {
222
+ (0, reader_1.setBlobCacheBudget)(budgetMb * 1024 * 1024);
223
+ }
220
224
  ctx.deps.addLazyResolver((name, existing) => this.resolve(name, existing));
221
225
  if (ctx.config.solver.sigdb.warmInBackground) {
222
226
  this.startBackgroundWarm();
@@ -137,13 +137,15 @@ export interface OpenSyncOptions {
137
137
  export interface OpenSyncFromOptions extends SigDbOpenOptions, OpenSyncOptions {
138
138
  hash?: string;
139
139
  }
140
+ /** Sets how many bytes of decoded blobs all open bundles may hold together (`solver.sigdb.blobCacheBudgetMb`). */
141
+ export declare function setBlobCacheBudget(bytes: number): void;
140
142
  /**
141
143
  * Fast, partial reader for a single bundle. `open()`/`openSync()` load the string dictionary + `.idx` once, then every
142
144
  * query seeks straight to one package blob; `open()` additionally decompresses a `.br`/`.gz` source into a hash-keyed cache.
143
145
  */
144
146
  export declare class SigDatabase implements PackageSignatureSource {
145
147
  private closed;
146
- /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; bounded by {@link BlobCacheBudget} */
148
+ /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; bounded by {@link setBlobCacheBudget|the shared budget} */
147
149
  private readonly blobCache;
148
150
  /** a version's function indices plus its `name -> index` view, keyed by package and version; FIFO-bounded */
149
151
  private readonly versionFnCache;
@@ -214,7 +216,7 @@ export declare class SigDatabase implements PackageSignatureSource {
214
216
  /**
215
217
  * Resolve a package version to its blob and the function records of that version (the shared prologue of
216
218
  * {@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.
219
+ * {@link versionFnCache}: holding one here would keep it decoded past what {@link setBlobCacheBudget|the shared budget} allows.
218
220
  */
219
221
  private versionFns;
220
222
  functions(pkg: string, version?: string): DecodedFunction[] | undefined;
@@ -8,6 +8,7 @@ exports.readSignatureDb = readSignatureDb;
8
8
  exports.availableVersionEntries = availableVersionEntries;
9
9
  exports.classOwnerIndexFor = classOwnerIndexFor;
10
10
  exports.sourceForPackage = sourceForPackage;
11
+ exports.setBlobCacheBudget = setBlobCacheBudget;
11
12
  exports.getSharedSigSourceSync = getSharedSigSourceSync;
12
13
  exports.getSharedSigSource = getSharedSigSource;
13
14
  exports.verifyShardedDatabase = verifyShardedDatabase;
@@ -313,20 +314,52 @@ const NoFile = -1;
313
314
  * anything: how many shards a query set opens is not something the caller picks, and each would claim the
314
315
  * budget again. A count would not bound anything either -- one package's blob outweighs a hundred small ones.
315
316
  */
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 */
317
+ let blobCacheBudget = 16 * 1024 * 1024;
318
+ /** Sets how many bytes of decoded blobs all open bundles may hold together (`solver.sigdb.blobCacheBudgetMb`). */
319
+ function setBlobCacheBudget(bytes) {
320
+ blobCacheBudget = Math.max(0, bytes);
321
+ }
322
+ /** what every open bundle holds decoded, so the budget is spent across all of them */
318
323
  const cachedBlobs = [];
324
+ /** where {@link keepBlob} resumes looking for something to drop */
325
+ let hand = 0;
319
326
  let cachedBlobBytes = 0;
320
- /** keep `blob` decoded for `db`, dropping what any bundle read longest ago until all of them fit the budget */
327
+ /**
328
+ * Keep `blob` decoded for `db`, dropping blobs until all of them fit the budget (age gated).
329
+ */
321
330
  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);
331
+ while (cachedBlobBytes + bytes > blobCacheBudget && cachedBlobs.length > 0) {
332
+ if (hand >= cachedBlobs.length) {
333
+ hand = 0;
334
+ }
335
+ const candidate = cachedBlobs[hand];
336
+ if (candidate.used) {
337
+ candidate.used = false;
338
+ hand++;
339
+ continue;
340
+ }
341
+ cachedBlobs.splice(hand, 1);
342
+ cachedBlobBytes -= candidate.bytes;
343
+ candidate.db.dropBlob(candidate.blobIdx);
327
344
  }
328
- cachedBlobs.push({ db, blobIdx, bytes });
345
+ const entry = { db, blobIdx, bytes, used: true };
346
+ cachedBlobs.push(entry);
329
347
  cachedBlobBytes += bytes;
348
+ return entry;
349
+ }
350
+ /** Mark `entry` read, so the hand passes over it once before dropping it. */
351
+ function touchBlob(entry) {
352
+ entry.used = true;
353
+ }
354
+ /** give back what `db` held, so a closed bundle stops spending the budget of the open ones */
355
+ function releaseBlobs(db) {
356
+ for (let i = cachedBlobs.length - 1; i >= 0; i--) {
357
+ if (cachedBlobs[i].db === db) {
358
+ cachedBlobBytes -= cachedBlobs[i].bytes;
359
+ cachedBlobs.splice(i, 1);
360
+ }
361
+ }
362
+ hand = 0;
330
363
  }
331
364
  /**
332
365
  * Fast, partial reader for a single bundle. `open()`/`openSync()` load the string dictionary + `.idx` once, then every
@@ -334,7 +367,7 @@ function keepBlob(db, blobIdx, bytes) {
334
367
  */
335
368
  class SigDatabase {
336
369
  closed = false;
337
- /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; bounded by {@link BlobCacheBudget} */
370
+ /** parsed blobs by blob index so repeated lookups skip the re-read + JSON.parse; bounded by {@link setBlobCacheBudget|the shared budget} */
338
371
  blobCache = new Map();
339
372
  /** a version's function indices plus its `name -> index` view, keyed by package and version; FIFO-bounded */
340
373
  versionFnCache = new Map();
@@ -361,7 +394,7 @@ class SigDatabase {
361
394
  static fromMemory(db) {
362
395
  const index = { byteCount: 0, dict: [0, 0], blobs: [], pkgs: db.pkgs, meta: db.meta };
363
396
  const source = new SigDatabase(NoFile, db.strings, index, db.content, db.cranBase ?? schema_1.DefaultCranBase);
364
- db.blobs.forEach((blob, i) => source.blobCache.set(i, blob));
397
+ db.blobs.forEach((blob, i) => source.blobCache.set(i, { blob }));
365
398
  return source;
366
399
  }
367
400
  /**
@@ -421,7 +454,10 @@ class SigDatabase {
421
454
  }
422
455
  const cached = this.blobCache.get(blobIdx);
423
456
  if (cached !== undefined) {
424
- return cached;
457
+ if (cached.entry !== undefined) {
458
+ touchBlob(cached.entry);
459
+ }
460
+ return cached.blob;
425
461
  }
426
462
  if (this.fd === NoFile) {
427
463
  return undefined; // an in-memory database starts out with every blob cached
@@ -431,8 +467,7 @@ class SigDatabase {
431
467
  if (!this.nameIdsOfBlob.has(blobIdx)) {
432
468
  this.nameIdsOfBlob.set(blobIdx, Int32Array.from(new Set(blob.fns.map(fn => fn[0]))).sort());
433
469
  }
434
- keepBlob(this, blobIdx, range[1]);
435
- this.blobCache.set(blobIdx, blob);
470
+ this.blobCache.set(blobIdx, { blob, entry: keepBlob(this, blobIdx, range[1]) });
436
471
  return blob;
437
472
  }
438
473
  /** the dictionary id of `name`, or `-1` if the dictionary does not hold it, so no package can offer it */
@@ -498,7 +533,7 @@ class SigDatabase {
498
533
  allBlobs() {
499
534
  // an in-memory database has no byte ranges to re-read: its blobs are the cached ones, in blob-index order
500
535
  return this.fd === NoFile
501
- ? [...this.blobCache.entries()].sort(([a], [b]) => a - b).map(([, blob]) => blob)
536
+ ? [...this.blobCache.entries()].sort(([a], [b]) => a - b).map(([, { blob }]) => blob)
502
537
  : this.index.blobs.map(range => this.readBlobAt(range));
503
538
  }
504
539
  /** recompute this bundle's self-contained content hash from its re-read data (matches {@link writeSignatureDb}) */
@@ -573,7 +608,7 @@ class SigDatabase {
573
608
  /**
574
609
  * Resolve a package version to its blob and the function records of that version (the shared prologue of
575
610
  * {@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.
611
+ * {@link versionFnCache}: holding one here would keep it decoded past what {@link setBlobCacheBudget|the shared budget} allows.
577
612
  */
578
613
  versionFns(pkg, version) {
579
614
  const bm = this.blobMeta(pkg);
@@ -677,6 +712,7 @@ class SigDatabase {
677
712
  close() {
678
713
  if (!this.closed) {
679
714
  this.closed = true;
715
+ releaseBlobs(this);
680
716
  this.blobCache.clear();
681
717
  this.versionFnCache.clear();
682
718
  this.classIndex = undefined;
@@ -593,11 +593,10 @@ class InputClassifier {
593
593
  // caller argument), follow it into the caller; only if that leads nowhere is it an opaque Scope origin
594
594
  const onCall = this.definedByOnCallTargets(v.id);
595
595
  if (onCall.length > 0) {
596
- const callers = onCall.map(t => this.classifyInFullGraph(t))
597
- .filter(assert_1.isNotUndefined)
598
- .filter(c => !c.types.includes(input_types_1.InputType.Unknown));
599
- if (callers.length > 0) {
600
- callers.forEach(c => acc.merge(c));
596
+ const callers = onCall.map(t => this.classifyInFullGraph(t)).filter(assert_1.isNotUndefined);
597
+ const known = callers.filter(c => !c.types.includes(input_types_1.InputType.Unknown));
598
+ known.forEach(c => acc.merge(c));
599
+ if (known.length > 0 && known.length === callers.length) {
601
600
  return;
602
601
  }
603
602
  acc.types.push(input_types_1.InputType.Scope);
@@ -32,7 +32,12 @@ function definitionHash(definition) {
32
32
  return hash;
33
33
  }
34
34
  function memoryHash(memory) {
35
- let hash = memoryHashes.get(memory);
35
+ let byVersion = memoryHashes.get(memory.frame);
36
+ if (byVersion === undefined) {
37
+ byVersion = new Map();
38
+ memoryHashes.set(memory.frame, byVersion);
39
+ }
40
+ let hash = byVersion.get(memory.version);
36
41
  if (hash === undefined) {
37
42
  const entries = [];
38
43
  for (const [name, definitions] of memory) {
@@ -40,7 +45,7 @@ function memoryHash(memory) {
40
45
  }
41
46
  entries.sort();
42
47
  hash = (0, object_hash_1.default)(entries, HashOptions);
43
- memoryHashes.set(memory, hash);
48
+ byVersion.set(memory.version, hash);
44
49
  }
45
50
  return hash;
46
51
  }
package/util/version.js CHANGED
@@ -42,9 +42,9 @@ const assert_1 = require("./assert");
42
42
  const sigdb_download_1 = require("../project/sigdb/sigdb-download");
43
43
  const doc_files_1 = require("../documentation/doc-util/doc-files");
44
44
  // this is automatically replaced with the current version by release-it
45
- const version = '2.15.3';
45
+ const version = '2.15.5';
46
46
  // this is automatically replaced with the release date by release-it (regex-bumper, see package.json)
47
- const versionDate = '2026-08-26T12:04:46Z';
47
+ const versionDate = '2026-08-26T19:54:19Z';
48
48
  /**
49
49
  * Retrieves the current flowR version as a new {@link SemVer} object.
50
50
  */