@eagleoutice/flowr 2.17.1 → 2.17.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 (90) hide show
  1. package/README.md +9 -9
  2. package/control-flow/semantic-cfg-guided-visitor.js +2 -0
  3. package/data/r-reexports.generated.d.ts +4 -0
  4. package/data/r-reexports.generated.js +43 -0
  5. package/dataflow/environments/ambient-state-name.d.ts +4 -0
  6. package/dataflow/environments/ambient-state-name.js +4 -0
  7. package/dataflow/environments/built-in-proc-name.d.ts +4 -0
  8. package/dataflow/environments/built-in-proc-name.js +4 -0
  9. package/dataflow/environments/built-in-props.d.ts +2 -0
  10. package/dataflow/environments/built-in-props.js +3 -1
  11. package/dataflow/environments/built-in.d.ts +16 -6
  12. package/dataflow/environments/built-in.js +45 -4
  13. package/dataflow/environments/default-builtin-config.d.ts +846 -21
  14. package/dataflow/environments/default-builtin-config.js +120 -26
  15. package/dataflow/environments/environment.d.ts +19 -2
  16. package/dataflow/environments/environment.js +90 -19
  17. package/dataflow/environments/identifier.d.ts +18 -0
  18. package/dataflow/environments/query-fn-props.js +4 -3
  19. package/dataflow/environments/resolve-by-name.js +5 -3
  20. package/dataflow/eval/resolve/node-value.d.ts +1 -1
  21. package/dataflow/eval/resolve/node-value.js +2 -2
  22. package/dataflow/eval/resolve/resolve-argument.js +1 -1
  23. package/dataflow/extractor.js +20 -4
  24. package/dataflow/graph/df-helper.d.ts +42 -1
  25. package/dataflow/graph/df-helper.js +83 -0
  26. package/dataflow/info.d.ts +2 -0
  27. package/dataflow/info.js +4 -0
  28. package/dataflow/internal/linker.js +21 -5
  29. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-keys.d.ts +4 -0
  30. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-keys.js +3 -0
  31. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +18 -2
  32. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +144 -30
  33. package/dataflow/internal/process/functions/call/built-in/built-in-apply.d.ts +1 -1
  34. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +2 -1
  35. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +1 -1
  36. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +10 -0
  37. package/dataflow/internal/process/functions/call/built-in/built-in-attach.d.ts +8 -4
  38. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +43 -8
  39. package/dataflow/internal/process/functions/call/built-in/built-in-env-contents.d.ts +1 -1
  40. package/dataflow/internal/process/functions/call/built-in/built-in-env-contents.js +5 -4
  41. package/dataflow/internal/process/functions/call/built-in/built-in-eval.js +67 -3
  42. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +4 -2
  43. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +27 -3
  44. package/dataflow/internal/process/functions/call/built-in/built-in-get.d.ts +1 -1
  45. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +2 -14
  46. package/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.js +1 -7
  47. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +28 -10
  48. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +138 -89
  49. package/dataflow/internal/process/functions/call/built-in/built-in-load.d.ts +1 -1
  50. package/dataflow/internal/process/functions/call/built-in/built-in-load.js +87 -10
  51. package/dataflow/internal/process/functions/call/built-in/built-in-local.d.ts +8 -0
  52. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +23 -12
  53. package/dataflow/internal/process/functions/call/built-in/built-in-source.d.ts +7 -1
  54. package/dataflow/internal/process/functions/call/built-in/built-in-source.js +28 -10
  55. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.js +1 -1
  56. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +7 -5
  57. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.d.ts +2 -2
  58. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +18 -15
  59. package/dataflow/internal/process/functions/call/named-call-handling.js +8 -4
  60. package/dataflow/internal/process/functions/call/quoted.d.ts +2 -0
  61. package/dataflow/internal/process/functions/call/quoted.js +8 -7
  62. package/documentation/wiki-dataflow-graph.js +25 -1
  63. package/linter/rules/undefined-symbol.js +2 -2
  64. package/package.json +1 -1
  65. package/project/attached-packages.d.ts +11 -6
  66. package/project/attached-packages.js +37 -9
  67. package/project/plugins/file-plugins/files/flowr-namespace-file.d.ts +5 -0
  68. package/project/plugins/file-plugins/files/flowr-namespace-file.js +13 -0
  69. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +1 -1
  70. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +25 -2
  71. package/project/sigdb/build.js +7 -6
  72. package/project/sigdb/decode.d.ts +2 -0
  73. package/project/sigdb/decode.js +9 -3
  74. package/project/sigdb/schema.d.ts +8 -3
  75. package/queries/catalog/signature-query/signature-query-executor.js +15 -1
  76. package/queries/catalog/signature-query/signature-query-format.d.ts +3 -2
  77. package/r-bridge/data/data.d.ts +2 -2
  78. package/r-bridge/data/data.js +2 -2
  79. package/r-bridge/lang-4.x/ast/model/model.d.ts +2 -0
  80. package/r-bridge/lang-4.x/ast/model/model.js +6 -1
  81. package/r-bridge/lang-4.x/ast/model/processing/node-id.d.ts +6 -1
  82. package/r-bridge/lang-4.x/ast/model/processing/node-id.js +12 -1
  83. package/reconstruct/reconstruct.js +2 -5
  84. package/search/search-executor/search-enrichers.js +17 -2
  85. package/search/search-executor/search-generators.js +6 -2
  86. package/slicing/static/slice-call.d.ts +16 -0
  87. package/slicing/static/slice-call.js +42 -0
  88. package/slicing/static/static-slicer.js +6 -0
  89. package/util/flowr-version.d.ts +1 -1
  90. package/util/flowr-version.js +2 -2
@@ -12,9 +12,13 @@ const vertex_1 = require("./vertex");
12
12
  const identifier_1 = require("../environments/identifier");
13
13
  const built_in_proc_name_1 = require("../environments/built-in-proc-name");
14
14
  const r_base_packages_1 = require("../../util/r-base-packages");
15
+ const flowr_namespace_file_1 = require("../../project/plugins/file-plugins/files/flowr-namespace-file");
15
16
  const defaultmap_1 = require("../../util/collections/defaultmap");
16
17
  const linker_1 = require("../internal/linker");
17
18
  const dfg_get_symbol_refs_1 = require("../origin/dfg-get-symbol-refs");
19
+ const built_in_library_1 = require("../internal/process/functions/call/built-in/built-in-library");
20
+ const environment_1 = require("../environments/environment");
21
+ const attached_packages_1 = require("../../project/attached-packages");
18
22
  /**
19
23
  * This is the root helper object to work with the {@link DataflowGraph}.
20
24
  *
@@ -25,6 +29,7 @@ const dfg_get_symbol_refs_1 = require("../origin/dfg-get-symbol-refs");
25
29
  * - {@link Dataflow.calleesOf}/{@link Dataflow.calleeIdsOf}/{@link Dataflow.callTargetsOf}/{@link Dataflow.callsIn} - for what a call calls and what a definition calls,
26
30
  * - {@link Dataflow.packagesOf} - for the packages a set of nodes (e.g. a slice) calls into,
27
31
  * - {@link Dataflow.valueIsUsed}/{@link Dataflow.hasComputedArguments} - for what a call does with, and gets as, values,
32
+ * - {@link Dataflow.library} - for what `library(pkg)` attaches, loads, and puts on the search path, without analyzing any code,
28
33
  *
29
34
  * What it used to re-expose under a second name is imported directly instead: {@link DfEdge} for the edges,
30
35
  * {@link CallGraph} for the call-graph view, {@link Resolve} for name and value resolution, and
@@ -394,6 +399,28 @@ exports.Dataflow = {
394
399
  */
395
400
  provenanceGraph(id, graph, consider) {
396
401
  return exports.Dataflow.reduceGraph(graph, exports.Dataflow.provenance(id, graph, consider));
402
+ },
403
+ /**
404
+ * What `library(pkg)` does, asked without analyzing any code.
405
+ * @example
406
+ * ```ts
407
+ * const ctx = analyzer.context();
408
+ * Dataflow.library.attaches(ctx, 'tidyverse'); // the search() entries it adds
409
+ * Dataflow.library.loads(ctx, 'tidyverse'); // every namespace it loads
410
+ * Dataflow.library.layers(ctx, 'tidyverse'); // the namespace and imports environments themselves
411
+ * Dataflow.library.reexports(ctx, 'dplyr'); // the exports it takes from others, `%>%` from magrittr included
412
+ * ```
413
+ */
414
+ library: {
415
+ name: 'library',
416
+ /** The `search()` entries `library(pkg)` adds; see {@link libraryAttachesOf}. */
417
+ attaches: libraryAttachesOf,
418
+ /** The namespaces `library(pkg)` loads; see {@link libraryLoadsOf}. */
419
+ loads: libraryLoadsOf,
420
+ /** The environment layers `library(pkg)` adds to the search path; see {@link libraryLayersOf}. */
421
+ layers: libraryLayersOf,
422
+ /** The exports of `pkg` that re-export another package's function, with that package; see {@link libraryReexportsOf}. */
423
+ reexports: libraryReexportsOf
397
424
  }
398
425
  };
399
426
  /** both qualifications of a call from a single origin resolution, as the base-R step only adds to what the origins gave */
@@ -422,4 +449,60 @@ function aliasedBaseR(graph, id, origins) {
422
449
  const owner = names.size === 1 ? (0, r_base_packages_1.baseRExportOwner)(name) : undefined;
423
450
  return owner === undefined ? undefined : identifier_1.Identifier.make(name, owner);
424
451
  }
452
+ /**
453
+ * The layers `library(pkg)` puts on an empty search path, innermost first, built by the {@link attachLibrary} the
454
+ * analysis uses: per attached package its namespace (exports) and imports layer, or for an unresolved one what flowR
455
+ * states about it or a bare {@link EnvType.LoadedNamespace}. `layer.n` is the package, `layer.t` the type, `layer.memory` the bindings.
456
+ */
457
+ function libraryLayersOf(ctx, pkg, spec) {
458
+ return [...environment_1.REnvironment.searchPath((0, built_in_library_1.attachLibrary)(pkg, ctx.deps.getDependency(pkg), ctx.env.makeCleanEnv(), ctx, spec).current)];
459
+ }
460
+ /** The `search()` entries `library(pkg)` adds, in `search()` order: `pkg`, its `Depends` and a meta-package's core set, recursively. */
461
+ function libraryAttachesOf(ctx, pkg, spec) {
462
+ if (spec?.namespaceOnly) {
463
+ return []; // loading a namespace puts nothing on the search path
464
+ }
465
+ /* a package R attaches on startup is on the search path already, so a `Depends: methods` adds no entry */
466
+ return libraryLayersOf(ctx, pkg, spec).filter(l => l.t !== environment_1.EnvType.Imports && l.n !== undefined && !r_base_packages_1.AttachedBasePackageSet.has(l.n)).map(l => l.n);
467
+ }
468
+ /**
469
+ * The exports of `pkg` it re-exports from another package, mapped to that package (`%>%` of dplyr to `magrittr`).
470
+ * The analysis keeps such an export as one of `pkg` (`dplyr::%>%`), so both stay apart; this tells where it comes from.
471
+ */
472
+ function libraryReexportsOf(ctx, pkg) {
473
+ const ns = ctx.deps.getDependency(pkg)?.namespaceInfo;
474
+ const reexports = new Map();
475
+ if (ns === undefined) {
476
+ return reexports;
477
+ }
478
+ for (const fn of (0, flowr_namespace_file_1.getCallables)(ns)) {
479
+ const origin = (0, flowr_namespace_file_1.importOrigin)(fn, ns);
480
+ if (origin !== undefined) {
481
+ reexports.set(fn, origin);
482
+ }
483
+ }
484
+ return reexports;
485
+ }
486
+ /** The packages loading `pkg` loads directly: its `Depends` and `Imports`, its `NAMESPACE` imports, and a meta-package's core set. */
487
+ function directLoadsOf(ctx, pkg) {
488
+ const db = ctx.deps.signatures();
489
+ const dependency = ctx.deps.getDependency(pkg);
490
+ return [
491
+ ...(db.sources().dependencies(pkg, db.versionOf(pkg)) ?? [])
492
+ .filter(d => (d.type === 0 /* DepType.Depends */ || d.type === 1 /* DepType.Imports */) && d.name !== 'R').map(d => d.name),
493
+ ...dependency?.namespaceInfo?.importedPackages.keys() ?? [],
494
+ ...dependency?.dependencies?.map(d => d.name) ?? [],
495
+ ...(0, attached_packages_1.metaPackageCore)(pkg, db.versionOf(pkg))
496
+ ];
497
+ }
498
+ /** The namespaces `library(pkg)` loads, `pkg` first: the closure over {@link directLoadsOf} at the versions the analysis assumes. */
499
+ function libraryLoadsOf(ctx, pkg) {
500
+ const loaded = new Set([pkg]);
501
+ for (const p of loaded) {
502
+ for (const d of directLoadsOf(ctx, p)) {
503
+ loaded.add(d);
504
+ }
505
+ }
506
+ return [...loaded];
507
+ }
425
508
  //# sourceMappingURL=df-helper.js.map
@@ -52,6 +52,8 @@ export declare const ControlDependency: {
52
52
  readonly isIterated: (this: void, cd: ControlDependency, idMap: AstIdMap | undefined) => boolean;
53
53
  /** The dependencies of `a` that `b` is not subject to as well. */
54
54
  readonly minus: (this: void, a: readonly ControlDependency[], b: readonly ControlDependency[]) => ControlDependency[];
55
+ /** A string telling the dependencies apart (by condition and branch), empty for none. */
56
+ readonly key: (this: void, cds: readonly ControlDependency[] | undefined) => string;
55
57
  };
56
58
  /** Appends the given control dependencies to `target`, skipping the ones that are already in there. */
57
59
  export declare function appendCds(target: ControlDependency[], toAdd: readonly ControlDependency[] | undefined): void;
package/dataflow/info.js CHANGED
@@ -44,6 +44,10 @@ exports.ControlDependency = {
44
44
  /** The dependencies of `a` that `b` is not subject to as well. */
45
45
  minus(a, b) {
46
46
  return a.filter(cd => !b.some(other => sameControlDependency(other, cd)));
47
+ },
48
+ /** A string telling the dependencies apart (by condition and branch), empty for none. */
49
+ key(cds) {
50
+ return cds?.map(cd => `${String(cd.id)}:${String(cd.when)}`).join(',') ?? '';
47
51
  }
48
52
  };
49
53
  /** Appends the given control dependencies to `target`, skipping the ones that are already in there. */
@@ -40,6 +40,7 @@ const r_function_definition_1 = require("../../r-bridge/lang-4.x/ast/model/nodes
40
40
  const r_binary_op_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op");
41
41
  const r_symbol_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
42
42
  const df_helper_1 = require("../graph/df-helper");
43
+ const ambient_state_name_1 = require("../environments/ambient-state-name");
43
44
  const ValueFlowBits = edge_1.EdgeType.Reads | edge_1.EdgeType.DefinedBy | edge_1.EdgeType.DefinedByOnCall;
44
45
  const FCallLinkReadBits = edge_1.EdgeType.Reads | edge_1.EdgeType.Calls | edge_1.EdgeType.DefinedByOnCall;
45
46
  /**
@@ -97,6 +98,18 @@ function environmentsOfCallee(info, environment) {
97
98
  }
98
99
  return (resolve_helper_1.Resolve.byName(info.name, environment) ?? []).filter(identifier_1.hasEnvState).map(d => d.envState);
99
100
  }
101
+ /**
102
+ * The frames of `environment` a function whose body runs at `bodyLevel` can see: the frame it was defined in and
103
+ * those around it, never the frames of the functions calling it.
104
+ */
105
+ function definitionFramesOf(bodyLevel, environment) {
106
+ const level = Math.max(0, Math.min(bodyLevel - 1, environment.level));
107
+ let current = environment.current;
108
+ for (let skip = environment.level - level; skip > 0 && current.parent !== undefined; skip--) {
109
+ current = current.parent;
110
+ }
111
+ return { current, level };
112
+ }
100
113
  /**
101
114
  * Links a function call with a single target function definition.
102
115
  */
@@ -105,17 +118,19 @@ function linkFunctionCallWithSingleTarget(graph, { subflow: fnSubflow, exitPoint
105
118
  const environment = info.environment;
106
119
  if (environment !== undefined) {
107
120
  let callee;
121
+ let lexical;
108
122
  /* for each open ingoing reference, try to resolve it here, and if so, add a read edge from the call to signal that it reads it */
109
123
  for (const ingoing of fnSubflow.in) {
110
124
  const name = ingoing.name;
111
125
  if (name === undefined) {
112
126
  continue;
113
127
  }
114
- callee ??= environmentsOfCallee(info, environment);
115
- const inCallee = callee.values().map(env => resolve_helper_1.Resolve.byNameAndType(name, env, ingoing.type)).find(assert_1.isNotUndefined);
116
- const defs = inCallee ?? resolve_helper_1.Resolve.byNameAndType(name, environment, ingoing.type) ?? [];
128
+ /* a variable is looked up where the function was defined, global state (options, files, the working directory) is what it is where it is called */
129
+ const inCallee = ambient_state_name_1.AmbientStateName.is(name) ? undefined : (callee ??= environmentsOfCallee(info, environment)).values().map(env => resolve_helper_1.Resolve.byNameAndType(name, env, ingoing.type)).find(assert_1.isNotUndefined);
130
+ const defs = inCallee ?? resolve_helper_1.Resolve.byNameAndType(name, ambient_state_name_1.AmbientStateName.is(name) ? environment : lexical ??= definitionFramesOf(fnSubflow.environment.level, environment), ingoing.type) ?? [];
117
131
  for (const { nodeId, type, value, definedAt, envState } of defs) {
118
- if (fnSubflow.graph.has(nodeId) || node_id_1.NodeId.isBuiltIn(nodeId)) {
132
+ /* the state an earlier run of the function left behind is what its next run reads */
133
+ if (fnSubflow.graph.has(nodeId) && !ambient_state_name_1.AmbientStateName.is(name) || node_id_1.NodeId.isBuiltIn(nodeId)) {
119
134
  continue;
120
135
  }
121
136
  graph.addEdge(ingoing.nodeId, nodeId, edge_1.EdgeType.DefinedByOnCall);
@@ -411,7 +426,8 @@ function linkInputs(referencesToLinkAgainstEnvironment, environmentInformation,
411
426
  graph.addEdge(alsoFrom, target.nodeId, edge_1.EdgeType.Reads);
412
427
  }
413
428
  }
414
- if (probableTarget.every(t => (0, identifier_1.isReferenceType)(t.type, identifier_1.ReferenceType.BuiltInConstant | identifier_1.ReferenceType.BuiltInFunction))) {
429
+ /* the state of the session (options, files, the working directory) may change before the next time the code runs, so it stays open */
430
+ if (probableTarget.every(t => (0, identifier_1.isReferenceType)(t.type, identifier_1.ReferenceType.BuiltInConstant | identifier_1.ReferenceType.BuiltInFunction)) || ambient_state_name_1.AmbientStateName.is(bodyInput.name)) {
415
431
  givenInputs.push(bodyInput);
416
432
  }
417
433
  }
@@ -14,6 +14,10 @@ export type AmbientKeys = {
14
14
  readonly from: 'argument-names';
15
15
  /** arguments to leave out, like `par(no.readonly = TRUE)` */
16
16
  readonly ignore?: readonly string[];
17
+ } | {
18
+ /** every unnamed argument names an entry, like `pacman::p_load(a, b)`; quoted ones are names themselves, others are looked up */
19
+ readonly from: 'unnamed';
20
+ readonly quoted: boolean;
17
21
  } | {
18
22
  /** the call always sets this entry, like `Sys.setLanguage` sets `LANGUAGE` */
19
23
  readonly from: 'constant';
@@ -78,6 +78,9 @@ function keysOf(keys, args, data) {
78
78
  });
79
79
  case 'parameter':
80
80
  return parameterKeys(keys, args, data);
81
+ case 'unnamed':
82
+ return args.flatMap(a => a === r_function_call_1.EmptyArgument || a.name !== undefined || a.value === undefined ? []
83
+ : (keys.quoted ? quotedName(a.value) : undefined) ?? stringValuesOf(a.value, data) ?? [ambient_state_name_1.UnknownKey]);
81
84
  }
82
85
  }
83
86
  /** The pseudo variables a write to the given entries of `state` defines: the entries and what every write to the state adds to. No entry has an empty name. */
@@ -74,8 +74,11 @@ export declare const enum AmbientStateAccessType {
74
74
  RunFinalizers = "run-finalizers",
75
75
  /** sets entries of a keyed state, like `Sys.setenv(A = "1")` sets the environment variable `A`, see {@link AmbientKeys} */
76
76
  SetKeyed = "set-keyed",
77
+ ReadKeyed = "read-keyed",
77
78
  /** sets a state without entries, like `sink(file)` diverts the output */
78
- SetState = "set-state"
79
+ SetState = "set-state",
80
+ /** reads a state without entries, like `search()` reads the search path */
81
+ ReadState = "read-state"
79
82
  }
80
83
  /** An {@link AmbientStateAccessType} together with what refines it for some of the types. */
81
84
  export type AmbientStateAccess = {
@@ -105,6 +108,14 @@ export type AmbientStateAccess = {
105
108
  readonly type: AmbientStateAccessType.SetKeyed;
106
109
  readonly state: KeyedState;
107
110
  readonly keys: AmbientKeys;
111
+ } | {
112
+ readonly type: AmbientStateAccessType.ReadState;
113
+ readonly state: string;
114
+ } | {
115
+ /** reads the entries the call names, like `Sys.getenv("HOME")`, all of them if it names none */
116
+ readonly type: AmbientStateAccessType.ReadKeyed;
117
+ readonly state: KeyedState;
118
+ readonly keys: AmbientKeys;
108
119
  } | {
109
120
  readonly type: AmbientStateAccessType.SetState;
110
121
  /** the pseudo variable the call sets, like {@link AmbientStateName.sink} */
@@ -127,6 +138,8 @@ declare const UnknownArguments: unique symbol;
127
138
  type UnknownArguments = typeof UnknownArguments;
128
139
  /** A call to `fn` made on our behalf (`do.call(fn, args)`, `sapply(x, fn)`): it accesses the state as `fn` does, or reads all of it if `fn` is opaque. */
129
140
  export declare function applyAmbientStateOfCallee<OtherInfo>(res: DataflowInformation, callId: NodeId, fn: Identifier, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): DataflowInformation;
141
+ /** Marks the call `callId` to the built-ins `targets` through a parameter or a variable as the unknown side effect they have, see {@link WritesEnvironment}. */
142
+ export declare function hiddenSideEffects(graph: DataflowGraph, environment: REnvironmentInformation, callId: NodeId, targets: readonly IdentifierDefinition[]): void;
130
143
  /** The (maybe) writes of the call `callId` to the built-in `target` through a parameter, like `g <- function(f, ...) f(...); g(options, digits = 3)`. */
131
144
  export declare function writesOfHiddenBuiltIn(target: IdentifierDefinition, callId: NodeId): (InGraphIdentifierDefinition & {
132
145
  name: string;
@@ -142,13 +155,16 @@ export declare function callOnlyQueries<OtherInfo>(fn: Identifier, args: readonl
142
155
  export declare function linkAmbientStateWithinLoop(graph: DataflowGraph, reads: readonly IdentifierReference[], body: DataflowInformation): IdentifierReference[];
143
156
  /** A scoped state change (`withr`, `rlang`): `with_*` undoes it after its code, `local_*` when the calling function returns. */
144
157
  export interface AmbientScope {
145
- readonly state: 'options' | 'graphics' | 'device' | 'rng';
158
+ /** the state the scope changes; the keyed ones (`options`, environment variables, locale) take the entries the call names */
159
+ readonly state: 'options' | 'graphics' | 'device' | 'rng' | 'wd' | KeyedState.Env | KeyedState.Locale;
146
160
  /** the formals in order, used to bind the arguments */
147
161
  readonly params: readonly string[];
148
162
  /** the formal evaluated with the change in effect, absent for the `local_*` variants */
149
163
  readonly code?: string;
150
164
  /** the formal holding a list of the new values (`list(digits = 3)`), other named arguments are values too */
151
165
  readonly new?: string;
166
+ /** the scope changes nothing, it only restores the state afterward (`with_preserve_seed`) */
167
+ readonly preserve?: boolean;
152
168
  }
153
169
  /** The processor for an {@link AmbientScope}. */
154
170
  export declare function processAmbientScope<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, scope: AmbientScope): DataflowInformation;
@@ -12,6 +12,7 @@ exports.mayForce = mayForce;
12
12
  exports.ambientAccessOfSymbol = ambientAccessOfSymbol;
13
13
  exports.applyAmbientStateAccess = applyAmbientStateAccess;
14
14
  exports.applyAmbientStateOfCallee = applyAmbientStateOfCallee;
15
+ exports.hiddenSideEffects = hiddenSideEffects;
15
16
  exports.writesOfHiddenBuiltIn = writesOfHiddenBuiltIn;
16
17
  exports.readsOfHiddenBuiltIn = readsOfHiddenBuiltIn;
17
18
  exports.callOnlyQueries = callOnlyQueries;
@@ -49,6 +50,7 @@ const assert_1 = require("../../../../../../util/assert");
49
50
  const resolve_helper_1 = require("../../../../../environments/resolve-helper");
50
51
  const r_access_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-access");
51
52
  const r_symbol_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
53
+ const r_if_then_else_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-if-then-else");
52
54
  const arrays_1 = require("../../../../../../util/collections/arrays");
53
55
  const ambient_state_name_1 = require("../../../../../environments/ambient-state-name");
54
56
  const built_in_ambient_keys_1 = require("./built-in-ambient-keys");
@@ -72,7 +74,7 @@ function hidesBody(definition) {
72
74
  }
73
75
  /** A call into code flowR cannot see may read any option, draw random numbers (with `draws` advancing the generator), and with `graphics` draw on the device. */
74
76
  function readsAllAmbientState(res, rootId, data, graphics, draws = true) {
75
- const reads = [ambient_state_name_1.AmbientStateName.allOptions, ambient_state_name_1.AmbientStateName.rng];
77
+ const reads = [ambient_state_name_1.AmbientStateName.allOptions, ambient_state_name_1.AmbientStateName.rng, ambient_state_name_1.AmbientStateName.allOf(ambient_state_name_1.KeyedState.Env)];
76
78
  if (graphics) {
77
79
  reads.push(ambient_state_name_1.AmbientStateName.graphics, ambient_state_name_1.AmbientStateName.palette);
78
80
  }
@@ -108,8 +110,9 @@ function defineAmbient(environment, rootId, cds, writes) {
108
110
  definedAt: rootId,
109
111
  cds: isMaybe ? cds ?? [] : cds
110
112
  };
111
- /* the state is global, wherever the call happens, unless the call scopes it to the current frame */
112
- environment = environment_1.REnvironment.define(def, mode !== 'local', environment, keep);
113
+ /* the state is global, wherever the call happens, unless the call or an earlier one (`local_seed`) scopes it to the current frame */
114
+ const local = mode === 'local' || (environment.level > 0 && environment.current.memory.has(name));
115
+ environment = environment_1.REnvironment.define(def, !local, environment, keep);
113
116
  }
114
117
  return environment;
115
118
  }
@@ -220,6 +223,12 @@ const GlobalEffectOptions = new Set([
220
223
  'warnPartialMatchDollar', 'keep.source', 'keep.parse.data', 'check.bounds', 'CBoundsCheck', 'catch.script.errors',
221
224
  'defaultPackages', 'topLevelEnvironment', 'java.parameters'
222
225
  ]);
226
+ /** Environment variables R or a child process reads by itself: the time zone, locale, library paths, temp dir, search path, proxies. */
227
+ const GlobalEffectEnv = /^(TZ|LANG|LANGUAGE|LC_\w+|R_\w+|TMPDIR|TEMP|TMP|HOME|PATH|SHELL|\w*_proxy|\w*_PROXY|no_proxy|NO_PROXY)$/;
228
+ /** What reading the given entries of `state` reads: each entry and the writes we cannot name, all of the state if no entry is known. */
229
+ function keyedReads(state, keys) {
230
+ return keys.length === 0 || keys.includes(ambient_state_name_1.UnknownKey) ? [ambient_state_name_1.AmbientStateName.allOf(state)] : [...keys.map(k => ambient_state_name_1.AmbientStateName.keyed(state, k)), ambient_state_name_1.AmbientStateName.keyed(state, ambient_state_name_1.UnknownKey)];
231
+ }
223
232
  /** Options that affect how values are printed and formatted (read by `print`, `format`, and `cat`). */
224
233
  exports.PrintingOptions = ['digits', 'width', 'max.print', 'digits.secs', 'useFancyQuotes'];
225
234
  /** Wires the {@link AmbientStateAccess} of a call into its dataflow information: reads become unknown references, writes define the pseudo variable globally. */
@@ -266,14 +275,26 @@ function applyAmbientStateAccess(res, args, rootId, data, access) {
266
275
  }
267
276
  case "set-options" /* AmbientStateAccessType.SetOptions */:
268
277
  return setOptions(res, args, rootId, data);
269
- case "set-keyed" /* AmbientStateAccessType.SetKeyed */:
270
- writes.push(...(0, built_in_ambient_keys_1.keyedWrites)(access.state, (0, built_in_ambient_keys_1.keysOf)(access.keys, args, data)));
278
+ case "set-keyed" /* AmbientStateAccessType.SetKeyed */: {
279
+ const keys = (0, built_in_ambient_keys_1.keysOf)(access.keys, args, data);
280
+ /* a variable R or a child process reads by itself is read by calls we cannot name */
281
+ if (access.state === ambient_state_name_1.KeyedState.Env && keys.some(k => k === ambient_state_name_1.UnknownKey || GlobalEffectEnv.test(k))) {
282
+ res.graph.markIdForUnknownSideEffects(rootId);
283
+ }
284
+ writes.push(...(0, built_in_ambient_keys_1.keyedWrites)(access.state, keys));
285
+ break;
286
+ }
287
+ case "read-keyed" /* AmbientStateAccessType.ReadKeyed */:
288
+ reads.push(...keyedReads(access.state, (0, built_in_ambient_keys_1.keysOf)(access.keys, args, data)));
271
289
  break;
272
290
  case "set-state" /* AmbientStateAccessType.SetState */:
273
291
  if (!onlyQueries(access, args)) {
274
292
  writes.push(access.state);
275
293
  }
276
294
  break;
295
+ case "read-state" /* AmbientStateAccessType.ReadState */:
296
+ reads.push(access.state);
297
+ break;
277
298
  case "open-device" /* AmbientStateAccessType.OpenDevice */:
278
299
  return deviceAccess(res, rootId, data, 'open');
279
300
  case "close-device" /* AmbientStateAccessType.CloseDevice */:
@@ -289,8 +310,10 @@ function applyAmbientStateAccess(res, args, rootId, data, access) {
289
310
  if (kindFrom > 0) {
290
311
  writes.push(ambient_state_name_1.AmbientStateName.rng);
291
312
  }
313
+ /* a new kind reseeds the generator from its current state, so it changes the stream as well */
292
314
  if (args.some((a, i) => a !== r_function_call_1.EmptyArgument && (a.name === undefined ? i >= kindFrom : identifier_1.Identifier.getName(a.name.content) !== 'seed'))) {
293
- writes.push(ambient_state_name_1.AmbientStateName.rngKind);
315
+ reads.push(ambient_state_name_1.AmbientStateName.rng);
316
+ writes.push(ambient_state_name_1.AmbientStateName.rngKind, ambient_state_name_1.AmbientStateName.rng);
294
317
  }
295
318
  break;
296
319
  }
@@ -301,6 +324,10 @@ function applyAmbientStateAccess(res, args, rootId, data, access) {
301
324
  case "read-files" /* AmbientStateAccessType.ReadFiles */: {
302
325
  const stems = fileStems(res, rootId, data, access);
303
326
  reads.push(ambient_state_name_1.AmbientStateName.workingDirectory, ...stems === undefined ? [ambient_state_name_1.AmbientStateName.files] : [...stems.map(ambient_state_name_1.AmbientStateName.file), ambient_state_name_1.AmbientStateName.anyFile]);
327
+ /* a read through a connection the program holds moves its position, so the next read depends on this one */
328
+ if (readsThroughHandle(res, rootId, data, access.sig)) {
329
+ writes.push(...stems === undefined ? [ambient_state_name_1.AmbientStateName.anyFile, ambient_state_name_1.AmbientStateName.files] : stems.map(ambient_state_name_1.AmbientStateName.file));
330
+ }
304
331
  break;
305
332
  }
306
333
  case "write-files" /* AmbientStateAccessType.WriteFiles */: {
@@ -369,6 +396,30 @@ function openTextConnection(res, args, rootId, data) {
369
396
  markForcing(environment);
370
397
  return withAccess({ ...res, environment }, rootId, data, [], names.map(ambient_state_name_1.AmbientStateName.textConnection));
371
398
  }
399
+ /** Whether one of the resources the call reads is a variable bound to a connection, like `con` in `con <- file(f); readLines(con)`. */
400
+ function readsThroughHandle(res, rootId, data, sig) {
401
+ const call = res.graph.getVertex(rootId);
402
+ if (sig === undefined || !vertex_1.DfgVertex.isFunctionCall(call)) {
403
+ return false;
404
+ }
405
+ return match_args_1.MatchArgs.findWithProps((0, applied_arguments_1.appliedArguments)(res.graph, call, data.completeAst.idMap).args, sig, built_in_props_1.ArgProp.Resource)
406
+ .some(id => boundValues(id, data, false).some(v => callsTagged(v, data, built_in_props_1.SemanticCallTag.Opens)));
407
+ }
408
+ /** What the argument `id` holds: its value, or with `direct` unset only what the variable it names is bound to. */
409
+ function boundValues(id, data, direct = true) {
410
+ const arg = data.completeAst.idMap.get(id);
411
+ const node = r_argument_1.RArgument.is(arg) ? r_argument_1.RArgument.valueOf(arg) : arg;
412
+ if (!r_symbol_1.RSymbol.is(node)) {
413
+ return direct && node !== undefined ? [node] : [];
414
+ }
415
+ return (resolve_helper_1.Resolve.byName(node.content, data.environment) ?? []).flatMap(d => d.value ?? [])
416
+ .map(v => data.completeAst.idMap.get(v)).filter(assert_1.isNotUndefined);
417
+ }
418
+ /** Whether `node` calls a function flowR states `tag` of, like {@link SemanticCallTag.Opens} for `file(f)`. */
419
+ function callsTagged(node, data, tag) {
420
+ return r_function_call_1.RFunctionCall.isNamed(node) && (resolve_helper_1.Resolve.byNameAndType(node.functionName.content, data.environment, identifier_1.ReferenceType.Function) ?? [])
421
+ .some(d => d.type === identifier_1.ReferenceType.BuiltInFunction && d.config?.tags?.includes(tag) === true);
422
+ }
372
423
  /** The stems of the files the call names, `undefined` unless every file argument is a known path to a file with an extension (a device's `plot%03d.png` or a directory may stand for others). */
373
424
  function fileStems(res, rootId, data, { sig, numbered }) {
374
425
  const call = res.graph.getVertex(rootId);
@@ -381,6 +432,12 @@ function fileStems(res, rootId, data, { sig, numbered }) {
381
432
  }
382
433
  const stems = [];
383
434
  for (const id of named) {
435
+ /* every `tempfile()` names a file no other call names */
436
+ const fresh = boundValues(id, data);
437
+ if (fresh.length > 0 && fresh.every(v => callsTagged(v, data, built_in_props_1.SemanticCallTag.TempFile))) {
438
+ stems.push(...fresh.map(v => `tmp-${v.info.id}`));
439
+ continue;
440
+ }
384
441
  const paths = node_value_1.NodeValue.stringsOf(id, data);
385
442
  for (const path of paths?.length ? paths : ['']) {
386
443
  const [stem, ...extension] = path.split(/[/\\]/).at(-1)?.split('.') ?? [];
@@ -426,7 +483,8 @@ function applyWithUnknownArguments(res, rootId, data, access) {
426
483
  return withAccess(res, rootId, data, reads, writes);
427
484
  }
428
485
  const Devices = { reads: [], writes: [ambient_state_name_1.AmbientStateName.graphics, ambient_state_name_1.AmbientStateName.device] };
429
- const Quoted = { reads: [ambient_state_name_1.AmbientStateName.allOptions, ambient_state_name_1.AmbientStateName.graphics, ambient_state_name_1.AmbientStateName.palette], writes: [ambient_state_name_1.AmbientStateName.unknownOption, ambient_state_name_1.AmbientStateName.allOptions, ambient_state_name_1.AmbientStateName.graphics, ambient_state_name_1.AmbientStateName.palette] };
486
+ /* evaluated code may attach a package as well, which every call nothing else resolves reads */
487
+ const Quoted = { reads: [ambient_state_name_1.AmbientStateName.allOptions, ambient_state_name_1.AmbientStateName.graphics, ambient_state_name_1.AmbientStateName.palette], writes: [ambient_state_name_1.AmbientStateName.unknownOption, ambient_state_name_1.AmbientStateName.allOptions, ambient_state_name_1.AmbientStateName.graphics, ambient_state_name_1.AmbientStateName.palette, ambient_state_name_1.AmbientStateName.allOf(ambient_state_name_1.KeyedState.SearchPath)] };
430
488
  /** What a call of the given kind may read and write when its arguments are unknown, as when only linking reveals it. */
431
489
  const UnknownArgumentAccess = {
432
490
  ["set-options" /* AmbientStateAccessType.SetOptions */]: { reads: [ambient_state_name_1.AmbientStateName.allOptions], writes: [ambient_state_name_1.AmbientStateName.unknownOption, ambient_state_name_1.AmbientStateName.allOptions, ambient_state_name_1.AmbientStateName.warnsAsErrors] },
@@ -454,8 +512,12 @@ function unknownArgumentAccess(access) {
454
512
  return { reads: optionReads(access.dispatchOn === undefined ? access.keys : undefined), writes: [] };
455
513
  case "set-keyed" /* AmbientStateAccessType.SetKeyed */:
456
514
  return { reads: [], writes: (0, built_in_ambient_keys_1.keyedWrites)(access.state, [ambient_state_name_1.UnknownKey]) };
515
+ case "read-keyed" /* AmbientStateAccessType.ReadKeyed */:
516
+ return { reads: [ambient_state_name_1.AmbientStateName.allOf(access.state)], writes: [] };
457
517
  case "set-state" /* AmbientStateAccessType.SetState */:
458
518
  return { reads: [], writes: [access.state] };
519
+ case "read-state" /* AmbientStateAccessType.ReadState */:
520
+ return { reads: [access.state], writes: [] };
459
521
  default:
460
522
  return UnknownArgumentAccess[access.type];
461
523
  }
@@ -493,17 +555,20 @@ function deviceAccess(res, rootId, data, kind) {
493
555
  res.graph.addEdge(open.nodeId, rootId, edge_1.EdgeType.Reads);
494
556
  }
495
557
  };
558
+ /* in a loop, an earlier round may have opened a device this one leaves behind, or a close may leave one open */
559
+ const repeats = model_1.RLoopConstructs.encloses(rootId, data.completeAst.idMap);
560
+ const earlierRound = repeats ? [{ nodeId: rootId, name: ambient_state_name_1.AmbientStateName.device, type: identifier_1.ReferenceType.Variable, definedAt: rootId, cds: cds ?? [] }] : [];
496
561
  switch (kind) {
497
562
  case 'open':
498
- environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.otherDevices, [...others, ...current]);
499
- environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.otherDevicesOpenedBy, [...otherOpeners, ...opener]);
563
+ environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.otherDevices, [...others, ...current, ...earlierRound]);
564
+ environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.otherDevicesOpenedBy, [...otherOpeners, ...opener, ...earlierRound]);
500
565
  environment = reset(ambient_state_name_1.AmbientStateName.graphics);
501
566
  environment = reset(ambient_state_name_1.AmbientStateName.device);
502
567
  break;
503
568
  case 'close':
504
569
  closes(opener);
505
- environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.graphics, others);
506
- environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.device, otherOpeners);
570
+ environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.graphics, repeats ? [...others, ...current] : others);
571
+ environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.device, repeats ? [...otherOpeners, ...opener] : otherOpeners);
507
572
  break;
508
573
  case 'close-all':
509
574
  closes([...opener, ...otherOpeners]);
@@ -512,7 +577,7 @@ function deviceAccess(res, rootId, data, kind) {
512
577
  }
513
578
  break;
514
579
  case 'switch':
515
- environment = defineAmbient(environment, rootId, cds, [ambient_state_name_1.AmbientStateName.graphics]);
580
+ environment = defineAmbient(environment, rootId, cds, [ambient_state_name_1.AmbientStateName.graphics, ambient_state_name_1.AmbientStateName.device]);
516
581
  environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.graphics, others, true);
517
582
  environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.otherDevices, current, true);
518
583
  environment = setAmbient(environment, ambient_state_name_1.AmbientStateName.device, otherOpeners, true);
@@ -526,9 +591,35 @@ function deviceAccess(res, rootId, data, kind) {
526
591
  function applyAmbientStateOfCallee(res, callId, fn, data) {
527
592
  const targets = resolve_helper_1.Resolve.byNameAndType(fn, data.environment, identifier_1.ReferenceType.Function) ?? [];
528
593
  res = applyAmbientStateAccess(res, UnknownArguments, callId, data, targets.flatMap(hiddenAccess));
594
+ hiddenSideEffects(res.graph, res.environment, callId, targets);
529
595
  const unknown = (targets.length === 0 && data.environment.level === 0) || targets.some(t => t.type !== identifier_1.ReferenceType.BuiltInFunction && hidesBody(t));
530
596
  return unknown ? readsAllAmbientState(res, callId, data, true) : res;
531
597
  }
598
+ /**
599
+ * The processors that write the environment from their arguments (define, remove, evaluate code): called through a
600
+ * parameter, `do.call`, or an apply function, what they write is unknown, so the values known so far may be stale.
601
+ */
602
+ const WritesEnvironment = new Set([
603
+ built_in_proc_name_1.BuiltInProcName.Source, built_in_proc_name_1.BuiltInProcName.Load, built_in_proc_name_1.BuiltInProcName.Rm, built_in_proc_name_1.BuiltInProcName.ListToEnv,
604
+ built_in_proc_name_1.BuiltInProcName.Assignment, built_in_proc_name_1.BuiltInProcName.AssignmentLike, built_in_proc_name_1.BuiltInProcName.SuperAssignment, built_in_proc_name_1.BuiltInProcName.Eval, built_in_proc_name_1.BuiltInProcName.Local
605
+ ]);
606
+ /** The processors that change the search path: called that way, what names resolve to may change, but no value. */
607
+ const WritesSearchPath = new Set([built_in_proc_name_1.BuiltInProcName.Library, built_in_proc_name_1.BuiltInProcName.Attach, built_in_proc_name_1.BuiltInProcName.Detach]);
608
+ /** Marks the call `callId` to the built-ins `targets` through a parameter or a variable as the unknown side effect they have, see {@link WritesEnvironment}. */
609
+ function hiddenSideEffects(graph, environment, callId, targets) {
610
+ for (const target of targets) {
611
+ const builtIn = target.type === identifier_1.ReferenceType.BuiltInFunction ? target : undefined;
612
+ const processor = builtIn?.processorName;
613
+ const effect = builtIn?.config?.hasUnknownSideEffects
614
+ ?? (processor !== undefined && WritesEnvironment.has(processor));
615
+ if (effect) {
616
+ (0, unknown_side_effect_1.handleUnknownSideEffect)(graph, environment, callId, effect === true ? undefined : effect);
617
+ }
618
+ else if (processor !== undefined && WritesSearchPath.has(processor)) {
619
+ graph.markIdForUnknownSideEffects(callId);
620
+ }
621
+ }
622
+ }
532
623
  function hiddenAccess(target) {
533
624
  const access = target.type === identifier_1.ReferenceType.BuiltInFunction ? target.config?.ambient : undefined;
534
625
  return [access ?? []].flat();
@@ -621,11 +712,18 @@ function isQuery(args) {
621
712
  function resultIsUsed(rootId, data) {
622
713
  const node = data.completeAst.idMap.get(rootId);
623
714
  const parent = node === undefined ? undefined : model_1.RNode.directParent(node, data.completeAst.idMap);
624
- if (!r_expression_list_1.RExpressionList.is(parent)) {
625
- return parent !== undefined;
715
+ if (parent === undefined) {
716
+ return false;
717
+ }
718
+ else if (r_expression_list_1.RExpressionList.is(parent)) {
719
+ /* a block yields its last value, which is used where the block's is */
720
+ return parent.children.at(-1)?.info.id === rootId && !data.completeAst.ast.files.some(f => f.root.info.id === parent.info.id) && resultIsUsed(parent.info.id, data);
626
721
  }
627
- const isLast = parent.children.at(-1)?.info.id === rootId;
628
- return isLast && !data.completeAst.ast.files.some(f => f.root.info.id === parent.info.id);
722
+ else if (r_if_then_else_1.RIfThenElse.is(parent)) {
723
+ return parent.condition.info.id === rootId || resultIsUsed(parent.info.id, data);
724
+ }
725
+ /* a loop discards what its body yields */
726
+ return !(model_1.RLoopConstructs.is(parent) && parent.body.info.id === rootId);
629
727
  }
630
728
  /** Links state reads in a loop body to the body's own writes of a later iteration and returns them, as the first iteration reads what is there before the loop. */
631
729
  function linkAmbientStateWithinLoop(graph, reads, body) {
@@ -645,7 +743,7 @@ function processAmbientScope(name, args, rootId, data, scope) {
645
743
  const code = scope.code === undefined ? undefined : bound.get(scope.code);
646
744
  const codeIndex = code === undefined ? -1 : args.findIndex(a => a !== r_function_call_1.EmptyArgument && a.info.id === code.info.id);
647
745
  const local = code === undefined && data.environment.level > 0;
648
- const { writes, unknown } = scopedWrites(scope, args, bound, local);
746
+ const { writes, unknown } = scope.preserve ? { writes: local ? [{ name: singleStateOf(scope.state), mode: 'local' }] : [], unknown: false } : scopedWrites(scope, args, bound, local);
649
747
  const cds = data.cds ? [...data.cds] : undefined;
650
748
  const apply = (environment) => scope.state === 'device' ? deviceAccess({ ...info_1.DataflowInformation.initialize(rootId, data), environment }, rootId, data, local ? 'switch' : 'open').environment
651
749
  : defineAmbient(environment, rootId, cds, writes);
@@ -657,17 +755,20 @@ function processAmbientScope(name, args, rootId, data, scope) {
657
755
  information.graph.markIdForUnknownSideEffects(rootId);
658
756
  }
659
757
  if (code === undefined) {
660
- return { ...information, environment: apply(information.environment) };
758
+ const applied = { ...information, environment: apply(information.environment) };
759
+ /* the frame starts out with the state as it was */
760
+ return scope.preserve && local ? withAccess(applied, rootId, data, [singleStateOf(scope.state)]) : applied;
661
761
  }
662
762
  /* afterward, what the scope changed is back to what it was before */
663
763
  let environment = information.environment;
764
+ const keyed = keyedStateOf(scope);
664
765
  const restored = scope.state === 'device' ? DeviceStates
665
- : scope.state === 'rng' ? [ambient_state_name_1.AmbientStateName.rng]
666
- : writes.map(w => typeof w === 'string' ? w : w.name).filter(n => n.startsWith('#option:') && n !== ambient_state_name_1.AmbientStateName.unknownOption);
766
+ : scope.state === 'rng' || scope.state === 'wd' ? [singleStateOf(scope.state)]
767
+ : writes.map(w => typeof w === 'string' ? w : w.name).filter(n => keyed !== undefined && n.startsWith(ambient_state_name_1.AmbientStateName.keyed(keyed, '')) && n !== ambient_state_name_1.AmbientStateName.keyed(keyed, ambient_state_name_1.UnknownKey));
667
768
  for (const state of restored) {
668
769
  const before = resolve_helper_1.Resolve.byName(state, data.environment);
669
- /* an option nothing set before keeps the scope's definition, we cannot tell R's default apart */
670
- if ((before !== undefined && before.length > 0) || ((scope.state === 'device' || scope.state === 'rng') && data.environment.level === 0)) {
770
+ /* an entry nothing set before keeps the scope's definition, we cannot tell R's default apart */
771
+ if ((before !== undefined && before.length > 0) || ((scope.state === 'device' || scope.state === 'rng' || scope.state === 'wd') && data.environment.level === 0)) {
671
772
  environment = setAmbient(environment, state, before ?? []);
672
773
  }
673
774
  }
@@ -678,10 +779,21 @@ function processAmbientScope(name, args, rootId, data, scope) {
678
779
  }
679
780
  return { ...information, environment };
680
781
  }
681
- /** what a scope call writes: the options it names, or the graphics state */
782
+ /** The keyed state an {@link AmbientScope} changes the entries of, `undefined` for a state without entries. */
783
+ function keyedStateOf(scope) {
784
+ return scope.state === 'options' ? ambient_state_name_1.KeyedState.Option : scope.state === ambient_state_name_1.KeyedState.Env || scope.state === ambient_state_name_1.KeyedState.Locale ? scope.state : undefined;
785
+ }
786
+ /** The pseudo variable of a scoped state without entries. */
787
+ function singleStateOf(state) {
788
+ return state === 'rng' ? ambient_state_name_1.AmbientStateName.rng : state === 'wd' ? ambient_state_name_1.AmbientStateName.workingDirectory : ambient_state_name_1.AmbientStateName.graphics;
789
+ }
790
+ /** what a scope call writes: the entries of a keyed state it names, or the state it changes as a whole */
682
791
  function scopedWrites(scope, args, bound, local) {
683
- if (scope.state !== 'options') {
684
- return { writes: [scope.state === 'rng' ? ambient_state_name_1.AmbientStateName.rng : ambient_state_name_1.AmbientStateName.graphics], unknown: false };
792
+ const keyed = keyedStateOf(scope);
793
+ if (keyed === undefined) {
794
+ const name = singleStateOf(scope.state);
795
+ /* only the directory is restored as a whole (withr's `local_seed` leaves the generator where the function's draws took it) */
796
+ return { writes: [local && scope.state === 'wd' ? { name, mode: 'local' } : name], unknown: false };
685
797
  }
686
798
  const keys = [];
687
799
  let unknown = false;
@@ -720,13 +832,14 @@ function scopedWrites(scope, args, bound, local) {
720
832
  }
721
833
  }
722
834
  /* we do not resolve the value a scope sets, so setting `warn` may turn warnings into errors */
723
- const names = keys.map(ambient_state_name_1.AmbientStateName.option).concat(keys.includes('warn') ? [ambient_state_name_1.AmbientStateName.warnsAsErrors] : []);
724
- const writes = names.map(name => local ? { name, mode: 'local' } : name);
835
+ const options = keyed === ambient_state_name_1.KeyedState.Option;
836
+ const names = keys.map(k => ambient_state_name_1.AmbientStateName.keyed(keyed, k)).concat(options && keys.includes('warn') ? [ambient_state_name_1.AmbientStateName.warnsAsErrors] : []);
725
837
  if (unknown) {
726
- writes.push(local ? { name: ambient_state_name_1.AmbientStateName.unknownOption, mode: 'local' } : ambient_state_name_1.AmbientStateName.unknownOption);
838
+ names.push(ambient_state_name_1.AmbientStateName.keyed(keyed, ambient_state_name_1.UnknownKey));
727
839
  }
728
- writes.push(local ? { name: ambient_state_name_1.AmbientStateName.allOptions, mode: 'local' } : ambient_state_name_1.AmbientStateName.allOptions);
729
- return { writes, unknown: unknown || keys.some(k => GlobalEffectOptions.has(k)) };
840
+ names.push(ambient_state_name_1.AmbientStateName.allOf(keyed));
841
+ const writes = names.map(name => local ? { name, mode: 'local' } : name);
842
+ return { writes, unknown: unknown || (options && keys.some(k => GlobalEffectOptions.has(k))) };
730
843
  }
731
844
  /** Evaluating captured code may access any state; `Quoted.finalize` drops the writes again once the code is known to change none. */
732
845
  function evaluatesCapturedCode(res, rootId, data) {
@@ -768,6 +881,7 @@ function applyAmbientStateOfCalledBuiltIns(res, callId, builtIns, before, graph,
768
881
  for (const builtIn of builtIns) {
769
882
  const targets = node_id_1.NodeId.isBuiltIn(builtIn) ? resolve_helper_1.Resolve.byNameAndType(node_id_1.NodeId.fromBuiltIn(builtIn), before, identifier_1.ReferenceType.Function) ?? [] : [];
770
883
  res = applyAmbientStateAccess(res, call.arguments, callId, data, targets.flatMap(hiddenAccess));
884
+ hiddenSideEffects(graph, before, callId, targets);
771
885
  }
772
886
  for (const read of res.unknownReferences.slice(known)) {
773
887
  for (const def of resolve_helper_1.Resolve.byName(read.name, before) ?? []) {