@eagleoutice/flowr 2.14.2 → 2.14.4

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 (58) hide show
  1. package/README.md +30 -42
  2. package/abstract-interpretation/absint-visitor.d.ts +45 -4
  3. package/abstract-interpretation/absint-visitor.js +252 -53
  4. package/config.d.ts +15 -8
  5. package/config.js +4 -1
  6. package/control-flow/semantic-cfg-guided-visitor.d.ts +7 -7
  7. package/control-flow/semantic-cfg-guided-visitor.js +23 -0
  8. package/dataflow/environments/default-builtin-config.d.ts +4 -13
  9. package/dataflow/environments/default-builtin-config.js +59 -23
  10. package/dataflow/environments/group-generics.d.ts +27 -0
  11. package/dataflow/environments/group-generics.js +39 -0
  12. package/dataflow/eval/resolve/alias-tracking.d.ts +1 -1
  13. package/dataflow/eval/resolve/alias-tracking.js +1 -1
  14. package/dataflow/info.d.ts +1 -6
  15. package/dataflow/info.js +0 -17
  16. package/dataflow/internal/control-flow.d.ts +14 -2
  17. package/dataflow/internal/control-flow.js +24 -0
  18. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +10 -1
  19. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.js +1 -1
  20. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.js +11 -10
  21. package/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.js +1 -2
  22. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +1 -1
  23. package/dataflow/internal/process/functions/call/built-in/built-in-quote.d.ts +1 -1
  24. package/dataflow/internal/process/functions/call/built-in/built-in-quote.js +9 -0
  25. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.js +1 -1
  26. package/dataflow/internal/process/functions/call/built-in/built-in-try-catch.js +7 -2
  27. package/dataflow/internal/process/functions/call/built-in/built-in-while-loop.js +1 -1
  28. package/dataflow/internal/process/functions/call/known-call-handling.js +21 -17
  29. package/documentation/doc-readme.js +0 -12
  30. package/documentation/wiki-absint.js +7 -2
  31. package/documentation/wiki-interface.js +1 -0
  32. package/documentation/wiki-signature-database.js +6 -1
  33. package/linter/rules/deprecated-functions.js +4 -2
  34. package/linter/rules/unused-definition.js +3 -3
  35. package/package.json +1 -1
  36. package/project/dependency-version-space.d.ts +1 -0
  37. package/project/dependency-version-space.js +1 -1
  38. package/project/flowr-analyzer-builder.d.ts +4 -4
  39. package/project/sigdb/reader.d.ts +6 -0
  40. package/project/sigdb/reader.js +2 -2
  41. package/project/sigdb/schema.d.ts +13 -1
  42. package/project/sigdb/schema.js +3 -1
  43. package/project/sigdb/signature-db.d.ts +4 -0
  44. package/project/sigdb/signature-db.js +8 -1
  45. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.js +1 -1
  46. package/queries/catalog/signature-query/signature-query-executor.d.ts +7 -2
  47. package/queries/catalog/signature-query/signature-query-executor.js +24 -9
  48. package/queries/catalog/signature-query/signature-query-format.d.ts +14 -3
  49. package/queries/catalog/signature-query/signature-query-render.js +6 -0
  50. package/r-bridge/lang-4.x/ast/model/nodes/r-parameter.d.ts +7 -0
  51. package/r-bridge/lang-4.x/ast/model/nodes/r-parameter.js +7 -0
  52. package/r-bridge/lang-4.x/ast/model/processing/node-id.d.ts +5 -1
  53. package/r-bridge/lang-4.x/ast/model/processing/node-id.js +0 -5
  54. package/search/search-executor/search-enrichers.d.ts +4 -0
  55. package/search/search-executor/search-enrichers.js +4 -4
  56. package/util/objects.d.ts +15 -4
  57. package/util/text/name-rank.js +8 -2
  58. package/util/version.js +1 -1
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AbstractInterpretationVisitor = void 0;
4
4
  const control_flow_graph_1 = require("../control-flow/control-flow-graph");
5
+ const simple_visitor_1 = require("../control-flow/simple-visitor");
5
6
  const semantic_cfg_guided_visitor_1 = require("../control-flow/semantic-cfg-guided-visitor");
6
7
  const built_in_proc_name_1 = require("../dataflow/environments/built-in-proc-name");
7
8
  const df_helper_1 = require("../dataflow/graph/df-helper");
@@ -18,10 +19,16 @@ const r_binary_op_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-binary-op"
18
19
  const r_expression_list_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-expression-list");
19
20
  const r_if_then_else_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-if-then-else");
20
21
  const r_pipe_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-pipe");
22
+ const r_parameter_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-parameter");
21
23
  const r_symbol_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
22
24
  function stepFrom(graph, node) {
23
25
  return { node, successors: [...graph.successors(node)], at: 0 };
24
26
  }
27
+ /** Whether two rounds of a fixpoint bound the same values, `undefined` standing for nothing known yet. */
28
+ function sameValues(a, b) {
29
+ return b !== undefined && a.length === b.length
30
+ && a.every((value, at) => value === undefined ? b[at] === undefined : b[at] !== undefined && value.equals(b[at]));
31
+ }
25
32
  /**
26
33
  * A control flow graph visitor to perform abstract interpretation.
27
34
  *
@@ -53,14 +60,33 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
53
60
  * @see {@link AbstractInterpretationVisitor#isWideningPoint|isWideningPoint()}
54
61
  */
55
62
  wideningPoints;
63
+ /**
64
+ * What leads to a vertex, without the call a body was entered from.
65
+ * {@link AbstractInterpretationVisitor#shouldSkipVertex|shouldSkipVertex()} is asked once per vertex, so
66
+ * an override of it has to say the same thing every time.
67
+ */
68
+ predecessorsOf = new Map();
69
+ /** What the control flow may reach from a vertex, asked only by a read with several definitions. */
70
+ reachableFrom = new Map();
71
+ /**
72
+ * The state each vertex was left in when it was last visited, so a re-visit can tell whether anything moved.
73
+ * The trace cannot say that: entering a call seeds it before the parameters and the call are visited.
74
+ */
75
+ lastState = new Map();
56
76
  /**
57
77
  * A set of nodes representing variable definitions that have already been visited but whose assignment has not yet been processed.
58
78
  */
59
79
  unassigned = new Set();
60
80
  /** The call a function body is currently being interpreted for, mapping the body's entry to it. */
61
81
  enteredFrom = new Map();
62
- /** The function definitions currently being interpreted, which is what stops a recursive call from running forever. */
82
+ /** The function definitions currently being interpreted, which is what makes a call back into one recursive. */
63
83
  running = new Set();
84
+ /** The definitions that turned out to call themselves, which are the ones run more than once. */
85
+ recursive = new Set();
86
+ /** What a definition being interpreted was last seen to leave behind, which is what its own calls are worth. */
87
+ returns = new Map();
88
+ /** The calls that lead back into a definition still being interpreted, and the definition they reach. */
89
+ recursiveCalls = new Map();
64
90
  constructor(config, stateDomain) {
65
91
  super({ ...config, defaultVisitingOrder: 'forward' });
66
92
  this.currentState = stateDomain.top();
@@ -81,7 +107,12 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
81
107
  else if (node === undefined) {
82
108
  return;
83
109
  }
84
- else if (state?.has(node.info.id)) {
110
+ const reached = this.recursiveCalls.get(node.info.id);
111
+ if (reached !== undefined) {
112
+ /* it is worth what the definition it reaches was last seen to leave behind, nothing in round one */
113
+ return this.returns.get(reached) ?? this.currentState.domain.bottom();
114
+ }
115
+ if (state?.has(node.info.id)) {
85
116
  return state.get(node.info.id);
86
117
  }
87
118
  const vertex = this.getDataflowGraph(node.info.id);
@@ -100,6 +131,12 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
100
131
  else if (r_expression_list_1.RExpressionList.is(node) && node.children.length > 0) {
101
132
  return this.getAbstractValue(node.children.at(-1), state);
102
133
  }
134
+ else if (origins.includes(built_in_proc_name_1.BuiltInProcName.Return)) {
135
+ /* leaving with `return(x)` is worth what `x` is worth, which is what a function that does it exits with */
136
+ if (call?.args.length === 1 && call.args[0] !== r_function_call_1.EmptyArgument) {
137
+ return this.getAbstractValue(call.args[0].nodeId, state);
138
+ }
139
+ }
103
140
  else if (origins.includes(built_in_proc_name_1.BuiltInProcName.Pipe)) {
104
141
  if (r_pipe_1.RPipe.is(node) || r_binary_op_1.RBinaryOp.is(node)) {
105
142
  return this.getAbstractValue(node.rhs, state);
@@ -150,17 +187,21 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
150
187
  (0, assert_1.guard)(this.trace.size === 0, 'Abstract interpretation visitor has already been started');
151
188
  super.start();
152
189
  this.unassigned.clear();
190
+ this.lastState.clear();
153
191
  }
154
192
  startVisitor(start) {
155
193
  this.stack = Array.from(start);
194
+ const queued = new Set(this.stack);
156
195
  while (this.stack.length > 0) {
157
196
  const current = this.stack.pop();
197
+ queued.delete(current);
158
198
  if (!this.visitNode(current)) {
159
199
  continue;
160
200
  }
161
201
  const successors = [...this.config.controlFlow.graph.successors(current)].reverse();
162
202
  for (const next of successors) {
163
- if (!this.stack.includes(next)) { // prevent double entries in working list
203
+ if (!queued.has(next)) { // prevent double entries in working list
204
+ queued.add(next);
164
205
  this.stack.push(next);
165
206
  }
166
207
  }
@@ -176,31 +217,28 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
176
217
  const predecessors = this.getPredecessors(nodeId);
177
218
  const predecessorStates = predecessors.map(pred => this.getPredecessorState(pred)).filter(assert_1.isNotUndefined);
178
219
  this.currentState = abstract_domain_1.AbstractDomain.joinAll(predecessorStates, this.currentState.top());
179
- // differentiate between widening points and other vertices
180
- if (this.isWideningPoint(nodeId)) {
181
- const oldState = this.trace.get(nodeId);
182
- if (oldState !== undefined && this.shouldWiden(vertex)) {
183
- this.currentState = oldState.widen(this.currentState);
184
- }
185
- this.trace.set(nodeId, this.currentState);
186
- const visitedCount = this.visited.get(nodeId) ?? 0;
187
- this.visited.set(nodeId, visitedCount + 1);
188
- // continue visiting after widening point if visited for the first time or the state changed
189
- return visitedCount === 0 || !oldState?.equals(this.currentState);
220
+ const oldState = this.lastState.get(nodeId);
221
+ /*
222
+ * A widening point is a node of the program like any other: the head of a `while` is its condition, of a
223
+ * `repeat` its first statement. The iteration is bounded here, the node still says what it says.
224
+ */
225
+ if (oldState !== undefined && this.isWideningPoint(nodeId) && this.shouldWiden(vertex)) {
226
+ this.currentState = oldState.widen(this.currentState);
190
227
  }
191
- else {
192
- this.onVisitNode(vertexId);
193
- // discard the inferred abstract state when encountering unsupported function calls
194
- if (this.isUnsupportedFunctionCall(nodeId)) {
195
- this.currentState = this.currentState.top();
196
- }
197
- this.trace.set(nodeId, this.currentState);
198
- const predecessorVisits = predecessors.map(pred => this.visited.get(pred.id) ?? 0);
199
- const visitedCount = this.visited.get(nodeId) ?? 0;
200
- this.visited.set(nodeId, visitedCount + 1);
201
- // continue visiting if vertex is not a join vertex or number of visits of predecessors is the same
202
- return predecessors.length <= 1 || this.stack.length === 0 || predecessorVisits.every(visits => visits === predecessorVisits[0]);
228
+ this.onVisitNode(vertexId);
229
+ // discard the inferred abstract state when encountering unsupported function calls
230
+ if (this.isUnsupportedFunctionCall(nodeId)) {
231
+ this.currentState = this.currentState.top();
203
232
  }
233
+ this.trace.set(nodeId, this.currentState);
234
+ this.lastState.set(nodeId, this.currentState);
235
+ const visitedCount = this.visited.get(nodeId) ?? 0;
236
+ this.visited.set(nodeId, visitedCount + 1);
237
+ /*
238
+ * Carry on wherever the vertex is new or its state moved. Waiting for the branches of a join to arrive
239
+ * in step instead drops the rest of the program whenever they do not, three arms in a loop say.
240
+ */
241
+ return visitedCount === 0 || !oldState?.equals(this.currentState);
204
242
  }
205
243
  onDispatchFunctionCallOrigin(call, origin) {
206
244
  if (origin === built_in_proc_name_1.BuiltInProcName.Replacement) {
@@ -235,6 +273,23 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
235
273
  if (!this.trace.has(vertex.id)) {
236
274
  this.unassigned.add(vertex.id);
237
275
  }
276
+ /*
277
+ * `bindParameters` hands the arguments over before the function is entered, so a parameter still without
278
+ * a value is one the call passed nothing for and is worth the default it names. That default runs before
279
+ * the body, so standing on the parameter is the moment to read it.
280
+ */
281
+ if (this.currentState.has(vertex.id)) {
282
+ return;
283
+ }
284
+ const declaration = this.getNormalizedAst(this.getNormalizedAst(vertex.id)?.info.parent);
285
+ if (!r_parameter_1.RParameter.isWithDefault(declaration)) {
286
+ return;
287
+ }
288
+ const value = this.getAbstractValue(declaration.defaultValue, this.currentState);
289
+ if (value !== undefined) {
290
+ this.currentState.set(vertex.id, value);
291
+ this.unassigned.delete(vertex.id);
292
+ }
238
293
  }
239
294
  onAssignmentCall({ target, source }) {
240
295
  if (target === undefined || source === undefined) {
@@ -270,6 +325,17 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
270
325
  * Skipped vertices hold no state of their own, so what led into them is reported instead.
271
326
  */
272
327
  getPredecessors(vertexId) {
328
+ let result = this.predecessorsOf.get(vertexId);
329
+ if (result === undefined) {
330
+ result = this.collectPredecessors(vertexId);
331
+ this.predecessorsOf.set(vertexId, result);
332
+ }
333
+ /* a body has no predecessor of its own, so what runs before it is the call we stepped in from */
334
+ const enteredFrom = this.enteredFrom.get(vertexId);
335
+ return enteredFrom === undefined ? result : [...result, { id: enteredFrom }];
336
+ }
337
+ /** What the control flow graph itself says leads here, which is the same however often it is asked. */
338
+ collectPredecessors(vertexId) {
273
339
  const result = [];
274
340
  for (const [id, edge] of this.config.controlFlow.graph.ingoingEdges(vertexId) ?? graph_1.NoEdges) {
275
341
  const branch = control_flow_graph_1.CfgEdge.isControlDependency(edge) ? edge : undefined;
@@ -279,17 +345,12 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
279
345
  }
280
346
  else if (this.shouldSkipVertex(vertex)) {
281
347
  /* the branch closest to us is the one that decided we get here at all, so it wins */
282
- result.push(...this.getPredecessors(id).map(pred => branch ? { ...pred, branch } : pred));
348
+ result.push(...this.collectPredecessors(id).map(pred => branch ? { ...pred, branch } : pred));
283
349
  }
284
350
  else {
285
351
  result.push({ id, branch });
286
352
  }
287
353
  }
288
- /* a body has no predecessor of its own, so what runs before it is the call we stepped in from */
289
- const enteredFrom = this.enteredFrom.get(vertexId);
290
- if (enteredFrom !== undefined) {
291
- result.push({ id: enteredFrom });
292
- }
293
354
  return result;
294
355
  }
295
356
  /**
@@ -308,11 +369,12 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
308
369
  }
309
370
  }
310
371
  /**
311
- * Whether the traversal should step into what the given call dispatches to.
312
- * Returning `true` runs the bodies and continues with the state at their exit points.
372
+ * Whether to step into what the given call dispatches to, which is what makes the analysis interprocedural.
373
+ * Defaults to `abstractInterpretation.followCalls`; override it to decide per call. A call that reaches no
374
+ * definition is left alone either way.
313
375
  */
314
376
  shouldEnterCall(_call) {
315
- return false;
377
+ return this.config.ctx.config.abstractInterpretation.followCalls;
316
378
  }
317
379
  /**
318
380
  * The function definitions the given call may dispatch to.
@@ -342,21 +404,93 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
342
404
  const states = [];
343
405
  const values = [];
344
406
  const outerState = this.currentState;
407
+ /* the entry picks its state up from the call, which is what makes the arguments visible in the body */
408
+ this.trace.set(callId, outerState);
409
+ /*
410
+ * The call is worth something only if every way out of every function it reaches is: one that leaves a
411
+ * frame on one path and something else on another says as little as `if(u) df else 42` does.
412
+ */
413
+ let known = true;
345
414
  for (const def of this.getCallTargets(callId)) {
346
415
  const entry = this.getFunctionEntry(def);
347
- if (entry === undefined || this.running.has(def)) {
416
+ if (entry === undefined) {
417
+ continue;
418
+ }
419
+ else if (this.running.has(def)) {
420
+ /* it is worth what it leaves behind, which is only known once it is done; see `getAbstractValue` */
421
+ this.recursive.add(def);
422
+ this.recursiveCalls.set(callId, def);
348
423
  continue;
349
424
  }
350
425
  this.running.add(def);
426
+ const left = this.runFunction(callId, def, entry, outerState);
427
+ this.running.delete(def);
428
+ this.recursive.delete(def);
429
+ this.returns.delete(def);
430
+ states.push(...left.states);
431
+ if (left.value === undefined) {
432
+ known = false;
433
+ }
434
+ else {
435
+ values.push(left.value);
436
+ }
437
+ }
438
+ this.currentState = outerState;
439
+ if (states.length === 0) {
440
+ return undefined;
441
+ }
442
+ const returned = abstract_domain_1.AbstractDomain.joinAll(states);
443
+ if (known && values.length > 0) {
444
+ /* what the call is worth is what its function leaves behind at its exits */
445
+ returned.set(callId, abstract_domain_1.AbstractDomain.joinAll(values));
446
+ }
447
+ return returned;
448
+ }
449
+ /**
450
+ * Runs one definition for one call until what it leaves behind stops moving.
451
+ *
452
+ * One that does not call itself is run once. One that does is a fixpoint in two halves: what it leaves
453
+ * behind, which its own calls read, and what its parameters are worth, which those calls decide, since
454
+ * `shrink(head(x, nrow(x) - 1))` hands over fewer rows than it was given. Both are widened so they stop.
455
+ * @returns the states at the exit points, and what the definition leaves behind if every way out says
456
+ */
457
+ runFunction(callId, def, entry, outerState) {
458
+ const threshold = this.config.ctx.config.abstractInterpretation.wideningThreshold;
459
+ /* the counts drive the widening within the body, and belong to this call rather than to the program */
460
+ const counts = this.regionVisits(entry);
461
+ let settled = undefined;
462
+ let bound = undefined;
463
+ for (let round = 0;; round++) {
464
+ /* the parameters are the definition's own, so they are bound in a state of its own */
465
+ const inner = outerState.create(outerState.value);
466
+ this.currentState = inner;
351
467
  this.bindParameters(callId, def);
352
- /* the entry picks its state up from the call, which is what makes the arguments visible in the body */
353
- this.trace.set(callId, outerState);
468
+ /*
469
+ * The calls a definition makes to itself enter it too, so its parameters are worth what either they
470
+ * or the outer call say. Widening them is what stops the rounds: a recursion that keeps adding to
471
+ * what it is handed would otherwise be described by the first step it takes.
472
+ */
473
+ for (const [call, reached] of this.recursiveCalls) {
474
+ if (reached === def) {
475
+ this.bindParameters(call, def, round > 0 ? 'widen' : 'join');
476
+ }
477
+ }
478
+ const handed = this.parameterValues(def);
479
+ this.trace.set(callId, inner);
354
480
  this.enteredFrom.set(entry, callId);
481
+ /* what a recursive call is worth is no part of the state, so the traversal has to be made to re-read */
482
+ if (round > 0) {
483
+ for (const id of this.reachableSet(entry)) {
484
+ this.lastState.delete(id);
485
+ }
486
+ }
355
487
  const outerStack = this.stack;
356
488
  this.startVisitor([entry]);
357
489
  this.stack = outerStack;
358
490
  this.enteredFrom.delete(entry);
359
- this.running.delete(def);
491
+ const states = [];
492
+ const exits = [];
493
+ let complete = true;
360
494
  for (const exit of this.getFunctionExits(def)) {
361
495
  const state = this.trace.get(exit);
362
496
  if (state === undefined) {
@@ -364,27 +498,67 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
364
498
  }
365
499
  states.push(state);
366
500
  const value = this.getAbstractValue(exit, state);
367
- if (value !== undefined) {
368
- values.push(value);
501
+ if (value === undefined) {
502
+ complete = false;
369
503
  }
504
+ else {
505
+ exits.push(value);
506
+ }
507
+ }
508
+ const left = complete && exits.length > 0 ? abstract_domain_1.AbstractDomain.joinAll(exits) : undefined;
509
+ if (!this.recursive.has(def)) {
510
+ this.restoreVisits(counts);
511
+ return { states, value: left };
512
+ }
513
+ else if (left === undefined) {
514
+ /* one way out of the recursion says nothing, so neither does the recursion */
515
+ this.restoreVisits(counts);
516
+ return { states, value: undefined };
517
+ }
518
+ /* widening bounds the rounds, the same way it bounds the rounds of a loop */
519
+ const next = settled !== undefined && round >= threshold ? settled.widen(left) : left;
520
+ const moved = settled === undefined || !next.equals(settled) || !sameValues(handed, bound);
521
+ settled = next;
522
+ bound = handed;
523
+ this.returns.set(def, next);
524
+ if (!moved) {
525
+ this.restoreVisits(counts);
526
+ return { states, value: settled };
370
527
  }
371
528
  }
372
- this.currentState = outerState;
373
- if (states.length === 0) {
374
- return undefined;
529
+ }
530
+ /** What the parameters of a definition are worth in the state they were just bound in. */
531
+ parameterValues(defId) {
532
+ const definition = this.getDataflowGraph(defId);
533
+ if (!vertex_1.FunctionDefinitionVertex.is(definition)) {
534
+ return [];
375
535
  }
376
- const returned = abstract_domain_1.AbstractDomain.joinAll(states);
377
- if (values.length > 0) {
378
- /* what the call is worth is what its function leaves behind at its exits */
379
- returned.set(callId, abstract_domain_1.AbstractDomain.joinAll(values));
536
+ return Object.keys(definition.params).map(key => this.currentState.get(node_id_1.NodeId.normalize(key)));
537
+ }
538
+ /** How often each vertex of a function has been visited, so one call does not widen the next one early. */
539
+ regionVisits(entry) {
540
+ const counts = new Map();
541
+ for (const id of this.reachableSet(entry)) {
542
+ counts.set(id, this.visited.get(id));
543
+ }
544
+ return counts;
545
+ }
546
+ /** Puts the visit counts back as they were before a function was run for one call. */
547
+ restoreVisits(counts) {
548
+ for (const [id, count] of counts) {
549
+ if (count === undefined) {
550
+ this.visited.delete(id);
551
+ }
552
+ else {
553
+ this.visited.set(id, count);
554
+ }
380
555
  }
381
- return returned;
382
556
  }
383
557
  /**
384
558
  * Hand the arguments of the call to the parameters of the function it enters, so the body can read them.
385
559
  * Only the arguments of this very call are used, whichever other calls the function has.
386
560
  */
387
- bindParameters(callId, defId) {
561
+ bindParameters(callId, defId, add) {
388
562
  const call = this.getDataflowGraph(callId);
389
563
  const definition = this.getDataflowGraph(defId);
390
564
  if (!vertex_1.FunctionCallVertex.is(call) || !vertex_1.FunctionDefinitionVertex.is(definition)) {
@@ -398,7 +572,12 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
398
572
  if (!edge_1.DfEdge.includesType(edge, edge_1.EdgeType.DefinedByOnCall) || !args.has(target)) {
399
573
  continue;
400
574
  }
401
- const value = this.getAbstractValue(target, this.currentState);
575
+ /* a call that is not the one being entered is read where it stands, not from the state here */
576
+ let value = add === undefined ? this.getAbstractValue(target, this.currentState) : this.getAbstractValue(target);
577
+ const previous = add === undefined ? undefined : this.currentState.get(parameter);
578
+ if (value !== undefined && previous !== undefined) {
579
+ value = (add === 'widen' ? previous.widen(value) : previous.join(value));
580
+ }
402
581
  if (value !== undefined) {
403
582
  this.currentState.set(parameter, value);
404
583
  /* the parameter is a definition like any other, so the body only reads it once it counts as assigned */
@@ -410,10 +589,29 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
410
589
  }
411
590
  /** Gets each variable origin that has already been visited and whose assignment has already been processed */
412
591
  getVariableOrigins(nodeId) {
413
- return df_helper_1.Dataflow.origin(this.config.dfg, nodeId)
592
+ const origins = df_helper_1.Dataflow.origin(this.config.dfg, nodeId)
414
593
  ?.filter(origin => origin.type === 0 /* OriginType.ReadVariableOrigin */)
415
594
  .map(origin => origin.id)
416
595
  .filter(origin => this.trace.has(origin) && !this.unassigned.has(origin)) ?? [];
596
+ /*
597
+ * A read with a single definition takes it whatever the control flow does. One with several only sees
598
+ * those that can reach it: `x` within `for(i in 1:nrow(x)) x$a[i] <- 1` is a definition of the `x` in
599
+ * the head of the loop, but the head runs before the body ever does.
600
+ */
601
+ return origins.length > 1 ? origins.filter(origin => this.reaches(origin, nodeId)) : origins;
602
+ }
603
+ /** Whether the control flow may get from one vertex to another, answered from one traversal per source. */
604
+ reaches(from, to) {
605
+ return this.reachableSet(from).has(to);
606
+ }
607
+ /** Everything the control flow may reach from a vertex, walked once per source and kept. */
608
+ reachableSet(from) {
609
+ let reachable = this.reachableFrom.get(from);
610
+ if (reachable === undefined) {
611
+ reachable = (0, simple_visitor_1.visitCfgInOrder)(this.config.controlFlow.graph, [from], () => { });
612
+ this.reachableFrom.set(from, reachable);
613
+ }
614
+ return reachable;
417
615
  }
418
616
  /** Checks whether a node represents a unsupported (environment-changing) function call (e.g. `eval`, `load`, `attach`, `rm`, ...) */
419
617
  isUnsupportedFunctionCall(nodeId) {
@@ -465,7 +663,8 @@ class AbstractInterpretationVisitor extends semantic_cfg_guided_visitor_1.Semant
465
663
  startingPoints() {
466
664
  const graph = this.config.controlFlow.graph;
467
665
  const starts = [...this.config.controlFlow.entryPoints];
468
- for (const [id] of graph.vertices(false)) {
666
+ /* asking the control flow for all of its vertices copies it out of the dataflow graph, which already has them */
667
+ for (const [id] of this.config.dfg.verticesOfType(vertex_1.VertexType.FunctionDefinition)) {
469
668
  starts.push(...graph.childrenOf(id) ?? control_flow_graph_1.NoNeighbors);
470
669
  }
471
670
  return starts;
package/config.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { type MergeableRecord } from './util/objects';
1
+ import { type AutocompletablePaths, type ValueAtPath, type MergeableRecord } from './util/objects';
2
2
  import { type LogLevelName } from './util/log';
3
3
  import Joi from 'joi';
4
4
  import type { BuiltInDefinitions } from './dataflow/environments/built-in-config';
5
5
  import type { KnownParser } from './r-bridge/parser';
6
- import type { DeepPartial, DeepWritable, Paths, PathValue } from 'ts-essentials';
6
+ import type { DeepPartial, DeepWritable } from 'ts-essentials';
7
7
  import type { DataflowProcessors } from './dataflow/processor';
8
8
  import type { ParentInformation } from './r-bridge/lang-4.x/ast/model/processing/decorate';
9
9
  import type { FlowrAnalyzerContext } from './project/context/flowr-analyzer-context';
@@ -112,7 +112,7 @@ export type SpecializeConfigEntry = DeepPartial<FlowrConfig> & {
112
112
  * @see {@link FlowrConfig.default} for the default configuration.
113
113
  * @see {@link FlowrConfig.Schema} for the Joi schema for validation.
114
114
  */
115
- export interface FlowrConfig extends MergeableRecord {
115
+ export interface FlowrConfig {
116
116
  readonly logLevel?: LogLevelName;
117
117
  /**
118
118
  * Whether source calls should be ignored, causing {@link processSourceCall}'s behavior to be skipped
@@ -344,6 +344,11 @@ export interface FlowrConfig extends MergeableRecord {
344
344
  * The threshold for the number of visitations of a node at which widening should be performed to ensure the termination of the fixpoint iteration
345
345
  */
346
346
  readonly wideningThreshold: number;
347
+ /**
348
+ * Whether the abstract interpretation is interprocedural, i.e. whether it steps into the functions a call
349
+ * may dispatch to instead of describing the call by its result alone
350
+ */
351
+ readonly followCalls: boolean;
347
352
  /**
348
353
  * The configuration of the shape inference for data frames
349
354
  */
@@ -408,9 +413,11 @@ export interface FlowrConfig extends MergeableRecord {
408
413
  */
409
414
  readonly gas: FlowrGasConfig;
410
415
  }
411
- export type ValidFlowrConfigPaths = Paths<FlowrConfig, {
412
- depth: 9;
413
- }>;
416
+ /**
417
+ * Every path into the configuration, which is what {@link FlowrConfig.setInConfig} and
418
+ * {@link FlowrAnalyzerBuilder#configure|configure()} take and what an editor completes.
419
+ */
420
+ export type ValidFlowrConfigPaths = AutocompletablePaths<FlowrConfig>;
414
421
  /** Whether library exports should be resolved from a signature database (`solver.sigdb.enabled`). */
415
422
  export declare function isSigDbEnabled(config: FlowrConfig | undefined): boolean;
416
423
  /**
@@ -524,12 +531,12 @@ export declare const FlowrConfig: {
524
531
  * console.log(newConfig.solver.variables); // Output: "builtin"
525
532
  * ```
526
533
  */
527
- readonly setInConfig: <Path extends ValidFlowrConfigPaths>(this: void, config: FlowrConfig, key: Path, value: PathValue<FlowrConfig, Path>) => FlowrConfig;
534
+ readonly setInConfig: <Path extends ValidFlowrConfigPaths>(this: void, config: FlowrConfig, key: Path, value: ValueAtPath<FlowrConfig, Path>) => FlowrConfig;
528
535
  /**
529
536
  * Modifies the given config object in place by setting the given value at the given key, where the key is a dot-separated path to the value in the config object.
530
537
  * @see {@link setInConfig} for a version that returns a new config object instead of modifying the given one in place.
531
538
  */
532
- readonly setInConfigInPlace: <Path extends ValidFlowrConfigPaths>(this: void, config: FlowrConfig, key: Path, value: PathValue<FlowrConfig, Path>) => void;
539
+ readonly setInConfigInPlace: <Path extends ValidFlowrConfigPaths>(this: void, config: FlowrConfig, key: Path, value: ValueAtPath<FlowrConfig, Path>) => void;
533
540
  };
534
541
  /** Path to the user-global `flowr.json`, read as a fallback when no project config is found. */
535
542
  export declare function globalConfigFilePath(): string;
package/config.js CHANGED
@@ -135,7 +135,8 @@ function mergeOverwrite(parent, own) {
135
135
  const result = { ...parent };
136
136
  for (const [key, value] of Object.entries(own)) {
137
137
  const prev = parent[key];
138
- result[key] = (0, objects_1.isPlainObject)(prev) && (0, objects_1.isPlainObject)(value) ? mergeOverwrite(prev, value) : value;
138
+ result[key] = (0, objects_1.isPlainObject)(prev) && (0, objects_1.isPlainObject)(value)
139
+ ? mergeOverwrite(prev, value) : value;
139
140
  }
140
141
  return result;
141
142
  }
@@ -295,6 +296,7 @@ exports.FlowrConfig = {
295
296
  },
296
297
  abstractInterpretation: {
297
298
  wideningThreshold: 4,
299
+ followCalls: true,
298
300
  dataFrame: {
299
301
  maxColNames: 50,
300
302
  readLoadedData: {
@@ -447,6 +449,7 @@ exports.FlowrConfig = {
447
449
  }).description('How to resolve constants, constraints, cells, ...'),
448
450
  abstractInterpretation: joi_1.default.object({
449
451
  wideningThreshold: joi_1.default.number().min(1).description('The threshold for the number of visitations of a node at which widening should be performed to ensure the termination of the fixpoint iteration.'),
452
+ followCalls: joi_1.default.boolean().description('Whether the abstract interpretation is interprocedural, i.e. whether it steps into the functions a call may dispatch to.'),
450
453
  dataFrame: joi_1.default.object({
451
454
  maxColNames: joi_1.default.number().min(0).description('The maximum number of columns names to infer for data frames before over-approximating the column names to top.'),
452
455
  readLoadedData: joi_1.default.object({
@@ -18,6 +18,13 @@ import { BuiltInProcName } from '../dataflow/environments/built-in-proc-name';
18
18
  export interface SemanticCfgGuidedVisitorConfiguration<OtherInfo = NoInfo, ControlFlow extends ControlFlowInformation = ControlFlowInformation, Ast extends NormalizedAst<OtherInfo> = NormalizedAst<OtherInfo>, Dfg extends DataflowGraph = DataflowGraph> extends DataflowCfgGuidedVisitorConfiguration<ControlFlow, Dfg>, SyntaxCfgGuidedVisitorConfiguration<OtherInfo, ControlFlow, Ast> {
19
19
  readonly ctx: ReadOnlyFlowrAnalyzerContext;
20
20
  }
21
+ /**
22
+ * What every `on...Call` hook of the {@link SemanticCfgGuidedVisitor} receives: the call vertex it fired for.
23
+ * Hooks that recognize more of the call's shape extend this with the parts they resolved.
24
+ */
25
+ export interface OnCall {
26
+ readonly call: DataflowGraphVertexFunctionCall;
27
+ }
21
28
  /**
22
29
  * This visitor extends on the {@link DataflowAwareCfgGuidedVisitor} by dispatching visitors for separate function calls as well,
23
30
  * providing more information!
@@ -41,13 +48,6 @@ export interface SemanticCfgGuidedVisitorConfiguration<OtherInfo = NoInfo, Contr
41
48
  *
42
49
  * Use {@link BasicCfgGuidedVisitor#start} to start the traversal.
43
50
  */
44
- /**
45
- * What every `on...Call` hook of the {@link SemanticCfgGuidedVisitor} receives: the call vertex it fired for.
46
- * Hooks that recognize more of the call's shape extend this with the parts they resolved.
47
- */
48
- export interface OnCall {
49
- readonly call: DataflowGraphVertexFunctionCall;
50
- }
51
51
  export declare class SemanticCfgGuidedVisitor<OtherInfo = NoInfo, ControlFlow extends ControlFlowInformation = ControlFlowInformation, Ast extends NormalizedAst<OtherInfo> = NormalizedAst<OtherInfo>, Dfg extends DataflowGraph = DataflowGraph, Config extends SemanticCfgGuidedVisitorConfiguration<OtherInfo, ControlFlow, Ast, Dfg> = SemanticCfgGuidedVisitorConfiguration<OtherInfo, ControlFlow, Ast, Dfg>> extends DataflowAwareCfgGuidedVisitor<ControlFlow, Dfg, Config> {
52
52
  /**
53
53
  * A helper function to get the normalized AST node for the given id or fail if it does not exist.
@@ -15,6 +15,29 @@ const node_value_1 = require("../dataflow/eval/resolve/node-value");
15
15
  const r_value_1 = require("../dataflow/eval/values/r-value");
16
16
  const r_function_definition_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
17
17
  const r_if_then_else_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-if-then-else");
18
+ /**
19
+ * This visitor extends on the {@link DataflowAwareCfgGuidedVisitor} by dispatching visitors for separate function calls as well,
20
+ * providing more information!
21
+ * In a way, this is the mixin of syntactic and dataflow guided visitation.
22
+ *
23
+ * Overwrite the functions starting with `on` to implement your logic.
24
+ * In general, there is just one special case that you need to be aware of:
25
+ *
26
+ * In the context of a function call, flowR may be unsure to which origin the call relates!
27
+ * Consider the following example:
28
+ *
29
+ * ```r
30
+ * if(u) foo <- library else foo <- rm
31
+ * foo(x)
32
+ * ```
33
+ *
34
+ * Obtaining the origins of the call to `foo` will return both built-in functions `library` and `rm`.
35
+ * The general semantic visitor cannot decide on how to combine these cases,
36
+ * and it is up to your overload of {@link SemanticCfgGuidedVisitor#onDispatchFunctionCallOrigins|onDispatchFunctionCallOrigins}
37
+ * to decide how to handle this.
38
+ *
39
+ * Use {@link BasicCfgGuidedVisitor#start} to start the traversal.
40
+ */
18
41
  class SemanticCfgGuidedVisitor extends dfg_cfg_guided_visitor_1.DataflowAwareCfgGuidedVisitor {
19
42
  /**
20
43
  * A helper function to get the normalized AST node for the given id or fail if it does not exist.
@@ -65,6 +65,8 @@ export interface StatedSignature {
65
65
  /** what it does, from {@link callPropWords} */
66
66
  readonly props: readonly string[];
67
67
  }
68
+ /** {@link PrimitivesPerTopic} the way a lookup wants it: the topic documenting a name. */
69
+ export declare const BasePrimitiveTopics: Readonly<Record<string, string>>;
68
70
  /**
69
71
  * What flowR states about every function it carries a definition for, as `name -> signatures`. A name may be
70
72
  * defined for several packages (`filter` is dplyr's and cohortBuilder's), so all of them are here and the
@@ -78,20 +80,9 @@ export declare function statedSignatures(definitions?: BuiltInDefinitions): Map<
78
80
  */
79
81
  export declare function statedSignatureOf(stated: ReadonlyMap<string, readonly StatedSignature[]>, name: string, pkg?: string): StatedSignature | undefined;
80
82
  /**
81
- * R's group generics: a class claims every member of a group at once, with an `Ops.cls` (S3) or a
82
- * `setMethod('Arith', ...)` (S4), so a call to any member may dispatch to a method named after the group.
83
- * `Ops` is what S3 calls the union of the three S4 groups it splits into.
83
+ * Contains the built-in definitions recognized by flowR, as they are written down: {@link DefaultBuiltinConfig}
84
+ * is what {@link markGenerics} makes of them, and a test checks that this is all it changes.
84
85
  */
85
- export declare const RGroupGenerics: {
86
- readonly Arith: readonly ["+", "-", "*", "/", "^", "**", "%%", "%/%"];
87
- readonly Compare: readonly ["==", "!=", "<", "<=", ">", ">="];
88
- readonly Logic: readonly ["&", "|"];
89
- readonly Ops: readonly ["+", "-", "*", "/", "^", "**", "%%", "%/%", "==", "!=", "<", "<=", ">", ">=", "&", "|", "!"];
90
- readonly Math: readonly ["abs", "sign", "sqrt", "floor", "ceiling", "trunc", "exp", "expm1", "log", "log2", "log10", "log1p", "cos", "sin", "tan", "cosh", "sinh", "tanh", "acos", "asin", "atan", "acosh", "asinh", "atanh", "cumsum", "cumprod", "cummax", "cummin"];
91
- readonly Math2: readonly ["round", "signif"];
92
- readonly Summary: readonly ["any", "sum", "prod", "min", "max", "range"];
93
- readonly Complex: readonly ["Re", "Im", "Mod", "Arg", "Conj"];
94
- };
95
86
  export declare const WrittenBuiltinDefinitions: [{
96
87
  readonly type: "constant";
97
88
  readonly names: Identifier[];