@eagleoutice/flowr 2.16.4 → 2.16.6

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 (64) hide show
  1. package/cli/repl/core.js +13 -2
  2. package/cli/repl/parser/slice-query-parser.d.ts +21 -5
  3. package/cli/repl/parser/slice-query-parser.js +33 -13
  4. package/core/steps/all/static-slicing/10-reconstruct.d.ts +2 -2
  5. package/dataflow/environments/built-in.d.ts +2 -0
  6. package/dataflow/environments/built-in.js +10 -2
  7. package/dataflow/environments/data-masking-functions.js +2 -1
  8. package/dataflow/environments/default-builtin-config.d.ts +31 -5
  9. package/dataflow/environments/default-builtin-config.js +12 -15
  10. package/dataflow/eval/resolve/alias-tracking.js +5 -2
  11. package/dataflow/eval/resolve/node-value.js +1 -1
  12. package/dataflow/eval/resolve/resolve-argument.js +2 -0
  13. package/dataflow/eval/resolve/resolve-strings.d.ts +10 -0
  14. package/dataflow/eval/resolve/resolve-strings.js +79 -12
  15. package/dataflow/extractor.js +11 -4
  16. package/dataflow/graph/applied-arguments.d.ts +5 -0
  17. package/dataflow/graph/applied-arguments.js +17 -0
  18. package/dataflow/graph/df-helper.js +2 -2
  19. package/dataflow/graph/graph.d.ts +5 -0
  20. package/dataflow/graph/graph.js +5 -0
  21. package/dataflow/info.js +8 -1
  22. package/dataflow/internal/linker.js +35 -13
  23. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +9 -1
  24. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +32 -12
  25. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +8 -1
  26. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +7 -4
  27. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +11 -1
  28. package/dataflow/internal/process/functions/call/named-call-handling.js +4 -2
  29. package/dataflow/internal/process/functions/call/quoted.js +3 -3
  30. package/dataflow/internal/program-order.js +7 -1
  31. package/dataflow/processor.d.ts +2 -0
  32. package/documentation/doc-util/doc-types.js +4 -0
  33. package/linter/linter-executor.js +7 -0
  34. package/linter/rules/problematic-inputs.js +2 -2
  35. package/linter/rules/stop-with-call-arg.js +1 -1
  36. package/linter/rules/undefined-symbol.js +26 -3
  37. package/linter/rules/unused-definition.js +20 -1
  38. package/package.json +1 -1
  39. package/project/dependency-version-space.js +4 -6
  40. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.d.ts +2 -0
  41. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +9 -8
  42. package/queries/catalog/dependencies-query/dependencies-query-executor.js +31 -0
  43. package/queries/catalog/dependencies-query/dependencies-query-format.d.ts +5 -0
  44. package/queries/catalog/dependencies-query/implicit-echo.js +26 -29
  45. package/queries/catalog/dependencies-query/plot-objects.js +6 -2
  46. package/queries/catalog/dice-query/dice-query-format.d.ts +1 -1
  47. package/queries/catalog/dice-query/dice-query-format.js +1 -1
  48. package/queries/catalog/slice-query-options.d.ts +3 -3
  49. package/queries/catalog/slice-query-options.js +1 -1
  50. package/queries/catalog/static-slice-query/static-slice-query-executor.js +12 -1
  51. package/queries/catalog/static-slice-query/static-slice-query-format.d.ts +7 -1
  52. package/queries/catalog/static-slice-query/static-slice-query-format.js +4 -2
  53. package/queries/query.d.ts +2 -2
  54. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize.js +19 -56
  55. package/reconstruct/inline/source-inline-map.d.ts +1 -1
  56. package/reconstruct/inline/source-inline-map.js +5 -3
  57. package/reconstruct/reconstruct.d.ts +8 -1
  58. package/reconstruct/reconstruct.js +12 -3
  59. package/slicing/static/removal-slice.d.ts +19 -0
  60. package/slicing/static/removal-slice.js +167 -0
  61. package/slicing/static/static-slicer.js +10 -5
  62. package/util/text/playground-link.d.ts +24 -1
  63. package/util/text/playground-link.js +16 -1
  64. package/util/version.js +2 -2
@@ -27,6 +27,7 @@ const assert_1 = require("../../../../../util/assert");
27
27
  const built_in_props_1 = require("../../../../environments/built-in-props");
28
28
  const query_fn_props_1 = require("../../../../environments/query-fn-props");
29
29
  const environment_1 = require("../../../../environments/environment");
30
+ const default_builtin_config_1 = require("../../../../environments/default-builtin-config");
30
31
  function mergeInformation(info, newInfo) {
31
32
  if (info === undefined) {
32
33
  return newInfo;
@@ -177,8 +178,9 @@ function processNamedCall(name, callArguments, rootId, data) {
177
178
  for (const own of toRun) {
178
179
  alternatives.push(own.processor(name, args, rootId, data));
179
180
  const pkg = own.name === undefined ? undefined : identifier_1.Identifier.getNamespace(own.name);
180
- /* unless flowR states how it accesses the state, as for `withr::with_options` */
181
- packageFn ||= pkg !== undefined && !(own.config !== undefined && ('ambient' in own.config || 'scope' in own.config)) && !(0, r_base_packages_1.isBaseRPackage)(String(pkg));
181
+ /* unless flowR states how it accesses the state, as for `withr::with_options`, or the export is a method the primitive dispatches to (lubridate's `rep`) */
182
+ packageFn ||= pkg !== undefined && !(own.config !== undefined && ('ambient' in own.config || 'scope' in own.config)) && !(0, r_base_packages_1.isBaseRPackage)(String(pkg))
183
+ && !default_builtin_config_1.InternalGenerics.has(identifier_1.Identifier.getName(own.name));
182
184
  }
183
185
  if (defaultProcessor && !shadowable) {
184
186
  processDefault();
@@ -110,7 +110,7 @@ exports.Quoted = {
110
110
  const reachOf = (sites) => reaches.get(sites.join('\0'));
111
111
  let enclosing;
112
112
  /* every call of a function lists the arguments of all its calls, so each is linked once per forces it meets */
113
- const linkedWith = new Map();
113
+ const linkedWith = new defaultmap_1.DefaultMap(() => new Set());
114
114
  for (const [id, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
115
115
  const masks = nse_1.Nse.dropResolvedMask(graph, id, vertex.name);
116
116
  if (masks !== undefined) {
@@ -163,8 +163,8 @@ exports.Quoted = {
163
163
  for (const argument of df_helper_1.Dataflow.argumentsBoundTo(graph, parameter)) {
164
164
  const index = namesOnce();
165
165
  const forces = forcesOf(graph, parameter, flow, forcing, reachOf);
166
- if (forces !== undefined && linkedWith.get(argument) !== forces) {
167
- linkedWith.set(argument, forces);
166
+ if (forces !== undefined && !linkedWith.get(argument).has(forces)) {
167
+ linkedWith.get(argument).add(forces);
168
168
  deferred_1.Deferred.link(graph, argument, index, idMap, forces);
169
169
  }
170
170
  }
@@ -44,6 +44,12 @@ function statementsAfter(id, statement, graph) {
44
44
  return 0;
45
45
  }
46
46
  const other = model_1.RNode.topLevelStatement(node, idMap);
47
- return other.info.parent === statement.info.parent ? other.info.index - statement.info.index : 0;
47
+ if (other.info.parent === statement.info.parent) {
48
+ return other.info.index - statement.info.index;
49
+ }
50
+ /* in another file, a statement is after one only if it starts once that one is done, and before only if it is done before that one starts */
51
+ const [start, end] = graph.statementOrder?.get(other.info.id) ?? [];
52
+ const [from, to] = graph.statementOrder?.get(statement.info.id) ?? [];
53
+ return start === undefined || end === undefined || from === undefined || to === undefined ? 0 : start >= to ? 1 : end <= from ? -1 : 0;
48
54
  }
49
55
  //# sourceMappingURL=program-order.js.map
@@ -70,6 +70,8 @@ export interface DataflowProcessorInformation<OtherInfo> {
70
70
  readonly rootId: NodeId;
71
71
  readonly argument: RArgument<OtherInfo & ParentInformation>;
72
72
  };
73
+ /** Where the top-level statements of every file start and end running, see {@link DataflowGraph#statementOrder} */
74
+ readonly statementOrder?: Map<NodeId, [start: number, end: number]>;
73
75
  }
74
76
  export type DataflowProcessor<OtherInfo, NodeType extends RNodeWithParent<OtherInfo>> = (node: NodeType, data: DataflowProcessorInformation<OtherInfo>) => DataflowInformation;
75
77
  type NodeWithKey<OtherInfo, Key> = RNode<OtherInfo & ParentInformation> & {
@@ -629,6 +629,10 @@ function retrieveNode(name, hierarchy, fuzzy = false, type = undefined) {
629
629
  return undefined;
630
630
  }
631
631
  }
632
+ if (!container) {
633
+ /* a bare name means the declaration itself, not a member that happens to share it (like the `Dataflow` gas key of `GasFeatureKey`) */
634
+ node = [...node.filter(n => n.extends.length === 0), ...node.filter(n => n.extends.length > 0)];
635
+ }
632
636
  return [container, name, node[0]];
633
637
  }
634
638
  /**
@@ -22,6 +22,11 @@ function withoutUntrustedRegexes(ruleName, config) {
22
22
  }
23
23
  return Object.fromEntries(Object.entries(config).filter(([k]) => !keys.includes(k)));
24
24
  }
25
+ /** the finding with the file it is in, which a rule pointing at a node of the program leaves to that node */
26
+ function locatedIn(found, idMap) {
27
+ const file = found.loc[4] ?? idMap.get([found.involvedId ?? []].flat()[0])?.info.file;
28
+ return file === found.loc[4] ? found : { ...found, loc: [found.loc[0], found.loc[1], found.loc[2], found.loc[3], file] };
29
+ }
25
30
  /**
26
31
  * Executes a specific linting rule on the given analysis provider input.
27
32
  */
@@ -36,8 +41,10 @@ async function executeLintingRule(ruleName, input, lintingRuleConfig) {
36
41
  const processStart = Date.now();
37
42
  const result = await rule.processSearchResult(searchResult, fullConfig, input);
38
43
  const processTime = Date.now() - processStart;
44
+ const { idMap } = await input.normalize();
39
45
  return {
40
46
  ...result,
47
+ results: result.results.map(found => locatedIn(found, idMap)),
41
48
  '.meta': {
42
49
  ...(result['.meta'] ?? {}),
43
50
  searchTimeMs: searchTime,
@@ -124,8 +124,8 @@ exports.PROBLEMATIC_INPUTS = {
124
124
  if (result.pipeCommand !== undefined) {
125
125
  return `Pipe command injection via '${result.pipeCommand}' in call to ${result.name} at ${range_1.SourceLocation.format(result.loc)}`;
126
126
  }
127
- const src = formatInputSources(result.sources ?? [], true).join('; ');
128
- return 'Use of configured dynamic call at ' + range_1.SourceLocation.format(result.loc) + (src ? '; inputs: ' + src : '');
127
+ const src = formatInputSources(result.sources ?? [], true).join(', ');
128
+ return 'Use of configured dynamic call at ' + range_1.SourceLocation.format(result.loc) + (src ? ' with inputs ' + src : '');
129
129
  },
130
130
  [linter_format_1.LintingPrettyPrintContext.Full]: result => {
131
131
  const lines = formatInputSources(result.sources ?? [], false);
@@ -93,7 +93,7 @@ exports.STOP_WITH_CALL_ARG = {
93
93
  },
94
94
  prettyPrint: {
95
95
  [linter_format_1.LintingPrettyPrintContext.Query]: result => `\`stop()\` without \`call. = FALSE\` at ${range_1.SourceLocation.format(result.loc)}`,
96
- [linter_format_1.LintingPrettyPrintContext.Full]: result => `\`stop()\` at ${range_1.SourceLocation.format(result.loc)} is called without \`call. = FALSE\`; the originating call is then appended to the error message, which is usually not intended - pass \`call. = FALSE\` to suppress it`,
96
+ [linter_format_1.LintingPrettyPrintContext.Full]: result => `\`stop()\` at ${range_1.SourceLocation.format(result.loc)} is called without \`call. = FALSE\`, so the error message names the call it was raised in, which is usually not intended. Pass \`call. = FALSE\` to leave it out.`,
97
97
  },
98
98
  info: {
99
99
  name: 'Stop Without Call',
@@ -40,6 +40,28 @@ function declaredGlobalVariables(graph, ctx) {
40
40
  }
41
41
  return names;
42
42
  }
43
+ /** the calls binding the name they are handed as a string, which flowR does not link to the reads of that name */
44
+ const NameBindingFunctions = new Set(['assign', 'delayedAssign']);
45
+ /**
46
+ * The names bound by the `assign(name, value)` calls of the code, as far as flowR resolves `name`:
47
+ * `assign(paste0("year", i), ...)` in a loop over `2000:2025` binds `year2000` to `year2025`.
48
+ */
49
+ function assignedNames(graph, ctx) {
50
+ const names = new Set();
51
+ for (const [, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
52
+ const [name, ns] = identifier_1.Identifier.toArray(vertex.name);
53
+ if (!NameBindingFunctions.has(name) || (ns !== undefined && ns !== 'base')) {
54
+ continue;
55
+ }
56
+ const values = (0, resolve_argument_1.getArgumentStringValue)(ctx.config.solver.variables, graph, vertex, 0, 'x', true, ctx);
57
+ for (const str of values?.values().flatMap(v => [...v]) ?? []) {
58
+ if (str !== undefined) {
59
+ names.add(str);
60
+ }
61
+ }
62
+ }
63
+ return names;
64
+ }
43
65
  /** calls that load a package; an unresolved one means we cannot enumerate all exports in scope */
44
66
  const LibraryLoadFunctions = new Set(['library', 'require', 'requireNamespace', 'loadNamespace', 'attachNamespace', 'load_all', 'use', 'p_load']);
45
67
  /** test frameworks whose namespace a test file runs under implicitly (e.g. `tests/testthat/test-*.R` sees testthat's exports without a `library()`) */
@@ -90,6 +112,7 @@ exports.UNDEFINED_SYMBOL = {
90
112
  .some(([id, v]) => unknownIds.has(id) && LibraryLoadFunctions.has(identifier_1.Identifier.getName(v.name)));
91
113
  // names a package declares global (`utils::globalVariables`) are no undefined symbols to R CMD check either
92
114
  const declaredGlobals = declaredGlobalVariables(graph, ctx);
115
+ const boundByAssign = assignedNames(graph, ctx);
93
116
  // scope-defined names, a fallback for closure variables flowR's dataflow did not statically link
94
117
  const scopeDefined = (0, undefined_symbol_util_1.collectScopeDefinedNames)(graph);
95
118
  // packages whose exports are in scope: DESCRIPTION/library() deps plus the default-attached base
@@ -141,7 +164,7 @@ exports.UNDEFINED_SYMBOL = {
141
164
  return suppress('declaredGlobal');
142
165
  }
143
166
  // forward-referenced closure binding flowR's dataflow did not link (unconditional bindings only)
144
- if ((0, undefined_symbol_util_1.isDefinedInEnclosingScope)(graph, scopeDefined, id, name)) {
167
+ if ((0, undefined_symbol_util_1.isDefinedInEnclosingScope)(graph, scopeDefined, id, name) || (kind === 'variable' && namespace === undefined && boundByAssign.has(name))) {
145
168
  return suppress('enclosingScope');
146
169
  }
147
170
  // consumed by non-standard evaluation (quoting), hence not an ordinary read
@@ -198,8 +221,8 @@ exports.UNDEFINED_SYMBOL = {
198
221
  const where = range_1.SourceLocation.format(result.loc);
199
222
  if (result.availableInPackages && result.availableInPackages.length > 0) {
200
223
  const pkgs = result.availableInPackages.map(p => `\`${p}\``).join(', ');
201
- const hint = result.availableInPackages.length === 1 ? `\`library(${result.availableInPackages[0]})\`` : `one of ${pkgs}`;
202
- return `\`${result.name}\` at ${where} is used but not defined; it is exported by ${pkgs} - did you forget to load it (e.g. ${hint})?`;
224
+ const hint = result.availableInPackages.length === 1 ? `with \`library(${result.availableInPackages[0]})\`` : 'from one of them';
225
+ return `\`${result.name}\` at ${where} is used but not defined. It is exported by ${pkgs}, so it may only need loading, for example ${hint}.`;
203
226
  }
204
227
  return result.kind === 'function'
205
228
  ? `\`${result.name}\` at ${where} is called but is neither defined locally, a base R builtin, nor exported by a loaded package`
@@ -27,6 +27,8 @@ const r_parameter_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-paramet
27
27
  const r_expression_list_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
28
28
  const r_argument_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
29
29
  const df_helper_1 = require("../../dataflow/graph/df-helper");
30
+ const resolve_helper_1 = require("../../dataflow/environments/resolve-helper");
31
+ const r_value_1 = require("../../dataflow/eval/values/r-value");
30
32
  /**
31
33
  * The dots parameter is a special parameter and must never be reported as an unused definition.
32
34
  */
@@ -242,6 +244,23 @@ function isWithinPromise(node, idMap) {
242
244
  }
243
245
  return false;
244
246
  }
247
+ /**
248
+ * Whether `node` writes into a parameter (`output$plot <- ...` in a Shiny server) that may hold an environment, so the
249
+ * caller sees the write. It may unless every call in the code passes a value flowR resolves, which is never an environment.
250
+ */
251
+ function mayWriteIntoCallerObject(node, graph, idMap, ctx) {
252
+ if (node.info.role !== "acc" /* RoleInParent.Accessed */) {
253
+ return false;
254
+ }
255
+ const environment = ctx.env.makeCleanEnv();
256
+ return df_helper_1.Dataflow.targetsOf(graph, node.info.id, edge_1.EdgeType.Reads).some(param => {
257
+ if (idMap.get(param)?.info.role !== "param-n" /* RoleInParent.ParameterName */) {
258
+ return false;
259
+ }
260
+ const handed = df_helper_1.Dataflow.targetsOf(graph, param, edge_1.EdgeType.DefinedByOnCall);
261
+ return handed.length === 0 || handed.some(arg => (0, r_value_1.isTop)(resolve_helper_1.Resolve.toValue(arg, { graph, idMap, environment, ctx })));
262
+ });
263
+ }
245
264
  exports.UNUSED_DEFINITION = {
246
265
  createSearch: config => flowr_search_builder_1.Q.all().filter(config.includeFunctionDefinitions ? flowr_search_filters_1.F.or(vertex_1.VertexType.VariableDefinition, vertex_1.VertexType.FunctionDefinition) : vertex_1.VertexType.VariableDefinition),
247
266
  processSearchResult: async (elements, config, data) => {
@@ -263,7 +282,7 @@ exports.UNUSED_DEFINITION = {
263
282
  if (!vertex || (!vertex_1.DfgVertex.isVariableDefinition(vertex) && vertex_1.DfgVertex.isFunctionDefinition(vertex) && !config.includeFunctionDefinitions)) {
264
283
  return false;
265
284
  }
266
- if (s3GenericParams.has(node.info.id)) {
285
+ if (s3GenericParams.has(node.info.id) || mayWriteIntoCallerObject(node, graph, normalize.idMap, ctx)) {
267
286
  return false;
268
287
  }
269
288
  // an anonymous dispatcher passed to setGeneric()/new_generic() runs on every dispatch, so it is used
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eagleoutice/flowr",
3
- "version": "2.16.4",
3
+ "version": "2.16.6",
4
4
  "description": "Static Dataflow Analyzer and Program Slicer for the R Programming Language",
5
5
  "engines": {
6
6
  "node": ">=22"
@@ -269,11 +269,6 @@ function collectOrphanUsage(graph, deps, usage, isKnown, options = {}) {
269
269
  continue;
270
270
  }
271
271
  const name = identifier_1.Identifier.getName(vertex.name);
272
- // a call bound to a real definition (local, parameter, closure, or import) *is* that definition, not a package
273
- // export; only an unresolved or builtin-modeled call can be an orphan (flowR models e.g. `ggplot` as a builtin)
274
- if (df_helper_1.Dataflow.origin(graph, id)?.some(o => o.type === 2 /* OriginType.FunctionCallOrigin */) === true) {
275
- continue;
276
- }
277
272
  // a bare name from a default-attached base package (or a base primitive) is defined without a library() call
278
273
  const baseOwner = (0, r_base_packages_1.baseRExportOwner)(name);
279
274
  if (baseOwner !== undefined && r_base_packages_1.AttachedBasePackages.includes(baseOwner)) {
@@ -295,7 +290,10 @@ function collectOrphanUsage(graph, deps, usage, isKnown, options = {}) {
295
290
  const pkg = builtin ? mapped
296
291
  : known.length === 1 ? known[0]
297
292
  : known.length === 0 && providers.length > 0 && providers.length <= MaxOrphanProviders ? providers[0] : undefined;
298
- if (pkg === undefined) {
293
+ // a call bound to a real definition (local, parameter, closure, or import) *is* that definition, not a package
294
+ // export; only an unresolved or builtin-modeled call can be an orphan (flowR models e.g. `ggplot` as a builtin).
295
+ // Resolving the call is what costs, so the cheaper checks above go first
296
+ if (pkg === undefined || df_helper_1.Dataflow.origin(graph, id)?.some(o => o.type === 2 /* OriginType.FunctionCallOrigin */) === true) {
299
297
  continue;
300
298
  }
301
299
  recordCallUsage(atKey(usage, pkg, () => new Map()), name, vertex.args, id);
@@ -93,3 +93,5 @@ export declare function restoreBlocksWithoutMd(blocks: readonly CodeBlock[], tot
93
93
  * Parses the options of an R code block from its header and content
94
94
  */
95
95
  export declare function parseCodeBlockOptions(header: string, content: string): CodeBlockOptions;
96
+ /** The `#|` lines that open a code block, which state its options rather than code */
97
+ export declare function cellOptionLines(content: string): string[];
@@ -8,6 +8,7 @@ exports.parseRMarkdownFile = parseRMarkdownFile;
8
8
  exports.isRCodeBlock = isRCodeBlock;
9
9
  exports.restoreBlocksWithoutMd = restoreBlocksWithoutMd;
10
10
  exports.parseCodeBlockOptions = parseCodeBlockOptions;
11
+ exports.cellOptionLines = cellOptionLines;
11
12
  const flowr_file_1 = require("../../../context/flowr-file");
12
13
  const assert_1 = require("../../../../util/assert");
13
14
  const commonmark_1 = require("commonmark");
@@ -273,16 +274,16 @@ function parseCodeBlockOptions(header, content) {
273
274
  const headerOpts = header.length === 3 // '{r}' => header.length=3 (no options in header)
274
275
  ? ''
275
276
  : header.slice(3, -1).trim();
276
- const cellLines = [];
277
- for (const line of content.split('\n')) {
278
- if (!line.trim().startsWith('#|')) {
279
- break;
280
- }
281
- // keep the indentation, yaml block scalars rely on it
282
- cellLines.push(line.trim().slice(2).replace(/^ /, ''));
283
- }
277
+ // keep the indentation, yaml block scalars rely on it
278
+ const cellLines = cellOptionLines(content).map(line => line.trim().slice(2).replace(/^ /, ''));
284
279
  return new Map([...parseOptionString(headerOpts), ...parseCellOptions(cellLines)]);
285
280
  }
281
+ /** The `#|` lines that open a code block, which state its options rather than code */
282
+ function cellOptionLines(content) {
283
+ const lines = content.split('\n');
284
+ const code = lines.findIndex(line => !line.trim().startsWith('#|'));
285
+ return lines.slice(0, code < 0 ? lines.length : code);
286
+ }
286
287
  /** Parses knitr's `key=value` option syntax as used in the chunk header */
287
288
  function parseOptionString(opts) {
288
289
  const parsedOptions = new Map();
@@ -24,6 +24,7 @@ const data_flow_1 = require("./data-flow");
24
24
  const match_args_1 = require("../../../dataflow/graph/match-args");
25
25
  const r_function_call_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
26
26
  const r_argument_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
27
+ const r_function_definition_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
27
28
  const r_base_packages_1 = require("../../../util/r-base-packages");
28
29
  /**
29
30
  * Executes a dependencies query.
@@ -81,6 +82,11 @@ async function executeDependenciesQuery({ analyzer, }, queries) {
81
82
  (0, plot_description_1.describePlots)(results.write ?? [], results.visualize, run, ctx);
82
83
  inheritPlotInputs(results.visualize);
83
84
  }
85
+ for (const [category, found] of Object.entries(results)) {
86
+ if (found !== undefined && !NotPassedOnByCalls.has(category)) {
87
+ results[category] = [...found, ...callSitesOf(found, dataflow.graph, normalize)];
88
+ }
89
+ }
84
90
  if (query.assumedPackages && (enabled === undefined || enabled.includes('library'))) {
85
91
  const explicit = new Set((results.library ?? []).map(r => r.value).filter((v) => v !== undefined && v !== dependencies_query_format_1.Unknown && v !== dependencies_query_format_1.Constant));
86
92
  const assumed = assumedBasePackageEntries(dataflow.graph, ctx.resolvedRVersion, explicit);
@@ -95,6 +101,31 @@ async function executeDependenciesQuery({ analyzer, }, queries) {
95
101
  ...results,
96
102
  };
97
103
  }
104
+ /** what a call of a function does not do itself: loading a package or a script there is still what the function does */
105
+ const NotPassedOnByCalls = new Set(['library', 'source', 'remote']);
106
+ /**
107
+ * The calls of the program's functions that do what the entries within their bodies do, transitively: a call of `report()`
108
+ * writes what the `cat()` in its body writes, and so does every call of a function that calls `report()`.
109
+ */
110
+ function callSitesOf(found, graph, ast) {
111
+ const added = [];
112
+ const known = new Set(found.map(f => f.nodeId));
113
+ const queue = [...found];
114
+ for (let entry = queue.shift(); entry !== undefined; entry = queue.shift()) {
115
+ const definition = entry.nodeId === undefined ? undefined : model_1.RNode.findEnclosing(entry.nodeId, ast.idMap, r_function_definition_1.RFunctionDefinition.is);
116
+ for (const call of definition === undefined ? [] : df_helper_1.Dataflow.sourcesOf(graph, definition, edge_1.EdgeType.Calls)) {
117
+ const vertex = graph.getVertex(call);
118
+ if (!vertex_1.DfgVertex.isFunctionCall(vertex) || known.has(call)) {
119
+ continue;
120
+ }
121
+ known.add(call);
122
+ const site = { functionName: vertex.name ?? entry.functionName, nodeId: call, via: entry.nodeId, ...entry.value === undefined ? {} : { value: entry.value } };
123
+ added.push(site);
124
+ queue.push(site);
125
+ }
126
+ }
127
+ return added;
128
+ }
98
129
  /** whether the call may reach a function definition of the code, whose formals differ from call to call */
99
130
  function callsDefinition(dfg, id) {
100
131
  for (const [target, edge] of dfg.edgesFrom(id)) {
@@ -67,6 +67,11 @@ export interface DependencyInfo extends Record<string, unknown> {
67
67
  /** the called name; an {@link Identifier}, so a namespaced call like `maps::map` keeps its package */
68
68
  functionName: Identifier;
69
69
  linkedIds?: readonly NodeId[];
70
+ /**
71
+ * Set on a call of a function of the program that does what this entry reports, transitively: the call of
72
+ * `report()` writes what the `cat()` in its body writes. It names the entry within the called function.
73
+ */
74
+ via?: NodeId;
70
75
  /**
71
76
  * The other statements that build this output: for a plot, the addons drawn onto it and, when it lands in a
72
77
  * file, the device opener and closer around it. Answers *which statements produce this output* without
@@ -5,6 +5,7 @@ const function_semantics_1 = require("../../../dataflow/fn/function-semantics");
5
5
  const identifier_1 = require("../../../dataflow/environments/identifier");
6
6
  const model_1 = require("../../../r-bridge/lang-4.x/ast/model/model");
7
7
  const type_1 = require("../../../r-bridge/lang-4.x/ast/model/type");
8
+ const r_expression_list_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
8
9
  const r_binary_op_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op");
9
10
  const r_function_call_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
10
11
  const r_argument_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
@@ -18,7 +19,7 @@ const plot_objects_1 = require("./plot-objects");
18
19
  const data_flow_1 = require("./data-flow");
19
20
  const test_functions_1 = require("./function-info/test-functions");
20
21
  /** the node whose value R echoes for a statement, `undefined` if the statement yields nothing visible */
21
- function echoedValue(node, dataflow, invisible) {
22
+ function echoedValue(node, dataflow, invisible, seen = new Set()) {
22
23
  switch (node?.type) {
23
24
  /* the loops hand back an invisible NULL, and the jumps never hand back anything at all */
24
25
  case undefined:
@@ -31,22 +32,22 @@ function echoedValue(node, dataflow, invisible) {
31
32
  case type_1.RType.LineDirective:
32
33
  return undefined;
33
34
  case type_1.RType.FunctionCall: {
34
- if (callName(node, dataflow, invisible) === undefined) {
35
+ if (callName(node, dataflow, invisible, seen) === undefined) {
35
36
  return undefined;
36
37
  }
37
38
  const handedOn = aliased(node, dataflow, invisible);
38
- return handedOn === undefined ? node : echoedValue(handedOn, dataflow, invisible);
39
+ return handedOn === undefined ? node : echoedValue(handedOn, dataflow, invisible, seen);
39
40
  }
40
41
  /* a block hands on the value of its last statement, a `( )` group that of what it holds, visibly:
41
42
  which is what makes `(x <- 1)` print what it assigned */
42
43
  case type_1.RType.ExpressionList:
43
44
  return grouped(node) ? lastStatement(node) ?? node
44
- : echoedValue(lastStatement(node), dataflow, invisible) ?? (node.children.length === 0 ? node : undefined);
45
+ : echoedValue(lastStatement(node), dataflow, invisible, seen) ?? (node.children.length === 0 ? node : undefined);
45
46
  case type_1.RType.Pipe:
46
- return echoedValue(node.rhs, dataflow, invisible);
47
+ return echoedValue(node.rhs, dataflow, invisible, seen);
47
48
  /* whichever branch runs decides; without an `else` a false condition yields an invisible NULL */
48
49
  case type_1.RType.IfThenElse:
49
- return echoedValue(node.then, dataflow, invisible) ?? echoedValue(node.otherwise, dataflow, invisible);
50
+ return echoedValue(node.then, dataflow, invisible, seen) ?? echoedValue(node.otherwise, dataflow, invisible, seen);
50
51
  case type_1.RType.BinaryOp:
51
52
  return r_binary_op_1.RBinaryOp.getOperatorInfo(node)?.usedAs === 'assignment' ? undefined : node;
52
53
  /* a symbol, a constant, an access, a unary operator, or a function definition is printed as it stands */
@@ -68,8 +69,8 @@ function aliased(node, dataflow, invisible) {
68
69
  ?.findIndex(([, p]) => (p & built_in_props_1.ArgProp.Alias) !== 0) ?? -1;
69
70
  const arg = at < 0 ? undefined : node.arguments[at];
70
71
  const value = typeof arg === 'object' && r_argument_1.RArgument.is(arg) ? arg.value : undefined;
71
- /* only a call of its own can be invisible where the one around it is not, a symbol says nothing new */
72
- return r_function_call_1.RFunctionCall.is(value) ? value : undefined;
72
+ /* only a call or a block (`local({ ... })`) can be invisible where the one around it is not, a symbol says nothing new */
73
+ return r_function_call_1.RFunctionCall.is(value) || r_expression_list_1.RExpressionList.is(value) ? value : undefined;
73
74
  }
74
75
  /** the last statement of a block, which is what its value comes from */
75
76
  function lastStatement(node) {
@@ -81,16 +82,30 @@ function lastStatement(node) {
81
82
  }
82
83
  return undefined;
83
84
  }
85
+ /**
86
+ * The name of the call if its result is visible, `undefined` if it hands it back invisibly. A call that reaches
87
+ * functions of the program is visible exactly when one of their exits yields a visible value, by the same rules as a
88
+ * statement of the top level, whatever a built-in of that name would do; only otherwise its built-in props decide.
89
+ */
84
90
  function callName(node, dataflow, invisible, seen = new Set()) {
85
91
  const name = (0, plot_objects_1.callIdentifierOf)(node, dataflow);
86
- if (name === undefined) {
92
+ if (name === undefined || test_functions_1.ExpectFunctionNames.test(identifier_1.Identifier.getName(name)) || isInvisible(name, invisible)) {
87
93
  return undefined;
88
94
  }
95
+ const idMap = dataflow.graph.idMap;
96
+ const callees = [...df_helper_1.Dataflow.calleesOf(dataflow.graph, node.info.id)];
97
+ if (callees.length > 0 && idMap !== undefined) {
98
+ /* a recursive call is as visible as the call that started it, which the others decide */
99
+ if (seen.has(node.info.id)) {
100
+ return undefined;
101
+ }
102
+ seen.add(node.info.id);
103
+ return callees.some(definition => definition.exitPoints.some(exit => echoedValue(idMap.get(exit.nodeId), dataflow, invisible, seen) !== undefined)) ? name : undefined;
104
+ }
89
105
  const props = (0, query_fn_props_1.queryFnProps)(name, { environment: dataflow.environment });
90
106
  /* a setter hands back the previous state invisibly, but queried, the state is what it returns */
91
107
  const hidden = function_semantics_1.FunctionSemantics.call.props.hasAny(props, [built_in_props_1.CallProp.Invisible]) && !(0, built_in_ambient_state_1.callOnlyQueries)(name, node.arguments, dataflow.environment);
92
- return hidden || test_functions_1.ExpectFunctionNames.test(identifier_1.Identifier.getName(name)) || isInvisible(name, invisible)
93
- || (props === undefined && calleesReturnInvisibly(node.info.id, dataflow, invisible, seen)) ? undefined : name;
108
+ return hidden ? undefined : name;
94
109
  }
95
110
  /** whether the call is to one of the functions stated to return invisibly, unless its package says it is another one */
96
111
  function isInvisible(name, invisible) {
@@ -98,24 +113,6 @@ function isInvisible(name, invisible) {
98
113
  const ns = identifier_1.Identifier.getNamespace(name);
99
114
  return invisible.some(f => f.name === fn && (f.package === undefined || ns === undefined || f.package === ns));
100
115
  }
101
- function calleesReturnInvisibly(id, dataflow, invisible, seen) {
102
- const idMap = dataflow.graph.idMap;
103
- if (idMap === undefined || seen.has(id)) {
104
- return false;
105
- }
106
- seen.add(id);
107
- let callee = false;
108
- for (const definition of df_helper_1.Dataflow.calleesOf(dataflow.graph, id)) {
109
- callee = true;
110
- for (const exit of definition.exitPoints) {
111
- const last = idMap.get(exit.nodeId);
112
- if (!r_function_call_1.RFunctionCall.is(last) || callName(last, dataflow, invisible, seen) !== undefined) {
113
- return false;
114
- }
115
- }
116
- }
117
- return callee;
118
- }
119
116
  /** what to report the echo under: the called name, or the operator or lexeme producing the value */
120
117
  function echoName(node, dataflow) {
121
118
  switch (node.type) {
@@ -55,7 +55,11 @@ function isPlotNode(node, dataflow, seen, memo) {
55
55
  /** whether the node calls one of the given graphics functions */
56
56
  function isPlotCall(node, dataflow, among) {
57
57
  const name = r_function_call_1.RFunctionCall.is(node) ? callIdentifierOf(node, dataflow) : undefined;
58
- return name !== undefined && among.has(identifier_1.Identifier.getName(name))
59
- && function_semantics_1.FunctionSemantics.call.props.hasAny((0, query_fn_props_1.queryFnProps)(name, { environment: dataflow.environment }), [built_in_props_1.SemanticCallTag.Graphics]);
58
+ if (name === undefined || !among.has(identifier_1.Identifier.getName(name))) {
59
+ return false;
60
+ }
61
+ /* without its package loaded, flowR knows nothing of `ggplot`, which still draws as its name says, unless the code defines its own */
62
+ const props = (0, query_fn_props_1.queryFnProps)(name, { environment: dataflow.environment });
63
+ return props === undefined ? [...df_helper_1.Dataflow.calleesOf(dataflow.graph, node.info.id)].length === 0 : function_semantics_1.FunctionSemantics.call.props.hasAny(props, [built_in_props_1.SemanticCallTag.Graphics]);
60
64
  }
61
65
  //# sourceMappingURL=plot-objects.js.map
@@ -47,7 +47,7 @@ export declare const DiceQueryDefinition: {
47
47
  readonly asciiSummarizer: (formatter: import("../../../util/text/ansi").OutputFormatter, _analyzer: import("../../..").ReadonlyFlowrAnalysisProvider<import("../../..").KnownParser>, queryResults: BaseQueryResult, result: string[]) => boolean;
48
48
  readonly fromLine: typeof diceQueryLineParser;
49
49
  readonly completer: typeof diceQueryCompleter;
50
- readonly syntax: "@dice (<crit>;...->crit;...)[iIcB] <code | file://path>";
50
+ readonly syntax: `@dice (<crit>;...->crit;...)[${string}] <code | file://path>`;
51
51
  readonly schema: Joi.ObjectSchema<any>;
52
52
  readonly flattenInvolvedNodes: (queryResults: BaseQueryResult) => NodeId[];
53
53
  };
@@ -50,7 +50,7 @@ exports.DiceQueryDefinition = {
50
50
  asciiSummarizer: (formatter, _analyzer, queryResults, result) => (0, slice_query_options_1.summarizeSliceResults)(formatter, 'dice', queryResults, result, (_, q) => q ? `Dice from {${q.from.join(', ')}} to {${q.to.join(', ')}}` : 'Dice'),
51
51
  fromLine: diceQueryLineParser,
52
52
  completer: diceQueryCompleter,
53
- syntax: '@dice (<crit>;...->crit;...)[iIcB] <code | file://path>',
53
+ syntax: `@dice (<crit>;...->crit;...)[${slice_query_parser_1.SharedSliceFlags.map(f => f.flag).join('')}] <code | file://path>`,
54
54
  schema: joi_1.default.object({
55
55
  type: joi_1.default.string().valid('dice').required().description('The type of the query.'),
56
56
  from: joi_1.default.array().items(joi_1.default.string()).min(1).required().description('Slicing criteria for the start of the dice (forward slice seeds).'),
@@ -8,7 +8,7 @@ import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-i
8
8
  import type { NormalizedAst } from '../../r-bridge/lang-4.x/ast/model/processing/decorate';
9
9
  import type { SlicingCriteria } from '../../slicing/criterion/parse';
10
10
  import type { DataflowGraph } from '../../dataflow/graph/graph';
11
- import { type InlineFull, type ReconstructionResult } from '../../reconstruct/reconstruct';
11
+ import { type InlineFull, type InlineSources, type ReconstructionResult } from '../../reconstruct/reconstruct';
12
12
  import type { OutputFormatter } from '../../util/text/ansi';
13
13
  /** The options every slicing query understands, independent of how it picks the nodes to keep. */
14
14
  export interface SliceQueryOptions {
@@ -25,7 +25,7 @@ export interface SliceQueryOptions {
25
25
  * Inline resolvable `source()` calls into the reconstruction so the result is a single self-contained R text.
26
26
  * Cyclic and unresolvable `source()` calls are kept verbatim and reported via `reconstruct.inlineWarnings`.
27
27
  */
28
- readonly inlineSources?: boolean;
28
+ readonly inlineSources?: InlineSources;
29
29
  /**
30
30
  * Inline _every_ file into the reconstruction, in flowR's loading order (which respects implicit sources),
31
31
  * independent of whether it is sourced explicitly; `'banner'` additionally precedes each file with a banner
@@ -51,7 +51,7 @@ export declare const SliceQueryOptionsSchema: {
51
51
  readonly name: Joi.StringSchema<string>;
52
52
  readonly noReconstruction: Joi.BooleanSchema<boolean>;
53
53
  readonly noMagicComments: Joi.BooleanSchema<boolean>;
54
- readonly inlineSources: Joi.BooleanSchema<boolean>;
54
+ readonly inlineSources: Joi.AlternativesSchema<string | boolean>;
55
55
  readonly inlineFull: Joi.AlternativesSchema<string | boolean>;
56
56
  readonly includeCallees: Joi.BooleanSchema<boolean>;
57
57
  readonly perFile: Joi.BooleanSchema<boolean>;
@@ -28,7 +28,7 @@ exports.SliceQueryOptionsSchema = {
28
28
  name: joi_1.default.string().min(1).optional().description('What to call this slice: the results are keyed by it instead of by the serialized query.'),
29
29
  noReconstruction: joi_1.default.boolean().optional().description('Do not reconstruct the slice into readable code.'),
30
30
  noMagicComments: joi_1.default.boolean().optional().description('Should the magic comments (force-including lines within the slice) be ignored?'),
31
- inlineSources: joi_1.default.boolean().optional().description('Inline resolvable source() calls into the reconstruction so the result is a single self-contained R text.'),
31
+ inlineSources: joi_1.default.alternatives(joi_1.default.boolean(), joi_1.default.string().valid('banner')).optional().description('Inline resolvable source() calls into the reconstruction so the result is a single self-contained R text; "banner" marks where each spliced file begins and ends with a banner comment naming it.'),
32
32
  inlineFull: joi_1.default.alternatives(joi_1.default.boolean(), joi_1.default.string().valid('banner')).optional().description('Inline all files into the reconstruction, in flowR\'s loading order and independent of whether they are sourced explicitly; "banner" precedes every file with a banner comment naming it.'),
33
33
  includeCallees: joi_1.default.boolean().optional().description('If set (and slicing backward), continue the slice past a function-definition boundary, also including the definition\'s binding and call sites.'),
34
34
  perFile: joi_1.default.boolean().optional().description('Reconstruct the slice as the project\'s files, reported in `reconstruct.files` in loading order with their paths, instead of only the entry file.'),
@@ -7,6 +7,7 @@ const slice_query_options_1 = require("../slice-query-options");
7
7
  const log_1 = require("../../../util/log");
8
8
  const slice_direction_1 = require("../../../util/slice-direction");
9
9
  const df_helper_1 = require("../../../dataflow/graph/df-helper");
10
+ const removal_slice_1 = require("../../../slicing/static/removal-slice");
10
11
  /** what a static slice is of, which is what its result is keyed by when it was given no name */
11
12
  const slicedBy = (query) => query.criteria.join(',');
12
13
  /**
@@ -35,7 +36,17 @@ async function executeStaticSliceQuery({ analyzer }, queries) {
35
36
  const sliceStart = Date.now();
36
37
  const n = await analyzer.normalize();
37
38
  const df = await analyzer.dataflow();
38
- const slice = (0, static_slicer_1.staticSlice)({ ctx: analyzer.inspectContext(), info: df, ast: n, ids: (0, slice_query_options_1.resolveSliceCriteria)(criteria, n), direction: query.direction ?? slice_direction_1.SliceDirection.Backward, threshold: analyzer.flowrConfig.solver.slicer?.threshold, includeCallees });
39
+ const ids = (0, slice_query_options_1.resolveSliceCriteria)(criteria, n);
40
+ const threshold = analyzer.flowrConfig.solver.slicer?.threshold;
41
+ if (query.removal) {
42
+ /* the plots, devices and saves the dependencies state are what a removed plot takes along */
43
+ const { dependencies } = await analyzer.query([{ type: 'dependencies' }]);
44
+ const removed = (0, removal_slice_1.staticRemovalSlice)(analyzer.inspectContext(), df, n, ids, Object.values(dependencies).filter(Array.isArray).flat(), threshold).result;
45
+ const kept = (0, removal_slice_1.keptAfterRemoval)(n, removed);
46
+ results[key] = (0, slice_query_options_1.timedSliceEntry)(query, { timesHitThreshold: 0, result: removed, slicedFor: ids }, Date.now() - sliceStart, () => (0, slice_query_options_1.reconstructSlice)(n, df.graph, kept, query));
47
+ continue;
48
+ }
49
+ const slice = (0, static_slicer_1.staticSlice)({ ctx: analyzer.inspectContext(), info: df, ast: n, ids, direction: query.direction ?? slice_direction_1.SliceDirection.Backward, threshold, includeCallees });
39
50
  const packages = query.reportPackages ? [...df_helper_1.Dataflow.packagesOf(slice.result, df.graph)] : undefined;
40
51
  results[key] = { packages, ...(0, slice_query_options_1.timedSliceEntry)(query, slice, Date.now() - sliceStart, () => (0, slice_query_options_1.reconstructSlice)(n, df.graph, slice.result, query)) };
41
52
  }
@@ -18,6 +18,12 @@ export interface StaticSliceQuery extends BaseQueryFormat, SliceQueryOptions {
18
18
  readonly criteria: SlicingCriteria;
19
19
  /** The direction to slice in. Defaults to backward slicing if unset. */
20
20
  readonly direction?: SliceDirection;
21
+ /**
22
+ * Compute the removal slice instead (see {@link staticRemovalSlice}): the code that only exists for the criteria,
23
+ * which can go while the rest keeps working. The result holds the removed statements, and the reconstruction is the
24
+ * program without them. Ignores the {@link StaticSliceQuery#direction|direction}.
25
+ */
26
+ readonly removal?: boolean;
21
27
  }
22
28
  export interface StaticSliceQueryResult extends BaseQueryResult {
23
29
  /**
@@ -41,7 +47,7 @@ export declare const StaticSliceQueryDefinition: {
41
47
  readonly asciiSummarizer: (formatter: import("../../../util/text/ansi").OutputFormatter, _analyzer: import("../../..").ReadonlyFlowrAnalysisProvider<import("../../..").KnownParser>, queryResults: BaseQueryResult, result: string[]) => boolean;
42
48
  readonly fromLine: typeof sliceQueryLineParser;
43
49
  readonly completer: typeof criteriaQueryCompleter;
44
- readonly syntax: "@static-slice (<crit>;...)[fiIcB] <code | file://path>";
50
+ readonly syntax: `@static-slice (<crit>;...)[${string}] <code | file://path>`;
45
51
  readonly schema: Joi.ObjectSchema<any>;
46
52
  readonly flattenInvolvedNodes: (queryResults: BaseQueryResult) => NodeId[];
47
53
  };