@eagleoutice/flowr 2.15.9 → 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 (244) hide show
  1. package/README.md +47 -41
  2. package/abstract-interpretation/absint-inference.d.ts +2 -2
  3. package/abstract-interpretation/absint-inference.js +32 -79
  4. package/abstract-interpretation/data-frame/arguments.js +11 -7
  5. package/benchmark/slicer.d.ts +0 -1
  6. package/benchmark/slicer.js +1 -2
  7. package/cli/repl/commands/repl-signature.js +12 -3
  8. package/config.d.ts +5 -1
  9. package/control-flow/cfg-properties.js +0 -22
  10. package/control-flow/happens-before.d.ts +7 -2
  11. package/control-flow/happens-before.js +55 -31
  12. package/control-flow/useless-loop.d.ts +1 -1
  13. package/control-flow/useless-loop.js +29 -42
  14. package/dataflow/environments/apply-kill.js +6 -2
  15. package/dataflow/environments/built-in-config.d.ts +2 -0
  16. package/dataflow/environments/built-in-props.d.ts +16 -1
  17. package/dataflow/environments/built-in-props.js +33 -20
  18. package/dataflow/environments/built-in.d.ts +8 -3
  19. package/dataflow/environments/built-in.js +52 -82
  20. package/dataflow/environments/default-builtin-config.d.ts +551 -21
  21. package/dataflow/environments/default-builtin-config.js +121 -45
  22. package/dataflow/environments/define.d.ts +3 -2
  23. package/dataflow/environments/define.js +4 -3
  24. package/dataflow/environments/deprecation-info.d.ts +45 -0
  25. package/dataflow/environments/deprecation-info.js +13 -0
  26. package/dataflow/environments/environment.d.ts +7 -5
  27. package/dataflow/environments/environment.js +55 -121
  28. package/dataflow/environments/identifier.d.ts +6 -2
  29. package/dataflow/environments/identifier.js +23 -69
  30. package/dataflow/environments/reference-to-maybe.d.ts +9 -0
  31. package/dataflow/environments/reference-to-maybe.js +23 -51
  32. package/dataflow/environments/resolve-by-name.js +37 -76
  33. package/dataflow/eval/resolve/resolve-argument.d.ts +3 -1
  34. package/dataflow/eval/resolve/resolve-argument.js +61 -64
  35. package/dataflow/eval/resolve/resolve-working-directory.d.ts +8 -2
  36. package/dataflow/eval/resolve/resolve-working-directory.js +12 -20
  37. package/dataflow/eval/resolve/resolve.d.ts +4 -0
  38. package/dataflow/eval/resolve/resolve.js +23 -14
  39. package/dataflow/extractor.js +180 -58
  40. package/dataflow/fn/class-declaration.d.ts +8 -13
  41. package/dataflow/fn/class-declaration.js +95 -116
  42. package/dataflow/fn/exceptions-of-function.js +68 -37
  43. package/dataflow/fn/frame-reflection.d.ts +12 -4
  44. package/dataflow/fn/frame-reflection.js +51 -41
  45. package/dataflow/fn/function-props.js +15 -33
  46. package/dataflow/fn/function-semantics.d.ts +11 -3
  47. package/dataflow/fn/function-semantics.js +6 -0
  48. package/dataflow/fn/higher-order-function.d.ts +9 -1
  49. package/dataflow/fn/higher-order-function.js +27 -24
  50. package/dataflow/fn/strict-function.d.ts +13 -0
  51. package/dataflow/fn/strict-function.js +291 -123
  52. package/dataflow/graph/call-graph.d.ts +7 -6
  53. package/dataflow/graph/call-graph.js +35 -46
  54. package/dataflow/graph/graph.d.ts +13 -1
  55. package/dataflow/graph/graph.js +74 -66
  56. package/dataflow/graph/vertex.d.ts +1 -1
  57. package/dataflow/info.d.ts +8 -1
  58. package/dataflow/info.js +24 -30
  59. package/dataflow/internal/control-flow.d.ts +31 -4
  60. package/dataflow/internal/control-flow.js +61 -39
  61. package/dataflow/internal/linker.d.ts +17 -8
  62. package/dataflow/internal/linker.js +286 -213
  63. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +179 -0
  64. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +874 -0
  65. package/dataflow/internal/process/functions/call/built-in/built-in-apply.d.ts +3 -1
  66. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +60 -48
  67. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +4 -2
  68. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +135 -198
  69. package/dataflow/internal/process/functions/call/built-in/built-in-class-generator.js +7 -9
  70. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +5 -1
  71. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +21 -14
  72. package/dataflow/internal/process/functions/call/built-in/built-in-eval.js +14 -4
  73. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.d.ts +1 -1
  74. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +141 -146
  75. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.js +56 -24
  76. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +292 -253
  77. package/dataflow/internal/process/functions/call/built-in/built-in-get.d.ts +1 -1
  78. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +30 -32
  79. package/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.js +68 -67
  80. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +91 -129
  81. package/dataflow/internal/process/functions/call/built-in/built-in-local.d.ts +1 -3
  82. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +16 -12
  83. package/dataflow/internal/process/functions/call/built-in/built-in-quote.d.ts +4 -4
  84. package/dataflow/internal/process/functions/call/built-in/built-in-quote.js +9 -35
  85. package/dataflow/internal/process/functions/call/built-in/built-in-repeat-loop.js +2 -0
  86. package/dataflow/internal/process/functions/call/built-in/built-in-rm.js +8 -3
  87. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.d.ts +5 -3
  88. package/dataflow/internal/process/functions/call/built-in/built-in-s-four.js +13 -31
  89. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.d.ts +1 -1
  90. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +42 -119
  91. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.d.ts +1 -3
  92. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.js +21 -21
  93. package/dataflow/internal/process/functions/call/built-in/built-in-source.d.ts +2 -0
  94. package/dataflow/internal/process/functions/call/built-in/built-in-source.js +93 -102
  95. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.d.ts +7 -3
  96. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.js +173 -114
  97. package/dataflow/internal/process/functions/call/built-in/built-in-while-loop.d.ts +1 -3
  98. package/dataflow/internal/process/functions/call/built-in/built-in-while-loop.js +23 -26
  99. package/dataflow/internal/process/functions/call/built-in/built-in-with.d.ts +1 -1
  100. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +34 -9
  101. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.d.ts +1 -1
  102. package/dataflow/internal/process/functions/call/built-in/transitive-side-effects.js +119 -93
  103. package/dataflow/internal/process/functions/call/common.d.ts +4 -4
  104. package/dataflow/internal/process/functions/call/common.js +49 -71
  105. package/dataflow/internal/process/functions/call/deferred.d.ts +12 -2
  106. package/dataflow/internal/process/functions/call/deferred.js +81 -63
  107. package/dataflow/internal/process/functions/call/known-call-handling.d.ts +4 -2
  108. package/dataflow/internal/process/functions/call/known-call-handling.js +65 -68
  109. package/dataflow/internal/process/functions/call/named-call-handling.d.ts +3 -5
  110. package/dataflow/internal/process/functions/call/named-call-handling.js +48 -19
  111. package/dataflow/internal/process/functions/call/quoted.d.ts +2 -0
  112. package/dataflow/internal/process/functions/call/quoted.js +257 -154
  113. package/dataflow/internal/process/functions/call/unnamed-call-handling.js +17 -38
  114. package/dataflow/internal/process/functions/process-parameter.js +25 -32
  115. package/dataflow/internal/process/process-symbol.js +4 -3
  116. package/dataflow/internal/program-order.d.ts +26 -0
  117. package/dataflow/internal/program-order.js +49 -0
  118. package/documentation/data/faq/faqs.js +3 -3
  119. package/documentation/data/interface/doc-writing-code.js +1 -2
  120. package/documentation/data/server/doc-data-server-messages.js +7 -7
  121. package/documentation/doc-capabilities.js +80 -34
  122. package/documentation/doc-util/doc-query.d.ts +0 -3
  123. package/documentation/doc-util/doc-query.js +4 -3
  124. package/documentation/wiki-analyzer.js +1 -1
  125. package/documentation/wiki-cfg.js +5 -6
  126. package/documentation/wiki-core.js +8 -8
  127. package/documentation/wiki-dataflow-graph.js +10 -11
  128. package/documentation/wiki-interface.js +2 -2
  129. package/documentation/wiki-linting-and-testing.js +3 -3
  130. package/documentation/wiki-overview.js +6 -6
  131. package/documentation/wiki-query.js +9 -101
  132. package/documentation/wiki-setup.js +23 -0
  133. package/documentation/wiki-signature-database.js +1 -1
  134. package/linter/linter-rules.d.ts +18 -9
  135. package/linter/rules/absolute-path.js +63 -87
  136. package/linter/rules/deprecated-functions.d.ts +1 -45
  137. package/linter/rules/deprecated-functions.js +24 -33
  138. package/linter/rules/file-path-validity.d.ts +4 -2
  139. package/linter/rules/file-path-validity.js +114 -80
  140. package/linter/rules/namespace-access.js +21 -33
  141. package/linter/rules/naming-convention.d.ts +1 -1
  142. package/linter/rules/naming-convention.js +60 -48
  143. package/linter/rules/network-functions.js +11 -7
  144. package/linter/rules/no-leaked-credentials.js +15 -18
  145. package/linter/rules/problematic-inputs.d.ts +2 -1
  146. package/linter/rules/problematic-inputs.js +39 -59
  147. package/linter/rules/roxygen-arguments.d.ts +9 -4
  148. package/linter/rules/roxygen-arguments.js +29 -48
  149. package/linter/rules/seeded-randomness.d.ts +7 -4
  150. package/linter/rules/seeded-randomness.js +128 -89
  151. package/linter/rules/stop-with-call-arg.d.ts +4 -2
  152. package/linter/rules/stop-with-call-arg.js +25 -22
  153. package/linter/rules/unclosed-connection.js +31 -24
  154. package/linter/rules/undefined-symbol.d.ts +4 -6
  155. package/linter/rules/undefined-symbol.js +58 -75
  156. package/linter/rules/unescaped-arguments.js +18 -44
  157. package/linter/rules/unused-definition.d.ts +6 -0
  158. package/linter/rules/unused-definition.js +105 -145
  159. package/linter/rules/unused-import.d.ts +3 -0
  160. package/linter/rules/unused-import.js +25 -43
  161. package/package.json +5 -2
  162. package/project/flowr-analyzer.d.ts +2 -0
  163. package/project/flowr-analyzer.js +28 -1
  164. package/project/plugins/file-plugins/files/flowr-jupyter-file.d.ts +2 -2
  165. package/project/plugins/file-plugins/files/flowr-jupyter-file.js +8 -12
  166. package/project/plugins/file-plugins/files/flowr-rda-file.d.ts +0 -2
  167. package/project/plugins/file-plugins/files/flowr-rda-file.js +10 -55
  168. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.d.ts +7 -5
  169. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +34 -56
  170. package/project/plugins/file-plugins/flowr-analyzer-file-plugin.js +2 -1
  171. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +22 -45
  172. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +2 -2
  173. package/project/sigdb/build.js +4 -0
  174. package/project/sigdb/manifest.d.ts +2 -0
  175. package/project/sigdb/manifest.js +10 -1
  176. package/project/sigdb/reader.js +23 -61
  177. package/project/sigdb/sigdb-download.d.ts +29 -6
  178. package/project/sigdb/sigdb-download.js +212 -64
  179. package/queries/base-query-format.js +1 -2
  180. package/queries/catalog/absint-query/absint-query-format.js +1 -1
  181. package/queries/catalog/call-context-query/cascade-action.d.ts +3 -1
  182. package/queries/catalog/call-context-query/cascade-action.js +2 -0
  183. package/queries/catalog/call-context-query/identify-link-to-last-call-relation.js +3 -0
  184. package/queries/catalog/dataflow-query/dataflow-query-executor.js +2 -2
  185. package/queries/catalog/dataflow-query/dataflow-query-format.d.ts +2 -0
  186. package/queries/catalog/dataflow-query/dataflow-query-format.js +4 -7
  187. package/queries/catalog/dependencies-query/dependencies-query-executor.js +50 -114
  188. package/queries/catalog/dependencies-query/function-info/library-functions.d.ts +5 -9
  189. package/queries/catalog/dependencies-query/function-info/library-functions.js +6 -0
  190. package/queries/catalog/dependencies-query/function-info/read-functions.js +1 -1
  191. package/queries/catalog/dependencies-query/function-info/write-functions.js +7 -3
  192. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +4 -4
  193. package/queries/catalog/input-sources-query/simple-input-classifier.js +192 -301
  194. package/queries/catalog/inspect-higher-order-query/inspect-higher-order-query-executor.js +2 -1
  195. package/queries/catalog/origin-query/origin-query-executor.d.ts +1 -1
  196. package/queries/catalog/origin-query/origin-query-executor.js +2 -2
  197. package/queries/catalog/origin-query/origin-query-format.d.ts +2 -2
  198. package/queries/catalog/origin-query/origin-query-format.js +1 -1
  199. package/queries/query.d.ts +1 -1
  200. package/r-bridge/data/data.d.ts +21 -14
  201. package/r-bridge/data/data.js +28 -20
  202. package/r-bridge/lang-4.x/ast/model/model.d.ts +3 -1
  203. package/r-bridge/lang-4.x/ast/model/model.js +19 -43
  204. package/r-bridge/lang-4.x/ast/model/nodes/r-access.d.ts +1 -0
  205. package/r-bridge/lang-4.x/ast/model/nodes/r-argument.d.ts +3 -0
  206. package/r-bridge/lang-4.x/ast/model/nodes/r-argument.js +5 -12
  207. package/r-bridge/lang-4.x/ast/model/nodes/r-binary-op.d.ts +1 -0
  208. package/r-bridge/lang-4.x/ast/model/nodes/r-break.d.ts +1 -0
  209. package/r-bridge/lang-4.x/ast/model/nodes/r-comment.d.ts +1 -0
  210. package/r-bridge/lang-4.x/ast/model/nodes/r-expression-list.d.ts +1 -0
  211. package/r-bridge/lang-4.x/ast/model/nodes/r-for-loop.d.ts +1 -0
  212. package/r-bridge/lang-4.x/ast/model/nodes/r-function-call.d.ts +1 -0
  213. package/r-bridge/lang-4.x/ast/model/nodes/r-function-definition.d.ts +1 -0
  214. package/r-bridge/lang-4.x/ast/model/nodes/r-if-then-else.d.ts +1 -0
  215. package/r-bridge/lang-4.x/ast/model/nodes/r-line-directive.d.ts +1 -0
  216. package/r-bridge/lang-4.x/ast/model/nodes/r-logical.d.ts +1 -0
  217. package/r-bridge/lang-4.x/ast/model/nodes/r-next.d.ts +1 -0
  218. package/r-bridge/lang-4.x/ast/model/nodes/r-number.d.ts +1 -0
  219. package/r-bridge/lang-4.x/ast/model/nodes/r-parameter.d.ts +1 -0
  220. package/r-bridge/lang-4.x/ast/model/nodes/r-pipe.d.ts +1 -0
  221. package/r-bridge/lang-4.x/ast/model/nodes/r-repeat-loop.d.ts +1 -0
  222. package/r-bridge/lang-4.x/ast/model/nodes/r-string.d.ts +1 -0
  223. package/r-bridge/lang-4.x/ast/model/nodes/r-symbol.d.ts +1 -0
  224. package/r-bridge/lang-4.x/ast/model/nodes/r-unary-op.d.ts +1 -0
  225. package/r-bridge/lang-4.x/ast/model/nodes/r-while-loop.d.ts +1 -0
  226. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.d.ts +2 -2
  227. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-executor.js +11 -2
  228. package/r-bridge/roxygen2/roxygen-parse.js +28 -42
  229. package/r-bridge/shell.js +6 -0
  230. package/search/search-executor/search-enrichers.js +25 -37
  231. package/slicing/static/slice-call.d.ts +4 -3
  232. package/slicing/static/slice-call.js +56 -88
  233. package/slicing/static/static-slicer.js +115 -79
  234. package/slicing/static/visiting-queue.d.ts +4 -6
  235. package/slicing/static/visiting-queue.js +9 -13
  236. package/util/files.d.ts +2 -0
  237. package/util/files.js +3 -1
  238. package/util/mermaid/mermaid.js +6 -2
  239. package/util/proc.js +2 -1
  240. package/util/r-base-packages.d.ts +2 -0
  241. package/util/r-base-packages.js +23 -13
  242. package/util/text/playground-link.d.ts +12 -3
  243. package/util/text/playground-link.js +18 -27
  244. 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,26 +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
- function dispatchesOnClass(name, environment) {
461
- return (((0, query_fn_props_1.queryFnProps)(name, { environment })?.props ?? 0) & built_in_props_1.CallProp.Generic) !== 0;
390
+ function dispatchesOnClass(name, environment, ctx) {
391
+ /* a generic only the signature database knows (`toString`) dispatches as well */
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);
462
394
  }
463
395
  /**
464
396
  * Links `call` to the S3 methods the analyzed code binds as `<name>.<class>`, returning their definition vertices.
465
- * 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.
466
398
  */
467
- function linkOwnS3Methods(call, name, graph, environment) {
399
+ function linkOwnS3Methods(call, name, graph, environment, statement, ctx) {
468
400
  const defs = resolve_helper_1.Resolve.byNameAndType(name, environment, identifier_1.ReferenceType.S3MethodPrefix)
469
- ?.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));
470
402
  if (defs === undefined || defs.length === 0) {
471
403
  return [];
472
404
  }
473
- for (const def of defs) {
405
+ const dispatched = dispatchedS3Methods(call, name, defs, graph, environment, statement, ctx) ?? defs;
406
+ for (const def of dispatched) {
474
407
  /* the dispatch looks the method up by name, just like a call written out would */
475
- graph.addEdge(call, def.nodeId, edge_1.EdgeType.Reads);
408
+ graph.addEdge(call.id, def.nodeId, edge_1.EdgeType.Reads);
476
409
  }
477
- const [definitions] = (0, linker_1.getAllLinkedFunctionDefinitions)(new Set(defs.map(d => d.nodeId)), graph);
478
- 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];
479
453
  }
480
454
  /**
481
455
  * Update the closure links of all nested function calls, done once at the end of the script.
@@ -483,8 +457,19 @@ function linkOwnS3Methods(call, name, graph, environment) {
483
457
  */
484
458
  function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
485
459
  const { shadowing, generics } = namesShadowingBuiltIns(outEnvironment);
486
- for (const [id, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
487
- 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;
488
473
  if (name === undefined) {
489
474
  continue;
490
475
  }
@@ -493,16 +478,35 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
493
478
  if (onlyBuiltin && !mayDispatch && !(!graph.isRoot(id) && shadowing.has(identifier_1.Identifier.getName(name)))) {
494
479
  continue;
495
480
  }
496
- 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);
497
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
+ }
498
491
  const collectedNextMethods = new Set();
499
492
  let treatAsS3 = origin.includes(built_in_proc_name_1.BuiltInProcName.S3Dispatch);
500
- if (mayDispatch && !treatAsS3 && dispatchesOnClass(name, effectiveEnvironment)) {
501
- for (const method of linkOwnS3Methods(id, name, graph, effectiveEnvironment)) {
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
+ }
503
+ if (mayDispatch && !treatAsS3 && dispatchesOnClass(name, effectiveEnvironment, ctx)) {
504
+ for (const method of linkOwnS3Methods(vertex, name, graph, effectiveEnvironment, runsOnceAt(id), ctx)) {
502
505
  targets.add(method);
503
506
  }
504
507
  treatAsS3 = true;
505
508
  }
509
+ const enclosing = graph.isRoot(id) ? undefined : enclosingOf(id);
506
510
  for (const target of targets) {
507
511
  if (node_id_1.NodeId.isBuiltIn(target)) {
508
512
  // a package export resolved lazily here (nested), so materialize it and link to its loader
@@ -515,7 +519,6 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
515
519
  continue;
516
520
  }
517
521
  const targetVertex = graph.getVertex(target);
518
- // support reads on symbols
519
522
  if (!vertex_1.DfgVertex.isFunctionDefinition(targetVertex)) {
520
523
  if (vertex_1.DfgVertex.isUse(targetVertex)) {
521
524
  graph.addEdge(id, target, edge_1.EdgeType.Reads);
@@ -534,16 +537,27 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
534
537
  targetVertex.mode.push('s3');
535
538
  }
536
539
  // collect all next method calls to link them to the same targets!
537
- for (const s of targetVertex.subflow.graph) {
538
- const v = graph.getVertex(s);
539
- if (vertex_1.DfgVertex.isFunctionCall(v) && v.origin.includes(built_in_proc_name_1.BuiltInProcName.S3DispatchNext)) {
540
- 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);
541
543
  }
542
544
  }
543
545
  }
544
- 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
+ }
545
559
  for (const { nodeId, envState } of resolved) {
546
- if (!node_id_1.NodeId.isBuiltIn(nodeId)) {
560
+ if (!node_id_1.NodeId.isBuiltIn(nodeId) && !definedLater(nodeId)) {
547
561
  graph.addEdge(ingoing.nodeId, nodeId, edge_1.EdgeType.DefinedByOnCall);
548
562
  graph.addEdge(id, nodeId, edge_1.EdgeType.DefinesOnCall);
549
563
  if (envState !== undefined && graph.idMap !== undefined) {
@@ -570,19 +584,13 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
570
584
  }
571
585
  }
572
586
  }
573
- const called = new Set();
574
- for (const [id] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
575
- for (const [target, edge] of graph.edgesFrom(id)) {
576
- if (edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Calls)) {
577
- called.add(target);
578
- }
579
- }
580
- }
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)));
581
589
  for (const [id, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionDefinition)) {
582
- if (vertex.subflow.in.length === 0 || called.has(id)) {
590
+ if (called.has(id)) {
583
591
  continue;
584
592
  }
585
- resolveIngoingRefs(vertex.subflow.in, outEnvironment, id, id, (ingoing, resolved) => {
593
+ resolveIngoingRefs(vertex.subflow.in, outEnvironment, (ingoing, resolved) => {
586
594
  for (const { nodeId } of resolved) {
587
595
  if (!node_id_1.NodeId.isBuiltIn(nodeId)) {
588
596
  graph.addEdge(ingoing.nodeId, nodeId, edge_1.EdgeType.Reads);
@@ -592,15 +600,60 @@ function updateNestedFunctionCalls(graph, outEnvironment, ctx) {
592
600
  });
593
601
  }
594
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
+ }
595
636
  function parseSysFrameOffset(node) {
596
- 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) {
597
638
  return undefined;
598
639
  }
599
- const arg = node.arguments[0];
600
- if (r_argument_1.RArgument.isEmpty(arg) || !arg.value) {
601
- 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
+ }
602
655
  }
603
- return r_number_1.RNumber.literalValueOf(arg.value);
656
+ return names;
604
657
  }
605
658
  function prepareFunctionEnvironment(data, rootId) {
606
659
  const level = data.environment.level;
@@ -634,37 +687,23 @@ function groupBodyWrites(out) {
634
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.
635
688
  */
636
689
  function linkParameterReadToBodyWrites(graph, read, writesByName) {
637
- const writingOuts = read.name === undefined ? undefined : writesByName.get(read.name);
638
- if (writingOuts === undefined) {
690
+ const writes = read.name === undefined ? undefined : writesByName.get(read.name);
691
+ if (writes === undefined) {
639
692
  return false;
640
693
  }
641
- if (writingOuts[0].cds === undefined) {
642
- graph.addEdge(read.nodeId, writingOuts[0].nodeId, edge_1.EdgeType.Reads);
643
- }
644
- else {
645
- for (const { nodeId } of writingOuts) {
646
- graph.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
647
- }
694
+ for (const { nodeId } of writes[0].cds === undefined ? writes.slice(0, 1) : writes) {
695
+ graph.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
648
696
  }
649
697
  return true;
650
698
  }
699
+ /** Binds the parameter reads `readInParameters` within the parameters, else to the body writes they may see; returns those still unresolved. */
651
700
  function findPromiseLinkagesForParameters(parameters, readInParameters, parameterEnvs, writesByName) {
652
- // first, we try to bind again within parameters - if we have it, fine
653
- const remainingRead = [];
654
- for (const read of readInParameters) {
701
+ return readInParameters.filter(read => {
655
702
  const resolved = read.name ? resolve_helper_1.Resolve.byNameAndType(read.name, parameterEnvs, read.type) : undefined;
656
- const rid = read.nodeId;
657
- if (resolved !== undefined) {
658
- for (const { nodeId } of resolved) {
659
- parameters.addEdge(rid, nodeId, edge_1.EdgeType.Reads);
660
- }
661
- continue;
703
+ for (const { nodeId } of resolved ?? []) {
704
+ parameters.addEdge(read.nodeId, nodeId, edge_1.EdgeType.Reads);
662
705
  }
663
- // If not resolved, link all outs within the body as potential reads.
664
- if (!linkParameterReadToBodyWrites(parameters, read, writesByName)) {
665
- remainingRead.push(read);
666
- }
667
- }
668
- return remainingRead;
706
+ return resolved === undefined && !linkParameterReadToBodyWrites(parameters, read, writesByName);
707
+ });
669
708
  }
670
709
  //# sourceMappingURL=built-in-function-definition.js.map