Skip to content

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.

python: os.environ, sys.argv and sys.stdin used without a call block too (#78)

Onur Ugurcc3dce72797d
diff --git a/src/python.rs b/src/python.rs
index 6550cd1..f7cd270 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -859,6 +859,50 @@ mod tests {
assert_eq!(strip_shim(&on, "fuzzy.levenshtein"), "class Text:\n pass\n");
}
+ #[test]
+ fn reading_the_environment_or_argv_blocks() {
+ let Some(python) = ["python3", "python"]
+ .into_iter()
+ .find(|p| Command::new(p).arg("--version").output().is_ok_and(|o| o.status.success()))
+ else {
+ eprintln!("no python on PATH, skipping");
+ return;
+ };
+ let dir = std::env::temp_dir().join(format!("fa-environ-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("runner.py"), RUNNER).unwrap();
+ fs::write(
+ dir.join("work.py"),
+ "import json\nimport os\nimport sys\n\n\
+ def subscript(x):\n return x * int(os.environ['SCALE'])\n\n\
+ def chained(x):\n return os.environ['PATHS'].split(':') + [x]\n\n\
+ def member(x):\n return x if 'CI' in os.environ else -x\n\n\
+ def argv(x):\n return len(sys.argv[1]) + x\n\n\
+ def getenv(x):\n return x * int(os.environ.get('SCALE', 1))\n\n\
+ def constants(x):\n return x + len(os.sep) + sys.maxsize\n\n\
+ def keys(x):\n return [k for k in os.environb] + [x]\n\n\
+ def orig(x):\n return sys.orig_argv[0] + x\n\n\
+ def load():\n return json.load(sys.stdin)\n\n\
+ def write(x):\n sys.stdout.write(x)\n",
+ )
+ .unwrap();
+ let check = "import runpy, sys, os\n\
+ d = sys.argv[1]\n\
+ describe = runpy.run_path(os.path.join(d, 'runner.py'))['describe']\n\
+ f = os.path.join(d, 'work.py')\n\
+ want = {5: ('subscript', ['does I/O: os.environ']), 8: ('chained', ['does I/O: os.environ']),\n\
+ 11: ('member', ['does I/O: os.environ']), 14: ('argv', ['does I/O: sys.argv']),\n\
+ 17: ('getenv', ['does I/O: os.environ.get']), 20: ('constants', []),\n\
+ 23: ('keys', ['does I/O: os.environb']), 26: ('orig', ['does I/O: sys.orig_argv']),\n\
+ 29: ('load', ['does I/O: sys.stdin']), 32: ('write', ['does I/O: sys.stdout.write'])}\n\
+ for line, (name, blockers) in want.items():\n\
+ \x20 got = describe(f, line, name, None, d)['blockers']\n\
+ \x20 assert got == blockers, (name, got)\n";
+ let out = Command::new(python).args(["-I", "-c", check]).arg(&dir).output().unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ }
+
#[test]
fn static_methods_are_portable() {
let Some(python) = ["python3", "python"]
diff --git a/src/python/runner.py b/src/python/runner.py
index daa4ac3..7a3dcf5 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -22,6 +22,10 @@ import time
DISABLE_ENV = "FAST_ANYTHING_DISABLE"
SKIP_DIRS = {".fast", ".git", "venv", ".venv", "env", ".env", "site-packages", "dist-packages",
"node_modules", "__pycache__", "build", "dist", ".tox", ".nox"}
+# Process state used without a call: `os.environ["X"]` is as much a hidden input as `os.getenv("X")`,
+# and `json.load(sys.stdin)` as much I/O as `sys.stdin.read()`. Calls on these are judged by IO_MODULES.
+STATE_READS = {"os.environ", "os.environb", "sys.argv", "sys.orig_argv",
+ "sys.stdin", "sys.stdout", "sys.stderr", "sys.__stdin__", "sys.__stdout__", "sys.__stderr__"}
IO_NAMES = {"print", "open", "input", "exec", "eval", "compile", "__import__", "breakpoint", "exit", "quit"}
IO_MODULES = {"os", "sys", "subprocess", "socket", "requests", "urllib", "http", "httpx", "aiohttp", "shutil",
"pathlib", "logging", "sqlite3", "tempfile", "glob", "asyncio", "threading", "multiprocessing", "io"}
@@ -355,6 +359,18 @@ def describe(path, line, name, entry, base):
factor *= 0.7
io, nondet, arrays, helpers = set(), set(), set(), set()
+ called = set() # the a.b of a call a.b.c(...), which the call check already judged
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Call):
+ n = sub.func
+ while isinstance(n, ast.Attribute):
+ called.add(id(n))
+ n = n.value
+ for sub in ast.walk(node):
+ if isinstance(sub, ast.Attribute) and id(sub) not in called:
+ read = ".".join(dotted(sub) or [])
+ if read in STATE_READS:
+ io.add(read)
is_generator = writes_globals = False
for sub in ast.walk(node):
if isinstance(sub, (ast.Yield, ast.YieldFrom)):