@eagleoutice/flowr 2.15.9 → 2.15.10

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 (112) hide show
  1. package/README.md +34 -25
  2. package/abstract-interpretation/absint-inference.d.ts +2 -2
  3. package/abstract-interpretation/absint-inference.js +32 -79
  4. package/benchmark/slicer.d.ts +0 -1
  5. package/benchmark/slicer.js +1 -2
  6. package/cli/repl/commands/repl-signature.js +12 -3
  7. package/config.d.ts +5 -1
  8. package/control-flow/cfg-properties.js +0 -22
  9. package/control-flow/happens-before.d.ts +2 -2
  10. package/control-flow/happens-before.js +29 -19
  11. package/dataflow/environments/apply-kill.js +6 -2
  12. package/dataflow/environments/built-in-config.d.ts +2 -0
  13. package/dataflow/environments/built-in-props.d.ts +7 -1
  14. package/dataflow/environments/built-in-props.js +8 -1
  15. package/dataflow/environments/built-in.d.ts +7 -2
  16. package/dataflow/environments/built-in.js +11 -5
  17. package/dataflow/environments/default-builtin-config.d.ts +386 -8
  18. package/dataflow/environments/default-builtin-config.js +84 -22
  19. package/dataflow/environments/define.d.ts +3 -2
  20. package/dataflow/environments/define.js +4 -3
  21. package/dataflow/environments/deprecation-info.d.ts +45 -0
  22. package/dataflow/environments/deprecation-info.js +13 -0
  23. package/dataflow/environments/environment.d.ts +1 -1
  24. package/dataflow/environments/environment.js +5 -4
  25. package/dataflow/environments/identifier.d.ts +2 -0
  26. package/dataflow/extractor.js +6 -1
  27. package/dataflow/fn/class-declaration.d.ts +0 -11
  28. package/dataflow/fn/class-declaration.js +0 -20
  29. package/dataflow/fn/higher-order-function.d.ts +9 -1
  30. package/dataflow/fn/higher-order-function.js +14 -7
  31. package/dataflow/fn/strict-function.js +8 -3
  32. package/dataflow/graph/graph.d.ts +7 -0
  33. package/dataflow/graph/graph.js +17 -0
  34. package/dataflow/graph/vertex.d.ts +1 -1
  35. package/dataflow/internal/linker.d.ts +3 -0
  36. package/dataflow/internal/linker.js +67 -6
  37. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +113 -0
  38. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +506 -0
  39. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +9 -0
  40. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +2 -0
  41. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +22 -19
  42. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +5 -1
  43. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +21 -14
  44. package/dataflow/internal/process/functions/call/built-in/built-in-eval.js +14 -4
  45. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +22 -2
  46. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.js +2 -0
  47. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +4 -3
  48. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +19 -3
  49. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +7 -3
  50. package/dataflow/internal/process/functions/call/built-in/built-in-repeat-loop.js +2 -0
  51. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.d.ts +4 -2
  52. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.js +3 -5
  53. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +2 -1
  54. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.js +8 -0
  55. package/dataflow/internal/process/functions/call/built-in/built-in-while-loop.js +2 -0
  56. package/dataflow/internal/process/functions/call/common.d.ts +3 -1
  57. package/dataflow/internal/process/functions/call/common.js +22 -4
  58. package/dataflow/internal/process/functions/call/deferred.d.ts +6 -0
  59. package/dataflow/internal/process/functions/call/deferred.js +33 -12
  60. package/dataflow/internal/process/functions/call/known-call-handling.js +1 -1
  61. package/dataflow/internal/process/functions/call/named-call-handling.js +15 -0
  62. package/dataflow/internal/process/functions/call/quoted.js +137 -24
  63. package/dataflow/internal/process/process-symbol.js +6 -2
  64. package/documentation/data/faq/faqs.js +3 -3
  65. package/documentation/data/interface/doc-writing-code.js +1 -2
  66. package/documentation/data/server/doc-data-server-messages.js +7 -7
  67. package/documentation/doc-capabilities.js +80 -34
  68. package/documentation/doc-util/doc-query.d.ts +0 -3
  69. package/documentation/doc-util/doc-query.js +4 -3
  70. package/documentation/wiki-analyzer.js +1 -1
  71. package/documentation/wiki-cfg.js +5 -6
  72. package/documentation/wiki-core.js +8 -8
  73. package/documentation/wiki-dataflow-graph.js +10 -11
  74. package/documentation/wiki-interface.js +2 -2
  75. package/documentation/wiki-linting-and-testing.js +3 -3
  76. package/documentation/wiki-overview.js +6 -6
  77. package/documentation/wiki-query.js +9 -101
  78. package/documentation/wiki-signature-database.js +1 -1
  79. package/linter/linter-rules.d.ts +1 -1
  80. package/linter/rules/deprecated-functions.d.ts +1 -45
  81. package/linter/rules/deprecated-functions.js +24 -33
  82. package/package.json +1 -1
  83. package/project/flowr-analyzer.d.ts +2 -0
  84. package/project/flowr-analyzer.js +24 -1
  85. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +0 -2
  86. package/project/plugins/file-plugins/files/flowr-rda-file.js +10 -55
  87. package/project/plugins/file-plugins/flowr-analyzer-file-plugin.js +2 -1
  88. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +6 -4
  89. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +2 -2
  90. package/project/sigdb/build.js +4 -0
  91. package/project/sigdb/manifest.d.ts +2 -0
  92. package/project/sigdb/manifest.js +10 -1
  93. package/project/sigdb/reader.js +23 -61
  94. package/project/sigdb/sigdb-download.d.ts +29 -6
  95. package/project/sigdb/sigdb-download.js +212 -64
  96. package/queries/catalog/call-context-query/cascade-action.d.ts +3 -1
  97. package/queries/catalog/call-context-query/cascade-action.js +2 -0
  98. package/queries/catalog/call-context-query/identify-link-to-last-call-relation.js +3 -0
  99. package/queries/catalog/inspect-higher-order-query/inspect-higher-order-query-executor.js +2 -1
  100. package/queries/catalog/origin-query/origin-query-executor.d.ts +1 -1
  101. package/queries/catalog/origin-query/origin-query-executor.js +2 -2
  102. package/queries/catalog/origin-query/origin-query-format.d.ts +2 -2
  103. package/queries/catalog/origin-query/origin-query-format.js +1 -1
  104. package/queries/query.d.ts +1 -1
  105. package/r-bridge/data/data.d.ts +21 -14
  106. package/r-bridge/data/data.js +28 -20
  107. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.d.ts +2 -2
  108. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.js +11 -2
  109. package/util/files.d.ts +2 -0
  110. package/util/files.js +3 -1
  111. package/util/mermaid/mermaid.js +6 -2
  112. package/util/version.js +2 -2
@@ -5,7 +5,7 @@ import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/
5
5
  import type { PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
6
6
  import { RFunctionCall } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
7
7
  import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
8
- import type { IdentifierDefinition, NamedInGraphIdentifierDefinition, Identifier } from '../../../../../environments/identifier';
8
+ import { Identifier, type IdentifierDefinition, type NamedInGraphIdentifierDefinition } from '../../../../../environments/identifier';
9
9
  import type { REnvironmentInformation } from '../../../../../environments/environment';
10
10
  import type { RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model';
11
11
  import { FnSig } from '../../../../../environments/built-in-props';
@@ -75,6 +75,10 @@ export declare function resolveFirstEnvirArg<OtherInfo>(args: readonly Potential
75
75
  export declare function unknownIfAmbiguous<OtherInfo>(routing: EnvirArgRouting<OtherInfo>, result: DataflowInformation, rootId: NodeId): boolean;
76
76
  /** Resolves a symbol by name to an {@link EnvirResolution} when it holds a tracked environment. */
77
77
  export declare function resolveSymbolToEnvir<OtherInfo>(symbolName: Identifier, nodeId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): EnvirResolution<OtherInfo> | undefined;
78
+ /** Binds every variable holding the environment of `envDef` to its new state, where that variable is bound. */
79
+ export declare function rebindHolders(environment: REnvironmentInformation, envDef: NamedInGraphIdentifierDefinition & {
80
+ envState: REnvironmentInformation;
81
+ }, envState: REnvironmentInformation, definedAt?: NodeId): REnvironmentInformation;
78
82
  /**
79
83
  * Routes writes into a real stack env's frame chain, the same way `<<-` reaches an outer scope.
80
84
  * Each write also gets a `Reads` edge back to `rootId`, so slicing does not drop the call that made it.
@@ -12,6 +12,7 @@ exports.suppliesArg = suppliesArg;
12
12
  exports.resolveFirstEnvirArg = resolveFirstEnvirArg;
13
13
  exports.unknownIfAmbiguous = unknownIfAmbiguous;
14
14
  exports.resolveSymbolToEnvir = resolveSymbolToEnvir;
15
+ exports.rebindHolders = rebindHolders;
15
16
  exports.routeWrittenToStackEnv = routeWrittenToStackEnv;
16
17
  exports.routeWrittenToEnvir = routeWrittenToEnvir;
17
18
  exports.resolveAttachPosition = resolveAttachPosition;
@@ -19,6 +20,7 @@ const r_value_1 = require("../../../../../eval/values/r-value");
19
20
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
20
21
  const unpack_argument_1 = require("../argument/unpack-argument");
21
22
  const identifier_1 = require("../../../../../environments/identifier");
23
+ const identifier_2 = require("../../../../../environments/identifier");
22
24
  const define_1 = require("../../../../../environments/define");
23
25
  const environment_1 = require("../../../../../environments/environment");
24
26
  const prefix_1 = require("../../../../../../util/prefix");
@@ -50,7 +52,7 @@ function resolveDefsToEnvirResolution(defs, nodeId, data) {
50
52
  const envDef = inDefs[0];
51
53
  return { envirData: { ...data, environment: envState }, envDef, envirNodeId: nodeId, stack: stackKindOf(envState) };
52
54
  }
53
- if (!inDefs.every(identifier_1.hasEnvState)) {
55
+ if (!inDefs.every(identifier_2.hasEnvState)) {
54
56
  return undefined;
55
57
  }
56
58
  const stack = stackKindOf(inDefs[0].envState);
@@ -115,9 +117,6 @@ function findReturnsEnvState(defs) {
115
117
  function envirOf(routing) {
116
118
  return routing === 'ambiguous' ? undefined : routing;
117
119
  }
118
- function isAmbiguousEnvirDef(d) {
119
- return d.type === identifier_1.ReferenceType.Parameter && !(0, identifier_1.hasEnvState)(d);
120
- }
121
120
  /** Resolves a single already-found argument (e.g. from {@link RFunctionCall.matchArgsToParams}) to an {@link EnvirArgRouting}. */
122
121
  function resolveArgToEnvirOrAmbiguous(arg, data) {
123
122
  if (r_argument_1.RArgument.isEmpty(arg)) {
@@ -132,9 +131,10 @@ function resolveArgToEnvirOrAmbiguous(arg, data) {
132
131
  if (!r_symbol_1.RSymbol.is(node)) {
133
132
  return undefined;
134
133
  }
135
- const defs = resolve_helper_1.Resolve.byNameAndType(node.content, data.environment, identifier_1.ReferenceType.Variable);
134
+ const defs = resolve_helper_1.Resolve.byNameAndType(node.content, data.environment, identifier_2.ReferenceType.Variable);
135
+ /* an environment we do not track, or a free variable of a function body bound only once the function is called */
136
136
  return resolveDefsToEnvirResolution(defs, node.info.id, data)
137
- ?? (defs?.some(isAmbiguousEnvirDef) ? 'ambiguous' : undefined);
137
+ ?? ((defs === undefined && data.environment.level === 0) || !data.ctx.config.solver.trackEnvironments ? undefined : 'ambiguous');
138
138
  }
139
139
  /** Builds an {@link EnvirResolution} for an environment obtained directly (not via a holder variable), e.g. `globalenv()` / `.GlobalEnv`. */
140
140
  function stackEnvirResolution(envState, nodeId, lexeme, data) {
@@ -142,7 +142,7 @@ function stackEnvirResolution(envState, nodeId, lexeme, data) {
142
142
  const envDef = {
143
143
  name: lexeme,
144
144
  nodeId,
145
- type: identifier_1.ReferenceType.Variable,
145
+ type: identifier_2.ReferenceType.Variable,
146
146
  definedAt: nodeId,
147
147
  envState,
148
148
  };
@@ -218,7 +218,7 @@ function unknownIfAmbiguous(routing, result, rootId) {
218
218
  }
219
219
  /** Resolves a symbol by name to an {@link EnvirResolution} when it holds a tracked environment. */
220
220
  function resolveSymbolToEnvir(symbolName, nodeId, data) {
221
- return envirOf(resolveDefsToEnvirResolution(resolve_helper_1.Resolve.byNameAndType(symbolName, data.environment, identifier_1.ReferenceType.Variable), nodeId, data));
221
+ return envirOf(resolveDefsToEnvirResolution(resolve_helper_1.Resolve.byNameAndType(symbolName, data.environment, identifier_2.ReferenceType.Variable), nodeId, data));
222
222
  }
223
223
  function writtenDefinitionsOf(result, definedAt) {
224
224
  return result.out.filter((d) => d.name !== undefined && 'definedAt' in d &&
@@ -230,7 +230,8 @@ function holdersOf(environment, envDef) {
230
230
  while (env !== undefined && !env.builtInEnv) {
231
231
  for (const defs of env.memory.values()) {
232
232
  for (const def of defs) {
233
- if (def.envState === envDef.envState && def.name !== undefined && def.nodeId !== envDef.nodeId) {
233
+ /* a copy (`g <- e`) holds the same environment object, even once one of them saw a write */
234
+ if ((def.envState === envDef.envState || (def.envId !== undefined && def.envId === envDef.envId)) && def.name !== undefined && def.nodeId !== envDef.nodeId) {
234
235
  holders.push(def);
235
236
  }
236
237
  }
@@ -245,15 +246,21 @@ function holdersOf(environment, envDef) {
245
246
  function routeWrittenToCustomEnv(result, envDef, newDefAt, definedAt) {
246
247
  const written = writtenDefinitionsOf(result, definedAt);
247
248
  let newEnvState = envDef.envState;
248
- const namesToRemove = written.map(w => ({ name: w.name }));
249
+ /* only a binding the write made here moves into the environment, `local(y <- 2, envir = e)` leaves the caller's `y` alone */
250
+ const namesToRemove = written.filter(w => result.environment.current.lookup(identifier_1.Identifier.getName(w.name))?.some(d => d.nodeId === w.nodeId)).map(w => ({ name: w.name }));
249
251
  for (const w of written) {
250
252
  newEnvState = (0, define_1.define)(w, false, newEnvState);
251
253
  }
252
- let newEnvironment = { current: result.environment.current.removeAll(namesToRemove), level: result.environment.level };
253
- for (const holder of holdersOf(result.environment, envDef)) {
254
- newEnvironment = (0, define_1.define)({ ...holder, definedAt: newDefAt, envState: newEnvState }, false, newEnvironment);
254
+ const stripped = { current: result.environment.current.removeAll(namesToRemove), level: result.environment.level };
255
+ return { ...result, environment: rebindHolders(stripped, envDef, newEnvState, newDefAt) };
256
+ }
257
+ /** Binds every variable holding the environment of `envDef` to its new state, where that variable is bound. */
258
+ function rebindHolders(environment, envDef, envState, definedAt) {
259
+ for (const holder of holdersOf(environment, envDef)) {
260
+ /* a holder bound in an enclosing frame is updated there, so the write escapes the function like a `<<-` */
261
+ environment = (0, define_1.define)({ ...holder, definedAt: definedAt ?? holder.definedAt, envState }, environment.current.lookup(identifier_1.Identifier.getName(holder.name)) === undefined, environment);
255
262
  }
256
- return { ...result, environment: newEnvironment };
263
+ return environment;
257
264
  }
258
265
  /**
259
266
  * Routes writes into a real stack env's frame chain, the same way `<<-` reaches an outer scope.
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.processEvalCall = processEvalCall;
4
+ const r_binary_op_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op");
4
5
  const function_semantics_1 = require("../../../../../fn/function-semantics");
5
6
  const info_1 = require("../../../../../info");
6
7
  const known_call_handling_1 = require("../known-call-handling");
@@ -25,6 +26,7 @@ const built_in_envir_utils_1 = require("./built-in-envir-utils");
25
26
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
26
27
  const r_string_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-string");
27
28
  const r_function_call_2 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
29
+ const built_in_ambient_state_1 = require("./built-in-ambient-state");
28
30
  const SymbolConstructors = new Set(['as.name', 'as.symbol']);
29
31
  const SyntacticName = /^[.a-zA-Z][.a-zA-Z0-9_]*$/;
30
32
  /** the formals of `eval(expr, envir, enclos)` */
@@ -84,7 +86,8 @@ function processEvalCall(name, args, rootId, data, config) {
84
86
  }
85
87
  (0, log_1.expensiveTrace)(logger_1.dataflowLogger, () => `Non-constant argument ${JSON.stringify(args)} for eval is currently not supported, skipping`);
86
88
  (0, unknown_side_effect_1.handleUnknownSideEffect)(information.graph, information.environment, rootId);
87
- return information;
89
+ /* a captured expression is linked once the graph is complete, but the state its calls access has to show now */
90
+ return (0, built_in_ambient_state_1.evaluatesCapturedCode)(information, rootId, data);
88
91
  }
89
92
  function namesParentFrame(envir, data) {
90
93
  return r_function_call_1.RFunctionCall.isNamed(envir)
@@ -130,6 +133,10 @@ function resolveEvalToCode(evalArgument, config, data) {
130
133
  }
131
134
  return getAsString(arg.value, data);
132
135
  }
136
+ else if (r_function_call_1.RFunctionCall.isNamed(val) && ['str2lang', 'str2expression'].includes(identifier_1.Identifier.getName(val.functionName.content))) {
137
+ /* both parse their string, like `parse(text = s)` */
138
+ return getAsString(r_function_call_1.RFunctionCall.soleArgument(val.arguments)?.value, data);
139
+ }
133
140
  else if (r_function_call_1.RFunctionCall.isNamed(val) && SymbolConstructors.has(identifier_1.Identifier.getName(val.functionName.content))
134
141
  && resolve_helper_1.Resolve.isBuiltIn(val.functionName.content, data.environment, identifier_1.ReferenceType.Function)) {
135
142
  const arg = r_function_call_1.RFunctionCall.soleArgument(val.arguments);
@@ -137,9 +144,12 @@ function resolveEvalToCode(evalArgument, config, data) {
137
144
  return named !== undefined && SyntacticName.test(named) ? [named] : undefined;
138
145
  }
139
146
  else if (r_symbol_1.RSymbol.is(val)) {
140
- // const resolved = resolveValueOfVariable(val.content, env);
141
- // see https://github.com/flowr-analysis/flowr/pull/1467
142
- return undefined;
147
+ /* `nm <- as.name("w"); eval(nm)`: a name bound once to code we can read is that code */
148
+ const defs = resolve_helper_1.Resolve.byName(val.content, data.environment);
149
+ const target = defs?.length === 1 ? defs[0].nodeId : undefined;
150
+ const assignment = target === undefined ? undefined : data.completeAst.idMap.get(data.completeAst.idMap.get(target)?.info.parent ?? '');
151
+ const source = r_binary_op_1.RBinaryOp.is(assignment) ? assignment.lhs.info.id === target ? assignment.rhs : assignment.lhs : undefined;
152
+ return source === undefined || r_symbol_1.RSymbol.is(source) ? undefined : resolveEvalToCode(source, config, data);
143
153
  }
144
154
  else {
145
155
  return undefined;
@@ -24,6 +24,7 @@ const general_1 = require("../../../../../eval/values/general");
24
24
  const vertex_2 = require("../../../../../graph/vertex");
25
25
  const resolve_helper_1 = require("../../../../../environments/resolve-helper");
26
26
  const type_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/type");
27
+ const built_in_ambient_state_1 = require("./built-in-ambient-state");
27
28
  /**
28
29
  * Whether the definitions of this list among the `targets` of a read cover every branch, alone or together.
29
30
  * Only then the read is resolved here and must not bubble up as an ingoing reference.
@@ -222,6 +223,14 @@ function updateSideEffectsForCalledFunctions(calledEnvs, inputEnvironment, nextG
222
223
  let callDependencies = null;
223
224
  for (const { fn: calledFn, direct } of transitivelyCalledDefinitions(called, nextGraph, inputEnvironment)) {
224
225
  (0, assert_1.guard)(vertex_2.DfgVertex.isFunctionDefinition(calledFn), 'called function must be a function definition');
226
+ /* walk the smaller of the two, a script may hold many unknown side effects and a function many vertices */
227
+ const inside = calledFn.subflow.graph;
228
+ const effects = nextGraph.unknownSideEffects;
229
+ for (const effect of inside.size < effects.size ? inside : effects) {
230
+ if (typeof effect !== 'object' && inside.has(effect) && effects.has(effect)) {
231
+ nextGraph.addEdge(effect, functionCall, edge_1.EdgeType.SideEffectOnCall);
232
+ }
233
+ }
225
234
  // only merge the environments they have in common
226
235
  let environment = direct ? calledFn.subflow.environment : withoutPackageLayers(calledFn.subflow.environment);
227
236
  if (environment.level > inputEnvironment.level) {
@@ -285,6 +294,8 @@ function processExpressionList(name, args, rootId, data) {
285
294
  const invertExitCds = [];
286
295
  const processedExpressions = [];
287
296
  let defaultReturnExpr = undefined;
297
+ /* R prints what the top level of the analyzed script leaves visible, but not what a sourced file does */
298
+ const autoPrint = data.referenceChain.length <= 1 && data.environment.level === 0 && data.completeAst.ast.files.some(f => f.root.info.id === rootId);
288
299
  let hooks;
289
300
  for (const arg of args) {
290
301
  const expression = (0, unpack_argument_1.unpackNonameArg)(arg);
@@ -294,7 +305,10 @@ function processExpressionList(name, args, rootId, data) {
294
305
  }
295
306
  // use the current environments for processing
296
307
  data.environment = environment;
297
- const processed = (0, processor_1.processDataflowFor)(expression, data);
308
+ let processed = (0, processor_1.processDataflowFor)(expression, data);
309
+ if (autoPrint) {
310
+ processed = (0, built_in_ambient_state_1.readsOfAutoPrint)(processed, expression, data);
311
+ }
298
312
  processedExpressions.push(processed);
299
313
  /* the expression's graph dies here, what is kept of it afterward is its entry point and its references */
300
314
  nextGraph.mergeWith(processed.graph, true, true);
@@ -327,6 +341,11 @@ function processExpressionList(name, args, rootId, data) {
327
341
  }
328
342
  }
329
343
  }
344
+ for (const c of calledEnvs) {
345
+ if (c.calledBuiltIns !== undefined) {
346
+ processed = (0, built_in_ambient_state_1.applyAmbientStateOfCalledBuiltIns)(processed, c.functionCall, c.calledBuiltIns, environment, nextGraph, data);
347
+ }
348
+ }
330
349
  (0, info_1.addNonDefaultExitPoints)(exitPoints, invertExitCds, activeCdsAtStart, processed.exitPoints);
331
350
  environment = exitPoints.length > 0 ? (0, overwrite_1.overwriteEnvironment)(environment, processed.environment) : processed.environment;
332
351
  // if the called function has global redefinitions, we have to keep them within our environment
@@ -404,7 +423,8 @@ function processExpressionList(name, args, rootId, data) {
404
423
  return {
405
424
  /* no active nodes remain, they are consumed within the remaining read collection */
406
425
  unknownReferences: [],
407
- in: ingoing,
426
+ /* at the top of the script, a read of the options or graphics state nothing set reads the state R starts with */
427
+ in: autoPrint ? ingoing.filter(r => !built_in_ambient_state_1.AmbientStateName.is(r.name)) : ingoing,
408
428
  /* a definition that a still-effective removal undid is no longer visible to the outside */
409
429
  out: (0, apply_kill_1.dropKilledWrites)(out, killed),
410
430
  environment: environment,
@@ -18,6 +18,7 @@ const identifier_1 = require("../../../../../environments/identifier");
18
18
  const reference_to_maybe_1 = require("../../../../../environments/reference-to-maybe");
19
19
  const apply_kill_1 = require("../../../../../environments/apply-kill");
20
20
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
21
+ const built_in_ambient_state_1 = require("./built-in-ambient-state");
21
22
  /**
22
23
  * Processes a for-loop call: `for(<variable> in <vector>) <body>`
23
24
  * desugared as:
@@ -70,6 +71,7 @@ function processForLoop(name, args, rootId, data) {
70
71
  (0, reference_to_maybe_1.applyCdToReferences)(body.out, cd);
71
72
  const outgoing = variable.out.concat(writtenVariable, body.out);
72
73
  (0, linker_1.linkCircularRedefinitionsWithinALoop)(nextGraph, nameIdShares, body.out, body.environment);
74
+ (0, built_in_ambient_state_1.linkAmbientStateWithinLoop)(nextGraph, bodyRefs, body);
73
75
  /* the loop variable is bound by the head whenever the body runs, so reads of it are not ingoing */
74
76
  const loopVariables = new Set(writtenVariable.map(w => w.name));
75
77
  const bodyReadsOfOthers = [...nameIdShares.entries()].filter(([n]) => !loopVariables.has(n)).flatMap(([, refs]) => refs);
@@ -457,8 +457,9 @@ function namesShadowingBuiltIns(environment) {
457
457
  return { shadowing, generics };
458
458
  }
459
459
  /** Whether `name` resolves to a built-in that dispatches, so the methods the code writes for it are reachable. */
460
- function dispatchesOnClass(name, environment) {
461
- return (((0, query_fn_props_1.queryFnProps)(name, { environment })?.props ?? 0) & built_in_props_1.CallProp.Generic) !== 0;
460
+ function dispatchesOnClass(name, environment, ctx) {
461
+ /* a generic only the signature database knows (`toString`) dispatches as well */
462
+ return built_in_props_1.CallProps.hasAny((0, query_fn_props_1.queryFnProps)(name, { environment }) ?? ctx.functionInfo(name), built_in_props_1.CallProp.Generic);
462
463
  }
463
464
  /**
464
465
  * Links `call` to the S3 methods the analyzed code binds as `<name>.<class>`, returning their definition vertices.
@@ -497,7 +498,7 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
497
498
  const targets = new Set((0, linker_1.getAllFunctionCallTargets)(id, graph, effectiveEnvironment));
498
499
  const collectedNextMethods = new Set();
499
500
  let treatAsS3 = origin.includes(built_in_proc_name_1.BuiltInProcName.S3Dispatch);
500
- if (mayDispatch && !treatAsS3 && dispatchesOnClass(name, effectiveEnvironment)) {
501
+ if (mayDispatch && !treatAsS3 && dispatchesOnClass(name, effectiveEnvironment, ctx)) {
501
502
  for (const method of linkOwnS3Methods(id, name, graph, effectiveEnvironment)) {
502
503
  targets.add(method);
503
504
  }
@@ -30,6 +30,7 @@ const edge_1 = require("../../../../../graph/edge");
30
30
  const assert_1 = require("../../../../../../util/assert");
31
31
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
32
32
  const node_value_1 = require("../../../../../eval/resolve/node-value");
33
+ const string_constants_1 = require("../../../../../eval/values/string/string-constants");
33
34
  const package_1 = require("../../../../../../project/plugins/package-version-plugins/package");
34
35
  const attached_packages_1 = require("../../../../../../project/attached-packages");
35
36
  const flowr_namespace_file_1 = require("../../../../../../project/plugins/file-plugins/files/flowr-namespace-file");
@@ -53,9 +54,23 @@ function processLibrary(name, args, rootId, data, config = {}) {
53
54
  /* parse the import selection before the library flow rewrites `args` below */
54
55
  const parsedSpec = config.fromImports ? parseFromSpec(args) : { namespaceOnly: config.namespaceOnly };
55
56
  // 'pos' last, so the positional fallback keeps its previous order; `import::from` has no `pos`, its extra arguments name exports
56
- const argMaps = function_semantics_1.FunctionSemantics.call.match.toSpec((0, common_1.convertFnArguments)(args), { 'package': 'pkg', 'character.only': 'char', 'pos': 'pos' });
57
+ const argMaps = function_semantics_1.FunctionSemantics.call.match.toSpec((0, common_1.convertFnArguments)(args), { 'package': 'pkg', 'character.only': 'char', 'pos': 'pos', 'include.only': 'only', 'exclude': 'except' });
57
58
  const charId = (0, arrays_1.uniqueArray)(argMaps.get('char') ?? []);
58
- const spec = { ...parsedSpec, pos: config.fromImports ? undefined : (0, built_in_envir_utils_1.resolveAttachPosition)(argMaps.get('pos')?.[0], data) };
59
+ /* `library(pkg, include.only = "f")` and `exclude = "f"` attach only part of the exports, as `import::from` does */
60
+ const namesIn = (key) => {
61
+ const value = r_argument_1.RArgument.getValue(args, argMaps.get(key)?.[0] ?? '');
62
+ /* usually a vector of names, `c("f", "g")` */
63
+ const elements = value === undefined ? undefined : node_value_1.NodeValue.setOf(value.info.id, data)?.elements.flatMap(v => v.type === 'vector' && (0, r_value_1.isValue)(v.elements) ? v.elements : [v]);
64
+ return elements === undefined ? undefined : (0, string_constants_1.collectStrings)(elements);
65
+ };
66
+ const only = config.fromImports ? undefined : namesIn('only');
67
+ const except = config.fromImports ? undefined : namesIn('except');
68
+ const spec = {
69
+ ...parsedSpec,
70
+ pos: config.fromImports ? undefined : (0, built_in_envir_utils_1.resolveAttachPosition)(argMaps.get('pos')?.[0], data),
71
+ ...(only !== undefined ? { include: new Map(only.map(n => [n, n])) } : {}),
72
+ ...(except !== undefined ? { exclude: new Set(except), all: true } : {})
73
+ };
59
74
  /* only a symbol or string literal names a package */
60
75
  const namesToLoad = (0, arrays_1.uniqueArray)(argMaps.get('pkg') ?? [])
61
76
  .map(v => r_argument_1.RArgument.getValue(args, v))
@@ -571,7 +586,8 @@ function attachStatedDefinitions(pack, envInfo, ctx, spec, as, loadedAt, cds) {
571
586
  return envInfo;
572
587
  }
573
588
  /* keyed as the configuration states them: a replacement is bound under `f<-`, which its `name` does not say */
574
- const memory = new Map(stated);
589
+ const memory = new Map(spec.include === undefined && spec.exclude === undefined ? stated
590
+ : [...stated].filter(([key]) => (spec.all || spec.include === undefined || spec.include.has(key)) && !spec.exclude?.has(key)));
575
591
  if (loadedAt !== undefined) {
576
592
  /* the marker an unresolved load leaves behind, so a call links back to the `library()` that made it resolve */
577
593
  memory.set(libraryLoadMarker, [{
@@ -4,6 +4,7 @@ exports.processLocal = processLocal;
4
4
  const function_semantics_1 = require("../../../../../fn/function-semantics");
5
5
  const processor_1 = require("../../../../../processor");
6
6
  const info_1 = require("../../../../../info");
7
+ const vertex_1 = require("../../../../../graph/vertex");
7
8
  const edge_1 = require("../../../../../graph/edge");
8
9
  const known_call_handling_1 = require("../known-call-handling");
9
10
  const control_flow_1 = require("../../../../control-flow");
@@ -64,12 +65,15 @@ function processLocal(name, args, rootId, data, config) {
64
65
  const resultEnvironment = envirResolution ? data.environment : (0, scoping_1.popLocalEnvironment)(dfExpr.environment);
65
66
  /* definitions of the local scope vanish with it, only what escaped it (e.g. via `<<-`) may bubble up */
66
67
  const escaping = envirResolution ? dfExpr.out : dfExpr.out.filter(o => o.name !== undefined && resolve_helper_1.Resolve.byNameAndType(o.name, resultEnvironment, o.type)?.some(d => d.nodeId === o.nodeId));
67
- for (const escaped of escaping) {
68
- dfExpr.graph.addEdge(escaped.nodeId, rootId, edge_1.EdgeType.Reads);
69
- }
70
68
  const ingoing = dfEnv.in.concat(dfExpr.in, dfEnv.unknownReferences, dfExpr.unknownReferences);
71
69
  ingoing.push({ nodeId: rootId, name: name.content, cds: data.cds, type: identifier_1.ReferenceType.Function });
72
70
  const graph = dfEnv.graph.mergeWith(dfExpr.graph);
71
+ /* the body only runs because `local` runs it */
72
+ for (const [id, vertex] of dfExpr.graph.vertices(false)) {
73
+ if (!vertex_1.DfgVertex.isUse(vertex) && !vertex_1.DfgVertex.isValue(vertex)) {
74
+ graph.addEdge(id, rootId, edge_1.EdgeType.Reads);
75
+ }
76
+ }
73
77
  const cfgEntry = control_flow_1.ControlFlow.inSequence(graph, env ? [dfEnv, dfExpr] : [dfExpr], rootId);
74
78
  const baseResult = {
75
79
  hooks: dfExpr.hooks.concat(dfEnv.hooks),
@@ -13,6 +13,7 @@ const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-
13
13
  const control_flow_1 = require("../../../../control-flow");
14
14
  const apply_kill_1 = require("../../../../../environments/apply-kill");
15
15
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
16
+ const built_in_ambient_state_1 = require("./built-in-ambient-state");
16
17
  /**
17
18
  * Process a built-in repeat loop function call like `repeat { ... }`.
18
19
  * @param name - The name of the function being called.
@@ -46,6 +47,7 @@ function processRepeatLoop(name, args, rootId, data) {
46
47
  const body = processedArguments[0];
47
48
  (0, assert_1.guard)(body !== undefined, () => `Repeat-Loop ${identifier_1.Identifier.toString(name.content)} has no body, impossible!`);
48
49
  (0, linker_1.linkCircularRedefinitionsWithinALoop)(information.graph, (0, linker_1.produceNameSharedIdMap)((0, linker_1.findNonLocalReads)(information.graph)), body.out, body.environment);
50
+ (0, built_in_ambient_state_1.linkAmbientStateWithinLoop)(information.graph, body.in.concat(body.unknownReferences), body);
49
51
  (0, linker_1.reapplyLoopExitPoints)(body.exitPoints, body.in.concat(body.out, body.unknownReferences), information.graph);
50
52
  information.exitPoints = (0, info_1.filterOutLoopExitPoints)(information.exitPoints);
51
53
  const graph = information.graph;
@@ -4,7 +4,7 @@ import type { RSymbol } from '../../../../../../r-bridge/lang-4.x/ast/model/node
4
4
  import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
5
5
  import type { DataflowInformation } from '../../../../../info';
6
6
  import type { DataflowProcessorInformation } from '../../../../../processor';
7
- import { type ClassArgRef, argFor } from '../../../../../fn/class-declaration';
7
+ import { type ClassArgRef } from '../../../../../fn/class-declaration';
8
8
  import { type Identifier } from '../../../../../environments/identifier';
9
9
  /** shorthand for the decorated-info generics every helper below carries through */
10
10
  type Data<O> = DataflowProcessorInformation<O & ParentInformation>;
@@ -15,12 +15,13 @@ export declare function s4ClassName(cls: string): Identifier;
15
15
  export interface S4UseConfig {
16
16
  /** the argument naming the S4 generic the call answers or asks about (`f` in `setMethod`) */
17
17
  readonly genericArg?: ClassArgRef;
18
+ /** appended to the generic named by {@link genericArg} (`setReplaceMethod("f", ...)` answers `f<-`) */
19
+ readonly genericSuffix?: string;
18
20
  /** the arguments naming S4 classes the call uses (`Class` in `new`, `signature` in `setMethod`) */
19
21
  readonly classArgs?: readonly ClassArgRef[];
20
22
  /** the argument naming an S4 class the call adds to without declaring it (`to` in `setAs`): read and registered anew, so a later use depends on this call as well as on the declaration */
21
23
  readonly registersArg?: ClassArgRef;
22
24
  }
23
- export { argFor };
24
25
  /** wires the S4 registrations a call *uses* (the classes and generic its arguments name by string), read against the registry so the call depends on whatever `setClass`/`setGeneric` wrote them */
25
26
  export declare function linkS4Uses<O>(info: DataflowInformation, args: Args<O>, rootId: NodeId, data: Data<O>, config: S4UseConfig): void;
26
27
  /** wires what the attached {@link DataflowGraphVertexFunctionCall.classDecl|class declaration} states, S4 only: a declaration reads the classes it builds on and registers its own name; a mere relation (`setIs`, `setValidity`) reads and re-registers the class it names */
@@ -29,3 +30,4 @@ export declare function linkS4Declaration<O>(info: DataflowInformation, rootId:
29
30
  export declare function linkS4Generic<O>(info: DataflowInformation, rootId: NodeId, names: readonly string[], data: Data<O>): void;
30
31
  /** Processes a call that consumes S4 registrations without declaring any, like `new("P")` or `getMethod("f", "P")`. */
31
32
  export declare function processS4Use<O>(name: RSymbol<O & ParentInformation>, args: Args<O>, rootId: NodeId, data: Data<O>, config: S4UseConfig): DataflowInformation;
33
+ export {};
@@ -1,6 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.argFor = void 0;
4
3
  exports.s4ClassName = s4ClassName;
5
4
  exports.linkS4Uses = linkS4Uses;
6
5
  exports.linkS4Declaration = linkS4Declaration;
@@ -9,7 +8,6 @@ exports.processS4Use = processS4Use;
9
8
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
10
9
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
11
10
  const class_declaration_1 = require("../../../../../fn/class-declaration");
12
- Object.defineProperty(exports, "argFor", { enumerable: true, get: function () { return class_declaration_1.argFor; } });
13
11
  const identifier_1 = require("../../../../../environments/identifier");
14
12
  const define_1 = require("../../../../../environments/define");
15
13
  const node_value_1 = require("../../../../../eval/resolve/node-value");
@@ -57,13 +55,13 @@ function defineOut(info, rootId, name, type, data) {
57
55
  /** wires the S4 registrations a call *uses* (the classes and generic its arguments name by string), read against the registry so the call depends on whatever `setClass`/`setGeneric` wrote them */
58
56
  function linkS4Uses(info, args, rootId, data, config) {
59
57
  for (const ref of config.classArgs ?? []) {
60
- readNames(info, rootId, namesOf((0, class_declaration_1.argFor)(args, ref), data).map(s4ClassName), identifier_1.ReferenceType.Variable, data);
58
+ readNames(info, rootId, namesOf((0, class_declaration_1.argForImpl)(args, ref), data).map(s4ClassName), identifier_1.ReferenceType.Variable, data);
61
59
  }
62
60
  if (config.genericArg !== undefined) {
63
- readNames(info, rootId, namesOf((0, class_declaration_1.argFor)(args, config.genericArg), data), identifier_1.ReferenceType.Function, data);
61
+ readNames(info, rootId, namesOf((0, class_declaration_1.argForImpl)(args, config.genericArg), data).map(n => n + (config.genericSuffix ?? '')), identifier_1.ReferenceType.Function, data);
64
62
  }
65
63
  if (config.registersArg !== undefined) {
66
- const registered = namesOf((0, class_declaration_1.argFor)(args, config.registersArg), data);
64
+ const registered = namesOf((0, class_declaration_1.argForImpl)(args, config.registersArg), data);
67
65
  readNames(info, rootId, registered.map(s4ClassName), identifier_1.ReferenceType.Variable, data);
68
66
  for (const cls of registered) {
69
67
  defineOut(info, rootId, s4ClassName(cls), identifier_1.ReferenceType.Variable, data);
@@ -19,6 +19,7 @@ const vertex_1 = require("../../../../../graph/vertex");
19
19
  const range_1 = require("../../../../../../util/range");
20
20
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
21
21
  const built_in_s_four_1 = require("./built-in-s-four");
22
+ const class_declaration_1 = require("../../../../../fn/class-declaration");
22
23
  const function_semantics_1 = require("../../../../../fn/function-semantics");
23
24
  /**
24
25
  * Process an S7 new generic dispatch call like `new_generic` or `setGeneric`.
@@ -102,7 +103,7 @@ function attachClassDeclaration(info, rootId, args, config) {
102
103
  }
103
104
  }
104
105
  function linkWrappedFunction(info, args, rootId, wrapIndex, wrapName, data) {
105
- const wrapped = (0, built_in_s_four_1.argFor)(args, { name: wrapName, idx: wrapIndex });
106
+ const wrapped = (0, class_declaration_1.argForImpl)(args, { name: wrapName, idx: wrapIndex });
106
107
  if (wrapped === undefined) {
107
108
  return;
108
109
  }
@@ -15,6 +15,8 @@ const range_1 = require("../../../../../../util/range");
15
15
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
16
16
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
17
17
  const control_flow_1 = require("../../../../control-flow");
18
+ const model_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/model");
19
+ const r_function_definition_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
18
20
  /**
19
21
  * Process an S3 dispatch call like `UseMethod`.
20
22
  */
@@ -57,6 +59,12 @@ function processS3Dispatch(name, args, rootId, data, config) {
57
59
  });
58
60
  const ingoing = dfObj.in.concat(dfObj.unknownReferences);
59
61
  ingoing.push({ nodeId: rootId, name: name.content, cds: data.cds, type: identifier_1.ReferenceType.Function });
62
+ /* the next method receives the current values of the formals of the method it is called from */
63
+ const idMap = data.completeAst.idMap;
64
+ const enclosing = idMap.get(model_1.RNode.findEnclosing(rootId, idMap, r_function_definition_1.RFunctionDefinition.is) ?? rootId);
65
+ for (const param of r_function_definition_1.RFunctionDefinition.is(enclosing) ? enclosing.parameters : []) {
66
+ ingoing.push({ nodeId: rootId, name: param.name.content, cds: data.cds, type: identifier_1.ReferenceType.Variable });
67
+ }
60
68
  const cfgEntry = control_flow_1.ControlFlow.inSequence(dfObj.graph, [dfObj], rootId);
61
69
  return {
62
70
  hooks: dfObj.hooks,
@@ -16,6 +16,7 @@ const apply_kill_1 = require("../../../../../environments/apply-kill");
16
16
  const append_1 = require("../../../../../environments/append");
17
17
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
18
18
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
19
+ const built_in_ambient_state_1 = require("./built-in-ambient-state");
19
20
  /**
20
21
  * Process a while loop like `while(cond) { ... }`.
21
22
  */
@@ -82,6 +83,7 @@ function processWhileLoop(name, args, rootId, data) {
82
83
  const remainingInputs = (0, linker_1.linkInputs)(bodyRead, information.environment, condition.in.concat(condition.unknownReferences), information.graph, true);
83
84
  (0, reference_to_maybe_1.applyCdToReferences)(body.out, cdTrue);
84
85
  (0, linker_1.linkCircularRedefinitionsWithinALoop)(information.graph, (0, linker_1.produceNameSharedIdMap)((0, linker_1.findNonLocalReads)(information.graph, new Set(condition.in.map(i => i.nodeId)))), body.out, body.environment);
86
+ (0, built_in_ambient_state_1.linkAmbientStateWithinLoop)(information.graph, bodyRead.concat(condition.in, condition.unknownReferences), body);
85
87
  (0, linker_1.reapplyLoopExitPoints)(body.exitPoints, body.in.concat(body.out, body.unknownReferences), information.graph);
86
88
  // as the while-loop always evaluates its condition
87
89
  information.graph.addEdge(nameId, condition.entryPoint, edge_1.EdgeType.Reads);
@@ -28,6 +28,8 @@ export interface ProcessAllArgumentInput<OtherInfo> {
28
28
  readonly markAsNSE?: readonly number[];
29
29
  /** symbols that name data rather than code, so they must not resolve to a function of the same name */
30
30
  readonly nonFunction?: ReadonlySet<NodeId>;
31
+ /** the arguments from this index on are alternatives of which at most one runs (the arms of `switch`) */
32
+ readonly alternativesFrom?: number;
31
33
  }
32
34
  export interface ProcessAllArgumentResult {
33
35
  readonly finalEnv: REnvironmentInformation;
@@ -56,7 +58,7 @@ export declare function isPipedArgument<OtherInfo>(arg: unknown, functionRootId:
56
58
  /**
57
59
  * Processes all arguments for a function call, updating the given final graph and environment.
58
60
  */
59
- export declare function processAllArguments<OtherInfo>({ functionName, args, data, finalGraph, functionRootId, forced, patchData, nonFunction }: ProcessAllArgumentInput<OtherInfo>): ProcessAllArgumentResult;
61
+ export declare function processAllArguments<OtherInfo>({ functionName, args, data, finalGraph, functionRootId, forced, patchData, nonFunction, alternativesFrom }: ProcessAllArgumentInput<OtherInfo>): ProcessAllArgumentResult;
60
62
  export interface PatchFunctionCallInput<OtherInfo> {
61
63
  readonly nextGraph: DataflowGraph;
62
64
  readonly rootId: NodeId;
@@ -16,6 +16,7 @@ const processor_1 = require("../../../../processor");
16
16
  const model_1 = require("../../../../../r-bridge/lang-4.x/ast/model/model");
17
17
  const r_function_call_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
18
18
  const identifier_1 = require("../../../../environments/identifier");
19
+ const built_in_ambient_state_1 = require("./built-in/built-in-ambient-state");
19
20
  const overwrite_1 = require("../../../../environments/overwrite");
20
21
  const resolve_by_name_1 = require("../../../../environments/resolve-by-name");
21
22
  const process_argument_1 = require("../process-argument");
@@ -23,6 +24,7 @@ const vertex_1 = require("../../../../graph/vertex");
23
24
  const edge_1 = require("../../../../graph/edge");
24
25
  const r_argument_1 = require("../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
25
26
  const vertex_2 = require("../../../../graph/vertex");
27
+ const append_1 = require("../../../../environments/append");
26
28
  function forceVertexArgumentValueReferences(rootId, value, graph, env) {
27
29
  const valueVertex = graph.getVertex(value.entryPoint);
28
30
  if (!valueVertex) {
@@ -95,15 +97,26 @@ function isPipedArgument(arg, functionRootId, data) {
95
97
  /**
96
98
  * Processes all arguments for a function call, updating the given final graph and environment.
97
99
  */
98
- function processAllArguments({ functionName, args, data, finalGraph, functionRootId, forced = [], patchData, nonFunction }) {
100
+ function processAllArguments({ functionName, args, data, finalGraph, functionRootId, forced = [], patchData, nonFunction, alternativesFrom }) {
99
101
  let finalEnv = functionName.environment;
100
102
  const callArgs = [];
101
103
  const processedArguments = [];
102
104
  const remainingReadInArgs = [];
103
105
  let i = -1;
106
+ /* each alternative starts from what holds before all of them, and what one of them defines only may hold afterward */
107
+ let beforeAlternatives;
108
+ let afterAlternatives;
104
109
  for (const arg of args) {
105
110
  i++;
111
+ if (alternativesFrom !== undefined && i >= alternativesFrom) {
112
+ beforeAlternatives ??= finalEnv;
113
+ finalEnv = beforeAlternatives;
114
+ }
106
115
  data = { ...data, environment: finalEnv };
116
+ if (beforeAlternatives !== undefined) {
117
+ /* whether an alternative runs depends on what the call picks */
118
+ data = { ...data, cds: [...data.cds ?? [], { id: functionRootId, when: true }] };
119
+ }
107
120
  data = patchData?.(data, i) ?? data;
108
121
  if (r_argument_1.RArgument.isEmpty(arg)) {
109
122
  callArgs.push(r_function_call_1.EmptyArgument);
@@ -129,6 +142,9 @@ function processAllArguments({ functionName, args, data, finalGraph, functionRoo
129
142
  }
130
143
  processedArguments.push(processed);
131
144
  finalEnv = (0, overwrite_1.overwriteEnvironment)(finalEnv, processed.environment);
145
+ if (beforeAlternatives !== undefined) {
146
+ afterAlternatives = (0, append_1.appendEnvironment)(afterAlternatives ?? beforeAlternatives, finalEnv);
147
+ }
132
148
  /* nothing reads the argument's own graph past this point, only its entry point and references */
133
149
  finalGraph.mergeWith(processed.graph, true, ownsGraph);
134
150
  // resolve reads within argument, we resolve before adding the `processed.environment` to avoid cyclic dependencies
@@ -139,8 +155,10 @@ function processAllArguments({ functionName, args, data, finalGraph, functionRoo
139
155
  /* a data argument holds a value, so a function of that name is not what it reads; the narrowed
140
156
  type stays on the reference as it bubbles through the enclosing calls */
141
157
  const ingoing = nonFunction?.has(inId) ? { ...original, type: identifier_1.ReferenceType.NonFunction } : original;
142
- const refType = vertex_2.DfgVertex.isFunctionCall(finalGraph.getVertex(inId)) ? identifier_1.ReferenceType.Function
143
- : ingoing.type === identifier_1.ReferenceType.NonFunction ? identifier_1.ReferenceType.NonFunction : identifier_1.ReferenceType.Unknown;
158
+ /* a call reading the options or graphics state (`#...`, see AmbientStateName) reads a variable, not itself */
159
+ const refType = built_in_ambient_state_1.AmbientStateName.is(ingoing.name) ? identifier_1.ReferenceType.Variable
160
+ : vertex_2.DfgVertex.isFunctionCall(finalGraph.getVertex(inId)) ? identifier_1.ReferenceType.Function
161
+ : ingoing.type === identifier_1.ReferenceType.NonFunction ? identifier_1.ReferenceType.NonFunction : identifier_1.ReferenceType.Unknown;
144
162
  const tryToResolve = ingoing.name ? (0, resolve_by_name_1.resolveByName)(ingoing.name, data.environment, refType) : undefined;
145
163
  if (tryToResolve === undefined) {
146
164
  remainingReadInArgs.push(ingoing);
@@ -171,7 +189,7 @@ function processAllArguments({ functionName, args, data, finalGraph, functionRoo
171
189
  }
172
190
  finalGraph.addEdge(functionRootId, processed.entryPoint, edge_1.EdgeType.Argument);
173
191
  }
174
- return { finalEnv, callArgs, remainingReadInArgs, processedArguments };
192
+ return { finalEnv: afterAlternatives ?? finalEnv, callArgs, remainingReadInArgs, processedArguments };
175
193
  }
176
194
  /**
177
195
  * Patches a function call vertex into the given dataflow graph.
@@ -8,6 +8,12 @@ export interface ForceSites {
8
8
  readonly sites: readonly NodeId[];
9
9
  /** the name the deferred expression is bound to, whose binding its own writes replace */
10
10
  readonly binding: NodeId;
11
+ /** what reaches the sites and what they reach, filled on first use and shared by everyone handed these sites */
12
+ readonly reach?: {
13
+ before?: ReadonlySet<NodeId>;
14
+ after?: ReadonlySet<NodeId>;
15
+ always?: Map<NodeId, boolean>;
16
+ };
11
17
  }
12
18
  /** Where a name is bound and where it is read, so that a deferred expression can reach either. */
13
19
  export interface NameIndex {