コード例 #1
0
ファイル: test_visitors.py プロジェクト: leonardt/ast_tools
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'}
コード例 #2
0
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
コード例 #3
0
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
コード例 #4
0
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()))
コード例 #5
0
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
コード例 #6
0
ファイル: common.py プロジェクト: leonardt/ast_tools
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