From b21b9f3478c9c6fddd46ca95cf8d7fdcd3d527ac Mon Sep 17 00:00:00 2001 From: Florian Sihler Date: Mon, 30 Nov 2026 09:38:33 +0100 Subject: [PATCH 1/3] feat(notebook): cell orders miss no order that runs in R - cell-order query: new option `runner` (knitr, session, jupyter) that overrides the runner of the format; session keeps the plot, the device, and the working directory across cells - the query's orders leave out orders that run into a read no cell provides; `|>` is a base function; relative file reads resolve against the notebook's directory; dev.off keeps the plot of another device; data masks over R's data sets know their columns - sure warnings: a table of base calls that surely warn and an analysis over the dataflow graph; options(warn = 2) makes a later sure warning a failure, unless it is suppressed or handled - conditional code: single random draws resolve to their range, so branches that can never run are dropped; reads, removals, and options that R may skip are not required or certain - sigdb: a `warns` property and flag - tests: every audit notebook pinned to the orders and dead ends that R produces under console and knit semantics, plus unit tests for warnings, value ranges, and the counterexamples found --- scripts/sigdb-page/about.ts | 1 + scripts/sigdb-page/export-flags.ts | 4 +- scripts/sigdb-page/filters.ts | 1 + .../environments/ambient-state-name.ts | 2 + .../environments/built-in-eval-name.ts | 2 + src/dataflow/environments/built-in.ts | 3 +- .../default-builtin-config/base-functions.ts | 8 +- .../default-builtin-config/warnings.ts | 77 +++++ src/dataflow/eval/resolve/resolve-numbers.ts | 55 ++++ .../eval/resolve/resolve-operators.ts | 46 ++- src/dataflow/eval/resolve/resolve.ts | 9 +- src/dataflow/fn/certain-warnings.ts | 210 ++++++++++++++ .../call/built-in/built-in-ambient-state.ts | 7 +- src/documentation/wiki-query.ts | 12 + src/notebook/cell-order.ts | 181 ++++++++++-- src/project/sigdb/schema.ts | 7 +- .../cell-order-query-format.ts | 16 +- .../signature-query-executor.ts | 12 +- .../signature-query/signature-query-format.ts | 3 + src/util/r-base-packages.ts | 10 +- .../environments/ambient-state.test.ts | 7 + .../environments/built-in-eval.test.ts | 6 +- .../functions/certain-warnings.test.ts | 92 ++++++ .../linter/lint-dead-code.test.ts | 6 +- .../linter/lint-seeded-randomness.test.ts | 2 +- .../notebook/cell-order-audit.test.ts | 265 ++++++++++++++++++ .../functionality/notebook/cell-order.test.ts | 147 +++++++++- .../queries/resolve-value-query.test.ts | 15 + .../assign-environments.test.ts | 4 +- .../calls.test.ts | 2 +- .../util/r-base-packages.test.ts | 4 + 31 files changed, 1159 insertions(+), 57 deletions(-) create mode 100644 src/dataflow/environments/default-builtin-config/warnings.ts create mode 100644 src/dataflow/fn/certain-warnings.ts create mode 100644 test/functionality/dataflow/functions/certain-warnings.test.ts create mode 100644 test/functionality/notebook/cell-order-audit.test.ts diff --git a/scripts/sigdb-page/about.ts b/scripts/sigdb-page/about.ts index db87cabc2e1..5da2e547a5d 100644 --- a/scripts/sigdb-page/about.ts +++ b/scripts/sigdb-page/about.ts @@ -27,6 +27,7 @@ interface FlagInfo { /** how a flag reads on the page and what it means, from the database property it stands for unless it is the page's own */ export const Flags: Readonly> = Object.fromEntries(Object.entries({ [ExportFlag.CanThrow]: { name: 'can throw' }, + [ExportFlag.Warns]: { name: 'may warn', short: 'warns' }, [ExportFlag.S3Method]: { name: 'S3 method', short: 's3' }, [ExportFlag.NonDeterministic]: { name: 'non-deterministic', short: 'nondet' }, [ExportFlag.CallsDeprecated]: { name: 'calls something deprecated', short: 'calls depr' }, diff --git a/scripts/sigdb-page/export-flags.ts b/scripts/sigdb-page/export-flags.ts index 6ea7067adc2..3f1eaa3e703 100644 --- a/scripts/sigdb-page/export-flags.ts +++ b/scripts/sigdb-page/export-flags.ts @@ -14,6 +14,7 @@ export enum ExportFlag { Deprecated = 'x', NoDoc = 'u', NoLocation = 'v', + Warns = 'w', /** the database does not list the name for the package, flowR states a signature for it there */ Stated = '?' } @@ -32,5 +33,6 @@ export const PropFlags: Readonly> = { 'value': ExportFlag.Value, 'higher-order': ExportFlag.HigherOrder, 'deprecated': ExportFlag.Deprecated, - 'no-doc': ExportFlag.NoDoc + 'no-doc': ExportFlag.NoDoc, + 'warns': ExportFlag.Warns }; diff --git a/scripts/sigdb-page/filters.ts b/scripts/sigdb-page/filters.ts index 60b41c293fb..57023b1abe8 100644 --- a/scripts/sigdb-page/filters.ts +++ b/scripts/sigdb-page/filters.ts @@ -49,6 +49,7 @@ const Filters: readonly Filter[] = [ { kind: FilterKind.Only, key: 'package', label: 'packages', about: 'list packages rather than the names they export' }, { kind: FilterKind.Package, key: 'archive', label: 'archived', about: 'names from a package CRAN no longer carries' }, { kind: FilterKind.Flag, key: ExportFlag.CanThrow, label: 'throw', about: Flags[ExportFlag.CanThrow].about ?? '' }, + { kind: FilterKind.Flag, key: ExportFlag.Warns, label: 'warns', about: Flags[ExportFlag.Warns].about ?? '' }, { kind: FilterKind.Flag, key: ExportFlag.NonDeterministic, label: 'non-det.', about: Flags[ExportFlag.NonDeterministic].about ?? '' }, { kind: FilterKind.Flag, key: ExportFlag.S3Method, label: 'S3', about: Flags[ExportFlag.S3Method].about ?? '' }, { kind: FilterKind.Flag, key: ExportFlag.Deprecated, label: 'depr.', about: Flags[ExportFlag.Deprecated].about ?? '' }, diff --git a/src/dataflow/environments/ambient-state-name.ts b/src/dataflow/environments/ambient-state-name.ts index 800e8a252e4..99f747d011c 100644 --- a/src/dataflow/environments/ambient-state-name.ts +++ b/src/dataflow/environments/ambient-state-name.ts @@ -100,6 +100,8 @@ export const AmbientStateName = { unknownOption: '#option:*', /** written along with the option `warn` when it may turn warnings into errors (`warn >= 2`) */ warnsAsErrors: '#warn-error', + /** written along with the option `warn` when it surely turns warnings into errors, every value it may get being 2 or more */ + warnsAsErrorsSurely: '#warn-error:sure', /** the finalizers registered (`reg.finalizer`) and the removals that may release their objects, which `gc()` may run */ finalizers: '#finalizers', /** marks `name` as bound to a text connection opened for writing, whose writes change it */ diff --git a/src/dataflow/environments/built-in-eval-name.ts b/src/dataflow/environments/built-in-eval-name.ts index afee6a7dded..20152165a3a 100644 --- a/src/dataflow/environments/built-in-eval-name.ts +++ b/src/dataflow/environments/built-in-eval-name.ts @@ -4,6 +4,8 @@ export enum BuiltInEvalName { Vector = 'eval:vector', /** the sequence operator `:`, see {@link resolveAsSeq} */ Seq = 'eval:seq', + /** a single random draw (`runif(1)`), folding to the interval of the values it can take, see {@link resolveAsRandomDraw} */ + RandomDraw = 'eval:random-draw', /** every numeric operator and function, from `+` to `sqrt`, see {@link resolveAsNumeric} */ Numeric = 'eval:numeric', /** the comparison operators, see {@link resolveAsComparison} */ diff --git a/src/dataflow/environments/built-in.ts b/src/dataflow/environments/built-in.ts index c33222e07a1..16daea0dfa7 100644 --- a/src/dataflow/environments/built-in.ts +++ b/src/dataflow/environments/built-in.ts @@ -45,7 +45,7 @@ import { resolveAsElement, resolveAsList, resolveAsSeq, resolveAsVector } from ' import { resolveAsStringFn } from '../eval/resolve/resolve-strings'; import { resolveAsComparison, resolveAsGroup, resolveAsLogical } from '../eval/resolve/resolve-operators'; import { resolveAsGet } from '../eval/resolve/resolve-get'; -import { resolveAsNumeric } from '../eval/resolve/resolve-numbers'; +import { resolveAsNumeric, resolveAsRandomDraw } from '../eval/resolve/resolve-numbers'; import { BuiltInEvalName } from './built-in-eval-name'; import type { VariableResolve } from '../../config'; import type { @@ -426,6 +426,7 @@ export const BuiltInEvalHandlerMapper = { [BuiltInEvalName.Vector]: resolveAsVector, [BuiltInEvalName.Seq]: resolveAsSeq, [BuiltInEvalName.Numeric]: resolveAsNumeric, + [BuiltInEvalName.RandomDraw]: resolveAsRandomDraw, [BuiltInEvalName.Comparison]: resolveAsComparison, [BuiltInEvalName.Logical]: resolveAsLogical, [BuiltInEvalName.StringFn]: resolveAsStringFn, diff --git a/src/dataflow/environments/default-builtin-config/base-functions.ts b/src/dataflow/environments/default-builtin-config/base-functions.ts index 5155b2a8d4e..164b71a2b97 100644 --- a/src/dataflow/environments/default-builtin-config/base-functions.ts +++ b/src/dataflow/environments/default-builtin-config/base-functions.ts @@ -207,9 +207,11 @@ export const BaseDefinitions = [ { props: CallProp.Invisible, tags: [SemanticCallTag.File, SemanticCallTag.Writes], sig: sig({ x: Forced.Value, file: Forced.Resource | ArgProp.Optional }) }), fn(base('jitter'), BuiltInProcName.DefaultReadAllArgs, { ambient: Ambient.rng.adds, tags: [SemanticCallTag.Random], sig: sig({ x: ArgProp.NoDefault, factor: 0, amount: 0 }) }, Primitive), - fn([...base('sample', 'sample.int'), ...stats('runif', 'rnorm', 'rbinom', 'rpois', 'rexp', 'rgamma', 'rbeta', 'rcauchy', 'rchisq', 'rgeom', 'rhyper', 'rlnorm', 'rlogis', - 'rmultinom', 'rnbinom', 'rsignrank', 'rt', 'rf', 'rweibull', 'rwilcox', 'arima.sim', 'simulate', 'kmeans')], BuiltInProcName.DefaultReadAllArgs, - { ambient: Ambient.rng.adds, tags: [SemanticCallTag.Random] }), + fn([...base('sample', 'sample.int'), ...stats('rnorm', 'rcauchy', 'rhyper', 'rlogis', 'rmultinom', 'rt', 'arima.sim', 'simulate', 'kmeans')], BuiltInProcName.DefaultReadAllArgs, + { ambient: Ambient.rng.adds, tags: [SemanticCallTag.Random] }), + /* a single draw of these folds to the values it can take, see `RandomDraws` of the value solver */ + fn(stats('runif', 'rbeta', 'rbinom', 'rpois', 'rexp', 'rgamma', 'rchisq', 'rgeom', 'rnbinom', 'rweibull', 'rlnorm', 'rf', 'rsignrank', 'rwilcox'), BuiltInProcName.DefaultReadAllArgs, + { ambient: Ambient.rng.adds, tags: [SemanticCallTag.Random] }, { evalHandler: BuiltInEvalName.RandomDraw }), fn(base('expression'), BuiltInProcName.Default, { props: CallProp.Lang, sig: sig({ '...': ArgProp.Nse }) }, Primitive), fn(base('reg.finalizer'), BuiltInProcName.Default, { ambient: Ambient.finalizers.adds, sig: sig({ e: ArgProp.Forced, f: ArgProp.Forced, onexit: Forced.Flag }) }), diff --git a/src/dataflow/environments/default-builtin-config/warnings.ts b/src/dataflow/environments/default-builtin-config/warnings.ts new file mode 100644 index 00000000000..32ab38db863 --- /dev/null +++ b/src/dataflow/environments/default-builtin-config/warnings.ts @@ -0,0 +1,77 @@ +/** + * When a call of a function R ships surely signals a warning, by the values of its arguments. Each entry was checked + * with R 4.6: a condition here only ever holds for values that warn, a value it does not hold for may warn or not. + * Under `options(warn = 2)` R turns each of these warnings into an error. + */ +export type WarnsWhen = + /** every call warns, as `warning("x")` does */ + | { readonly always: true } + /** a call without any argument warns, as `max()` answers `-Inf` with a warning */ + | { readonly noArguments: true } + /** a value of the formal (one element of it suffices) is a string R cannot read as a number, as in `as.numeric("a")` */ + | { readonly formal: string, readonly notANumber: true } + /** a value of the formal is a string at all, as `mean("a")` answers `NA` with a warning */ + | { readonly formal: string, readonly aString: true } + /** a finite number of the formal lies outside of the closed range `[from, to]`, as `sqrt(-1)` produces `NaN` with a warning */ + | { readonly formal: string, readonly outside: readonly [from: number, to: number] } + /** a number of the formal is a whole number of at most `wholeAtMost`, where the function has a pole (`gamma(0)`, `factorial(-1)`) */ + | { readonly formal: string, readonly wholeAtMost: number }; + +/** what R does not read as a number: everything but decimal and hexadecimal numbers, `Inf`, `Infinity`, `NaN`, and `NA` (which warns, but is left out to keep this list exact), around them only white space */ +const RNumberSyntax = /^\s*(?:[+-]?(?:(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?|0[xX](?:[0-9a-fA-F]+\.?[0-9a-fA-F]*|\.[0-9a-fA-F]+)(?:[pP][+-]?\d+)?|inf(?:inity)?|nan|na))?\s*$/i; + +/** Whether R's coercion of the string to a number surely warns: it is no number (an empty string or white space gives `NA` silently). */ +export function notANumber(str: string): boolean { + return !RNumberSyntax.test(str); +} + +/** the coercions that warn about strings they cannot read (`NAs introduced by coercion`) */ +const Coerces: readonly WarnsWhen[] = [{ formal: 'x', notANumber: true }]; +/** beyond it, `as.integer` gives `NA` (a value between it and the largest integer truncates into the range) */ +const IntegerBound = 2147483648; + +/** + * The functions of R that surely warn for some values of their arguments, by name. Functions not listed may warn as + * well (any closure may call `warning`), they are just never sure to. + */ +export const RWarnings: Readonly> = { + 'warning': [{ always: true }], + 'as.numeric': Coerces, + 'as.double': Coerces, + 'as.complex': Coerces, + /* `as.integer(3e9)`: NAs introduced by coercion to integer range */ + 'as.integer': [...Coerces, { formal: 'x', outside: [-IntegerBound, IntegerBound] }], + /* NaNs produced */ + 'log': [{ formal: 'x', outside: [0, Infinity] }], + 'log2': [{ formal: 'x', outside: [0, Infinity] }], + 'log10': [{ formal: 'x', outside: [0, Infinity] }], + 'log1p': [{ formal: 'x', outside: [-1, Infinity] }], + 'sqrt': [{ formal: 'x', outside: [0, Infinity] }], + 'asin': [{ formal: 'x', outside: [-1, 1] }], + 'acos': [{ formal: 'x', outside: [-1, 1] }], + 'acosh': [{ formal: 'x', outside: [1, Infinity] }], + 'atanh': [{ formal: 'x', outside: [-1, 1] }], + 'gamma': [{ formal: 'x', wholeAtMost: 0 }], + 'factorial': [{ formal: 'x', wholeAtMost: -1 }], + /* argument is not numeric or logical: returning NA */ + 'mean': [{ formal: 'x', aString: true }], + /* no non-missing arguments to max; returning -Inf */ + 'max': [{ noArguments: true }], + 'min': [{ noArguments: true }] +}; + +/** Whether the scalar `value` of an argument makes `when` hold, `undefined` for a condition on no argument. */ +export function warnsFor(when: WarnsWhen, value: string | number): boolean | undefined { + if('always' in when || 'noArguments' in when) { + return undefined; + } else if('notANumber' in when) { + return typeof value === 'string' && notANumber(value); + } else if('aString' in when) { + return typeof value === 'string'; + } else if(typeof value !== 'number' || !Number.isFinite(value)) { + return false; + } else if('outside' in when) { + return value < when.outside[0] || value > when.outside[1]; + } + return value <= when.wholeAtMost && Number.isInteger(value); +} diff --git a/src/dataflow/eval/resolve/resolve-numbers.ts b/src/dataflow/eval/resolve/resolve-numbers.ts index a3f4c8e5be0..5a1f9ec155f 100644 --- a/src/dataflow/eval/resolve/resolve-numbers.ts +++ b/src/dataflow/eval/resolve/resolve-numbers.ts @@ -214,3 +214,58 @@ export function resolveAsNumeric(this: void, args: BuiltInEvalHandlerArgs): Valu return folded === undefined ? Top : vectorFrom(folded.map(n => intervalFrom(n, n))); } + +/** A bound of the values a draw takes: a number, or the parameter giving it with the default R uses without it. */ +type DrawBound = number | { readonly param: string, readonly default?: number }; + +/** + * The values one random draw of a distribution can take, by the parameters R declares for it (see `?Distributions`). + * Teaching flowR one more is a line here plus the `evalHandler` `eval:random-draw` in the built-in configuration. + */ +export interface RandomDraw { + /** the parameter names, in the order R declares them, the first being the number of draws */ + readonly params: readonly string[] + readonly lower: DrawBound + readonly upper: DrawBound +} + +/** the distributions whose draws flowR bounds, all of them within closed bounds (a draw of `runif` never is one of its bounds) */ +export const RandomDraws = { + runif: { params: ['n', 'min', 'max'], lower: { param: 'min', default: 0 }, upper: { param: 'max', default: 1 } }, + rbeta: { params: ['n', 'shape1', 'shape2', 'ncp'], lower: 0, upper: 1 }, + rbinom: { params: ['n', 'size', 'prob'], lower: 0, upper: { param: 'size' } }, + rpois: { params: ['n', 'lambda'], lower: 0, upper: Infinity }, + rexp: { params: ['n', 'rate'], lower: 0, upper: Infinity }, + rgamma: { params: ['n', 'shape', 'rate', 'scale'], lower: 0, upper: Infinity }, + rchisq: { params: ['n', 'df', 'ncp'], lower: 0, upper: Infinity }, + rgeom: { params: ['n', 'prob'], lower: 0, upper: Infinity }, + rnbinom: { params: ['n', 'size', 'prob', 'mu'], lower: 0, upper: Infinity }, + rweibull: { params: ['n', 'shape', 'scale'], lower: 0, upper: Infinity }, + rlnorm: { params: ['n', 'meanlog', 'sdlog'], lower: 0, upper: Infinity }, + rf: { params: ['n', 'df1', 'df2', 'ncp'], lower: 0, upper: Infinity }, + rsignrank: { params: ['nn', 'n'], lower: 0, upper: Infinity }, + rwilcox: { params: ['nn', 'm', 'n'], lower: 0, upper: Infinity } +} as const satisfies Record; + +/** + * Resolves a single random draw (`runif(1)`, `rbinom(1, 5, 0.5)`) to the interval of the values it can take, so that a + * comparison no draw passes (`runif(1) > 2`) folds. More than one draw, or a bound that does not resolve, stays `Top`. + */ +export function resolveAsRandomDraw(this: void, args: BuiltInEvalHandlerArgs): Value { + const name = calledName(args.node); + const draw = name === undefined ? undefined : RandomDraws[name as keyof typeof RandomDraws] as RandomDraw | undefined; + const nodes = draw === undefined ? undefined : matchCallArguments(args.node, draw.params as BrandedIdentifier[]) as (RNodeWithParent | undefined)[] | undefined; + if(draw === undefined || nodes === undefined || nodes[0] === undefined || numeric(nodes[0], args) !== 1) { + return Top; + } + const bound = (b: DrawBound): number | undefined => { + if(typeof b === 'number') { + return b; + } + const node = nodes[draw.params.indexOf(b.param)]; + const value = node === undefined ? b.default : numeric(node, args); + return typeof value === 'number' ? value : undefined; + }; + const [lower, upper] = [bound(draw.lower), bound(draw.upper)]; + return lower === undefined || upper === undefined || Number.isNaN(lower) || Number.isNaN(upper) || lower > upper ? Top : intervalFrom(lower, upper); +} diff --git a/src/dataflow/eval/resolve/resolve-operators.ts b/src/dataflow/eval/resolve/resolve-operators.ts index ab774285e4e..2f30fc39db9 100644 --- a/src/dataflow/eval/resolve/resolve-operators.ts +++ b/src/dataflow/eval/resolve/resolve-operators.ts @@ -4,7 +4,7 @@ import { type BrandedIdentifier, Identifier } from '../../environments/identifie import { isRNumberValue, unliftRValue } from '../../../util/r-value'; import type { BuiltInEvalHandlerArgs } from '../../environments/built-in'; import { ValueLogicalFalse, ValueLogicalTrue } from '../values/logical/logical-constants'; -import { Top, type Value } from '../values/r-value'; +import { isValue, Top, type Value } from '../values/r-value'; import { valueSetGuard } from '../values/general'; import { Resolve } from '../../environments/resolve-helper'; import { NodeValue } from './node-value'; @@ -12,6 +12,7 @@ import { RArgument } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-argument import { RBinaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op'; import { RExpressionList } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; import { RUnaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-unary-op'; +import { RNumber } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-number'; /** the scalar an operand folds to, with a logical counting as its `0`/`1` just like R would coerce it */ function operand(node: RNodeWithParent, args: BuiltInEvalHandlerArgs): number | string | undefined { @@ -70,6 +71,10 @@ export function resolveAsComparison(args: BuiltInEvalHandlerArgs): Value { if(bin === undefined) { return Top; } + const ranged = compareRanges(bin.op, rangeOf(bin.lhs, args), rangeOf(bin.rhs, args)); + if(ranged !== undefined) { + return logicalValue(ranged); + } const lhs = operand(bin.lhs, args); const rhs = operand(bin.rhs, args); if(lhs === undefined || rhs === undefined || typeof lhs !== typeof rhs || (typeof lhs === 'string' && !bin.op.strings)) { @@ -78,6 +83,45 @@ export function resolveAsComparison(args: BuiltInEvalHandlerArgs): Value { return logicalValue(bin.op.apply(lhs, rhs)); } +/** the closed range of numbers an operand may hold, a number or a call of a random draw (see `resolveAsRandomDraw`), `undefined` for anything else */ +function rangeOf(node: RNodeWithParent, args: BuiltInEvalHandlerArgs): readonly [number, number] | undefined { + /* only a call draws: a name may hold a range for the rounds of a loop, which differ from one another */ + if(!RFunctionCall.is(node) && !RNumber.is(node)) { + return undefined; + } + if(RNumber.is(node)) { + return node.content.complexNumber || Number.isNaN(node.content.num) ? undefined : [node.content.num, node.content.num]; + } + /* resolving a node blocks it for the rest of the fold, which still has to resolve it as an operand */ + const set = valueSetGuard(Resolve.toValue(node, { ...args, blocked: new Set(args.blocked) })); + const value = set?.elements.length === 1 ? set.elements[0] : undefined; + if(value === undefined || !isValue(value) || value.type !== 'interval') { + return undefined; + } + const [start, end] = [value.start, value.end]; + if(!isValue(start) || !isValue(end) || !isValue(start.value) || !isValue(end.value) || start.value.complexNumber || end.value.complexNumber) { + return undefined; + } + const [lo, hi] = [start.value.num, end.value.num]; + return Number.isNaN(lo) || Number.isNaN(hi) ? undefined : [lo, hi]; +} + +/** + * A comparison of two ranges that holds for every pair of values in them, or for none, as `runif(1) > 2` holds for none. + * The ranges count as closed, which may only leave a comparison undecided; one of two single numbers is left to the plain fold. + */ +function compareRanges(op: typeof ComparisonOps[keyof typeof ComparisonOps], lhs: readonly [number, number] | undefined, rhs: readonly [number, number] | undefined): boolean | undefined { + if(lhs === undefined || rhs === undefined || (lhs[0] === lhs[1] && rhs[0] === rhs[1])) { + return undefined; + } + const [always, never] = [op.apply(lhs[1], rhs[0]) && op.apply(lhs[0], rhs[1]), !op.apply(lhs[0], rhs[1]) && !op.apply(lhs[1], rhs[0])]; + if(op === ComparisonOps['=='] || op === ComparisonOps['!=']) { + const apart = lhs[1] < rhs[0] || rhs[1] < lhs[0]; + return apart ? op === ComparisonOps['!='] : undefined; + } + return always ? true : never ? false : undefined; +} + /** `decidedBy` is the lhs that fixes the result of the short-circuiting `&&`/`||` on its own; `&`/`|` vectorize, so they need both sides */ export const LogicalOps = { '&&': { apply: (a: boolean, b: boolean) => a && b, decidedBy: false }, diff --git a/src/dataflow/eval/resolve/resolve.ts b/src/dataflow/eval/resolve/resolve.ts index 99e1aec8598..541085406a8 100644 --- a/src/dataflow/eval/resolve/resolve.ts +++ b/src/dataflow/eval/resolve/resolve.ts @@ -66,6 +66,13 @@ export function onlyLiterals(node: RNode): boolean { : RNumber.is(node) || RString.is(node) || RLogical.is(node); } +/** Whether the node folds while the analysis runs: literals, and operators and calls on nothing else (`runif(1) > 2`), as no name in them may change its value; the called names are checked where they fold. */ +function foldsWhileAnalyzing(node: RNode): boolean { + return onlyLiterals(node) || (RBinaryOp.is(node) ? foldsWhileAnalyzing(node.lhs) && foldsWhileAnalyzing(node.rhs) + : RUnaryOp.is(node) ? foldsWhileAnalyzing(node.operand) + : RFunctionCall.isNamed(node) && node.arguments.every(a => a !== EmptyArgument && a.value !== undefined && foldsWhileAnalyzing(a.value))); +} + /** The name of the built-in the given node folds through, `undefined` if it is no call to one or if it may just as well resolve to something else (a user redefinition, a conditional one, ...), which must not be folded. */ function evalNameOf({ node, graph, environment, ctx }: BuiltInEvalHandlerArgs): Identifier | undefined { if(!EvalNodeTypes.includes(node.type)) { @@ -73,7 +80,7 @@ function evalNameOf({ node, graph, environment, ctx }: BuiltInEvalHandlerArgs): } else if(graph === undefined) { const named = RExpressionList.is(node) ? RExpressionList.groupStart(node)?.content : RAccess.is(node) ? Identifier.make(node.operator) - : RFunctionCall.calledName(node) ?? ((RBinaryOp.is(node) || RUnaryOp.is(node)) && onlyLiterals(node) ? Identifier.make(node.operator) : undefined); + : RFunctionCall.calledName(node) ?? ((RBinaryOp.is(node) || RUnaryOp.is(node)) && foldsWhileAnalyzing(node) ? Identifier.make(node.operator) : undefined); return named !== undefined && environment !== undefined && foldsThroughBuiltIn(named, ctx) && Resolve.isBuiltIn(named, environment, ReferenceType.Function) ? named : undefined; } diff --git a/src/dataflow/fn/certain-warnings.ts b/src/dataflow/fn/certain-warnings.ts new file mode 100644 index 00000000000..6b1c3e29cf5 --- /dev/null +++ b/src/dataflow/fn/certain-warnings.ts @@ -0,0 +1,210 @@ +import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id'; +import type { AstIdMap, ParentInformation, RNodeWithParent } from '../../r-bridge/lang-4.x/ast/model/processing/decorate'; +import type { DataflowGraph } from '../graph/graph'; +import type { ReadOnlyFlowrAnalyzerContext } from '../../project/context/flowr-analyzer-context'; +import type { ResolveInfo } from '../eval/resolve/alias-tracking'; +import { RNode } from '../../r-bridge/lang-4.x/ast/model/model'; +import { RFunctionCall, EmptyArgument } from '../../r-bridge/lang-4.x/ast/model/nodes/r-function-call'; +import { RFunctionDefinition } from '../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition'; +import { RExpressionList } from '../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; +import { RArgument } from '../../r-bridge/lang-4.x/ast/model/nodes/r-argument'; +import { RBinaryOp } from '../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op'; +import { Identifier, ReferenceType } from '../environments/identifier'; +import { Dataflow } from '../graph/df-helper'; +import { OriginType } from '../origin/dfg-get-origin'; +import { BuiltInProcName } from '../environments/built-in-proc-name'; +import { ArgProp, type FnSig } from '../environments/built-in-props'; +import { NodeValue } from '../eval/resolve/node-value'; +import { isValue, type Value } from '../eval/values/r-value'; +import { RWarnings, warnsFor, type WarnsWhen } from '../environments/default-builtin-config/warnings'; +import { isBaseRPackage } from '../../util/r-base-packages'; + +/** What {@link CertainWarnings} looks at: the finished graph, and where to resolve the values of arguments. */ +export interface CertainWarningsInfo { + readonly graph: DataflowGraph + readonly idMap: AstIdMap + readonly ctx: ReadOnlyFlowrAnalyzerContext + readonly resolve: ResolveInfo +} + +/** the processors of built-ins that evaluate the arguments they are handed right away, as far as their signature says so */ +const Eager: ReadonlySet = new Set([BuiltInProcName.Default, BuiltInProcName.DefaultReadAllArgs]); + +/** the function calls stopping a body before its end, so that a warning after them need not happen */ +const Exits: ReadonlySet = new Set(['return', 'invokeRestart', 'q', 'quit', 'stop', 'on.exit', 'Recall']); + +/** + * The calls that surely signal a warning when they run, as `as.numeric("a")` or a call of a function whose body surely + * calls one (see {@link RWarnings}). What it reports is sure: a call may well warn without being reported, as for + * arguments whose value flowR does not know. Whether a handler catches the warning (`suppressWarnings`, `tryCatch`) + * is for {@link CertainWarnings.sites} to say, which only reports what runs eagerly with no handler around it. + */ +export const CertainWarnings = { + name: 'CertainWarnings', + /** Whether the call `id` surely signals a warning when it runs (a handler around it aside). */ + warns(this: void, id: NodeId, info: CertainWarningsInfo, seen: ReadonlySet = new Set()): boolean { + const node = info.idMap.get(id); + if(!RFunctionCall.is(node) || seen.has(id)) { + return false; + } + const builtin = builtInOf(id, info); + if(builtin !== undefined) { + return (RWarnings[builtin] ?? []).some(w => holds(w, node, info)); + } + const callees = Dataflow.calleeIdsOf(info.graph, id).map(c => info.idMap.get(c)); + const within = new Set(seen).add(id); + return callees.length > 0 && callees.every(c => RFunctionDefinition.is(c) && bodyWarns(c, info, within)); + }, + /** + * The calls within `root` (a top-level expression, say) that surely run whenever `root` runs and surely warn: none in a + * branch or loop, in a function definition, in an argument a call may not evaluate (`quote`, a closure's promise), or + * within a construct handling or muffling warnings (`suppressWarnings`, `tryCatch`, `try`, `withCallingHandlers`). + */ + sites(this: void, root: NodeId, info: CertainWarningsInfo, seen: ReadonlySet = new Set()): NodeId[] { + const top = info.idMap.get(root); + if(top === undefined) { + return []; + } + const found: NodeId[] = []; + RNode.visitAst(top, n => { + if(RFunctionDefinition.is(n)) { + return true; + } + if(RFunctionCall.is(n) && runsWith(n, top, info) && CertainWarnings.warns(n.info.id, info, seen)) { + found.push(n.info.id); + } + return false; + }); + return found; + } +} as const; + +/** the name of the one built-in the call goes to, `undefined` if it may go to a closure or to several built-ins */ +function builtInOf(id: NodeId, info: CertainWarningsInfo): string | undefined { + const origins = Dataflow.origin(info.graph, id) ?? []; + /* what a package other than those of R defines under the name is not what the table states */ + const names = new Set(origins.map(o => o.type === OriginType.BuiltInFunctionOrigin && isBaseRPackage(String(Identifier.getNamespace(o.fn.name) ?? 'base')) ? String(Identifier.getName(o.fn.name)) : undefined)); + return names.size === 1 && !names.has(undefined) && origins.every(o => o.type === OriginType.BuiltInFunctionOrigin) ? [...names][0] : undefined; +} + +/** the signature and processor of the built-in of that name */ +function builtInDefinition(name: string, info: CertainWarningsInfo): { readonly sig?: FnSig, readonly processor: string, readonly muffles: boolean } | undefined { + const defs = info.ctx.env.builtInDefinitionsOf(Identifier.make(name)).filter(d => d.type === ReferenceType.BuiltInFunction); + const [def] = defs; + if(defs.length !== 1 || def.type !== ReferenceType.BuiltInFunction) { + return undefined; + } + return { sig: def.config?.sig, processor: def.processorName ?? '', muffles: (def.config?.muffles?.length ?? 0) > 0 }; +} + +/** Whether the body of the definition surely warns before it may return, with no branch around the warning. */ +function bodyWarns(fn: RFunctionDefinition, info: CertainWarningsInfo, seen: ReadonlySet): boolean { + const statements = RExpressionList.is(fn.body) ? fn.body.children : [fn.body]; + for(const statement of statements) { + /* a statement that may leave the body may do so before its warning */ + if(mayExit(statement)) { + return false; + } + if(CertainWarnings.sites(statement.info.id, info, seen).length > 0) { + return true; + } + } + return false; +} + +function mayExit(node: RNodeWithParent): boolean { + let exits = false; + RNode.visitAst(node, n => { + if(RFunctionDefinition.is(n)) { + return true; + } + exits ||= RFunctionCall.isNamed(n, Exits); + return exits; + }); + return exits; +} + +/** Whether the call runs whenever `top` runs: every node between them evaluates it right away, outside of any branch, loop, or handler. */ +function runsWith(call: RNodeWithParent, top: RNodeWithParent, info: CertainWarningsInfo): boolean { + if((info.graph.getVertex(call.info.id)?.cds?.length ?? 0) > 0) { + return false; + } + for(let child = call, at = RNode.directParent(call, info.idMap); child !== top; child = at, at = RNode.directParent(at, info.idMap)) { + if(at === undefined || !evaluates(at, child, info)) { + return false; + } + } + return true; +} + +/** Whether `parent` evaluates its child `child` as it runs, and lets a warning of it through. */ +function evaluates(parent: RNodeWithParent, child: RNodeWithParent, info: CertainWarningsInfo): boolean { + if(RExpressionList.is(parent) || RArgument.is(parent)) { + return true; + } else if(RBinaryOp.is(parent)) { + /* the value of an assignment */ + return ['<-', '=', '<<-'].includes(parent.operator) ? parent.rhs === child : ['->', '->>'].includes(parent.operator) && parent.lhs === child; + } else if(!RFunctionCall.is(parent) || parent.functionName === child) { + return false; + } + const name = builtInOf(parent.info.id, info); + const def = name === undefined ? undefined : builtInDefinition(name, info); + if(def === undefined || def.muffles || !Eager.has(def.processor) || def.sig === undefined) { + return false; + } + const props = formalOf(parent, child, def.sig); + return props !== undefined && (props & ArgProp.Forced) !== 0 && (props & (ArgProp.Nse | ArgProp.Lazy)) === 0; +} + +/** what the signature says of the formal the argument `arg` of the call is matched to */ +function formalOf(call: RFunctionCall, arg: RNodeWithParent, sig: FnSig): number | undefined { + const named = RArgument.isNamed(arg) ? Identifier.getName(arg.name.content) : undefined; + if(named !== undefined) { + return (sig.find(([f]) => f === named) ?? sig.find(([f]) => f === '...'))?.[1]; + } + const taken = new Set(call.arguments.flatMap(a => a !== EmptyArgument && a.name !== undefined ? [Identifier.getName(a.name.content)] : [])); + const positional = sig.filter(([f]) => !taken.has(f)); + const index = call.arguments.filter(a => a === EmptyArgument || a.name === undefined).indexOf(arg as RArgument); + const dots = positional.findIndex(([f]) => f === '...'); + return index < 0 ? undefined : (dots >= 0 && index >= dots ? positional[dots] : positional[index])?.[1]; +} + +/** Whether the condition holds for every value the call's arguments may have. */ +function holds(when: WarnsWhen, call: RFunctionCall, info: CertainWarningsInfo): boolean { + if('always' in when) { + return true; + } + const args = call.arguments.filter(a => a !== EmptyArgument); + if('noArguments' in when) { + return call.arguments.every(a => a === EmptyArgument) && args.length === 0; + } + const arg = args.find(a => a.name !== undefined && Identifier.getName(a.name.content) === when.formal) ?? args.find(a => a.name === undefined); + const values = NodeValue.setOf(arg?.value?.info.id, info.resolve)?.elements; + return values !== undefined && values.length > 0 && values.every(v => scalarsOf(v)?.some(s => warnsFor(when, s)) === true); +} + +/** the strings and numbers a value holds, `undefined` if any element is not known */ +function scalarsOf(value: Value): (string | number)[] | undefined { + if(!isValue(value)) { + return undefined; + } + switch(value.type) { + case 'string': + return isValue(value.value) ? [value.value.str] : undefined; + case 'number': + return isValue(value.value) && !value.value.complexNumber ? [value.value.num] : undefined; + case 'interval': { + const [start, end] = [value.start, value.end]; + return isValue(start) && isValue(end) && isValue(start.value) && isValue(end.value) && start.value.num === end.value.num && !start.value.complexNumber ? [start.value.num] : undefined; + } + case 'vector': { + if(!isValue(value.elements)) { + return undefined; + } + const all = value.elements.map(scalarsOf); + return all.every(s => s !== undefined) ? all.flat() : undefined; + } + default: + return undefined; + } +} diff --git a/src/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.ts b/src/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.ts index f35c778f1f9..7b2f88b1e74 100644 --- a/src/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.ts +++ b/src/dataflow/internal/process/functions/call/built-in/built-in-ambient-state.ts @@ -977,6 +977,7 @@ function setOptions(res: DataflowInformation, args: readonly Potentia const queried: string[] = []; const written: AmbientStateName[] = []; let warnsAsErrors = false; + let surely = false; let global = false; let unknownKeys = false; for(const arg of args) { @@ -987,7 +988,9 @@ function setOptions(res: DataflowInformation, args: readonly Potentia const key = Identifier.getName(arg.name.content); written.push(AmbientStateName.option(key)); global ||= GlobalEffectOptions.has(key); - warnsAsErrors ||= key === 'warn' && !NodeValue.setOf(arg.value?.info.id, data)?.elements.every(value => value.type === 'logical' || (RValue.numberOf(value) ?? 2) < 2); + const levels = key === 'warn' ? NodeValue.setOf(arg.value?.info.id, data)?.elements : undefined; + warnsAsErrors ||= key === 'warn' && !levels?.every(value => value.type === 'logical' || (RValue.numberOf(value) ?? 2) < 2); + surely ||= levels !== undefined && levels.length > 0 && levels.every(value => (RValue.numberOf(value) ?? 0) >= 2); } else if(RString.is(arg.value)) { queried.push(arg.value.content.str); } else { @@ -1002,7 +1005,7 @@ function setOptions(res: DataflowInformation, args: readonly Potentia /* the call returns the previous values of what it sets, which only matters if that value is used */ const previous = resultIsUsed(rootId, data) ? written : []; const reads = [...queried.map(AmbientStateName.option), ...previous, ...args.length === 0 || unknownKeys ? [AmbientStateName.allOptions] : []]; - const writes = [...written, ...unknownKeys ? [AmbientStateName.unknownOption] : [], ...warnsAsErrors ? [AmbientStateName.warnsAsErrors] : []]; + const writes = [...written, ...unknownKeys ? [AmbientStateName.unknownOption] : [], ...warnsAsErrors ? [AmbientStateName.warnsAsErrors] : [], ...surely ? [AmbientStateName.warnsAsErrorsSurely] : []]; return withAccess(res, rootId, data, reads.length > 0 ? [...reads, AmbientStateName.unknownOption] : [], writes.length > 0 ? [...writes, AmbientStateName.allOptions] : []); } diff --git a/src/documentation/wiki-query.ts b/src/documentation/wiki-query.ts index 91b45eae336..dccb756677d 100644 --- a/src/documentation/wiki-query.ts +++ b/src/documentation/wiki-query.ts @@ -1153,6 +1153,18 @@ registerQueryDocumentation('cell-order', { return ` 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. 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. +The orders listed run without an error: a cell that lacks what no cell provides (\`y <- x + 1\` where nothing binds \`x\`) runs in none of them, so they end before it. +A cell that surely warns (\`as.numeric("a")\`, \`log(-1)\`, or a function whose body surely does, unless a handler such as \`suppressWarnings\` catches it) fails after a cell that set \`options(warn = 2)\`. +What may not run, as code in a branch or in a loop that may run no round, is not needed for a cell to run, and a removal there (\`if (cond) rm(x)\`) removes nothing for sure; a branch no value can take (\`if (runif(1) > 2)\`) does not run at all. + +What runs the cells decides what each cell starts with, which \`runner\` sets: +- \`knitr\` (the default for R Markdown, Quarto, and knitr Sweave) knits the document: each chunk starts with a new plot and in the directory of the document, + so \`abline(h = 1)\` in a chunk after \`plot(1:10)\` fails (unless \`opts_knit$set(global.device = TRUE)\`), and a \`setwd\` holds only for its own chunk. + RStudio runs the chunks of a notebook shown inline the same way. +- \`session\` (the default for \`# %%\` scripts, R console transcripts, and Sweave) runs the cells one after another in one R session, as a console does: + the plot, the graphics device, and the working directory stay from one cell to the next, and knitr evaluates no chunk options. + Ask for it to check the cells of a document someone runs in a console. +- \`jupyter\` runs the cells of a Jupyter notebook, each with a new plot. ${ await showQuery(shell, exampleCode, [{ type: 'cell-order', orders: 3, changed: [1] }]) } diff --git a/src/notebook/cell-order.ts b/src/notebook/cell-order.ts index 20fb97c8b99..943a8040398 100644 --- a/src/notebook/cell-order.ts +++ b/src/notebook/cell-order.ts @@ -25,7 +25,9 @@ import { RFunctionCall, EmptyArgument } from '../r-bridge/lang-4.x/ast/model/no import { RArgument } from '../r-bridge/lang-4.x/ast/model/nodes/r-argument'; import { RIfThenElse } from '../r-bridge/lang-4.x/ast/model/nodes/r-if-then-else'; import { RForLoop } from '../r-bridge/lang-4.x/ast/model/nodes/r-for-loop'; +import { RRepeatLoop } from '../r-bridge/lang-4.x/ast/model/nodes/r-repeat-loop'; import { CellRunner, freshStateOf, RunnerFreshState } from '../project/plugins/file-plugins/files/cell-runner'; +import { CertainWarnings } from '../dataflow/fn/certain-warnings'; import { Resolve } from '../dataflow/environments/resolve-helper'; import { runsBodyOnce } from '../dataflow/internal/process/functions/call/built-in/built-in-for-loop'; import { RBinaryOp } from '../r-bridge/lang-4.x/ast/model/nodes/r-binary-op'; @@ -37,9 +39,9 @@ import { RFunctionDefinition } from '../r-bridge/lang-4.x/ast/model/nodes/r-func import { type Line, SourceRange } from '../util/range'; import { uniqueArray, uniqueArrayMerge } from '../util/collections/arrays'; import { DefaultMap, getOrSet } from '../util/collections/defaultmap'; -import { relativeTo } from '../util/files'; +import { relativeTo, RPath } from '../util/files'; import { Ternary } from '../util/logic'; -import { BaseDatasets, BaseValues, baseRExportOwner } from '../util/r-base-packages'; +import { BaseDatasets, BaseValues, baseRExportOwner, isBaseRPackage } from '../util/r-base-packages'; import { datasetShape, MaxDatasetColumns } from '../util/r-datasets'; import { type CodeBlock, type CodeBlockOptions, continuesAfterError, ErrorTolerantValues, FlowrRMarkdownFile, globalChunkOptions, isExecutableCell, NonExecutableEvalValues, optionReads } from '../project/plugins/file-plugins/files/flowr-rmarkdown-file'; import { FlowrSweaveFile } from '../project/plugins/file-plugins/files/flowr-sweave-file'; @@ -126,6 +128,8 @@ export interface CellNeed { readonly changes?: true /** the function definition whose body reads it, as the cell calls it: the cell needs it only if, as it runs, a name it needs is bound to that function */ readonly of?: NodeId + /** the cell fails if the session has it, as a cell that surely warns fails once a cell before turned warnings into errors; the providers are the cells that put it there */ + readonly absent?: true } /** A function definition a value is, or holds as its element `at` (`list(run = function() 1)`). */ @@ -167,11 +171,13 @@ export type CellEffect = EffectPlace & { readonly of?: NodeId } & ( | { readonly bindsAny: CellResource.Variable | CellResource.Attached }); export interface CellFacts { - readonly cell: NotebookCell - readonly needs: readonly CellNeed[] + readonly cell: NotebookCell + readonly needs: readonly CellNeed[] /** what the cell reads and no other cell binds, before it binds it itself (`print(d); d <- 1`) or not at all: no order of the cells helps, but a run of the cell without it fails */ - readonly lacks: readonly CellNeed[] - readonly effects: readonly CellEffect[] + readonly lacks: readonly CellNeed[] + /** what the cell fails with if the session holds it (see {@link CellNeed.absent}), as a warning once a cell before set `options(warn = 2)` */ + readonly forbids?: readonly CellNeed[] + readonly effects: readonly CellEffect[] } /** A read of a cell before the reads are resolved to the cells that provide them. */ @@ -193,6 +199,8 @@ interface CellRead extends CellSymbol { readonly range?: SourceRange /** where in the body of a function the call `id` runs the read is */ readonly inner?: NodeId + /** the cell needs the symbol not to be there, see {@link CellNeed.absent} */ + readonly absent?: true } /** The session between cells: what is bound, by {@link sessionKey}, and to what kind of value, with the function definitions it holds. */ @@ -227,6 +235,10 @@ const FrameKeepers: readonly Identifier[] = [...[PkgName.Tibble, PkgName.Dplyr]. type ColumnOp = { readonly add: string } | { readonly drop: string } | { readonly keep: readonly string[] } | { readonly any: true }; const opColumns = (o: ColumnOp): readonly string[] => 'add' in o ? [o.add] : 'drop' in o ? [o.drop] : 'keep' in o ? o.keep : []; const PlotState = resource(CellResource.State, 'plot'); +/** the state of warnings being errors, which `options(warn = 2)` surely puts the session in */ +const WarnsAsErrorsState = resource(CellResource.State, AmbientStateName.warnsAsErrorsSurely.slice(1)); +/** the tracked states a setting of the option `warn` writes */ +const WarnLevelWrites = /^option:warn$/; const DeviceState = resource(CellResource.State, AmbientStateName.deviceOpener.slice(1)); /** 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 */ const ChunkOptions = { eval: [resource(CellResource.State, 'opts_chunk:eval=FALSE'), NonExecutableEvalValues], error: [resource(CellResource.State, 'opts_chunk:error=TRUE'), ErrorTolerantValues] } as const; @@ -308,14 +320,31 @@ export function scriptCells(text: string): NotebookCell[] { } /** The facts of the cells of the analyzed notebook (or of `cells` if given), derived once per analysis from its dataflow graph. */ -export function analyzeNotebook(analyzer: ReadonlyFlowrAnalysisProvider, cells?: readonly NotebookCell[]): Promise { +export function analyzeNotebook(analyzer: ReadonlyFlowrAnalysisProvider, cells?: readonly NotebookCell[], runner?: CellRunner): Promise { const compute = async() => { const files = analyzer.inspectContext().files; /* code given as text rather than as a file may have cells as well */ - 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) ?? []; + 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) ?? []) + .map(c => runner === undefined ? c : runAs(c, runner)); return found.length === 0 ? [] : cellFacts(found, await analyzer.normalize(), await analyzer.dataflow(), await cellDependencies(analyzer), analyzer.inspectContext()); }; - return cells === undefined ? analyzer.derive(analyzeNotebook, compute) : compute(); + return cells === undefined ? analyzer.derive(runner === undefined ? analyzeNotebook : RunnerKeys[runner], compute) : compute(); +} + +/** a key for each runner to keep the facts of a notebook run by a runner other than its own apart, see {@link analyzeNotebook} */ +const RunnerKeys: Readonly> = { [CellRunner.Session]: {}, [CellRunner.Knitr]: {}, [CellRunner.Jupyter]: {} }; + +/** + * The cell as `runner` runs it, whatever runs it by its format: a session or Jupyter does not evaluate the chunk options of + * knitr (`eval = cran`) and runs each cell one asks it to. A cell that goes on after an error (`error = TRUE`) still does, as + * flowR reads its code as wrapped in `tryCatch`, which only promises more orders. + */ +export function runAs(cell: NotebookCell, runner: CellRunner): NotebookCell { + if(runner === CellRunner.Knitr) { + return { ...cell, runner }; + } + const { sets: _s, reads: _r, maybe: _m, ...rest } = cell; + return { ...rest, runner }; } async function cellDependencies(analyzer: ReadonlyFlowrAnalysisProvider): Promise { @@ -418,6 +447,12 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df }; /* the code of a sourced script runs in the cell that sources it */ const sourcedBy = (deps.sources ?? []).flatMap(s => s.nodeId === undefined || typeof s.value !== 'string' || s.value === '' ? [] : [{ file: s.value, by: s.nodeId }]); + /* whether flowR read the code of node `id` for the call `by` of `source`, which names the ids of what it reads by where the name of the call is */ + const sourcedAt = (by: NodeId, id: NodeId) => { + const call = ast.idMap.get(by); + const at = RFunctionCall.isNamed(call) ? call.functionName.location : undefined; + return at !== undefined && String(id).includes(`:${at[0]}:${at[1]}-`); + }; /* 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 */ const evaluatedBy = new Map(graph.verticesOfType(VertexType.FunctionCall).filter(([, v]) => DfgVertex.hasOrigin(v, BuiltInProcName.Eval)) .flatMap(([id]) => Dataflow.targetsOf(graph, id, EdgeType.Returns).map(t => [t, id] as const))); @@ -435,7 +470,9 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df const runnerOf = (at: NodeId, seen = new Set()): NodeId => { const id = hostOf(at); const file = ast.idMap.get(id)?.info.file; - const source = sourcedBy.find(s => file?.endsWith(s.file) === true && !seen.has(s.by)); + const sources = sourcedBy.filter(s => file?.endsWith(s.file) === true && !seen.has(s.by)); + /* a file sourced more than once (by two cells) is read anew for each call, its ids carrying where the call is (`helpers.R:6:1-0`) */ + const source = sources.length > 1 ? sources.find(s => sourcedAt(s.by, id)) ?? sources[0] : sources[0]; return source === undefined ? id : runnerOf(source.by, seen.add(source.by)); }; const cellOf = (at: NodeId) => lineCell(runnerOf(at)); @@ -486,7 +523,7 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df return pa[0] - pb[0] || pa[1] - pb[1]; }; /* an effect a call has as it runs a function is `at` the call, `inner` where in the body */ - const raw = cells.map(() => ({ reads: [] as CellRead[], effects: [] as { at: NodeId, inner?: NodeId, effect: CellEffect }[] })); + const raw: { reads: CellRead[], effects: { at: NodeId, inner?: NodeId, effect: CellEffect }[] }[] = cells.map(() => ({ reads: [], effects: [] })); const placed = (at: NodeId, e: CellEffect) => ({ at, effect: { ...e, ...placeOf(at, true), ...'binds' in e ? { id: at } : {} } }); const effect = (at: NodeId | undefined, e: CellEffect) => at === undefined ? undefined : raw[cellOf(at)]?.effects.push(placed(at, e)); const read = (r: CellRead) => raw[cellOf(r.id)]?.reads.push(r); @@ -741,6 +778,11 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df if(data !== undefined && !(RFunctionCall.is(at) && data.value !== undefined && maskedBy(at.info.id, data.value.info.id))) { return data.value; } + /* a call a pipe gives its first argument (`mtcars |> subset(mpg > 20)`, `mtcars %>% filter(mpg > 20)`) has the left side as its data */ + const pipe = RFunctionCall.is(at) && data === undefined ? RNode.directParent(at, ast.idMap) : undefined; + if((RPipe.is(pipe) || RBinaryOp.is(pipe) && pipe.operator === '%>%') && pipe.rhs === at) { + return RArgument.is(pipe.lhs) ? pipe.lhs.value : pipe.lhs; + } } return undefined; }; @@ -838,7 +880,9 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df /* 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 */ const user = (partial || piped ? Dataflow.targetsOf(graph, id, EdgeType.Reads).filter(t => DfgVertex.isVariableDefinition(graph.getVertex(t)) || DfgVertex.hasOrigin(graph.getVertex(t), BuiltInProcName.Library)).map((target): Origin => ({ type: OriginType.ReadVariableOrigin, id: target })) : definedBy(graph, id)).map(attachedBy) /* a formula (`lm(mpg ~ wt, data = d)`) finds the columns of its data before the lazy data of a package */ - .filter(o => !inFormula(id) || !DfgVertex.hasOrigin(graph.getVertex(o.id), BuiltInProcName.Library)); + .filter(o => !inFormula(id) || !DfgVertex.hasOrigin(graph.getVertex(o.id), BuiltInProcName.Library)) + /* a function the call is handed and runs (the handler of `withCallingHandlers`) is no definition of the name it calls */ + .filter(o => !call || RNode.findEnclosing(o.id, ast.idMap, n => n.info.id === id) === undefined); const kind = call ? SymbolKind.Function : values.has(id) || data.has(id) ? SymbolKind.Value : SymbolKind.Any; const lookup = call ? lookupOf(id) : undefined; if(lookup !== undefined && DfgVertex.isFunctionCall(vertex)) { @@ -883,7 +927,12 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df /* the columns the data certainly has, as the call making it names them (`data.frame(x = 1)`, an environment from `new.env()` has none), also through every assignment a name reads, unless it is not known */ const madeColumns = (node: RNode | undefined, seen: ReadonlySet = new Set()): readonly string[] | undefined => { if(RSymbol.is(node)) { - return meetColumns((Dataflow.origin(graph, node.info.id) ?? []).map(o => o.type === OriginType.ReadVariableOrigin ? columnsAt(o.id, seen) : undefined)); + const origins = Dataflow.origin(graph, node.info.id) ?? []; + /* a name no code binds is the data set of R it names (`with(mtcars, mpg)`), if it is one */ + if(origins.length === 0) { + return datasetShape(Identifier.getName(node.content))?.columns; + } + return meetColumns(origins.map(o => o.type === OriginType.ReadVariableOrigin ? columnsAt(o.id, seen) : undefined)); } return RFunctionCall.is(node) && DfgVertex.hasOrigin(graph.getVertex(node.info.id), BuiltInProcName.NewEnv) ? [] : frameColumns(node, RFunctionCall.is(node) ? calledFunction(node.info.id) : undefined); }; @@ -992,6 +1041,12 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df const drops = changes(o => 'any' in o || 'drop' in o && o.drop === name || 'keep' in o && !o.keep.includes(name)); return frame === undefined || !known.has(frame) ? [] : added(frame, name) && !changes(o => 'any' in o) ? [column(frame, name)] : drops ? [column(frame, name), maybe(frame, name)] : []; }; + /* the package of the function masking `id` (`dplyr` of `filter(d, a > 1)`), if R has a function of its name as well */ + const maskingPackage = (id: NodeId) => graph.edgesTo(id).entries().flatMap(([from, e]) => { + const fn = DfEdge.includesType(e, EdgeType.NonStandardEvaluation) ? qualified.get(from) : undefined; + const ns = fn === undefined ? undefined : Identifier.getNamespace(fn); + return fn !== undefined && ns !== undefined && !isBaseRPackage(String(ns)) && baseRExportOwner(Identifier.getName(fn)) !== undefined ? [String(ns)] : []; + }).toArray()[0]; /* unless a cell may drop the column again */ const inData = (id: NodeId, name: string) => masked(id) && madeColumns(dataOf(id))?.includes(name) === true && columnRead({ id, name }).length === 0; /* the functions the cells bind under each name, also through the names they bind anew (`g <- f`) */ @@ -1074,13 +1129,20 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df } } } - /* a file read is a hard need where the project does not have the file, so only the cell writing it can make it */ - const fileReads = new Map(deps.reads.flatMap(r => r.nodeId === undefined || typeof r.value !== 'string' ? [] : [[r.nodeId, !ctx.files.hasFile(r.value)] as const])); + /* a file read is a hard need where the project does not have the file, so only the cell writing it can make it; a relative path is + * where the notebook is, as knitr, RStudio, and a session started there read it (not where flowR runs) */ + const present = (read: string, at: NodeId) => { + const file = ast.idMap.get(at)?.info.file; + return ctx.files.hasFile(read) || file !== undefined && ctx.files.hasFile(RPath.join(RPath.dirname(file), read)); + }; + const fileReads = new Map(deps.reads.flatMap(r => r.nodeId === undefined || typeof r.value !== 'string' ? [] : [[r.nodeId, !present(r.value, r.nodeId)] as const])); /* the search path entry each attach makes and each detach takes away, by its name */ const entries = new Map(); const detached = new Map(); /* what each cell does to the global state, through the functions it calls as well, where flowR knows it: a body does it where a call runs the function, as it is bound then */ let functions: ReadonlyMap | undefined; + /* the removals of the plot by closing the active device, by cell */ + const activeCloses: [number, (typeof raw)[number]['effects'][number]][] = []; for(const [c, scope] of scopes.entries()) { const into = (e: CellEffect, at: NodeId, inner?: NodeId) => raw[c].effects.push({ inner, ...placed(at, e) }); const stateOf = (name: string) => name.startsWith('file:') ? resource(CellResource.File, name.slice(5)) : resource(CellResource.State, name); @@ -1088,6 +1150,10 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df const apply = (ambient: AmbientAccess, call?: NodeId, of?: NodeId) => { const tag = of === undefined ? {} : { of }; for(const [state, ids] of ambient[AmbientAccessKind.Write]) { + /* options flowR cannot name (`options(op)`) may set `warn` back */ + if(state === AmbientStateName.unknownOption) { + ids.forEach(id => into({ removes: WarnsAsErrorsState, ...tag }, call ?? id, id)); + } const name = trackedState(String(state)); const entry = SearchPathEntry.exec(name ?? '')?.[1]; for(const id of name === undefined ? [] : ids) { @@ -1142,6 +1208,9 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df } if(does(AmbientVerb.Closes)) { into({ removes: PlotState, ...tag }, call ?? draw, draw); + if(closesActive) { + activeCloses.push([c, raw[c].effects[raw[c].effects.length - 1]]); + } } } }; @@ -1155,6 +1224,49 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df } } + /* a removal that may not happen (`if (cond) rm(x)`, in a loop or a branch) may leave what it removes, so it removes nothing for sure */ + const conditional = (id: NodeId | undefined) => id !== undefined && (graph.getVertex(id)?.cds?.length ?? 0) > 0; + for(const r of raw) { + r.effects = r.effects.filter(({ at, inner, effect: e }) => !('removes' in e || 'clears' in e || 'binds' in e && binds(e.binds, WarnsAsErrorsState)) || !conditional(at) && !conditional(inner)); + } + /* `options(warn = 2)` turns warnings into errors, any other setting of `warn` (or a restore, `options(op)`) may undo that */ + for(const r of raw) { + const sure = new Set(r.effects.filter(({ effect: e }) => 'binds' in e && binds(e.binds, WarnsAsErrorsState)).map(e => e.at)); + r.effects = r.effects.flatMap(e => 'binds' in e.effect && e.effect.binds.resource === CellResource.State && WarnLevelWrites.test(e.effect.binds.name) && !sure.has(e.at) + ? [e, { ...e, effect: { removes: WarnsAsErrorsState, ...e.effect.of === undefined ? {} : { of: e.effect.of }, range: e.effect.range, unit: e.effect.unit } }] : [e]); + } + /* a cell that surely warns fails once warnings are errors, unless it sets `warn` itself before */ + const warnInfo = { graph, idMap: ast.idMap, ctx, resolve: resolveInfo }; + for(const top of unitOf.keys()) { + const c = cellOf(top); + for(const site of c < 0 ? [] : CertainWarnings.sites(top, warnInfo)) { + if(!raw[c].effects.some(({ at, effect: e }) => 'binds' in e && e.binds.resource === CellResource.State && WarnLevelWrites.test(e.binds.name) && before(at, site) < 0)) { + raw[c].reads.push({ ...WarnsAsErrorsState, id: site, call: false, absent: true }); + } + } + } + /* whether R may skip the node: it is in a branch, the body of a loop that may not run once, or the right side of `&&` or `||` (a promise or a default aside, which the call decides) */ + const mayBeSkipped = (id: NodeId | undefined) => id !== undefined && (graph.getVertex(id)?.cds ?? []).some(cd => { + if(cd.byPromise) { + return false; + } + const node = ast.idMap.get(cd.id); + const around = [node, node === undefined ? undefined : RNode.directParent(node, ast.idMap)]; + if(around.some(n => RRepeatLoop.is(n))) { + return false; + } + const loop = around.find(RForLoop.is); + return loop === undefined || !runsOnce(loop.info.id); + }); + /* closing the active device (`dev.off()`) makes the device opened before it active again, with its plot, so where another cell opens a device (`pdf(NULL)`) the plot may stay */ + for(const [c, effect] of activeCloses) { + if(raw.some((r, j) => j !== c && r.effects.some(e => 'binds' in e.effect && e.effect.binds.resource === CellResource.State && e.effect.binds.name === DeviceState.name))) { + const at = raw[c].effects.indexOf(effect); + if(at >= 0) { + raw[c].effects.splice(at, 1); + } + } + } /* `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 */ const attaches = graph.verticesOfType(VertexType.FunctionCall).filter(([id, v]) => DfgVertex.hasOrigin(v, BuiltInProcName.Attach) && !bodies.has(id)).map(([id]) => id).toArray().sort(before); for(const [id] of graph.verticesOfType(VertexType.FunctionCall).filter(([id, v]) => DfgVertex.hasOrigin(v, BuiltInProcName.Detach) && !bodies.has(id))) { @@ -1201,11 +1313,19 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df const lacks = f.lacks as CellNeed[]; /* 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 */ const same = (a: CellRead, b: CellRead) => a.resource === b.resource && a.name === b.name && a.soft === b.soft && a.of === b.of && a.column === b.column && a.data === b.data; - const reads = raw[i].reads.filter(u => u.resource !== CellResource.Variable || u.call || !inData(u.id, u.name)); + /* a column the data mask of a package's function reads (`filter(mtcars, mpg > 20)` of dplyr) needs that package where R has a function of that name too (`stats::filter`), which evaluates it as is */ + /* a read that may not run (`if (cond) print(x)`, in a loop) need not be satisfied for the cell to run: R may skip it */ + const reads = raw[i].reads.map(u => u.soft !== true && (mayBeSkipped(u.id) || mayBeSkipped(u.inner)) ? { ...u, soft: true } as const : u).flatMap(u => { + if(u.resource !== CellResource.Variable || u.call || !inData(u.id, u.name)) { + return [u]; + } + const pkg = maskingPackage(u.id); + return pkg === undefined ? [] : [{ ...u, ...resource(CellResource.Package, pkg), or: [variable(u.name, SymbolKind.Any)] }]; + }); 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)))) { const symbol = { resource: use.resource, name: use.name, kind: use.kind }; const anyOf = [symbol, ...use.or ?? []]; - const where = { name: use.name, resource: use.resource, id: use.id, ...placeOf(use.id), ...use.range === undefined ? {} : { range: use.range }, ...use.of === undefined ? {} : { of: use.of } }; + const where = { name: use.name, resource: use.resource, id: use.id, ...placeOf(use.id), ...use.range === undefined ? {} : { range: use.range }, ...use.of === undefined ? {} : { of: use.of }, ...use.absent ? { absent: true } as const : {} }; /* 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 */ /* a call that sets state reads its arguments first (`options(digits = getOption("digits") - 1)`) */ const setBefore = (use.resource !== CellResource.Variable || use.deferred) && raw[i].effects.some(e => 'binds' in e.effect && anyOf.some(s => binds((e.effect as { binds: CellSymbol }).binds, s)) && (use.deferred ? before(e.at, use.id) < 0 : endsBefore(e.at, use.id) @@ -1309,7 +1429,8 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df const libProviders = facts.flatMap((o, j) => j !== i && (libs.some(l => provides(o, l)) || sourcing.includes(j)) ? [j] : []); if(libProviders.length > 0) { needs.push({ ...where, resource: CellResource.Package, anyOf: sourcing.length > 0 ? [...libs, symbol] : libs, providers: libProviders, ...use.soft ? { soft: true } : {} }); - } else if(lazy && !provides(f, symbol) && failsToRead(use.id, use.name)) { + } else if((lazy || unseen && use.soft !== true && use.deferred !== true && !masked(use.id)) && !provides(f, symbol) && failsToRead(use.id, use.name)) { + /* as does a call of a function no cell, package, or R defines (`g()`), where no cell attaches a package or sources code flowR does not see */ lacks.push({ ...where, anyOf: [symbol], providers: [] }); } else if(base === undefined && avoidable(use)) { needs.push({ ...where, anyOf: [symbol], providers: [] }); @@ -1319,6 +1440,9 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df if(f.cell.maybe) { needs.forEach((n, k) => needs[k] = optionReads.has(n.id) ? n : { ...n, soft: true }); } + /* what the cell fails with is no need of what other cells provide */ + (f as { forbids?: readonly CellNeed[] }).forbids = needs.filter(n => n.absent); + (f as { needs: readonly CellNeed[] }).needs = needs.filter(n => !n.absent); } /* 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 */ const isColumn = (n: CellNeed) => !made.has(n.id) && n.anyOf.length > 0 && n.anyOf.every(s => s.resource === CellResource.Column || s.resource === CellResource.ObjectState); @@ -1696,7 +1820,7 @@ function boundBefore(graph: DataflowGraph, def: NodeId, read: NodeId): boolean { const bindingOf = (session: Session, need: CellNeed) => need.anyOf.flatMap(want => lookups(want).flatMap(r => [ sessionKey({ resource: r, name: want.name }), ...want.resource === CellResource.Variable ? [sessionKey({ resource: r, name: AnyName })] : [] ]).filter(key => session.has(key) && matches(want.kind, session.get(key)?.kind ?? SymbolKind.Any)))[0]; -const satisfied = (session: Session, need: CellNeed) => bindingOf(session, need) !== undefined; +const satisfied = (session: Session, need: CellNeed) => (bindingOf(session, need) !== undefined) !== (need.absent === true); /** the function definitions a cell running in the session calls: those a need that counts is bound to, as the call of the name resolves to whatever it is bound to then */ function liveDefinitions(session: Session, needs: readonly CellNeed[]): ReadonlySet { const live = new Set(); @@ -1716,8 +1840,8 @@ const chunkOption = (session: Session, cell: NotebookCell, option: ChunkOption) /** whether knitting goes on after the knitted cell fails, as its options or a cell before say `error = TRUE` */ const continues = (session: Session, cell: NotebookCell) => cell.tolerant === true || chunkOption(session, cell, 'error'); /** 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 */ -function missingIn(session: Session, facts: CellFacts): CellNeed[] { - const missing = chunkOption(session, facts.cell, 'eval') ? [] : liveNeeds(session, facts.needs).filter(n => !satisfied(session, n)); +function missingIn(session: Session, facts: CellFacts, withLacks = false): CellNeed[] { + const missing = chunkOption(session, facts.cell, 'eval') ? [] : liveNeeds(session, [...facts.needs, ...facts.forbids ?? [], ...withLacks ? facts.lacks : []]).filter(n => !satisfied(session, n)); return continues(session, facts.cell) ? missing.map(n => ({ ...n, soft: true })) : missing; } @@ -1733,7 +1857,7 @@ function run(session: Session, facts: CellFacts, at = -1, by = new Map sessionKey(option)).filter(k => session.has(k)).map(k => [k, AnyValue])); - const needs = [...facts.needs, ...facts.lacks]; + const needs = [...facts.needs, ...facts.lacks, ...facts.forbids ?? []]; const live = counts(liveDefinitions(session, needs)); const failing = needs.filter(live).filter(n => !n.soft && n.range !== undefined && !satisfied(session, n)); const tolerant = continues(session, facts.cell); @@ -1789,13 +1913,15 @@ export function checkOrder(facts: readonly CellFacts[], order: readonly CellInde /** * Every order in which the cells run without missing anything, each running as many cells as it can, cells earlier in the * notebook first. An order that ends before all cells ran left the others unable to run (e.g., after an `rm`). + * With `withLacks`, a cell that lacks what no order provides (see {@link CellFacts#lacks}) does not run either, so that every order + * listed runs without an error; without, the orders are those that run as far as the order of the cells is concerned, as a reordering asks. */ -export function* workingOrders(facts: readonly CellFacts[]): Generator { +export function* workingOrders(facts: readonly CellFacts[], withLacks = false): Generator { const order: CellIndex[] = []; function* extend(session: Session): Generator { let extended = false; for(const [i, f] of facts.entries()) { - if(!order.includes(i) && missingIn(session, f).every(n => n.soft)) { + if(!order.includes(i) && missingIn(session, f, withLacks).every(n => n.soft)) { extended = true; const next = new Map(session); run(next, f); @@ -1973,7 +2099,7 @@ export function runStates(facts: readonly CellFacts[], runs: readonly CellIndex[ const by = new Map(); const replayed = runs.map((c, at) => { /* the session also lacks what only the cell itself binds, after it reads it */ - const needs = [...facts[c].needs, ...facts[c].lacks]; + const needs = [...facts[c].needs, ...facts[c].lacks, ...facts[c].forbids ?? []]; const missing = liveNeeds(session, needs).filter(n => !n.soft && !satisfied(session, n)); const used = new Map(facts[c].needs.map(n => [n, by.get(bindingOf(session, n) ?? '') ?? -1])); run(session, facts[c], at, by); @@ -2056,6 +2182,11 @@ export function describeRunStates(facts: readonly CellFacts[], states: readonly /** What a cell failing in an order lacks and which cells provide it, `undefined` if it only reads global state another cell sets. */ export function describeFailure(failure: OrderFailure, name: CellNamer = byNumber): string | undefined { + /* a warning that a cell before turned into an error */ + const errs = uniqueArray(failure.missing.filter(m => !m.soft && m.absent).flatMap(m => m.providers)); + if(errs.length > 0) { + return `${name(failure.cell)} warns, which ${listed(errs, name)} turned into an error with options(warn = 2)`; + } const hard = failure.missing.filter(m => !m.soft); const needs = uniqueArray(hard.map(describeNeed)); const from = uniqueArray(hard.flatMap(m => m.providers)); diff --git a/src/project/sigdb/schema.ts b/src/project/sigdb/schema.ts index eeb953ab278..7373d9d581e 100644 --- a/src/project/sigdb/schema.ts +++ b/src/project/sigdb/schema.ts @@ -101,7 +101,9 @@ export const enum FnProp { /** runs code concurrently: it reaches a call flowR knows does (`future::future`), or a native routine that forks or starts threads */ Concurrent = 1 << 15, /** computes a result and nothing else (flowR's `CallProp.Pure`): every call it makes does so, a native routine one only if {@link NativeFlag.Pure} */ - Pure = 1 << 16 + Pure = 1 << 16, + /** may signal a warning: it calls `warning`, or a function that may (like `as.numeric` or `log`, see `RWarnings`), which `options(warn = 2)` turns into an error */ + Warns = 1 << 17 } /** the {@link FnProp} bit to its name (for decoding); integer keys iterate in ascending bit order */ @@ -122,7 +124,8 @@ export const FnPropNames: Readonly> = { [FnProp.Value]: 'value', [FnProp.Generic]: 'generic', [FnProp.Concurrent]: 'concurrent', - [FnProp.Pure]: 'pure' + [FnProp.Pure]: 'pure', + [FnProp.Warns]: 'warns' }; /** diff --git a/src/queries/catalog/cell-order-query/cell-order-query-format.ts b/src/queries/catalog/cell-order-query/cell-order-query-format.ts index afc63c72193..dd9020f1b9b 100644 --- a/src/queries/catalog/cell-order-query/cell-order-query-format.ts +++ b/src/queries/catalog/cell-order-query/cell-order-query-format.ts @@ -4,6 +4,7 @@ import type { QueryResults, SupportedQuery } from '../../query'; import { queryHeader } from '../../query-print'; import { metaSince } from '../../query-meta'; import { CellGraph } from '../../../notebook/cell-graph'; +import { CellRunner } from '../../../project/plugins/file-plugins/files/cell-runner'; import { type CellSplit, cellsInCycle, splitForCycle } from '../../../notebook/cell-split'; import { affectedCells, analyzeNotebook, analyzeProject, type projectFiles, type CellRunState, describeFailure, describeHazard, describeLinks, describeRunStates, firstWorkingOrder, type OrderHazard, projectEntry, orderHazards, type RunStateText, runStates, type CellFacts, type CellIndex, checkOrder, describeNeed, type NotebookCell, type OrderFailure, workingOrders } from '../../../notebook/cell-order'; @@ -30,6 +31,12 @@ export interface CellOrderQuery extends BaseQueryFormat { readonly files?: boolean | 'every'; /** what to call the cells, to have the answer in words as well */ readonly names?: readonly string[]; + /** + * what runs the cells, which decides the state each cell starts afresh with (see `RunnerFreshState`): `knitr` (as knitting the document), + * `session` (one R session or console running cell after cell, keeping the plot and the working directory), or `jupyter`. + * By default the runner of the format: knitr for R Markdown, Quarto, and knitr Sweave, a session for `# %%` scripts, console transcripts, and Sweave. + */ + readonly runner?: `${CellRunner}`; } /** The answer in words, the cells called by the names of the query. */ @@ -80,9 +87,9 @@ export interface CellOrderQueryResult extends BaseQueryResult { async function executeCellOrderQuery({ analyzer }: BasicQueryData, queries: readonly CellOrderQuery[]): Promise { const start = Date.now(); const results = await Promise.all(queries.map(async(q): Promise => { - const facts = q.files ? await analyzeProject(analyzer, q.files === 'every') : await analyzeNotebook(analyzer, q.cells); + const facts = q.files ? await analyzeProject(analyzer, q.files === 'every') : await analyzeNotebook(analyzer, q.cells, q.runner as CellRunner | undefined); const order = q.order ?? facts.map((_, i) => i); - const orders = q.orders ? workingOrders(facts).take(q.orders + 1).toArray() : undefined; + const orders = q.orders ? workingOrders(facts, true).take(q.orders + 1).toArray() : undefined; const failures = checkOrder(facts, order); const hazards = orderHazards(facts); const states = q.session === undefined ? undefined : runStates(facts, q.session, new Set(q.edited)); @@ -97,7 +104,7 @@ async function executeCellOrderQuery({ analyzer }: BasicQueryData, queries: read hazards, orders: orders?.slice(0, q.orders), firstOrder: first, - count: workingOrders(facts).take(CountedOrders).filter(o => o.length === facts.length).toArray().length, + count: workingOrders(facts, true).take(CountedOrders).filter(o => o.length === facts.length).toArray().length, cycle: cycle.length === 0 ? undefined : { cells: cycle, split: q.files ? undefined : await splitForCycle(analyzer) }, entry: q.files ? projectEntry(analyzer) : undefined, more: orders === undefined ? undefined : orders.length > (q.orders ?? 0), @@ -142,6 +149,7 @@ export const CellOrderQueryDefinition = { cells: Joi.array().items(Joi.object({ from: Joi.number().required(), to: Joi.number().required(), head: Joi.number().optional(), tail: Joi.number().optional(), file: Joi.string().optional(), runner: Joi.string().optional(), sets: Joi.array().items(Joi.string()).optional() })).optional().description('The cells as line ranges, if not those of the analyzed notebook.'), graph: Joi.boolean().optional().description('Whether to return the cell graph: the dataflow graph of what the cells read of each other.'), files: Joi.alternatives(Joi.boolean(), Joi.valid('every')).optional().description('Whether the units are the files of the project (each notebook as one) rather than the cells of a notebook; every makes each file a unit, also those another file sources.'), - names: Joi.array().items(Joi.string()).optional().description('What to call the cells, to have the answer in words as well.') + names: Joi.array().items(Joi.string()).optional().description('What to call the cells, to have the answer in words as well.'), + runner: Joi.string().valid(...Object.values(CellRunner)).optional().description('What runs the cells: knitr (each chunk starts with a fresh plot and the directory of the document), a session (an R console keeping both across cells), or jupyter; the runner of the format by default.') }).description('Checks whether the cells of a notebook run in a given order, lists the orders they run in, and which cells a change affects.') } as const satisfies SupportedQuery<'cell-order'>; diff --git a/src/queries/catalog/signature-query/signature-query-executor.ts b/src/queries/catalog/signature-query/signature-query-executor.ts index 52583079697..bf1316f84c7 100644 --- a/src/queries/catalog/signature-query/signature-query-executor.ts +++ b/src/queries/catalog/signature-query/signature-query-executor.ts @@ -1,3 +1,4 @@ +import { RWarnings } from '../../../dataflow/environments/default-builtin-config/warnings'; import { satisfies as semverSatisfies, validRange } from 'semver'; import { Ambient } from '../../../dataflow/environments/ambient-effect'; import { FunctionSemantics } from '../../../dataflow/fn/function-semantics'; @@ -25,7 +26,7 @@ import { type BuiltInFnInfo, type FnSig, ArgProp } from '../../../dataflow/envir import { Identifier, PkgName, ReferenceType, type BrandedIdentifier, type BrandedNamespace } from '../../../dataflow/environments/identifier'; import { globOf, matchArgs, norm, parseSpec } from '../../../project/sigdb/spec-query'; import { RVersion } from '../../../util/r-version'; -import { baseRPackages, baseRExportOwner } from '../../../util/r-base-packages'; +import { baseRPackages, baseRExportOwner, isBaseRPackage } from '../../../util/r-base-packages'; import { Mermaid } from '../../../util/mermaid/mermaid'; import type { CommandCompletions } from '../../../cli/repl/completion'; import { Resolve } from '../../../dataflow/environments/resolve-helper'; @@ -173,7 +174,7 @@ function locationFields(pkg: BrandedNamespace, fn: DecodedFunction, version: str } /** the view of one {@link BuiltInFnInfo}: every declared parameter with what it is used for, and what comes back */ -function flowrViewOf(info: BuiltInFnInfo, sigParams: readonly BrandedIdentifier[]): SignatureFlowrView { +function flowrViewOf(info: BuiltInFnInfo, sigParams: readonly BrandedIdentifier[], name?: BrandedIdentifier): SignatureFlowrView { /* every declared parameter, even one flowR says nothing about, so the answer is the whole signature */ const args = (info.sig ?? []).map(([n, p]) => ({ name: n, roles: FunctionSemantics.call.argument.words(p) })); const params = args.map(a => a.name); @@ -187,7 +188,8 @@ function flowrViewOf(info: BuiltInFnInfo, sigParams: readonly BrandedIdentifier[ returns, parameters: params.length > 0 && !same ? params : undefined, ambient: ambient.length > 0 ? ambient : undefined, - muffles: info.muffles?.length ? info.muffles : undefined + muffles: info.muffles?.length ? info.muffles : undefined, + warns: name === undefined ? undefined : RWarnings[String(name)] }); } @@ -197,10 +199,10 @@ function flowrViewOf(info: BuiltInFnInfo, sigParams: readonly BrandedIdentifier[ */ function flowrView(env: REnvironmentInformation | undefined, pkg: BrandedNamespace, name: BrandedIdentifier, sigParams: readonly BrandedIdentifier[]): SignatureFlowrView | undefined { const info = env === undefined ? undefined : queryFnProps(Identifier.make(name, pkg), { environment: env }); - if(info === undefined || (info.props === undefined && info.sig === undefined && info.ambient === undefined && info.muffles === undefined)) { + if(info === undefined || (info.props === undefined && info.sig === undefined && info.ambient === undefined && info.muffles === undefined && RWarnings[String(name)] === undefined)) { return undefined; } - return flowrViewOf(info, sigParams); + return flowrViewOf(info, sigParams, isBaseRPackage(pkg) ? name : undefined); } /** diff --git a/src/queries/catalog/signature-query/signature-query-format.ts b/src/queries/catalog/signature-query/signature-query-format.ts index b6596ad87d3..ac76809f467 100644 --- a/src/queries/catalog/signature-query/signature-query-format.ts +++ b/src/queries/catalog/signature-query/signature-query-format.ts @@ -1,3 +1,4 @@ +import type { WarnsWhen } from '../../../dataflow/environments/default-builtin-config/warnings'; import type { BaseQueryFormat, BaseQueryResult } from '../../base-query-format'; import type { ArgProps } from '../../../dataflow/environments/built-in-props'; import { queryHeader } from '../../query-print'; @@ -136,6 +137,8 @@ export interface SignatureFlowrView { readonly ambient?: readonly string[]; /** the condition classes the call muffles while its code runs, like `message` for `suppressMessages` */ readonly muffles?: readonly string[]; + /** when a call surely warns, by the values of its arguments, see `RWarnings` */ + readonly warns?: readonly WarnsWhen[]; } /** one declared dependency of a package */ diff --git a/src/util/r-base-packages.ts b/src/util/r-base-packages.ts index b4141e05bd4..49b5efbe5cb 100644 --- a/src/util/r-base-packages.ts +++ b/src/util/r-base-packages.ts @@ -79,9 +79,15 @@ export function attachedBasePackages(rVersion?: string): readonly BrandedNamespa /** the base export to owning-package map, materialised once from the grouped store (never per lookup) */ let exportOwners: Map | undefined; -/** whether `name` is a base primitive or internal that the sigdb export lists do not carry */ +/** + * Syntax of R that flowR reads as a call of its own name although R exports no function of that name: the native pipe + * `x |> f()`, which the R parser turns into `f(x)`. R itself provides it, whatever is attached. + */ +const RSyntaxCalls: ReadonlySet = new Set(['|>'] as BrandedIdentifier[]); + +/** whether `name` is a base primitive or internal that the sigdb export lists do not carry, or syntax R reads as a call (`|>`) */ export function isBasePrimitive(name: BrandedIdentifier): boolean { - return (RBasePrimitives).has(name); + return RBasePrimitives.has(name) || RSyntaxCalls.has(name); } /** diff --git a/test/functionality/dataflow/environments/ambient-state.test.ts b/test/functionality/dataflow/environments/ambient-state.test.ts index 7981808daae..757239f1716 100644 --- a/test/functionality/dataflow/environments/ambient-state.test.ts +++ b/test/functionality/dataflow/environments/ambient-state.test.ts @@ -148,6 +148,13 @@ describe('Ambient state summaries', withTreeSitter(ts => { check('reading the console reads no file', 'a01 <- function() readLines()\na22 <- function() scan(file = "")', { a01: [], a22: [] }); }); + describe('warnings as errors', () => { + /* `warn` of 2 or more surely turns warnings into errors, a value flowR does not know only may */ + check('the level of warn', 'a01 <- function() options(warn = 2)\na22 <- function() options(warn = 1)\na03 <- function(w) options(warn = w)', { + a01: ['#option:warn', '#options', '#warn-error', '#warn-error:sure'], a22: ['#option:warn', '#options'], a03: ['#option:warn', '#options', '#warn-error'] + }); + }); + describe('aliases', () => { check('an alias keeps the names of its arguments', 'a01 <- function() { set <- Sys.setenv; set(TZ = "UTC") }\na22 <- function() { o <- options; o(digits = 4) }\na03 <- function() { o <- options; o("digits") }', { a01: ['#env', '#env:TZ'], a22: ['#option:digits', '#options'], a03: [] diff --git a/test/functionality/dataflow/environments/built-in-eval.test.ts b/test/functionality/dataflow/environments/built-in-eval.test.ts index 5f3558c4d6a..39f3e5e3214 100644 --- a/test/functionality/dataflow/environments/built-in-eval.test.ts +++ b/test/functionality/dataflow/environments/built-in-eval.test.ts @@ -5,7 +5,7 @@ import { BuiltInEvalHandlerMapper } from '../../../../src/dataflow/environments/ import { BuiltInEvalName } from '../../../../src/dataflow/environments/built-in-eval-name'; import { CallProp, InputProps } from '../../../../src/dataflow/environments/built-in-props'; import { ComparisonOps, LogicalOps } from '../../../../src/dataflow/eval/resolve/resolve-operators'; -import { NumericFns } from '../../../../src/dataflow/eval/resolve/resolve-numbers'; +import { NumericFns, RandomDraws } from '../../../../src/dataflow/eval/resolve/resolve-numbers'; import { StringFns } from '../../../../src/dataflow/eval/resolve/resolve-strings'; import { GetFns } from '../../../../src/dataflow/eval/resolve/resolve-get'; import { FieldOperators } from '../../../../src/dataflow/eval/resolve/resolve-field'; @@ -18,6 +18,7 @@ import { label } from '../../_helper/label'; */ const FoldedBy: Record = { [BuiltInEvalName.Numeric]: Object.keys(NumericFns), + [BuiltInEvalName.RandomDraw]: Object.keys(RandomDraws), [BuiltInEvalName.Comparison]: Object.keys(ComparisonOps), /* `!` is the unary case the handler covers besides the binary operators */ [BuiltInEvalName.Logical]: [...Object.keys(LogicalOps), '!'], @@ -45,7 +46,8 @@ describe('Built-in value folding', () => { }); test(label('a folded call is pure and names its argument as its handler expects', ['name-normal'], ['other']), () => { - for(const { name, info } of folded) { + /* a random draw folds to the range of what it can draw, not to one value */ + for(const { name, info } of folded.filter(f => f.handler !== BuiltInEvalName.RandomDraw)) { assert.isTrue(FunctionSemantics.call.props.hasAny(info, CallProp.Pure), `${name} is folded but does not claim to be pure`); assert.isTrue(!FunctionSemantics.call.props.hasAny(info, InputProps), `${name} is folded but brings in data of its own`); /* the handlers match arguments by the parameter names they declare, so the signature has to use the same ones */ diff --git a/test/functionality/dataflow/functions/certain-warnings.test.ts b/test/functionality/dataflow/functions/certain-warnings.test.ts new file mode 100644 index 00000000000..2cb4579285c --- /dev/null +++ b/test/functionality/dataflow/functions/certain-warnings.test.ts @@ -0,0 +1,92 @@ +import { assert, describe, test } from 'vitest'; +import { withTreeSitter } from '../../_helper/shell'; +import { analyze } from '../../_helper/analyzer'; +import { CertainWarnings } from '../../../../src/dataflow/fn/certain-warnings'; +import { Resolve } from '../../../../src/dataflow/environments/resolve-helper'; +import { notANumber, RWarnings, warnsFor } from '../../../../src/dataflow/environments/default-builtin-config/warnings'; + +/* + * Every expectation was checked with R 4.6 (`withCallingHandlers(expr, warning = ...)`): a top-level expression marked + * `W` warns whenever it runs. One marked `-` may or may not warn; what matters is that it is never reported as sure. + */ +describe('Calls that surely warn', withTreeSitter(parser => { + /** whether each top-level expression of the code surely warns, `W` if so and `-` otherwise */ + async function marks(code: string): Promise { + const analyzer = await analyze(parser, code); + const ast = await analyzer.normalize(); + const { graph } = await analyzer.dataflow(); + const info = { graph, idMap: ast.idMap, ctx: analyzer.inspectContext(), resolve: Resolve.info(graph, analyzer.inspectContext()) }; + return ast.ast.files[0].root.children.map(e => CertainWarnings.sites(e.info.id, info).length > 0 ? 'W' : '-').join(''); + } + const cases: readonly (readonly [string, string])[] = [ + ['as.numeric("a")', 'W'], + ['x <- as.numeric("a")', 'W'], + ['as.numeric("1")', '-'], + ['as.numeric("")', '-'], + ['as.integer(3e9)', 'W'], + ['as.integer("2.7")', '-'], + ['log(-1)', 'W'], + ['log(0)', '-'], + ['sqrt(c(1, -1))', 'W'], + ['acos(2)', 'W'], + ['gamma(0)', 'W'], + ['factorial(0)', '-'], + ['mean("a")', 'W'], + ['max()', 'W'], + ['max(1, 2)', '-'], + ['warning("w")', 'W'], + ['print(log(-1))', 'W'], + ['invisible(as.numeric("a"))', 'W'], + ['v <- "a"; as.numeric(v)', '-W'], + ['x <- c(1, -1); sqrt(x)', '-W'], + /* handlers and constructs that catch or muffle the warning */ + ['suppressWarnings(as.numeric("a"))', '-'], + ['tryCatch(as.numeric("a"), warning = function(w) 1)', '-'], + ['try(log(-1))', '-'], + ['withCallingHandlers(log(-1), warning = function(w) invokeRestart("muffleWarning"))', '-'], + /* code that may not run */ + ['if (u) sqrt(-1)', '-'], + ['for (i in seq_len(n)) log(-1)', '-'], + ['quote(log(-1))', '-'], + ['f <- function() log(-1)', '-'], + ['f <- function(x) 1; f(as.numeric("a"))', '--'], + ['sapply(1, function(i) log(-1))', '-'], + /* functions of the program */ + ['f <- function() as.numeric("a"); f()', '-W'], + ['g <- function() warning("x"); h <- function() g(); h()', '--W'], + ['f <- function() { return(1); warning("x") }; f()', '--'], + ['f <- function(v) if (v) warning("x"); f(TRUE)', '--'], + ['log <- function(x) 1; log(-1)', '--'] + ]; + for(const [code, expected] of cases) { + test(`${code}: ${expected}`, async() => { + assert.strictEqual(await marks(code), expected); + }); + } +})); + +describe('The warnings R gives for the values of arguments', () => { + /* checked with R 4.6: `as.numeric(s)` warns for the strings marked true */ + const coercions: readonly (readonly [string, boolean])[] = [ + ['a', true], ['', false], [' 3 ', false], ['1e5', false], ['0x1A', false], ['Inf', false], ['inf', false], ['Infinity', false], + ['-inf', false], ['nan', false], ['NaN', false], ['1.5e-3', false], ['0x1p3', false], ['1L', true], ['1,5', true], ['TRUE', true], + ['1d5', true], ['.', true], ['+', true], ['1e', true], ['1p3', true], ['1_000', true], [' ', false] + ]; + for(const [str, warns] of coercions) { + test(`as.numeric(${JSON.stringify(str)}) ${warns ? 'warns' : 'is not sure to warn'}`, () => { + assert.strictEqual(notANumber(str), warns); + }); + } + test('the bounds of the functions with poles and domains', () => { + assert.isTrue(warnsFor(RWarnings['log'][0], -1)); + assert.isFalse(warnsFor(RWarnings['log'][0], 0)); + assert.isTrue(warnsFor(RWarnings['log1p'][0], -2)); + assert.isFalse(warnsFor(RWarnings['log1p'][0], -1)); + assert.isTrue(warnsFor(RWarnings['gamma'][0], 0)); + assert.isFalse(warnsFor(RWarnings['gamma'][0], -0.5)); + assert.isTrue(warnsFor(RWarnings['factorial'][0], -1)); + assert.isFalse(warnsFor(RWarnings['factorial'][0], 0)); + assert.isFalse(warnsFor(RWarnings['sqrt'][0], Number.NaN)); + assert.isFalse(warnsFor(RWarnings['mean'][0], 1)); + }); +}); diff --git a/test/functionality/linter/lint-dead-code.test.ts b/test/functionality/linter/lint-dead-code.test.ts index 6a7d8e72406..9b8efb4e235 100644 --- a/test/functionality/linter/lint-dead-code.test.ts +++ b/test/functionality/linter/lint-dead-code.test.ts @@ -61,7 +61,7 @@ print(2) ]); assertLinter('a stop in an argument forced within tryCatch stops nothing', parser, 'f <- function(x) tryCatch(x, error = function(e) 1)\nf(stop("a"))\nprint(2)', 'dead-code', []); assertLinter('a stop in an argument forced within try stops nothing', parser, 'f <- function(x) { r <- try(x, silent = TRUE); class(r) }\nf(stop("a"))\nprint(2)', 'dead-code', []); - assertLinter('a while condition on an outer variable the body redefines locally is not constant', parser, 'k <- 0\ng <- function() {\n while(k < 2) {\n k <- k + 1\n if(runif(1) > 2) return(1)\n }\n cat("live")\n}\ng()', 'dead-code', []); + assertLinter('a while condition on an outer variable the body redefines locally is not constant', parser, 'k <- 0\ng <- function() {\n while(k < 2) {\n k <- k + 1\n if(runif(1) > 0.5) return(1)\n }\n cat("live")\n}\ng()', 'dead-code', []); assertLinter('try complex', parser, 'f <- function() { try(stop(1)); 2 }; f(); stop(1); 2', 'dead-code', [ { certainty: LintingResultCertainty.Certain, loc: [1, 52, 1, 52], quickFix: [{ type: 'remove', loc: [1, 52, 1, 52], description: 'Remove the unreachable code' }] } ]); @@ -219,7 +219,7 @@ print(2) assertLinter('a read forces the write', parser, 'x <- FALSE\ndelayedAssign("y", x <- TRUE)\ny\nif (x) cat("live") else cat("dead")', 'dead-code', [ { certainty: LintingResultCertainty.Certain, loc: [4, 25, 4, 35], quickFix: [emptied([4, 25, 4, 35])] } ]); - assertLinter('a read that may not happen', parser, 'x <- FALSE\ndelayedAssign("y", x <- TRUE)\nif(runif(1) > 2) y\nif (x) cat("a") else cat("b")', 'dead-code', []); + assertLinter('a read that may not happen', parser, 'x <- FALSE\ndelayedAssign("y", x <- TRUE)\nif(runif(1) > 0.5) y\nif (x) cat("a") else cat("b")', 'dead-code', []); assertLinter('without a read nothing is written', parser, 'x <- FALSE\ndelayedAssign("y", x <- TRUE)\nif (x) cat("dead") else cat("live")', 'dead-code', [ { certainty: LintingResultCertainty.Certain, loc: [3, 8, 3, 18], quickFix: [emptied([3, 8, 3, 18])] } ]); @@ -229,7 +229,7 @@ print(2) assertLinter('a forced return', parser, 'f <- function() {\n delayedAssign("p", return(1))\n p\n cat("dead")\n}\nf()', 'dead-code', [ { certainty: LintingResultCertainty.Certain, loc: [4, 3, 4, 13], quickFix: [{ type: 'remove', loc: [4, 3, 4, 13], description: 'Remove the unreachable code' }] } ]); - assertLinter('a raise that is never forced', parser, 'f <- function() {\n delayedAssign("p", stop("boom"))\n if(runif(1) > 2) p\n cat("live")\n}\nf()', 'dead-code', []); + assertLinter('a raise that is never forced', parser, 'f <- function() {\n delayedAssign("p", stop("boom"))\n if(runif(1) > 0.5) p\n cat("live")\n}\nf()', 'dead-code', []); }); describe('reflective name arguments', () => { diff --git a/test/functionality/linter/lint-seeded-randomness.test.ts b/test/functionality/linter/lint-seeded-randomness.test.ts index db23d781aca..a99d3b34240 100644 --- a/test/functionality/linter/lint-seeded-randomness.test.ts +++ b/test/functionality/linter/lint-seeded-randomness.test.ts @@ -118,7 +118,7 @@ describe('flowR linter', withTreeSitter(parser => { assertLinter('a seed in a closure handed to a user function', parser, 'g <- function(f) f()\ng(function() set.seed(1))\nrunif(1)', 'seeded-randomness', []); assertLinter('a seed in a closure handed down twice', parser, 'g <- function(f) f()\nk <- function(f) g(f)\nk(function() set.seed(1))\nrunif(1)', 'seeded-randomness', []); /* the closure is only called on some paths, so the draw may see the initial state */ - assertLinter('a seed in a closure the receiver may not call', parser, 'g <- function(f) if(runif(1) > 2) f()\ng(function() set.seed(1))\nrnorm(1)', 'seeded-randomness', [ + assertLinter('a seed in a closure the receiver may not call', parser, 'g <- function(f) if(runif(1) > 0.5) f()\ng(function() set.seed(1))\nrnorm(1)', 'seeded-randomness', [ { loc: [1, 21, 1, 28], function: 'runif', certainty: LintingResultCertainty.Uncertain }, { loc: [3, 1, 3, 8], function: 'rnorm', certainty: LintingResultCertainty.Uncertain } ]); diff --git a/test/functionality/notebook/cell-order-audit.test.ts b/test/functionality/notebook/cell-order-audit.test.ts new file mode 100644 index 00000000000..1345a834c3b --- /dev/null +++ b/test/functionality/notebook/cell-order-audit.test.ts @@ -0,0 +1,265 @@ +import { assert, describe, test } from 'vitest'; +import { withTreeSitter } from '../_helper/shell'; +import { analyze } from '../_helper/analyzer'; +import { FlowrInlineTextFile } from '../../../src/project/context/flowr-file'; +import { analyzeNotebook, workingOrders } from '../../../src/notebook/cell-order'; +import { expFn, fakeSigDb } from '../_helper/sigdb'; +import { CellRunner } from '../../../src/project/plugins/file-plugins/files/cell-runner'; + +/* + * Small R Markdown notebooks of 2 to 4 cells and a larger example, each with the orders of its cells that run in R + * (as the cell indices of flowR, which skip `eval = FALSE` chunks) and the dead ends, the orders that run as far as + * they can but not to the last cell. The orders were found by running every permutation in a fresh `Rscript --vanilla` + * (R 4.6, knitr 1.51), once per setting: + * - console: all cells in one global environment, with one graphics device and working directory, stopping at the first error; + * - knit: `knitr::knit` of the document with the chunks in that order and `error = FALSE`, stopping at the first error. + * flowR must never miss an order or a dead end that runs in R; where it promises more, the case says why (`imprecise`). + * The names say what a case is about: `w` cases turn warnings into errors, `c` cases define or remove under conditions. + */ +interface Truth { + readonly orders: readonly (readonly number[])[] + readonly deadEnds: readonly (readonly number[])[] + /** why flowR promises orders that fail in R */ + readonly imprecise?: string +} +interface AuditCase { + readonly name: string + readonly files: Readonly> + readonly console: Truth + readonly knit: Truth +} + +const AuditCases: readonly AuditCase[] = [ + { name: '01-defuse', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- y * 2\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2]], deadEnds: [] } }, + { name: '02-redef', files: { 'nb.Rmd': '```{r}\nd <- 1:10\n```\n\ntext\n\n```{r}\nd <- d[d > 3]\n```\n\ntext\n\n```{r}\nm <- mean(d)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [] } }, + { name: '03-library', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '04-library-ggplot', files: { 'nb.Rmd': '```{r}\nlibrary(ggplot2)\n```\n\ntext\n\n```{r}\np <- ggplot(mtcars, aes(mpg, wt)) + geom_point()\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '05-rm', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- x\n```\n\ntext\n\n```{r}\nrm(x)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [2, 0, 1]], deadEnds: [[0, 2]] }, + knit: { orders: [[0, 1, 2], [2, 0, 1]], deadEnds: [[0, 2]] } }, + { name: '06-rmall', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nrm(list = ls())\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3]], deadEnds: [] }, + knit: { orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3]], deadEnds: [] } }, + { name: '07-plot', files: { 'nb.Rmd': '```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\nabline(h = 1)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, + { name: '08-evalfalse', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\n```{r, eval = FALSE}\nrm(x)\n```\n\n```{r}\ny <- x\n```\n' }, + console: { orders: [[0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1]], deadEnds: [] } }, + { name: '09-options', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nx <- as.integer("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, + { name: '10-setenv', files: { 'nb.Rmd': '```{r}\nSys.setenv(INPUT = "in.csv")\n```\n\ntext\n\n```{r}\nd <- read.csv(Sys.getenv("INPUT"))\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n', 'in.csv': 'a,b\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside, so the need is soft' }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside, so the need is soft' } }, + { name: '11-setwd', files: { 'nb.Rmd': '```{r}\nsetwd("sub")\n```\n\ntext\n\n```{r}\nd <- read.csv("in.csv")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n', 'sub/in.csv': 'a,b\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: 'knitr resets the directory, so in.csv is read from the directory of the document, which lacks it; flowR does not check the file system' } }, + { name: '12-files', files: { 'nb.Rmd': '```{r}\nwrite.csv(data.frame(a = 1), "out.csv")\n```\n\ntext\n\n```{r}\nd <- read.csv("out.csv")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '13-random', files: { 'nb.Rmd': '```{r}\nset.seed(1)\n```\n\ntext\n\n```{r}\nx <- sample(10, 1)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: '14-columns', files: { 'nb.Rmd': '```{r}\nd <- data.frame(a = 1:3)\n```\n\ntext\n\n```{r}\nd$b <- d$a * 2\n```\n\ntext\n\n```{r}\nv <- d[, "b"]\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2]], deadEnds: [] } }, + { name: '15-closure', files: { 'nb.Rmd': '```{r}\nf <- function() x + 1\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- f()\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] } }, + { name: '16-superassign', files: { 'nb.Rmd': '```{r}\ng <- function() x <<- 1\n```\n\ntext\n\n```{r}\ng()\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2]], deadEnds: [] } }, + { name: '17-superassign-top', files: { 'nb.Rmd': '```{r}\nx <<- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '18-assign', files: { 'nb.Rmd': '```{r}\nassign("x", 1)\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '19-source', files: { 'nb.Rmd': '```{r}\nsource("helpers.R")\n```\n\ntext\n\n```{r}\ny <- helper(1)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n', 'helpers.R': 'helper <- function(v) v + 1\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '20-attach', files: { 'nb.Rmd': '```{r}\nd <- data.frame(a = 1:3)\n```\n\ntext\n\n```{r}\nattach(d)\n```\n\ntext\n\n```{r}\nv <- a + 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2]], deadEnds: [] } }, + { name: '21-rmsetdiff', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- 2\n```\n\ntext\n\n```{r}\nrm(list = setdiff(ls(), "x"))\n```\n\ntext\n\n```{r}\nz <- y\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 3, 2], [0, 2, 1, 3], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [1, 0, 2], [1, 2, 0]] }, + knit: { orders: [[0, 1, 3, 2], [0, 2, 1, 3], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [1, 0, 2], [1, 2, 0]] } }, + { name: '22-conddef', files: { 'nb.Rmd': '```{r}\nif (FALSE) x <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, + { name: '23-exists', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (!exists("x")) stop("no x")\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '24-rm-plot', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\nrm(list = ls())\n```\n\ntext\n\n```{r}\nabline(h = fractions(0.5))\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [2, 0, 1, 3], [2, 1, 0, 3]], deadEnds: [] }, + knit: { orders: [], deadEnds: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] } }, + { name: '25-funcdef-uses-lib', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nh <- function(v) fractions(v)\n```\n\ntext\n\n```{r}\ny <- h(0.5)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] } }, + { name: '26-dev-off', files: { 'nb.Rmd': '```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\ndev.off()\n```\n\ntext\n\n```{r}\nabline(h = 1)\n```\n\ntext\n\n' }, + console: { orders: [[0, 2, 1]], deadEnds: [[0, 1]] }, + knit: { orders: [], deadEnds: [[0, 1], [1, 0]] } }, + { name: '27-require', files: { 'nb.Rmd': '```{r}\nrequire(MASS)\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '28-pipe-lib', files: { 'nb.Rmd': '```{r}\nlibrary(dplyr)\n```\n\ntext\n\n```{r}\nd <- mtcars |> filter(mpg > 20)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '29-local-shadow', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nf <- function(x) x + 1\n```\n\ntext\n\n```{r}\ny <- f(2)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, + { name: '30-loop-def', files: { 'nb.Rmd': '```{r}\nfor (i in 1:3) x <- i\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '31-conddef-rt', files: { 'nb.Rmd': '```{r}\nset.seed(1)\nif (runif(1) > 2) x <- 1\n```\n\n```{r}\ny <- x + 1\n```\n\n```{r}\nz <- 1\n```\n' }, + console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, + { name: 'c01-cond-runif-never', files: { 'nb.Rmd': '```{r}\nif (runif(1) > 2) x <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, + { name: 'c02-cond-runif-always', files: { 'nb.Rmd': '```{r}\nif (runif(1) < 2) x <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: 'c03-cond-rm-never', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (runif(1) > 2) rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'c04-cond-rm-unknown', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (Sys.getenv("NOPE") == "yes") rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'c05-cond-empty-loop', files: { 'nb.Rmd': '```{r}\nfor (i in seq_len(0)) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: 'the loop over seq_len(0) never runs, so x is never defined; flowR does not know the loop runs no round' }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: 'the loop over seq_len(0) never runs, so x is never defined; flowR does not know the loop runs no round' } }, + { name: 'c06-cond-while-false-rm', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nwhile (FALSE) rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'c07-cond-rbinom-never', files: { 'nb.Rmd': '```{r}\nif (rbinom(1, 1, 0.5) == 2) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, + console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, + { name: 'c08-cond-both-branches', files: { 'nb.Rmd': '```{r}\nif (exists("y")) x <- 1 else x <- 2\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: 'c09-cond-detach-never', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nif (runif(1) > 5) detach("package:MASS")\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'c10-cond-dev-off-never', files: { 'nb.Rmd': '```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\nif (runif(1) > 2) dev.off()\n```\n\ntext\n\n```{r}\nabline(h = 1)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [], deadEnds: [[0, 1], [1, 0]] } }, + { name: 'c11-cond-rm-true', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (TRUE) rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, + console: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [[0, 1]] }, + knit: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [[0, 1]] } }, + { name: 'c12-cond-superassign', files: { 'nb.Rmd': '```{r}\nf <- function() if (runif(1) > 2) x <<- 1\n```\n\ntext\n\n```{r}\nf()\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, + console: { orders: [], deadEnds: [[0, 1]] }, + knit: { orders: [], deadEnds: [[0, 1]] } }, + { name: 'c13-cond-rmall-unknown', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (nchar(Sys.getenv("NOPE")) > 0) rm(list = ls())\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'c14-cond-runif-scaled', files: { 'nb.Rmd': '```{r}\nu <- runif(1, 5, 10)\n```\n\ntext\n\n```{r}\nif (u < 4) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, + console: { orders: [], deadEnds: [[0, 1]], imprecise: 'u is a draw of another cell, which flowR does not follow into the condition while it analyzes' }, + knit: { orders: [], deadEnds: [[0, 1]], imprecise: 'u is a draw of another cell, which flowR does not follow into the condition while it analyzes' } }, + { name: 'running-example', files: { 'nb.Rmd': '```{r setup}\nlibrary(ggplot2)\ntheme_set(theme_minimal())\n```\n\nLoad the survey.\n\n```{r load}\ndata <- read.csv("survey.csv")\ndata <- na.omit(data)\n```\n\n```{r analysis}\nmodel <- lm(score ~ age, data = data)\nsummary(model)\nggplot(data, aes(age, score)) +\n geom_point() + geom_smooth(method = "lm")\n```\n\n```{r filter}\n# drop participants under 18 (written last)\ndata <- subset(data, age >= 18)\nnrow(data)\n```\n\n```{r cleanup}\nrm(data)\ngc()\n```\n', 'survey.csv': '"age","score"\n18,54\n25,44\n52,62\n49,59\n53,NA\n56,75\n44,63\n21,47\n33,67\n23,64\n68,76\n53,72\n61,65\n53,72\n21,67\n50,65\n15,NA\n42,69\n57,73\n58,65\n18,69\n53,60\n50,68\n22,38\n22,55\n69,80\n67,66\n31,52\n29,65\n38,55\n25,60\n53,52\n35,49\n64,66\n19,47\n53,77\n28,66\n23,51\n24,62\n42,70\n' }, + console: { orders: [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 4, 1, 2, 3], [0, 4, 1, 3, 2], [1, 0, 2, 3, 4], [1, 0, 3, 2, 4], [1, 3, 0, 2, 4], [4, 0, 1, 2, 3], [4, 0, 1, 3, 2], [4, 1, 0, 2, 3], [4, 1, 0, 3, 2], [4, 1, 3, 0, 2]], deadEnds: [[0, 1, 2, 4], [0, 1, 3, 4], [0, 1, 4], [1, 0, 2, 4], [1, 0, 3, 4], [1, 0, 4], [1, 3, 0, 4], [1, 3, 4, 0], [1, 4, 0]] }, + knit: { orders: [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 4, 1, 2, 3], [0, 4, 1, 3, 2], [1, 0, 2, 3, 4], [1, 0, 3, 2, 4], [1, 3, 0, 2, 4], [4, 0, 1, 2, 3], [4, 0, 1, 3, 2], [4, 1, 0, 2, 3], [4, 1, 0, 3, 2], [4, 1, 3, 0, 2]], deadEnds: [[0, 1, 2, 4], [0, 1, 3, 4], [0, 1, 4], [1, 0, 2, 4], [1, 0, 3, 4], [1, 0, 4], [1, 3, 0, 4], [1, 3, 4, 0], [1, 4, 0]] } }, + { name: 'w01-warn-coerce', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nx <- as.numeric("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, + { name: 'w02-warn-suppressed', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nx <- suppressWarnings(as.numeric("a"))\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w03-warn-restore', files: { 'nb.Rmd': '```{r}\nop <- options(warn = 2)\n```\n\ntext\n\n```{r}\nz <- log(-1)\n```\n\ntext\n\n```{r}\noptions(op)\n```\n\ntext\n\n' }, + console: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'w04-warn-in-function', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nf <- function() as.numeric("a")\n```\n\ntext\n\n```{r}\nf()\n```\n\ntext\n\n' }, + console: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] }, + knit: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] } }, + { name: 'w05-warn-trycatch', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nr <- tryCatch(warning("w"), warning = function(w) 1)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w06-warn-calling-handler', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nwithCallingHandlers(sqrt(-1), warning = function(w) invokeRestart("muffleWarning"))\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w07-warn-reset', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\noptions(warn = 0)\n```\n\ntext\n\n```{r}\nwarning("x")\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] }, + knit: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] } }, + { name: 'w08-warn-try', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nr <- try(log(-1), silent = TRUE)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w09-warn-level-one', files: { 'nb.Rmd': '```{r}\noptions(warn = 1)\n```\n\ntext\n\n```{r}\ni <- as.integer("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w10-warn-conditional-set', files: { 'nb.Rmd': '```{r}\nif (Sys.getenv("NOPE") == "yes") options(warn = 2)\n```\n\ntext\n\n```{r}\nx <- as.numeric("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w11-warn-variable', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nv <- "a"\n```\n\ntext\n\n```{r}\nn <- as.numeric(v)\n```\n\ntext\n\n' }, + console: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] }, + knit: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] } }, + { name: 'w12-warn-mean-max', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nm <- mean("a")\n```\n\ntext\n\n```{r}\nk <- max()\n```\n\ntext\n\n' }, + console: { orders: [[1, 2, 0], [2, 1, 0]], deadEnds: [[0], [1, 0], [2, 0]] }, + knit: { orders: [[1, 2, 0], [2, 1, 0]], deadEnds: [[0], [1, 0], [2, 0]] } }, + { name: 'w13-warn-nested-functions', files: { 'nb.Rmd': '```{r}\ng <- function() warning("w")\n```\n\ntext\n\n```{r}\nh <- function() g()\n```\n\ntext\n\n```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nh()\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 3, 2], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] }, + knit: { orders: [[0, 1, 3, 2], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] } }, + { name: 'w14-warn-none', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\na <- as.numeric("1")\n```\n\ntext\n\n```{r}\nb <- sqrt(4)\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w15-warn-unforced-promise', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nf <- function(x) 1\n```\n\ntext\n\n```{r}\nf(as.numeric("a"))\n```\n\ntext\n\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, + { name: 'w16-warn-same-cell', files: { 'nb.Rmd': '```{r}\noptions(warn = 2); x <- 1\n```\n\ntext\n\n```{r}\ny <- log(-1)\n```\n\ntext\n\n```{r}\nz <- 2\n```\n\ntext\n\n' }, + console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, + { name: 'w17-warn-in-function-set', files: { 'nb.Rmd': '```{r}\nstrict <- function() options(warn = 2)\n```\n\ntext\n\n```{r}\nstrict()\n```\n\ntext\n\n```{r}\nx <- as.numeric("b")\n```\n\ntext\n\n' }, + console: { orders: [[0, 2, 1], [2, 0, 1]], deadEnds: [[0, 1]] }, + knit: { orders: [[0, 2, 1], [2, 0, 1]], deadEnds: [[0, 1]] } }, + { name: 'w18-warn-gamma', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\ng <- gamma(0)\n```\n\ntext\n\n```{r}\nf <- factorial(0)\n```\n\ntext\n\n' }, + console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } } +]; + +const key = (orders: readonly (readonly number[])[]) => orders.map(o => o.join(',')).sort(); +/* the functions the notebooks call from packages, as the signature database of flowR knows them */ +const SigDb = fakeSigDb({ + MASS: [expFn('fractions')], + dplyr: [expFn('filter')], + ggplot2: ['ggplot', 'aes', 'geom_point', 'geom_smooth', 'theme_set', 'theme_minimal'].map(f => expFn(f)) +}); +const Modes = { console: CellRunner.Session, knit: CellRunner.Knitr } as const; + +describe('Notebook cell orders of the audit notebooks against R', withTreeSitter(parser => { + for(const c of AuditCases) { + describe(c.name, () => { + for(const [mode, runner] of Object.entries(Modes) as [keyof typeof Modes, CellRunner][]) { + const truth = c[mode]; + const flowr = async(r: CellRunner = runner) => { + const analyzer = await analyze(parser, { request: 'file', content: 'nb.Rmd' }, { files: Object.entries(c.files).map(([f, t]) => new FlowrInlineTextFile(f, t)), sigDb: SigDb }); + const facts = await analyzeNotebook(analyzer, undefined, r); + const all = workingOrders(facts, true).toArray(); + return { orders: all.filter(o => o.length === facts.length), deadEnds: all.filter(o => o.length < facts.length) }; + }; + test(`${mode}: no order or dead end that runs in R is missing`, async() => { + const { orders, deadEnds } = await flowr(); + const runs = [...orders, ...deadEnds]; + for(const o of truth.orders) { + assert.includeDeepMembers(key(orders), key([o]), `R runs ${o.join(',')}`); + } + for(const d of truth.deadEnds) { + assert.isTrue(runs.some(o => d.every((x, k) => o[k] === x)), `R runs ${d.join(',')} before it gets stuck`); + } + }); + (truth.imprecise === undefined ? test : test.fails)(`${mode}: the orders and dead ends are those of R${truth.imprecise === undefined ? '' : ` (imprecise: ${truth.imprecise})`}`, async() => { + const { orders, deadEnds } = await flowr(); + assert.deepStrictEqual(key(orders), key(truth.orders)); + assert.deepStrictEqual(key(deadEnds), key(truth.deadEnds)); + }); + } + }); + } +})); diff --git a/test/functionality/notebook/cell-order.test.ts b/test/functionality/notebook/cell-order.test.ts index 0fcbf130a4c..195c2d6c9f0 100644 --- a/test/functionality/notebook/cell-order.test.ts +++ b/test/functionality/notebook/cell-order.test.ts @@ -7,6 +7,7 @@ import { CellGraph } from '../../../src/notebook/cell-graph'; import { DfEdge, EdgeType } from '../../../src/dataflow/graph/edge'; import { affectedCells, analyzeNotebook, CellResource, describeFailure, describeLinks, HazardKind, orderHazards, reorderCells, runStates, checkOrder, workingOrders } from '../../../src/notebook/cell-order'; import type { KnownParser } from '../../../src/r-bridge/parser'; +import { CellRunner } from '../../../src/project/plugins/file-plugins/files/cell-runner'; import { expFn, fakeSigDb } from '../_helper/sigdb'; import type { SigDbSource } from '../../../src/project/plugins/package-version-plugins/flowr-analyzer-package-versions-sigdb-plugin'; @@ -87,7 +88,8 @@ describe('Notebook cell orders', withTreeSitter(parser => { describe('checked against R', () => { orders('a for loop binds its variable', ['for (i in 1:3) NULL', 'print(i)'], [[0, 1]], undefined, 'script'); orders('a call may return a function', ['mk <- function() function() 1', 'g <- mk()', 'g()'], [[0, 1, 2]], undefined, 'script'); - orders('a call of unknown result may give a function', ['g <- unknown()', 'g()'], [[0, 1]], undefined, 'script'); + /* `unknown` may come from the package flowR does not know; without any package, the call fails in every order (see below) */ + orders('a call of unknown result may give a function', ['library(unknownpkg)\ng <- unknown()', 'g()'], [[0, 1]], undefined, 'script'); orders('attach binds the names of a list', ['attach(list(bb = 2))', 'print(bb)'], [[0, 1]], undefined, 'script'); orders('a pipe operator needs its package', ['library(magrittr)', 'x <- 1:3 %>% sum'], [[0, 1]], undefined, 'script'); orders('assign into another environment binds no global', ['e <- new.env()', 'assign("av", 1, envir = e)', 'print(av)', 'av <- 0'], [[0, 1, 3, 2], [0, 3, 1, 2], [0, 3, 2, 1], [3, 0, 1, 2], [3, 0, 2, 1], [3, 2, 0, 1]], undefined, 'script'); @@ -797,4 +799,147 @@ describe('Notebook cell orders', withTreeSitter(parser => { fails('a function Reduce is given', ['f <- function(x, y) x + y + a', 'f <- function(x, y) x + y + b', 'a <- 1', 'Reduce(f, 1:3)'], [[[0, 1, 2, 3], [3]], [[1, 0, 2, 3], []]]); fails('functions calling one another', ['f <- function(n) if (n > 0) g(n - 1) else 0', 'g <- function(n) f(n) + a', 'a <- 1', 'f(2)'], [[[0, 1, 3], [3]], [[0, 1, 2, 3], []]]); }); + describe('the runner of the cells', () => { + /* checked in R (cases 07-plot, 11-setwd, and 26-dev-off of the notebooks in cell-order-audit.test.ts): knitr gives each chunk a new plot and the directory of the document, a console keeps both */ + const runs = async(cells: readonly string[], runner?: CellRunner) => { + const analyzer = await analyze(parser, { request: 'file', content: 'nb.Rmd' }, { files: [new FlowrInlineTextFile('nb.Rmd', rmd(cells))] }); + return key(workingOrders(await analyzeNotebook(analyzer, undefined, runner), true).toArray()); + }; + const plot = ['plot(1:10)', 'abline(h = 1)', 'x <- 1']; + test('knitting a document draws on no plot of a chunk before', async() => { + assert.deepStrictEqual(await runs(plot), key([[0, 2], [2, 0]])); + assert.deepStrictEqual(await runs(plot, CellRunner.Knitr), key([[0, 2], [2, 0]])); + }); + test('a session keeps the plot for the cells after', async() => { + assert.deepStrictEqual(await runs(plot, CellRunner.Session), key([[0, 1, 2], [0, 2, 1], [2, 0, 1]])); + }); + test('a session keeps the plot across a removal of all variables', async() => { + assert.deepStrictEqual(await runs(['plot(1:10)', 'rm(list = ls())', 'abline(h = 1)'], CellRunner.Session), key([[0, 1, 2], [0, 2, 1], [1, 0, 2]])); + }); + test('a session closes the plot it keeps with dev.off', async() => { + assert.deepStrictEqual(await runs(['plot(1:10)', 'dev.off()', 'abline(h = 1)'], CellRunner.Session), key([[0, 1], [0, 2, 1]])); + }); + test('a session keeps the working directory', async() => { + assert.deepStrictEqual(await runs(['setwd("sub")', 'd <- read.csv("in.csv")'], CellRunner.Session), key([[0, 1]])); + }); + test('a session runs a chunk knitr would not run', async() => { + const analyzer = await analyze(parser, { request: 'file', content: 'nb.Rmd' }, { files: [new FlowrInlineTextFile('nb.Rmd', rmd(['knitr::opts_chunk$set(eval = FALSE)', 'print(y)', 'y <- 1']))] }); + const knit = key(workingOrders(await analyzeNotebook(analyzer, undefined, CellRunner.Knitr), true).toArray()); + const session = key(workingOrders(await analyzeNotebook(analyzer, undefined, CellRunner.Session), true).toArray()); + assert.include(knit, '0,1,2'); + assert.notInclude(session, '0,1,2'); + assert.include(session, '0,2,1'); + }); + }); + describe('a cell lacking what no cell binds runs in no order', () => { + /* checked in R (case 22-conddef of cell-order-audit.test.ts): `if (FALSE)` binds nothing, so `y <- x + 1` fails in every order */ + test('the orders that run skip it', async() => { + const facts = await factsOf(parser, ['if (FALSE) x <- 1', 'y <- x + 1', 'z <- 1']); + assert.deepStrictEqual(key(workingOrders(facts, true).toArray()), key([[0, 2], [2, 0]])); + /* as far as the order is concerned, every order does */ + assert.lengthOf(workingOrders(facts).toArray(), 6); + }); + /* checked in R: `g()` fails with could not find function "g" */ + test('a call of a function nothing defines', async() => { + assert.deepStrictEqual(key(workingOrders(await factsOf(parser, ['g()', 'x <- 1']), true).toArray()), key([[1]])); + }); + test('but not one in a function body no cell calls', async() => { + assert.deepStrictEqual(key(workingOrders(await factsOf(parser, ['f <- function() g()', 'x <- 1']), true).toArray()), key([[0, 1], [1, 0]])); + }); + test('nor one a cell defines later', async() => { + assert.deepStrictEqual(key(workingOrders(await factsOf(parser, ['g()', 'g <- function() 1']), true).toArray()), key([[1, 0]])); + }); + }); + describe('checked against R: sourced scripts, pipes, files, devices, and data masks', () => { + const runs = async(files: Readonly>, runner: CellRunner) => { + const [main] = Object.keys(files); + const analyzer = await analyze(parser, { request: 'file', content: main }, { files: Object.entries(files).map(([f, t]) => new FlowrInlineTextFile(f, t)), sigDb: fakeSigDb({ dplyr: [expFn('filter'), expFn('%>%')], magrittr: [expFn('%>%')] }) }); + return key(workingOrders(await analyzeNotebook(analyzer, undefined, runner), true).toArray()); + }; + for(const runner of [CellRunner.Session, CellRunner.Knitr]) { + /* checked in R: each `source` reads the script anew, so either cell gives `helper` */ + test(`two cells sourcing the same script each define what it defines (${runner})`, async() => { + assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['source("helpers.R")', 'source("helpers.R")', 'y <- helper(1)']), 'helpers.R': 'helper <- function(v) v + 1\n' }, runner), + key([[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0]])); + }); + test(`sys.source and source of the same script each define what it defines (${runner})`, async() => { + assert.includeMembers(await runs({ 'nb.Rmd': rmd(['sys.source("helpers.R", envir = globalenv())', 'z <- helper(1)', 'source("helpers.R")']), 'helpers.R': 'helper <- function(v) v + 1\n' }, runner), + ['0,1,2', '2,1,0', '0,2,1', '2,0,1']); + }); + /* checked in R: the parser turns `x |> f()` into `f(x)`, which needs no package */ + for(const lib of ['dplyr', 'magrittr']) { + test(`the native pipe needs no package, not even ${lib} (${runner})`, async() => { + assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['d <- mtcars |> head()', `library(${lib})`]) }, runner), key([[0, 1], [1, 0]])); + }); + } + /* checked in R: a relative path is read from the directory of the notebook, wherever flowR runs */ + test(`a file next to the notebook is read without the setwd of another cell (${runner})`, async() => { + assert.includeMembers(await runs({ 'dir/nb.Rmd': rmd(['d <- read.csv("in.csv")', 'setwd("sub")']), 'dir/in.csv': 'a\n1\n', 'dir/sub/in.csv': 'a\n1\n' }, runner), ['0,1']); + }); + } + /* checked in R: `dev.off()` closes the device `pdf(NULL)` opened, which makes the device with the histogram active again */ + test('closing a device another cell opened leaves the plot of the device before', async() => { + assert.includeMembers(await runs({ 'nb.Rmd': rmd(['hist(c(1, 2, 2, 3))', 'points(1, 1)', 'dev.off()', 'pdf(NULL)']) }, CellRunner.Session), ['0,3,2,1']); + }); + test('closing the only device closes its plot', async() => { + assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['plot(1:10)', 'dev.off()', 'abline(h = 1)']) }, CellRunner.Session), key([[0, 1], [0, 2, 1]])); + }); + /* checked in R: a data mask reads the columns of the data set R ships first, so `attach` of another cell gives nothing it needs */ + test('a data mask reads the columns of a data set of R', async() => { + assert.includeMembers(await runs({ 'nb.Rmd': rmd(['d <- data.frame(a = 1:3)', 'b <- with(mtcars, mean(mpg))', 'attach(d)', 'v <- a + 1']) }, CellRunner.Session), ['0,1,2,3', '1,0,2,3']); + }); + test('a call the native pipe gives the data has it as its data', async() => { + assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['d2 <- mtcars |> subset(mpg > 20)', 'attach(mtcars)']) }, CellRunner.Session), key([[0, 1], [1, 0]])); + }); + test('a call the magrittr pipe gives the data has it as its data', async() => { + assert.includeMembers(await runs({ 'nb.Rmd': rmd(['library(dplyr)', 'd <- mtcars %>% filter(mpg > 20)', 'attach(mtcars)']) }, CellRunner.Session), ['0,1,2', '0,2,1', '2,0,1']); + }); + /* checked in R (case 28-pipe-lib of cell-order-audit.test.ts): without dplyr, `filter` is `stats::filter`, which evaluates `mpg > 20` and fails */ + test('a column a function of a package masks needs the package where R has a function of its name', async() => { + assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['library(dplyr)', 'd <- mtcars |> filter(mpg > 20)', 'x <- 1']) }, CellRunner.Session), key([[0, 1, 2], [0, 2, 1], [2, 0, 1]])); + }); + test('a file only in another directory needs the setwd of a session', async() => { + assert.deepStrictEqual(await runs({ 'dir/nb.Rmd': rmd(['setwd("sub")', 'd <- read.csv("in.csv")']), 'dir/sub/in.csv': 'a\n1\n' }, CellRunner.Session), key([[0, 1]])); + }); + }); + describe('what may not run', () => { + const strict = async(cells: readonly string[]) => key(workingOrders(await scriptFacts(parser, cells), true).toArray()); + /* checked in R: with the condition false, the read, the removal, and the setting of `warn` do not happen */ + test('a read in a branch need not be satisfied', async() => { + assert.deepStrictEqual(await strict(['if (Sys.getenv("NOPE") == "1") print(x)', 'x <- 1']), key([[0, 1], [1, 0]])); + }); + test('a read in a loop that surely runs must be', async() => { + assert.deepStrictEqual(await strict(['for (i in 1:3) print(x)', 'x <- 1']), key([[1, 0]])); + }); + test('a removal in a branch removes nothing for sure', async() => { + assert.deepStrictEqual(await strict(['x <- 1', 'if (Sys.getenv("NOPE") == "1") rm(x)', 'print(x)']), key([[0, 1, 2], [0, 2, 1], [1, 0, 2]])); + }); + test('a branch no draw takes does not run', async() => { + assert.deepStrictEqual(await strict(['if (runif(1) > 2) x <- 1', 'print(x)']), key([[0]])); + }); + test('warnings as errors set in a branch are not sure', async() => { + assert.deepStrictEqual(await strict(['if (Sys.getenv("NOPE") == "1") options(warn = 2)', 'x <- as.numeric("a")']), key([[0, 1], [1, 0]])); + }); + }); + describe('warnings as errors', () => { + const strict = async(cells: readonly string[]) => key(workingOrders(await scriptFacts(parser, cells), true).toArray()); + /* checked in R: under `options(warn = 2)` a warning is an error */ + test('a cell that surely warns runs before warnings become errors', async() => { + assert.deepStrictEqual(await strict(['options(warn = 2)', 'x <- as.numeric("a")']), key([[0], [1, 0]])); + }); + test('and after they are no longer', async() => { + assert.deepStrictEqual(await strict(['options(warn = 2)', 'options(warn = 0)', 'warning("w")']).then(o => o.includes('0,1,2')), true); + }); + test('a muffled warning does not fail', async() => { + assert.deepStrictEqual(await strict(['options(warn = 2)', 'x <- suppressWarnings(as.numeric("a"))']), key([[0, 1], [1, 0]])); + }); + /* checked in R: the handler `withCallingHandlers` runs is no definition of its name, so removing all variables before it leaves it */ + test('a handler is no definition of the call it is handed to', async() => { + assert.deepStrictEqual(await strict(['rm(list = ls()); withCallingHandlers(log(-1), warning = function(e) invokeRestart("muffleWarning"))', 'x <- 1']), key([[0, 1], [1, 0]])); + }); + test('the failure says why', async() => { + const facts = await scriptFacts(parser, ['options(warn = 2)', 'x <- log(-1)']); + assert.deepStrictEqual(checkOrder(facts, [0, 1]).map(f => describeFailure(f)), ['cell 2 warns, which cell 1 turned into an error with options(warn = 2)']); + }); + }); })); diff --git a/test/functionality/queries/resolve-value-query.test.ts b/test/functionality/queries/resolve-value-query.test.ts index 2bb016672ed..bf8a3570edd 100644 --- a/test/functionality/queries/resolve-value-query.test.ts +++ b/test/functionality/queries/resolve-value-query.test.ts @@ -2,6 +2,7 @@ import { assertQuery } from '../_helper/query'; import type { FlowrCapabilityId } from '../../../src/r-bridge/data/get'; import { label } from '../_helper/label'; import { assert, describe } from 'vitest'; +import { ValueLogicalFalse, ValueLogicalTrue } from '../../../src/dataflow/eval/values/logical/logical-constants'; import { type ResolveValueQuery, type ResolveValueQueryResult, @@ -144,6 +145,20 @@ describe('Resolve Value Query', withTreeSitter(parser => { }); /* R answers `NA` for everything its 32-bit integers cannot hold, so those fold to nothing */ + describe('Random draws', () => { + /* checked in R: a single draw lies within the support of its distribution, which decides comparisons beyond it */ + testQuery('a uniform draw lies within its bounds', 'x <- runif(1)', ['1@x'], [[setFrom(intervalFrom(0, 1))]]); + testQuery('a uniform draw with bounds', 'x <- runif(1, 5, 10)', ['1@x'], [[setFrom(intervalFrom(5, 10))]]); + testQuery('several draws are not one range', 'x <- runif(2)', ['1@x'], [[Top]]); + testQuery('a draw never beyond its bound', 'x <- runif(1) > 2', ['1@x'], [[setFrom(ValueLogicalFalse)]]); + testQuery('a draw always within its bound', 'x <- runif(1) < 2', ['1@x'], [[setFrom(ValueLogicalTrue)]]); + testQuery('a draw that may be either side', 'x <- runif(1) > 0.5', ['1@x'], [[Top]]); + testQuery('a binomial draw is at most its size', 'x <- rbinom(1, 3, 0.5) <= 3', ['1@x'], [[setFrom(ValueLogicalTrue)]]); + testQuery('an exponential draw is not negative', 'x <- rexp(1) < 0', ['1@x'], [[setFrom(ValueLogicalFalse)]]); + testQuery('a draw equal to a value beyond it', 'x <- rbinom(1, 1, 0.5) == 2', ['1@x'], [[setFrom(ValueLogicalFalse)]]); + testQuery('a branch no draw takes defines nothing', 'x <- 0\nif (runif(1) > 2) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0))]]); + testQuery('a branch a draw may take may define', 'x <- 0\nif (runif(1) > 0.5) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0), intervalFrom(1, 1))]]); + }); describe('Bit twiddling', () => { testQuery('within the integers', 'x <- bitwShiftL(1, 3)\nprint(x)', ['2@x'], [[setFrom(intervalFrom(8, 8))]]); testQuery('a result that is none', 'x <- bitwShiftL(1, 31)\nprint(x)', ['2@x'], [[Top]]); diff --git a/test/functionality/slicing/backward/static-backward-program-slices/assign-environments.test.ts b/test/functionality/slicing/backward/static-backward-program-slices/assign-environments.test.ts index 8cc6458cc57..bc6ba26de08 100644 --- a/test/functionality/slicing/backward/static-backward-program-slices/assign-environments.test.ts +++ b/test/functionality/slicing/backward/static-backward-program-slices/assign-environments.test.ts @@ -22,7 +22,7 @@ const Programs: readonly (readonly [name: string, code: string])[] = [ ['into .GlobalEnv', 'x <- 1\nf <- function() assign("x", 2, envir = .GlobalEnv)\nf()\nprint(x)'], ['local keeps its bindings', 'local({\n assign("w", 4)\n})\nprint(exists("w"))'], ['the last value of the name counts', 'nm <- "a"\nnm <- "b"\nassign(nm, 1)\nprint(c(exists("a"), b))'], - ['a name chosen by a branch', 'nm <- if(runif(1) > 2) "a" else "b"\nassign(nm, 1)\nprint(b)'], + ['a name chosen by a branch', 'nm <- if(nchar(Sys.getenv("R_FLOWR_UNSET")) > 0) "a" else "b"\nassign(nm, 1)\nprint(b)'], ['names of a list', 'vals <- list(a = 1, b = 2)\nfor(k in names(vals)) assign(k, vals[[k]])\nprint(a + b)'], ['mapply into the global environment', 'invisible(mapply(function(n, v) assign(n, v, envir = globalenv()), c("m1", "m2"), 1:2))\nprint(m1 + m2)'], ['lapply into the global environment', 'invisible(lapply(c("s1", "s2"), function(n) assign(n, n, envir = .GlobalEnv)))\nprint(s2)'], @@ -60,7 +60,7 @@ const Programs: readonly (readonly [name: string, code: string])[] = [ ['a function under a computed name', 'nm <- "f3"\nassign(nm, function(x) x + 1)\nprint(f3(1))'], ['a function under a list field', 'obj <- list(nm = "f4")\nassign(obj$nm, function() "hi")\nprint(f4())'], ['a named vector element', 'x <- c(a = "n1")\nassign(x[["a"]], 1)\nprint(n1)'], - ['both branches assign', 'nm <- "y1"\nif(runif(1) < 2) assign(nm, 1) else assign(nm, 2)\nprint(y1)'], + ['both branches assign', 'nm <- "y1"\nif(nchar(Sys.getenv("R_FLOWR_UNSET")) == 0) assign(nm, 1) else assign(nm, 2)\nprint(y1)'], ['a handler assigning globally', 'nm <- "y2"\ntryCatch(assign(nm, stop("no")), error = function(e) assign(nm, -1, envir = globalenv()))\nprint(y2)'], ['within a repeat', 'nm <- "y3"\nrepeat {\n assign(nm, 1)\n break\n}\nprint(y3)'], ['get0', 'nm <- "y4"\nassign(nm, 2)\nprint(get0(nm))'], diff --git a/test/functionality/slicing/backward/static-backward-program-slices/calls.test.ts b/test/functionality/slicing/backward/static-backward-program-slices/calls.test.ts index b728e79067a..518ee141d22 100644 --- a/test/functionality/slicing/backward/static-backward-program-slices/calls.test.ts +++ b/test/functionality/slicing/backward/static-backward-program-slices/calls.test.ts @@ -1537,7 +1537,7 @@ describe('Primer', { concurrent: false }, withShell(shell => { ['muffled in braces', 'options(warn = 2)\n', '7@print', 'f <- function() "after"\noptions(warn = 2)\n', 'withCallingHandlers(f(), warning = function(w) { invokeRestart("muffleWarning") })', '[1] "after"'], ['not muffled', 'options(warn = 2)\n', '7@print', fn + 'options(warn = 2)\n', 'withCallingHandlers(f(), warning = function(w) 1)', '[1] "aborted"'], ['muffled messages only', 'options(warn = 2)\n', '7@print', fn + 'options(warn = 2)\n', 'withCallingHandlers(f(), message = function(m) invokeRestart("muffleMessage"))', '[1] "aborted"'], - ['branch', 'if(runif(1) < 2) options(warn = 2)\n', '7@print', fn + 'if(runif(1) < 2) options(warn = 2)\n', 'f()', '[1] "aborted"'], + ['branch', 'if(nchar(Sys.getenv("R_FLOWR_UNSET")) == 0) options(warn = 2)\n', '7@print', fn + 'if(nchar(Sys.getenv("R_FLOWR_UNSET")) == 0) options(warn = 2)\n', 'f()', '[1] "aborted"'], ['in function', 'g <- function() options(warn = 2)\ng()\n', '8@print', fn + 'g <- function() options(warn = 2)\ng()\n', 'f()', '[1] "aborted"'], ['restore', 'options(warn = 0)\nop <- options(warn = 2)\noptions(op)\n', '9@print', fn + 'options(warn = 0)\nop <- options(warn = 2)\noptions(op)\n', 'f()', '[1] "after"'], ] as const) { diff --git a/test/functionality/util/r-base-packages.test.ts b/test/functionality/util/r-base-packages.test.ts index 547ba18c068..aa87aad003d 100644 --- a/test/functionality/util/r-base-packages.test.ts +++ b/test/functionality/util/r-base-packages.test.ts @@ -9,6 +9,10 @@ import { RBasePackageStore } from '../../../src/data/r-base-packages.generated'; * invariants the generator promises, so a bad regeneration is caught here rather than deep in dataflow. */ describe('generated base-R export list (loader)', () => { + test('the native pipe is base R, though R exports no function of its name', () => { + /* `mtcars |> head()` in a notebook needed whatever package a cell attached */ + expect(baseRExportOwner('|>')).toBe('base'); + }); test('baseRExportOwner maps real base exports to their owning package', () => { // spread across several base packages, so this actually exercises the grouped generated list expect(baseRExportOwner('sd')).toBe('stats'); From 3e797821532715b5ae07edc58e0617f25b2f721b Mon Sep 17 00:00:00 2001 From: Florian Sihler Date: Mon, 30 Nov 2026 10:44:58 +0100 Subject: [PATCH 2/3] feat-fix(notebook): harden cell orders - values count only if they are the same in every cell order (CodeBindings); this gates the folding of conditions, loops, random draws, and sure-warning arguments - redefined or masked base functions, S3 methods, and attached packages that export a name disable that function's sure warnings - a warn level set in a called function counts; as.complex no longer claims a warning; rm(x) of an unbound x warns - seq_len(0) loops never run; knitr::knit_exit() skips all later chunks - rm(list = ls()) keeps dot names, other lists remove nothing for sure - .GlobalEnv$x <- v rebinds x - every former expected failure is fixed or pinned to the sound answer; 31 more audit cases and unit tests --- .../environments/built-in-eval-name.ts | 2 + src/dataflow/environments/built-in.ts | 3 +- .../default-builtin-config/base-functions.ts | 3 +- .../default-builtin-config/warnings.ts | 12 +- src/dataflow/eval/resolve/code-bindings.ts | 186 ++++++++++++++++++ .../eval/resolve/resolve-operators.ts | 20 +- src/dataflow/eval/resolve/resolve.ts | 27 ++- .../values/intervals/interval-constants.ts | 15 +- src/dataflow/fn/certain-warnings.ts | 61 ++++-- .../call/built-in/built-in-assignment.ts | 5 +- .../call/built-in/built-in-envir-utils.ts | 9 +- .../call/built-in/built-in-for-loop.ts | 14 +- .../call/built-in/built-in-if-then-else.ts | 5 +- src/documentation/wiki-query.ts | 5 +- src/notebook/cell-order.ts | 80 +++++--- .../environments/built-in-eval.test.ts | 1 + .../environments/stack-env-access.test.ts | 5 +- .../functions/certain-warnings.test.ts | 23 ++- .../linter/lint-dead-code.test.ts | 10 +- .../notebook/cell-order-audit.test.ts | 110 +++++++++-- .../queries/input-source.test.ts | 4 +- .../queries/resolve-value-query.test.ts | 5 + 22 files changed, 501 insertions(+), 104 deletions(-) create mode 100644 src/dataflow/eval/resolve/code-bindings.ts diff --git a/src/dataflow/environments/built-in-eval-name.ts b/src/dataflow/environments/built-in-eval-name.ts index 20152165a3a..2c2aa9a0cb9 100644 --- a/src/dataflow/environments/built-in-eval-name.ts +++ b/src/dataflow/environments/built-in-eval-name.ts @@ -4,6 +4,8 @@ export enum BuiltInEvalName { Vector = 'eval:vector', /** the sequence operator `:`, see {@link resolveAsSeq} */ Seq = 'eval:seq', + /** `seq_len(n)`, see {@link resolveAsSeqLen} */ + SeqLen = 'eval:seq-len', /** a single random draw (`runif(1)`), folding to the interval of the values it can take, see {@link resolveAsRandomDraw} */ RandomDraw = 'eval:random-draw', /** every numeric operator and function, from `+` to `sqrt`, see {@link resolveAsNumeric} */ diff --git a/src/dataflow/environments/built-in.ts b/src/dataflow/environments/built-in.ts index 16daea0dfa7..ff6c55af663 100644 --- a/src/dataflow/environments/built-in.ts +++ b/src/dataflow/environments/built-in.ts @@ -41,7 +41,7 @@ import { Ternary } from '../../util/logic'; import { type REnvironmentInformation, REnvironment } from './environment'; import type { Value } from '../eval/values/r-value'; import type { ResolveInfo } from '../eval/resolve/alias-tracking'; -import { resolveAsElement, resolveAsList, resolveAsSeq, resolveAsVector } from '../eval/resolve/resolve'; +import { resolveAsElement, resolveAsList, resolveAsSeq, resolveAsSeqLen, resolveAsVector } from '../eval/resolve/resolve'; import { resolveAsStringFn } from '../eval/resolve/resolve-strings'; import { resolveAsComparison, resolveAsGroup, resolveAsLogical } from '../eval/resolve/resolve-operators'; import { resolveAsGet } from '../eval/resolve/resolve-get'; @@ -425,6 +425,7 @@ export const BuiltInProcessorMapper = { export const BuiltInEvalHandlerMapper = { [BuiltInEvalName.Vector]: resolveAsVector, [BuiltInEvalName.Seq]: resolveAsSeq, + [BuiltInEvalName.SeqLen]: resolveAsSeqLen, [BuiltInEvalName.Numeric]: resolveAsNumeric, [BuiltInEvalName.RandomDraw]: resolveAsRandomDraw, [BuiltInEvalName.Comparison]: resolveAsComparison, diff --git a/src/dataflow/environments/default-builtin-config/base-functions.ts b/src/dataflow/environments/default-builtin-config/base-functions.ts index 164b71a2b97..47e2828cda2 100644 --- a/src/dataflow/environments/default-builtin-config/base-functions.ts +++ b/src/dataflow/environments/default-builtin-config/base-functions.ts @@ -145,7 +145,8 @@ export const BaseDefinitions = [ /* indices and index sequences: bounded by the shape of what they are handed, never by its contents */ /* `seq_along(x)` asks `length(x)` and `which.max(x)` asks `xtfrm(x)` */ - fn(base('which', 'which.max', 'which.min', 'seq_len', 'seq_along'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, tags: [SemanticCallTag.Narrows], dispatches: ['length', 'xtfrm'] }, Primitive), + fn(base('which', 'which.max', 'which.min', 'seq_along'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, tags: [SemanticCallTag.Narrows], dispatches: ['length', 'xtfrm'] }, Primitive), + fn(base('seq_len'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, tags: [SemanticCallTag.Narrows], dispatches: ['length', 'xtfrm'] }, { ...Primitive, evalHandler: BuiltInEvalName.SeqLen }), /* `seq` dispatches, so `...` really is all it declares; the named formals belong to `seq.default`/`seq.int` */ fn(base('seq'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, sig: sig({ '...': Forced.Value }) }, Primitive), fn(base('scan'), BuiltInProcName.DefaultReadAllArgs, diff --git a/src/dataflow/environments/default-builtin-config/warnings.ts b/src/dataflow/environments/default-builtin-config/warnings.ts index 32ab38db863..129674fa45f 100644 --- a/src/dataflow/environments/default-builtin-config/warnings.ts +++ b/src/dataflow/environments/default-builtin-config/warnings.ts @@ -15,7 +15,9 @@ export type WarnsWhen = /** a finite number of the formal lies outside of the closed range `[from, to]`, as `sqrt(-1)` produces `NaN` with a warning */ | { readonly formal: string, readonly outside: readonly [from: number, to: number] } /** a number of the formal is a whole number of at most `wholeAtMost`, where the function has a pole (`gamma(0)`, `factorial(-1)`) */ - | { readonly formal: string, readonly wholeAtMost: number }; + | { readonly formal: string, readonly wholeAtMost: number } + /** a name the call removes (`rm(x)`, `rm("x")`) is not bound where it runs, which only the code running before can tell (see `CertainWarnings.removals`) */ + | { readonly removesUnbound: true }; /** what R does not read as a number: everything but decimal and hexadecimal numbers, `Inf`, `Infinity`, `NaN`, and `NA` (which warns, but is left out to keep this list exact), around them only white space */ const RNumberSyntax = /^\s*(?:[+-]?(?:(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?|0[xX](?:[0-9a-fA-F]+\.?[0-9a-fA-F]*|\.[0-9a-fA-F]+)(?:[pP][+-]?\d+)?|inf(?:inity)?|nan|na))?\s*$/i; @@ -38,7 +40,7 @@ export const RWarnings: Readonly> = { 'warning': [{ always: true }], 'as.numeric': Coerces, 'as.double': Coerces, - 'as.complex': Coerces, + /* `as.complex` is left out: it reads complex numbers (`"1+2i"`), which the syntax above does not cover */ /* `as.integer(3e9)`: NAs introduced by coercion to integer range */ 'as.integer': [...Coerces, { formal: 'x', outside: [-IntegerBound, IntegerBound] }], /* NaNs produced */ @@ -57,12 +59,14 @@ export const RWarnings: Readonly> = { 'mean': [{ formal: 'x', aString: true }], /* no non-missing arguments to max; returning -Inf */ 'max': [{ noArguments: true }], - 'min': [{ noArguments: true }] + 'min': [{ noArguments: true }], + /* object 'x' not found */ + 'rm': [{ removesUnbound: true }] }; /** Whether the scalar `value` of an argument makes `when` hold, `undefined` for a condition on no argument. */ export function warnsFor(when: WarnsWhen, value: string | number): boolean | undefined { - if('always' in when || 'noArguments' in when) { + if('always' in when || 'noArguments' in when || 'removesUnbound' in when) { return undefined; } else if('notANumber' in when) { return typeof value === 'string' && notANumber(value); diff --git a/src/dataflow/eval/resolve/code-bindings.ts b/src/dataflow/eval/resolve/code-bindings.ts new file mode 100644 index 00000000000..2a7cde5884a --- /dev/null +++ b/src/dataflow/eval/resolve/code-bindings.ts @@ -0,0 +1,186 @@ +import type { AstIdMap, ParentInformation, RNodeWithParent } from '../../../r-bridge/lang-4.x/ast/model/processing/decorate'; +import type { ReadOnlyFlowrAnalyzerContext } from '../../../project/context/flowr-analyzer-context'; +import { RNode } from '../../../r-bridge/lang-4.x/ast/model/model'; +import { RBinaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op'; +import { RUnaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-unary-op'; +import { RSymbol } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol'; +import { RString } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-string'; +import { RNumber } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-number'; +import { RLogical } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-logical'; +import { RAccess } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-access'; +import { RArgument } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-argument'; +import { RExpressionList } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; +import { RForLoop } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-for-loop'; +import { RFunctionDefinition } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition'; +import { EmptyArgument, RFunctionCall } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call'; +import { type BrandedIdentifier, Identifier, ReferenceType } from '../../environments/identifier'; +import { BuiltInProcName } from '../../environments/built-in-proc-name'; +import { RandomDraws } from './resolve-numbers'; +import { BaseDatasets, BaseValues, baseRExportOwner, isBaseRPackage } from '../../../util/r-base-packages'; + +/** + * What the code binds, read off its syntax as a whole: a notebook may run its cells in any order, so the value a name + * has where it is read may come from any binding of it, not just from those before in the file. + */ +interface Bindings { + /** for each name the code binds, the value of each binding: the assigned expression for a plain assignment at the top level, `undefined` for any other binding */ + readonly bound: ReadonlyMap + /** the packages the code attaches (or what it hands a call attaching packages, which may name none flowR knows) */ + readonly packages: readonly string[] + /** the code binds names flowR cannot tell from its syntax (`load`, `eval(parse(...))`, `attach`, an `assign` to a computed name, methods it declares) */ + readonly dynamic: boolean +} + +/** the calls binding names their code does not show, by the processor of their built-in */ +const DynamicBinders: ReadonlySet = new Set([BuiltInProcName.Attach, BuiltInProcName.Load, BuiltInProcName.Source, BuiltInProcName.Eval, BuiltInProcName.ListToEnv]); +/** the calls binding the name their first argument gives, which binds a name the code does not show unless it is a string */ +const NamedBinders: ReadonlySet = new Set(['assign', 'delayedAssign', 'makeActiveBinding']); +/** the calls declaring methods a function may dispatch to, as `setMethod("mean", "character", ...)` does */ +const Dispatchers: ReadonlySet = new Set(['setGeneric', 'setMethod', 'setGroupGeneric', 'setReplaceMethod', 'registerS3method', '.S3method']); +const Assignments: ReadonlySet = new Set(['<-', '=', '<<-', ':=']); +const RightAssignments: ReadonlySet = new Set(['->', '->>']); + +/** how a call of the function binds names: by attaching packages, by the name its first argument gives, or in a way flowR cannot tell from the code */ +function binderKind(name: string, ctx: ReadOnlyFlowrAnalyzerContext): 'library' | 'named' | 'dynamic' | undefined { + const processors = ctx.env.builtInDefinitionsOf(Identifier.make(name)).flatMap(d => d.type === ReferenceType.BuiltInFunction && d.processorName !== undefined ? [d.processorName] : []); + return processors.includes(BuiltInProcName.Library) ? 'library' : NamedBinders.has(name) ? 'named' + : Dispatchers.has(name) || processors.some(p => DynamicBinders.has(p)) ? 'dynamic' : undefined; +} + +/** the bindings per id map, along with its size, as the map grows when more code joins the analysis */ +const Cache = new WeakMap(); + +/** a top-level expression runs once, as no loop, branch, or function encloses it */ +function atTopLevel(node: RNodeWithParent, idMap: AstIdMap): boolean { + for(let at = RNode.directParent(node, idMap); at !== undefined; at = RNode.directParent(at, idMap)) { + if(!RExpressionList.is(at) || at.grouping !== undefined) { + return false; + } + } + return true; +} + +/** the symbol a replacement (`x$a <- 1`, `names(x) <- n`) changes */ +function rootSymbol(node: RNodeWithParent | undefined): RSymbol | undefined { + while(node !== undefined && !RSymbol.is(node)) { + node = RAccess.is(node) ? node.accessed : RFunctionCall.is(node) ? (node.arguments[0] === EmptyArgument ? undefined : node.arguments[0]?.value) : RArgument.is(node) ? node.value : undefined; + } + return node; +} + +const nameOf = (node: RNodeWithParent | undefined) => RSymbol.is(node) ? String(Identifier.getName(node.content)) : RString.is(node) ? node.content.str : undefined; + +function codeBindings(idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext): Bindings { + const cached = Cache.get(idMap); + if(cached?.size === idMap.size) { + return cached; + } + const bound = new Map(); + const bind = (name: string | undefined, value?: RNodeWithParent) => { + if(name !== undefined) { + bound.set(name, [...bound.get(name) ?? [], value]); + } + }; + const packages: string[] = []; + let dynamic = false; + /* the map may hold a node under more than one id */ + for(const node of new Set(idMap.values())) { + if(RBinaryOp.is(node) && (Assignments.has(node.operator) || RightAssignments.has(node.operator))) { + const [target, value] = Assignments.has(node.operator) ? [node.lhs, node.rhs] : [node.rhs, node.lhs]; + const name = nameOf(target); + if(name !== undefined) { + bind(name, node.operator !== '<<-' && node.operator !== '->>' && atTopLevel(node, idMap) ? value : undefined); + } else { + /* a replacement changes its target, and an access may bind the member of an environment (`.GlobalEnv$x <- 1`) */ + bind(nameOf(rootSymbol(target))); + bind(RAccess.is(target) ? nameOf(target.access[0] === EmptyArgument ? undefined : target.access[0]?.value) : undefined); + } + } else if(RFunctionDefinition.is(node)) { + node.parameters.forEach(p => bind(String(Identifier.getName(p.name.content)))); + } else if(RForLoop.is(node)) { + bind(String(Identifier.getName(node.variable.content))); + } else if(RFunctionCall.isNamed(node)) { + const called = String(Identifier.getName(node.functionName.content)); + const kind = binderKind(called, ctx); + const args = node.arguments.flatMap(a => a === EmptyArgument || a.value === undefined ? [] : [a]); + if(kind === 'library') { + /* every symbol or string it takes may name a package, anything else names one flowR cannot tell */ + const names = args.map(a => nameOf(a.value)); + dynamic ||= names.length === 0; + packages.push(...names.filter(n => n !== undefined)); + } else if(kind === 'named') { + const name = RString.is(args[0]?.value) ? args[0].value.content.str : undefined; + dynamic ||= name === undefined; + bind(name); + } + dynamic ||= kind === 'dynamic'; + } else if(RSymbol.is(node) || RString.is(node)) { + /* a binder handed on as a value (`lapply(pkgs, library, character.only = TRUE)`, `do.call("assign", args)`) binds what flowR cannot tell */ + const parent = RNode.directParent(node, idMap); + dynamic ||= !(RFunctionCall.isNamed(parent) && parent.functionName === node) && binderKind(nameOf(node) ?? '', ctx) !== undefined; + } + } + const result = { bound, packages, dynamic, size: idMap.size }; + Cache.set(idMap, result); + return result; +} + +/** whether the node is a single random draw, which the value solver folds to the range of values it can take */ +const drawn = (node: RNodeWithParent) => RFunctionCall.isNamed(node) && Object.hasOwn(RandomDraws, Identifier.getName(node.functionName.content)); + +/** what R provides under a name the code does not bind (`pi`, `iris`, `c`) */ +const providedByR = (name: BrandedIdentifier) => baseRExportOwner(name) !== undefined || BaseDatasets.has(name) || BaseValues.has(name); + +/** Whether a package the code attaches may provide the name: one flowR does not know, or one that exports it or a method of it. */ +function attachedMayProvide(name: string, { packages }: Bindings, ctx: ReadOnlyFlowrAnalyzerContext): boolean { + return packages.some(p => { + if(isBaseRPackage(p)) { + return false; + } + const pkg = ctx.deps.getDependency(p); + return pkg?.namespaceInfo === undefined || pkg.has(name) || pkg.s3For(name).length > 0; + }); +} + +export const CodeBindings = { + /** + * Whether a call of the function R ships under the name runs it in any order of the code: the code binds neither the + * name nor a method of it (`mean.character`), declares no methods, binds nothing flowR cannot see, and attaches no + * package that may provide it. + */ + callsBuiltIn(this: void, name: string, idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext): boolean { + const code = codeBindings(idMap, ctx); + return !code.dynamic && !code.bound.has(name) && !code.bound.keys().some(b => b.startsWith(`${name}.`)) && !attachedMayProvide(name, code, ctx); + }, + /** + * Whether the value of the node is the same in any order the top-level expressions of the code may run in (as the + * cells of a notebook do): it is a literal, an operator or call of a function R ships (see {@link CodeBindings.callsBuiltIn}) + * on such values (`runif(1) > 2`), or a name the code binds once, at the top level, to such a value, which R does not + * provide otherwise. With `names` set to `draws`, a name counts only if it holds a single random draw (`u <- runif(1)`). + * Value resolution may fold such a node while the analysis runs or for code running in another order. + */ + inAnyOrder(this: void, node: RNodeWithParent | undefined, idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext, names: 'any' | 'draws' = 'any', seen: ReadonlySet = new Set()): boolean { + const inAnyOrder = (n: RNodeWithParent | undefined) => CodeBindings.inAnyOrder(n, idMap, ctx, names, seen); + const calls = (name: string) => CodeBindings.callsBuiltIn(name, idMap, ctx); + if(node === undefined) { + return false; + } else if(RNumber.is(node) || RString.is(node) || RLogical.is(node)) { + return true; + } else if(RExpressionList.is(node)) { + return node.grouping !== undefined && node.children.length === 1 && inAnyOrder(node.children[0]); + } else if(RBinaryOp.is(node)) { + return calls(node.operator) && inAnyOrder(node.lhs) && inAnyOrder(node.rhs); + } else if(RUnaryOp.is(node)) { + return calls(node.operator) && inAnyOrder(node.operand); + } else if(RFunctionCall.isNamed(node)) { + return calls(String(Identifier.getName(node.functionName.content))) && node.arguments.every(a => a !== EmptyArgument && inAnyOrder(a.value)); + } else if(!RSymbol.is(node)) { + return false; + } + const name = String(Identifier.getName(node.content)); + const code = codeBindings(idMap, ctx); + const [value, ...others] = code.bound.get(name) ?? []; + return others.length === 0 && value !== undefined && !seen.has(name) && !code.dynamic && !providedByR(name) && !attachedMayProvide(name, code, ctx) + && (names === 'any' || drawn(value)) && CodeBindings.inAnyOrder(value, idMap, ctx, names, new Set(seen).add(name)); + } +} as const; diff --git a/src/dataflow/eval/resolve/resolve-operators.ts b/src/dataflow/eval/resolve/resolve-operators.ts index 2f30fc39db9..9ff69abd2ed 100644 --- a/src/dataflow/eval/resolve/resolve-operators.ts +++ b/src/dataflow/eval/resolve/resolve-operators.ts @@ -4,7 +4,7 @@ import { type BrandedIdentifier, Identifier } from '../../environments/identifie import { isRNumberValue, unliftRValue } from '../../../util/r-value'; import type { BuiltInEvalHandlerArgs } from '../../environments/built-in'; import { ValueLogicalFalse, ValueLogicalTrue } from '../values/logical/logical-constants'; -import { isValue, Top, type Value } from '../values/r-value'; +import { Top, type Value } from '../values/r-value'; import { valueSetGuard } from '../values/general'; import { Resolve } from '../../environments/resolve-helper'; import { NodeValue } from './node-value'; @@ -13,6 +13,9 @@ import { RBinaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-o import { RExpressionList } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; import { RUnaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-unary-op'; import { RNumber } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-number'; +import { intervalBounds } from '../values/intervals/interval-constants'; +import { RSymbol } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol'; +import { CodeBindings } from './code-bindings'; /** the scalar an operand folds to, with a logical counting as its `0`/`1` just like R would coerce it */ function operand(node: RNodeWithParent, args: BuiltInEvalHandlerArgs): number | string | undefined { @@ -85,8 +88,8 @@ export function resolveAsComparison(args: BuiltInEvalHandlerArgs): Value { /** the closed range of numbers an operand may hold, a number or a call of a random draw (see `resolveAsRandomDraw`), `undefined` for anything else */ function rangeOf(node: RNodeWithParent, args: BuiltInEvalHandlerArgs): readonly [number, number] | undefined { - /* only a call draws: a name may hold a range for the rounds of a loop, which differ from one another */ - if(!RFunctionCall.is(node) && !RNumber.is(node)) { + /* a name only where it has its value in any order of the code, else the rounds of a loop may hold different values of it */ + if(!RFunctionCall.is(node) && !RNumber.is(node) && !(RSymbol.is(node) && args.idMap !== undefined && CodeBindings.inAnyOrder(node, args.idMap, args.ctx))) { return undefined; } if(RNumber.is(node)) { @@ -94,16 +97,7 @@ function rangeOf(node: RNodeWithParent, args: BuiltInEvalHandlerArgs): readonly } /* resolving a node blocks it for the rest of the fold, which still has to resolve it as an operand */ const set = valueSetGuard(Resolve.toValue(node, { ...args, blocked: new Set(args.blocked) })); - const value = set?.elements.length === 1 ? set.elements[0] : undefined; - if(value === undefined || !isValue(value) || value.type !== 'interval') { - return undefined; - } - const [start, end] = [value.start, value.end]; - if(!isValue(start) || !isValue(end) || !isValue(start.value) || !isValue(end.value) || start.value.complexNumber || end.value.complexNumber) { - return undefined; - } - const [lo, hi] = [start.value.num, end.value.num]; - return Number.isNaN(lo) || Number.isNaN(hi) ? undefined : [lo, hi]; + return intervalBounds(set?.elements.length === 1 ? set.elements[0] : undefined); } /** diff --git a/src/dataflow/eval/resolve/resolve.ts b/src/dataflow/eval/resolve/resolve.ts index 541085406a8..082b0cfb472 100644 --- a/src/dataflow/eval/resolve/resolve.ts +++ b/src/dataflow/eval/resolve/resolve.ts @@ -37,6 +37,7 @@ import type { REnvironmentInformation } from '../../environments/environment'; import type { ReadOnlyFlowrAnalyzerContext } from '../../../project/context/flowr-analyzer-context'; import { Dataflow } from '../../graph/df-helper'; import { NodeId } from '../../../r-bridge/lang-4.x/ast/model/processing/node-id'; +import { CodeBindings } from './code-bindings'; import { Resolve } from '../../environments/resolve-helper'; import { RBinaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op'; import { RUnaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-unary-op'; @@ -66,21 +67,16 @@ export function onlyLiterals(node: RNode): boolean { : RNumber.is(node) || RString.is(node) || RLogical.is(node); } -/** Whether the node folds while the analysis runs: literals, and operators and calls on nothing else (`runif(1) > 2`), as no name in them may change its value; the called names are checked where they fold. */ -function foldsWhileAnalyzing(node: RNode): boolean { - return onlyLiterals(node) || (RBinaryOp.is(node) ? foldsWhileAnalyzing(node.lhs) && foldsWhileAnalyzing(node.rhs) - : RUnaryOp.is(node) ? foldsWhileAnalyzing(node.operand) - : RFunctionCall.isNamed(node) && node.arguments.every(a => a !== EmptyArgument && a.value !== undefined && foldsWhileAnalyzing(a.value))); -} /** The name of the built-in the given node folds through, `undefined` if it is no call to one or if it may just as well resolve to something else (a user redefinition, a conditional one, ...), which must not be folded. */ -function evalNameOf({ node, graph, environment, ctx }: BuiltInEvalHandlerArgs): Identifier | undefined { +function evalNameOf({ node, graph, environment, ctx, idMap }: BuiltInEvalHandlerArgs): Identifier | undefined { if(!EvalNodeTypes.includes(node.type)) { return undefined; } else if(graph === undefined) { + /* while the analysis runs, an operator folds on what has its value in any order of the code, a name in it only if it holds a single draw (`u < 4` after `u <- runif(1, 5, 10)`) */ const named = RExpressionList.is(node) ? RExpressionList.groupStart(node)?.content : RAccess.is(node) ? Identifier.make(node.operator) - : RFunctionCall.calledName(node) ?? ((RBinaryOp.is(node) || RUnaryOp.is(node)) && foldsWhileAnalyzing(node) ? Identifier.make(node.operator) : undefined); + : RFunctionCall.calledName(node) ?? ((RBinaryOp.is(node) || RUnaryOp.is(node)) && idMap !== undefined && CodeBindings.inAnyOrder(node, idMap, ctx, 'draws') ? Identifier.make(node.operator) : undefined); return named !== undefined && environment !== undefined && foldsThroughBuiltIn(named, ctx) && Resolve.isBuiltIn(named, environment, ReferenceType.Function) ? named : undefined; } @@ -227,6 +223,21 @@ export function resolveAsSeq(args: BuiltInEvalHandlerArgs): ValueVector> | typeof Top { + const call = args.node; + const [arg, ...rest] = RFunctionCall.is(call) ? call.arguments : []; + if(arg === undefined || arg === EmptyArgument || arg.value === undefined || rest.length > 0) { + return Top; + } + const n = unliftRValue(Resolve.toValue(arg.value, args)); + if(!isRNumberValue(n) || n.complexNumber || !Number.isInteger(n.num) || n.num < 0) { + return Top; + } + const sequence = n.num === 0 ? [] : createNumberSequence({ ...n, num: 1 }, n); + return sequence === undefined ? Top : vectorFrom(sequence.map(liftScalar)); +} + /** The elements `from:to` runs over, counting down whenever `to` is the smaller one, and stopping before it would pass `to` (`1:3.5` ends at `3`). */ function createNumberSequence(start: RNumberValue, end: RNumberValue): RNumberValue[] | undefined { if(!Number.isFinite(start.num) || !Number.isFinite(end.num)) { diff --git a/src/dataflow/eval/values/intervals/interval-constants.ts b/src/dataflow/eval/values/intervals/interval-constants.ts index 624c47ca306..1427bd955e2 100644 --- a/src/dataflow/eval/values/intervals/interval-constants.ts +++ b/src/dataflow/eval/values/intervals/interval-constants.ts @@ -1,5 +1,5 @@ import type { RNumberValue } from '../../../../r-bridge/lang-4.x/convert-values'; -import { type Lift, type ValueInterval, type ValueNumber, isBottom, isTop } from '../r-value'; +import { type Lift, type Value, type ValueInterval, type ValueNumber, isBottom, isTop, isValue } from '../r-value'; import { getScalarFromInteger, liftScalar } from '../scalar/scalar-constants'; /** @@ -30,3 +30,16 @@ function shiftNum(v: Lift): ValueNumber { export function intervalFromValues(start: Lift, end = start, startInclusive = true, endInclusive = true): ValueInterval { return { type: 'interval', start: shiftNum(start), end: shiftNum(end), startInclusive, endInclusive }; } + +/** The real bounds of an interval value (counting it as closed), `undefined` for any other value and for an unknown, complex, or `NaN` bound. */ +export function intervalBounds(value: Value | undefined): readonly [number, number] | undefined { + if(value === undefined || !isValue(value) || value.type !== 'interval') { + return undefined; + } + const [start, end] = [value.start, value.end]; + if(!isValue(start) || !isValue(end) || !isValue(start.value) || !isValue(end.value) || start.value.complexNumber || end.value.complexNumber) { + return undefined; + } + const [lo, hi] = [start.value.num, end.value.num]; + return Number.isNaN(lo) || Number.isNaN(hi) ? undefined : [lo, hi]; +} diff --git a/src/dataflow/fn/certain-warnings.ts b/src/dataflow/fn/certain-warnings.ts index 6b1c3e29cf5..32a840efcad 100644 --- a/src/dataflow/fn/certain-warnings.ts +++ b/src/dataflow/fn/certain-warnings.ts @@ -9,15 +9,19 @@ import { RFunctionDefinition } from '../../r-bridge/lang-4.x/ast/model/nodes/r-f import { RExpressionList } from '../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; import { RArgument } from '../../r-bridge/lang-4.x/ast/model/nodes/r-argument'; import { RBinaryOp } from '../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op'; -import { Identifier, ReferenceType } from '../environments/identifier'; +import { Identifier, ReferenceType } from '../environments/identifier'; +import { RSymbol } from '../../r-bridge/lang-4.x/ast/model/nodes/r-symbol'; +import { RString } from '../../r-bridge/lang-4.x/ast/model/nodes/r-string'; import { Dataflow } from '../graph/df-helper'; import { OriginType } from '../origin/dfg-get-origin'; import { BuiltInProcName } from '../environments/built-in-proc-name'; import { ArgProp, type FnSig } from '../environments/built-in-props'; import { NodeValue } from '../eval/resolve/node-value'; import { isValue, type Value } from '../eval/values/r-value'; +import { intervalBounds } from '../eval/values/intervals/interval-constants'; import { RWarnings, warnsFor, type WarnsWhen } from '../environments/default-builtin-config/warnings'; import { isBaseRPackage } from '../../util/r-base-packages'; +import { CodeBindings } from '../eval/resolve/code-bindings'; /** What {@link CertainWarnings} looks at: the finished graph, and where to resolve the values of arguments. */ export interface CertainWarningsInfo { @@ -61,30 +65,47 @@ export const CertainWarnings = { * within a construct handling or muffling warnings (`suppressWarnings`, `tryCatch`, `try`, `withCallingHandlers`). */ sites(this: void, root: NodeId, info: CertainWarningsInfo, seen: ReadonlySet = new Set()): NodeId[] { - const top = info.idMap.get(root); - if(top === undefined) { - return []; - } - const found: NodeId[] = []; - RNode.visitAst(top, n => { - if(RFunctionDefinition.is(n)) { - return true; - } - if(RFunctionCall.is(n) && runsWith(n, top, info) && CertainWarnings.warns(n.info.id, info, seen)) { - found.push(n.info.id); + return eagerCalls(root, info).filter(n => CertainWarnings.warns(n.info.id, info, seen)).map(n => n.info.id); + }, + /** + * The calls within `root` that run whenever it runs (as for {@link CertainWarnings.sites}) and warn if a name they remove + * is not bound where they run, as `rm(x)` does without `x`, with the names they remove. + */ + removals(this: void, root: NodeId, info: CertainWarningsInfo): { readonly id: NodeId, readonly names: readonly string[] }[] { + return eagerCalls(root, info).flatMap(n => { + const builtin = builtInOf(n.info.id, info); + /* a named argument may point the call elsewhere (`envir = e`) or list further names */ + if(builtin === undefined || !RWarnings[builtin]?.some(w => 'removesUnbound' in w) || n.arguments.some(a => a !== EmptyArgument && a.name !== undefined)) { + return []; } - return false; + const names = n.arguments.flatMap(a => a !== EmptyArgument && (RSymbol.is(a.value) || RString.is(a.value)) ? [RString.unquote(a.value.lexeme)] : []); + return names.length === 0 ? [] : [{ id: n.info.id, names }]; }); - return found; } } as const; +/** the calls within `root` that surely run whenever it does, outside of function definitions (see {@link runsWith}) */ +function eagerCalls(root: NodeId, info: CertainWarningsInfo): RFunctionCall[] { + const top = info.idMap.get(root); + const found: RFunctionCall[] = []; + if(top !== undefined) { + RNode.visitAst(top, n => { + if(RFunctionCall.is(n) && runsWith(n, top, info)) { + found.push(n); + } + return RFunctionDefinition.is(n); + }); + } + return found; +} + /** the name of the one built-in the call goes to, `undefined` if it may go to a closure or to several built-ins */ function builtInOf(id: NodeId, info: CertainWarningsInfo): string | undefined { const origins = Dataflow.origin(info.graph, id) ?? []; /* what a package other than those of R defines under the name is not what the table states */ const names = new Set(origins.map(o => o.type === OriginType.BuiltInFunctionOrigin && isBaseRPackage(String(Identifier.getNamespace(o.fn.name) ?? 'base')) ? String(Identifier.getName(o.fn.name)) : undefined)); - return names.size === 1 && !names.has(undefined) && origins.every(o => o.type === OriginType.BuiltInFunctionOrigin) ? [...names][0] : undefined; + const [name] = names; + return names.size === 1 && name !== undefined && origins.every(o => o.type === OriginType.BuiltInFunctionOrigin) && CodeBindings.callsBuiltIn(name, info.idMap, info.ctx) ? name : undefined; } /** the signature and processor of the built-in of that name */ @@ -173,12 +194,18 @@ function formalOf(call: RFunctionCall, arg: RNodeWithParent, function holds(when: WarnsWhen, call: RFunctionCall, info: CertainWarningsInfo): boolean { if('always' in when) { return true; + } else if('removesUnbound' in when) { + return false; } const args = call.arguments.filter(a => a !== EmptyArgument); if('noArguments' in when) { return call.arguments.every(a => a === EmptyArgument) && args.length === 0; } const arg = args.find(a => a.name !== undefined && Identifier.getName(a.name.content) === when.formal) ?? args.find(a => a.name === undefined); + /* a value another order of the code may change does not surely warn */ + if(!CodeBindings.inAnyOrder(arg?.value, info.idMap, info.ctx)) { + return false; + } const values = NodeValue.setOf(arg?.value?.info.id, info.resolve)?.elements; return values !== undefined && values.length > 0 && values.every(v => scalarsOf(v)?.some(s => warnsFor(when, s)) === true); } @@ -194,8 +221,8 @@ function scalarsOf(value: Value): (string | number)[] | undefined { case 'number': return isValue(value.value) && !value.value.complexNumber ? [value.value.num] : undefined; case 'interval': { - const [start, end] = [value.start, value.end]; - return isValue(start) && isValue(end) && isValue(start.value) && isValue(end.value) && start.value.num === end.value.num && !start.value.complexNumber ? [start.value.num] : undefined; + const bounds = intervalBounds(value); + return bounds !== undefined && bounds[0] === bounds[1] ? [bounds[0]] : undefined; } case 'vector': { if(!isValue(value.elements)) { diff --git a/src/dataflow/internal/process/functions/call/built-in/built-in-assignment.ts b/src/dataflow/internal/process/functions/call/built-in/built-in-assignment.ts index 14a3554f3ca..588de510fac 100644 --- a/src/dataflow/internal/process/functions/call/built-in/built-in-assignment.ts +++ b/src/dataflow/internal/process/functions/call/built-in/built-in-assignment.ts @@ -32,7 +32,7 @@ import { RoleInParent } from '../../../../../../r-bridge/lang-4.x/ast/model/proc import { ControlFlow } from '../../../../control-flow'; import { type REnvironmentInformation, REnvironment } from '../../../../../environments/environment'; import type { DataflowGraph } from '../../../../../graph/graph'; -import { closureFrameResolution, type EnvirResolution, EnvironmentProducers, EnvirPositionFormals, findReturnsEnvState, suppliesArg, resolveConstantString, resolveEnvirArgOrAmbiguous, resolveFirstEnvirArg, resolveSymbolToEnvir, rebindHolders, routeWrittenToEnvir } from './built-in-envir-utils'; +import { closureFrameResolution, type EnvirResolution, globalFrameResolution, EnvironmentProducers, EnvirPositionFormals, findReturnsEnvState, suppliesArg, resolveConstantString, resolveEnvirArgOrAmbiguous, resolveFirstEnvirArg, resolveSymbolToEnvir, rebindHolders, routeWrittenToEnvir } from './built-in-envir-utils'; import { markAsOnlyBuiltIn } from '../named-call-handling'; import { BuiltInProcessorMapper } from '../../../../../environments/built-in'; import { ArgProp, type FnSig } from '../../../../../environments/built-in-props'; @@ -516,7 +516,8 @@ function tryRouteFieldEnvAssign( if(!fieldNode || (target.operator !== '$' && (target.operator !== '[[' || !RString.is(fieldNode)))) { return undefined; } - const envirResolution = RSymbol.is(target.accessed) ? resolveSymbolToEnvir(target.accessed.content, target.accessed.info.id, data) : closureFrameResolution(target.accessed, data); + const envirResolution = globalFrameResolution(target.accessed, data) + ?? (RSymbol.is(target.accessed) ? resolveSymbolToEnvir(target.accessed.content, target.accessed.info.id, data) : closureFrameResolution(target.accessed, data)); if(!envirResolution) { return undefined; } diff --git a/src/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.ts b/src/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.ts index 40ca8daf7e3..b56ffa61e0d 100644 --- a/src/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.ts +++ b/src/dataflow/internal/process/functions/call/built-in/built-in-envir-utils.ts @@ -27,7 +27,8 @@ import { REnvironment } from '../../../../../environments/environment'; import { findByPrefixIfUnique } from '../../../../../../util/prefix'; -import { isEnclosingFrame, resolveNodeToStackEnv } from './built-in-stack-env'; +import { isEnclosingFrame, resolveNodeToStackEnv, stackEnvKindOf } from './built-in-stack-env'; +import { StackEnvKind } from '../../../../../environments/default-builtin-config/shared-configs'; import { NodeValue } from '../../../../../eval/resolve/node-value'; import type { RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model'; import { dataflowLogger } from '../../../../../logger'; @@ -223,6 +224,12 @@ function freeEnvirResolution(name: Identifier, nodeId: NodeId, data: return { envirData: { ...data, environment: envState }, envDef, envirNodeId: nodeId }; } +/** The global frame `.GlobalEnv` and `globalenv()` name directly, as in `.GlobalEnv$f <- v`, `undefined` for any other node. */ +export function globalFrameResolution(node: RNode, data: DataflowProcessorInformation): EnvirResolution | undefined { + const envState = stackEnvKindOf(node, data) === StackEnvKind.Global ? resolveNodeToStackEnv(node, data) : undefined; + return envState === undefined ? undefined : stackEnvirResolution(envState, node.info.id, node.lexeme ?? '', data); +} + /** Builds an {@link EnvirResolution} for an environment obtained directly (not via a holder variable), e.g. `globalenv()` / `.GlobalEnv`. */ function stackEnvirResolution(envState: REnvironmentInformation, nodeId: NodeId, lexeme: string, data: DataflowProcessorInformation): EnvirResolution { // no holder variable: envDef is only a carrier for envState/nodeId diff --git a/src/dataflow/internal/process/functions/call/built-in/built-in-for-loop.ts b/src/dataflow/internal/process/functions/call/built-in/built-in-for-loop.ts index 2891e389975..632fd21187a 100644 --- a/src/dataflow/internal/process/functions/call/built-in/built-in-for-loop.ts +++ b/src/dataflow/internal/process/functions/call/built-in/built-in-for-loop.ts @@ -2,7 +2,7 @@ import type { Writable } from 'ts-essentials'; import { hooksUnder } from '../../../../../hooks'; import { RArgument } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-argument'; import { type DataflowProcessorInformation, processDataflowFor } from '../../../../../processor'; -import { type DataflowInformation, ExitPointType, filterOutLoopExitPoints } from '../../../../../info'; +import { DataflowInformation, ExitPointType, filterOutLoopExitPoints } from '../../../../../info'; import { findNonLocalReads, linkCircularRedefinitionsWithinALoop, produceNameSharedIdMap, reapplyLoopExitPoints } from '../../../../linker'; import { processKnownFunctionCall } from '../known-call-handling'; import { guard } from '../../../../../../util/assert'; @@ -20,6 +20,7 @@ import { applyKills, makeKillsMaybe } from '../../../../../environments/apply-ki import { BuiltInProcName } from '../../../../../environments/built-in-proc-name'; import { linkAmbientStateWithinLoop } from './built-in-ambient-state'; import { NodeValue } from '../../../../../eval/resolve/node-value'; +import { CodeBindings } from '../../../../../eval/resolve/code-bindings'; import type { Value } from '../../../../../eval/values/r-value'; import { RLoopConstructs, RNode } from '../../../../../../r-bridge/lang-4.x/ast/model/model'; import type { ResolveInfo } from '../../../../../eval/resolve/alias-tracking'; @@ -39,6 +40,9 @@ function hasElement(value: Value): boolean { return value.type === 'vector' ? Array.isArray(value.elements) && value.elements.length > 0 : ScalarTypes.has(value.type); } +/** a value R iterates over no round: `NULL` and an empty vector */ +const hasNoElement = (value: Value) => value.type === 'null' || value.type === 'vector' && Array.isArray(value.elements) && value.elements.length === 0; + type Against = DataflowProcessorInformation | ResolveInfo; /** whether the node certainly holds a value and every value it may hold satisfies `holds` */ @@ -97,6 +101,8 @@ export function processForLoop( /* resolved before the loop variable is bound, as it may share the name of what the vector reads */ const nonEmpty = iterates(vectorArg, vector.graph, data); + /* a vector with no element in any order of the code (`seq_len(0)`) never runs the body, so nothing in it happens */ + const empty = CodeBindings.inAnyOrder(vectorArg, data.completeAst.idMap, data.ctx) && alwaysHolds(vectorArg, data, hasNoElement); const variable = processDataflowFor(variableArg, data); let headEnvironments = REnvironment.overwrite(vector.environment, variable.environment); /* only the vector's references and entry point are read past this, its graph is not */ @@ -115,7 +121,7 @@ export function processForLoop( } (data as Writable).environment = headEnvironments; - const body = processDataflowFor(bodyArg, data); + const body = empty ? DataflowInformation.initialize(bodyArg.info.id, data) : processDataflowFor(bodyArg, data); const cd = [{ id: name.info.id, when: true }]; const bodyRefs = body.in.concat(body.unknownReferences); applyCdsToAllInGraphButConstants(body.graph, bodyRefs, cd); @@ -148,7 +154,9 @@ export function processForLoop( reapplyLoopExitPoints(body.exitPoints, body.in.concat(body.out, body.unknownReferences), nextGraph); patchFunctionCall({ nextGraph, rootId, name, data, argumentProcessResult: [variable, vector, body], origin: BuiltInProcName.ForLoop }); - nextGraph.addEdge(rootId, body.entryPoint, EdgeType.NonStandardEvaluation); + if(!empty) { + nextGraph.addEdge(rootId, body.entryPoint, EdgeType.NonStandardEvaluation); + } nextGraph.addEdge(name.info.id, vector.entryPoint, EdgeType.Reads); const variableEntry = ControlFlow.entryOf(variable); diff --git a/src/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.ts b/src/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.ts index d9ddcd52c34..999c9a7a0ca 100644 --- a/src/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.ts +++ b/src/dataflow/internal/process/functions/call/built-in/built-in-if-then-else.ts @@ -3,6 +3,7 @@ import { type DataflowProcessorInformation, processDataflowFor } from '../../../ import { FunctionSemantics } from '../../../../../fn/function-semantics'; import { type ControlDependency, type DataflowInformation, type KillReference, withCds } from '../../../../../info'; import { onlyLiterals } from '../../../../../eval/resolve/resolve'; +import { CodeBindings } from '../../../../../eval/resolve/code-bindings'; import { processKnownFunctionCall } from '../known-call-handling'; import { convertFnArguments, patchFunctionCall } from '../common'; import type { RSymbol } from '../../../../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol'; @@ -76,7 +77,9 @@ export function processIfThenElse( /* within a loop, what the condition reads may change after it, for the next iteration */ const mayChange = !onlyLiterals(condArg) && RLoopConstructs.encloses(rootId, data.completeAst.idMap); - const values = mayChange ? undefined : NodeValue.setOf(condArg.info.id, data); + /* as is a condition whose value another order of the top-level expressions (the cells of a notebook) may change */ + const settled = !mayChange && CodeBindings.inAnyOrder(condArg, data.completeAst.idMap, data.ctx); + const values = settled ? NodeValue.setOf(condArg.info.id, data) : undefined; /* `ifelse` and its relatives are ordinary functions, so R evaluates every argument whatever the condition says; only the `if` keyword leaves a branch unevaluated and may therefore be resolved away here. */ const branchesAreLazy = config?.args === undefined; const conditionIsAlways = (value: boolean) => branchesAreLazy && (values?.elements.every(d => d.type === 'logical' && d.value === value) ?? false); diff --git a/src/documentation/wiki-query.ts b/src/documentation/wiki-query.ts index dccb756677d..7163ff647ec 100644 --- a/src/documentation/wiki-query.ts +++ b/src/documentation/wiki-query.ts @@ -1154,8 +1154,9 @@ registerQueryDocumentation('cell-order', { 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. 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. The orders listed run without an error: a cell that lacks what no cell provides (\`y <- x + 1\` where nothing binds \`x\`) runs in none of them, so they end before it. -A cell that surely warns (\`as.numeric("a")\`, \`log(-1)\`, or a function whose body surely does, unless a handler such as \`suppressWarnings\` catches it) fails after a cell that set \`options(warn = 2)\`. -What may not run, as code in a branch or in a loop that may run no round, is not needed for a cell to run, and a removal there (\`if (cond) rm(x)\`) removes nothing for sure; a branch no value can take (\`if (runif(1) > 2)\`) does not run at all. +A cell that surely warns (\`as.numeric("a")\`, \`log(-1)\`, \`rm(x)\` without \`x\`, or a function whose body surely does, unless a handler such as \`suppressWarnings\` catches it) fails after a cell that set \`options(warn = 2)\`. +With knitr, no chunk after one calling \`knitr::knit_exit()\` runs. +What may not run, as code in a branch or in a loop that may run no round, is not needed for a cell to run, and a removal there (\`if (cond) rm(x)\`) removes nothing for sure; a branch no value can take (\`if (runif(1) > 2)\`) and a loop over no element (\`for (i in seq_len(0))\`) do not run at all, as far as the values are the same in every order of the cells (no cell binds \`runif\` or a name the condition reads twice). What runs the cells decides what each cell starts with, which \`runner\` sets: - \`knitr\` (the default for R Markdown, Quarto, and knitr Sweave) knits the document: each chunk starts with a new plot and in the directory of the document, diff --git a/src/notebook/cell-order.ts b/src/notebook/cell-order.ts index 943a8040398..6754746a84c 100644 --- a/src/notebook/cell-order.ts +++ b/src/notebook/cell-order.ts @@ -130,6 +130,8 @@ export interface CellNeed { readonly of?: NodeId /** the cell fails if the session has it, as a cell that surely warns fails once a cell before turned warnings into errors; the providers are the cells that put it there */ readonly absent?: true + /** the need does not count if the session binds any of these, as `rm(x)` warns only without `x` */ + readonly unless?: readonly CellSymbol[] } /** A function definition a value is, or holds as its element `at` (`list(run = function() 1)`). */ @@ -165,8 +167,8 @@ export type CellEffect = EffectPlace & { readonly of?: NodeId } & ( readonly when?: CellSymbol } | { readonly removes: CellSymbol } - /** `rm(list = ls())` removes the names of the global environment, all but those it keeps */ - | { readonly clears: true, readonly except?: readonly BrandedIdentifier[] } + /** `rm(list = ls())` removes the names of the global environment, all but those it keeps and, unless `ls(all.names = TRUE)` lists them, those starting with a dot */ + | { readonly clears: true, readonly except?: readonly BrandedIdentifier[], readonly hidden?: true } /** `load` of a file whose names flowR does not know, or `attach` of what it cannot see into, may bind any name */ | { readonly bindsAny: CellResource.Variable | CellResource.Attached }); @@ -201,6 +203,8 @@ interface CellRead extends CellSymbol { readonly inner?: NodeId /** the cell needs the symbol not to be there, see {@link CellNeed.absent} */ readonly absent?: true + /** see {@link CellNeed.unless} */ + readonly unless?: readonly CellSymbol[] } /** The session between cells: what is bound, by {@link sessionKey}, and to what kind of value, with the function definitions it holds. */ @@ -237,12 +241,14 @@ const opColumns = (o: ColumnOp): readonly string[] => 'add' in o ? [o.add] : 'dr const PlotState = resource(CellResource.State, 'plot'); /** the state of warnings being errors, which `options(warn = 2)` surely puts the session in */ const WarnsAsErrorsState = resource(CellResource.State, AmbientStateName.warnsAsErrorsSurely.slice(1)); -/** the tracked states a setting of the option `warn` writes */ -const WarnLevelWrites = /^option:warn$/; +/** whether the effect sets the option `warn` */ +const setsWarnLevel = (e: CellEffect) => 'binds' in e && e.binds.resource === CellResource.State && e.binds.name === 'option:warn'; const DeviceState = resource(CellResource.State, AmbientStateName.deviceOpener.slice(1)); /** 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 */ const ChunkOptions = { eval: [resource(CellResource.State, 'opts_chunk:eval=FALSE'), NonExecutableEvalValues], error: [resource(CellResource.State, 'opts_chunk:error=TRUE'), ErrorTolerantValues] } as const; type ChunkOption = keyof typeof ChunkOptions; +/** `knitr::knit_exit()` ends knitting after its chunk, so no chunk after it runs, whatever its options say */ +const KnitExitState = resource(CellResource.State, 'knit_exit'); /** the package options of knitr (`opts_knit`) that keep state of a chunk for the next, see {@link RunnerFreshState} */ const KnitOptions: Readonly> = Object.fromEntries(Object.values(RunnerFreshState).flat().flatMap(f => f.keptBy ?? []) .map(o => [o, [resource(CellResource.State, `opts_knit:${o}=TRUE`), ErrorTolerantValues]])); @@ -266,6 +272,22 @@ function trackedState(name: string): string | undefined { return /^(rng|wd)$/.test(bare) || (/^[\w-]+:./.test(bare) && !bare.endsWith(':*') && !bare.startsWith('sink:')) ? bare : undefined; } +/** whether `ls()` lists every name of the global environment, those starting with a dot only with `all.names = TRUE`; `undefined` for any other call listing only some (`ls(pattern = "^a")`) */ +function listsAll(node: RNode | undefined): { readonly hidden: boolean } | undefined { + if(!RFunctionCall.isNamed(node, Identifier.make('ls'))) { + return undefined; + } + const args = node.arguments.map(a => a === EmptyArgument ? undefined : { name: a.name === undefined ? undefined : String(Identifier.getName(a.name.content)), value: valueOf(a) }); + if(!args.every(a => a !== undefined && (a.name === 'sorted' || a.name === 'all.names'))) { + return undefined; + } + const all = args.find(a => a?.name === 'all.names')?.value; + return { hidden: RLogical.is(all) && all.content || RSymbol.is(all) && all.lexeme === 'T' }; +} + +/** whether `rm(list = ls())` removes the name */ +const clearsName = (e: { readonly except?: readonly BrandedIdentifier[], readonly hidden?: true }, name: string) => !e.except?.includes(name) && (e.hidden === true || !name.startsWith('.')); + const lineCount = (code: string) => code.replace(/\n$/, '').split('\n').length; /** a cell whose code starts in the line after the fence `head` and is closed by a fence after it */ const fenced = (head: number, code: string, runner: CellRunner, sets?: readonly string[]): NotebookCell => ({ head, from: head + 1, to: head + lineCount(code), tail: head + lineCount(code) + 1, runner, ...sets?.length ? { sets } : {} }); @@ -715,19 +737,22 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df if(value === undefined) { continue; } - /* `rm(list = setdiff(ls(), "x"))` clears all but the names it keeps, `rm(list = "x")` removes those it names, anything else all */ - if(RFunctionCall.isNamed(value, Identifier.make('setdiff')) && value.arguments[0] !== EmptyArgument && RFunctionCall.isNamed(valueOf(value.arguments[0]), Identifier.make('ls'))) { - remove({ clears: true, except: value.arguments.slice(1).flatMap(a => a === EmptyArgument ? [] : strings(a)) }); + /* `rm(list = setdiff(ls(), "x"))` clears all but the names it keeps, `rm(list = "x")` removes those it names; anything else (`ls(pattern = "^a")`, a variable) may remove only some, so it removes nothing for sure */ + const setdiff = RFunctionCall.isNamed(value, Identifier.make('setdiff')) && value.arguments[0] !== EmptyArgument ? value : undefined; + const listed = listsAll(setdiff === undefined ? value : valueOf(setdiff.arguments[0] as RArgument)); + if(listed !== undefined) { + remove({ clears: true, ...setdiff === undefined ? {} : { except: setdiff.arguments.slice(1).flatMap(a => a === EmptyArgument ? [] : strings(a)) }, ...listed.hidden ? { hidden: true } : {} }); } else if(RString.is(value) || RFunctionCall.isNamed(value, Identifier.make('c')) && value.arguments.every(a => a !== EmptyArgument && RString.is(valueOf(a)))) { strings(value).forEach(name => remove({ removes: resource(CellResource.Variable, name) })); - } else { - remove({ clears: true }); } } } /* `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 */ - for(const [id] of graph.verticesOfType(VertexType.FunctionCall).filter(([id]) => !bodies.has(id) && cells[cellOf(id)]?.runner === CellRunner.Knitr)) { + for(const [id, vertex] of graph.verticesOfType(VertexType.FunctionCall).filter(([id]) => !bodies.has(id) && cells[cellOf(id)]?.runner === CellRunner.Knitr)) { const node = ast.idMap.get(id); + if(Identifier.getName(vertex.name) === 'knit_exit' && (vertex.cds?.length ?? 0) === 0) { + effect(id, { binds: KnitExitState }); + } const fn = RFunctionCall.isUnnamed(node) ? node.calledFunction : undefined; const options = RAccess.isNamed(fn) && RSymbol.is(fn.accessed) && fn.access[0].value?.lexeme === 'set' ? KnitrOptions.get(String(Identifier.getName(fn.accessed.content))) : undefined; if(!RFunctionCall.isUnnamed(node) || options === undefined) { @@ -1232,16 +1257,25 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df /* `options(warn = 2)` turns warnings into errors, any other setting of `warn` (or a restore, `options(op)`) may undo that */ for(const r of raw) { const sure = new Set(r.effects.filter(({ effect: e }) => 'binds' in e && binds(e.binds, WarnsAsErrorsState)).map(e => e.at)); - r.effects = r.effects.flatMap(e => 'binds' in e.effect && e.effect.binds.resource === CellResource.State && WarnLevelWrites.test(e.effect.binds.name) && !sure.has(e.at) + r.effects = r.effects.flatMap(e => setsWarnLevel(e.effect) && !sure.has(e.at) ? [e, { ...e, effect: { removes: WarnsAsErrorsState, ...e.effect.of === undefined ? {} : { of: e.effect.of }, range: e.effect.range, unit: e.effect.unit } }] : [e]); } /* a cell that surely warns fails once warnings are errors, unless it sets `warn` itself before */ const warnInfo = { graph, idMap: ast.idMap, ctx, resolve: resolveInfo }; for(const top of unitOf.keys()) { const c = cellOf(top); - for(const site of c < 0 ? [] : CertainWarnings.sites(top, warnInfo)) { - if(!raw[c].effects.some(({ at, effect: e }) => 'binds' in e && e.binds.resource === CellResource.State && WarnLevelWrites.test(e.binds.name) && before(at, site) < 0)) { - raw[c].reads.push({ ...WarnsAsErrorsState, id: site, call: false, absent: true }); + if(c < 0) { + continue; + } + /* a function the call runs may set `warn` before it warns */ + const setsWarn = (site: NodeId) => raw[c].effects.some(({ at, effect }) => setsWarnLevel(effect) && before(at, site) <= 0); + for(const site of CertainWarnings.sites(top, warnInfo).filter(s => !setsWarn(s))) { + raw[c].reads.push({ ...WarnsAsErrorsState, id: site, call: false, absent: true }); + } + /* `rm(x)` warns unless the session or the cell before binds `x` */ + for(const { id, names } of CertainWarnings.removals(top, warnInfo).filter(r => !setsWarn(r.id))) { + for(const name of names.filter(n => !raw[c].effects.some(({ at, effect: e }) => 'binds' in e && binds(e.binds, variable(n, SymbolKind.Any)) && before(at, id) < 0))) { + raw[c].reads.push({ ...WarnsAsErrorsState, id, call: false, absent: true, unless: [variable(name, SymbolKind.Any)] }); } } } @@ -1325,7 +1359,7 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df 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)))) { const symbol = { resource: use.resource, name: use.name, kind: use.kind }; const anyOf = [symbol, ...use.or ?? []]; - const where = { name: use.name, resource: use.resource, id: use.id, ...placeOf(use.id), ...use.range === undefined ? {} : { range: use.range }, ...use.of === undefined ? {} : { of: use.of }, ...use.absent ? { absent: true } as const : {} }; + const where = { name: use.name, resource: use.resource, id: use.id, ...placeOf(use.id), ...use.range === undefined ? {} : { range: use.range }, ...use.of === undefined ? {} : { of: use.of }, ...use.absent ? { absent: true } as const : {}, ...use.unless === undefined ? {} : { unless: use.unless } }; /* 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 */ /* a call that sets state reads its arguments first (`options(digits = getOption("digits") - 1)`) */ const setBefore = (use.resource !== CellResource.Variable || use.deferred) && raw[i].effects.some(e => 'binds' in e.effect && anyOf.some(s => binds((e.effect as { binds: CellSymbol }).binds, s)) && (use.deferred ? before(e.at, use.id) < 0 : endsBefore(e.at, use.id) @@ -1351,7 +1385,7 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df /* a cell that removes a variable before it reads it (`rm(list = ls()); a + 1`) lacks it whatever ran before */ /* only what a cell binds is in the global environment that `rm` clears, R's own functions are not */ const removedBefore = use.resource === CellResource.Variable && facts.some(o => provides(o, symbol)) && raw[i].effects.some(e => endsBefore(e.at, use.id) - && ('removes' in e.effect && e.effect.removes.name === use.name || 'clears' in e.effect && !e.effect.except?.includes(use.name))); + && ('removes' in e.effect && e.effect.removes.name === use.name || 'clears' in e.effect && clearsName(e.effect, use.name))); if(removedBefore) { /* no symbol of any session satisfies it, and what only asks for it (`exists("x")`) gets the same whatever ran before */ if(use.soft !== true) { @@ -1412,9 +1446,9 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df } /* 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 */ const unbound = !use.call && use.soft !== true && use.deferred !== true && base === undefined && !inFormula(use.id); - const skippers = unbound ? facts.flatMap((o, j) => j !== i && provides(o, ChunkOptions.eval[0]) ? [j] : []) : []; + const skippers = unbound ? facts.flatMap((o, j) => j !== i && (provides(o, ChunkOptions.eval[0]) || provides(o, KnitExitState)) ? [j] : []) : []; if(skippers.length > 0) { - needs.push({ ...where, anyOf: [ChunkOptions.eval[0]], providers: skippers }); + needs.push({ ...where, anyOf: [ChunkOptions.eval[0], KnitExitState], providers: skippers }); continue; } /* 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`) */ @@ -1817,10 +1851,11 @@ function boundBefore(graph: DataflowGraph, def: NodeId, read: NodeId): boolean { } /** 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`). */ -const bindingOf = (session: Session, need: CellNeed) => need.anyOf.flatMap(want => lookups(want).flatMap(r => [ +const bindingOf = (session: Session, need: Pick) => need.anyOf.flatMap(want => lookups(want).flatMap(r => [ sessionKey({ resource: r, name: want.name }), ...want.resource === CellResource.Variable ? [sessionKey({ resource: r, name: AnyName })] : [] ]).filter(key => session.has(key) && matches(want.kind, session.get(key)?.kind ?? SymbolKind.Any)))[0]; -const satisfied = (session: Session, need: CellNeed) => (bindingOf(session, need) !== undefined) !== (need.absent === true); +const satisfied = (session: Session, need: CellNeed) => (bindingOf(session, need) !== undefined) !== (need.absent === true) + || need.unless !== undefined && bindingOf(session, { anyOf: need.unless }) !== undefined; /** the function definitions a cell running in the session calls: those a need that counts is bound to, as the call of the name resolves to whatever it is bound to then */ function liveDefinitions(session: Session, needs: readonly CellNeed[]): ReadonlySet { const live = new Set(); @@ -1836,7 +1871,8 @@ const counts = (live: ReadonlySet) => (n: { readonly of?: NodeId }) => n /** the needs of a cell running in the session: a read of a function body counts only if the cell calls that function */ const liveNeeds = (session: Session, needs: readonly CellNeed[]) => needs.filter(counts(liveDefinitions(session, needs))); /** whether a cell before set the chunk option for the knitted cell, unless its own header sets it */ -const chunkOption = (session: Session, cell: NotebookCell, option: ChunkOption) => cell.runner === CellRunner.Knitr && cell.sets?.includes(option) !== true && session.has(sessionKey(ChunkOptions[option][0])); +const chunkOption = (session: Session, cell: NotebookCell, option: ChunkOption) => cell.runner === CellRunner.Knitr + && (option === 'eval' && session.has(sessionKey(KnitExitState)) || cell.sets?.includes(option) !== true && session.has(sessionKey(ChunkOptions[option][0]))); /** whether knitting goes on after the knitted cell fails, as its options or a cell before say `error = TRUE` */ const continues = (session: Session, cell: NotebookCell) => cell.tolerant === true || chunkOption(session, cell, 'error'); /** 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 */ @@ -1881,7 +1917,7 @@ function run(session: Session, facts: CellFacts, at = -1, by = new Map k.startsWith(`${CellResource.Variable} `) && !e.except?.includes(k.slice(CellResource.Variable.length + 1) as BrandedIdentifier)).toArray()) { + for(const key of session.keys().filter(k => k.startsWith(`${CellResource.Variable} `) && clearsName(e, k.slice(CellResource.Variable.length + 1))).toArray()) { session.delete(key); } } diff --git a/test/functionality/dataflow/environments/built-in-eval.test.ts b/test/functionality/dataflow/environments/built-in-eval.test.ts index 39f3e5e3214..c74e21fb7f4 100644 --- a/test/functionality/dataflow/environments/built-in-eval.test.ts +++ b/test/functionality/dataflow/environments/built-in-eval.test.ts @@ -24,6 +24,7 @@ const FoldedBy: Record = { [BuiltInEvalName.Logical]: [...Object.keys(LogicalOps), '!'], [BuiltInEvalName.StringFn]: Object.keys(StringFns), [BuiltInEvalName.Seq]: [':'], + [BuiltInEvalName.SeqLen]: ['seq_len'], [BuiltInEvalName.Vector]: ['c'], [BuiltInEvalName.Group]: ['(', '{'], [BuiltInEvalName.Get]: Object.keys(GetFns), diff --git a/test/functionality/dataflow/environments/stack-env-access.test.ts b/test/functionality/dataflow/environments/stack-env-access.test.ts index ed26a8fcc25..c899e4bb048 100644 --- a/test/functionality/dataflow/environments/stack-env-access.test.ts +++ b/test/functionality/dataflow/environments/stack-env-access.test.ts @@ -49,6 +49,7 @@ describe('access on stack environments', withTreeSitter(ts => { 'x <- 5\ng <- function() function() 1\nf <- g()\ne <- environment(f)\ne$x', '5@$', []); assertReads('environment(f) of an unknown f is not the current env', ['dollar-access', 'environment-alias'], 'x <- 5\ne <- environment(f)\ne$x', '3@$', []); - assertReads('assignment through the stack env keeps the old definition readable', ['dollar-access', 'search-path'], - 'x <- 5\n.GlobalEnv$x <- 1\nprint(x)', '3@x', ['1@x']); + /* checked in R: `print(x)` prints 1, `.GlobalEnv$x <- 1` binds `x` anew as `x <- 1` does */ + assertReads('assignment through the stack env rebinds the variable', ['dollar-access', 'search-path'], + 'x <- 5\n.GlobalEnv$x <- 1\nprint(x)', '3@x', ['2@x']); })); diff --git a/test/functionality/dataflow/functions/certain-warnings.test.ts b/test/functionality/dataflow/functions/certain-warnings.test.ts index 2cb4579285c..ce0f3743b14 100644 --- a/test/functionality/dataflow/functions/certain-warnings.test.ts +++ b/test/functionality/dataflow/functions/certain-warnings.test.ts @@ -56,13 +56,31 @@ describe('Calls that surely warn', withTreeSitter(parser => { ['g <- function() warning("x"); h <- function() g(); h()', '--W'], ['f <- function() { return(1); warning("x") }; f()', '--'], ['f <- function(v) if (v) warning("x"); f(TRUE)', '--'], - ['log <- function(x) 1; log(-1)', '--'] + ['log <- function(x) 1; log(-1)', '--'], + /* the cells of a notebook run in any order, so what the code binds anywhere may come first */ + ['log(-1); log <- function(x) 1', '--'], + ['mean("a"); mean.character <- function(x, ...) 1', '--'], + ['as.numeric(s); s <- "a"; s <- "1"', '---'], + ['setGeneric("mean"); mean("a")', '--'], + ['library(otel); log(-1)', '--'], + ['lapply("otel", library, character.only = TRUE); log(-1)', '--'], + ['do.call("assign", list("log", function(x) 1)); log(-1)', '--'], + ['as.complex("1+2i")', '-'], + /* `rm(x)` warns only where `x` is not bound, which the code before tells */ + ['rm(x)', '-'] ]; for(const [code, expected] of cases) { test(`${code}: ${expected}`, async() => { assert.strictEqual(await marks(code), expected); }); } + test('the names rm removes, which warn where they are not bound', async() => { + const analyzer = await analyze(parser, 'rm(x, "y"); suppressWarnings(rm(z)); rm(w, envir = e)'); + const ast = await analyzer.normalize(); + const { graph } = await analyzer.dataflow(); + const info = { graph, idMap: ast.idMap, ctx: analyzer.inspectContext(), resolve: Resolve.info(graph, analyzer.inspectContext()) }; + assert.deepStrictEqual(ast.ast.files[0].root.children.map(e => CertainWarnings.removals(e.info.id, info).map(r => r.names)), [[['x', 'y']], [], []]); + }); })); describe('The warnings R gives for the values of arguments', () => { @@ -70,7 +88,7 @@ describe('The warnings R gives for the values of arguments', () => { const coercions: readonly (readonly [string, boolean])[] = [ ['a', true], ['', false], [' 3 ', false], ['1e5', false], ['0x1A', false], ['Inf', false], ['inf', false], ['Infinity', false], ['-inf', false], ['nan', false], ['NaN', false], ['1.5e-3', false], ['0x1p3', false], ['1L', true], ['1,5', true], ['TRUE', true], - ['1d5', true], ['.', true], ['+', true], ['1e', true], ['1p3', true], ['1_000', true], [' ', false] + ['1d5', true], ['.', true], ['+', true], ['1e', true], ['1p3', true], ['1_000', true], [' ', false], ['1+2i', true], ['NA', false] ]; for(const [str, warns] of coercions) { test(`as.numeric(${JSON.stringify(str)}) ${warns ? 'warns' : 'is not sure to warn'}`, () => { @@ -88,5 +106,6 @@ describe('The warnings R gives for the values of arguments', () => { assert.isFalse(warnsFor(RWarnings['factorial'][0], 0)); assert.isFalse(warnsFor(RWarnings['sqrt'][0], Number.NaN)); assert.isFalse(warnsFor(RWarnings['mean'][0], 1)); + assert.isUndefined(RWarnings['as.complex']); }); }); diff --git a/test/functionality/linter/lint-dead-code.test.ts b/test/functionality/linter/lint-dead-code.test.ts index 9b8efb4e235..5ddc2fe16bc 100644 --- a/test/functionality/linter/lint-dead-code.test.ts +++ b/test/functionality/linter/lint-dead-code.test.ts @@ -220,9 +220,8 @@ print(2) { certainty: LintingResultCertainty.Certain, loc: [4, 25, 4, 35], quickFix: [emptied([4, 25, 4, 35])] } ]); assertLinter('a read that may not happen', parser, 'x <- FALSE\ndelayedAssign("y", x <- TRUE)\nif(runif(1) > 0.5) y\nif (x) cat("a") else cat("b")', 'dead-code', []); - assertLinter('without a read nothing is written', parser, 'x <- FALSE\ndelayedAssign("y", x <- TRUE)\nif (x) cat("dead") else cat("live")', 'dead-code', [ - { certainty: LintingResultCertainty.Certain, loc: [3, 8, 3, 18], quickFix: [emptied([3, 8, 3, 18])] } - ]); + /* the promise binds `x` as well, so its value depends on whether and when something reads `y`, which flowR does not fold */ + assertLinter('without a read nothing is written', parser, 'x <- FALSE\ndelayedAssign("y", x <- TRUE)\nif (x) cat("dead") else cat("live")', 'dead-code', []); }); describe('promises leaving the function', () => { @@ -248,7 +247,10 @@ print(2) assertLinter('after infinite while', parser, 'while(TRUE){ foo }; 2', 'dead-code', [ { certainty: LintingResultCertainty.Certain, loc: [1, 21, 1, 21], quickFix: [{ type: 'remove', loc: [1, 21, 1, 21], description: 'Remove the unreachable code' }] } ]); - assertLinter('a stop in a for body that may not run', parser, 'for(i in seq_len(0)) stop("never")\nprint("alive")', 'dead-code', []); + assertLinter('a stop in a for body that never runs', parser, 'for(i in seq_len(0)) stop("never")\nprint("alive")', 'dead-code', [ + { certainty: LintingResultCertainty.Certain, loc: [1, 22, 1, 34], quickFix: [emptied([1, 22, 1, 34])] } + ]); + assertLinter('a stop in a for body that may not run', parser, 'for(i in seq_len(n)) stop("never")\nprint("alive")', 'dead-code', []); assertLinter('a stop in a while body that may not run', parser, 'while(x) stop("never")\nprint("alive")', 'dead-code', []); assertLinter('a return in a for body that may not run', parser, 'f <- function(x) { for(i in x) return(1); 2 }\nprint(f(integer(0)))', 'dead-code', []); }); diff --git a/test/functionality/notebook/cell-order-audit.test.ts b/test/functionality/notebook/cell-order-audit.test.ts index 1345a834c3b..4909104c553 100644 --- a/test/functionality/notebook/cell-order-audit.test.ts +++ b/test/functionality/notebook/cell-order-audit.test.ts @@ -13,14 +13,18 @@ import { CellRunner } from '../../../src/project/plugins/file-plugins/files/cell * (R 4.6, knitr 1.51), once per setting: * - console: all cells in one global environment, with one graphics device and working directory, stopping at the first error; * - knit: `knitr::knit` of the document with the chunks in that order and `error = FALSE`, stopping at the first error. - * flowR must never miss an order or a dead end that runs in R; where it promises more, the case says why (`imprecise`). - * The names say what a case is about: `w` cases turn warnings into errors, `c` cases define or remove under conditions. + * flowR must never miss an order or a dead end that runs in R; where it promises more, the case says why and pins what flowR + * promises instead (`imprecise`), as where R's orders depend on what lies outside of the notebook. + * The names say what a case is about: `w` cases turn warnings into errors, `c` cases define or remove under conditions, + * `k` cases use what knitr does, `e` cases remove names of the global environment. */ -interface Truth { - readonly orders: readonly (readonly number[])[] - readonly deadEnds: readonly (readonly number[])[] - /** why flowR promises orders that fail in R */ - readonly imprecise?: string +interface Orders { + readonly orders: readonly (readonly number[])[] + readonly deadEnds: readonly (readonly number[])[] +} +interface Truth extends Orders { + /** what flowR promises where it promises orders that fail in R, and why */ + readonly imprecise?: Orders & { readonly why: string } } interface AuditCase { readonly name: string @@ -58,11 +62,11 @@ const AuditCases: readonly AuditCase[] = [ console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, { name: '10-setenv', files: { 'nb.Rmd': '```{r}\nSys.setenv(INPUT = "in.csv")\n```\n\ntext\n\n```{r}\nd <- read.csv(Sys.getenv("INPUT"))\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n', 'in.csv': 'a,b\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside, so the need is soft' }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside, so the need is soft' } }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: { why: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside of the notebook, so flowR does not take it as absent', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: { why: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside of the notebook, so flowR does not take it as absent', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, { name: '11-setwd', files: { 'nb.Rmd': '```{r}\nsetwd("sub")\n```\n\ntext\n\n```{r}\nd <- read.csv("in.csv")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n', 'sub/in.csv': 'a,b\n' }, console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: 'knitr resets the directory, so in.csv is read from the directory of the document, which lacks it; flowR does not check the file system' } }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: { why: 'knitr resets the directory, so in.csv is read from the directory of the document, which lacks it; flowR does not take a file the project lacks as absent', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, { name: '12-files', files: { 'nb.Rmd': '```{r}\nwrite.csv(data.frame(a = 1), "out.csv")\n```\n\ntext\n\n```{r}\nd <- read.csv("out.csv")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, @@ -136,8 +140,8 @@ const AuditCases: readonly AuditCase[] = [ console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, { name: 'c05-cond-empty-loop', files: { 'nb.Rmd': '```{r}\nfor (i in seq_len(0)) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: 'the loop over seq_len(0) never runs, so x is never defined; flowR does not know the loop runs no round' }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: 'the loop over seq_len(0) never runs, so x is never defined; flowR does not know the loop runs no round' } }, + console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, + knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, { name: 'c06-cond-while-false-rm', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nwhile (FALSE) rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, @@ -163,8 +167,8 @@ const AuditCases: readonly AuditCase[] = [ console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, { name: 'c14-cond-runif-scaled', files: { 'nb.Rmd': '```{r}\nu <- runif(1, 5, 10)\n```\n\ntext\n\n```{r}\nif (u < 4) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 1]], imprecise: 'u is a draw of another cell, which flowR does not follow into the condition while it analyzes' }, - knit: { orders: [], deadEnds: [[0, 1]], imprecise: 'u is a draw of another cell, which flowR does not follow into the condition while it analyzes' } }, + console: { orders: [], deadEnds: [[0, 1]] }, + knit: { orders: [], deadEnds: [[0, 1]] } }, { name: 'running-example', files: { 'nb.Rmd': '```{r setup}\nlibrary(ggplot2)\ntheme_set(theme_minimal())\n```\n\nLoad the survey.\n\n```{r load}\ndata <- read.csv("survey.csv")\ndata <- na.omit(data)\n```\n\n```{r analysis}\nmodel <- lm(score ~ age, data = data)\nsummary(model)\nggplot(data, aes(age, score)) +\n geom_point() + geom_smooth(method = "lm")\n```\n\n```{r filter}\n# drop participants under 18 (written last)\ndata <- subset(data, age >= 18)\nnrow(data)\n```\n\n```{r cleanup}\nrm(data)\ngc()\n```\n', 'survey.csv': '"age","score"\n18,54\n25,44\n52,62\n49,59\n53,NA\n56,75\n44,63\n21,47\n33,67\n23,64\n68,76\n53,72\n61,65\n53,72\n21,67\n50,65\n15,NA\n42,69\n57,73\n58,65\n18,69\n53,60\n50,68\n22,38\n22,55\n69,80\n67,66\n31,52\n29,65\n38,55\n25,60\n53,52\n35,49\n64,66\n19,47\n53,77\n28,66\n23,51\n24,62\n42,70\n' }, console: { orders: [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 4, 1, 2, 3], [0, 4, 1, 3, 2], [1, 0, 2, 3, 4], [1, 0, 3, 2, 4], [1, 3, 0, 2, 4], [4, 0, 1, 2, 3], [4, 0, 1, 3, 2], [4, 1, 0, 2, 3], [4, 1, 0, 3, 2], [4, 1, 3, 0, 2]], deadEnds: [[0, 1, 2, 4], [0, 1, 3, 4], [0, 1, 4], [1, 0, 2, 4], [1, 0, 3, 4], [1, 0, 4], [1, 3, 0, 4], [1, 3, 4, 0], [1, 4, 0]] }, knit: { orders: [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 4, 1, 2, 3], [0, 4, 1, 3, 2], [1, 0, 2, 3, 4], [1, 0, 3, 2, 4], [1, 3, 0, 2, 4], [4, 0, 1, 2, 3], [4, 0, 1, 3, 2], [4, 1, 0, 2, 3], [4, 1, 0, 3, 2], [4, 1, 3, 0, 2]], deadEnds: [[0, 1, 2, 4], [0, 1, 3, 4], [0, 1, 4], [1, 0, 2, 4], [1, 0, 3, 4], [1, 0, 4], [1, 3, 0, 4], [1, 3, 4, 0], [1, 4, 0]] } }, @@ -221,7 +225,76 @@ const AuditCases: readonly AuditCase[] = [ knit: { orders: [[0, 2, 1], [2, 0, 1]], deadEnds: [[0, 1]] } }, { name: 'w18-warn-gamma', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\ng <- gamma(0)\n```\n\ntext\n\n```{r}\nf <- factorial(0)\n```\n\ntext\n\n' }, console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } } + knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, + { name: 'w26-redef-later', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n\ntext\n\n```{r}\nlog <- function(x) 1\n```\n' }, + console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, + { name: 'w19-s3-method', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nm <- mean("a")\n```\n\ntext\n\n```{r}\nmean.character <- function(x, ...) 1\n```\n' }, + console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell defines a method of mean, so flowR takes no call of mean for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell defines a method of mean, so flowR takes no call of mean for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, + { name: 'w20-warn-reset-in-fn', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nf <- function() { options(warn = 0); log(-1) }\n```\n\ntext\n\n```{r}\nf()\n```\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, + { name: 'w21-string-name', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\noptions("warn" = 0)\n```\n\ntext\n\n```{r}\nw <- as.numeric("a")\n```\n' }, + console: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] }, + knit: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] } }, + { name: 'w22-rm-missing', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nrm(x)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n' }, + console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w23-otel', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nlibrary(otel)\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package the notebook attaches exports log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package the notebook attaches exports log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, + { name: 'w24-complex', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nz <- as.complex("1+2i")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + { name: 'w25-same-cell-redef', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n\ntext\n\n```{r}\nlog <- function(x) 1; l2 <- log(-1)\n```\n' }, + console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, + { name: 'c15-runif-redef', files: { 'nb.Rmd': '```{r}\nif (runif(1) > 2) x <- 1\n```\n\ntext\n\n```{r}\nrunif <- function(n, ...) 5\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, + console: { orders: [[1, 0, 2]], deadEnds: [[0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + knit: { orders: [[1, 0, 2]], deadEnds: [[0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } } }, + { name: 'c16-warn-arg-other-cell', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\ns <- "a"\n```\n\ntext\n\n```{r}\nw <- as.numeric(s)\n```\n\ntext\n\n```{r}\ns <- "1"\n```\n' }, + console: { orders: [[0, 1, 3, 2], [0, 3, 2, 1], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 2, 1], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [[0, 3, 1], [3, 0, 1], [3, 1, 0]], imprecise: { why: 'two cells bind s, so flowR does not know which value as.numeric gets', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [] } }, + knit: { orders: [[0, 1, 3, 2], [0, 3, 2, 1], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 2, 1], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [[0, 3, 1], [3, 0, 1], [3, 1, 0]], imprecise: { why: 'two cells bind s, so flowR does not know which value as.numeric gets', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [] } } }, + { name: 'c17-ifelse-draw', files: { 'nb.Rmd': '```{r}\ny <- ifelse(runif(1) > 2, stop("no"), 1)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n' }, + console: { orders: [[0, 1], [1, 0]], deadEnds: [] }, + knit: { orders: [[0, 1], [1, 0]], deadEnds: [] } }, + { name: 'c18-switch-draw', files: { 'nb.Rmd': '```{r}\nswitch(as.character(rbinom(1, 1, 0.5)), "0" = { x <- 1 }, "1" = { x <- 2 })\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, + console: { orders: [[0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1]], deadEnds: [] } }, + { name: 'c19-runif-redef-fn-arg', files: { 'nb.Rmd': '```{r}\nif (runif(1) > 2) x <- 1\n```\n\ntext\n\n```{r}\nrunif <- function(n, min = 0, max = 1) 5\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\nrm(runif)\n```\n' }, + console: { orders: [[1, 0, 2, 3], [1, 0, 3, 2], [3, 1, 0, 2]], deadEnds: [[0, 1, 3], [0, 3, 1], [1, 3, 0], [3, 0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 3, 0, 2], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2]], deadEnds: [] } }, + knit: { orders: [[1, 0, 2, 3], [1, 0, 3, 2], [3, 1, 0, 2]], deadEnds: [[0, 1, 3], [0, 3, 1], [1, 3, 0], [3, 0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 3, 0, 2], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2]], deadEnds: [] } } }, + { name: 'c20-cond-literal-redef-T', files: { 'nb.Rmd': '```{r}\nif (T) x <- 1\n```\n\ntext\n\n```{r}\nT <- FALSE\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'T read before a cell binds it is TRUE, which flowR does not follow', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + knit: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'T read before a cell binds it is TRUE, which flowR does not follow', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } } }, + { name: 'k01-knit-exit', files: { 'nb.Rmd': '```{r}\nknitr::knit_exit()\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, + { name: 'c21-cond-name-two-cells', files: { 'nb.Rmd': '```{r}\nk <- FALSE\n```\n\ntext\n\n```{r}\nif (k) x <- 1\n```\n\ntext\n\n```{r}\nk <- TRUE\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, + console: { orders: [[0, 2, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [2, 0, 1]], imprecise: { why: 'two cells bind k, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [] } }, + knit: { orders: [[0, 2, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [2, 0, 1]], imprecise: { why: 'two cells bind k, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [] } } }, + { name: 'e01-dot-name-rmall', files: { 'nb.Rmd': '```{r}\n.x <- 1\n```\n\ntext\n\n```{r}\nrm(list = ls())\n```\n\ntext\n\n```{r}\nprint(.x)\n```\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'e02-rm-pattern', files: { 'nb.Rmd': '```{r}\nax <- 1; b <- 2\n```\n\ntext\n\n```{r}\nrm(list = ls(pattern = "^a"))\n```\n\ntext\n\n```{r}\nprint(b)\n```\n\ntext\n\n```{r}\nprint(ax)\n```\n' }, + console: { orders: [[0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1]], imprecise: { why: 'ls(pattern = ...) may list only some names, so flowR takes rm to remove none for sure', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [] } }, + knit: { orders: [[0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1]], imprecise: { why: 'ls(pattern = ...) may list only some names, so flowR takes rm to remove none for sure', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [] } } }, + { name: 'c22-cond-dataset-name', files: { 'nb.Rmd': '```{r}\nif (is.data.frame(iris)) x <- 1\n```\n\ntext\n\n```{r}\niris <- 5\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'iris read before a cell binds it is the data set of R, so flowR does not fold the condition', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + knit: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'iris read before a cell binds it is the data set of R, so flowR does not fold the condition', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } } }, + { name: 'w27-library-through-lapply', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\ninvisible(lapply("otel", library, character.only = TRUE))\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n' }, + console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package attached through lapply may export log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, + knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package attached through lapply may export log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, + { name: 'w28-rm-envir', files: { 'nb.Rmd': '```{r}\ne <- new.env(); assign("x", 1, envir = e)\n```\n\ntext\n\n```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nrm(x, envir = e)\n```\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, + { name: 'e03-globalenv-member-cond', files: { 'nb.Rmd': '```{r}\nu <- runif(1, 5, 10)\n```\n\ntext\n\n```{r}\n.GlobalEnv$u <- 1\n```\n\ntext\n\n```{r}\nif (u < 4) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, + console: { orders: [[0, 1, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [[0, 2, 1], [1, 0, 2]], imprecise: { why: 'two cells bind u, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [] } }, + knit: { orders: [[0, 1, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [[0, 2, 1], [1, 0, 2]], imprecise: { why: 'two cells bind u, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [] } } }, + { name: 'e04-globalenv-member', files: { 'nb.Rmd': '```{r}\n.GlobalEnv$u <- 1\n```\n\ntext\n\n```{r}\nprint(u)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n' }, + console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, + knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, ]; const key = (orders: readonly (readonly number[])[]) => orders.map(o => o.join(',')).sort(); @@ -254,10 +327,11 @@ describe('Notebook cell orders of the audit notebooks against R', withTreeSitter assert.isTrue(runs.some(o => d.every((x, k) => o[k] === x)), `R runs ${d.join(',')} before it gets stuck`); } }); - (truth.imprecise === undefined ? test : test.fails)(`${mode}: the orders and dead ends are those of R${truth.imprecise === undefined ? '' : ` (imprecise: ${truth.imprecise})`}`, async() => { + const expected = truth.imprecise ?? truth; + test(`${mode}: the orders and dead ends are ${truth.imprecise === undefined ? 'those of R' : `more than those of R, as ${truth.imprecise.why}`}`, async() => { const { orders, deadEnds } = await flowr(); - assert.deepStrictEqual(key(orders), key(truth.orders)); - assert.deepStrictEqual(key(deadEnds), key(truth.deadEnds)); + assert.deepStrictEqual(key(orders), key(expected.orders)); + assert.deepStrictEqual(key(deadEnds), key(expected.deadEnds)); }); } }); diff --git a/test/functionality/queries/input-source.test.ts b/test/functionality/queries/input-source.test.ts index eef0bed5435..cff7766bd71 100644 --- a/test/functionality/queries/input-source.test.ts +++ b/test/functionality/queries/input-source.test.ts @@ -490,8 +490,8 @@ describe('Input Source Test', { concurrent: false }, withTreeSitter(parser => { testQuery('a load may rebind a variable', "x <- 'a'\nload('a.rda')\nfoo(x)", q('3@foo'), { '3@foo': [{ id: '3@x', types: [InputType.Constant, InputType.Unknown], trace: InputTraceType.Alias }] }); - testQuery('a field written on an environment may rebind a variable', "x <- 'a'\n.GlobalEnv$x <- readLines('f')\nfoo(x)", q('3@foo'), { - '3@foo': [{ id: '3@x', types: [InputType.Constant, InputType.Unknown], trace: InputTraceType.Alias }] + testQuery('a field written on the global environment rebinds the variable', "x <- 'a'\n.GlobalEnv$x <- readLines('f')\nfoo(x)", q('3@foo'), { + '3@foo': [{ id: '3@x', types: [InputType.File, InputType.Unknown], trace: InputTraceType.Alias }] }); testQuery('the session state is no constant', 'x <- ls()\nfoo(x)', q('2@foo'), { '2@foo': [{ id: '2@x', types: [InputType.Unknown], trace: InputTraceType.Alias }] diff --git a/test/functionality/queries/resolve-value-query.test.ts b/test/functionality/queries/resolve-value-query.test.ts index bf8a3570edd..b27e9480575 100644 --- a/test/functionality/queries/resolve-value-query.test.ts +++ b/test/functionality/queries/resolve-value-query.test.ts @@ -158,6 +158,11 @@ describe('Resolve Value Query', withTreeSitter(parser => { testQuery('a draw equal to a value beyond it', 'x <- rbinom(1, 1, 0.5) == 2', ['1@x'], [[setFrom(ValueLogicalFalse)]]); testQuery('a branch no draw takes defines nothing', 'x <- 0\nif (runif(1) > 2) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0))]]); testQuery('a branch a draw may take may define', 'x <- 0\nif (runif(1) > 0.5) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0), intervalFrom(1, 1))]]); + /* the cells of a notebook may run in any order: a condition folds only on what has the same value in every order */ + testQuery('a draw a name is bound to once', 'u <- runif(1, 5, 10)\nx <- 0\nif (u < 4) x <- 1\ny <- x', ['4@y'], [[setFrom(intervalFrom(0, 0))]]); + testQuery('a draw of a function the code binds as well', 'x <- 0\nif (runif(1) > 2) x <- 1\nrunif <- function(n) 5\ny <- x', ['4@y'], [[setFrom(intervalFrom(0, 0), intervalFrom(1, 1))]]); + testQuery('a name the code binds twice', 'k <- FALSE\nx <- 0\nif (k) x <- 1\nk <- TRUE\ny <- x', ['5@y'], [[setFrom(intervalFrom(0, 0), intervalFrom(1, 1))]]); + testQuery('a loop over no element defines nothing', 'x <- 0\nfor (i in seq_len(0)) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0))]]); }); describe('Bit twiddling', () => { testQuery('within the integers', 'x <- bitwShiftL(1, 3)\nprint(x)', ['2@x'], [[setFrom(intervalFrom(8, 8))]]); From e085795b3b94e82b6228d32a98976f5c045db23e Mon Sep 17 00:00:00 2001 From: Florian Sihler Date: Mon, 30 Nov 2026 13:00:38 +0100 Subject: [PATCH 3/3] feat-fix(notebook): fold run-once bindings - a name has a fixed value if its one assignment runs exactly once: in blocks, under if (TRUE), as top-level <<-, or via assign() without an environment; this restores folding the mutation tests rely on - smaller diff: audit and unit tests as compact tables, certain warnings reuse argument matching and value helpers, seq_len folds through resolveAsSeq, warning and random-draw data as tables --- .../environments/built-in-eval-name.ts | 4 +- src/dataflow/environments/built-in.ts | 3 +- .../default-builtin-config/base-functions.ts | 2 +- .../default-builtin-config/warnings.ts | 53 +-- src/dataflow/eval/resolve/code-bindings.ts | 79 ++-- src/dataflow/eval/resolve/resolve-numbers.ts | 70 +-- .../eval/resolve/resolve-operators.ts | 18 +- src/dataflow/eval/resolve/resolve.ts | 27 +- .../values/intervals/interval-constants.ts | 15 +- src/dataflow/fn/certain-warnings.ts | 167 ++----- src/documentation/wiki-query.ts | 10 +- src/notebook/cell-order.ts | 113 ++--- .../cell-order-query-format.ts | 6 +- src/util/r-base-packages.ts | 5 +- .../environments/built-in-eval.test.ts | 3 +- .../functions/certain-warnings.test.ts | 117 ++--- .../notebook/cell-order-audit.test.ts | 421 +++++------------- .../functionality/notebook/cell-order.test.ts | 185 ++------ .../queries/resolve-value-query.test.ts | 4 +- 19 files changed, 352 insertions(+), 950 deletions(-) diff --git a/src/dataflow/environments/built-in-eval-name.ts b/src/dataflow/environments/built-in-eval-name.ts index 2c2aa9a0cb9..684b6a17166 100644 --- a/src/dataflow/environments/built-in-eval-name.ts +++ b/src/dataflow/environments/built-in-eval-name.ts @@ -2,10 +2,8 @@ export enum BuiltInEvalName { /** `c(...)`, see {@link resolveAsVector} */ Vector = 'eval:vector', - /** the sequence operator `:`, see {@link resolveAsSeq} */ + /** the sequence operator `:` and `seq_len`, see {@link resolveAsSeq} */ Seq = 'eval:seq', - /** `seq_len(n)`, see {@link resolveAsSeqLen} */ - SeqLen = 'eval:seq-len', /** a single random draw (`runif(1)`), folding to the interval of the values it can take, see {@link resolveAsRandomDraw} */ RandomDraw = 'eval:random-draw', /** every numeric operator and function, from `+` to `sqrt`, see {@link resolveAsNumeric} */ diff --git a/src/dataflow/environments/built-in.ts b/src/dataflow/environments/built-in.ts index ff6c55af663..16daea0dfa7 100644 --- a/src/dataflow/environments/built-in.ts +++ b/src/dataflow/environments/built-in.ts @@ -41,7 +41,7 @@ import { Ternary } from '../../util/logic'; import { type REnvironmentInformation, REnvironment } from './environment'; import type { Value } from '../eval/values/r-value'; import type { ResolveInfo } from '../eval/resolve/alias-tracking'; -import { resolveAsElement, resolveAsList, resolveAsSeq, resolveAsSeqLen, resolveAsVector } from '../eval/resolve/resolve'; +import { resolveAsElement, resolveAsList, resolveAsSeq, resolveAsVector } from '../eval/resolve/resolve'; import { resolveAsStringFn } from '../eval/resolve/resolve-strings'; import { resolveAsComparison, resolveAsGroup, resolveAsLogical } from '../eval/resolve/resolve-operators'; import { resolveAsGet } from '../eval/resolve/resolve-get'; @@ -425,7 +425,6 @@ export const BuiltInProcessorMapper = { export const BuiltInEvalHandlerMapper = { [BuiltInEvalName.Vector]: resolveAsVector, [BuiltInEvalName.Seq]: resolveAsSeq, - [BuiltInEvalName.SeqLen]: resolveAsSeqLen, [BuiltInEvalName.Numeric]: resolveAsNumeric, [BuiltInEvalName.RandomDraw]: resolveAsRandomDraw, [BuiltInEvalName.Comparison]: resolveAsComparison, diff --git a/src/dataflow/environments/default-builtin-config/base-functions.ts b/src/dataflow/environments/default-builtin-config/base-functions.ts index 47e2828cda2..66b305a9d7f 100644 --- a/src/dataflow/environments/default-builtin-config/base-functions.ts +++ b/src/dataflow/environments/default-builtin-config/base-functions.ts @@ -146,7 +146,7 @@ export const BaseDefinitions = [ /* indices and index sequences: bounded by the shape of what they are handed, never by its contents */ /* `seq_along(x)` asks `length(x)` and `which.max(x)` asks `xtfrm(x)` */ fn(base('which', 'which.max', 'which.min', 'seq_along'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, tags: [SemanticCallTag.Narrows], dispatches: ['length', 'xtfrm'] }, Primitive), - fn(base('seq_len'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, tags: [SemanticCallTag.Narrows], dispatches: ['length', 'xtfrm'] }, { ...Primitive, evalHandler: BuiltInEvalName.SeqLen }), + fn(base('seq_len'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, tags: [SemanticCallTag.Narrows], dispatches: ['length', 'xtfrm'] }, { ...Primitive, evalHandler: BuiltInEvalName.Seq }), /* `seq` dispatches, so `...` really is all it declares; the named formals belong to `seq.default`/`seq.int` */ fn(base('seq'), BuiltInProcName.DefaultReadAllArgs, { props: CallProp.Pure, sig: sig({ '...': Forced.Value }) }, Primitive), fn(base('scan'), BuiltInProcName.DefaultReadAllArgs, diff --git a/src/dataflow/environments/default-builtin-config/warnings.ts b/src/dataflow/environments/default-builtin-config/warnings.ts index 129674fa45f..e3551560f29 100644 --- a/src/dataflow/environments/default-builtin-config/warnings.ts +++ b/src/dataflow/environments/default-builtin-config/warnings.ts @@ -1,23 +1,6 @@ -/** - * When a call of a function R ships surely signals a warning, by the values of its arguments. Each entry was checked - * with R 4.6: a condition here only ever holds for values that warn, a value it does not hold for may warn or not. - * Under `options(warn = 2)` R turns each of these warnings into an error. - */ -export type WarnsWhen = - /** every call warns, as `warning("x")` does */ - | { readonly always: true } - /** a call without any argument warns, as `max()` answers `-Inf` with a warning */ - | { readonly noArguments: true } - /** a value of the formal (one element of it suffices) is a string R cannot read as a number, as in `as.numeric("a")` */ - | { readonly formal: string, readonly notANumber: true } - /** a value of the formal is a string at all, as `mean("a")` answers `NA` with a warning */ - | { readonly formal: string, readonly aString: true } - /** a finite number of the formal lies outside of the closed range `[from, to]`, as `sqrt(-1)` produces `NaN` with a warning */ - | { readonly formal: string, readonly outside: readonly [from: number, to: number] } - /** a number of the formal is a whole number of at most `wholeAtMost`, where the function has a pole (`gamma(0)`, `factorial(-1)`) */ - | { readonly formal: string, readonly wholeAtMost: number } - /** a name the call removes (`rm(x)`, `rm("x")`) is not bound where it runs, which only the code running before can tell (see `CertainWarnings.removals`) */ - | { readonly removesUnbound: true }; +/** When a call of a function R ships surely signals a warning, by the values of its arguments: always (`warning("x")`), without any argument (`max()`), where a name it removes is not bound (`rm(x)`, which only the code running before can tell), or where a value of the formal (one element suffices) is a string R cannot read as a number (`as.numeric("a")`), a string at all (`mean("a")`), a finite number outside of the closed range `[from, to]` (`sqrt(-1)`), or a whole number of at most `wholeAtMost`, a pole (`gamma(0)`). Each entry was checked with R 4.6: a condition only ever holds for values that warn. Under `options(warn = 2)` R turns each of these warnings into an error. */ +export type WarnsWhen = { readonly always: true } | { readonly noArguments: true } | { readonly removesUnbound: true } + | { readonly formal: string } & ({ readonly notANumber: true } | { readonly aString: true } | { readonly outside: readonly [from: number, to: number] } | { readonly wholeAtMost: number }); /** what R does not read as a number: everything but decimal and hexadecimal numbers, `Inf`, `Infinity`, `NaN`, and `NA` (which warns, but is left out to keep this list exact), around them only white space */ const RNumberSyntax = /^\s*(?:[+-]?(?:(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?|0[xX](?:[0-9a-fA-F]+\.?[0-9a-fA-F]*|\.[0-9a-fA-F]+)(?:[pP][+-]?\d+)?|inf(?:inity)?|nan|na))?\s*$/i; @@ -32,36 +15,24 @@ const Coerces: readonly WarnsWhen[] = [{ formal: 'x', notANumber: true }]; /** beyond it, `as.integer` gives `NA` (a value between it and the largest integer truncates into the range) */ const IntegerBound = 2147483648; -/** - * The functions of R that surely warn for some values of their arguments, by name. Functions not listed may warn as - * well (any closure may call `warning`), they are just never sure to. - */ +/** The functions of R that surely warn for some values of their arguments, by name. Functions not listed may warn as well (any closure may call `warning`), they are just never sure to. */ export const RWarnings: Readonly> = { 'warning': [{ always: true }], 'as.numeric': Coerces, 'as.double': Coerces, - /* `as.complex` is left out: it reads complex numbers (`"1+2i"`), which the syntax above does not cover */ - /* `as.integer(3e9)`: NAs introduced by coercion to integer range */ + /* `as.complex` is left out: it reads complex numbers (`"1+2i"`), which the syntax above does not cover */ /* `as.integer(3e9)`: NAs introduced by coercion to integer range */ 'as.integer': [...Coerces, { formal: 'x', outside: [-IntegerBound, IntegerBound] }], /* NaNs produced */ - 'log': [{ formal: 'x', outside: [0, Infinity] }], - 'log2': [{ formal: 'x', outside: [0, Infinity] }], - 'log10': [{ formal: 'x', outside: [0, Infinity] }], - 'log1p': [{ formal: 'x', outside: [-1, Infinity] }], - 'sqrt': [{ formal: 'x', outside: [0, Infinity] }], - 'asin': [{ formal: 'x', outside: [-1, 1] }], - 'acos': [{ formal: 'x', outside: [-1, 1] }], - 'acosh': [{ formal: 'x', outside: [1, Infinity] }], - 'atanh': [{ formal: 'x', outside: [-1, 1] }], - 'gamma': [{ formal: 'x', wholeAtMost: 0 }], - 'factorial': [{ formal: 'x', wholeAtMost: -1 }], + ...Object.fromEntries([['log', 0, Infinity], ['log2', 0, Infinity], ['log10', 0, Infinity], ['sqrt', 0, Infinity], ['log1p', -1, Infinity], + ['asin', -1, 1], ['acos', -1, 1], ['atanh', -1, 1], ['acosh', 1, Infinity]].map(([f, from, to]) => [f, [{ formal: 'x', outside: [from, to] }]])), + 'gamma': [{ formal: 'x', wholeAtMost: 0 }], + 'factorial': [{ formal: 'x', wholeAtMost: -1 }], /* argument is not numeric or logical: returning NA */ - 'mean': [{ formal: 'x', aString: true }], + 'mean': [{ formal: 'x', aString: true }], /* no non-missing arguments to max; returning -Inf */ - 'max': [{ noArguments: true }], - 'min': [{ noArguments: true }], + 'max': [{ noArguments: true }], 'min': [{ noArguments: true }], /* object 'x' not found */ - 'rm': [{ removesUnbound: true }] + 'rm': [{ removesUnbound: true }] }; /** Whether the scalar `value` of an argument makes `when` hold, `undefined` for a condition on no argument. */ diff --git a/src/dataflow/eval/resolve/code-bindings.ts b/src/dataflow/eval/resolve/code-bindings.ts index 2a7cde5884a..b1c0fce0780 100644 --- a/src/dataflow/eval/resolve/code-bindings.ts +++ b/src/dataflow/eval/resolve/code-bindings.ts @@ -10,6 +10,7 @@ import { RLogical } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-logical'; import { RAccess } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-access'; import { RArgument } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-argument'; import { RExpressionList } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; +import { RIfThenElse } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-if-then-else'; import { RForLoop } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-for-loop'; import { RFunctionDefinition } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-function-definition'; import { EmptyArgument, RFunctionCall } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-function-call'; @@ -19,17 +20,11 @@ import { RandomDraws } from './resolve-numbers'; import { BaseDatasets, BaseValues, baseRExportOwner, isBaseRPackage } from '../../../util/r-base-packages'; /** - * What the code binds, read off its syntax as a whole: a notebook may run its cells in any order, so the value a name - * has where it is read may come from any binding of it, not just from those before in the file. + * What the code binds, read off its syntax as a whole (a notebook runs its cells in any order): for each name the values + * of its bindings (`undefined` but for a plain assignment that runs once), the packages it attaches, and whether it binds + * names flowR cannot tell from its syntax (`load`, `eval(parse(...))`, `attach`, `assign` to a computed name, methods). */ -interface Bindings { - /** for each name the code binds, the value of each binding: the assigned expression for a plain assignment at the top level, `undefined` for any other binding */ - readonly bound: ReadonlyMap - /** the packages the code attaches (or what it hands a call attaching packages, which may name none flowR knows) */ - readonly packages: readonly string[] - /** the code binds names flowR cannot tell from its syntax (`load`, `eval(parse(...))`, `attach`, an `assign` to a computed name, methods it declares) */ - readonly dynamic: boolean -} +type Bindings = { readonly bound: ReadonlyMap, readonly packages: readonly string[], readonly dynamic: boolean }; /** the calls binding names their code does not show, by the processor of their built-in */ const DynamicBinders: ReadonlySet = new Set([BuiltInProcName.Attach, BuiltInProcName.Load, BuiltInProcName.Source, BuiltInProcName.Eval, BuiltInProcName.ListToEnv]); @@ -37,8 +32,8 @@ const DynamicBinders: ReadonlySet = new Set([BuiltInProcName.Attach, Bui const NamedBinders: ReadonlySet = new Set(['assign', 'delayedAssign', 'makeActiveBinding']); /** the calls declaring methods a function may dispatch to, as `setMethod("mean", "character", ...)` does */ const Dispatchers: ReadonlySet = new Set(['setGeneric', 'setMethod', 'setGroupGeneric', 'setReplaceMethod', 'registerS3method', '.S3method']); -const Assignments: ReadonlySet = new Set(['<-', '=', '<<-', ':=']); -const RightAssignments: ReadonlySet = new Set(['->', '->>']); +/** the assignment operators, whether they assign to the right */ +const Assignments: Readonly> = { '<-': false, '=': false, '<<-': false, ':=': false, '->': true, '->>': true }; /** how a call of the function binds names: by attaching packages, by the name its first argument gives, or in a way flowR cannot tell from the code */ function binderKind(name: string, ctx: ReadOnlyFlowrAnalyzerContext): 'library' | 'named' | 'dynamic' | undefined { @@ -50,10 +45,10 @@ function binderKind(name: string, ctx: ReadOnlyFlowrAnalyzerContext): 'library' /** the bindings per id map, along with its size, as the map grows when more code joins the analysis */ const Cache = new WeakMap(); -/** a top-level expression runs once, as no loop, branch, or function encloses it */ -function atTopLevel(node: RNodeWithParent, idMap: AstIdMap): boolean { - for(let at = RNode.directParent(node, idMap); at !== undefined; at = RNode.directParent(at, idMap)) { - if(!RExpressionList.is(at) || at.grouping !== undefined) { +/** whether the node runs exactly once whenever the code runs: only blocks enclose it, or the branch of `if (TRUE)` */ +function runsOnce(node: RNodeWithParent, idMap: AstIdMap): boolean { + for(let child = node, at = RNode.directParent(node, idMap); at !== undefined; child = at, at = RNode.directParent(at, idMap)) { + if(!RExpressionList.is(at) && !(RIfThenElse.is(at) && at.then === child && RLogical.is(at.condition) && at.condition.content)) { return false; } } @@ -76,29 +71,23 @@ function codeBindings(idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext): Bindi return cached; } const bound = new Map(); - const bind = (name: string | undefined, value?: RNodeWithParent) => { - if(name !== undefined) { - bound.set(name, [...bound.get(name) ?? [], value]); - } - }; + const bind = (name: string | undefined, value?: RNodeWithParent) => name === undefined || bound.set(name, [...bound.get(name) ?? [], value]); const packages: string[] = []; let dynamic = false; /* the map may hold a node under more than one id */ for(const node of new Set(idMap.values())) { - if(RBinaryOp.is(node) && (Assignments.has(node.operator) || RightAssignments.has(node.operator))) { - const [target, value] = Assignments.has(node.operator) ? [node.lhs, node.rhs] : [node.rhs, node.lhs]; + if(RBinaryOp.is(node) && Object.hasOwn(Assignments, node.operator)) { + const [target, value] = Assignments[node.operator] ? [node.rhs, node.lhs] : [node.lhs, node.rhs]; const name = nameOf(target); if(name !== undefined) { - bind(name, node.operator !== '<<-' && node.operator !== '->>' && atTopLevel(node, idMap) ? value : undefined); + bind(name, runsOnce(node, idMap) ? value : undefined); } else { /* a replacement changes its target, and an access may bind the member of an environment (`.GlobalEnv$x <- 1`) */ bind(nameOf(rootSymbol(target))); bind(RAccess.is(target) ? nameOf(target.access[0] === EmptyArgument ? undefined : target.access[0]?.value) : undefined); } - } else if(RFunctionDefinition.is(node)) { - node.parameters.forEach(p => bind(String(Identifier.getName(p.name.content)))); - } else if(RForLoop.is(node)) { - bind(String(Identifier.getName(node.variable.content))); + } else if(RFunctionDefinition.is(node) || RForLoop.is(node)) { + (RForLoop.is(node) ? [node.variable] : node.parameters.map(p => p.name)).forEach(v => bind(nameOf(v))); } else if(RFunctionCall.isNamed(node)) { const called = String(Identifier.getName(node.functionName.content)); const kind = binderKind(called, ctx); @@ -111,7 +100,9 @@ function codeBindings(idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext): Bindi } else if(kind === 'named') { const name = RString.is(args[0]?.value) ? args[0].value.content.str : undefined; dynamic ||= name === undefined; - bind(name); + /* `assign("x", v)` with no environment named is `x <- v` */ + const plain = called === 'assign' && args.length === 2 && args[1].name === undefined && runsOnce(node, idMap); + bind(name, plain ? args[1].value : undefined); } dynamic ||= kind === 'dynamic'; } else if(RSymbol.is(node) || RString.is(node)) { @@ -127,45 +118,25 @@ function codeBindings(idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext): Bindi /** whether the node is a single random draw, which the value solver folds to the range of values it can take */ const drawn = (node: RNodeWithParent) => RFunctionCall.isNamed(node) && Object.hasOwn(RandomDraws, Identifier.getName(node.functionName.content)); - /** what R provides under a name the code does not bind (`pi`, `iris`, `c`) */ const providedByR = (name: BrandedIdentifier) => baseRExportOwner(name) !== undefined || BaseDatasets.has(name) || BaseValues.has(name); - /** Whether a package the code attaches may provide the name: one flowR does not know, or one that exports it or a method of it. */ function attachedMayProvide(name: string, { packages }: Bindings, ctx: ReadOnlyFlowrAnalyzerContext): boolean { - return packages.some(p => { - if(isBaseRPackage(p)) { - return false; - } - const pkg = ctx.deps.getDependency(p); - return pkg?.namespaceInfo === undefined || pkg.has(name) || pkg.s3For(name).length > 0; - }); + return packages.filter(p => !isBaseRPackage(p)).map(p => ctx.deps.getDependency(p)).some(pkg => pkg?.namespaceInfo === undefined || pkg.has(name) || pkg.s3For(name).length > 0); } export const CodeBindings = { - /** - * Whether a call of the function R ships under the name runs it in any order of the code: the code binds neither the - * name nor a method of it (`mean.character`), declares no methods, binds nothing flowR cannot see, and attaches no - * package that may provide it. - */ + /** Whether a call of the function R ships under the name runs it in any order of the code: the code binds neither the name nor a method of it (`mean.character`), declares no methods, binds nothing flowR cannot see, and attaches no package that may provide it. */ callsBuiltIn(this: void, name: string, idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext): boolean { const code = codeBindings(idMap, ctx); return !code.dynamic && !code.bound.has(name) && !code.bound.keys().some(b => b.startsWith(`${name}.`)) && !attachedMayProvide(name, code, ctx); }, - /** - * Whether the value of the node is the same in any order the top-level expressions of the code may run in (as the - * cells of a notebook do): it is a literal, an operator or call of a function R ships (see {@link CodeBindings.callsBuiltIn}) - * on such values (`runif(1) > 2`), or a name the code binds once, at the top level, to such a value, which R does not - * provide otherwise. With `names` set to `draws`, a name counts only if it holds a single random draw (`u <- runif(1)`). - * Value resolution may fold such a node while the analysis runs or for code running in another order. - */ + /** Whether the value of the node is the same in any order the top-level expressions of the code may run in (as the cells of a notebook do): it is a literal, an operator or call of a function R ships (see {@link CodeBindings.callsBuiltIn}) on such values (`runif(1) > 2`), or a name the code binds once, at the top level, to such a value, which R does not provide otherwise. With `names` set to `draws`, a name counts only if it holds a single random draw (`u <- runif(1)`). Value resolution may fold such a node while the analysis runs or for code running in another order. */ inAnyOrder(this: void, node: RNodeWithParent | undefined, idMap: AstIdMap, ctx: ReadOnlyFlowrAnalyzerContext, names: 'any' | 'draws' = 'any', seen: ReadonlySet = new Set()): boolean { const inAnyOrder = (n: RNodeWithParent | undefined) => CodeBindings.inAnyOrder(n, idMap, ctx, names, seen); const calls = (name: string) => CodeBindings.callsBuiltIn(name, idMap, ctx); - if(node === undefined) { - return false; - } else if(RNumber.is(node) || RString.is(node) || RLogical.is(node)) { - return true; + if(node === undefined || RNumber.is(node) || RString.is(node) || RLogical.is(node)) { + return node !== undefined; } else if(RExpressionList.is(node)) { return node.grouping !== undefined && node.children.length === 1 && inAnyOrder(node.children[0]); } else if(RBinaryOp.is(node)) { diff --git a/src/dataflow/eval/resolve/resolve-numbers.ts b/src/dataflow/eval/resolve/resolve-numbers.ts index 5a1f9ec155f..a85fffea998 100644 --- a/src/dataflow/eval/resolve/resolve-numbers.ts +++ b/src/dataflow/eval/resolve/resolve-numbers.ts @@ -216,56 +216,30 @@ export function resolveAsNumeric(this: void, args: BuiltInEvalHandlerArgs): Valu /** A bound of the values a draw takes: a number, or the parameter giving it with the default R uses without it. */ -type DrawBound = number | { readonly param: string, readonly default?: number }; - -/** - * The values one random draw of a distribution can take, by the parameters R declares for it (see `?Distributions`). - * Teaching flowR one more is a line here plus the `evalHandler` `eval:random-draw` in the built-in configuration. - */ -export interface RandomDraw { - /** the parameter names, in the order R declares them, the first being the number of draws */ - readonly params: readonly string[] - readonly lower: DrawBound - readonly upper: DrawBound -} - -/** the distributions whose draws flowR bounds, all of them within closed bounds (a draw of `runif` never is one of its bounds) */ -export const RandomDraws = { - runif: { params: ['n', 'min', 'max'], lower: { param: 'min', default: 0 }, upper: { param: 'max', default: 1 } }, - rbeta: { params: ['n', 'shape1', 'shape2', 'ncp'], lower: 0, upper: 1 }, - rbinom: { params: ['n', 'size', 'prob'], lower: 0, upper: { param: 'size' } }, - rpois: { params: ['n', 'lambda'], lower: 0, upper: Infinity }, - rexp: { params: ['n', 'rate'], lower: 0, upper: Infinity }, - rgamma: { params: ['n', 'shape', 'rate', 'scale'], lower: 0, upper: Infinity }, - rchisq: { params: ['n', 'df', 'ncp'], lower: 0, upper: Infinity }, - rgeom: { params: ['n', 'prob'], lower: 0, upper: Infinity }, - rnbinom: { params: ['n', 'size', 'prob', 'mu'], lower: 0, upper: Infinity }, - rweibull: { params: ['n', 'shape', 'scale'], lower: 0, upper: Infinity }, - rlnorm: { params: ['n', 'meanlog', 'sdlog'], lower: 0, upper: Infinity }, - rf: { params: ['n', 'df1', 'df2', 'ncp'], lower: 0, upper: Infinity }, - rsignrank: { params: ['nn', 'n'], lower: 0, upper: Infinity }, - rwilcox: { params: ['nn', 'm', 'n'], lower: 0, upper: Infinity } -} as const satisfies Record; - -/** - * Resolves a single random draw (`runif(1)`, `rbinom(1, 5, 0.5)`) to the interval of the values it can take, so that a - * comparison no draw passes (`runif(1) > 2`) folds. More than one draw, or a bound that does not resolve, stays `Top`. - */ +type DrawBound = number | readonly [param: string, fallback?: number]; +/** The values one draw of each distribution can take, within closed bounds, by the parameters R declares for it (see `?Distributions`), the first being the number of draws. Teaching flowR one more is a line here plus the `evalHandler` `eval:random-draw` in the built-in configuration. */ +export const RandomDraws: Readonly> = { + runif: [['n', 'min', 'max'], ['min', 0], ['max', 1]], + rbeta: [['n', 'shape1', 'shape2', 'ncp'], 0, 1], + rbinom: [['n', 'size', 'prob'], 0, ['size']], + /* the distributions on the non-negative numbers, each with its parameters */ + ...Object.fromEntries([['rpois', 'n', 'lambda'], ['rexp', 'n', 'rate'], ['rgamma', 'n', 'shape', 'rate', 'scale'], ['rchisq', 'n', 'df', 'ncp'], ['rgeom', 'n', 'prob'], + ['rnbinom', 'n', 'size', 'prob', 'mu'], ['rweibull', 'n', 'shape', 'scale'], ['rlnorm', 'n', 'meanlog', 'sdlog'], ['rf', 'n', 'df1', 'df2', 'ncp'], + ['rsignrank', 'nn', 'n'], ['rwilcox', 'nn', 'm', 'n']].map(([f, ...params]) => [f, [params, 0, Infinity] as const])) +}; + +/** Resolves a single random draw (`runif(1)`, `rbinom(1, 5, 0.5)`) to the interval of the values it can take, so that a comparison no draw passes (`runif(1) > 2`) folds. More than one draw, or a bound that does not resolve, stays `Top`. */ export function resolveAsRandomDraw(this: void, args: BuiltInEvalHandlerArgs): Value { const name = calledName(args.node); - const draw = name === undefined ? undefined : RandomDraws[name as keyof typeof RandomDraws] as RandomDraw | undefined; - const nodes = draw === undefined ? undefined : matchCallArguments(args.node, draw.params as BrandedIdentifier[]) as (RNodeWithParent | undefined)[] | undefined; - if(draw === undefined || nodes === undefined || nodes[0] === undefined || numeric(nodes[0], args) !== 1) { + const [params, ...bounds] = (name === undefined ? undefined : RandomDraws[String(name)]) ?? [[] as string[]]; + const nodes = matchCallArguments(args.node, params as BrandedIdentifier[]) as (RNodeWithParent | undefined)[] | undefined; + if(nodes?.[0] === undefined || bounds.length === 0 || numeric(nodes[0], args) !== 1) { return Top; } - const bound = (b: DrawBound): number | undefined => { - if(typeof b === 'number') { - return b; - } - const node = nodes[draw.params.indexOf(b.param)]; - const value = node === undefined ? b.default : numeric(node, args); - return typeof value === 'number' ? value : undefined; - }; - const [lower, upper] = [bound(draw.lower), bound(draw.upper)]; - return lower === undefined || upper === undefined || Number.isNaN(lower) || Number.isNaN(upper) || lower > upper ? Top : intervalFrom(lower, upper); + const [lower, upper] = (bounds as DrawBound[]).map(b => { + const node = typeof b === 'number' ? undefined : nodes[params.indexOf(b[0])]; + const value = typeof b === 'number' ? b : node === undefined ? b[1] : numeric(node, args); + return typeof value === 'number' && !Number.isNaN(value) ? value : undefined; + }); + return lower === undefined || upper === undefined || lower > upper ? Top : intervalFrom(lower, upper); } diff --git a/src/dataflow/eval/resolve/resolve-operators.ts b/src/dataflow/eval/resolve/resolve-operators.ts index 9ff69abd2ed..6f9cb5b8f3a 100644 --- a/src/dataflow/eval/resolve/resolve-operators.ts +++ b/src/dataflow/eval/resolve/resolve-operators.ts @@ -4,7 +4,7 @@ import { type BrandedIdentifier, Identifier } from '../../environments/identifie import { isRNumberValue, unliftRValue } from '../../../util/r-value'; import type { BuiltInEvalHandlerArgs } from '../../environments/built-in'; import { ValueLogicalFalse, ValueLogicalTrue } from '../values/logical/logical-constants'; -import { Top, type Value } from '../values/r-value'; +import { isValue, RValue, Top, type Value } from '../values/r-value'; import { valueSetGuard } from '../values/general'; import { Resolve } from '../../environments/resolve-helper'; import { NodeValue } from './node-value'; @@ -13,7 +13,6 @@ import { RBinaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-binary-o import { RExpressionList } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; import { RUnaryOp } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-unary-op'; import { RNumber } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-number'; -import { intervalBounds } from '../values/intervals/interval-constants'; import { RSymbol } from '../../../r-bridge/lang-4.x/ast/model/nodes/r-symbol'; import { CodeBindings } from './code-bindings'; @@ -86,24 +85,19 @@ export function resolveAsComparison(args: BuiltInEvalHandlerArgs): Value { return logicalValue(bin.op.apply(lhs, rhs)); } -/** the closed range of numbers an operand may hold, a number or a call of a random draw (see `resolveAsRandomDraw`), `undefined` for anything else */ +/** the closed range of numbers an operand may hold: a number, a call (a random draw, see `resolveAsRandomDraw`), or a name with its value in any order of the code (else the rounds of a loop may hold different values of it) */ function rangeOf(node: RNodeWithParent, args: BuiltInEvalHandlerArgs): readonly [number, number] | undefined { - /* a name only where it has its value in any order of the code, else the rounds of a loop may hold different values of it */ if(!RFunctionCall.is(node) && !RNumber.is(node) && !(RSymbol.is(node) && args.idMap !== undefined && CodeBindings.inAnyOrder(node, args.idMap, args.ctx))) { return undefined; } - if(RNumber.is(node)) { - return node.content.complexNumber || Number.isNaN(node.content.num) ? undefined : [node.content.num, node.content.num]; - } /* resolving a node blocks it for the rest of the fold, which still has to resolve it as an operand */ const set = valueSetGuard(Resolve.toValue(node, { ...args, blocked: new Set(args.blocked) })); - return intervalBounds(set?.elements.length === 1 ? set.elements[0] : undefined); + const value = set?.elements.length === 1 && isValue(set.elements[0]) ? set.elements[0] : undefined; + const [lo, hi] = value?.type === 'interval' ? [value.start, value.end].map(RValue.numberOf) : [value, value].map(v => v && RValue.numberOf(v)); + return lo === undefined || hi === undefined || Number.isNaN(lo) || Number.isNaN(hi) ? undefined : [lo, hi]; } -/** - * A comparison of two ranges that holds for every pair of values in them, or for none, as `runif(1) > 2` holds for none. - * The ranges count as closed, which may only leave a comparison undecided; one of two single numbers is left to the plain fold. - */ +/** A comparison of two ranges that holds for every pair of values in them, or for none, as `runif(1) > 2` holds for none. The ranges count as closed, which may only leave a comparison undecided; one of two single numbers is left to the plain fold. */ function compareRanges(op: typeof ComparisonOps[keyof typeof ComparisonOps], lhs: readonly [number, number] | undefined, rhs: readonly [number, number] | undefined): boolean | undefined { if(lhs === undefined || rhs === undefined || (lhs[0] === lhs[1] && rhs[0] === rhs[1])) { return undefined; diff --git a/src/dataflow/eval/resolve/resolve.ts b/src/dataflow/eval/resolve/resolve.ts index 082b0cfb472..08465f6968e 100644 --- a/src/dataflow/eval/resolve/resolve.ts +++ b/src/dataflow/eval/resolve/resolve.ts @@ -210,33 +210,18 @@ export function resolveAsElement(args: BuiltInEvalHandlerArgs): Value { /** Resolves the sequence operator `:` to a {@link ValueVector} of {@link ValueNumber}s; helper of {@link resolveNode}. */ export function resolveAsSeq(args: BuiltInEvalHandlerArgs): ValueVector> | typeof Top { - const operator = args.node; - if(!RBinaryOp.is(operator)) { - return Top; - } - const leftValue = unliftRValue(Resolve.toValue(operator.lhs, args)); - const rightValue = unliftRValue(Resolve.toValue(operator.rhs, args)); - const sequence = isRNumberValue(leftValue) && isRNumberValue(rightValue) ? createNumberSequence(leftValue, rightValue) : undefined; + const node = args.node; + /* `seq_len(n)` is `1:n`, but no number at all for `n = 0` */ + const [lhs, rhs] = RBinaryOp.is(node) ? [node.lhs, node.rhs] : RFunctionCall.is(node) && node.arguments.length === 1 && node.arguments[0] !== EmptyArgument ? [undefined, node.arguments[0].value] : []; + const right = rhs === undefined ? undefined : unliftRValue(Resolve.toValue(rhs, args)); + const left = lhs === undefined ? isRNumberValue(right) && Number.isInteger(right.num) && right.num >= 0 ? { ...right, num: 1 } : undefined : unliftRValue(Resolve.toValue(lhs, args)); + const sequence = isRNumberValue(left) && isRNumberValue(right) && !right.complexNumber ? lhs === undefined && right.num === 0 ? [] : createNumberSequence(left, right) : undefined; return sequence === undefined ? Top : vectorFrom(sequence.map(liftScalar)); } /** How many elements of a sequence are worth naming one by one. */ const MaxSequenceLength = 4096; -/** Resolves `seq_len(n)` to the numbers from 1 to `n`, an empty vector for `n = 0`. */ -export function resolveAsSeqLen(args: BuiltInEvalHandlerArgs): ValueVector> | typeof Top { - const call = args.node; - const [arg, ...rest] = RFunctionCall.is(call) ? call.arguments : []; - if(arg === undefined || arg === EmptyArgument || arg.value === undefined || rest.length > 0) { - return Top; - } - const n = unliftRValue(Resolve.toValue(arg.value, args)); - if(!isRNumberValue(n) || n.complexNumber || !Number.isInteger(n.num) || n.num < 0) { - return Top; - } - const sequence = n.num === 0 ? [] : createNumberSequence({ ...n, num: 1 }, n); - return sequence === undefined ? Top : vectorFrom(sequence.map(liftScalar)); -} /** The elements `from:to` runs over, counting down whenever `to` is the smaller one, and stopping before it would pass `to` (`1:3.5` ends at `3`). */ function createNumberSequence(start: RNumberValue, end: RNumberValue): RNumberValue[] | undefined { diff --git a/src/dataflow/eval/values/intervals/interval-constants.ts b/src/dataflow/eval/values/intervals/interval-constants.ts index 1427bd955e2..624c47ca306 100644 --- a/src/dataflow/eval/values/intervals/interval-constants.ts +++ b/src/dataflow/eval/values/intervals/interval-constants.ts @@ -1,5 +1,5 @@ import type { RNumberValue } from '../../../../r-bridge/lang-4.x/convert-values'; -import { type Lift, type Value, type ValueInterval, type ValueNumber, isBottom, isTop, isValue } from '../r-value'; +import { type Lift, type ValueInterval, type ValueNumber, isBottom, isTop } from '../r-value'; import { getScalarFromInteger, liftScalar } from '../scalar/scalar-constants'; /** @@ -30,16 +30,3 @@ function shiftNum(v: Lift): ValueNumber { export function intervalFromValues(start: Lift, end = start, startInclusive = true, endInclusive = true): ValueInterval { return { type: 'interval', start: shiftNum(start), end: shiftNum(end), startInclusive, endInclusive }; } - -/** The real bounds of an interval value (counting it as closed), `undefined` for any other value and for an unknown, complex, or `NaN` bound. */ -export function intervalBounds(value: Value | undefined): readonly [number, number] | undefined { - if(value === undefined || !isValue(value) || value.type !== 'interval') { - return undefined; - } - const [start, end] = [value.start, value.end]; - if(!isValue(start) || !isValue(end) || !isValue(start.value) || !isValue(end.value) || start.value.complexNumber || end.value.complexNumber) { - return undefined; - } - const [lo, hi] = [start.value.num, end.value.num]; - return Number.isNaN(lo) || Number.isNaN(hi) ? undefined : [lo, hi]; -} diff --git a/src/dataflow/fn/certain-warnings.ts b/src/dataflow/fn/certain-warnings.ts index 32a840efcad..a7abdc898f1 100644 --- a/src/dataflow/fn/certain-warnings.ts +++ b/src/dataflow/fn/certain-warnings.ts @@ -1,7 +1,6 @@ import type { NodeId } from '../../r-bridge/lang-4.x/ast/model/processing/node-id'; import type { AstIdMap, ParentInformation, RNodeWithParent } from '../../r-bridge/lang-4.x/ast/model/processing/decorate'; import type { DataflowGraph } from '../graph/graph'; -import type { ReadOnlyFlowrAnalyzerContext } from '../../project/context/flowr-analyzer-context'; import type { ResolveInfo } from '../eval/resolve/alias-tracking'; import { RNode } from '../../r-bridge/lang-4.x/ast/model/model'; import { RFunctionCall, EmptyArgument } from '../../r-bridge/lang-4.x/ast/model/nodes/r-function-call'; @@ -9,40 +8,28 @@ import { RFunctionDefinition } from '../../r-bridge/lang-4.x/ast/model/nodes/r-f import { RExpressionList } from '../../r-bridge/lang-4.x/ast/model/nodes/r-expression-list'; import { RArgument } from '../../r-bridge/lang-4.x/ast/model/nodes/r-argument'; import { RBinaryOp } from '../../r-bridge/lang-4.x/ast/model/nodes/r-binary-op'; -import { Identifier, ReferenceType } from '../environments/identifier'; import { RSymbol } from '../../r-bridge/lang-4.x/ast/model/nodes/r-symbol'; import { RString } from '../../r-bridge/lang-4.x/ast/model/nodes/r-string'; +import { Identifier, ReferenceType } from '../environments/identifier'; import { Dataflow } from '../graph/df-helper'; import { OriginType } from '../origin/dfg-get-origin'; import { BuiltInProcName } from '../environments/built-in-proc-name'; -import { ArgProp, type FnSig } from '../environments/built-in-props'; +import { ArgProp } from '../environments/built-in-props'; import { NodeValue } from '../eval/resolve/node-value'; -import { isValue, type Value } from '../eval/values/r-value'; -import { intervalBounds } from '../eval/values/intervals/interval-constants'; +import { matchCallArguments } from '../eval/resolve/match-arguments'; +import { isValue, RValue, type Value } from '../eval/values/r-value'; import { RWarnings, warnsFor, type WarnsWhen } from '../environments/default-builtin-config/warnings'; import { isBaseRPackage } from '../../util/r-base-packages'; import { CodeBindings } from '../eval/resolve/code-bindings'; -/** What {@link CertainWarnings} looks at: the finished graph, and where to resolve the values of arguments. */ -export interface CertainWarningsInfo { - readonly graph: DataflowGraph - readonly idMap: AstIdMap - readonly ctx: ReadOnlyFlowrAnalyzerContext - readonly resolve: ResolveInfo -} +/** What {@link CertainWarnings} looks at: the finished graph, and how to resolve the values of arguments. */ +export type CertainWarningsInfo = ResolveInfo & { readonly graph: DataflowGraph, readonly idMap: AstIdMap }; -/** the processors of built-ins that evaluate the arguments they are handed right away, as far as their signature says so */ +/** the processors of built-ins that evaluate their arguments right away (as far as their signature says), and the calls that may stop a body before a warning after them */ const Eager: ReadonlySet = new Set([BuiltInProcName.Default, BuiltInProcName.DefaultReadAllArgs]); - -/** the function calls stopping a body before its end, so that a warning after them need not happen */ const Exits: ReadonlySet = new Set(['return', 'invokeRestart', 'q', 'quit', 'stop', 'on.exit', 'Recall']); -/** - * The calls that surely signal a warning when they run, as `as.numeric("a")` or a call of a function whose body surely - * calls one (see {@link RWarnings}). What it reports is sure: a call may well warn without being reported, as for - * arguments whose value flowR does not know. Whether a handler catches the warning (`suppressWarnings`, `tryCatch`) - * is for {@link CertainWarnings.sites} to say, which only reports what runs eagerly with no handler around it. - */ +/** The calls that surely signal a warning when they run, as `as.numeric("a")` or a call of a function whose body surely calls one (see {@link RWarnings}). A call may well warn without being reported, as for arguments whose value flowR does not know. */ export const CertainWarnings = { name: 'CertainWarnings', /** Whether the call `id` surely signals a warning when it runs (a handler around it aside). */ @@ -56,26 +43,17 @@ export const CertainWarnings = { return (RWarnings[builtin] ?? []).some(w => holds(w, node, info)); } const callees = Dataflow.calleeIdsOf(info.graph, id).map(c => info.idMap.get(c)); - const within = new Set(seen).add(id); - return callees.length > 0 && callees.every(c => RFunctionDefinition.is(c) && bodyWarns(c, info, within)); + return callees.length > 0 && callees.every(c => RFunctionDefinition.is(c) && bodyWarns(c, info, new Set(seen).add(id))); }, - /** - * The calls within `root` (a top-level expression, say) that surely run whenever `root` runs and surely warn: none in a - * branch or loop, in a function definition, in an argument a call may not evaluate (`quote`, a closure's promise), or - * within a construct handling or muffling warnings (`suppressWarnings`, `tryCatch`, `try`, `withCallingHandlers`). - */ + /** The calls within `root` (a top-level expression, say) that surely run whenever `root` runs and surely warn: none in a branch or loop, in a function definition, in an argument a call may not evaluate (`quote`, a closure's promise), or within a construct handling or muffling warnings (`suppressWarnings`, `tryCatch`, `try`, `withCallingHandlers`). */ sites(this: void, root: NodeId, info: CertainWarningsInfo, seen: ReadonlySet = new Set()): NodeId[] { return eagerCalls(root, info).filter(n => CertainWarnings.warns(n.info.id, info, seen)).map(n => n.info.id); }, - /** - * The calls within `root` that run whenever it runs (as for {@link CertainWarnings.sites}) and warn if a name they remove - * is not bound where they run, as `rm(x)` does without `x`, with the names they remove. - */ + /** The calls within `root` that run as {@link CertainWarnings.sites} do and warn where a name they remove is not bound (`rm(x)`), with those names. */ removals(this: void, root: NodeId, info: CertainWarningsInfo): { readonly id: NodeId, readonly names: readonly string[] }[] { return eagerCalls(root, info).flatMap(n => { - const builtin = builtInOf(n.info.id, info); /* a named argument may point the call elsewhere (`envir = e`) or list further names */ - if(builtin === undefined || !RWarnings[builtin]?.some(w => 'removesUnbound' in w) || n.arguments.some(a => a !== EmptyArgument && a.name !== undefined)) { + if(!RWarnings[builtInOf(n.info.id, info) ?? '']?.some(w => 'removesUnbound' in w) || n.arguments.some(a => a !== EmptyArgument && a.name !== undefined)) { return []; } const names = n.arguments.flatMap(a => a !== EmptyArgument && (RSymbol.is(a.value) || RString.is(a.value)) ? [RString.unquote(a.value.lexeme)] : []); @@ -88,63 +66,41 @@ export const CertainWarnings = { function eagerCalls(root: NodeId, info: CertainWarningsInfo): RFunctionCall[] { const top = info.idMap.get(root); const found: RFunctionCall[] = []; - if(top !== undefined) { - RNode.visitAst(top, n => { - if(RFunctionCall.is(n) && runsWith(n, top, info)) { - found.push(n); - } - return RFunctionDefinition.is(n); - }); - } + RNode.visitAst(top, n => { + if(RFunctionCall.is(n) && top !== undefined && runsWith(n, top, info)) { + found.push(n); + } + return RFunctionDefinition.is(n); + }); return found; } -/** the name of the one built-in the call goes to, `undefined` if it may go to a closure or to several built-ins */ +/** the name of the one function of R the call goes to in any order of the code, `undefined` if it may go to a closure, a package, or several */ function builtInOf(id: NodeId, info: CertainWarningsInfo): string | undefined { const origins = Dataflow.origin(info.graph, id) ?? []; - /* what a package other than those of R defines under the name is not what the table states */ const names = new Set(origins.map(o => o.type === OriginType.BuiltInFunctionOrigin && isBaseRPackage(String(Identifier.getNamespace(o.fn.name) ?? 'base')) ? String(Identifier.getName(o.fn.name)) : undefined)); const [name] = names; return names.size === 1 && name !== undefined && origins.every(o => o.type === OriginType.BuiltInFunctionOrigin) && CodeBindings.callsBuiltIn(name, info.idMap, info.ctx) ? name : undefined; } -/** the signature and processor of the built-in of that name */ -function builtInDefinition(name: string, info: CertainWarningsInfo): { readonly sig?: FnSig, readonly processor: string, readonly muffles: boolean } | undefined { - const defs = info.ctx.env.builtInDefinitionsOf(Identifier.make(name)).filter(d => d.type === ReferenceType.BuiltInFunction); - const [def] = defs; - if(defs.length !== 1 || def.type !== ReferenceType.BuiltInFunction) { - return undefined; - } - return { sig: def.config?.sig, processor: def.processorName ?? '', muffles: (def.config?.muffles?.length ?? 0) > 0 }; -} - /** Whether the body of the definition surely warns before it may return, with no branch around the warning. */ function bodyWarns(fn: RFunctionDefinition, info: CertainWarningsInfo, seen: ReadonlySet): boolean { - const statements = RExpressionList.is(fn.body) ? fn.body.children : [fn.body]; - for(const statement of statements) { + for(const statement of RExpressionList.is(fn.body) ? fn.body.children : [fn.body]) { /* a statement that may leave the body may do so before its warning */ - if(mayExit(statement)) { + let exits = false; + RNode.visitAst(statement, n => { + exits ||= RFunctionCall.isNamed(n, Exits); + return exits || RFunctionDefinition.is(n); + }); + if(exits) { return false; - } - if(CertainWarnings.sites(statement.info.id, info, seen).length > 0) { + } else if(CertainWarnings.sites(statement.info.id, info, seen).length > 0) { return true; } } return false; } -function mayExit(node: RNodeWithParent): boolean { - let exits = false; - RNode.visitAst(node, n => { - if(RFunctionDefinition.is(n)) { - return true; - } - exits ||= RFunctionCall.isNamed(n, Exits); - return exits; - }); - return exits; -} - /** Whether the call runs whenever `top` runs: every node between them evaluates it right away, outside of any branch, loop, or handler. */ function runsWith(call: RNodeWithParent, top: RNodeWithParent, info: CertainWarningsInfo): boolean { if((info.graph.getVertex(call.info.id)?.cds?.length ?? 0) > 0) { @@ -168,70 +124,37 @@ function evaluates(parent: RNodeWithParent, child: RNodeWithParent, info: Certai } else if(!RFunctionCall.is(parent) || parent.functionName === child) { return false; } - const name = builtInOf(parent.info.id, info); - const def = name === undefined ? undefined : builtInDefinition(name, info); - if(def === undefined || def.muffles || !Eager.has(def.processor) || def.sig === undefined) { + const defs = info.ctx.env.builtInDefinitionsOf(Identifier.make(builtInOf(parent.info.id, info) ?? '')).filter(d => d.type === ReferenceType.BuiltInFunction); + const def = defs.length === 1 && defs[0].type === ReferenceType.BuiltInFunction ? defs[0] : undefined; + const sig = def?.config?.sig; + if(sig === undefined || (def?.config?.muffles?.length ?? 0) > 0 || !Eager.has(def?.processorName ?? '')) { return false; } - const props = formalOf(parent, child, def.sig); + /* the formal R matches the argument to */ + const value = RArgument.is(child) ? child.value : child; + const props = sig[matchCallArguments(parent, sig.map(([f]) => f))?.findIndex(m => m === value || Array.isArray(m) && m.includes(value)) ?? -1]?.[1]; return props !== undefined && (props & ArgProp.Forced) !== 0 && (props & (ArgProp.Nse | ArgProp.Lazy)) === 0; } -/** what the signature says of the formal the argument `arg` of the call is matched to */ -function formalOf(call: RFunctionCall, arg: RNodeWithParent, sig: FnSig): number | undefined { - const named = RArgument.isNamed(arg) ? Identifier.getName(arg.name.content) : undefined; - if(named !== undefined) { - return (sig.find(([f]) => f === named) ?? sig.find(([f]) => f === '...'))?.[1]; - } - const taken = new Set(call.arguments.flatMap(a => a !== EmptyArgument && a.name !== undefined ? [Identifier.getName(a.name.content)] : [])); - const positional = sig.filter(([f]) => !taken.has(f)); - const index = call.arguments.filter(a => a === EmptyArgument || a.name === undefined).indexOf(arg as RArgument); - const dots = positional.findIndex(([f]) => f === '...'); - return index < 0 ? undefined : (dots >= 0 && index >= dots ? positional[dots] : positional[index])?.[1]; -} - -/** Whether the condition holds for every value the call's arguments may have. */ +/** Whether the condition holds for every value the call's arguments may have, which must be the same in any order of the code. */ function holds(when: WarnsWhen, call: RFunctionCall, info: CertainWarningsInfo): boolean { - if('always' in when) { - return true; - } else if('removesUnbound' in when) { - return false; - } const args = call.arguments.filter(a => a !== EmptyArgument); - if('noArguments' in when) { - return call.arguments.every(a => a === EmptyArgument) && args.length === 0; + if('always' in when || 'removesUnbound' in when) { + return 'always' in when; + } else if('noArguments' in when) { + return call.arguments.length === args.length && args.length === 0; } const arg = args.find(a => a.name !== undefined && Identifier.getName(a.name.content) === when.formal) ?? args.find(a => a.name === undefined); - /* a value another order of the code may change does not surely warn */ - if(!CodeBindings.inAnyOrder(arg?.value, info.idMap, info.ctx)) { - return false; - } - const values = NodeValue.setOf(arg?.value?.info.id, info.resolve)?.elements; + const values = CodeBindings.inAnyOrder(arg?.value, info.idMap, info.ctx) ? NodeValue.setOf(arg?.value?.info.id, info)?.elements : undefined; return values !== undefined && values.length > 0 && values.every(v => scalarsOf(v)?.some(s => warnsFor(when, s)) === true); } /** the strings and numbers a value holds, `undefined` if any element is not known */ function scalarsOf(value: Value): (string | number)[] | undefined { - if(!isValue(value)) { - return undefined; - } - switch(value.type) { - case 'string': - return isValue(value.value) ? [value.value.str] : undefined; - case 'number': - return isValue(value.value) && !value.value.complexNumber ? [value.value.num] : undefined; - case 'interval': { - const bounds = intervalBounds(value); - return bounds !== undefined && bounds[0] === bounds[1] ? [bounds[0]] : undefined; - } - case 'vector': { - if(!isValue(value.elements)) { - return undefined; - } - const all = value.elements.map(scalarsOf); - return all.every(s => s !== undefined) ? all.flat() : undefined; - } - default: - return undefined; + if(value.type === 'vector') { + const all = isValue(value.elements) ? value.elements.map(scalarsOf) : [undefined]; + return all.every(s => s !== undefined) ? all.flat() : undefined; } + const scalar = isValue(value) ? RValue.numberOf(value) ?? RValue.stringOf(value) : undefined; + return scalar === undefined ? undefined : [scalar]; } diff --git a/src/documentation/wiki-query.ts b/src/documentation/wiki-query.ts index 7163ff647ec..832ef023fc6 100644 --- a/src/documentation/wiki-query.ts +++ b/src/documentation/wiki-query.ts @@ -1158,14 +1158,8 @@ A cell that surely warns (\`as.numeric("a")\`, \`log(-1)\`, \`rm(x)\` without \` With knitr, no chunk after one calling \`knitr::knit_exit()\` runs. What may not run, as code in a branch or in a loop that may run no round, is not needed for a cell to run, and a removal there (\`if (cond) rm(x)\`) removes nothing for sure; a branch no value can take (\`if (runif(1) > 2)\`) and a loop over no element (\`for (i in seq_len(0))\`) do not run at all, as far as the values are the same in every order of the cells (no cell binds \`runif\` or a name the condition reads twice). -What runs the cells decides what each cell starts with, which \`runner\` sets: -- \`knitr\` (the default for R Markdown, Quarto, and knitr Sweave) knits the document: each chunk starts with a new plot and in the directory of the document, - so \`abline(h = 1)\` in a chunk after \`plot(1:10)\` fails (unless \`opts_knit$set(global.device = TRUE)\`), and a \`setwd\` holds only for its own chunk. - RStudio runs the chunks of a notebook shown inline the same way. -- \`session\` (the default for \`# %%\` scripts, R console transcripts, and Sweave) runs the cells one after another in one R session, as a console does: - the plot, the graphics device, and the working directory stay from one cell to the next, and knitr evaluates no chunk options. - Ask for it to check the cells of a document someone runs in a console. -- \`jupyter\` runs the cells of a Jupyter notebook, each with a new plot. +What runs the cells decides what each cell starts with, which \`runner\` sets: \`knitr\` (the default for R Markdown, Quarto, and knitr Sweave, as RStudio runs inline chunks) starts each chunk with a new plot and in the directory of the document, so \`abline(h = 1)\` in a chunk after \`plot(1:10)\` fails (unless \`opts_knit$set(global.device = TRUE)\`) and a \`setwd\` holds only for its own chunk; +\`session\` (the default for \`# %%\` scripts, R console transcripts, and Sweave) runs the cells in one R session as a console does, keeping the plot, the graphics device, and the working directory, and evaluates no chunk options; \`jupyter\` starts each cell with a new plot. ${ await showQuery(shell, exampleCode, [{ type: 'cell-order', orders: 3, changed: [1] }]) } diff --git a/src/notebook/cell-order.ts b/src/notebook/cell-order.ts index 6754746a84c..7ac7f417baa 100644 --- a/src/notebook/cell-order.ts +++ b/src/notebook/cell-order.ts @@ -173,17 +173,17 @@ export type CellEffect = EffectPlace & { readonly of?: NodeId } & ( | { readonly bindsAny: CellResource.Variable | CellResource.Attached }); export interface CellFacts { - readonly cell: NotebookCell - readonly needs: readonly CellNeed[] + readonly cell: NotebookCell + readonly needs: readonly CellNeed[] /** what the cell reads and no other cell binds, before it binds it itself (`print(d); d <- 1`) or not at all: no order of the cells helps, but a run of the cell without it fails */ - readonly lacks: readonly CellNeed[] + readonly lacks: readonly CellNeed[] /** what the cell fails with if the session holds it (see {@link CellNeed.absent}), as a warning once a cell before set `options(warn = 2)` */ - readonly forbids?: readonly CellNeed[] - readonly effects: readonly CellEffect[] + readonly bans?: readonly CellNeed[] + readonly effects: readonly CellEffect[] } /** A read of a cell before the reads are resolved to the cells that provide them. */ -interface CellRead extends CellSymbol { +interface CellRead extends CellSymbol, Pick { readonly id: NodeId readonly call: boolean readonly soft?: true @@ -201,10 +201,6 @@ interface CellRead extends CellSymbol { readonly range?: SourceRange /** where in the body of a function the call `id` runs the read is */ readonly inner?: NodeId - /** the cell needs the symbol not to be there, see {@link CellNeed.absent} */ - readonly absent?: true - /** see {@link CellNeed.unless} */ - readonly unless?: readonly CellSymbol[] } /** The session between cells: what is bound, by {@link sessionKey}, and to what kind of value, with the function definitions it holds. */ @@ -241,7 +237,6 @@ const opColumns = (o: ColumnOp): readonly string[] => 'add' in o ? [o.add] : 'dr const PlotState = resource(CellResource.State, 'plot'); /** the state of warnings being errors, which `options(warn = 2)` surely puts the session in */ const WarnsAsErrorsState = resource(CellResource.State, AmbientStateName.warnsAsErrorsSurely.slice(1)); -/** whether the effect sets the option `warn` */ const setsWarnLevel = (e: CellEffect) => 'binds' in e && e.binds.resource === CellResource.State && e.binds.name === 'option:warn'; const DeviceState = resource(CellResource.State, AmbientStateName.deviceOpener.slice(1)); /** 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 */ @@ -272,20 +267,13 @@ function trackedState(name: string): string | undefined { return /^(rng|wd)$/.test(bare) || (/^[\w-]+:./.test(bare) && !bare.endsWith(':*') && !bare.startsWith('sink:')) ? bare : undefined; } -/** whether `ls()` lists every name of the global environment, those starting with a dot only with `all.names = TRUE`; `undefined` for any other call listing only some (`ls(pattern = "^a")`) */ +/** whether `ls()` lists every name of the global environment, those starting with a dot only with `all.names = TRUE`; `undefined` for a call listing only some (`ls(pattern = "^a")`) */ function listsAll(node: RNode | undefined): { readonly hidden: boolean } | undefined { - if(!RFunctionCall.isNamed(node, Identifier.make('ls'))) { - return undefined; - } - const args = node.arguments.map(a => a === EmptyArgument ? undefined : { name: a.name === undefined ? undefined : String(Identifier.getName(a.name.content)), value: valueOf(a) }); - if(!args.every(a => a !== undefined && (a.name === 'sorted' || a.name === 'all.names'))) { - return undefined; - } - const all = args.find(a => a?.name === 'all.names')?.value; - return { hidden: RLogical.is(all) && all.content || RSymbol.is(all) && all.lexeme === 'T' }; + const args = RFunctionCall.isNamed(node, Identifier.make('ls')) ? node.arguments.map(a => a === EmptyArgument ? undefined : a) : [undefined]; + const all = valueOf(args.find(a => a?.name?.content === 'all.names')); + return args.every(a => a?.name !== undefined && ['sorted', 'all.names'].includes(a.name.content)) ? { hidden: RLogical.is(all) ? all.content : all?.lexeme === 'T' } : undefined; } -/** whether `rm(list = ls())` removes the name */ const clearsName = (e: { readonly except?: readonly BrandedIdentifier[], readonly hidden?: true }, name: string) => !e.except?.includes(name) && (e.hidden === true || !name.startsWith('.')); const lineCount = (code: string) => code.replace(/\n$/, '').split('\n').length; @@ -356,11 +344,7 @@ export function analyzeNotebook(analyzer: ReadonlyFlowrAnalysisProvider, cells?: /** a key for each runner to keep the facts of a notebook run by a runner other than its own apart, see {@link analyzeNotebook} */ const RunnerKeys: Readonly> = { [CellRunner.Session]: {}, [CellRunner.Knitr]: {}, [CellRunner.Jupyter]: {} }; -/** - * The cell as `runner` runs it, whatever runs it by its format: a session or Jupyter does not evaluate the chunk options of - * knitr (`eval = cran`) and runs each cell one asks it to. A cell that goes on after an error (`error = TRUE`) still does, as - * flowR reads its code as wrapped in `tryCatch`, which only promises more orders. - */ +/** The cell as `runner` runs it, whatever runs it by its format: a session or Jupyter does not evaluate the chunk options of knitr (`eval = cran`) and runs each cell one asks it to. A cell that goes on after an error (`error = TRUE`) still does, as flowR reads its code as wrapped in `tryCatch`, which only promises more orders. */ export function runAs(cell: NotebookCell, runner: CellRunner): NotebookCell { if(runner === CellRunner.Knitr) { return { ...cell, runner }; @@ -1154,8 +1138,7 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df } } } - /* a file read is a hard need where the project does not have the file, so only the cell writing it can make it; a relative path is - * where the notebook is, as knitr, RStudio, and a session started there read it (not where flowR runs) */ + /* a file read is a hard need where the project does not have the file, so only the cell writing it can make it; a relative path is where the notebook is, as knitr, RStudio, and a session started there read it (not where flowR runs) */ const present = (read: string, at: NodeId) => { const file = ast.idMap.get(at)?.info.file; return ctx.files.hasFile(read) || file !== undefined && ctx.files.hasFile(RPath.join(RPath.dirname(file), read)); @@ -1166,7 +1149,6 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df const detached = new Map(); /* what each cell does to the global state, through the functions it calls as well, where flowR knows it: a body does it where a call runs the function, as it is bound then */ let functions: ReadonlyMap | undefined; - /* the removals of the plot by closing the active device, by cell */ const activeCloses: [number, (typeof raw)[number]['effects'][number]][] = []; for(const [c, scope] of scopes.entries()) { const into = (e: CellEffect, at: NodeId, inner?: NodeId) => raw[c].effects.push({ inner, ...placed(at, e) }); @@ -1249,57 +1231,38 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df } } - /* a removal that may not happen (`if (cond) rm(x)`, in a loop or a branch) may leave what it removes, so it removes nothing for sure */ + /* a removal that may not happen (`if (cond) rm(x)`, in a loop or a branch) may leave what it removes, so it removes nothing for sure; `options(warn = 2)` turns warnings into errors, any other setting of `warn` (or a restore, `options(op)`) may undo that */ const conditional = (id: NodeId | undefined) => id !== undefined && (graph.getVertex(id)?.cds?.length ?? 0) > 0; for(const r of raw) { r.effects = r.effects.filter(({ at, inner, effect: e }) => !('removes' in e || 'clears' in e || 'binds' in e && binds(e.binds, WarnsAsErrorsState)) || !conditional(at) && !conditional(inner)); - } - /* `options(warn = 2)` turns warnings into errors, any other setting of `warn` (or a restore, `options(op)`) may undo that */ - for(const r of raw) { const sure = new Set(r.effects.filter(({ effect: e }) => 'binds' in e && binds(e.binds, WarnsAsErrorsState)).map(e => e.at)); r.effects = r.effects.flatMap(e => setsWarnLevel(e.effect) && !sure.has(e.at) ? [e, { ...e, effect: { removes: WarnsAsErrorsState, ...e.effect.of === undefined ? {} : { of: e.effect.of }, range: e.effect.range, unit: e.effect.unit } }] : [e]); } - /* a cell that surely warns fails once warnings are errors, unless it sets `warn` itself before */ - const warnInfo = { graph, idMap: ast.idMap, ctx, resolve: resolveInfo }; - for(const top of unitOf.keys()) { - const c = cellOf(top); - if(c < 0) { - continue; - } - /* a function the call runs may set `warn` before it warns */ - const setsWarn = (site: NodeId) => raw[c].effects.some(({ at, effect }) => setsWarnLevel(effect) && before(at, site) <= 0); - for(const site of CertainWarnings.sites(top, warnInfo).filter(s => !setsWarn(s))) { - raw[c].reads.push({ ...WarnsAsErrorsState, id: site, call: false, absent: true }); - } - /* `rm(x)` warns unless the session or the cell before binds `x` */ - for(const { id, names } of CertainWarnings.removals(top, warnInfo).filter(r => !setsWarn(r.id))) { - for(const name of names.filter(n => !raw[c].effects.some(({ at, effect: e }) => 'binds' in e && binds(e.binds, variable(n, SymbolKind.Any)) && before(at, id) < 0))) { - raw[c].reads.push({ ...WarnsAsErrorsState, id, call: false, absent: true, unless: [variable(name, SymbolKind.Any)] }); + /* a cell that surely warns (or removes a name it lacks, `rm(x)`) fails once warnings are errors, unless it (or a function it calls) sets `warn` itself before */ + for(const top of unitOf.keys().filter(t => cellOf(t) >= 0)) { + const { effects, reads } = raw[cellOf(top)]; + const forbid = (id: NodeId, unless?: string) => { + if(!effects.some(({ at, effect }) => setsWarnLevel(effect) && before(at, id) <= 0)) { + reads.push({ ...WarnsAsErrorsState, id, call: false, absent: true, ...unless === undefined ? {} : { unless: [variable(unless, SymbolKind.Any)] } }); } - } + }; + CertainWarnings.sites(top, resolveInfo).forEach(site => forbid(site)); + CertainWarnings.removals(top, resolveInfo).forEach(({ id, names }) => names + .filter(n => !effects.some(({ at, effect: e }) => 'binds' in e && binds(e.binds, variable(n, SymbolKind.Any)) && before(at, id) < 0)).forEach(n => forbid(id, n))); } /* whether R may skip the node: it is in a branch, the body of a loop that may not run once, or the right side of `&&` or `||` (a promise or a default aside, which the call decides) */ const mayBeSkipped = (id: NodeId | undefined) => id !== undefined && (graph.getVertex(id)?.cds ?? []).some(cd => { - if(cd.byPromise) { - return false; - } const node = ast.idMap.get(cd.id); const around = [node, node === undefined ? undefined : RNode.directParent(node, ast.idMap)]; - if(around.some(n => RRepeatLoop.is(n))) { - return false; - } const loop = around.find(RForLoop.is); - return loop === undefined || !runsOnce(loop.info.id); + return !cd.byPromise && !around.some(n => RRepeatLoop.is(n)) && (loop === undefined || !runsOnce(loop.info.id)); }); + /* closing the active device (`dev.off()`) makes the device opened before it active again, with its plot, so where another cell opens a device (`pdf(NULL)`) the plot may stay */ - for(const [c, effect] of activeCloses) { - if(raw.some((r, j) => j !== c && r.effects.some(e => 'binds' in e.effect && e.effect.binds.resource === CellResource.State && e.effect.binds.name === DeviceState.name))) { - const at = raw[c].effects.indexOf(effect); - if(at >= 0) { - raw[c].effects.splice(at, 1); - } - } + const opensDevice = (j: number) => raw[j].effects.some(e => 'binds' in e.effect && e.effect.binds.resource === CellResource.State && e.effect.binds.name === DeviceState.name); + for(const [c, effect] of activeCloses.filter(([c]) => raw.some((_, j) => j !== c && opensDevice(j)))) { + raw[c].effects = raw[c].effects.filter(e => e !== effect); } /* `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 */ const attaches = graph.verticesOfType(VertexType.FunctionCall).filter(([id, v]) => DfgVertex.hasOrigin(v, BuiltInProcName.Attach) && !bodies.has(id)).map(([id]) => id).toArray().sort(before); @@ -1347,8 +1310,7 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df const lacks = f.lacks as CellNeed[]; /* 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 */ const same = (a: CellRead, b: CellRead) => a.resource === b.resource && a.name === b.name && a.soft === b.soft && a.of === b.of && a.column === b.column && a.data === b.data; - /* a column the data mask of a package's function reads (`filter(mtcars, mpg > 20)` of dplyr) needs that package where R has a function of that name too (`stats::filter`), which evaluates it as is */ - /* a read that may not run (`if (cond) print(x)`, in a loop) need not be satisfied for the cell to run: R may skip it */ + /* a column the data mask of a package's function reads (`filter(mtcars, mpg > 20)` of dplyr) needs that package where R has a function of that name too (`stats::filter`), which evaluates it as is */ /* a read that may not run (`if (cond) print(x)`, in a loop) need not be satisfied for the cell to run: R may skip it */ const reads = raw[i].reads.map(u => u.soft !== true && (mayBeSkipped(u.id) || mayBeSkipped(u.inner)) ? { ...u, soft: true } as const : u).flatMap(u => { if(u.resource !== CellResource.Variable || u.call || !inData(u.id, u.name)) { return [u]; @@ -1474,8 +1436,7 @@ export function cellFacts(cells: readonly NotebookCell[], ast: NormalizedAst, df if(f.cell.maybe) { needs.forEach((n, k) => needs[k] = optionReads.has(n.id) ? n : { ...n, soft: true }); } - /* what the cell fails with is no need of what other cells provide */ - (f as { forbids?: readonly CellNeed[] }).forbids = needs.filter(n => n.absent); + (f as { bans?: readonly CellNeed[] }).bans = needs.filter(n => n.absent); (f as { needs: readonly CellNeed[] }).needs = needs.filter(n => !n.absent); } /* 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 */ @@ -1877,7 +1838,7 @@ const chunkOption = (session: Session, cell: NotebookCell, option: ChunkOption) const continues = (session: Session, cell: NotebookCell) => cell.tolerant === true || chunkOption(session, cell, 'error'); /** 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 */ function missingIn(session: Session, facts: CellFacts, withLacks = false): CellNeed[] { - const missing = chunkOption(session, facts.cell, 'eval') ? [] : liveNeeds(session, [...facts.needs, ...facts.forbids ?? [], ...withLacks ? facts.lacks : []]).filter(n => !satisfied(session, n)); + const missing = chunkOption(session, facts.cell, 'eval') ? [] : liveNeeds(session, [...facts.needs, ...facts.bans ?? [], ...withLacks ? facts.lacks : []]).filter(n => !satisfied(session, n)); return continues(session, facts.cell) ? missing.map(n => ({ ...n, soft: true })) : missing; } @@ -1893,7 +1854,7 @@ function run(session: Session, facts: CellFacts, at = -1, by = new Map sessionKey(option)).filter(k => session.has(k)).map(k => [k, AnyValue])); - const needs = [...facts.needs, ...facts.lacks, ...facts.forbids ?? []]; + const needs = [...facts.needs, ...facts.lacks, ...facts.bans ?? []]; const live = counts(liveDefinitions(session, needs)); const failing = needs.filter(live).filter(n => !n.soft && n.range !== undefined && !satisfied(session, n)); const tolerant = continues(session, facts.cell); @@ -1946,12 +1907,7 @@ export function checkOrder(facts: readonly CellFacts[], order: readonly CellInde }); } -/** - * Every order in which the cells run without missing anything, each running as many cells as it can, cells earlier in the - * notebook first. An order that ends before all cells ran left the others unable to run (e.g., after an `rm`). - * With `withLacks`, a cell that lacks what no order provides (see {@link CellFacts#lacks}) does not run either, so that every order - * listed runs without an error; without, the orders are those that run as far as the order of the cells is concerned, as a reordering asks. - */ +/** Every order in which the cells run without missing anything, each running as many cells as it can, cells earlier in the notebook first. An order that ends before all cells ran left the others unable to run (e.g., after an `rm`). With `withLacks`, a cell that lacks what no order provides (see {@link CellFacts#lacks}) does not run either, so that every order listed runs without an error; without, the orders are those that run as far as the order of the cells is concerned, as a reordering asks. */ export function* workingOrders(facts: readonly CellFacts[], withLacks = false): Generator { const order: CellIndex[] = []; function* extend(session: Session): Generator { @@ -2135,7 +2091,7 @@ export function runStates(facts: readonly CellFacts[], runs: readonly CellIndex[ const by = new Map(); const replayed = runs.map((c, at) => { /* the session also lacks what only the cell itself binds, after it reads it */ - const needs = [...facts[c].needs, ...facts[c].lacks, ...facts[c].forbids ?? []]; + const needs = [...facts[c].needs, ...facts[c].lacks, ...facts[c].bans ?? []]; const missing = liveNeeds(session, needs).filter(n => !n.soft && !satisfied(session, n)); const used = new Map(facts[c].needs.map(n => [n, by.get(bindingOf(session, n) ?? '') ?? -1])); run(session, facts[c], at, by); @@ -2218,7 +2174,6 @@ export function describeRunStates(facts: readonly CellFacts[], states: readonly /** What a cell failing in an order lacks and which cells provide it, `undefined` if it only reads global state another cell sets. */ export function describeFailure(failure: OrderFailure, name: CellNamer = byNumber): string | undefined { - /* a warning that a cell before turned into an error */ const errs = uniqueArray(failure.missing.filter(m => !m.soft && m.absent).flatMap(m => m.providers)); if(errs.length > 0) { return `${name(failure.cell)} warns, which ${listed(errs, name)} turned into an error with options(warn = 2)`; diff --git a/src/queries/catalog/cell-order-query/cell-order-query-format.ts b/src/queries/catalog/cell-order-query/cell-order-query-format.ts index dd9020f1b9b..7212b21d6a5 100644 --- a/src/queries/catalog/cell-order-query/cell-order-query-format.ts +++ b/src/queries/catalog/cell-order-query/cell-order-query-format.ts @@ -31,11 +31,7 @@ export interface CellOrderQuery extends BaseQueryFormat { readonly files?: boolean | 'every'; /** what to call the cells, to have the answer in words as well */ readonly names?: readonly string[]; - /** - * what runs the cells, which decides the state each cell starts afresh with (see `RunnerFreshState`): `knitr` (as knitting the document), - * `session` (one R session or console running cell after cell, keeping the plot and the working directory), or `jupyter`. - * By default the runner of the format: knitr for R Markdown, Quarto, and knitr Sweave, a session for `# %%` scripts, console transcripts, and Sweave. - */ + /** what runs the cells, which decides the state each cell starts afresh with (see `RunnerFreshState`): `knitr` (as knitting the document), `session` (one R session or console running cell after cell, keeping the plot and the working directory), or `jupyter`. By default the runner of the format: knitr for R Markdown, Quarto, and knitr Sweave, a session for `# %%` scripts, console transcripts, and Sweave. */ readonly runner?: `${CellRunner}`; } diff --git a/src/util/r-base-packages.ts b/src/util/r-base-packages.ts index 49b5efbe5cb..c392969c20f 100644 --- a/src/util/r-base-packages.ts +++ b/src/util/r-base-packages.ts @@ -79,10 +79,7 @@ export function attachedBasePackages(rVersion?: string): readonly BrandedNamespa /** the base export to owning-package map, materialised once from the grouped store (never per lookup) */ let exportOwners: Map | undefined; -/** - * Syntax of R that flowR reads as a call of its own name although R exports no function of that name: the native pipe - * `x |> f()`, which the R parser turns into `f(x)`. R itself provides it, whatever is attached. - */ +/** Syntax of R that flowR reads as a call of its own name although R exports no function of that name: the native pipe `x |> f()`, which the R parser turns into `f(x)`. R itself provides it, whatever is attached. */ const RSyntaxCalls: ReadonlySet = new Set(['|>'] as BrandedIdentifier[]); /** whether `name` is a base primitive or internal that the sigdb export lists do not carry, or syntax R reads as a call (`|>`) */ diff --git a/test/functionality/dataflow/environments/built-in-eval.test.ts b/test/functionality/dataflow/environments/built-in-eval.test.ts index c74e21fb7f4..5cb2c9d16b3 100644 --- a/test/functionality/dataflow/environments/built-in-eval.test.ts +++ b/test/functionality/dataflow/environments/built-in-eval.test.ts @@ -23,8 +23,7 @@ const FoldedBy: Record = { /* `!` is the unary case the handler covers besides the binary operators */ [BuiltInEvalName.Logical]: [...Object.keys(LogicalOps), '!'], [BuiltInEvalName.StringFn]: Object.keys(StringFns), - [BuiltInEvalName.Seq]: [':'], - [BuiltInEvalName.SeqLen]: ['seq_len'], + [BuiltInEvalName.Seq]: [':', 'seq_len'], [BuiltInEvalName.Vector]: ['c'], [BuiltInEvalName.Group]: ['(', '{'], [BuiltInEvalName.Get]: Object.keys(GetFns), diff --git a/test/functionality/dataflow/functions/certain-warnings.test.ts b/test/functionality/dataflow/functions/certain-warnings.test.ts index ce0f3743b14..bc9a8e91588 100644 --- a/test/functionality/dataflow/functions/certain-warnings.test.ts +++ b/test/functionality/dataflow/functions/certain-warnings.test.ts @@ -3,109 +3,48 @@ import { withTreeSitter } from '../../_helper/shell'; import { analyze } from '../../_helper/analyzer'; import { CertainWarnings } from '../../../../src/dataflow/fn/certain-warnings'; import { Resolve } from '../../../../src/dataflow/environments/resolve-helper'; -import { notANumber, RWarnings, warnsFor } from '../../../../src/dataflow/environments/default-builtin-config/warnings'; -/* - * Every expectation was checked with R 4.6 (`withCallingHandlers(expr, warning = ...)`): a top-level expression marked - * `W` warns whenever it runs. One marked `-` may or may not warn; what matters is that it is never reported as sure. - */ +/* Every expectation was checked with R 4.6 (`withCallingHandlers(expr, warning = ...)`): a top-level expression marked `W` warns whenever it runs. One marked `-` may or may not warn; what matters is that it is never reported as sure. */ describe('Calls that surely warn', withTreeSitter(parser => { - /** whether each top-level expression of the code surely warns, `W` if so and `-` otherwise */ - async function marks(code: string): Promise { + async function infoOf(code: string) { const analyzer = await analyze(parser, code); const ast = await analyzer.normalize(); const { graph } = await analyzer.dataflow(); - const info = { graph, idMap: ast.idMap, ctx: analyzer.inspectContext(), resolve: Resolve.info(graph, analyzer.inspectContext()) }; - return ast.ast.files[0].root.children.map(e => CertainWarnings.sites(e.info.id, info).length > 0 ? 'W' : '-').join(''); + return { tops: ast.ast.files[0].root.children, info: { ...Resolve.info(graph, analyzer.inspectContext()), graph, idMap: ast.idMap } }; } - const cases: readonly (readonly [string, string])[] = [ - ['as.numeric("a")', 'W'], - ['x <- as.numeric("a")', 'W'], - ['as.numeric("1")', '-'], - ['as.numeric("")', '-'], - ['as.integer(3e9)', 'W'], - ['as.integer("2.7")', '-'], - ['log(-1)', 'W'], - ['log(0)', '-'], - ['sqrt(c(1, -1))', 'W'], - ['acos(2)', 'W'], - ['gamma(0)', 'W'], - ['factorial(0)', '-'], - ['mean("a")', 'W'], - ['max()', 'W'], - ['max(1, 2)', '-'], - ['warning("w")', 'W'], - ['print(log(-1))', 'W'], - ['invisible(as.numeric("a"))', 'W'], - ['v <- "a"; as.numeric(v)', '-W'], - ['x <- c(1, -1); sqrt(x)', '-W'], + const cases: Readonly> = { + 'as.numeric("a")': 'W', 'x <- as.numeric("a")': 'W', 'as.numeric("1")': '-', 'as.numeric("")': '-', 'as.integer(3e9)': 'W', 'as.integer("2.7")': '-', + 'log(-1)': 'W', 'log(0)': '-', 'sqrt(c(1, -1))': 'W', 'acos(2)': 'W', 'gamma(0)': 'W', 'factorial(0)': '-', 'mean("a")': 'W', 'max()': 'W', 'max(1, 2)': '-', + 'warning("w")': 'W', 'print(log(-1))': 'W', 'invisible(as.numeric("a"))': 'W', 'v <- "a"; as.numeric(v)': '-W', 'x <- c(1, -1); sqrt(x)': '-W', /* handlers and constructs that catch or muffle the warning */ - ['suppressWarnings(as.numeric("a"))', '-'], - ['tryCatch(as.numeric("a"), warning = function(w) 1)', '-'], - ['try(log(-1))', '-'], - ['withCallingHandlers(log(-1), warning = function(w) invokeRestart("muffleWarning"))', '-'], + 'suppressWarnings(as.numeric("a"))': '-', 'tryCatch(as.numeric("a"), warning = function(w) 1)': '-', 'try(log(-1))': '-', + 'withCallingHandlers(log(-1), warning = function(w) invokeRestart("muffleWarning"))': '-', /* code that may not run */ - ['if (u) sqrt(-1)', '-'], - ['for (i in seq_len(n)) log(-1)', '-'], - ['quote(log(-1))', '-'], - ['f <- function() log(-1)', '-'], - ['f <- function(x) 1; f(as.numeric("a"))', '--'], - ['sapply(1, function(i) log(-1))', '-'], + 'if (u) sqrt(-1)': '-', 'for (i in seq_len(n)) log(-1)': '-', 'quote(log(-1))': '-', 'f <- function() log(-1)': '-', + 'f <- function(x) 1; f(as.numeric("a"))': '--', 'sapply(1, function(i) log(-1))': '-', /* functions of the program */ - ['f <- function() as.numeric("a"); f()', '-W'], - ['g <- function() warning("x"); h <- function() g(); h()', '--W'], - ['f <- function() { return(1); warning("x") }; f()', '--'], - ['f <- function(v) if (v) warning("x"); f(TRUE)', '--'], - ['log <- function(x) 1; log(-1)', '--'], + 'f <- function() as.numeric("a"); f()': '-W', 'g <- function() warning("x"); h <- function() g(); h()': '--W', + 'f <- function() { return(1); warning("x") }; f()': '--', 'f <- function(v) if (v) warning("x"); f(TRUE)': '--', 'log <- function(x) 1; log(-1)': '--', /* the cells of a notebook run in any order, so what the code binds anywhere may come first */ - ['log(-1); log <- function(x) 1', '--'], - ['mean("a"); mean.character <- function(x, ...) 1', '--'], - ['as.numeric(s); s <- "a"; s <- "1"', '---'], - ['setGeneric("mean"); mean("a")', '--'], - ['library(otel); log(-1)', '--'], - ['lapply("otel", library, character.only = TRUE); log(-1)', '--'], - ['do.call("assign", list("log", function(x) 1)); log(-1)', '--'], - ['as.complex("1+2i")', '-'], + 'log(-1); log <- function(x) 1': '--', 'mean("a"); mean.character <- function(x, ...) 1': '--', 'as.numeric(s); s <- "a"; s <- "1"': '---', + 'setGeneric("mean"); mean("a")': '--', 'library(otel); log(-1)': '--', 'lapply("otel", library, character.only = TRUE); log(-1)': '--', + 'do.call("assign", list("log", function(x) 1)); log(-1)': '--', 'as.complex("1+2i")': '-', + /* strings R reads as no number, and those it reads */ + 'as.numeric("a"); as.numeric("1L"); as.numeric("1,5"); as.numeric("TRUE"); as.numeric("1d5"); as.numeric("."); as.numeric("+"); as.numeric("1e"); as.numeric("1p3"); as.numeric("1_000"); as.numeric("1+2i")': 'WWWWWWWWWWW', + 'as.numeric(""); as.numeric(" 3 "); as.numeric("1e5"); as.numeric("0x1A"); as.numeric("Inf"); as.numeric("inf"); as.numeric("Infinity"); as.numeric("-inf"); as.numeric("nan"); as.numeric("NaN"); as.numeric("1.5e-3"); as.numeric("0x1p3"); as.numeric(" "); as.numeric("NA")': '--------------', + /* poles and domains */ + 'log(-1); log(0); log1p(-2); log1p(-1); gamma(0); gamma(-0.5); factorial(-1); factorial(0); sqrt(NaN); mean(1)': 'W-W-W-----', /* `rm(x)` warns only where `x` is not bound, which the code before tells */ - ['rm(x)', '-'] - ]; - for(const [code, expected] of cases) { + 'rm(x)': '-' + }; + for(const [code, expected] of Object.entries(cases)) { test(`${code}: ${expected}`, async() => { - assert.strictEqual(await marks(code), expected); + const { tops, info } = await infoOf(code); + assert.strictEqual(tops.map(e => CertainWarnings.sites(e.info.id, info).length > 0 ? 'W' : '-').join(''), expected); }); } test('the names rm removes, which warn where they are not bound', async() => { - const analyzer = await analyze(parser, 'rm(x, "y"); suppressWarnings(rm(z)); rm(w, envir = e)'); - const ast = await analyzer.normalize(); - const { graph } = await analyzer.dataflow(); - const info = { graph, idMap: ast.idMap, ctx: analyzer.inspectContext(), resolve: Resolve.info(graph, analyzer.inspectContext()) }; - assert.deepStrictEqual(ast.ast.files[0].root.children.map(e => CertainWarnings.removals(e.info.id, info).map(r => r.names)), [[['x', 'y']], [], []]); + const { tops, info } = await infoOf('rm(x, "y"); suppressWarnings(rm(z)); rm(w, envir = e)'); + assert.deepStrictEqual(tops.map(e => CertainWarnings.removals(e.info.id, info).map(r => r.names)), [[['x', 'y']], [], []]); }); })); - -describe('The warnings R gives for the values of arguments', () => { - /* checked with R 4.6: `as.numeric(s)` warns for the strings marked true */ - const coercions: readonly (readonly [string, boolean])[] = [ - ['a', true], ['', false], [' 3 ', false], ['1e5', false], ['0x1A', false], ['Inf', false], ['inf', false], ['Infinity', false], - ['-inf', false], ['nan', false], ['NaN', false], ['1.5e-3', false], ['0x1p3', false], ['1L', true], ['1,5', true], ['TRUE', true], - ['1d5', true], ['.', true], ['+', true], ['1e', true], ['1p3', true], ['1_000', true], [' ', false], ['1+2i', true], ['NA', false] - ]; - for(const [str, warns] of coercions) { - test(`as.numeric(${JSON.stringify(str)}) ${warns ? 'warns' : 'is not sure to warn'}`, () => { - assert.strictEqual(notANumber(str), warns); - }); - } - test('the bounds of the functions with poles and domains', () => { - assert.isTrue(warnsFor(RWarnings['log'][0], -1)); - assert.isFalse(warnsFor(RWarnings['log'][0], 0)); - assert.isTrue(warnsFor(RWarnings['log1p'][0], -2)); - assert.isFalse(warnsFor(RWarnings['log1p'][0], -1)); - assert.isTrue(warnsFor(RWarnings['gamma'][0], 0)); - assert.isFalse(warnsFor(RWarnings['gamma'][0], -0.5)); - assert.isTrue(warnsFor(RWarnings['factorial'][0], -1)); - assert.isFalse(warnsFor(RWarnings['factorial'][0], 0)); - assert.isFalse(warnsFor(RWarnings['sqrt'][0], Number.NaN)); - assert.isFalse(warnsFor(RWarnings['mean'][0], 1)); - assert.isUndefined(RWarnings['as.complex']); - }); -}); diff --git a/test/functionality/notebook/cell-order-audit.test.ts b/test/functionality/notebook/cell-order-audit.test.ts index 4909104c553..5c7e62b9164 100644 --- a/test/functionality/notebook/cell-order-audit.test.ts +++ b/test/functionality/notebook/cell-order-audit.test.ts @@ -7,297 +7,118 @@ import { expFn, fakeSigDb } from '../_helper/sigdb'; import { CellRunner } from '../../../src/project/plugins/file-plugins/files/cell-runner'; /* - * Small R Markdown notebooks of 2 to 4 cells and a larger example, each with the orders of its cells that run in R - * (as the cell indices of flowR, which skip `eval = FALSE` chunks) and the dead ends, the orders that run as far as - * they can but not to the last cell. The orders were found by running every permutation in a fresh `Rscript --vanilla` - * (R 4.6, knitr 1.51), once per setting: - * - console: all cells in one global environment, with one graphics device and working directory, stopping at the first error; - * - knit: `knitr::knit` of the document with the chunks in that order and `error = FALSE`, stopping at the first error. - * flowR must never miss an order or a dead end that runs in R; where it promises more, the case says why and pins what flowR - * promises instead (`imprecise`), as where R's orders depend on what lies outside of the notebook. - * The names say what a case is about: `w` cases turn warnings into errors, `c` cases define or remove under conditions, - * `k` cases use what knitr does, `e` cases remove names of the global environment. + * Notebooks with the orders of their cells that run in R (every permutation in a fresh `Rscript --vanilla`, R 4.6, knitr 1.51): `console` runs all cells in one session, + * `knit` runs `knitr::knit` (`error = FALSE`, left out where equal), both stopping at the first error. `'012 021 / 02'` lists the orders 0,1,2 and 0,2,1 and the dead end 0,2 + * (a prefix no cell extends), by cell indices skipping `eval = FALSE` chunks; a cell starting with `#|` has the rest of its chunk header on that line. flowR must miss none; + * `imprecise` pins what it promises beyond, and why. `w`: warnings as errors, `c`: binding or removing under conditions, `k`: knitr, `e`: the global environment. */ -interface Orders { - readonly orders: readonly (readonly number[])[] - readonly deadEnds: readonly (readonly number[])[] -} -interface Truth extends Orders { - /** what flowR promises where it promises orders that fail in R, and why */ - readonly imprecise?: Orders & { readonly why: string } -} interface AuditCase { - readonly name: string - readonly files: Readonly> - readonly console: Truth - readonly knit: Truth + readonly name: string + readonly cells: readonly string[] + readonly files?: Readonly> + readonly console: string + readonly knit?: string + readonly imprecise?: { readonly why: string, readonly console?: string, readonly knit?: string } } const AuditCases: readonly AuditCase[] = [ - { name: '01-defuse', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- y * 2\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2]], deadEnds: [] } }, - { name: '02-redef', files: { 'nb.Rmd': '```{r}\nd <- 1:10\n```\n\ntext\n\n```{r}\nd <- d[d > 3]\n```\n\ntext\n\n```{r}\nm <- mean(d)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [] } }, - { name: '03-library', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '04-library-ggplot', files: { 'nb.Rmd': '```{r}\nlibrary(ggplot2)\n```\n\ntext\n\n```{r}\np <- ggplot(mtcars, aes(mpg, wt)) + geom_point()\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '05-rm', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- x\n```\n\ntext\n\n```{r}\nrm(x)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [2, 0, 1]], deadEnds: [[0, 2]] }, - knit: { orders: [[0, 1, 2], [2, 0, 1]], deadEnds: [[0, 2]] } }, - { name: '06-rmall', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nrm(list = ls())\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3]], deadEnds: [] }, - knit: { orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [2, 0, 1, 3], [2, 0, 3, 1], [2, 1, 0, 3]], deadEnds: [] } }, - { name: '07-plot', files: { 'nb.Rmd': '```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\nabline(h = 1)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, - { name: '08-evalfalse', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\n```{r, eval = FALSE}\nrm(x)\n```\n\n```{r}\ny <- x\n```\n' }, - console: { orders: [[0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1]], deadEnds: [] } }, - { name: '09-options', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nx <- as.integer("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, - { name: '10-setenv', files: { 'nb.Rmd': '```{r}\nSys.setenv(INPUT = "in.csv")\n```\n\ntext\n\n```{r}\nd <- read.csv(Sys.getenv("INPUT"))\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n', 'in.csv': 'a,b\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: { why: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside of the notebook, so flowR does not take it as absent', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [], imprecise: { why: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside of the notebook, so flowR does not take it as absent', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, - { name: '11-setwd', files: { 'nb.Rmd': '```{r}\nsetwd("sub")\n```\n\ntext\n\n```{r}\nd <- read.csv("in.csv")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n', 'sub/in.csv': 'a,b\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]], imprecise: { why: 'knitr resets the directory, so in.csv is read from the directory of the document, which lacks it; flowR does not take a file the project lacks as absent', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, - { name: '12-files', files: { 'nb.Rmd': '```{r}\nwrite.csv(data.frame(a = 1), "out.csv")\n```\n\ntext\n\n```{r}\nd <- read.csv("out.csv")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '13-random', files: { 'nb.Rmd': '```{r}\nset.seed(1)\n```\n\ntext\n\n```{r}\nx <- sample(10, 1)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: '14-columns', files: { 'nb.Rmd': '```{r}\nd <- data.frame(a = 1:3)\n```\n\ntext\n\n```{r}\nd$b <- d$a * 2\n```\n\ntext\n\n```{r}\nv <- d[, "b"]\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2]], deadEnds: [] } }, - { name: '15-closure', files: { 'nb.Rmd': '```{r}\nf <- function() x + 1\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- f()\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] } }, - { name: '16-superassign', files: { 'nb.Rmd': '```{r}\ng <- function() x <<- 1\n```\n\ntext\n\n```{r}\ng()\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2]], deadEnds: [] } }, - { name: '17-superassign-top', files: { 'nb.Rmd': '```{r}\nx <<- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '18-assign', files: { 'nb.Rmd': '```{r}\nassign("x", 1)\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '19-source', files: { 'nb.Rmd': '```{r}\nsource("helpers.R")\n```\n\ntext\n\n```{r}\ny <- helper(1)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n', 'helpers.R': 'helper <- function(v) v + 1\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '20-attach', files: { 'nb.Rmd': '```{r}\nd <- data.frame(a = 1:3)\n```\n\ntext\n\n```{r}\nattach(d)\n```\n\ntext\n\n```{r}\nv <- a + 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2]], deadEnds: [] } }, - { name: '21-rmsetdiff', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\ny <- 2\n```\n\ntext\n\n```{r}\nrm(list = setdiff(ls(), "x"))\n```\n\ntext\n\n```{r}\nz <- y\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 3, 2], [0, 2, 1, 3], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [1, 0, 2], [1, 2, 0]] }, - knit: { orders: [[0, 1, 3, 2], [0, 2, 1, 3], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [1, 0, 2], [1, 2, 0]] } }, - { name: '22-conddef', files: { 'nb.Rmd': '```{r}\nif (FALSE) x <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, - { name: '23-exists', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (!exists("x")) stop("no x")\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '24-rm-plot', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\nrm(list = ls())\n```\n\ntext\n\n```{r}\nabline(h = fractions(0.5))\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [2, 0, 1, 3], [2, 1, 0, 3]], deadEnds: [] }, - knit: { orders: [], deadEnds: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] } }, - { name: '25-funcdef-uses-lib', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nh <- function(v) fractions(v)\n```\n\ntext\n\n```{r}\ny <- h(0.5)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [1, 0, 2]], deadEnds: [] } }, - { name: '26-dev-off', files: { 'nb.Rmd': '```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\ndev.off()\n```\n\ntext\n\n```{r}\nabline(h = 1)\n```\n\ntext\n\n' }, - console: { orders: [[0, 2, 1]], deadEnds: [[0, 1]] }, - knit: { orders: [], deadEnds: [[0, 1], [1, 0]] } }, - { name: '27-require', files: { 'nb.Rmd': '```{r}\nrequire(MASS)\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '28-pipe-lib', files: { 'nb.Rmd': '```{r}\nlibrary(dplyr)\n```\n\ntext\n\n```{r}\nd <- mtcars |> filter(mpg > 20)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '29-local-shadow', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nf <- function(x) x + 1\n```\n\ntext\n\n```{r}\ny <- f(2)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, - { name: '30-loop-def', files: { 'nb.Rmd': '```{r}\nfor (i in 1:3) x <- i\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: '31-conddef-rt', files: { 'nb.Rmd': '```{r}\nset.seed(1)\nif (runif(1) > 2) x <- 1\n```\n\n```{r}\ny <- x + 1\n```\n\n```{r}\nz <- 1\n```\n' }, - console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, - { name: 'c01-cond-runif-never', files: { 'nb.Rmd': '```{r}\nif (runif(1) > 2) x <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, - { name: 'c02-cond-runif-always', files: { 'nb.Rmd': '```{r}\nif (runif(1) < 2) x <- 1\n```\n\ntext\n\n```{r}\ny <- x + 1\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: 'c03-cond-rm-never', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (runif(1) > 2) rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'c04-cond-rm-unknown', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (Sys.getenv("NOPE") == "yes") rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'c05-cond-empty-loop', files: { 'nb.Rmd': '```{r}\nfor (i in seq_len(0)) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, - { name: 'c06-cond-while-false-rm', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nwhile (FALSE) rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'c07-cond-rbinom-never', files: { 'nb.Rmd': '```{r}\nif (rbinom(1, 1, 0.5) == 2) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [], deadEnds: [[0, 2], [2, 0]] } }, - { name: 'c08-cond-both-branches', files: { 'nb.Rmd': '```{r}\nif (exists("y")) x <- 1 else x <- 2\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, - { name: 'c09-cond-detach-never', files: { 'nb.Rmd': '```{r}\nlibrary(MASS)\n```\n\ntext\n\n```{r}\nif (runif(1) > 5) detach("package:MASS")\n```\n\ntext\n\n```{r}\nf <- fractions(0.5)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'c10-cond-dev-off-never', files: { 'nb.Rmd': '```{r}\nplot(1:10)\n```\n\ntext\n\n```{r}\nif (runif(1) > 2) dev.off()\n```\n\ntext\n\n```{r}\nabline(h = 1)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [], deadEnds: [[0, 1], [1, 0]] } }, - { name: 'c11-cond-rm-true', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (TRUE) rm(x)\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [[0, 1]] }, - knit: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [[0, 1]] } }, - { name: 'c12-cond-superassign', files: { 'nb.Rmd': '```{r}\nf <- function() if (runif(1) > 2) x <<- 1\n```\n\ntext\n\n```{r}\nf()\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 1]] }, - knit: { orders: [], deadEnds: [[0, 1]] } }, - { name: 'c13-cond-rmall-unknown', files: { 'nb.Rmd': '```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nif (nchar(Sys.getenv("NOPE")) > 0) rm(list = ls())\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'c14-cond-runif-scaled', files: { 'nb.Rmd': '```{r}\nu <- runif(1, 5, 10)\n```\n\ntext\n\n```{r}\nif (u < 4) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n' }, - console: { orders: [], deadEnds: [[0, 1]] }, - knit: { orders: [], deadEnds: [[0, 1]] } }, - { name: 'running-example', files: { 'nb.Rmd': '```{r setup}\nlibrary(ggplot2)\ntheme_set(theme_minimal())\n```\n\nLoad the survey.\n\n```{r load}\ndata <- read.csv("survey.csv")\ndata <- na.omit(data)\n```\n\n```{r analysis}\nmodel <- lm(score ~ age, data = data)\nsummary(model)\nggplot(data, aes(age, score)) +\n geom_point() + geom_smooth(method = "lm")\n```\n\n```{r filter}\n# drop participants under 18 (written last)\ndata <- subset(data, age >= 18)\nnrow(data)\n```\n\n```{r cleanup}\nrm(data)\ngc()\n```\n', 'survey.csv': '"age","score"\n18,54\n25,44\n52,62\n49,59\n53,NA\n56,75\n44,63\n21,47\n33,67\n23,64\n68,76\n53,72\n61,65\n53,72\n21,67\n50,65\n15,NA\n42,69\n57,73\n58,65\n18,69\n53,60\n50,68\n22,38\n22,55\n69,80\n67,66\n31,52\n29,65\n38,55\n25,60\n53,52\n35,49\n64,66\n19,47\n53,77\n28,66\n23,51\n24,62\n42,70\n' }, - console: { orders: [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 4, 1, 2, 3], [0, 4, 1, 3, 2], [1, 0, 2, 3, 4], [1, 0, 3, 2, 4], [1, 3, 0, 2, 4], [4, 0, 1, 2, 3], [4, 0, 1, 3, 2], [4, 1, 0, 2, 3], [4, 1, 0, 3, 2], [4, 1, 3, 0, 2]], deadEnds: [[0, 1, 2, 4], [0, 1, 3, 4], [0, 1, 4], [1, 0, 2, 4], [1, 0, 3, 4], [1, 0, 4], [1, 3, 0, 4], [1, 3, 4, 0], [1, 4, 0]] }, - knit: { orders: [[0, 1, 2, 3, 4], [0, 1, 3, 2, 4], [0, 4, 1, 2, 3], [0, 4, 1, 3, 2], [1, 0, 2, 3, 4], [1, 0, 3, 2, 4], [1, 3, 0, 2, 4], [4, 0, 1, 2, 3], [4, 0, 1, 3, 2], [4, 1, 0, 2, 3], [4, 1, 0, 3, 2], [4, 1, 3, 0, 2]], deadEnds: [[0, 1, 2, 4], [0, 1, 3, 4], [0, 1, 4], [1, 0, 2, 4], [1, 0, 3, 4], [1, 0, 4], [1, 3, 0, 4], [1, 3, 4, 0], [1, 4, 0]] } }, - { name: 'w01-warn-coerce', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nx <- as.numeric("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, - { name: 'w02-warn-suppressed', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nx <- suppressWarnings(as.numeric("a"))\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w03-warn-restore', files: { 'nb.Rmd': '```{r}\nop <- options(warn = 2)\n```\n\ntext\n\n```{r}\nz <- log(-1)\n```\n\ntext\n\n```{r}\noptions(op)\n```\n\ntext\n\n' }, - console: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'w04-warn-in-function', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nf <- function() as.numeric("a")\n```\n\ntext\n\n```{r}\nf()\n```\n\ntext\n\n' }, - console: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] }, - knit: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] } }, - { name: 'w05-warn-trycatch', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nr <- tryCatch(warning("w"), warning = function(w) 1)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w06-warn-calling-handler', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nwithCallingHandlers(sqrt(-1), warning = function(w) invokeRestart("muffleWarning"))\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w07-warn-reset', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\noptions(warn = 0)\n```\n\ntext\n\n```{r}\nwarning("x")\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] }, - knit: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] } }, - { name: 'w08-warn-try', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nr <- try(log(-1), silent = TRUE)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w09-warn-level-one', files: { 'nb.Rmd': '```{r}\noptions(warn = 1)\n```\n\ntext\n\n```{r}\ni <- as.integer("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w10-warn-conditional-set', files: { 'nb.Rmd': '```{r}\nif (Sys.getenv("NOPE") == "yes") options(warn = 2)\n```\n\ntext\n\n```{r}\nx <- as.numeric("a")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w11-warn-variable', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nv <- "a"\n```\n\ntext\n\n```{r}\nn <- as.numeric(v)\n```\n\ntext\n\n' }, - console: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] }, - knit: { orders: [[1, 2, 0]], deadEnds: [[0, 1], [1, 0]] } }, - { name: 'w12-warn-mean-max', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nm <- mean("a")\n```\n\ntext\n\n```{r}\nk <- max()\n```\n\ntext\n\n' }, - console: { orders: [[1, 2, 0], [2, 1, 0]], deadEnds: [[0], [1, 0], [2, 0]] }, - knit: { orders: [[1, 2, 0], [2, 1, 0]], deadEnds: [[0], [1, 0], [2, 0]] } }, - { name: 'w13-warn-nested-functions', files: { 'nb.Rmd': '```{r}\ng <- function() warning("w")\n```\n\ntext\n\n```{r}\nh <- function() g()\n```\n\ntext\n\n```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nh()\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 3, 2], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] }, - knit: { orders: [[0, 1, 3, 2], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] } }, - { name: 'w14-warn-none', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\na <- as.numeric("1")\n```\n\ntext\n\n```{r}\nb <- sqrt(4)\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w15-warn-unforced-promise', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nf <- function(x) 1\n```\n\ntext\n\n```{r}\nf(as.numeric("a"))\n```\n\ntext\n\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, - { name: 'w16-warn-same-cell', files: { 'nb.Rmd': '```{r}\noptions(warn = 2); x <- 1\n```\n\ntext\n\n```{r}\ny <- log(-1)\n```\n\ntext\n\n```{r}\nz <- 2\n```\n\ntext\n\n' }, - console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, - { name: 'w17-warn-in-function-set', files: { 'nb.Rmd': '```{r}\nstrict <- function() options(warn = 2)\n```\n\ntext\n\n```{r}\nstrict()\n```\n\ntext\n\n```{r}\nx <- as.numeric("b")\n```\n\ntext\n\n' }, - console: { orders: [[0, 2, 1], [2, 0, 1]], deadEnds: [[0, 1]] }, - knit: { orders: [[0, 2, 1], [2, 0, 1]], deadEnds: [[0, 1]] } }, - { name: 'w18-warn-gamma', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\ng <- gamma(0)\n```\n\ntext\n\n```{r}\nf <- factorial(0)\n```\n\ntext\n\n' }, - console: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] }, - knit: { orders: [[1, 0, 2], [1, 2, 0], [2, 1, 0]], deadEnds: [[0, 2], [2, 0]] } }, - { name: 'w26-redef-later', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n\ntext\n\n```{r}\nlog <- function(x) 1\n```\n' }, - console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, - { name: 'w19-s3-method', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nm <- mean("a")\n```\n\ntext\n\n```{r}\nmean.character <- function(x, ...) 1\n```\n' }, - console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell defines a method of mean, so flowR takes no call of mean for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell defines a method of mean, so flowR takes no call of mean for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, - { name: 'w20-warn-reset-in-fn', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nf <- function() { options(warn = 0); log(-1) }\n```\n\ntext\n\n```{r}\nf()\n```\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, - { name: 'w21-string-name', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\noptions("warn" = 0)\n```\n\ntext\n\n```{r}\nw <- as.numeric("a")\n```\n' }, - console: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] }, - knit: { orders: [[0, 1, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [[1, 0]] } }, - { name: 'w22-rm-missing', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nrm(x)\n```\n\ntext\n\n```{r}\nx <- 1\n```\n' }, - console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w23-otel', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nlibrary(otel)\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package the notebook attaches exports log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package the notebook attaches exports log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, - { name: 'w24-complex', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nz <- as.complex("1+2i")\n```\n\ntext\n\n```{r}\ny <- 1\n```\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - { name: 'w25-same-cell-redef', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n\ntext\n\n```{r}\nlog <- function(x) 1; l2 <- log(-1)\n```\n' }, - console: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - knit: { orders: [[0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, - { name: 'c15-runif-redef', files: { 'nb.Rmd': '```{r}\nif (runif(1) > 2) x <- 1\n```\n\ntext\n\n```{r}\nrunif <- function(n, ...) 5\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, - console: { orders: [[1, 0, 2]], deadEnds: [[0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - knit: { orders: [[1, 0, 2]], deadEnds: [[0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } } }, - { name: 'c16-warn-arg-other-cell', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\ns <- "a"\n```\n\ntext\n\n```{r}\nw <- as.numeric(s)\n```\n\ntext\n\n```{r}\ns <- "1"\n```\n' }, - console: { orders: [[0, 1, 3, 2], [0, 3, 2, 1], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 2, 1], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [[0, 3, 1], [3, 0, 1], [3, 1, 0]], imprecise: { why: 'two cells bind s, so flowR does not know which value as.numeric gets', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [] } }, - knit: { orders: [[0, 1, 3, 2], [0, 3, 2, 1], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 2, 1], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [[0, 3, 1], [3, 0, 1], [3, 1, 0]], imprecise: { why: 'two cells bind s, so flowR does not know which value as.numeric gets', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 2, 0, 3], [1, 2, 3, 0], [1, 3, 0, 2], [1, 3, 2, 0], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2], [3, 1, 2, 0], [3, 2, 0, 1], [3, 2, 1, 0]], deadEnds: [] } } }, - { name: 'c17-ifelse-draw', files: { 'nb.Rmd': '```{r}\ny <- ifelse(runif(1) > 2, stop("no"), 1)\n```\n\ntext\n\n```{r}\nz <- 1\n```\n' }, - console: { orders: [[0, 1], [1, 0]], deadEnds: [] }, - knit: { orders: [[0, 1], [1, 0]], deadEnds: [] } }, - { name: 'c18-switch-draw', files: { 'nb.Rmd': '```{r}\nswitch(as.character(rbinom(1, 1, 0.5)), "0" = { x <- 1 }, "1" = { x <- 2 })\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, - console: { orders: [[0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1]], deadEnds: [] } }, - { name: 'c19-runif-redef-fn-arg', files: { 'nb.Rmd': '```{r}\nif (runif(1) > 2) x <- 1\n```\n\ntext\n\n```{r}\nrunif <- function(n, min = 0, max = 1) 5\n```\n\ntext\n\n```{r}\nprint(x)\n```\n\ntext\n\n```{r}\nrm(runif)\n```\n' }, - console: { orders: [[1, 0, 2, 3], [1, 0, 3, 2], [3, 1, 0, 2]], deadEnds: [[0, 1, 3], [0, 3, 1], [1, 3, 0], [3, 0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 3, 0, 2], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2]], deadEnds: [] } }, - knit: { orders: [[1, 0, 2, 3], [1, 0, 3, 2], [3, 1, 0, 2]], deadEnds: [[0, 1, 3], [0, 3, 1], [1, 3, 0], [3, 0, 1]], imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2], [1, 3, 0, 2], [3, 0, 1, 2], [3, 0, 2, 1], [3, 1, 0, 2]], deadEnds: [] } } }, - { name: 'c20-cond-literal-redef-T', files: { 'nb.Rmd': '```{r}\nif (T) x <- 1\n```\n\ntext\n\n```{r}\nT <- FALSE\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'T read before a cell binds it is TRUE, which flowR does not follow', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - knit: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'T read before a cell binds it is TRUE, which flowR does not follow', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } } }, - { name: 'k01-knit-exit', files: { 'nb.Rmd': '```{r}\nknitr::knit_exit()\n```\n\ntext\n\n```{r}\nx <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0]], deadEnds: [] } }, - { name: 'c21-cond-name-two-cells', files: { 'nb.Rmd': '```{r}\nk <- FALSE\n```\n\ntext\n\n```{r}\nif (k) x <- 1\n```\n\ntext\n\n```{r}\nk <- TRUE\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, - console: { orders: [[0, 2, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [2, 0, 1]], imprecise: { why: 'two cells bind k, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [] } }, - knit: { orders: [[0, 2, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [[0, 1, 2], [2, 0, 1]], imprecise: { why: 'two cells bind k, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0]], deadEnds: [] } } }, - { name: 'e01-dot-name-rmall', files: { 'nb.Rmd': '```{r}\n.x <- 1\n```\n\ntext\n\n```{r}\nrm(list = ls())\n```\n\ntext\n\n```{r}\nprint(.x)\n```\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'e02-rm-pattern', files: { 'nb.Rmd': '```{r}\nax <- 1; b <- 2\n```\n\ntext\n\n```{r}\nrm(list = ls(pattern = "^a"))\n```\n\ntext\n\n```{r}\nprint(b)\n```\n\ntext\n\n```{r}\nprint(ax)\n```\n' }, - console: { orders: [[0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1]], imprecise: { why: 'ls(pattern = ...) may list only some names, so flowR takes rm to remove none for sure', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [] } }, - knit: { orders: [[0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [[0, 1, 2], [0, 2, 1]], imprecise: { why: 'ls(pattern = ...) may list only some names, so flowR takes rm to remove none for sure', orders: [[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 1, 3], [0, 2, 3, 1], [0, 3, 1, 2], [0, 3, 2, 1], [1, 0, 2, 3], [1, 0, 3, 2]], deadEnds: [] } } }, - { name: 'c22-cond-dataset-name', files: { 'nb.Rmd': '```{r}\nif (is.data.frame(iris)) x <- 1\n```\n\ntext\n\n```{r}\niris <- 5\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'iris read before a cell binds it is the data set of R, so flowR does not fold the condition', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - knit: { orders: [[0, 1, 2], [0, 2, 1]], deadEnds: [[1, 0]], imprecise: { why: 'iris read before a cell binds it is the data set of R, so flowR does not fold the condition', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } } }, - { name: 'w27-library-through-lapply', files: { 'nb.Rmd': '```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\ninvisible(lapply("otel", library, character.only = TRUE))\n```\n\ntext\n\n```{r}\nl <- log(-1)\n```\n' }, - console: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package attached through lapply may export log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } }, - knit: { orders: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [], imprecise: { why: 'a package attached through lapply may export log, so flowR takes no call of log for the one of R', orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]], deadEnds: [] } } }, - { name: 'w28-rm-envir', files: { 'nb.Rmd': '```{r}\ne <- new.env(); assign("x", 1, envir = e)\n```\n\ntext\n\n```{r}\noptions(warn = 2)\n```\n\ntext\n\n```{r}\nrm(x, envir = e)\n```\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [1, 0, 2]], deadEnds: [] } }, - { name: 'e03-globalenv-member-cond', files: { 'nb.Rmd': '```{r}\nu <- runif(1, 5, 10)\n```\n\ntext\n\n```{r}\n.GlobalEnv$u <- 1\n```\n\ntext\n\n```{r}\nif (u < 4) x <- 1\n```\n\ntext\n\n```{r}\nprint(x)\n```\n' }, - console: { orders: [[0, 1, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [[0, 2, 1], [1, 0, 2]], imprecise: { why: 'two cells bind u, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [] } }, - knit: { orders: [[0, 1, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [[0, 2, 1], [1, 0, 2]], imprecise: { why: 'two cells bind u, so flowR does not fold the condition', orders: [[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0]], deadEnds: [] } } }, - { name: 'e04-globalenv-member', files: { 'nb.Rmd': '```{r}\n.GlobalEnv$u <- 1\n```\n\ntext\n\n```{r}\nprint(u)\n```\n\ntext\n\n```{r}\ny <- 1\n```\n' }, - console: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] }, - knit: { orders: [[0, 1, 2], [0, 2, 1], [2, 0, 1]], deadEnds: [] } }, + { name: '01-defuse', cells: ['x <- 1', 'y <- x + 1', 'z <- y * 2'], console: '012' }, + { name: '02-redef', cells: ['d <- 1:10', 'd <- d[d > 3]', 'm <- mean(d)'], console: '012 021' }, + { name: '03-library', cells: ['library(MASS)', 'f <- fractions(0.5)', 'x <- 1'], console: '012 021 201' }, + { name: '04-library-ggplot', cells: ['library(ggplot2)', 'p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()', 'x <- 1'], console: '012 021 201' }, + { name: '05-rm', cells: ['x <- 1', 'y <- x', 'rm(x)'], console: '012 201 / 02' }, + { name: '06-rmall', cells: ['library(MASS)', 'x <- 1', 'rm(list = ls())', 'f <- fractions(0.5)'], console: '0123 0132 0213 0231 0312 0321 1023 1032 1203 2013 2031 2103' }, + { name: '07-plot', cells: ['plot(1:10)', 'abline(h = 1)', 'x <- 1'], console: '012 021 201', knit: ' / 02 20' }, + { name: '08-evalfalse', cells: ['x <- 1', '#|, eval = FALSE\nrm(x)', 'y <- x'], console: '01' }, + { name: '09-options', cells: ['options(warn = 2)', 'x <- as.integer("a")', 'y <- 1'], console: '102 120 210 / 02 20' }, + { name: '10-setenv', cells: ['Sys.setenv(INPUT = "in.csv")', 'd <- read.csv(Sys.getenv("INPUT"))', 'y <- 1'], files: { 'in.csv': 'a,b\n' }, console: '012 021 201', imprecise: { why: 'without Sys.setenv, Sys.getenv("INPUT") gives "" and read.csv fails, but the variable may come from outside of the notebook, so flowR does not take it as absent', console: '012 021 102 120 201 210', knit: '012 021 102 120 201 210' } }, + { name: '11-setwd', cells: ['setwd("sub")', 'd <- read.csv("in.csv")', 'y <- 1'], files: { 'sub/in.csv': 'a,b\n' }, console: '012 021 201', knit: ' / 02 20', imprecise: { why: 'knitr resets the directory, so in.csv is read from the directory of the document, which lacks it; flowR does not take a file the project lacks as absent', knit: '012 021 102 120 201 210' } }, + { name: '12-files', cells: ['write.csv(data.frame(a = 1), "out.csv")', 'd <- read.csv("out.csv")', 'y <- 1'], console: '012 021 201' }, + { name: '13-random', cells: ['set.seed(1)', 'x <- sample(10, 1)', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: '14-columns', cells: ['d <- data.frame(a = 1:3)', 'd$b <- d$a * 2', 'v <- d[, "b"]'], console: '012' }, + { name: '15-closure', cells: ['f <- function() x + 1', 'x <- 1', 'y <- f()'], console: '012 102' }, + { name: '16-superassign', cells: ['g <- function() x <<- 1', 'g()', 'y <- x + 1'], console: '012' }, + { name: '17-superassign-top', cells: ['x <<- 1', 'y <- x + 1', 'z <- 1'], console: '012 021 201' }, + { name: '18-assign', cells: ['assign("x", 1)', 'y <- x + 1', 'z <- 1'], console: '012 021 201' }, + { name: '19-source', cells: ['source("helpers.R")', 'y <- helper(1)', 'z <- 1'], files: { 'helpers.R': 'helper <- function(v) v + 1\n' }, console: '012 021 201' }, + { name: '20-attach', cells: ['d <- data.frame(a = 1:3)', 'attach(d)', 'v <- a + 1'], console: '012' }, + { name: '21-rmsetdiff', cells: ['x <- 1', 'y <- 2', 'rm(list = setdiff(ls(), "x"))', 'z <- y'], console: '0132 0213 1032 1302 1320 2013 2103 2130 / 012 102 120' }, + { name: '22-conddef', cells: ['if (FALSE) x <- 1', 'y <- x + 1', 'z <- 1'], console: ' / 02 20' }, + { name: '23-exists', cells: ['x <- 1', 'if (!exists("x")) stop("no x")', 'z <- 1'], console: '012 021 201' }, + { name: '24-rm-plot', cells: ['library(MASS)', 'plot(1:10)', 'rm(list = ls())', 'abline(h = fractions(0.5))'], console: '0123 0132 0213 1023 1032 1203 2013 2103', knit: ' / 012 021 102 120 201 210' }, + { name: '25-funcdef-uses-lib', cells: ['library(MASS)', 'h <- function(v) fractions(v)', 'y <- h(0.5)'], console: '012 102' }, + { name: '26-dev-off', cells: ['plot(1:10)', 'dev.off()', 'abline(h = 1)'], console: '021 / 01', knit: ' / 01 10' }, + { name: '27-require', cells: ['require(MASS)', 'f <- fractions(0.5)', 'x <- 1'], console: '012 021 201' }, + { name: '28-pipe-lib', cells: ['library(dplyr)', 'd <- mtcars |> filter(mpg > 20)', 'x <- 1'], console: '012 021 201' }, + { name: '29-local-shadow', cells: ['x <- 1', 'f <- function(x) x + 1', 'y <- f(2)'], console: '012 102 120' }, + { name: '30-loop-def', cells: ['for (i in 1:3) x <- i', 'y <- x + 1', 'z <- 1'], console: '012 021 201' }, + { name: '31-conddef-rt', cells: ['set.seed(1)\nif (runif(1) > 2) x <- 1', 'y <- x + 1', 'z <- 1'], console: ' / 02 20' }, + { name: 'c01-cond-runif-never', cells: ['if (runif(1) > 2) x <- 1', 'y <- x + 1', 'z <- 1'], console: ' / 02 20' }, + { name: 'c02-cond-runif-always', cells: ['if (runif(1) < 2) x <- 1', 'y <- x + 1', 'z <- 1'], console: '012 021 201' }, + { name: 'c03-cond-rm-never', cells: ['x <- 1', 'if (runif(1) > 2) rm(x)', 'print(x)'], console: '012 021 102' }, + { name: 'c04-cond-rm-unknown', cells: ['x <- 1', 'if (Sys.getenv("NOPE") == "yes") rm(x)', 'print(x)'], console: '012 021 102' }, + { name: 'c05-cond-empty-loop', cells: ['for (i in seq_len(0)) x <- 1', 'print(x)', 'z <- 1'], console: ' / 02 20' }, + { name: 'c06-cond-while-false-rm', cells: ['x <- 1', 'while (FALSE) rm(x)', 'print(x)'], console: '012 021 102' }, + { name: 'c07-cond-rbinom-never', cells: ['if (rbinom(1, 1, 0.5) == 2) x <- 1', 'print(x)', 'z <- 1'], console: ' / 02 20' }, + { name: 'c08-cond-both-branches', cells: ['if (exists("y")) x <- 1 else x <- 2', 'print(x)', 'y <- 1'], console: '012 021 201' }, + { name: 'c09-cond-detach-never', cells: ['library(MASS)', 'if (runif(1) > 5) detach("package:MASS")', 'f <- fractions(0.5)'], console: '012 021 102' }, + { name: 'c10-cond-dev-off-never', cells: ['plot(1:10)', 'if (runif(1) > 2) dev.off()', 'abline(h = 1)'], console: '012 021 102', knit: ' / 01 10' }, + { name: 'c11-cond-rm-true', cells: ['x <- 1', 'if (TRUE) rm(x)', 'print(x)'], console: '021 102 / 01' }, + { name: 'c12-cond-superassign', cells: ['f <- function() if (runif(1) > 2) x <<- 1', 'f()', 'print(x)'], console: ' / 01' }, + { name: 'c13-cond-rmall-unknown', cells: ['x <- 1', 'if (nchar(Sys.getenv("NOPE")) > 0) rm(list = ls())', 'print(x)'], console: '012 021 102' }, + { name: 'c14-cond-runif-scaled', cells: ['u <- runif(1, 5, 10)', 'if (u < 4) x <- 1', 'print(x)'], console: ' / 01' }, + { name: 'running-example', cells: ['#| setup\nlibrary(ggplot2)\ntheme_set(theme_minimal())', '#| load\ndata <- read.csv("survey.csv")\ndata <- na.omit(data)', '#| analysis\nmodel <- lm(score ~ age, data = data)\nsummary(model)\nggplot(data, aes(age, score)) +\n geom_point() + geom_smooth(method = "lm")', '#| filter\n# drop participants under 18 (written last)\ndata <- subset(data, age >= 18)\nnrow(data)', '#| cleanup\nrm(data)\ngc()'], files: { 'survey.csv': '"age","score"\n18,54\n25,44\n52,62\n49,59\n53,NA\n56,75\n44,63\n21,47\n33,67\n23,64\n68,76\n53,72\n61,65\n53,72\n21,67\n50,65\n15,NA\n42,69\n57,73\n58,65\n18,69\n53,60\n50,68\n22,38\n22,55\n69,80\n67,66\n31,52\n29,65\n38,55\n25,60\n53,52\n35,49\n64,66\n19,47\n53,77\n28,66\n23,51\n24,62\n42,70\n' }, console: '01234 01324 04123 04132 10234 10324 13024 40123 40132 41023 41032 41302 / 0124 0134 014 1024 1034 104 1304 1340 140' }, + { name: 'w01-warn-coerce', cells: ['options(warn = 2)', 'x <- as.numeric("a")', 'y <- 1'], console: '102 120 210 / 02 20' }, + { name: 'w02-warn-suppressed', cells: ['options(warn = 2)', 'x <- suppressWarnings(as.numeric("a"))', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: 'w03-warn-restore', cells: ['op <- options(warn = 2)', 'z <- log(-1)', 'options(op)'], console: '021 102' }, + { name: 'w04-warn-in-function', cells: ['options(warn = 2)', 'f <- function() as.numeric("a")', 'f()'], console: '120 / 01 10' }, + { name: 'w05-warn-trycatch', cells: ['options(warn = 2)', 'r <- tryCatch(warning("w"), warning = function(w) 1)', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: 'w06-warn-calling-handler', cells: ['options(warn = 2)', 'withCallingHandlers(sqrt(-1), warning = function(w) invokeRestart("muffleWarning"))', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: 'w07-warn-reset', cells: ['options(warn = 2)', 'options(warn = 0)', 'warning("x")'], console: '012 120 201 210 / 10' }, + { name: 'w08-warn-try', cells: ['options(warn = 2)', 'r <- try(log(-1), silent = TRUE)', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: 'w09-warn-level-one', cells: ['options(warn = 1)', 'i <- as.integer("a")', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: 'w10-warn-conditional-set', cells: ['if (Sys.getenv("NOPE") == "yes") options(warn = 2)', 'x <- as.numeric("a")', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: 'w11-warn-variable', cells: ['options(warn = 2)', 'v <- "a"', 'n <- as.numeric(v)'], console: '120 / 01 10' }, + { name: 'w12-warn-mean-max', cells: ['options(warn = 2)', 'm <- mean("a")', 'k <- max()'], console: '120 210 / 0 10 20' }, + { name: 'w13-warn-nested-functions', cells: ['g <- function() warning("w")', 'h <- function() g()', 'options(warn = 2)', 'h()'], console: '0132 1032 / 012 021 102 120 201 210' }, + { name: 'w14-warn-none', cells: ['options(warn = 2)', 'a <- as.numeric("1")', 'b <- sqrt(4)'], console: '012 021 102 120 201 210' }, + { name: 'w15-warn-unforced-promise', cells: ['options(warn = 2)', 'f <- function(x) 1', 'f(as.numeric("a"))'], console: '012 102 120' }, + { name: 'w16-warn-same-cell', cells: ['options(warn = 2); x <- 1', 'y <- log(-1)', 'z <- 2'], console: '102 120 210 / 02 20' }, + { name: 'w17-warn-in-function-set', cells: ['strict <- function() options(warn = 2)', 'strict()', 'x <- as.numeric("b")'], console: '021 201 / 01' }, + { name: 'w18-warn-gamma', cells: ['options(warn = 2)', 'g <- gamma(0)', 'f <- factorial(0)'], console: '102 120 210 / 02 20' }, + { name: 'w26-redef-later', cells: ['options(warn = 2)', 'l <- log(-1)', 'log <- function(x) 1'], console: '021 102 120 201 210', imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', console: '012 021 102 120 201 210', knit: '012 021 102 120 201 210' } }, + { name: 'w19-s3-method', cells: ['options(warn = 2)', 'm <- mean("a")', 'mean.character <- function(x, ...) 1'], console: '021 102 120 201 210', imprecise: { why: 'a cell defines a method of mean, so flowR takes no call of mean for the one of R', console: '012 021 102 120 201 210', knit: '012 021 102 120 201 210' } }, + { name: 'w20-warn-reset-in-fn', cells: ['options(warn = 2)', 'f <- function() { options(warn = 0); log(-1) }', 'f()'], console: '012 102 120' }, + { name: 'w21-string-name', cells: ['options(warn = 2)', 'options("warn" = 0)', 'w <- as.numeric("a")'], console: '012 120 201 210 / 10' }, + { name: 'w22-rm-missing', cells: ['options(warn = 2)', 'rm(x)', 'x <- 1'], console: '021 102 120 201 210' }, + { name: 'w23-otel', cells: ['options(warn = 2)', 'library(otel)', 'l <- log(-1)'], console: '012 102 120 201 210', imprecise: { why: 'a package the notebook attaches exports log, so flowR takes no call of log for the one of R', console: '012 021 102 120 201 210', knit: '012 021 102 120 201 210' } }, + { name: 'w24-complex', cells: ['options(warn = 2)', 'z <- as.complex("1+2i")', 'y <- 1'], console: '012 021 102 120 201 210' }, + { name: 'w25-same-cell-redef', cells: ['options(warn = 2)', 'l <- log(-1)', 'log <- function(x) 1; l2 <- log(-1)'], console: '021 102 120 201 210', imprecise: { why: 'a cell binds log, so flowR takes no call of log for the one of R', console: '012 021 102 120 201 210', knit: '012 021 102 120 201 210' } }, + { name: 'c15-runif-redef', cells: ['if (runif(1) > 2) x <- 1', 'runif <- function(n, ...) 5', 'print(x)'], console: '102 / 01', imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', console: '012 021 102', knit: '012 021 102' } }, + { name: 'c16-warn-arg-other-cell', cells: ['options(warn = 2)', 's <- "a"', 'w <- as.numeric(s)', 's <- "1"'], console: '0132 0321 1032 1203 1230 1302 1320 3021 3120 3201 3210 / 031 301 310', imprecise: { why: 'two cells bind s, so flowR does not know which value as.numeric gets', console: '0123 0132 0312 0321 1023 1032 1203 1230 1302 1320 3012 3021 3102 3120 3201 3210', knit: '0123 0132 0312 0321 1023 1032 1203 1230 1302 1320 3012 3021 3102 3120 3201 3210' } }, + { name: 'c17-ifelse-draw', cells: ['y <- ifelse(runif(1) > 2, stop("no"), 1)', 'z <- 1'], console: '01 10' }, + { name: 'c18-switch-draw', cells: ['switch(as.character(rbinom(1, 1, 0.5)), "0" = { x <- 1 }, "1" = { x <- 2 })', 'print(x)'], console: '01' }, + { name: 'c19-runif-redef-fn-arg', cells: ['if (runif(1) > 2) x <- 1', 'runif <- function(n, min = 0, max = 1) 5', 'print(x)', 'rm(runif)'], console: '1023 1032 3102 / 013 031 130 301', imprecise: { why: 'a cell binds runif, so flowR does not fold the draw', console: '0123 0132 0213 0231 0312 0321 1023 1032 1302 3012 3021 3102', knit: '0123 0132 0213 0231 0312 0321 1023 1032 1302 3012 3021 3102' } }, + { name: 'c20-cond-literal-redef-T', cells: ['if (T) x <- 1', 'T <- FALSE', 'print(x)'], console: '012 021 / 10', imprecise: { why: 'T read before a cell binds it is TRUE, which flowR does not follow', console: '012 021 102', knit: '012 021 102' } }, + { name: 'k01-knit-exit', cells: ['knitr::knit_exit()', 'x <- 1', 'print(x)'], console: '012 102 120', knit: '012 021 102 120' }, + { name: 'c21-cond-name-two-cells', cells: ['k <- FALSE', 'if (k) x <- 1', 'k <- TRUE', 'print(x)'], console: '0213 2103 2130 / 012 201', imprecise: { why: 'two cells bind k, so flowR does not fold the condition', console: '0123 0132 0213 2013 2103 2130', knit: '0123 0132 0213 2013 2103 2130' } }, + { name: 'e01-dot-name-rmall', cells: ['.x <- 1', 'rm(list = ls())', 'print(.x)'], console: '012 021 102' }, + { name: 'e02-rm-pattern', cells: ['ax <- 1; b <- 2', 'rm(list = ls(pattern = "^a"))', 'print(b)', 'print(ax)'], console: '0231 0312 0321 1023 1032 / 012 021', imprecise: { why: 'ls(pattern = ...) may list only some names, so flowR takes rm to remove none for sure', console: '0123 0132 0213 0231 0312 0321 1023 1032', knit: '0123 0132 0213 0231 0312 0321 1023 1032' } }, + { name: 'c22-cond-dataset-name', cells: ['if (is.data.frame(iris)) x <- 1', 'iris <- 5', 'print(x)'], console: '012 021 / 10', imprecise: { why: 'iris read before a cell binds it is the data set of R, so flowR does not fold the condition', console: '012 021 102', knit: '012 021 102' } }, + { name: 'w27-library-through-lapply', cells: ['options(warn = 2)', 'invisible(lapply("otel", library, character.only = TRUE))', 'l <- log(-1)'], console: '012 102 120 201 210', imprecise: { why: 'a package attached through lapply may export log, so flowR takes no call of log for the one of R', console: '012 021 102 120 201 210', knit: '012 021 102 120 201 210' } }, + { name: 'w28-rm-envir', cells: ['e <- new.env(); assign("x", 1, envir = e)', 'options(warn = 2)', 'rm(x, envir = e)'], console: '012 021 102' }, + { name: 'e03-globalenv-member-cond', cells: ['u <- runif(1, 5, 10)', '.GlobalEnv$u <- 1', 'if (u < 4) x <- 1', 'print(x)'], console: '0123 1203 1230 / 021 102', imprecise: { why: 'two cells bind u, so flowR does not fold the condition', console: '0123 0213 0231 1023 1203 1230', knit: '0123 0213 0231 1023 1203 1230' } }, + { name: 'e04-globalenv-member', cells: ['.GlobalEnv$u <- 1', 'print(u)', 'y <- 1'], console: '012 021 201' }, ]; -const key = (orders: readonly (readonly number[])[]) => orders.map(o => o.join(',')).sort(); +const rmd = (cells: readonly string[]) => cells.map(c => { + const [head, ...code] = c.startsWith('#|') ? c.slice(2).split('\n') : ['', c]; + return `\`\`\`{r${head}}\n${code.join('\n')}\n\`\`\`\n`; +}).join('\ntext\n\n'); +const parse = (orders: string) => { + const [full = '', ends = ''] = orders.split('/').map(s => s.trim()); + return { orders: full.split(' ').filter(o => o !== '').sort(), deadEnds: ends.split(' ').filter(o => o !== '').sort() }; +}; /* the functions the notebooks call from packages, as the signature database of flowR knows them */ const SigDb = fakeSigDb({ MASS: [expFn('fractions')], @@ -310,28 +131,16 @@ describe('Notebook cell orders of the audit notebooks against R', withTreeSitter for(const c of AuditCases) { describe(c.name, () => { for(const [mode, runner] of Object.entries(Modes) as [keyof typeof Modes, CellRunner][]) { - const truth = c[mode]; - const flowr = async(r: CellRunner = runner) => { - const analyzer = await analyze(parser, { request: 'file', content: 'nb.Rmd' }, { files: Object.entries(c.files).map(([f, t]) => new FlowrInlineTextFile(f, t)), sigDb: SigDb }); - const facts = await analyzeNotebook(analyzer, undefined, r); - const all = workingOrders(facts, true).toArray(); - return { orders: all.filter(o => o.length === facts.length), deadEnds: all.filter(o => o.length < facts.length) }; - }; - test(`${mode}: no order or dead end that runs in R is missing`, async() => { - const { orders, deadEnds } = await flowr(); - const runs = [...orders, ...deadEnds]; - for(const o of truth.orders) { - assert.includeDeepMembers(key(orders), key([o]), `R runs ${o.join(',')}`); - } - for(const d of truth.deadEnds) { - assert.isTrue(runs.some(o => d.every((x, k) => o[k] === x)), `R runs ${d.join(',')} before it gets stuck`); - } - }); - const expected = truth.imprecise ?? truth; - test(`${mode}: the orders and dead ends are ${truth.imprecise === undefined ? 'those of R' : `more than those of R, as ${truth.imprecise.why}`}`, async() => { - const { orders, deadEnds } = await flowr(); - assert.deepStrictEqual(key(orders), key(expected.orders)); - assert.deepStrictEqual(key(deadEnds), key(expected.deadEnds)); + const truth = parse(c[mode] ?? c.console); + const pinned = c.imprecise?.[mode]; + test(`${mode}: the orders and dead ends are ${pinned === undefined ? 'those of R' : `more than those of R, as ${c.imprecise?.why}`}`, async() => { + const files = [new FlowrInlineTextFile('nb.Rmd', rmd(c.cells)), ...Object.entries(c.files ?? {}).map(([f, t]) => new FlowrInlineTextFile(f, t))]; + const facts = await analyzeNotebook(await analyze(parser, { request: 'file', content: 'nb.Rmd' }, { files, sigDb: SigDb }), undefined, runner); + const all = workingOrders(facts, true).toArray().map(o => o.join('')); + const [orders, deadEnds] = [all.filter(o => o.length === facts.length).sort(), all.filter(o => o.length < facts.length).sort()]; + assert.includeMembers(orders, truth.orders, 'an order that runs in R is missing'); + assert.isTrue(truth.deadEnds.every(d => all.some(o => o.startsWith(d))), 'a dead end that runs in R is missing'); + assert.deepStrictEqual({ orders, deadEnds }, pinned === undefined ? truth : parse(pinned)); }); } }); diff --git a/test/functionality/notebook/cell-order.test.ts b/test/functionality/notebook/cell-order.test.ts index 195c2d6c9f0..4bf486e349f 100644 --- a/test/functionality/notebook/cell-order.test.ts +++ b/test/functionality/notebook/cell-order.test.ts @@ -799,145 +799,58 @@ describe('Notebook cell orders', withTreeSitter(parser => { fails('a function Reduce is given', ['f <- function(x, y) x + y + a', 'f <- function(x, y) x + y + b', 'a <- 1', 'Reduce(f, 1:3)'], [[[0, 1, 2, 3], [3]], [[1, 0, 2, 3], []]]); fails('functions calling one another', ['f <- function(n) if (n > 0) g(n - 1) else 0', 'g <- function(n) f(n) + a', 'a <- 1', 'f(2)'], [[[0, 1, 3], [3]], [[0, 1, 2, 3], []]]); }); - describe('the runner of the cells', () => { - /* checked in R (cases 07-plot, 11-setwd, and 26-dev-off of the notebooks in cell-order-audit.test.ts): knitr gives each chunk a new plot and the directory of the document, a console keeps both */ - const runs = async(cells: readonly string[], runner?: CellRunner) => { - const analyzer = await analyze(parser, { request: 'file', content: 'nb.Rmd' }, { files: [new FlowrInlineTextFile('nb.Rmd', rmd(cells))] }); - return key(workingOrders(await analyzeNotebook(analyzer, undefined, runner), true).toArray()); - }; - const plot = ['plot(1:10)', 'abline(h = 1)', 'x <- 1']; - test('knitting a document draws on no plot of a chunk before', async() => { - assert.deepStrictEqual(await runs(plot), key([[0, 2], [2, 0]])); - assert.deepStrictEqual(await runs(plot, CellRunner.Knitr), key([[0, 2], [2, 0]])); - }); - test('a session keeps the plot for the cells after', async() => { - assert.deepStrictEqual(await runs(plot, CellRunner.Session), key([[0, 1, 2], [0, 2, 1], [2, 0, 1]])); - }); - test('a session keeps the plot across a removal of all variables', async() => { - assert.deepStrictEqual(await runs(['plot(1:10)', 'rm(list = ls())', 'abline(h = 1)'], CellRunner.Session), key([[0, 1, 2], [0, 2, 1], [1, 0, 2]])); - }); - test('a session closes the plot it keeps with dev.off', async() => { - assert.deepStrictEqual(await runs(['plot(1:10)', 'dev.off()', 'abline(h = 1)'], CellRunner.Session), key([[0, 1], [0, 2, 1]])); - }); - test('a session keeps the working directory', async() => { - assert.deepStrictEqual(await runs(['setwd("sub")', 'd <- read.csv("in.csv")'], CellRunner.Session), key([[0, 1]])); - }); - test('a session runs a chunk knitr would not run', async() => { - const analyzer = await analyze(parser, { request: 'file', content: 'nb.Rmd' }, { files: [new FlowrInlineTextFile('nb.Rmd', rmd(['knitr::opts_chunk$set(eval = FALSE)', 'print(y)', 'y <- 1']))] }); - const knit = key(workingOrders(await analyzeNotebook(analyzer, undefined, CellRunner.Knitr), true).toArray()); - const session = key(workingOrders(await analyzeNotebook(analyzer, undefined, CellRunner.Session), true).toArray()); - assert.include(knit, '0,1,2'); - assert.notInclude(session, '0,1,2'); - assert.include(session, '0,2,1'); - }); - }); - describe('a cell lacking what no cell binds runs in no order', () => { - /* checked in R (case 22-conddef of cell-order-audit.test.ts): `if (FALSE)` binds nothing, so `y <- x + 1` fails in every order */ - test('the orders that run skip it', async() => { - const facts = await factsOf(parser, ['if (FALSE) x <- 1', 'y <- x + 1', 'z <- 1']); - assert.deepStrictEqual(key(workingOrders(facts, true).toArray()), key([[0, 2], [2, 0]])); - /* as far as the order is concerned, every order does */ - assert.lengthOf(workingOrders(facts).toArray(), 6); - }); - /* checked in R: `g()` fails with could not find function "g" */ - test('a call of a function nothing defines', async() => { - assert.deepStrictEqual(key(workingOrders(await factsOf(parser, ['g()', 'x <- 1']), true).toArray()), key([[1]])); - }); - test('but not one in a function body no cell calls', async() => { - assert.deepStrictEqual(key(workingOrders(await factsOf(parser, ['f <- function() g()', 'x <- 1']), true).toArray()), key([[0, 1], [1, 0]])); - }); - test('nor one a cell defines later', async() => { - assert.deepStrictEqual(key(workingOrders(await factsOf(parser, ['g()', 'g <- function() 1']), true).toArray()), key([[1, 0]])); - }); - }); - describe('checked against R: sourced scripts, pipes, files, devices, and data masks', () => { - const runs = async(files: Readonly>, runner: CellRunner) => { - const [main] = Object.keys(files); - const analyzer = await analyze(parser, { request: 'file', content: main }, { files: Object.entries(files).map(([f, t]) => new FlowrInlineTextFile(f, t)), sigDb: fakeSigDb({ dplyr: [expFn('filter'), expFn('%>%')], magrittr: [expFn('%>%')] }) }); - return key(workingOrders(await analyzeNotebook(analyzer, undefined, runner), true).toArray()); - }; - for(const runner of [CellRunner.Session, CellRunner.Knitr]) { - /* checked in R: each `source` reads the script anew, so either cell gives `helper` */ - test(`two cells sourcing the same script each define what it defines (${runner})`, async() => { - assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['source("helpers.R")', 'source("helpers.R")', 'y <- helper(1)']), 'helpers.R': 'helper <- function(v) v + 1\n' }, runner), - key([[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0]])); - }); - test(`sys.source and source of the same script each define what it defines (${runner})`, async() => { - assert.includeMembers(await runs({ 'nb.Rmd': rmd(['sys.source("helpers.R", envir = globalenv())', 'z <- helper(1)', 'source("helpers.R")']), 'helpers.R': 'helper <- function(v) v + 1\n' }, runner), - ['0,1,2', '2,1,0', '0,2,1', '2,0,1']); - }); - /* checked in R: the parser turns `x |> f()` into `f(x)`, which needs no package */ - for(const lib of ['dplyr', 'magrittr']) { - test(`the native pipe needs no package, not even ${lib} (${runner})`, async() => { - assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['d <- mtcars |> head()', `library(${lib})`]) }, runner), key([[0, 1], [1, 0]])); - }); - } - /* checked in R: a relative path is read from the directory of the notebook, wherever flowR runs */ - test(`a file next to the notebook is read without the setwd of another cell (${runner})`, async() => { - assert.includeMembers(await runs({ 'dir/nb.Rmd': rmd(['d <- read.csv("in.csv")', 'setwd("sub")']), 'dir/in.csv': 'a\n1\n', 'dir/sub/in.csv': 'a\n1\n' }, runner), ['0,1']); + describe('orders checked against R', () => { + /* Each case: the cells of a script (`script`) or of an R Markdown notebook run by `runner` (by its default without), or the files of a project whose first one is the notebook, and the orders of cell indices that run (`'012 02'`); with `>=` R runs at least those, and an order written `!012` runs in no case. */ + const sigDb = fakeSigDb({ dplyr: [expFn('filter'), expFn('%>%')], magrittr: [expFn('%>%')] }); + const helpers = { 'helpers.R': 'helper <- function(v) v + 1\n' }; + const cases: readonly (readonly [string, readonly string[] | Readonly>, CellRunner | 'script' | undefined, string])[] = [ + /* knitr gives each chunk a new plot and the directory of the document, a console keeps both (cell-order-audit.test.ts has the plain cases) */ + ['a session keeps the plot across a removal of all variables', ['plot(1:10)', 'rm(list = ls())', 'abline(h = 1)'], CellRunner.Session, '012 021 102'], + ['knitr does not run a chunk after opts_chunk$set(eval = FALSE)', ['knitr::opts_chunk$set(eval = FALSE)', 'print(y)', 'y <- 1'], CellRunner.Knitr, '>= 012'], + ['a session runs a chunk knitr would not run', ['knitr::opts_chunk$set(eval = FALSE)', 'print(y)', 'y <- 1'], CellRunner.Session, '>= 021 !012'], + /* a cell lacking what no cell binds runs in no order (case 22-conddef of the audit): `g()` fails with could not find function "g" */ + ['a call of a function nothing defines', ['g()', 'x <- 1'], undefined, '1'], + ['but not one in a function body no cell calls', ['f <- function() g()', 'x <- 1'], undefined, '01 10'], + ['nor one a cell defines later', ['g()', 'g <- function() 1'], undefined, '10'], + ...[CellRunner.Session, CellRunner.Knitr].flatMap(runner => [ + [`two cells sourcing the same script each define what it defines (${runner})`, { 'nb.Rmd': rmd(['source("helpers.R")', 'source("helpers.R")', 'y <- helper(1)']), ...helpers }, runner, '012 021 102 120'], + [`sys.source and source of the same script each define what it defines (${runner})`, { 'nb.Rmd': rmd(['sys.source("helpers.R", envir = globalenv())', 'z <- helper(1)', 'source("helpers.R")']), ...helpers }, runner, '>= 012 210 021 201'], + /* the parser turns `x |> f()` into `f(x)`, which needs no package */ + [`the native pipe needs no package, not even dplyr or magrittr (${runner})`, ['d <- mtcars |> head()', 'library(dplyr)', 'library(magrittr)'], runner, '012 021 102 120 201 210'], + [`a file next to the notebook is read without the setwd of another cell (${runner})`, { 'dir/nb.Rmd': rmd(['d <- read.csv("in.csv")', 'setwd("sub")']), 'dir/in.csv': 'a\n1\n', 'dir/sub/in.csv': 'a\n1\n' }, runner, '>= 01'] + ] as const), + /* `dev.off()` closes the device `pdf(NULL)` opened, which makes the device with the histogram active again */ + ['closing a device another cell opened leaves the plot of the device before', ['hist(c(1, 2, 2, 3))', 'points(1, 1)', 'dev.off()', 'pdf(NULL)'], CellRunner.Session, '>= 0321'], + /* a data mask reads the columns of the data set R ships first, so `attach` of another cell gives nothing it needs */ + ['a data mask reads the columns of a data set of R', ['d <- data.frame(a = 1:3)', 'b <- with(mtcars, mean(mpg))', 'attach(d)', 'v <- a + 1'], CellRunner.Session, '>= 0123 1023'], + ['a call the native pipe gives the data has it as its data', ['d2 <- mtcars |> subset(mpg > 20)', 'attach(mtcars)'], CellRunner.Session, '01 10'], + ['a call the magrittr pipe gives the data has it as its data', ['library(dplyr)', 'd <- mtcars %>% filter(mpg > 20)', 'attach(mtcars)'], CellRunner.Session, '>= 012 021 201'], + ['a file only in another directory needs the setwd of a session', { 'dir/nb.Rmd': rmd(['setwd("sub")', 'd <- read.csv("in.csv")']), 'dir/sub/in.csv': 'a\n1\n' }, CellRunner.Session, '01'], + /* what may not run (cases c01-c14 and w10 of the audit): with the condition false, the read does not happen */ + ['a read in a branch need not be satisfied', ['if (Sys.getenv("NOPE") == "1") print(x)', 'x <- 1'], 'script', '01 10'], + ['a read in a loop that surely runs must be', ['for (i in 1:3) print(x)', 'x <- 1'], 'script', '10'], + /* the handler `withCallingHandlers` runs is no definition of its name, so removing all variables before it leaves it */ + ['a handler is no definition of the call it is handed to', ['rm(list = ls()); withCallingHandlers(log(-1), warning = function(e) invokeRestart("muffleWarning"))', 'x <- 1'], 'script', '01 10'] + ]; + for(const [name, code, runner, expected] of cases) { + test(name, async() => { + const files = Array.isArray(code) ? undefined : code as Readonly>; + const facts = runner === 'script' ? await scriptFacts(parser, code as readonly string[]) : await analyzeNotebook(await analyze(parser, { request: 'file', content: files ? Object.keys(files)[0] : 'nb.Rmd' }, + { files: Object.entries(files ?? { 'nb.Rmd': rmd(code as readonly string[]) }).map(([f, t]) => new FlowrInlineTextFile(f, t)), sigDb }), undefined, runner); + const got = workingOrders(facts, true).toArray().map(o => o.join('')).sort(); + const words = expected.replace(/^>= /, '').split(' '); + if(expected.startsWith('>= ')) { + assert.includeMembers(got, words.filter(w => !w.startsWith('!'))); + assert.isFalse(words.some(w => w.startsWith('!') && got.includes(w.slice(1)))); + } else { + assert.deepStrictEqual(got, words.sort()); + } }); } - /* checked in R: `dev.off()` closes the device `pdf(NULL)` opened, which makes the device with the histogram active again */ - test('closing a device another cell opened leaves the plot of the device before', async() => { - assert.includeMembers(await runs({ 'nb.Rmd': rmd(['hist(c(1, 2, 2, 3))', 'points(1, 1)', 'dev.off()', 'pdf(NULL)']) }, CellRunner.Session), ['0,3,2,1']); - }); - test('closing the only device closes its plot', async() => { - assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['plot(1:10)', 'dev.off()', 'abline(h = 1)']) }, CellRunner.Session), key([[0, 1], [0, 2, 1]])); - }); - /* checked in R: a data mask reads the columns of the data set R ships first, so `attach` of another cell gives nothing it needs */ - test('a data mask reads the columns of a data set of R', async() => { - assert.includeMembers(await runs({ 'nb.Rmd': rmd(['d <- data.frame(a = 1:3)', 'b <- with(mtcars, mean(mpg))', 'attach(d)', 'v <- a + 1']) }, CellRunner.Session), ['0,1,2,3', '1,0,2,3']); - }); - test('a call the native pipe gives the data has it as its data', async() => { - assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['d2 <- mtcars |> subset(mpg > 20)', 'attach(mtcars)']) }, CellRunner.Session), key([[0, 1], [1, 0]])); - }); - test('a call the magrittr pipe gives the data has it as its data', async() => { - assert.includeMembers(await runs({ 'nb.Rmd': rmd(['library(dplyr)', 'd <- mtcars %>% filter(mpg > 20)', 'attach(mtcars)']) }, CellRunner.Session), ['0,1,2', '0,2,1', '2,0,1']); - }); - /* checked in R (case 28-pipe-lib of cell-order-audit.test.ts): without dplyr, `filter` is `stats::filter`, which evaluates `mpg > 20` and fails */ - test('a column a function of a package masks needs the package where R has a function of its name', async() => { - assert.deepStrictEqual(await runs({ 'nb.Rmd': rmd(['library(dplyr)', 'd <- mtcars |> filter(mpg > 20)', 'x <- 1']) }, CellRunner.Session), key([[0, 1, 2], [0, 2, 1], [2, 0, 1]])); - }); - test('a file only in another directory needs the setwd of a session', async() => { - assert.deepStrictEqual(await runs({ 'dir/nb.Rmd': rmd(['setwd("sub")', 'd <- read.csv("in.csv")']), 'dir/sub/in.csv': 'a\n1\n' }, CellRunner.Session), key([[0, 1]])); - }); - }); - describe('what may not run', () => { - const strict = async(cells: readonly string[]) => key(workingOrders(await scriptFacts(parser, cells), true).toArray()); - /* checked in R: with the condition false, the read, the removal, and the setting of `warn` do not happen */ - test('a read in a branch need not be satisfied', async() => { - assert.deepStrictEqual(await strict(['if (Sys.getenv("NOPE") == "1") print(x)', 'x <- 1']), key([[0, 1], [1, 0]])); - }); - test('a read in a loop that surely runs must be', async() => { - assert.deepStrictEqual(await strict(['for (i in 1:3) print(x)', 'x <- 1']), key([[1, 0]])); - }); - test('a removal in a branch removes nothing for sure', async() => { - assert.deepStrictEqual(await strict(['x <- 1', 'if (Sys.getenv("NOPE") == "1") rm(x)', 'print(x)']), key([[0, 1, 2], [0, 2, 1], [1, 0, 2]])); - }); - test('a branch no draw takes does not run', async() => { - assert.deepStrictEqual(await strict(['if (runif(1) > 2) x <- 1', 'print(x)']), key([[0]])); - }); - test('warnings as errors set in a branch are not sure', async() => { - assert.deepStrictEqual(await strict(['if (Sys.getenv("NOPE") == "1") options(warn = 2)', 'x <- as.numeric("a")']), key([[0, 1], [1, 0]])); - }); - }); - describe('warnings as errors', () => { - const strict = async(cells: readonly string[]) => key(workingOrders(await scriptFacts(parser, cells), true).toArray()); - /* checked in R: under `options(warn = 2)` a warning is an error */ - test('a cell that surely warns runs before warnings become errors', async() => { - assert.deepStrictEqual(await strict(['options(warn = 2)', 'x <- as.numeric("a")']), key([[0], [1, 0]])); - }); - test('and after they are no longer', async() => { - assert.deepStrictEqual(await strict(['options(warn = 2)', 'options(warn = 0)', 'warning("w")']).then(o => o.includes('0,1,2')), true); - }); - test('a muffled warning does not fail', async() => { - assert.deepStrictEqual(await strict(['options(warn = 2)', 'x <- suppressWarnings(as.numeric("a"))']), key([[0, 1], [1, 0]])); - }); - /* checked in R: the handler `withCallingHandlers` runs is no definition of its name, so removing all variables before it leaves it */ - test('a handler is no definition of the call it is handed to', async() => { - assert.deepStrictEqual(await strict(['rm(list = ls()); withCallingHandlers(log(-1), warning = function(e) invokeRestart("muffleWarning"))', 'x <- 1']), key([[0, 1], [1, 0]])); + test('as far as the order is concerned, a cell lacking what no cell binds runs in every order', async() => { + assert.lengthOf(workingOrders(await factsOf(parser, ['if (FALSE) x <- 1', 'y <- x + 1', 'z <- 1'])).toArray(), 6); }); - test('the failure says why', async() => { + test('a failure under warnings as errors says why', async() => { const facts = await scriptFacts(parser, ['options(warn = 2)', 'x <- log(-1)']); assert.deepStrictEqual(checkOrder(facts, [0, 1]).map(f => describeFailure(f)), ['cell 2 warns, which cell 1 turned into an error with options(warn = 2)']); }); diff --git a/test/functionality/queries/resolve-value-query.test.ts b/test/functionality/queries/resolve-value-query.test.ts index b27e9480575..4b4081070cd 100644 --- a/test/functionality/queries/resolve-value-query.test.ts +++ b/test/functionality/queries/resolve-value-query.test.ts @@ -158,10 +158,8 @@ describe('Resolve Value Query', withTreeSitter(parser => { testQuery('a draw equal to a value beyond it', 'x <- rbinom(1, 1, 0.5) == 2', ['1@x'], [[setFrom(ValueLogicalFalse)]]); testQuery('a branch no draw takes defines nothing', 'x <- 0\nif (runif(1) > 2) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0))]]); testQuery('a branch a draw may take may define', 'x <- 0\nif (runif(1) > 0.5) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0), intervalFrom(1, 1))]]); - /* the cells of a notebook may run in any order: a condition folds only on what has the same value in every order */ + /* the cells of a notebook may run in any order: a condition folds only on what has the same value in every order (cases c15 and c21 of cell-order-audit.test.ts bind it twice) */ testQuery('a draw a name is bound to once', 'u <- runif(1, 5, 10)\nx <- 0\nif (u < 4) x <- 1\ny <- x', ['4@y'], [[setFrom(intervalFrom(0, 0))]]); - testQuery('a draw of a function the code binds as well', 'x <- 0\nif (runif(1) > 2) x <- 1\nrunif <- function(n) 5\ny <- x', ['4@y'], [[setFrom(intervalFrom(0, 0), intervalFrom(1, 1))]]); - testQuery('a name the code binds twice', 'k <- FALSE\nx <- 0\nif (k) x <- 1\nk <- TRUE\ny <- x', ['5@y'], [[setFrom(intervalFrom(0, 0), intervalFrom(1, 1))]]); testQuery('a loop over no element defines nothing', 'x <- 0\nfor (i in seq_len(0)) x <- 1\ny <- x', ['3@y'], [[setFrom(intervalFrom(0, 0))]]); }); describe('Bit twiddling', () => {