@eagleoutice/flowr 2.13.7 → 2.13.9

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 (42) hide show
  1. package/README.md +23 -23
  2. package/dataflow/cluster.js +48 -24
  3. package/dataflow/environments/default-builtin-config.d.ts +30 -0
  4. package/dataflow/environments/default-builtin-config.js +9 -0
  5. package/dataflow/graph/df-helper.d.ts +13 -0
  6. package/dataflow/graph/df-helper.js +21 -0
  7. package/dataflow/graph/graph.d.ts +1 -0
  8. package/dataflow/graph/graph.js +21 -6
  9. package/linter/rules/undefined-symbol-util.d.ts +4 -1
  10. package/linter/rules/undefined-symbol-util.js +6 -3
  11. package/package.json +2 -2
  12. package/project/dependency-version-space.d.ts +18 -3
  13. package/project/dependency-version-space.js +40 -6
  14. package/project/plugins/package-version-plugins/package.d.ts +2 -0
  15. package/project/plugins/package-version-plugins/package.js +4 -0
  16. package/queries/catalog/call-context-query/call-context-query-executor.js +1 -9
  17. package/queries/catalog/call-context-query/identify-link-to-last-call-relation.d.ts +4 -2
  18. package/queries/catalog/call-context-query/identify-link-to-last-call-relation.js +25 -0
  19. package/queries/catalog/dataflow-lens-query/dataflow-lens-query-executor.js +11 -1
  20. package/queries/catalog/dependencies-query/dependencies-query-executor.js +3 -2
  21. package/queries/catalog/dependencies-query/dependencies-query-format.d.ts +8 -0
  22. package/queries/catalog/dependencies-query/dependencies-query-format.js +47 -5
  23. package/queries/catalog/dependencies-query/function-info/library-functions.js +2 -1
  24. package/queries/catalog/dependencies-query/function-info/read-functions.js +26 -0
  25. package/queries/catalog/dependencies-query/function-info/test-functions.d.ts +2 -0
  26. package/queries/catalog/dependencies-query/function-info/test-functions.js +33 -31
  27. package/queries/catalog/dependencies-query/function-info/write-functions.js +20 -1
  28. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-executor.js +1 -1
  29. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.d.ts +1 -1
  30. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.js +1 -1
  31. package/queries/catalog/happens-before-query/happens-before-query-format.js +3 -2
  32. package/queries/catalog/static-slice-query/static-slice-query-format.js +1 -0
  33. package/r-bridge/data/data.d.ts +1 -1
  34. package/r-bridge/data/data.js +1 -1
  35. package/slicing/criterion/parse.d.ts +2 -1
  36. package/slicing/criterion/parse.js +37 -1
  37. package/slicing/static/fingerprint.d.ts +1 -1
  38. package/slicing/static/fingerprint.js +40 -8
  39. package/slicing/static/static-slicer.js +1 -1
  40. package/slicing/static/visiting-queue.d.ts +4 -2
  41. package/slicing/static/visiting-queue.js +10 -1
  42. package/util/version.js +1 -1
@@ -35,6 +35,8 @@ export declare class Package {
35
35
  get resolvedVersion(): string | undefined;
36
36
  get versionConstraints(): readonly Range[];
37
37
  get derivedRange(): Range | undefined;
38
+ /** {@link derivedRange} if a source declared one, else the {@link resolvedVersion} the exports were read from. */
39
+ get effectiveRange(): Range | undefined;
38
40
  constructor(info: {
39
41
  name: string;
40
42
  } & PackageOptions);
@@ -44,6 +44,10 @@ class Package {
44
44
  this._derivedRange ??= this.deriveRange();
45
45
  return this._derivedRange;
46
46
  }
47
+ /** {@link derivedRange} if a source declared one, else the {@link resolvedVersion} the exports were read from. */
48
+ get effectiveRange() {
49
+ return this.derivedRange ?? (this._resolvedVersion !== undefined ? r_version_1.RRange.parse('=' + this._resolvedVersion) : undefined);
50
+ }
47
51
  constructor(info) {
48
52
  this.name = info.name;
49
53
  this.addInfo(info);
@@ -15,14 +15,6 @@ const identifier_1 = require("../../../dataflow/environments/identifier");
15
15
  const df_helper_1 = require("../../../dataflow/graph/df-helper");
16
16
  const queue_1 = require("../../../util/collections/queue");
17
17
  const r_base_packages_1 = require("../../../util/r-base-packages");
18
- /* if the node is effected by nse, we have an ingoing nse edge */
19
- function isQuoted(node, graph) {
20
- const vertex = graph.ingoingEdges(node);
21
- if (vertex === undefined) {
22
- return false;
23
- }
24
- return vertex.values().some(e => edge_1.DfEdge.includesType(e, edge_1.EdgeType.NonStandardEvaluation));
25
- }
26
18
  function makeReport(collector) {
27
19
  const result = {};
28
20
  for (const [kind, collected] of collector.store) {
@@ -319,7 +311,7 @@ async function executeCallContextQueries({ analyzer }, queries) {
319
311
  continue;
320
312
  }
321
313
  }
322
- if (isQuoted(nodeId, dataflow.graph)) {
314
+ if (df_helper_1.Dataflow.isQuoted(nodeId, dataflow.graph)) {
323
315
  /* if the call is quoted, we do not want to link to it */
324
316
  continue;
325
317
  }
@@ -7,6 +7,7 @@ import type { LinkToLastCall } from './call-context-query-format';
7
7
  import type { PromotedLinkTo } from './call-context-query-executor';
8
8
  import type { ReadonlyFlowrAnalysisProvider } from '../../../project/flowr-analyzer';
9
9
  import type { ControlFlowGraph } from '../../../control-flow/control-flow-graph';
10
+ type KnownCalls = Map<NodeId, Required<DataflowGraphVertexFunctionCall>>;
10
11
  export declare enum CallTargets {
11
12
  /** call targets a function that is not defined locally in the script (e.g., the call targets a library function) */
12
13
  OnlyGlobal = "global",
@@ -41,8 +42,9 @@ export declare function getValueOfArgument<Types extends readonly RType[] = read
41
42
  * the known calls available.
42
43
  * @see {@link identifyLinkToLastCallRelationSync} for the synchronous version.
43
44
  */
44
- export declare function identifyLinkToLastCallRelation(from: NodeId, analyzer: ReadonlyFlowrAnalysisProvider, l: LinkToLastCall<RegExp> | PromotedLinkTo<LinkToLastCall<RegExp>>, knownCalls?: Map<NodeId, Required<DataflowGraphVertexFunctionCall>>): Promise<NodeId[]>;
45
+ export declare function identifyLinkToLastCallRelation(from: NodeId, analyzer: ReadonlyFlowrAnalysisProvider, l: LinkToLastCall<RegExp> | PromotedLinkTo<LinkToLastCall<RegExp>>, knownCalls?: KnownCalls): Promise<NodeId[]>;
45
46
  /**
46
47
  * Synchronous version of {@link identifyLinkToLastCallRelation}.
47
48
  */
48
- export declare function identifyLinkToLastCallRelationSync(from: NodeId, cfg: ControlFlowGraph, graph: DataflowGraph, { callName, cascadeIf, ignoreIf }: LinkToLastCall<RegExp> | PromotedLinkTo<LinkToLastCall<RegExp>>, knownCalls?: Map<NodeId, Required<DataflowGraphVertexFunctionCall>>): NodeId[];
49
+ export declare function identifyLinkToLastCallRelationSync(from: NodeId, cfg: ControlFlowGraph, graph: DataflowGraph, { callName, cascadeIf, ignoreIf }: LinkToLastCall<RegExp> | PromotedLinkTo<LinkToLastCall<RegExp>>, knownCalls?: KnownCalls): NodeId[];
50
+ export {};
@@ -133,6 +133,25 @@ async function identifyLinkToLastCallRelation(from, analyzer, l, knownCalls) {
133
133
  const cfg = (await analyzer.controlflow([], cfg_kind_1.CfgKind.WithDataflow)).graph;
134
134
  return identifyLinkToLastCallRelationSync(from, cfg, graph, l, knownCalls);
135
135
  }
136
+ /**
137
+ * Memoizes, per set of known calls and per `callName`, whether any call can match it at all. One link keeps the same
138
+ * `callName` object across every call site it is evaluated against, so identity is enough to key it.
139
+ */
140
+ const candidatesPerCallSet = new WeakMap();
141
+ function anyCallMatches(knownCalls, callName, matches) {
142
+ let perName = candidatesPerCallSet.get(knownCalls);
143
+ if (perName === undefined) {
144
+ perName = new Map();
145
+ candidatesPerCallSet.set(knownCalls, perName);
146
+ }
147
+ const cached = perName.get(callName);
148
+ if (cached !== undefined) {
149
+ return cached;
150
+ }
151
+ const matched = knownCalls.values().some(matches);
152
+ perName.set(callName, matched);
153
+ return matched;
154
+ }
136
155
  /**
137
156
  * Synchronous version of {@link identifyLinkToLastCallRelation}.
138
157
  */
@@ -143,6 +162,12 @@ function identifyLinkToLastCallRelationSync(from, cfg, graph, { callName, cascad
143
162
  const found = [];
144
163
  const cNameCheck = callName instanceof RegExp ? ({ name }) => callName.test(identifier_1.Identifier.getName(name))
145
164
  : ({ name }) => callName(identifier_1.Identifier.getName(name));
165
+ /* only a call matching `callName` is ever collected, so with none in the whole graph every walk below returns
166
+ * nothing: skipping them turns one reverse walk per call site into a single scan (a `sink` redirect in a
167
+ * script that never sinks is the common case) */
168
+ if (knownCalls !== undefined && !anyCallMatches(knownCalls, callName, cNameCheck)) {
169
+ return [];
170
+ }
146
171
  const getVertex = knownCalls ?
147
172
  (node) => knownCalls.get(node) :
148
173
  (node) => {
@@ -4,6 +4,16 @@ exports.executeDataflowLensQuery = executeDataflowLensQuery;
4
4
  const log_1 = require("../../../util/log");
5
5
  const dfg_view_1 = require("../../../util/simple-df/dfg-view");
6
6
  const vertex_1 = require("../../../dataflow/graph/vertex");
7
+ const arguments_1 = require("../../../abstract-interpretation/data-frame/mappers/arguments");
8
+ const operators_1 = require("../../../r-bridge/lang-4.x/ast/model/operators");
9
+ /**
10
+ * The lens hides syntax: every operator R has, the native pipe (which {@link OperatorDatabase} does not list), and the
11
+ * control-flow keywords. None of them names anything, unlike the built-in *functions* (`print`, `ifelse`) it keeps.
12
+ * Anchored and escaped, as most of these are regex syntax themselves and an unanchored alternative would also drop
13
+ * every lexeme merely *containing* one (`if` in `identifier`).
14
+ */
15
+ const HiddenLexemes = `^(${[...Object.keys(operators_1.OperatorDatabase), '|>', 'function', 'repeat', 'if', 'next', 'break']
16
+ .map(name => (0, arguments_1.escapeRegExp)(name)).join('|')})$`;
7
17
  /**
8
18
  * Executes the given dataflow lens queries using the provided analyzer.
9
19
  */
@@ -17,7 +27,7 @@ async function executeDataflowLensQuery({ analyzer }, queries) {
17
27
  keepEnv: false,
18
28
  keepCd: true,
19
29
  tags: [vertex_1.VertexType.Use, vertex_1.VertexType.VariableDefinition, vertex_1.VertexType.FunctionDefinition, vertex_1.VertexType.FunctionCall],
20
- nameRegex: '<-|<<-|->|->>|=|+|-|*|/|\\|>|function|repeat|if|next|break',
30
+ nameRegex: HiddenLexemes,
21
31
  blacklistWithName: true
22
32
  }
23
33
  }, analyzer.inspectContext().env.makeCleanEnv());
@@ -48,7 +48,8 @@ async function executeDependenciesQuery({ analyzer, }, queries) {
48
48
  if (query.additionalCategories !== undefined) {
49
49
  for (const [category, value] of Object.entries(query.additionalCategories)) {
50
50
  // custom categories only use the "functions" collection and do not allow specifying additional functions in the object itself, so we "undefined" a lot here
51
- functions.set(category, getFunctionsToCheck(undefined, category, undefined, false, value.functions));
51
+ const custom = getFunctionsToCheck(undefined, category, undefined, false, value.functions);
52
+ functions.set(category, [...(functions.get(category) ?? []), ...custom]);
52
53
  }
53
54
  }
54
55
  const queryResults = !functions.values().toArray().some(f => f.length > 0) ? { kinds: {}, '.meta': { timing: 0 } } :
@@ -197,7 +198,7 @@ function getResults(queries, { dataflow, config, normalize }, results, kind, fun
197
198
  linkedIds: linked?.length ? linked : undefined,
198
199
  value: resolvedValue ?? info.defaultValue ?? defaultValue,
199
200
  versionConstraints: dep?.versionConstraints,
200
- derivedRange: dep?.derivedRange,
201
+ derivedRange: dep?.effectiveRange,
201
202
  namespaceInfo: dep?.namespaceInfo
202
203
  }));
203
204
  }
@@ -48,6 +48,12 @@ export declare const DefaultDependencyCategories: {
48
48
  readonly functions: FunctionInfo[];
49
49
  readonly defaultValue: "stdout";
50
50
  };
51
+ readonly print: {
52
+ readonly queryDisplayName: "Auto-printed Results";
53
+ readonly functions: [];
54
+ readonly defaultValue: "stdout";
55
+ readonly additionalAnalysis: (data: BasicQueryData, ignoreDefault: boolean, _functions: FunctionInfo[], queryResults: CallContextQueryResult, result: DependencyInfo[]) => Promise<void>;
56
+ };
51
57
  readonly visualize: {
52
58
  readonly queryDisplayName: "Visualizations";
53
59
  readonly functions: FunctionInfo[];
@@ -63,6 +69,7 @@ export interface DependenciesQuery extends BaseQueryFormat, Partial<Record<`${De
63
69
  readonly type: 'dependencies';
64
70
  readonly enabledCategories?: DependencyCategoryName[];
65
71
  readonly ignoreDefaultFunctions?: boolean;
72
+ /** Naming a built-in category extends it; use `ignoreDefaultFunctions` to drop the built-in functions. */
66
73
  readonly additionalCategories?: Record<string, MarkOptional<DependencyCategorySettings, 'additionalAnalysis'>>;
67
74
  }
68
75
  export type DependenciesQueryResult = BaseQueryResult & {
@@ -85,6 +92,7 @@ export interface DependencyInfo extends Record<string, unknown> {
85
92
  }
86
93
  /**
87
94
  * Gets all dependency categories, including user-defined additional categories.
95
+ * A category named like a built-in one extends it instead of replacing it.
88
96
  */
89
97
  export declare function getAllCategories(queries: readonly DependenciesQuery[]): Record<DependencyCategoryName, DependencyCategorySettings>;
90
98
  export declare const DependenciesQueryDefinition: {
@@ -19,6 +19,11 @@ const test_functions_1 = require("./function-info/test-functions");
19
19
  const identifier_1 = require("../../../dataflow/environments/identifier");
20
20
  const r_project_1 = require("../../../r-bridge/lang-4.x/ast/model/nodes/r-project");
21
21
  const model_1 = require("../../../r-bridge/lang-4.x/ast/model/model");
22
+ const objects_1 = require("../../../util/objects");
23
+ const query_fn_props_1 = require("../../../dataflow/environments/query-fn-props");
24
+ const built_in_props_1 = require("../../../dataflow/environments/built-in-props");
25
+ const vertex_1 = require("../../../dataflow/graph/vertex");
26
+ const df_helper_1 = require("../../../dataflow/graph/df-helper");
22
27
  exports.Unknown = 'unknown';
23
28
  exports.DefaultDependencyCategories = {
24
29
  'library': {
@@ -38,7 +43,7 @@ exports.DefaultDependencyCategories = {
38
43
  functionName: model_1.RNode.lexeme(node).includes(':::') ? ':::' : '::',
39
44
  value: ns,
40
45
  versionConstraints: dep?.versionConstraints,
41
- derivedRange: dep?.derivedRange,
46
+ derivedRange: dep?.effectiveRange,
42
47
  namespaceInfo: dep?.namespaceInfo
43
48
  });
44
49
  }
@@ -61,6 +66,37 @@ exports.DefaultDependencyCategories = {
61
66
  functions: write_functions_1.WriteFunctions,
62
67
  defaultValue: 'stdout'
63
68
  },
69
+ 'print': {
70
+ queryDisplayName: 'Auto-printed Results',
71
+ functions: [],
72
+ defaultValue: 'stdout',
73
+ additionalAnalysis: async (data, ignoreDefault, _functions, queryResults, result) => {
74
+ if (ignoreDefault) {
75
+ return;
76
+ }
77
+ const [{ ast }, dataflow] = await Promise.all([data.analyzer.normalize(), data.analyzer.dataflow()]);
78
+ const accountedFor = new Set(Object.values(queryResults?.kinds ?? {})
79
+ .flatMap(k => Object.values(k.subkinds).flat()).map(r => r.id));
80
+ for (const file of ast.files) {
81
+ for (const statement of file.root.children) {
82
+ if (statement.type !== type_1.RType.FunctionCall || accountedFor.has(statement.info.id)) {
83
+ continue;
84
+ }
85
+ const vertex = dataflow.graph.getVertex(statement.info.id);
86
+ const functionName = vertex?.tag === vertex_1.VertexType.FunctionCall
87
+ ? df_helper_1.Dataflow.qualify(statement.info.id, dataflow.graph, false) ?? vertex.name : undefined;
88
+ if (functionName === undefined) {
89
+ continue;
90
+ }
91
+ const props = (0, query_fn_props_1.queryFnProps)(functionName, { environment: dataflow.environment })?.props ?? 0;
92
+ if ((props & (built_in_props_1.CallProp.Invisible | built_in_props_1.CallProp.Graphics)) !== 0 || test_functions_1.ExpectFunctionNames.test(identifier_1.Identifier.getName(functionName))) {
93
+ continue;
94
+ }
95
+ result.push({ nodeId: statement.info.id, functionName, value: 'stdout' });
96
+ }
97
+ }
98
+ }
99
+ },
64
100
  'visualize': {
65
101
  queryDisplayName: 'Visualizations',
66
102
  functions: visualize_functions_1.VisualizeFunctions
@@ -86,12 +122,18 @@ function printResultSection(title, infos, result, formatter) {
86
122
  }
87
123
  /**
88
124
  * Gets all dependency categories, including user-defined additional categories.
125
+ * A category named like a built-in one extends it instead of replacing it.
89
126
  */
90
127
  function getAllCategories(queries) {
91
- let categories = exports.DefaultDependencyCategories;
128
+ const categories = { ...exports.DefaultDependencyCategories };
92
129
  for (const query of queries) {
93
- if (query.additionalCategories) {
94
- categories = { ...categories, ...query.additionalCategories };
130
+ for (const [name, settings] of Object.entries(query.additionalCategories ?? {})) {
131
+ const known = categories[name];
132
+ categories[name] = known === undefined ? settings : {
133
+ ...known,
134
+ ...(0, objects_1.compactRecord)(settings),
135
+ functions: [...known.functions, ...settings.functions]
136
+ };
95
137
  }
96
138
  }
97
139
  return categories;
@@ -122,7 +164,7 @@ exports.DependenciesQueryDefinition = {
122
164
  queryDisplayName: joi_1.default.string().description('The display name in the query result.'),
123
165
  functions: functionInfoSchema.description('The functions that this additional category should search for.'),
124
166
  defaultValue: joi_1.default.string().description('The default value to return when there is no value to gather from the function information.').optional()
125
- })).description('A set of additional, user-supplied dependency categories, whose results will be included in the query return value.').optional()
167
+ })).description('A set of additional, user-supplied dependency categories, whose results will be included in the query return value. Using the name of a built-in category extends it instead of replacing it.').optional()
126
168
  }).description('The dependencies query retrieves and returns the set of all dependencies in the dataflow graph, which includes libraries, sourced files, read data, and written data.'),
127
169
  flattenInvolvedNodes: (queryResults, query) => {
128
170
  const out = queryResults;
@@ -16,6 +16,7 @@ exports.LibraryFunctions = [
16
16
  { package: 'librarian', name: 'shelf', argIdx: 'unnamed', resolveValue: true },
17
17
  { package: 'devtools', name: 'load_all', argIdx: 0, argName: 'path', resolveValue: true, defaultValue: '.' },
18
18
  { package: 'devtools', name: 'load_code', argIdx: 0, argName: 'path', resolveValue: true, defaultValue: '.' },
19
- { package: 'import', name: 'from', argIdx: 0, argName: 'package', resolveValue: true }
19
+ { package: 'import', name: 'from', argIdx: 0, argName: 'package', resolveValue: true },
20
+ { package: 'rlang', name: 'on_package_load', argIdx: 0, argName: 'pkg', resolveValue: true }
20
21
  ];
21
22
  //# sourceMappingURL=library-functions.js.map
@@ -132,6 +132,32 @@ const ReadFunctionsWithMore = [
132
132
  { package: 'tuneR', name: 'readMidi', argIdx: 0, argName: 'file', resolveValue: true },
133
133
  { package: 'seewave', name: 'read.audacity', argIdx: 0, argName: 'file', resolveValue: true },
134
134
  { package: 'audio', name: 'load.wave', argIdx: 0, argName: 'where', resolveValue: true },
135
+ /* geospatial (no `raster::stack`: only the name is matched on and `utils::stack` shares it) */
136
+ { package: 'terra', name: 'rast', argIdx: 0, argName: 'x', resolveValue: true },
137
+ { package: 'terra', name: 'vect', argIdx: 0, argName: 'x', resolveValue: true },
138
+ { package: 'raster', name: 'raster', argIdx: 0, argName: 'x', resolveValue: true },
139
+ { package: 'raster', name: 'brick', argIdx: 0, argName: 'x', resolveValue: true },
140
+ { package: 'raster', name: 'shapefile', argIdx: 0, argName: 'x', resolveValue: true },
141
+ { package: 'stars', name: 'read_stars', argIdx: 0, argName: '.x', resolveValue: true },
142
+ { package: 'stars', name: 'read_ncdf', argIdx: 0, argName: '.x', resolveValue: true },
143
+ { package: 'maptools', name: 'readShapeLines', argIdx: 0, argName: 'fn', resolveValue: true },
144
+ { package: 'maptools', name: 'readShapePoints', argIdx: 0, argName: 'fn', resolveValue: true },
145
+ { package: 'maptools', name: 'readShapeSpatial', argIdx: 0, argName: 'fn', resolveValue: true },
146
+ /* array / binary science formats */
147
+ { package: 'ncdf4', name: 'nc_open', argIdx: 0, argName: 'filename', resolveValue: true },
148
+ { package: 'RNetCDF', name: 'open.nc', argIdx: 0, argName: 'con', resolveValue: true },
149
+ { package: 'R.matlab', name: 'readMat', argIdx: 0, argName: 'con', resolveValue: true },
150
+ { package: 'rhdf5', name: 'h5read', argIdx: 0, argName: 'file', resolveValue: true },
151
+ { package: 'rhdf5', name: 'h5ls', argIdx: 0, argName: 'file', resolveValue: true },
152
+ { package: 'fst', name: 'read_fst', argIdx: 0, argName: 'path', resolveValue: true },
153
+ { package: 'qs', name: 'qread', argIdx: 0, argName: 'file', resolveValue: true },
154
+ { package: 'yaml', name: 'read_yaml', argIdx: 0, argName: 'file', resolveValue: true, ignoreIf: 'arg-set', additionalArgs: { argSet: { argName: 'text' } } },
155
+ /* phylogeny / sequence */
156
+ { package: 'ape', name: 'read.nexus', argIdx: 0, argName: 'file', resolveValue: true },
157
+ { package: 'ape', name: 'read.nexus.data', argIdx: 0, argName: 'file', resolveValue: true },
158
+ { package: 'ape', name: 'read.dna', argIdx: 0, argName: 'file', resolveValue: true },
159
+ { package: 'ape', name: 'read.FASTA', argIdx: 0, argName: 'file', resolveValue: true },
160
+ { package: 'seqinr', name: 'read.fasta', argIdx: 0, argName: 'file', resolveValue: true },
135
161
  /* shinyjs - loads an external JavaScript file */
136
162
  { package: 'shinyjs', name: 'extendShinyjs', argIdx: 0, argName: 'script', resolveValue: true, ignoreIf: 'arg-missing' }
137
163
  ];
@@ -1,4 +1,6 @@
1
1
  import type { FunctionInfo } from './function-info';
2
2
  import type { LinkToNestedCall } from '../../call-context-query/call-context-query-format';
3
+ /** the assertion helpers of the test frameworks; each hands its input back invisibly, so none reaches stdout */
4
+ export declare const ExpectFunctionNames: RegExp;
3
5
  export declare const ExpectFunctions: LinkToNestedCall;
4
6
  export declare const TestFunctions: FunctionInfo[];
@@ -1,38 +1,40 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.TestFunctions = exports.ExpectFunctions = void 0;
3
+ exports.TestFunctions = exports.ExpectFunctions = exports.ExpectFunctionNames = void 0;
4
+ /** the assertion helpers of the test frameworks; each hands its input back invisibly, so none reaches stdout */
5
+ exports.ExpectFunctionNames = new RegExp(/* testthat */ '^(expect_equal|expect_identical|expect_error|expect_warning|expect_message|expect_condition|' +
6
+ 'expect_true|expect_false|expect_all_equal|expect_all_true|expect_all_false|expect_lt|expect_lte|expect_gt|expect_gte|' +
7
+ 'expect_length|expect_shape|expect_match|expect_no_match|expect_named|expect_null|expect_setequal|expect_mapequal|' +
8
+ 'expect_contains|expect_in|expect_disjoint|expect_type|expect_s3_class|expect_s4_class|expect_r6_class|expect_s7_class|' +
9
+ 'expect_vector|expect_no_error|expect_no_warning|expect_no_message|expect_no_condition|expect_invisible|expect_visible|' +
10
+ 'expect_output|expect_silent|expect_snapshot|expect_snapshot_value|expect_snapshot_file|announce_snapshot_file|' +
11
+ 'compare_file_binary|compare_file_text|snapshot_accept|snapshot_reject|snapshot_review|' +
12
+ 'fail|pass|expect_success|expect_failure|expect_snapshot_failure|show_failure|' +
13
+ /* tinytest */
14
+ 'exit_file|exit_if_not|expect_equal|expect_identical|expect_equivalent|expect_true|expect_false|expect_silent|expect_null|' +
15
+ 'expect_inherits|expect_error|expect_warning|expect_message|expect_stdout|expect_equal_to_reference|' +
16
+ 'expect_equivalent_to_reference|expect_length|expect_match|ignore|report_side_effects|' +
17
+ /* testit */
18
+ 'assert|' +
19
+ /* RUnit */
20
+ 'checkEquals|checkEqualsNumeric|checkIdentical|checkTrue|checkException|' +
21
+ /* checkmate */
22
+ 'assertAccess|assert_access|assertArray|assert_array|assert_atomic|assertAtomic|assert_atomic_vector|assertAtomicVector|' +
23
+ 'assert_character|assertCharacter|assert_choice|assertChoice|assert_class|assertClass|assert_complex|assertComplex|' +
24
+ 'assert_count|assertCount|assert_data_frame|assertDataFrame|assert_data_table|assertDataTable|assert_date|assertDate|' +
25
+ 'assert_directory|assertDirectory|assert_directory_exists|assertDirectoryExists|assert_disjunct|assertDisjunct|assert_double|' +
26
+ 'assertDouble|assert_environment|assertEnvironment|assert_factor|assertFactor|assert_false|assertFalse|assert_file|assertFile|' +
27
+ 'assert_file_exists|assertFileExists|assert_flag|assertFlag|assert_formula|assertFormula|assert_function|assertFunction|' +
28
+ 'assert_int|assertInt|assert_integer|assertInteger|assert_list|assertList|assert_logical|assertLogical|assert_matrix|' +
29
+ 'assertMatrix|assert_multi_class|assertMultiClass|assert_named|assertNamed|assert_names|assertNames|assert_null|assertNull|' +
30
+ 'assert_number|assertNumber|assert_numeric|assertNumeric|assert_os|assertOs|assert_path_for_output|assertPathForOutput|' +
31
+ 'assert_permutation|assertPermutation|assert_posixct|assertPOSIXct|assert_r6|assertR6|assert_raw|assertRaw|assert_scalar|' +
32
+ 'assertScalar|assert_scalar_na|assertScalarNA|assert_set_equal|assertSetEqual|assert_string|assertString|assert_subset|' +
33
+ 'assertSubset|assert_tibble|assertTibble|assert_true|assertTrue|assert_vector|assertVector' +
34
+ ')$');
4
35
  exports.ExpectFunctions = {
5
36
  type: 'link-to-nested-call',
6
- callName: new RegExp(/* testthat */ '^(expect_equal|expect_identical|expect_error|expect_warning|expect_message|expect_condition|' +
7
- 'expect_true|expect_false|expect_all_equal|expect_all_true|expect_all_false|expect_lt|expect_lte|expect_gt|expect_gte|' +
8
- 'expect_length|expect_shape|expect_match|expect_no_match|expect_named|expect_null|expect_setequal|expect_mapequal|' +
9
- 'expect_contains|expect_in|expect_disjoint|expect_type|expect_s3_class|expect_s4_class|expect_r6_class|expect_s7_class|' +
10
- 'expect_vector|expect_no_error|expect_no_warning|expect_no_message|expect_no_condition|expect_invisible|expect_visible|' +
11
- 'expect_output|expect_silent|expect_snapshot|expect_snapshot_value|expect_snapshot_file|announce_snapshot_file|' +
12
- 'compare_file_binary|compare_file_text|snapshot_accept|snapshot_reject|snapshot_review|' +
13
- 'fail|pass|expect_success|expect_failure|expect_snapshot_failure|show_failure|' +
14
- /* tinytest */
15
- 'exit_file|exit_if_not|expect_equal|expect_identical|expect_equivalent|expect_true|expect_false|expect_silent|expect_null|' +
16
- 'expect_inherits|expect_error|expect_warning|expect_message|expect_stdout|expect_equal_to_reference|' +
17
- 'expect_equivalent_to_reference|expect_length|expect_match|ignore|report_side_effects|' +
18
- /* testit */
19
- 'assert|' +
20
- /* RUnit */
21
- 'checkEquals|checkEqualsNumeric|checkIdentical|checkTrue|checkException|' +
22
- /* checkmate */
23
- 'assertAccess|assert_access|assertArray|assert_array|assert_atomic|assertAtomic|assert_atomic_vector|assertAtomicVector|' +
24
- 'assert_character|assertCharacter|assert_choice|assertChoice|assert_class|assertClass|assert_complex|assertComplex|' +
25
- 'assert_count|assertCount|assert_data_frame|assertDataFrame|assert_data_table|assertDataTable|assert_date|assertDate|' +
26
- 'assert_directory|assertDirectory|assert_directory_exists|assertDirectoryExists|assert_disjunct|assertDisjunct|assert_double|' +
27
- 'assertDouble|assert_environment|assertEnvironment|assert_factor|assertFactor|assert_false|assertFalse|assert_file|assertFile|' +
28
- 'assert_file_exists|assertFileExists|assert_flag|assertFlag|assert_formula|assertFormula|assert_function|assertFunction|' +
29
- 'assert_int|assertInt|assert_integer|assertInteger|assert_list|assertList|assert_logical|assertLogical|assert_matrix|' +
30
- 'assertMatrix|assert_multi_class|assertMultiClass|assert_named|assertNamed|assert_names|assertNames|assert_null|assertNull|' +
31
- 'assert_number|assertNumber|assert_numeric|assertNumeric|assert_os|assertOs|assert_path_for_output|assertPathForOutput|' +
32
- 'assert_permutation|assertPermutation|assert_posixct|assertPOSIXct|assert_r6|assertR6|assert_raw|assertRaw|assert_scalar|' +
33
- 'assertScalar|assert_scalar_na|assertScalarNA|assert_set_equal|assertSetEqual|assert_string|assertString|assert_subset|' +
34
- 'assertSubset|assert_tibble|assertTibble|assert_true|assertTrue|assert_vector|assertVector' +
35
- ')$')
37
+ callName: exports.ExpectFunctionNames
36
38
  };
37
39
  const ContextFunctions = {
38
40
  type: 'link-to-last-call',
@@ -128,7 +128,26 @@ const WriteFunctionsWithMore = [
128
128
  { package: 'av', name: 'av_capture_graphics', argIdx: 1, argName: 'output', resolveValue: true },
129
129
  { package: 'tuneR', name: 'writeWave', argIdx: 1, argName: 'filename', resolveValue: true },
130
130
  { package: 'seewave', name: 'savewav', argName: 'filename', resolveValue: true, defaultValue: '<wave-name>' },
131
- { package: 'audio', name: 'save.wave', argIdx: 1, argName: 'where', resolveValue: true }
131
+ { package: 'audio', name: 'save.wave', argIdx: 1, argName: 'where', resolveValue: true },
132
+ /* geospatial */
133
+ { package: 'terra', name: 'writeRaster', argIdx: 1, argName: 'filename', resolveValue: true },
134
+ { package: 'terra', name: 'writeVector', argIdx: 1, argName: 'filename', resolveValue: true },
135
+ { package: 'terra', name: 'writeCDF', argIdx: 1, argName: 'filename', resolveValue: true },
136
+ { package: 'raster', name: 'writeRaster', argIdx: 1, argName: 'filename', resolveValue: true },
137
+ { package: 'stars', name: 'write_stars', argIdx: 1, argName: 'dsn', resolveValue: true },
138
+ /* array / binary science formats */
139
+ { package: 'ncdf4', name: 'nc_create', argIdx: 0, argName: 'filename', resolveValue: true },
140
+ { package: 'RNetCDF', name: 'create.nc', argIdx: 0, argName: 'filename', resolveValue: true },
141
+ { package: 'R.matlab', name: 'writeMat', argIdx: 0, argName: 'con', resolveValue: true },
142
+ { package: 'rhdf5', name: 'h5write', argIdx: 1, argName: 'file', resolveValue: true },
143
+ { package: 'rhdf5', name: 'h5createFile', argIdx: 0, argName: 'file', resolveValue: true },
144
+ { package: 'fst', name: 'write_fst', argIdx: 1, argName: 'path', resolveValue: true },
145
+ { package: 'qs', name: 'qsave', argIdx: 1, argName: 'file', resolveValue: true },
146
+ { package: 'yaml', name: 'write_yaml', argIdx: 1, argName: 'file', resolveValue: true },
147
+ /* phylogeny / sequence */
148
+ { package: 'ape', name: 'write.dna', argIdx: 1, argName: 'file', resolveValue: true },
149
+ { package: 'ape', name: 'write.nexus.data', argIdx: 1, argName: 'file', resolveValue: true },
150
+ { package: 'seqinr', name: 'write.fasta', argIdx: 2, argName: 'file.out', resolveValue: true }
132
151
  ];
133
152
  exports.WriteFunctions = [
134
153
  ...WriteFunctionsWithMore,
@@ -266,7 +266,7 @@ async function executeGuessDepVersionsQuery({ analyzer }, queries) {
266
266
  }
267
267
  }
268
268
  const assignments = query.explode
269
- ? [...(0, dependency_version_space_1.assignmentsOf)(ordered, query.explode.limit ?? dependency_version_space_1.DefaultExplodeLimit)].map(a => ({ versions: Object.fromEntries(a.versions) }))
269
+ ? [...(0, dependency_version_space_1.assignmentsOf)(ordered, query.explode.limit ?? dependency_version_space_1.DefaultExplodeLimit, (0, dependency_version_space_1.declaredDependenciesOf)(space))].map(a => ({ versions: Object.fromEntries(a.versions) }))
270
270
  : undefined;
271
271
  return (0, objects_1.compactRecord)({
272
272
  '.meta': { timing: Date.now() - start },
@@ -39,7 +39,7 @@ export interface GuessExplodeOptions {
39
39
  readonly order?: 'newest' | 'oldest';
40
40
  /** a version to prefer per dependency when it survives the constraints (package name to version) */
41
41
  readonly prefer?: Readonly<Record<string, VersionString>>;
42
- /** cap the number of assignments produced */
42
+ /** cap the number of combinations considered; the ones that cannot be loaded together are skipped, not returned */
43
43
  readonly limit?: number;
44
44
  }
45
45
  /** one concrete version choice per resolvable dependency (`package -> version`) */
@@ -374,7 +374,7 @@ exports.GuessDepVersionsQueryDefinition = {
374
374
  explode: joi_1.default.object({
375
375
  order: joi_1.default.string().valid('newest', 'oldest').optional().description('Iterate each dependency newest-first (default) or oldest-first.'),
376
376
  prefer: joi_1.default.object().pattern(joi_1.default.string(), joi_1.default.string()).optional().description('A version to prefer per dependency when it survives the constraints.'),
377
- limit: joi_1.default.number().integer().min(0).optional().description('Cap the number of concrete assignments produced.')
377
+ limit: joi_1.default.number().integer().min(0).optional().description('Cap the number of version combinations considered. Combinations whose versions cannot be loaded together are skipped, so fewer assignments may come out.')
378
378
  }).optional().description('Also explode the guessed space into concrete per-dependency version assignments.')
379
379
  }).description('Guesses the possible version range of every dependency from declared constraints and signature-database usage.'),
380
380
  flattenInvolvedNodes: () => []
@@ -14,8 +14,9 @@ exports.HappensBeforeQueryDefinition = {
14
14
  asciiSummarizer: (formatter, _analyzer, queryResults, result) => {
15
15
  const out = queryResults;
16
16
  result.push(`Query: ${(0, ansi_1.bold)('happens-before', formatter)} (${(0, time_1.printAsMs)(out['.meta'].timing, 0)})`);
17
- for (const [key, value] of Object.entries(out.results)) {
18
- result.push(` ╰ ${key}: ${value}`);
17
+ for (const [fingerprint, value] of Object.entries(out.results)) {
18
+ const { a, b } = JSON.parse(fingerprint);
19
+ result.push(` ╰ ${(0, ansi_1.bold)(a, formatter)} happens before ${(0, ansi_1.bold)(b, formatter)}: ${value}`);
19
20
  }
20
21
  return true;
21
22
  },
@@ -18,6 +18,7 @@ const SliceCriterionHelp = [
18
18
  ' <line>@[<n>]<name> the n-th occurrence of <name> in line <line> (e.g. 2@[2]x, 2@[-1]x)',
19
19
  ' <line>:<col> the element starting at line <line>, column <col> (e.g. 2:5)',
20
20
  ' <line>~<col> the innermost element containing line <line>, column <col> (e.g. 2~5)',
21
+ ' <line>^ the top-level statement line <line> belongs to (e.g. 2^)',
21
22
  ' $<id> the normalized node with the id <id> (e.g. $42)',
22
23
  'A negative <line> counts from the end; a trailing (file-regex) restricts to a file (e.g. 2@x(tmp/.*)).',
23
24
  `Append flags after the ")": ${(0, slice_query_parser_1.describeSliceFlags)(slice_query_parser_1.StaticSliceFlags)}.`,
@@ -565,7 +565,7 @@ export declare const flowrCapabilities: {
565
565
  readonly name: "Hooks";
566
566
  readonly id: "hooks";
567
567
  readonly supported: "partially";
568
- readonly description: "_Handle hooks like [`userhooks`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/userhooks.html) and [`on.exit`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/on.exit)._ We do not support hooks.";
568
+ readonly description: "_Handle hooks like [`userhooks`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/userhooks.html) and [`on.exit`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/on.exit)._ We support `on.exit` and rlang's [`on_load`/`run_on_load`/`on_package_load`](https://rlang.r-lib.org/reference/on_load.html), whose expressions we analyze where they are registered. `setHook` and the other user hooks are not modelled.";
569
569
  }, {
570
570
  readonly name: "Precedence";
571
571
  readonly id: "precedence";
@@ -715,7 +715,7 @@ ${await (0, doc_dfg_1.printDfGraphForCode)(parser, code, { simplified: true })}
715
715
  name: 'Hooks',
716
716
  id: 'hooks',
717
717
  supported: 'partially',
718
- description: '_Handle hooks like [`userhooks`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/userhooks.html) and [`on.exit`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/on.exit)._ We do not support hooks.'
718
+ description: '_Handle hooks like [`userhooks`](https://stat.ethz.ch/R-manual/R-devel/library/base/html/userhooks.html) and [`on.exit`](https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/on.exit)._ We support `on.exit` and rlang\'s [`on_load`/`run_on_load`/`on_package_load`](https://rlang.r-lib.org/reference/on_load.html), whose expressions we analyze where they are registered. `setHook` and the other user hooks are not modelled.'
719
719
  },
720
720
  {
721
721
  name: 'Precedence',
@@ -6,7 +6,7 @@ type FileFilterSuffix = '' | `(${string})`;
6
6
  * Either `line:column`, `line~column`, `line@variable-name`, or `$id`; all but `$id` accept a trailing
7
7
  * `(file-regex)`. See {@link SlicingCriterion.tryParse} for what each of them resolves to.
8
8
  */
9
- export type SlicingCriterion = `${number}:${number}${FileFilterSuffix}` | `${number}~${number}${FileFilterSuffix}` | `${number}@${string}` | `$${NodeId | number}`;
9
+ export type SlicingCriterion = `${number}:${number}${FileFilterSuffix}` | `${number}~${number}${FileFilterSuffix}` | `${number}^${FileFilterSuffix}` | `${number}@${string}` | `$${NodeId | number}`;
10
10
  /**
11
11
  * The helper object associated with {@link SlicingCriterion} which makes it easy
12
12
  * to parse, validate and resolve slicing criteria.
@@ -33,6 +33,7 @@ export declare const SlicingCriterion: {
33
33
  * | `2@[3]x` | the 3rd occurrence of `x` in line 2 (by column); `[-1]` for the last |
34
34
  * | `2:5` | the element *starting* at line 2, column 5 |
35
35
  * | `2~5` | the innermost element *containing* line 2, column 5 |
36
+ * | `2^` | the top-level statement line 2 belongs to, the first one when several share the line |
36
37
  * | `$42` | the node with the normalized id 42 |
37
38
  *
38
39
  * A negative line counts from the end of the input (`-1` being the last line). Every criterion but `$id`
@@ -18,7 +18,7 @@ exports.SlicingCriterion = {
18
18
  * @see {@link SlicingCriterion.parse} to parse a slicing criterion to a node ID
19
19
  */
20
20
  isValid(criterion) {
21
- return typeof criterion === 'string' && criterion.match(/^\d+:\d+|\d+@.+|\$.+$/) !== null;
21
+ return typeof criterion === 'string' && /^(-?\d+([:~]\d+|\^|@.+)|\$.+)$/.test(criterion);
22
22
  },
23
23
  /**
24
24
  * Takes a criterion in the form of `line:column`, `line~column`, or `line@variable-name` and returns the corresponding node id
@@ -40,6 +40,7 @@ exports.SlicingCriterion = {
40
40
  * | `2@[3]x` | the 3rd occurrence of `x` in line 2 (by column); `[-1]` for the last |
41
41
  * | `2:5` | the element *starting* at line 2, column 5 |
42
42
  * | `2~5` | the innermost element *containing* line 2, column 5 |
43
+ * | `2^` | the top-level statement line 2 belongs to, the first one when several share the line |
43
44
  * | `$42` | the node with the normalized id 42 |
44
45
  *
45
46
  * A negative line counts from the end of the input (`-1` being the last line). Every criterion but `$id`
@@ -81,6 +82,10 @@ exports.SlicingCriterion = {
81
82
  const location = parseLocation(base, '~', idMap, file);
82
83
  return location && fuzzyLocationToId(location, idMap, file);
83
84
  }
85
+ else if (base.endsWith('^')) {
86
+ const line = parseLineNumber(base.slice(0, -1), idMap, file);
87
+ return line === undefined ? undefined : topLevelStatementToId(line, idMap, file);
88
+ }
84
89
  },
85
90
  /**
86
91
  * Converts a node id to a slicing criterion in the form of `$id`
@@ -149,6 +154,37 @@ function fuzzyLocationToId(location, dataflowIdMap, file) {
149
154
  // prefer the call over the symbol it refers to, exactly as locationToId does
150
155
  return (candidates.find(n => n.type === type_1.RType.FunctionCall) ?? candidates[0])?.info.id;
151
156
  }
157
+ /** Walks up to the statement `node` belongs to: the outermost node still below the root of its file. */
158
+ function enclosingTopLevelStatement(node, idMap) {
159
+ let current = node;
160
+ for (;;) {
161
+ const parent = current.info.parent !== undefined ? idMap.get(current.info.parent) : undefined;
162
+ if (parent === undefined || parent.info.parent === undefined) {
163
+ return current;
164
+ }
165
+ current = parent;
166
+ }
167
+ }
168
+ /**
169
+ * Resolves a `line^` criterion: the top-level statement covering the line, which is what has to be excised to
170
+ * remove that line from the program. Unlike {@link fuzzyLocationToId} this widens rather than narrows, so an
171
+ * inner sub-expression on the line never stands in for the statement carrying it.
172
+ */
173
+ function topLevelStatementToId(line, idMap, file) {
174
+ const potentials = [...idMap.values()].filter(nodeInfo => matchesFile(nodeInfo, file));
175
+ let best;
176
+ let bestRange;
177
+ for (const node of range_1.SourceRange.nodesContaining(potentials, line)) {
178
+ const statement = enclosingTopLevelStatement(node, idMap);
179
+ const range = range_1.SourceRange.fromNode(statement);
180
+ /* several statements may cover the line (`a <- 1; b <- 2`), the one starting first wins */
181
+ if (range !== undefined && (bestRange === undefined || range_1.SourceRange.compare(range, bestRange) < 0)) {
182
+ best = statement;
183
+ bestRange = range;
184
+ }
185
+ }
186
+ return best?.info.id;
187
+ }
152
188
  /**
153
189
  * Splits the optional trailing `(file-regex)` off a criterion (e.g. `2@x(tmp/.*)`), which restricts it to nodes
154
190
  * originating from a matching file. Returns `undefined` if the regex is malformed.
@@ -1,4 +1,4 @@
1
- import { type REnvironmentInformation } from '../../dataflow/environments/environment';
1
+ import type { REnvironmentInformation } from '../../dataflow/environments/environment';
2
2
  import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id';
3
3
  export type Fingerprint = string;
4
4
  /**