@eagleoutice/flowr 2.13.1 → 2.13.2

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 (74) hide show
  1. package/cli/flowr.js +21 -5
  2. package/cli/repl/commands/repl-commands.js +11 -9
  3. package/cli/repl/commands/repl-query.js +1 -1
  4. package/cli/repl/commands/repl-signature.js +8 -1
  5. package/cli/repl/core.js +13 -10
  6. package/cli/repl/print-version.js +1 -1
  7. package/cli/repl/server/connection.d.ts +1 -1
  8. package/cli/repl/server/net.js +15 -0
  9. package/config.d.ts +29 -0
  10. package/config.js +54 -2
  11. package/data/sigdb/sigdb.remote.json +1 -1
  12. package/dataflow/environments/identifier.d.ts +9 -8
  13. package/dataflow/environments/identifier.js +21 -13
  14. package/dataflow/eval/resolve/resolve-working-directory.d.ts +29 -0
  15. package/dataflow/eval/resolve/resolve-working-directory.js +168 -0
  16. package/dataflow/extractor.js +2 -1
  17. package/dataflow/graph/df-helper.d.ts +3 -2
  18. package/dataflow/graph/df-helper.js +11 -15
  19. package/dataflow/graph/diff-dataflow-graph.js +1 -1
  20. package/dataflow/graph/graph-helper.js +2 -6
  21. package/dataflow/graph/graph.d.ts +24 -0
  22. package/dataflow/graph/graph.js +25 -1
  23. package/documentation/wiki-linter.js +1 -0
  24. package/documentation/wiki-mk/doc-context.d.ts +10 -0
  25. package/documentation/wiki-mk/doc-context.js +3 -0
  26. package/documentation/wiki-signature-database.js +16 -6
  27. package/linter/linter-rules.d.ts +24 -2
  28. package/linter/linter-rules.js +3 -1
  29. package/linter/rules/absolute-path.d.ts +4 -4
  30. package/linter/rules/absolute-path.js +7 -5
  31. package/linter/rules/file-path-validity.d.ts +1 -1
  32. package/linter/rules/file-path-validity.js +48 -8
  33. package/linter/rules/function-finder-util.d.ts +2 -1
  34. package/linter/rules/syntactically-valid.d.ts +58 -0
  35. package/linter/rules/syntactically-valid.js +203 -0
  36. package/linter/rules/undefined-symbol.js +3 -2
  37. package/package.json +5 -4
  38. package/project/context/classify-project-kind.d.ts +40 -0
  39. package/project/context/classify-project-kind.js +76 -0
  40. package/project/context/flowr-analyzer-dependencies-context.d.ts +23 -4
  41. package/project/context/flowr-analyzer-dependencies-context.js +23 -1
  42. package/project/context/flowr-analyzer-files-context.d.ts +10 -8
  43. package/project/context/flowr-analyzer-files-context.js +26 -67
  44. package/project/context/flowr-file.d.ts +5 -0
  45. package/project/context/flowr-file.js +5 -0
  46. package/project/plugins/file-plugins/flowr-analyzer-rprofile-file-plugin.d.ts +12 -4
  47. package/project/plugins/file-plugins/flowr-analyzer-rprofile-file-plugin.js +25 -10
  48. package/project/plugins/plugin-registry.d.ts +2 -1
  49. package/project/plugins/plugin-registry.js +4 -1
  50. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.d.ts +57 -2
  51. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +150 -28
  52. package/project/sigdb/decompress.d.ts +1 -1
  53. package/project/sigdb/decompress.js +4 -1
  54. package/project/sigdb/manifest.js +60 -26
  55. package/project/sigdb/sigdb-download.d.ts +6 -7
  56. package/project/sigdb/sigdb-download.js +30 -9
  57. package/queries/catalog/dependencies-query/dependencies-query-format.d.ts +0 -10
  58. package/queries/catalog/dependencies-query/dependencies-query-format.js +0 -106
  59. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.js +1 -1
  60. package/queries/catalog/linter-query/linter-query-format.js +9 -2
  61. package/queries/catalog/signature-query/signature-query-executor.js +3 -0
  62. package/queries/catalog/signature-query/signature-query-render.js +4 -4
  63. package/queries/query.js +9 -2
  64. package/r-bridge/data/data.d.ts +5 -0
  65. package/r-bridge/data/data.js +6 -0
  66. package/r-bridge/retriever.js +6 -1
  67. package/r-bridge/shell.js +5 -0
  68. package/search/flowr-search-filters.d.ts +2 -1
  69. package/util/files.d.ts +6 -4
  70. package/util/files.js +30 -8
  71. package/util/mermaid/dfg.js +1 -1
  72. package/util/text/ansi.d.ts +7 -3
  73. package/util/text/ansi.js +8 -5
  74. package/util/version.js +4 -4
package/cli/flowr.js CHANGED
@@ -212,10 +212,26 @@ async function mainServer(useWebSocket) {
212
212
  const backend = useWebSocket ? new WebSocketServerWrapper() : new NetServer();
213
213
  await new FlowRServer(engines.engines, engines.default, options['r-session-access'], config, backend).start(options.port);
214
214
  }
215
- if (options.server) {
216
- void mainServer(options.ws);
217
- }
218
- else {
219
- void mainRepl();
215
+ async function main() {
216
+ try {
217
+ if (options.server) {
218
+ await mainServer(options.ws);
219
+ }
220
+ else {
221
+ await mainRepl();
222
+ }
223
+ }
224
+ catch (e) {
225
+ const err = e;
226
+ console.error(ansi_1.formatter.format(`flowR failed to start: ${err.message}`, { color: 1 /* Colors.Red */, effect: ansi_1.ColorEffect.Foreground, style: 1 /* FontStyles.Bold */ }));
227
+ if (options.verbose) {
228
+ console.error(err.stack);
229
+ }
230
+ else {
231
+ console.error((0, ansi_1.italic)('Run again with --verbose for the full stack trace.'));
232
+ }
233
+ (0, proc_1.exitSafe)(1);
234
+ }
220
235
  }
236
+ void main();
221
237
  //# sourceMappingURL=flowr.js.map
@@ -180,7 +180,6 @@ function getReplCommands() {
180
180
  if (commandsInitialized) {
181
181
  return _commands;
182
182
  }
183
- commandsInitialized = true;
184
183
  for (const [script, { target, description, type, options }] of Object.entries(scripts_info_1.scripts)) {
185
184
  if (type === 'master script') {
186
185
  _commands[script] = {
@@ -204,6 +203,7 @@ function getReplCommands() {
204
203
  };
205
204
  }
206
205
  }
206
+ commandsInitialized = true;
207
207
  return _commands;
208
208
  }
209
209
  /**
@@ -219,18 +219,20 @@ let commandNames = undefined;
219
219
  // maps command names or aliases to the actual command name
220
220
  let commandMapping = undefined;
221
221
  function initCommandMapping() {
222
- commandMapping = {};
223
- commandNames = [];
222
+ const mapping = {};
223
+ const names = [];
224
224
  for (const [command, { aliases }] of Object.entries(getReplCommands())) {
225
- (0, assert_1.guard)(commandMapping[command] === undefined, `Command ${command} is already registered!`);
226
- commandMapping[command] = command;
225
+ (0, assert_1.guard)(mapping[command] === undefined, `Command ${command} is already registered!`);
226
+ mapping[command] = command;
227
227
  for (const alias of aliases) {
228
- (0, assert_1.guard)(commandMapping[alias] === undefined, `Command (alias) ${alias} is already registered!`);
229
- commandMapping[alias] = command;
228
+ (0, assert_1.guard)(mapping[alias] === undefined, `Command (alias) ${alias} is already registered!`);
229
+ mapping[alias] = command;
230
230
  }
231
- commandNames.push(command);
232
- commandNames.push(...aliases);
231
+ names.push(command);
232
+ names.push(...aliases);
233
233
  }
234
+ commandMapping = mapping;
235
+ commandNames = names;
234
236
  }
235
237
  /**
236
238
  * Get the command for a given command name or alias.
@@ -61,7 +61,7 @@ function printQueryDoc(output, name) {
61
61
  output.stdout(`Run: ${(0, ansi_1.bold)(':query ' + syntax, output.formatter)}`);
62
62
  output.stdout(`JSON: ${(0, ansi_1.italic)(queryTemplate(name, def.schema), output.formatter)}`);
63
63
  const wiki = `https://github.com/flowr-analysis/flowr/wiki/${encodeURIComponent((0, query_1.queryWikiPage)(def.title).replaceAll(' ', '-'))}`;
64
- output.stdout(`Docs: ${(0, ansi_1.supportsHyperlinks)() ? output.formatter.hyperlink(`${name} query`, wiki) : wiki}`);
64
+ output.stdout(`Docs: ${output.formatter.hyperlink(`${name} query`, wiki)}`);
65
65
  }
66
66
  /** A copy-pasteable JSON template for a query type: its `type` plus each required field as a placeholder. */
67
67
  function queryTemplate(type, schema) {
@@ -8,6 +8,7 @@ const query_1 = require("../../../queries/query");
8
8
  const signature_query_format_1 = require("../../../queries/catalog/signature-query/signature-query-format");
9
9
  const query_print_1 = require("../../../queries/query-print");
10
10
  const sigdb_download_1 = require("../../../project/sigdb/sigdb-download");
11
+ const config_1 = require("../../../config");
11
12
  const retriever_1 = require("../../../r-bridge/retriever");
12
13
  const signature_query_executor_1 = require("../../../queries/catalog/signature-query/signature-query-executor");
13
14
  /** treat the whole line as arguments, no R code to separate */
@@ -67,7 +68,13 @@ async function runDownload(output, analyzer, rest) {
67
68
  if (manifest) {
68
69
  await analyzer.context().deps.addDatabaseSource(manifest);
69
70
  analyzer.reset();
70
- output.stdout(`Mounted ${(0, ansi_1.bold)(manifest, f)} (will be available on next startup from the cache).`);
71
+ output.stdout(`Mounted ${(0, ansi_1.bold)(manifest, f)}.`);
72
+ }
73
+ try {
74
+ output.stdout(`Recorded in ${(0, ansi_1.bold)((0, config_1.persistSigDbPathToGlobalConfig)(dir), f)}; loads automatically on the next startup.`);
75
+ }
76
+ catch (e) {
77
+ output.stderr((0, ansi_1.italic)(`Could not update global config (${e.message}); add ${dir} to solver.sigdb.additionalPaths manually.`, f));
71
78
  }
72
79
  }
73
80
  catch (e) {
package/cli/repl/core.js CHANGED
@@ -246,10 +246,16 @@ async function executeStatement(output, statement, analyzer, allowRSessionAccess
246
246
  }
247
247
  if (statement.startsWith(':')) {
248
248
  const command = statement.slice(1).split(' ')[0].toLowerCase();
249
- const processor = (0, repl_commands_1.getCommand)(command);
250
249
  const bold = (s) => output.formatter.format(s, { style: 1 /* FontStyles.Bold */ });
251
- if (processor) {
252
- try {
250
+ const reportFailure = (e) => {
251
+ output.stderr(`${bold(`Failed to execute command ${command}`)}: ${e?.message}. Using the ${bold('--verbose')} flag on startup may provide additional information.\n`);
252
+ if (log_1.log.settings.minLevel < 6 /* LogLevel.Fatal */) {
253
+ console.error(e);
254
+ }
255
+ };
256
+ try {
257
+ const processor = (0, repl_commands_1.getCommand)(command);
258
+ if (processor) {
253
259
  await (0, query_1.genericWrapReplFailIfNoRequest)(async () => {
254
260
  const remainingLine = statement.slice(command.length + 2).trim();
255
261
  if (processor.isCodeCommand) {
@@ -265,15 +271,12 @@ async function executeStatement(output, statement, analyzer, allowRSessionAccess
265
271
  }
266
272
  }, output, analyzer);
267
273
  }
268
- catch (e) {
269
- output.stderr(`${bold(`Failed to execute command ${command}`)}: ${e?.message}. Using the ${bold('--verbose')} flag on startup may provide additional information.\n`);
270
- if (log_1.log.settings.minLevel < 6 /* LogLevel.Fatal */) {
271
- console.error(e);
272
- }
274
+ else {
275
+ output.stderr(`the command '${command}' is unknown, try ${bold(':help')} for more information\n`);
273
276
  }
274
277
  }
275
- else {
276
- output.stderr(`the command '${command}' is unknown, try ${bold(':help')} for more information\n`);
278
+ catch (e) {
279
+ reportFailure(e);
277
280
  }
278
281
  }
279
282
  else {
@@ -40,7 +40,7 @@ function sigDbSummaryString() {
40
40
  if (entries.length === 0) {
41
41
  return it('no sigdb');
42
42
  }
43
- const link = (text, file) => it(ansi_1.formatter.hyperlink(text, (0, node_url_1.pathToFileURL)(file).href));
43
+ const link = (text, file) => it(ansi_1.formatter.hyperlink(text, (0, node_url_1.pathToFileURL)(file).href, true));
44
44
  // if every ref shares the same date, print it once
45
45
  const shared = entries.every(e => e.date !== undefined && e.date === entries[0].date) ? entries[0].date : undefined;
46
46
  const refs = entries.map(e => link(shared === undefined && e.date !== undefined ? `${e.label} ${e.date}` : e.label, e.file));
@@ -1,5 +1,5 @@
1
1
  import type { Socket } from './net';
2
- import { type TREE_SITTER_DATAFLOW_PIPELINE, DEFAULT_SLICING_PIPELINE } from '../../../core/steps/pipeline/default-pipelines';
2
+ import { DEFAULT_SLICING_PIPELINE, type TREE_SITTER_DATAFLOW_PIPELINE } from '../../../core/steps/pipeline/default-pipelines';
3
3
  import type { PipelineOutput } from '../../../core/steps/pipeline/pipeline';
4
4
  import type { DeepPartial } from 'ts-essentials';
5
5
  import type { KnownParser, ParseStepOutput } from '../../../r-bridge/parser';
@@ -18,6 +18,7 @@ class WebSocketServerWrapper {
18
18
  }
19
19
  start(port) {
20
20
  this.server = new ws_1.WebSocketServer({ port, maxPayload: 1024 * 1024 * 1024 * 1024 });
21
+ this.server.on('error', (e) => reportListenFailure(port, e));
21
22
  server_1.serverLog.info('WebSocket-Server wrapper is active!');
22
23
  this.server.on('connection', c => this.connectHandler?.(new WebSocketWrapper(c)));
23
24
  }
@@ -56,8 +57,22 @@ class NetServer {
56
57
  this.server.on('connection', handler);
57
58
  }
58
59
  start(port) {
60
+ this.server.on('error', (e) => reportListenFailure(port, e));
59
61
  this.server.listen(port);
60
62
  }
61
63
  }
62
64
  exports.NetServer = NetServer;
65
+ /** Log a clear, actionable message for a server that failed to bind its port, then exit (there is nothing left to serve). */
66
+ function reportListenFailure(port, e) {
67
+ if (e.code === 'EADDRINUSE') {
68
+ server_1.serverLog.error(`Port ${port} is already in use. Pick another port with --port <number> or stop the process using it.`);
69
+ }
70
+ else if (e.code === 'EACCES') {
71
+ server_1.serverLog.error(`Not allowed to listen on port ${port} (permission denied). Try a port above 1024 with --port <number>.`);
72
+ }
73
+ else {
74
+ server_1.serverLog.error(`Failed to start the server on port ${port}: ${e.message}`);
75
+ }
76
+ process.exit(1);
77
+ }
63
78
  //# sourceMappingURL=net.js.map
package/config.d.ts CHANGED
@@ -156,6 +156,8 @@ export interface FlowrConfig extends MergeableRecord {
156
156
  readonly project: {
157
157
  /** Whether to resolve unknown paths loaded by the r project disk when trying to source/analyze files */
158
158
  resolveUnknownPathsOnDisk: boolean;
159
+ /** Whether a directory that cannot be traversed during file discovery (e.g. due to permissions) aborts the analysis; when `false` (the default) such paths are logged and skipped. */
160
+ failOnInaccessiblePath?: boolean;
159
161
  /** Overwrite the {@link ProjectKind} flowR would otherwise infer from the analyzed files, e.g. when auto-detection guesses wrong. */
160
162
  useProjectType?: ProjectKind;
161
163
  /**
@@ -170,6 +172,29 @@ export interface FlowrConfig extends MergeableRecord {
170
172
  * {@link FlowrConfig.specializeConfig}.
171
173
  */
172
174
  implicitSources?: string[];
175
+ /** Scoping options for the default project discovery. */
176
+ discovery?: {
177
+ /** Collect every file below the project root (greedy) instead of only the files the detected {@link ProjectKind} needs (default `false`). */
178
+ full?: boolean;
179
+ /** Per-{@link ProjectKind} include/exclude glob overrides layered on the default scoping. */
180
+ perKind?: Partial<Record<ProjectKind, {
181
+ include?: string[];
182
+ exclude?: string[];
183
+ }>>;
184
+ /** Case-insensitive globs that drop matching files from the intelligent discovery, regardless of kind (e.g. `.Renviron` to ignore environment files). */
185
+ ignore?: string[];
186
+ };
187
+ /** Overrides for the signals flowR uses to classify the {@link ProjectKind}; unset fields keep the built-in defaults. */
188
+ classification?: {
189
+ /** DESCRIPTION `Type:` values that mark a shiny app (default `shiny`, `shiny-app`, `shinyapp`). */
190
+ shinyDescriptionTypes?: string[];
191
+ /** File names a shiny app is assembled from (default `app.R`, `ui.R`, `server.R`, `global.R`). */
192
+ shinyEntryFiles?: string[];
193
+ /** Regex source evidencing shiny usage in an entry file. */
194
+ shinyUsagePattern?: string;
195
+ /** File extensions marking a notebook (default `ipynb`, `rmd`, `qmd`, `rnw`). */
196
+ notebookExtensions?: string[];
197
+ };
173
198
  };
174
199
  /** Linter configuration, usually specialized per {@link ProjectKind} via {@link FlowrConfig.specializeConfig}. */
175
200
  readonly linter: {
@@ -425,3 +450,7 @@ export declare const FlowrConfig: {
425
450
  */
426
451
  readonly setInConfigInPlace: <Path extends ValidFlowrConfigPaths>(this: void, config: FlowrConfig, key: Path, value: PathValue<FlowrConfig, Path>) => void;
427
452
  };
453
+ /** Path to the user-global `flowr.json`, read as a fallback when no project config is found. */
454
+ export declare function globalConfigFilePath(): string;
455
+ /** Persist `dbPath` into `solver.sigdb.additionalPaths` in the global config (creating it, preserving the user's raw JSON); idempotent, returns the file written. */
456
+ export declare function persistSigDbPathToGlobalConfig(dbPath: string): string;
package/config.js CHANGED
@@ -6,9 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.FlowrConfig = exports.FlowrDefaultPlugins = exports.DefaultAssumedRVersion = exports.DropPathsOption = exports.InferWorkingDirectory = exports.VersionSelection = exports.VariableResolve = void 0;
7
7
  exports.isSigDbEnabled = isSigDbEnabled;
8
8
  exports.resolveAssumedRVersion = resolveAssumedRVersion;
9
+ exports.globalConfigFilePath = globalConfigFilePath;
10
+ exports.persistSigDbPathToGlobalConfig = persistSigDbPathToGlobalConfig;
9
11
  const objects_1 = require("./util/objects");
10
12
  const path_1 = __importDefault(require("path"));
11
13
  const fs_1 = __importDefault(require("fs"));
14
+ const os_1 = __importDefault(require("os"));
12
15
  const log_1 = require("./util/log");
13
16
  const files_1 = require("./util/files");
14
17
  const joi_1 = __importDefault(require("joi"));
@@ -208,7 +211,8 @@ exports.FlowrConfig = {
208
211
  showPlugins: false,
209
212
  },
210
213
  project: {
211
- resolveUnknownPathsOnDisk: true
214
+ resolveUnknownPathsOnDisk: true,
215
+ failOnInaccessiblePath: false
212
216
  },
213
217
  linter: {
214
218
  disabledRules: []
@@ -294,9 +298,24 @@ exports.FlowrConfig = {
294
298
  }).description('Configuration options for the REPL.'),
295
299
  project: joi_1.default.object({
296
300
  resolveUnknownPathsOnDisk: joi_1.default.boolean().optional().description('Whether to resolve unknown paths loaded by the r project disk when trying to source/analyze files.'),
301
+ failOnInaccessiblePath: joi_1.default.boolean().optional().description('Whether a directory that cannot be traversed during file discovery (e.g. due to permissions) aborts the analysis; when false (the default) such paths are logged and skipped.'),
297
302
  basePackages: joi_1.default.array().items(joi_1.default.string()).optional().description('The packages considered part of R itself (base and recommended); if unset, flowR uses its built-in list.'),
298
303
  implicitSources: joi_1.default.array().items(joi_1.default.string()).optional().description('Files a framework loads on its own, without any source() call (e.g. global.R in a shiny app), in the order they are loaded; flowR orders the matching project files accordingly and analyzes them as one program. Entries are case-insensitive globs matched against the file path, a plain name matches any file with that name, and entries matching no project file are warned about. Usually set per project kind via specializeConfig.'),
299
- useProjectType: joi_1.default.string().valid(...Object.values(project_kind_1.ProjectKind)).optional().description('Overwrite the project kind flowR would otherwise infer from the analyzed files, e.g. when auto-detection guesses wrong.')
304
+ useProjectType: joi_1.default.string().valid(...Object.values(project_kind_1.ProjectKind)).optional().description('Overwrite the project kind flowR would otherwise infer from the analyzed files, e.g. when auto-detection guesses wrong.'),
305
+ discovery: joi_1.default.object({
306
+ full: joi_1.default.boolean().optional().description('Collect every file below the project root (greedy) instead of only the files the detected project kind needs (default false).'),
307
+ perKind: joi_1.default.object().pattern(joi_1.default.string().valid(...Object.values(project_kind_1.ProjectKind)), joi_1.default.object({
308
+ include: joi_1.default.array().items(joi_1.default.string()).optional(),
309
+ exclude: joi_1.default.array().items(joi_1.default.string()).optional()
310
+ })).optional().description('Per-kind include/exclude glob overrides layered on the default scoping.'),
311
+ ignore: joi_1.default.array().items(joi_1.default.string()).optional().description('Case-insensitive globs that drop matching files from the intelligent discovery, regardless of kind (e.g. .Renviron to ignore environment files).')
312
+ }).optional().description('Scoping options for the default project discovery.'),
313
+ classification: joi_1.default.object({
314
+ shinyDescriptionTypes: joi_1.default.array().items(joi_1.default.string()).optional().description('DESCRIPTION Type: values that mark a shiny app.'),
315
+ shinyEntryFiles: joi_1.default.array().items(joi_1.default.string()).optional().description('File names a shiny app is assembled from.'),
316
+ shinyUsagePattern: joi_1.default.string().optional().description('Regex source evidencing shiny usage in an entry file.'),
317
+ notebookExtensions: joi_1.default.array().items(joi_1.default.string()).optional().description('File extensions marking a notebook.')
318
+ }).optional().description('Overrides for the signals flowR uses to classify the project kind.')
300
319
  }).description('Project specific configuration options.'),
301
320
  linter: joi_1.default.object({
302
321
  disabledRules: joi_1.default.array().items(joi_1.default.string()).description('Linting rule names excluded from the default rule set (a rule requested explicitly via a linter query still runs). Usually set per project kind via specializeConfig.')
@@ -485,6 +504,31 @@ exports.FlowrConfig = {
485
504
  object_path_1.default.set(config, key, value);
486
505
  },
487
506
  };
507
+ /** Path to the user-global `flowr.json`, read as a fallback when no project config is found. */
508
+ function globalConfigFilePath() {
509
+ const base = process.env.FLOWR_CONFIG_HOME
510
+ ?? (process.env.XDG_CONFIG_HOME ? path_1.default.join(process.env.XDG_CONFIG_HOME, 'flowr') : undefined)
511
+ ?? (process.env.APPDATA ? path_1.default.join(process.env.APPDATA, 'flowr') : undefined)
512
+ ?? path_1.default.join(os_1.default.homedir?.() || os_1.default.tmpdir(), '.config', 'flowr');
513
+ return path_1.default.join(base, 'flowr.json');
514
+ }
515
+ /** Persist `dbPath` into `solver.sigdb.additionalPaths` in the global config (creating it, preserving the user's raw JSON); idempotent, returns the file written. */
516
+ function persistSigDbPathToGlobalConfig(dbPath) {
517
+ const file = globalConfigFilePath();
518
+ let raw = {};
519
+ try {
520
+ raw = fs_1.default.existsSync(file) ? JSON.parse(fs_1.default.readFileSync(file, 'utf-8')) : {};
521
+ }
522
+ catch (e) {
523
+ log_1.log.warn(`Could not read global config ${file}, recreating it: ${e.message}`);
524
+ }
525
+ const current = object_path_1.default.get(raw, 'solver.sigdb.additionalPaths');
526
+ const paths = Array.isArray(current) ? current : [];
527
+ object_path_1.default.set(raw, 'solver.sigdb.additionalPaths', [...new Set([...paths, dbPath])]);
528
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
529
+ fs_1.default.writeFileSync(file, JSON.stringify(raw, null, '\t') + '\n');
530
+ return file;
531
+ }
488
532
  function loadConfigFromFile(configFile, workingDirectory) {
489
533
  if (configFile !== undefined) {
490
534
  if (path_1.default.isAbsolute(configFile) && fs_1.default.existsSync(configFile)) {
@@ -510,6 +554,14 @@ function loadConfigFromFile(configFile, workingDirectory) {
510
554
  searchPath = (0, files_1.getParentDirectory)(searchPath);
511
555
  } while (fs_1.default.existsSync(searchPath));
512
556
  }
557
+ const global = globalConfigFilePath();
558
+ if (fs_1.default.existsSync(global)) {
559
+ const ret = exports.FlowrConfig.parse(fs_1.default.readFileSync(global, { encoding: 'utf-8' }));
560
+ if (ret) {
561
+ log_1.log.info(`Using global config ${global}`);
562
+ return ret;
563
+ }
564
+ }
513
565
  log_1.log.info('Using default config');
514
566
  return exports.FlowrConfig.default();
515
567
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "format": "flowr-sigdb-remote",
3
- "schema": 1,
3
+ "schema": 2,
4
4
  "tag": "v2.12.3",
5
5
  "repo": "flowr-analysis/flowr",
6
6
  "shards": {
@@ -112,17 +112,18 @@ export declare const Identifier: {
112
112
  */
113
113
  readonly toArray: (this: void, id: Identifier) => [BrandedIdentifier, BrandedNamespace | undefined, boolean | undefined];
114
114
  /**
115
- * The qualified identifier of a call from its dataflow {@link Origin}s (via `getOriginInDfg`), if it
116
- * resolves to an export of a loaded package (the signature-database info attached by `library()`/`use()`);
117
- * `undefined` otherwise. With `purrr` loaded, `map()` yields `Identifier.make('map', 'purrr')`.
115
+ * The package-qualified identifier of a call, resolved in order of decreasing certainty:
116
+ * 1. a package export the {@link Origin|origins} resolve to (`map()` with `purrr` loaded yields `purrr::map`),
117
+ * 2. an already-namespaced `name` returned unchanged (an explicit `pkg::fn` call),
118
+ * 3. with `qualifyBaseR`, a bare base-R call qualified from its exporting package via {@link baseRExportOwner}
119
+ * (`sd` yields `stats::sd`), needing no loaded database or graph edge and skipped when the call resolves to
120
+ * a user definition, so a local `sd()` stays bare.
118
121
  *
119
- * Pass the call's `name` to additionally get *edge-free* base-R qualification: a bare base call is qualified
120
- * from the base package that exports it (`sd` yields `stats::sd`, `plot` yields `base::plot`) via the
121
- * precomputed {@link baseRExportOwner} store -- no loaded database, no graph edges. This is suppressed when
122
- * the call resolves to a user definition or is already namespaced, so a local `sd()` is never `stats::sd`.
122
+ * Returns `undefined` when none apply. Steps 2 and 3 need the call's `name`.
123
+ * @param qualifyBaseR - whether to also qualify a bare base-R call from its exporting package (default `true`)
123
124
  * @see {@link Dataflow.qualify} - the compact form, if you have the call's id and its graph
124
125
  */
125
- readonly toQualified: (this: void, origins: readonly Origin[] | undefined, name?: Identifier) => Identifier | undefined;
126
+ readonly toQualified: (this: void, origins: readonly Origin[] | undefined, name?: Identifier, qualifyBaseR?: boolean) => Identifier | undefined;
126
127
  };
127
128
  /**
128
129
  * Well-known R package names used in {@link DefaultBuiltinConfig}.
@@ -192,32 +192,40 @@ exports.Identifier = {
192
192
  }
193
193
  },
194
194
  /**
195
- * The qualified identifier of a call from its dataflow {@link Origin}s (via `getOriginInDfg`), if it
196
- * resolves to an export of a loaded package (the signature-database info attached by `library()`/`use()`);
197
- * `undefined` otherwise. With `purrr` loaded, `map()` yields `Identifier.make('map', 'purrr')`.
195
+ * The package-qualified identifier of a call, resolved in order of decreasing certainty:
196
+ * 1. a package export the {@link Origin|origins} resolve to (`map()` with `purrr` loaded yields `purrr::map`),
197
+ * 2. an already-namespaced `name` returned unchanged (an explicit `pkg::fn` call),
198
+ * 3. with `qualifyBaseR`, a bare base-R call qualified from its exporting package via {@link baseRExportOwner}
199
+ * (`sd` yields `stats::sd`), needing no loaded database or graph edge and skipped when the call resolves to
200
+ * a user definition, so a local `sd()` stays bare.
198
201
  *
199
- * Pass the call's `name` to additionally get *edge-free* base-R qualification: a bare base call is qualified
200
- * from the base package that exports it (`sd` yields `stats::sd`, `plot` yields `base::plot`) via the
201
- * precomputed {@link baseRExportOwner} store -- no loaded database, no graph edges. This is suppressed when
202
- * the call resolves to a user definition or is already namespaced, so a local `sd()` is never `stats::sd`.
202
+ * Returns `undefined` when none apply. Steps 2 and 3 need the call's `name`.
203
+ * @param qualifyBaseR - whether to also qualify a bare base-R call from its exporting package (default `true`)
203
204
  * @see {@link Dataflow.qualify} - the compact form, if you have the call's id and its graph
204
205
  */
205
- toQualified(origins, name) {
206
+ toQualified(origins, name, qualifyBaseR = true) {
206
207
  let sawUserDefinition = false;
207
208
  for (const origin of origins ?? []) {
208
- // an attached package export carries the target builtin id `built-in:pkg:func` in `proc`
209
209
  if ('proc' in origin) {
210
- const pkgFn = node_id_1.NodeId.toPkgFn(origin.proc); // [pkg, func], or undefined for a bare/processor-level builtin
210
+ const pkgFn = node_id_1.NodeId.toPkgFn(origin.proc);
211
211
  if (pkgFn) {
212
212
  return exports.Identifier.make(pkgFn[1], pkgFn[0]);
213
213
  }
214
+ else if (exports.Identifier.getNamespace(origin.fn.name) !== undefined) {
215
+ return origin.fn.name;
216
+ }
214
217
  }
215
218
  else {
216
- sawUserDefinition = true; // a function-call/variable origin: resolves to a user definition
219
+ sawUserDefinition = true;
217
220
  }
218
221
  }
219
- // only qualify a bare base call: never override a user definition, nor an explicitly namespaced call
220
- if (name !== undefined && !sawUserDefinition && exports.Identifier.getNamespace(name) === undefined) {
222
+ if (name === undefined) {
223
+ return undefined;
224
+ }
225
+ if (exports.Identifier.getNamespace(name) !== undefined) {
226
+ return name;
227
+ }
228
+ if (qualifyBaseR && !sawUserDefinition) {
221
229
  const bare = exports.Identifier.getName(name);
222
230
  const owner = (0, r_base_packages_1.baseRExportOwner)(bare);
223
231
  if (owner !== undefined) {
@@ -0,0 +1,29 @@
1
+ import type { NodeId } from '../../../r-bridge/lang-4.x/ast/model/processing/node-id';
2
+ import type { DataflowGraph } from '../../graph/graph';
3
+ import type { ControlFlowGraph } from '../../../control-flow/control-flow-graph';
4
+ import type { ReadOnlyFlowrAnalyzerContext } from '../../../project/context/flowr-analyzer-context';
5
+ import { type ControlDependency } from '../../info';
6
+ /** a resolved `setwd`-style call: its `dir` is `undefined` when it cannot be determined statically */
7
+ export interface WorkingDirectoryChange {
8
+ readonly id: NodeId;
9
+ readonly dir: string | undefined;
10
+ readonly cds: readonly ControlDependency[];
11
+ readonly iterated: boolean;
12
+ readonly enclosedInFunction: boolean;
13
+ }
14
+ /** over-approximating candidate set (empty means unbounded), and whether exactly one directory is guaranteed */
15
+ export interface WorkingDirectoryResolution {
16
+ readonly candidates: readonly string[];
17
+ readonly certain: boolean;
18
+ }
19
+ type Guards = readonly ControlDependency[];
20
+ declare function resolveAt(target: NodeId, targetCds: Guards, baseWd: string, changes: readonly WorkingDirectoryChange[], cfg: ControlFlowGraph): WorkingDirectoryResolution;
21
+ declare function collect(graph: DataflowGraph, ctx: ReadOnlyFlowrAnalyzerContext): WorkingDirectoryChange[];
22
+ /** Resolve R's process-global working directory (sensitive to `setwd`) at a program point; path-sensitive, unbounded rather than wrong under loops/functions. */
23
+ export declare const WorkingDirectory: {
24
+ readonly collect: typeof collect;
25
+ readonly resolveAt: typeof resolveAt;
26
+ /** reusable `(callId, scriptFile?) => candidate roots`, collecting the changes once for the whole graph */
27
+ readonly rootsResolver: (graph: DataflowGraph, cfg: ControlFlowGraph, ctx: ReadOnlyFlowrAnalyzerContext) => (id: NodeId, file?: string) => readonly string[];
28
+ };
29
+ export {};
@@ -0,0 +1,168 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.WorkingDirectory = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const vertex_1 = require("../../graph/vertex");
9
+ const happens_before_1 = require("../../../control-flow/happens-before");
10
+ const logic_1 = require("../../../util/logic");
11
+ const identifier_1 = require("../../environments/identifier");
12
+ const resolve_argument_1 = require("./resolve-argument");
13
+ const dependencies_query_format_1 = require("../../../queries/catalog/dependencies-query/dependencies-query-format");
14
+ const strings_1 = require("../../../util/text/strings");
15
+ const info_1 = require("../../info");
16
+ const type_1 = require("../../../r-bridge/lang-4.x/ast/model/type");
17
+ const edge_1 = require("../../graph/edge");
18
+ const defaultmap_1 = require("../../../util/collections/defaultmap");
19
+ const files_1 = require("../../../util/files");
20
+ const built_in_source_1 = require("../../internal/process/functions/call/built-in/built-in-source");
21
+ /** functions recognized as changing the working directory; a registry so more (e.g. `withr::with_dir`) can be added */
22
+ const ChangeFunctions = [
23
+ { name: 'setwd', namespace: 'base', argIdx: 0, argName: 'dir' }
24
+ ];
25
+ const LoopTypes = new Set([type_1.RType.ForLoop, type_1.RType.WhileLoop, type_1.RType.RepeatLoop]);
26
+ const CandidateCap = 64;
27
+ function matchSpec(name) {
28
+ if (name === undefined) {
29
+ return undefined;
30
+ }
31
+ const bare = identifier_1.Identifier.getName(name);
32
+ const ns = identifier_1.Identifier.getNamespace(name);
33
+ return ChangeFunctions.find(s => s.name === bare && (ns === undefined || ns === s.namespace));
34
+ }
35
+ function isAbsoluteDir(dir) {
36
+ return dir.startsWith('~') || (0, strings_1.isAbsolutePath)(dir, undefined);
37
+ }
38
+ /** apply one `setwd(dir)`: an absolute (or `~`-rooted) `dir` replaces `current`, a relative `dir` joins onto it */
39
+ function applyChange(current, dir) {
40
+ const d = (0, files_1.toPosixPath)(dir);
41
+ return isAbsoluteDir(dir) ? path_1.default.posix.normalize(d) : path_1.default.posix.join((0, files_1.toPosixPath)(current), d);
42
+ }
43
+ function guardIn(g, set) {
44
+ return set.some(b => b.id === g.id && b.when === g.when);
45
+ }
46
+ function subsumed(inner, outer) {
47
+ return inner.every(g => guardIn(g, outer));
48
+ }
49
+ function consistent(inner, outer) {
50
+ return inner.every(g => !outer.some(b => b.id === g.id && b.when !== g.when));
51
+ }
52
+ function mergeGuards(a, b) {
53
+ const out = [...a];
54
+ for (const g of b) {
55
+ if (!guardIn(g, out)) {
56
+ out.push(g);
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+ /** the changes ordered so predecessors come first; parallel branches keep an arbitrary relative order */
62
+ function topoOrder(changes, cfg) {
63
+ const remaining = [...changes];
64
+ const result = [];
65
+ while (remaining.length > 0) {
66
+ const idx = Math.max(0, remaining.findIndex(a => remaining.every(b => b === a || (0, happens_before_1.happensBefore)(cfg, b.id, a.id) === logic_1.Ternary.Never)));
67
+ result.push(remaining.splice(idx, 1)[0]);
68
+ }
69
+ return result;
70
+ }
71
+ function enclosingFunction(idMap, id) {
72
+ let cursor = idMap?.get(id)?.info.parent;
73
+ while (cursor !== undefined) {
74
+ const node = idMap?.get(cursor);
75
+ if (node?.type === type_1.RType.FunctionDefinition) {
76
+ return node.info.id;
77
+ }
78
+ cursor = node?.info.parent;
79
+ }
80
+ return undefined;
81
+ }
82
+ function isIterated(cds, idMap) {
83
+ return cds.some(cd => cd.byIteration || LoopTypes.has(idMap?.get(cd.id)?.type));
84
+ }
85
+ function resolveAt(target, targetCds, baseWd, changes, cfg) {
86
+ const relevant = changes.filter(c => (0, happens_before_1.happensBefore)(cfg, c.id, target) !== logic_1.Ternary.Never);
87
+ // a setwd hidden in a function may still have run before target via a call happensBefore cannot see
88
+ if (changes.some(c => c.enclosedInFunction && !relevant.includes(c))) {
89
+ return { candidates: [], certain: false };
90
+ }
91
+ if (relevant.length === 0) {
92
+ return { candidates: [baseWd], certain: true };
93
+ }
94
+ if (relevant.some(c => c.dir === undefined || (c.iterated && !isAbsoluteDir(c.dir)))) {
95
+ return { candidates: [], certain: false };
96
+ }
97
+ let states = [{ wd: baseWd, guards: [] }];
98
+ for (const c of topoOrder(relevant, cfg)) {
99
+ const next = [];
100
+ for (const s of states) {
101
+ if (!consistent(c.cds, s.guards)) {
102
+ next.push(s);
103
+ continue;
104
+ }
105
+ const ran = { wd: applyChange(s.wd, c.dir), guards: mergeGuards(s.guards, c.cds) };
106
+ if (!c.iterated && subsumed(c.cds, s.guards)) {
107
+ next.push(ran);
108
+ }
109
+ else {
110
+ const neg = c.cds.length === 1 ? [(0, info_1.negateControlDependency)(c.cds[0])] : [];
111
+ next.push({ wd: s.wd, guards: mergeGuards(s.guards, neg) });
112
+ next.push(ran);
113
+ }
114
+ }
115
+ states = next;
116
+ if (states.length > CandidateCap) {
117
+ return { candidates: [], certain: false };
118
+ }
119
+ }
120
+ const candidates = [...new Set(states.filter(s => consistent(targetCds, s.guards)).map(s => s.wd))];
121
+ return { candidates, certain: candidates.length === 1 };
122
+ }
123
+ function collect(graph, ctx) {
124
+ const out = [];
125
+ const byFn = new defaultmap_1.DefaultMap(() => []);
126
+ for (const [id, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
127
+ const spec = matchSpec(vertex.name);
128
+ if (spec === undefined) {
129
+ continue;
130
+ }
131
+ const resolved = (0, resolve_argument_1.getArgumentStringValue)(ctx.config.solver.variables, graph, vertex, spec.argIdx, spec.argName, true, ctx);
132
+ const values = resolved ? Array.from(resolved.values()).flatMap(s => Array.from(s)) : [];
133
+ const known = values.filter(v => v !== undefined && v !== dependencies_query_format_1.Unknown);
134
+ const dir = values.length > 0 && known.length === values.length && new Set(known).size === 1 ? known[0] : undefined;
135
+ const cds = vertex.cds ?? [];
136
+ const iterated = isIterated(cds, graph.idMap);
137
+ const fn = enclosingFunction(graph.idMap, id);
138
+ if (fn === undefined) {
139
+ out.push({ id, dir, cds, iterated, enclosedInFunction: false });
140
+ }
141
+ else {
142
+ byFn.get(fn).push({ dir, cds, iterated });
143
+ }
144
+ }
145
+ // a function's setwd is propagated to its call sites; only a lone unconditional setwd has a site-independent effect
146
+ for (const [fn, setwds] of byFn.entries()) {
147
+ const net = setwds.length === 1 && setwds[0].cds.length === 0 && !setwds[0].iterated ? setwds[0].dir : undefined;
148
+ for (const [site, edge] of graph.ingoingEdges(fn) ?? []) {
149
+ if (!edge_1.DfEdge.includesType(edge, edge_1.EdgeType.Calls)) {
150
+ continue;
151
+ }
152
+ const cds = graph.getVertex(site)?.cds ?? [];
153
+ out.push({ id: site, dir: net, cds, iterated: isIterated(cds, graph.idMap), enclosedInFunction: enclosingFunction(graph.idMap, site) !== undefined });
154
+ }
155
+ }
156
+ return out;
157
+ }
158
+ /** Resolve R's process-global working directory (sensitive to `setwd`) at a program point; path-sensitive, unbounded rather than wrong under loops/functions. */
159
+ exports.WorkingDirectory = {
160
+ collect,
161
+ resolveAt,
162
+ /** reusable `(callId, scriptFile?) => candidate roots`, collecting the changes once for the whole graph */
163
+ rootsResolver(graph, cfg, ctx) {
164
+ const changes = collect(graph, ctx);
165
+ return (id, file) => resolveAt(id, graph.getVertex(id)?.cds ?? [], file ? (0, built_in_source_1.platformDirname)(file) : '.', changes, cfg).candidates;
166
+ }
167
+ };
168
+ //# sourceMappingURL=resolve-working-directory.js.map