@eagleoutice/flowr 2.16.4 → 2.16.5

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 +165 -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
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.StringFold = exports.PasteLikeCalls = exports.StringFns = void 0;
4
4
  const identifier_1 = require("../../environments/identifier");
5
5
  const r_value_1 = require("../values/r-value");
6
+ const set_constants_1 = require("../values/sets/set-constants");
6
7
  const string_constants_1 = require("../values/string/string-constants");
7
8
  const interval_constants_1 = require("../values/intervals/interval-constants");
8
9
  const match_arguments_1 = require("./match-arguments");
@@ -26,6 +27,20 @@ function dirname(path) {
26
27
  const head = trimmed.slice(0, cut).replace(/\/+$/, '');
27
28
  return head === '' ? '/' : head;
28
29
  }
30
+ /** `sprintf` with only `%s`, `%d` (or `%i`) and `%%` in its format and one argument for each, `undefined` for anything else (a width, a precision, another conversion) */
31
+ function format(fmt, parts) {
32
+ let next = 0;
33
+ let failed = false;
34
+ const formatted = fmt.replace(/%(.)/g, (_, conversion) => {
35
+ if (conversion === '%') {
36
+ return '%';
37
+ }
38
+ const part = parts[next++];
39
+ failed ||= part === undefined || (conversion !== 's' && !(/[di]/.test(conversion) && /^-?\d+$/.test(part)));
40
+ return part ?? '';
41
+ });
42
+ return failed || next !== parts.length || fmt.replaceAll('%%', '').endsWith('%') ? undefined : formatted;
43
+ }
29
44
  /**
30
45
  * Every string built-in the value solver folds, the joining ones included: `paste` is an entry like `toupper`
31
46
  * is, and both are reached through {@link resolveAsStringFn}. Teaching flowR one more is a line here plus the
@@ -39,6 +54,7 @@ exports.StringFns = {
39
54
  paste: { pkg: "base" /* PkgName.Base */, params: ['...', 'sep'], defaults: { sep: ' ' }, ignored: ['collapse'], fold: (parts, sep) => parts.join(sep) },
40
55
  paste0: { pkg: "base" /* PkgName.Base */, params: ['...', 'sep'], defaults: { sep: '' }, ignored: ['collapse'], fold: (parts, sep) => parts.join(sep) },
41
56
  'file.path': { pkg: "base" /* PkgName.Base */, params: ['...', 'fsep'], defaults: { fsep: '/' }, fold: (parts, fsep) => parts.join(fsep) },
57
+ sprintf: { pkg: "base" /* PkgName.Base */, params: ['fmt', '...'], fold: (fmt, parts = []) => format(fmt, parts) },
42
58
  /* the project root stays implicit, so the fold yields the path below it */
43
59
  here: { pkg: "here" /* PkgName.Here */, params: ['...'], fold: (parts) => parts.length > 0 ? parts.join('/') : '.' },
44
60
  /* the path splits, which only ever treat `/` as a separator, so a Windows path keeps its non-`\` parts */
@@ -99,26 +115,76 @@ function foldStringCall(node, resolveArg) {
99
115
  }
100
116
  return args.length > 0 ? known.fold(...args) : undefined;
101
117
  }
102
- function argAsString(id, against, coerce) {
103
- const sole = node_value_1.NodeValue.sole(node_value_1.NodeValue.setOf(id, against));
104
- if (sole === undefined) {
105
- return undefined;
106
- }
107
- if (sole.type === 'string' && (0, r_value_1.isValue)(sole.value)) {
108
- return sole.value.str;
118
+ /** the string a single value stands for, coercing a number or logical like `as.character` does if `coerce` is set */
119
+ function valueAsString(value, coerce) {
120
+ if (value.type === 'string' && (0, r_value_1.isValue)(value.value)) {
121
+ return value.value.str;
109
122
  }
110
123
  if (!coerce) {
111
124
  return undefined;
112
125
  }
113
- const num = r_value_1.RValue.numberOf(sole);
126
+ const num = r_value_1.RValue.numberOf(value);
114
127
  if (num !== undefined) {
115
128
  return Number.isInteger(num) && Math.abs(num) < 1e5 ? String(num) : undefined;
116
129
  }
117
- if (sole.type === 'logical' && (0, r_value_1.isValue)(sole.value) && sole.value !== 'maybe') {
118
- return sole.value ? 'TRUE' : 'FALSE';
130
+ if (value.type === 'logical' && (0, r_value_1.isValue)(value.value) && value.value !== 'maybe') {
131
+ return value.value ? 'TRUE' : 'FALSE';
119
132
  }
120
133
  return undefined;
121
134
  }
135
+ /** every string an argument may hold (e.g. the variable of a `for` loop), `undefined` if any of its values is none */
136
+ function argAsStrings(id, against, coerce) {
137
+ const set = node_value_1.NodeValue.setOf(id, against);
138
+ if (set === undefined || set.elements.length === 0) {
139
+ return undefined;
140
+ }
141
+ const strings = set.elements.map(e => valueAsString(e, coerce));
142
+ return strings.includes(undefined) ? undefined : strings;
143
+ }
144
+ /** how many combinations of argument values a fold is tried for, as `paste0(i, j)` of two long loops is no value worth listing */
145
+ const MaxFoldCombinations = 256;
146
+ /**
147
+ * Every value a fold may yield for the values its arguments may hold, one fold for each combination of them,
148
+ * `undefined` if an argument does not resolve to strings or there are too many combinations.
149
+ * The values are resolved once, as the solver does not resolve a node again while it is still resolving the call.
150
+ */
151
+ function foldAcrossValues(node, args, coerce) {
152
+ const options = new Map();
153
+ let unresolved = false;
154
+ const first = foldStringCall(node, arg => {
155
+ const strings = argAsStrings(arg.info.id, args, coerce);
156
+ if (strings === undefined) {
157
+ unresolved = true;
158
+ return undefined;
159
+ }
160
+ options.set(arg.info.id, strings);
161
+ return strings[0];
162
+ });
163
+ if (unresolved || first === undefined) {
164
+ return undefined;
165
+ }
166
+ const combinations = [...options.values()].reduce((n, o) => n * o.length, 1);
167
+ if (combinations > MaxFoldCombinations) {
168
+ return undefined;
169
+ }
170
+ const ids = [...options.keys()];
171
+ const pick = new Map();
172
+ const results = [];
173
+ const enumerate = (at) => {
174
+ if (at === ids.length) {
175
+ const folded = foldStringCall(node, arg => pick.get(arg.info.id));
176
+ if (folded !== undefined) {
177
+ results.push(folded);
178
+ }
179
+ return folded !== undefined;
180
+ }
181
+ return options.get(ids[at])?.every(s => {
182
+ pick.set(ids[at], s);
183
+ return enumerate(at + 1);
184
+ }) ?? false;
185
+ };
186
+ return enumerate(0) ? results : undefined;
187
+ }
122
188
  /**
123
189
  * Resolves any call of a {@link StringFns} entry to a {@link Value}, with its arguments in any order R accepts:
124
190
  * a join like `paste0("cfg_", k)` when every part resolves to a single string constant (coercing a joined
@@ -131,11 +197,12 @@ function resolveAsStringFn(args) {
131
197
  return r_value_1.Top;
132
198
  }
133
199
  const joined = exports.PasteLikeCalls.has(identifier_1.Identifier.getName(node.functionName.content));
134
- const folded = foldStringCall(node, arg => argAsString(arg.info.id, args, joined));
200
+ const folded = foldAcrossValues(node, args, joined);
135
201
  if (folded === undefined) {
136
202
  return r_value_1.Top;
137
203
  }
138
- return typeof folded === 'number' ? (0, interval_constants_1.intervalFrom)(folded, folded) : (0, string_constants_1.stringFrom)(folded);
204
+ const asValue = (f) => typeof f === 'number' ? (0, interval_constants_1.intervalFrom)(f, f) : (0, string_constants_1.stringFrom)(f);
205
+ return folded.length === 1 ? asValue(folded[0]) : (0, set_constants_1.setOf)(folded.map(asValue));
139
206
  }
140
207
  /**
141
208
  * Folding the string built-ins, from `paste` to `basename`.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.processors = void 0;
4
4
  exports.produceDataFlowGraph = produceDataFlowGraph;
5
+ const applied_arguments_1 = require("./graph/applied-arguments");
5
6
  const function_semantics_1 = require("./fn/function-semantics");
6
7
  const processor_1 = require("./processor");
7
8
  const process_uninteresting_leaf_1 = require("./internal/process/process-uninteresting-leaf");
@@ -298,7 +299,7 @@ function linkResourceReadersToWriters(graph, environment, ctx) {
298
299
  if (!reads && !writes) {
299
300
  continue;
300
301
  }
301
- const resource = argsWithProp(vertex, info, built_in_props_1.ArgProp.Resource)[0];
302
+ const resource = argsWithProp((0, applied_arguments_1.appliedArguments)(graph, vertex), info, built_in_props_1.ArgProp.Resource)[0];
302
303
  /* writing to the console names no file, and neither does a reader we cannot pin down */
303
304
  if (resource !== undefined) {
304
305
  (reads ? readers : writers).push({ id, resource });
@@ -314,9 +315,13 @@ function linkResourceReadersToWriters(graph, environment, ctx) {
314
315
  if (a === b || !reachedBy(b).isDisjointFrom(reachedBy(a))) {
315
316
  return true;
316
317
  }
318
+ /* a path we cannot resolve may name the other one */
317
319
  const path = pathOf(a);
318
- return path !== undefined && path === pathOf(b);
320
+ const other = pathOf(b);
321
+ return path === undefined || other === undefined || path === other;
319
322
  };
323
+ /* each added edge clears the graph's cached call names, but none of these edges changes what a call targets */
324
+ const prints = (0, defaultmap_1.memoize)((id) => function_semantics_1.FunctionSemantics.call.props.hasAll((0, query_fn_props_1.callFnProps)(id, { graph, environment }), [built_in_props_1.SemanticCallTag.Prints]));
320
325
  let cfg;
321
326
  for (const reader of readers) {
322
327
  let before;
@@ -327,8 +332,8 @@ function linkResourceReadersToWriters(graph, environment, ctx) {
327
332
  before ??= (0, happens_before_1.reachableTo)(cfg ??= new control_flow_graph_1.ControlFlowGraph(graph), [reader.id]);
328
333
  if (before.has(writer.id)) {
329
334
  graph.addEdge(reader.id, writer.id, edge_1.EdgeType.Reads);
330
- /* whatever is linked to a diverting writer (`print` after `sink(file)`) writes to the resource as well */
331
- for (const id of df_helper_1.Dataflow.sourcesOf(graph, writer.id, edge_1.EdgeType.Reads)) {
335
+ /* whatever prints into a diverting writer (`print` after `sink(file)`) writes to the resource as well */
336
+ for (const id of df_helper_1.Dataflow.sourcesOf(graph, writer.id, edge_1.EdgeType.Reads).filter(prints)) {
332
337
  graph.addEdge(reader.id, id, edge_1.EdgeType.Reads);
333
338
  }
334
339
  }
@@ -438,6 +443,7 @@ function extractDataFlowGraph(parser, completeAst, ctx) {
438
443
  processors: ctx.config.solver.instrument.dataflowExtractors?.(exports.processors, ctx) ?? exports.processors,
439
444
  cds: undefined,
440
445
  referenceChain: [files[0].filePath],
446
+ statementOrder: new Map(),
441
447
  ctx
442
448
  };
443
449
  let df = (0, assert_1.guardNesting)('Dataflow analysis', files[0].filePath, () => (0, processor_1.processDataflowFor)(files[0].root, dfData));
@@ -448,6 +454,7 @@ function extractDataFlowGraph(parser, completeAst, ctx) {
448
454
  // resolve linkages and propagate transitive side effects across calls to a fixpoint
449
455
  callActiveBindings(df.graph);
450
456
  readFramesThroughEnvironment(df.graph);
457
+ df.graph.statementOrder = dfData.statementOrder;
451
458
  (0, built_in_function_definition_1.updateNestedFunctionCalls)(df.graph, df.environment, ctx);
452
459
  const escapedNames = new Set();
453
460
  /* carried across the rounds, so a definition already folded in does not read as growth again */
@@ -0,0 +1,5 @@
1
+ import { type DataflowGraph } from './graph';
2
+ import { type DataflowGraphVertexFunctionCall } from './vertex';
3
+ import type { AstIdMap } from '../../r-bridge/lang-4.x/ast/model/processing/decorate';
4
+ /** `do.call(f, list(a, b))` calls `f` with what the `list` holds, so the call of `f` takes the arguments of the `list` */
5
+ export declare function appliedArguments(graph: DataflowGraph, vertex: DataflowGraphVertexFunctionCall, idMap?: AstIdMap | undefined): DataflowGraphVertexFunctionCall;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.appliedArguments = appliedArguments;
4
+ const graph_1 = require("./graph");
5
+ const vertex_1 = require("./vertex");
6
+ const r_symbol_1 = require("../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
7
+ const identifier_1 = require("../environments/identifier");
8
+ /** `do.call(f, list(a, b))` calls `f` with what the `list` holds, so the call of `f` takes the arguments of the `list` */
9
+ function appliedArguments(graph, vertex, idMap = graph.idMap) {
10
+ if (vertex.args.length !== 1 || !r_symbol_1.RSymbol.is(idMap?.get(vertex.id))) {
11
+ return vertex;
12
+ }
13
+ const ref = graph_1.FunctionArgument.getReference(vertex.args[0]);
14
+ const list = ref === undefined ? undefined : graph.getVertex(ref);
15
+ return vertex_1.DfgVertex.isFunctionCall(list) && identifier_1.Identifier.getName(list.name) === 'list' ? { ...vertex, args: list.args } : vertex;
16
+ }
17
+ //# sourceMappingURL=applied-arguments.js.map
@@ -332,7 +332,7 @@ exports.Dataflow = {
332
332
  * @see {@link Dataflow.provenanceGraph} - for a convenience wrapper to directly obtain the graph of the provenance.
333
333
  */
334
334
  provenance(id, graph, consider, followEdges = edge_1.EdgeType.Calls | edge_1.EdgeType.Reads | edge_1.EdgeType.Returns | edge_1.EdgeType.Argument | edge_1.EdgeType.DefinedBy | edge_1.EdgeType.DefinedByOnCall) {
335
- return graph_helper_1.GraphHelper.reachable(graph, id, { follow: followEdges, consider, cds: true });
335
+ return exports.Dataflow.reachable(graph, id, { follow: followEdges, consider, cds: true });
336
336
  },
337
337
  /**
338
338
  * A simple visitor akin to {@link RNode.visitAst} to traverse the dataflow graph starting from the start id and only
@@ -377,7 +377,7 @@ exports.Dataflow = {
377
377
  };
378
378
  /** both qualifications of a call from a single origin resolution, as the base-R step only adds to what the origins gave */
379
379
  const resolveQualification = (graph, id, vertex) => {
380
- const origins = (0, dfg_get_origin_1.getOriginInDfg)(graph, id);
380
+ const origins = exports.Dataflow.origin(graph, id);
381
381
  const name = vertex_1.DfgVertex.isFunctionCall(vertex) ? vertex.name : undefined;
382
382
  const bare = identifier_1.Identifier.toQualified(origins, name, false);
383
383
  return [bare, bare ?? identifier_1.Identifier.toQualified(origins, name, true)];
@@ -133,6 +133,11 @@ export declare const UnknownSideEffect: {
133
133
  */
134
134
  export declare class DataflowGraph<Vertex extends DataflowGraphVertexInfo = DataflowGraphVertexInfo, Edge extends DfEdge = DfEdge> {
135
135
  private _idMap;
136
+ /**
137
+ * Where the top-level statements of every file start and end running, counted in the order they first do, as a
138
+ * statement sourcing a file runs that file's statements in between. Set once the whole program is analyzed.
139
+ */
140
+ statementOrder: ReadonlyMap<NodeId, readonly [start: number, end: number]> | undefined;
136
141
  private readonly _unknownSideEffects;
137
142
  constructor(idMap: AstIdMap | undefined);
138
143
  /** Contains the vertices of the root level graph (i.e., included those vertices from the complete graph, that are nested within function definitions) */
@@ -99,6 +99,11 @@ exports.UnknownSideEffect = {
99
99
  */
100
100
  class DataflowGraph {
101
101
  _idMap;
102
+ /**
103
+ * Where the top-level statements of every file start and end running, counted in the order they first do, as a
104
+ * statement sourcing a file runs that file's statements in between. Set once the whole program is analyzed.
105
+ */
106
+ statementOrder;
102
107
  /*
103
108
  * Set of vertices which have sideEffects that we do not know anything about.
104
109
  * As a (temporary) solution until we have FD edges, a side effect may also store known target links
package/dataflow/info.js CHANGED
@@ -48,7 +48,14 @@ exports.ControlDependency = {
48
48
  };
49
49
  /** Appends the given control dependencies to `target`, skipping the ones that are already in there. */
50
50
  function appendCds(target, toAdd) {
51
- for (const add of toAdd ?? []) {
51
+ const adds = toAdd ?? [];
52
+ /* the lists often share a run copied from one growing list (e.g., the exits of every stopifnot in a script), so skip it */
53
+ const start = target.indexOf(adds[0]);
54
+ let i = 0;
55
+ while (start >= 0 && i < adds.length && target[start + i] === adds[i]) {
56
+ i++;
57
+ }
58
+ for (const add of adds.slice(i)) {
52
59
  if (!target.some(have => sameControlDependency(have, add))) {
53
60
  target.push(add);
54
61
  }
@@ -199,10 +199,21 @@ function linkFieldWritesOnCall(graph, id, fnId, start, binding, envState, idMap)
199
199
  }
200
200
  }
201
201
  }
202
+ /**
203
+ * Whether the call `info` may get its function from `target`, which it has the edge `e` to. An unnamed call reads
204
+ * the expression that gives its function. A named call that only reads another call reads state that call wrote,
205
+ * like the options, unless that call binds the name. No call binds a name that resolves to nothing (`unbound`),
206
+ * and a call processed by default (`options()`, `par()`) binds no name at all.
207
+ */
208
+ function mayBeFunctionSource(graph, info, target, e, unbound = false) {
209
+ const vertex = graph.getVertex(target);
210
+ return vertex_2.DfgVertex.hasOrigin(info, built_in_proc_name_1.BuiltInProcName.Unnamed) || edge_1.DfEdge.includesType(e, edge_1.EdgeType.Calls | edge_1.EdgeType.DefinedByOnCall) || !vertex_2.DfgVertex.isFunctionCall(vertex)
211
+ || (!unbound && (vertex.origin === 'unnamed' || vertex.origin.some(o => o !== built_in_proc_name_1.BuiltInProcName.Default)));
212
+ }
202
213
  function linkFunctionCall(graph, id, info, idMap, isRoot) {
203
214
  const readIds = new Set();
204
215
  for (const [t, e] of graph.edgesFrom(id)) {
205
- if (!node_id_1.NodeId.isBuiltIn(t) && edge_1.DfEdge.doesNotIncludeType(e, edge_1.EdgeType.Argument) && edge_1.DfEdge.includesType(e, FCallLinkReadBits)) {
216
+ if (!node_id_1.NodeId.isBuiltIn(t) && edge_1.DfEdge.doesNotIncludeType(e, edge_1.EdgeType.Argument) && edge_1.DfEdge.includesType(e, FCallLinkReadBits) && mayBeFunctionSource(graph, info, t, e)) {
206
217
  readIds.add(t);
207
218
  }
208
219
  }
@@ -259,8 +270,10 @@ function getAllFunctionCallTargets(call, graph, environment) {
259
270
  functionCallDefs = resolve_helper_1.Resolve.byNameAndType(info.name, known, refType)?.map(d => d.nodeId) ?? [];
260
271
  }
261
272
  const followBits = vertex_2.DfgVertex.hasOrigin(info, built_in_proc_name_1.BuiltInProcName.Unnamed) || functionCallDefs.length === 0 ? FCallLinkReadBits : edge_1.EdgeType.Calls;
273
+ const unbound = known !== undefined && functionCallDefs.length === 0;
262
274
  for (const [target, edge] of graph.edgesFrom(call)) {
263
- if (edge_1.DfEdge.includesType(edge, followBits) && edge_1.DfEdge.doesNotIncludeType(edge, edge_1.EdgeType.Argument) && (known !== undefined || !node_id_1.NodeId.isBuiltIn(target))) {
275
+ if (edge_1.DfEdge.includesType(edge, followBits) && edge_1.DfEdge.doesNotIncludeType(edge, edge_1.EdgeType.Argument) && (known !== undefined || !node_id_1.NodeId.isBuiltIn(target))
276
+ && mayBeFunctionSource(graph, info, target, edge, unbound)) {
264
277
  functionCallDefs.push(target);
265
278
  }
266
279
  }
@@ -277,18 +290,20 @@ function getAllFunctionCallTargets(call, graph, environment) {
277
290
  function getAllLinkedFunctionDefinitions(functionDefinitionReadIds, dataflowGraph) {
278
291
  const result = new Set();
279
292
  const builtIns = new Set();
280
- const potential = Array.from(functionDefinitionReadIds, id => [id, false]);
293
+ /* `call` is the call whose return led into the current body, so a parameter it binds holds only what it passes */
294
+ const potential = Array.from(functionDefinitionReadIds, id => [id, false, undefined]);
281
295
  const visited = new Set();
282
296
  const expanded = new Set();
283
297
  const expandedViaAccess = new Set();
298
+ const at = (id, call) => `${id}@${call ?? ''}`;
284
299
  while (potential.length !== 0) {
285
- const [cid, viaAccess] = potential.pop();
300
+ const [cid, viaAccess, call] = potential.pop();
286
301
  const done = viaAccess ? expandedViaAccess : expanded;
287
- if (done.has(cid)) {
302
+ if (done.has(at(cid, call))) {
288
303
  continue;
289
304
  }
290
- done.add(cid);
291
- visited.add(cid);
305
+ done.add(at(cid, call));
306
+ visited.add(at(cid, call));
292
307
  if (node_id_1.NodeId.isBuiltIn(cid)) {
293
308
  builtIns.add(cid);
294
309
  continue;
@@ -307,20 +322,27 @@ function getAllLinkedFunctionDefinitions(functionDefinitionReadIds, dataflowGrap
307
322
  let followTargets;
308
323
  /* a list handed on as a whole (a loop, an apply) yields its entries, an access the entry it names */
309
324
  const handedBack = !viaAccess && vertex_2.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.List) ? edge_1.EdgeType.Returns | edge_1.EdgeType.Argument : edge_1.EdgeType.Returns;
325
+ const returnedTo = vertex_2.DfgVertex.isFunctionCall(vertex) ? cid : call;
310
326
  for (const [target, e] of dataflowGraph.edgesFrom(cid)) {
311
327
  if (edge_1.DfEdge.includesType(e, handedBack)) {
312
328
  hasReturnEdge = true;
313
- if (!visited.has(target)) {
314
- potential.push([target, nextViaAccess]);
329
+ if (!visited.has(at(target, returnedTo))) {
330
+ potential.push([target, nextViaAccess, returnedTo]);
315
331
  }
316
332
  }
317
- else if (!isSkipType && !hasReturnEdge && edge_1.DfEdge.includesType(e, ValueFlowBits) && !visited.has(target)) {
318
- (followTargets ??= []).push(target);
333
+ else if (!isSkipType && !hasReturnEdge && edge_1.DfEdge.includesType(e, ValueFlowBits)) {
334
+ (followTargets ??= []).push([target, edge_1.DfEdge.includesType(e, edge_1.EdgeType.DefinedByOnCall)]);
319
335
  }
320
336
  }
321
337
  if (!hasReturnEdge && followTargets) {
322
- for (const target of followTargets) {
323
- potential.push([target, nextViaAccess]);
338
+ /* a parameter the call binds holds only what that call passes, the walk then goes on in the caller */
339
+ const passed = call === undefined ? undefined : new Set(df_helper_1.Dataflow.targetsOf(dataflowGraph, call, edge_1.EdgeType.Argument));
340
+ const bound = followTargets.some(([target, onCall]) => onCall && passed?.has(target));
341
+ for (const [target, onCall] of followTargets) {
342
+ const next = onCall ? undefined : call;
343
+ if ((!bound || !onCall || passed?.has(target)) && !visited.has(at(target, next))) {
344
+ potential.push([target, nextViaAccess, next]);
345
+ }
324
346
  }
325
347
  }
326
348
  }
@@ -28,6 +28,8 @@ export declare const AmbientStateName: {
28
28
  readonly files: "#files";
29
29
  /** written by a call writing a file we cannot name, which every call reading a file reads */
30
30
  readonly anyFile: "#file:*";
31
+ /** the working directory `setwd` changes, which every call accessing a file reads to resolve a relative path */
32
+ readonly workingDirectory: "#wd";
31
33
  /** the state of the random number generator, which `set.seed` sets and every draw advances */
32
34
  readonly rng: "#rng";
33
35
  /** the kind of generator, which `set.seed` keeps unless it is given one */
@@ -101,6 +103,10 @@ export declare const enum AmbientStateAccessType {
101
103
  ReadFiles = "read-files",
102
104
  /** writes a file, like `write.csv` */
103
105
  WriteFiles = "write-files",
106
+ /** `setwd(dir)`: changes the working directory, returning the previous one */
107
+ SetWorkingDirectory = "set-working-directory",
108
+ /** `getwd()`: reads the working directory */
109
+ GetWorkingDirectory = "get-working-directory",
104
110
  /** `textConnection(object, open)`: opened for writing, it binds the variable `object` names to what is written to it */
105
111
  OpenTextConnection = "open-text-connection",
106
112
  /** `reg.finalizer(e, f)`: registers `f` to run once `e` is released */
@@ -110,11 +116,13 @@ export declare const enum AmbientStateAccessType {
110
116
  }
111
117
  /** An {@link AmbientStateAccessType} together with what refines it for some of the types. */
112
118
  export type AmbientStateAccess = {
113
- readonly type: AmbientStateAccessType.SetOptions | AmbientStateAccessType.GetOption | AmbientStateAccessType.ReadGraphics | AmbientStateAccessType.SetPalette | AmbientStateAccessType.OpenDevice | AmbientStateAccessType.SwitchDevice | AmbientStateAccessType.DrawRng | AmbientStateAccessType.OpenTextConnection | AmbientStateAccessType.RegisterFinalizer | AmbientStateAccessType.RunFinalizers;
119
+ readonly type: AmbientStateAccessType.SetOptions | AmbientStateAccessType.GetOption | AmbientStateAccessType.ReadGraphics | AmbientStateAccessType.SetPalette | AmbientStateAccessType.OpenDevice | AmbientStateAccessType.SwitchDevice | AmbientStateAccessType.DrawRng | AmbientStateAccessType.SetWorkingDirectory | AmbientStateAccessType.GetWorkingDirectory | AmbientStateAccessType.OpenTextConnection | AmbientStateAccessType.RegisterFinalizer | AmbientStateAccessType.RunFinalizers;
114
120
  } | {
115
121
  readonly type: AmbientStateAccessType.ReadFiles | AmbientStateAccessType.WriteFiles;
116
122
  /** the signature whose {@link ArgProp.Resource} arguments name the files, absent if they do not name them exactly (like a glob) */
117
123
  readonly sig?: FnSig;
124
+ /** a device numbers the files of its pages with a `%d` in the name (`plot%03d.png`) */
125
+ readonly numbered?: boolean;
118
126
  } | {
119
127
  readonly type: AmbientStateAccessType.SetRng;
120
128
  /** the position from which on (unnamed) arguments, and every argument named other than `seed`, set the kind of generator */
@@ -42,6 +42,7 @@ const match_args_1 = require("../../../../../graph/match-args");
42
42
  const known_call_handling_1 = require("../known-call-handling");
43
43
  const built_in_proc_name_1 = require("../../../../../environments/built-in-proc-name");
44
44
  const node_value_1 = require("../../../../../eval/resolve/node-value");
45
+ const applied_arguments_1 = require("../../../../../graph/applied-arguments");
45
46
  const unknown_side_effect_1 = require("../../../../../graph/unknown-side-effect");
46
47
  const edge_1 = require("../../../../../graph/edge");
47
48
  const assert_1 = require("../../../../../../util/assert");
@@ -68,6 +69,8 @@ exports.AmbientStateName = {
68
69
  files: '#files',
69
70
  /** written by a call writing a file we cannot name, which every call reading a file reads */
70
71
  anyFile: '#file:*',
72
+ /** the working directory `setwd` changes, which every call accessing a file reads to resolve a relative path */
73
+ workingDirectory: '#wd',
71
74
  /** the state of the random number generator, which `set.seed` sets and every draw advances */
72
75
  rng: '#rng',
73
76
  /** the kind of generator, which `set.seed` keeps unless it is given one */
@@ -337,15 +340,24 @@ function applyAmbientStateAccess(res, args, rootId, data, access) {
337
340
  writes.push(exports.AmbientStateName.rng);
338
341
  break;
339
342
  case "read-files" /* AmbientStateAccessType.ReadFiles */: {
340
- const stems = fileStems(res, rootId, data, access.sig);
341
- reads.push(...stems === undefined ? [exports.AmbientStateName.files] : [...stems.map(exports.AmbientStateName.file), exports.AmbientStateName.anyFile]);
343
+ const stems = fileStems(res, rootId, data, access);
344
+ reads.push(exports.AmbientStateName.workingDirectory, ...stems === undefined ? [exports.AmbientStateName.files] : [...stems.map(exports.AmbientStateName.file), exports.AmbientStateName.anyFile]);
342
345
  break;
343
346
  }
344
347
  case "write-files" /* AmbientStateAccessType.WriteFiles */: {
345
- const stems = fileStems(res, rootId, data, access.sig);
348
+ const stems = fileStems(res, rootId, data, access);
349
+ reads.push(exports.AmbientStateName.workingDirectory);
346
350
  writes.push(...stems === undefined ? [exports.AmbientStateName.anyFile] : stems.map(exports.AmbientStateName.file), exports.AmbientStateName.files);
347
351
  break;
348
352
  }
353
+ case "set-working-directory" /* AmbientStateAccessType.SetWorkingDirectory */:
354
+ /* a relative `dir` resolves against the current one, which the call also returns */
355
+ reads.push(exports.AmbientStateName.workingDirectory);
356
+ writes.push(exports.AmbientStateName.workingDirectory);
357
+ break;
358
+ case "get-working-directory" /* AmbientStateAccessType.GetWorkingDirectory */:
359
+ reads.push(exports.AmbientStateName.workingDirectory);
360
+ break;
349
361
  case "open-text-connection" /* AmbientStateAccessType.OpenTextConnection */:
350
362
  return openTextConnection(res, args, rootId, data);
351
363
  case "register-finalizer" /* AmbientStateAccessType.RegisterFinalizer */:
@@ -398,14 +410,14 @@ function openTextConnection(res, args, rootId, data) {
398
410
  markForcing(environment);
399
411
  return withAccess({ ...res, environment }, rootId, data, [], names.map(exports.AmbientStateName.textConnection));
400
412
  }
401
- /** The stems of the files the call names, `undefined` unless every file argument is a known path to a file with an extension (`plot%03d.png` or a directory may stand for others). */
402
- function fileStems(res, rootId, data, sig) {
413
+ /** 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). */
414
+ function fileStems(res, rootId, data, { sig, numbered }) {
403
415
  const call = res.graph.getVertex(rootId);
404
416
  if (sig === undefined || !vertex_1.DfgVertex.isFunctionCall(call)) {
405
417
  return undefined;
406
418
  }
407
- const named = match_args_1.MatchArgs.findWithProps(call.args, sig, built_in_props_1.ArgProp.Resource);
408
- if (named.length === 0 || named.length < sig.filter(([n, p]) => n !== '...' && (p & built_in_props_1.ArgProp.Resource) !== 0).length) {
419
+ const named = match_args_1.MatchArgs.findWithProps((0, applied_arguments_1.appliedArguments)(res.graph, call, data.completeAst.idMap).args, sig, built_in_props_1.ArgProp.Resource);
420
+ if (named.length === 0 || named.length < sig.filter(([n, p]) => n !== '...' && (p & built_in_props_1.ArgProp.Resource) !== 0 && (p & built_in_props_1.ArgProp.Forced) !== 0).length) {
409
421
  return undefined;
410
422
  }
411
423
  const stems = [];
@@ -413,7 +425,7 @@ function fileStems(res, rootId, data, sig) {
413
425
  const paths = node_value_1.NodeValue.stringsOf(id, data);
414
426
  for (const path of paths?.length ? paths : ['']) {
415
427
  const [stem, ...extension] = path.split(/[/\\]/).at(-1)?.split('.') ?? [];
416
- if (!stem || extension.length === 0 || /[%*?[]/.test(path)) {
428
+ if (!stem || extension.length === 0 || /[*?[]/.test(path) || (numbered && path.includes('%'))) {
417
429
  return undefined;
418
430
  }
419
431
  stems.push(stem);
@@ -441,8 +453,11 @@ function applyWithUnknownArguments(res, rootId, data, access) {
441
453
  switch (access.type) {
442
454
  case "close-device" /* AmbientStateAccessType.CloseDevice */:
443
455
  return deviceAccess(res, rootId, data, access.all ? 'close-all' : 'switch');
456
+ /* the arguments handed on (`do.call(readLines, list("a.txt"))`, `lapply(files, readLines)`) may still name the files */
444
457
  case "open-device" /* AmbientStateAccessType.OpenDevice */:
445
458
  case "switch-device" /* AmbientStateAccessType.SwitchDevice */:
459
+ case "read-files" /* AmbientStateAccessType.ReadFiles */:
460
+ case "write-files" /* AmbientStateAccessType.WriteFiles */:
446
461
  return applyAmbientStateAccess(res, [], rootId, data, access);
447
462
  case "set-options" /* AmbientStateAccessType.SetOptions */:
448
463
  /* like `options(op)`: it may set anything */
@@ -466,8 +481,10 @@ const UnknownArgumentAccess = {
466
481
  ["evaluate-quoted" /* AmbientStateAccessType.EvaluateQuoted */]: Quoted,
467
482
  ["set-rng" /* AmbientStateAccessType.SetRng */]: { reads: [exports.AmbientStateName.rngKind], writes: [exports.AmbientStateName.rng, exports.AmbientStateName.rngKind] },
468
483
  ["draw-rng" /* AmbientStateAccessType.DrawRng */]: { reads: [exports.AmbientStateName.rng], writes: [exports.AmbientStateName.rng] },
469
- ["read-files" /* AmbientStateAccessType.ReadFiles */]: { reads: [exports.AmbientStateName.files], writes: [] },
470
- ["write-files" /* AmbientStateAccessType.WriteFiles */]: { reads: [], writes: [exports.AmbientStateName.anyFile, exports.AmbientStateName.files] },
484
+ ["read-files" /* AmbientStateAccessType.ReadFiles */]: { reads: [exports.AmbientStateName.workingDirectory, exports.AmbientStateName.files], writes: [] },
485
+ ["write-files" /* AmbientStateAccessType.WriteFiles */]: { reads: [exports.AmbientStateName.workingDirectory], writes: [exports.AmbientStateName.anyFile, exports.AmbientStateName.files] },
486
+ ["set-working-directory" /* AmbientStateAccessType.SetWorkingDirectory */]: { reads: [exports.AmbientStateName.workingDirectory], writes: [exports.AmbientStateName.workingDirectory] },
487
+ ["get-working-directory" /* AmbientStateAccessType.GetWorkingDirectory */]: { reads: [exports.AmbientStateName.workingDirectory], writes: [] },
471
488
  ["open-text-connection" /* AmbientStateAccessType.OpenTextConnection */]: { reads: [], writes: [] },
472
489
  ["register-finalizer" /* AmbientStateAccessType.RegisterFinalizer */]: { reads: [], writes: [exports.AmbientStateName.finalizers] },
473
490
  ["run-finalizers" /* AmbientStateAccessType.RunFinalizers */]: { reads: [exports.AmbientStateName.finalizers], writes: [] }
@@ -482,8 +499,10 @@ function unknownArgumentAccess(access) {
482
499
  function deviceAccess(res, rootId, data, kind) {
483
500
  /* only a switch reads the state; what a closed device holds reaches its file through the plots on it (see LinkToLastPlot) */
484
501
  const reads = kind === 'switch' ? [exports.AmbientStateName.graphics] : [];
502
+ /* closing writes the file of the device, which its opening names unless we do not know the device closed */
503
+ const unnamedFile = kind === 'open' ? [] : [exports.AmbientStateName.anyFile, exports.AmbientStateName.files];
485
504
  if (data.environment.level > 0) {
486
- return withAccess(res, rootId, data, reads, [exports.AmbientStateName.graphics]);
505
+ return withAccess(res, rootId, data, reads, [exports.AmbientStateName.graphics, ...unnamedFile]);
487
506
  }
488
507
  const cds = data.cds ? [...data.cds] : undefined;
489
508
  const lookup = (name) => resolve_helper_1.Resolve.byName(name, res.environment) ?? [];
@@ -525,7 +544,8 @@ function deviceAccess(res, rootId, data, kind) {
525
544
  environment = setAmbient(environment, exports.AmbientStateName.otherDevicesOpenedBy, opener, true);
526
545
  break;
527
546
  }
528
- return withAccess({ ...res, environment }, rootId, data, reads, []);
547
+ const known = kind === 'close' ? opener.length > 0 : kind === 'close-all' && opener.length + otherOpeners.length > 0;
548
+ return withAccess({ ...res, environment }, rootId, data, reads, kind === 'open' || known ? [] : unnamedFile);
529
549
  }
530
550
  /** A call to `fn` made on our behalf (`do.call(fn, args)`, `sapply(x, fn)`): it accesses the state as `fn` does, or reads all of it if `fn` is opaque. */
531
551
  function applyAmbientStateOfCallee(res, callId, fn, data) {
@@ -135,7 +135,6 @@ function processApply(name, args, rootId, data, config) {
135
135
  }
136
136
  }
137
137
  else {
138
- information = (0, built_in_ambient_state_1.applyAmbientStateOfCallee)(information, functionId, functionName, data);
139
138
  /* a callee binding names (`do.call("assign", ...)`) does so with arguments we cannot see here; loading a package is handled on its own */
140
139
  if (resolve_helper_1.Resolve.byNameAndType(functionName, data.environment, identifier_1.ReferenceType.Function)?.some(t => t.type === identifier_1.ReferenceType.BuiltInFunction
141
140
  && 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))) {
@@ -151,6 +150,14 @@ function processApply(name, args, rootId, data, config) {
151
150
  cds: data.cds,
152
151
  origin: [built_in_proc_name_1.BuiltInProcName.Function]
153
152
  });
153
+ /* once the call has its arguments, which may name the files it accesses */
154
+ information = (0, built_in_ambient_state_1.applyAmbientStateOfCallee)(information, functionId, functionName, data);
155
+ /* `do.call(new.env, list())` creates an environment just like `new.env()` does */
156
+ const call = information.graph.getVertex(rootId);
157
+ if (vertex_1.DfgVertex.isFunctionCall(call) && resolve_helper_1.Resolve.byNameAndType(functionName, data.environment, identifier_1.ReferenceType.Function)
158
+ ?.some(t => t.type === identifier_1.ReferenceType.BuiltInFunction && t.processorName === built_in_proc_name_1.BuiltInProcName.NewEnv)) {
159
+ call.origin = [...Array.isArray(call.origin) ? call.origin : [], built_in_proc_name_1.BuiltInProcName.NewEnv];
160
+ }
154
161
  }
155
162
  for (const [i, arg] of processedArguments.entries()) {
156
163
  if (arg && !(anonymous && i === index)) {
@@ -486,12 +486,15 @@ function processAssignmentToSymbol(config) {
486
486
  envId = copied === undefined ? undefined : copied.envId ?? copied.nodeId;
487
487
  }
488
488
  else {
489
- const entryVertex = sourceArg.graph.getVertex(sourceArg.entryPoint);
489
+ /* `(list(...))` and `{ mk() }` hand on the value of what they hold */
490
+ const entry = valueEntry ?? sourceArg.entryPoint;
491
+ const value = data.completeAst.idMap.get(entry) ?? source;
492
+ const entryVertex = sourceArg.graph.getVertex(entry);
490
493
  if (vertex_1.DfgVertex.hasOrigin(entryVertex, built_in_proc_name_1.BuiltInProcName.List)) {
491
- envState = (0, built_in_list_1.resolveListToEnvState)(source, data);
494
+ envState = (0, built_in_list_1.resolveListToEnvState)(value, data);
492
495
  }
493
496
  else if (vertex_1.DfgVertex.hasOrigin(entryVertex, built_in_proc_name_1.BuiltInProcName.ClassGenerator)) {
494
- returnsEnvState = (0, built_in_class_generator_1.resolveClassMethodsToEnvState)(source, data);
497
+ returnsEnvState = (0, built_in_class_generator_1.resolveClassMethodsToEnvState)(value, data);
495
498
  }
496
499
  else if (vertex_1.DfgVertex.isFunctionDefinition(entryVertex) && entryVertex.returnEnvState !== undefined) {
497
500
  returnsEnvState = entryVertex.returnEnvState;
@@ -499,7 +502,7 @@ function processAssignmentToSymbol(config) {
499
502
  else if (vertex_1.DfgVertex.isFunctionCall(entryVertex) && entryVertex.name) {
500
503
  envState = (0, built_in_envir_utils_1.findReturnsEnvState)(resolve_helper_1.Resolve.byNameAndType(entryVertex.name, data.environment, identifier_1.ReferenceType.Function));
501
504
  }
502
- envState ??= (0, built_in_class_generator_1.resolveConstructorInstanceEnvState)(source, data);
505
+ envState ??= (0, built_in_class_generator_1.resolveConstructorInstanceEnvState)(value, data);
503
506
  }
504
507
  }
505
508
  const forces = quoteSource ? (0, built_in_ambient_state_1.ambientWritesBetween)(sourceArg.environment, data.environment) : [];
@@ -293,7 +293,8 @@ function processExpressionList(name, args, rootId, data) {
293
293
  const processedExpressions = [];
294
294
  let defaultReturnExpr;
295
295
  /* R prints what the top level of the analyzed script leaves visible, but not what a sourced file does */
296
- const autoPrint = data.referenceChain.length <= 1 && data.environment.level === 0 && data.completeAst.ast.files.some(f => f.root.info.id === rootId);
296
+ const fileRoot = data.completeAst.ast.files.some(f => f.root.info.id === rootId);
297
+ const autoPrint = data.referenceChain.length <= 1 && data.environment.level === 0 && fileRoot;
297
298
  let initialState;
298
299
  const hooks = [];
299
300
  for (const arg of args) {
@@ -303,7 +304,16 @@ function processExpressionList(name, args, rootId, data) {
303
304
  continue;
304
305
  }
305
306
  data.environment = environment;
307
+ /* a statement runs first where it is first analyzed, a file sourced again later does not move it */
308
+ const order = fileRoot && !data.statementOrder?.has(expression.info.id) ? data.statementOrder : undefined;
309
+ const span = order === undefined ? undefined : [order.size, Infinity];
310
+ if (span !== undefined) {
311
+ order?.set(expression.info.id, span);
312
+ }
306
313
  let processed = (0, processor_1.processDataflowFor)(expression, data);
314
+ if (span !== undefined) {
315
+ span[1] = order?.size ?? Infinity;
316
+ }
307
317
  const printed = autoPrint && (0, built_in_ambient_state_1.autoPrints)(expression, processed, data);
308
318
  if (printed) {
309
319
  processed = (0, built_in_ambient_state_1.readsOfAutoPrint)(processed, expression, data);