@smoothbricks/nx-plugin 0.4.28 → 0.4.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +277 -89
- package/dist/bin/smoo-nx-test-clocks.d.ts +3 -0
- package/dist/bin/smoo-nx-test-clocks.d.ts.map +1 -0
- package/dist/bin/smoo-nx-test-clocks.js +28 -0
- package/dist/bounded-test-policy.d.ts +8 -8
- package/dist/bounded-test-policy.d.ts.map +1 -1
- package/dist/bounded-test-policy.js +18 -30
- package/dist/cargo-closure-input.d.ts +23 -0
- package/dist/cargo-closure-input.d.ts.map +1 -1
- package/dist/cargo-closure-input.js +41 -9
- package/dist/cargo-source-hash.d.ts.map +1 -1
- package/dist/cargo-source-hash.js +42 -19
- package/dist/ensure-built-receipt.d.ts +40 -6
- package/dist/ensure-built-receipt.d.ts.map +1 -1
- package/dist/ensure-built-receipt.js +297 -159
- package/dist/ensure-built-witness.d.ts +65 -4
- package/dist/ensure-built-witness.d.ts.map +1 -1
- package/dist/ensure-built-witness.js +2237 -23
- package/dist/ensure-built.d.ts +99 -1
- package/dist/ensure-built.d.ts.map +1 -1
- package/dist/ensure-built.js +45 -56
- package/dist/executors/bounded-exec/cpu-pool.d.ts +22 -7
- package/dist/executors/bounded-exec/cpu-pool.d.ts.map +1 -1
- package/dist/executors/bounded-exec/cpu-pool.js +51 -22
- package/dist/executors/bounded-exec/executor.d.ts +12 -3
- package/dist/executors/bounded-exec/executor.d.ts.map +1 -1
- package/dist/executors/bounded-exec/executor.js +174 -51
- package/dist/executors/bounded-exec/no-space.d.ts +8 -0
- package/dist/executors/bounded-exec/no-space.d.ts.map +1 -0
- package/dist/executors/bounded-exec/no-space.js +31 -0
- package/dist/executors/bounded-exec/ram-temp.d.ts +20 -11
- package/dist/executors/bounded-exec/ram-temp.d.ts.map +1 -1
- package/dist/executors/bounded-exec/ram-temp.js +42 -17
- package/dist/executors/bounded-exec/verdict.d.ts +34 -4
- package/dist/executors/bounded-exec/verdict.d.ts.map +1 -1
- package/dist/executors/bounded-exec/verdict.js +54 -3
- package/dist/generators/bun-test-tracing/generator.js +2 -2
- package/dist/graph-input-contract.d.ts +102 -0
- package/dist/graph-input-contract.d.ts.map +1 -0
- package/dist/graph-input-contract.js +637 -0
- package/dist/index.d.ts +12 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +17 -3
- package/dist/managed-files/ci-workflow.d.ts.map +1 -1
- package/dist/managed-files/ci-workflow.js +5 -2
- package/dist/managed-files/publish-workflow.d.ts +11 -1
- package/dist/managed-files/publish-workflow.d.ts.map +1 -1
- package/dist/owned-installation.d.ts +14 -0
- package/dist/owned-installation.d.ts.map +1 -0
- package/dist/owned-installation.js +324 -0
- package/dist/producer-receipts.d.ts +19 -0
- package/dist/producer-receipts.d.ts.map +1 -0
- package/dist/producer-receipts.js +926 -0
- package/dist/test-backstop.d.ts +9 -0
- package/dist/test-backstop.d.ts.map +1 -0
- package/dist/test-backstop.js +10 -0
- package/dist/test-clock-policy.d.ts +30 -0
- package/dist/test-clock-policy.d.ts.map +1 -0
- package/dist/test-clock-policy.js +686 -0
- package/dist/testing.d.ts +8 -0
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +66 -1
- package/managed/raw/patches/nx@23.2.1.patch +328 -50
- package/managed/raw/tooling/direnv/developer-links.ts +148 -29
- package/managed/raw/tooling/direnv/devenv.smoo.nix +7 -7
- package/managed/raw/tooling/direnv/github-actions-bootstrap.sh +14 -5
- package/managed/raw/tooling/direnv/linked-snapshots.ts +206 -40
- package/managed/raw/tooling/direnv/repo-path +15 -2
- package/managed/raw/tooling/direnv/setup-environment.ts +179 -115
- package/managed/templates/github/actions/cache-node-modules/action.yml +9 -0
- package/managed/templates/github/actions/setup-devenv/action.yml +63 -7
- package/nextest.toml +1 -1
- package/package.json +25 -9
- package/src/__tests__/cargo-closure-fixture.ts +113 -0
- package/src/__tests__/counted-cargo.ts +8 -25
- package/src/__tests__/directory-change.ts +27 -0
- package/src/__tests__/fixture-nx-env.ts +7 -0
- package/src/__tests__/owned-installation.ts +14 -0
- package/src/__tests__/past-tick.ts +12 -0
- package/src/bin/smoo-nx-bound-failures.test.ts +1 -1
- package/src/bin/smoo-nx-test-clocks.ts +29 -0
- package/src/bounded-test-policy.test.ts +36 -22
- package/src/bounded-test-policy.ts +18 -32
- package/src/bun-bootstrap.test.ts +1 -1
- package/src/cargo-closure-input.property.test.ts +50 -0
- package/src/cargo-closure-input.test.ts +73 -121
- package/src/cargo-closure-input.ts +47 -8
- package/src/cargo-closure-key.test.ts +239 -0
- package/src/cargo-resolve-cache.test.ts +168 -31
- package/src/cargo-source-hash.test.ts +78 -3
- package/src/cargo-source-hash.ts +48 -30
- package/src/cross-check-policy.test.ts +2 -2
- package/src/ensure-built-receipt.test.ts +111 -16
- package/src/ensure-built-receipt.ts +294 -149
- package/src/ensure-built-witness.test.ts +306 -13
- package/src/ensure-built-witness.ts +255 -24
- package/src/ensure-built.test.ts +228 -102
- package/src/ensure-built.ts +127 -66
- package/src/executors/bounded-exec/cpu-pool.test.ts +134 -32
- package/src/executors/bounded-exec/cpu-pool.ts +64 -20
- package/src/executors/bounded-exec/cpu-tokens.test.ts +2 -2
- package/src/executors/bounded-exec/disk-lease.test.ts +47 -13
- package/src/executors/bounded-exec/executor-host.test.ts +74 -52
- package/src/executors/bounded-exec/executor.test.ts +343 -97
- package/src/executors/bounded-exec/executor.ts +192 -56
- package/src/executors/bounded-exec/hang-diagnostics.test.ts +14 -8
- package/src/executors/bounded-exec/no-space.ts +40 -0
- package/src/executors/bounded-exec/progress.test.ts +1 -1
- package/src/executors/bounded-exec/ram-temp-host.test.ts +51 -21
- package/src/executors/bounded-exec/ram-temp.test.ts +92 -16
- package/src/executors/bounded-exec/ram-temp.ts +49 -20
- package/src/executors/bounded-exec/verdict.test.ts +127 -22
- package/src/executors/bounded-exec/verdict.ts +78 -3
- package/src/generators/bounded-test-targets/generator.test.ts +1 -3
- package/src/generators/bun-test-tracing/generator.test.ts +2 -2
- package/src/generators/bun-test-tracing/generator.ts +2 -2
- package/src/graph-input-contract.test.ts +379 -0
- package/src/graph-input-contract.ts +627 -0
- package/src/index.test.ts +3 -3
- package/src/index.ts +24 -3
- package/src/linked-snapshots.nx.test.ts +112 -30
- package/src/managed-files/ci-workflow.ts +5 -2
- package/src/managed-files/publish-workflow.ts +12 -1
- package/src/managed-files/repo-path.test.ts +44 -1
- package/src/managed-files/setup-devenv-free-disk.test.ts +95 -0
- package/src/nextest-code-bound.test.ts +23 -17
- package/src/nextest-extraction.test.ts +114 -4
- package/src/nextest-partitions.test.ts +7 -1
- package/src/nx-cache-restore-mtime.test.ts +2 -2
- package/src/nx-daemon-claim.test.ts +10 -8
- package/src/nx-daemon-idle-cpu.test.ts +0 -1
- package/src/nx-daemon-idle-policy.test.ts +61 -1
- package/src/nx-daemon-ignore-files.test.ts +2 -2
- package/src/nx-daemon-validity.test.ts +36 -22
- package/src/nx-dot-input-policy.test.ts +5 -5
- package/src/nx-files-archive-racy.test.ts +1 -1
- package/src/nx-incomplete-run-summary.test.ts +1 -1
- package/src/nx-plugin-load-errors.test.ts +2 -2
- package/src/nx-project-graph-errors.test.ts +70 -0
- package/src/nx-skipped-task-exit.test.ts +2 -2
- package/src/nx-store-resolution.test.ts +7 -25
- package/src/nx-task-output-lease.test.ts +3 -3
- package/src/nx-use-local.test.ts +7 -5
- package/src/owned-installation.ts +174 -0
- package/src/producer-receipts.test.ts +164 -0
- package/src/producer-receipts.ts +636 -0
- package/src/runtime-input.test.ts +1 -1
- package/src/serial-group-wiring.test.ts +4 -4
- package/src/task-results.test.ts +18 -16
- package/src/test-backstop.ts +11 -0
- package/src/test-clock-policy.test.ts +338 -0
- package/src/test-clock-policy.ts +708 -0
- package/src/test-timings.test.ts +2 -2
- package/src/testing.test.ts +5 -5
- package/src/testing.ts +67 -1
- package/src/typecheck-test-policy.test.ts +1 -1
- package/src/typescript-resolution.test.ts +76 -0
- package/test-timings.json +8 -0
|
@@ -0,0 +1,708 @@
|
|
|
1
|
+
// TEST-CLOCK-ORACLE: a test's duration is a property of its work, not of the host. Bun legs delete the runner's
|
|
2
|
+
// per-test deadline with `--timeout=0`, the leg's no-progress bound (`BOUNDED_TEST_IDLE_TIMEOUT_MS`) is the only bound
|
|
3
|
+
// that decides a hang, and a test waits for the event it is waiting for however long a loaded host makes the work take
|
|
4
|
+
// (README "Bounded Test Targets"; specs/cowshed/08_testing.md). Within test code this refuses four kinds:
|
|
5
|
+
// - runner-deadline: a deadline handed to the test runner (`test(name, fn, 60_000)`, `{ timeout }`,
|
|
6
|
+
// `setDefaultTimeout`). It is deleted and nothing takes its place.
|
|
7
|
+
// - test-deadline: the Rust test's own deadline, a `recv_timeout`, `park_timeout` or `timeout` bounded by a literal
|
|
8
|
+
// below the backstop whose expiry fails the case (`.expect`/`.unwrap`). A quiet window (`.await.is_err()`) passes.
|
|
9
|
+
// - clock-delta (class A): an assertion that elapsed host time stays under a bound, `expect(Date.now() - t)
|
|
10
|
+
// .toBeLessThan(N)` or `assert!(started.elapsed() < d)`, which a loaded host breaks while the work is unchanged.
|
|
11
|
+
// Clock values are typed as a reading, a reading moved by a fixed span (a deadline) or time passed, so a lower bound
|
|
12
|
+
// (the wait really waited), ordering against a product timestamp, an epoch stamp, CPU time and an injected clock
|
|
13
|
+
// (`timer.now()`, `clock.elapsed()`) pass.
|
|
14
|
+
// - clocked-bound (class D): a literal product bound below the no-progress backstop in a case whose stand-in a timer or
|
|
15
|
+
// sleep ends before that backstop, so the bound races the stand-in's clock. A bound that is the case's subject with
|
|
16
|
+
// the event that would beat it held off by construction (a child that never answers, or one held at or past the
|
|
17
|
+
// backstop such as `exec sleep 3600`), 0 (disabled), or at the backstop passes.
|
|
18
|
+
// Callers choose the files and, for a diff-scoped check, the changed line ranges: a site is judged when the test case
|
|
19
|
+
// holding it overlaps a change (the whole case, so an edit cannot retain its old site), or, outside any case, when its
|
|
20
|
+
// own line changed. Existing sites therefore need no allowance table. Paused tokio time (`tokio::time::pause()`,
|
|
21
|
+
// `start_paused = true`) is virtual, so a Rust fn using it is not examined.
|
|
22
|
+
//
|
|
23
|
+
// What it cannot do. It stops new sites and removes none: a case nobody edits keeps its elapsed bound, its deadline
|
|
24
|
+
// and its racing bound until a migration touches it. It does not see: a bound passed positionally
|
|
25
|
+
// (`collect(child, 750)`) or held in a constant declared outside the case; a stand-in timer in another file or written
|
|
26
|
+
// by a helper; a bound below the backstop beside real work that no timer delays, which reads exactly like a subject
|
|
27
|
+
// bound whose event is held off by construction; a host clock read through a helper (`elapsedSince(t)`) or a struct
|
|
28
|
+
// field; a deadline enforced by `if (…) throw` or a `while` condition, which it reads as a hang guard, although
|
|
29
|
+
// `assert!(Instant::now() < deadline)` is refused; a Rust deadline in a socket option (`set_read_timeout`),
|
|
30
|
+
// `libc::poll`, a `Duration` held in a variable, or one whose expiry is matched rather than unwrapped; a Rust runner
|
|
31
|
+
// deadline (nextest's slow-timeout is configuration); timer waits themselves (`Bun.sleep` in a test); clock assertions
|
|
32
|
+
// in Python or shell.
|
|
33
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
34
|
+
import { extname, join } from 'node:path';
|
|
35
|
+
import ts from 'typescript';
|
|
36
|
+
import { BOUNDED_TEST_IDLE_TIMEOUT_MS } from './bounded-test-policy.js';
|
|
37
|
+
import { type ChangeRange, TEST_PATH, testCases } from './test-walk-policy.js';
|
|
38
|
+
|
|
39
|
+
export type ClockOracleKind = 'runner-deadline' | 'test-deadline' | 'clock-delta' | 'clocked-bound';
|
|
40
|
+
|
|
41
|
+
export const TEST_CLOCK_ORACLE = {
|
|
42
|
+
id: 'TEST-CLOCK-ORACLE',
|
|
43
|
+
/** The leg's no-progress backstop: a bound at or above it, or 0 (disabled), cannot decide a case. */
|
|
44
|
+
backstopMs: BOUNDED_TEST_IDLE_TIMEOUT_MS,
|
|
45
|
+
message: {
|
|
46
|
+
'runner-deadline': 'tests must not carry a per-test deadline',
|
|
47
|
+
'test-deadline': 'a test-owned deadline decides the case',
|
|
48
|
+
'clock-delta': 'tests must not bound elapsed host time',
|
|
49
|
+
'clocked-bound': 'a configured bound races a stand-in that a timer ends',
|
|
50
|
+
} satisfies Record<ClockOracleKind, string>,
|
|
51
|
+
help: {
|
|
52
|
+
'runner-deadline':
|
|
53
|
+
"Delete the deadline and put nothing in its place: every bun leg runs with --timeout=0 and the leg's " +
|
|
54
|
+
'no-progress bound is the only bound that decides a hang.',
|
|
55
|
+
'test-deadline':
|
|
56
|
+
"Wait for the event itself: the leg's no-progress bound is the only bound that decides a hang. Assert a quiet " +
|
|
57
|
+
'window with `.is_err()`, or advance virtual time with `tokio::time::pause()`.',
|
|
58
|
+
'clock-delta':
|
|
59
|
+
'Elapsed time on a loaded host measures the host, not the work. Assert the order of events or the work done; ' +
|
|
60
|
+
'time-dependent behavior uses an injected clock and asserts its readings.',
|
|
61
|
+
'clocked-bound':
|
|
62
|
+
"A bound a test configures is the case's subject, with the event that would beat it held off by construction " +
|
|
63
|
+
'(a child that never answers, a stand-in that never writes readiness), or it cannot decide: disabled, or at ' +
|
|
64
|
+
"the leg's no-progress backstop (BOUNDED_TEST_IDLE_TIMEOUT_MS). A stand-in that a timer or sleep ends races " +
|
|
65
|
+
'the bound on a loaded host.',
|
|
66
|
+
} satisfies Record<ClockOracleKind, string>,
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export interface ClockOracle {
|
|
70
|
+
readonly kind: ClockOracleKind;
|
|
71
|
+
readonly file: string;
|
|
72
|
+
readonly line: number;
|
|
73
|
+
/** The 1-based column of the site's first character. */
|
|
74
|
+
readonly column: number;
|
|
75
|
+
readonly text: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
interface Site {
|
|
79
|
+
readonly kind: ClockOracleKind;
|
|
80
|
+
readonly offset: number;
|
|
81
|
+
readonly text: string;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const JS_EXTENSION = /^\.(?:[cm]?[jt]sx?)$/u;
|
|
85
|
+
/** A call that sleeps: the stand-in sleeps a child or helper runs. */
|
|
86
|
+
const SLEEP_CALL =
|
|
87
|
+
/(?:\bBun\.sleep(?:Sync)?|\b(?:std::)?thread::sleep|\btokio::time::sleep|\b(?:asyncio|time)\.sleep|\bThread\.sleep|(?<![.\w])(?:sleep|sleep_for|sleep_until|usleep)|\b\w+\.waitForTimeout)\s*\(/u;
|
|
88
|
+
/** A call that arms a timer. */
|
|
89
|
+
const TIMER_CALL_PATTERN =
|
|
90
|
+
/(?:(?<![.\w])(?:setTimeout|setInterval)|\b(?:globalThis|window)\.(?:setTimeout|setInterval))\s*\(/u;
|
|
91
|
+
/** A call that sleeps or arms a timer. */
|
|
92
|
+
const TIMER_CALL = new RegExp(`${SLEEP_CALL.source}|${TIMER_CALL_PATTERN.source}`, 'u');
|
|
93
|
+
/** Source text of a stand-in that a timer or sleep ends: a call, a child's `-e` script, a shell line, an argv `sleep`. */
|
|
94
|
+
const TIMED_STAND_IN = new RegExp(
|
|
95
|
+
`${TIMER_CALL.source}|${/(?:^|[;&|\n"'`(]|\bexec)\s*sleep\s+(?:\d|["'$])|["'`]sleep["'`]/u.source}`,
|
|
96
|
+
'gu',
|
|
97
|
+
);
|
|
98
|
+
/** A span written as a number or one constant operation on two (`5000`, `1 << 30`, `2 ** 31`, `60 * 1000`). */
|
|
99
|
+
function spanValue(text: string): number | undefined {
|
|
100
|
+
const operation = /^\s*(\d[\d_]*(?:\.\d+)?)\s*(?:(<<|\*\*|\*)\s*(\d[\d_]*(?:\.\d+)?))?\s*$/u.exec(text);
|
|
101
|
+
if (operation === null) return undefined;
|
|
102
|
+
const left = Number((operation[1] ?? '').replaceAll('_', ''));
|
|
103
|
+
const right = Number((operation[3] ?? '').replaceAll('_', ''));
|
|
104
|
+
switch (operation[2]) {
|
|
105
|
+
case '<<':
|
|
106
|
+
return left * 2 ** right;
|
|
107
|
+
case '**':
|
|
108
|
+
return left ** right;
|
|
109
|
+
case '*':
|
|
110
|
+
return left * right;
|
|
111
|
+
default:
|
|
112
|
+
return left;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/** The span of the timer or sleep starting `text`, in milliseconds, when its source states one. */
|
|
116
|
+
function timerSpanMs(text: string): number | undefined {
|
|
117
|
+
const shell = /^(?:[;&|\n"'`(]|exec)?\s*sleep\s+(\d+(?:\.\d+)?)([smhd]?)(?![\w.])/u.exec(text);
|
|
118
|
+
if (shell !== null) return Number(shell[1]) * 1000 * ({ m: 60, h: 3600, d: 86_400 }[shell[2] ?? ''] ?? 1);
|
|
119
|
+
const argv = /^["'`]sleep["'`]\s*(?:,|\)\s*\.arg\()\s*["'`](\d+(?:\.\d+)?)["'`]/u.exec(text);
|
|
120
|
+
if (argv !== null) return Number(argv[1]) * 1000;
|
|
121
|
+
const timer = /^(?:(?:globalThis|window)\.)?set(?:Timeout|Interval)\s*\([^;]*?,\s*([^,()]+?)\s*\)/u.exec(
|
|
122
|
+
text.slice(0, 400),
|
|
123
|
+
);
|
|
124
|
+
if (timer !== null) return spanValue(timer[1] ?? '');
|
|
125
|
+
const bun = /^Bun\.sleep(?:Sync)?\s*\(([^()]+)\)/u.exec(text);
|
|
126
|
+
if (bun !== null) return spanValue(bun[1] ?? '');
|
|
127
|
+
const seconds = /^(?:asyncio|time)\.sleep\s*\(\s*(\d+(?:\.\d+)?)\s*\)/u.exec(text);
|
|
128
|
+
if (seconds !== null) return Number(seconds[1]) * 1000;
|
|
129
|
+
const rust =
|
|
130
|
+
/^(?:(?:std::)?thread|tokio::time)::sleep\s*\(\s*(?:std::time::)?Duration::from_(secs|millis)\s*\(\s*(\d[\d_]*)\s*\)\s*\)/u.exec(
|
|
131
|
+
text,
|
|
132
|
+
);
|
|
133
|
+
if (rust !== null) return Number((rust[2] ?? '').replaceAll('_', '')) * (rust[1] === 'secs' ? 1000 : 1);
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Whether source text holds a stand-in whose timer can beat a bound before the leg's backstop. A one-shot timer or
|
|
138
|
+
* sleep ends or advances its stand-in when it fires. A repeating timer never ends one, so it races only a progress
|
|
139
|
+
* (idle) bound, and only when its callback does something. A span at or past the backstop (`exec sleep 3600`,
|
|
140
|
+
* `setInterval(() => {}, 1 << 30)`) outlasts the leg, so its stand-in is held off as surely as a child that never
|
|
141
|
+
* answers; an unstated span races.
|
|
142
|
+
*/
|
|
143
|
+
function racesBound(text: string, idle: boolean): boolean {
|
|
144
|
+
for (const match of text.matchAll(TIMED_STAND_IN)) {
|
|
145
|
+
const at = text.slice(match.index);
|
|
146
|
+
const repeating = /^(?:(?:globalThis|window)\.)?setInterval\s*\(/u.exec(at);
|
|
147
|
+
if (repeating !== null && (!idle || /^\s*\(\s*\)\s*=>\s*\{\s*\}\s*,/u.test(at.slice(repeating[0].length))))
|
|
148
|
+
continue;
|
|
149
|
+
const ms = timerSpanMs(at);
|
|
150
|
+
if (ms === undefined || ms < TEST_CLOCK_ORACLE.backstopMs) return true;
|
|
151
|
+
}
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
/** A liveness bound by name: any timeout or deadline, or a grace, kill, budget or idle span carrying a time unit. */
|
|
155
|
+
function boundName(name: string): boolean {
|
|
156
|
+
return (
|
|
157
|
+
/time_?out|deadline/iu.test(name) ||
|
|
158
|
+
(/grace|kill_?after|budget|idle/iu.test(name) && /(?:ms|millis|milliseconds|seconds?|secs?)$/iu.test(name))
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
/** A bound's value in milliseconds from its name's unit; one that is 0 or at the backstop cannot decide a case. */
|
|
162
|
+
function decides(name: string, value: number): boolean {
|
|
163
|
+
const ms = /(?:seconds?|secs?|_s)$/iu.test(name) ? value * 1000 : value;
|
|
164
|
+
return ms > 0 && ms < TEST_CLOCK_ORACLE.backstopMs;
|
|
165
|
+
}
|
|
166
|
+
/** `--timeout=100`, `--idle-timeout 5s`, `--deadline-ms=50` inside a command string. */
|
|
167
|
+
const FLAG_BOUND = /--[\w-]*(?:timeout|deadline)[\w-]*[= ](\d[\d_]*(?:\.\d+)?)(ms|s)?\b/giu;
|
|
168
|
+
|
|
169
|
+
/** What a value read from the host clock is: a reading, a reading moved by a fixed span, or time passed. */
|
|
170
|
+
type Clock = 'instant' | 'deadline' | 'duration';
|
|
171
|
+
const CLOCK_RANK = { instant: 1, deadline: 2, duration: 3 } as const satisfies Record<Clock, number>;
|
|
172
|
+
|
|
173
|
+
function strongest(clocks: readonly (Clock | undefined)[]): Clock | undefined {
|
|
174
|
+
let found: Clock | undefined;
|
|
175
|
+
for (const clock of clocks)
|
|
176
|
+
if (clock !== undefined && (found === undefined || CLOCK_RANK[clock] > CLOCK_RANK[found])) found = clock;
|
|
177
|
+
return found;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Whether asserting `lower` below `upper` bounds host time: a duration under any bound, or a reading under a deadline.
|
|
182
|
+
* A duration over a bound (the wait really waited) and a reading below a product timestamp (ordering) do not.
|
|
183
|
+
*/
|
|
184
|
+
function boundsHostTime(lower: Clock | undefined, upper: Clock | undefined): boolean {
|
|
185
|
+
return lower === 'duration' || (lower === 'instant' && upper === 'deadline');
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function literalNumber(node: ts.Expression): number | undefined {
|
|
189
|
+
if (ts.isNumericLiteral(node)) return Number(node.text);
|
|
190
|
+
if (ts.isParenthesizedExpression(node)) return literalNumber(node.expression);
|
|
191
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
|
|
192
|
+
const value = literalNumber(node.operand);
|
|
193
|
+
return value === undefined ? undefined : -value;
|
|
194
|
+
}
|
|
195
|
+
if (!ts.isBinaryExpression(node)) return undefined;
|
|
196
|
+
const [left, right] = [literalNumber(node.left), literalNumber(node.right)];
|
|
197
|
+
if (left === undefined || right === undefined) return undefined;
|
|
198
|
+
switch (node.operatorToken.kind) {
|
|
199
|
+
case ts.SyntaxKind.AsteriskToken:
|
|
200
|
+
return left * right;
|
|
201
|
+
case ts.SyntaxKind.SlashToken:
|
|
202
|
+
return left / right;
|
|
203
|
+
case ts.SyntaxKind.PlusToken:
|
|
204
|
+
return left + right;
|
|
205
|
+
case ts.SyntaxKind.MinusToken:
|
|
206
|
+
return left - right;
|
|
207
|
+
default:
|
|
208
|
+
return undefined;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const CLOCK_READ = /^(?:Date\.now|performance\.now|Bun\.nanoseconds|process\.hrtime\.bigint)$/u;
|
|
213
|
+
const COMPARISON: Partial<Record<ts.SyntaxKind, 'below' | 'above'>> = {
|
|
214
|
+
[ts.SyntaxKind.LessThanToken]: 'below',
|
|
215
|
+
[ts.SyntaxKind.LessThanEqualsToken]: 'below',
|
|
216
|
+
[ts.SyntaxKind.GreaterThanToken]: 'above',
|
|
217
|
+
[ts.SyntaxKind.GreaterThanEqualsToken]: 'above',
|
|
218
|
+
};
|
|
219
|
+
const ORDER_MATCHER = /^toBe(Less|Greater)Than(?:OrEqual)?$/u;
|
|
220
|
+
const TRUTH_MATCHER = /^to(?:Be|Equal|StrictEqual)$/u;
|
|
221
|
+
const CASE_CALLEE = /^(?:test|it)(?:\.\w+)*$/u;
|
|
222
|
+
/** A harness that runs its callback on faked timers: `onProgressClock`, `withFakeClock`, `underMemoryTimer`. */
|
|
223
|
+
const VIRTUAL_CLOCK_CALL = /^(?:on|with|under)\w*(?:Clock|Timers?)$/u;
|
|
224
|
+
|
|
225
|
+
/** Class A and class D sites of one TypeScript/JavaScript test file. */
|
|
226
|
+
function jsClockSites(parsed: ts.SourceFile): Site[] {
|
|
227
|
+
const sites: Site[] = [];
|
|
228
|
+
const site = (node: ts.Node, kind: ClockOracleKind): void => {
|
|
229
|
+
sites.push({ kind, offset: node.getStart(parsed), text: node.getText(parsed) });
|
|
230
|
+
};
|
|
231
|
+
// Lexical scopes of the names bound to a host clock value; an inner declaration or parameter shadows an outer one.
|
|
232
|
+
const scopes: Map<string, Clock | undefined>[] = [new Map()];
|
|
233
|
+
const lookup = (name: string): Clock | undefined => {
|
|
234
|
+
for (let index = scopes.length - 1; index >= 0; index -= 1) {
|
|
235
|
+
const scope = scopes[index];
|
|
236
|
+
if (scope?.has(name)) return scope.get(name);
|
|
237
|
+
}
|
|
238
|
+
return undefined;
|
|
239
|
+
};
|
|
240
|
+
const clockOf = (node: ts.Expression): Clock | undefined => {
|
|
241
|
+
if (
|
|
242
|
+
ts.isParenthesizedExpression(node) ||
|
|
243
|
+
ts.isAsExpression(node) ||
|
|
244
|
+
ts.isNonNullExpression(node) ||
|
|
245
|
+
ts.isSatisfiesExpression(node) ||
|
|
246
|
+
ts.isTypeAssertionExpression(node) ||
|
|
247
|
+
ts.isElementAccessExpression(node)
|
|
248
|
+
)
|
|
249
|
+
return clockOf(node.expression);
|
|
250
|
+
if (ts.isIdentifier(node)) return lookup(node.text);
|
|
251
|
+
if (ts.isNewExpression(node))
|
|
252
|
+
return ts.isIdentifier(node.expression) && node.expression.text === 'Date' && !node.arguments?.length
|
|
253
|
+
? 'instant'
|
|
254
|
+
: undefined;
|
|
255
|
+
if (ts.isPrefixUnaryExpression(node)) return clockOf(node.operand);
|
|
256
|
+
if (ts.isConditionalExpression(node)) return strongest([clockOf(node.whenTrue), clockOf(node.whenFalse)]);
|
|
257
|
+
if (ts.isCallExpression(node)) {
|
|
258
|
+
const callee = node.expression.getText(parsed);
|
|
259
|
+
if (CLOCK_READ.test(callee)) return 'instant';
|
|
260
|
+
if (callee === 'process.hrtime') return node.arguments.length === 0 ? 'instant' : 'duration';
|
|
261
|
+
if (ts.isPropertyAccessExpression(node.expression) && /^(?:getTime|valueOf)$/u.test(node.expression.name.text))
|
|
262
|
+
return clockOf(node.expression.expression);
|
|
263
|
+
if (/^(?:Math\.\w+|Number|BigInt)$/u.test(callee)) return strongest(node.arguments.map(clockOf));
|
|
264
|
+
return undefined;
|
|
265
|
+
}
|
|
266
|
+
if (!ts.isBinaryExpression(node)) return undefined;
|
|
267
|
+
const [left, right] = [clockOf(node.left), clockOf(node.right)];
|
|
268
|
+
switch (node.operatorToken.kind) {
|
|
269
|
+
case ts.SyntaxKind.MinusToken:
|
|
270
|
+
if (left === 'duration' || right === 'duration') return 'duration';
|
|
271
|
+
if (left === undefined && right === undefined) return undefined;
|
|
272
|
+
// A reading less a fixed span is still a moment; a reading less anything else is time passed.
|
|
273
|
+
return right === undefined && literalNumber(node.right) !== undefined ? 'deadline' : 'duration';
|
|
274
|
+
case ts.SyntaxKind.PlusToken:
|
|
275
|
+
if (left === 'duration' || right === 'duration') return 'duration';
|
|
276
|
+
return left === undefined && right === undefined ? undefined : 'deadline';
|
|
277
|
+
case ts.SyntaxKind.AsteriskToken:
|
|
278
|
+
case ts.SyntaxKind.SlashToken:
|
|
279
|
+
case ts.SyntaxKind.PercentToken:
|
|
280
|
+
return strongest([left, right]);
|
|
281
|
+
case ts.SyntaxKind.CommaToken:
|
|
282
|
+
return right;
|
|
283
|
+
default:
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
// Whether an assertion over `node` asserts a comparison that bounds host time; `negated` when it asserts the
|
|
288
|
+
// comparison's negation. Nested functions are not the assertion's own comparison.
|
|
289
|
+
const comparesHostTime = (node: ts.Node, negated: boolean): boolean => {
|
|
290
|
+
if (ts.isFunctionLike(node)) return false;
|
|
291
|
+
if (ts.isBinaryExpression(node)) {
|
|
292
|
+
const direction = COMPARISON[node.operatorToken.kind];
|
|
293
|
+
if (direction !== undefined) {
|
|
294
|
+
const [lower, upper] = (direction === 'below') !== negated ? [node.left, node.right] : [node.right, node.left];
|
|
295
|
+
return boundsHostTime(clockOf(lower), clockOf(upper));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.ExclamationToken)
|
|
299
|
+
return comparesHostTime(node.operand, !negated);
|
|
300
|
+
return ts.forEachChild(node, (child) => comparesHostTime(child, negated) || undefined) ?? false;
|
|
301
|
+
};
|
|
302
|
+
const expectation = (
|
|
303
|
+
call: ts.CallExpression,
|
|
304
|
+
): { subject: ts.Expression; negated: boolean; matcher: string } | undefined => {
|
|
305
|
+
if (!ts.isPropertyAccessExpression(call.expression)) return undefined;
|
|
306
|
+
let negated = false;
|
|
307
|
+
let receiver = call.expression.expression;
|
|
308
|
+
while (ts.isPropertyAccessExpression(receiver) && receiver.name.text === 'not') {
|
|
309
|
+
negated = !negated;
|
|
310
|
+
receiver = receiver.expression;
|
|
311
|
+
}
|
|
312
|
+
if (!ts.isCallExpression(receiver) || !ts.isIdentifier(receiver.expression)) return undefined;
|
|
313
|
+
const subject = receiver.arguments[0];
|
|
314
|
+
if (receiver.expression.text !== 'expect' || subject === undefined) return undefined;
|
|
315
|
+
return { subject, negated, matcher: call.expression.name.text };
|
|
316
|
+
};
|
|
317
|
+
const assertsHostTime = (call: ts.CallExpression): boolean => {
|
|
318
|
+
const expected = expectation(call);
|
|
319
|
+
const argument = call.arguments[0];
|
|
320
|
+
if (expected === undefined) {
|
|
321
|
+
let root: ts.Expression = call.expression;
|
|
322
|
+
while (ts.isPropertyAccessExpression(root)) root = root.expression;
|
|
323
|
+
return (
|
|
324
|
+
ts.isIdentifier(root) &&
|
|
325
|
+
/^(?:assert\w*|ok)$/u.test(root.text) &&
|
|
326
|
+
call.arguments.some((each) => comparesHostTime(each, false))
|
|
327
|
+
);
|
|
328
|
+
}
|
|
329
|
+
const { subject, negated, matcher } = expected;
|
|
330
|
+
const order = ORDER_MATCHER.exec(matcher);
|
|
331
|
+
if (order !== null && argument !== undefined) {
|
|
332
|
+
const [lower, upper] = (order[1] === 'Less') !== negated ? [subject, argument] : [argument, subject];
|
|
333
|
+
return boundsHostTime(clockOf(lower), clockOf(upper));
|
|
334
|
+
}
|
|
335
|
+
if (matcher === 'toBeCloseTo' && argument !== undefined)
|
|
336
|
+
return clockOf(subject) !== undefined || clockOf(argument) !== undefined;
|
|
337
|
+
const truth =
|
|
338
|
+
matcher === 'toBeTruthy' || matcher === 'toBeTrue'
|
|
339
|
+
? true
|
|
340
|
+
: matcher === 'toBeFalsy' || matcher === 'toBeFalse'
|
|
341
|
+
? false
|
|
342
|
+
: TRUTH_MATCHER.test(matcher) && argument?.kind === ts.SyntaxKind.TrueKeyword
|
|
343
|
+
? true
|
|
344
|
+
: TRUTH_MATCHER.test(matcher) && argument?.kind === ts.SyntaxKind.FalseKeyword
|
|
345
|
+
? false
|
|
346
|
+
: undefined;
|
|
347
|
+
return truth !== undefined && comparesHostTime(subject, truth === negated);
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
// Top-level string constants a case may hand a child as its source (`const SLOW_TEST = \`…setTimeout(r, 5000)…\``).
|
|
351
|
+
const constants = new Map<string, string>();
|
|
352
|
+
for (const statement of parsed.statements) {
|
|
353
|
+
if (!ts.isVariableStatement(statement)) continue;
|
|
354
|
+
for (const declaration of statement.declarationList.declarations) {
|
|
355
|
+
const value = declaration.initializer;
|
|
356
|
+
if (ts.isIdentifier(declaration.name) && value !== undefined && ts.isStringLiteralLike(value))
|
|
357
|
+
constants.set(declaration.name.text, value.getText(parsed));
|
|
358
|
+
if (ts.isIdentifier(declaration.name) && value !== undefined && ts.isTemplateExpression(value))
|
|
359
|
+
constants.set(declaration.name.text, value.getText(parsed));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// What the stand-ins under `scope` do to a bound: none is there, every one is held off, or one races it.
|
|
363
|
+
const standIns = (scope: ts.Node, idle: boolean): 'none' | 'held' | 'races' => {
|
|
364
|
+
let found = false;
|
|
365
|
+
const visit = (node: ts.Node): boolean => {
|
|
366
|
+
const text =
|
|
367
|
+
ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)
|
|
368
|
+
? node.getText(parsed)
|
|
369
|
+
: ts.isCallExpression(node) && TIMER_CALL.test(`${node.expression.getText(parsed)}(`)
|
|
370
|
+
? node.getText(parsed)
|
|
371
|
+
: ts.isIdentifier(node)
|
|
372
|
+
? constants.get(node.text)
|
|
373
|
+
: undefined;
|
|
374
|
+
if (text !== undefined && text.search(TIMED_STAND_IN) !== -1) {
|
|
375
|
+
found = true;
|
|
376
|
+
if (racesBound(text, idle)) return true;
|
|
377
|
+
}
|
|
378
|
+
return ts.forEachChild(node, (child) => visit(child) || undefined) ?? false;
|
|
379
|
+
};
|
|
380
|
+
return visit(scope) ? 'races' : found ? 'held' : 'none';
|
|
381
|
+
};
|
|
382
|
+
// The case a bound belongs to: its enclosing `test`/`it` call, else its function, else the file.
|
|
383
|
+
const owner = (node: ts.Node): ts.Node => {
|
|
384
|
+
let fn: ts.Node | undefined;
|
|
385
|
+
for (let up = node.parent; up !== undefined; up = up.parent) {
|
|
386
|
+
if (ts.isCallExpression(up) && CASE_CALLEE.test(up.expression.getText(parsed))) return up;
|
|
387
|
+
if (fn === undefined && ts.isFunctionLike(up)) fn = up;
|
|
388
|
+
}
|
|
389
|
+
return fn ?? parsed;
|
|
390
|
+
};
|
|
391
|
+
const bounds: { readonly node: ts.Node; readonly idle: boolean }[] = [];
|
|
392
|
+
const runnerOptions = new Set<ts.Node>();
|
|
393
|
+
|
|
394
|
+
const visit = (node: ts.Node): void => {
|
|
395
|
+
const opens = node !== parsed && (ts.isFunctionLike(node) || ts.isBlock(node));
|
|
396
|
+
if (opens) scopes.push(new Map());
|
|
397
|
+
if (ts.isFunctionLike(node))
|
|
398
|
+
for (const parameter of node.parameters)
|
|
399
|
+
if (ts.isIdentifier(parameter.name)) scopes.at(-1)?.set(parameter.name.text, undefined);
|
|
400
|
+
if (ts.isCallExpression(node) && assertsHostTime(node)) site(node, 'clock-delta');
|
|
401
|
+
if (ts.isCallExpression(node)) {
|
|
402
|
+
// `test(name, fn, 60_000)`, `test(name, fn, { timeout })`, `test.each(table)(name, fn, n)`, `setDefaultTimeout(n)`.
|
|
403
|
+
const callee = node.expression;
|
|
404
|
+
const runner =
|
|
405
|
+
CASE_CALLEE.test(callee.getText(parsed)) ||
|
|
406
|
+
(ts.isCallExpression(callee) && /^(?:test|it)(?:\.\w+)*\.each$/u.test(callee.expression.getText(parsed)));
|
|
407
|
+
const body = node.arguments.findIndex((each) => ts.isArrowFunction(each) || ts.isFunctionExpression(each));
|
|
408
|
+
if (runner && body !== -1)
|
|
409
|
+
for (const option of node.arguments.slice(body + 1))
|
|
410
|
+
if (
|
|
411
|
+
literalNumber(option) !== undefined ||
|
|
412
|
+
(ts.isObjectLiteralExpression(option) &&
|
|
413
|
+
option.properties.some((each) => each.name?.getText(parsed) === 'timeout'))
|
|
414
|
+
) {
|
|
415
|
+
runnerOptions.add(option);
|
|
416
|
+
site(option, 'runner-deadline');
|
|
417
|
+
}
|
|
418
|
+
if (/^(?:setDefaultTimeout|jest\.setTimeout)$/u.test(callee.getText(parsed))) site(node, 'runner-deadline');
|
|
419
|
+
}
|
|
420
|
+
// A runner's own `{ timeout }` is a runner deadline above, never also a product bound.
|
|
421
|
+
if ((ts.isPropertyAssignment(node) && !runnerOptions.has(node.parent)) || ts.isVariableDeclaration(node)) {
|
|
422
|
+
const name =
|
|
423
|
+
ts.isIdentifier(node.name) || ts.isStringLiteral(node.name) ? node.name.text : node.name.getText(parsed);
|
|
424
|
+
const value = node.initializer === undefined ? undefined : literalNumber(node.initializer);
|
|
425
|
+
if (boundName(name) && value !== undefined && decides(name, value))
|
|
426
|
+
bounds.push({ node, idle: /idle/iu.test(name) });
|
|
427
|
+
}
|
|
428
|
+
if (ts.isStringLiteralLike(node) || ts.isTemplateExpression(node)) {
|
|
429
|
+
for (const flag of node.getText(parsed).matchAll(FLAG_BOUND)) {
|
|
430
|
+
const value = Number((flag[1] ?? '').replaceAll('_', ''));
|
|
431
|
+
if (decides(flag[2] === 's' ? 'seconds' : 'ms', value)) bounds.push({ node, idle: /idle/iu.test(flag[0]) });
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
ts.forEachChild(node, visit);
|
|
435
|
+
// A declaration binds after its initializer is read; an assignment rebinds the nearest declaration.
|
|
436
|
+
if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name))
|
|
437
|
+
scopes.at(-1)?.set(node.name.text, node.initializer === undefined ? undefined : clockOf(node.initializer));
|
|
438
|
+
if (
|
|
439
|
+
ts.isBinaryExpression(node) &&
|
|
440
|
+
node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
|
|
441
|
+
ts.isIdentifier(node.left)
|
|
442
|
+
) {
|
|
443
|
+
const name = node.left.text;
|
|
444
|
+
for (let index = scopes.length - 1; index >= 0; index -= 1) {
|
|
445
|
+
const scope = scopes[index];
|
|
446
|
+
if (scope?.has(name)) {
|
|
447
|
+
scope.set(name, clockOf(node.right));
|
|
448
|
+
break;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (opens) scopes.pop();
|
|
453
|
+
};
|
|
454
|
+
visit(parsed);
|
|
455
|
+
// A bound is judged against the stand-ins of the call it configures when that call names any (`verdictOf(command,
|
|
456
|
+
// { idleTimeoutMs })`), else against its case's: one case may hold a talking child under a ceiling and a silent one
|
|
457
|
+
// under a progress bound. A value an assertion expects (`toMatchObject({ idleMs: 400 })`) configures nothing, and a
|
|
458
|
+
// bound run under faked timers (`jest.useFakeTimers()` in its case, or inside a clock harness such as
|
|
459
|
+
// `onProgressClock(moves, step, run)`) expires only when the test moves the clock.
|
|
460
|
+
const reported = new Set<ts.Node>();
|
|
461
|
+
for (const { node, idle } of bounds) {
|
|
462
|
+
if (reported.has(node)) continue;
|
|
463
|
+
let call: ts.CallExpression | undefined;
|
|
464
|
+
let virtual = false;
|
|
465
|
+
for (let up = node.parent; up !== undefined; up = up.parent) {
|
|
466
|
+
if (!ts.isCallExpression(up)) continue;
|
|
467
|
+
call ??= up;
|
|
468
|
+
const callee = up.expression.getText(parsed);
|
|
469
|
+
if (VIRTUAL_CLOCK_CALL.test(callee.slice(callee.lastIndexOf('.') + 1))) virtual = true;
|
|
470
|
+
}
|
|
471
|
+
const scope = owner(node);
|
|
472
|
+
if (virtual || /\buseFakeTimers\s*\(/u.test(scope.getText(parsed))) continue;
|
|
473
|
+
if (call !== undefined && /^expect\s*\(/u.test(call.expression.getText(parsed))) continue;
|
|
474
|
+
const near = call === undefined ? 'none' : standIns(call, idle);
|
|
475
|
+
if ((near === 'none' ? standIns(scope, idle) : near) !== 'races') continue;
|
|
476
|
+
reported.add(node);
|
|
477
|
+
site(node, 'clocked-bound');
|
|
478
|
+
}
|
|
479
|
+
return sites;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/**
|
|
483
|
+
* Blank comments and, with `strings`, quoted text, keeping every byte position. A single quote never spans a line, so
|
|
484
|
+
* a Rust lifetime (`&'a str`) masks at most the rest of its own line.
|
|
485
|
+
*/
|
|
486
|
+
function maskNative(source: string, strings: boolean): string {
|
|
487
|
+
return source.replace(
|
|
488
|
+
/\/\/[^\n]*|\/\*[\s\S]*?\*\/|"""[\s\S]*?"""|'''[\s\S]*?'''|\br(#*)"[\s\S]*?"\1|"(?:\\[\s\S]|[^"\\])*"|'(?:\\.|[^'\\\n])*'/gu,
|
|
489
|
+
(text) => (strings || text.startsWith('/') ? text.replace(/[^\r\n]/g, ' ') : text),
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/** Where a native file's test code starts: Rust src/ files are examined only inside their embedded test module. */
|
|
494
|
+
function testCodeStart(masked: string, file: string): number | undefined {
|
|
495
|
+
if (extname(file) !== '.rs' || TEST_PATH.test(file)) return 0;
|
|
496
|
+
return /#\[cfg\(test\)\][\s\S]*?\bmod\s+tests\s*\{/u.exec(masked)?.index;
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/** The index closing the group opened at `open` in comment/string-masked text. */
|
|
500
|
+
function closingIndex(masked: string, open: number): number {
|
|
501
|
+
let depth = 0;
|
|
502
|
+
for (let index = open; index < masked.length; index += 1) {
|
|
503
|
+
const char = masked[index];
|
|
504
|
+
if (char === '(' || char === '[' || char === '{') depth += 1;
|
|
505
|
+
else if (char === ')' || char === ']' || char === '}') {
|
|
506
|
+
depth -= 1;
|
|
507
|
+
if (depth === 0) return index;
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
return masked.length;
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** The host clock value a Rust expression holds, given the `let` bindings of its fn. */
|
|
514
|
+
function rustClock(expression: string, bindings: ReadonlyMap<string, Clock | undefined>): Clock | undefined {
|
|
515
|
+
// `elapsed`/`duration_since` on a host reading is time passed; on an injected clock (`clock.elapsed()`) it is not,
|
|
516
|
+
// and since `UNIX_EPOCH` it is a timestamp, still a reading.
|
|
517
|
+
for (const call of expression.matchAll(
|
|
518
|
+
/(\b[a-z_]\w*|\b(?:Instant|SystemTime)::now\s*\(\s*\))\s*\.\s*(?:elapsed|(?:saturating_|checked_)?duration_since)\s*\(/gu,
|
|
519
|
+
)) {
|
|
520
|
+
if (/^\s*(?:std::time::)?(?:SystemTime::)?UNIX_EPOCH\b/u.test(expression.slice(call.index + call[0].length)))
|
|
521
|
+
continue;
|
|
522
|
+
const receiver = call[1] ?? '';
|
|
523
|
+
const held = bindings.get(receiver);
|
|
524
|
+
if (receiver.endsWith(')') || held === 'instant' || held === 'deadline') return 'duration';
|
|
525
|
+
}
|
|
526
|
+
const clocks = (text: string): Clock | undefined =>
|
|
527
|
+
strongest([
|
|
528
|
+
/\b(?:Instant|SystemTime)::now\s*\(\s*\)/u.test(text) ? 'instant' : undefined,
|
|
529
|
+
...Array.from(text.matchAll(/\b[a-z_]\w*\b/gu), (name) => bindings.get(name[0])),
|
|
530
|
+
]);
|
|
531
|
+
const base = clocks(expression);
|
|
532
|
+
if (base === undefined || base === 'duration') return base;
|
|
533
|
+
const minus = /[\w)\]]\s*-(?!>)/u.exec(expression);
|
|
534
|
+
if (minus !== null) {
|
|
535
|
+
// A reading less a reading is time passed; a reading less a `Duration` is still a moment.
|
|
536
|
+
const right = clocks(expression.slice(minus.index + minus[0].length));
|
|
537
|
+
return right === 'instant' || right === 'deadline' ? 'duration' : 'deadline';
|
|
538
|
+
}
|
|
539
|
+
return /[\w)\]]\s*\+/u.test(expression) ? 'deadline' : base;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** The first top-level comparison of a Rust assertion's condition, as its asserted lower and upper side. */
|
|
543
|
+
function rustComparison(condition: string): { lower: string; upper: string } | undefined {
|
|
544
|
+
let depth = 0;
|
|
545
|
+
let angles = 0;
|
|
546
|
+
for (let index = 0; index < condition.length; index += 1) {
|
|
547
|
+
const char = condition[index] ?? '';
|
|
548
|
+
const next = condition[index + 1] ?? '';
|
|
549
|
+
const previous = condition[index - 1] ?? '';
|
|
550
|
+
if ('([{'.includes(char)) depth += 1;
|
|
551
|
+
else if (')]}'.includes(char)) depth -= 1;
|
|
552
|
+
if (depth !== 0) continue;
|
|
553
|
+
if (char === '<' && condition.slice(index - 2, index) === '::') {
|
|
554
|
+
angles += 1;
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
if (char === '>' && angles > 0) {
|
|
558
|
+
angles -= 1;
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
if (char !== '<' && char !== '>') continue;
|
|
562
|
+
if (next === char || previous === char || previous === '-' || previous === '=') continue;
|
|
563
|
+
const width = next === '=' ? 2 : 1;
|
|
564
|
+
const [left, right] = [condition.slice(0, index), condition.slice(index + width)];
|
|
565
|
+
return char === '<' ? { lower: left, upper: right } : { lower: right, upper: left };
|
|
566
|
+
}
|
|
567
|
+
return undefined;
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/** The text before a group's first top-level comma: an assertion's condition, a call's first argument. */
|
|
571
|
+
function firstArgument(group: string): string {
|
|
572
|
+
let depth = 0;
|
|
573
|
+
for (let index = 0; index < group.length; index += 1) {
|
|
574
|
+
const char = group[index] ?? '';
|
|
575
|
+
if ('([{'.includes(char)) depth += 1;
|
|
576
|
+
else if (')]}'.includes(char)) depth -= 1;
|
|
577
|
+
else if (char === ',' && depth === 0) return group.slice(0, index);
|
|
578
|
+
}
|
|
579
|
+
return group;
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** Milliseconds of a `Duration::from_*` unit. */
|
|
583
|
+
const DURATION_MS: Record<string, number> = { secs: 1000, millis: 1, micros: 1 / 1000, nanos: 1 / 1_000_000 };
|
|
584
|
+
|
|
585
|
+
/** Runner deadlines' Rust counterpart, and class A and class D sites, of one Rust file inside its test code. */
|
|
586
|
+
function rustClockSites(source: string, file: string): Site[] {
|
|
587
|
+
const masked = maskNative(source, true);
|
|
588
|
+
const begin = testCodeStart(masked, file);
|
|
589
|
+
if (begin === undefined) return [];
|
|
590
|
+
const commentless = maskNative(source, false);
|
|
591
|
+
const sites: Site[] = [];
|
|
592
|
+
for (const declaration of masked.slice(begin).matchAll(/\bfn\s+\w+/gu)) {
|
|
593
|
+
const start = begin + declaration.index;
|
|
594
|
+
const open = masked.indexOf('{', start);
|
|
595
|
+
if (open === -1) continue;
|
|
596
|
+
const end = closingIndex(masked, open);
|
|
597
|
+
const body = masked.slice(open, end + 1);
|
|
598
|
+
// Paused tokio time is virtual: its `Instant::now()`, `sleep` and `timeout` advance with the test, not the host.
|
|
599
|
+
const attributes = masked.slice(Math.max(begin, start - 300), start);
|
|
600
|
+
if (/\btokio::time::pause\s*\(/u.test(body) || /\bstart_paused\s*=\s*true\b/u.test(attributes)) continue;
|
|
601
|
+
const bindings = new Map<string, Clock | undefined>();
|
|
602
|
+
for (const binding of body.matchAll(/\blet\s+(?:mut\s+)?([a-z_]\w*)\s*(?::[^=;]*)?=([^;]*);/gu))
|
|
603
|
+
bindings.set(binding[1] ?? '', rustClock(binding[2] ?? '', bindings));
|
|
604
|
+
// A nested fn is examined as itself and again as part of its enclosing fn; the return keeps one site per offset.
|
|
605
|
+
// A deadline the test owns: a receive, park or `timeout` bounded below the backstop whose expiry fails the case.
|
|
606
|
+
// A quiet window (`timeout(d, f).await.is_err()`) asserts that nothing happened and passes.
|
|
607
|
+
// Anchored at the name (`timeout`, not `tokio::time::`), where a clocked-bound reading of it would start too.
|
|
608
|
+
for (const call of body.matchAll(/\b(?:recv_timeout|park_timeout|timeout)\s*\(/gu)) {
|
|
609
|
+
const opening = open + call.index + call[0].length - 1;
|
|
610
|
+
const closing = closingIndex(masked, opening);
|
|
611
|
+
const span =
|
|
612
|
+
/^\s*(?:std::time::|core::time::)?Duration::from_(secs|millis|micros|nanos)(?:_f32|_f64)?\s*\(\s*(\d[\d_]*(?:\.\d+)?)\s*\)\s*$/u.exec(
|
|
613
|
+
firstArgument(masked.slice(opening + 1, closing)),
|
|
614
|
+
);
|
|
615
|
+
const ms =
|
|
616
|
+
span === null ? undefined : Number((span[2] ?? '').replaceAll('_', '')) * (DURATION_MS[span[1] ?? ''] ?? 1);
|
|
617
|
+
if (ms === undefined || !decides('ms', ms)) continue;
|
|
618
|
+
if (!/^\s*(?:\.await)?\s*\.(?:expect|unwrap|unwrap_or_else)\b/u.test(masked.slice(closing + 1, closing + 200)))
|
|
619
|
+
continue;
|
|
620
|
+
sites.push({
|
|
621
|
+
kind: 'test-deadline',
|
|
622
|
+
offset: open + call.index,
|
|
623
|
+
text: source.slice(open + call.index, closing + 1),
|
|
624
|
+
});
|
|
625
|
+
}
|
|
626
|
+
for (const assertion of body.matchAll(/\b(?:debug_|prop_)?assert!\s*\(/gu)) {
|
|
627
|
+
const opening = open + assertion.index + assertion[0].length - 1;
|
|
628
|
+
const closing = closingIndex(masked, opening);
|
|
629
|
+
const compared = rustComparison(firstArgument(masked.slice(opening + 1, closing)));
|
|
630
|
+
if (
|
|
631
|
+
compared !== undefined &&
|
|
632
|
+
boundsHostTime(rustClock(compared.lower, bindings), rustClock(compared.upper, bindings))
|
|
633
|
+
)
|
|
634
|
+
sites.push({
|
|
635
|
+
kind: 'clock-delta',
|
|
636
|
+
offset: open + assertion.index,
|
|
637
|
+
text: source.slice(open + assertion.index, closing + 1),
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
const fnText = commentless.slice(open, end + 1);
|
|
641
|
+
if (fnText.search(TIMED_STAND_IN) === -1) continue;
|
|
642
|
+
for (const bound of body.matchAll(
|
|
643
|
+
/\b([a-z_]\w*)\s*(?::(?!:)|=(?![=>])|\()\s*(?:Duration::from_(secs|millis|micros|nanos)(?:_f32|_f64)?\s*\(\s*)?(\d[\d_]*(?:\.\d+)?)/giu,
|
|
644
|
+
)) {
|
|
645
|
+
const name = bound[1] ?? '';
|
|
646
|
+
const value = Number((bound[3] ?? '').replaceAll('_', ''));
|
|
647
|
+
const unit = bound[2];
|
|
648
|
+
const decided = unit === undefined ? decides(name, value) : decides('ms', value * (DURATION_MS[unit] ?? 1));
|
|
649
|
+
// A `timeout(d, f)` / `recv_timeout(d)` call is the test's own wait, judged above as a test-deadline (a quiet
|
|
650
|
+
// window passes there); only a bound handed to the product is a clocked-bound.
|
|
651
|
+
const deadlineCall =
|
|
652
|
+
/^(?:recv_timeout|park_timeout|timeout)$/u.test(name) &&
|
|
653
|
+
bound[0].slice(name.length).trimStart().startsWith('(');
|
|
654
|
+
if (deadlineCall || !boundName(name) || !decided || !racesBound(fnText, /idle/iu.test(name))) continue;
|
|
655
|
+
const offset = open + bound.index;
|
|
656
|
+
sites.push({ kind: 'clocked-bound', offset, text: source.slice(offset, offset + bound[0].length) });
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
// One site per offset, the first found: a test-owned deadline is not also reported as the bound it carries.
|
|
660
|
+
const kept = new Map<number, Site>();
|
|
661
|
+
for (const site of sites) if (!kept.has(site.offset)) kept.set(site.offset, site);
|
|
662
|
+
return [...kept.values()];
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/** Class A and D sites and runner deadlines of one test file, or undefined for a file holding no test code. */
|
|
666
|
+
function clockSites(file: string, text: string): Site[] | undefined {
|
|
667
|
+
if (JS_EXTENSION.test(extname(file)))
|
|
668
|
+
return TEST_PATH.test(file)
|
|
669
|
+
? jsClockSites(ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true))
|
|
670
|
+
: undefined;
|
|
671
|
+
return extname(file) === '.rs' ? rustClockSites(text, file) : undefined;
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
export function findClockOracles(
|
|
675
|
+
root: string,
|
|
676
|
+
files: readonly string[],
|
|
677
|
+
changes?: ReadonlyMap<string, readonly ChangeRange[]>,
|
|
678
|
+
): ClockOracle[] {
|
|
679
|
+
const found: ClockOracle[] = [];
|
|
680
|
+
for (const file of files) {
|
|
681
|
+
const path = join(root, file);
|
|
682
|
+
if (!existsSync(path)) continue;
|
|
683
|
+
const text = readFileSync(path, 'utf8');
|
|
684
|
+
const sites = clockSites(file, text);
|
|
685
|
+
if (sites === undefined || sites.length === 0) continue;
|
|
686
|
+
const ranges = changes?.get(file);
|
|
687
|
+
const cases = ranges === undefined ? [] : (testCases(file, text) ?? []);
|
|
688
|
+
for (const site of sites.sort((left, right) => left.offset - right.offset)) {
|
|
689
|
+
const prefix = text.slice(0, site.offset);
|
|
690
|
+
const line = prefix.split('\n').length;
|
|
691
|
+
if (ranges !== undefined) {
|
|
692
|
+
const owner = cases.find((test) => test.start <= line && test.end >= line);
|
|
693
|
+
const [start, end] = owner === undefined ? [line, line] : [owner.start, owner.end];
|
|
694
|
+
if (!ranges.some((range) => range.start <= end && range.end >= start)) continue;
|
|
695
|
+
}
|
|
696
|
+
found.push({ kind: site.kind, file, line, column: site.offset - prefix.lastIndexOf('\n'), text: site.text });
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
return found;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
export function formatClockOracle(oracle: ClockOracle): string {
|
|
703
|
+
return (
|
|
704
|
+
`error[${TEST_CLOCK_ORACLE.id}]: ${TEST_CLOCK_ORACLE.message[oracle.kind]}: ${oracle.text}\n` +
|
|
705
|
+
` --> ${oracle.file}:${oracle.line}:${oracle.column}\n` +
|
|
706
|
+
` = help: ${TEST_CLOCK_ORACLE.help[oracle.kind]}`
|
|
707
|
+
);
|
|
708
|
+
}
|