@eagleoutice/flowr 2.17.12 → 2.17.14

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 (115) hide show
  1. package/README.md +15 -15
  2. package/cli/repl/core.js +9 -27
  3. package/config.d.ts +1 -0
  4. package/config.js +4 -2
  5. package/data/r-datasets.generated.js +2 -2
  6. package/dataflow/environments/ambient-effect.d.ts +4 -0
  7. package/dataflow/environments/ambient-effect.js +5 -4
  8. package/dataflow/environments/ambient-state-name.d.ts +2 -2
  9. package/dataflow/environments/ambient-state-name.js +3 -3
  10. package/dataflow/environments/built-in-props.d.ts +5 -0
  11. package/dataflow/environments/default-builtin-config/base-functions.d.ts +1 -1
  12. package/dataflow/environments/default-builtin-config/base-functions.js +6 -2
  13. package/dataflow/environments/default-builtin-config/base-language.d.ts +12 -1
  14. package/dataflow/environments/default-builtin-config/base-language.js +3 -2
  15. package/dataflow/environments/default-builtin-config/guards.js +3 -1
  16. package/dataflow/environments/default-builtin-config/index.d.ts +12 -2
  17. package/dataflow/environments/default-builtin-config/misc-packages.d.ts +1 -1
  18. package/dataflow/environments/default-builtin-config/misc-packages.js +2 -0
  19. package/dataflow/environments/default-builtin-config/shared-configs.d.ts +24 -0
  20. package/dataflow/environments/default-builtin-config/shared-configs.js +8 -6
  21. package/dataflow/environments/pkg-name.d.ts +1 -0
  22. package/dataflow/eval/resolve/alias-tracking.js +11 -12
  23. package/dataflow/extractor.js +58 -0
  24. package/dataflow/fn/guards/built-in-guards.js +4 -4
  25. package/dataflow/fn/guards/call-contracts.js +8 -8
  26. package/dataflow/fn/guards/condition-grouping.js +4 -3
  27. package/dataflow/fn/guards/function-guards.js +103 -97
  28. package/dataflow/fn/guards/group-method-guards.js +10 -8
  29. package/dataflow/fn/guards/guard-claims.js +152 -128
  30. package/dataflow/fn/guards/guard-knowledge.js +19 -18
  31. package/dataflow/fn/guards/guard-term-syntax.js +13 -12
  32. package/dataflow/fn/guards/guard-term.d.ts +71 -0
  33. package/dataflow/fn/guards/guard-term.js +183 -75
  34. package/dataflow/graph/df-helper.d.ts +6 -6
  35. package/dataflow/graph/df-helper.js +1 -1
  36. package/dataflow/graph/graph.d.ts +9 -0
  37. package/dataflow/graph/graph.js +19 -0
  38. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +18 -14
  39. package/dataflow/internal/process/functions/call/built-in/built-in-apply.d.ts +1 -1
  40. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +29 -0
  41. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +2 -1
  42. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +2 -1
  43. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +6 -2
  44. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +9 -2
  45. package/dataflow/internal/process/functions/call/built-in/built-in-eval.js +1 -1
  46. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.d.ts +12 -1
  47. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.js +24 -6
  48. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +10 -10
  49. package/dataflow/internal/process/functions/call/built-in/built-in-load.js +2 -2
  50. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +1 -1
  51. package/dataflow/internal/process/functions/call/built-in/built-in-source.js +19 -9
  52. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +35 -3
  53. package/documentation/doc-readme.js +1 -2
  54. package/documentation/doc-util/doc-query.d.ts +1 -1
  55. package/documentation/doc-util/doc-query.js +4 -2
  56. package/documentation/wiki-interface.js +1 -0
  57. package/documentation/wiki-linter.d.ts +2 -0
  58. package/documentation/wiki-linter.js +7 -1
  59. package/documentation/wiki-query.js +28 -0
  60. package/linter/linter-format.d.ts +5 -1
  61. package/linter/linter-format.js +4 -0
  62. package/linter/linter-output.js +18 -16
  63. package/linter/linter-rules.d.ts +50 -0
  64. package/linter/linter-rules.js +5 -1
  65. package/linter/rules/notebook-cell-order.d.ts +43 -0
  66. package/linter/rules/notebook-cell-order.js +97 -0
  67. package/linter/rules/project-entry-point.d.ts +53 -0
  68. package/linter/rules/project-entry-point.js +62 -0
  69. package/linter/rules/undefined-symbol.d.ts +2 -0
  70. package/linter/rules/undefined-symbol.js +6 -1
  71. package/notebook/cell-graph.d.ts +23 -0
  72. package/notebook/cell-graph.js +48 -0
  73. package/notebook/cell-order-mermaid.d.ts +16 -0
  74. package/notebook/cell-order-mermaid.js +51 -0
  75. package/notebook/cell-order.d.ts +270 -0
  76. package/notebook/cell-order.js +1452 -0
  77. package/notebook/cell-split.d.ts +27 -0
  78. package/notebook/cell-split.js +99 -0
  79. package/package.json +1 -1
  80. package/project/context/flowr-analyzer-dependencies-context.d.ts +4 -0
  81. package/project/context/flowr-analyzer-files-context.d.ts +2 -0
  82. package/project/flowr-analyzer.js +5 -1
  83. package/project/plugins/file-plugins/files/cell-runner.d.ts +22 -0
  84. package/project/plugins/file-plugins/files/cell-runner.js +32 -0
  85. package/project/plugins/file-plugins/files/flowr-jupyter-file.d.ts +4 -0
  86. package/project/plugins/file-plugins/files/flowr-jupyter-file.js +22 -6
  87. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.d.ts +22 -0
  88. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +63 -7
  89. package/project/plugins/file-plugins/files/flowr-rsession-file.d.ts +2 -0
  90. package/project/plugins/file-plugins/files/flowr-rsession-file.js +2 -0
  91. package/project/plugins/file-plugins/files/flowr-sweave-file.d.ts +3 -5
  92. package/project/plugins/file-plugins/files/flowr-sweave-file.js +6 -0
  93. package/project/plugins/file-plugins/files/recorded-runs.d.ts +2 -0
  94. package/queries/catalog/aliases-query/aliases-query-executor.d.ts +6 -0
  95. package/queries/catalog/aliases-query/aliases-query-executor.js +108 -0
  96. package/queries/catalog/aliases-query/aliases-query-format.d.ts +21 -0
  97. package/queries/catalog/aliases-query/aliases-query-format.js +34 -0
  98. package/queries/catalog/cell-order-query/cell-order-query-format.d.ts +81 -0
  99. package/queries/catalog/cell-order-query/cell-order-query-format.js +82 -0
  100. package/queries/catalog/linter-query/linter-query-format.js +2 -1
  101. package/queries/query.d.ts +17 -2
  102. package/queries/query.js +6 -2
  103. package/queries/virtual-query/compound-query.d.ts +1 -1
  104. package/util/flowr-version.d.ts +1 -1
  105. package/util/flowr-version.js +2 -2
  106. package/util/mermaid/ast.js +4 -11
  107. package/util/mermaid/cfg.js +1 -2
  108. package/util/mermaid/dfg.d.ts +5 -0
  109. package/util/mermaid/dfg.js +23 -4
  110. package/util/mermaid/mermaid.d.ts +5 -0
  111. package/util/mermaid/mermaid.js +8 -0
  112. package/util/r-datasets.d.ts +2 -0
  113. package/util/r-datasets.js +3 -0
  114. package/util/text/playground-link.d.ts +2 -2
  115. package/util/text/playground-link.js +2 -2
@@ -575,18 +575,22 @@ function readOptions(res, args, rootId, data, effect, keys) {
575
575
  }
576
576
  /** what every access of a file reads to find it: the working directory a relative path starts from and the directories the path leads through */
577
577
  const FileSystemReads = [ambient_state_name_1.AmbientStateName.workingDirectory, ambient_state_name_1.AmbientStateName.directories];
578
- /** What reading or writing the files the call names does, see {@link fileStems}. */
578
+ /** What reading or writing the files the call names does, see {@link fileNames}. */
579
579
  function fileAccess(res, rootId, data, effect) {
580
- const stems = fileStems(res, rootId, data, effect);
581
- if (stems?.length === 0) {
580
+ const names = fileNames(res, rootId, data, effect);
581
+ if (names?.length === 0) {
582
582
  return res;
583
583
  }
584
584
  if (effect.access === ambient_effect_1.AmbientVerb.Reads) {
585
585
  /* a read through a connection the program holds moves its position, so the next read depends on this one */
586
- const moves = readsThroughHandle(res, rootId, data, effect.sig) ? stems === undefined ? [ambient_state_name_1.AmbientStateName.anyFile, ambient_state_name_1.AmbientStateName.files] : stems.map(ambient_state_name_1.AmbientStateName.file) : [];
587
- return withAccess(res, rootId, data, [...FileSystemReads, ...stems === undefined ? [ambient_state_name_1.AmbientStateName.files] : [...stems.map(ambient_state_name_1.AmbientStateName.file), ambient_state_name_1.AmbientStateName.anyFile]], moves);
586
+ const moves = readsThroughHandle(res, rootId, data, effect.sig) ? names === undefined ? [ambient_state_name_1.AmbientStateName.anyFile, ambient_state_name_1.AmbientStateName.files] : names.map(ambient_state_name_1.AmbientStateName.file) : [];
587
+ return withAccess(res, rootId, data, [...FileSystemReads, ...names === undefined ? [ambient_state_name_1.AmbientStateName.files] : [...names.map(ambient_state_name_1.AmbientStateName.file), ambient_state_name_1.AmbientStateName.anyFile]], moves);
588
588
  }
589
- return withAccess(res, rootId, data, FileSystemReads, [...stems === undefined ? [ambient_state_name_1.AmbientStateName.anyFile] : stems.map(ambient_state_name_1.AmbientStateName.file), ambient_state_name_1.AmbientStateName.files]);
589
+ /* removing a file (`unlink`) leaves nothing of what was written to it */
590
+ if (effect.access === ambient_effect_1.AmbientVerb.Kills) {
591
+ return withAccess(res, rootId, data, FileSystemReads, [ambient_state_name_1.AmbientStateName.files], names?.map(ambient_state_name_1.AmbientStateName.file) ?? []);
592
+ }
593
+ return withAccess(res, rootId, data, FileSystemReads, [...names === undefined ? [ambient_state_name_1.AmbientStateName.anyFile] : names.map(ambient_state_name_1.AmbientStateName.file), ambient_state_name_1.AmbientStateName.files]);
590
594
  }
591
595
  /** `gc()` may run every registered finalizer whose object is released. */
592
596
  function runFinalizers(res, rootId, data) {
@@ -703,8 +707,8 @@ function namesNoFile(id, data) {
703
707
  const values = boundValues(id, data);
704
708
  return values.length > 0 && values.every(v => (r_string_1.RString.is(v) && v.content.str === '') || (r_symbol_1.RSymbol.is(v) && v.content === convert_values_1.RNull) || callsTagged(v, data, built_in_props_1.SemanticCallTag.Console));
705
709
  }
706
- /** The stems of the files the call names, `undefined` unless every file argument is a known path to a file with an extension (a device's `plot%03d.png` or a directory may stand for others). */
707
- function fileStems(res, rootId, data, { sig, numbered }) {
710
+ /** The names of the files the call names (`data.csv` for `out/data.csv`), `undefined` unless every file argument is a known path to a file with an extension (a device's `plot%03d.png` or a directory may stand for others). */
711
+ function fileNames(res, rootId, data, { sig, numbered }) {
708
712
  const call = res.graph.getVertex(rootId);
709
713
  if (sig === undefined || !vertex_1.DfgVertex.isFunctionCall(call)) {
710
714
  return undefined;
@@ -715,7 +719,7 @@ function fileStems(res, rootId, data, { sig, numbered }) {
715
719
  : named.length < resources.filter(([n, p]) => n !== '...' && (p & (built_in_props_1.ArgProp.Forced | built_in_props_1.ArgProp.Optional)) === built_in_props_1.ArgProp.Forced).length) {
716
720
  return undefined;
717
721
  }
718
- const stems = [];
722
+ const names = [];
719
723
  for (const id of named) {
720
724
  if (namesNoFile(id, data)) {
721
725
  continue;
@@ -723,19 +727,19 @@ function fileStems(res, rootId, data, { sig, numbered }) {
723
727
  /* every `tempfile()` names a file no other call names */
724
728
  const fresh = boundValues(id, data);
725
729
  if (fresh.length > 0 && fresh.every(v => callsTagged(v, data, built_in_props_1.SemanticCallTag.TempFile))) {
726
- stems.push(...fresh.map(v => `tmp-${v.info.id}`));
730
+ names.push(...fresh.map(v => `tmp-${v.info.id}`));
727
731
  continue;
728
732
  }
729
733
  const paths = node_value_1.NodeValue.stringsOf(id, data);
730
734
  for (const path of paths?.length ? paths : ['']) {
731
- const [stem, ...extension] = path.split(/[/\\]/).at(-1)?.split('.') ?? [];
732
- if (!stem || extension.length === 0 || /[*?[]/.test(path) || (numbered && path.includes('%'))) {
735
+ const name = path.split(/[/\\]/).at(-1) ?? '';
736
+ if (!/^[^.]+\../.test(name) || /[*?[]/.test(path) || (numbered && path.includes('%'))) {
733
737
  return undefined;
734
738
  }
735
- stems.push(stem);
739
+ names.push(name);
736
740
  }
737
741
  }
738
- return stems;
742
+ return names;
739
743
  }
740
744
  /** What printing `value` reads: the printing `keys` for a plain value, all options for an unknown one (a tibble reads the pillar options). */
741
745
  function printingReads(value, dispatches, keys, data) {
@@ -1,4 +1,4 @@
1
- import type { DataflowProcessorInformation } from '../../../../../processor';
1
+ import { type DataflowProcessorInformation } from '../../../../../processor';
2
2
  import type { DataflowInformation } from '../../../../../info';
3
3
  import { type PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
4
4
  import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/decorate';
@@ -3,10 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.resolveFunctionArgument = resolveFunctionArgument;
4
4
  exports.processApply = processApply;
5
5
  exports.callNamedFunction = callNamedFunction;
6
+ const processor_1 = require("../../../../../processor");
7
+ const control_flow_1 = require("../../../../control-flow");
6
8
  const built_in_expression_list_1 = require("./built-in-expression-list");
7
9
  const function_semantics_1 = require("../../../../../fn/function-semantics");
8
10
  const known_call_handling_1 = require("../known-call-handling");
9
11
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
12
+ const type_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/type");
13
+ const named_call_handling_1 = require("../named-call-handling");
10
14
  const built_in_get_1 = require("./built-in-get");
11
15
  const r_symbol_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
12
16
  const node_id_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id");
@@ -51,6 +55,14 @@ function resolveFunctionArgument(val, data, opts) {
51
55
  /** Process an apply call like `vapply` or `mapply`. */
52
56
  function processApply(name, args, rootId, data, config) {
53
57
  const { indexOfFunction = 1, nameOfFunctionArgument, unquoteFunction, resolveInEnvironment, resolveValue, hasUnknownSideEffects, isTheCall, folds, sig } = config;
58
+ const direct = isTheCall ? directCallOf(args, data) : undefined;
59
+ if (direct !== undefined) {
60
+ /* the name is still evaluated first */
61
+ const named = (0, processor_1.processDataflowFor)(args[0], data);
62
+ const call = (0, named_call_handling_1.processNamedCall)(direct.name, direct.args, rootId, { ...data, environment: named.environment });
63
+ call.graph.mergeWith(named.graph);
64
+ return { ...call, in: [...named.in, ...call.in], unknownReferences: [...named.unknownReferences, ...call.unknownReferences], cfgEntry: control_flow_1.ControlFlow.inSequence(call.graph, [named, call]) };
65
+ }
54
66
  /* the length is one-based and the argument mapping zero-based, so the function sits at `indexOfFunction` */
55
67
  const resFn = (0, known_call_handling_1.processKnownFunctionCall)({
56
68
  name, args, rootId, data, sig: function_semantics_1.FunctionSemantics.call.signature.only(indexOfFunction, nameOfFunctionArgument ?? 'FUN'), origin: built_in_proc_name_1.BuiltInProcName.Apply
@@ -175,6 +187,23 @@ function processApply(name, args, rootId, data, config) {
175
187
  unknownReferences: information.unknownReferences.filter(ref => ref.nodeId !== functionId)
176
188
  };
177
189
  }
190
+ /**
191
+ * The call `do.call(what, args)` makes, when `what` is a literal naming built-ins only that bind or remove names (`"assign"`) and `args` a literal `list(...)`:
192
+ * processed as that call (`assign("x", 1)`), its processor sees the arguments it needs to know which names it binds.
193
+ */
194
+ function directCallOf(args, data) {
195
+ const [what, list] = args.map(r_argument_1.RArgument.valueOf);
196
+ if (args.length !== 2 || args.some(a => a === r_function_call_1.EmptyArgument || (a.name !== undefined && a.name.content !== (a === args[0] ? 'what' : 'args')))
197
+ || !(r_string_1.RString.is(what) || r_symbol_1.RSymbol.is(what)) || !r_function_call_1.RFunctionCall.isNamed(list, identifier_1.Identifier.make('list'))) {
198
+ return undefined;
199
+ }
200
+ const content = r_string_1.RString.is(what) ? identifier_1.Identifier.make(what.content.str) : what.content;
201
+ const builtIn = (name, binds) => {
202
+ const targets = resolve_helper_1.Resolve.byNameAndType(name, data.environment, identifier_1.ReferenceType.Function) ?? [];
203
+ return targets.length > 0 && targets.every(t => t.type === identifier_1.ReferenceType.BuiltInFunction && (!binds || built_in_props_1.CallProps.hasAny(t.config, built_in_props_1.CallProp.Scope) && !built_in_props_1.CallProps.hasAny(t.config, built_in_props_1.SemanticCallTag.LoadsPackage)));
204
+ };
205
+ return builtIn(content, true) && builtIn(list.functionName.content, false) ? { name: { ...what, type: type_1.RType.Symbol, content, lexeme: identifier_1.Identifier.toString(content) }, args: list.arguments } : undefined;
206
+ }
178
207
  /** Makes the node naming a function (`resolved`) the call of that function with `args`, as `do.call` does or evaluating a constructed call (`eval(call("f", x))`); a computed name gets a call of its own (`functionId`) that reads it. */
179
208
  function callNamedFunction(information, resolved, args, rootId, data, resolveInEnvironment, functionId = resolved.computed ? `${resolved.functionId}-call` : resolved.functionId) {
180
209
  const { functionName, asString } = resolved;
@@ -79,7 +79,8 @@ function yieldsEnvironment(node, graph, data) {
79
79
  }
80
80
  function tryReplacement(rootId, functionName, data, superAssignment, args, beforeDefine) {
81
81
  const resolved = resolve_helper_1.Resolve.byNameAndType(functionName.content, data.environment, identifier_1.ReferenceType.Function) ?? [];
82
- const builtIn = resolved.length === 1 && resolved[0].type === identifier_1.ReferenceType.BuiltInFunction ? resolved[0] : undefined;
82
+ /* an export named like a primitive (lubridate's `$<-`) is a method for it, which carries what flowR states about the primitive along, as the primitive still runs the call */
83
+ const builtIn = resolved.length === 1 && (resolved[0].type === identifier_1.ReferenceType.BuiltInFunction || 'processor' in resolved[0]) ? resolved[0] : undefined;
83
84
  /* every replacement function rebinds its target, no matter whether we ship a built-in for it or the user wrote it; a user-defined one is only ever bound under its `<-` name, the `<<-` form stays in the configuration */
84
85
  const name = builtIn ? functionName.content : identifier_1.Identifier.mapName(functionName.content, n => superAssignment ? n.slice(0, -'<<-'.length) + '<-' : n);
85
86
  const replacementConfig = builtIn ? builtIn.config : { readIndices: true, assignmentOperator: superAssignment ? '<<-' : '<-' };
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.processAttach = processAttach;
4
4
  exports.processDetach = processDetach;
5
+ const r_function_definition_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
5
6
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
6
7
  const known_call_handling_1 = require("../known-call-handling");
7
8
  const r_function_call_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
@@ -43,7 +44,7 @@ _config = {}) {
43
44
  const injected = [];
44
45
  for (const entry of listed ?? []) {
45
46
  const at = entry.value.info.id;
46
- injected.push({ nodeId: at, name: entry.name?.content, type: identifier_1.ReferenceType.Variable, definedAt: rootId, cds: data.cds ? [...data.cds] : undefined });
47
+ injected.push({ nodeId: at, name: entry.name?.content, type: r_function_definition_1.RFunctionDefinition.is(entry.value) ? identifier_1.ReferenceType.Function : identifier_1.ReferenceType.Variable, definedAt: rootId, cds: data.cds ? [...data.cds] : undefined });
47
48
  result.graph.addEdge(at, rootId, edge_1.EdgeType.Reads);
48
49
  }
49
50
  for (const column of dataset?.columns ?? []) {
@@ -54,8 +54,12 @@ export declare function suppliesArg<OtherInfo>(args: readonly PotentiallyEmptyRA
54
54
  export declare function resolveEnvirOrPosition<OtherInfo>(arg: PotentiallyEmptyRArgument<OtherInfo & ParentInformation>, formal: BrandedIdentifier, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): EnvirResolution<OtherInfo> | undefined;
55
55
  /** The first of `formals` whose argument resolves to a tracked environment; ambiguity is left to the caller. */
56
56
  export declare function resolveFirstEnvirArg<OtherInfo>(args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], data: DataflowProcessorInformation<OtherInfo & ParentInformation>, sig: FnSig | undefined, formals: readonly BrandedIdentifier[]): EnvirResolution<OtherInfo> | undefined;
57
- /** Marks `result` as an unknown side effect when the envir argument names a value that cannot be pinned down (e.g. a parameter), so routing the writes anywhere would be a guess (and what they bind may be any method); reports whether it did. */
58
- export declare function unknownIfAmbiguous<OtherInfo>(routing: EnvirArgRouting<OtherInfo>, result: DataflowInformation, rootId: NodeId): boolean;
57
+ /**
58
+ * Marks `result` as an unknown side effect when the envir argument names a value that cannot be pinned down (e.g. a parameter), so routing the writes anywhere would be a guess (and what they bind may be any method); reports whether it did.
59
+ * With the node `envir` of the argument's value, the effect only holds while that value may be an environment, which the dataflow extractor decides on the complete graph
60
+ * (see {@link DataflowGraph#markUnknownUnlessNoEnvironment}): a list or a data frame gives the evaluation a frame of its own, which no other binding sees.
61
+ */
62
+ export declare function unknownIfAmbiguous<OtherInfo>(routing: EnvirArgRouting<OtherInfo>, result: DataflowInformation, rootId: NodeId, envir?: NodeId): boolean;
59
63
  /** Resolves a symbol by name to an {@link EnvirResolution} when it holds a tracked environment. */
60
64
  export declare function resolveSymbolToEnvir<OtherInfo>(symbolName: Identifier, nodeId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): EnvirResolution<OtherInfo> | undefined;
61
65
  /** The calls that look up bindings in an environment they are given, or write into it, see {@link readEnvironmentContents}. */
@@ -225,12 +225,19 @@ function resolveFirstEnvirArg(args, data, sig, formals) {
225
225
  }
226
226
  return undefined;
227
227
  }
228
- /** Marks `result` as an unknown side effect when the envir argument names a value that cannot be pinned down (e.g. a parameter), so routing the writes anywhere would be a guess (and what they bind may be any method); reports whether it did. */
229
- function unknownIfAmbiguous(routing, result, rootId) {
228
+ /**
229
+ * Marks `result` as an unknown side effect when the envir argument names a value that cannot be pinned down (e.g. a parameter), so routing the writes anywhere would be a guess (and what they bind may be any method); reports whether it did.
230
+ * With the node `envir` of the argument's value, the effect only holds while that value may be an environment, which the dataflow extractor decides on the complete graph
231
+ * (see {@link DataflowGraph#markUnknownUnlessNoEnvironment}): a list or a data frame gives the evaluation a frame of its own, which no other binding sees.
232
+ */
233
+ function unknownIfAmbiguous(routing, result, rootId, envir) {
230
234
  if (routing !== 'ambiguous') {
231
235
  return false;
232
236
  }
233
237
  (0, unknown_side_effect_1.handleUnknownSideEffect)(result.graph, result.environment, rootId);
238
+ if (envir !== undefined) {
239
+ result.graph.markUnknownUnlessNoEnvironment(rootId, envir);
240
+ }
234
241
  (0, built_in_expression_list_1.noteUnknownMethods)(result.environment, rootId);
235
242
  return true;
236
243
  }
@@ -173,7 +173,7 @@ function evaluateQuoted(code, envir, rootId, information, data) {
173
173
  for (const r of results) {
174
174
  result.graph.addEdge(rootId, r.entryPoint, edge_1.EdgeType.Returns);
175
175
  }
176
- (0, built_in_envir_utils_1.unknownIfAmbiguous)(routing, result, rootId);
176
+ (0, built_in_envir_utils_1.unknownIfAmbiguous)(routing, result, rootId, envir === undefined ? undefined : r_argument_1.RArgument.valueOf(envir)?.info.id);
177
177
  return result;
178
178
  }
179
179
  function namesParentFrame(envir, data) {
@@ -1,8 +1,19 @@
1
1
  import { type DataflowProcessorInformation } from '../../../../../processor';
2
2
  import { type DataflowInformation } from '../../../../../info';
3
- import type { ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/decorate';
3
+ import type { AstIdMap, ParentInformation } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/decorate';
4
4
  import type { PotentiallyEmptyRArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call';
5
5
  import type { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing/node-id';
6
6
  import type { RSymbol } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol';
7
+ import type { ResolveInfo } from '../../../../../eval/resolve/alias-tracking';
8
+ import type { DataflowGraph } from '../../../../../graph/graph';
9
+ import type { RForLoop } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-for-loop';
10
+ /**
11
+ * Whether the for loop certainly runs its body to the end once, as {@link processForLoop} defines what the body defines as definitely
12
+ * as the code around the loop: it iterates over a vector with an element, and no `break` or `next` of its own cuts the first iteration short.
13
+ */
14
+ export declare function runsBodyOnce(loop: RForLoop<ParentInformation>, info: ResolveInfo & {
15
+ readonly idMap: AstIdMap;
16
+ readonly graph: DataflowGraph;
17
+ }): boolean;
7
18
  /** Processes a for-loop call: `for(<variable> in <vector>) <body>` desugared as a call of `for` with the three as arguments. */
8
19
  export declare function processForLoop<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>): DataflowInformation;
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.runsBodyOnce = runsBodyOnce;
3
4
  exports.processForLoop = processForLoop;
4
5
  const hooks_1 = require("../../../../../hooks");
5
6
  const r_argument_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
@@ -18,6 +19,10 @@ const apply_kill_1 = require("../../../../../environments/apply-kill");
18
19
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
19
20
  const built_in_ambient_state_1 = require("./built-in-ambient-state");
20
21
  const node_value_1 = require("../../../../../eval/resolve/node-value");
22
+ const model_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/model");
23
+ const r_break_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-break");
24
+ const r_next_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-next");
25
+ const r_function_definition_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
21
26
  const r_binary_op_1 = require("../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op");
22
27
  const vertex_1 = require("../../../../../graph/vertex");
23
28
  const environment_1 = require("../../../../../environments/environment");
@@ -27,19 +32,32 @@ function hasElement(value) {
27
32
  return value.type === 'vector' ? Array.isArray(value.elements) && value.elements.length > 0 : ScalarTypes.has(value.type);
28
33
  }
29
34
  /** whether the node certainly holds a value and every value it may hold satisfies `holds` */
30
- function alwaysHolds(node, data, holds) {
31
- const values = node_value_1.NodeValue.setOf(node.info.id, data)?.elements;
35
+ function alwaysHolds(node, against, holds) {
36
+ const values = node_value_1.NodeValue.setOf(node.info.id, against)?.elements;
32
37
  return values !== undefined && values.length > 0 && values.every(holds);
33
38
  }
34
39
  /** `a:b` always has an element or fails, unless both sides are factors, which a plain value is not */
35
- function isNonEmptyRange(vector, entry, data) {
40
+ function isNonEmptyRange(vector, graph, against) {
36
41
  if (!r_binary_op_1.RBinaryOp.is(vector) || vector.operator !== ':') {
37
42
  return false;
38
43
  }
39
- if (!vertex_1.DfgVertex.hasOrigin(entry.graph.getVertex(vector.info.id), built_in_proc_name_1.BuiltInProcName.Default)) {
44
+ if (!vertex_1.DfgVertex.hasOrigin(graph.getVertex(vector.info.id), built_in_proc_name_1.BuiltInProcName.Default)) {
40
45
  return false;
41
46
  }
42
- return [vector.lhs, vector.rhs].some(side => alwaysHolds(side, data, v => v.type !== 'vector' && hasElement(v)));
47
+ return [vector.lhs, vector.rhs].some(side => alwaysHolds(side, against, v => v.type !== 'vector' && hasElement(v)));
48
+ }
49
+ /** whether the loop iterates over a vector with an element, so it runs its body at least once */
50
+ const iterates = (vector, graph, against) => isNonEmptyRange(vector, graph, against) || alwaysHolds(vector, against, hasElement);
51
+ /**
52
+ * Whether the for loop certainly runs its body to the end once, as {@link processForLoop} defines what the body defines as definitely
53
+ * as the code around the loop: it iterates over a vector with an element, and no `break` or `next` of its own cuts the first iteration short.
54
+ */
55
+ function runsBodyOnce(loop, info) {
56
+ const cuts = [...model_1.RNode.collectAllIds(loop.body)].some(id => {
57
+ const node = info.idMap.get(id);
58
+ return (r_break_1.RBreak.is(node) || r_next_1.RNext.is(node)) && model_1.RNode.findEnclosing(id, info.idMap, n => r_function_definition_1.RFunctionDefinition.is(n) || model_1.RLoopConstructs.is(n)) === loop.info.id;
59
+ });
60
+ return !cuts && iterates(loop.vector, info.graph, info);
43
61
  }
44
62
  /** Processes a for-loop call: `for(<variable> in <vector>) <body>` desugared as a call of `for` with the three as arguments. */
45
63
  function processForLoop(name, args, rootId, data) {
@@ -57,7 +75,7 @@ function processForLoop(name, args, rootId, data) {
57
75
  return vector;
58
76
  }
59
77
  /* resolved before the loop variable is bound, as it may share the name of what the vector reads */
60
- const nonEmpty = isNonEmptyRange(vectorArg, vector, data) || alwaysHolds(vectorArg, data, hasElement);
78
+ const nonEmpty = iterates(vectorArg, vector.graph, data);
61
79
  const variable = (0, processor_1.processDataflowFor)(variableArg, data);
62
80
  let headEnvironments = environment_1.REnvironment.overwrite(vector.environment, variable.environment);
63
81
  /* only the vector's references and entry point are read past this, its graph is not */
@@ -8,7 +8,7 @@ import { NodeId } from '../../../../../../r-bridge/lang-4.x/ast/model/processing
8
8
  import { type BrandedIdentifier, type BrandedNamespace } from '../../../../../environments/identifier';
9
9
  import type { BuiltInFnInfo } from '../../../../../environments/built-in-props';
10
10
  import { type REnvironmentInformation } from '../../../../../environments/environment';
11
- import type { FlowrAnalyzerContext } from '../../../../../../project/context/flowr-analyzer-context';
11
+ import type { ReadOnlyFlowrAnalyzerContext } from '../../../../../../project/context/flowr-analyzer-context';
12
12
  import { Package } from '../../../../../../project/plugins/package-version-plugins/package';
13
13
  /** Controls how {@link processLibrary} brings a package into scope. */
14
14
  export interface LibraryProcessorConfig extends BuiltInFnInfo {
@@ -46,12 +46,12 @@ export interface AttachSpec {
46
46
  /** Process a library call like `library` or `require` */
47
47
  export declare function processLibrary<OtherInfo>(name: RSymbol<OtherInfo & ParentInformation>, args: readonly PotentiallyEmptyRArgument<OtherInfo & ParentInformation>[], rootId: NodeId, data: DataflowProcessorInformation<OtherInfo & ParentInformation>, config?: LibraryProcessorConfig): DataflowInformation;
48
48
  /** Materialize the empty built-in function-definition vertex for a package export (idempotent). */
49
- export declare function attachExportVertex(graph: DataflowGraph, builtInId: NodeId, environment: REnvironmentInformation, ctx: FlowrAnalyzerContext, cds?: readonly ControlDependency[]): void;
49
+ export declare function attachExportVertex(graph: DataflowGraph, builtInId: NodeId, environment: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext, cds?: readonly ControlDependency[]): void;
50
50
  /**
51
51
  * Attaches `pack` as `library(pack)` does: its resolved exports, else what flowR states about it, else a bare
52
52
  * {@link EnvType.LoadedNamespace} recording the load. The `library()` processor and `Dataflow.library` both use this.
53
53
  */
54
- export declare function attachLibrary(pack: BrandedNamespace, dependency: Package | undefined, envInfo: REnvironmentInformation, ctx: FlowrAnalyzerContext, spec?: AttachSpec, loadedAt?: NodeId, cds?: readonly ControlDependency[]): REnvironmentInformation;
54
+ export declare function attachLibrary(pack: BrandedNamespace, dependency: Readonly<Package> | undefined, envInfo: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext, spec?: AttachSpec, loadedAt?: NodeId, cds?: readonly ControlDependency[]): REnvironmentInformation;
55
55
  /**
56
56
  * The load calls (`library()`/`require()`) that brought package `pack` (any package if not given) into scope without a
57
57
  * database, collected from the {@link libraryLoadMarker} of every matching {@link EnvType.LoadedNamespace} layer below the
@@ -72,29 +72,29 @@ export declare function processPrefer<OtherInfo>(name: RSymbol<OtherInfo & Paren
72
72
  * Attaches `dependency`'s exports at `spec`'s {@link AttachSpec#pos|search position} (below global by default) and
73
73
  * returns the enriched environment (graph untouched). Used by `library()`, `import::from`, `box::use`, `requireNamespace`, and transitive side-effect propagation.
74
74
  */
75
- export declare function attachDependencyToEnvironment(dependency: Package, envInfo: REnvironmentInformation, ctx: FlowrAnalyzerContext, spec?: AttachSpec, definedAt?: NodeId): REnvironmentInformation;
75
+ export declare function attachDependencyToEnvironment(dependency: Readonly<Package>, envInfo: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext, spec?: AttachSpec, definedAt?: NodeId): REnvironmentInformation;
76
76
  /**
77
77
  * Attach the {@link baseRPackages|base-R} exports below the global so bare base calls resolve without `library()`.
78
78
  * No-op when no database resolves a base package; the built layer is cached per {@link baseNamespaceCacheKey}.
79
79
  */
80
- export declare function attachBaseRNamespaces(env: REnvironmentInformation, ctx: FlowrAnalyzerContext): REnvironmentInformation;
80
+ export declare function attachBaseRNamespaces(env: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext): REnvironmentInformation;
81
81
  /**
82
82
  * Attach the project's declared `DESCRIPTION` dependencies below the global, mirroring base-R auto-attach, so their bare
83
83
  * calls resolve without an explicit `library()`; skips a dependency no database resolves, no-ops via {@link isAttached}.
84
84
  */
85
- export declare function attachDeclaredDependencies(env: REnvironmentInformation, ctx: FlowrAnalyzerContext): REnvironmentInformation;
85
+ export declare function attachDeclaredDependencies(env: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext): REnvironmentInformation;
86
86
  /** attach the analyzed package's own `NAMESPACE importFrom(...)` symbols (by their bare name) below the global, so a bare imported call resolves to its source package */
87
- export declare function attachProjectImports(env: REnvironmentInformation, ctx: FlowrAnalyzerContext): REnvironmentInformation;
87
+ export declare function attachProjectImports(env: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext): REnvironmentInformation;
88
88
  /**
89
89
  * Attaches the packages `solver.assumeAttachedPackages` names as if the code had called `library()` on them.
90
90
  * Covers the case where such a call is simply not part of what is being analyzed (a snippet, a chunk, a cell).
91
91
  */
92
- export declare function attachAssumedPackages(env: REnvironmentInformation, ctx: FlowrAnalyzerContext): REnvironmentInformation;
92
+ export declare function attachAssumedPackages(env: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext): REnvironmentInformation;
93
93
  /**
94
94
  * Defines the objects `R/sysdata.rda` lazy-loads into the package namespace: internal, not exported, available
95
95
  * to the package's own code without a call bringing them in. Modelled on the global env for R's resolution order.
96
96
  * @see https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Data-in-packages
97
97
  */
98
- export declare function defineProjectSysdata(env: REnvironmentInformation, ctx: FlowrAnalyzerContext): REnvironmentInformation;
98
+ export declare function defineProjectSysdata(env: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext): REnvironmentInformation;
99
99
  /** attach every project-level environment layer in order: base R namespaces, the project's own `importFrom` symbols, its declared dependencies, whatever the configuration assumes attached, then the package's own system data */
100
- export declare function attachProject(env: REnvironmentInformation, ctx: FlowrAnalyzerContext): REnvironmentInformation;
100
+ export declare function attachProject(env: REnvironmentInformation, ctx: ReadOnlyFlowrAnalyzerContext): REnvironmentInformation;
@@ -105,8 +105,8 @@ function savedInto(paths, data) {
105
105
  const names = new Set();
106
106
  let complete = true;
107
107
  for (const path of paths) {
108
- const stem = r_string_1.RString.unquote(path).split(/[/\\]/).at(-1)?.split('.')[0];
109
- const writers = stem ? resolve_helper_1.Resolve.byName(ambient_state_name_1.AmbientStateName.file(stem), data.environment) : undefined;
108
+ const name = r_string_1.RString.unquote(path).split(/[/\\]/).at(-1);
109
+ const writers = name ? resolve_helper_1.Resolve.byName(ambient_state_name_1.AmbientStateName.file(name), data.environment) : undefined;
110
110
  if (writers === undefined || writers.length === 0) {
111
111
  return undefined;
112
112
  }
@@ -78,7 +78,7 @@ function processLocal(name, args, rootId, data, config) {
78
78
  out: dfExpr.out.concat(dfEnv.out),
79
79
  unknownReferences: []
80
80
  };
81
- (0, built_in_envir_utils_1.unknownIfAmbiguous)(envirRouting, baseResult, rootId);
81
+ (0, built_in_envir_utils_1.unknownIfAmbiguous)(envirRouting, baseResult, rootId, env?.info.id);
82
82
  return baseResult;
83
83
  }
84
84
  /** Evaluates `expr` in the environment `envir` pins down, or in a fresh frame on top of the current one, as `local` and `eval(expr, envir)` do. */
@@ -115,7 +115,7 @@ function processSourceCall(name, args, rootId, data, config) {
115
115
  if (sourceFileArgument === undefined) {
116
116
  logger_1.dataflowLogger.warn('Expected a file argument for source, skipping');
117
117
  const unknown = (0, known_call_handling_1.processKnownFunctionCall)({ name, args, rootId, data, origin: 'default' }).information;
118
- (0, built_in_expression_list_1.bindsUnknownNames)(unknown.graph, unknown.environment, rootId);
118
+ bindsUnseen(unknown, rootId, data);
119
119
  return unknown;
120
120
  }
121
121
  const localArg = bound.get(config.envIn ?? 'local');
@@ -130,7 +130,7 @@ function processSourceCall(name, args, rootId, data, config) {
130
130
  const withAmbient = () => config.ambient === undefined ? information : (0, built_in_ambient_state_1.applyAmbientEffects)(information, args, rootId, data, config.ambient);
131
131
  if (!config.forceFollow && data.ctx.config.ignoreSourceCalls) {
132
132
  (0, log_1.expensiveTrace)(logger_1.dataflowLogger, () => `Skipping source call ${JSON.stringify(sourceFileArgument)} (disabled in config file)`);
133
- (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
133
+ bindsUnseen(information, rootId, data);
134
134
  return withAmbient();
135
135
  }
136
136
  let sourceFile;
@@ -143,7 +143,7 @@ function processSourceCall(name, args, rootId, data, config) {
143
143
  const path = sourceFile?.length === 1 ? r_string_1.RString.unquote(sourceFile[0]) : undefined;
144
144
  const filepath = path ? findSource(data.ctx.config.solver.resolveSource, path, data) : undefined;
145
145
  if (localArg !== undefined && !r_logical_1.RLogical.is(localArg.value) && resolution === undefined) {
146
- (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
146
+ bindsUnseen(information, rootId, data);
147
147
  return withAmbient();
148
148
  }
149
149
  if (filepath !== undefined && filepath.length > 0) {
@@ -183,9 +183,18 @@ function processSourceCall(name, args, rootId, data, config) {
183
183
  return routed;
184
184
  }
185
185
  (0, log_1.expensiveTrace)(logger_1.dataflowLogger, () => `Non-constant argument ${JSON.stringify(sourceFile)} for source is currently not supported, skipping`);
186
- (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
186
+ bindsUnseen(information, rootId, data);
187
187
  return withAmbient();
188
188
  }
189
+ /** Code we cannot see has an unknown side effect, and binds methods only if `solver.resolveSource.unseenMethods` is set. */
190
+ function bindsUnseen(information, rootId, data) {
191
+ if (data.ctx.config.solver.resolveSource?.unseenMethods) {
192
+ (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
193
+ }
194
+ else {
195
+ (0, unknown_side_effect_1.handleUnknownSideEffect)(information.graph, information.environment, rootId);
196
+ }
197
+ }
189
198
  /** The reads of code evaluated in the global environment, which no frame of the function running it binds; the `call`'s own reads stay as they are. */
190
199
  function readGlobally(result, call) {
191
200
  const own = new Set([...call.in, ...call.unknownReferences]);
@@ -207,20 +216,20 @@ function sourceRequest(rootId, request, data, information, makeMaybe, getId, eva
207
216
  const textRequest = data.ctx.files.resolveRequest(request);
208
217
  if (textRequest === undefined && request.request === 'file') {
209
218
  logger_1.dataflowLogger.warn(`Failed to analyze sourced file ${JSON.stringify(request)}: file does not exist`);
210
- (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
219
+ bindsUnseen(information, rootId, data);
211
220
  return information;
212
221
  }
213
222
  (0, assert_1.guard)(textRequest !== undefined, `Expected text request to be defined for sourced file ${JSON.stringify(request)}`);
214
223
  const ext = textRequest.path ? /\.[^.]*$/.exec(textRequest.path)?.[0].toLowerCase() : undefined;
215
224
  if (ext !== undefined && ext !== '.r') {
216
225
  (0, log_1.expensiveTrace)(logger_1.dataflowLogger, () => `Skipping source of non-R file ${JSON.stringify(textRequest.path)}`);
217
- (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
226
+ bindsUnseen(information, rootId, data);
218
227
  return information;
219
228
  }
220
229
  const gasLevel = data.ctx.gas.checkGas(gas_1.GasFeatureKey.Source);
221
230
  if (gasLevel >= 2 /* GasLevel.Critical */) {
222
231
  logger_1.dataflowLogger.warn(`Skipping source of ${JSON.stringify(request)} due to resource pressure (gas: critical). See ${gas_1.GasWikiRef}`);
223
- (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
232
+ bindsUnseen(information, rootId, data);
224
233
  return information;
225
234
  }
226
235
  else if (gasLevel >= 1 /* GasLevel.Problematic */) {
@@ -257,7 +266,7 @@ function sourceRequest(rootId, request, data, information, makeMaybe, getId, eva
257
266
  catch (e) {
258
267
  logger_1.dataflowLogger.error(`Failed to analyze sourced file ${JSON.stringify(request)}, skipping: ${e.message}`);
259
268
  logger_1.dataflowLogger.error(e.stack);
260
- (0, built_in_expression_list_1.bindsUnknownNames)(information.graph, information.environment, rootId);
269
+ bindsUnseen(information, rootId, data);
261
270
  return information;
262
271
  }
263
272
  // take the entry point as well as all the written references, and give them a control dependency to the source call to show that they are conditional
@@ -304,10 +313,11 @@ function standaloneSourceFile(idx, file, data, information) {
304
313
  (0, unknown_side_effect_1.handleUnknownSideEffect)(information.graph, information.environment, file.root.info.id);
305
314
  return information;
306
315
  }
316
+ /* `sourceRequest` appends the file itself, so it runs at the top level just like the first file (e.g., auto-printing) */
307
317
  return sourceRequest('file-' + idx, file, {
308
318
  ...data,
309
319
  environment: information.environment,
310
- referenceChain: [file.filePath]
320
+ referenceChain: []
311
321
  }, information, false, undefined, false, false);
312
322
  }
313
323
  /** Folds the results of analyzing sourced code back into the information of the call that asked for it, which `eval` and the string templates both need: the code contributes everything it reads, writes, and leaves open. */
@@ -68,11 +68,35 @@ function processWithEnv(name, args, rootId, data) {
68
68
  const envirResolution = (0, built_in_envir_utils_1.envirOf)(envirRouting);
69
69
  if (!envirResolution) {
70
70
  const fallback = markAsMaskedFallback(name, args, rootId, data, exprArg.value);
71
+ const isWithin = identifier_1.Identifier.getName(name.content) === 'within';
72
+ if (isWithin) {
73
+ /* the copy `within` returns carries every variable `expr` defines, so the call needs all of these definitions, not just the last */
74
+ for (const [defId] of fallback.graph.verticesOfType(vertex_1.VertexType.VariableDefinition)) {
75
+ fallback.graph.addEdge(rootId, defId, edge_1.EdgeType.Reads);
76
+ }
77
+ }
78
+ /*
79
+ * `within` only has methods for lists and data frames and works on a copy of them, so what `expr` writes into a value
80
+ * the program defines (but we cannot track as an environment) never reaches the caller; a parameter is left alone,
81
+ * as the caller may hand in anything
82
+ */
83
+ if (isWithin && envirRouting === 'ambiguous' && !mayBeParameter(dataArg.value, data)) {
84
+ return fallback;
85
+ }
86
+ const defines = !fallback.graph.verticesOfType(vertex_1.VertexType.VariableDefinition).next().done;
71
87
  /* only a definition or a call we cannot see into (a closure of `data`) can write to a `data` we cannot pin down */
72
- if ((!fallback.graph.verticesOfType(vertex_1.VertexType.VariableDefinition).next().done || callsOpaque(fallback.graph, rootId)) && !(0, built_in_envir_utils_1.unknownIfAmbiguous)(envirRouting, fallback, rootId)) {
73
- return mayWriteInto(dataArg.value, fallback, rootId, data);
88
+ if (!defines && !callsOpaque(fallback.graph, rootId)) {
89
+ return fallback;
74
90
  }
75
- return fallback;
91
+ /*
92
+ * a definition in `expr` lands in `data` if it is an environment, which may be the global one, so only a definition
93
+ * makes the call an unknown side effect; a call we cannot see into is no more opaque than the same call outside of `with`,
94
+ * it can at most change `data`, which `mayWriteInto` covers
95
+ */
96
+ if (defines && (0, built_in_envir_utils_1.unknownIfAmbiguous)(envirRouting, fallback, rootId, dataArg.value.info.id)) {
97
+ return fallback;
98
+ }
99
+ return mayWriteInto(dataArg.value, fallback, rootId, data);
76
100
  }
77
101
  const pipedData = (0, common_1.isPipedArgument)(dataArg, rootId, data);
78
102
  const dfDataArg = pipedData ? info_1.DataflowInformation.initialize(rootId, data) : (0, processor_1.processDataflowFor)(dataArg.value, data);
@@ -192,6 +216,14 @@ function processWithLiteralList(name, rootId, data, dataNode, expr, elements) {
192
216
  function callsOpaque(graph, rootId) {
193
217
  return graph.verticesOfType(vertex_1.VertexType.FunctionCall).some(([id, vertex]) => id !== rootId && !vertex.onlyBuiltin);
194
218
  }
219
+ /** whether `dataNode` is not a symbol, or a symbol of which some definition is a parameter of the enclosing function */
220
+ function mayBeParameter(dataNode, data) {
221
+ if (!r_symbol_1.RSymbol.is(dataNode)) {
222
+ return true;
223
+ }
224
+ const defs = resolve_helper_1.Resolve.byNameAndType(dataNode.content, data.environment, identifier_1.ReferenceType.Variable);
225
+ return defs === undefined || defs.some(d => (d.type & identifier_1.ReferenceType.Parameter) !== 0);
226
+ }
195
227
  /** `data` may be an untracked environment `expr` writes into, so later reads of its variable see the call as a maybe redefinition. */
196
228
  function mayWriteInto(dataNode, result, rootId, data) {
197
229
  keepCallFor(result.out, result.graph, rootId);
@@ -173,7 +173,6 @@ The following showcases the dependency view of the ${ctx.linkPage('flowr:vscode'
173
173
  ${(0, doc_playground_1.tryInPlayground)({
174
174
  code: playgroundSample,
175
175
  marks: ['lint:unused-definitions'],
176
- collapsed: [playground_link_1.PlaygroundBox.Deps],
177
176
  at: '10@unused_total'
178
177
  }, 'the linter example')}
179
178
 
@@ -200,7 +199,7 @@ ${res}
200
199
  * 🍕 **program slicing**\\
201
200
  Given a point of interest like the visualization of a plot, _flowR_ reduces the program to just the parts which are relevant
202
201
  for the computation of the point of interest.
203
- ${(0, doc_playground_1.tryInPlayground)({ code: example, marks: [playground_link_1.PlaygroundBox.Slice], collapsed: [playground_link_1.PlaygroundBox.Deps], at: '11@sum' }, 'the slicing example')}
202
+ ${(0, doc_playground_1.tryInPlayground)({ code: example, marks: [playground_link_1.PlaygroundBox.Slice], at: '11@sum' }, 'the slicing example')}
204
203
 
205
204
 
206
205
  ${(0, doc_general_1.prefixLines)((0, doc_structure_1.details)('Example: Slicing with flowR', `
@@ -22,7 +22,7 @@ export interface ShowQueryOptions {
22
22
  readonly prepare?: (builder: FlowrAnalyzerBuilder) => void;
23
23
  }
24
24
  /** Visualizes a query and its results in markdown format. */
25
- export declare function showQuery<Base extends SupportedQueryTypes, VirtualArguments extends VirtualCompoundConstraint<Base> = VirtualCompoundConstraint<Base>>(parser: KnownParser, code: string, queries: Queries<Base, VirtualArguments>, { showCode, collapseResult, withJson, shorthand, ctx, files, prepare }?: ShowQueryOptions): Promise<string>;
25
+ export declare function showQuery<Base extends SupportedQueryTypes, VirtualArguments extends VirtualCompoundConstraint<Base> = VirtualCompoundConstraint<Base>>(parser: KnownParser, code: string | readonly string[], queries: Queries<Base, VirtualArguments>, { showCode, collapseResult, withJson, shorthand, ctx, files, prepare }?: ShowQueryOptions): Promise<string>;
26
26
  export interface QueryDocumentation {
27
27
  /** only for virtual queries, active ones carry their {@link SupportedQuery.title} */
28
28
  readonly name?: string;
@@ -40,7 +40,9 @@ async function showQuery(parser, code, queries, { showCode, collapseResult, with
40
40
  analyzer.addFile(new flowr_file_1.FlowrInlineTextFile(file.name, file.content));
41
41
  }
42
42
  /* code naming one of the files above analyzes that file, as a package's code is analyzed */
43
- analyzer.addRequest(files?.some(f => `${retriever_1.fileProtocol}${f.name}` === code) ? (0, retriever_1.requestFromInput)(code) : code);
43
+ for (const c of typeof code === 'string' ? [code] : code) {
44
+ analyzer.addRequest(files?.some(f => `${retriever_1.fileProtocol}${f.name}` === c) ? (0, retriever_1.requestFromInput)(c) : c);
45
+ }
44
46
  const results = await analyzer.query(queries);
45
47
  const duration = performance.now() - now;
46
48
  const metaInfo = `
@@ -80,7 +82,7 @@ ${(0, doc_code_1.jsonWithLimit)(results)}
80
82
  ${showCode ? `
81
83
  <details> <summary style="color:gray">Original Code</summary>
82
84
 
83
- ${(0, doc_code_1.codeBlock)('r', code)}
85
+ ${(0, doc_code_1.codeBlock)('r', typeof code === 'string' ? code : code.join('\n'))}
84
86
 
85
87
  </details>
86
88
  ` : ''}
@@ -229,6 +229,7 @@ The schema below documents every option; the ones you most likely want are:
229
229
  - ${ctx.linkConfig('semantics.environment.overwriteBuiltIns')}: overwrite _flowR_'s handling of built-in functions, or clear the preset definitions entirely.
230
230
  See [Configure BuiltIn Semantics](#configure-builtin-semantics) for more information.
231
231
  - ${ctx.linkConfig('semantics.ambient.drawingWritesDevice')}: whether calls drawing on a graphics device (e.g., \`plot\`) count as writing the device in the ambient state queries.
232
+ - ${ctx.linkConfig('solver.resolveSource.unseenMethods')}: whether a sourced file _flowR_ cannot read may bind S3/S4 methods that later calls dispatch to (sound, but chains every such call, off by default).
232
233
  - ${ctx.linkConfig('solver.variables')}: how to resolve variables and their values (${Object.values(config_1.VariableResolve).map(v => `\`${v}\``).join(', ')}).
233
234
  - ${ctx.linkConfig('engines')} and ${ctx.linkConfig('defaultEngine')}: the engines used to interact with R code, see the ${ctx.linkPage('wiki/Engines', 'Engines wiki page')}.
234
235
  - ${ctx.linkConfig('project.implicitSources')}: the files a framework loads without any \`source()\` call, in the order in which they are