@eagleoutice/flowr 2.13.3 → 2.13.4

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 (67) hide show
  1. package/README.md +11 -11
  2. package/abstract-interpretation/absint-visitor.js +2 -2
  3. package/abstract-interpretation/data-frame/mappers/arguments.js +2 -2
  4. package/abstract-interpretation/data-frame/mappers/replacement-mapper.js +1 -1
  5. package/abstract-interpretation/unsupported-functions.js +1 -1
  6. package/control-flow/cfg-dead-code.js +72 -11
  7. package/control-flow/extract-cfg.js +85 -8
  8. package/control-flow/semantic-cfg-guided-visitor.js +2 -0
  9. package/dataflow/environments/built-in-proc-name.d.ts +4 -0
  10. package/dataflow/environments/built-in-proc-name.js +4 -0
  11. package/dataflow/environments/built-in.d.ts +5 -1
  12. package/dataflow/environments/built-in.js +5 -1
  13. package/dataflow/environments/default-builtin-config.d.ts +59 -4
  14. package/dataflow/environments/default-builtin-config.js +23 -11
  15. package/dataflow/environments/identifier.d.ts +1 -0
  16. package/dataflow/eval/resolve/alias-tracking.d.ts +2 -0
  17. package/dataflow/eval/resolve/alias-tracking.js +8 -1
  18. package/dataflow/eval/resolve/resolve.d.ts +14 -0
  19. package/dataflow/eval/resolve/resolve.js +47 -0
  20. package/dataflow/fn/higher-order-function.js +3 -3
  21. package/dataflow/fn/recursive-function.js +1 -1
  22. package/dataflow/graph/df-helper.js +1 -1
  23. package/dataflow/graph/vertex.d.ts +32 -25
  24. package/dataflow/graph/vertex.js +40 -36
  25. package/dataflow/internal/process/functions/call/built-in/built-in-access.d.ts +1 -0
  26. package/dataflow/internal/process/functions/call/built-in/built-in-access.js +7 -4
  27. package/dataflow/internal/process/functions/call/built-in/built-in-apply.d.ts +14 -0
  28. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +28 -29
  29. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +41 -48
  30. package/dataflow/internal/process/functions/call/built-in/built-in-class-generator.d.ts +14 -0
  31. package/dataflow/internal/process/functions/call/built-in/built-in-class-generator.js +45 -0
  32. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +7 -1
  33. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +29 -0
  34. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +62 -2
  35. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +63 -16
  36. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +29 -9
  37. package/dataflow/internal/process/functions/call/built-in/built-in-list.d.ts +5 -1
  38. package/dataflow/internal/process/functions/call/built-in/built-in-list.js +35 -0
  39. package/dataflow/internal/process/functions/call/built-in/built-in-new-env.js +2 -2
  40. package/dataflow/internal/process/functions/call/built-in/built-in-recall.js +1 -1
  41. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.d.ts +2 -0
  42. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +46 -0
  43. package/dataflow/internal/process/functions/call/built-in/built-in-stack-env.js +3 -1
  44. package/dataflow/internal/process/functions/call/unnamed-call-handling.js +24 -0
  45. package/dataflow/internal/process/functions/process-parameter.js +2 -1
  46. package/linter/rules/absolute-path.js +1 -1
  47. package/linter/rules/function-finder-util.js +1 -1
  48. package/linter/rules/no-leaked-credentials.js +1 -1
  49. package/linter/rules/undefined-symbol.js +1 -1
  50. package/linter/rules/unused-definition.js +15 -10
  51. package/linter/rules/useless-loop.js +1 -1
  52. package/package.json +1 -1
  53. package/queries/catalog/call-context-query/identify-link-to-last-call-relation.js +1 -1
  54. package/queries/catalog/call-context-query/identify-link-to-nested-call-relation.js +1 -1
  55. package/queries/catalog/dependencies-query/function-info/read-functions.js +1 -1
  56. package/queries/catalog/dependencies-query/function-info/write-functions.js +23 -24
  57. package/queries/catalog/input-sources-query/input-source-functions.d.ts +2 -1
  58. package/queries/catalog/input-sources-query/input-source-functions.js +14 -20
  59. package/queries/catalog/input-sources-query/input-sources-query-executor.js +11 -6
  60. package/queries/catalog/input-sources-query/input-sources-query-format.js +2 -1
  61. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +14 -1
  62. package/queries/catalog/input-sources-query/simple-input-classifier.js +24 -0
  63. package/r-bridge/data/data.d.ts +2 -2
  64. package/r-bridge/data/data.js +2 -2
  65. package/reconstruct/inline/source-inline-map.js +1 -1
  66. package/util/mermaid/dfg.js +1 -1
  67. package/util/version.js +1 -1
@@ -5,6 +5,20 @@ import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/
5
5
  import type { 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
7
  import type { MergeableRecord } from '../../../../../../util/objects';
8
+ import { type Identifier } from '../../../../../environments/identifier';
9
+ import type { RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model';
10
+ /** the function reference extracted from an argument passed to a higher-order call */
11
+ export interface ResolvedFunctionArgument {
12
+ readonly functionId: NodeId;
13
+ readonly functionName: Identifier;
14
+ readonly anonymous: boolean;
15
+ readonly asString: boolean;
16
+ }
17
+ /** Resolve the function an argument stands for: a string literal, a symbol, or an inline definition; `undefined` if none. */
18
+ export declare function resolveFunctionArgument<OtherInfo>(val: RNode<OtherInfo & ParentInformation>, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, opts: {
19
+ readonly unquoteFunction?: boolean;
20
+ readonly resolveValue?: boolean;
21
+ }): ResolvedFunctionArgument | undefined;
8
22
  export interface BuiltInApplyConfiguration extends MergeableRecord {
9
23
  /** the 0-based index of the argument which is the actual function passed, defaults to 1 */
10
24
  readonly indexOfFunction?: number;
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveFunctionArgument = resolveFunctionArgument;
3
4
  exports.processApply = processApply;
4
5
  const known_call_handling_1 = require("../known-call-handling");
5
6
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
@@ -7,15 +8,30 @@ const logger_1 = require("../../../../../logger");
7
8
  const type_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/type");
8
9
  const vertex_1 = require("../../../../../graph/vertex");
9
10
  const edge_1 = require("../../../../../graph/edge");
11
+ const unknown_side_effect_1 = require("../../../../../graph/unknown-side-effect");
10
12
  const identifier_1 = require("../../../../../environments/identifier");
11
13
  const resolve_by_name_1 = require("../../../../../environments/resolve-by-name");
12
14
  const unnamed_call_handling_1 = require("../unnamed-call-handling");
13
- const general_1 = require("../../../../../eval/values/general");
14
- const r_value_1 = require("../../../../../eval/values/r-value");
15
15
  const log_1 = require("../../../../../../util/log");
16
16
  const alias_tracking_1 = require("../../../../../eval/resolve/alias-tracking");
17
17
  const r_string_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-string");
18
18
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
19
+ /** Resolve the function an argument stands for: a string literal, a symbol, or an inline definition; `undefined` if none. */
20
+ function resolveFunctionArgument(val, data, opts) {
21
+ if (opts.unquoteFunction && r_string_1.RString.is(val)) {
22
+ return { functionId: val.info.id, functionName: val.content.str, anonymous: false, asString: true };
23
+ }
24
+ if (val.type === type_1.RType.FunctionDefinition) {
25
+ return { functionId: val.info.id, functionName: `${unnamed_call_handling_1.UnnamedFunctionCallPrefix}${val.info.id}`, anonymous: true, asString: false };
26
+ }
27
+ if (val.type !== type_1.RType.Symbol) {
28
+ return undefined;
29
+ }
30
+ const functionName = opts.resolveValue
31
+ ? (0, alias_tracking_1.resolveIdToSingleString)(val.info.id, { environment: data.environment, idMap: data.completeAst.idMap, resolve: data.ctx.config.solver.variables, ctx: data.ctx })
32
+ : val.content;
33
+ return functionName === undefined ? undefined : { functionId: val.info.id, functionName, anonymous: false, asString: false };
34
+ }
19
35
  /**
20
36
  * Process an apply call like `vapply` or `mapply`.
21
37
  */
@@ -60,39 +76,22 @@ function processApply(name, args, rootId, data, config) {
60
76
  const arg = args[index];
61
77
  if (arg === r_function_call_1.EmptyArgument || !arg.value || (!unquoteFunction && arg.value.type !== type_1.RType.Symbol && arg.value.type !== type_1.RType.FunctionDefinition)) {
62
78
  logger_1.dataflowLogger.warn(`Expected symbol as argument at index ${index}, but got ${JSON.stringify(arg)} instead.`);
79
+ (0, unknown_side_effect_1.handleUnknownSideEffect)(information.graph, information.environment, rootId);
63
80
  return information;
64
81
  }
65
- let functionId = undefined;
66
- let functionName = undefined;
67
- let anonymous = false;
68
82
  const val = arg.value;
69
- if (unquoteFunction && r_string_1.RString.is(val)) {
70
- functionId = val.info.id;
71
- functionName = val.content.str;
72
- information.in = [...information.in, { type: identifier_1.ReferenceType.Function, name: functionName, cds: data.cds, nodeId: functionId }];
73
- }
74
- else if (val.type === type_1.RType.Symbol) {
75
- functionId = val.info.id;
76
- if (resolveValue) {
77
- const resolved = (0, general_1.valueSetGuard)((0, alias_tracking_1.resolveIdToValue)(val.info.id, { environment: data.environment, idMap: data.completeAst.idMap, resolve: data.ctx.config.solver.variables, ctx: data.ctx }));
78
- if (resolved?.elements.length === 1 && resolved.elements[0].type === 'string') {
79
- const r = resolved.elements[0];
80
- functionName = (0, r_value_1.isValue)(r.value) ? r.value.str : undefined;
81
- }
82
- }
83
- else {
84
- functionName = val.content;
85
- }
86
- }
87
- else if (val.type === type_1.RType.FunctionDefinition) {
88
- anonymous = true;
89
- functionId = val.info.id;
90
- functionName = `${unnamed_call_handling_1.UnnamedFunctionCallPrefix}${functionId}`;
91
- }
92
- if (functionName === undefined || functionId === undefined) {
83
+ const resolvedFn = resolveFunctionArgument(val, data, { unquoteFunction, resolveValue });
84
+ if (resolvedFn === undefined) {
93
85
  logger_1.dataflowLogger.warn(`Expected symbol or string as function argument at index ${index}, but got ${JSON.stringify(val)} instead.`);
86
+ // the called function is dynamic and unresolvable: reached-but-unknown rather than dropped
87
+ (0, unknown_side_effect_1.handleUnknownSideEffect)(information.graph, information.environment, rootId);
94
88
  return information;
95
89
  }
90
+ const { functionName, anonymous, asString } = resolvedFn;
91
+ let functionId = resolvedFn.functionId;
92
+ if (asString) {
93
+ information.in = [...information.in, { type: identifier_1.ReferenceType.Function, name: functionName, cds: data.cds, nodeId: functionId }];
94
+ }
96
95
  const allOtherArguments = processedArguments.map((arg, i) => {
97
96
  const counterpart = args[i];
98
97
  if (arg && counterpart !== r_function_call_1.EmptyArgument) {
@@ -24,9 +24,10 @@ const named_call_handling_1 = require("../named-call-handling");
24
24
  const built_in_1 = require("../../../../../environments/built-in");
25
25
  const unknown_side_effect_1 = require("../../../../../graph/unknown-side-effect");
26
26
  const alias_tracking_1 = require("../../../../../eval/resolve/alias-tracking");
27
- const r_value_1 = require("../../../../../eval/values/r-value");
28
27
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
29
28
  const built_in_new_env_1 = require("./built-in-new-env");
29
+ const built_in_list_1 = require("./built-in-list");
30
+ const built_in_class_generator_1 = require("./built-in-class-generator");
30
31
  const built_in_stack_env_1 = require("./built-in-stack-env");
31
32
  function toReplacementSymbol(target, prefix, superAssignment) {
32
33
  return {
@@ -120,8 +121,31 @@ args, rootId, data, config) {
120
121
  return (0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, forceArgs: config.forceArgs, origin: 'default' }).information;
121
122
  }
122
123
  const { type, named } = target;
123
- if (type === type_1.RType.Symbol) {
124
- if (!config.targetVariable) {
124
+ if (type === type_1.RType.Symbol && !config.targetVariable) {
125
+ const res = (0, known_call_handling_1.processKnownFunctionCall)({
126
+ name,
127
+ args,
128
+ rootId,
129
+ data,
130
+ reverseOrder: !config.swapSourceAndTarget,
131
+ forceArgs: config.forceArgs,
132
+ origin: config.superAssignment ? built_in_proc_name_1.BuiltInProcName.SuperAssignment : built_in_proc_name_1.BuiltInProcName.Assignment
133
+ });
134
+ return processAssignmentToSymbol({
135
+ ...config,
136
+ nameOfAssignmentFunction: name.content,
137
+ source,
138
+ targetId: target.info.id,
139
+ args: getEffectiveOrder(config, res.processedArguments),
140
+ rootId,
141
+ data,
142
+ information: res.information,
143
+ });
144
+ }
145
+ else if (config.targetVariable && (type === type_1.RType.Symbol || type === type_1.RType.FunctionCall)) {
146
+ // the target expression (`assign(x, v)` / `assign(paste0("cfg_", k), v)`) resolving to a constant name defines that name, keeping the reads that produced it; a dynamic name falls through to the unknown-target handling below
147
+ const resolvedName = (0, built_in_envir_utils_1.resolveConstantString)(target, data);
148
+ if (resolvedName !== undefined) {
125
149
  const res = (0, known_call_handling_1.processKnownFunctionCall)({
126
150
  name,
127
151
  args,
@@ -136,41 +160,13 @@ args, rootId, data, config) {
136
160
  nameOfAssignmentFunction: name.content,
137
161
  source,
138
162
  targetId: target.info.id,
163
+ targetName: resolvedName,
139
164
  args: getEffectiveOrder(config, res.processedArguments),
140
165
  rootId,
141
166
  data,
142
167
  information: res.information,
143
168
  });
144
169
  }
145
- else {
146
- // try to resolve the variable first
147
- const n = (0, alias_tracking_1.resolveIdToValue)(target.info.id, { environment: data.environment, resolve: data.ctx.config.solver.variables, idMap: data.completeAst.idMap, full: true, ctx: data.ctx });
148
- if (n.type === 'set' && n.elements.length === 1 && n.elements[0].type === 'string') {
149
- const val = n.elements[0].value;
150
- if ((0, r_value_1.isValue)(val)) {
151
- const res = (0, known_call_handling_1.processKnownFunctionCall)({
152
- name,
153
- args,
154
- rootId,
155
- data,
156
- reverseOrder: !config.swapSourceAndTarget,
157
- forceArgs: config.forceArgs,
158
- origin: config.superAssignment ? built_in_proc_name_1.BuiltInProcName.SuperAssignment : built_in_proc_name_1.BuiltInProcName.Assignment
159
- });
160
- return processAssignmentToSymbol({
161
- ...config,
162
- nameOfAssignmentFunction: name.content,
163
- source,
164
- targetId: target.info.id,
165
- targetName: val.str,
166
- args: getEffectiveOrder(config, res.processedArguments),
167
- rootId,
168
- data,
169
- information: res.information,
170
- });
171
- }
172
- }
173
- }
174
170
  }
175
171
  else if (config.canBeReplacement && type === type_1.RType.FunctionCall && named) {
176
172
  /* as replacement functions take precedence over the lhs fn-call (i.e., `names(x) <- ...` is independent from the definition of `names`), we do not have to process the call */
@@ -306,7 +302,7 @@ function checkTargetReferenceType(sourceInfo, fnModes) {
306
302
  */
307
303
  function isEnvCreatorSource(sourceInfo) {
308
304
  const vert = sourceInfo.graph.getVertex(sourceInfo.entryPoint);
309
- return (0, vertex_1.isFunctionCallVertex)(vert) && vert.origin.includes(built_in_proc_name_1.BuiltInProcName.NewEnv);
305
+ return vertex_1.FunctionCallVertex.hasOrigin(vert, built_in_proc_name_1.BuiltInProcName.NewEnv);
310
306
  }
311
307
  /**
312
308
  * When `e$x <- val` and `e` holds a tracked {@link InGraphIdentifierDefinition#envState},
@@ -458,27 +454,24 @@ function processAssignmentToSymbol(config) {
458
454
  }
459
455
  else if (source.type === type_1.RType.Symbol) {
460
456
  const defs = (0, resolve_by_name_1.resolveByName)(source.content, data.environment, identifier_1.ReferenceType.Variable);
461
- const def = defs?.find((d) => d.envState !== undefined);
462
- envState = def?.envState;
463
- if (!envState) {
464
- const fnDef = defs?.find((d) => d.returnsEnvState !== undefined);
465
- if (fnDef?.returnsEnvState) {
466
- envState = fnDef.returnsEnvState;
467
- }
468
- }
457
+ envState = defs?.find((d) => d.envState !== undefined)?.envState
458
+ ?? (0, built_in_envir_utils_1.findReturnsEnvState)(defs);
469
459
  }
470
460
  else {
471
461
  const entryVertex = sourceArg.graph.getVertex(sourceArg.entryPoint);
472
- if ((0, vertex_1.isFunctionDefinitionVertex)(entryVertex) && entryVertex.returnEnvState !== undefined) {
462
+ if (vertex_1.FunctionCallVertex.hasOrigin(entryVertex, built_in_proc_name_1.BuiltInProcName.List)) {
463
+ envState = (0, built_in_list_1.resolveListToEnvState)(source, data);
464
+ }
465
+ else if (vertex_1.FunctionCallVertex.hasOrigin(entryVertex, built_in_proc_name_1.BuiltInProcName.ClassGenerator)) {
466
+ returnsEnvState = (0, built_in_class_generator_1.resolveClassMethodsToEnvState)(source, data);
467
+ }
468
+ else if (vertex_1.FunctionDefinitionVertex.is(entryVertex) && entryVertex.returnEnvState !== undefined) {
473
469
  returnsEnvState = entryVertex.returnEnvState;
474
470
  }
475
- else if ((0, vertex_1.isFunctionCallVertex)(entryVertex) && entryVertex.name) {
476
- const fnDefs = (0, resolve_by_name_1.resolveByName)(entryVertex.name, data.environment, identifier_1.ReferenceType.Function);
477
- const fnDef = fnDefs?.find((d) => d.returnsEnvState !== undefined);
478
- if (fnDef?.returnsEnvState) {
479
- envState = fnDef.returnsEnvState;
480
- }
471
+ else if (vertex_1.FunctionCallVertex.is(entryVertex) && entryVertex.name) {
472
+ envState = (0, built_in_envir_utils_1.findReturnsEnvState)((0, resolve_by_name_1.resolveByName)(entryVertex.name, data.environment, identifier_1.ReferenceType.Function));
481
473
  }
474
+ envState ??= (0, built_in_class_generator_1.resolveConstructorInstanceEnvState)(source, data);
482
475
  }
483
476
  if (envState) {
484
477
  for (let i = 0; i < writeNodes.length; i++) {
@@ -0,0 +1,14 @@
1
+ import { type PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
2
+ import type { RSymbol } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol';
3
+ import type { RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model';
4
+ import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/decorate';
5
+ import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
6
+ import type { DataflowInformation } from '../../../../../info';
7
+ import type { DataflowProcessorInformation } from '../../../../../processor';
8
+ import type { REnvironmentInformation } from '../../../../../environments/environment';
9
+ /** Processes an `R6Class`/`setRefClass` generator call, tagging it so the assignment layer can record its method list. */
10
+ export declare function processClassGenerator<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): DataflowInformation;
11
+ /** The method env of a class generator's `public`/`methods` `list(...)` (via {@link resolveListToEnvState}); `undefined` if absent. */
12
+ export declare function resolveClassMethodsToEnvState<OtherInfo>(source: RNode<OtherInfo & ParentInformation>, data: Pick<DataflowProcessorInformation<never>, 'environment'>): REnvironmentInformation | undefined;
13
+ /** The method env an instance from `<Cls>$new(...)`/`<Cls>[["new"]](...)` carries, from the generator's recorded `returnsEnvState`; `undefined` otherwise. */
14
+ export declare function resolveConstructorInstanceEnvState<OtherInfo>(source: RNode<OtherInfo & ParentInformation>, data: Pick<DataflowProcessorInformation<never>, 'environment'>): REnvironmentInformation | undefined;
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processClassGenerator = processClassGenerator;
4
+ exports.resolveClassMethodsToEnvState = resolveClassMethodsToEnvState;
5
+ exports.resolveConstructorInstanceEnvState = resolveConstructorInstanceEnvState;
6
+ const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
7
+ const known_call_handling_1 = require("../known-call-handling");
8
+ const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
9
+ const built_in_list_1 = require("./built-in-list");
10
+ const built_in_envir_utils_1 = require("./built-in-envir-utils");
11
+ const type_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/type");
12
+ const resolve_by_name_1 = require("../../../../../environments/resolve-by-name");
13
+ const identifier_1 = require("../../../../../environments/identifier");
14
+ /** R6's `public` / Reference Class's `methods` argument carrying the class generator's methods. */
15
+ const MethodListArguments = ['public', 'methods'];
16
+ /** Processes an `R6Class`/`setRefClass` generator call, tagging it so the assignment layer can record its method list. */
17
+ function processClassGenerator(name, args, rootId, data) {
18
+ return (0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, origin: built_in_proc_name_1.BuiltInProcName.ClassGenerator }).information;
19
+ }
20
+ /** The method env of a class generator's `public`/`methods` `list(...)` (via {@link resolveListToEnvState}); `undefined` if absent. */
21
+ function resolveClassMethodsToEnvState(source, data) {
22
+ if (!r_function_call_1.RFunctionCall.isNamed(source)) {
23
+ return undefined;
24
+ }
25
+ const methodList = source.arguments.find(arg => arg !== r_function_call_1.EmptyArgument && arg.name !== undefined && MethodListArguments.includes(arg.name.content));
26
+ return methodList && methodList !== r_function_call_1.EmptyArgument && methodList.value !== undefined ? (0, built_in_list_1.resolveListToEnvState)(methodList.value, data) : undefined;
27
+ }
28
+ const ConstructorField = 'new';
29
+ /** The method env an instance from `<Cls>$new(...)`/`<Cls>[["new"]](...)` carries, from the generator's recorded `returnsEnvState`; `undefined` otherwise. */
30
+ function resolveConstructorInstanceEnvState(source, data) {
31
+ if (source.type !== type_1.RType.FunctionCall || source.named) {
32
+ return undefined;
33
+ }
34
+ const callee = source.calledFunction;
35
+ if (callee.type !== type_1.RType.Access || (callee.operator !== '$' && callee.operator !== '[[') || callee.accessed.type !== type_1.RType.Symbol) {
36
+ return undefined;
37
+ }
38
+ const field = callee.access[0] === r_function_call_1.EmptyArgument ? undefined : callee.access[0]?.value;
39
+ const fieldName = field?.type === type_1.RType.String ? field.content.str : field?.lexeme;
40
+ if (fieldName !== ConstructorField) {
41
+ return undefined;
42
+ }
43
+ return (0, built_in_envir_utils_1.findReturnsEnvState)((0, resolve_by_name_1.resolveByName)(callee.accessed.content, data.environment, identifier_1.ReferenceType.Variable));
44
+ }
45
+ //# sourceMappingURL=built-in-class-generator.js.map
@@ -4,8 +4,10 @@ import type { DataflowInformation } from '../../../../../info';
4
4
  import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/decorate';
5
5
  import type { PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
6
6
  import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
7
- import type { Identifier, NamedInGraphIdentifierDefinition } from '../../../../../environments/identifier';
7
+ import type { IdentifierDefinition, NamedInGraphIdentifierDefinition } from '../../../../../environments/identifier';
8
+ import { Identifier } from '../../../../../environments/identifier';
8
9
  import type { REnvironmentInformation } from '../../../../../environments/environment';
10
+ import type { RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model';
9
11
  /** Result type for a successful envir-argument resolution. */
10
12
  export interface EnvirResolution<OtherInfo> {
11
13
  /** `data` with its `environment` replaced by the resolved `envState` for in-env lookups. */
@@ -32,6 +34,10 @@ export declare function bindArgs<OtherInfo>(args: readonly PotentiallyEmptyRArgu
32
34
  * instead of a hardcoded formal list, while staying correct -- and graph-invariant -- when no signature is available.
33
35
  */
34
36
  export declare function signatureParamNames<OtherInfo>(data: DataflowProcessorInformation<OtherInfo & ParentInformation>, id: Identifier, fallback: readonly string[]): readonly string[];
37
+ /** The constant string a name-position node denotes at construction time (string literal, aliased variable, or `paste`/`paste0` of such); `undefined` if any part is dynamic or the paste builtin is user-shadowed. */
38
+ export declare function resolveConstantString<OtherInfo>(node: RNode<OtherInfo & ParentInformation>, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): string | undefined;
39
+ /** The `returnsEnvState` of the first reaching definition that carries one, else `undefined`. */
40
+ export declare function findReturnsEnvState(defs: readonly IdentifierDefinition[] | undefined): REnvironmentInformation | undefined;
35
41
  /** Resolves a single already-found argument (e.g. from {@link bindArgs}) to an {@link EnvirResolution} when it is a symbol holding a tracked envState. */
36
42
  export declare function resolveArgToEnvir<OtherInfo>(arg: PotentiallyEmptyRArgument<OtherInfo & ParentInformation>, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): EnvirResolution<OtherInfo> | undefined;
37
43
  /** Resolves the `argName` argument (default `'envir'`, pmatch against `allParamNames`), falling back to `positionalFallbackIndex`, to an {@link EnvirResolution}. */
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.bindArgs = bindArgs;
4
4
  exports.signatureParamNames = signatureParamNames;
5
+ exports.resolveConstantString = resolveConstantString;
6
+ exports.findReturnsEnvState = findReturnsEnvState;
5
7
  exports.resolveArgToEnvir = resolveArgToEnvir;
6
8
  exports.resolveEnvirArg = resolveEnvirArg;
7
9
  exports.resolveSymbolToEnvir = resolveSymbolToEnvir;
@@ -18,6 +20,7 @@ const environment_1 = require("../../../../../environments/environment");
18
20
  const prefix_1 = require("../../../../../../util/prefix");
19
21
  const built_in_stack_env_1 = require("./built-in-stack-env");
20
22
  const alias_tracking_1 = require("../../../../../eval/resolve/alias-tracking");
23
+ const resolve_1 = require("../../../../../eval/resolve/resolve");
21
24
  const general_1 = require("../../../../../eval/values/general");
22
25
  const logger_1 = require("../../../../../logger");
23
26
  /** A tracked env is a real stack environment (not a private custom env) when its current layer is the global or the built-in/base env. */
@@ -77,6 +80,32 @@ function signatureParamNames(data, id, fallback) {
77
80
  const names = sig ? (0, decode_1.signatureParameterNames)(sig) : [];
78
81
  return names.length > 0 ? names : fallback;
79
82
  }
83
+ /** The constant string a name-position node denotes at construction time (string literal, aliased variable, or `paste`/`paste0` of such); `undefined` if any part is dynamic or the paste builtin is user-shadowed. */
84
+ function resolveConstantString(node, data) {
85
+ const info = { environment: data.environment, idMap: data.completeAst.idMap, resolve: data.ctx.config.solver.variables, ctx: data.ctx, full: true };
86
+ const unshadowed = new Map();
87
+ const fold = (n) => {
88
+ if (!r_function_call_1.RFunctionCall.isNamed(n)) {
89
+ return (0, alias_tracking_1.resolveIdToSingleString)(n.info.id, info);
90
+ }
91
+ const fnName = identifier_1.Identifier.getName(n.functionName.content);
92
+ if (fnName !== 'paste0' && fnName !== 'paste') {
93
+ return undefined;
94
+ }
95
+ let ok = unshadowed.get(fnName);
96
+ if (ok === undefined) {
97
+ const defs = (0, resolve_by_name_1.resolveByName)(n.functionName.content, data.environment, identifier_1.ReferenceType.Function);
98
+ ok = defs === undefined || defs.every(d => (0, identifier_1.isReferenceType)(d.type, identifier_1.ReferenceType.BuiltInFunction));
99
+ unshadowed.set(fnName, ok);
100
+ }
101
+ return ok ? (0, resolve_1.foldPasteCall)(n, fold) : undefined;
102
+ };
103
+ return fold(node);
104
+ }
105
+ /** The `returnsEnvState` of the first reaching definition that carries one, else `undefined`. */
106
+ function findReturnsEnvState(defs) {
107
+ return defs?.find((d) => d.returnsEnvState !== undefined)?.returnsEnvState;
108
+ }
80
109
  /** Resolves a single already-found argument (e.g. from {@link bindArgs}) to an {@link EnvirResolution} when it is a symbol holding a tracked envState. */
81
110
  function resolveArgToEnvir(arg, data) {
82
111
  if (arg === r_function_call_1.EmptyArgument) {
@@ -62,13 +62,73 @@ function linkReadNameToWriteIfPossible(read, environments, listEnvironments, rem
62
62
  }
63
63
  }
64
64
  }
65
+ /**
66
+ * Expands the directly-called function definitions (`direct`) with those they transitively call (resolved by name in
67
+ * `resolveEnv`). A sibling/outer callee is invisible inside its caller's (clean) body, so its escaped globals never fold
68
+ * into the caller's subflow; pulling them here lets a super-assignment escaping through several call levels reach the
69
+ * outer read. Escapes are folded popped to the fold level, so a write binding an intermediate frame stops there.
70
+ * Package attachments keep their own (lazy) propagation, so transitive callees only contribute their `<<-` escapes.
71
+ */
72
+ function* transitivelyCalledDefinitions(initial, graph, resolveEnv) {
73
+ const seen = new Set();
74
+ const stack = initial.map(fn => ({ fn, direct: true }));
75
+ while (stack.length > 0) {
76
+ const { fn, direct } = stack.pop();
77
+ if (fn.tag !== vertex_1.VertexType.FunctionDefinition || seen.has(fn.id)) {
78
+ continue;
79
+ }
80
+ seen.add(fn.id);
81
+ yield { fn, direct };
82
+ for (const nodeId of fn.subflow.graph) {
83
+ const call = graph.getVertex(nodeId);
84
+ if (call?.tag !== vertex_1.VertexType.FunctionCall || call.onlyBuiltin || call.name === undefined) {
85
+ continue;
86
+ }
87
+ const resolved = (0, resolve_by_name_1.resolveByName)(call.name, resolveEnv, identifier_1.ReferenceType.Function);
88
+ if (resolved === undefined) {
89
+ continue;
90
+ }
91
+ const [targets] = (0, linker_1.getAllLinkedFunctionDefinitions)(new Set(resolved.map(r => r.nodeId)), graph);
92
+ for (const target of targets) {
93
+ if (!seen.has(target.id)) {
94
+ stack.push({ fn: target, direct: false });
95
+ }
96
+ }
97
+ }
98
+ }
99
+ }
100
+ /** Rebuilds `env` without its attached-package/namespace layers (`t !== undefined`), keeping only the lexical frames a `<<-` can bind. */
101
+ function withoutPackageLayers(env) {
102
+ let builtIn = env.current;
103
+ const core = [];
104
+ let hasPackage = false;
105
+ while (!builtIn.builtInEnv) {
106
+ if (builtIn.t === undefined) {
107
+ core.push(builtIn);
108
+ }
109
+ else {
110
+ hasPackage = true;
111
+ }
112
+ builtIn = builtIn.parent;
113
+ }
114
+ if (!hasPackage) {
115
+ return env;
116
+ }
117
+ let parent = builtIn;
118
+ for (let i = core.length - 1; i >= 0; i--) {
119
+ const cloned = core[i].clone(false);
120
+ cloned.parent = parent;
121
+ parent = cloned;
122
+ }
123
+ return { current: parent, level: env.level };
124
+ }
65
125
  function updateSideEffectsForCalledFunctions(calledEnvs, inputEnvironment, nextGraph, localDefs) {
66
126
  for (const { functionCall, called } of calledEnvs) {
67
127
  let callDependencies = null;
68
- for (const calledFn of called) {
128
+ for (const { fn: calledFn, direct } of transitivelyCalledDefinitions(called, nextGraph, inputEnvironment)) {
69
129
  (0, assert_1.guard)(calledFn.tag === vertex_1.VertexType.FunctionDefinition, 'called function must be a function definition');
70
130
  // only merge the environments they have in common
71
- let environment = calledFn.subflow.environment;
131
+ let environment = direct ? calledFn.subflow.environment : withoutPackageLayers(calledFn.subflow.environment);
72
132
  while (environment.level > inputEnvironment.level) {
73
133
  environment = (0, scoping_1.popLocalEnvironment)(environment);
74
134
  }
@@ -42,6 +42,7 @@ function processFunctionDefinition(name, args, rootId, data) {
42
42
  data = prepareFunctionEnvironment(data, rootId);
43
43
  const subgraph = new graph_1.DataflowGraph(data.completeAst.idMap);
44
44
  let readInParameters = [];
45
+ const allParameterReads = [];
45
46
  const paramIds = [];
46
47
  for (const param of parameters) {
47
48
  (0, assert_1.guard)(param !== r_function_call_1.EmptyArgument, () => `Empty param arg in function definition ${identifier_1.Identifier.toString(name.content)}, ${JSON.stringify(args)}`);
@@ -51,6 +52,7 @@ function processFunctionDefinition(name, args, rootId, data) {
51
52
  }
52
53
  subgraph.mergeWith(processed.graph);
53
54
  const read = processed.in.concat(processed.unknownReferences);
55
+ allParameterReads.push(...read);
54
56
  (0, linker_1.linkInputs)(read, data.environment, readInParameters, subgraph, false);
55
57
  data.environment = (0, overwrite_1.overwriteEnvironment)(data.environment, processed.environment);
56
58
  }
@@ -95,7 +97,15 @@ function processFunctionDefinition(name, args, rootId, data) {
95
97
  // As we know, parameters cannot technically duplicate (i.e., their names are unique), we overwrite their environments.
96
98
  // This is the correct behavior, even if someone uses non-`=` arguments in functions.
97
99
  const bodyEnvironment = body.environment;
98
- readInParameters = findPromiseLinkagesForParameters(subgraph, readInParameters, paramsEnvironments, body);
100
+ // a default read (e.g. `function(x, y = x)`) may also see a later body reassignment, as the default is a promise
101
+ const writesByName = groupBodyWrites(body.out);
102
+ const unresolvedParamReads = new Set(readInParameters);
103
+ for (const read of allParameterReads) {
104
+ if (read.name && !unresolvedParamReads.has(read)) {
105
+ linkParameterReadToBodyWrites(subgraph, read, writesByName);
106
+ }
107
+ }
108
+ readInParameters = findPromiseLinkagesForParameters(subgraph, readInParameters, paramsEnvironments, writesByName);
99
109
  const readInBody = body.in.concat(body.unknownReferences);
100
110
  // there is no uncertainty regarding the arguments, as if a function header is executed, so is its body
101
111
  const remainingRead = (0, linker_1.linkInputs)(readInBody, paramsEnvironments, readInParameters.slice(), body.graph, true /* functions do not have to be called */);
@@ -115,7 +125,7 @@ function processFunctionDefinition(name, args, rootId, data) {
115
125
  (0, linker_1.linkCircularRedefinitionsWithinALoop)(body.graph, nameIdShares, globalBodyOut);
116
126
  }
117
127
  subgraph.mergeWith(body.graph);
118
- const outEnvironment = (0, overwrite_1.overwriteEnvironment)(paramsEnvironments, bodyEnvironment);
128
+ let outEnvironment = (0, overwrite_1.overwriteEnvironment)(paramsEnvironments, bodyEnvironment);
119
129
  for (const read of remainingRead) {
120
130
  if (read.name) {
121
131
  subgraph.addVertex({
@@ -128,6 +138,18 @@ function processFunctionDefinition(name, args, rootId, data) {
128
138
  }
129
139
  const compactedHooks = (0, hooks_1.compactHookStates)(body.hooks);
130
140
  const exitHooks = (0, hooks_1.getHookInformation)(compactedHooks, hooks_1.KnownHooks.OnFnExit);
141
+ // an on.exit hook's `<<-` escapes like a body `<<-`; fold its escaping writes into this function's subflow
142
+ for (const hook of exitHooks) {
143
+ const vert = subgraph.getVertex(hook.id);
144
+ if (vert?.tag !== vertex_1.VertexType.FunctionDefinition) {
145
+ continue;
146
+ }
147
+ let hookEnvironment = vert.subflow.environment;
148
+ while (hookEnvironment.level > outEnvironment.level) {
149
+ hookEnvironment = (0, scoping_1.popLocalEnvironment)(hookEnvironment);
150
+ }
151
+ outEnvironment = (0, overwrite_1.overwriteEnvironment)(outEnvironment, hookEnvironment);
152
+ }
131
153
  const flow = {
132
154
  unknownReferences: [],
133
155
  in: remainingRead,
@@ -175,7 +197,7 @@ function processFunctionDefinition(name, args, rootId, data) {
175
197
  if (data.ctx.config.solver.trackEnvironments) {
176
198
  for (const ep of afterHookExitPoints) {
177
199
  const epVertex = subgraph.getVertex(ep.nodeId);
178
- if ((0, vertex_1.isFunctionCallVertex)(epVertex) && epVertex.origin.includes(built_in_proc_name_1.BuiltInProcName.NewEnv)) {
200
+ if (vertex_1.FunctionCallVertex.is(epVertex) && epVertex.origin.includes(built_in_proc_name_1.BuiltInProcName.NewEnv)) {
179
201
  returnEnvState = (0, built_in_new_env_1.createFreshEnvState)(data, { graph: subgraph, entryPoint: ep.nodeId });
180
202
  break;
181
203
  }
@@ -445,7 +467,43 @@ function prepareFunctionEnvironment(data, rootId) {
445
467
  * <p>
446
468
  * <b>Currently we may be unable to narrow down every definition within the body as we have not implemented ways to track what covers the first definitions precisely</b>
447
469
  */
448
- function findPromiseLinkagesForParameters(parameters, readInParameters, parameterEnvs, body) {
470
+ /** Links a parameter default read to the body writes of the same name (may), returning whether any was linked. */
471
+ /** Groups body writes by name, each list sorted by descending id (so the lowest id is last), for `linkParameterReadToBodyWrites`. */
472
+ function groupBodyWrites(out) {
473
+ const byName = new Map();
474
+ for (const o of out) {
475
+ if (o.name === undefined) {
476
+ continue;
477
+ }
478
+ const writes = byName.get(o.name);
479
+ if (writes === undefined) {
480
+ byName.set(o.name, [o]);
481
+ }
482
+ else {
483
+ writes.push(o);
484
+ }
485
+ }
486
+ for (const writes of byName.values()) {
487
+ writes.sort((a, b) => String(a.nodeId) < String(b.nodeId) ? 1 : -1);
488
+ }
489
+ return byName;
490
+ }
491
+ function linkParameterReadToBodyWrites(graph, read, writesByName) {
492
+ const writingOuts = read.name === undefined ? undefined : writesByName.get(read.name);
493
+ if (writingOuts === undefined) {
494
+ return false;
495
+ }
496
+ if (writingOuts[0].cds === undefined) {
497
+ graph.addEdge(read.nodeId, writingOuts[0].nodeId, edge_1.EdgeType.Reads);
498
+ }
499
+ else {
500
+ for (const { nodeId } of writingOuts) {
501
+ graph.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
502
+ }
503
+ }
504
+ return true;
505
+ }
506
+ function findPromiseLinkagesForParameters(parameters, readInParameters, parameterEnvs, writesByName) {
449
507
  // first, we try to bind again within parameters - if we have it, fine
450
508
  const remainingRead = [];
451
509
  for (const read of readInParameters) {
@@ -458,19 +516,8 @@ function findPromiseLinkagesForParameters(parameters, readInParameters, paramete
458
516
  continue;
459
517
  }
460
518
  // If not resolved, link all outs within the body as potential reads.
461
- // Regarding the sort, we can ignore equality as nodeIds are unique.
462
- // We sort to get the lowest id - if it is an 'always' flag, we can safely use it instead of all of them.
463
- const writingOuts = body.out.filter(o => o.name === read.name).sort((a, b) => String(a.nodeId) < String(b.nodeId) ? 1 : -1);
464
- if (writingOuts.length === 0) {
519
+ if (!linkParameterReadToBodyWrites(parameters, read, writesByName)) {
465
520
  remainingRead.push(read);
466
- continue;
467
- }
468
- if (writingOuts[0].cds === undefined) {
469
- parameters.addEdge(rid, writingOuts[0].nodeId, edge_1.EdgeType.Reads);
470
- continue;
471
- }
472
- for (const { nodeId } of writingOuts) {
473
- parameters.addEdge(rid, nodeId, edge_1.EdgeType.Reads);
474
521
  }
475
522
  }
476
523
  return remainingRead;