@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
@@ -4,6 +4,8 @@ import { type DocMakerArgs, DocMaker } from './wiki-mk/doc-maker';
4
4
  export interface PackageExample {
5
5
  readonly code: string;
6
6
  readonly files: Readonly<Record<string, string>>;
7
+ /** files of {@link PackageExample#files} analyzed after the code, as a project analyzes all of its scripts */
8
+ readonly requests?: readonly string[];
7
9
  }
8
10
  /** what the wiki shows for each linting rule: its configuration and implementation types, its tests, and an example with findings */
9
11
  export declare const LintingRuleExamples: Readonly<Record<LintingRuleNames, {
@@ -262,6 +262,12 @@ server <- function(input, output, session) {
262
262
  },
263
263
  'autoload-files': {
264
264
  example: { code: 'f <- function() 1', files: { '.RProfile': 'system("rm -rf /")' } }
265
+ },
266
+ 'notebook-cell-order': {
267
+ example: '# %%\nprint(total)\n# %%\ntotal <- 1 + 2'
268
+ },
269
+ 'project-entry-point': {
270
+ example: { code: 'print(total)', files: { 'R/setup.R': 'total <- 1 + 2' }, requests: ['R/setup.R'] }
265
271
  }
266
272
  };
267
273
  /** the kinds of issue a rule finds, each rule carries at most one */
@@ -347,7 +353,7 @@ More examples are the test cases in ${(0, doc_files_1.linkFlowRSourceFile)(`test
347
353
  async function exampleQuery(parser, name, example, config = {}) {
348
354
  const queries = [{ type: 'linter', rules: [{ name, config: config }] }];
349
355
  const shown = typeof example === 'string' ? await (0, doc_query_1.showQuery)(parser, example, queries, { withJson: false })
350
- : await (0, doc_query_1.showQuery)(parser, `${retriever_1.fileProtocol}${ExampleRoot}/R/code.R`, queries, {
356
+ : await (0, doc_query_1.showQuery)(parser, [`${retriever_1.fileProtocol}${ExampleRoot}/R/code.R`, ...(example.requests ?? []).map(f => `${retriever_1.fileProtocol}${ExampleRoot}/${f}`)], queries, {
351
357
  withJson: false,
352
358
  files: [['R/code.R', example.code], ...Object.entries(example.files)].map(([file, content]) => ({ name: `${ExampleRoot}/${file}`, content }))
353
359
  });
@@ -973,6 +973,34 @@ ${await (0, doc_query_1.showQuery)(shell, '', [{ type: 'function-info', name: 'g
973
973
  ${(0, doc_structure_1.block)('NOTE', `To find out what a script _uses_, reach for the ${(0, doc_query_1.linkToQueryOfName)('dependencies')}; to inspect a specific
974
974
  package/version in the database directly, reach for the ${(0, doc_query_1.linkToQueryOfName)('signature')}. In the REPL, \`:signature info <name>\` is a shorthand for this query.`)}
975
975
  `);
976
+ (0, doc_query_1.registerQueryDocumentation)('cell-order', {
977
+ type: 'active',
978
+ shortDescription: 'Checks in which orders the cells of a notebook run.',
979
+ buildExplanation: async (shell, _) => {
980
+ const exampleCode = '# %%\nprint(total)\n# %%\ntotal <- 1 + 2';
981
+ return `
982
+ The cells are the chunks of an R Markdown or Quarto document, the code cells of a Jupyter notebook, or the \`# %%\` cells of a script, numbered from 0.
983
+ The query checks the given \`order\` (top to bottom by default), lists up to \`orders\` working orders, and with \`changed\` names the cells that may have to run again after these cells ran again or were edited.
984
+ ${await (0, doc_query_1.showQuery)(shell, exampleCode, [{ type: 'cell-order', orders: 3, changed: [1] }])}
985
+ `;
986
+ }
987
+ });
988
+ (0, doc_query_1.registerQueryDocumentation)('aliases', {
989
+ type: 'active',
990
+ shortDescription: 'Returns all aliases of a given identifier.',
991
+ buildExplanation: async (shell, _) => {
992
+ const exampleCode = 'x <- 1\ng <- x\nh <- g';
993
+ const criteria = ['1@x'];
994
+ const id = [3];
995
+ return `
996
+ If the identifier is given as a NodeId the aliases will be returned as NodeId as well. If the identifier uses a slicing criterion the location of the corresponding aliases will be returned.
997
+ The following example uses both functionalities:
998
+ Given the code ${(0, doc_code_1.codeBlock)('r', exampleCode)}. Here '2@g' resolves to NodeId 3.
999
+ Then the following query will return the location of the aliases of x and the NodeIds of the aliases of g.
1000
+ ${await (0, doc_query_1.showQuery)(shell, exampleCode, [{ type: 'aliases', criteria: criteria, id: id }])}
1001
+ `;
1002
+ }
1003
+ });
976
1004
  /** https://github.com/flowr-analysis/flowr/wiki/Query-API */
977
1005
  class WikiQuery extends doc_maker_1.DocMaker {
978
1006
  constructor() {
@@ -100,13 +100,17 @@ export declare const LintQuickFix: {
100
100
  * Every kind of fix is named here, so a new one cannot quietly inherit the behaviour of another.
101
101
  */
102
102
  readonly inserted: (this: void, fix: LintQuickFix) => string;
103
+ /** The fixes a finding offers to choose from: its {@link LintingResult#quickFix} first, then its {@link LintingResult#alternatives}, each a list of edits carried out together. */
104
+ readonly choices: (this: void, result: Pick<LintingResult, "quickFix" | "alternatives">) => readonly (readonly LintQuickFix[])[];
103
105
  };
104
106
  /** A linting result for a single linting rule match. */
105
107
  export interface LintingResult {
106
108
  /** The certainty of the linting result. */
107
109
  readonly certainty: LintingResultCertainty;
108
- /** If available, what to do to fix the linting result. */
110
+ /** If available, what to do to fix the linting result: the edits of one fix, which are carried out together. */
109
111
  readonly quickFix?: LintQuickFix[];
112
+ /** Other fixes to choose from instead of the {@link LintingResult#quickFix}, each again the edits carried out together, see {@link LintQuickFix.choices}. */
113
+ readonly alternatives?: readonly (readonly LintQuickFix[])[];
110
114
  /** The node ID or IDs involved in this linting result, if applicable. */
111
115
  readonly involvedId: NodeId | NodeId[] | undefined;
112
116
  /** The source location where this linting result occurs */
@@ -33,6 +33,10 @@ exports.LintQuickFix = {
33
33
  default:
34
34
  (0, assert_1.assertUnreachable)(fix);
35
35
  }
36
+ },
37
+ /** The fixes a finding offers to choose from: its {@link LintingResult#quickFix} first, then its {@link LintingResult#alternatives}, each a list of edits carried out together. */
38
+ choices(result) {
39
+ return [result.quickFix ?? [], ...result.alternatives ?? []].filter(fix => fix.length > 0);
36
40
  }
37
41
  };
38
42
  /**
@@ -30,14 +30,14 @@ function findings(results) {
30
30
  const perRule = perRuleResults;
31
31
  /* staying silent about a rule that threw would claim it passed */
32
32
  if (linter_format_1.LintingResults.isError(perRule)) {
33
- return [{ rule, message: `the linting rule failed: ${linter_format_1.LintingResults.stringifyError(perRule)}`, level: 'error', loc: undefined, quickFix: [] }];
33
+ return [{ rule, message: `the linting rule failed: ${linter_format_1.LintingResults.stringifyError(perRule)}`, level: 'error', loc: undefined, fixes: [] }];
34
34
  }
35
35
  return perRule.results.map(result => ({
36
36
  rule,
37
37
  message: linter_rules_1.LintingRules[rule].prettyPrint[linter_format_1.LintingPrettyPrintContext.Query](result, perRule['.meta']),
38
38
  level: (result.certainty === linter_format_1.LintingResultCertainty.Certain ? 'warning' : 'note'),
39
39
  loc: result.loc,
40
- quickFix: result.quickFix ?? []
40
+ fixes: linter_format_1.LintQuickFix.choices(result)
41
41
  }));
42
42
  });
43
43
  }
@@ -58,28 +58,30 @@ function sarifLocation(loc) {
58
58
  }];
59
59
  }
60
60
  /**
61
- * The quick fixes of one finding as SARIF `fixes`. A fix needs a file and a span to change, so the ones flowR cannot
62
- * place are left out rather than reported against no artifact or an invalid region.
61
+ * The fixes to choose from of one finding as SARIF `fixes`, the edits of each as the changes it makes. A fix needs a file and
62
+ * a span for each edit, so one flowR cannot place is left out rather than reported against no artifact or an invalid region.
63
63
  */
64
- function sarifFixes(fixes) {
65
- return fixes.flatMap(fix => {
66
- const file = range_1.SourceLocation.getFile(fix.loc);
67
- if (file === undefined || !linter_format_1.LintQuickFix.isPlaced(fix)) {
64
+ function sarifFixes(choices) {
65
+ return choices.flatMap(fix => {
66
+ if (fix.some(edit => range_1.SourceLocation.getFile(edit.loc) === undefined || !linter_format_1.LintQuickFix.isPlaced(edit))) {
68
67
  return [];
69
68
  }
70
- const [startLine, startColumn, endLine, endColumn] = range_1.SourceLocation.getRange(fix.loc);
71
69
  return [{
72
- description: { text: fix.description },
73
- artifactChanges: [{
74
- artifactLocation: { uri: reportedPath(file) },
70
+ description: { text: describeFix(fix) },
71
+ artifactChanges: fix.map(edit => {
72
+ const [startLine, startColumn, endLine, endColumn] = range_1.SourceLocation.getRange(edit.loc);
73
+ return {
74
+ artifactLocation: { uri: reportedPath(range_1.SourceLocation.getFile(edit.loc)) },
75
75
  replacements: [{
76
76
  deletedRegion: { startLine, startColumn, endLine, endColumn },
77
- insertedContent: { text: linter_format_1.LintQuickFix.inserted(fix) }
77
+ insertedContent: { text: linter_format_1.LintQuickFix.inserted(edit) }
78
78
  }]
79
- }]
79
+ };
80
+ })
80
81
  }];
81
82
  });
82
83
  }
84
+ const describeFix = (fix) => (0, arrays_1.uniqueArray)(fix.map(edit => edit.description)).join('; ');
83
85
  /**
84
86
  * Renders the linting results as SARIF 2.1.0, the format code scanners (e.g. GitHub's) ingest, on a single line.
85
87
  * Only the rules that produced a finding are described, as SARIF requires every reported rule to be declared.
@@ -105,7 +107,7 @@ function lintsToSarif(results, flowrVersion) {
105
107
  }
106
108
  },
107
109
  results: flat.map(f => {
108
- const fixes = sarifFixes(f.quickFix);
110
+ const fixes = sarifFixes(f.fixes);
109
111
  return {
110
112
  ruleId: f.rule,
111
113
  level: f.level,
@@ -129,7 +131,7 @@ function lintsToGithub(results) {
129
131
  const loc = f.loc !== undefined && f.loc[4] !== undefined ? f.loc : undefined;
130
132
  const where = loc === undefined ? '' : ` file=${escapeGithubData(reportedPath(loc[4]))},line=${loc[0]},col=${loc[1]},endLine=${loc[2]},endColumn=${loc[3]},`;
131
133
  // github annotations carry no fix of their own, so the offer goes into the message
132
- const fixes = f.quickFix.length === 0 ? '' : ` [quick fix: ${f.quickFix.map(fix => fix.description).join('; ')}]`;
134
+ const fixes = f.fixes.length === 0 ? '' : ` [quick fix: ${f.fixes.map(describeFix).join(' or ')}]`;
133
135
  return `::${githubCommand[f.level]}${where}${loc === undefined ? ' ' : ''}title=${escapeGithubData(f.rule)}::${escapeGithubData(f.message + fixes)}`;
134
136
  }).join('\n');
135
137
  }
@@ -1296,6 +1296,56 @@ export declare const LintingRules: {
1296
1296
  };
1297
1297
  };
1298
1298
  };
1299
+ readonly 'notebook-cell-order': {
1300
+ readonly createSearch: () => import("../search/flowr-search-builder").FlowrSearchBuilder<"from", [], import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElements<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElement<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>>;
1301
+ readonly processSearchResult: (_elements: import("../search/flowr-search").FlowrSearchElements<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElement<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>, _config: import("../util/objects").MergeableRecord, data: import("..").ReadonlyFlowrAnalysisProvider<import("..").KnownParser>) => Promise<{
1302
+ results: import("./rules/notebook-cell-order").NotebookCellOrderResult[];
1303
+ '.meta': {};
1304
+ }>;
1305
+ readonly prettyPrint: {
1306
+ readonly query: (r: import("./rules/notebook-cell-order").NotebookCellOrderResult, metadata: unknown) => string;
1307
+ readonly full: (r: import("./rules/notebook-cell-order").NotebookCellOrderResult, metadata: unknown) => string;
1308
+ };
1309
+ readonly info: {
1310
+ readonly name: "Notebook Cell Order";
1311
+ readonly tags: readonly [LintingRuleTag.Reproducibility, LintingRuleTag.Bug, LintingRuleTag.QuickFix];
1312
+ readonly certainty: import("./linter-format").LintingRuleCertainty.BestEffort;
1313
+ readonly description: "Finds notebook cells that read what only a cell further down provides, so the notebook fails or behaves differently when run top to bottom, and offers to move the providing cell up.";
1314
+ readonly defaultConfig: () => {};
1315
+ };
1316
+ };
1317
+ readonly 'project-entry-point': {
1318
+ readonly createSearch: () => import("../search/flowr-search-builder").FlowrSearchBuilder<"from", [], import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElements<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElement<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>>;
1319
+ readonly processSearchResult: (_elements: import("../search/flowr-search").FlowrSearchElements<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../search/flowr-search").FlowrSearchElement<import("../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>, _config: import("../util/objects").MergeableRecord, data: import("..").ReadonlyFlowrAnalysisProvider<import("..").KnownParser>) => Promise<{
1320
+ results: {
1321
+ certainty: import("./linter-format").LintingResultCertainty;
1322
+ involvedId: import("..").NodeId;
1323
+ loc: readonly [startLine: import("../util/range").Line, startColumn: import("../util/range").Column, endLine: import("../util/range").Line, endColumn: import("../util/range").Column, f?: string | undefined] | undefined;
1324
+ files: string[];
1325
+ runs: boolean;
1326
+ reads: string[];
1327
+ entry: string;
1328
+ quickFix: {
1329
+ type: "replace";
1330
+ description: string;
1331
+ loc: readonly [startLine: import("../util/range").Line, startColumn: import("../util/range").Column, endLine: import("../util/range").Line, endColumn: import("../util/range").Column, f?: string | undefined];
1332
+ replacement: string;
1333
+ }[] | undefined;
1334
+ }[];
1335
+ '.meta': {};
1336
+ }>;
1337
+ readonly prettyPrint: {
1338
+ readonly query: (r: import("./rules/project-entry-point").ProjectEntryPointResult, metadata: unknown) => string;
1339
+ readonly full: (r: import("./rules/project-entry-point").ProjectEntryPointResult, metadata: unknown) => string;
1340
+ };
1341
+ readonly info: {
1342
+ readonly name: "Project Entry Point";
1343
+ readonly tags: readonly [LintingRuleTag.Reproducibility, LintingRuleTag.Smell, LintingRuleTag.QuickFix];
1344
+ readonly certainty: import("./linter-format").LintingRuleCertainty.BestEffort;
1345
+ readonly description: "Finds projects whose scripts read what other scripts define but that have no entry file (such as a main.R, a makefile, or _targets.R) that runs them in an order that works, and suggests a main.R that sources them in one.";
1346
+ readonly defaultConfig: () => {};
1347
+ };
1348
+ };
1299
1349
  };
1300
1350
  export type LintingRuleNames = keyof typeof LintingRules;
1301
1351
  /**
@@ -22,6 +22,8 @@ const software_has_tests_1 = require("./rules/software-has-tests");
22
22
  const no_leaked_credentials_1 = require("./rules/no-leaked-credentials");
23
23
  const undefined_symbol_1 = require("./rules/undefined-symbol");
24
24
  const unused_import_1 = require("./rules/unused-import");
25
+ const notebook_cell_order_1 = require("./rules/notebook-cell-order");
26
+ const project_entry_point_1 = require("./rules/project-entry-point");
25
27
  const syntactically_valid_1 = require("./rules/syntactically-valid");
26
28
  const unclosed_connection_1 = require("./rules/unclosed-connection");
27
29
  const overwritten_file_1 = require("./rules/overwritten-file");
@@ -104,7 +106,9 @@ exports.LintingRules = {
104
106
  'code-clones': code_clones_1.CODE_CLONES,
105
107
  'call-contracts': call_contracts_1.CALL_CONTRACTS,
106
108
  'interactive-functions': interactive_functions_1.INTERACTIVE_FUNCTIONS,
107
- 'autoload-files': autoload_files_1.AUTOLOAD_FILES
109
+ 'autoload-files': autoload_files_1.AUTOLOAD_FILES,
110
+ 'notebook-cell-order': notebook_cell_order_1.NOTEBOOK_CELL_ORDER,
111
+ 'project-entry-point': project_entry_point_1.PROJECT_ENTRY_POINT
108
112
  };
109
113
  const DigitWords = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
110
114
  /**
@@ -0,0 +1,43 @@
1
+ import { type LintingResult, LintingRuleCertainty } from '../linter-format';
2
+ import { LintingRuleTag } from '../linter-tags';
3
+ import type { MergeableRecord } from '../../util/objects';
4
+ import { type CellIndex, CellResource } from '../../notebook/cell-order';
5
+ /** the rule has nothing to configure */
6
+ export type NotebookCellOrderConfig = MergeableRecord;
7
+ export interface NotebookCellOrderResult extends LintingResult {
8
+ /** the name the cell reads before any cell above binds it */
9
+ readonly name: string;
10
+ /** what the name stands for: a variable, a package the called function comes from, a file, or global state */
11
+ readonly resource: CellResource;
12
+ /** the reading cell */
13
+ readonly cell: CellIndex;
14
+ /** the cells that bind it */
15
+ readonly providers: readonly CellIndex[];
16
+ /** the lines the code of {@link NotebookCellOrderResult#providers} starts at, which say the cells whatever counts them */
17
+ readonly providedAt: readonly number[];
18
+ /** whether a cell above that binds it fails itself when the notebook runs top to bottom, so it never binds it */
19
+ readonly providerFails?: boolean;
20
+ }
21
+ /**
22
+ * Flags reads of a notebook cell that only work if a cell further down ran before, so the notebook does not run top to bottom,
23
+ * and offers to move that cell up. Reads of global state, like an option another cell sets, are only uncertain findings,
24
+ * as the cell runs either way, but does something else.
25
+ */
26
+ export declare const NOTEBOOK_CELL_ORDER: {
27
+ readonly createSearch: () => import("../../search/flowr-search-builder").FlowrSearchBuilder<"from", [], import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElements<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElement<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>>;
28
+ readonly processSearchResult: (_elements: import("../../search/flowr-search").FlowrSearchElements<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElement<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>, _config: MergeableRecord, data: import("../..").ReadonlyFlowrAnalysisProvider<import("../..").KnownParser>) => Promise<{
29
+ results: NotebookCellOrderResult[];
30
+ '.meta': {};
31
+ }>;
32
+ readonly prettyPrint: {
33
+ readonly query: (r: NotebookCellOrderResult, metadata: unknown) => string;
34
+ readonly full: (r: NotebookCellOrderResult, metadata: unknown) => string;
35
+ };
36
+ readonly info: {
37
+ readonly name: "Notebook Cell Order";
38
+ readonly tags: readonly [LintingRuleTag.Reproducibility, LintingRuleTag.Bug, LintingRuleTag.QuickFix];
39
+ readonly certainty: LintingRuleCertainty.BestEffort;
40
+ readonly description: "Finds notebook cells that read what only a cell further down provides, so the notebook fails or behaves differently when run top to bottom, and offers to move the providing cell up.";
41
+ readonly defaultConfig: () => {};
42
+ };
43
+ };
@@ -0,0 +1,97 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NOTEBOOK_CELL_ORDER = void 0;
4
+ const linter_format_1 = require("../linter-format");
5
+ const linter_tags_1 = require("../linter-tags");
6
+ const flowr_search_builder_1 = require("../../search/flowr-search-builder");
7
+ const range_1 = require("../../util/range");
8
+ const cell_split_1 = require("../../notebook/cell-split");
9
+ const cell_order_1 = require("../../notebook/cell-order");
10
+ /** A change of the lines `from` to `to` to `text` as a quick fix. */
11
+ const replaceLines = (rows, change, description, file) => ({
12
+ type: 'replace',
13
+ description,
14
+ loc: range_1.SourceLocation.from(range_1.SourceRange.from(change.from, 1, change.to, Math.max(1, (rows[change.to - 1] ?? '').length)), file),
15
+ replacement: change.text
16
+ });
17
+ /**
18
+ * The fixes to choose from: moving the cells so that the notebook runs top to bottom, the text between them staying or moving along with the cell below it.
19
+ * Cells that need each other in a cycle no order mends, so then one statement moves out of its cell into one of its own.
20
+ */
21
+ async function reorder(rows, facts, file, analyzer) {
22
+ const moves = [[false, 'Reorder the cells to run top to bottom'], [true, 'Reorder the cells with the text above each']].flatMap(([withText, description]) => {
23
+ const change = (0, cell_order_1.reorderCells)(rows, facts, withText);
24
+ return change === undefined ? [] : [replaceLines(rows, change, description, file)];
25
+ });
26
+ if (moves.length > 0) {
27
+ return moves;
28
+ }
29
+ const split = await (0, cell_split_1.splitForCycle)(analyzer);
30
+ const change = split === undefined ? undefined : (0, cell_split_1.applySplit)(rows, facts, split);
31
+ return change === undefined || split === undefined ? [] : [replaceLines(rows, change, `The cells need each other: move lines ${split.from} to ${split.to} into a cell of their own ${split.before === undefined ? 'at the end' : `above the cell at line ${facts[split.before].cell.from}`}`, file)];
32
+ }
33
+ /**
34
+ * Flags reads of a notebook cell that only work if a cell further down ran before, so the notebook does not run top to bottom,
35
+ * and offers to move that cell up. Reads of global state, like an option another cell sets, are only uncertain findings,
36
+ * as the cell runs either way, but does something else.
37
+ */
38
+ exports.NOTEBOOK_CELL_ORDER = {
39
+ createSearch: () => flowr_search_builder_1.Q.from([]),
40
+ processSearchResult: async (_elements, _config, data) => {
41
+ const facts = await (0, cell_order_1.analyzeNotebook)(data);
42
+ const files = data.inspectContext().files;
43
+ const file = files.getAllFiles().find(f => (0, cell_order_1.notebookCells)(f).length > 0);
44
+ /* the text of the notebook, from its file, or the code itself when it is given as text */
45
+ const text = file === undefined ? files.loadingOrder.getUnorderedRequests().find(r => r.request === 'text')?.content
46
+ : 'rawText' in file && typeof file.rawText === 'function' ? String(file.rawText()) : file.content().toString();
47
+ const rows = (text ?? '').split(/\r?\n/);
48
+ const ast = await data.normalize();
49
+ const fix = await reorder(rows, facts, file?.path(), data);
50
+ const failures = (0, cell_order_1.checkOrder)(facts, facts.map((_, i) => i));
51
+ const fails = new Set(failures.filter(f => f.missing.some(m => !m.soft)).map(f => f.cell));
52
+ const results = failures.flatMap(({ cell, missing }) => missing.map(need => {
53
+ const loc = range_1.SourceLocation.fromNode(ast.idMap.get(need.id));
54
+ return {
55
+ certainty: need.soft ? linter_format_1.LintingResultCertainty.Uncertain : linter_format_1.LintingResultCertainty.Certain,
56
+ involvedId: need.id,
57
+ loc,
58
+ name: need.name,
59
+ resource: need.resource,
60
+ cell,
61
+ providers: need.providers,
62
+ providedAt: need.providers.map(p => facts[p].cell.from),
63
+ providerFails: need.providers.some(p => p < cell && fails.has(p)),
64
+ /* only cells with fences or markers can be moved as text, a transcript or the json of a notebook cannot */
65
+ /* each fix is a single edit, the reorders are alternatives to one another */
66
+ quickFix: fix.length > 0 ? fix.slice(0, 1) : undefined,
67
+ alternatives: fix.length > 1 ? fix.slice(1).map(f => [f]) : undefined
68
+ };
69
+ }));
70
+ return { results, '.meta': {} };
71
+ },
72
+ prettyPrint: (0, linter_format_1.prettyPrintAt)(r => r.resource === cell_order_1.CellResource.File || r.resource === cell_order_1.CellResource.State ? (0, cell_order_1.describeSymbol)(r) : `\`${r.name}\``, r => {
73
+ const at = `the cell at line ${r.providedAt.join(' or ')}`;
74
+ if (r.providers.length === 0) {
75
+ return 'is drawn on, but each cell starts with a new plot when the notebook is knitted, so this fails.';
76
+ }
77
+ /* every cell binding it is above, so it is not the order of these two that fails, but what happens in between */
78
+ if (r.providers.every(p => p < r.cell)) {
79
+ return r.providerFails ? `comes from ${at}, but that cell fails itself, so the notebook fails when run top to bottom.`
80
+ : `comes from ${at}, but is removed again before this cell, so the notebook fails when run top to bottom.`;
81
+ }
82
+ switch (r.resource) {
83
+ case cell_order_1.CellResource.Package: return `comes from a package that only ${at} loads, so the notebook fails when run top to bottom.`;
84
+ case cell_order_1.CellResource.File: return `is read before ${at} writes it, so the notebook fails on a fresh checkout.`;
85
+ case cell_order_1.CellResource.State: return `is used before ${at} sets it, so the result depends on the order.`;
86
+ default: return `is used before ${at} defines it, so the notebook fails when run top to bottom.`;
87
+ }
88
+ }),
89
+ info: {
90
+ name: 'Notebook Cell Order',
91
+ tags: [linter_tags_1.LintingRuleTag.Reproducibility, linter_tags_1.LintingRuleTag.Bug, linter_tags_1.LintingRuleTag.QuickFix],
92
+ certainty: linter_format_1.LintingRuleCertainty.BestEffort,
93
+ description: 'Finds notebook cells that read what only a cell further down provides, so the notebook fails or behaves differently when run top to bottom, and offers to move the providing cell up.',
94
+ defaultConfig: () => ({})
95
+ }
96
+ };
97
+ //# sourceMappingURL=notebook-cell-order.js.map
@@ -0,0 +1,53 @@
1
+ import { type LintingResult, LintingResultCertainty, LintingRuleCertainty } from '../linter-format';
2
+ import { LintingRuleTag } from '../linter-tags';
3
+ import type { MergeableRecord } from '../../util/objects';
4
+ /** the rule has nothing to configure */
5
+ export type ProjectEntryPointConfig = MergeableRecord;
6
+ export interface ProjectEntryPointResult extends LintingResult {
7
+ /** the files of the project that depend on each other, in an order they run in if there is one, else in the loading order */
8
+ readonly files: readonly string[];
9
+ /** whether {@link ProjectEntryPointResult#files} is an order in which the files run */
10
+ readonly runs: boolean;
11
+ /** what the files read of each other, as `b.R reads x from a.R` */
12
+ readonly reads: readonly string[];
13
+ /** a `main.R` that sources the files in that order */
14
+ readonly entry: string;
15
+ }
16
+ /**
17
+ * Flags a project whose scripts read what other scripts define, but which has no file that runs them in an order that
18
+ * works (a `main.R`, a makefile, `_targets.R`, or a package), and suggests a `main.R` that sources them in one.
19
+ * The files are the units here, as the cells of a notebook are for `notebook-cell-order`: a notebook counts as one file,
20
+ * and a file another file sources runs as part of it.
21
+ */
22
+ export declare const PROJECT_ENTRY_POINT: {
23
+ readonly createSearch: () => import("../../search/flowr-search-builder").FlowrSearchBuilder<"from", [], import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElements<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElement<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>>;
24
+ readonly processSearchResult: (_elements: import("../../search/flowr-search").FlowrSearchElements<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation, import("../../search/flowr-search").FlowrSearchElement<import("../../r-bridge/lang-4.x/ast/model/processing/decorate").ParentInformation>[]>, _config: MergeableRecord, data: import("../..").ReadonlyFlowrAnalysisProvider<import("../..").KnownParser>) => Promise<{
25
+ results: {
26
+ certainty: LintingResultCertainty;
27
+ involvedId: import("../..").NodeId;
28
+ loc: readonly [startLine: import("../../util/range").Line, startColumn: import("../../util/range").Column, endLine: import("../../util/range").Line, endColumn: import("../../util/range").Column, f?: string | undefined] | undefined;
29
+ files: string[];
30
+ runs: boolean;
31
+ reads: string[];
32
+ entry: string;
33
+ quickFix: {
34
+ type: "replace";
35
+ description: string;
36
+ loc: readonly [startLine: import("../../util/range").Line, startColumn: import("../../util/range").Column, endLine: import("../../util/range").Line, endColumn: import("../../util/range").Column, f?: string | undefined];
37
+ replacement: string;
38
+ }[] | undefined;
39
+ }[];
40
+ '.meta': {};
41
+ }>;
42
+ readonly prettyPrint: {
43
+ readonly query: (r: ProjectEntryPointResult, metadata: unknown) => string;
44
+ readonly full: (r: ProjectEntryPointResult, metadata: unknown) => string;
45
+ };
46
+ readonly info: {
47
+ readonly name: "Project Entry Point";
48
+ readonly tags: readonly [LintingRuleTag.Reproducibility, LintingRuleTag.Smell, LintingRuleTag.QuickFix];
49
+ readonly certainty: LintingRuleCertainty.BestEffort;
50
+ readonly description: "Finds projects whose scripts read what other scripts define but that have no entry file (such as a main.R, a makefile, or _targets.R) that runs them in an order that works, and suggests a main.R that sources them in one.";
51
+ readonly defaultConfig: () => {};
52
+ };
53
+ };
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PROJECT_ENTRY_POINT = void 0;
4
+ const linter_format_1 = require("../linter-format");
5
+ const linter_tags_1 = require("../linter-tags");
6
+ const flowr_search_builder_1 = require("../../search/flowr-search-builder");
7
+ const range_1 = require("../../util/range");
8
+ const path_1 = require("path");
9
+ const cell_order_1 = require("../../notebook/cell-order");
10
+ /**
11
+ * Flags a project whose scripts read what other scripts define, but which has no file that runs them in an order that
12
+ * works (a `main.R`, a makefile, `_targets.R`, or a package), and suggests a `main.R` that sources them in one.
13
+ * The files are the units here, as the cells of a notebook are for `notebook-cell-order`: a notebook counts as one file,
14
+ * and a file another file sources runs as part of it.
15
+ */
16
+ exports.PROJECT_ENTRY_POINT = {
17
+ createSearch: () => flowr_search_builder_1.Q.from([]),
18
+ processSearchResult: async (_elements, _config, data) => {
19
+ const facts = await (0, cell_order_1.analyzeProject)(data);
20
+ const hard = facts.flatMap(f => f.needs.filter(n => !n.soft));
21
+ if (hard.length === 0 || (0, cell_order_1.projectEntry)(data) !== undefined) {
22
+ return { results: [], '.meta': {} };
23
+ }
24
+ const ast = await data.normalize();
25
+ const order = (0, cell_order_1.firstWorkingOrder)(facts);
26
+ /* the main.R goes into the root of the project, so it counts as its entry, and sources each file from there */
27
+ const context = data.inspectContext().files;
28
+ const root = context.root();
29
+ const path = (i) => context.relativePath(facts[i].cell.file ?? `${i + 1}`);
30
+ const files = (order ?? facts.map((_, i) => i)).map(path);
31
+ const entry = files.map(f => `source("${f}")`).join('\n') + '\n';
32
+ const reads = (0, cell_order_1.describeLinks)(facts, path);
33
+ /* the finding stands at the first read that fails in the loading order, else at the first read of another file */
34
+ const at = (0, cell_order_1.checkOrder)(facts, facts.map((_, i) => i)).flatMap(f => f.missing.filter(m => !m.soft))[0] ?? hard[0];
35
+ return { results: [{
36
+ certainty: order === undefined ? linter_format_1.LintingResultCertainty.Certain : linter_format_1.LintingResultCertainty.Uncertain,
37
+ involvedId: at.id,
38
+ loc: range_1.SourceLocation.fromNode(ast.idMap.get(at.id)),
39
+ files,
40
+ runs: order !== undefined,
41
+ reads,
42
+ entry,
43
+ quickFix: order === undefined ? undefined : [{
44
+ type: 'replace',
45
+ description: `Add a main.R that sources ${files.join(', ')}`,
46
+ loc: range_1.SourceLocation.from(range_1.SourceRange.from(1, 1, 1, 0), root === undefined ? 'main.R' : (0, path_1.join)(root, 'main.R')),
47
+ replacement: entry
48
+ }]
49
+ }], '.meta': {} };
50
+ },
51
+ prettyPrint: (0, linter_format_1.prettyPrintAt)(r => `${r.files.length} files`, r => r.runs
52
+ ? `depend on each other (${r.reads.join('; ')}) in an unclear order: add a main.R that sources ${r.files.join(', ')}.`
53
+ : `depend on each other (${r.reads.join('; ')}) in a cycle, so no order of the files runs them all.`),
54
+ info: {
55
+ name: 'Project Entry Point',
56
+ tags: [linter_tags_1.LintingRuleTag.Reproducibility, linter_tags_1.LintingRuleTag.Smell, linter_tags_1.LintingRuleTag.QuickFix],
57
+ certainty: linter_format_1.LintingRuleCertainty.BestEffort,
58
+ description: 'Finds projects whose scripts read what other scripts define but that have no entry file (such as a main.R, a makefile, or _targets.R) that runs them in an order that works, and suggests a main.R that sources them in one.',
59
+ defaultConfig: () => ({})
60
+ }
61
+ };
62
+ //# sourceMappingURL=project-entry-point.js.map
@@ -43,6 +43,8 @@ export interface SuppressionCounts {
43
43
  unresolvedLibrary: number;
44
44
  /** declared by `utils::globalVariables()` or set by R's method dispatch (`.Generic`, `.Method`, `.Class`) */
45
45
  declaredGlobal: number;
46
+ /** another cell of the notebook binds it, see the `notebook-cell-order` rule for whether it runs before */
47
+ notebookCell: number;
46
48
  }
47
49
  export interface UndefinedSymbolMetadata extends MergeableRecord {
48
50
  totalFunctionCalls: number;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UNDEFINED_SYMBOL = void 0;
4
+ const cell_order_1 = require("../../notebook/cell-order");
4
5
  const built_in_proc_name_1 = require("../../dataflow/environments/built-in-proc-name");
5
6
  const vertex_1 = require("../../dataflow/graph/vertex");
6
7
  const graph_1 = require("../../dataflow/graph/graph");
@@ -96,7 +97,7 @@ exports.UNDEFINED_SYMBOL = {
96
97
  const meta = {
97
98
  totalFunctionCalls: 0,
98
99
  totalVariableUses: 0,
99
- suppressed: { installed: 0, loadedPackage: 0, enclosingScope: 0, nonStandardEval: 0, subscript: 0, unresolvedLibrary: 0, declaredGlobal: 0 }
100
+ suppressed: { installed: 0, loadedPackage: 0, enclosingScope: 0, nonStandardEval: 0, subscript: 0, unresolvedLibrary: 0, declaredGlobal: 0, notebookCell: 0 }
100
101
  };
101
102
  function suppress(reason) {
102
103
  meta.suppressed[reason]++;
@@ -117,6 +118,7 @@ exports.UNDEFINED_SYMBOL = {
117
118
  // names a package declares global (`utils::globalVariables`) are no undefined symbols to R CMD check either
118
119
  const declaredGlobals = declaredGlobalVariables(graph, ctx);
119
120
  const boundByAssign = assignedNames(graph, ctx);
121
+ const otherCellBinds = new Set((await (0, cell_order_1.analyzeNotebook)(data)).flatMap(f => f.needs.map(n => n.id)));
120
122
  // scope-defined names, a fallback for closure variables flowR's dataflow did not statically link
121
123
  const scopeDefined = (0, undefined_symbol_util_1.collectScopeDefinedNames)(graph);
122
124
  // packages whose exports are in scope: DESCRIPTION/library() deps plus the default-attached base
@@ -145,6 +147,9 @@ exports.UNDEFINED_SYMBOL = {
145
147
  || (namespace === undefined ? isAttachedBaseName(name) : (0, r_base_packages_1.baseRExportOwner)(name) === namespace)) {
146
148
  return undefined;
147
149
  }
150
+ if (otherCellBinds.has(id)) {
151
+ return suppress('notebookCell');
152
+ }
148
153
  // a bare name a test framework exports, used in a test file where that framework's namespace is attached
149
154
  if (namespace === undefined && isImplicitTestExport(name, node.info.file)) {
150
155
  return suppress('loadedPackage');
@@ -0,0 +1,23 @@
1
+ import { DataflowGraph } from '../dataflow/graph/graph';
2
+ import type { NodeId } from '../r-bridge/lang-4.x/ast/model/processing/node-id';
3
+ import { type CellFacts } from './cell-order';
4
+ /**
5
+ * A cell graph is the dataflow graph of what the cells of a notebook read of each other: the vertices that read
6
+ * what another cell provides, the vertices of the other cells that provide it, and a reads edge from each read to them.
7
+ * Like a {@link CallGraph} it is a view of the dataflow graph, so whatever draws one draws the other.
8
+ */
9
+ export type CellGraph = DataflowGraph;
10
+ /**
11
+ * Helper object for cell graphs, see {@link CellGraph}.
12
+ * @helper dataflow
13
+ */
14
+ export declare const CellGraph: {
15
+ readonly name: "CellGraph";
16
+ /** The cell graph of the notebook whose cells have the `facts`, out of its whole dataflow `graph`. */
17
+ readonly compute: (this: void, graph: DataflowGraph, facts: readonly CellFacts[]) => CellGraph;
18
+ /** The vertices of `graph` boxed by the cell (or file) whose lines they stand in, `label` saying what to call each box. */
19
+ readonly groups: (this: void, graph: DataflowGraph, facts: readonly CellFacts[], label?: (cell: number) => string) => {
20
+ readonly label: string;
21
+ readonly ids: ReadonlySet<NodeId>;
22
+ }[];
23
+ };