@eagleoutice/flowr 2.11.1 → 2.12.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 (255) hide show
  1. package/README.md +193 -263
  2. package/abstract-interpretation/data-frame/mappers/arguments.js +7 -1
  3. package/abstract-interpretation/domains/set-range-domain.js +1 -1
  4. package/abstract-interpretation/domains/set-upper-bound-domain.js +6 -2
  5. package/benchmark/slicer.d.ts +1 -1
  6. package/benchmark/slicer.js +3 -1
  7. package/benchmark/summarizer/second-phase/graph.js +5 -0
  8. package/cli/common/options.d.ts +8 -0
  9. package/cli/common/options.js +2 -0
  10. package/cli/common/scripts-info.d.ts +8 -0
  11. package/cli/repl/commands/repl-commands.d.ts +1 -0
  12. package/cli/repl/commands/repl-commands.js +66 -15
  13. package/cli/repl/commands/repl-dataflow.js +48 -4
  14. package/cli/repl/commands/repl-main.d.ts +2 -0
  15. package/cli/repl/commands/repl-main.js +5 -0
  16. package/cli/repl/commands/repl-query.d.ts +4 -1
  17. package/cli/repl/commands/repl-query.js +72 -22
  18. package/cli/repl/commands/repl-signature.d.ts +7 -0
  19. package/cli/repl/commands/repl-signature.js +119 -0
  20. package/cli/repl/core.d.ts +8 -1
  21. package/cli/repl/core.js +46 -6
  22. package/cli/repl/ghost-hint.d.ts +37 -0
  23. package/cli/repl/ghost-hint.js +72 -0
  24. package/cli/repl/parser/slice-query-parser.d.ts +11 -1
  25. package/cli/repl/parser/slice-query-parser.js +45 -16
  26. package/cli/repl/print-version.d.ts +2 -4
  27. package/cli/repl/print-version.js +41 -23
  28. package/cli/repl/server/connection.js +19 -17
  29. package/cli/slicer-app.d.ts +2 -0
  30. package/cli/slicer-app.js +3 -3
  31. package/cli/wiki.d.ts +2 -2
  32. package/cli/wiki.js +2 -2
  33. package/config.d.ts +63 -2
  34. package/config.js +64 -8
  35. package/control-flow/cfg-dead-code.js +0 -1
  36. package/control-flow/control-flow-graph.js +6 -6
  37. package/control-flow/diff-cfg.js +2 -2
  38. package/control-flow/semantic-cfg-guided-visitor.js +2 -0
  39. package/core/print/slice-diff-ansi.js +8 -8
  40. package/core/steps/all/core/20-dataflow.d.ts +2 -2
  41. package/core/steps/all/static-slicing/00-slice.d.ts +5 -0
  42. package/core/steps/all/static-slicing/00-slice.js +1 -1
  43. package/core/steps/all/static-slicing/10-reconstruct.d.ts +7 -0
  44. package/core/steps/all/static-slicing/10-reconstruct.js +6 -2
  45. package/core/steps/pipeline/default-pipelines.d.ts +20 -16
  46. package/data/r-base-packages.generated.d.ts +44 -0
  47. package/data/r-base-packages.generated.js +32 -0
  48. package/data/r-base-primitives.generated.d.ts +1 -0
  49. package/data/r-base-primitives.generated.js +15 -0
  50. package/data/sigdb/sigdb.remote.json +112 -0
  51. package/dataflow/environments/built-in-proc-name.d.ts +4 -0
  52. package/dataflow/environments/built-in-proc-name.js +4 -0
  53. package/dataflow/environments/built-in.d.ts +14 -4
  54. package/dataflow/environments/built-in.js +13 -2
  55. package/dataflow/environments/data-masking-functions.d.ts +12 -0
  56. package/dataflow/environments/data-masking-functions.js +46 -0
  57. package/dataflow/environments/default-builtin-config.d.ts +72 -19
  58. package/dataflow/environments/default-builtin-config.js +48 -14
  59. package/dataflow/environments/diff.js +1 -1
  60. package/dataflow/environments/environment.js +1 -2
  61. package/dataflow/environments/identifier.d.ts +11 -4
  62. package/dataflow/environments/identifier.js +28 -10
  63. package/dataflow/environments/resolve-by-name.js +16 -2
  64. package/dataflow/extractor.js +6 -3
  65. package/dataflow/graph/call-graph.d.ts +2 -2
  66. package/dataflow/graph/df-helper.d.ts +4 -4
  67. package/dataflow/graph/diff-dataflow-graph.js +2 -2
  68. package/dataflow/graph/edge.d.ts +3 -3
  69. package/dataflow/graph/edge.js +3 -3
  70. package/dataflow/graph/graph-helper.d.ts +2 -2
  71. package/dataflow/internal/linker.js +1 -1
  72. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +7 -0
  73. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +20 -0
  74. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +1 -0
  75. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +2 -49
  76. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +6 -1
  77. package/dataflow/internal/process/functions/call/built-in/built-in-get.js +7 -1
  78. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +19 -0
  79. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +111 -6
  80. package/dataflow/internal/process/functions/call/built-in/built-in-pipe.js +13 -0
  81. package/dataflow/internal/process/functions/call/built-in/built-in-replacement.js +2 -3
  82. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.d.ts +9 -0
  83. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +19 -0
  84. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +12 -4
  85. package/dataflow/internal/process/functions/call/common.js +8 -1
  86. package/dataflow/internal/process/functions/call/default-call-handling.js +6 -0
  87. package/dataflow/internal/process/functions/call/known-call-handling.d.ts +17 -0
  88. package/dataflow/internal/process/functions/call/known-call-handling.js +32 -0
  89. package/dataflow/internal/process/functions/call/named-call-handling.js +29 -7
  90. package/dataflow/internal/process/functions/process-argument.js +12 -1
  91. package/dataflow/internal/process/process-named-call.d.ts +18 -1
  92. package/dataflow/internal/process/process-named-call.js +94 -0
  93. package/dataflow/processor.d.ts +18 -0
  94. package/documentation/data/faq/faqs.js +5 -1
  95. package/documentation/doc-capabilities.js +1 -1
  96. package/documentation/doc-util/doc-cli-option.d.ts +10 -0
  97. package/documentation/doc-util/doc-cli-option.js +23 -0
  98. package/documentation/doc-util/doc-dfg.js +2 -1
  99. package/documentation/doc-util/doc-query.d.ts +9 -3
  100. package/documentation/doc-util/doc-query.js +9 -4
  101. package/documentation/wiki-dataflow-graph.js +8 -5
  102. package/documentation/wiki-interface.js +3 -1
  103. package/documentation/wiki-linter.js +1 -1
  104. package/documentation/wiki-linting-and-testing.js +4 -1
  105. package/documentation/wiki-mk/doc-context.d.ts +14 -0
  106. package/documentation/wiki-mk/doc-context.js +3 -0
  107. package/documentation/wiki-mk/doc-maker.js +3 -1
  108. package/documentation/wiki-query.js +19 -1
  109. package/documentation/wiki-setup.js +10 -7
  110. package/documentation/wiki-signature-database.d.ts +16 -0
  111. package/documentation/wiki-signature-database.js +293 -0
  112. package/linter/linter-format.d.ts +7 -0
  113. package/linter/linter-rules.d.ts +10 -9
  114. package/linter/rules/naming-convention.d.ts +1 -0
  115. package/linter/rules/naming-convention.js +2 -0
  116. package/linter/rules/no-leaked-credentials.js +1 -2
  117. package/linter/rules/roxygen-arguments.js +18 -5
  118. package/linter/rules/stop-with-call-arg.js +2 -2
  119. package/linter/rules/undefined-symbol-util.d.ts +36 -0
  120. package/linter/rules/undefined-symbol-util.js +149 -0
  121. package/linter/rules/undefined-symbol.d.ts +58 -17
  122. package/linter/rules/undefined-symbol.js +143 -33
  123. package/linter/rules/unused-definition.d.ts +8 -1
  124. package/linter/rules/unused-definition.js +126 -1
  125. package/package.json +22 -10
  126. package/project/context/abstract-flowr-analyzer-context.js +7 -1
  127. package/project/context/flowr-analyzer-context.d.ts +8 -0
  128. package/project/context/flowr-analyzer-context.js +10 -0
  129. package/project/context/flowr-analyzer-dependencies-context.d.ts +28 -4
  130. package/project/context/flowr-analyzer-dependencies-context.js +51 -2
  131. package/project/context/flowr-analyzer-files-context.d.ts +1 -0
  132. package/project/context/flowr-analyzer-files-context.js +2 -1
  133. package/project/context/flowr-analyzer-functions-context.js +1 -1
  134. package/project/context/flowr-file.d.ts +5 -0
  135. package/project/context/flowr-file.js +5 -0
  136. package/project/flowr-analyzer-builder.js +12 -2
  137. package/project/plugins/file-plugins/files/flowr-description-file.js +6 -3
  138. package/project/plugins/file-plugins/files/flowr-namespace-file.js +9 -3
  139. package/project/plugins/file-plugins/files/flowr-news-file.js +1 -3
  140. package/project/plugins/file-plugins/flowr-analyzer-inst-file-plugin.d.ts +26 -0
  141. package/project/plugins/file-plugins/flowr-analyzer-inst-file-plugin.js +39 -0
  142. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-description-file-plugin.js +1 -1
  143. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-lockfile-plugin.js +2 -2
  144. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-namespace-file-plugin.js +1 -0
  145. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.d.ts +18 -2
  146. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-plugin.js +19 -0
  147. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +120 -0
  148. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +518 -0
  149. package/project/plugins/package-version-plugins/package.d.ts +5 -3
  150. package/project/plugins/package-version-plugins/package.js +27 -25
  151. package/project/plugins/plugin-registry.d.ts +3 -2
  152. package/project/plugins/plugin-registry.js +4 -2
  153. package/project/plugins/project-discovery/flowr-analyzer-gitignore-project-discovery-plugin.js +7 -2
  154. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +3 -1
  155. package/project/sigdb/build.d.ts +131 -0
  156. package/project/sigdb/build.js +628 -0
  157. package/project/sigdb/codec.d.ts +51 -0
  158. package/project/sigdb/codec.js +122 -0
  159. package/project/sigdb/decode.d.ts +58 -0
  160. package/project/sigdb/decode.js +129 -0
  161. package/project/sigdb/decompress.d.ts +44 -0
  162. package/project/sigdb/decompress.js +176 -0
  163. package/project/sigdb/hash.d.ts +9 -0
  164. package/project/sigdb/hash.js +54 -0
  165. package/project/sigdb/index-format.d.ts +40 -0
  166. package/project/sigdb/index-format.js +28 -0
  167. package/project/sigdb/manifest.d.ts +68 -0
  168. package/project/sigdb/manifest.js +146 -0
  169. package/project/sigdb/reader.d.ts +250 -0
  170. package/project/sigdb/reader.js +692 -0
  171. package/project/sigdb/schema.d.ts +196 -0
  172. package/project/sigdb/schema.js +33 -0
  173. package/project/sigdb/sigdb-download.d.ts +65 -0
  174. package/project/sigdb/sigdb-download.js +237 -0
  175. package/project/sigdb/signature-match.d.ts +26 -0
  176. package/project/sigdb/signature-match.js +40 -0
  177. package/project/sigdb/version.d.ts +20 -0
  178. package/project/sigdb/version.js +55 -0
  179. package/queries/catalog/call-context-query/call-context-query-executor.js +1 -3
  180. package/queries/catalog/config-query/config-query-format.d.ts +3 -1
  181. package/queries/catalog/config-query/config-query-format.js +68 -9
  182. package/queries/catalog/dataflow-query/dataflow-query-format.js +11 -1
  183. package/queries/catalog/dependencies-query/dependencies-query-executor.js +1 -1
  184. package/queries/catalog/linter-query/linter-query-executor.d.ts +2 -0
  185. package/queries/catalog/linter-query/linter-query-executor.js +6 -1
  186. package/queries/catalog/linter-query/linter-query-format.d.ts +2 -1
  187. package/queries/catalog/linter-query/linter-query-format.js +40 -8
  188. package/queries/catalog/project-query/project-query-executor.d.ts +15 -0
  189. package/queries/catalog/project-query/project-query-executor.js +96 -4
  190. package/queries/catalog/project-query/project-query-format.d.ts +44 -0
  191. package/queries/catalog/project-query/project-query-format.js +33 -2
  192. package/queries/catalog/signature-query/signature-query-executor.d.ts +29 -0
  193. package/queries/catalog/signature-query/signature-query-executor.js +461 -0
  194. package/queries/catalog/signature-query/signature-query-format.d.ts +138 -0
  195. package/queries/catalog/signature-query/signature-query-format.js +76 -0
  196. package/queries/catalog/signature-query/signature-query-render.d.ts +15 -0
  197. package/queries/catalog/signature-query/signature-query-render.js +155 -0
  198. package/queries/catalog/static-slice-query/static-slice-query-executor.js +9 -3
  199. package/queries/catalog/static-slice-query/static-slice-query-format.d.ts +10 -0
  200. package/queries/catalog/static-slice-query/static-slice-query-format.js +19 -1
  201. package/queries/query-print.js +5 -0
  202. package/queries/query.d.ts +10 -1
  203. package/queries/query.js +5 -2
  204. package/r-bridge/init.js +5 -1
  205. package/r-bridge/lang-4.x/ast/model/nodes/r-function-call.d.ts +10 -0
  206. package/r-bridge/lang-4.x/ast/model/nodes/r-function-call.js +55 -0
  207. package/r-bridge/lang-4.x/ast/model/processing/node-id.d.ts +16 -0
  208. package/r-bridge/lang-4.x/ast/model/processing/node-id.js +27 -0
  209. package/r-bridge/lang-4.x/ast/parser/json/format.js +89 -2
  210. package/r-bridge/lang-4.x/ast/parser/main/internal/structure/normalize-expressions.js +2 -4
  211. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize.js +2 -1
  212. package/r-bridge/parser.d.ts +2 -0
  213. package/r-bridge/retriever.js +4 -1
  214. package/r-bridge/roxygen2/documentation-provider.js +2 -1
  215. package/r-bridge/shell.d.ts +5 -0
  216. package/r-bridge/shell.js +17 -1
  217. package/reconstruct/inline/source-inline-map.d.ts +48 -0
  218. package/reconstruct/inline/source-inline-map.js +94 -0
  219. package/reconstruct/reconstruct.d.ts +19 -2
  220. package/reconstruct/reconstruct.js +79 -16
  221. package/search/search-executor/search-generators.js +5 -22
  222. package/search/search-executor/search-transformer.js +10 -6
  223. package/slicing/criterion/parse.d.ts +22 -4
  224. package/slicing/criterion/parse.js +125 -18
  225. package/slicing/static/slice-call.d.ts +24 -1
  226. package/slicing/static/slice-call.js +90 -0
  227. package/slicing/static/static-slicer.d.ts +7 -0
  228. package/slicing/static/static-slicer.js +38 -3
  229. package/util/collections/arrays.d.ts +4 -5
  230. package/util/collections/arrays.js +7 -18
  231. package/util/hash.d.ts +14 -0
  232. package/util/hash.js +31 -0
  233. package/util/mermaid/dfg.d.ts +7 -2
  234. package/util/mermaid/dfg.js +53 -13
  235. package/util/r-base-packages.d.ts +19 -0
  236. package/util/r-base-packages.js +72 -0
  237. package/util/r-license.js +2 -10
  238. package/util/r-version.d.ts +45 -15
  239. package/util/r-version.js +97 -36
  240. package/util/range.d.ts +15 -0
  241. package/util/range.js +39 -0
  242. package/util/schema.d.ts +10 -0
  243. package/util/schema.js +22 -0
  244. package/util/text/ansi.d.ts +3 -0
  245. package/util/text/ansi.js +10 -0
  246. package/util/text/args.js +1 -2
  247. package/util/version.js +28 -8
  248. package/data/pkgdb/pkgdb-latest.json.br +0 -0
  249. package/data/pkgdb/pkgdb-tiny.json.br +0 -0
  250. package/documentation/wiki-package-database.d.ts +0 -9
  251. package/documentation/wiki-package-database.js +0 -63
  252. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-pkgdb-plugin.d.ts +0 -63
  253. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-pkgdb-plugin.js +0 -176
  254. package/project/plugins/package-version-plugins/pkgdb.d.ts +0 -133
  255. package/project/plugins/package-version-plugins/pkgdb.js +0 -370
@@ -76,15 +76,10 @@ function reconstructRawBinaryOperator(lhs, n, rhs) {
76
76
  ];
77
77
  }
78
78
  function reconstructUnaryOp(leaf, operand, configuration) {
79
- if (configuration.selection.has(leaf.info.id)) {
80
- return foldToConst(leaf);
81
- }
82
- else if (operand.length === 0) {
79
+ if (!configuration.selection.has(leaf.info.id) && operand.length === 0) {
83
80
  return [];
84
81
  }
85
- else {
86
- return foldToConst(leaf);
87
- }
82
+ return foldToConst(leaf);
88
83
  }
89
84
  function reconstructBinaryOp(n, lhs, rhs, config) {
90
85
  if (lhs.length === 0 && rhs.length === 0) {
@@ -333,8 +328,49 @@ function reconstructSpecialInfixFunctionCall(args, call) {
333
328
  }
334
329
  return plain(`${getLexeme(call.arguments[0])} ${identifier_1.Identifier.toString(call.functionName.content)} ${getLexeme(call.arguments[1])}`);
335
330
  }
331
+ /**
332
+ * If `inlineSources` is active and this call is a selected `source()` that we can resolve, this returns the
333
+ * reconstruction to splice in place of the call (or the literal call at a cycle edge). It returns `undefined`
334
+ * to signal that the call should be reconstructed as usual (e.g., an unresolvable `source()`).
335
+ */
336
+ function tryInlineSourceCall(call, config) {
337
+ const id = call.info.id;
338
+ const targetFile = config.sourceMap?.get(id);
339
+ if (targetFile !== undefined) {
340
+ const visited = config.visited ?? new Set([config.currentFile ?? 0]);
341
+ const path = config.fullAst.ast.files[targetFile]?.filePath;
342
+ if (visited.has(targetFile)) {
343
+ // cyclic source() - keep the literal call and mark the cycle edge
344
+ config.warnings?.push({ kind: 'cycle', callId: id, path });
345
+ exports.reconstructLogger.warn(`cyclic source() not inlined at node ${JSON.stringify(id)}: ${JSON.stringify(path)}`);
346
+ const literal = plain(getLexeme(call));
347
+ literal.push({ line: `# [flowR] cyclic source() not inlined: ${path ?? '<unknown>'}`, indent: 0 });
348
+ return literal;
349
+ }
350
+ const childConfig = {
351
+ ...config,
352
+ visited: new Set([...visited, config.currentFile ?? 0, targetFile]),
353
+ currentFile: targetFile
354
+ };
355
+ return stripOuterExpressionList(reconstructFileCode(config.fullAst, targetFile, childConfig));
356
+ }
357
+ // a selected source() that we could not link to a file (dynamic/missing path): keep it verbatim
358
+ if (call.named && call.functionName.lexeme === 'source') {
359
+ const arg = call.arguments[0];
360
+ const path = arg !== undefined && arg !== r_function_call_1.EmptyArgument && arg.value?.type === type_1.RType.String ? arg.value.content.str : undefined;
361
+ config.warnings?.push({ kind: 'unresolved', callId: id, path });
362
+ exports.reconstructLogger.warn(`unresolved source() not inlined at node ${JSON.stringify(id)}: ${JSON.stringify(path)}`);
363
+ }
364
+ return undefined;
365
+ }
336
366
  function reconstructFunctionCall(call, functionName, args, configuration) {
337
367
  const selected = isSelected(configuration, call);
368
+ if (configuration.inlineSources && selected) {
369
+ const inlined = tryInlineSourceCall(call, configuration);
370
+ if (inlined !== undefined) {
371
+ return inlined;
372
+ }
373
+ }
338
374
  if (!selected) {
339
375
  const f = args.filter(a => a !== r_function_call_1.EmptyArgument && a.length !== 0);
340
376
  if (f.length === 0) {
@@ -410,14 +446,22 @@ function getIndentString(indent) {
410
446
  function prettyPrintCodeToString(code, lf = '\n') {
411
447
  return code.map(({ line, indent }) => `${getIndentString(indent)}${line}`).join(lf);
412
448
  }
413
- function removeOuterExpressionListIfApplicable(result) {
449
+ /** Removes a redundant outer `{ }` block (de-indenting its content) if present. */
450
+ function stripOuterExpressionList(result) {
414
451
  if (result.length > 1 && result[0].line === '{' && result[result.length - 1].line === '}') {
415
- // remove outer block
416
- return prettyPrintCodeToString(indentBy(result.slice(1, result.length - 1), -1));
452
+ return indentBy(result.slice(1, result.length - 1), -1);
417
453
  }
418
- else {
419
- return prettyPrintCodeToString(result);
454
+ return result;
455
+ }
456
+ function removeOuterExpressionListIfApplicable(result) {
457
+ return prettyPrintCodeToString(stripOuterExpressionList(result));
458
+ }
459
+ /** Folds a single file of the project into {@link Code}, reused by the top-level reconstruction and the `source()` inlining recursion. */
460
+ function reconstructFileCode(ast, fileIndex, config) {
461
+ if (exports.reconstructLogger.settings.minLevel <= 1 /* LogLevel.Trace */) {
462
+ exports.reconstructLogger.trace(`reconstructing file index ${fileIndex} with root id ${ast.ast.files[fileIndex].root.info.id}`);
420
463
  }
464
+ return (0, stateful_fold_1.foldAstStateful)(ast.ast.files[fileIndex].root, config, reconstructAstFolds);
421
465
  }
422
466
  /**
423
467
  * Reconstructs parts of a normalized R ast into R code on an expression basis.
@@ -441,15 +485,34 @@ function reconstructToCode(ast, selection, autoSelectIf = auto_select_defaults_1
441
485
  }
442
486
  return result;
443
487
  };
488
+ // when inlining sources we produce a single self-contained file (the main file, index 0),
489
+ // splicing every resolvable `source()` in place; this overrides `reconstructFiles`.
490
+ if (selection.inlineSources) {
491
+ const warnings = [];
492
+ const code = removeOuterExpressionListIfApplicable(reconstructFileCode(ast, 0, {
493
+ selection: selection.nodes,
494
+ autoSelectIf: autoSelectIfWrapper,
495
+ fullAst: ast,
496
+ inlineSources: true,
497
+ sourceMap: selection.sourceMap ?? new Map(),
498
+ visited: new Set([0]),
499
+ currentFile: 0,
500
+ warnings
501
+ }));
502
+ return {
503
+ code,
504
+ linesWithAutoSelected: linesWithAutoSelected.size,
505
+ inlineWarnings: warnings
506
+ };
507
+ }
444
508
  const indices = selection.reconstructFiles === 'all' ? ast.ast.files.map((_, i) => i) : (selection.reconstructFiles ?? [0]);
445
509
  (0, assert_1.guard)(indices.every(i => i >= 0 && i < ast.ast.files.length), `reconstructToCode: reconstructFiles contains invalid file indices: ${JSON.stringify(indices)} for ast with ${ast.ast.files.length} files`);
446
510
  const results = [];
447
511
  // fold of the normalized ast
448
512
  for (const i of indices) {
449
- if (exports.reconstructLogger.settings.minLevel <= 1 /* LogLevel.Trace */) {
450
- exports.reconstructLogger.trace(`reconstructing file index ${i} with root id ${ast.ast.files[i].root.info.id}`);
451
- }
452
- results.push(removeOuterExpressionListIfApplicable((0, stateful_fold_1.foldAstStateful)(ast.ast.files[i].root, { selection: selection.nodes, autoSelectIf: autoSelectIfWrapper, fullAst: ast }, reconstructAstFolds)));
513
+ results.push(removeOuterExpressionListIfApplicable(reconstructFileCode(ast, i, {
514
+ selection: selection.nodes, autoSelectIf: autoSelectIfWrapper, fullAst: ast, currentFile: i
515
+ })));
453
516
  }
454
517
  (0, log_1.expensiveTrace)(exports.reconstructLogger, () => `reconstructed ast before string conversion: ${JSON.stringify(results)}`);
455
518
  return {
@@ -48,27 +48,9 @@ async function generateGet(input, { filter: { line, column, id, name, nameIsRege
48
48
  }
49
49
  if (fuzzy) {
50
50
  (0, assert_1.guard)(line, 'Fuzzy location matching requires line to be provided');
51
- potentials = potentials.filter(node => {
52
- const range = range_1.SourceRange.fromNode(node);
53
- if (!range) {
54
- return false;
55
- }
56
- return column === undefined ? (range[0] <= line && line <= range[2]) : range_1.SourceRange.containsPosition(range, line, column);
57
- });
58
- if (innermostOnly && potentials.length > 1) {
59
- potentials = potentials.filter(node => {
60
- const range = range_1.SourceRange.fromNode(node);
61
- return range && !potentials.some(other => {
62
- if (other === node) {
63
- return false;
64
- }
65
- else if (other.info.parent === node.info.id) {
66
- return true;
67
- }
68
- const otherRange = range_1.SourceRange.fromNode(other);
69
- return otherRange && range_1.SourceRange.isStrictSubsetOf(otherRange, range);
70
- });
71
- });
51
+ potentials = range_1.SourceRange.nodesContaining(potentials, line, column);
52
+ if (innermostOnly) {
53
+ potentials = range_1.SourceRange.innermostNodes(potentials);
72
54
  }
73
55
  }
74
56
  else if (line && column) {
@@ -95,6 +77,7 @@ function generateFrom(_input, args) {
95
77
  async function generateFromQuery(input, args) {
96
78
  const result = await (0, query_1.executeQueries)({ analyzer: input }, args.from);
97
79
  // collect involved nodes
80
+ const { idMap } = await input.normalize();
98
81
  const nodesByQuery = new Map();
99
82
  for (const [query, content] of Object.entries(result)) {
100
83
  if (query === '.meta') {
@@ -103,7 +86,7 @@ async function generateFromQuery(input, args) {
103
86
  const nodes = new Set();
104
87
  const queryDef = query_1.SupportedQueries[query];
105
88
  for (const node of queryDef.flattenInvolvedNodes(content, args.from, args.certainty)) {
106
- nodes.add({ node: (await input.normalize()).idMap.get(node) });
89
+ nodes.add({ node: idMap.get(node) });
107
90
  }
108
91
  nodesByQuery.set(query, nodes);
109
92
  }
@@ -112,11 +112,15 @@ data, elements, other) {
112
112
  return elements.addAll([...resultOther.getElements()]);
113
113
  }
114
114
  function getUnique(data, elements) {
115
- return elements.mutate(e => e.reduce((acc, cur) => {
116
- if (!acc.some(el => el.node.id === cur.node.id)) {
117
- acc.push(cur);
118
- }
119
- return acc;
120
- }, []));
115
+ return elements.mutate(e => {
116
+ const seen = new Set();
117
+ return e.filter(cur => {
118
+ if (seen.has(cur.node.id)) {
119
+ return false;
120
+ }
121
+ seen.add(cur.node.id);
122
+ return true;
123
+ });
124
+ });
121
125
  }
122
126
  //# sourceMappingURL=search-transformer.js.map
@@ -1,7 +1,12 @@
1
1
  import { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id';
2
2
  import type { AstIdMap } from '../../r-bridge/lang-4.x/ast/model/processing/decorate';
3
- /** Either `line:column`, `line@variable-name`, or `$id` */
4
- export type SlicingCriterion = `${number}:${number}` | `${number}@${string}` | `$${NodeId | number}`;
3
+ /** An optional `(file-regex)` suffix restricting a criterion to nodes stemming from a matching file. */
4
+ type FileFilterSuffix = '' | `(${string})`;
5
+ /**
6
+ * Either `line:column`, `line~column`, `line@variable-name`, or `$id`; all but `$id` accept a trailing
7
+ * `(file-regex)`. See {@link SlicingCriterion.tryParse} for what each of them resolves to.
8
+ */
9
+ export type SlicingCriterion = `${number}:${number}${FileFilterSuffix}` | `${number}~${number}${FileFilterSuffix}` | `${number}@${string}` | `$${NodeId | number}`;
5
10
  /**
6
11
  * The helper object associated with {@link SlicingCriterion} which makes it easy
7
12
  * to parse, validate and resolve slicing criteria.
@@ -9,12 +14,23 @@ export type SlicingCriterion = `${number}:${number}` | `${number}@${string}` | `
9
14
  export declare const SlicingCriterion: {
10
15
  readonly name: "SlicingCriterion";
11
16
  /**
12
- * Takes a criterion in the form of `line:column` or `line@variable-name` and returns the corresponding node id
17
+ * Takes a criterion in the form of `line:column`, `line~column`, or `line@variable-name` and returns the corresponding node id
13
18
  * @see {@link SlicingCriterion.tryParse} for a version that does not throw an error
14
19
  */
15
20
  readonly parse: (this: void, criterion: SlicingCriterion, idMap: AstIdMap) => NodeId;
16
21
  /**
17
22
  * Tries to resolve a slicing criterion to an id, but does not throw an error if it fails.
23
+ *
24
+ * | Criterion | Resolves to |
25
+ * | --------- | ----------- |
26
+ * | `2@x` | `x` in line 2, preferring a call over the symbol it refers to |
27
+ * | `2@[3]x` | the 3rd occurrence of `x` in line 2 (by column); `[-1]` for the last |
28
+ * | `2:5` | the element *starting* at line 2, column 5 |
29
+ * | `2~5` | the innermost element *containing* line 2, column 5 |
30
+ * | `$42` | the node with the normalized id 42 |
31
+ *
32
+ * A negative line counts from the end of the input (`-1` being the last line). Every criterion but `$id`
33
+ * accepts a trailing `(file-regex)` (e.g. `2@x(tmp/.*)`) restricting it to a matching file.
18
34
  * @see {@link SlicingCriterion.parse} for the version that throws an error
19
35
  */
20
36
  readonly tryParse: (this: void, criterion: SlicingCriterion | NodeId, idMap: AstIdMap) => NodeId | undefined;
@@ -24,7 +40,8 @@ export declare const SlicingCriterion: {
24
40
  readonly fromId: (this: void, id: NodeId) => SlicingCriterion;
25
41
  };
26
42
  /**
27
- * A slicing criterion is a list of single slicing criteria, which can be in the form of `line:column`, `line@variable-name`, or `$id`.
43
+ * A slicing criterion is a list of single slicing criteria, which can be in the form of `line:column`,
44
+ * `line~column`, `line@variable-name`, or `$id`.
28
45
  */
29
46
  export type SlicingCriteria = SlicingCriterion[];
30
47
  export interface DecodedCriterion {
@@ -54,3 +71,4 @@ export declare const SlicingCriteria: {
54
71
  export declare class CriteriaParseError extends Error {
55
72
  constructor(message: string);
56
73
  }
74
+ export {};
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.CriteriaParseError = exports.SlicingCriteria = exports.SlicingCriterion = void 0;
4
+ const range_1 = require("../../util/range");
4
5
  const log_1 = require("../../util/log");
5
6
  const node_id_1 = require("../../r-bridge/lang-4.x/ast/model/processing/node-id");
6
7
  const static_slicer_1 = require("../static/static-slicer");
@@ -12,7 +13,7 @@ const type_1 = require("../../r-bridge/lang-4.x/ast/model/type");
12
13
  exports.SlicingCriterion = {
13
14
  name: 'SlicingCriterion',
14
15
  /**
15
- * Takes a criterion in the form of `line:column` or `line@variable-name` and returns the corresponding node id
16
+ * Takes a criterion in the form of `line:column`, `line~column`, or `line@variable-name` and returns the corresponding node id
16
17
  * @see {@link SlicingCriterion.tryParse} for a version that does not throw an error
17
18
  */
18
19
  parse(criterion, idMap) {
@@ -24,6 +25,17 @@ exports.SlicingCriterion = {
24
25
  },
25
26
  /**
26
27
  * Tries to resolve a slicing criterion to an id, but does not throw an error if it fails.
28
+ *
29
+ * | Criterion | Resolves to |
30
+ * | --------- | ----------- |
31
+ * | `2@x` | `x` in line 2, preferring a call over the symbol it refers to |
32
+ * | `2@[3]x` | the 3rd occurrence of `x` in line 2 (by column); `[-1]` for the last |
33
+ * | `2:5` | the element *starting* at line 2, column 5 |
34
+ * | `2~5` | the innermost element *containing* line 2, column 5 |
35
+ * | `$42` | the node with the normalized id 42 |
36
+ *
37
+ * A negative line counts from the end of the input (`-1` being the last line). Every criterion but `$id`
38
+ * accepts a trailing `(file-regex)` (e.g. `2@x(tmp/.*)`) restricting it to a matching file.
27
39
  * @see {@link SlicingCriterion.parse} for the version that throws an error
28
40
  */
29
41
  tryParse(criterion, idMap) {
@@ -31,15 +43,31 @@ exports.SlicingCriterion = {
31
43
  if (criterion.startsWith('$')) {
32
44
  return node_id_1.NodeId.normalize(criterion.substring(1));
33
45
  }
34
- else if (criterion.includes('@')) {
35
- const at = criterion.indexOf('@');
36
- const line = parseInt(criterion.substring(0, at));
37
- const name = criterion.substring(at + 1);
38
- return conventionalCriteriaToId(line, name, idMap);
46
+ const split = splitFileFilter(criterion);
47
+ if (split === undefined) {
48
+ return undefined; // a malformed file filter must not silently resolve without it
39
49
  }
40
- else if (criterion.includes(':')) {
41
- const [line, column] = criterion.split(':').map(c => parseInt(c));
42
- return locationToId([line, column], idMap);
50
+ const { rest: base, file } = split;
51
+ if (base.includes('@')) {
52
+ const at = base.indexOf('@');
53
+ const line = parseLineNumber(base.substring(0, at), idMap, file);
54
+ const name = base.substring(at + 1);
55
+ if (line === undefined || name.length === 0) {
56
+ return undefined;
57
+ }
58
+ // an optional `[n]` prefix picks the n-th occurrence within the line (`2@[2]a`, `2@[-1]a` for the last one)
59
+ const nth = /^\[(-?\d+)](.+)$/.exec(name);
60
+ return nth ?
61
+ nthOccurrenceToId(line, nth[2], idMap, parseInt(nth[1]), file) :
62
+ nthOccurrenceToId(line, name, idMap, 1, file);
63
+ }
64
+ else if (base.includes(':')) {
65
+ const location = parseLocation(base, ':', idMap, file);
66
+ return location && locationToId(location, idMap, file);
67
+ }
68
+ else if (base.includes('~')) {
69
+ const location = parseLocation(base, '~', idMap, file);
70
+ return location && fuzzyLocationToId(location, idMap, file);
43
71
  }
44
72
  },
45
73
  /**
@@ -79,10 +107,10 @@ class CriteriaParseError extends Error {
79
107
  }
80
108
  }
81
109
  exports.CriteriaParseError = CriteriaParseError;
82
- function locationToId(location, dataflowIdMap) {
110
+ function locationToId(location, dataflowIdMap, file) {
83
111
  let candidate;
84
112
  for (const [id, nodeInfo] of dataflowIdMap.entries()) {
85
- if (nodeInfo.location === undefined || nodeInfo.location[0] !== location[0] || nodeInfo.location[1] !== location[1]) {
113
+ if (nodeInfo.location === undefined || nodeInfo.location[0] !== location[0] || nodeInfo.location[1] !== location[1] || !matchesFile(nodeInfo, file)) {
86
114
  continue; // only consider those with position information
87
115
  }
88
116
  (0, log_1.expensiveTrace)(static_slicer_1.slicerLogger, () => `can resolve id ${id} (${JSON.stringify(nodeInfo.location)}) for location ${JSON.stringify(location)}`);
@@ -94,18 +122,97 @@ function locationToId(location, dataflowIdMap) {
94
122
  }
95
123
  return candidate?.info.id;
96
124
  }
97
- function conventionalCriteriaToId(line, name, dataflowIdMap) {
98
- let candidate;
125
+ /**
126
+ * Resolves a `line~column` criterion: unlike {@link locationToId}, which wants a node *starting* exactly there,
127
+ * this accepts any node whose source range *contains* the position and returns the innermost of them (the same
128
+ * matching the search API performs for `fuzzy` with `innermostOnly`).
129
+ */
130
+ function fuzzyLocationToId(location, dataflowIdMap, file) {
131
+ const potentials = [...dataflowIdMap.values()].filter(nodeInfo =>
132
+ // arguments and expression lists only wrap their content, sharing its range, so they never say more than it
133
+ nodeInfo.type !== type_1.RType.Argument && nodeInfo.type !== type_1.RType.ExpressionList && matchesFile(nodeInfo, file));
134
+ /* a call shares its range with the symbol naming it, so keep both (`treatChildAsInner: false`) and let the
135
+ * preference below decide, rather than always landing on the symbol */
136
+ const candidates = range_1.SourceRange.innermostNodes(range_1.SourceRange.nodesContaining(potentials, location[0], location[1]), false);
137
+ // prefer the call over the symbol it refers to, exactly as locationToId does
138
+ return (candidates.find(n => n.type === type_1.RType.FunctionCall) ?? candidates[0])?.info.id;
139
+ }
140
+ /**
141
+ * Splits the optional trailing `(file-regex)` off a criterion (e.g. `2@x(tmp/.*)`), which restricts it to nodes
142
+ * originating from a matching file. Returns `undefined` if the regex is malformed.
143
+ */
144
+ function splitFileFilter(criterion) {
145
+ const match = /^(.*)\(([^()]*)\)$/.exec(criterion);
146
+ if (match === null) {
147
+ return { rest: criterion, file: undefined };
148
+ }
149
+ try {
150
+ return { rest: match[1], file: new RegExp(match[2]) };
151
+ }
152
+ catch {
153
+ return undefined;
154
+ }
155
+ }
156
+ /** Whether the node stems from a file matching the criterion's `(file-regex)` suffix (if any). */
157
+ function matchesFile(nodeInfo, file) {
158
+ return file === undefined || file.test(nodeInfo.info.file ?? '');
159
+ }
160
+ /**
161
+ * The last line covered by the given AST (restricted to `file`), used to resolve lines counted from the end.
162
+ */
163
+ function lastLineOf(dataflowIdMap, file) {
164
+ let last = 0;
99
165
  for (const nodeInfo of dataflowIdMap.values()) {
100
- if (nodeInfo.location === undefined || nodeInfo.location[0] !== line || nodeInfo.lexeme !== name) {
166
+ const range = range_1.SourceRange.fromNode(nodeInfo);
167
+ if (range !== undefined && range[2] > last && matchesFile(nodeInfo, file)) {
168
+ last = range[2];
169
+ }
170
+ }
171
+ return last;
172
+ }
173
+ /**
174
+ * Parses the line part of a criterion, resolving a negative line (`-1` being the last line) against the AST.
175
+ * Returns `undefined` if it is not a number at all (e.g. `x@y`), so the criterion can be rejected as invalid.
176
+ */
177
+ function parseLineNumber(text, dataflowIdMap, file) {
178
+ if (!/^-?\d+$/.test(text)) {
179
+ return undefined;
180
+ }
181
+ const line = parseInt(text);
182
+ return line < 0 ? lastLineOf(dataflowIdMap, file) + line + 1 : line;
183
+ }
184
+ /** Parses a `line<sep>column` criterion, rejecting anything that is not a pair of numbers. */
185
+ function parseLocation(criterion, separator, dataflowIdMap, file) {
186
+ const parts = criterion.split(separator);
187
+ if (parts.length !== 2 || !/^\d+$/.test(parts[1])) {
188
+ return undefined;
189
+ }
190
+ const line = parseLineNumber(parts[0], dataflowIdMap, file);
191
+ return line === undefined ? undefined : [line, parseInt(parts[1])];
192
+ }
193
+ /**
194
+ * Resolves the `nth` occurrence of `name` in the given line (as written by the optional `[n]` prefix of
195
+ * `line@[n]name`); `n` is 1-based and may be negative to count from the end of the line (`-1` being the last).
196
+ * Occurrences are counted by column, as a function call and the symbol it refers to share a position and are
197
+ * thus one and the same occurrence.
198
+ */
199
+ function nthOccurrenceToId(line, name, dataflowIdMap, nth, file) {
200
+ const byColumn = new Map();
201
+ for (const nodeInfo of dataflowIdMap.values()) {
202
+ if (nodeInfo.location === undefined || nodeInfo.location[0] !== line || nodeInfo.lexeme !== name || !matchesFile(nodeInfo, file)) {
101
203
  continue;
102
204
  }
103
- // function calls have the same location as the symbol they refer to, so we need to prefer the function call
104
- if (candidate !== undefined && nodeInfo.type !== type_1.RType.FunctionCall || nodeInfo.type === type_1.RType.Argument || nodeInfo.type === type_1.RType.ExpressionList) {
205
+ if (nodeInfo.type === type_1.RType.Argument || nodeInfo.type === type_1.RType.ExpressionList) {
105
206
  continue;
106
207
  }
107
- candidate = nodeInfo;
208
+ const column = nodeInfo.location[1];
209
+ // function calls have the same location as the symbol they refer to, so we need to prefer the function call
210
+ if (!byColumn.has(column) || nodeInfo.type === type_1.RType.FunctionCall) {
211
+ byColumn.set(column, nodeInfo);
212
+ }
108
213
  }
109
- return candidate?.info.id;
214
+ const columns = [...byColumn.keys()].sort((a, b) => a - b);
215
+ const index = nth < 0 ? columns.length + nth : nth - 1;
216
+ return index >= 0 && index < columns.length ? byColumn.get(columns[index])?.info.id : undefined;
110
217
  }
111
218
  //# sourceMappingURL=parse.js.map
@@ -1,17 +1,40 @@
1
1
  import type { NodeToSlice } from './slicer-types';
2
2
  import type { VisitingQueue } from './visiting-queue';
3
3
  import { type Fingerprint } from './fingerprint';
4
- import type { DataflowGraphVertexFunctionCall, DataflowGraphVertexInfo } from '../../dataflow/graph/vertex';
4
+ import { type DataflowGraphVertexFunctionCall, type DataflowGraphVertexInfo } from '../../dataflow/graph/vertex';
5
5
  import type { REnvironmentInformation } from '../../dataflow/environments/environment';
6
6
  import { type DataflowGraph, type OutgoingEdges } from '../../dataflow/graph/graph';
7
7
  import { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id';
8
8
  import type { DataflowInformation } from '../../dataflow/info';
9
9
  import type { ReadOnlyFlowrAnalyzerContext } from '../../project/context/flowr-analyzer-context';
10
+ import type { AstIdMap } from '../../r-bridge/lang-4.x/ast/model/processing/decorate';
10
11
  /**
11
12
  * Returns the function call targets (definitions) by the given caller
12
13
  */
13
14
  export declare function getAllFunctionCallTargetsForSlice(dataflowGraph: DataflowGraph, callerInfo: DataflowGraphVertexFunctionCall, baseEnvironment: REnvironmentInformation, queue: VisitingQueue, ctx: ReadOnlyFlowrAnalyzerContext): [Set<DataflowGraphVertexInfo>, REnvironmentInformation];
14
15
  /** returns the new threshold hit count */
15
16
  export declare function sliceForCall(current: NodeToSlice, callerInfo: DataflowGraphVertexFunctionCall, { graph }: DataflowInformation, queue: VisitingQueue, ctx: ReadOnlyFlowrAnalyzerContext): void;
17
+ /**
18
+ * Finds the nearest enclosing function-definition node for the given id by walking up the AST parent chain.
19
+ * Used by `includeCallees` to detect the function-definition boundary a node sits inside, as backward slicing
20
+ * does not otherwise visit the function-definition vertex itself (nothing within the body links to it).
21
+ */
22
+ export declare function findEnclosingFunctionDefinition(id: NodeId, idMap: AstIdMap): NodeId | undefined;
23
+ /**
24
+ * For `includeCallees`: decides whether the current slice of a function definition's body actually depends on
25
+ * the function's interface, i.e., whether the callers can influence the sliced result at all. This is the case iff
26
+ * the slice reaches one of the definition's parameters, or it reads a free reference captured from the enclosing
27
+ * scope. If the sliced body is self-contained (only locally-defined variables, no parameter and no captured
28
+ * variable), the callers are irrelevant and the boundary must not be crossed.
29
+ */
30
+ export declare function sliceReachesFunctionInterface(fnDefId: NodeId, graph: DataflowGraph, queue: VisitingQueue, idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext): boolean;
31
+ /**
32
+ * For `includeCallees`: given the id of a function-definition vertex, enqueues the vertex that binds/defines
33
+ * the function (e.g. `f <- function...`, via the `defined-by` edge) as well as all of its call sites (via
34
+ * `calls` edges). Call site arguments are picked up automatically once the call vertex is processed normally,
35
+ * as `argument` edges are always traversed.
36
+ * This is the reverse of what {@link sliceForCall} does for call -\> definition linking.
37
+ */
38
+ export declare function includeCalleesOfDefinition(fnDefId: NodeId, graph: DataflowGraph, queue: VisitingQueue, baseEnvironment: REnvironmentInformation, baseEnvFingerprint: Fingerprint): void;
16
39
  /** Returns true if we found at least one return edge */
17
40
  export declare function handleReturns(from: NodeId, queue: VisitingQueue, currentEdges: OutgoingEdges, baseEnvFingerprint: Fingerprint, baseEnvironment: REnvironmentInformation): boolean;
@@ -2,10 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getAllFunctionCallTargetsForSlice = getAllFunctionCallTargetsForSlice;
4
4
  exports.sliceForCall = sliceForCall;
5
+ exports.findEnclosingFunctionDefinition = findEnclosingFunctionDefinition;
6
+ exports.sliceReachesFunctionInterface = sliceReachesFunctionInterface;
7
+ exports.includeCalleesOfDefinition = includeCalleesOfDefinition;
5
8
  exports.handleReturns = handleReturns;
6
9
  const assert_1 = require("../../util/assert");
7
10
  const fingerprint_1 = require("./fingerprint");
8
11
  const linker_1 = require("../../dataflow/internal/linker");
12
+ const vertex_1 = require("../../dataflow/graph/vertex");
9
13
  const graph_1 = require("../../dataflow/graph/graph");
10
14
  const resolve_by_name_1 = require("../../dataflow/environments/resolve-by-name");
11
15
  const edge_1 = require("../../dataflow/graph/edge");
@@ -13,6 +17,8 @@ const node_id_1 = require("../../r-bridge/lang-4.x/ast/model/processing/node-id"
13
17
  const identifier_1 = require("../../dataflow/environments/identifier");
14
18
  const built_in_function_definition_1 = require("../../dataflow/internal/process/functions/call/built-in/built-in-function-definition");
15
19
  const static_slicer_1 = require("./static-slicer");
20
+ const type_1 = require("../../r-bridge/lang-4.x/ast/model/type");
21
+ const model_1 = require("../../r-bridge/lang-4.x/ast/model/model");
16
22
  /**
17
23
  * Returns the function call targets (definitions) by the given caller
18
24
  */
@@ -74,6 +80,90 @@ function sliceForCall(current, callerInfo, { graph }, queue, ctx) {
74
80
  const activeEnvironmentFingerprint = (0, fingerprint_1.envFingerprint)(activeEnvironment);
75
81
  linkCallTargets(current.onlyForSideEffects, functionCallTargets, activeEnvironment, activeEnvironmentFingerprint, queue);
76
82
  }
83
+ /**
84
+ * Finds the nearest enclosing function-definition node for the given id by walking up the AST parent chain.
85
+ * Used by `includeCallees` to detect the function-definition boundary a node sits inside, as backward slicing
86
+ * does not otherwise visit the function-definition vertex itself (nothing within the body links to it).
87
+ */
88
+ function findEnclosingFunctionDefinition(id, idMap) {
89
+ let node = idMap.get(id);
90
+ while (node !== undefined) {
91
+ if (node.type === type_1.RType.FunctionDefinition) {
92
+ return node.info.id;
93
+ }
94
+ node = node.info.parent !== undefined ? idMap.get(node.info.parent) : undefined;
95
+ }
96
+ return undefined;
97
+ }
98
+ /**
99
+ * For `includeCallees`: decides whether the current slice of a function definition's body actually depends on
100
+ * the function's interface, i.e., whether the callers can influence the sliced result at all. This is the case iff
101
+ * the slice reaches one of the definition's parameters, or it reads a free reference captured from the enclosing
102
+ * scope. If the sliced body is self-contained (only locally-defined variables, no parameter and no captured
103
+ * variable), the callers are irrelevant and the boundary must not be crossed.
104
+ */
105
+ function sliceReachesFunctionInterface(fnDefId, graph, queue, idMap, ctx) {
106
+ const vertex = graph.getVertex(fnDefId);
107
+ if (vertex === undefined || vertex.tag !== vertex_1.VertexType.FunctionDefinition) {
108
+ return false;
109
+ }
110
+ // (a) the slice reaches a parameter of this definition
111
+ for (const paramId of Object.keys(vertex.params)) {
112
+ if (queue.hasId(node_id_1.NodeId.normalize(paramId))) {
113
+ return true;
114
+ }
115
+ }
116
+ // (b) a sliced body node captures a variable from the enclosing scope: it links (via `defined-by-on-call`, the
117
+ // closure/argument binding resolved at the call site) to a non-builtin definition that lives outside this body.
118
+ const fnNode = idMap.get(fnDefId);
119
+ const bodyIds = fnNode ? new Set(model_1.RNode.collectAllIds(fnNode)) : new Set();
120
+ for (const bodyId of bodyIds) {
121
+ if (!queue.hasId(bodyId)) {
122
+ continue;
123
+ }
124
+ const outgoing = graph.outgoingEdges(bodyId);
125
+ if (outgoing === undefined) {
126
+ continue;
127
+ }
128
+ for (const [target, edge] of outgoing) {
129
+ if (edge_1.DfEdge.includesType(edge, edge_1.EdgeType.DefinedByOnCall) && !node_id_1.NodeId.isBuiltIn(target) && !bodyIds.has(target)) {
130
+ return true;
131
+ }
132
+ }
133
+ }
134
+ // (c) fallback for captures that could not be resolved at definition time: an open in-reference that is in the
135
+ // slice and resolves to a non-builtin definition in the enclosing scope.
136
+ const definitionEnvironment = vertex.environment ?? ctx.env.makeCleanEnv();
137
+ for (const open of vertex.subflow.in) {
138
+ if (open.name === undefined || !queue.hasId(open.nodeId)) {
139
+ continue;
140
+ }
141
+ const resolved = (0, resolve_by_name_1.resolveByName)(open.name, definitionEnvironment, open.type ?? identifier_1.ReferenceType.Unknown);
142
+ if (resolved?.some(d => !node_id_1.NodeId.isBuiltIn(d.nodeId))) {
143
+ return true;
144
+ }
145
+ }
146
+ return false;
147
+ }
148
+ const CalleeBoundaryEdges = edge_1.EdgeType.DefinedBy | edge_1.EdgeType.Calls;
149
+ /**
150
+ * For `includeCallees`: given the id of a function-definition vertex, enqueues the vertex that binds/defines
151
+ * the function (e.g. `f <- function...`, via the `defined-by` edge) as well as all of its call sites (via
152
+ * `calls` edges). Call site arguments are picked up automatically once the call vertex is processed normally,
153
+ * as `argument` edges are always traversed.
154
+ * This is the reverse of what {@link sliceForCall} does for call -\> definition linking.
155
+ */
156
+ function includeCalleesOfDefinition(fnDefId, graph, queue, baseEnvironment, baseEnvFingerprint) {
157
+ const ingoing = graph.ingoingEdges(fnDefId);
158
+ if (ingoing === undefined) {
159
+ return;
160
+ }
161
+ for (const [source, edge] of ingoing) {
162
+ if (edge_1.DfEdge.includesType(edge, CalleeBoundaryEdges)) {
163
+ queue.add(source, baseEnvironment, baseEnvFingerprint, false);
164
+ }
165
+ }
166
+ }
77
167
  const PotentialFollowOnReturn = edge_1.EdgeType.DefinesOnCall | edge_1.EdgeType.DefinedByOnCall | edge_1.EdgeType.Argument;
78
168
  /** Returns true if we found at least one return edge */
79
169
  function handleReturns(from, queue, currentEdges, baseEnvFingerprint, baseEnvironment) {
@@ -34,6 +34,13 @@ export interface StaticSliceOptions {
34
34
  * Used by {@link staticDice} to pass a reduced-and-inverted graph in a single allocation.
35
35
  */
36
36
  readonly sliceGraph?: DataflowGraph;
37
+ /**
38
+ * If set (and slicing backward), continue the slice past a function-definition boundary: whenever the
39
+ * slice reaches a node that lives inside a function definition, also include the vertex that binds/defines
40
+ * the function (e.g. `f <- function(...)`) as well as all of its call sites (and their arguments).
41
+ * Defaults to `false` (slicing stops at the function-definition boundary, the historic behavior).
42
+ */
43
+ readonly includeCallees?: boolean;
37
44
  }
38
45
  /**
39
46
  * Computes the node ids to include in a static slice, starting from the given seed ids.