Datasets:
Download code/evaluation-code/v0.2-0c2690ae/tools/workspace/reachability.py from VEHwang/cocogni4d: direct link, hf CLI and curl.
- Browser
- Download file 29.5 kB
-
https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/tools/workspace/reachability.py
- Command line
-
hf download hf://datasets/VEHwang/cocogni4d/code/evaluation-code/v0.2-0c2690ae/tools/workspace/reachability.py
-
curl -L -o reachability.py https://huggingface.co/datasets/VEHwang/cocogni4d/resolve/main/code/evaluation-code/v0.2-0c2690ae/tools/workspace/reachability.py
29.5 kB
| #!/usr/bin/env python3 | |
| """Conservative static deletion guards; no runtime execution or writes. | |
| Graph rules follow arch-facts/facts.py; product rules follow arch-review/products.py. | |
| Literal paths/products are candidates for review, not proof of compatible artifacts. | |
| """ | |
| import argparse | |
| import ast | |
| from collections import defaultdict | |
| from fnmatch import fnmatchcase as match | |
| import importlib | |
| import json | |
| from pathlib import Path | |
| import posixpath | |
| import re | |
| import subprocess | |
| import sys | |
| if __package__: | |
| from .manage import files as source_files | |
| else: | |
| from manage import files as source_files | |
| def is_test(f): | |
| p = Path(f) | |
| return 'tests' in p.parts[:-1] or p.name.startswith('test_') or p.name.endswith('_test.py') or p.name == 'conftest.py' | |
| def modname(f): | |
| parts = list(Path(f).with_suffix('').parts) | |
| return '.'.join(parts[:-1] if parts[-1] == '__init__' else parts) | |
| class Repository: | |
| def __init__(self, root): | |
| self.root = root | |
| self.files = [f for f in source_files(root) if (root / f).is_file()] | |
| self.modules = {modname(f): f for f in self.files if f.endswith('.py')} | |
| self.tops = {m.split('.')[0] for m in self.modules} | |
| self.trees = {f: ast.parse((root / f).read_text(), filename=f) for f in self.modules.values()} | |
| self.edges = {f: self.references(f, tree) for f, tree in self.trees.items()} | |
| config = json.loads((root / 'tools/workspace/entrypoints.json').read_text()) | |
| if config['schema'] != 1: raise ValueError('unsupported entrypoint schema') | |
| todo = [m for m, f in self.modules.items() if not is_test(f) and | |
| (any(m == p or m.startswith(p + '.') for p in config['modules']) or any(match(f, p) for p in config['files']))] | |
| todo += [m for m in self.named_in_build() if not is_test(self.modules[m])] | |
| if not todo: raise ValueError('no entrypoints matched') | |
| self.reach = set() | |
| while todo: | |
| m = todo.pop() | |
| if m in self.reach or is_test(self.modules[m]): continue | |
| self.reach.add(m) | |
| for target, _, _ in self.edges[self.modules[m]]: | |
| todo.extend(p for p in self.parents(target) if not is_test(self.modules[p])) | |
| self.nontest = {m for m, f in self.modules.items() if not is_test(f)} | |
| def named_in_build(self): | |
| # Makefile 和 CI 里点名的入口(-m 模块、.py 路径),和 entrypoints.json 一起起算,不靠人补 | |
| found = set() | |
| for f in self.files: | |
| if Path(f).name != 'Makefile' and not f.startswith('.github/workflows/'): continue | |
| text = (self.root / f).read_text() | |
| found.update(m for name in re.findall(r'-m\s+([A-Za-z_][\w.]*)', text) if (m := self.longest(name))) | |
| found.update(modname(q) for p in re.findall(r'[\w./-]+\.py\b', text) | |
| if (q := str(Path(f).parent / p.removeprefix('./'))) in self.files) | |
| return sorted(found) | |
| def git(self, *args): | |
| p = subprocess.run(['git', '-C', str(self.root), *args], capture_output=True, text=True) | |
| if p.returncode not in (0, 1) or (p.returncode and args[0] != 'grep'): raise ValueError(p.stderr) | |
| return p.stdout | |
| def parents(self, m): | |
| return [p for i in range(1, len(m.split('.')) + 1) if (p := '.'.join(m.split('.')[:i])) in self.modules] | |
| def longest(self, m): | |
| while m and m not in self.modules: m = m.rpartition('.')[0] | |
| return m | |
| def resolve(self, f, name): | |
| first = name.split('.')[0] | |
| if first in self.tops: | |
| if result := self.longest(name): return result | |
| if first in sys.stdlib_module_names: return '' | |
| dirs = Path(f).parent.parts | |
| for prefix in ['.'.join(dirs[:i]) for i in range(len(dirs), 0, -1)] + ['spec.questions', 'apps.console']: | |
| result = self.longest(prefix + '.' + name) | |
| if result.count('.') >= prefix.count('.') + 1: return result | |
| return '' | |
| def references(self, f, tree): | |
| refs = set() | |
| for n in ast.walk(tree): | |
| raw = [] | |
| if isinstance(n, ast.Import): raw = [a.name for a in n.names] | |
| elif isinstance(n, ast.ImportFrom): | |
| parts = modname(f).split('.') | |
| prefix = parts[:len(parts)-n.level+1] if Path(f).name == '__init__.py' else parts[:-n.level] | |
| base = '.'.join(prefix + ([n.module] if n.module else [])) if n.level else (n.module or '') | |
| raw = [base] + [base + '.' + a.name for a in n.names if a.name != '*'] | |
| for name in raw: | |
| if (m := self.resolve(f, name)) and m != modname(f): refs.add((m, n.lineno, name)) | |
| if isinstance(n, ast.Constant) and isinstance(n.value, str) and len(n.value) < 200: | |
| names = ([n.value] if re.fullmatch(r'(?:embodied_pipeline|np|apps\.console|tools|spec\.questions)(?:\.\w+)*', n.value) else []) | |
| names += re.findall(r'(?:^|\s)-m\s+((?:embodied_pipeline|np|apps\.console|tools|spec\.questions)(?:\.\w+)*)', n.value) | |
| for name in names: | |
| if (m := self.longest(name)) and m != modname(f): refs.add((m, n.lineno, name)) | |
| if (isinstance(n, ast.Call) and isinstance(n.func, ast.Attribute) and n.func.attr == 'glob' and n.args | |
| and isinstance(n.args[0], ast.Constant) and str(n.args[0].value).endswith('.py')): | |
| refs.update((m, n.lineno, n.args[0].value) for m, g in self.modules.items() | |
| if g != f and Path(g).parent == Path(f).parent and match(Path(g).name, n.args[0].value)) | |
| if isinstance(n, ast.Call) and isinstance(n.func, (ast.Name, ast.Attribute)) and ast.unparse(n.func) in ('importlib.import_module', '__import__'): | |
| if n.args and isinstance(n.args[0], ast.Constant) and isinstance(n.args[0].value, str): | |
| if m := self.resolve(f, n.args[0].value): refs.add((m, n.lineno, n.args[0].value)) | |
| return sorted(refs) | |
| def check(repo): | |
| config = json.loads((repo.root / 'tools/workspace/keep.json').read_text()) | |
| if config['schema'] != 1: raise ValueError('unsupported keep schema') | |
| keep = config['keep']; unreachable = repo.nontest - repo.reach | |
| missing = sorted(m for m in unreachable if not any(match(m, k['pattern']) for k in keep)) | |
| stale = [k['pattern'] for k in keep if not any(match(m, k['pattern']) for m in repo.nontest)] | |
| return dict(reachable=len(repo.reach), unreachable=len(unreachable), patterns=len(keep), missing=missing, stale=stale), bool(missing or stale) | |
| def closure(repo, selected): | |
| importers = [dict(file=f, line=ln, target=m, raw=raw) for f, refs in repo.edges.items() | |
| if not is_test(f) and modname(f) not in selected for m, ln, raw in refs if set(repo.parents(m)) & selected] | |
| tests = []; before = defaultdict(set); after = defaultdict(set) | |
| for f, tree in repo.trees.items(): | |
| if not is_test(f): continue | |
| refs = repo.edges[f]; targets = {m for m, ln, _ in refs if not any(t.startswith(m + '.') and line == ln for t, line, _ in refs)} | |
| category = 'unrelated' if not targets & selected else ('all' if targets <= selected else 'mixed') | |
| aliases = set() | |
| for n in ast.walk(tree): | |
| if not isinstance(n, (ast.Import, ast.ImportFrom)): continue | |
| for a in n.names: | |
| single = ast.Import(names=[a]) if isinstance(n, ast.Import) else ast.ImportFrom(module=n.module, names=[a], level=n.level) | |
| if any(m in selected for m, _, _ in repo.references(f, ast.copy_location(single, n))): | |
| aliases.add(a.asname or (a.name.split('.')[0] if isinstance(n, ast.Import) else a.name)) | |
| affected = [] | |
| for n in ast.walk(tree): | |
| if isinstance(n, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)) and ( | |
| any(isinstance(x, ast.Name) and x.id in aliases for x in ast.walk(n)) or | |
| any(m in selected for m, _, _ in repo.references(f, n))): | |
| affected.append(dict(name=n.name, line=n.lineno, end=n.end_lineno)) | |
| tests.append(dict(file=f, category=category, affected=affected)) | |
| for m, ln, _ in refs: | |
| if m in repo.reach: before[m].add(f) | |
| if category != 'all' and m not in selected and not any(a['line'] <= ln <= a['end'] for a in affected): after[m].add(f) | |
| coverage = [dict(module=m, before=len(before[m]), after=len(after[m])) for m in sorted(repo.reach - selected)] | |
| lost = [c for c in coverage if c['before'] and not c['after']] | |
| return dict(importers=importers, tests=tests, coverage=coverage, lost=lost), bool(importers or lost) | |
| def paths(repo, selected): | |
| files = {repo.modules[m] for m in selected}; needles = set() | |
| for f in files: | |
| needles.update((f, Path(f).name)) | |
| if Path(f).parent != Path('.'): needles.add(str(Path(f).parent) + '/') | |
| candidates = [f for f in repo.files if f not in files and (Path(f).suffix in ('.py', '.ts', '.tsx', '.js', '.mjs', '.json', '.yml') or Path(f).name == 'Makefile')] | |
| # git grep also scans untracked source additions, so pre-commit checks are real. | |
| hits = repo.git('grep', '--no-index', '-nIF', *[a for n in sorted(needles) for a in ('-e', n)], '--', *candidates) if candidates and needles else '' | |
| return dict(hits=hits.splitlines()), bool(hits) | |
| def products(repo, selected): | |
| ops = []; unresolved = [] | |
| for m in sorted(repo.nontest): product_walk(repo.trees[repo.modules[m]].body, {}, repo.modules[m], ops, unresolved) | |
| writes = [o for o in ops if modname(o[0]) in selected and o[2] == 'write'] | |
| reads = [o for o in ops if modname(o[0]) in repo.reach - selected and o[2] == 'read'] | |
| pairs = sorted(set((w[3], f'{w[0]}:{w[1]}', f'{r[0]}:{r[1]}') for w in writes for r in reads if w[3] == r[3])) | |
| unresolved = [x for x in unresolved if modname(x[0]) in selected] # 核不了的写入不当没有(重构稿 ⑧ H3) | |
| return dict(pairs=pairs, unresolved_writes=unresolved, scope='normalized literal paths; dynamic paths not exhaustive'), bool(pairs or unresolved) | |
| FUNCS = (ast.FunctionDef, ast.AsyncFunctionDef) | |
| # 往派发表里登记的装饰器(prover 的 @method('…')、@evaluator('…')):被它装饰就算用上。新添一种登记方式,函数会报 zero,在这里加名字。 | |
| REGISTRARS = {'method', 'evaluator'} | |
| def dotted(n): | |
| parts = [] | |
| while isinstance(n, ast.Attribute): parts.append(n.attr); n = n.value | |
| return '.'.join([n.id] + parts[::-1]) if isinstance(n, ast.Name) else None | |
| def stdlib_callbacks(tree, cls): | |
| """类继承标准库的类(HTMLParser、Unpickler、BaseHTTPRequestHandler…)时,覆盖的方法由框架调:返回这些方法名。只导入标准库。""" | |
| names = {} | |
| for n in tree.body: | |
| if isinstance(n, ast.Import): names.update((a.asname or a.name.split('.')[0], a.asname and a.name or a.name.split('.')[0]) for a in n.names) | |
| elif isinstance(n, ast.ImportFrom) and n.module and not n.level: names.update((a.asname or a.name, f'{n.module}.{a.name}') for a in n.names) | |
| found = set() | |
| for base in cls.bases: | |
| head, _, rest = (dotted(base) or '').partition('.') | |
| full = '.'.join(x for x in (names.get(head, ''), rest) if x) | |
| if full.split('.')[0] not in sys.stdlib_module_names: continue | |
| module, _, attr = full.rpartition('.') | |
| try: found.update(dir(getattr(importlib.import_module(module), attr))) | |
| except (ImportError, AttributeError): pass | |
| return found | |
| def definitions(repo): | |
| """顶层函数、类、类里的方法:名 -> (文件, 行, 是否由派发表或框架调)。""" | |
| defs = {} | |
| for f, tree in repo.trees.items(): | |
| for n in tree.body: | |
| if not isinstance(n, (*FUNCS, ast.ClassDef)): continue | |
| callbacks = stdlib_callbacks(tree, n) if isinstance(n, ast.ClassDef) else set() | |
| for k, q in [(n, f'{modname(f)}.{n.name}')] + [(k, f'{modname(f)}.{n.name}.{k.name}') for k in n.body if isinstance(n, ast.ClassDef) and isinstance(k, FUNCS)]: | |
| defs[q] = (f, k.lineno, k.name in callbacks or | |
| any(isinstance(d, ast.Call) and ast.unparse(d.func).rsplit('.', 1)[-1] in REGISTRARS for d in k.decorator_list)) | |
| return defs | |
| def users(repo, defs): | |
| """每个定义被哪些文件引用:调用、当值传、字符串里写名字(表驱动派发);解析不到对象类型的 x.meth 按方法名宽松算。""" | |
| byname = defaultdict(set); used = defaultdict(set) | |
| for q in defs: byname[q.rsplit('.', 1)[1]].add(q) | |
| methods = {q for q in defs if q.rsplit('.', 2)[0] in repo.modules and q.count('.') >= 2 and q.rsplit('.', 1)[0] in defs} | |
| for q, (f, _, registered) in defs.items(): | |
| if registered: used[q].add(f) | |
| for f, tree in repo.trees.items(): | |
| own, alias = modname(f), {} | |
| for n in ast.walk(tree): | |
| if isinstance(n, ast.Import): | |
| for a in n.names: | |
| if m := repo.resolve(f, a.name): | |
| alias[a.asname] = m if a.asname else None | |
| if not a.asname: alias[a.name.split('.')[0]] = '.'.join(m.split('.')[:len(m.split('.')) - a.name.count('.')]) | |
| elif isinstance(n, ast.ImportFrom): | |
| parts = own.split('.') | |
| prefix = parts[:len(parts)-n.level+1] if Path(f).name == '__init__.py' else parts[:-n.level] | |
| base = repo.resolve(f, '.'.join(prefix + ([n.module] if n.module else [])) if n.level else (n.module or '')) | |
| for a in n.names: | |
| if base and a.name != '*': alias[a.asname or a.name] = f'{base}.{a.name}' | |
| alias.pop(None, None) | |
| for n in ast.walk(tree): | |
| hits = set() | |
| if isinstance(n, (ast.Name, ast.Attribute)) and (d := dotted(n)): | |
| head, _, rest = d.partition('.') | |
| if target := alias.get(head, f'{own}.{head}' if f'{own}.{head}' in defs else None): | |
| hits.add(target + ('.' + rest if rest else '')) | |
| if isinstance(n, ast.Attribute): hits.update(byname[n.attr] & methods) | |
| elif isinstance(n, ast.Attribute): hits.update(byname[n.attr] & methods) | |
| elif isinstance(n, ast.Constant) and isinstance(n.value, str) and n.value.isidentifier(): hits.update(byname[n.value]) | |
| for q in hits & defs.keys(): | |
| if defs[q][0] != f or n.lineno != defs[q][1]: used[q].add(f) | |
| return used | |
| def node_at(repo, f, line): | |
| return next(k for k in ast.walk(repo.trees[f]) if isinstance(k, (*FUNCS, ast.ClassDef)) and k.lineno == line) | |
| def changed(repo, base, defs): | |
| """base 以来(含工作区)改到的定义:diff 新侧的行落在函数、方法的 lineno..end_lineno 里;只删不加的 hunk 记删除点那一行。""" | |
| lines, f = defaultdict(set), None | |
| for l in repo.git('diff', '-U0', base, '--', '*.py').splitlines(): | |
| if l.startswith('+++ '): | |
| f = l[6:] if l.startswith('+++ b/') else None | |
| elif f and (m := re.match(r'@@ -\S+ \+(\d+)(?:,(\d+))? @@', l)): | |
| start, n = int(m.group(1)), int(m.group(2) or 1) | |
| lines[f].update(range(start, start + max(n, 1))) | |
| hit = set() | |
| for q, (f, line, _) in defs.items(): | |
| node = node_at(repo, f, line) | |
| inner = [k for k in getattr(node, 'body', []) if isinstance(k, FUNCS)] if isinstance(node, ast.ClassDef) else [] | |
| span = set(range(line, node.end_lineno + 1)) - {i for k in inner for i in range(k.lineno, k.end_lineno + 1)} | |
| if span & lines.get(f, set()): hit.add(q) | |
| return hit | |
| def tests_for(repo, base): | |
| """改函数契约时要跑的测试(H3 返工,11-01:只跑了改动文件的测试,调用方的测试在 CI 才红):直接引用改到的定义的测试, | |
| 加调用方函数的测试。调用方是引用文件(含改动文件本身)里函数体用到改动名字的函数,不按整个文件算。""" | |
| defs = definitions(repo); used = users(repo, defs); hit = changed(repo, base, defs) | |
| files, names = {g for q in hit for g in used[q] if not is_test(g)} | {defs[q][0] for q in hit}, {q.rsplit('.', 1)[1] for q in hit} | |
| refers = lambda node: any(isinstance(n, ast.Name) and n.id in names or isinstance(n, ast.Attribute) and n.attr in names for n in ast.walk(node)) | |
| callers = {q for q, (f, line, _) in defs.items() if f in files and q not in hit and not is_test(f) | |
| and isinstance(node := node_at(repo, f, line), FUNCS) and refers(node)} | |
| tests = {g for q in hit | callers for g in used[q] if is_test(g)} | |
| return dict(changed=sorted(hit), callers=sorted(callers), tests=sorted(tests)), False | |
| def functions(repo, selected=None): | |
| defs = definitions(repo); used = users(repo, defs); rows = [] | |
| for q, (f, line, _) in sorted(defs.items()): | |
| name = q.rsplit('.', 1)[1] | |
| if is_test(f) or (name.startswith('__') and name.endswith('__')): continue | |
| by = used[q] | |
| bucket = ('used-live' if any(not is_test(g) and modname(g) in repo.reach for g in by) else | |
| 'used-test-only' if by and all(is_test(g) for g in by) else 'used-unreached-only' if by else 'zero') | |
| rows.append(dict(name=q, file=f, line=line, live=modname(f) in repo.reach, bucket=bucket, users=len(by))) | |
| counts = defaultdict(int) | |
| for x in rows: counts[('live ' if x['live'] else 'unreached ') + x['bucket']] += 1 | |
| return dict(counts=dict(sorted(counts.items())), rows=rows), False | |
| BASELINE = 'tools/workspace/dead_baseline.txt' | |
| def read_baseline(text): | |
| rows = [line.split('\t') for line in text.splitlines()[1:] if line.strip()] | |
| return {x[0]: x for x in rows} | |
| def check_dead(repo, base=None): | |
| """现行文件里的 zero、used-test-only 函数要和基线逐行对上:新增的、基线里已不死的都失败;--base 给出时基线只许减。""" | |
| dead = {x['name']: x for x in functions(repo)[0]['rows'] if x['live'] and x['bucket'] in ('zero', 'used-test-only')} | |
| baseline = read_baseline((repo.root / BASELINE).read_text()) | |
| added = [] | |
| if base: | |
| repo.git('rev-parse', '--verify', '--quiet', f'{base}^{{commit}}') | |
| listed = repo.git('ls-tree', '--name-only', base, '--', BASELINE) | |
| if listed.strip(): # 基准里还没有基线文件,是首次引入,没有可比的 | |
| added = sorted(baseline.keys() - read_baseline(repo.git('show', f'{base}:{BASELINE}')).keys()) | |
| result = dict(dead=len(dead), baseline=len(baseline), | |
| new=[f"{x['file']}:{x['line']} {q} {x['bucket']}" for q, x in sorted(dead.items()) if q not in baseline], | |
| stale=sorted(baseline.keys() - dead.keys()), unexplained=sorted(q for q, x in baseline.items() if len(x) < 3 or not x[2].strip()), | |
| added=added) | |
| return result, bool(result['new'] or result['stale'] or result['unexplained'] or added) | |
| def main(argv=None): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('command', choices=('check', 'closure', 'paths', 'products', 'functions', 'check-dead', 'tests-for')) | |
| parser.add_argument('modules', nargs='*', help='module names or fnmatch patterns') | |
| parser.add_argument('--exclude', action='append', default=[], help='subtract a module pattern from S') | |
| parser.add_argument('--root', type=Path, default=Path(__file__).resolve().parents[2]) | |
| parser.add_argument('--json', action='store_true') | |
| parser.add_argument('--base', help='check-dead:和这个提交的基线比,基线只许减;tests-for:从这个提交起的改动') | |
| args = parser.parse_args(argv) | |
| try: | |
| repo = Repository(args.root.resolve()) | |
| selected = {m for m in repo.modules if any(match(m, p) for p in args.modules) and not any(match(m, p) for p in args.exclude)} | |
| if args.command in ('closure', 'paths', 'products') and (not args.modules or any(not any(match(m, p) for m in repo.modules) for p in args.modules) or not selected): | |
| raise ValueError('each selection pattern must match; S must not be empty') | |
| result, failed = (check(repo) if args.command == 'check' else check_dead(repo, args.base) if args.command == 'check-dead' | |
| else tests_for(repo, args.base or 'HEAD') if args.command == 'tests-for' | |
| else globals()[args.command](repo, selected)) | |
| if args.json: print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| elif args.command == 'functions': | |
| print('名\t文件\t行\t文件可达\t档\t引用文件数') | |
| for x in result['rows']: print(f"{x['name']}\t{x['file']}\t{x['line']}\t{int(x['live'])}\t{x['bucket']}\t{x['users']}") | |
| elif args.command == 'check-dead' and not failed: print(f"现行文件里没用上的函数 {result['dead']} 个,都在基线里({result['baseline']} 行)") | |
| elif args.command == 'tests-for': print(' '.join(result['tests'])) | |
| elif args.command == 'check' and not failed: print(f"可达 {result['reachable']}、不可达 {result['unreachable']}、保留 pattern {result['patterns']}") | |
| else: print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| return int(failed) | |
| except (ValueError, OSError, SyntaxError, KeyError) as error: | |
| print(json.dumps({'error': str(error)}, ensure_ascii=False), file=sys.stderr) | |
| return 2 | |
| RX=re.compile(r'(?<![\w%{}-])([A-Za-z0-9_][\w.-]*\.(?:jsonl|json|npz|npy|png|html|mp4|csv|txt|md|bin|gz|lock))(?![\w.-])') | |
| def values(n,env): | |
| if isinstance(n,ast.Constant) and isinstance(n.value,str): return {n.value} | |
| if isinstance(n,ast.Name): return env.get(n.id,{None}) | |
| if isinstance(n,(ast.List,ast.Tuple)): return set().union(*(values(x,env) for x in n.elts)) | |
| if isinstance(n,ast.IfExp): return values(n.body,env)|values(n.orelse,env) | |
| if isinstance(n,ast.BinOp): | |
| left,right=values(n.left,env),values(n.right,env) | |
| if isinstance(n.op,(ast.Add,ast.Div)): | |
| return {None if x is None or y is None else x+y if isinstance(n.op,ast.Add) | |
| else posixpath.normpath(str(Path(x)/y)) for x in left for y in right} | |
| if isinstance(n,ast.Attribute) and n.attr=='parent': | |
| return {None if v is None else str(Path(v).parent) for v in values(n.value,env)} | |
| if isinstance(n,ast.Call): | |
| if isinstance(n.func,ast.Name) and n.func.id in ('Path','str') and not n.keywords: | |
| if n.func.id=='str':return values(n.args[0],env) if len(n.args)==1 else {None} | |
| parts={'.'} | |
| for arg in n.args: | |
| parts={None if a is None or b is None else posixpath.normpath(str(Path(a)/b)) | |
| for a in parts for b in values(arg,env)} | |
| return parts | |
| if isinstance(n.func,ast.Attribute): | |
| base=values(n.func.value,env) | |
| if n.func.attr=='resolve' and not n.args and not n.keywords: | |
| return {None if v is None else posixpath.normpath(v) for v in base} | |
| if n.func.attr in ('with_name','with_suffix') and len(n.args)==1 and not n.keywords: | |
| result=set() | |
| for path in base: | |
| for replacement in values(n.args[0],env): | |
| try: | |
| result.add(str(getattr(Path(path),n.func.attr)(replacement)) | |
| if path is not None and replacement is not None else None) | |
| except ValueError: | |
| result.add(None) | |
| return result | |
| return {None} | |
| def names(n,env): | |
| return {posixpath.normpath(v) for v in values(n,env) if v is not None and RX.fullmatch(Path(v).name)} | |
| def product_walk(nodes,env,f,ops,unresolved): | |
| env=dict(env) | |
| def merge(states): | |
| return {key:set().union(*(state.get(key,{None}) for state in states)) for key in set().union(*(s.keys() for s in states))} | |
| def bind(target,value): | |
| if isinstance(target,ast.Name): env[target.id]=values(value,env) | |
| elif isinstance(target,(ast.Tuple,ast.List)) and isinstance(value,(ast.Tuple,ast.List)): | |
| for t,v in zip(target.elts,value.elts): bind(t,v) | |
| for n in nodes: | |
| scan_env=dict(env) | |
| if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef,ast.ClassDef)): | |
| sub=dict(env) | |
| if isinstance(n,(ast.FunctionDef,ast.AsyncFunctionDef)): | |
| for arg in (*n.args.posonlyargs,*n.args.args,*n.args.kwonlyargs,n.args.vararg,n.args.kwarg): | |
| if arg is not None: sub.pop(arg.arg,None) | |
| product_walk(n.body,sub,f,ops,unresolved); continue | |
| if isinstance(n,ast.Assign): | |
| for t in n.targets: bind(t,n.value) | |
| if isinstance(n,ast.AnnAssign) and n.value: bind(n.target,n.value) | |
| if isinstance(n,(ast.For,ast.AsyncFor)): | |
| sub=dict(env) | |
| choices=n.iter.elts if isinstance(n.iter,(ast.List,ast.Tuple)) else [ast.Constant(value=v) for v in values(n.iter,env)] | |
| if choices: | |
| previous=dict(env) | |
| accumulated={} | |
| for item in choices: | |
| bind(n.target,item) | |
| for key in env:accumulated[key]=accumulated.get(key,set())|env[key] | |
| sub.update(accumulated) | |
| env=previous | |
| after=product_walk(n.body,sub,f,ops,unresolved) | |
| env=merge([env,after]) | |
| env=merge([env,product_walk(n.orelse,env,f,ops,unresolved)]) | |
| continue | |
| if isinstance(n,(ast.With,ast.AsyncWith)): | |
| sub=dict(env) | |
| for item in n.items: | |
| call=item.context_expr | |
| if isinstance(call,ast.Call) and isinstance(call.func,ast.Attribute) and call.func.attr=='open' and isinstance(item.optional_vars,ast.Name): | |
| sub[item.optional_vars.id]=names(call.func.value,env) | |
| # Process the context open calls once, body separately. | |
| children=[x.context_expr for x in n.items] | |
| env=product_walk(n.body,sub,f,ops,unresolved) | |
| elif isinstance(n,ast.Try): | |
| body=product_walk(n.body,env,f,ops,unresolved) | |
| branches=[product_walk(n.orelse,body,f,ops,unresolved)] | |
| branches += [product_walk(h.body,merge([env,body]),f,ops,unresolved) for h in n.handlers] | |
| env=product_walk(n.finalbody,merge(branches),f,ops,unresolved) | |
| children=[] | |
| elif isinstance(n,(ast.If,ast.While)): | |
| body=product_walk(n.body,env,f,ops,unresolved) | |
| other=product_walk(n.orelse,env,f,ops,unresolved) | |
| env=merge([body,other] if isinstance(n,ast.If) else [env,body,other]) | |
| children=[n.test] if hasattr(n,'test') else [] | |
| else: children=[n] | |
| for child in children: | |
| for call in ast.walk(child): | |
| if not isinstance(call,ast.Call):continue | |
| fn=ast.unparse(call.func); tail=fn.rsplit('.',1)[-1]; typ=None; target=None | |
| if tail in ('write_text','write_bytes') and isinstance(call.func,ast.Attribute): typ='write';target=call.func.value | |
| elif tail=='open': | |
| method=isinstance(call.func,ast.Attribute) and fn not in ('gzip.open','io.open') | |
| target=call.func.value if method else (call.args[0] if call.args else None) | |
| modes=call.args[0:1] if method else call.args[1:2] | |
| modes += [v.value for v in call.keywords if v.arg=='mode'] | |
| mode=modes[0].value if modes and isinstance(modes[0],ast.Constant) else 'r' | |
| typ='write' if isinstance(mode,str) and any(x in mode for x in 'wax+') else 'read' | |
| elif fn in ('np.save','np.savez','np.savez_compressed','numpy.save','numpy.savez','numpy.savez_compressed','dump','_json','_save','_npz'): | |
| typ='write'; target=call.args[0] if call.args else None | |
| elif fn in ('shutil.copy','shutil.copy2','shutil.copyfile','shutil.copytree'): | |
| typ='write'; target=call.args[1] if len(call.args)>1 else None | |
| elif fn=='json.dump':typ='write';target=call.args[1] if len(call.args)>1 else None | |
| elif fn=='zipfile.ZipFile' and len(call.args)>1 and isinstance(call.args[1],ast.Constant) and call.args[1].value in ('x','w','a'): | |
| typ='write';target=call.args[0] | |
| elif fn=='copy_actor_table' and len(call.args)>2:typ='write';target=call.args[2] | |
| elif tail in ('json','write') and isinstance(call.func,ast.Attribute) and isinstance(call.func.value,ast.Name) and call.func.value.id in ('output','writer'): | |
| typ='write';target=call.args[0] if call.args else None | |
| elif tail in ('read_text','read_bytes','is_file') and isinstance(call.func,ast.Attribute):typ='read';target=call.func.value | |
| elif fn in ('np.load','numpy.load','json.load') or tail in ('read_json','small_json'): | |
| typ='read';target=call.args[0] if call.args else None | |
| if target is not None: | |
| found=names(target,scan_env) | |
| for name in found: ops.append((f,call.lineno,typ,name,fn)) | |
| if typ=='write' and (not found or None in values(target,scan_env)): | |
| unresolved.append((f,call.lineno,ast.unparse(call)[:180])) | |
| return env | |
| if __name__ == '__main__': | |
| sys.exit(main()) | |