Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
node: see I/O and randomness reached through an import
Onur Ugur7cb2aef460ed
diff --git a/src/node.rs b/src/node.rsindex 609cc32..563675d 100644--- a/src/node.rs+++ b/src/node.rs@@ -712,6 +712,545 @@ mod tests {assert_eq!(leftovers, 0, "worker files are absorbed and removed");}+ /// Calls reached through an import: `readFileSync` after `import { readFileSync } from "node:fs"`,+ /// `cp.spawnSync` after `const cp = require("child_process")`. Each case says what scan must block,+ /// and what it must leave alone (pure members, shadowed names, the app's own modules, comments).+ const IMPORT_CASES: &[(&str, &str, &str, &[&str])] = &[+ (+ "named",+ "import { readFileSync } from \"node:fs\";\nexport function f(p) {\n return readFileSync(p, \"utf8\").length;\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "alias",+ "import { execSync as run } from \"child_process\";\nexport function f(x) {\n run(\"true\");\n return x;\n}\n",+ "f",+ &["does I/O: child_process.execSync"],+ ),+ (+ "namespace",+ "import * as files from \"node:fs\";\nexport function f(p) {\n return files.statSync(p).size;\n}\n",+ "f",+ &["does I/O: fs.statSync"],+ ),+ (+ "default",+ "import disk from \"fs\";\nexport function f(p, x) {\n disk.writeFileSync(p, String(x));\n return x;\n}\n",+ "f",+ &["does I/O: fs.writeFileSync"],+ ),+ (+ "promises member",+ "import { promises as fsp } from \"fs\";\nexport function f(p) {\n return fsp.stat(p);\n}\n",+ "f",+ &["does I/O: fs.promises"],+ ),+ (+ "fs/promises",+ "import { readFile } from \"node:fs/promises\";\nexport function f(p) {\n return readFile(p);\n}\n",+ "f",+ &["does I/O: fs.readFile"],+ ),+ (+ "multi-line",+ "import {\n readFileSync,\n statSync,\n} from \"node:fs\";\nexport function f(p) {\n return statSync(p).size;\n}\n",+ "f",+ &["does I/O: fs.statSync"],+ ),+ (+ "random",+ "import { randomInt } from \"node:crypto\";\nexport function f(x) {\n return x + randomInt(10);\n}\n",+ "f",+ &["not deterministic: crypto.randomInt"],+ ),+ (+ "perf alias",+ "import { performance as perf } from \"node:perf_hooks\";\nexport function f(x) {\n return x + perf.now();\n}\n",+ "f",+ &["not deterministic: perf_hooks.performance"],+ ),+ (+ "process member",+ "import { env } from \"node:process\";\nexport function f(x) {\n return env.HOME ?? x;\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "require destructure",+ "const { readFileSync: rd } = require(\"fs\");\nfunction f(p) {\n return rd(p).length;\n}\nmodule.exports = { f };\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "require module",+ "const cp = require(\"node:child_process\");\nfunction f(x) {\n cp.spawnSync(\"true\");\n return x;\n}\nmodule.exports = { f };\n",+ "f",+ &["does I/O: child_process.spawnSync"],+ ),+ (+ "require member",+ "const fsp = require(\"fs\").promises;\nfunction f(p) {\n return fsp.readFile(p);\n}\nmodule.exports = { f };\n",+ "f",+ &["does I/O: fs.promises"],+ ),+ (+ "fs as fs, once",+ "import fs from \"node:fs\";\nexport function f(p) {\n return fs.readFileSync(p).length;\n}\n",+ "f",+ &["does I/O: fs"],+ ),+ (+ "hash pure",+ "import { createHash } from \"node:crypto\";\nexport function f(s) {\n return createHash(\"sha1\").update(s).digest(\"hex\");\n}\n",+ "f",+ &[],+ ),+ (+ "path pure",+ "import { join } from \"node:path\";\nexport function f(a, b) {\n return join(a, b);\n}\n",+ "f",+ &[],+ ),+ (+ "fs.constants pure",+ "import { constants } from \"node:fs\";\nexport function f(x) {\n return constants.F_OK + x;\n}\n",+ "f",+ &[],+ ),+ (+ "net.isIP pure",+ "import * as net from \"node:net\";\nexport function f(s) {\n return net.isIP(s) === 4;\n}\n",+ "f",+ &[],+ ),+ (+ "param shadow",+ "import { env } from \"node:process\";\nexport function f(env) {\n return env.k;\n}\n",+ "f",+ &[],+ ),+ (+ "local shadow",+ "import { readFileSync } from \"fs\";\nexport function f(x) {\n const readFileSync = (v) => v + 1;\n return readFileSync(x);\n}\n",+ "f",+ &[],+ ),+ (+ "arrow param shadow",+ "import * as os from \"node:os\";\nexport function f(items) {\n return items.map((os) => os.name);\n}\n",+ "f",+ &[],+ ),+ (+ "object key",+ "import { env } from \"node:process\";\nexport function f(x) {\n return { env: x };\n}\n",+ "f",+ &[],+ ),+ (+ "commented import",+ "/*\nimport { statSync } from \"fs\";\n*/\nfunction statSync(x) {\n return { size: x };\n}\nexport function f(x) {\n return statSync(x).size;\n}\n",+ "f",+ &[],+ ),+ ("own module", "import { load } from \"./io.mjs\";\nexport function f(x) {\n return load(x);\n}\n", "f", &[]),+ (+ "other function",+ "import { readFileSync } from \"fs\";\nexport function load(p) {\n return readFileSync(p);\n}\nexport function f(x) {\n return x * 2;\n}\n",+ "f",+ &[],+ ),+ (+ "type import",+ "import type { Stats } from \"node:fs\";\nexport function f(s: Stats): number {\n return s.size;\n}\n",+ "f",+ &[],+ ),+ // a name taken over in one place still counts everywhere else+ (+ "arrow shadow, used outside it",+ "import * as os from \"node:os\";\nexport function f(items) {\n const host = os.hostname();\n return items.map((os) => os.name).concat(host);\n}\n",+ "f",+ &["does I/O: os.hostname"],+ ),+ (+ "used in a default",+ "import { readFileSync } from \"node:fs\";\nexport function f(p, fallback = readFileSync(\"/x\", \"utf8\")) {\n return readFileSync(p, \"utf8\") || fallback;\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "used in an arrow's default",+ "import { env } from \"node:process\";\nexport function f(xs) {\n return xs.map((x = env.DEFAULT) => x);\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "destructured key",+ "import { env } from \"node:process\";\nexport function f(cfg) {\n const { env: mode } = cfg;\n return mode + env.HOME;\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "computed key",+ "import { env } from \"node:process\";\nexport function f(cfg) {\n const { [env.KEY]: val } = cfg;\n return val;\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "parameter pattern key",+ "import { env } from \"node:process\";\nexport function f({ env: mode }) {\n return mode + env.HOME;\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "for-of pattern",+ "import { env } from \"node:process\";\nexport function f(items, t) {\n for (const { a } of items) t[env.HOME] = a;\n return t;\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ // import forms+ (+ "comment in an import",+ "import {\n // sync read\n readFileSync,\n} from \"node:fs\";\nexport function f(p) {\n return readFileSync(p, \"utf8\").length;\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "require, comment inside",+ "const {\n readFileSync, // reads\n statSync,\n} = require(\"node:fs\");\nfunction f(p) {\n return statSync(p).size;\n}\nmodule.exports = { f };\n",+ "f",+ &["does I/O: fs.statSync"],+ ),+ (+ "require, defaults",+ "const { fn = () => 1, readFileSync } = require(\"node:fs\");\nfunction f(p) {\n return readFileSync(p).length;\n}\nmodule.exports = { f };\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "require, nested",+ "const { promises: { readFile } } = require(\"node:fs\");\nfunction f(p) {\n return readFile(p);\n}\nmodule.exports = { f };\n",+ "f",+ &["does I/O: fs.promises"],+ ),+ (+ "require, .default",+ "const { randomBytes } = require(\"node:crypto\").default;\nfunction f() {\n return randomBytes(16).toString(\"hex\");\n}\nmodule.exports = { f };\n",+ "f",+ &["not deterministic: crypto.randomBytes"],+ ),+ (+ "require, .default pure",+ "const { isIP } = require(\"node:net\").default;\nfunction f(s) {\n return isIP(s);\n}\nmodule.exports = { f };\n",+ "f",+ &[],+ ),+ (+ "require in a function keeps the top one",+ "const { readFileSync: run } = require(\"node:fs\");\nfunction helper() {\n const run = require(\"node:path\").join;\n return run(\"a\", \"b\");\n}\nfunction f(p) {\n return run(p, \"utf8\").length;\n}\nmodule.exports = { helper, f };\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "require in a function stays there",+ "const env = { scale: 2 };\nfunction readHome() {\n const { env } = require(\"node:process\");\n return env.HOME;\n}\nfunction f(x) {\n return x * env.scale;\n}\nmodule.exports = { readHome, f };\n",+ "f",+ &[],+ ),+ (+ "compact import",+ "import{readFileSync}from\"node:fs\";\nexport function f(p) {\n return readFileSync(p).length;\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "type: import = require",+ "import cp = require(\"node:child_process\");\nexport function f(x: number): number {\n cp.spawnSync(\"true\");\n return x;\n}\n",+ "f",+ &["does I/O: child_process.spawnSync"],+ ),+ (+ "top-level alias",+ "import fs from \"node:fs\";\nconst { readFileSync } = fs;\nexport function f(p) {\n return readFileSync(p).length;\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "member named type",+ "import { type as osType } from \"node:os\";\nexport function f() {\n return osType();\n}\n",+ "f",+ &["does I/O: os.type"],+ ),+ // modules and members+ (+ "console",+ "import { log } from \"node:console\";\nexport function f(x) {\n log(x);\n return x * 2;\n}\n",+ "f",+ &["does I/O: console.log"],+ ),+ (+ "pseudoRandomBytes",+ "import { pseudoRandomBytes } from \"node:crypto\";\nexport function f() {\n return pseudoRandomBytes(16).toString(\"hex\");\n}\n",+ "f",+ &["not deterministic: crypto.pseudoRandomBytes"],+ ),+ (+ "crypto destructured",+ "import * as c from \"node:crypto\";\nexport function f() {\n const { randomUUID } = c;\n return randomUUID();\n}\n",+ "f",+ &["not deterministic: crypto"],+ ),+ // names that aren't the import+ (+ "method shorthand",+ "import { env } from \"node:process\";\nexport function f(x) {\n return { env(v) { return v + 1; } }.env(x);\n}\n",+ "f",+ &[],+ ),+ (+ "function expression param",+ "import * as os from \"node:os\";\nexport function f(items) {\n return items.map(function (os) {\n return os.name;\n });\n}\n",+ "f",+ &[],+ ),+ (+ "nested function param",+ "import { env } from \"node:process\";\nexport function f() {\n function getK(env) {\n return env.k;\n }\n return getK({ k: 1 });\n}\n",+ "f",+ &[],+ ),+ (+ "second declarator",+ "import { readFileSync } from \"node:fs\";\nexport function f(x) {\n const a = 1, readFileSync = (v) => v + 1;\n return readFileSync(x) + a;\n}\n",+ "f",+ &[],+ ),+ (+ "type: optional key",+ "import { env } from \"node:process\";\nexport function f(x: string): string {\n const cfg: { env?: string } = { env: x };\n return cfg.env;\n}\n",+ "f",+ &[],+ ),+ // scopes that end where JavaScript ends them+ (+ "for-of loop variable",+ "import { env } from \"node:process\";\nexport function f(items) {\n for (const env of items) {\n if (env.stop) break;\n }\n return env.HOME;\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "var in a nested function",+ "import { env } from \"node:process\";\nexport function f() {\n function helper() {\n var env = { HOME: \"x\" };\n return env.HOME;\n }\n return env.HOME + helper();\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "var in an arrow",+ "import { env } from \"node:process\";\nexport function f(items) {\n const xs = items.map((x) => { var env = x; return env; });\n return env.HOME + xs;\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "named function expression",+ "import { readFileSync } from \"node:fs\";\nexport function f(p) {\n const g = function readFileSync(x) { return x; };\n return readFileSync(p).length + g(1);\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "arrow without semicolons",+ "import * as os from \"node:os\";\nexport function f() {\n const getName = (os) => os.name\n return os.hostname() + getName({ name: 1 })\n}\n",+ "f",+ &["does I/O: os.hostname"],+ ),+ (+ "arrow in a ternary",+ "import * as os from \"node:os\";\nexport function f(x) {\n return x ? (os) => os.name : os.hostname();\n}\n",+ "f",+ &["does I/O: os.hostname"],+ ),+ (+ "arrow with a ternary body",+ "import * as os from \"node:os\";\nexport function f(items, c) {\n return items.map((os) => (c ? os.a : os.b));\n}\n",+ "f",+ &[],+ ),+ (+ "call in a ternary",+ "import { readFileSync } from \"node:fs\";\nexport function f(cond, p) {\n return cond ? JSON.parse(readFileSync(p, \"utf8\")) : { empty: true };\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "type: function type annotation",+ "import { env } from \"node:process\";\nexport function f(): number {\n const fn: (env: string) => number = () => env.HOME.length;\n return fn(\"a\");\n}\n",+ "f",+ &["does I/O: process.env"],+ ),+ (+ "type: arrow return type",+ "import * as os from \"node:os\";\nexport function f(items: Array<{ name: string }>): string[] {\n return items.map((os): string => os.name);\n}\n",+ "f",+ &[],+ ),+ (+ "type: generic nested function",+ "import { env } from \"node:process\";\nexport function f(): number {\n function id<T>(env: T): T {\n return env;\n }\n return id(1);\n}\n",+ "f",+ &[],+ ),+ (+ "type: key after a semicolon",+ "import { env } from \"node:process\";\nexport function f(x: string): string {\n const cfg: { a: number; env?: string } = { a: 1, env: x };\n return cfg.env ?? \"\";\n}\n",+ "f",+ &[],+ ),+ (+ "type: import type{",+ "import type{ Stats } from \"node:fs\";\nexport function f(x: unknown): boolean {\n const s = x as Stats;\n return s.size > 0;\n}\n",+ "f",+ &[],+ ),+ (+ "comparison before a binding",+ "import { env } from \"node:process\";\nexport function f(x) {\n const ok = x < 10, env = { k: x };\n return env.k + ok;\n}\n",+ "f",+ &[],+ ),+ (+ "declaration over two lines",+ "import { readFileSync } from \"node:fs\";\nexport function f(x) {\n const a = x +\n 1, readFileSync = (v) => v;\n return readFileSync(a);\n}\n",+ "f",+ &[],+ ),+ (+ "property on the next line",+ "import { exec } from \"node:child_process\";\nexport function f(re, s) {\n return re\n .exec(s);\n}\n",+ "f",+ &[],+ ),+ (+ "import in a template string",+ "const doc = `\nimport { readFileSync } from \"fs\";\n`;\nfunction readFileSync(x) {\n return x;\n}\nexport function f(x) {\n return readFileSync(x) + doc;\n}\n",+ "f",+ &[],+ ),+ // more import forms+ (+ "require, no semicolons",+ "const { a } = getConfig()\nconst { readFileSync } = require(\"node:fs\")\nfunction f(p) {\n return readFileSync(p, \"utf8\").length\n}\nfunction getConfig() {\n return { a: 1 }\n}\nmodule.exports = { f, a }\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "require, rest",+ "const { createHash, ...rest } = require(\"node:crypto\");\nfunction f() {\n return rest.randomInt(10);\n}\nmodule.exports = { f, createHash };\n",+ "f",+ &["not deterministic: crypto.randomInt"],+ ),+ (+ "require, after a regex with a brace",+ "const OPEN = /\\{/;\nconst { readFileSync } = require(\"node:fs\");\nfunction f(p) {\n return readFileSync(p, \"utf8\").length + OPEN.source.length;\n}\nmodule.exports = { f };\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "require, .default.member pure",+ "const isIP = require(\"node:net\").default.isIP;\nfunction f(s) {\n return isIP(s) === 4;\n}\nmodule.exports = { f };\n",+ "f",+ &[],+ ),+ (+ "chained alias",+ "import fs from \"node:fs\";\nconst read = fs.promises.readFile;\nexport function f(p) {\n return read(p);\n}\n",+ "f",+ &["does I/O: fs.promises"],+ ),+ (+ "exported alias",+ "import fs from \"node:fs\";\nexport const { readFileSync } = fs;\nexport function f(p) {\n return readFileSync(p).length;\n}\n",+ "f",+ &["does I/O: fs.readFileSync"],+ ),+ (+ "type: as const without semicolons",+ "import { writeFileSync } from \"node:fs\";\nexport function f(p: string) {\n const opts = { encoding: \"utf8\" } as const\n writeFileSync(p, \"hi\", opts)\n return 1\n}\n",+ "f",+ &["does I/O: fs.writeFileSync"],+ ),+ (+ "type: a function type's parameter",+ "import { env } from \"node:process\";\nexport function f(): number {\n const fn: (env: string) => number = (s) => s.length;\n return fn(\"a\");\n}\n",+ "f",+ &[],+ ),+ ];++ #[test]+ fn scan_sees_io_reached_through_an_import() {+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no node on PATH, skipping");+ return;+ }+ // the profile step describes the 40 hottest functions: 30 cases a run+ for (chunk, cases) in IMPORT_CASES.chunks(30).enumerate() {+ let dir = std::env::temp_dir().join(format!("fa-node-imports-{}-{chunk}", std::process::id()));+ let prof = dir.join("cpuprof");+ fs::create_dir_all(&prof).unwrap();+ // a made-up profile with one sample in each case's function+ let root = json!({ "functionName": "(root)", "url": "", "lineNumber": -1, "columnNumber": -1 });+ let mut nodes = vec![json!({ "id": 1, "callFrame": root, "children": [] })];+ for (i, (name, src, func, _)) in cases.iter().enumerate() {+ let ext = if name.starts_with("require") {+ "cjs"+ } else if name.starts_with("type") {+ "ts"+ } else {+ "mjs"+ };+ let file = dir.join(format!("case{i}.{ext}"));+ fs::write(&file, src).unwrap();+ let line = src.lines().position(|l| l.contains(&format!("function {func}("))).unwrap();+ let url = format!("file://{}", file.display());+ let frame = json!({ "functionName": func, "url": url, "lineNumber": line, "columnNumber": 0 });+ nodes.push(json!({ "id": i + 2, "callFrame": frame, "children": [] }));+ }+ let ids: Vec<usize> = (2..cases.len() + 2).collect();+ nodes[0]["children"] = json!(ids);+ let deltas = vec![1000; ids.len()];+ let profile =+ json!({ "nodes": nodes, "startTime": 0, "endTime": 1_000_000, "samples": ids, "timeDeltas": deltas });+ fs::write(prof.join("a.cpuprofile"), profile.to_string()).unwrap();+ fs::write(dir.join("runner.mjs"), RUNNER).unwrap();+ let result = dir.join("profile.json");+ let job = json!({ "root": dir, "dir": prof, "entry": dir.join("main.mjs"), "out": result });+ fs::write(dir.join("job.json"), job.to_string()).unwrap();+ let out =+ Command::new("node").args(["runner.mjs", "profile", "job.json"]).current_dir(&dir).output().unwrap();+ let result = fs::read_to_string(&result).unwrap_or_default();+ let _ = fs::remove_dir_all(&dir);+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));+ let result: Value = serde_json::from_str(&result).unwrap();+ let functions = result["functions"].as_array().unwrap();+ for (i, (name, _, _, expected)) in cases.iter().enumerate() {+ let prefix = format!("case{i}.");+ let f = functions+ .iter()+ .find(|f| f["file"].as_str().is_some_and(|p| p.starts_with(&prefix)))+ .unwrap_or_else(|| panic!("{name}: not described"));+ let got: Vec<&str> = f["blockers"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(Value::as_str)+ .filter(|b| b.starts_with("does I/O") || b.starts_with("not deterministic"))+ .collect();+ assert_eq!(got, *expected, "{name}");+ }+ }+ }+#[test]fn maps_typescript() {assert_eq!(rust_type("number").as_deref(), Some("f64"));diff --git a/src/node/runner.mjs b/src/node/runner.mjsindex 435472f..8afaf3a 100644--- a/src/node/runner.mjs+++ b/src/node/runner.mjs@@ -11,6 +11,17 @@ const IO =/\b(console|fs|process|fetch|require|XMLHttpRequest|document|window|localStorage|sessionStorage|setTimeout|setInterval|setImmediate|queueMicrotask|Bun|Deno)\b|\bimport\s*\(/g;const NONDET = /\bMath\.random\b|\bDate\.now\b|\bnew\s+Date\b|\bperformance\.now\b|\bcrypto\.\w+/g;const IDENT = "[A-Za-z_$][\\w$]*";+// Built-in modules whose functions do I/O (or read the machine and the process) wherever they're reached+// from, and the members that don't: constants and pure helpers like `net.isIP`.+const IO_MODULES = new Set(["fs", "child_process", "net", "http", "https", "http2", "dgram", "dns", "tls", "readline",+ "process", "os", "worker_threads", "cluster", "inspector", "timers", "tty", "repl", "module", "console", "sqlite",+ "wasi", "v8"]);+const IO_PURE = new Set(["fs.constants", "os.EOL", "os.constants", "os.devNull", "net.isIP", "net.isIPv4", "net.isIPv6",+ "http.STATUS_CODES", "http.METHODS", "module.isBuiltin", "module.builtinModules", "module.stripTypeScriptTypes"]);+// crypto's hashes and ciphers give the same answer every time; its random and key generators, and the+// signatures and encryption that pad or salt at random, don't.+const NONDET_CRYPTO =+ /^(random\w*|pseudoRandom\w*|getRandomValues|generateKey\w*|generatePrime\w*|webcrypto|subtle|createECDH|createDiffieHellman\w*|getDiffieHellman|createSign|sign|publicEncrypt)$/;const esc = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");// ------------------------------------------------------------------ source scanning@@ -107,20 +118,356 @@ function topLevelFunctions(src) {return new Set([...src.matchAll(re)].map((m) => m[1] || m[2]));}+/** What a built-in module's member is: "io", "nondet" or null. `member` is null for the module itself+ * (destructured, indexed or passed along), which counts as what the module does. */+function builtin(mod, member) {+ const base = mod.replace(/^node:/, "").split("/")[0];+ if (IO_MODULES.has(base)) return member && IO_PURE.has(base + "." + member) ? null : "io";+ if (base === "perf_hooks") return "nondet";+ if (base === "crypto" && (!member || NONDET_CRYPTO.test(member))) return "nondet";+ return null;+}++/** splitTop, without taking an arrow's `>` or a spaced comparison (`a < b`, `x >= 1`) for a bracket. */+const topParts = (s) => splitTop(s.replace(/=>|\s[<>]=?\s|[<>]=/g, (m) => " ".repeat(m.length)));++/** Where a parameter's or declarator's default starts, or -1. */+const defaultOf = (p) => defaultAt(p.replace(/=>|\s[<>]=?\s|[<>]=/g, (m) => " ".repeat(m.length)));++/** The names a parameter or a declarator binds: `x`, `x = 1`, `...x`, `x: T`, `{ a, b: c, d = 1 }`, `[a, [b]]`. */+function bindingNames(p) {+ p = p.trim();+ const eq = defaultOf(p);+ if (eq >= 0) p = p.slice(0, eq).trim();+ if (p.startsWith("...")) p = p.slice(3).trim();+ if (p[0] === "{" || p[0] === "[") {+ const end = matching(p, 0);+ return topParts(p.slice(1, end < 0 ? p.length : end)).flatMap((part) => {+ if (p[0] === "[") return bindingNames(part);+ const d = defaultOf(part);+ const colon = colonAt(d < 0 ? part : part.slice(0, d));+ return bindingNames(colon >= 0 ? part.slice(colon + 1) : part);+ });+ }+ const id = p.match(/^[A-Za-z_$][\w$]*/);+ return id ? [id[0]] : [];+}++/** Where `key: value` splits in an object pattern part: the first `:` outside brackets. */+function colonAt(s) {+ let depth = 0;+ for (let i = 0; i < s.length; i++) {+ if ("([{".includes(s[i])) depth++;+ else if (")]}".includes(s[i])) depth--;+ else if (s[i] === ":" && depth === 0) return i;+ }+ return -1;+}++/** The bracket that opens the one closing at `close`, looking back. */+function openOf(code, close) {+ const open = { ")": "(", "}": "{", "]": "[" }[code[close]];+ let depth = 0;+ for (let i = close; i >= 0; i--) {+ if (code[i] === code[close]) depth++;+ else if (code[i] === open && --depth === 0) return i;+ }+ return -1;+}++/** The last `n` characters of `s` before `at`, without trailing space: enough to see what comes just before. */+const tail = (s, at, n = 80) => s.slice(Math.max(0, at - n), at).trimEnd();++/** The `{` of the innermost block around `at`, or -1. */+function openAround(body, at) {+ let depth = 0;+ for (let i = at - 1; i >= 0; i--) {+ if (body[i] === "}") depth++;+ else if (body[i] === "{" && depth-- === 0) return i;+ }+ return -1;+}++/** [start, end) of a block opening at `open`, or the whole body when there's none. */+function blockAt(body, open) {+ if (open < 0) return [0, body.length];+ const end = matching(body, open);+ return [open, end < 0 ? body.length : end + 1];+}++/** Whether the block opening at `open` is a function's body: after `) {`, `): T {` or `=> {` that isn't+ * an if/for/while/switch/catch/with header. */+function isFunctionBody(body, open) {+ const before = tail(body, open, 200);+ if (before.endsWith("=>")) return true;+ const m = before.match(/\)\s*(?::[^(){};=]*)?$/);+ if (!m) return false;+ const paren = openOf(body, trimmedEnd(body, open) - m[0].length);+ return paren >= 0 && !/\b(?:if|for|while|switch|catch|with)$/.test(tail(body, paren, 20));+}++/** The index just past the last non-space character before `at`. */+function trimmedEnd(s, at) {+ while (at > 0 && /\s/.test(s[at - 1])) at--;+ return at;+}++/** Where an expression that starts at `from` ends: a `,` `;` `:` or closing bracket outside brackets, or the+ * end of its line unless the next line goes on with it. A ternary's own `:` doesn't end it. */+function expressionEnd(body, from) {+ let depth = 0;+ let ternary = 0;+ let last = "";+ for (let i = from; i < body.length; i++) {+ const c = body[i];+ if ("([{".includes(c)) depth++;+ else if (")]}".includes(c) && --depth < 0) return i;+ else if (depth === 0 && c === "?" && body[i + 1] !== "." && body[i + 1] !== "?" && body[i - 1] !== "?") ternary++;+ else if (depth === 0 && c === ":" && ternary > 0) ternary--;+ else if ((c === "," || c === ";" || c === ":") && depth === 0) return i;+ else if (c === "\n" && depth === 0 && !/[-+*/%&|^!=<>?:.,(]$/.test(last)) {+ const next = body.slice(i + 1, i + 40).trimStart()[0] || "";+ if (!/[-+*/%&|^=<>?:.,)\]}]/.test(next) || next === "") return i;+ }+ if (!/\s/.test(c)) last = c;+ }+ return body.length;+}++/** Where a let/const/var's declarators that start at `from` end: `;`, a closing bracket, or a line end where+ * the declaration doesn't go on. */+function declarationEnd(body, from) {+ let depth = 0;+ let last = "";+ for (let i = from; i < body.length; i++) {+ const c = body[i];+ if ("([{".includes(c)) depth++;+ else if (")]}".includes(c) && --depth < 0) return i;+ else if (depth === 0 && c === ";") return i;+ else if (depth === 0 && c === "\n" && !/[-+*/%&|^!=<>?:.,]$/.test(last)) {+ const next = body.slice(i + 1, i + 40).trimStart()[0] || "";+ if (!/[-+*/%&|^=<>?:.,]/.test(next)) return i;+ }+ if (!/\s/.test(c)) last = c;+ }+ return body.length;+}++const DEFINES = /(?:^|[{},;])\s*(?:(?:get|set|async|static|private|public|protected|readonly|override)\s+)*\*?\s*$/;++/** [start, end) ranges of `body` where `name` stands for something of the function's own: inside a nested+ * function, arrow, method or catch block that takes it as a parameter, inside a for loop that declares it,+ * and in the block of a let/const (the function for var), function or class that declares it. */+function shadowedIn(body, name) {+ const ranges = [];+ const n = esc(name);+ for (const d of body.matchAll(/\b(let|const|var)\s+/g)) {+ if (/\bas$/.test(tail(body, d.index, 20))) continue; // `as const`+ const start = d.index + d[0].length;+ const end = declarationEnd(body, start);+ if (!topParts(body.slice(start, end)).flatMap(bindingNames).includes(name)) continue;+ const loop = tail(body, d.index, 40).match(/\bfor\s*(?:await\s*)?\($/);+ if (loop) {+ // the loop's own: its header and its body+ const paren = body.lastIndexOf("(", d.index);+ const close = matching(body, paren);+ let from = close + 1;+ while (/\s/.test(body[from] || "")) from++;+ const stop = body[from] === "{" ? matching(body, from) + 1 : expressionEnd(body, from);+ ranges.push([paren, stop <= 0 ? body.length : stop]);+ continue;+ }+ let open = openAround(body, d.index);+ if (d[1] === "var") while (open >= 0 && !isFunctionBody(body, open)) open = openAround(body, open);+ ranges.push(blockAt(body, open));+ }+ for (const d of body.matchAll(new RegExp("\\b(?:function(?=[\\s*])\\s*(?:\\*\\s*)?|class\\s+)" + n + "(?![\\w$])", "g"))) {+ const before = tail(body, d.index, 20);+ const declaration = before === "" || /[{};]$/.test(before) || /\bexport(?:\s+default)?$/.test(before);+ if (declaration) ranges.push(blockAt(body, openAround(body, d.index)));+ else {+ // a named function or class expression: the name is its own, inside it+ const open = body.indexOf("{", d.index);+ ranges.push(blockAt(body, open));+ }+ }+ // parameters: function expressions and declarations, methods, catch clauses+ const KEYWORDS = new Set(["if", "for", "while", "switch", "with", "return", "typeof", "await", "yield", "new", "catch"]);+ for (const p of body.matchAll(/(?:\bfunction\b(?:\s*\*)?(?:\s*[\w$]+)?|\bcatch|(?<![\w$])([\w$]+))\s*(?:<[^()<>]*(?:<[^()<>]*>[^()<>]*)*>\s*)?\(/g)) {+ if (p[1] && (KEYWORDS.has(p[1]) || !DEFINES.test(tail(body, p.index)))) continue; // a call, not a method+ const open = p.index + p[0].length - 1;+ const close = matching(body, open);+ if (close < 0) continue;+ const after = body.slice(close + 1, close + 300).match(/^\s*(?::[^{=;]*)?\{/);+ if (!after) continue; // a call, not a definition+ if (!topParts(body.slice(open + 1, close)).flatMap(bindingNames).includes(name)) continue;+ ranges.push([open, blockAt(body, close + after[0].length)[1]]);+ }+ // parameters of arrows: (a, b) => ..., (a): T => ..., a => ...+ for (const a of body.matchAll(/=>/g)) {+ const before = tail(body, a.index, 200);+ const at = trimmedEnd(body, a.index);+ let start, params;+ const typed = before.match(/\)\s*(?::[^(){};=]*)?$/);+ if (typed) {+ const close = at - typed[0].length;+ start = openOf(body, close);+ if (start < 0) continue;+ params = topParts(body.slice(start + 1, close)).flatMap(bindingNames);+ } else {+ const id = before.match(/[A-Za-z_$][\w$]*$/);+ if (!id) continue;+ start = at - id[0].length;+ params = [id[0]];+ }+ if (!params.includes(name)) continue;+ let from = a.index + 2;+ while (/\s/.test(body[from] || "")) from++;+ // a function type in an annotation, `(env: string) => number = ...`, binds nothing+ if (/^[\w$.<>[\]|& ]+=(?![=>])/.test(body.slice(from, from + 200)) && /:\s*$/.test(tail(body, start, 20))) continue;+ const end = body[from] === "{" ? matching(body, from) + 1 : expressionEnd(body, from);+ ranges.push([start, end <= 0 ? body.length : end]);+ }+ return ranges;+}++/** Local name -> { mod, member } for the module's top-level imports and requires of a module by name:+ * `import { readFileSync as read } from "node:fs"` gives read: fs.readFileSync, `import * as fs from "fs"`+ * and `const cp = require("child_process")` give the module itself (member null), and so does a top-level+ * `const { readFileSync } = fs` after it. Read from the code with comments blanked out, the module names+ * from the source. Relative paths are the app's own and left out; so are `import type` and type-only members,+ * and requires that are indented inside a block or function (IO sees one in the function as `require`). */+function importsOf(src, code) {+ const out = new Map();+ const add = (local, mod, member) => {+ local = local.trim();+ if (/^[A-Za-z_$][\w$]*$/.test(local) && !/^[./]/.test(mod))+ out.set(local, { mod, member: member || null });+ };+ const braces = [];+ for (let i = 0, depth = 0; i < code.length; i++)+ if (code[i] === "{" || code[i] === "}") braces.push([i, (depth += code[i] === "{" ? 1 : -1)]);+ // at the top of the module: not indented, or outside every brace (regex literals can throw the count off)+ const topLevel = (m) => {+ if (!/^[ \t]/.test(m[0])) return true;+ let lo = 0, hi = braces.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (braces[mid][0] < m.index) lo = mid + 1;+ else hi = mid;+ }+ return lo === 0 || braces[lo - 1][1] === 0;+ };+ const spec = (m, g) => src.slice(m.indices[g][0], m.indices[g][1]);+ /** The first member of `.a.b.c` that isn't `default`. */+ const first = (chain) => (chain || "").split(".").map((x) => x.trim()).filter((x) => x && x !== "default")[0] || null;+ /** [member, local] for each name a `{ ... }` pattern takes out of what it destructures; a rest takes the lot. */+ const destructured = (pattern) =>+ topParts(pattern.trim().slice(1, -1)).flatMap((part) => {+ if (part.trim().startsWith("...")) return bindingNames(part).map((local) => [null, local]);+ const d = defaultOf(part);+ const head = d < 0 ? part : part.slice(0, d);+ const colon = colonAt(head);+ const key = (colon >= 0 ? head.slice(0, colon) : head).trim();+ return bindingNames(colon >= 0 ? part.slice(colon + 1) : part).map((local) => [/^[\w$]+$/.test(key) ? key : null, local]);+ });++ // import ... from "x": found by its keyword, then read up to the module name's quote (no backtracking)+ for (const m of code.matchAll(/^[ \t]*import(?=[\s{*])/gm)) {+ const from = m.index + m[0].length;+ const q = code.slice(from, from + 4000).search(/["'`;()]/);+ if (q < 0 || !/["']/.test(code[from + q])) continue;+ const head = code.slice(from, from + q).trim();+ if (!head.endsWith("from")) continue;+ const clause = head.slice(0, -4).trim();+ if (!/^[\w$*{}\s,]+$/.test(clause) || /^type[\s{]/.test(clause)) continue;+ const quote = from + q;+ const close = code.indexOf(code[quote], quote + 1);+ if (close < 0) continue;+ const mod = src.slice(quote + 1, close);+ const named = clause.match(/\{([^}]*)\}/);+ for (const part of splitTop(clause.replace(/\{[^}]*\}/, ""))) {+ const ns = part.match(/^\*\s*as\s+([\w$]+)$/);+ add(ns ? ns[1] : part, mod, null);+ }+ for (const part of named ? splitTop(named[1]) : []) {+ if (/^type\s+(?!as\b)/.test(part)) continue; // `type as x` imports a member named type+ const [member, local = member] = part.split(/\s+as\s+/);+ add(local, mod, member.trim() === "default" ? null : member.trim());+ }+ }+ for (const m of code.matchAll(/^[ \t]*(?:export\s+)?import\s+([\w$]+)\s*=\s*require\s*\(\s*(["'])([^"'\n]*)\2\s*\)/dgm))+ add(m[1], spec(m, 3), null);+ const PATTERN = "(\\{[^;{}]*(?:\\{[^;{}]*\\}[^;{}]*)*\\}|[\\w$]+)";+ const CHAIN = "((?:\\s*\\.\\s*[\\w$]+)*)";+ const req = new RegExp("^[ \\t]*(?:export\\s+)?(?:const|let|var)\\s+" + PATTERN + "\\s*=\\s*require\\s*\\(\\s*([\"'])([^\"'\\n]*)\\2\\s*\\)" + CHAIN, "dgm");+ for (const m of code.matchAll(req)) {+ if (!topLevel(m)) continue;+ const mod = spec(m, 3);+ const prop = first(m[4]);+ if (!m[1].startsWith("{")) add(m[1], mod, prop);+ else for (const [key, local] of destructured(m[1])) add(local, mod, prop || key);+ }+ // a top-level alias of one of them: const { readFileSync } = fs, const read = fs.promises.readFile+ const alias = new RegExp("^[ \\t]*(?:export\\s+)?(?:const|let|var)\\s+" + PATTERN + "\\s*=\\s*([\\w$]+)" + CHAIN + "\\s*(?=;|$)", "gm");+ for (const m of code.matchAll(alias)) {+ const from = out.get(m[2]);+ if (!from || !topLevel(m)) continue;+ const member = from.member ?? first(m[3]);+ if (!m[1].startsWith("{")) add(m[1], from.mod, member);+ else for (const [key, local] of destructured(m[1])) add(local, from.mod, member || key);+ }+ return out;+}++/** [what, label] for each use in `body` of an imported built-in that does I/O or isn't deterministic.+ * A use where the name is the function's own (a parameter of it, or of a nested function, arrow or catch+ * around the use, or declared in a block around it) doesn't count, nor does a property, an object key or a+ * method's name. Names IO or NONDET already matched (`fs` imported as fs, `performance.now`) aren't+ * reported twice. */+function importedCalls(imports, body, params, seen) {+ const out = [];+ for (const [local, { mod, member }] of imports) {+ if ([...seen].some((t) => t === local || t.startsWith(local + "."))) continue;+ if (topParts(params).flatMap(bindingNames).includes(local)) continue;+ let hidden = null;+ const base = mod.replace(/^node:/, "").split("/")[0];+ for (const use of body.matchAll(new RegExp("(?<![\\w$.])" + esc(local) + "(?![\\w$])(\\s*\\??\\.\\s*([\\w$]+))?", "g"))) {+ const before = tail(body, use.index);+ const after = use.index + local.length;+ const rest = body.slice(after, after + 300);+ if (before.endsWith(".")) continue; // a property on the line above: `re\n .exec(s)`+ if (/[{,;(]$/.test(before) && /^\s*\??\s*:/.test(rest)) continue; // a key or a typed name: `{ env: x }`, `(env: T) =>`+ if (DEFINES.test(before) && /^\s*(?:<[^()]*>)?\s*\(/.test(rest)) {+ const open = after + rest.indexOf("(");+ const close = matching(body, open);+ if (close >= 0 && /^\s*(?::[^{=;]*)?\{/.test(body.slice(close + 1, close + 300))) continue; // a method+ }+ hidden ??= shadowedIn(body, local);+ if (hidden.some(([a, b]) => use.index >= a && use.index < b)) continue;+ const at = member ?? use[2] ?? null;+ const what = builtin(mod, at);+ if (what) out.push([what, at ? base + "." + at : base]);+ }+ }+ return out;+}+const parsed = new Map();function describe(file, line0, name, entry, root) {if (!parsed.has(file)) {try {const src = readFileSync(file, "utf8");- parsed.set(file, { src, code: codeOnly(src), top: topLevelFunctions(src) });+ const code = codeOnly(src);+ parsed.set(file, { src, code, top: topLevelFunctions(src), imports: importsOf(src, code) });} catch {parsed.set(file, null);}}const f = parsed.get(file);if (!f) return null;- const { src, code, top } = f;+ const { src, code, top, imports } = f;const lines = code.split("\n");const n = esc(name);const patterns = [@@ -197,6 +544,7 @@ function describe(file, line0, name, entry, root) {const io = new Set([...body.matchAll(IO)].map((x) => x[0]));const nondet = new Set([...body.matchAll(NONDET)].map((x) => x[0]));+ for (const [what, label] of importedCalls(imports, body, code.slice(open + 1, close), new Set([...io, ...nondet]))) (what === "io" ? io : nondet).add(label);if (/\byield\b/.test(body) && !blockers.some((b) => b.startsWith("generator"))) blockers.push("generator (yield)");if (/\bawait\b/.test(body) && !blockers.includes("async")) blockers.push("async");if (/\bthis\b/.test(body)) blockers.push("uses this");