@eagleoutice/flowr 2.16.3 → 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 (148) hide show
  1. package/README.md +14 -14
  2. package/cli/repl/core.js +13 -2
  3. package/cli/repl/parser/slice-query-parser.d.ts +21 -5
  4. package/cli/repl/parser/slice-query-parser.js +33 -13
  5. package/core/steps/all/static-slicing/10-reconstruct.d.ts +2 -2
  6. package/dataflow/environments/built-in.d.ts +2 -0
  7. package/dataflow/environments/built-in.js +10 -2
  8. package/dataflow/environments/data-masking-functions.js +2 -1
  9. package/dataflow/environments/default-builtin-config.d.ts +31 -5
  10. package/dataflow/environments/default-builtin-config.js +12 -15
  11. package/dataflow/environments/query-fn-props.js +2 -1
  12. package/dataflow/eval/resolve/alias-tracking.js +5 -2
  13. package/dataflow/eval/resolve/node-value.js +1 -1
  14. package/dataflow/eval/resolve/resolve-argument.js +2 -0
  15. package/dataflow/eval/resolve/resolve-strings.d.ts +10 -0
  16. package/dataflow/eval/resolve/resolve-strings.js +79 -12
  17. package/dataflow/eval/resolve/resolve.js +2 -6
  18. package/dataflow/extractor.js +11 -4
  19. package/dataflow/graph/applied-arguments.d.ts +5 -0
  20. package/dataflow/graph/applied-arguments.js +17 -0
  21. package/dataflow/graph/df-helper.js +2 -2
  22. package/dataflow/graph/graph.d.ts +5 -0
  23. package/dataflow/graph/graph.js +5 -0
  24. package/dataflow/info.js +8 -1
  25. package/dataflow/internal/linker.js +35 -13
  26. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.d.ts +9 -1
  27. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +32 -12
  28. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +8 -1
  29. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +7 -4
  30. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +11 -1
  31. package/dataflow/internal/process/functions/call/named-call-handling.js +4 -2
  32. package/dataflow/internal/process/functions/call/quoted.js +3 -3
  33. package/dataflow/internal/program-order.js +7 -1
  34. package/dataflow/processor.d.ts +2 -0
  35. package/documentation/doc-util/doc-query.d.ts +1 -1
  36. package/documentation/doc-util/doc-query.js +3 -1
  37. package/documentation/doc-util/doc-timings.js +3 -2
  38. package/documentation/doc-util/doc-types.js +4 -0
  39. package/documentation/wiki-create-linting-rules.js +1 -1
  40. package/documentation/wiki-linter.d.ts +14 -0
  41. package/documentation/wiki-linter.js +341 -126
  42. package/linter/linter-executor.js +7 -0
  43. package/linter/linter-rules.d.ts +47 -47
  44. package/linter/rules/absolute-path.d.ts +1 -1
  45. package/linter/rules/absolute-path.js +6 -4
  46. package/linter/rules/cmd-check/call-arguments.d.ts +1 -1
  47. package/linter/rules/cmd-check/call-arguments.js +10 -5
  48. package/linter/rules/cmd-check/compiled-code.d.ts +1 -1
  49. package/linter/rules/cmd-check/compiled-code.js +1 -1
  50. package/linter/rules/cmd-check/conformance.d.ts +5 -1
  51. package/linter/rules/cmd-check/conformance.js +64 -64
  52. package/linter/rules/cmd-check/description-metadata.d.ts +1 -1
  53. package/linter/rules/cmd-check/description-metadata.js +1 -1
  54. package/linter/rules/cmd-check/documentation-mismatch.d.ts +6 -0
  55. package/linter/rules/cmd-check/foreign-function-calls.d.ts +1 -1
  56. package/linter/rules/cmd-check/foreign-function-calls.js +1 -1
  57. package/linter/rules/cmd-check/namespace-tampering.d.ts +1 -1
  58. package/linter/rules/cmd-check/namespace-tampering.js +1 -1
  59. package/linter/rules/cmd-check/non-ascii-code.d.ts +1 -1
  60. package/linter/rules/cmd-check/non-ascii-code.js +1 -1
  61. package/linter/rules/cmd-check/package-data.d.ts +3 -1
  62. package/linter/rules/cmd-check/package-data.js +1 -1
  63. package/linter/rules/cmd-check/package-hooks.d.ts +2 -2
  64. package/linter/rules/cmd-check/package-hooks.js +13 -5
  65. package/linter/rules/cmd-check/package-metafiles.d.ts +1 -1
  66. package/linter/rules/cmd-check/package-metafiles.js +1 -1
  67. package/linter/rules/cmd-check/package-structure.d.ts +1 -1
  68. package/linter/rules/cmd-check/package-structure.js +1 -1
  69. package/linter/rules/cmd-check/rd-files.d.ts +17 -1
  70. package/linter/rules/cmd-check/rd-files.js +1 -1
  71. package/linter/rules/cmd-check/true-false-abbreviation.d.ts +1 -1
  72. package/linter/rules/cmd-check/true-false-abbreviation.js +1 -1
  73. package/linter/rules/dataframe-access-validation.d.ts +1 -1
  74. package/linter/rules/dataframe-access-validation.js +1 -1
  75. package/linter/rules/dead-code.d.ts +4 -4
  76. package/linter/rules/dead-code.js +19 -4
  77. package/linter/rules/deprecated-functions.d.ts +1 -1
  78. package/linter/rules/deprecated-functions.js +1 -1
  79. package/linter/rules/file-path-validity.d.ts +6 -2
  80. package/linter/rules/file-path-validity.js +7 -3
  81. package/linter/rules/namespace-access.d.ts +3 -3
  82. package/linter/rules/namespace-access.js +12 -3
  83. package/linter/rules/naming-convention.d.ts +1 -1
  84. package/linter/rules/naming-convention.js +1 -1
  85. package/linter/rules/network-functions.d.ts +1 -1
  86. package/linter/rules/network-functions.js +1 -1
  87. package/linter/rules/no-leaked-credentials.d.ts +1 -1
  88. package/linter/rules/no-leaked-credentials.js +1 -1
  89. package/linter/rules/problematic-inputs.d.ts +2 -2
  90. package/linter/rules/problematic-inputs.js +4 -4
  91. package/linter/rules/roxygen-arguments.d.ts +2 -2
  92. package/linter/rules/roxygen-arguments.js +2 -2
  93. package/linter/rules/seeded-randomness.d.ts +2 -2
  94. package/linter/rules/seeded-randomness.js +2 -2
  95. package/linter/rules/software-has-license.d.ts +2 -2
  96. package/linter/rules/software-has-license.js +2 -2
  97. package/linter/rules/software-has-tests.d.ts +2 -2
  98. package/linter/rules/software-has-tests.js +2 -2
  99. package/linter/rules/stop-with-call-arg.d.ts +3 -3
  100. package/linter/rules/stop-with-call-arg.js +22 -5
  101. package/linter/rules/syntactically-valid.d.ts +1 -1
  102. package/linter/rules/syntactically-valid.js +1 -1
  103. package/linter/rules/unclosed-connection.d.ts +2 -2
  104. package/linter/rules/unclosed-connection.js +2 -2
  105. package/linter/rules/undefined-symbol.d.ts +1 -1
  106. package/linter/rules/undefined-symbol.js +27 -4
  107. package/linter/rules/unescaped-arguments.d.ts +1 -1
  108. package/linter/rules/unescaped-arguments.js +1 -1
  109. package/linter/rules/unused-definition.d.ts +1 -1
  110. package/linter/rules/unused-definition.js +21 -2
  111. package/linter/rules/unused-import.d.ts +1 -1
  112. package/linter/rules/unused-import.js +1 -1
  113. package/linter/rules/useless-loop.d.ts +1 -1
  114. package/linter/rules/useless-loop.js +1 -1
  115. package/package.json +1 -1
  116. package/project/context/flowr-analyzer-environment-context.d.ts +1 -1
  117. package/project/context/flowr-analyzer-environment-context.js +2 -1
  118. package/project/context/flowr-analyzer-files-context.js +12 -11
  119. package/project/dependency-version-space.js +4 -6
  120. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.d.ts +2 -0
  121. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +9 -8
  122. package/project/plugins/file-plugins/flowr-analyzer-test-file-plugin.js +1 -1
  123. package/project/plugins/file-plugins/flowr-analyzer-vignette-file-plugin.js +1 -1
  124. package/queries/catalog/dependencies-query/data-flow.d.ts +2 -0
  125. package/queries/catalog/dependencies-query/data-flow.js +6 -0
  126. package/queries/catalog/dependencies-query/dependencies-query-executor.js +31 -0
  127. package/queries/catalog/dependencies-query/dependencies-query-format.d.ts +5 -0
  128. package/queries/catalog/dependencies-query/implicit-echo.js +29 -30
  129. package/queries/catalog/dependencies-query/plot-objects.js +6 -2
  130. package/queries/catalog/dice-query/dice-query-format.d.ts +1 -1
  131. package/queries/catalog/dice-query/dice-query-format.js +1 -1
  132. package/queries/catalog/slice-query-options.d.ts +3 -3
  133. package/queries/catalog/slice-query-options.js +1 -1
  134. package/queries/catalog/static-slice-query/static-slice-query-executor.js +12 -1
  135. package/queries/catalog/static-slice-query/static-slice-query-format.d.ts +7 -1
  136. package/queries/catalog/static-slice-query/static-slice-query-format.js +4 -2
  137. package/queries/query.d.ts +2 -2
  138. package/r-bridge/lang-4.x/tree-sitter/tree-sitter-normalize.js +19 -56
  139. package/reconstruct/inline/source-inline-map.d.ts +1 -1
  140. package/reconstruct/inline/source-inline-map.js +5 -3
  141. package/reconstruct/reconstruct.d.ts +8 -1
  142. package/reconstruct/reconstruct.js +12 -3
  143. package/slicing/static/removal-slice.d.ts +19 -0
  144. package/slicing/static/removal-slice.js +165 -0
  145. package/slicing/static/static-slicer.js +10 -5
  146. package/util/text/playground-link.d.ts +24 -1
  147. package/util/text/playground-link.js +16 -1
  148. package/util/version.js +2 -2
@@ -365,6 +365,7 @@ function trackAliasesInGraph(id, graph, ctx, idMap, blocked) {
365
365
  const value = resolveIdToValue(sequence.info.id, { graph, idMap, ctx, blocked });
366
366
  return (0, r_value_1.isTop)(value) ? r_value_1.Top : (0, set_constants_1.setOf)(iteratedElements(value));
367
367
  }
368
+ const start = id;
368
369
  const queue = new visiting_queue_1.VisitingQueue(10);
369
370
  const clean = ctx.env.makeCleanEnv();
370
371
  const cleanFingerprint = ctx.env.getCleanEnvFingerprint();
@@ -380,7 +381,9 @@ function trackAliasesInGraph(id, graph, ctx, idMap, blocked) {
380
381
  continue;
381
382
  }
382
383
  const cds = vertex.cds;
383
- for (const cd of cds ?? []) {
384
+ /* a read in a loop sees the same value every round unless a definition in the loop reaches it, which the walk meets */
385
+ const loopedRead = id === start && vertex_1.DfgVertex.isUse(vertex);
386
+ for (const cd of loopedRead ? [] : cds ?? []) {
384
387
  const target = graph.idMap?.get(cd.id);
385
388
  if (target === undefined) {
386
389
  continue;
@@ -390,7 +393,7 @@ function trackAliasesInGraph(id, graph, ctx, idMap, blocked) {
390
393
  break;
391
394
  }
392
395
  }
393
- if (!forceTop && (cds?.length === 0 && isNestedInLoop(idMap.get(id), idMap))) {
396
+ if (!forceTop && !loopedRead && (cds?.length === 0 && isNestedInLoop(idMap.get(id), idMap))) {
394
397
  forceTop = true;
395
398
  }
396
399
  if (forceTop) {
@@ -64,7 +64,7 @@ exports.NodeValue = {
64
64
  sole: general_1.soleValue,
65
65
  /** The one value the node resolves to, `undefined` unless it is exactly one, optionally of the given kind. */
66
66
  soleOf(id, against, type, overrides) {
67
- return (0, general_1.soleValue)((0, general_1.valueSetGuard)(resolve_helper_1.Resolve.toValue(id, infoOf(against, overrides))), type);
67
+ return exports.NodeValue.sole((0, general_1.valueSetGuard)(resolve_helper_1.Resolve.toValue(id, infoOf(against, overrides))), type);
68
68
  },
69
69
  };
70
70
  //# sourceMappingURL=node-value.js.map
@@ -21,6 +21,7 @@ const string_constants_1 = require("../values/string/string-constants");
21
21
  const resolve_helper_1 = require("../../environments/resolve-helper");
22
22
  const r_argument_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-argument");
23
23
  const r_symbol_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
24
+ const applied_arguments_1 = require("../../graph/applied-arguments");
24
25
  /**
25
26
  * The index of the argument of `vertex` that binds the formal `argumentName`, R's matching when the formals are known and the `argumentIndex`-th unnamed argument otherwise.
26
27
  * Pass the `formals` of the call when they are known already, which saves looking them up again.
@@ -49,6 +50,7 @@ function boundArgumentIndex(graph, vertex, argumentIndex, argumentName, ctx, for
49
50
  * Pass the `formals` of the call when they are known already, see {@link boundArgumentIndex}.
50
51
  */
51
52
  function getArgumentStringValue(variableResolve, graph, vertex, argumentIndex, argumentName, resolveValue, ctx, formals) {
53
+ vertex = (0, applied_arguments_1.appliedArguments)(graph, vertex);
52
54
  if (argumentName && argumentIndex !== 'unnamed') {
53
55
  argumentIndex = boundArgumentIndex(graph, vertex, argumentIndex, argumentName, ctx, formals);
54
56
  }
@@ -61,6 +61,11 @@ export declare const StringFns: {
61
61
  };
62
62
  readonly fold: (parts: string[], fsep: string) => string;
63
63
  };
64
+ readonly sprintf: {
65
+ readonly pkg: PkgName.Base;
66
+ readonly params: readonly ["fmt", "..."];
67
+ readonly fold: (fmt: string, parts?: string[]) => string | undefined;
68
+ };
64
69
  readonly here: {
65
70
  readonly pkg: PkgName.Here;
66
71
  readonly params: readonly ["..."];
@@ -148,6 +153,11 @@ export declare const StringFold: {
148
153
  };
149
154
  readonly fold: (parts: string[], fsep: string) => string;
150
155
  };
156
+ readonly sprintf: {
157
+ readonly pkg: PkgName.Base;
158
+ readonly params: readonly ["fmt", "..."];
159
+ readonly fold: (fmt: string, parts?: string[]) => string | undefined;
160
+ };
151
161
  readonly here: {
152
162
  readonly pkg: PkgName.Here;
153
163
  readonly params: readonly ["..."];
@@ -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`.
@@ -30,16 +30,12 @@ const r_expression_list_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/
30
30
  */
31
31
  function evalHandlerOf(name, environment, ctx) {
32
32
  /* without an environment the search path is unknown, so what a package states about the name has its say */
33
- const defs = environment ? resolve_helper_1.Resolve.byNameAndType(name, environment, identifier_1.ReferenceType.BuiltInFunction) : builtInDefinitionsOf(name, ctx);
33
+ const defs = environment ? resolve_helper_1.Resolve.byNameAndType(name, environment, identifier_1.ReferenceType.BuiltInFunction) : ctx.env.builtInDefinitionsOf(name);
34
34
  const def = defs?.length === 1 ? defs[0] : undefined;
35
35
  return def?.type === identifier_1.ReferenceType.BuiltInFunction ? def.evalHandler : undefined;
36
36
  }
37
- function builtInDefinitionsOf(name, ctx) {
38
- return ctx.env.builtInEnvironment.memory.get(identifier_1.Identifier.getName(name))
39
- ?? ctx.env.statedDefinitionsOf(name);
40
- }
41
37
  function foldsThroughBuiltIn(name, ctx) {
42
- return builtInDefinitionsOf(name, ctx)?.some(d => d.type === identifier_1.ReferenceType.BuiltInFunction && d.evalHandler !== undefined) ?? false;
38
+ return ctx.env.builtInDefinitionsOf(name).some(d => d.type === identifier_1.ReferenceType.BuiltInFunction && d.evalHandler !== undefined);
43
39
  }
44
40
  /** the node types that may fold through a built-in: calls, operators, and the `(`/`{` groupings */
45
41
  const EvalNodeTypes = [type_1.RType.FunctionCall, type_1.RType.BinaryOp, type_1.RType.UnaryOp, type_1.RType.ExpressionList];
@@ -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 */