def test_used_names(): tree = cst.parse_module(''' x = 1 def foo(): def g(): pass class A: def __init__(self): pass class B: pass x.f = 7 async def h(): pass ''') assert used_names(tree) == {'x', 'foo', 'A', 'h'} assert used_names(tree.body[1].body) == {'g'}
def gen_free_name(tree: ast.AST, env: SymbolTable, prefix: tp.Optional[str] = None) -> str: names = used_names(tree) | env.keys() if prefix is not None and prefix not in names: return prefix elif prefix is None: prefix = '__auto_name_' f_str = prefix + '{}' c = 0 name = f_str.format(c) while name in names: c += 1 name = f_str.format(c) return name
def gen_free_prefix(tree: ast.AST, env: SymbolTable, preprefix: tp.Optional[str] = None) -> str: def check_prefix(prefix: str, used_names: tp.AbstractSet[str]) -> bool: return not any(name.startswith(prefix) for name in used_names) names = used_names(tree) | env.keys() if preprefix is not None and check_prefix(preprefix, names): return preprefix elif preprefix is None: preprefix = '__auto_prefix_' f_str = preprefix + '{}' c = 0 prefix = f_str.format(c) while not check_prefix(prefix, names): c += 1 prefix = f_str.format(c) return prefix
def is_free_prefix(tree: ast.AST, env: SymbolTable, prefix: str): names = used_names(tree) return not any( name.startswith(prefix) for name in itertools.chain(names, env.keys()))
def is_free_name(tree: ast.AST, env: SymbolTable, name: str): names = used_names(tree) return name not in names and name not in env
def is_free_name(tree: cst.CSTNode, env: SymbolTable, name: str): names = used_names(tree) return name not in names and name not in env