@eagleoutice/flowr 2.17.0 → 2.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +8 -8
  2. package/config.d.ts +32 -0
  3. package/config.js +22 -2
  4. package/control-flow/semantic-cfg-guided-visitor.js +2 -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 +18 -2
  10. package/dataflow/environments/built-in-props.js +26 -4
  11. package/dataflow/environments/built-in.d.ts +16 -6
  12. package/dataflow/environments/built-in.js +58 -7
  13. package/dataflow/environments/default-builtin-config.d.ts +1245 -159
  14. package/dataflow/environments/default-builtin-config.js +191 -38
  15. package/dataflow/environments/environment.d.ts +19 -2
  16. package/dataflow/environments/environment.js +90 -19
  17. package/dataflow/environments/identifier.d.ts +25 -1
  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 +68 -17
  24. package/dataflow/fn/function-semantics.d.ts +1 -0
  25. package/dataflow/graph/df-helper.d.ts +34 -1
  26. package/dataflow/graph/df-helper.js +60 -0
  27. package/dataflow/info.d.ts +2 -0
  28. package/dataflow/info.js +4 -0
  29. package/dataflow/internal/linker.js +21 -5
  30. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-keys.d.ts +4 -0
  31. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-keys.js +3 -0
  32. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +18 -2
  33. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +144 -30
  34. package/dataflow/internal/process/functions/call/built-in/built-in-apply.d.ts +1 -1
  35. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +2 -1
  36. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +1 -1
  37. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +10 -0
  38. package/dataflow/internal/process/functions/call/built-in/built-in-attach.d.ts +8 -4
  39. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +43 -8
  40. package/dataflow/internal/process/functions/call/built-in/built-in-env-contents.d.ts +1 -1
  41. package/dataflow/internal/process/functions/call/built-in/built-in-env-contents.js +5 -4
  42. package/dataflow/internal/process/functions/call/built-in/built-in-eval.js +67 -3
  43. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +4 -2
  44. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +27 -3
  45. package/dataflow/internal/process/functions/call/built-in/built-in-get.d.ts +1 -1
  46. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +2 -14
  47. package/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.js +1 -7
  48. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +28 -10
  49. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +134 -88
  50. package/dataflow/internal/process/functions/call/built-in/built-in-load.d.ts +1 -1
  51. package/dataflow/internal/process/functions/call/built-in/built-in-load.js +87 -10
  52. package/dataflow/internal/process/functions/call/built-in/built-in-local.d.ts +8 -0
  53. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +23 -12
  54. package/dataflow/internal/process/functions/call/built-in/built-in-source.d.ts +7 -1
  55. package/dataflow/internal/process/functions/call/built-in/built-in-source.js +28 -10
  56. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.js +1 -1
  57. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +7 -5
  58. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.d.ts +2 -2
  59. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +18 -15
  60. package/dataflow/internal/process/functions/call/named-call-handling.js +8 -4
  61. package/dataflow/internal/process/functions/call/quoted.d.ts +2 -0
  62. package/dataflow/internal/process/functions/call/quoted.js +8 -7
  63. package/documentation/wiki-dataflow-graph.js +20 -1
  64. package/linter/rules/network-functions.js +10 -2
  65. package/linter/rules/undefined-symbol.js +2 -2
  66. package/linter/rules/unused-import.js +11 -1
  67. package/package.json +1 -1
  68. package/project/attached-packages.d.ts +11 -6
  69. package/project/attached-packages.js +37 -9
  70. package/project/cache/flowr-analyzer-cache.d.ts +4 -0
  71. package/project/cache/flowr-analyzer-cache.js +11 -0
  72. package/project/context/flowr-analyzer-dependencies-context.d.ts +3 -0
  73. package/project/context/flowr-analyzer-dependencies-context.js +6 -0
  74. package/project/context/flowr-file.d.ts +2 -2
  75. package/project/context/flowr-file.js +2 -2
  76. package/project/plugins/file-plugins/files/flowr-manifest-files.d.ts +39 -4
  77. package/project/plugins/file-plugins/files/flowr-manifest-files.js +134 -30
  78. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +1 -1
  79. package/project/plugins/file-plugins/flowr-analyzer-manifest-file-plugin.d.ts +7 -0
  80. package/project/plugins/file-plugins/flowr-analyzer-manifest-file-plugin.js +14 -1
  81. package/project/plugins/file-plugins/flowr-analyzer-virtualenv-file-plugin.d.ts +1 -1
  82. package/project/plugins/file-plugins/flowr-analyzer-virtualenv-file-plugin.js +3 -3
  83. package/project/plugins/package-version-plugins/flowr-analyzer-meta-manifest-file-plugin.d.ts +18 -5
  84. package/project/plugins/package-version-plugins/flowr-analyzer-meta-manifest-file-plugin.js +43 -15
  85. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.d.ts +12 -0
  86. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.js +31 -2
  87. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-on-demand-plugin.d.ts +58 -0
  88. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-on-demand-plugin.js +237 -0
  89. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.d.ts +8 -0
  90. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.js +8 -0
  91. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +7 -0
  92. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +24 -18
  93. package/project/plugins/plugin-registry.d.ts +5 -4
  94. package/project/plugins/plugin-registry.js +6 -0
  95. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +4 -4
  96. package/project/sigdb/decode.js +13 -3
  97. package/project/sigdb/memory-source.d.ts +6 -4
  98. package/project/sigdb/memory-source.js +6 -5
  99. package/project/sigdb/on-demand/fetch.d.ts +18 -0
  100. package/project/sigdb/on-demand/fetch.js +127 -0
  101. package/project/sigdb/on-demand/package-sources.d.ts +40 -0
  102. package/project/sigdb/on-demand/package-sources.js +263 -0
  103. package/project/sigdb/on-demand/recoverer.d.ts +40 -0
  104. package/project/sigdb/on-demand/recoverer.js +169 -0
  105. package/project/sigdb/on-demand/remote-sources.d.ts +72 -0
  106. package/project/sigdb/on-demand/remote-sources.js +132 -0
  107. package/project/sigdb/on-demand/tar.d.ts +19 -0
  108. package/project/sigdb/on-demand/tar.js +119 -0
  109. package/queries/catalog/dependencies-query/function-info/derived-functions.d.ts +5 -0
  110. package/queries/catalog/dependencies-query/function-info/derived-functions.js +17 -1
  111. package/queries/catalog/dependencies-query/function-info/read-functions.js +3 -1
  112. package/queries/catalog/dependencies-query/function-info/write-functions.js +11 -1
  113. package/queries/catalog/signature-query/signature-query-executor.js +15 -1
  114. package/queries/catalog/signature-query/signature-query-format.d.ts +3 -2
  115. package/r-bridge/data/data.d.ts +31 -2
  116. package/r-bridge/data/data.js +25 -2
  117. package/r-bridge/lang-4.x/ast/model/model.d.ts +2 -0
  118. package/r-bridge/lang-4.x/ast/model/model.js +6 -1
  119. package/r-bridge/lang-4.x/ast/model/processing/node-id.d.ts +6 -1
  120. package/r-bridge/lang-4.x/ast/model/processing/node-id.js +12 -1
  121. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.d.ts +4 -0
  122. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.js +8 -0
  123. package/reconstruct/reconstruct.js +2 -5
  124. package/search/search-executor/search-enrichers.js +17 -2
  125. package/search/search-executor/search-generators.js +6 -2
  126. package/slicing/static/slice-call.d.ts +16 -0
  127. package/slicing/static/slice-call.js +42 -0
  128. package/slicing/static/static-slicer.js +6 -0
  129. package/taint-analysis/predefined/secret-analysis.js +7 -2
  130. package/taint-analysis/taint-mapping.d.ts +5 -2
  131. package/taint-analysis/taint-mapping.js +17 -6
  132. package/util/flowr-version.d.ts +1 -1
  133. package/util/flowr-version.js +2 -2
  134. package/util/r-version.js +4 -2
@@ -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) ?? []) {
@@ -3,7 +3,7 @@ import type { DataflowInformation } from '../../../../../info';
3
3
  import { type PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
4
4
  import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/decorate';
5
5
  import { RSymbol } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol';
6
- import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
6
+ import { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
7
7
  import type { MergeableRecord } from '../../../../../../util/objects';
8
8
  import { Identifier } from '../../../../../environments/identifier';
9
9
  import type { RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model';
@@ -6,6 +6,7 @@ const function_semantics_1 = require("../../../../../fn/function-semantics");
6
6
  const known_call_handling_1 = require("../known-call-handling");
7
7
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
8
8
  const r_symbol_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
9
+ const node_id_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id");
9
10
  const logger_1 = require("../../../../../logger");
10
11
  const vertex_1 = require("../../../../../graph/vertex");
11
12
  const graph_1 = require("../../../../../graph/graph");
@@ -117,7 +118,7 @@ function processApply(name, args, rootId, data, config) {
117
118
  const allOtherArguments = vertex_1.DfgVertex.isFunctionCall(spread) && vertex_1.DfgVertex.hasOrigin(spread, built_in_proc_name_1.BuiltInProcName.List) ? spread.args : handedOn;
118
119
  if (anonymous) {
119
120
  const rootFnId = functionId;
120
- functionId = 'anon-' + rootFnId;
121
+ functionId = node_id_1.NodeId.anonymousCall(rootFnId);
121
122
  information.graph.addVertex({
122
123
  tag: vertex_1.VertexType.FunctionCall,
123
124
  id: functionId,
@@ -4,7 +4,7 @@ import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/
4
4
  import { RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model';
5
5
  import { RSymbol } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol';
6
6
  import type { PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
7
- import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
7
+ import { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
8
8
  import { Identifier, type InGraphIdentifierDefinition } from '../../../../../environments/identifier';
9
9
  import type { DataflowGraphVertexFunctionDefinition } from '../../../../../graph/vertex';
10
10
  import type { REnvironmentInformation } from '../../../../../environments/environment';
@@ -16,6 +16,7 @@ const r_access_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/
16
16
  const r_symbol_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
17
17
  const type_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/type");
18
18
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
19
+ const node_id_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id");
19
20
  const logger_1 = require("../../../../../logger");
20
21
  const identifier_1 = require("../../../../../environments/identifier");
21
22
  const built_in_ambient_state_1 = require("./built-in-ambient-state");
@@ -442,6 +443,15 @@ function processDefineArgument(name, args, rootId, data, config) {
442
443
  }
443
444
  /** Define `nodeToDefine` in the environment and wire the `DefinedBy` edges from it to its sources and the assignment root (dropping the child-added read edges). */
444
445
  function markAsAssignment(information, nodeToDefine, sourceIds, rootIdOfAssignment, data, assignmentConfig) {
446
+ if (assignmentConfig?.superAssignment) {
447
+ /* `<<-` reaching the binding of an attached package fails on it, so it depends on the attach */
448
+ for (const def of resolve_helper_1.Resolve.byName(nodeToDefine.name, information.environment) ?? []) {
449
+ const definedAt = def.definedAt;
450
+ if (node_id_1.NodeId.isBuiltIn(def.nodeId) && definedAt !== undefined && !node_id_1.NodeId.isBuiltIn(definedAt)) {
451
+ information.graph.addEdge(rootIdOfAssignment, definedAt, edge_1.EdgeType.Reads);
452
+ }
453
+ }
454
+ }
445
455
  information.environment = environment_1.REnvironment.define(nodeToDefine, assignmentConfig?.superAssignment, information.environment);
446
456
  information.environment = (0, built_in_ambient_state_1.ambientWritesOfAssignment)(information.environment, nodeToDefine.name, rootIdOfAssignment, data.cds ? [...data.cds] : undefined, assignmentConfig?.superAssignment === true || data.environment.level === 0);
447
457
  information.graph.setDefinitionOfVertex(nodeToDefine, sourceIds);
@@ -4,8 +4,12 @@ import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/
4
4
  import type { PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
5
5
  import { RSymbol } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol';
6
6
  import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
7
- import { type AmbientStateAccess } from './built-in-ambient-state';
7
+ import type { AmbientConfig } from '../../../../../environments/built-in';
8
8
  /** Processes `attach(what, ...)`, injecting the tracked env's known definitions into a new scope layer below `.GlobalEnv`. */
9
- export declare function processAttach<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, config?: {
10
- readonly ambient?: AmbientStateAccess | readonly AmbientStateAccess[];
11
- }): DataflowInformation;
9
+ export declare function processAttach<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, _config?: AmbientConfig): DataflowInformation;
10
+ /**
11
+ * Processes `detach(name)` and `unloadNamespace(ns)`: the search path entry named (`package:x`, `"x"`, a position, the
12
+ * topmost one if nothing is given) is removed, uncovering what it masked. The entry is read with the keys of the
13
+ * call's search path {@link AmbientConfig|ambient} write.
14
+ */
15
+ export declare function processDetach<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, config?: AmbientConfig): DataflowInformation;
@@ -1,34 +1,44 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.processAttach = processAttach;
4
+ exports.processDetach = processDetach;
4
5
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
5
6
  const known_call_handling_1 = require("../known-call-handling");
6
7
  const r_symbol_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
8
+ const r_string_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-string");
7
9
  const identifier_1 = require("../../../../../environments/identifier");
8
10
  const environment_1 = require("../../../../../environments/environment");
9
11
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
10
12
  const unknown_side_effect_1 = require("../../../../../graph/unknown-side-effect");
11
13
  const edge_1 = require("../../../../../graph/edge");
12
14
  const built_in_envir_utils_1 = require("./built-in-envir-utils");
15
+ const built_in_ambient_keys_1 = require("./built-in-ambient-keys");
16
+ const ambient_state_name_1 = require("../../../../../environments/ambient-state-name");
13
17
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
14
- const built_in_ambient_state_1 = require("./built-in-ambient-state");
18
+ const AttachableLiterals = new Set(['list', 'data.frame']);
15
19
  /** Processes `attach(what, ...)`, injecting the tracked env's known definitions into a new scope layer below `.GlobalEnv`. */
16
- function processAttach(name, args, rootId, data, config = {}) {
17
- const result = attachLayer(name, args, rootId, data);
18
- return config.ambient === undefined ? result : (0, built_in_ambient_state_1.applyAmbientStateAccess)(result, args, rootId, data, config.ambient);
19
- }
20
- function attachLayer(name, args, rootId, data) {
20
+ function processAttach(name, args, rootId, data,
21
+ /* the search path it writes is applied by the registration, see {@link AmbientConfig} */
22
+ _config = {}) {
21
23
  const result = (0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, origin: built_in_proc_name_1.BuiltInProcName.Attach }).information;
22
24
  const whatArg = args.length >= 1 ? args[0] : undefined;
23
25
  const whatNode = whatArg && whatArg !== r_function_call_1.EmptyArgument ? r_argument_1.RArgument.valueOf(whatArg) : undefined;
24
26
  const envirResolution = r_symbol_1.RSymbol.is(whatNode) ? (0, built_in_envir_utils_1.resolveSymbolToEnvir)(whatNode.content, whatNode.info.id, data) : undefined;
25
- if (!envirResolution) {
27
+ /* a list written out names its bindings, `attach(list(a = 1))` binds `a` to `1` */
28
+ const listed = envirResolution === undefined && r_function_call_1.RFunctionCall.isNamed(whatNode, AttachableLiterals)
29
+ && whatNode.arguments.every(a => a !== r_function_call_1.EmptyArgument && a.name !== undefined && a.value !== undefined) ? whatNode.arguments : undefined;
30
+ if (!envirResolution && !listed) {
26
31
  (0, unknown_side_effect_1.handleUnknownSideEffect)(result.graph, result.environment, rootId);
27
32
  return result;
28
33
  }
29
34
  /* build the attached layer with the env's known bindings */
30
35
  const injected = [];
31
- for (const [varName, varDefs] of envirResolution.envDef.envState.current.memory) {
36
+ for (const entry of listed ?? []) {
37
+ const at = entry.value.info.id;
38
+ injected.push({ nodeId: at, name: entry.name?.content, type: identifier_1.ReferenceType.Variable, definedAt: rootId, cds: data.cds ? [...data.cds] : undefined });
39
+ result.graph.addEdge(at, rootId, edge_1.EdgeType.Reads);
40
+ }
41
+ for (const [varName, varDefs] of envirResolution?.envDef.envState.current.memory ?? []) {
32
42
  for (const varDef of varDefs) {
33
43
  const inDef = varDef;
34
44
  injected.push({
@@ -40,10 +50,35 @@ function attachLayer(name, args, rootId, data) {
40
50
  }
41
51
  }
42
52
  const attachedLayer = new environment_1.Environment(result.environment.current).defineAll(injected);
53
+ attachedLayer.t = environment_1.EnvType.Attached;
54
+ /* R names the entry by `name`, else by the variable given as `what` */
55
+ const named = r_argument_1.RArgument.valueOf(args.find(a => a !== r_function_call_1.EmptyArgument && a.name !== undefined && identifier_1.Identifier.getName(a.name.content) === 'name'));
56
+ attachedLayer.n = r_string_1.RString.is(named) ? named.content.str : r_symbol_1.RSymbol.is(whatNode) ? identifier_1.Identifier.getName(whatNode.content) : undefined;
43
57
  /* R attaches below `.GlobalEnv`, so existing global bindings shadow the attached ones */
44
58
  return { ...result, environment: {
45
59
  current: environment_1.REnvironment.attachAt(result.environment.current, attachedLayer, attachedLayer),
46
60
  level: result.environment.level
47
61
  } };
48
62
  }
63
+ /**
64
+ * Processes `detach(name)` and `unloadNamespace(ns)`: the search path entry named (`package:x`, `"x"`, a position, the
65
+ * topmost one if nothing is given) is removed, uncovering what it masked. The entry is read with the keys of the
66
+ * call's search path {@link AmbientConfig|ambient} write.
67
+ */
68
+ function processDetach(name, args, rootId, data, config = {}) {
69
+ const info = (0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, origin: built_in_proc_name_1.BuiltInProcName.Detach }).information;
70
+ const keys = [config.ambient ?? []].flat().flatMap(a => a.type === "set-keyed" /* AmbientStateAccessType.SetKeyed */ ? (0, built_in_ambient_keys_1.keysOf)(a.keys, args, data) : []);
71
+ const first = r_argument_1.RArgument.valueOf(args.find(a => a !== r_function_call_1.EmptyArgument));
72
+ const positions = first === undefined ? [environment_1.DefaultAttachPosition]
73
+ : keys.includes(ambient_state_name_1.UnknownKey) ? [(0, built_in_envir_utils_1.resolveAttachPosition)(first.info.id, data)]
74
+ : keys.map(k => environment_1.REnvironment.searchPosition(info.environment.current, k));
75
+ /* what a later read no longer finds still depends on the removal, which only an unknown side effect tells it */
76
+ (0, unknown_side_effect_1.handleUnknownSideEffect)(info.graph, info.environment, rootId);
77
+ if (!positions.includes(undefined)) {
78
+ for (const pos of positions) {
79
+ info.environment = { level: info.environment.level, current: environment_1.REnvironment.detachAt(info.environment.current, pos) };
80
+ }
81
+ }
82
+ return info;
83
+ }
49
84
  //# sourceMappingURL=built-in-attach.js.map
@@ -9,7 +9,7 @@ import type { FnSig } from '../../../../../environments/built-in-props';
9
9
  * Processes a call listing what an environment holds (`ls`, `objects`), which reads every binding in it: the
10
10
  * answer changes with each one, so each has to stay.
11
11
  */
12
- export declare function processEnvContents<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, config?: {
12
+ export declare function processEnvContents<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, { sig }?: {
13
13
  sig?: FnSig;
14
14
  }): DataflowInformation;
15
15
  /**
@@ -18,13 +18,14 @@ const environment_1 = require("../../../../../environments/environment");
18
18
  * Processes a call listing what an environment holds (`ls`, `objects`), which reads every binding in it: the
19
19
  * answer changes with each one, so each has to stay.
20
20
  */
21
- function processEnvContents(name, args, rootId, data, config = {}) {
21
+ function processEnvContents(name, args, rootId, data, { sig } = {}) {
22
22
  const result = (0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, origin: built_in_proc_name_1.BuiltInProcName.EnvContents }).information;
23
- const resolution = (0, built_in_envir_utils_1.resolveFirstEnvirArg)(args, data, config.sig, ['envir', 'name']);
24
- if (!resolution) {
23
+ const formals = ['envir', 'name'];
24
+ const resolution = (0, built_in_envir_utils_1.resolveFirstEnvirArg)(args, data, sig, formals);
25
+ if (!resolution && (0, built_in_envir_utils_1.suppliesArg)(args, sig, formals)) {
25
26
  return result;
26
27
  }
27
- for (const defs of resolution.envDef.envState.current.memory.values()) {
28
+ for (const defs of (resolution?.envDef.envState ?? data.environment).current.memory.values()) {
28
29
  (0, linker_1.linkFieldReads)(result.graph, rootId, defs, false);
29
30
  }
30
31
  return result;