@eagleoutice/flowr 2.13.1 → 2.13.3

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 (158) hide show
  1. package/README.md +46 -44
  2. package/abstract-interpretation/data-frame/mappers/access-mapper.js +1 -0
  3. package/abstract-interpretation/data-frame/mappers/function-mapper.d.ts +1 -1
  4. package/abstract-interpretation/data-frame/mappers/function-mapper.js +3 -0
  5. package/abstract-interpretation/domains/state-domain-like.d.ts +1 -1
  6. package/cli/flowr.js +21 -5
  7. package/cli/repl/commands/repl-commands.js +11 -9
  8. package/cli/repl/commands/repl-query.js +1 -1
  9. package/cli/repl/commands/repl-signature.js +8 -1
  10. package/cli/repl/core.js +13 -10
  11. package/cli/repl/print-version.js +1 -1
  12. package/cli/repl/server/connection.d.ts +1 -1
  13. package/cli/repl/server/net.js +15 -0
  14. package/config.d.ts +37 -0
  15. package/config.js +63 -3
  16. package/control-flow/control-flow-graph.js +2 -1
  17. package/control-flow/semantic-cfg-guided-visitor.d.ts +1 -1
  18. package/core/steps/all/core/11-normalize-tree-sitter.d.ts +1 -1
  19. package/data/sigdb/sigdb.remote.json +1 -1
  20. package/dataflow/environments/append.d.ts +1 -1
  21. package/dataflow/environments/clone.d.ts +1 -1
  22. package/dataflow/environments/environment.d.ts +28 -4
  23. package/dataflow/environments/environment.js +66 -11
  24. package/dataflow/environments/identifier.d.ts +9 -8
  25. package/dataflow/environments/identifier.js +21 -13
  26. package/dataflow/environments/overwrite.d.ts +1 -1
  27. package/dataflow/eval/resolve/alias-tracking.d.ts +1 -1
  28. package/dataflow/eval/resolve/resolve-working-directory.d.ts +29 -0
  29. package/dataflow/eval/resolve/resolve-working-directory.js +168 -0
  30. package/dataflow/extractor.js +2 -1
  31. package/dataflow/graph/dataflowgraph-builder.d.ts +1 -1
  32. package/dataflow/graph/df-helper.d.ts +3 -2
  33. package/dataflow/graph/df-helper.js +11 -15
  34. package/dataflow/graph/diff-dataflow-graph.js +1 -1
  35. package/dataflow/graph/graph-helper.js +2 -6
  36. package/dataflow/graph/graph.d.ts +24 -0
  37. package/dataflow/graph/graph.js +25 -1
  38. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.d.ts +1 -1
  39. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +1 -1
  40. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +7 -0
  41. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +51 -0
  42. package/dataflow/internal/process/functions/call/built-in/built-in-eval.d.ts +1 -1
  43. package/dataflow/internal/process/functions/call/built-in/built-in-expression-list.js +1 -1
  44. package/dataflow/internal/process/functions/call/built-in/built-in-function-definition.d.ts +1 -1
  45. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +5 -2
  46. package/dataflow/internal/process/functions/call/built-in/built-in-library.js +15 -9
  47. package/dataflow/internal/process/functions/call/built-in/built-in-list.d.ts +1 -1
  48. package/dataflow/internal/process/functions/call/built-in/built-in-quote.d.ts +1 -1
  49. package/dataflow/internal/process/functions/call/built-in/built-in-register-hook.d.ts +1 -1
  50. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-dispatch.d.ts +1 -1
  51. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.d.ts +7 -1
  52. package/dataflow/internal/process/functions/call/built-in/built-in-s-seven-new-generic.js +9 -2
  53. package/dataflow/internal/process/functions/call/built-in/built-in-s-three-dispatch.d.ts +1 -1
  54. package/dataflow/internal/process/functions/call/built-in/built-in-stack-env.js +2 -2
  55. package/dataflow/internal/process/functions/call/built-in/built-in-vector.d.ts +1 -1
  56. package/documentation/doc-readme.js +14 -12
  57. package/documentation/doc-util/doc-normalized-ast.d.ts +1 -1
  58. package/documentation/wiki-dataflow-graph.js +4 -24
  59. package/documentation/wiki-linter.js +1 -0
  60. package/documentation/wiki-mk/doc-context.d.ts +10 -0
  61. package/documentation/wiki-mk/doc-context.js +3 -0
  62. package/documentation/wiki-query.js +47 -0
  63. package/documentation/wiki-signature-database.js +18 -7
  64. package/linter/linter-rules.d.ts +24 -2
  65. package/linter/linter-rules.js +3 -1
  66. package/linter/rules/absolute-path.d.ts +4 -4
  67. package/linter/rules/absolute-path.js +7 -5
  68. package/linter/rules/dataframe-access-validation.d.ts +1 -1
  69. package/linter/rules/file-path-validity.d.ts +1 -1
  70. package/linter/rules/file-path-validity.js +48 -8
  71. package/linter/rules/function-finder-util.d.ts +2 -1
  72. package/linter/rules/syntactically-valid.d.ts +58 -0
  73. package/linter/rules/syntactically-valid.js +203 -0
  74. package/linter/rules/undefined-symbol-util.js +3 -1
  75. package/linter/rules/undefined-symbol.js +6 -6
  76. package/package.json +25 -12
  77. package/project/context/classify-project-kind.d.ts +40 -0
  78. package/project/context/classify-project-kind.js +76 -0
  79. package/project/context/flowr-analyzer-context.d.ts +4 -4
  80. package/project/context/flowr-analyzer-context.js +3 -3
  81. package/project/context/flowr-analyzer-dependencies-context.d.ts +34 -9
  82. package/project/context/flowr-analyzer-dependencies-context.js +30 -3
  83. package/project/context/flowr-analyzer-files-context.d.ts +10 -8
  84. package/project/context/flowr-analyzer-files-context.js +26 -67
  85. package/project/context/flowr-analyzer-meta-context.d.ts +1 -0
  86. package/project/context/flowr-file.d.ts +5 -0
  87. package/project/context/flowr-file.js +5 -0
  88. package/project/dependency-version-space.d.ts +118 -26
  89. package/project/dependency-version-space.js +343 -87
  90. package/project/plugins/file-plugins/files/flowr-description-file.d.ts +4 -0
  91. package/project/plugins/file-plugins/files/flowr-description-file.js +8 -1
  92. package/project/plugins/file-plugins/files/flowr-rda-file.js +27 -25
  93. package/project/plugins/file-plugins/flowr-analyzer-rprofile-file-plugin.d.ts +12 -4
  94. package/project/plugins/file-plugins/flowr-analyzer-rprofile-file-plugin.js +25 -10
  95. package/project/plugins/file-plugins/notebooks/flowr-analyzer-rmd-file-plugin.d.ts +1 -1
  96. package/project/plugins/file-plugins/notebooks/flowr-analyzer-sweave-file-plugin.d.ts +1 -1
  97. package/project/plugins/package-version-plugins/flowr-analyzer-meta-description-file-plugin.js +2 -1
  98. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.d.ts +1 -1
  99. package/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin.js +4 -4
  100. package/project/plugins/package-version-plugins/package.d.ts +27 -10
  101. package/project/plugins/package-version-plugins/package.js +50 -25
  102. package/project/plugins/plugin-registry.d.ts +2 -1
  103. package/project/plugins/plugin-registry.js +4 -1
  104. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.d.ts +57 -2
  105. package/project/plugins/project-discovery/flowr-analyzer-project-discovery-plugin.js +150 -28
  106. package/project/sigdb/decompress.d.ts +1 -1
  107. package/project/sigdb/decompress.js +4 -1
  108. package/project/sigdb/manifest.js +60 -26
  109. package/project/sigdb/reader.d.ts +26 -16
  110. package/project/sigdb/reader.js +52 -21
  111. package/project/sigdb/sigdb-download.d.ts +6 -7
  112. package/project/sigdb/sigdb-download.js +30 -9
  113. package/queries/catalog/dependencies-query/dependencies-query-executor.js +1 -1
  114. package/queries/catalog/dependencies-query/dependencies-query-format.d.ts +2 -12
  115. package/queries/catalog/dependencies-query/dependencies-query-format.js +2 -108
  116. package/queries/catalog/does-call-query/does-call-query-format.d.ts +1 -1
  117. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-executor.js +39 -77
  118. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.d.ts +12 -0
  119. package/queries/catalog/guess-dep-versions-query/guess-dep-versions-query-format.js +54 -24
  120. package/queries/catalog/input-sources-query/input-source-functions.d.ts +13 -0
  121. package/queries/catalog/input-sources-query/input-source-functions.js +96 -1
  122. package/queries/catalog/input-sources-query/input-sources-query-executor.js +40 -4
  123. package/queries/catalog/input-sources-query/input-sources-query-format.js +21 -3
  124. package/queries/catalog/input-sources-query/input-types.d.ts +58 -0
  125. package/queries/catalog/input-sources-query/input-types.js +64 -0
  126. package/queries/catalog/input-sources-query/simple-input-classifier.d.ts +62 -52
  127. package/queries/catalog/input-sources-query/simple-input-classifier.js +334 -101
  128. package/queries/catalog/linter-query/linter-query-format.js +9 -2
  129. package/queries/catalog/project-query/project-query-executor.js +1 -1
  130. package/queries/catalog/signature-query/signature-query-executor.d.ts +7 -1
  131. package/queries/catalog/signature-query/signature-query-executor.js +115 -39
  132. package/queries/catalog/signature-query/signature-query-format.d.ts +5 -1
  133. package/queries/catalog/signature-query/signature-query-format.js +1 -1
  134. package/queries/catalog/signature-query/signature-query-render.js +12 -7
  135. package/queries/query.js +9 -2
  136. package/r-bridge/data/data.d.ts +5 -0
  137. package/r-bridge/data/data.js +6 -0
  138. package/r-bridge/lang-4.x/ast/parser/json/format.js +1 -1
  139. package/r-bridge/retriever.d.ts +1 -1
  140. package/r-bridge/retriever.js +6 -1
  141. package/r-bridge/shell.js +5 -0
  142. package/search/flowr-search-filters.d.ts +2 -1
  143. package/search/flowr-search-printer.js +10 -8
  144. package/slicing/static/static-slicer.d.ts +2 -2
  145. package/util/files.d.ts +6 -4
  146. package/util/files.js +30 -8
  147. package/util/mermaid/dfg.js +1 -1
  148. package/util/objects.js +6 -4
  149. package/util/r-base-packages.d.ts +2 -0
  150. package/util/r-base-packages.js +3 -0
  151. package/util/r-license.js +1 -4
  152. package/util/r-version.d.ts +12 -0
  153. package/util/r-version.js +16 -0
  154. package/util/range.d.ts +6 -2
  155. package/util/range.js +33 -15
  156. package/util/text/ansi.d.ts +7 -3
  157. package/util/text/ansi.js +8 -5
  158. package/util/version.js +4 -4
package/config.js CHANGED
@@ -6,15 +6,19 @@ 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"));
15
18
  const project_kind_1 = require("./project/context/project-kind");
16
19
  const object_path_1 = __importDefault(require("object-path"));
17
20
  const gas_1 = require("./gas");
21
+ const input_types_1 = require("./queries/catalog/input-sources-query/input-types");
18
22
  var VariableResolve;
19
23
  (function (VariableResolve) {
20
24
  /** Don't resolve constants at all */
@@ -208,7 +212,8 @@ exports.FlowrConfig = {
208
212
  showPlugins: false,
209
213
  },
210
214
  project: {
211
- resolveUnknownPathsOnDisk: true
215
+ resolveUnknownPathsOnDisk: true,
216
+ failOnInaccessiblePath: false
212
217
  },
213
218
  linter: {
214
219
  disabledRules: []
@@ -217,7 +222,8 @@ exports.FlowrConfig = {
217
222
  [project_kind_1.ProjectKind.Package]: { solver: { resolveSource: { assumeFilesExist: true } } },
218
223
  [project_kind_1.ProjectKind.Project]: { solver: { resolveSource: { assumeFilesExist: true } } },
219
224
  [project_kind_1.ProjectKind.ShinyApp]: {
220
- project: { implicitSources: ['global.R', 'ui.R', 'server.R', 'app.R'] },
225
+ /* shiny evaluates global.R before the supporting files in R/, and the app itself last */
226
+ project: { implicitSources: ['global.R', 'R/*.R', 'ui.R', 'server.R', 'app.R'] },
221
227
  solver: { resolveSource: { assumeFilesExist: true } }
222
228
  },
223
229
  [project_kind_1.ProjectKind.Script]: { inherit: project_kind_1.ProjectKind.Unknown },
@@ -294,13 +300,34 @@ exports.FlowrConfig = {
294
300
  }).description('Configuration options for the REPL.'),
295
301
  project: joi_1.default.object({
296
302
  resolveUnknownPathsOnDisk: joi_1.default.boolean().optional().description('Whether to resolve unknown paths loaded by the r project disk when trying to source/analyze files.'),
303
+ 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
304
  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
305
  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.')
306
+ 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.'),
307
+ discovery: joi_1.default.object({
308
+ 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).'),
309
+ perKind: joi_1.default.object().pattern(joi_1.default.string().valid(...Object.values(project_kind_1.ProjectKind)), joi_1.default.object({
310
+ include: joi_1.default.array().items(joi_1.default.string()).optional(),
311
+ exclude: joi_1.default.array().items(joi_1.default.string()).optional()
312
+ })).optional().description('Per-kind include/exclude glob overrides layered on the default scoping.'),
313
+ 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).')
314
+ }).optional().description('Scoping options for the default project discovery.'),
315
+ classification: joi_1.default.object({
316
+ shinyDescriptionTypes: joi_1.default.array().items(joi_1.default.string()).optional().description('DESCRIPTION Type: values that mark a shiny app.'),
317
+ shinyEntryFiles: joi_1.default.array().items(joi_1.default.string()).optional().description('File names a shiny app is assembled from.'),
318
+ shinyUsagePattern: joi_1.default.string().optional().description('Regex source evidencing shiny usage in an entry file.'),
319
+ notebookExtensions: joi_1.default.array().items(joi_1.default.string()).optional().description('File extensions marking a notebook.')
320
+ }).optional().description('Overrides for the signals flowR uses to classify the project kind.')
300
321
  }).description('Project specific configuration options.'),
301
322
  linter: joi_1.default.object({
302
323
  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.')
303
324
  }).description('Linter configuration options.'),
325
+ inputSources: joi_1.default.object({
326
+ pure: joi_1.default.array().items(joi_1.default.string()).optional().description('Functions that only pass the constantness of their arguments on.'),
327
+ ...Object.fromEntries(Object.values(input_types_1.InputType).map(t => [t, joi_1.default.array().items(joi_1.default.string()).optional().description(`Functions whose result is a '${t}' input.`)])),
328
+ linkedObjects: joi_1.default.array().items(joi_1.default.object()).optional().description('Objects a framework provides without a definition in the code, e.g. shiny\'s input.'),
329
+ linkedEntryPoints: joi_1.default.array().items(joi_1.default.object()).optional().description('Calls that hand a function to a framework, which binds its objects to the parameters by position.')
330
+ }).optional().description('Further frameworks the input-sources analysis should know about; entries are added to flowR\'s defaults.'),
304
331
  specializeConfig: joi_1.default.object().pattern(joi_1.default.string().valid(...Object.values(project_kind_1.ProjectKind)), joi_1.default.object({
305
332
  inherit: joi_1.default.string().valid(...Object.values(project_kind_1.ProjectKind)).optional().description('Inherit another kind\'s overwrite first (merged before this entry\'s own keys, which win).')
306
333
  }).unknown(true)).optional()
@@ -485,6 +512,31 @@ exports.FlowrConfig = {
485
512
  object_path_1.default.set(config, key, value);
486
513
  },
487
514
  };
515
+ /** Path to the user-global `flowr.json`, read as a fallback when no project config is found. */
516
+ function globalConfigFilePath() {
517
+ const base = process.env.FLOWR_CONFIG_HOME
518
+ ?? (process.env.XDG_CONFIG_HOME ? path_1.default.join(process.env.XDG_CONFIG_HOME, 'flowr') : undefined)
519
+ ?? (process.env.APPDATA ? path_1.default.join(process.env.APPDATA, 'flowr') : undefined)
520
+ ?? path_1.default.join(os_1.default.homedir?.() || os_1.default.tmpdir(), '.config', 'flowr');
521
+ return path_1.default.join(base, 'flowr.json');
522
+ }
523
+ /** Persist `dbPath` into `solver.sigdb.additionalPaths` in the global config (creating it, preserving the user's raw JSON); idempotent, returns the file written. */
524
+ function persistSigDbPathToGlobalConfig(dbPath) {
525
+ const file = globalConfigFilePath();
526
+ let raw = {};
527
+ try {
528
+ raw = fs_1.default.existsSync(file) ? JSON.parse(fs_1.default.readFileSync(file, 'utf-8')) : {};
529
+ }
530
+ catch (e) {
531
+ log_1.log.warn(`Could not read global config ${file}, recreating it: ${e.message}`);
532
+ }
533
+ const current = object_path_1.default.get(raw, 'solver.sigdb.additionalPaths');
534
+ const paths = Array.isArray(current) ? current : [];
535
+ object_path_1.default.set(raw, 'solver.sigdb.additionalPaths', [...new Set([...paths, dbPath])]);
536
+ fs_1.default.mkdirSync(path_1.default.dirname(file), { recursive: true });
537
+ fs_1.default.writeFileSync(file, JSON.stringify(raw, null, '\t') + '\n');
538
+ return file;
539
+ }
488
540
  function loadConfigFromFile(configFile, workingDirectory) {
489
541
  if (configFile !== undefined) {
490
542
  if (path_1.default.isAbsolute(configFile) && fs_1.default.existsSync(configFile)) {
@@ -510,6 +562,14 @@ function loadConfigFromFile(configFile, workingDirectory) {
510
562
  searchPath = (0, files_1.getParentDirectory)(searchPath);
511
563
  } while (fs_1.default.existsSync(searchPath));
512
564
  }
565
+ const global = globalConfigFilePath();
566
+ if (fs_1.default.existsSync(global)) {
567
+ const ret = exports.FlowrConfig.parse(fs_1.default.readFileSync(global, { encoding: 'utf-8' }));
568
+ if (ret) {
569
+ log_1.log.info(`Using global config ${global}`);
570
+ return ret;
571
+ }
572
+ }
513
573
  log_1.log.info('Using default config');
514
574
  return exports.FlowrConfig.default();
515
575
  }
@@ -224,7 +224,8 @@ exports.CfgVertex = {
224
224
  * @see {@link CfgVertex#getRootId|getRootId()} - for a way to get the root id of a vertex
225
225
  */
226
226
  getId(vertex) {
227
- return vertex === undefined ? undefined : (Array.isArray(vertex) ? vertex[1] : vertex);
227
+ const id = vertex === undefined ? undefined : (Array.isArray(vertex) ? vertex[1] : vertex);
228
+ return id;
228
229
  },
229
230
  /**
230
231
  * Check whether two vertices are equal, i.e., they have the same type, id, and if they are basic block vertices, they also have the same elements in the same order.
@@ -3,7 +3,7 @@ import { DataflowAwareCfgGuidedVisitor, type DataflowCfgGuidedVisitorConfigurati
3
3
  import type { NormalizedAst, ParentInformation } from '../r-bridge/lang-4.x/ast/model/processing/decorate';
4
4
  import type { SyntaxCfgGuidedVisitorConfiguration } from './syntax-cfg-guided-visitor';
5
5
  import type { NodeId } from '../r-bridge/lang-4.x/ast/model/processing/node-id';
6
- import { type Origin } from '../dataflow/origin/dfg-get-origin';
6
+ import type { Origin } from '../dataflow/origin/dfg-get-origin';
7
7
  import type { DataflowGraphVertexFunctionCall, DataflowGraphVertexFunctionDefinition, DataflowGraphVertexUse, DataflowGraphVertexValue, DataflowGraphVertexVariableDefinition } from '../dataflow/graph/vertex';
8
8
  import type { RString } from '../r-bridge/lang-4.x/ast/model/nodes/r-string';
9
9
  import type { RNumber } from '../r-bridge/lang-4.x/ast/model/nodes/r-number';
@@ -1,7 +1,7 @@
1
1
  import { internalPrinter } from '../../../print/print';
2
2
  import { normalizedAstToJson, normalizedAstToQuads, printNormalizedAstToMermaid, printNormalizedAstToMermaidUrl } from '../../../print/normalize-printer';
3
3
  import { PipelineStepStage } from '../../pipeline-step';
4
- import { type NormalizeRequiredInput } from './10-normalize';
4
+ import type { NormalizeRequiredInput } from './10-normalize';
5
5
  import type { ParseStepOutput } from '../../../../r-bridge/parser';
6
6
  import type { Tree } from 'web-tree-sitter';
7
7
  declare function processor(results: {
@@ -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": {
@@ -1,4 +1,4 @@
1
- import { type REnvironmentInformation } from './environment';
1
+ import type { REnvironmentInformation } from './environment';
2
2
  import type { IdentifierDefinition } from './identifier';
3
3
  /**
4
4
  * Merges two arrays of identifier definitions into a fresh array, unique by `nodeId` and `definedAt`.
@@ -1,4 +1,4 @@
1
- import { type REnvironmentInformation } from './environment';
1
+ import type { REnvironmentInformation } from './environment';
2
2
  /**
3
3
  * Produce a clone of the given environment information.
4
4
  * @param environment - The environment information to clone.
@@ -102,10 +102,30 @@ export declare class Environment implements IEnvironment {
102
102
  }
103
103
  /** Walks up to the global environment (see {@link Environment#globalEnv}), falling back to the last non-builtin env. */
104
104
  declare function findGlobalEnvironment(this: void, env: Environment): Environment;
105
+ /** The `search()` position directly below the global environment; where R attaches by default. */
106
+ export declare const DefaultAttachPosition = 2;
107
+ /** Prefix of a package's entry in R's `search()` list. */
108
+ export declare const SearchPathPackagePrefix = "package:";
109
+ /** Name of the global environment in R's `search()` list. */
110
+ export declare const GlobalEnvEntryName = ".GlobalEnv";
105
111
  /**
106
- * Splices a package block (`blockTop`..`blockBottom`) directly below the global environment. Returns a fresh `current`, cloning only the path down to global.
112
+ * Splices a package block (`blockTop`..`blockBottom`) into the search path at the 1-based `search()` position `pos`
113
+ * ({@link DefaultAttachPosition|2} being directly below the global environment, the default). A position past the end
114
+ * of the search path attaches directly above the built-in environment, mirroring R's clamping. Returns a fresh
115
+ * `current`, cloning only the path down to the insertion point.
107
116
  */
108
- declare function attachPackageBelowGlobal(this: void, current: Environment, blockTop: Environment, blockBottom: Environment): Environment;
117
+ declare function attachPackageAt(this: void, current: Environment, blockTop: Environment, blockBottom: Environment, pos?: number): Environment;
118
+ /**
119
+ * The 1-based `search()` position of the entry called `name` (`.GlobalEnv`, `package:x`, or a bare package name),
120
+ * or `undefined` if no such entry is on the search path. `package:base` resolves to the built-in environment at the
121
+ * very bottom if base R is not attached as its own layer.
122
+ */
123
+ declare function searchPositionOf(this: void, env: Environment, name: string): number | undefined;
124
+ /**
125
+ * The packages attached below the global environment, i.e. those whose exports R resolves without a namespace.
126
+ * Base is always among them, as it backs the built-in environment even when it is no layer of its own.
127
+ */
128
+ declare function attachedPackagesOf(this: void, env: Environment): Set<string>;
109
129
  /**
110
130
  * Helpers for navigating and manipulating {@link REnvironmentInformation|environments} around the global environment and attached-package search path.
111
131
  */
@@ -113,8 +133,12 @@ export declare const REnvironment: {
113
133
  readonly name: "REnvironment";
114
134
  /** Walks up to the global environment (`.GlobalEnv`); see {@link findGlobalEnvironment}. */
115
135
  readonly findGlobal: typeof findGlobalEnvironment;
116
- /** Attaches a package block below the global environment; see {@link attachPackageBelowGlobal}. */
117
- readonly attachBelowGlobal: typeof attachPackageBelowGlobal;
136
+ /** Attaches a package block at a `search()` position, below the global by default; see {@link attachPackageAt}. */
137
+ readonly attachAt: typeof attachPackageAt;
138
+ /** The `search()` position of a named entry; see {@link searchPositionOf}. */
139
+ readonly searchPosition: typeof searchPositionOf;
140
+ /** The packages on the search path; see {@link attachedPackagesOf}. */
141
+ readonly attachedPackages: typeof attachedPackagesOf;
118
142
  };
119
143
  /**
120
144
  * An environment describes a ({@link IEnvironment#parent|scoped}) mapping of names to their definitions ({@link BuiltIns}).
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.REnvironment = exports.Environment = exports.EnvType = void 0;
3
+ exports.REnvironment = exports.GlobalEnvEntryName = exports.SearchPathPackagePrefix = exports.DefaultAttachPosition = exports.Environment = exports.EnvType = void 0;
4
4
  exports.isDefaultBuiltInEnvironment = isDefaultBuiltInEnvironment;
5
5
  exports.builtInEnvJsonReplacer = builtInEnvJsonReplacer;
6
6
  /**
@@ -381,20 +381,71 @@ function findGlobalEnvironment(env) {
381
381
  }
382
382
  return current;
383
383
  }
384
+ /** The `search()` position directly below the global environment; where R attaches by default. */
385
+ exports.DefaultAttachPosition = 2;
386
+ /** Prefix of a package's entry in R's `search()` list. */
387
+ exports.SearchPathPackagePrefix = 'package:';
388
+ /** Name of the global environment in R's `search()` list. */
389
+ exports.GlobalEnvEntryName = '.GlobalEnv';
384
390
  /**
385
- * Splices a package block (`blockTop`..`blockBottom`) directly below the global environment. Returns a fresh `current`, cloning only the path down to global.
391
+ * Splices a package block (`blockTop`..`blockBottom`) into the search path at the 1-based `search()` position `pos`
392
+ * ({@link DefaultAttachPosition|2} being directly below the global environment, the default). A position past the end
393
+ * of the search path attaches directly above the built-in environment, mirroring R's clamping. Returns a fresh
394
+ * `current`, cloning only the path down to the insertion point.
386
395
  */
387
- function attachPackageBelowGlobal(current, blockTop, blockBottom) {
396
+ function attachPackageAt(current, blockTop, blockBottom, pos = exports.DefaultAttachPosition) {
388
397
  const clonedCurrent = current.clone(false);
389
- let global = clonedCurrent;
390
- while (!global.globalEnv && !global.parent.builtInEnv) {
391
- global.parent = global.parent.clone(false);
392
- global = global.parent;
398
+ let anchor = clonedCurrent;
399
+ while (!anchor.globalEnv && !anchor.parent.builtInEnv) {
400
+ anchor.parent = anchor.parent.clone(false);
401
+ anchor = anchor.parent;
393
402
  }
394
- blockBottom.parent = global.parent; // the built-in env, or the previously attached packages
395
- global.parent = blockTop;
403
+ /* walk past the `pos - 2` search entries below the global; an imports layer belongs to the entry above it and is never one itself */
404
+ for (let skip = pos - exports.DefaultAttachPosition; skip > 0 && !anchor.parent.builtInEnv; skip--) {
405
+ do {
406
+ anchor.parent = anchor.parent.clone(false);
407
+ anchor = anchor.parent;
408
+ } while (anchor.parent.t === EnvType.Imports);
409
+ }
410
+ blockBottom.parent = anchor.parent; // the built-in env, or the packages attached further down
411
+ anchor.parent = blockTop;
396
412
  return clonedCurrent;
397
413
  }
414
+ /**
415
+ * The 1-based `search()` position of the entry called `name` (`.GlobalEnv`, `package:x`, or a bare package name),
416
+ * or `undefined` if no such entry is on the search path. `package:base` resolves to the built-in environment at the
417
+ * very bottom if base R is not attached as its own layer.
418
+ */
419
+ function searchPositionOf(env, name) {
420
+ const target = name.startsWith(exports.SearchPathPackagePrefix) ? name.slice(exports.SearchPathPackagePrefix.length) : name;
421
+ if (target === exports.GlobalEnvEntryName) {
422
+ return 1;
423
+ }
424
+ let pos = 1;
425
+ for (let e = findGlobalEnvironment(env).parent; !e.builtInEnv; e = e.parent) {
426
+ if (e.t === EnvType.Imports) {
427
+ continue; // internal layer, not a search-path entry
428
+ }
429
+ pos++;
430
+ if (e.n === target) {
431
+ return pos;
432
+ }
433
+ }
434
+ return target === "base" /* PkgName.Base */ ? pos + 1 : undefined; // base is the built-in env when it is not attached as a layer
435
+ }
436
+ /**
437
+ * The packages attached below the global environment, i.e. those whose exports R resolves without a namespace.
438
+ * Base is always among them, as it backs the built-in environment even when it is no layer of its own.
439
+ */
440
+ function attachedPackagesOf(env) {
441
+ const attached = new Set(["base" /* PkgName.Base */]);
442
+ for (let e = findGlobalEnvironment(env).parent; !e.builtInEnv; e = e.parent) {
443
+ if (e.t !== EnvType.Imports && e.n !== undefined) {
444
+ attached.add(e.n);
445
+ }
446
+ }
447
+ return attached;
448
+ }
398
449
  /**
399
450
  * Helpers for navigating and manipulating {@link REnvironmentInformation|environments} around the global environment and attached-package search path.
400
451
  */
@@ -402,8 +453,12 @@ exports.REnvironment = {
402
453
  name: 'REnvironment',
403
454
  /** Walks up to the global environment (`.GlobalEnv`); see {@link findGlobalEnvironment}. */
404
455
  findGlobal: findGlobalEnvironment,
405
- /** Attaches a package block below the global environment; see {@link attachPackageBelowGlobal}. */
406
- attachBelowGlobal: attachPackageBelowGlobal,
456
+ /** Attaches a package block at a `search()` position, below the global by default; see {@link attachPackageAt}. */
457
+ attachAt: attachPackageAt,
458
+ /** The `search()` position of a named entry; see {@link searchPositionOf}. */
459
+ searchPosition: searchPositionOf,
460
+ /** The packages on the search path; see {@link attachedPackagesOf}. */
461
+ attachedPackages: attachedPackagesOf,
407
462
  };
408
463
  /** Splits a package block (a contiguous run of attached-package layers, see {@link EnvType}) into its layers and the env below them. */
409
464
  function splitLibraryLayers(env) {
@@ -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) {
@@ -1,4 +1,4 @@
1
- import { type REnvironmentInformation } from './environment';
1
+ import type { REnvironmentInformation } from './environment';
2
2
  import type { ControlDependency } from '../info';
3
3
  export declare function overwriteEnvironment(base: REnvironmentInformation, next: REnvironmentInformation | undefined, applyCds?: readonly ControlDependency[]): REnvironmentInformation;
4
4
  export declare function overwriteEnvironment(base: REnvironmentInformation | undefined, next: REnvironmentInformation, applyCds?: readonly ControlDependency[]): REnvironmentInformation;
@@ -1,7 +1,7 @@
1
1
  import { VariableResolve } from '../../../config';
2
2
  import type { AstIdMap, RNodeWithParent } from '../../../r-bridge/lang-4.x/ast/model/processing/decorate';
3
3
  import type { NodeId } from '../../../r-bridge/lang-4.x/ast/model/processing/node-id';
4
- import { type REnvironmentInformation } from '../../environments/environment';
4
+ import type { REnvironmentInformation } from '../../environments/environment';
5
5
  import { Identifier } from '../../environments/identifier';
6
6
  import type { DataflowGraph } from '../../graph/graph';
7
7
  import { type Lift, type Value, type ValueSet } from '../values/r-value';
@@ -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