@eagleoutice/flowr 2.15.10 → 2.16.0

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 (181) hide show
  1. package/README.md +23 -26
  2. package/abstract-interpretation/data-frame/arguments.js +11 -7
  3. package/control-flow/happens-before.d.ts +5 -0
  4. package/control-flow/happens-before.js +48 -34
  5. package/control-flow/useless-loop.d.ts +1 -1
  6. package/control-flow/useless-loop.js +29 -42
  7. package/dataflow/environments/built-in-props.d.ts +9 -0
  8. package/dataflow/environments/built-in-props.js +25 -19
  9. package/dataflow/environments/built-in.d.ts +2 -2
  10. package/dataflow/environments/built-in.js +41 -77
  11. package/dataflow/environments/default-builtin-config.d.ts +181 -29
  12. package/dataflow/environments/default-builtin-config.js +38 -24
  13. package/dataflow/environments/environment.d.ts +6 -4
  14. package/dataflow/environments/environment.js +54 -121
  15. package/dataflow/environments/identifier.d.ts +4 -2
  16. package/dataflow/environments/identifier.js +23 -69
  17. package/dataflow/environments/reference-to-maybe.d.ts +9 -0
  18. package/dataflow/environments/reference-to-maybe.js +23 -51
  19. package/dataflow/environments/resolve-by-name.js +37 -76
  20. package/dataflow/eval/resolve/resolve-argument.d.ts +3 -1
  21. package/dataflow/eval/resolve/resolve-argument.js +61 -64
  22. package/dataflow/eval/resolve/resolve-working-directory.d.ts +8 -2
  23. package/dataflow/eval/resolve/resolve-working-directory.js +12 -20
  24. package/dataflow/eval/resolve/resolve.d.ts +4 -0
  25. package/dataflow/eval/resolve/resolve.js +23 -14
  26. package/dataflow/extractor.js +176 -59
  27. package/dataflow/fn/class-declaration.d.ts +8 -2
  28. package/dataflow/fn/class-declaration.js +96 -97
  29. package/dataflow/fn/exceptions-of-function.js +68 -37
  30. package/dataflow/fn/frame-reflection.d.ts +12 -4
  31. package/dataflow/fn/frame-reflection.js +51 -41
  32. package/dataflow/fn/function-props.js +15 -33
  33. package/dataflow/fn/function-semantics.d.ts +11 -3
  34. package/dataflow/fn/function-semantics.js +6 -0
  35. package/dataflow/fn/higher-order-function.js +13 -17
  36. package/dataflow/fn/strict-function.d.ts +13 -0
  37. package/dataflow/fn/strict-function.js +285 -122
  38. package/dataflow/graph/call-graph.d.ts +7 -6
  39. package/dataflow/graph/call-graph.js +35 -46
  40. package/dataflow/graph/graph.d.ts +6 -1
  41. package/dataflow/graph/graph.js +57 -66
  42. package/dataflow/info.d.ts +8 -1
  43. package/dataflow/info.js +24 -30
  44. package/dataflow/internal/control-flow.d.ts +31 -4
  45. package/dataflow/internal/control-flow.js +61 -39
  46. package/dataflow/internal/linker.d.ts +15 -9
  47. package/dataflow/internal/linker.js +253 -241
  48. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +80 -14
  49. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +446 -78
  50. package/dataflow/internal/process/functions/call/built-in/built-in-apply.d.ts +3 -1
  51. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +51 -48
  52. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +2 -2
  53. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +119 -185
  54. package/dataflow/internal/process/functions/call/built-in/built-in-class-generator.js +7 -9
  55. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.d.ts +1 -1
  56. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +122 -147
  57. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.js +55 -25
  58. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +289 -251
  59. package/dataflow/internal/process/functions/call/built-in/built-in-get.d.ts +1 -1
  60. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +30 -32
  61. package/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.js +68 -67
  62. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +72 -126
  63. package/dataflow/internal/process/functions/call/built-in/built-in-local.d.ts +1 -3
  64. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +10 -10
  65. package/dataflow/internal/process/functions/call/built-in/built-in-quote.d.ts +4 -4
  66. package/dataflow/internal/process/functions/call/built-in/built-in-quote.js +9 -35
  67. package/dataflow/internal/process/functions/call/built-in/built-in-rm.js +8 -3
  68. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.d.ts +1 -1
  69. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.js +12 -28
  70. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.d.ts +1 -1
  71. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +40 -118
  72. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.d.ts +1 -3
  73. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.js +16 -24
  74. package/dataflow/internal/process/functions/call/built-in/built-in-source.d.ts +2 -0
  75. package/dataflow/internal/process/functions/call/built-in/built-in-source.js +93 -102
  76. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.d.ts +7 -3
  77. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.js +173 -114
  78. package/dataflow/internal/process/functions/call/built-in/built-in-while-loop.d.ts +1 -3
  79. package/dataflow/internal/process/functions/call/built-in/built-in-while-loop.js +22 -27
  80. package/dataflow/internal/process/functions/call/built-in/built-in-with.d.ts +1 -1
  81. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +34 -9
  82. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.d.ts +1 -1
  83. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +119 -93
  84. package/dataflow/internal/process/functions/call/common.d.ts +1 -3
  85. package/dataflow/internal/process/functions/call/common.js +36 -76
  86. package/dataflow/internal/process/functions/call/deferred.d.ts +6 -2
  87. package/dataflow/internal/process/functions/call/deferred.js +54 -57
  88. package/dataflow/internal/process/functions/call/known-call-handling.d.ts +4 -2
  89. package/dataflow/internal/process/functions/call/known-call-handling.js +65 -68
  90. package/dataflow/internal/process/functions/call/named-call-handling.d.ts +3 -5
  91. package/dataflow/internal/process/functions/call/named-call-handling.js +35 -21
  92. package/dataflow/internal/process/functions/call/quoted.d.ts +2 -0
  93. package/dataflow/internal/process/functions/call/quoted.js +162 -172
  94. package/dataflow/internal/process/functions/call/unnamed-call-handling.js +17 -38
  95. package/dataflow/internal/process/functions/process-parameter.js +25 -32
  96. package/dataflow/internal/process/process-symbol.js +3 -6
  97. package/dataflow/internal/program-order.d.ts +26 -0
  98. package/dataflow/internal/program-order.js +49 -0
  99. package/documentation/wiki-setup.js +23 -0
  100. package/linter/linter-rules.d.ts +17 -8
  101. package/linter/rules/absolute-path.js +63 -87
  102. package/linter/rules/file-path-validity.d.ts +4 -2
  103. package/linter/rules/file-path-validity.js +114 -80
  104. package/linter/rules/namespace-access.js +21 -33
  105. package/linter/rules/naming-convention.d.ts +1 -1
  106. package/linter/rules/naming-convention.js +60 -48
  107. package/linter/rules/network-functions.js +11 -7
  108. package/linter/rules/no-leaked-credentials.js +15 -18
  109. package/linter/rules/problematic-inputs.d.ts +2 -1
  110. package/linter/rules/problematic-inputs.js +39 -59
  111. package/linter/rules/roxygen-arguments.d.ts +9 -4
  112. package/linter/rules/roxygen-arguments.js +29 -48
  113. package/linter/rules/seeded-randomness.d.ts +7 -4
  114. package/linter/rules/seeded-randomness.js +128 -89
  115. package/linter/rules/stop-with-call-arg.d.ts +4 -2
  116. package/linter/rules/stop-with-call-arg.js +25 -22
  117. package/linter/rules/unclosed-connection.js +31 -24
  118. package/linter/rules/undefined-symbol.d.ts +4 -6
  119. package/linter/rules/undefined-symbol.js +58 -75
  120. package/linter/rules/unescaped-arguments.js +18 -44
  121. package/linter/rules/unused-definition.d.ts +6 -0
  122. package/linter/rules/unused-definition.js +105 -145
  123. package/linter/rules/unused-import.d.ts +3 -0
  124. package/linter/rules/unused-import.js +25 -43
  125. package/package.json +5 -2
  126. package/project/flowr-analyzer.js +6 -2
  127. package/project/plugins/file-plugins/files/flowr-jupyter-file.d.ts +2 -2
  128. package/project/plugins/file-plugins/files/flowr-jupyter-file.js +8 -12
  129. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.d.ts +7 -5
  130. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +34 -56
  131. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +16 -41
  132. package/queries/base-query-format.js +1 -2
  133. package/queries/catalog/absint-query/absint-query-format.js +1 -1
  134. package/queries/catalog/dataflow-query/dataflow-query-executor.js +2 -2
  135. package/queries/catalog/dataflow-query/dataflow-query-format.d.ts +2 -0
  136. package/queries/catalog/dataflow-query/dataflow-query-format.js +4 -7
  137. package/queries/catalog/dependencies-query/dependencies-query-executor.js +50 -114
  138. package/queries/catalog/dependencies-query/function-info/library-functions.d.ts +5 -9
  139. package/queries/catalog/dependencies-query/function-info/library-functions.js +6 -0
  140. package/queries/catalog/dependencies-query/function-info/read-functions.js +1 -1
  141. package/queries/catalog/dependencies-query/function-info/write-functions.js +7 -3
  142. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +4 -4
  143. package/queries/catalog/input-sources-query/simple-input-classifier.js +192 -301
  144. package/r-bridge/lang-4.x/ast/model/model.d.ts +3 -1
  145. package/r-bridge/lang-4.x/ast/model/model.js +19 -43
  146. package/r-bridge/lang-4.x/ast/model/nodes/r-access.d.ts +1 -0
  147. package/r-bridge/lang-4.x/ast/model/nodes/r-argument.d.ts +3 -0
  148. package/r-bridge/lang-4.x/ast/model/nodes/r-argument.js +5 -12
  149. package/r-bridge/lang-4.x/ast/model/nodes/r-binary-op.d.ts +1 -0
  150. package/r-bridge/lang-4.x/ast/model/nodes/r-break.d.ts +1 -0
  151. package/r-bridge/lang-4.x/ast/model/nodes/r-comment.d.ts +1 -0
  152. package/r-bridge/lang-4.x/ast/model/nodes/r-expression-list.d.ts +1 -0
  153. package/r-bridge/lang-4.x/ast/model/nodes/r-for-loop.d.ts +1 -0
  154. package/r-bridge/lang-4.x/ast/model/nodes/r-function-call.d.ts +1 -0
  155. package/r-bridge/lang-4.x/ast/model/nodes/r-function-definition.d.ts +1 -0
  156. package/r-bridge/lang-4.x/ast/model/nodes/r-if-then-else.d.ts +1 -0
  157. package/r-bridge/lang-4.x/ast/model/nodes/r-line-directive.d.ts +1 -0
  158. package/r-bridge/lang-4.x/ast/model/nodes/r-logical.d.ts +1 -0
  159. package/r-bridge/lang-4.x/ast/model/nodes/r-next.d.ts +1 -0
  160. package/r-bridge/lang-4.x/ast/model/nodes/r-number.d.ts +1 -0
  161. package/r-bridge/lang-4.x/ast/model/nodes/r-parameter.d.ts +1 -0
  162. package/r-bridge/lang-4.x/ast/model/nodes/r-pipe.d.ts +1 -0
  163. package/r-bridge/lang-4.x/ast/model/nodes/r-repeat-loop.d.ts +1 -0
  164. package/r-bridge/lang-4.x/ast/model/nodes/r-string.d.ts +1 -0
  165. package/r-bridge/lang-4.x/ast/model/nodes/r-symbol.d.ts +1 -0
  166. package/r-bridge/lang-4.x/ast/model/nodes/r-unary-op.d.ts +1 -0
  167. package/r-bridge/lang-4.x/ast/model/nodes/r-while-loop.d.ts +1 -0
  168. package/r-bridge/roxygen2/roxygen-parse.js +28 -42
  169. package/r-bridge/shell.js +6 -0
  170. package/search/search-executor/search-enrichers.js +25 -37
  171. package/slicing/static/slice-call.d.ts +4 -3
  172. package/slicing/static/slice-call.js +56 -88
  173. package/slicing/static/static-slicer.js +115 -79
  174. package/slicing/static/visiting-queue.d.ts +4 -6
  175. package/slicing/static/visiting-queue.js +9 -13
  176. package/util/proc.js +2 -1
  177. package/util/r-base-packages.d.ts +2 -0
  178. package/util/r-base-packages.js +23 -13
  179. package/util/text/playground-link.d.ts +12 -3
  180. package/util/text/playground-link.js +18 -27
  181. package/util/version.js +4 -10
@@ -18,19 +18,21 @@ const r_symbol_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/
18
18
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
19
19
  const node_id_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id");
20
20
  const model_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/model");
21
+ const program_order_1 = require("../../../../program-order");
21
22
  const graph_1 = require("../../../../../graph/graph");
22
23
  const identifier_1 = require("../../../../../environments/identifier");
23
24
  const overwrite_1 = require("../../../../../environments/overwrite");
24
25
  const vertex_1 = require("../../../../../graph/vertex");
26
+ const class_declaration_1 = require("../../../../../fn/class-declaration");
25
27
  const built_in_new_env_1 = require("./built-in-new-env");
26
28
  const scoping_1 = require("../../../../../environments/scoping");
27
29
  const edge_1 = require("../../../../../graph/edge");
28
- const log_1 = require("../../../../../../util/log");
29
30
  const built_in_library_1 = require("./built-in-library");
30
31
  const r_number_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-number");
31
32
  const hooks_1 = require("../../../../../hooks");
32
33
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
33
34
  const resolve_helper_1 = require("../../../../../environments/resolve-helper");
35
+ const built_in_ambient_state_1 = require("./built-in-ambient-state");
34
36
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
35
37
  const r_function_definition_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
36
38
  const r_parameter_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-parameter");
@@ -38,6 +40,10 @@ const r_string_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/
38
40
  const query_fn_props_1 = require("../../../../../environments/query-fn-props");
39
41
  const built_in_props_1 = require("../../../../../environments/built-in-props");
40
42
  const arrays_1 = require("../../../../../../util/collections/arrays");
43
+ const group_generics_1 = require("../../../../../environments/group-generics");
44
+ const arg_matching_1 = require("../../../../../../util/arg-matching");
45
+ const defaultmap_1 = require("../../../../../../util/collections/defaultmap");
46
+ const frame_reflection_1 = require("../../../../../fn/frame-reflection");
41
47
  /**
42
48
  * Process a function definition, i.e., `function(a, b) { ... }`
43
49
  */
@@ -51,9 +57,10 @@ function processFunctionDefinition(name, args, rootId, data) {
51
57
  const bodyArg = (0, unpack_argument_1.unpackNonameArg)(args.at(-1));
52
58
  (0, assert_1.guard)(bodyArg !== undefined, () => `Function Definition ${JSON.stringify(args)} has no body! This is bad!`);
53
59
  const originalEnvironment = data.environment;
60
+ const idMap = data.completeAst.idMap;
54
61
  // within a function def we do not pass on the outer binds as they could be overwritten when called
55
62
  data = prepareFunctionEnvironment(data, rootId);
56
- const subgraph = new graph_1.DataflowGraph(data.completeAst.idMap);
63
+ const subgraph = new graph_1.DataflowGraph(idMap);
57
64
  let readInParameters = [];
58
65
  const allParameterReads = [];
59
66
  const paramIds = [];
@@ -65,7 +72,7 @@ function processFunctionDefinition(name, args, rootId, data) {
65
72
  if (r_parameter_1.RParameter.is(param.value)) {
66
73
  paramIds.push(param.value.name.info.id);
67
74
  }
68
- subgraph.mergeWith(processed.graph);
75
+ subgraph.mergeWith(processed.graph, true, true);
69
76
  const read = processed.in.concat(processed.unknownReferences);
70
77
  allParameterReads.push(...read);
71
78
  (0, linker_1.linkInputs)(read, data.environment, readInParameters, subgraph, false);
@@ -74,48 +81,28 @@ function processFunctionDefinition(name, args, rootId, data) {
74
81
  const paramsEnvironments = data.environment;
75
82
  const body = (0, processor_1.processDataflowFor)(bodyArg, data);
76
83
  for (const [, v] of body.graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
77
- if (!v.origin.includes(built_in_proc_name_1.BuiltInProcName.Rm)) {
78
- continue;
79
- }
80
- const ea = v.args.find(a => a !== r_function_call_1.EmptyArgument && graph_1.FunctionArgument.isNamed(a) && a.name === 'envir');
81
- if (!ea || !graph_1.FunctionArgument.isNamed(ea)) {
82
- continue;
83
- }
84
- const offset = parseSysFrameOffset(data.completeAst.idMap.get(ea.valueId ?? ea.nodeId));
84
+ const envir = v.origin.includes(built_in_proc_name_1.BuiltInProcName.Rm) ? v.args.find(a => graph_1.FunctionArgument.hasName(a, 'envir')) : undefined;
85
+ const offset = envir && parseSysFrameOffset(idMap.get(envir.valueId ?? envir.nodeId));
85
86
  if (offset === undefined || offset > 0) {
86
87
  continue;
87
88
  }
88
- const names = [];
89
- for (const a of v.args) {
90
- if (a === r_function_call_1.EmptyArgument || (graph_1.FunctionArgument.isNamed(a) && a.name === 'envir')) {
91
- continue;
92
- }
93
- const node = data.completeAst.idMap.get(graph_1.FunctionArgument.isNamed(a) ? (a.valueId ?? a.nodeId) : a.nodeId);
94
- if (r_string_1.RString.is(node)) {
95
- names.push(node.content.str);
96
- }
97
- else if (r_symbol_1.RSymbol.is(node)) {
98
- names.push(node.content);
99
- }
100
- }
101
89
  const targetLevel = offset === 0 ? 0 : originalEnvironment.level + 1 + offset;
102
90
  let targetEnv = originalEnvironment;
103
91
  while (targetEnv.level > targetLevel && targetEnv.level > 0) {
104
92
  targetEnv = (0, scoping_1.popLocalEnvironment)(targetEnv);
105
93
  }
106
- if (targetEnv.level === targetLevel) {
107
- for (const n of names) {
108
- targetEnv.current.remove(n);
109
- }
94
+ if (targetEnv.level !== targetLevel) {
95
+ continue;
96
+ }
97
+ for (const removed of namesRemovedBy(v, idMap)) {
98
+ targetEnv.current.remove(removed);
110
99
  }
111
100
  }
112
- // parameter names are unique, so overwriting their environments here is correct even with non-`=` arguments
113
- const bodyEnvironment = body.environment;
114
101
  // a default read (e.g. `function(x, y = x)`) may also see a later body reassignment, as the default is a promise
115
102
  const writesByName = groupBodyWrites(body.out);
116
103
  const unresolvedParamReads = new Set(readInParameters);
117
104
  for (const read of allParameterReads) {
118
- if (read.name && !unresolvedParamReads.has(read)) {
105
+ if (!unresolvedParamReads.has(read)) {
119
106
  linkParameterReadToBodyWrites(subgraph, read, writesByName);
120
107
  }
121
108
  }
@@ -124,26 +111,20 @@ function processFunctionDefinition(name, args, rootId, data) {
124
111
  // there is no uncertainty regarding the arguments, as if a function header is executed, so is its body
125
112
  const remainingRead = (0, linker_1.linkInputs)(readInBody, paramsEnvironments, readInParameters.slice(), body.graph, true /* functions do not have to be called */);
126
113
  // functions can be called multiple times, so a global effect must link as if executed in a loop
127
- /* theoretically, we should just check if there is a global effect-write somewhere within */
128
114
  if (remainingRead.length > 0) {
129
115
  const nameIdShares = (0, linker_1.produceNameSharedIdMap)(remainingRead);
130
- const definedInLocalEnvironment = new Set(bodyEnvironment.current.memory.values().flatMap(defs => defs.map(d => d.nodeId)));
116
+ const definedInLocalEnvironment = new Set(body.environment.current.memory.values().flatMap(defs => defs.map(d => d.nodeId)));
131
117
  // everything in body.out but not within the local environment populated for the function scope is a potential escape (global definition)
132
118
  const globalBodyOut = body.out.filter(d => !definedInLocalEnvironment.has(d.nodeId));
133
119
  (0, linker_1.linkCircularRedefinitionsWithinALoop)(body.graph, nameIdShares, globalBodyOut);
134
120
  }
135
- subgraph.mergeWith(body.graph);
121
+ subgraph.mergeWith(body.graph, true, true);
136
122
  for (const param of parameters) {
137
123
  const parameter = param !== r_function_call_1.EmptyArgument && r_parameter_1.RParameter.is(param.value) ? param.value : undefined;
138
124
  if (parameter?.defaultValue === undefined) {
139
125
  continue;
140
126
  }
141
- const forcedAt = [];
142
- for (const [reader, edge] of subgraph.edgesTo(parameter.name.info.id)) {
143
- if (edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Reads)) {
144
- forcedAt.push(reader);
145
- }
146
- }
127
+ const forcedAt = (0, frame_reflection_1.edgeSources)(subgraph, parameter.name.info.id, edge_1.EdgeType.Reads);
147
128
  model_1.RNode.visitAst(parameter.defaultValue, inner => {
148
129
  if (r_symbol_1.RSymbol.is(inner) && vertex_1.DfgVertex.isUse(subgraph.getVertex(inner.info.id))
149
130
  && linkParameterReadToBodyWrites(subgraph, { nodeId: inner.info.id, name: inner.content, cds: undefined, type: identifier_1.ReferenceType.Variable }, writesByName)) {
@@ -154,7 +135,8 @@ function processFunctionDefinition(name, args, rootId, data) {
154
135
  return false;
155
136
  });
156
137
  }
157
- let outEnvironment = (0, overwrite_1.overwriteEnvironment)(paramsEnvironments, bodyEnvironment);
138
+ // parameter names are unique, so overwriting their environments here is correct even with non-`=` arguments
139
+ let outEnvironment = (0, overwrite_1.overwriteEnvironment)(paramsEnvironments, body.environment);
158
140
  for (const read of remainingRead) {
159
141
  if (read.name) {
160
142
  subgraph.addVertex({
@@ -166,18 +148,36 @@ function processFunctionDefinition(name, args, rootId, data) {
166
148
  }
167
149
  }
168
150
  const compactedHooks = (0, hooks_1.compactHookStates)(body.hooks);
169
- const exitHooks = (0, hooks_1.getHookInformation)(compactedHooks, hooks_1.KnownHooks.OnFnExit);
170
- // an on.exit hook's `<<-` escapes like a body `<<-`; fold its escaping writes into this function's subflow
171
- for (const hook of exitHooks) {
151
+ /* a jump in a default leaves the function from where the parameter is first used */
152
+ const exitPoints = body.exitPoints.concat(processedParameters.flatMap(p => p.exitPoints.filter(e => e.type !== 0 /* ExitPointType.Default */)));
153
+ let afterHookExitPoints = exitPoints.filter(e => e.type === 1 /* ExitPointType.Return */ || e.type === 0 /* ExitPointType.Default */ || e.type === 4 /* ExitPointType.Error */);
154
+ for (const hook of (0, hooks_1.getHookInformation)(compactedHooks, hooks_1.KnownHooks.OnFnExit)) {
172
155
  const vert = subgraph.getVertex(hook.id);
173
156
  if (!vertex_1.DfgVertex.isFunctionDefinition(vert)) {
174
157
  continue;
175
158
  }
159
+ /* an on.exit hook's `<<-` escapes like a body `<<-` */
160
+ for (const read of vert.subflow.in) {
161
+ for (const { nodeId } of resolve_helper_1.Resolve.byName(read.name, outEnvironment) ?? []) {
162
+ if (subgraph.hasVertex(nodeId)) {
163
+ subgraph.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
164
+ }
165
+ }
166
+ if (built_in_ambient_state_1.AmbientStateName.is(read.name)) {
167
+ remainingRead.push(read);
168
+ }
169
+ }
176
170
  let hookEnvironment = vert.subflow.environment;
177
171
  while (hookEnvironment.level > outEnvironment.level) {
178
172
  hookEnvironment = (0, scoping_1.popLocalEnvironment)(hookEnvironment);
179
173
  }
180
174
  outEnvironment = (0, overwrite_1.overwriteEnvironment)(outEnvironment, hookEnvironment);
175
+ /* the jumps and errors of an exit hook overrule the exit points of the body */
176
+ subgraph.addEdge(rootId, hook.id, edge_1.EdgeType.Calls);
177
+ const hookExitPoints = vert.exitPoints.filter(e => e.type === 1 /* ExitPointType.Return */ || e.type === 4 /* ExitPointType.Error */);
178
+ if (hookExitPoints.length > 0) {
179
+ afterHookExitPoints = (0, info_1.overwriteExitPoints)(afterHookExitPoints, hookExitPoints);
180
+ }
181
181
  }
182
182
  const flowEntry = control_flow_1.ControlFlow.inSequence(subgraph, processedParameters, control_flow_1.ControlFlow.entryOf(body)) ?? control_flow_1.ControlFlow.entryOf(body);
183
183
  const flow = {
@@ -194,7 +194,7 @@ function processFunctionDefinition(name, args, rootId, data) {
194
194
  if (r_argument_1.RArgument.isEmpty(p)) {
195
195
  return r_function_call_1.EmptyArgument;
196
196
  }
197
- else if (!p.name && p.value && r_parameter_1.RParameter.is(p.value)) {
197
+ else if (!p.name && r_parameter_1.RParameter.is(p.value)) {
198
198
  return { type: identifier_1.ReferenceType.Argument, cds: data.cds, nodeId: p.value.name.info.id, name: p.value.name.content, valueId: p.value.defaultValue?.info.id };
199
199
  }
200
200
  else if (p.name) {
@@ -203,59 +203,16 @@ function processFunctionDefinition(name, args, rootId, data) {
203
203
  else {
204
204
  return r_function_call_1.EmptyArgument;
205
205
  }
206
- }), data.completeAst.idMap);
207
- updateNestedFunctionClosures(subgraph, outEnvironment, name.info.id, remainingRead);
208
- const exitPoints = body.exitPoints;
206
+ }), idMap);
207
+ updateNestedFunctionClosures(subgraph, outEnvironment, remainingRead);
209
208
  const readParams = {};
210
209
  for (const paramId of paramIds) {
211
- const ingoing = subgraph.ingoingEdges(paramId);
212
- readParams[paramId] = ingoing?.values().some(e => edge_1.DfEdge.includesType(e, edge_1.EdgeType.Reads)) ?? false;
213
- }
214
- let afterHookExitPoints = exitPoints?.filter(e => e.type === 1 /* ExitPointType.Return */ || e.type === 0 /* ExitPointType.Default */ || e.type === 4 /* ExitPointType.Error */) ?? [];
215
- for (const hook of exitHooks) {
216
- const vert = subgraph.getVertex(hook.id);
217
- if (!vertex_1.DfgVertex.isFunctionDefinition(vert)) {
218
- continue;
219
- }
220
- // call all hooks
221
- subgraph.addEdge(rootId, hook.id, edge_1.EdgeType.Calls);
222
- const hookExitPoints = vert.exitPoints.filter(e => e.type === 1 /* ExitPointType.Return */ || e.type === 4 /* ExitPointType.Error */);
223
- if (hookExitPoints.length > 0) {
224
- afterHookExitPoints = (0, info_1.overwriteExitPoints)(afterHookExitPoints, hookExitPoints);
225
- }
210
+ readParams[paramId] = (0, frame_reflection_1.edgeSources)(subgraph, paramId, edge_1.EdgeType.Reads).length > 0;
226
211
  }
227
- let returnEnvState;
228
- if (data.ctx.config.solver.trackEnvironments) {
229
- for (const ep of afterHookExitPoints) {
230
- const epVertex = subgraph.getVertex(ep.nodeId);
231
- if (vertex_1.DfgVertex.hasOrigin(epVertex, built_in_proc_name_1.BuiltInProcName.NewEnv)) {
232
- returnEnvState = (0, built_in_new_env_1.createFreshEnvState)(data, { graph: subgraph, entryPoint: ep.nodeId });
233
- break;
234
- }
235
- const epNode = subgraph.idMap?.get(ep.nodeId);
236
- if (vertex_1.DfgVertex.hasOrigin(epVertex, built_in_proc_name_1.BuiltInProcName.List) && epNode !== undefined) {
237
- returnEnvState = (0, built_in_list_1.resolveListToEnvState)(epNode, { environment: outEnvironment });
238
- if (returnEnvState) {
239
- break;
240
- }
241
- }
242
- if (vertex_1.DfgVertex.hasOrigin(epVertex, built_in_proc_name_1.BuiltInProcName.ClassGenerator) && epNode !== undefined) {
243
- returnEnvState = (0, built_in_class_generator_1.resolveClassMethodsToEnvState)(epNode, { environment: outEnvironment });
244
- if (returnEnvState) {
245
- break;
246
- }
247
- }
248
- if (r_symbol_1.RSymbol.is(epNode)) {
249
- const defs = resolve_helper_1.Resolve.byNameAndType(epNode.content, outEnvironment, identifier_1.ReferenceType.Variable);
250
- const def = defs?.find(identifier_1.hasEnvState);
251
- if (def?.envState) {
252
- returnEnvState = def.envState;
253
- break;
254
- }
255
- }
256
- }
257
- }
258
- const graph = new graph_1.DataflowGraph(data.completeAst.idMap).mergeWith(subgraph, false);
212
+ const returnEnvState = data.ctx.config.solver.trackEnvironments
213
+ ? afterHookExitPoints.values().map(({ nodeId }) => envStateReturnedAt(nodeId, subgraph, outEnvironment, data)).find(assert_1.isNotUndefined)
214
+ : undefined;
215
+ const graph = new graph_1.DataflowGraph(idMap).mergeWith(subgraph, false, true);
259
216
  graph.addVertex({
260
217
  tag: vertex_1.VertexType.FunctionDefinition,
261
218
  id: name.info.id,
@@ -267,7 +224,6 @@ function processFunctionDefinition(name, args, rootId, data) {
267
224
  returnEnvState
268
225
  }, data.ctx.env.cleanEnv);
269
226
  return {
270
- /* nothing escapes a function definition, but the function itself, will be forced in assignment: { nodeId: functionDefinition.info.id, scope: data.activeScope, used: 'always', name: functionDefinition.info.id as string } */
271
227
  unknownReferences: [],
272
228
  in: [],
273
229
  out: [],
@@ -280,18 +236,35 @@ function processFunctionDefinition(name, args, rootId, data) {
280
236
  hooks: []
281
237
  };
282
238
  }
239
+ /** The tracked environment state returned at `nodeId`: a fresh `new.env()`, a list or class generator of methods, or a variable holding one. */
240
+ function envStateReturnedAt(nodeId, graph, outEnvironment, data) {
241
+ const vertex = graph.getVertex(nodeId);
242
+ if (vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.NewEnv)) {
243
+ return (0, built_in_new_env_1.createFreshEnvState)(data, { graph, entryPoint: nodeId });
244
+ }
245
+ const node = graph.idMap?.get(nodeId);
246
+ if (node === undefined) {
247
+ return undefined;
248
+ }
249
+ const environment = { environment: outEnvironment };
250
+ const fromList = vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.List) ? (0, built_in_list_1.resolveListToEnvState)(node, environment) : undefined;
251
+ if (fromList) {
252
+ return fromList;
253
+ }
254
+ const fromClass = vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.ClassGenerator) ? (0, built_in_class_generator_1.resolveClassMethodsToEnvState)(node, environment) : undefined;
255
+ if (fromClass) {
256
+ return fromClass;
257
+ }
258
+ return r_symbol_1.RSymbol.is(node) ? resolve_helper_1.Resolve.byNameAndType(node.content, outEnvironment, identifier_1.ReferenceType.Variable)?.find(identifier_1.hasEnvState)?.envState : undefined;
259
+ }
283
260
  /** Retrieve the active environment when entering a function definition or call. */
284
261
  function retrieveActiveEnvironment(callerEnvironment, baseEnvironment, ctx) {
285
262
  callerEnvironment ??= ctx.env.makeCleanEnv();
286
- let level = callerEnvironment.level ?? 0;
287
- if (baseEnvironment.level !== level) {
288
- while (baseEnvironment.level < level) {
289
- baseEnvironment = (0, scoping_1.pushLocalEnvironment)(baseEnvironment);
290
- }
291
- while (baseEnvironment.level > level) {
292
- callerEnvironment = (0, scoping_1.pushLocalEnvironment)(callerEnvironment);
293
- level = callerEnvironment.level;
294
- }
263
+ while (baseEnvironment.level < callerEnvironment.level) {
264
+ baseEnvironment = (0, scoping_1.pushLocalEnvironment)(baseEnvironment);
265
+ }
266
+ while (baseEnvironment.level > callerEnvironment.level) {
267
+ callerEnvironment = (0, scoping_1.pushLocalEnvironment)(callerEnvironment);
295
268
  }
296
269
  return (0, overwrite_1.overwriteEnvironment)(baseEnvironment, callerEnvironment);
297
270
  }
@@ -300,75 +273,61 @@ function retrieveActiveEnvironment(callerEnvironment, baseEnvironment, ctx) {
300
273
  * the object itself (`UseMethod("f", y)`), in which case that argument carries the read already.
301
274
  */
302
275
  function dispatchesOnFirstParameter(id, idMap) {
303
- let node = idMap.get(id);
304
- while (node !== undefined && !r_function_call_1.RFunctionCall.is(node)) {
305
- node = node.info.parent !== undefined ? idMap.get(node.info.parent) : undefined;
306
- }
307
- return node === undefined || (node.arguments?.length ?? 0) <= 1;
276
+ const enclosing = model_1.RNode.findEnclosing(id, idMap, r_function_call_1.RFunctionCall.is);
277
+ const call = enclosing === undefined ? undefined : idMap.get(enclosing);
278
+ return !r_function_call_1.RFunctionCall.is(call) || call.arguments.length <= 1;
308
279
  }
309
280
  function updateDispatches(graph, myArgs, idMap) {
310
281
  for (const [, info] of graph.vertices(false)) {
311
- if (!vertex_1.DfgVertex.isFunctionCall(info) || (!info.origin.includes(built_in_proc_name_1.BuiltInProcName.S3Dispatch) && !info.origin.includes(built_in_proc_name_1.BuiltInProcName.S7Dispatch))) {
282
+ const isDispatch = vertex_1.DfgVertex.isFunctionCall(info)
283
+ && (info.origin.includes(built_in_proc_name_1.BuiltInProcName.S3Dispatch) || info.origin.includes(built_in_proc_name_1.BuiltInProcName.S7Dispatch));
284
+ if (!isDispatch || info.args.length > 0) {
312
285
  continue;
313
286
  }
314
- if (info.args.length === 0) {
315
- info.args = myArgs;
316
- /* dispatch evaluates the object to know its class, whatever the method it picks does with it */
317
- let dispatchesOn = dispatchesOnFirstParameter(info.id, idMap);
318
- for (const arg of myArgs) {
319
- // add argument edges
320
- if (arg !== r_function_call_1.EmptyArgument) {
321
- graph.addEdge(info.id, arg.nodeId, dispatchesOn ? edge_1.EdgeType.Argument | edge_1.EdgeType.Reads : edge_1.EdgeType.Argument);
322
- dispatchesOn = false;
323
- }
287
+ info.args = myArgs;
288
+ /* dispatch evaluates the object to know its class, whatever the method it picks does with it */
289
+ let dispatchesOn = dispatchesOnFirstParameter(info.id, idMap);
290
+ for (const arg of myArgs) {
291
+ if (arg !== r_function_call_1.EmptyArgument) {
292
+ graph.addEdge(info.id, arg.nodeId, dispatchesOn ? edge_1.EdgeType.Argument | edge_1.EdgeType.Reads : edge_1.EdgeType.Argument);
293
+ dispatchesOn = false;
324
294
  }
325
295
  }
326
296
  }
327
297
  }
328
298
  /**
329
- * Resolves `refs` (open reads of a nested definition/call `openRefId`, closing over `closureId`) against `environment`;
299
+ * Resolves `refs` (open reads of a nested definition or call) against `environment`;
330
300
  * `onResolved` handles each resolved reference and says whether it should stay in the returned "still open" list.
331
301
  */
332
- function resolveIngoingRefs(refs, environment, openRefId, closureId, onResolved) {
333
- const remainingIn = [];
334
- for (const ingoing of refs) {
302
+ function resolveIngoingRefs(refs, environment, onResolved) {
303
+ return refs.filter(ingoing => {
335
304
  const resolved = ingoing.name ? resolve_helper_1.Resolve.byNameAndType(ingoing.name, environment, ingoing.type) : undefined;
336
- if (resolved === undefined) {
337
- remainingIn.push(ingoing);
338
- continue;
339
- }
340
- (0, log_1.expensiveTrace)(logger_1.dataflowLogger, () => `Found ${resolved.length} references to open ref ${openRefId} in closure of function definition ${closureId}`);
341
- if (onResolved(ingoing, resolved)) {
342
- remainingIn.push(ingoing);
343
- }
344
- }
345
- (0, log_1.expensiveTrace)(logger_1.dataflowLogger, () => `Keeping ${remainingIn.length} references to open ref ${openRefId} in closure of function definition ${closureId}`);
346
- return remainingIn;
305
+ return resolved === undefined || onResolved(ingoing, resolved);
306
+ });
347
307
  }
348
- function updateNestedFunctionClosures(graph, outEnvironment, fnId, openReads) {
308
+ function updateNestedFunctionClosures(graph, outEnvironment, openReads) {
349
309
  const open = new Set(openReads.map(r => r.nodeId));
350
310
  const settled = new Set();
351
- const superWrites = superAssignedInFrame(graph);
311
+ const superWrites = new defaultmap_1.DefaultMap(() => []);
312
+ for (const [, { subflow }] of graph.verticesOfType(vertex_1.VertexType.FunctionDefinition)) {
313
+ for (const [target, name] of superAssignedTargets(graph, subflow.graph)) {
314
+ superWrites.get(name).push(target);
315
+ }
316
+ }
352
317
  // track *all* function definitions, including those nested within, resolving their 'in' via the lowest scope (popped after this definition)
353
- for (const [id, { subflow }] of graph.verticesOfType(vertex_1.VertexType.FunctionDefinition)) {
354
- subflow.in = resolveIngoingRefs(subflow.in, outEnvironment, id, fnId, (ingoing, resolved) => {
355
- const writes = (ingoing.name !== undefined ? superWrites.get(ingoing.name) : undefined) ?? [];
356
- let allBuiltIn = true;
357
- let allClosureWrites = true;
318
+ for (const [, { subflow }] of graph.verticesOfType(vertex_1.VertexType.FunctionDefinition)) {
319
+ subflow.in = resolveIngoingRefs(subflow.in, outEnvironment, (ingoing, resolved) => {
320
+ const writes = superWrites.get(ingoing.name);
358
321
  for (const ref of resolved) {
359
322
  graph.addEdge(ingoing.nodeId, ref.nodeId, edge_1.EdgeType.Reads);
360
- if (!(0, identifier_1.isReferenceType)(ref.type, identifier_1.ReferenceType.BuiltInConstant | identifier_1.ReferenceType.BuiltInFunction)) {
361
- allBuiltIn = false;
362
- }
363
- if (!writes.includes(ref.nodeId)) {
364
- allClosureWrites = false;
365
- }
366
323
  }
367
324
  for (const write of writes) {
368
325
  if (write !== ingoing.nodeId) {
369
326
  graph.addEdge(ingoing.nodeId, write, edge_1.EdgeType.Reads);
370
327
  }
371
328
  }
329
+ const allBuiltIn = resolved.every(ref => (0, identifier_1.isReferenceType)(ref.type, identifier_1.ReferenceType.BuiltInConstant | identifier_1.ReferenceType.BuiltInFunction));
330
+ const allClosureWrites = resolved.every(ref => writes.includes(ref.nodeId));
372
331
  if (allBuiltIn && resolved.length > 0 && !allClosureWrites) {
373
332
  settled.add(ingoing.nodeId);
374
333
  }
@@ -380,56 +339,24 @@ function updateNestedFunctionClosures(graph, outEnvironment, fnId, openReads) {
380
339
  openReads.push(ref);
381
340
  }
382
341
  }
383
- linkSuperAssignmentsToOuterDefinitions(graph, subflow.graph, outEnvironment);
384
- }
385
- }
386
- function superAssignedInFrame(graph) {
387
- const written = new Map();
388
- for (const [, { subflow }] of graph.verticesOfType(vertex_1.VertexType.FunctionDefinition)) {
389
- for (const nodeId of subflow.graph) {
390
- if (!vertex_1.DfgVertex.hasOrigin(graph.getVertex(nodeId), built_in_proc_name_1.BuiltInProcName.SuperAssignment)) {
391
- continue;
392
- }
393
- for (const [targetId, edge] of graph.edgesFrom(nodeId)) {
394
- const target = graph.idMap?.get(targetId);
395
- if (edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Returns) && vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(targetId)) && r_symbol_1.RSymbol.is(target)) {
396
- written.set(target.content, [...(written.get(target.content) ?? []), targetId]);
342
+ for (const [target, name] of superAssignedTargets(graph, subflow.graph)) {
343
+ for (const { nodeId } of resolve_helper_1.Resolve.byNameAndType(name, outEnvironment, identifier_1.ReferenceType.Variable) ?? []) {
344
+ if (nodeId !== target && !node_id_1.NodeId.isBuiltIn(nodeId)) {
345
+ graph.addEdge(target, nodeId, edge_1.EdgeType.Reads);
397
346
  }
398
347
  }
399
348
  }
400
349
  }
401
- return written;
402
350
  }
403
- function linkSuperAssignmentsToOuterDefinitions(parentGraph, nestedGraphNodeIds, parentEnvironment) {
404
- for (const nodeId of nestedGraphNodeIds) {
405
- const vertex = parentGraph.getVertex(nodeId);
406
- if (!vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.SuperAssignment)) {
351
+ function* superAssignedTargets(graph, nodes) {
352
+ for (const nodeId of nodes) {
353
+ if (!vertex_1.DfgVertex.hasOrigin(graph.getVertex(nodeId), built_in_proc_name_1.BuiltInProcName.SuperAssignment)) {
407
354
  continue;
408
355
  }
409
- const outgoingReturns = parentGraph.outgoingEdges(nodeId);
410
- if (!outgoingReturns) {
411
- continue;
412
- }
413
- for (const [targetId, edge] of outgoingReturns) {
414
- if (!edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Returns)) {
415
- continue;
416
- }
417
- const targetVertex = parentGraph.getVertex(targetId);
418
- if (!vertex_1.DfgVertex.isVariableDefinition(targetVertex)) {
419
- continue;
420
- }
421
- const targetNode = parentGraph.idMap?.get(targetId);
422
- if (!r_symbol_1.RSymbol.is(targetNode)) {
423
- continue;
424
- }
425
- const varName = targetNode.content;
426
- const resolved = resolve_helper_1.Resolve.byNameAndType(varName, parentEnvironment, identifier_1.ReferenceType.Variable);
427
- if (resolved) {
428
- for (const ref of resolved) {
429
- if (ref.nodeId !== targetId && !node_id_1.NodeId.isBuiltIn(ref.nodeId)) {
430
- parentGraph.addEdge(targetId, ref.nodeId, edge_1.EdgeType.Reads);
431
- }
432
- }
356
+ for (const target of (0, frame_reflection_1.edgeTargets)(graph, nodeId, edge_1.EdgeType.Returns)) {
357
+ const node = graph.idMap?.get(target);
358
+ if (vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(target)) && r_symbol_1.RSymbol.is(node)) {
359
+ yield [target, node.content];
433
360
  }
434
361
  }
435
362
  }
@@ -443,7 +370,7 @@ function namesShadowingBuiltIns(environment) {
443
370
  const generics = new Set();
444
371
  for (let env = environment.current; env !== undefined && !env.builtInEnv; env = env.parent) {
445
372
  for (const [identifier, definitions] of env.memory) {
446
- if (!definitions.some(d => !node_id_1.NodeId.isBuiltIn(d.nodeId))) {
373
+ if (definitions.every(d => node_id_1.NodeId.isBuiltIn(d.nodeId))) {
447
374
  continue;
448
375
  }
449
376
  const name = identifier_1.Identifier.getName(identifier);
@@ -456,27 +383,73 @@ function namesShadowingBuiltIns(environment) {
456
383
  }
457
384
  return { shadowing, generics };
458
385
  }
386
+ function fnPropsOf(name, environment, ctx) {
387
+ return (0, query_fn_props_1.queryFnProps)(name, { environment }) ?? ctx.functionInfo(name);
388
+ }
459
389
  /** Whether `name` resolves to a built-in that dispatches, so the methods the code writes for it are reachable. */
460
390
  function dispatchesOnClass(name, environment, ctx) {
461
391
  /* 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);
392
+ const props = fnPropsOf(name, environment, ctx);
393
+ return props === undefined ? resolve_helper_1.Resolve.byNameAndType(name, environment, identifier_1.ReferenceType.Function) === undefined : built_in_props_1.CallProps.hasAny(props, built_in_props_1.CallProp.Generic);
463
394
  }
464
395
  /**
465
396
  * Links `call` to the S3 methods the analyzed code binds as `<name>.<class>`, returning their definition vertices.
466
- * flowR does not track the object's class, so every such method counts, same as the {@link BuiltInProcName.S3Dispatch} path.
397
+ * Unless {@link dispatchedS3Methods} knows the class, every such method counts, same as the {@link BuiltInProcName.S3Dispatch} path.
467
398
  */
468
- function linkOwnS3Methods(call, name, graph, environment) {
399
+ function linkOwnS3Methods(call, name, graph, environment, statement, ctx) {
469
400
  const defs = resolve_helper_1.Resolve.byNameAndType(name, environment, identifier_1.ReferenceType.S3MethodPrefix)
470
- ?.filter(d => !node_id_1.NodeId.isBuiltIn(d.nodeId));
401
+ ?.filter(d => !node_id_1.NodeId.isBuiltIn(d.nodeId) && !program_order_1.ProgramOrder.definedLater(d.nodeId, statement, graph));
471
402
  if (defs === undefined || defs.length === 0) {
472
403
  return [];
473
404
  }
474
- for (const def of defs) {
405
+ const dispatched = dispatchedS3Methods(call, name, defs, graph, environment, statement, ctx) ?? defs;
406
+ for (const def of dispatched) {
475
407
  /* the dispatch looks the method up by name, just like a call written out would */
476
- graph.addEdge(call, def.nodeId, edge_1.EdgeType.Reads);
408
+ graph.addEdge(call.id, def.nodeId, edge_1.EdgeType.Reads);
477
409
  }
478
- const [definitions] = (0, linker_1.getAllLinkedFunctionDefinitions)(new Set(defs.map(d => d.nodeId)), graph);
479
- return definitions.values().map(d => d.id).toArray();
410
+ return linkedDefinitions(dispatched, graph);
411
+ }
412
+ function linkedDefinitions(defs, graph) {
413
+ return (0, linker_1.getAllLinkedFunctionDefinitions)(new Set(defs.map(d => d.nodeId)), graph)[0].values().map(d => d.id).toArray();
414
+ }
415
+ /**
416
+ * The `methods` a call dispatches to per known class of its dispatch object (then `default`), stopping for a top-level call at one surely bound before it;
417
+ * `undefined` if the class is unknown or a method may `NextMethod()`.
418
+ */
419
+ function dispatchedS3Methods(call, name, methods, graph, environment, statement, ctx) {
420
+ const generic = identifier_1.Identifier.getName(name);
421
+ const node = graph.idMap?.get(call.id);
422
+ const first = call.args[0];
423
+ if (graph.idMap === undefined || !r_function_call_1.RFunctionCall.is(node) || first === r_function_call_1.EmptyArgument || first === undefined || (call.args.length > 1 && (0, group_generics_1.groupGenericOf)(generic) !== undefined)) {
424
+ return undefined;
425
+ }
426
+ const formals = function_semantics_1.FunctionSemantics.call.match.formalsOf(node, graph, ctx);
427
+ const bound = formals === undefined || formals[0] === arg_matching_1.DotsParameterName ? undefined : function_semantics_1.FunctionSemantics.call.match.toSpec(call.args, Object.fromEntries(formals.map(f => [f, f]))).get(formals[0]);
428
+ if (call.args.length > 1 && bound?.length !== 1) {
429
+ return undefined;
430
+ }
431
+ /* a closure dispatches on what binds its first formal, a primitive (or anything else) may on the first argument given */
432
+ const props = fnPropsOf(name, environment, ctx);
433
+ const closure = bound !== undefined && props !== undefined && !built_in_props_1.CallProps.hasAny(props, built_in_props_1.CallProp.Primitive);
434
+ const classes = new Set(closure ? bound : [first.nodeId, ...bound ?? []]).values().map(a => (0, class_declaration_1.s3DispatchClassesOf)(a, { graph, idMap: graph.idMap, ctx })).toArray();
435
+ if (!classes.every(assert_1.isNotUndefined)) {
436
+ return undefined;
437
+ }
438
+ const picked = new Set();
439
+ for (const cls of classes.flat()) {
440
+ for (const c of [...cls, 'default']) {
441
+ const found = methods.filter(m => m.name === undefined || identifier_1.Identifier.getName(m.name) === `${generic}.${c}`);
442
+ found.forEach(m => picked.add(m));
443
+ if (statement !== undefined && found.some(m => m.name !== undefined && m.cds === undefined && program_order_1.ProgramOrder.offset(m.nodeId, statement, graph) < 0)) {
444
+ break;
445
+ }
446
+ }
447
+ }
448
+ const callsNext = linkedDefinitions([...picked], graph).some(d => {
449
+ const v = graph.getVertex(d);
450
+ return vertex_1.DfgVertex.isFunctionDefinition(v) && (0, frame_reflection_1.callsIn)(v, graph).some(([, c]) => c.origin.includes(built_in_proc_name_1.BuiltInProcName.S3DispatchNext));
451
+ });
452
+ return callsNext ? undefined : [...picked];
480
453
  }
481
454
  /**
482
455
  * Update the closure links of all nested function calls, done once at the end of the script.
@@ -484,8 +457,19 @@ function linkOwnS3Methods(call, name, graph, environment) {
484
457
  */
485
458
  function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
486
459
  const { shadowing, generics } = namesShadowingBuiltIns(outEnvironment);
487
- for (const [id, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
488
- const { onlyBuiltin, environment, name, args, origin } = vertex;
460
+ let rootDefinitions;
461
+ const calls = graph.verticesOfType(vertex_1.VertexType.FunctionCall).toArray();
462
+ const deferred = new Set();
463
+ const lifted = [];
464
+ const enclosingOf = (0, defaultmap_1.memoize)((id) => graph.idMap === undefined ? undefined : model_1.RNode.strictlyEnclosingFunction(id, graph.idMap));
465
+ const runsOnceAt = (0, defaultmap_1.memoize)((id) => program_order_1.ProgramOrder.runsOnceAt(id, graph));
466
+ const environmentAt = (0, defaultmap_1.memoize)((id) => {
467
+ const environment = graph.getVertex(id).environment;
468
+ return environment ? (0, overwrite_1.overwriteEnvironment)(outEnvironment, environment) : outEnvironment;
469
+ });
470
+ for (let i = 0; i < calls.length; i++) {
471
+ const [id, vertex] = calls[i];
472
+ const { onlyBuiltin, name, args, origin } = vertex;
489
473
  if (name === undefined) {
490
474
  continue;
491
475
  }
@@ -494,16 +478,35 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
494
478
  if (onlyBuiltin && !mayDispatch && !(!graph.isRoot(id) && shadowing.has(identifier_1.Identifier.getName(name)))) {
495
479
  continue;
496
480
  }
497
- const effectiveEnvironment = environment ? (0, overwrite_1.overwriteEnvironment)(outEnvironment, environment) : outEnvironment;
481
+ const effectiveEnvironment = environmentAt(id);
482
+ /* a call the program runs once, at the top and outside any loop, cannot see what is defined after it */
483
+ const definedLater = (definition) => program_order_1.ProgramOrder.definedLater(definition, runsOnceAt(id), graph);
498
484
  const targets = new Set((0, linker_1.getAllFunctionCallTargets)(id, graph, effectiveEnvironment));
485
+ /* a call of a parameter sees what it is bound to only once the calls handing it down are linked */
486
+ if (!deferred.has(id) && targets.size > 0 && targets.values().every(t => !node_id_1.NodeId.isBuiltIn(t) && vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(t)))) {
487
+ deferred.add(id);
488
+ calls.push(calls[i]);
489
+ continue;
490
+ }
499
491
  const collectedNextMethods = new Set();
500
492
  let treatAsS3 = origin.includes(built_in_proc_name_1.BuiltInProcName.S3Dispatch);
493
+ if (treatAsS3 && !graph.isRoot(id)) {
494
+ /* a body dispatches where it is called, which may see a method the end of the script has replaced */
495
+ rootDefinitions ??= (0, frame_reflection_1.definitionsByName)(graph);
496
+ const prefix = identifier_1.Identifier.getName(name) + '.';
497
+ for (const [defined, ids] of rootDefinitions.entries()) {
498
+ if (defined.startsWith(prefix)) {
499
+ (0, linker_1.getAllLinkedFunctionDefinitions)(new Set(ids.filter(d => graph.isRoot(d))), graph)[0].forEach(t => targets.add(t.id));
500
+ }
501
+ }
502
+ }
501
503
  if (mayDispatch && !treatAsS3 && dispatchesOnClass(name, effectiveEnvironment, ctx)) {
502
- for (const method of linkOwnS3Methods(id, name, graph, effectiveEnvironment)) {
504
+ for (const method of linkOwnS3Methods(vertex, name, graph, effectiveEnvironment, runsOnceAt(id), ctx)) {
503
505
  targets.add(method);
504
506
  }
505
507
  treatAsS3 = true;
506
508
  }
509
+ const enclosing = graph.isRoot(id) ? undefined : enclosingOf(id);
507
510
  for (const target of targets) {
508
511
  if (node_id_1.NodeId.isBuiltIn(target)) {
509
512
  // a package export resolved lazily here (nested), so materialize it and link to its loader
@@ -516,7 +519,6 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
516
519
  continue;
517
520
  }
518
521
  const targetVertex = graph.getVertex(target);
519
- // support reads on symbols
520
522
  if (!vertex_1.DfgVertex.isFunctionDefinition(targetVertex)) {
521
523
  if (vertex_1.DfgVertex.isUse(targetVertex)) {
522
524
  graph.addEdge(id, target, edge_1.EdgeType.Reads);
@@ -535,16 +537,27 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
535
537
  targetVertex.mode.push('s3');
536
538
  }
537
539
  // collect all next method calls to link them to the same targets!
538
- for (const s of targetVertex.subflow.graph) {
539
- const v = graph.getVertex(s);
540
- if (vertex_1.DfgVertex.isFunctionCall(v) && v.origin.includes(built_in_proc_name_1.BuiltInProcName.S3DispatchNext)) {
541
- collectedNextMethods.add(v.id);
540
+ for (const [next, v] of (0, frame_reflection_1.callsIn)(targetVertex, graph)) {
541
+ if (v.origin.includes(built_in_proc_name_1.BuiltInProcName.S3DispatchNext)) {
542
+ collectedNextMethods.add(next);
542
543
  }
543
544
  }
544
545
  }
545
- targetVertex.subflow.in = resolveIngoingRefs(targetVertex.subflow.in, effectiveEnvironment, id, id, (ingoing, resolved) => {
546
+ const global = enclosingOf(target) === undefined;
547
+ targetVertex.subflow.in = resolveIngoingRefs(targetVertex.subflow.in, effectiveEnvironment, (ingoing, resolved) => {
548
+ if (enclosing !== undefined && resolved.some(d => !node_id_1.NodeId.isBuiltIn(d.nodeId)) && (global || resolved.every(d => node_id_1.NodeId.isBuiltIn(d.nodeId) || graph.isRoot(d.nodeId)))) {
549
+ lifted.push([enclosing, ingoing, target]);
550
+ return false;
551
+ }
552
+ /* only writes from within functions (`<<-`) are left, and the call may run before them, seeing what they replace */
553
+ if (resolved.every(d => !graph.isRoot(d.nodeId)) && ingoing.name !== undefined) {
554
+ rootDefinitions ??= (0, frame_reflection_1.definitionsByName)(graph);
555
+ for (const def of rootDefinitions.get(identifier_1.Identifier.getName(ingoing.name)).filter(d => graph.isRoot(d))) {
556
+ graph.addEdge(ingoing.nodeId, def, edge_1.EdgeType.Reads);
557
+ }
558
+ }
546
559
  for (const { nodeId, envState } of resolved) {
547
- if (!node_id_1.NodeId.isBuiltIn(nodeId)) {
560
+ if (!node_id_1.NodeId.isBuiltIn(nodeId) && !definedLater(nodeId)) {
548
561
  graph.addEdge(ingoing.nodeId, nodeId, edge_1.EdgeType.DefinedByOnCall);
549
562
  graph.addEdge(id, nodeId, edge_1.EdgeType.DefinesOnCall);
550
563
  if (envState !== undefined && graph.idMap !== undefined) {
@@ -571,19 +584,13 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
571
584
  }
572
585
  }
573
586
  }
574
- const called = new Set();
575
- for (const [id] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
576
- for (const [target, edge] of graph.edgesFrom(id)) {
577
- if (edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Calls)) {
578
- called.add(target);
579
- }
580
- }
581
- }
587
+ linkLiftedReads(graph, lifted, enclosingOf, environmentAt, runsOnceAt);
588
+ const called = new Set(graph.verticesOfType(vertex_1.VertexType.FunctionCall).flatMap(([id]) => (0, frame_reflection_1.edgeTargets)(graph, id, edge_1.EdgeType.Calls)));
582
589
  for (const [id, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionDefinition)) {
583
- if (vertex.subflow.in.length === 0 || called.has(id)) {
590
+ if (called.has(id)) {
584
591
  continue;
585
592
  }
586
- resolveIngoingRefs(vertex.subflow.in, outEnvironment, id, id, (ingoing, resolved) => {
593
+ resolveIngoingRefs(vertex.subflow.in, outEnvironment, (ingoing, resolved) => {
587
594
  for (const { nodeId } of resolved) {
588
595
  if (!node_id_1.NodeId.isBuiltIn(nodeId)) {
589
596
  graph.addEdge(ingoing.nodeId, nodeId, edge_1.EdgeType.Reads);
@@ -593,15 +600,60 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
593
600
  });
594
601
  }
595
602
  }
603
+ /** Resolves each global read of a nested call where the enclosing function is called. */
604
+ function linkLiftedReads(graph, lifted, enclosingOf, environmentAt, runsOnceAt) {
605
+ const seen = new defaultmap_1.DefaultMap(() => new Set());
606
+ while (lifted.length > 0) {
607
+ const [definition, read, holder] = lifted.pop();
608
+ const known = seen.get(definition);
609
+ if (known.has(read.nodeId) || read.name === undefined) {
610
+ continue;
611
+ }
612
+ known.add(read.nodeId);
613
+ for (const call of (0, frame_reflection_1.edgeSources)(graph, definition, edge_1.EdgeType.Calls)) {
614
+ if (!vertex_1.DfgVertex.isFunctionCall(graph.getVertex(call))) {
615
+ continue;
616
+ }
617
+ const outer = graph.isRoot(call) ? undefined : enclosingOf(call);
618
+ if (outer !== undefined) {
619
+ lifted.push([outer, read, holder]);
620
+ continue;
621
+ }
622
+ const resolved = resolve_helper_1.Resolve.byNameAndType(read.name, environmentAt(call), read.type);
623
+ const target = graph.getVertex(holder);
624
+ if (resolved === undefined && vertex_1.DfgVertex.isFunctionDefinition(target) && !target.subflow.in.some(r => r.nodeId === read.nodeId)) {
625
+ target.subflow.in = [...target.subflow.in, read];
626
+ }
627
+ for (const { nodeId } of resolved ?? []) {
628
+ if (!node_id_1.NodeId.isBuiltIn(nodeId) && !program_order_1.ProgramOrder.definedLater(nodeId, runsOnceAt(call), graph)) {
629
+ graph.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
630
+ graph.addEdge(call, nodeId, edge_1.EdgeType.DefinesOnCall);
631
+ }
632
+ }
633
+ }
634
+ }
635
+ }
596
636
  function parseSysFrameOffset(node) {
597
- if (!node || !r_function_call_1.RFunctionCall.is(node) || !node.named || identifier_1.Identifier.getName(node.functionName.content) !== 'sys.frame' || node.arguments.length !== 1) {
637
+ if (!r_function_call_1.RFunctionCall.isNamed(node) || identifier_1.Identifier.getName(node.functionName.content) !== 'sys.frame' || node.arguments.length !== 1) {
598
638
  return undefined;
599
639
  }
600
- const arg = node.arguments[0];
601
- if (r_argument_1.RArgument.isEmpty(arg) || !arg.value) {
602
- return undefined;
640
+ return r_number_1.RNumber.literalValueOf(r_argument_1.RArgument.valueOf(node.arguments[0]));
641
+ }
642
+ function namesRemovedBy(call, idMap) {
643
+ const names = [];
644
+ for (const a of call.args) {
645
+ if (a === r_function_call_1.EmptyArgument || graph_1.FunctionArgument.hasName(a, 'envir')) {
646
+ continue;
647
+ }
648
+ const node = idMap.get(graph_1.FunctionArgument.getReference(a) ?? a.nodeId);
649
+ if (r_string_1.RString.is(node)) {
650
+ names.push(node.content.str);
651
+ }
652
+ else if (r_symbol_1.RSymbol.is(node)) {
653
+ names.push(node.content);
654
+ }
603
655
  }
604
- return r_number_1.RNumber.literalValueOf(arg.value);
656
+ return names;
605
657
  }
606
658
  function prepareFunctionEnvironment(data, rootId) {
607
659
  const level = data.environment.level;
@@ -635,37 +687,23 @@ function groupBodyWrites(out) {
635
687
  * e.g. in `f <- function(a=b) { b <- 1; a; b <- 5 }`, `a` links to `b <- 1`; may not narrow this down precisely in every case.
636
688
  */
637
689
  function linkParameterReadToBodyWrites(graph, read, writesByName) {
638
- const writingOuts = read.name === undefined ? undefined : writesByName.get(read.name);
639
- if (writingOuts === undefined) {
690
+ const writes = read.name === undefined ? undefined : writesByName.get(read.name);
691
+ if (writes === undefined) {
640
692
  return false;
641
693
  }
642
- if (writingOuts[0].cds === undefined) {
643
- graph.addEdge(read.nodeId, writingOuts[0].nodeId, edge_1.EdgeType.Reads);
644
- }
645
- else {
646
- for (const { nodeId } of writingOuts) {
647
- graph.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
648
- }
694
+ for (const { nodeId } of writes[0].cds === undefined ? writes.slice(0, 1) : writes) {
695
+ graph.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
649
696
  }
650
697
  return true;
651
698
  }
699
+ /** Binds the parameter reads `readInParameters` within the parameters, else to the body writes they may see; returns those still unresolved. */
652
700
  function findPromiseLinkagesForParameters(parameters, readInParameters, parameterEnvs, writesByName) {
653
- // first, we try to bind again within parameters - if we have it, fine
654
- const remainingRead = [];
655
- for (const read of readInParameters) {
701
+ return readInParameters.filter(read => {
656
702
  const resolved = read.name ? resolve_helper_1.Resolve.byNameAndType(read.name, parameterEnvs, read.type) : undefined;
657
- const rid = read.nodeId;
658
- if (resolved !== undefined) {
659
- for (const { nodeId } of resolved) {
660
- parameters.addEdge(rid, nodeId, edge_1.EdgeType.Reads);
661
- }
662
- continue;
703
+ for (const { nodeId } of resolved ?? []) {
704
+ parameters.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
663
705
  }
664
- // If not resolved, link all outs within the body as potential reads.
665
- if (!linkParameterReadToBodyWrites(parameters, read, writesByName)) {
666
- remainingRead.push(read);
667
- }
668
- }
669
- return remainingRead;
706
+ return resolved === undefined && !linkParameterReadToBodyWrites(parameters, read, writesByName);
707
+ });
670
708
  }
671
709
  //# sourceMappingURL=built-in-function-definition.js.map