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: see I/O and randomness reached through an import (#77)

Onur Ugurc929a728fff7
diff --git a/src/python.rs b/src/python.rs
index f7cd270..12fe75f 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -933,6 +933,127 @@ mod tests {
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
}
+ /// Calls reached through an import: `sp.run` after `import subprocess as sp`, `system` after
+ /// `from os import system`. Each case says what `describe` must block, and what it must leave alone
+ /// (shadowed names, imports in another function, pure calls, the checks that worked without imports).
+ const IMPORT_CASES: &str = r#"import ast, os, runpy, sys
+runner, d = sys.argv[1], sys.argv[2]
+describe = runpy.run_path(runner)["describe"]
+CASES = [
+ # (name, source, function, expected blockers)
+ ("alias", "import subprocess as sp\ndef f(x):\n sp.run(['true'])\n return x\n", "f", ["does I/O: subprocess.run"]),
+ ("from", "from os import system\ndef f(x):\n system('true')\n return x\n", "f", ["does I/O: os.system"]),
+ ("path", "from pathlib import Path\ndef f(x, p):\n Path(p).write_text(str(x))\n return x\n", "f", ["does I/O: pathlib.Path"]),
+ ("random", "from random import random\ndef f(x):\n return x + random()\n", "f", ["not deterministic: random.random"]),
+ ("local import", "def f(x):\n from time import sleep\n sleep(0)\n return x\n", "f", ["not deterministic: time.sleep"]),
+ ("gzip open (regression)", "from gzip import open\ndef f(p):\n return open(p).read()\n", "f", ["does I/O: open"]),
+ ("rich print (regression)", "from rich import print\ndef f(x):\n print(x)\n return x\n", "f", ["does I/O: print"]),
+ ("builtins alias", "import builtins as b\ndef f(p):\n return b.open(p)\n", "f", ["does I/O: open"]),
+ ("numpy random (regression)", "from numpy import random\ndef f():\n return random.random()\n", "f", ["not deterministic: random.random"]),
+ ("local leak FP", "def other():\n import random as r\n return r.random()\n\ndef pure(r):\n return r.get('k')\n", "pure", []),
+ ("local overwrite FN", "import random as r\ndef impure():\n return r.random()\ndef other():\n import math as r\n return r.sqrt(4)\n", "impure", ["not deterministic: random.random"]),
+ ("local overwrite FP", "import math as m\ndef pure(x):\n return m.sqrt(x)\ndef other():\n import random as m\n return m.random()\n", "pure", []),
+ ("main leak FP", "def parse(p):\n return p.split('/')\n\nif __name__ == '__main__':\n import pathlib as p\n p.Path('x').write_text('hi')\n", "parse", []),
+ ("param shadow", "from os import path\ndef f(path):\n return path.strip()\n", "f", []),
+ ("local assign shadow", "from os import system\ndef f(x):\n system = lambda v: v + 1\n return system(x)\n", "f", []),
+ ("nested def shadow", "from os import system\ndef f(x):\n def system(y):\n return y + 1\n return system(x)\n", "f", []),
+ ("class shadow", "from pathlib import Path\nclass Path:\n pass\ndef f(x):\n return Path(x)\n", "f", []),
+ ("local import beats top", "def run(x):\n return x + 1\ndef danger(cmd):\n from subprocess import run\n run(cmd)\n return 0\n", "danger", ["does I/O: subprocess.run"]),
+ ("top beats module import", "from subprocess import run\ndef run(x):\n return x + 1\ndef f(x):\n return run(x)\n", "f", []),
+ ("try/except both", "try:\n import subprocess as sp\nexcept ImportError:\n import my_stub as sp\ndef f(x):\n sp.run(['true'])\n return x\n", "f", ["does I/O: subprocess.run"]),
+ ("relative shadows", "import random as helper\ndef f():\n from . import helper\n return helper.compute()\n", "f", []),
+ ("urlparse pure", "from urllib.parse import urlparse\ndef f(u):\n return urlparse(u).netloc\n", "f", []),
+ ("timedelta pure", "from datetime import date, timedelta\ndef f(y):\n return date(y, 1, 1) + timedelta(days=1)\n", "f", []),
+ ("datetime.now nondet", "from datetime import datetime\ndef f():\n return datetime.now()\n", "f", ["not deterministic: datetime.now"]),
+ ("os.path.join pure", "from os.path import join\ndef f(a, b):\n return join(a, b)\n", "f", []),
+ ("os.path.exists io", "from os.path import exists\ndef f(p):\n return exists(p)\n", "f", ["does I/O: os.path.exists"]),
+ ("StringIO pure", "from io import StringIO\ndef f(s):\n return StringIO(s).read()\n", "f", []),
+ ("math pure", "from math import sqrt\ndef f(x):\n return sqrt(x)\n", "f", []),
+ ("future", "from __future__ import annotations\ndef f(x: int) -> int:\n return x\n", "f", []),
+ ("dotted alias", "import os.path as osp\ndef f(p):\n return osp.getsize(p)\n", "f", ["does I/O: os.path.getsize"]),
+ ("plain dotted import", "import os.path\ndef f(p):\n return os.path.getsize(p)\n", "f", ["does I/O: os.path.getsize"]),
+ ("pl alias is pathlib", "import pathlib as pl\ndef f(p, x):\n pl.Path(p).write_text(str(x))\n return x\n", "f", ["does I/O: pathlib.Path"]),
+ ("numpy random alias", "from numpy import random as rng\ndef f():\n return rng.random()\n", "f", ["not deterministic: numpy.random.random"]),
+ ("comprehension target", "import pathlib as p\ndef f(items):\n xs = [p.strip() for p in items]\n p.Path('o').write_text('x')\n return xs\n", "f", ["does I/O: pathlib.Path"]),
+ ("nested def binding", "from os import system\ndef f(x):\n def inner():\n system = 1\n return system(x)\n", "f", ["does I/O: os.system"]),
+ ("nested def import", "import random as r\ndef f():\n def inner():\n import math as r\n return r.random()\n", "f", ["not deterministic: random.random"]),
+ ("nested import stays inside", "import math as m\ndef f(x):\n def inner():\n import subprocess as m\n return m.sqrt(x)\n", "f", []),
+ ("lambda param", "from os import path\ndef f(items):\n return sorted(items, key=lambda path: path.lower())\n", "f", []),
+ ("nested def param", "from os import path\ndef f(items):\n def norm(path):\n return path.strip()\n return [norm(i) for i in items]\n", "f", []),
+ ("main guard import counts", "def f(x):\n return p.Path(x).read_text()\nif __name__ == '__main__':\n import pathlib as p\n f('x')\n", "f", ["does I/O: pathlib.Path"]),
+ ("polyfill def", "try:\n from subprocess import run\nexcept ImportError:\n def run(cmd):\n return None\ndef f(cmd):\n run(cmd)\n return 0\n", "f", ["does I/O: subprocess.run"]),
+ ("import after def", "def run(x):\n return x + 1\nfrom subprocess import run\ndef f(x):\n return run(x)\n", "f", ["does I/O: subprocess.run"]),
+ ("module reassign", "from os import path\npath = {'a': 1}\ndef f(k):\n return path.get(k)\n", "f", []),
+ ("module relative after", "import random as helper\nfrom . import helper\ndef f():\n return helper.compute()\n", "f", []),
+ ("match capture", "from os import path\ndef f(x):\n match x:\n case str() as path:\n return path.strip()\n return x\n", "f", []),
+ ("builtins param", "def f(builtins, x):\n return builtins.open(x)\n", "f", []),
+ ("plain builtins import", "import builtins\ndef f(x):\n return builtins.open(x)\n", "f", ["does I/O: open"]),
+ ("fromisoformat pure", "from datetime import date\ndef f(s):\n return date.fromisoformat(s)\n", "f", []),
+ ("datetime alias now", "from datetime import datetime as dt\ndef f():\n return dt.now()\n", "f", ["not deterministic: datetime.datetime.now"]),
+ ("uuid5 pure", "from uuid import uuid5, NAMESPACE_DNS\ndef f(s):\n return uuid5(NAMESPACE_DNS, s)\n", "f", []),
+ ("class method scope", "import subprocess as sp\nclass C:\n sp = 1\n @staticmethod\n def f(x):\n sp.run(['true'])\n return x\n", "f", ["does I/O: subprocess.run"]),
+ ("np.random", "import numpy as np\ndef f(n):\n return np.random.rand(n)\n", "f", ["not deterministic: numpy.random.rand"]),
+ ("local import then reassign", "def f(k):\n from os import path\n path = {'a': 1}\n return path.get(k)\n", "f", []),
+ ("two local imports", "def f(x):\n import subprocess as m\n import math as m\n return m.sqrt(x)\n", "f", []),
+ ("local import then relative", "def f():\n import random as helper\n from . import helper\n return helper.compute()\n", "f", []),
+ ("param then later import", "def f(p):\n s = p.strip()\n import pathlib as p\n return p.PurePath(s)\n", "f", []),
+ ("comprehension first iterable", "from pathlib import Path\ndef f():\n return [Path.name for Path in Path('.').iterdir()]\n", "f", ["does I/O: pathlib.Path"]),
+ ("nested default", "import random as r\ndef f():\n def inner(r=r.random()):\n return r\n return inner()\n", "f", ["not deterministic: random.random"]),
+ ("nested decorator", "import random as r\nfrom functools import lru_cache\ndef f():\n @lru_cache(maxsize=r.randint(1, 9))\n def g(r):\n return r\n return g(1)\n", "f", ["not deterministic: random.randint"]),
+ ("own default", "from os import getcwd\ndef f(getcwd=getcwd()):\n return getcwd\n", "f", ["does I/O: os.getcwd"]),
+ ("class body is no scope for methods", "import subprocess as sp\ndef f(x):\n class C:\n sp = 1\n def m(self):\n sp.run(['true'])\n C().m()\n return x\n", "f", ["does I/O: subprocess.run"]),
+ ("class import stays in class", "import math as m\ndef f(x):\n class C:\n import subprocess as m\n def g(self):\n return m.sqrt(x)\n return C().g()\n", "f", []),
+ ("bare annotation", "from pathlib import Path\nPath: object\ndef f(p):\n Path(p).write_text('hi')\n", "f", ["does I/O: pathlib.Path"]),
+ ("module for target", "import subprocess as sp\nfor sp in []:\n pass\ndef f():\n sp.run(['true'])\n", "f", ["does I/O: subprocess.run"]),
+ ("rebound module name", "import time\nFLAG = True\nif FLAG:\n time = lambda x: x + 1\ndef f(x):\n return time(x)\n", "f", []),
+ ("if-branch local binding", "from os import path\ndef f(x):\n if x:\n path = x\n return path.strip()\n", "f", []),
+ ("rebind from own value", "def f():\n import subprocess as sp\n sp = sp.run(['true'])\n return sp\n", "f", ["does I/O: subprocess.run"]),
+ ("with target from own call", "def f():\n from pathlib import Path\n with Path('x').open() as Path:\n pass\n", "f", ["does I/O: pathlib.Path"]),
+ ("class in class", "import subprocess as sp\ndef f():\n class C:\n sp = 1\n class D:\n y = sp.run(['true'])\n return C\n", "f", ["does I/O: subprocess.run"]),
+]
+fails = 0
+for i, (label, src, func, want) in enumerate(CASES):
+ f = os.path.join(d, f"case{i}.py")
+ open(f, "w").write(src)
+ line = next(n.lineno for n in ast.walk(ast.parse(src)) if isinstance(n, ast.FunctionDef) and n.name == func)
+ info = describe(f, line, func, None, d)
+ got = info["blockers"] if info else None
+ ok = got == want and info["module"] == f"case{i}"
+ fails += not ok
+ if not ok:
+ print("FAIL", label, f"got={got} want={want}", file=sys.stderr)
+# array-library warning kept, named once
+src = "import numpy as np\ndef f(x):\n return np.sum(x)\n"
+f = os.path.join(d, "arr.py"); open(f, "w").write(src)
+w = describe(f, 2, "f", None, d)["warnings"]
+ok = any(x.startswith("already uses np,") for x in w); fails += not ok
+if not ok:
+ print("FAIL numpy warning", w, file=sys.stderr)
+sys.exit(1 if fails else 0)
+"#;
+
+ #[test]
+ fn io_through_an_import_is_seen() {
+ 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-import-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("runner.py"), RUNNER).unwrap();
+ let out = Command::new(python)
+ .args(["-I", "-c", IMPORT_CASES])
+ .arg(dir.join("runner.py"))
+ .arg(&dir)
+ .output()
+ .unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ }
+
#[test]
fn maps_annotations() {
assert_eq!(rust_type("str", false).as_deref(), Some("&str"));
diff --git a/src/python/runner.py b/src/python/runner.py
index 7a3dcf5..3b496ac 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -31,6 +31,21 @@ IO_MODULES = {"os", "sys", "subprocess", "socket", "requests", "urllib", "http",
"pathlib", "logging", "sqlite3", "tempfile", "glob", "asyncio", "threading", "multiprocessing", "io"}
NONDET_MODULES = {"random", "time", "datetime", "uuid", "secrets"}
ARRAY_LIBS = {"np", "numpy", "pd", "pandas", "torch", "scipy", "numba", "polars", "pl"}
+# Pure callables from the modules above: imported by name, they don't block a function.
+PURE_CALLS = {
+ "datetime.date", "datetime.datetime", "datetime.time", "datetime.timedelta", "datetime.timezone",
+ "datetime.date.fromisoformat", "datetime.date.fromordinal", "datetime.date.fromisocalendar",
+ "datetime.datetime.fromisoformat", "datetime.datetime.strptime", "datetime.datetime.combine",
+ "datetime.time.fromisoformat", "io.StringIO", "io.BytesIO",
+ "pathlib.PurePath", "pathlib.PurePosixPath", "pathlib.PureWindowsPath",
+ "os.fspath", "os.fsdecode", "os.fsencode", "os.path.join", "os.path.basename", "os.path.dirname",
+ "os.path.split", "os.path.splitext", "os.path.normpath", "os.path.normcase", "os.path.isabs",
+ "os.path.commonpath", "os.path.commonprefix", "uuid.UUID", "uuid.uuid3", "uuid.uuid5",
+ "http.HTTPStatus", "http.HTTPMethod", "secrets.compare_digest", "glob.escape", "glob.has_magic",
+ "socket.inet_aton", "socket.inet_ntoa", "socket.inet_pton", "socket.inet_ntop",
+ "socket.htons", "socket.ntohs", "socket.htonl", "socket.ntohl",
+}
+PURE_MODULES = {"urllib.parse"}
# ------------------------------------------------------------------ values
@@ -266,10 +281,207 @@ def parse_file(path):
guard = next((n.lineno for n in tree.body if isinstance(n, ast.If) and is_main_guard(n.test)), None)
records = {n.name: record_class_fields(n) for n in tree.body
if isinstance(n, ast.ClassDef) and is_record_class(n)}
- _files[path] = (src, by_line, top, guard, records)
+ _files[path] = (src, by_line, top, guard, records, module_names(tree))
return _files[path]
+# --- names that stand for an imported module or function, by scope
+
+# Nodes with a scope of their own: names bound inside them don't reach the code around them.
+SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda, ast.ClassDef,
+ ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
+BLOCKS = ("body", "orelse", "finalbody", "handlers", "cases")
+
+
+def imports_in(node):
+ """name -> dotted names, for an import statement. `import subprocess as sp` gives sp: subprocess,
+ `from os import system` gives system: os.system; a relative import gives () (the app's own)."""
+ out = {}
+ if isinstance(node, ast.Import):
+ for a in node.names:
+ name = a.asname or a.name.split(".")[0]
+ out.setdefault(name, set()).add(tuple(a.name.split(".")) if a.asname else (name,))
+ elif isinstance(node, ast.ImportFrom) and node.module != "__future__":
+ for a in node.names:
+ if a.name != "*":
+ target = tuple(node.module.split(".")) + (a.name,) if node.module and node.level == 0 else ()
+ out.setdefault(a.asname or a.name, set()).add(target)
+ return out
+
+
+def binds(node):
+ """Names `node` binds in the scope it sits in, other than by importing."""
+ if isinstance(node, ast.Name) and isinstance(node.ctx, (ast.Store, ast.Del)):
+ return [node.id]
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ return [node.name]
+ if isinstance(node, (ast.ExceptHandler, ast.MatchAs, ast.MatchStar)) and node.name:
+ return [node.name]
+ if isinstance(node, ast.MatchMapping) and node.rest:
+ return [node.rest]
+ return []
+
+
+def evaluated_outside(scope):
+ """The parts of a scope node that run in the scope around it: decorators, defaults, class bases,
+ a comprehension's first iterable."""
+ if isinstance(scope, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
+ args = scope.args
+ parts = list(args.defaults) + [d for d in args.kw_defaults if d is not None]
+ return parts + list(getattr(scope, "decorator_list", []))
+ if isinstance(scope, ast.ClassDef):
+ return list(scope.decorator_list) + list(scope.bases) + [k.value for k in scope.keywords]
+ return [scope.generators[0].iter]
+
+
+def header_binds(st):
+ """What a statement binds outside its blocks (assignment, for and with targets...), not entering scopes."""
+ if isinstance(st, SCOPES):
+ return binds(st)
+ if isinstance(st, ast.AnnAssign) and st.value is None:
+ return [] # `x: int` declares, it doesn't bind
+ names, stack = binds(st), [v for f, v in ast.iter_fields(st) if f not in BLOCKS]
+ while stack:
+ v = stack.pop()
+ if isinstance(v, list):
+ stack.extend(v)
+ elif isinstance(v, ast.AST) and not isinstance(v, SCOPES):
+ names += binds(v)
+ stack.extend(ast.iter_child_nodes(v))
+ return names
+
+
+def bound_at(st):
+ """Where a statement's bindings take effect: once its header ran (an assignment's value, a with's
+ context, a for's iterable, a def's defaults), so `sp = sp.run()` still calls the imported `sp`."""
+ ends = [(n.end_lineno, n.end_col_offset) for f, v in ast.iter_fields(st) if f not in BLOCKS
+ for top in (v if isinstance(v, list) else [v]) if isinstance(top, ast.AST)
+ for n in ast.walk(top) if getattr(n, "end_lineno", None)] # a withitem has no position of its own
+ return max(ends) if ends else (getattr(st, "lineno", 0), getattr(st, "col_offset", 0))
+
+
+def bindings(stmts, maybe=False, out=None):
+ """(position, name, dotted names, maybe) for each binding in `stmts`, in order. An import binds what it
+ imports, anything else binds nothing known. A binding inside an if/try/with/for/while/match block, or a
+ for target, may or may not have happened."""
+ out = [] if out is None else out
+ for st in stmts:
+ pos = bound_at(st)
+ for name, targets in imports_in(st).items():
+ out.append((pos, name, frozenset(targets), maybe))
+ if not isinstance(st, (ast.Import, ast.ImportFrom)):
+ loop = isinstance(st, (ast.For, ast.AsyncFor))
+ out += [(pos, name, frozenset(), maybe or loop) for name in header_binds(st)]
+ if not isinstance(st, SCOPES):
+ for f in BLOCKS:
+ bindings(getattr(st, f, None) or [], True, out)
+ return out
+
+
+def state(entries, names=None, before=None):
+ """What each name stands for after `entries` (up to position `before`): a later plain binding replaces
+ an earlier one, a maybe-binding adds to it."""
+ names = dict(names or {})
+ for pos, name, targets, maybe in entries:
+ if before is None or pos < before:
+ names[name] = names.get(name, frozenset()) | targets if maybe else targets
+ return names
+
+
+def module_names(tree):
+ """What each name stands for at module level, after the whole module ran (imported names only)."""
+ return {name: targets for name, targets in state(bindings(tree.body)).items() if targets}
+
+
+def scope_bindings(scope):
+ """The bindings of a scope node's own body, its parameters first."""
+ if isinstance(scope, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)):
+ a = scope.args
+ params = [((0, 0), x.arg, frozenset(), False)
+ for x in a.posonlyargs + a.args + a.kwonlyargs + [v for v in (a.vararg, a.kwarg) if v]]
+ body = scope.body if isinstance(scope.body, list) else []
+ return params + bindings(body)
+ if isinstance(scope, ast.ClassDef):
+ return bindings(scope.body)
+ # a comprehension binds its targets
+ return [((0, 0), name, frozenset(), False) for g in scope.generators for n in ast.walk(g.target) for name in binds(n)]
+
+
+def resolved_calls(function, module_level):
+ """Calls in `function` (nested scopes included) whose first name stands for an imported module or
+ function at that call, with what it stands for. Follows Python's scoping: a scope's own bindings hide
+ the outer ones (the last one before the call counts), a class body is no scope for the functions in
+ it, and decorators, defaults and a comprehension's first iterable run in the scope around."""
+ found = []
+ flat = {}
+
+ def lookup(env, name, at):
+ local, outer = env
+ if name in local:
+ entries, imported = local[name]
+ if not imported:
+ return frozenset() # a plain local
+ return state(entries, before=at).get(name, frozenset())
+ return outer.get(name, frozenset())
+
+ def visit(node, env, fn_env, skip):
+ for child in ast.iter_child_nodes(node):
+ if id(child) in skip:
+ continue
+ if isinstance(child, SCOPES):
+ enter(child, env, fn_env)
+ continue
+ if isinstance(child, ast.Call):
+ target = dotted(child.func)
+ if target:
+ origins = lookup(env, target[0], (child.lineno, child.col_offset))
+ if origins:
+ found.append((target, origins))
+ visit(child, env, fn_env, skip)
+
+ def flatten(env):
+ """An env as plain names, for a nested scope to start from (its own bindings come on top)."""
+ if id(env) not in flat:
+ local, outer = env
+ names = dict(outer)
+ for name, (entries, _) in local.items():
+ names[name] = state(entries).get(name, frozenset())
+ flat[id(env)] = (env, names) # keep env alive so its id isn't reused
+ return flat[id(env)][1]
+
+ def enter(scope, env, fn_env):
+ heads = evaluated_outside(scope)
+ for h in heads:
+ visit(ast.Expr(value=h), env, fn_env, frozenset())
+ entries = {}
+ for entry in scope_bindings(scope):
+ entries.setdefault(entry[1], []).append(entry)
+ own = {name: (es, any(e[2] for e in es)) for name, es in entries.items()}
+ is_class = isinstance(scope, ast.ClassDef)
+ inner = (own, flatten(fn_env)) # a class body sees the enclosing function, never an outer class body
+ visit(scope, inner, fn_env if is_class else inner, frozenset(map(id, heads)))
+
+ enter(function, ({}, module_level), ({}, module_level))
+ return found
+
+
+def resolved_effect(full):
+ """("io" | "nondet", name) for a call resolved through an import, or None."""
+ name = ".".join(full)
+ if name in PURE_CALLS or any(name.startswith(m + ".") for m in PURE_MODULES):
+ return None
+ if len(full) < 2:
+ return None # a module isn't callable: the name was rebound to something else
+ head = full[0]
+ if head == "builtins" and len(full) == 2 and full[1] in IO_NAMES:
+ return "io", full[1]
+ if head in IO_MODULES:
+ return "io", name
+ if head in NONDET_MODULES or (head in ARRAY_LIBS and len(full) > 2 and full[1] == "random"):
+ return "nondet", name
+ return None
+
+
def is_record_class(node):
"""@dataclass (or @dataclasses.dataclass(...)) or a NamedTuple subclass."""
for d in node.decorator_list:
@@ -329,7 +541,7 @@ def describe(path, line, name, entry, base):
parsed = parse_file(path)
if parsed is None:
return None
- src, by_line, top, guard, records = parsed
+ src, by_line, top, guard, records, module_level_names = parsed
hit = by_line.get(line)
if hit is None or hit[0].name != name:
return None
@@ -393,6 +605,15 @@ def describe(path, line, name, entry, base):
nondet.add(".".join(target))
elif head in ARRAY_LIBS:
arrays.add(head)
+ # the same calls through an import: `sp.run` is subprocess.run, `system` is os.system
+ for target, origins in resolved_calls(node, module_level_names):
+ head = target[0]
+ if (head in IO_NAMES if len(target) == 1 else head in IO_MODULES or head in NONDET_MODULES):
+ continue # already caught by name
+ for origin in origins:
+ effect = origin and resolved_effect(list(origin) + target[1:])
+ if effect:
+ (io if effect[0] == "io" else nondet).add(effect[1])
if is_generator:
blockers.append("generator (yield)")
if writes_globals: