@eagleoutice/flowr 2.17.12 → 2.17.14

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 (115) hide show
  1. package/README.md +15 -15
  2. package/cli/repl/core.js +9 -27
  3. package/config.d.ts +1 -0
  4. package/config.js +4 -2
  5. package/data/r-datasets.generated.js +2 -2
  6. package/dataflow/environments/ambient-effect.d.ts +4 -0
  7. package/dataflow/environments/ambient-effect.js +5 -4
  8. package/dataflow/environments/ambient-state-name.d.ts +2 -2
  9. package/dataflow/environments/ambient-state-name.js +3 -3
  10. package/dataflow/environments/built-in-props.d.ts +5 -0
  11. package/dataflow/environments/default-builtin-config/base-functions.d.ts +1 -1
  12. package/dataflow/environments/default-builtin-config/base-functions.js +6 -2
  13. package/dataflow/environments/default-builtin-config/base-language.d.ts +12 -1
  14. package/dataflow/environments/default-builtin-config/base-language.js +3 -2
  15. package/dataflow/environments/default-builtin-config/guards.js +3 -1
  16. package/dataflow/environments/default-builtin-config/index.d.ts +12 -2
  17. package/dataflow/environments/default-builtin-config/misc-packages.d.ts +1 -1
  18. package/dataflow/environments/default-builtin-config/misc-packages.js +2 -0
  19. package/dataflow/environments/default-builtin-config/shared-configs.d.ts +24 -0
  20. package/dataflow/environments/default-builtin-config/shared-configs.js +8 -6
  21. package/dataflow/environments/pkg-name.d.ts +1 -0
  22. package/dataflow/eval/resolve/alias-tracking.js +11 -12
  23. package/dataflow/extractor.js +58 -0
  24. package/dataflow/fn/guards/built-in-guards.js +4 -4
  25. package/dataflow/fn/guards/call-contracts.js +8 -8
  26. package/dataflow/fn/guards/condition-grouping.js +4 -3
  27. package/dataflow/fn/guards/function-guards.js +103 -97
  28. package/dataflow/fn/guards/group-method-guards.js +10 -8
  29. package/dataflow/fn/guards/guard-claims.js +152 -128
  30. package/dataflow/fn/guards/guard-knowledge.js +19 -18
  31. package/dataflow/fn/guards/guard-term-syntax.js +13 -12
  32. package/dataflow/fn/guards/guard-term.d.ts +71 -0
  33. package/dataflow/fn/guards/guard-term.js +183 -75
  34. package/dataflow/graph/df-helper.d.ts +6 -6
  35. package/dataflow/graph/df-helper.js +1 -1
  36. package/dataflow/graph/graph.d.ts +9 -0
  37. package/dataflow/graph/graph.js +19 -0
  38. package/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.js +18 -14
  39. package/dataflow/internal/process/functions/call/built-in/built-in-apply.d.ts +1 -1
  40. package/dataflow/internal/process/functions/call/built-in/built-in-apply.js +29 -0
  41. package/dataflow/internal/process/functions/call/built-in/built-in-assignment.js +2 -1
  42. package/dataflow/internal/process/functions/call/built-in/built-in-attach.js +2 -1
  43. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.d.ts +6 -2
  44. package/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.js +9 -2
  45. package/dataflow/internal/process/functions/call/built-in/built-in-eval.js +1 -1
  46. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.d.ts +12 -1
  47. package/dataflow/internal/process/functions/call/built-in/built-in-for-loop.js +24 -6
  48. package/dataflow/internal/process/functions/call/built-in/built-in-library.d.ts +10 -10
  49. package/dataflow/internal/process/functions/call/built-in/built-in-load.js +2 -2
  50. package/dataflow/internal/process/functions/call/built-in/built-in-local.js +1 -1
  51. package/dataflow/internal/process/functions/call/built-in/built-in-source.js +19 -9
  52. package/dataflow/internal/process/functions/call/built-in/built-in-with.js +35 -3
  53. package/documentation/doc-readme.js +1 -2
  54. package/documentation/doc-util/doc-query.d.ts +1 -1
  55. package/documentation/doc-util/doc-query.js +4 -2
  56. package/documentation/wiki-interface.js +1 -0
  57. package/documentation/wiki-linter.d.ts +2 -0
  58. package/documentation/wiki-linter.js +7 -1
  59. package/documentation/wiki-query.js +28 -0
  60. package/linter/linter-format.d.ts +5 -1
  61. package/linter/linter-format.js +4 -0
  62. package/linter/linter-output.js +18 -16
  63. package/linter/linter-rules.d.ts +50 -0
  64. package/linter/linter-rules.js +5 -1
  65. package/linter/rules/notebook-cell-order.d.ts +43 -0
  66. package/linter/rules/notebook-cell-order.js +97 -0
  67. package/linter/rules/project-entry-point.d.ts +53 -0
  68. package/linter/rules/project-entry-point.js +62 -0
  69. package/linter/rules/undefined-symbol.d.ts +2 -0
  70. package/linter/rules/undefined-symbol.js +6 -1
  71. package/notebook/cell-graph.d.ts +23 -0
  72. package/notebook/cell-graph.js +48 -0
  73. package/notebook/cell-order-mermaid.d.ts +16 -0
  74. package/notebook/cell-order-mermaid.js +51 -0
  75. package/notebook/cell-order.d.ts +270 -0
  76. package/notebook/cell-order.js +1452 -0
  77. package/notebook/cell-split.d.ts +27 -0
  78. package/notebook/cell-split.js +99 -0
  79. package/package.json +1 -1
  80. package/project/context/flowr-analyzer-dependencies-context.d.ts +4 -0
  81. package/project/context/flowr-analyzer-files-context.d.ts +2 -0
  82. package/project/flowr-analyzer.js +5 -1
  83. package/project/plugins/file-plugins/files/cell-runner.d.ts +22 -0
  84. package/project/plugins/file-plugins/files/cell-runner.js +32 -0
  85. package/project/plugins/file-plugins/files/flowr-jupyter-file.d.ts +4 -0
  86. package/project/plugins/file-plugins/files/flowr-jupyter-file.js +22 -6
  87. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.d.ts +22 -0
  88. package/project/plugins/file-plugins/files/flowr-rmarkdown-file.js +63 -7
  89. package/project/plugins/file-plugins/files/flowr-rsession-file.d.ts +2 -0
  90. package/project/plugins/file-plugins/files/flowr-rsession-file.js +2 -0
  91. package/project/plugins/file-plugins/files/flowr-sweave-file.d.ts +3 -5
  92. package/project/plugins/file-plugins/files/flowr-sweave-file.js +6 -0
  93. package/project/plugins/file-plugins/files/recorded-runs.d.ts +2 -0
  94. package/queries/catalog/aliases-query/aliases-query-executor.d.ts +6 -0
  95. package/queries/catalog/aliases-query/aliases-query-executor.js +108 -0
  96. package/queries/catalog/aliases-query/aliases-query-format.d.ts +21 -0
  97. package/queries/catalog/aliases-query/aliases-query-format.js +34 -0
  98. package/queries/catalog/cell-order-query/cell-order-query-format.d.ts +81 -0
  99. package/queries/catalog/cell-order-query/cell-order-query-format.js +82 -0
  100. package/queries/catalog/linter-query/linter-query-format.js +2 -1
  101. package/queries/query.d.ts +17 -2
  102. package/queries/query.js +6 -2
  103. package/queries/virtual-query/compound-query.d.ts +1 -1
  104. package/util/flowr-version.d.ts +1 -1
  105. package/util/flowr-version.js +2 -2
  106. package/util/mermaid/ast.js +4 -11
  107. package/util/mermaid/cfg.js +1 -2
  108. package/util/mermaid/dfg.d.ts +5 -0
  109. package/util/mermaid/dfg.js +23 -4
  110. package/util/mermaid/mermaid.d.ts +5 -0
  111. package/util/mermaid/mermaid.js +8 -0
  112. package/util/r-datasets.d.ts +2 -0
  113. package/util/r-datasets.js +3 -0
  114. package/util/text/playground-link.d.ts +2 -2
  115. package/util/text/playground-link.js +2 -2
@@ -0,0 +1,1452 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CellOrder = exports.RunState = exports.HazardKind = exports.binds = exports.CellResource = exports.SymbolKind = void 0;
4
+ exports.notebookCells = notebookCells;
5
+ exports.scriptCells = scriptCells;
6
+ exports.analyzeNotebook = analyzeNotebook;
7
+ exports.projectFiles = projectFiles;
8
+ exports.analyzeProject = analyzeProject;
9
+ exports.projectEntry = projectEntry;
10
+ exports.describeSymbol = describeSymbol;
11
+ exports.describeNeed = describeNeed;
12
+ exports.cellFacts = cellFacts;
13
+ exports.checkOrder = checkOrder;
14
+ exports.workingOrders = workingOrders;
15
+ exports.affectedCells = affectedCells;
16
+ exports.orderHazards = orderHazards;
17
+ exports.firstWorkingOrder = firstWorkingOrder;
18
+ exports.reorderCells = reorderCells;
19
+ exports.runStates = runStates;
20
+ exports.describeRunStates = describeRunStates;
21
+ exports.describeFailure = describeFailure;
22
+ exports.describeHazard = describeHazard;
23
+ exports.cellLinks = cellLinks;
24
+ exports.describeLinks = describeLinks;
25
+ const model_1 = require("../r-bridge/lang-4.x/ast/model/model");
26
+ const node_id_1 = require("../r-bridge/lang-4.x/ast/model/processing/node-id");
27
+ const vertex_1 = require("../dataflow/graph/vertex");
28
+ const df_helper_1 = require("../dataflow/graph/df-helper");
29
+ const identifier_1 = require("../dataflow/environments/identifier");
30
+ const ambient_access_1 = require("../dataflow/graph/ambient-access");
31
+ const ambient_effect_1 = require("../dataflow/environments/ambient-effect");
32
+ const built_in_ambient_state_1 = require("../dataflow/internal/process/functions/call/built-in/built-in-ambient-state");
33
+ const ambient_state_name_1 = require("../dataflow/environments/ambient-state-name");
34
+ const default_builtin_config_1 = require("../dataflow/environments/default-builtin-config");
35
+ const library_functions_1 = require("../queries/catalog/dependencies-query/function-info/library-functions");
36
+ const r_string_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-string");
37
+ const r_symbol_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-symbol");
38
+ const query_fn_props_1 = require("../dataflow/environments/query-fn-props");
39
+ const r_logical_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-logical");
40
+ const r_access_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-access");
41
+ const r_function_call_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-function-call");
42
+ const r_argument_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-argument");
43
+ const r_if_then_else_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-if-then-else");
44
+ const r_for_loop_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-for-loop");
45
+ const cell_runner_1 = require("../project/plugins/file-plugins/files/cell-runner");
46
+ const resolve_helper_1 = require("../dataflow/environments/resolve-helper");
47
+ const built_in_for_loop_1 = require("../dataflow/internal/process/functions/call/built-in/built-in-for-loop");
48
+ const r_binary_op_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-binary-op");
49
+ const r_pipe_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-pipe");
50
+ const r_unary_op_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-unary-op");
51
+ const arguments_1 = require("../abstract-interpretation/data-frame/arguments");
52
+ const r_function_definition_1 = require("../r-bridge/lang-4.x/ast/model/nodes/r-function-definition");
53
+ const range_1 = require("../util/range");
54
+ const arrays_1 = require("../util/collections/arrays");
55
+ const files_1 = require("../util/files");
56
+ const logic_1 = require("../util/logic");
57
+ const monoid_1 = require("../util/monoid");
58
+ const r_base_packages_1 = require("../util/r-base-packages");
59
+ const r_datasets_1 = require("../util/r-datasets");
60
+ const flowr_rmarkdown_file_1 = require("../project/plugins/file-plugins/files/flowr-rmarkdown-file");
61
+ const flowr_sweave_file_1 = require("../project/plugins/file-plugins/files/flowr-sweave-file");
62
+ const flowr_rsession_file_1 = require("../project/plugins/file-plugins/files/flowr-rsession-file");
63
+ const r_session_1 = require("../project/plugins/file-plugins/files/r-session");
64
+ const flowr_jupyter_file_1 = require("../project/plugins/file-plugins/files/flowr-jupyter-file");
65
+ const built_in_proc_name_1 = require("../dataflow/environments/built-in-proc-name");
66
+ const graph_1 = require("../dataflow/graph/graph");
67
+ const edge_1 = require("../dataflow/graph/edge");
68
+ const dependencies_query_executor_1 = require("../queries/catalog/dependencies-query/dependencies-query-executor");
69
+ /** Whether a name is bound to a function, to something else, or either. */
70
+ var SymbolKind;
71
+ (function (SymbolKind) {
72
+ SymbolKind["Function"] = "function";
73
+ SymbolKind["Value"] = "value";
74
+ SymbolKind["Any"] = "any";
75
+ })(SymbolKind || (exports.SymbolKind = SymbolKind = {}));
76
+ /** What a cell reads from the session or puts into it. */
77
+ var CellResource;
78
+ (function (CellResource) {
79
+ /** a name of the global environment */
80
+ CellResource["Variable"] = "variable";
81
+ /** a name bound beside the global environment, as `attach` binds it: assigning the name does not replace it, nor does `rm(list = ls())` remove it */
82
+ CellResource["Attached"] = "attached";
83
+ /** a package on the search path */
84
+ CellResource["Package"] = "package";
85
+ /** a part of R's global state flowR tracks (an option, the random seed, the working directory, the plot, ...), without its `#` */
86
+ CellResource["State"] = "state";
87
+ /** a file a cell writes, which another reads */
88
+ CellResource["File"] = "file";
89
+ /** a column a cell adds to a data frame (`d$c <- 1`, `d <- mutate(d, c = 1)`), named `d$c`, which a cell reading the bare name (`lm(c ~ x, data = d)`) needs and binding `d` anew takes away */
90
+ CellResource["Column"] = "column";
91
+ /** a state a call puts the object a name holds in (`solve(lp)`), named `lp#solved`, which a call needing it (`get.variables(lp)`) needs and binding `lp` anew takes away */
92
+ CellResource["ObjectState"] = "object-state";
93
+ })(CellResource || (exports.CellResource = CellResource = {}));
94
+ const sessionKey = (s) => `${s.resource} ${s.name}`;
95
+ /** the name a {@link CellEffect} binding any name stands for in the session, which no name of R is */
96
+ const AnyName = '';
97
+ const variable = (name, kind) => ({ resource: CellResource.Variable, name, kind });
98
+ const resource = (resource, name) => ({ resource, name, kind: SymbolKind.Any });
99
+ const column = (frame, name) => resource(CellResource.Column, `${frame}$${name}`);
100
+ /** the calls whose named arguments add columns to the data they are given (`mutate(d, c = 1)`) */
101
+ const ColumnAdders = [...identifier_1.Identifier.fromAll("dplyr" /* PkgName.Dplyr */, ['mutate', 'transmute', 'summarise', 'summarize', 'reframe']), identifier_1.Identifier.make('transform', "base" /* PkgName.Base */)];
102
+ /** the calls making a data frame of their named arguments (`data.frame(x = 1)`) */
103
+ const FrameMakers = [identifier_1.Identifier.make('data.frame', "base" /* PkgName.Base */), ...identifier_1.Identifier.fromAll("tibble" /* PkgName.Tibble */, ['tibble', 'data_frame'])];
104
+ /** the calls fitting a model of a formula, whose prediction for new data (`predict(m, newdata = d)`) finds the variables of the formula in that data */
105
+ const ModelFitters = identifier_1.Identifier.fromAll("stats" /* PkgName.Stats */, ['lm', 'glm']);
106
+ const Predictors = identifier_1.Identifier.fromAll("stats" /* PkgName.Stats */, ['predict', 'predict.lm', 'predict.glm']);
107
+ /** the calls giving a data frame of the columns of the one they are given (`as_tibble(d)`) */
108
+ const FrameKeepers = [...["tibble" /* PkgName.Tibble */, "dplyr" /* PkgName.Dplyr */].map(p => identifier_1.Identifier.make('as_tibble', p)), identifier_1.Identifier.make('as.data.frame', "base" /* PkgName.Base */)];
109
+ const PlotState = resource(CellResource.State, 'plot');
110
+ const DeviceState = resource(CellResource.State, ambient_state_name_1.AmbientStateName.deviceOpener.slice(1));
111
+ /** what `opts_chunk$set` of a knitted cell sets for the cells after it: to run no chunk, or to keep knitting after an error */
112
+ const ChunkOptions = { eval: [resource(CellResource.State, 'opts_chunk:eval=FALSE'), flowr_rmarkdown_file_1.NonExecutableEvalValues], error: [resource(CellResource.State, 'opts_chunk:error=TRUE'), flowr_rmarkdown_file_1.ErrorTolerantValues] };
113
+ /** the package options of knitr (`opts_knit`) that keep state of a chunk for the next, see {@link RunnerFreshState} */
114
+ const KnitOptions = Object.fromEntries(Object.values(cell_runner_1.RunnerFreshState).flat().flatMap(f => f.keptBy ?? [])
115
+ .map(o => [o, [resource(CellResource.State, `opts_knit:${o}=TRUE`), flowr_rmarkdown_file_1.ErrorTolerantValues]]));
116
+ const KnitrOptions = new Map([['opts_chunk', ChunkOptions], ['opts_knit', KnitOptions]]);
117
+ const SearchPathEntry = /^search-path:(.+)$/;
118
+ const StatedSignatures = (0, default_builtin_config_1.statedSignatures)();
119
+ /** Whether the cell starts with the state `name` afresh, as its runner gives each cell (see {@link RunnerFreshState}), unless the options set in `session` keep it. */
120
+ function startsAfresh(runner, name, session = new Map()) {
121
+ const fresh = (0, cell_runner_1.freshStateOf)(runner, name);
122
+ return fresh !== undefined && !(fresh.keptBy ?? []).some(o => session.has(sessionKey(KnitOptions[o][0])));
123
+ }
124
+ /**
125
+ * The global state a notebook depends on across cells, without its `#`: a keyed entry (`option:digits`), the random seed,
126
+ * or the working directory. The coarse rest (all options, every file, the output stream) would tie every cell to every other.
127
+ */
128
+ function trackedState(name) {
129
+ const bare = name.slice(1);
130
+ return /^(rng|wd)$/.test(bare) || (/^[\w-]+:./.test(bare) && !bare.endsWith(':*') && !bare.startsWith('sink:')) ? bare : undefined;
131
+ }
132
+ const lineCount = (code) => code.replace(/\n$/, '').split('\n').length;
133
+ /** a cell whose code starts in the line after the fence `head` and is closed by a fence after it */
134
+ const fenced = (head, code, runner, sets) => ({ head, from: head + 1, to: head + lineCount(code), tail: head + lineCount(code) + 1, runner, ...sets?.length ? { sets } : {} });
135
+ /** a knitted chunk, with what its options read */
136
+ function chunk(block, runner) {
137
+ const reads = (0, flowr_rmarkdown_file_1.optionReads)(block.header);
138
+ const cell = fenced(block.startpos.line - 1, block.code, runner, Object.keys(ChunkOptions).filter(o => block.options.has(o)));
139
+ return reads.size === 0 ? cell : { ...cell, reads: (0, arrays_1.uniqueArray)([...reads.values()].flat()), ...reads.has('eval') ? { maybe: true } : {} };
140
+ }
141
+ /**
142
+ * The code cells of a notebook: the chunks of R Markdown, Quarto, and Sweave, the code cells of a Jupyter notebook,
143
+ * the commands of an R console transcript, or the `# %%` cells of a script. A file that has none is no notebook.
144
+ */
145
+ function notebookCells(file) {
146
+ if (file instanceof flowr_rmarkdown_file_1.FlowrRMarkdownFile) {
147
+ const defaults = (0, flowr_rmarkdown_file_1.globalChunkOptions)(file.rmd.options);
148
+ /* inline code runs where it stands in the text, as a cell of its own line */
149
+ const inline = (0, arrays_1.uniqueArray)(file.rmd.inline.map(i => i.line)).map(line => ({ from: line, to: line }));
150
+ return [...file.rmd.blocks.filter(b => b.code !== '' && (0, flowr_rmarkdown_file_1.isExecutableCell)(b, defaults)).map(b => chunk(b, file.runner)), ...inline].sort((a, b) => a.from - b.from);
151
+ }
152
+ if (file instanceof flowr_sweave_file_1.FlowrSweaveFile) {
153
+ return file.rnw.blocks.flatMap(b => b.type === 'content' && b.options.eval !== false && b.content !== '' ? [fenced(b.startLine, b.content, file.runner)] : []);
154
+ }
155
+ if (file instanceof flowr_rsession_file_1.FlowrRSessionFile) {
156
+ /* an empty prompt, as a transcript ends with, runs nothing */
157
+ return (0, r_session_1.parseRSession)(file.rawText()).flatMap(s => s.kind === 'input' && s.lines.some(l => l.trim() !== '') ? [{ from: s.firstLine, to: s.firstLine + s.lines.length - 1 }] : []);
158
+ }
159
+ if (file instanceof flowr_jupyter_file_1.FlowrJupyterFile) {
160
+ /* the cells follow each other line by line, as flowR reads the notebook (text cells as comments) */
161
+ let line = 1;
162
+ return (0, flowr_jupyter_file_1.jupyterCells)(file.rawText()).flatMap(([code, source]) => {
163
+ const from = line;
164
+ line += source.split('\n').length;
165
+ return code && source.trim() !== '' ? [{ from, to: line - 1, runner: file.runner }] : [];
166
+ });
167
+ }
168
+ return scriptCells(file?.content().toString() ?? '');
169
+ }
170
+ /** The `# %%` cells of a script, a `# %% [markdown]` cell holding text. */
171
+ function scriptCells(text) {
172
+ const rows = text.split(/\r?\n/);
173
+ const heads = rows.flatMap((row, at) => /^#\s?%%/.test(row) ? [at + 1] : []);
174
+ return heads.flatMap((head, i) => {
175
+ let to = (heads[i + 1] ?? rows.length + 1) - 1;
176
+ while (to > head && rows[to - 1].trim() === '') {
177
+ to--;
178
+ }
179
+ return /\[markdown\]/i.test(rows[head - 1]) ? [] : [{ head, from: head + 1, to }];
180
+ });
181
+ }
182
+ /** The facts of the cells of the analyzed notebook (or of `cells` if given), derived once per analysis from its dataflow graph. */
183
+ function analyzeNotebook(analyzer, cells) {
184
+ const compute = async () => {
185
+ const files = analyzer.inspectContext().files;
186
+ /* code given as text rather than as a file may have cells as well */
187
+ const found = cells ?? [...files.getAllFiles().map(f => notebookCells(f).map(c => ({ ...c, file: f.path() }))), ...files.loadingOrder.getUnorderedRequests().map(r => r.request === 'text' ? scriptCells(r.content) : [])].find(c => c.length > 0) ?? [];
188
+ return found.length === 0 ? [] : cellFacts(found, await analyzer.normalize(), await analyzer.dataflow(), await cellDependencies(analyzer), analyzer.inspectContext());
189
+ };
190
+ return cells === undefined ? analyzer.derive(analyzeNotebook, compute) : compute();
191
+ }
192
+ async function cellDependencies(analyzer) {
193
+ const deps = await (0, dependencies_query_executor_1.executeDependenciesQuery)({ analyzer }, [{ type: 'dependencies', enabledCategories: ['library', 'read', 'source'] }]);
194
+ return { libraries: deps.library ?? [], reads: deps.read ?? [], sources: deps.source ?? [] };
195
+ }
196
+ /** Whether a file another file of the project sources names `path`, so it runs as part of that file. */
197
+ const sourcedFile = (path, sources) => sources.some(s => typeof s.value === 'string' && s.value !== '' && path.endsWith(s.value) && !path.endsWith(`${s.value}/`));
198
+ /**
199
+ * The files of a project as the units that run one after another, in flowR's loading order: each script or notebook as
200
+ * one cell of all its lines, but not a file another file sources, as it runs as part of that file. A notebook is one unit
201
+ * as a whole, as running a cell, then a whole file, and then another cell is no order anyone means.
202
+ */
203
+ async function projectFiles(analyzer, everyFile = false) {
204
+ const files = analyzer.inspectContext().files;
205
+ const sources = everyFile ? [] : (await cellDependencies(analyzer)).sources ?? [];
206
+ return files.loadingOrder.getLoadingOrder().flatMap(r => {
207
+ const file = r.request === 'file' ? files.getFileByPath(r.content) : undefined;
208
+ const text = file === undefined ? '' : 'rawText' in file && typeof file.rawText === 'function' ? String(file.rawText()) : file.content().toString();
209
+ return r.request !== 'file' || sourcedFile(r.content, sources) ? [] : [{ from: 1, to: Math.max(1, lineCount(text)), file: r.content }];
210
+ });
211
+ }
212
+ /**
213
+ * The facts of the files of the analyzed project as {@link projectFiles}, derived once per analysis. With `everyFile`, each file
214
+ * is a unit of its own, also one another file sources, to show what each file reads of the others rather than how they run.
215
+ */
216
+ function analyzeProject(analyzer, everyFile = false) {
217
+ return analyzer.derive(everyFile ? analyzeEveryFile : analyzeProject, async () => {
218
+ const units = await projectFiles(analyzer, everyFile);
219
+ const deps = await cellDependencies(analyzer);
220
+ return units.length < 2 ? [] : cellFacts(units, await analyzer.normalize(), await analyzer.dataflow(), everyFile ? { ...deps, sources: [] } : deps, analyzer.inspectContext());
221
+ });
222
+ }
223
+ /* the key {@link analyzeProject} derives the facts of every file under */
224
+ const analyzeEveryFile = (analyzer) => analyzeProject(analyzer, true);
225
+ /** The names of files that run a project as a whole, as `main.R` or a makefile, which say in which order the other files run. */
226
+ const EntryFile = /(^|[\\/])(main|run|run_all|runall|make|_targets)\.R$|(^|[\\/])(Makefile|DESCRIPTION)$/i;
227
+ /**
228
+ * The file that says in which order the files of a project run, if the project has one: a file named like an entry
229
+ * (`main.R`, `_targets.R`, a makefile, a package's `DESCRIPTION`) in the root of the project, or an order flowR knows for sure, else `undefined`.
230
+ * An entry deeper down (a package in a subfolder) runs only its own part of the project.
231
+ */
232
+ function projectEntry(analyzer) {
233
+ const files = analyzer.inspectContext().files;
234
+ const root = files.root();
235
+ return files.getAllFiles().map(f => f.path()).find(p => EntryFile.test(p) && !/[\\/]/.test(root === undefined ? p : (0, files_1.relativeTo)(root, p))) ?? (files.loadingOrder.currentKnownOrder() === undefined ? undefined : 'the known loading order');
236
+ }
237
+ /** What a symbol stands for, said in words: `dplyr` as `package dplyr`, the state `option:digits` as `option digits`, or the name itself. */
238
+ function describeSymbol(symbol) {
239
+ switch (symbol.resource) {
240
+ case CellResource.Package: return `package ${symbol.name}`;
241
+ case CellResource.File: return `file ${symbol.name}`;
242
+ case CellResource.State: return symbol.name.replace(/:/g, ' ');
243
+ default: return symbol.name;
244
+ }
245
+ }
246
+ /** What a cell needs, said in words: `mutate (package dplyr)`, `file out`, `option digits`, or the name it reads. */
247
+ function describeNeed(need) {
248
+ switch (need.resource) {
249
+ case CellResource.Package: return `${need.name} (${need.anyOf.map(describeSymbol).join(' or ')})`;
250
+ case CellResource.File:
251
+ case CellResource.State: return describeSymbol(need);
252
+ default: return need.name;
253
+ }
254
+ }
255
+ const matches = (want, have) => want === SymbolKind.Any || have === SymbolKind.Any || want === have;
256
+ /** a variable is found in the global environment and beside it, where `attach` puts it */
257
+ const lookups = (want) => want.resource === CellResource.Variable ? [CellResource.Variable, CellResource.Attached] : [want.resource];
258
+ const binds = (have, want) => lookups(want).includes(have.resource) && have.name === want.name && matches(want.kind, have.kind);
259
+ exports.binds = binds;
260
+ const provides = (facts, want) => facts.effects.some(e => 'binds' in e && (0, exports.binds)(e.binds, want));
261
+ const bindsAnyOf = (e, want) => 'bindsAny' in e && lookups(want).includes(e.bindsAny);
262
+ /**
263
+ * What each of the `cells` needs and does, read off the one dataflow graph of the whole notebook: a cell needs what it
264
+ * reads before it binds it itself, the packages its calls come from, the files other cells write, and the global state
265
+ * (options, the seed, the plot, ...) it reads.
266
+ */
267
+ function cellFacts(cells, ast, df, deps, ctx) {
268
+ const graph = df.graph;
269
+ const lineCell = (id) => {
270
+ /* a call flowR makes up for an anonymous function a call runs (`Map(function(a) a + off, x)`) is where the function is */
271
+ const node = node_id_1.NodeId.nodeOf(id, ast.idMap);
272
+ const line = range_1.SourceRange.getStartLine(range_1.SourceRange.fromNode(node));
273
+ return line === undefined ? -1 : cells.findIndex(c => (c.file === undefined || c.file === node?.info.file) && line >= c.from && line <= c.to);
274
+ };
275
+ /* the code of a sourced script runs in the cell that sources it */
276
+ const sourcedBy = (deps.sources ?? []).flatMap(s => s.nodeId === undefined || typeof s.value !== 'string' || s.value === '' ? [] : [{ file: s.value, by: s.nodeId }]);
277
+ /* the code `eval` runs, which flowR links to it by a returns edge: quoted code of the notebook, or a string it parses into a tree of its own */
278
+ const evaluatedBy = new Map(graph.verticesOfType(vertex_1.VertexType.FunctionCall).filter(([, v]) => vertex_1.DfgVertex.hasOrigin(v, built_in_proc_name_1.BuiltInProcName.Eval))
279
+ .flatMap(([id]) => df_helper_1.Dataflow.targetsOf(graph, id, edge_1.EdgeType.Returns).map(t => [t, id])));
280
+ const rootOf = (id) => model_1.RNode.findEnclosing(id, ast.idMap, n => n.info.parent === undefined);
281
+ const parsedBy = new Map(evaluatedBy.entries().flatMap(([t, by]) => {
282
+ const root = rootOf(t);
283
+ return root === undefined || root === rootOf(by) ? [] : [[root, by]];
284
+ }));
285
+ /* the code of a string `eval(parse(text = "..."))` runs where the `eval` is */
286
+ const hostOf = (id) => {
287
+ const by = parsedBy.size === 0 ? undefined : parsedBy.get(rootOf(id));
288
+ return by === undefined ? id : hostOf(by);
289
+ };
290
+ /* the cell of a node, through as many files sourcing one another as it takes (a file sourced in a cycle stays where it is) */
291
+ const cellOf = (at, seen = new Set()) => {
292
+ const id = hostOf(at);
293
+ const file = ast.idMap.get(id)?.info.file;
294
+ const source = sourcedBy.find(s => file?.endsWith(s.file) === true && !seen.has(s.by));
295
+ return source === undefined ? lineCell(id) : cellOf(source.by, seen.add(source.by));
296
+ };
297
+ const posOf = (id) => range_1.SourceRange.fromNode(node_id_1.NodeId.nodeOf(hostOf(id), ast.idMap)) ?? [0, 0, 0, 0];
298
+ /* whether the code of `a` ends before that of `b` starts, so a removal is done before a read, not around it */
299
+ const endsBefore = (a, b) => {
300
+ const [ea, sb] = [posOf(a), posOf(b)];
301
+ return ea[2] < sb[0] || ea[2] === sb[0] && ea[3] < sb[1];
302
+ };
303
+ const before = (a, b) => {
304
+ const [pa, pb] = [posOf(a), posOf(b)];
305
+ return pa[0] - pb[0] || pa[1] - pb[1];
306
+ };
307
+ const raw = cells.map(() => ({ reads: [], effects: [] }));
308
+ const rangeOf = (id) => range_1.SourceRange.ownFromNode(ast.idMap.get(id));
309
+ const effect = (at, e) => at === undefined ? undefined : raw[cellOf(at)]?.effects.push({ at, effect: 'binds' in e ? { ...e, range: rangeOf(at), id: at } : e });
310
+ const read = (r) => raw[cellOf(r.id)]?.reads.push(r);
311
+ const removed = new Set();
312
+ const attachedAnywhere = new Set();
313
+ for (const lib of deps.libraries) {
314
+ if (lib.nodeId !== undefined && lib.value !== undefined && (0, library_functions_1.attachesPackage)(lib)) {
315
+ for (const pkg of [lib.value, ...df_helper_1.Dataflow.library.attaches(ctx, lib.value)]) {
316
+ attachedAnywhere.add(pkg);
317
+ effect(lib.nodeId, { binds: resource(CellResource.Package, pkg) });
318
+ }
319
+ }
320
+ }
321
+ const qualified = df_helper_1.Dataflow.qualifyAll(graph);
322
+ /* the function a call calls, a built-in flowR cannot tie to a package (as no package database says where `data.frame` comes from) by its name */
323
+ const calledFunction = (id) => {
324
+ const call = graph.getVertex(id);
325
+ return qualified.get(id) ?? (vertex_1.DfgVertex.isFunctionCall(call) && df_helper_1.Dataflow.origin(graph, id)?.some(o => o.type === 3 /* OriginType.BuiltInFunctionOrigin */) ? call.name : undefined);
326
+ };
327
+ /* the bodies of the functions, which run only once called */
328
+ /* the code of a file a function sources (`source("a.R", local = TRUE)`) is part of the body only where the file runs as part of the one sourcing it, with the call flowR makes up for an anonymous function where the function is */
329
+ const fileOf = (id) => node_id_1.NodeId.nodeOf(id, ast.idMap)?.info.file;
330
+ const bodies = new Set(graph.verticesOfType(vertex_1.VertexType.FunctionDefinition).flatMap(([fn, f]) => [...f.subflow.graph].filter(id => {
331
+ const file = fileOf(id);
332
+ return file === fileOf(fn) || sourcedBy.some(s => file?.endsWith(s.file) === true);
333
+ })));
334
+ /* what `local(...)` and `with(...)` define stays in an environment of their own */
335
+ const scoped = new Set(graph.verticesOfType(vertex_1.VertexType.FunctionCall).filter(([, v]) => vertex_1.DfgVertex.hasOrigin(v, built_in_proc_name_1.BuiltInProcName.Local) || vertex_1.DfgVertex.hasOrigin(v, built_in_proc_name_1.BuiltInProcName.With))
336
+ .flatMap(([id]) => {
337
+ const call = ast.idMap.get(id);
338
+ return call === undefined ? [] : [...model_1.RNode.collectAllIds(call)].filter(inner => inner !== id);
339
+ }));
340
+ const calls = [];
341
+ const inFormula = (id) => model_1.RNode.findEnclosing(id, ast.idMap, n => r_binary_op_1.RBinaryOp.is(n) && n.operator === '~') !== undefined;
342
+ const resolveInfo = { ...resolve_helper_1.Resolve.info(graph, ctx), idMap: ast.idMap, graph };
343
+ const runsOnce = (loop) => {
344
+ const node = ast.idMap.get(loop);
345
+ return r_for_loop_1.RForLoop.is(node) && (0, built_in_for_loop_1.runsBodyOnce)(node, resolveInfo);
346
+ };
347
+ /* the code each cell runs itself, not the bodies of the functions it defines */
348
+ const scopes = cells.map(() => new Set());
349
+ for (const [id] of graph.vertices(true)) {
350
+ if (!bodies.has(id)) {
351
+ scopes[cellOf(id)]?.add(id);
352
+ }
353
+ }
354
+ const values = valueReads(graph, ast, qualified);
355
+ /* what `attach` brings in (flowR links it to the attach) the attach binds, not the assignment that bound it before (`e$v <- 1; attach(e)`) */
356
+ const attachedBy = (o) => {
357
+ const by = df_helper_1.Dataflow.targetsOf(graph, o.id, edge_1.EdgeType.Reads).find(t => vertex_1.DfgVertex.hasOrigin(graph.getVertex(t), built_in_proc_name_1.BuiltInProcName.Attach));
358
+ return by === undefined ? o : { type: 4 /* OriginType.ConstantOrigin */, id: by };
359
+ };
360
+ const unknownEffects = new Set(graph.unknownSideEffects.values().map(graph_1.UnknownSideEffect.id));
361
+ /* whether the condition `id` decides an `if` whose branches stop the cell (`if (!exists("x")) stop()`), or `stopifnot` asserts it */
362
+ const stopsOn = (id) => {
363
+ const enclosing = model_1.RNode.findEnclosing(id, ast.idMap, n => r_if_then_else_1.RIfThenElse.is(n) || r_function_call_1.RFunctionCall.isNamed(n, identifier_1.Identifier.make('stopifnot')));
364
+ const at = enclosing === undefined ? undefined : ast.idMap.get(enclosing);
365
+ if (!r_if_then_else_1.RIfThenElse.is(at)) {
366
+ return at !== undefined;
367
+ }
368
+ return [at.then, ...at.otherwise === undefined ? [] : [at.otherwise]].some(b => [...model_1.RNode.collectAllIds(b)].some(n => r_function_call_1.RFunctionCall.isNamed(ast.idMap.get(n), identifier_1.Identifier.make('stop'))));
369
+ };
370
+ /* whether `id` runs in the expression of `try(...)` or of `tryCatch(..., error = )`, which catches its failure */
371
+ const caught = (id) => {
372
+ for (let at = ast.idMap.get(id); at !== undefined;) {
373
+ const parent = model_1.RNode.directParent(at, ast.idMap);
374
+ if (r_function_call_1.RFunctionCall.is(parent) && vertex_1.DfgVertex.hasOrigin(graph.getVertex(parent.info.id), built_in_proc_name_1.BuiltInProcName.Try) && parent.arguments.find(a => a !== r_function_call_1.EmptyArgument) === at
375
+ && (r_function_call_1.RFunctionCall.isNamed(parent, identifier_1.Identifier.make('try')) || parent.arguments.some(a => a !== r_function_call_1.EmptyArgument && a.name?.content === identifier_1.Identifier.make('error')))) {
376
+ return true;
377
+ }
378
+ at = parent;
379
+ }
380
+ return false;
381
+ };
382
+ /* a read that only runs once `exists("x")` said so (`if (exists("x")) x`) runs either way, without it it is just skipped */
383
+ const existsGuarded = (cds, name) => (cds ?? []).some(cd => {
384
+ const node = ast.idMap.get(cd.id);
385
+ const condition = r_if_then_else_1.RIfThenElse.is(node) ? node.condition : node;
386
+ return r_function_call_1.RFunctionCall.isNamed(condition, identifier_1.Identifier.make('exists')) && condition.arguments.some(a => {
387
+ const value = valueOf(a === r_function_call_1.EmptyArgument ? undefined : a);
388
+ return r_string_1.RString.is(value) && value.content.str === name;
389
+ });
390
+ });
391
+ /* the cells that source code flowR cannot see, which may define the functions no cell defines */
392
+ const unseenSources = new Set();
393
+ for (const [id, vertex] of graph.vertices(true)) {
394
+ /* a load or attach that binds names flowR does not know may bind any name */
395
+ const into = vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Load) ? CellResource.Variable : vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Attach) ? CellResource.Attached : undefined;
396
+ if (vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Source) && unknownEffects.has(id) && !bodies.has(id) && !inOtherEnvironment(vertex, ast)) {
397
+ unseenSources.add(cellOf(id));
398
+ }
399
+ if (into !== undefined && unknownEffects.has(id) && !bodies.has(id) && !inOtherEnvironment(vertex, ast)) {
400
+ effect(id, { bindsAny: into });
401
+ }
402
+ else if (into === CellResource.Attached && !bodies.has(id)) {
403
+ attachedNames(graph, ast, id).forEach(name => effect(id, { binds: resource(CellResource.Attached, name) }));
404
+ }
405
+ /* what `rm` removes, read off the call itself: flowR applies a removal within the file it is in, and knows none of a name not bound yet */
406
+ /* in a function body only a removal from the global environment counts, where the function is called */
407
+ const inBody = bodies.has(id);
408
+ if (vertex_1.DfgVertex.isFunctionCall(vertex) && vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Rm) && (!inBody || inGlobalEnvironment(vertex, ast) === true)) {
409
+ const fn = inBody ? model_1.RNode.findEnclosing(id, ast.idMap, r_function_definition_1.RFunctionDefinition.is) : undefined;
410
+ const at = fn === undefined ? [id] : graph.ingoingEdges(fn)?.entries().filter(([, e]) => edge_1.DfEdge.includesType(e, edge_1.EdgeType.Calls)).map(([from]) => from).toArray() ?? [];
411
+ /* what it names it never reads, but within `local` or another environment it removes no global */
412
+ const remove = scoped.has(id) || inOtherEnvironment(vertex, ast) ? () => undefined : (e) => at.forEach(a => effect(a, e));
413
+ for (const arg of vertex.args.filter(graph_1.FunctionArgument.isPositional)) {
414
+ const name = r_string_1.RString.unquote(node_id_1.NodeId.recoverName(arg.nodeId, ast.idMap) ?? '');
415
+ if (name !== '') {
416
+ removed.add(arg.nodeId);
417
+ remove({ removes: resource(CellResource.Variable, name) });
418
+ }
419
+ }
420
+ const list = vertex.args.find(a => a !== r_function_call_1.EmptyArgument && a.name === 'list');
421
+ const value = list === undefined || list === r_function_call_1.EmptyArgument ? undefined : valueOf(ast.idMap.get(list.nodeId));
422
+ const strings = (node) => [...node === undefined ? [] : model_1.RNode.collectAllIds(node)].map(i => ast.idMap.get(i)).filter(r_string_1.RString.is).map(n => n.content.str);
423
+ if (value === undefined) {
424
+ continue;
425
+ }
426
+ /* `rm(list = setdiff(ls(), "x"))` clears all but the names it keeps, `rm(list = "x")` removes those it names, anything else all */
427
+ if (r_function_call_1.RFunctionCall.isNamed(value, identifier_1.Identifier.make('setdiff')) && value.arguments[0] !== r_function_call_1.EmptyArgument && r_function_call_1.RFunctionCall.isNamed(valueOf(value.arguments[0]), identifier_1.Identifier.make('ls'))) {
428
+ remove({ clears: true, except: value.arguments.slice(1).flatMap(a => a === r_function_call_1.EmptyArgument ? [] : strings(a)) });
429
+ }
430
+ else if (r_string_1.RString.is(value) || r_function_call_1.RFunctionCall.isNamed(value, identifier_1.Identifier.make('c')) && value.arguments.every(a => a !== r_function_call_1.EmptyArgument && r_string_1.RString.is(valueOf(a)))) {
431
+ strings(value).forEach(name => remove({ removes: resource(CellResource.Variable, name) }));
432
+ }
433
+ else {
434
+ remove({ clears: true });
435
+ }
436
+ }
437
+ }
438
+ /* `knitr::opts_chunk$set(eval = FALSE)` keeps the chunks after it from running, `error = TRUE` lets knitting go on after an error, `opts_knit$set(global.device = TRUE)` keeps the plot */
439
+ for (const [id] of graph.verticesOfType(vertex_1.VertexType.FunctionCall).filter(([id]) => !bodies.has(id) && cells[cellOf(id)]?.runner === cell_runner_1.CellRunner.Knitr)) {
440
+ const node = ast.idMap.get(id);
441
+ const fn = r_function_call_1.RFunctionCall.isUnnamed(node) ? node.calledFunction : undefined;
442
+ const options = r_access_1.RAccess.isNamed(fn) && r_symbol_1.RSymbol.is(fn.accessed) && fn.access[0].value?.lexeme === 'set' ? KnitrOptions.get(String(identifier_1.Identifier.getName(fn.accessed.content))) : undefined;
443
+ if (!r_function_call_1.RFunctionCall.isUnnamed(node) || options === undefined) {
444
+ continue;
445
+ }
446
+ /* the options are given one by one or as a list (`opts_knit$set(list(global.par = TRUE))`) */
447
+ for (const arg of node.arguments.flatMap(a => {
448
+ const value = valueOf(a === r_function_call_1.EmptyArgument ? undefined : a);
449
+ return a !== r_function_call_1.EmptyArgument && a.name === undefined && r_function_call_1.RFunctionCall.isNamed(value, identifier_1.Identifier.make('list')) ? value.arguments : [a];
450
+ })) {
451
+ const option = arg === r_function_call_1.EmptyArgument ? undefined : Object.hasOwn(options, String(arg.name?.content)) ? options[String(arg.name?.content)] : undefined;
452
+ const value = valueOf(arg === r_function_call_1.EmptyArgument ? undefined : arg);
453
+ /* a value other than a logical constant (`eval = answers`) flowR does not know */
454
+ if (option !== undefined && (r_logical_1.RLogical.is(value) || r_symbol_1.RSymbol.is(value) && (value.lexeme === 'T' || value.lexeme === 'F'))) {
455
+ effect(id, option[1].has(value.lexeme) ? { binds: option[0] } : { removes: option[0] });
456
+ }
457
+ }
458
+ }
459
+ /* the code `quote` holds runs where an `eval` runs it, else nowhere */
460
+ const runsAt = (id) => {
461
+ if (model_1.RNode.findEnclosing(id, ast.idMap, n => vertex_1.DfgVertex.hasOrigin(graph.getVertex(n.info.id), built_in_proc_name_1.BuiltInProcName.Quote)) === undefined) {
462
+ return id;
463
+ }
464
+ const evaluated = model_1.RNode.findEnclosing(id, ast.idMap, n => evaluatedBy.has(n.info.id));
465
+ return evaluated === undefined ? undefined : evaluatedBy.get(evaluated);
466
+ };
467
+ const bindings = [];
468
+ for (const [id, vertex] of graph.vertices(true)) {
469
+ /* where the code runs, which for quoted code is where it is evaluated */
470
+ const at = runsAt(id);
471
+ const c = at === undefined ? -1 : cellOf(at);
472
+ if (at === undefined || c < 0 || removed.has(id) || bodies.has(id) || r_argument_1.RArgument.is(ast.idMap.get(id))) {
473
+ continue;
474
+ }
475
+ /* the name a call resolved to, as an operator's lexeme is all of `x %>% f` */
476
+ const name = vertex_1.DfgVertex.isFunctionCall(vertex) ? identifier_1.Identifier.getName(vertex.name) : node_id_1.NodeId.recoverName(id, ast.idMap);
477
+ /* `knitr::opts_chunk` reads no global */
478
+ const node = ast.idMap.get(id);
479
+ if (name === undefined || r_symbol_1.RSymbol.is(node) && identifier_1.Identifier.getNamespace(node.content) !== undefined) {
480
+ continue;
481
+ }
482
+ /* a partial definition (`x[1] <- 5`, `x$a <- 1`) changes what is bound already, so it reads it and binds it anew */
483
+ const partial = vertex_1.DfgVertex.isVariableDefinition(vertex) && vertex.par === true;
484
+ /* the left side of an assigning pipe (`x %<>% rev`) is what the call it is piped into reads, before it is bound anew */
485
+ const piped = vertex_1.DfgVertex.isVariableDefinition(vertex) && graph.ingoingEdges(id)?.values().some(e => edge_1.DfEdge.includesType(e, edge_1.EdgeType.Reads) && edge_1.DfEdge.includesType(e, edge_1.EdgeType.Argument)) === true;
486
+ if (vertex_1.DfgVertex.isVariableDefinition(vertex)) {
487
+ /* `x <<- 1` within `local` binds the global `x`, `assign("x", 1, envir = e)` does not */
488
+ const global = scoped.has(id) ? df_helper_1.Dataflow.definedBySuperAssignment(graph, id) : !df_helper_1.Dataflow.targetsOf(graph, id, edge_1.EdgeType.DefinedBy).some(t => inOtherEnvironment(graph.getVertex(t), ast));
489
+ if (global) {
490
+ effect(at, { binds: variable(r_string_1.RString.unquote(name), partial ? SymbolKind.Any : boundKind(graph, id)) });
491
+ bindings.push({ at, frame: r_string_1.RString.unquote(name), ...addedColumns(id, graph, ast, qualified, partial || piped, attachedAnywhere) });
492
+ }
493
+ if (!piped && !partial) {
494
+ continue;
495
+ }
496
+ }
497
+ const call = vertex_1.DfgVertex.isFunctionCall(vertex);
498
+ /* an assignment reads what it assigns, not a function (flowR may link one within `local` to the function it returns) */
499
+ const assignment = vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Assignment) || vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.SuperAssignment);
500
+ /* an operator that assigns (`x %<>% rev`, which flowR runs as `x <- rev(x)`) is a call of the package it comes from */
501
+ const written = r_binary_op_1.RBinaryOp.is(node) ? identifier_1.Identifier.make(node.operator) : r_function_call_1.RFunctionCall.isNamed(node) ? identifier_1.Identifier.getName(node.functionName.content) : undefined;
502
+ if (assignment && vertex_1.DfgVertex.isFunctionCall(vertex) && written !== undefined && written !== identifier_1.Identifier.getName(vertex.name)) {
503
+ read({ ...variable(String(written), SymbolKind.Function), id: at, call: true });
504
+ }
505
+ if (!call && !partial && !piped && !vertex_1.DfgVertex.isUse(vertex) || call && (assignment || identifier_1.Identifier.getNamespace(vertex.name) !== undefined)) {
506
+ continue;
507
+ }
508
+ /* what a partial definition reads: the definitions of its name before it (or the lazy data it changes), not the replacement call it reads as well */
509
+ const user = (partial || piped ? df_helper_1.Dataflow.targetsOf(graph, id, edge_1.EdgeType.Reads).filter(t => vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(t)) || vertex_1.DfgVertex.hasOrigin(graph.getVertex(t), built_in_proc_name_1.BuiltInProcName.Library)).map((target) => ({ type: 0 /* OriginType.ReadVariableOrigin */, id: target })) : definedBy(graph, id)).map(attachedBy)
510
+ /* a formula (`lm(mpg ~ wt, data = d)`) finds the columns of its data before the lazy data of a package */
511
+ .filter(o => !inFormula(id) || !vertex_1.DfgVertex.hasOrigin(graph.getVertex(o.id), built_in_proc_name_1.BuiltInProcName.Library));
512
+ const kind = call ? SymbolKind.Function : values.has(id) ? SymbolKind.Value : SymbolKind.Any;
513
+ /* `get("x")` and `exists("x")` read the name they are given (flowR resolves it on a vertex of its own), unless the cell binds it itself */
514
+ if (call && vertex_1.DfgVertex.hasOrigin(vertex, built_in_proc_name_1.BuiltInProcName.Get)) {
515
+ const first = r_function_call_1.RFunctionCall.is(node) ? node.arguments.find(a => a !== r_function_call_1.EmptyArgument) : undefined;
516
+ const named = valueOf(first);
517
+ const target = vertex.args.find(a => a !== r_function_call_1.EmptyArgument);
518
+ const resolved = target === undefined ? [] : definedBy(graph, target.nodeId);
519
+ if (r_string_1.RString.is(named) && (resolved.length === 0 || resolved.some(o => cellOf(o.id) !== c || before(o.id, id) > 0))) {
520
+ /* `exists` and `get0` ask without failing, so what it reads changes only what the cell does, unless the cell stops without it */
521
+ const asks = (r_function_call_1.RFunctionCall.isNamed(node, identifier_1.Identifier.make('exists')) || r_function_call_1.RFunctionCall.isNamed(node, identifier_1.Identifier.make('get0'))) && !stopsOn(id);
522
+ /* `get("c")` finds a function of R as well, which a plain read like `lm(data = data)` cannot use */
523
+ const ofR = (0, r_base_packages_1.baseRExportOwner)(named.content.str) !== undefined;
524
+ read({ ...variable(named.content.str, SymbolKind.Any), id, call: false, ...asks || ofR ? { soft: true } : {} });
525
+ }
526
+ }
527
+ if (call) {
528
+ calls.push(id);
529
+ }
530
+ /* a definition of the cell itself only satisfies the read if it always happens before */
531
+ const local = (o) => cellOf(o.id) === c && before(o.id, at) < 0 && (vertex.cds !== undefined || unconditional(graph, o.id, runsOnce));
532
+ /* one that always happens before satisfies it whatever else may reach it (`i <- 1; while (i < 9) i <- i + 1`), as does one under the same conditions as the read (`g({ x <- 1; x })`) */
533
+ const dominates = (o) => local(o) && !bodies.has(o.id) && unconditional(graph, o.id, runsOnce, vertex.cds);
534
+ /* a call of what an expression gives (`opts_chunk$set(...)`) names nothing it reads, but runs what the function it gives reads */
535
+ if ((!user.every(local) && !user.some(dominates) || user.length === 0) && !r_function_call_1.RFunctionCall.isUnnamed(node)) {
536
+ /* lazy data (`lung` once `library(survival)` ran) needs the package that ships it attached, as a cell binding the name would do */
537
+ const lazy = user.filter(o => vertex_1.DfgVertex.hasOrigin(graph.getVertex(o.id), built_in_proc_name_1.BuiltInProcName.Library)).flatMap(o => raw[cellOf(o.id)]?.effects
538
+ .flatMap(e => e.at === o.id && 'binds' in e.effect && e.effect.binds.resource === CellResource.Package ? [e.effect.binds] : []) ?? []);
539
+ read({ ...variable(name, kind), id: at, call, ...existsGuarded(vertex.cds, name) || caught(id) ? { soft: true } : {}, ...partial ? { changes: true } : {}, ...lazy.length > 0 ? { or: lazy } : {} });
540
+ /* what flowR resolves the read to binds the name, even where no assignment does (`attach`, `assign`, ...) */
541
+ /* unless it reads a variable, as calling `g` after `g <- make()` reaches the function `make` returns as well */
542
+ const assigned = user.some(o => o.type === 0 /* OriginType.ReadVariableOrigin */);
543
+ for (const o of assigned ? [] : user.filter(o => !local(o) && !isAssigned(graph, o.id) && !vertex_1.DfgVertex.hasOrigin(graph.getVertex(o.id), built_in_proc_name_1.BuiltInProcName.Library))) {
544
+ effect(o.id, { binds: { resource: CellResource.Attached, name, kind } });
545
+ }
546
+ }
547
+ }
548
+ /* the data the closest call around a read is given (`data = d`, its first argument, or what is piped into it) */
549
+ const dataOf = (id) => {
550
+ for (let from = ast.idMap.get(id), at = from === undefined ? undefined : model_1.RNode.directParent(from, ast.idMap); at !== undefined; from = at, at = model_1.RNode.directParent(at, ast.idMap)) {
551
+ const args = r_function_call_1.RFunctionCall.is(at) ? at.arguments.flatMap(a => a === r_function_call_1.EmptyArgument || a === from ? [] : [a]) : [];
552
+ const data = args.find(a => a.name !== undefined && ['data', '.data'].includes(String(identifier_1.Identifier.getName(a.name.content)))) ?? (r_function_call_1.RFunctionCall.is(at) && at.arguments[0] === from ? undefined : args.find(a => a.name === undefined));
553
+ /* a call masking its first argument too (`aes(x, y)`) has no data of its own */
554
+ if (data !== undefined && !(r_function_call_1.RFunctionCall.is(at) && data.value !== undefined && maskedBy(at.info.id, data.value.info.id))) {
555
+ return data.value;
556
+ }
557
+ }
558
+ return undefined;
559
+ };
560
+ /* the columns the data certainly has, as the call making it names them (`data.frame(x = 1)`), also through every assignment a name reads */
561
+ const madeColumns = (node) => {
562
+ if (r_symbol_1.RSymbol.is(node)) {
563
+ const made = (df_helper_1.Dataflow.origin(graph, node.info.id) ?? []).map(o => {
564
+ const def = o.type === 0 /* OriginType.ReadVariableOrigin */ ? ast.idMap.get(o.id) : undefined;
565
+ const assignment = def === undefined ? undefined : model_1.RNode.directParent(def, ast.idMap);
566
+ return r_binary_op_1.RBinaryOp.is(assignment) && assignment.lhs.info.id === o.id && vertex_1.DfgVertex.hasOrigin(graph.getVertex(assignment.info.id), built_in_proc_name_1.BuiltInProcName.Assignment) ? madeColumns(assignment.rhs) : [];
567
+ });
568
+ return made.length === 0 ? [] : made.reduce((a, b) => a.filter(c => b.includes(c)));
569
+ }
570
+ const fn = r_function_call_1.RFunctionCall.is(node) ? calledFunction(node.info.id) : undefined;
571
+ return fn !== undefined && r_function_call_1.RFunctionCall.is(node) && FrameMakers.some(m => identifier_1.Identifier.matches(fn, m))
572
+ ? node.arguments.flatMap(a => a === r_function_call_1.EmptyArgument || a.name === undefined ? [] : [String(identifier_1.Identifier.getName(a.name.content))]) : [];
573
+ };
574
+ /* a name a data mask reads (`aes(x = x)` within `ggplot(d, ...)`, `lm(y ~ x, data = d)`) is the column of the data where the data has it, as R asks the data first */
575
+ const masked = (id) => graph.edgesTo(id).entries().some(([from, e]) => edge_1.DfEdge.includesType(e, edge_1.EdgeType.NonStandardEvaluation) && vertex_1.DfgVertex.isFunctionCall(graph.getVertex(from)));
576
+ const maskedBy = (call, id) => {
577
+ const edge = graph.edgesTo(id).get(call);
578
+ return edge !== undefined && edge_1.DfEdge.includesType(edge, edge_1.EdgeType.NonStandardEvaluation);
579
+ };
580
+ /* the state a call puts the object its first argument names in, or needs it in, as flowR's built-ins state */
581
+ const builtIns = (0, query_fn_props_1.builtInLookup)(ctx);
582
+ const objectStates = new Set();
583
+ for (const [id, vertex] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
584
+ /* a function of a package flowR does not resolve the call to is that of an attached package stating it */
585
+ const stated = bodies.has(id) ? undefined : builtIns(qualified.get(id) ?? vertex.name)?.objectState
586
+ ?? attachedAnywhere.values().map(p => builtIns(identifier_1.Identifier.make(identifier_1.Identifier.getName(vertex.name), p))?.objectState).find(s => s !== undefined);
587
+ const first = vertex.args.find(a => a !== r_function_call_1.EmptyArgument);
588
+ const object = stated === undefined || first === undefined ? undefined : valueOf(ast.idMap.get(first.nodeId));
589
+ if (stated === undefined || !r_symbol_1.RSymbol.is(object)) {
590
+ continue;
591
+ }
592
+ const state = (name) => resource(CellResource.ObjectState, `${identifier_1.Identifier.getName(object.content)}#${name}`);
593
+ if (stated.needs !== undefined) {
594
+ read({ ...state(stated.needs), id, call: false });
595
+ objectStates.add(state(stated.needs).name);
596
+ }
597
+ if (stated.sets !== undefined) {
598
+ effect(id, { binds: state(stated.sets) });
599
+ objectStates.add(state(stated.sets).name);
600
+ }
601
+ }
602
+ for (const { at, frame } of bindings.filter(b => !b.keeps)) {
603
+ objectStates.values().filter(s => s.startsWith(`${frame}#`)).forEach(s => effect(at, { removes: resource(CellResource.ObjectState, s) }));
604
+ }
605
+ /* the variables the formula of the model a definition fits reads (`m <- lm(y ~ a + log(b))`), if flowR knows them */
606
+ const termsOf = (def) => {
607
+ const target = ast.idMap.get(def);
608
+ const assignment = target === undefined ? undefined : model_1.RNode.directParent(target, ast.idMap);
609
+ const fit = r_binary_op_1.RBinaryOp.is(assignment) && assignment.lhs.info.id === def ? assignment.rhs : undefined;
610
+ const fn = r_function_call_1.RFunctionCall.is(fit) ? calledFunction(fit.info.id) : undefined;
611
+ const formula = fn !== undefined && ModelFitters.some(m => identifier_1.Identifier.matches(fn, m)) && r_function_call_1.RFunctionCall.is(fit)
612
+ ? valueOf(fit.arguments.flatMap(a => a === r_function_call_1.EmptyArgument ? [] : [a]).find(a => a.name === undefined || identifier_1.Identifier.getName(a.name.content) === 'formula')) : undefined;
613
+ if (!r_binary_op_1.RBinaryOp.is(formula) || formula.operator !== '~') {
614
+ return undefined;
615
+ }
616
+ const symbols = [...model_1.RNode.collectAllIds(formula.rhs)].map(id => ast.idMap.get(id)).filter(n => r_symbol_1.RSymbol.is(n) && !r_function_call_1.RFunctionCall.isNamed(model_1.RNode.directParent(n, ast.idMap)));
617
+ return symbols.some(n => r_symbol_1.RSymbol.is(n) && n.lexeme === '.') ? undefined : symbols.flatMap(n => r_symbol_1.RSymbol.is(n) ? [n.lexeme] : []);
618
+ };
619
+ /* R finds a variable the new data lacks where the formula was made, which only a binding no cell makes (an unknown one) leaves out */
620
+ const boundAnywhere = (name) => providedByR(name, SymbolKind.Value) || raw.some(r => r.effects.some(e => 'bindsAny' in e.effect || 'binds' in e.effect && e.effect.binds.name === name));
621
+ /* `predict(m, newdata = data.frame(a = 1))` needs a cell to have fitted `m` of no variable but those of the new data, which binding `m` anew takes away */
622
+ for (const [id] of graph.verticesOfType(vertex_1.VertexType.FunctionCall)) {
623
+ const fn = bodies.has(id) ? undefined : calledFunction(id);
624
+ const node = ast.idMap.get(id);
625
+ if (fn === undefined || !Predictors.some(p => identifier_1.Identifier.matches(fn, p)) || !r_function_call_1.RFunctionCall.is(node)) {
626
+ continue;
627
+ }
628
+ const args = node.arguments.flatMap(a => a === r_function_call_1.EmptyArgument ? [] : [a]);
629
+ const positional = args.filter(a => a.name === undefined);
630
+ const model = valueOf(positional[0]);
631
+ const columns = madeColumns(valueOf(args.find(a => a.name !== undefined && identifier_1.Identifier.getName(a.name.content) === 'newdata') ?? positional[1]));
632
+ const fitted = r_symbol_1.RSymbol.is(model) ? bindings.filter(b => b.frame === identifier_1.Identifier.getName(model.content) && !b.keeps) : [];
633
+ const fits = (def) => termsOf(def)?.every(t => columns.includes(t) || boundAnywhere(t)) ?? true;
634
+ if (!r_symbol_1.RSymbol.is(model) || columns.length === 0 || fitted.every(b => fits(b.at))) {
635
+ continue;
636
+ }
637
+ const state = resource(CellResource.ObjectState, `${identifier_1.Identifier.getName(model.content)}#fits:${columns.join(',')}`);
638
+ read({ ...state, id, call: false });
639
+ fitted.forEach(b => effect(b.at, fits(b.at) ? { binds: state } : { removes: state }));
640
+ }
641
+ /* the columns of the frames whose columns a cell changes, as named or read; a binding not building on the frame may bind any of them */
642
+ const known = new Map();
643
+ bindings.forEach(({ frame, ops }) => ops.forEach(o => ('add' in o ? [o.add] : 'drop' in o ? [o.drop] : o.keep).forEach(c => (known.get(frame) ?? known.set(frame, new Set()).get(frame))?.add(c))));
644
+ raw.flatMap(r => r.reads).filter(r => !r.call).forEach(r => known.get(rootFrame(dataOf(r.id)) ?? '')?.add(r.name));
645
+ const added = (frame, name) => bindings.some(b => b.frame === frame && b.ops.some(o => 'add' in o && o.add === name));
646
+ const maybe = (frame, name) => column(frame, `${name}?`);
647
+ for (const { at, frame, ops, keeps } of bindings.filter(b => known.has(b.frame))) {
648
+ const all = [...known.get(frame) ?? []];
649
+ const removes = (names) => names.forEach(c => [column(frame, c), maybe(frame, c)].forEach(s => effect(at, { removes: s })));
650
+ if (!keeps) {
651
+ removes(all);
652
+ all.forEach(c => effect(at, { binds: maybe(frame, c) }));
653
+ }
654
+ for (const o of ops) {
655
+ removes('add' in o ? [] : 'drop' in o ? [o.drop] : all.filter(c => !o.keep.includes(c)));
656
+ ('add' in o ? [o.add] : 'drop' in o ? [] : o.keep).forEach(c => effect(at, { binds: column(frame, c) }));
657
+ }
658
+ }
659
+ /* a column a cell adds was not there before, any other may come with the frame unless a cell drops it */
660
+ const columnRead = (id, name) => {
661
+ const frame = rootFrame(dataOf(id));
662
+ const drops = bindings.some(b => b.frame === frame && b.ops.some(o => !('add' in o)));
663
+ return frame === undefined || !known.has(frame) ? [] : added(frame, name) ? [column(frame, name)] : drops ? [column(frame, name), maybe(frame, name)] : [];
664
+ };
665
+ /* unless a cell may drop the column again */
666
+ const inData = (id, name) => masked(id) && madeColumns(dataOf(id)).includes(name) && columnRead(id, name).length === 0;
667
+ /* a call above the definition of its function (`g()` before a cell binds `g <- function() ...`) runs the functions the other cells bind under its name */
668
+ const definitions = df_helper_1.Dataflow.definitionsByName(graph);
669
+ const byName = new Map();
670
+ const targetsOf = (call) => {
671
+ const found = df_helper_1.Dataflow.callTargetsOf(call, graph);
672
+ const vertex = graph.getVertex(call);
673
+ if (found.length > 0 || !vertex_1.DfgVertex.isFunctionCall(vertex) || identifier_1.Identifier.getNamespace(vertex.name) !== undefined) {
674
+ return found;
675
+ }
676
+ if (!byName.has(call)) {
677
+ byName.set(call, definitions.get(identifier_1.Identifier.getName(vertex.name)).filter(d => !bodies.has(d) && cellOf(d) !== cellOf(call))
678
+ .flatMap(d => df_helper_1.Dataflow.valueSources(d, graph) ?? []).filter(t => vertex_1.DfgVertex.isFunctionDefinition(graph.getVertex(t))));
679
+ }
680
+ return byName.get(call);
681
+ };
682
+ /* calling a function reads what its body leaves open (and that of whatever it calls), wherever the function was defined */
683
+ for (const id of calls) {
684
+ for (const open of openReadsOfCalled(id, graph, scoped, targetsOf)) {
685
+ const name = node_id_1.NodeId.recoverName(open, ast.idMap);
686
+ const call = vertex_1.DfgVertex.isFunctionCall(graph.getVertex(open));
687
+ if (name !== undefined) {
688
+ read({ ...variable(name, call ? SymbolKind.Function : values.has(open) ? SymbolKind.Value : SymbolKind.Any), id, call, deferred: true });
689
+ }
690
+ }
691
+ }
692
+ /* a file read is a hard need where the project does not have the file, so only the cell writing it can make it */
693
+ const fileReads = new Map(deps.reads.flatMap(r => r.nodeId === undefined || typeof r.value !== 'string' ? [] : [[r.nodeId, !ctx.files.hasFile(r.value)]]));
694
+ /* the search path entry each attach makes and each detach takes away, by its name */
695
+ const entries = new Map();
696
+ const detached = new Map();
697
+ /* what each cell does to the global state, through the functions it calls as well, where flowR knows it */
698
+ let functions;
699
+ for (const [c, scope] of scopes.entries()) {
700
+ /* and what the functions it runs only by name access */
701
+ const named = calls.filter(id => scope.has(id)).flatMap(id => byName.get(id) ?? []);
702
+ functions ??= named.length === 0 ? undefined : df_helper_1.Dataflow.sideEffects.ambientAccessOfFunctions(df);
703
+ const ambient = monoid_1.Monoid.fold(ambient_access_1.AmbientAccess.monoid, [df_helper_1.Dataflow.sideEffects.ambientAccess(df, scope), ...named.flatMap(fn => functions?.get(fn) ?? [])]);
704
+ const into = (e, at) => raw[c].effects.push({ at, effect: 'binds' in e ? { ...e, range: rangeOf(at), id: at } : e });
705
+ const stateOf = (name) => name.startsWith('file:') ? resource(CellResource.File, name.slice(5)) : resource(CellResource.State, name);
706
+ for (const [state, ids] of ambient[ambient_access_1.AmbientAccessKind.Write]) {
707
+ const name = trackedState(String(state));
708
+ const entry = SearchPathEntry.exec(name ?? '')?.[1];
709
+ for (const id of name === undefined ? [] : ids) {
710
+ const detaches = vertex_1.DfgVertex.hasOrigin(graph.getVertex(id), built_in_proc_name_1.BuiltInProcName.Detach);
711
+ if (entry !== undefined && vertex_1.DfgVertex.hasOrigin(graph.getVertex(id), built_in_proc_name_1.BuiltInProcName.Attach)) {
712
+ entries.set(id, name);
713
+ }
714
+ if (entry === undefined || !detaches) {
715
+ into({ binds: stateOf(name) }, id);
716
+ }
717
+ }
718
+ }
719
+ for (const [state, ids] of ambient[ambient_access_1.AmbientAccessKind.Read]) {
720
+ const name = trackedState(String(state));
721
+ /* asking for a file (`file.exists`) changes only what the cell does, unless the cell stops without it */
722
+ ids.forEach(id => name === undefined ? undefined : raw[c].reads.push({ ...stateOf(name), id, call: false, soft: fileReads.get(id) === true || stateOf(name).resource === CellResource.File && stopsOn(id) ? undefined : true }));
723
+ }
724
+ for (const [state, ids] of ambient[ambient_access_1.AmbientAccessKind.Kill]) {
725
+ const name = trackedState(String(state));
726
+ /* `detach(package:dplyr)` takes the package off the search path, and fails if it is not on it */
727
+ const pkg = SearchPathEntry.exec(name ?? '')?.[1];
728
+ ids.forEach(id => name === undefined ? undefined : into({ removes: pkg === undefined ? stateOf(name) : resource(CellResource.Package, pkg) }, id));
729
+ ids.forEach(id => pkg === undefined ? undefined : detached.set(id, name));
730
+ }
731
+ /* the global variables the functions it calls bind, as `x <<- 1` in a function body does */
732
+ for (const [name, ids] of ambient.variables) {
733
+ ids.forEach(id => into({ binds: variable(String(name), SymbolKind.Any) }, id));
734
+ }
735
+ /* an access the arguments of the call rule out (`contour(z, add = TRUE)` opens no plot) does not happen */
736
+ const mayHappen = (a, draw) => {
737
+ const node = ast.idMap.get(draw);
738
+ const args = r_function_call_1.RFunctionCall.is(node) ? node.arguments : [];
739
+ return (a.when === undefined || (0, built_in_ambient_state_1.holds)(a.when, args) !== logic_1.Ternary.Never) && (a.unless === undefined || (0, built_in_ambient_state_1.holds)(a.unless, args) !== logic_1.Ternary.Always);
740
+ };
741
+ for (const draw of ambient.draws) {
742
+ const fn = qualified.get(draw);
743
+ const accesses = fn === undefined ? [] : (0, default_builtin_config_1.statedSignatureOf)(StatedSignatures, identifier_1.Identifier.getName(fn), identifier_1.Identifier.getNamespace(fn))?.ambient
744
+ ?.filter(a => a.family === ambient_effect_1.AmbientPart.Device).flatMap(a => a.accesses).filter(a => (a.part === ambient_effect_1.AmbientPart.Plot || a.part === ambient_effect_1.AmbientPart.Device) && mayHappen(a, draw)) ?? [];
745
+ const does = (verb) => accesses.some(a => a.access === verb);
746
+ /* closing the active device fails without one, closing every one (`graphics.off()`) does not */
747
+ const closesActive = accesses.some(a => a.access === ambient_effect_1.AmbientVerb.Closes && !a.names.includes('every'));
748
+ /* a high-level plot (`barplot`) opens the plot it adds to, and closing a fresh plot closes the device of the cell itself */
749
+ const adds = does(ambient_effect_1.AmbientVerb.Adds) && !does(ambient_effect_1.AmbientVerb.Resets);
750
+ if (adds || closesActive && !startsAfresh(cells[c].runner, PlotState.name)) {
751
+ /* closing needs a device open, which a device (`pdf(NULL)`) opens without a plot; a call that starts a plot of its own without
752
+ * any device (`curve(add = TRUE)`) fails only if a session opened one, but knitr and Jupyter open one for every cell */
753
+ const orStarts = adds && accesses.some(a => a.orStarts) && (cells[c].runner ?? cell_runner_1.CellRunner.Session) === cell_runner_1.CellRunner.Session;
754
+ raw[c].reads.push({ ...PlotState, id: draw, call: false, ...adds ? {} : { or: [DeviceState] }, ...orStarts ? { soft: true } : {} });
755
+ }
756
+ if (does(ambient_effect_1.AmbientVerb.Resets)) {
757
+ into({ binds: PlotState }, draw);
758
+ }
759
+ if (does(ambient_effect_1.AmbientVerb.Closes)) {
760
+ into({ removes: PlotState }, draw);
761
+ }
762
+ }
763
+ }
764
+ /* `detach` takes away what the attach of the entry it names brought in (`detach()` what the last attach before it did), and fails without the entry */
765
+ const attaches = graph.verticesOfType(vertex_1.VertexType.FunctionCall).filter(([id, v]) => vertex_1.DfgVertex.hasOrigin(v, built_in_proc_name_1.BuiltInProcName.Attach) && !bodies.has(id)).map(([id]) => id).toArray().sort(before);
766
+ for (const [id] of graph.verticesOfType(vertex_1.VertexType.FunctionCall).filter(([id, v]) => vertex_1.DfgVertex.hasOrigin(v, built_in_proc_name_1.BuiltInProcName.Detach) && !bodies.has(id))) {
767
+ const at = raw[cellOf(id)];
768
+ const entry = detached.get(id);
769
+ const by = entry === undefined ? attaches.filter(a => before(a, id) < 0).slice(-1) : attaches.filter(a => entries.get(a) === entry);
770
+ if (entry !== undefined) {
771
+ const pkg = SearchPathEntry.exec(entry)?.[1];
772
+ at?.reads.push({ ...by.length > 0 ? resource(CellResource.State, entry) : resource(CellResource.Package, pkg), id, call: false });
773
+ }
774
+ for (const { effect: e } of raw.flatMap(r => r.effects).filter(e => by.some(a => model_1.RNode.findEnclosing(e.at, ast.idMap, n => n.info.id === a) !== undefined))) {
775
+ const name = 'binds' in e && e.binds.resource === CellResource.Attached ? e.binds.name : 'bindsAny' in e && e.bindsAny === CellResource.Attached ? AnyName : undefined;
776
+ if (name !== undefined) {
777
+ at?.effects.push({ at: id, effect: { removes: resource(CellResource.Attached, name) } });
778
+ }
779
+ }
780
+ }
781
+ /* knitr evaluates the chunk options in the session before the chunk runs, as `eval = cran` reads `cran` */
782
+ const optionReads = new Set();
783
+ for (const [i, cell] of cells.entries()) {
784
+ cell.reads?.forEach(name => {
785
+ optionReads.add(`${i}-option-${name}`);
786
+ raw[i].reads.push({ ...variable(name, SymbolKind.Any), id: `${i}-option-${name}`, call: false, range: range_1.SourceRange.from(cell.head ?? cell.from, 1) });
787
+ });
788
+ }
789
+ const facts = cells.map((cell, i) => ({ cell, effects: raw[i].effects.sort((a, b) => before(a.at, b.at)).map(e => e.effect), needs: [], lacks: [] }));
790
+ /* the options of knitr some cell sets */
791
+ const settable = new Map(Object.values(KnitOptions).filter(([option]) => facts.some(o => provides(o, option))).map(([option]) => [sessionKey(option), SymbolKind.Any]));
792
+ const packageOf = (name, pkg) => ctx.functionInfo(pkg === undefined ? name : identifier_1.Identifier.from([name, pkg]))?.package;
793
+ for (const [i, f] of facts.entries()) {
794
+ const needs = f.needs;
795
+ const lacks = f.lacks;
796
+ /* the first read of a name stands for all later ones of the cell, a read that needs a function or a value for those that take either */
797
+ const same = (a, b) => a.resource === b.resource && a.name === b.name && a.soft === b.soft;
798
+ const reads = raw[i].reads.filter(u => u.resource !== CellResource.Variable || u.call || !inData(u.id, u.name));
799
+ for (const use of reads.filter((u, at, all) => all.findIndex(o => same(o, u) && o.kind === u.kind) === at && (u.kind !== SymbolKind.Any || !all.some(o => same(o, u) && o.kind !== SymbolKind.Any)))) {
800
+ const symbol = { resource: use.resource, name: use.name, kind: use.kind };
801
+ const anyOf = [symbol, ...use.or ?? []];
802
+ const where = { name: use.name, resource: use.resource, id: use.id, range: use.range ?? rangeOf(use.id) };
803
+ /* a cell that sets the state it reads (draws on the plot it opens) or binds what a function it calls reads before the call needs no other cell for it */
804
+ /* a call that sets state reads its arguments first (`options(digits = getOption("digits") - 1)`) */
805
+ const setBefore = (use.resource !== CellResource.Variable || use.deferred) && raw[i].effects.some(e => 'binds' in e.effect && anyOf.some(s => (0, exports.binds)(e.effect.binds, s)) && (use.deferred ? before(e.at, use.id) < 0 : endsBefore(e.at, use.id))
806
+ /* what a function binds as it runs (`y <<- y + 1`) does not count for what it reads before */
807
+ && (use.resource !== CellResource.Variable || cellOf(e.at) === i))
808
+ || raw[i].effects.some(e => bindsAnyOf(e.effect, symbol) && endsBefore(e.at, use.id));
809
+ if (setBefore) {
810
+ continue;
811
+ }
812
+ /* a cell that removes a variable before it reads it (`rm(list = ls()); a + 1`) lacks it whatever ran before */
813
+ /* only what a cell binds is in the global environment that `rm` clears, R's own functions are not */
814
+ const removedBefore = use.resource === CellResource.Variable && facts.some(o => provides(o, symbol)) && raw[i].effects.some(e => endsBefore(e.at, use.id)
815
+ && ('removes' in e.effect && e.effect.removes.name === use.name || 'clears' in e.effect && !e.effect.except?.includes(use.name)));
816
+ if (removedBefore) {
817
+ /* no symbol of any session satisfies it, and what only asks for it (`exists("x")`) gets the same whatever ran before */
818
+ if (use.soft !== true) {
819
+ needs.push({ ...where, anyOf: [], providers: [] });
820
+ }
821
+ continue;
822
+ }
823
+ /* state the cell starts afresh with comes from no other cell, a draw without a plot of its own fails, unless a cell has knitr keep it */
824
+ if (use.resource === CellResource.State && startsAfresh(f.cell.runner, use.name, settable)) {
825
+ if (use.name === PlotState.name) {
826
+ needs.push({ ...where, anyOf: [symbol], providers: [] });
827
+ }
828
+ continue;
829
+ }
830
+ const providers = facts.flatMap((o, j) => j !== i && anyOf.some(s => provides(o, s)) ? [j] : []);
831
+ /* what R provides itself (base functions, data sets) runs without any cell, a cell redefining it only changes what it reads */
832
+ const byR = use.resource === CellResource.Variable && providedByR(use.name, use.kind);
833
+ if (providers.length > 0) {
834
+ needs.push({ ...where, anyOf, providers, soft: use.soft ?? (byR ? true : undefined), changes: use.changes });
835
+ continue;
836
+ }
837
+ if (use.resource !== CellResource.Variable) {
838
+ continue;
839
+ }
840
+ /* a value no cell binds may be a column a cell adds (`lm(c ~ x, data = d)` after `d$c <- 1`), unless the cell adds it itself */
841
+ const asColumn = use.call || use.soft || use.deferred ? [] : columnRead(use.id, use.name);
842
+ const columnProviders = facts.flatMap((o, j) => j !== i && asColumn.some(s => provides(o, s)) ? [j] : []);
843
+ if (columnProviders.length > 0 && !raw[i].effects.some(e => 'binds' in e.effect && asColumn.some(s => (0, exports.binds)(e.effect.binds, s)) && endsBefore(e.at, use.id))) {
844
+ needs.push({ ...where, anyOf: asColumn, providers: columnProviders });
845
+ continue;
846
+ }
847
+ const base = byR ? 'base' : packageOf(use.name);
848
+ const node = ast.idMap.get(use.id);
849
+ const named = r_function_call_1.RFunctionCall.isNamed(node) && identifier_1.Identifier.getName(node.functionName.content) === use.name;
850
+ const exporting = [...attachedAnywhere].filter(l => packageOf(use.name, l) !== undefined);
851
+ /* a named call no cell defines and no package attached exports may call what code a cell sources defines, which binds just that */
852
+ const unseen = base === undefined && named && exporting.length === 0;
853
+ /* what no cell binds by name, a cell binding any name may bind */
854
+ const anyProviders = base === undefined ? facts.flatMap((o, j) => j !== i && o.effects.some(e => bindsAnyOf(e, symbol)) ? [j] : []) : [];
855
+ if (anyProviders.length > 0) {
856
+ needs.push({ ...where, anyOf: [symbol], providers: anyProviders });
857
+ continue;
858
+ }
859
+ if (use.soft !== true && raw[i].effects.some(e => 'binds' in e.effect && (0, exports.binds)(e.effect.binds, symbol) && graph.getVertex(e.at)?.cds === undefined)) {
860
+ lacks.push({ ...where, anyOf: [symbol], providers: [] });
861
+ continue;
862
+ }
863
+ /* a value no cell binds fails to read, unless a cell before keeps knitr from running the cell at all, but a function body or a formula (`lm(y ~ x, data = d)`) may read it from elsewhere */
864
+ const unbound = !use.call && use.soft !== true && use.deferred !== true && base === undefined && !inFormula(use.id);
865
+ const skippers = unbound ? facts.flatMap((o, j) => j !== i && provides(o, ChunkOptions.eval[0]) ? [j] : []) : [];
866
+ if (skippers.length > 0) {
867
+ needs.push({ ...where, anyOf: [ChunkOptions.eval[0]], providers: skippers });
868
+ continue;
869
+ }
870
+ /* a named call no package flowR knows exports may come from any attached package, as flowR may know a package only in part (`make.lp` of `lpSolveAPI`, `glimpse` that `tibble` re-exports), and so may such a value as lazy data (`un_votes` of `unvotes`) */
871
+ const lazy = unbound && !masked(use.id);
872
+ const candidates = exporting.length > 0 || base !== undefined || !named && !lazy ? exporting : [...attachedAnywhere];
873
+ const libs = !use.call && !lazy || base !== undefined && !attachedAnywhere.has(String(base)) ? [] : candidates.map(l => resource(CellResource.Package, l));
874
+ if (libs.some(l => provides(f, l)) || unseen && unseenSources.has(i)) {
875
+ continue;
876
+ }
877
+ const sourcing = unseen ? [...unseenSources].filter(j => j !== i) : [];
878
+ sourcing.forEach(j => facts[j].effects.push({ binds: symbol }));
879
+ const libProviders = facts.flatMap((o, j) => j !== i && (libs.some(l => provides(o, l)) || sourcing.includes(j)) ? [j] : []);
880
+ if (libProviders.length > 0) {
881
+ needs.push({ ...where, resource: CellResource.Package, anyOf: sourcing.length > 0 ? [...libs, symbol] : libs, providers: libProviders });
882
+ }
883
+ }
884
+ /* what a cell knitr may not run reads it may not need, only what its options read knitr always evaluates */
885
+ if (f.cell.maybe) {
886
+ needs.forEach((n, k) => needs[k] = optionReads.has(n.id) ? n : { ...n, soft: true });
887
+ }
888
+ }
889
+ /* a column counts as added only if the data had none of that name before, and an object state as needed only if no other call put the object in it, which the order of the notebook shows: there, it is there whenever read */
890
+ const isColumn = (n) => n.anyOf.length > 0 && n.anyOf.every(s => s.resource === CellResource.Column || s.resource === CellResource.ObjectState);
891
+ for (let missing = checkOrder(facts, facts.keys().toArray()).flatMap(f => f.missing.filter(isColumn)); missing.length > 0; missing = checkOrder(facts, facts.keys().toArray()).flatMap(f => f.missing.filter(isColumn))) {
892
+ for (const f of facts) {
893
+ f.needs = f.needs.filter(n => !isColumn(n) || !missing.some(m => m.id === n.id));
894
+ }
895
+ }
896
+ return facts;
897
+ }
898
+ /**
899
+ * What the definition binds: a function if its value may be one (`f <- function() 1`, or `g <- make()` where `make`
900
+ * returns one), else a value, or either if it comes from a call flowR does not know.
901
+ */
902
+ function boundKind(graph, id) {
903
+ let kind = SymbolKind.Value;
904
+ const seen = new Set();
905
+ for (const todo = [id]; todo.length > 0;) {
906
+ for (const source of df_helper_1.Dataflow.valueSources(todo.pop(), graph) ?? []) {
907
+ const vertex = graph.getVertex(source);
908
+ if (vertex_1.DfgVertex.isFunctionDefinition(vertex)) {
909
+ return SymbolKind.Function;
910
+ }
911
+ const returned = df_helper_1.Dataflow.targetsOf(graph, source, edge_1.EdgeType.Returns).filter(t => !seen.has(t));
912
+ returned.forEach(t => seen.add(t));
913
+ todo.push(...returned);
914
+ if (vertex_1.DfgVertex.isFunctionCall(vertex) && df_helper_1.Dataflow.origin(graph, source) === undefined) {
915
+ kind = SymbolKind.Any;
916
+ }
917
+ }
918
+ }
919
+ return kind;
920
+ }
921
+ /**
922
+ * The columns the definition `def` of a frame adds (`d$c <- 1`, `d <- d |> mutate(c = 1)`), leaving out one it reads as well
923
+ * (`d$c <- d$c * 2`), which was there before, and whether the value it binds builds on the frame (so it `keeps` its columns).
924
+ */
925
+ function addedColumns(def, graph, ast, qualified, keeps, attached) {
926
+ /* `d$c <- v` is a replacement of the access, `d <- v` an assignment, and `d %<>% f()` an assigning call binding what its right side gives */
927
+ const origin = (n) => vertex_1.DfgVertex.hasOrigin(graph.getVertex(n.info.id), built_in_proc_name_1.BuiltInProcName.Assignment) || vertex_1.DfgVertex.hasOrigin(graph.getVertex(n.info.id), built_in_proc_name_1.BuiltInProcName.Replacement);
928
+ const found = ast.idMap.get(model_1.RNode.findEnclosing(def, ast.idMap, origin) ?? '');
929
+ const target = r_function_call_1.RFunctionCall.is(found) ? undefined : found;
930
+ const assignment = r_access_1.RAccess.is(target) ? model_1.RNode.directParent(target, ast.idMap) : target;
931
+ if (target !== undefined && (!r_binary_op_1.RBinaryOp.is(assignment) || !r_access_1.RAccess.is(target) && !model_1.RNode.collectAllIds(assignment.lhs).has(def))) {
932
+ return { ops: [], keeps };
933
+ }
934
+ const piped = r_function_call_1.RFunctionCall.is(found) ? found.arguments[1] : undefined;
935
+ const value = !r_binary_op_1.RBinaryOp.is(assignment) ? valueOf(piped === r_function_call_1.EmptyArgument ? undefined : piped) : assignment.rhs === target ? assignment.lhs : assignment.rhs;
936
+ const within = (node) => [...model_1.RNode.collectAllIds(node)].map(id => ast.idMap.get(id));
937
+ const frame = node_id_1.NodeId.recoverName(def, ast.idMap);
938
+ /* the column `d$c` or `d[["c"]]` names */
939
+ const columnOf = (node) => {
940
+ const last = r_access_1.RAccess.is(node) && r_symbol_1.RSymbol.is(node.accessed) && node.accessed.lexeme === frame ? node.access[node.access.length - 1] : undefined;
941
+ const at = valueOf(last === r_function_call_1.EmptyArgument ? undefined : last);
942
+ return r_symbol_1.RSymbol.is(at) && r_access_1.RAccess.isNamed(node) ? at.lexeme : r_string_1.RString.is(at) ? at.content.str : undefined;
943
+ };
944
+ const reads = (node, name) => within(node).some(n => r_symbol_1.RSymbol.is(n) && n.lexeme === name || columnOf(n) === name);
945
+ if (r_access_1.RAccess.is(target)) {
946
+ const name = columnOf(target);
947
+ /* `d$c <- NULL` drops the column */
948
+ return { ops: name === undefined || reads(value, name) ? [] : [(0, arguments_1.isRNull)(value) ? { drop: name } : { add: name }], keeps: true };
949
+ }
950
+ /* the named arguments of the calls adding columns along the pipe that gives the value, but not one reading the column it sets (`mutate(d, c = c + 1)`) */
951
+ const adds = (node, piped = false) => {
952
+ if (node !== undefined && vertex_1.DfgVertex.hasOrigin(graph.getVertex(node.info.id), built_in_proc_name_1.BuiltInProcName.Pipe)) {
953
+ return (r_binary_op_1.RBinaryOp.is(node) || r_pipe_1.RPipe.is(node) ? [node.lhs, node.rhs] : r_function_call_1.RFunctionCall.is(node) ? node.arguments.map(a => valueOf(a === r_function_call_1.EmptyArgument ? undefined : a)) : []).flatMap((n, i) => adds(n, i > 0));
954
+ }
955
+ if (!r_function_call_1.RFunctionCall.is(node)) {
956
+ return [];
957
+ }
958
+ /* a built-in flowR cannot tie to a package (as no package database says where `mutate` comes from) by its name */
959
+ const call = graph.getVertex(node.info.id);
960
+ const fn = qualified.get(node.info.id) ?? (vertex_1.DfgVertex.isFunctionCall(call) && df_helper_1.Dataflow.origin(graph, node.info.id)?.some(o => o.type === 3 /* OriginType.BuiltInFunctionOrigin */) ? call.name : undefined);
961
+ const data = piped ? undefined : node.arguments.find(a => a !== r_function_call_1.EmptyArgument && a.name === undefined);
962
+ const args = node.arguments.flatMap(a => a === r_function_call_1.EmptyArgument || a === data ? [] : [a]);
963
+ const before = adds(valueOf(data === r_function_call_1.EmptyArgument ? undefined : data));
964
+ const named = (a) => a.name === undefined ? undefined : String(identifier_1.Identifier.getName(a.name.content));
965
+ /* `select(d, a, b)` keeps only the columns it names, `select(d, -a)` drops them, and `rename(d, b = a)` drops `a` for `b` */
966
+ const symbols = args.map(a => a.name === undefined && r_symbol_1.RSymbol.is(a.value) ? a.value.lexeme : undefined);
967
+ const negated = args.map(a => a.name === undefined && r_unary_op_1.RUnaryOp.is(a.value) && a.value.operator === '-' && r_symbol_1.RSymbol.is(a.value.operand) ? a.value.operand.lexeme : undefined);
968
+ if (fn !== undefined && identifier_1.Identifier.matches(fn, identifier_1.Identifier.make('select', "dplyr" /* PkgName.Dplyr */))) {
969
+ return [...before, ...symbols.every(c => c !== undefined) ? [{ keep: symbols }] : negated.every(c => c !== undefined) ? negated.map(c => ({ drop: c })) : []];
970
+ }
971
+ if (fn !== undefined && identifier_1.Identifier.matches(fn, identifier_1.Identifier.make('rename', "dplyr" /* PkgName.Dplyr */))) {
972
+ return [...before, ...args.flatMap(a => r_symbol_1.RSymbol.is(a.value) && named(a) !== undefined ? [{ drop: a.value.lexeme }, { add: named(a) }] : [])];
973
+ }
974
+ if (fn === undefined || !ColumnAdders.some(a => identifier_1.Identifier.matches(fn, a))) {
975
+ return before;
976
+ }
977
+ return [...before, ...args.flatMap(a => {
978
+ const name = named(a);
979
+ return name === undefined || (0, arguments_1.isRNull)(a.value) || reads(a.value, name) ? [] : [{ add: name }];
980
+ })];
981
+ };
982
+ /* the columns of the one data set that a name no cell binds is (`d <- as_tibble(mtcars)`), unless the table of data sets left some out */
983
+ const dataset = (node) => {
984
+ const fn = r_function_call_1.RFunctionCall.is(node) ? qualified.get(node.info.id) : undefined;
985
+ if (fn !== undefined && r_function_call_1.RFunctionCall.is(node) && FrameKeepers.some(k => identifier_1.Identifier.matches(fn, k))) {
986
+ const first = node.arguments[0];
987
+ return node.arguments.length === 1 && first !== r_function_call_1.EmptyArgument ? dataset(valueOf(first)) : undefined;
988
+ }
989
+ if (!r_symbol_1.RSymbol.is(node) || df_helper_1.Dataflow.origin(graph, node.info.id)?.some(o => vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(o.id))) === true) {
990
+ return undefined;
991
+ }
992
+ const shapes = ['datasets', ...attached].flatMap(p => (0, r_datasets_1.datasetShape)(identifier_1.Identifier.getName(node.content), p) ?? []);
993
+ return shapes.length === 1 && shapes[0].columns.length < r_datasets_1.MaxDatasetColumns ? shapes[0].columns : undefined;
994
+ };
995
+ const columns = dataset(value);
996
+ return columns === undefined ? { ops: adds(value), keeps: keeps || within(value).some(n => r_symbol_1.RSymbol.is(n) && n.lexeme === frame) } : { ops: [{ keep: columns }], keeps: false };
997
+ }
998
+ /** the variable the data comes from, along its first arguments (`d |> filter(a > 1)`, `subset(d, a > 1)`) */
999
+ function rootFrame(node) {
1000
+ if (r_symbol_1.RSymbol.is(node)) {
1001
+ return node.lexeme;
1002
+ }
1003
+ const first = r_function_call_1.RFunctionCall.is(node) ? node.arguments[0] : r_binary_op_1.RBinaryOp.is(node) || r_pipe_1.RPipe.is(node) ? node.lhs : undefined;
1004
+ return first === undefined || first === r_function_call_1.EmptyArgument ? undefined : rootFrame(valueOf(first));
1005
+ }
1006
+ /**
1007
+ * The names `attach` brings in, which flowR links to the call: the names of the list it is given (`attach(list(a = 1))`),
1008
+ * the bindings of the environment (`attach(e)`), or the columns of the data set R ships (`attach(mtcars)`).
1009
+ */
1010
+ function attachedNames(graph, ast, call) {
1011
+ return graph.ingoingEdges(call)?.entries().filter(([, e]) => edge_1.DfEdge.includesType(e, edge_1.EdgeType.Reads)).flatMap(([from]) => {
1012
+ const node = ast.idMap.get(from);
1013
+ const parent = node === undefined ? undefined : model_1.RNode.directParent(node, ast.idMap);
1014
+ if (r_argument_1.RArgument.isNamed(parent)) {
1015
+ return [String(identifier_1.Identifier.getName(parent.name.content))];
1016
+ }
1017
+ return vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(from)) ? [node_id_1.NodeId.recoverName(from, ast.idMap) ?? ''] : r_symbol_1.RSymbol.is(node) ? (0, r_datasets_1.datasetShape)(identifier_1.Identifier.getName(node.content))?.columns ?? [] : [];
1018
+ }).filter(n => n !== '').toArray() ?? [];
1019
+ }
1020
+ /** Whether the definition happens whenever the code around it runs (that is under the conditions `within`): what `load` binds depends only on the load itself, and the body of a loop that `runsOnce` runs as well. */
1021
+ const unconditional = (graph, id, runsOnce, within = []) => graph.getVertex(id)?.cds?.every(cd => vertex_1.DfgVertex.hasOrigin(graph.getVertex(cd.id), built_in_proc_name_1.BuiltInProcName.Load) || within.some(w => w.id === cd.id && w.when === cd.when) || cd.when === true && runsOnce(cd.id)) ?? true;
1022
+ /** Whether `id` is a name `rm` is given, which it does not read. */
1023
+ const removesNamed = (graph, id) => graph.edgesTo(id).entries().some(([from, e]) => edge_1.DfEdge.includesType(e, edge_1.EdgeType.NonStandardEvaluation) && vertex_1.DfgVertex.hasOrigin(graph.getVertex(from), built_in_proc_name_1.BuiltInProcName.Rm));
1024
+ /** Whether the definition is an assignment or what one assigns, which flowR knows as a definition of its own. */
1025
+ function isAssigned(graph, id) {
1026
+ return vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(id)) || graph.ingoingEdges(id)?.entries().some(([from, e]) => edge_1.DfEdge.includesType(e, edge_1.EdgeType.DefinedBy) && vertex_1.DfgVertex.isVariableDefinition(graph.getVertex(from))) === true;
1027
+ }
1028
+ /** The reads that are arguments a call takes as plain data (like both sides of `==`), which a function cannot be. */
1029
+ function valueReads(graph, ast, qualified) {
1030
+ const reads = new Set();
1031
+ for (const [id, vertex] of graph.vertices(true)) {
1032
+ const fn = vertex_1.DfgVertex.isFunctionCall(vertex) ? qualified.get(id) : undefined;
1033
+ const formals = fn === undefined ? undefined : (0, default_builtin_config_1.statedSignatureOf)(StatedSignatures, identifier_1.Identifier.getName(fn), identifier_1.Identifier.getNamespace(fn))?.args;
1034
+ if (formals === undefined || !vertex_1.DfgVertex.isFunctionCall(vertex)) {
1035
+ continue;
1036
+ }
1037
+ const dots = formals.findIndex(([name]) => name === '...');
1038
+ for (const [i, arg] of vertex.args.entries()) {
1039
+ if (arg === r_function_call_1.EmptyArgument) {
1040
+ continue;
1041
+ }
1042
+ const formal = arg.name === undefined ? dots < 0 || i < dots ? formals[i] : undefined : formals.find(([name]) => name === arg.name);
1043
+ const node = ast.idMap.get(arg.nodeId);
1044
+ if (formal?.[1].includes('atomic') && node !== undefined) {
1045
+ reads.add(r_argument_1.RArgument.isWithValue(node) ? node.value.info.id : node.info.id);
1046
+ }
1047
+ }
1048
+ }
1049
+ return reads;
1050
+ }
1051
+ /**
1052
+ * Whether R provides the name itself in the way it is read: a call finds the functions of the base packages, any other read
1053
+ * the data sets R ships, or a function of the base packages, which many calls take as any value (`glimpse(df)`, `c(q, 1)`).
1054
+ */
1055
+ const providedByR = (name, kind) => (0, r_base_packages_1.baseRExportOwner)(name) !== undefined || kind !== SymbolKind.Function && (r_base_packages_1.BaseDatasets.has(name) || (0, r_datasets_1.datasetShape)(name) !== undefined);
1056
+ /** Whether the call works in the global environment, as its `envir` names it (`rm(x, envir = globalenv())`), `undefined` if it names none. */
1057
+ function inGlobalEnvironment(vertex, ast) {
1058
+ const envir = vertex_1.DfgVertex.isFunctionCall(vertex) ? vertex.args.find(a => a !== r_function_call_1.EmptyArgument && a.name === 'envir') : undefined;
1059
+ const value = envir === undefined || envir === r_function_call_1.EmptyArgument ? undefined : valueOf(ast.idMap.get(envir.nodeId));
1060
+ return value === undefined ? undefined : r_function_call_1.RFunctionCall.isNamed(value, identifier_1.Identifier.make('globalenv')) || r_function_call_1.RFunctionCall.isNamed(value, identifier_1.Identifier.make('environment')) || r_symbol_1.RSymbol.is(value) && value.content === identifier_1.Identifier.make('.GlobalEnv');
1061
+ }
1062
+ /** Whether the call works in the environment its `envir` names (`rm(x, envir = e)`), other than the global one. */
1063
+ const inOtherEnvironment = (vertex, ast) => inGlobalEnvironment(vertex, ast) === false;
1064
+ /** the value of an argument, or the node itself if it is none */
1065
+ const valueOf = (node) => r_argument_1.RArgument.isWithValue(node) ? node.value : node;
1066
+ /**
1067
+ * Where the code defines what `id` reads or calls, leaving out R's own functions and constants. A read of a value bound
1068
+ * without an assignment (`x` once `attach(list(x = 1))` or `list2env(list(x = 1))` ran) has no origin, but reads the value or the argument naming it, and lazy data (`lung` once `library(survival)` ran) the load attaching it.
1069
+ */
1070
+ const definedBy = (graph, id) => df_helper_1.Dataflow.origin(graph, id)?.filter(o => o.type !== 3 /* OriginType.BuiltInFunctionOrigin */ && o.type !== 4 /* OriginType.ConstantOrigin */)
1071
+ ?? (vertex_1.DfgVertex.isUse(graph.getVertex(id)) ? df_helper_1.Dataflow.targetsOf(graph, id, edge_1.EdgeType.Reads).filter(t => !node_id_1.NodeId.isBuiltIn(t) && (vertex_1.DfgVertex.isValue(graph.getVertex(t)) || vertex_1.DfgVertex.hasOrigin(graph.getVertex(t), built_in_proc_name_1.BuiltInProcName.Library) || r_argument_1.RArgument.is(graph.idMap?.get(t)))).map(t => ({ type: 4 /* OriginType.ConstantOrigin */, id: t })) : []);
1072
+ /**
1073
+ * The reads the functions a call runs leave open, through the functions these call in turn: the reads of their bodies
1074
+ * that resolve to nothing of the body itself (which is all a parameter or a local is) nor to what `local` defines (in `scoped`) the function is made in.
1075
+ */
1076
+ function openReadsOfCalled(call, graph, scoped, targetsOf) {
1077
+ const seen = new Set();
1078
+ const found = [];
1079
+ for (const todo = [call]; todo.length > 0;) {
1080
+ const at = todo.pop();
1081
+ const caller = graph.getVertex(at);
1082
+ const given = new Set(vertex_1.DfgVertex.isFunctionCall(caller) ? caller.args.flatMap(a => a === r_function_call_1.EmptyArgument ? [] : [a.nodeId]) : []);
1083
+ /* the default of a parameter the call gives an argument for is never evaluated */
1084
+ const defaulted = (id) => graph.getVertex(id)?.cds?.some(cd => cd.byPromise === true && df_helper_1.Dataflow.targetsOf(graph, cd.id, edge_1.EdgeType.DefinedByOnCall).some(t => given.has(t))) === true;
1085
+ /* the hook a call registers (`on.exit(print(x))`) runs when the function registering it ends, within it */
1086
+ const hooks = vertex_1.DfgVertex.hasOrigin(caller, built_in_proc_name_1.BuiltInProcName.RegisterHook) ? [...given].filter(a => vertex_1.DfgVertex.isFunctionDefinition(graph.getVertex(a))) : [];
1087
+ for (const target of [...targetsOf(at), ...hooks]) {
1088
+ const fn = graph.getVertex(target);
1089
+ if (seen.has(target) || !vertex_1.DfgVertex.isFunctionDefinition(fn)) {
1090
+ continue;
1091
+ }
1092
+ seen.add(target);
1093
+ const scope = graph.idMap === undefined || graph.idMap.has(target) ? target : model_1.RNode.findEnclosing(at, graph.idMap, r_function_definition_1.RFunctionDefinition.is) ?? target;
1094
+ /* what the function defines, in the functions it defines as well (`inner <- function() v <<- 1`) */
1095
+ /* and what the files it sources define (`source("a.R", local = TRUE)`) */
1096
+ const inside = (id) => fn.subflow.graph.has(id) || graph.idMap !== undefined && model_1.RNode.findEnclosing(id, graph.idMap, n => n.info.id === scope) !== undefined;
1097
+ for (const id of fn.subflow.graph) {
1098
+ const vertex = graph.getVertex(id);
1099
+ const resolved = definedBy(graph, id);
1100
+ if (!defaulted(id) && (vertex_1.DfgVertex.isUse(vertex) && !removesNamed(graph, id) || vertex_1.DfgVertex.isFunctionCall(vertex) && identifier_1.Identifier.getNamespace(vertex.name) === undefined) && (resolved.length === 0 || resolved.some(o => (!inside(o.id) || !boundBefore(graph, o.id, id)) && !scoped.has(o.id)))) {
1101
+ found.push(id);
1102
+ }
1103
+ }
1104
+ todo.push(...df_helper_1.Dataflow.callsIn(fn, graph).map(([id]) => id));
1105
+ }
1106
+ }
1107
+ return found;
1108
+ }
1109
+ /** Whether the body binds what it reads before the read: a global it binds (`b <<- b + 1`) only once the assignment is done. */
1110
+ function boundBefore(graph, def, read) {
1111
+ const node = graph.idMap?.get(def);
1112
+ const assignment = range_1.SourceRange.fromNode(node === undefined || graph.idMap === undefined ? undefined : model_1.RNode.directParent(node, graph.idMap));
1113
+ const at = range_1.SourceRange.fromNode(graph.idMap?.get(read));
1114
+ return !df_helper_1.Dataflow.definedBySuperAssignment(graph, def) || assignment !== undefined && at !== undefined && (assignment[2] < at[0] || assignment[2] === at[0] && assignment[3] < at[1]);
1115
+ }
1116
+ /** The key of what the session binds that satisfies `need`, if it binds any: the name itself, or for a variable whatever binds any name (`load`). */
1117
+ const bindingOf = (session, need) => need.anyOf.flatMap(want => lookups(want).flatMap(r => [
1118
+ sessionKey({ resource: r, name: want.name }), ...want.resource === CellResource.Variable ? [sessionKey({ resource: r, name: AnyName })] : []
1119
+ ]).filter(key => session.has(key) && matches(want.kind, session.get(key) ?? SymbolKind.Any)))[0];
1120
+ const satisfied = (session, need) => bindingOf(session, need) !== undefined;
1121
+ /** whether a cell before set the chunk option for the knitted cell, unless its own header sets it */
1122
+ const chunkOption = (session, cell, option) => cell.runner === cell_runner_1.CellRunner.Knitr && cell.sets?.includes(option) !== true && session.has(sessionKey(ChunkOptions[option][0]));
1123
+ /** what the cell misses when it runs in the session: nothing if knitr does not run it, and only softly if knitting goes on after it fails */
1124
+ function missingIn(session, facts) {
1125
+ const missing = chunkOption(session, facts.cell, 'eval') ? [] : facts.needs.filter(n => !satisfied(session, n));
1126
+ return chunkOption(session, facts.cell, 'error') ? missing.map(n => ({ ...n, soft: true })) : missing;
1127
+ }
1128
+ /** Runs the cell in the session as run `at`, noting in `by` which run bound what. A cell lacking what it `needs` stops at the line of the first read it lacks, binding nothing from there on. */
1129
+ function run(session, facts, at = -1, by = new Map(), needs = facts.needs) {
1130
+ if (chunkOption(session, facts.cell, 'eval')) {
1131
+ return;
1132
+ }
1133
+ const started = new Map(Object.values(KnitOptions).map(([option]) => sessionKey(option)).filter(k => session.has(k)).map(k => [k, SymbolKind.Any]));
1134
+ /* knitr with `error = TRUE` runs each expression after one that failed */
1135
+ const stop = chunkOption(session, facts.cell, 'error') ? Infinity : Math.min(...needs.filter(n => !n.soft && !satisfied(session, n)).map(n => range_1.SourceRange.getStartLine(n.range) ?? Infinity));
1136
+ for (const e of facts.effects) {
1137
+ if ('binds' in e) {
1138
+ if ((range_1.SourceRange.getStartLine(e.range) ?? 0) >= stop) {
1139
+ continue;
1140
+ }
1141
+ session.set(sessionKey(e.binds), e.binds.kind);
1142
+ by.set(sessionKey(e.binds), at);
1143
+ }
1144
+ else if ('bindsAny' in e) {
1145
+ session.set(sessionKey({ resource: e.bindsAny, name: AnyName }), SymbolKind.Any);
1146
+ by.set(sessionKey({ resource: e.bindsAny, name: AnyName }), at);
1147
+ }
1148
+ else if (facts.cell.maybe) {
1149
+ /* what a cell knitr may not run removes may stay */
1150
+ continue;
1151
+ }
1152
+ else if ('removes' in e) {
1153
+ session.delete(sessionKey(e.removes));
1154
+ }
1155
+ else {
1156
+ /* `rm(list = ls())` clears the global environment, but leaves attached names, packages, state, and files alone */
1157
+ for (const key of session.keys().filter(k => k.startsWith(`${CellResource.Variable} `) && !e.except?.includes(k.slice(CellResource.Variable.length + 1))).toArray()) {
1158
+ session.delete(key);
1159
+ }
1160
+ }
1161
+ }
1162
+ /* knitr reads its options as a chunk starts and ends, so the chunk setting one keeps nothing yet */
1163
+ const afresh = (name) => startsAfresh(facts.cell.runner, name, started) || startsAfresh(facts.cell.runner, name, session);
1164
+ for (const key of session.keys().filter(k => k.startsWith(`${CellResource.State} `) && afresh(k.slice(CellResource.State.length + 1))).toArray()) {
1165
+ session.delete(key);
1166
+ }
1167
+ }
1168
+ /** Runs the cells in `order` in one fresh session and reports each cell that needs something the session lacks when it runs. */
1169
+ function checkOrder(facts, order) {
1170
+ const session = new Map();
1171
+ return order.flatMap((cell, at) => {
1172
+ const missing = missingIn(session, facts[cell]);
1173
+ run(session, facts[cell]);
1174
+ return missing.length > 0 ? [{ cell, at, missing }] : [];
1175
+ });
1176
+ }
1177
+ /**
1178
+ * Every order in which the cells run without missing anything, each running as many cells as it can, cells earlier in the
1179
+ * notebook first. An order that ends before all cells ran left the others unable to run (e.g., after an `rm`).
1180
+ */
1181
+ function* workingOrders(facts) {
1182
+ const order = [];
1183
+ function* extend(session) {
1184
+ let extended = false;
1185
+ for (const [i, f] of facts.entries()) {
1186
+ if (!order.includes(i) && missingIn(session, f).every(n => n.soft)) {
1187
+ extended = true;
1188
+ const next = new Map(session);
1189
+ run(next, f);
1190
+ order.push(i);
1191
+ yield* extend(next);
1192
+ order.pop();
1193
+ }
1194
+ }
1195
+ if (!extended) {
1196
+ yield [...order];
1197
+ }
1198
+ }
1199
+ yield* extend(new Map());
1200
+ }
1201
+ /** The cells that may have to run again once the `changed` cells ran again or changed, as they (transitively) read what these provide. */
1202
+ function affectedCells(facts, changed) {
1203
+ const affected = new Set(changed);
1204
+ for (let grew = true; grew;) {
1205
+ grew = false;
1206
+ for (const [i, f] of facts.entries()) {
1207
+ if (!affected.has(i) && f.needs.some(n => n.providers.some(p => affected.has(p)))) {
1208
+ affected.add(i);
1209
+ grew = true;
1210
+ }
1211
+ }
1212
+ }
1213
+ return [...affected].filter(c => !changed.includes(c)).sort((a, b) => a - b);
1214
+ }
1215
+ /** What makes the result of a notebook depend on how often and in which order its cells ran, beyond whether they run. */
1216
+ var HazardKind;
1217
+ (function (HazardKind) {
1218
+ /** the cell reads what it binds itself (`x <- x + 1`), so each time it runs again it builds on its own last result */
1219
+ HazardKind["Accumulates"] = "accumulates";
1220
+ /** several cells bind what the cell reads, each without reading it, so the cell gets the value of whichever ran last */
1221
+ HazardKind["Competes"] = "competes";
1222
+ /** the cell draws on a plot another cell opens, so each time it runs again it draws once more */
1223
+ HazardKind["Draws"] = "draws";
1224
+ })(HazardKind || (exports.HazardKind = HazardKind = {}));
1225
+ /* closing the device (`dev.off()`), which any open device satisfies, draws nothing */
1226
+ const drawsOn = (need) => need.resource === CellResource.State && need.name === PlotState.name && !need.anyOf.some(s => s.name === DeviceState.name);
1227
+ /** whether the cell binds the variable or state (as `runif` advances the seed) it needs from another cell, after reading it, but not a plot it opens anew after drawing on the old one */
1228
+ const rebinds = (facts, need) => !need.changes && (need.resource === CellResource.Variable || need.resource === CellResource.State && !drawsOn(need)) && need.anyOf.some(s => provides(facts, s));
1229
+ /** whether running the cell again changes what it did before: it builds on its own result or draws once more */
1230
+ const buildsOnItself = (facts, need) => rebinds(facts, need) || drawsOn(need);
1231
+ const reads = (facts, need) => facts.needs.some(n => n.resource === need.resource && n.name === need.name);
1232
+ /**
1233
+ * The reads of the cells whose result depends on more than whether the cells run: a cell building on its own last result,
1234
+ * which gives another result each time it runs again, and a read of a name several cells bind anew, which gets the value of
1235
+ * whichever of them ran last.
1236
+ */
1237
+ function orderHazards(facts) {
1238
+ return facts.flatMap((f, cell) => f.needs.flatMap((need) => {
1239
+ if (rebinds(f, need)) {
1240
+ return [{ kind: HazardKind.Accumulates, cell, need, providers: need.providers }];
1241
+ }
1242
+ if (drawsOn(need) && need.providers.length > 0) {
1243
+ return [{ kind: HazardKind.Draws, cell, need, providers: need.providers }];
1244
+ }
1245
+ const anew = need.resource === CellResource.Variable ? need.providers.filter(p => !reads(facts[p], need)) : [];
1246
+ return anew.length > 1 ? [{ kind: HazardKind.Competes, cell, need, providers: anew }] : [];
1247
+ }));
1248
+ }
1249
+ /** The first order in which every cell runs, preferring the order of the notebook, if one of the first `tries` orders is one. */
1250
+ function firstWorkingOrder(facts, tries = 256) {
1251
+ return workingOrders(facts).take(tries).find(o => o.length === facts.length);
1252
+ }
1253
+ /**
1254
+ * Moves the cells of `rows` so that the notebook runs top to bottom, or `undefined` if it does already or no order of
1255
+ * the first `tries` does. Only cells with fences or markers move, as text. With `withText`, the text above a cell (up
1256
+ * to the cell before it) moves along with it, inline code in it included, else the text stays where it is. Either
1257
+ * way, the inline code of the text must still find what it reads in the cells above it.
1258
+ */
1259
+ function reorderCells(rows, facts, withText = false, tries = 256) {
1260
+ const runs = (order) => checkOrder(facts, order).every(f => f.missing.every(m => m.soft));
1261
+ const movable = facts.flatMap((f, i) => f.cell.head === undefined ? [] : [i]);
1262
+ if (movable.length < 2 || runs(facts.map((_, i) => i))) {
1263
+ return undefined;
1264
+ }
1265
+ const end = (i) => facts[i].cell.tail ?? facts[i].cell.to;
1266
+ /* the lines that move as one: a cell, and with `withText` the text above it, but never the text above the first cell */
1267
+ const blocks = movable.map((c, k) => ({ from: withText && k > 0 ? end(movable[k - 1]) + 1 : facts[c].cell.head, to: end(c) }));
1268
+ /* without the text of the cells (code given as text has none) there is nothing to move */
1269
+ if (rows.length < blocks[blocks.length - 1].to) {
1270
+ return undefined;
1271
+ }
1272
+ const blockOf = (line) => blocks.findIndex(b => line >= b.from && line <= b.to);
1273
+ for (const order of workingOrders(facts).take(tries).filter(o => o.length === facts.length)) {
1274
+ const wanted = order.flatMap(i => movable.includes(i) ? [movable.indexOf(i)] : []);
1275
+ /* lays the blocks out in the wanted order, the lines between them staying, and keeps where each cell lands */
1276
+ const out = [];
1277
+ const landed = new Map();
1278
+ const place = (from, to, keep) => {
1279
+ facts.forEach((f, i) => keep(f.cell.from) && f.cell.from >= from && f.cell.from <= to ? landed.set(i, out.length + f.cell.from - from) : undefined);
1280
+ out.push(...rows.slice(from - 1, to));
1281
+ };
1282
+ for (const [k, w] of wanted.entries()) {
1283
+ if (k > 0) {
1284
+ place(blocks[k - 1].to + 1, blocks[k].from - 1, line => blockOf(line) < 0);
1285
+ if (withText && w === 0) {
1286
+ out.push('');
1287
+ }
1288
+ }
1289
+ /* the blank lines that part a moved text from the cell before it are not needed in the first place */
1290
+ let from = blocks[w].from;
1291
+ while (k === 0 && withText && from < blocks[w].to && rows[from - 1].trim() === '') {
1292
+ from++;
1293
+ }
1294
+ place(from, blocks[w].to, line => blockOf(line) === w);
1295
+ }
1296
+ const key = (i) => landed.get(i) ?? (facts[i].cell.from < blocks[0].from ? facts[i].cell.from - blocks[0].from : out.length + facts[i].cell.from);
1297
+ const after = facts.map((_, i) => i).sort((x, y) => key(x) - key(y));
1298
+ if (runs(after)) {
1299
+ return { from: blocks[0].from, to: blocks[blocks.length - 1].to, text: out.join('\n'), order: after };
1300
+ }
1301
+ }
1302
+ return undefined;
1303
+ }
1304
+ /** What the runs of a session mean for a cell that ran, in the order they are checked. */
1305
+ var RunState;
1306
+ (function (RunState) {
1307
+ /** its code changed since it ran, so its run says nothing about the code as it is now */
1308
+ RunState["Edited"] = "edited";
1309
+ /** when it last ran, something it needs was missing, see {@link CellRunState#missing} */
1310
+ RunState["Missing"] = "missing";
1311
+ /** it used what only a cell below provides, which running the notebook top to bottom does not reproduce */
1312
+ RunState["OutOfOrder"] = "out of order";
1313
+ /** it builds on its own last result and ran again since a cell it reads first bound it, see {@link CellRunState#because} */
1314
+ RunState["Repeated"] = "repeated";
1315
+ /** a cell it reads changed, ran again, or is stale itself since it ran, see {@link CellRunState#because} */
1316
+ RunState["Stale"] = "stale";
1317
+ RunState["UpToDate"] = "up to date";
1318
+ })(RunState || (exports.RunState = RunState = {}));
1319
+ /**
1320
+ * What the `runs` of a session (the cells in the order they ran, a cell as often as it ran) mean for each cell that ran.
1321
+ * `edited` are the cells whose code changed since they last ran.
1322
+ */
1323
+ function runStates(facts, runs, edited = new Set()) {
1324
+ const last = new Map(runs.map((c, k) => [c, k]));
1325
+ /* for each run, what the cell lacked, and the run whose binding each of its needs used */
1326
+ const session = new Map();
1327
+ const by = new Map();
1328
+ const replayed = runs.map((c, at) => {
1329
+ /* the session also lacks what only the cell itself binds, after it reads it */
1330
+ const needs = [...facts[c].needs, ...facts[c].lacks];
1331
+ const missing = needs.filter(n => !n.soft && !satisfied(session, n));
1332
+ const used = new Map(facts[c].needs.map(n => [n, by.get(bindingOf(session, n) ?? '') ?? -1]));
1333
+ run(session, facts[c], at, by, needs);
1334
+ return { missing, used };
1335
+ });
1336
+ const usedCell = (k, need) => runs[replayed[k].used.get(need) ?? -1];
1337
+ const stale = new Map();
1338
+ for (let grew = true; grew;) {
1339
+ grew = false;
1340
+ for (const [i, k] of last) {
1341
+ /* a provider ran again since, or the one it used changed or is stale itself */
1342
+ const cause = stale.has(i) ? undefined : facts[i]?.needs.flatMap(n => [...n.providers.filter(p => (last.get(p) ?? -1) > k), usedCell(k, n)])
1343
+ .find(p => p !== undefined && (edited.has(p) || stale.has(p) || (last.get(p) ?? -1) > k));
1344
+ if (cause !== undefined) {
1345
+ stale.set(i, cause);
1346
+ grew = true;
1347
+ }
1348
+ }
1349
+ }
1350
+ return [...last].sort(([a], [b]) => a - b).map(([i, k]) => {
1351
+ const missing = replayed[k].missing;
1352
+ /* a soft read as well: what `exists("x")` or an option gives decides what the cell computes */
1353
+ const below = facts[i].needs.find(n => (usedCell(k, n) ?? -1) > i);
1354
+ /* a cell building on its own result that ran more than once since the run that bound what it builds on, its own first run counting */
1355
+ const again = facts[i].needs.filter(n => buildsOnItself(facts[i], n)).find(n => runs.slice(Math.max(0, replayed[k].used.get(n) ?? 0), k + 1).filter(c => c === i).length > 1);
1356
+ /* the facts are those of the code as it is now, so they say nothing about the run of a cell edited since */
1357
+ return edited.has(i) ? { cell: i, state: RunState.Edited }
1358
+ : missing.length > 0 ? { cell: i, state: RunState.Missing, missing }
1359
+ : below !== undefined ? { cell: i, state: RunState.OutOfOrder, below }
1360
+ : again !== undefined ? { cell: i, state: RunState.Repeated, because: again.providers.find(p => !reads(facts[p], again)) ?? again.providers[0] }
1361
+ : stale.has(i) ? { cell: i, state: RunState.Stale, because: stale.get(i) }
1362
+ : { cell: i, state: RunState.UpToDate };
1363
+ });
1364
+ }
1365
+ const byNumber = i => `cell ${i + 1}`;
1366
+ const listed = (cells, name, join = ' or ') => (0, arrays_1.uniqueArray)(cells).map(name).join(join);
1367
+ /** The `states` of {@link runStates} in words, for each cell that is not up to date. */
1368
+ function describeRunStates(facts, states, name = byNumber) {
1369
+ const of = new Map(states.map(s => [s.cell, s]));
1370
+ const texts = new Map();
1371
+ for (const s of states) {
1372
+ const cause = s.because ?? s.cell;
1373
+ switch (s.state) {
1374
+ case RunState.Missing:
1375
+ texts.set(s.cell, { label: `missing ${s.missing?.map(describeNeed).join(', ')}`, reason: `when this cell last ran, ${s.missing?.map(m => `${describeNeed(m)}${m.providers.length === 0 ? '' : ` (from ${listed(m.providers, name)})`}`).join(', ')} did not exist yet`, issue: true });
1376
+ break;
1377
+ case RunState.OutOfOrder:
1378
+ texts.set(s.cell, { label: 'out of order', reason: `this cell used ${s.below === undefined ? 'a value' : describeNeed(s.below)} from ${listed(s.below?.providers.filter(p => p > s.cell) ?? [], name)}, which comes after it. Run top to bottom, it gets something else.`, issue: true });
1379
+ break;
1380
+ case RunState.Repeated:
1381
+ texts.set(s.cell, { label: 'repeated', reason: `this cell ran again without ${listed([cause], name)} before it, so it built on its own last result. Run ${listed([cause], name)}, then this cell.`, issue: true });
1382
+ break;
1383
+ case RunState.Edited: {
1384
+ const affected = affectedCells(facts, [s.cell]).filter(a => of.has(a));
1385
+ texts.set(s.cell, { label: 'edited', reason: `changed since it ran${affected.length > 0 ? `. The results of ${listed(affected, name, ', ')} may be out of date` : ''}`, issue: false });
1386
+ break;
1387
+ }
1388
+ case RunState.Stale: {
1389
+ const why = of.get(cause)?.state === RunState.Edited ? 'changed since this cell ran' : of.get(cause)?.state === RunState.Stale ? 'is out of date itself. Run it first' : 'ran again after this cell';
1390
+ texts.set(s.cell, { label: 'stale', reason: `${listed([cause], name)} ${why}. Run this cell again.`, issue: false });
1391
+ break;
1392
+ }
1393
+ default:
1394
+ break;
1395
+ }
1396
+ }
1397
+ return texts;
1398
+ }
1399
+ /** What a cell failing in an order lacks and which cells provide it, `undefined` if it only reads global state another cell sets. */
1400
+ function describeFailure(failure, name = byNumber) {
1401
+ const hard = failure.missing.filter(m => !m.soft);
1402
+ const needs = (0, arrays_1.uniqueArray)(hard.map(describeNeed));
1403
+ const from = (0, arrays_1.uniqueArray)(hard.flatMap(m => m.providers));
1404
+ const after = from.filter(p => p > failure.cell);
1405
+ return hard.length === 0 ? undefined : from.length === 0 ? `${name(failure.cell)} uses ${needs.join(', ')}, which no cell before it provides`
1406
+ : after.length === 0 ? `${name(failure.cell)} uses ${needs.join(', ')} from ${listed(from, name)}, which failed or was removed again before`
1407
+ : `${name(failure.cell)} uses ${needs.join(', ')} from ${listed(after, name)}, which comes after it`;
1408
+ }
1409
+ /** A hazard of {@link orderHazards} in words: what the cell reads, and what to run before it. */
1410
+ function describeHazard(hazard, name = byNumber) {
1411
+ switch (hazard.kind) {
1412
+ case HazardKind.Accumulates: return `${name(hazard.cell)} changes ${describeNeed(hazard.need)} based on its old value, so rerun ${listed(hazard.providers, name)} first`;
1413
+ case HazardKind.Draws: return `${name(hazard.cell)} adds to the plot of ${listed(hazard.providers, name)}, so rerun ${listed(hazard.providers, name)} first`;
1414
+ default: return `${name(hazard.cell)} uses ${describeNeed(hazard.need)}, which ${listed(hazard.providers, name, ' and ')} both set, so it gets whichever ran last`;
1415
+ }
1416
+ }
1417
+ /** For each cell that reads what others provide: what and from which, without the global state it reads. */
1418
+ function cellLinks(facts) {
1419
+ return facts.flatMap((f, cell) => {
1420
+ const hard = f.needs.filter(n => !n.soft);
1421
+ return hard.length === 0 ? [] : [{ cell, reads: (0, arrays_1.uniqueArray)(hard.map(describeNeed)), from: (0, arrays_1.uniqueArray)(hard.flatMap(n => n.providers)) }];
1422
+ });
1423
+ }
1424
+ /** The {@link cellLinks} in words, as `cell 2 reads x from cell 1`, or `b.R reads x from a.R` with a namer for files. */
1425
+ function describeLinks(facts, name = byNumber) {
1426
+ return cellLinks(facts).map(l => `${name(l.cell)} reads ${l.reads.join(', ')} from ${listed(l.from, name, ', ')}`);
1427
+ }
1428
+ /**
1429
+ * Helper object for the cells of a notebook: which cells there are, what each needs of the others, the orders they run in,
1430
+ * what reruns and edits mean for them, and all of this in words. See {@link CellGraph} for the cells as a dataflow graph.
1431
+ * @helper project
1432
+ */
1433
+ exports.CellOrder = {
1434
+ name: 'CellOrder',
1435
+ cells: notebookCells,
1436
+ analyze: analyzeNotebook,
1437
+ check: checkOrder,
1438
+ orders: workingOrders,
1439
+ firstOrder: firstWorkingOrder,
1440
+ affected: affectedCells,
1441
+ links: cellLinks,
1442
+ hazards: orderHazards,
1443
+ runStates,
1444
+ reorder: reorderCells,
1445
+ describeSymbol,
1446
+ describeNeed,
1447
+ describeFailure,
1448
+ describeHazard,
1449
+ describeLinks,
1450
+ describeRunStates
1451
+ };
1452
+ //# sourceMappingURL=cell-order.js.map