@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
@@ -35,7 +35,8 @@ function sliceQueryLineParser(output, line, _config) {
35
35
  type: 'static-slice',
36
36
  criteria: criteria,
37
37
  direction: direction,
38
- ...options
38
+ ...options,
39
+ ...(0, slice_query_parser_1.sliceRemovalParser)(line[0]) ? { removal: true } : {}
39
40
  }
40
41
  ], rCode: (0, slice_query_parser_1.queryLineCode)(line) };
41
42
  }
@@ -45,11 +46,12 @@ exports.StaticSliceQueryDefinition = {
45
46
  asciiSummarizer: (formatter, _analyzer, queryResults, result) => (0, slice_query_options_1.summarizeSliceResults)(formatter, 'static-slice', queryResults, result, (key, q) => `Slice ${q === undefined ? `"${key}"` : `for {${q.criteria.join(', ')}}`}`),
46
47
  fromLine: sliceQueryLineParser,
47
48
  completer: slice_query_parser_1.criteriaQueryCompleter,
48
- syntax: '@static-slice (<crit>;...)[fiIcB] <code | file://path>',
49
+ syntax: `@static-slice (<crit>;...)[${slice_query_parser_1.StaticSliceFlags.map(f => f.flag).join('')}] <code | file://path>`,
49
50
  schema: joi_1.default.object({
50
51
  type: joi_1.default.string().valid('static-slice').required().description('The type of the query.'),
51
52
  criteria: joi_1.default.array().items(joi_1.default.string()).min(0).required().description('The slicing criteria to use.'),
52
53
  direction: joi_1.default.string().valid(...Object.values(slice_direction_1.SliceDirection)).optional().description('The direction to slice in. Defaults to backward slicing if unset.'),
54
+ removal: joi_1.default.boolean().optional().description('Compute the removal slice instead: the code that only exists for the criteria, which can go while the rest keeps working. The result holds the removed statements, the reconstruction the program without them.'),
53
55
  ...slice_query_options_1.SliceQueryOptionsSchema
54
56
  }).description('Slice query used to slice the dataflow graph'),
55
57
  flattenInvolvedNodes: (queryResults) => {
@@ -184,7 +184,7 @@ export declare const SupportedQueries: {
184
184
  readonly asciiSummarizer: (formatter: OutputFormatter, _analyzer: ReadonlyFlowrAnalysisProvider<import("..").KnownParser>, queryResults: BaseQueryResult, result: string[]) => boolean;
185
185
  readonly fromLine: (output: ReplOutput, line: readonly string[], _config: FlowrConfig) => ParsedQueryLine<"static-slice">;
186
186
  readonly completer: typeof import("../cli/repl/parser/slice-query-parser").criteriaQueryCompleter;
187
- readonly syntax: "@static-slice (<crit>;...)[fiIcB] <code | file://path>";
187
+ readonly syntax: `@static-slice (<crit>;...)[${string}] <code | file://path>`;
188
188
  readonly schema: Joi.ObjectSchema<any>;
189
189
  readonly flattenInvolvedNodes: (queryResults: BaseQueryResult) => NodeId[];
190
190
  };
@@ -334,7 +334,7 @@ export declare const SupportedQueries: {
334
334
  readonly asciiSummarizer: (formatter: OutputFormatter, _analyzer: ReadonlyFlowrAnalysisProvider<import("..").KnownParser>, queryResults: BaseQueryResult, result: string[]) => boolean;
335
335
  readonly fromLine: (output: ReplOutput, line: readonly string[], _config: FlowrConfig) => ParsedQueryLine<"dice">;
336
336
  readonly completer: (line: readonly string[], startingNewArg: boolean, _config: FlowrConfig) => CommandCompletions;
337
- readonly syntax: "@dice (<crit>;...->crit;...)[iIcB] <code | file://path>";
337
+ readonly syntax: `@dice (<crit>;...->crit;...)[${string}] <code | file://path>`;
338
338
  readonly schema: Joi.ObjectSchema<any>;
339
339
  readonly flattenInvolvedNodes: (queryResults: BaseQueryResult) => NodeId[];
340
340
  };
@@ -88,7 +88,7 @@ function convertTreeNode(node) {
88
88
  case tree_sitter_types_1.TreeSitterType.Program: {
89
89
  const [comments, children] = splitCommentNodes(nonErrorChildren(node));
90
90
  const body = children.map(n => [n, convertTreeNode(n)]);
91
- const remainingComments = linkCommentsToNextNodes(body, comments);
91
+ const remainingComments = linkCommentsToNextNodes(node, body, comments);
92
92
  return {
93
93
  type: type_1.RType.ExpressionList,
94
94
  children: body.map(n => n[1]),
@@ -105,7 +105,7 @@ function convertTreeNode(node) {
105
105
  const [comments, children] = splitCommentNodes(nonErrorChildren(node));
106
106
  const opening = children[0];
107
107
  const body = children.slice(1, -1).map(n => [n, convertTreeNode(n)]);
108
- const remainingComments = linkCommentsToNextNodes(body, comments);
108
+ const remainingComments = linkCommentsToNextNodes(node, body, comments);
109
109
  const closing = children[children.length - 1];
110
110
  const openText = opening.text;
111
111
  const closeText = closing.text;
@@ -651,65 +651,28 @@ function splitCommentNodes(nodes) {
651
651
  }
652
652
  return [comments, others];
653
653
  }
654
- /**
655
- * Find the first sibling of the given node that is not a comment, starting from the given node and going to the right.
656
- * @param snode - the node for which to find the first non-comment sibling
657
- * @param knownNexts - cache map from node id to the id of the first non-comment sibling
658
- */
659
- function findFirstNonCommentSibling(snode, knownNexts) {
660
- const cache = knownNexts.get(snode.id);
661
- if (cache !== undefined) {
662
- return cache;
663
- }
664
- const cursor = snode.parent?.walk();
665
- if (!cursor) {
666
- return null;
667
- }
668
- const linkCaches = [snode.id];
669
- cursor.gotoFirstChild();
670
- while (cursor.nodeId !== snode.id && cursor.gotoNextSibling()) {
671
- /* skip */
672
- }
673
- cursor.gotoNextSibling();
674
- while (cursor.nodeType === tree_sitter_types_1.TreeSitterType.Comment && cursor.gotoNextSibling()) {
675
- /* skip */
676
- linkCaches.push(cursor.nodeId);
677
- }
678
- const cur = cursor.currentNode;
679
- for (const id of linkCaches) {
680
- knownNexts.set(id, cur);
681
- }
682
- cursor.delete();
683
- return cur;
684
- }
685
- function linkCommentsToNextNodes(nodes, comments) {
686
- if (comments.length === 0) {
654
+ function linkCommentsToNextNodes(parent, nodes, comments) {
655
+ if (comments.length === 0 || nodes.length === 0) {
687
656
  return comments;
688
657
  }
689
- const remain = [];
690
- const cacheMap = new Map();
691
- const nodeById = new Map(nodes.map(n => [n[0].id, n]));
658
+ const nodeById = new Map(nodes.map(([s, n]) => [s.id, n]));
659
+ /* one pass over the siblings, walking them per comment is quadratic in long scripts */
660
+ const siblings = parent.children;
661
+ const indexOf = new Map(siblings.map((s, i) => [s.id, i]));
662
+ const nextNonComment = [];
663
+ for (let i = siblings.length - 2; i >= 0; i--) {
664
+ nextNonComment[i] = siblings[i + 1].type === tree_sitter_types_1.TreeSitterType.Comment ? nextNonComment[i + 1] : siblings[i + 1];
665
+ }
692
666
  for (const [commentSyntaxNode, commentNode] of comments) {
693
- let sibling;
694
- const prev = commentSyntaxNode.previousSibling;
695
- if (prev?.endIndex === commentSyntaxNode.startIndex) {
696
- // if there is a sibling on the same line, we link the comment to that node
697
- sibling = prev;
698
- }
699
- else {
700
- sibling = findFirstNonCommentSibling(commentSyntaxNode, cacheMap);
701
- }
667
+ const i = indexOf.get(commentSyntaxNode.id) ?? -1;
668
+ const prev = siblings[i - 1];
669
+ // if there is a sibling on the same line, we link the comment to that node
670
+ const sibling = prev?.endIndex === commentSyntaxNode.startIndex ? prev : nextNonComment[i];
702
671
  // if there is no valid sibling, we just link the comment to the first node (see normalize-expressions.ts)
703
- const [, node] = (sibling ? nodeById.get(sibling.id) : undefined) ?? nodes[0] ?? [];
704
- if (node) {
705
- node.info.adToks ??= [];
706
- node.info.adToks.push(commentNode);
707
- }
708
- else {
709
- remain.push([commentSyntaxNode, commentNode]);
710
- }
672
+ const node = (sibling && nodeById.get(sibling.id)) ?? nodes[0][1];
673
+ (node.info.adToks ??= []).push(commentNode);
711
674
  }
712
- return remain;
675
+ return [];
713
676
  }
714
677
  function getNodesUntil(nodes, type, startIndex = 0) {
715
678
  const ret = [];
@@ -28,7 +28,7 @@ export interface InlineWarning {
28
28
  readonly path?: string;
29
29
  }
30
30
  /**
31
- * Connect each `source()` call node to the index of the file it sources in `ast.ast.files` (index 0 is main).
31
+ * Connect each `source()` call node to the index of the file it sources in `ast.ast.files`, whichever file flowR loaded first.
32
32
  *
33
33
  * A `source()` call lives in its parent file, so we reach its sourced block via the control dependency the
34
34
  * dataflow analysis adds (see {@link sourceRequest}): a vertex whose innermost cd (`cds[0]`) is a source call
@@ -13,7 +13,7 @@ function sourcePathOf(node) {
13
13
  return r_string_1.RString.is(path) ? path.content.str : undefined;
14
14
  }
15
15
  /**
16
- * Connect each `source()` call node to the index of the file it sources in `ast.ast.files` (index 0 is main).
16
+ * Connect each `source()` call node to the index of the file it sources in `ast.ast.files`, whichever file flowR loaded first.
17
17
  *
18
18
  * A `source()` call lives in its parent file, so we reach its sourced block via the control dependency the
19
19
  * dataflow analysis adds (see {@link sourceRequest}): a vertex whose innermost cd (`cds[0]`) is a source call
@@ -34,7 +34,7 @@ function buildSourceInlineMap(ast, graph) {
34
34
  }
35
35
  // resolved file path -> its index (paths are unique per stored file)
36
36
  const pathToIndex = new Map();
37
- for (let i = 1; i < files.length; i++) {
37
+ for (let i = 0; i < files.length; i++) {
38
38
  const path = files[i].root.info.file;
39
39
  if (path !== undefined) {
40
40
  pathToIndex.set(path, i);
@@ -75,9 +75,11 @@ function buildSourceInlineMap(ast, graph) {
75
75
  argToIndex.set(arg, idx);
76
76
  }
77
77
  }
78
+ /* a file the project analyzes on its own as well has no block under the call, its path still names it */
79
+ const byPath = (arg) => [...pathToIndex].find(([path]) => path === arg || path.endsWith(`/${arg}`))?.[1];
78
80
  for (const [callId, arg] of sourceArgs) {
79
81
  if (arg !== undefined && !map.has(callId)) {
80
- const idx = argToIndex.get(arg);
82
+ const idx = argToIndex.get(arg) ?? byPath(arg);
81
83
  if (idx !== undefined) {
82
84
  map.set(callId, idx);
83
85
  }
@@ -13,6 +13,13 @@ import { type InlineWarning } from './inline/source-inline-map';
13
13
  * @see {@link Selection#inlineFull}
14
14
  */
15
15
  export type InlineFull = boolean | 'banner';
16
+ /**
17
+ * Whether to splice resolvable `source()` calls: `true` splices them, `'banner'` additionally marks where each
18
+ * spliced file begins and ends with a banner comment naming it.
19
+ */
20
+ export type InlineSources = boolean | 'banner';
21
+ /** The banner comment that names a file where an inlining puts it, or where it ends (`end`). */
22
+ export declare function fileBanner(path: string | undefined, end?: boolean): string;
16
23
  interface Selection {
17
24
  /** The set of node ids to be reconstructed. */
18
25
  nodes: ReadonlySet<NodeId>;
@@ -22,7 +29,7 @@ interface Selection {
22
29
  * If set, selected `source()` calls are replaced by the (spliced) reconstruction of the sourced file, producing a
23
30
  * single self-contained reconstruction. Requires {@link Selection#sourceMap}; overrides {@link Selection#reconstructFiles}.
24
31
  */
25
- inlineSources?: boolean;
32
+ inlineSources?: InlineSources;
26
33
  /**
27
34
  * If set, every file is reconstructed into a single self-contained text, in flowR's loading order; files sourced
28
35
  * explicitly are spliced into their `source()` call instead of repeated at the top level (`'banner'` names each).
@@ -6,6 +6,7 @@
6
6
  */
7
7
  Object.defineProperty(exports, "__esModule", { value: true });
8
8
  exports.reconstructLogger = void 0;
9
+ exports.fileBanner = fileBanner;
9
10
  exports.reconstructToCode = reconstructToCode;
10
11
  const log_1 = require("../util/log");
11
12
  const assert_1 = require("../util/assert");
@@ -21,6 +22,10 @@ const auto_select_defaults_1 = require("./auto-select/auto-select-defaults");
21
22
  const identifier_1 = require("../dataflow/environments/identifier");
22
23
  const source_inline_map_1 = require("./inline/source-inline-map");
23
24
  const type_1 = require("../r-bridge/lang-4.x/ast/model/type");
25
+ /** The banner comment that names a file where an inlining puts it, or where it ends (`end`). */
26
+ function fileBanner(path, end = false) {
27
+ return `# ---- ${end ? 'end of ' : ''}${path ?? '<inline>'} ----`;
28
+ }
24
29
  function plain(text) {
25
30
  return [{ line: Array.isArray(text) ? identifier_1.Identifier.toString(text) : text, indent: 0 }];
26
31
  }
@@ -342,7 +347,8 @@ function tryInlineSourceCall(call, config) {
342
347
  visited: visited.union(new Set([config.currentFile ?? 0, targetFile])),
343
348
  currentFile: targetFile
344
349
  };
345
- return stripOuterExpressionList(reconstructFileCode(config.fullAst, targetFile, childConfig));
350
+ const spliced = stripOuterExpressionList(reconstructFileCode(config.fullAst, targetFile, childConfig));
351
+ return config.banner ? [{ line: fileBanner(path), indent: 0 }, ...spliced, { line: fileBanner(path, true), indent: 0 }] : spliced;
346
352
  }
347
353
  // a selected source() that we could not link to a file (dynamic/missing path): keep it verbatim
348
354
  if (r_function_call_1.RFunctionCall.isNamed(call, 'source')) {
@@ -473,7 +479,9 @@ function reconstructToCode(ast, selection, autoSelectIf = auto_select_defaults_1
473
479
  const warnings = [];
474
480
  const sourceMap = selection.sourceMap ?? new Map();
475
481
  const splicedIn = new Set(sourceMap.values());
476
- const indices = selection.inlineFull ? ast.ast.files.map((_, i) => i).filter(i => !splicedIn.has(i)) : [0];
482
+ const roots = ast.ast.files.map((_, i) => i).filter(i => !splicedIn.has(i));
483
+ /* the program starts in the first file no other one sources, wherever flowR happened to load it */
484
+ const indices = selection.inlineFull ? roots : [roots[0] ?? 0];
477
485
  const parts = [];
478
486
  for (const i of indices) {
479
487
  const code = removeOuterExpressionListIfApplicable(reconstructFileCode(ast, i, {
@@ -481,13 +489,14 @@ function reconstructToCode(ast, selection, autoSelectIf = auto_select_defaults_1
481
489
  autoSelectIf: autoSelectIfWrapper,
482
490
  fullAst: ast,
483
491
  inlineSources: true,
492
+ banner: selection.inlineFull === 'banner' || selection.inlineSources === 'banner',
484
493
  sourceMap,
485
494
  visited: new Set([i]),
486
495
  currentFile: i,
487
496
  warnings
488
497
  }));
489
498
  if (code.length > 0) {
490
- parts.push(selection.inlineFull === 'banner' ? `# ---- ${ast.ast.files[i].filePath ?? '<inline>'} ----\n${code}` : code);
499
+ parts.push(selection.inlineFull === 'banner' ? `${fileBanner(ast.ast.files[i].filePath)}\n${code}` : code);
491
500
  }
492
501
  }
493
502
  return {
@@ -0,0 +1,19 @@
1
+ import type { ReadOnlyFlowrAnalyzerContext } from '../../project/context/flowr-analyzer-context';
2
+ import type { DataflowInformation } from '../../dataflow/info';
3
+ import type { NormalizedAst } from '../../r-bridge/lang-4.x/ast/model/processing/decorate';
4
+ import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id';
5
+ import type { DependencyInfo } from '../../queries/catalog/dependencies-query/dependencies-query-format';
6
+ /** What removing code for a set of criteria takes out of the program. */
7
+ export interface RemovalSliceResult {
8
+ /** the statements removed as a whole, outermost first */
9
+ readonly removed: readonly NodeId[];
10
+ /** every node of the removed statements */
11
+ readonly result: ReadonlySet<NodeId>;
12
+ }
13
+ /** every node left once `removed` is out, but the file roots, which would keep removed functions as stubs */
14
+ export declare function keptAfterRemoval(ast: NormalizedAst, removed: ReadonlySet<NodeId>): Set<NodeId>;
15
+ /**
16
+ * The removal slice of `ids`: the statements of their backward slice that nothing else needs. A statement the rest
17
+ * needs even in part stays as a whole. Removed plots take their device and saving calls along.
18
+ */
19
+ export declare function staticRemovalSlice(ctx: ReadOnlyFlowrAnalyzerContext, info: DataflowInformation, ast: NormalizedAst, ids: readonly NodeId[], dependencies?: readonly DependencyInfo[], threshold?: number): RemovalSliceResult;
@@ -0,0 +1,167 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.keptAfterRemoval = keptAfterRemoval;
4
+ exports.staticRemovalSlice = staticRemovalSlice;
5
+ const model_1 = require("../../r-bridge/lang-4.x/ast/model/model");
6
+ const r_expression_list_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
7
+ const r_function_definition_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
8
+ const r_function_call_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
9
+ const r_argument_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
10
+ const r_binary_op_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op");
11
+ const static_slicer_1 = require("./static-slicer");
12
+ const slice_direction_1 = require("../../util/slice-direction");
13
+ const df_helper_1 = require("../../dataflow/graph/df-helper");
14
+ const edge_1 = require("../../dataflow/graph/edge");
15
+ const default_builtin_config_1 = require("../../dataflow/environments/default-builtin-config");
16
+ const identifier_1 = require("../../dataflow/environments/identifier");
17
+ const built_in_props_1 = require("../../dataflow/environments/built-in-props");
18
+ function builtInNames(stated) {
19
+ return new Set(default_builtin_config_1.DefaultBuiltinConfig.flatMap(d => d.type === 'function' && stated((d.config ?? {})) ? d.names.map(name => String(identifier_1.Identifier.getName(name))) : []));
20
+ }
21
+ const accesses = (type) => (config) => [config.ambient ?? []].flat().some(access => access.type === type);
22
+ const DeviceOpeners = builtInNames(accesses("open-device" /* AmbientStateAccessType.OpenDevice */));
23
+ const DeviceClosers = builtInNames(accesses("close-device" /* AmbientStateAccessType.CloseDevice */));
24
+ /* a call handing back its argument is that argument: `invisible(dev.off())` closes the device */
25
+ const PassingOn = builtInNames(config => ((config.sig?.[0]?.[1] ?? 0) & built_in_props_1.ArgProp.Alias) !== 0);
26
+ /** the statements of the program, without function bodies, which only run when called */
27
+ function statementsOf(ast) {
28
+ const result = new Map();
29
+ model_1.RNode.visitAst(ast.ast.files.map(f => f.root), node => {
30
+ if (r_expression_list_1.RExpressionList.is(node)) {
31
+ for (const child of node.children) {
32
+ result.set(child.info.id, child);
33
+ }
34
+ }
35
+ return r_function_definition_1.RFunctionDefinition.is(node);
36
+ });
37
+ return result;
38
+ }
39
+ /** the node and everything it lies within, innermost first */
40
+ function* ancestors(ast, id) {
41
+ for (let at = id; at !== undefined; at = ast.idMap.get(at)?.info.parent) {
42
+ yield at;
43
+ }
44
+ }
45
+ function statementOf(ast, statements, id) {
46
+ const at = ancestors(ast, id).find(a => statements.has(a));
47
+ return at === undefined ? undefined : statements.get(at);
48
+ }
49
+ const within = (ast, id, ancestor) => ancestors(ast, id).some(at => at === ancestor);
50
+ function callOf(node) {
51
+ while (r_function_call_1.RFunctionCall.isNamed(node, PassingOn) && node.arguments.length === 1) {
52
+ node = r_argument_1.RArgument.valueOf(node.arguments[0]);
53
+ }
54
+ return node;
55
+ }
56
+ const isNamed = (node, names) => r_function_call_1.RFunctionCall.isNamed(callOf(node), names);
57
+ /** the calls from a device to its `dev.off()` around each criterion, assignments in between stay as the rest may use them */
58
+ function deviceWindows(ast, statements, ids) {
59
+ const found = new Set();
60
+ for (const id of ids) {
61
+ const statement = statementOf(ast, statements, id);
62
+ const block = statement?.info.parent === undefined ? undefined : ast.idMap.get(statement.info.parent);
63
+ if (statement === undefined || !r_expression_list_1.RExpressionList.is(block)) {
64
+ continue;
65
+ }
66
+ const siblings = block.children;
67
+ const at = siblings.indexOf(statement);
68
+ let open = at;
69
+ while (open >= 0 && !isNamed(siblings[open], DeviceOpeners) && (open === at || !isNamed(siblings[open], DeviceClosers))) {
70
+ open--;
71
+ }
72
+ let close = at;
73
+ while (close < siblings.length && !isNamed(siblings[close], DeviceClosers) && (close === at || !isNamed(siblings[close], DeviceOpeners))) {
74
+ close++;
75
+ }
76
+ if (open < 0 || close >= siblings.length || !isNamed(siblings[open], DeviceOpeners) || !isNamed(siblings[close], DeviceClosers)) {
77
+ continue;
78
+ }
79
+ for (const sibling of siblings.slice(open, close + 1)) {
80
+ if (!r_binary_op_1.RBinaryOp.is(sibling) || r_binary_op_1.RBinaryOp.getOperatorInfo(sibling)?.usedAs !== 'assignment') {
81
+ found.add(sibling.info.id);
82
+ }
83
+ }
84
+ }
85
+ return [...found];
86
+ }
87
+ const PackageBuiltIn = /^built-in:[^:]+:/;
88
+ /** a definition the code that is left still reads, `undefined` if there is none */
89
+ function danglingRead(info, removed) {
90
+ for (const [id] of info.graph.vertices(true)) {
91
+ /* the built-ins a loaded package provides (`built-in:pkg:fn`) are no code that is left, they read its library() call */
92
+ if (!removed.has(id) && !(typeof id === 'string' && PackageBuiltIn.test(id))) {
93
+ const target = df_helper_1.Dataflow.targetsOf(info.graph, id, edge_1.EdgeType.Reads).find(t => removed.has(t));
94
+ if (target !== undefined) {
95
+ return target;
96
+ }
97
+ }
98
+ }
99
+ return undefined;
100
+ }
101
+ /** every node left once `removed` is out, but the file roots, which would keep removed functions as stubs */
102
+ function keptAfterRemoval(ast, removed) {
103
+ return new Set([...ast.idMap.entries()].filter(([id, node]) => !removed.has(id) && node.info.parent !== undefined).map(([id]) => id));
104
+ }
105
+ /**
106
+ * The removal slice of `ids`: the statements of their backward slice that nothing else needs. A statement the rest
107
+ * needs even in part stays as a whole. Removed plots take their device and saving calls along.
108
+ */
109
+ function staticRemovalSlice(ctx, info, ast, ids, dependencies = [], threshold) {
110
+ const statements = statementsOf(ast);
111
+ const statementId = (id) => statementOf(ast, statements, id)?.info.id;
112
+ const removable = (seeds) => {
113
+ const slice = (0, static_slicer_1.staticSlice)({ ctx, info, ast, ids: seeds, direction: slice_direction_1.SliceDirection.Backward, threshold }).result;
114
+ /* a statement is in the slice once any part of it is, as the slice of `body(f) <- x` may hold its parts alone */
115
+ const inSlice = new Set([...slice, ...seeds].map(statementId).filter(id => id !== undefined));
116
+ const rest = [...statements.keys()].filter(id => !inSlice.has(id));
117
+ const needed = new Set();
118
+ if (rest.length > 0) {
119
+ for (const id of (0, static_slicer_1.staticSlice)({ ctx, info, ast, ids: rest, direction: slice_direction_1.SliceDirection.Backward, threshold }).result) {
120
+ for (let at = id; at !== undefined && !needed.has(at); at = ast.idMap.get(at)?.info.parent) {
121
+ needed.add(at);
122
+ }
123
+ }
124
+ }
125
+ const candidates = [...statements.keys()].filter(id => inSlice.has(id) && !needed.has(id));
126
+ const chosen = new Set(candidates);
127
+ return candidates.filter(id => !ancestors(ast, ast.idMap.get(id)?.info.parent).some(at => chosen.has(at)));
128
+ };
129
+ /* removing a save (`ggsave()`) or a device removes what it saves, which would otherwise keep it alive */
130
+ const seeds = new Set(ids);
131
+ const inSeeds = (id) => seeds.has(id) || seeds.has(statementId(id) ?? -1);
132
+ for (const linked of [
133
+ ...dependencies.filter(d => d.nodeId !== undefined && inSeeds(d.nodeId)).flatMap(d => d.linkedIds ?? []),
134
+ ...dependencies.filter(d => d.parts?.some(inSeeds) || d.linkedIds?.some(inSeeds)).map(d => d.nodeId)
135
+ ]) {
136
+ if (linked !== undefined && !inSeeds(linked)) {
137
+ seeds.add(linked);
138
+ }
139
+ }
140
+ let removed = removable([...seeds]);
141
+ const gone = (id) => id !== undefined && removed.some(r => within(ast, id, r));
142
+ const parts = [
143
+ ...dependencies.filter(d => gone(d.nodeId)).flatMap(d => d.parts ?? [])
144
+ .filter(p => !dependencies.some(d => !gone(d.nodeId) && d.parts?.includes(p))),
145
+ ...dependencies.filter(d => d.linkedIds?.some(gone)).map(d => d.nodeId).filter(id => id !== undefined),
146
+ ...deviceWindows(ast, statements, [...seeds])
147
+ ].filter(id => !gone(id));
148
+ if (parts.length > 0) {
149
+ removed = removable([...seeds, ...parts]);
150
+ /* every file access is ordered after the ones before it, so a part may seem needed by later code */
151
+ for (const statement of parts.map(statementId)) {
152
+ if (statement !== undefined && !removed.some(r => within(ast, statement, r))) {
153
+ removed.push(statement);
154
+ }
155
+ }
156
+ }
157
+ const below = () => new Set([...ast.idMap.entries()].filter(([, node]) => removed.some(r => within(ast, node.info.id, r))).map(([id]) => id));
158
+ let result = below();
159
+ /* a slice keeps a value, not every name the code it keeps reads: what is left must not read what is gone */
160
+ for (let dangling = danglingRead(info, result); dangling !== undefined; dangling = danglingRead(info, result)) {
161
+ const back = dangling;
162
+ removed = removed.filter(r => !within(ast, back, r));
163
+ result = below();
164
+ }
165
+ return { removed, result };
166
+ }
167
+ //# sourceMappingURL=removal-slice.js.map
@@ -45,7 +45,9 @@ function staticSlice(options) {
45
45
  const basePrint = ctx.env.getCleanEnvFingerprint();
46
46
  const queue = new visiting_queue_1.VisitingQueue(options.threshold ?? 75, cache, graph, ctx.gas.scope(options.gas), [emptyEnv, basePrint]);
47
47
  const enclosingHandled = new Set();
48
- const missesSeeds = sliceGraph === undefined ? outsideSeedRun(ids, idMap, direction, graph) : undefined;
48
+ /* the unknown side effects every slice keeps are seeds as well, so what they reach is not cut off as running too late */
49
+ const effects = [...graph.unknownSideEffects].filter((id) => typeof id !== 'object');
50
+ const missesSeeds = sliceGraph === undefined ? outsideSeedRun([...ids, ...effects], idMap, direction, graph) : undefined;
49
51
  const enqueue = (id, env, print) => {
50
52
  if (!queue.hasId(id)) {
51
53
  queue.add(id, env, print, true);
@@ -61,10 +63,13 @@ function staticSlice(options) {
61
63
  openBodiesAround(startId);
62
64
  }
63
65
  /* include all the implicit side effects that we have to consider as we are unable to narrow them down */
64
- for (const id of graph.unknownSideEffects) {
65
- /* a linked side effect is no vertex of its own, its target is just missing */
66
- if (typeof id !== 'object') {
67
- queue.add(id, emptyEnv, basePrint, true);
66
+ /* a linked side effect is no vertex of its own, its target is just missing; the effect is the whole call, so what its parts read
67
+ is kept as well (the `<-` of `environment(g)$y <- 10` has no edges of its own to `g`) */
68
+ for (const id of effects) {
69
+ for (const part of model_1.RNode.collectAllIds(idMap.get(id))) {
70
+ if (part === id || graph.hasVertex(part)) {
71
+ queue.add(part, emptyEnv, basePrint, true);
72
+ }
68
73
  }
69
74
  }
70
75
  /* a call asked about does what the functions it runs do, which includes what they print */
@@ -7,7 +7,9 @@ export declare enum PlaygroundBox {
7
7
  /** what the dependency query found */
8
8
  Deps = "deps",
9
9
  /** what the linter found */
10
- Lints = "lints"
10
+ Lints = "lints",
11
+ /** what the DESCRIPTION of the project says */
12
+ Project = "project"
11
13
  }
12
14
  /**
13
15
  * What a link can point at, written the way flowR names a place in a script:
@@ -53,6 +55,22 @@ export interface PlaygroundLinkParts {
53
55
  /** another deployment of the page, for a local build or a fork */
54
56
  readonly base?: string;
55
57
  }
58
+ /**
59
+ * The letter each setting of the view takes in the view field of a link, in the order a link writes them. Links in
60
+ * papers and mails have to open as they were sent: a letter is never reused for something else, only new ones are added.
61
+ */
62
+ declare const ViewFlags: {
63
+ readonly forward: ">";
64
+ readonly removal: "-";
65
+ readonly dim: "d";
66
+ readonly replOpen: "r";
67
+ readonly wholeSlice: "a";
68
+ readonly inline: "i";
69
+ };
70
+ /** how the view of the page was left, as the view field of a link carries it */
71
+ export type PlaygroundView = {
72
+ readonly [Setting in keyof typeof ViewFlags]?: boolean;
73
+ };
56
74
  /**
57
75
  * Everything about flowR's playground that is not the page itself: what a link to it carries, and how
58
76
  * one is written. The page reads back exactly what {@link Playground.link} writes.
@@ -86,6 +104,10 @@ export declare const Playground: {
86
104
  };
87
105
  /** the boxes of the page a mark can point at */
88
106
  Box: typeof PlaygroundBox;
107
+ /** the view field's letters for the settings of `view` that are on */
108
+ viewFlags(this: void, view: PlaygroundView): string;
109
+ /** which settings of the view the letters of a view field turn on */
110
+ readView(this: void, flags: string): Required<PlaygroundView>;
89
111
  /**
90
112
  * The link that opens the playground on exactly this: a script, what it points at, where its cursor
91
113
  * sits, and how the page is laid out.
@@ -127,3 +149,4 @@ export declare const Playground: {
127
149
  /** where a name stands in a line, as a name rather than as a substring of a longer one */
128
150
  nameIndexIn(this: void, text: string, name: string): number | undefined;
129
151
  };
152
+ export {};
@@ -15,6 +15,8 @@ var PlaygroundBox;
15
15
  PlaygroundBox["Deps"] = "deps";
16
16
  /** what the linter found */
17
17
  PlaygroundBox["Lints"] = "lints";
18
+ /** what the DESCRIPTION of the project says */
19
+ PlaygroundBox["Project"] = "project";
18
20
  })(PlaygroundBox || (exports.PlaygroundBox = PlaygroundBox = {}));
19
21
  /** a mark that stands for a place in the script: a line, a range, a column, or a name on a line, in another file with a `(file-regex)` */
20
22
  const CodeMarkPattern = /^\d+(:\d+|-\d+|@.+)?(\(.+\))?$/;
@@ -82,6 +84,11 @@ const Mark = {
82
84
  });
83
85
  }
84
86
  };
87
+ /**
88
+ * The letter each setting of the view takes in the view field of a link, in the order a link writes them. Links in
89
+ * papers and mails have to open as they were sent: a letter is never reused for something else, only new ones are added.
90
+ */
91
+ const ViewFlags = { forward: '>', removal: '-', dim: 'd', replOpen: 'r', wholeSlice: 'a', inline: 'i' };
85
92
  /**
86
93
  * Everything about flowR's playground that is not the page itself: what a link to it carries, and how
87
94
  * one is written. The page reads back exactly what {@link Playground.link} writes.
@@ -101,6 +108,14 @@ exports.Playground = {
101
108
  Mark,
102
109
  /** the boxes of the page a mark can point at */
103
110
  Box: PlaygroundBox,
111
+ /** the view field's letters for the settings of `view` that are on */
112
+ viewFlags(view) {
113
+ return Object.entries(ViewFlags).filter(([setting]) => view[setting]).map(([, letter]) => letter).join('');
114
+ },
115
+ /** which settings of the view the letters of a view field turn on */
116
+ readView(flags) {
117
+ return Object.fromEntries(Object.entries(ViewFlags).map(([setting, letter]) => [setting, flags.includes(letter)]));
118
+ },
104
119
  /**
105
120
  * The link that opens the playground on exactly this: a script, what it points at, where its cursor
106
121
  * sits, and how the page is laid out.
@@ -112,7 +127,7 @@ exports.Playground = {
112
127
  const view = [
113
128
  split === undefined ? '' : String(split),
114
129
  repl === undefined ? '' : String(repl),
115
- `${forward ? '>' : ''}${dim ? 'd' : ''}${replOpen ? 'r' : ''}${wholeSlice ? 'a' : ''}`
130
+ exports.Playground.viewFlags({ forward, dim, replOpen, wholeSlice })
116
131
  ];
117
132
  while (view.length > 0 && view[view.length - 1].length === 0) {
118
133
  view.pop();
package/util/version.js CHANGED
@@ -43,9 +43,9 @@ const sigdb_download_1 = require("../project/sigdb/sigdb-download");
43
43
  const doc_files_1 = require("../documentation/doc-util/doc-files");
44
44
  const strings_1 = require("./text/strings");
45
45
  // this is automatically replaced with the current version by release-it
46
- const version = '2.16.4';
46
+ const version = '2.16.6';
47
47
  // this is automatically replaced with the release date by release-it (scripts/bump-version.ts)
48
- const versionDate = '2026-10-19T19:06:26Z';
48
+ const versionDate = '2026-10-22T19:05:13Z';
49
49
  /**
50
50
  * Retrieves the current flowR version as a new {@link SemVer} object.
51
51
  */