Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def checkLocals(self, code, ref):
node = ast.parse(code)
c = StrictDefUseChains()
c.visit(node)
functions = [n for n in node.body if isinstance(n, ast.FunctionDef)]
assert len(functions) == 1, "only one top-level function per test case"
f = functions[0]
self.assertEqual(c.dump_definitions(f), ref)
def check_unbound_identifier_message(self, code, expected_messages, filename=None):
node = ast.parse(code)
c = beniget.DefUseChains(filename)
with captured_output() as (out, err):
c.visit(node)
produced_messages = out.getvalue().strip().split("\n")
self.assertEqual(len(expected_messages), len(produced_messages))
for expected, produced in zip(expected_messages, produced_messages):
self.assertIn(expected, produced, "actual message contains expected message")
def py2js(value):
"""Convert Python code or Python function to JavaScript code."""
if isinstance(value, str):
parsed = ast.parse(value, '', 'exec')
return ';\n'.join([Py2JSVisitor().visit(node) for node in parsed.body])
if isinstance(value, (types.FunctionType, types.MethodType)):
if getattr(value, '__name__', '') in ('', ''):
raise RuntimeError('Anonymous functions not supported')
value = inspect.getsource(value)
module = ast.parse(value, '', 'exec')
func = module.body[0]
return ';\n'.join([Py2JSVisitor().visit(node) for node in func.body])
raise RuntimeError('py2js only supports a code string or function as input')
def strip_typehints(source):
"""Strip the type hints from a function"""
source = format_str(source)
# parse the source code into an AST
parsed_source = ast.parse(source)
# remove all type annotations, function return type definitions
# and import statements from 'typing'
transformed = TypeHintRemover().visit(parsed_source)
# convert the AST back to source code
striped_code = extast.unparse(transformed)
return striped_code
print_unparsed,
filter_code_typevars
)
path_examples = Path("examples")
files = sorted(path_examples.glob("*.py"))
with open(files[1]) as file:
code = file.read()
print("ast.parse")
module = ast.parse(code)
print("compute DefUseChains")
duc = beniget.DefUseChains()
duc.visit(module)
print("compute Ancestors")
ancestors = beniget.Ancestors()
ancestors.visit(module)
code_filtered = filter_code_typevars(module, duc, ancestors)
print(code_filtered)
import gast as ast
import beniget
mod = ast.parse("""
T = int
def func() -> T:
return 1
""")
fdef = mod.body[1]
node = fdef.returns
du = beniget.DefUseChains()
du.visit(mod)
du.chains[node]
ud = beniget.UseDefChains(du)
ud.chains[node]
import beniget
import gast as ast
import astunparse
from capturex import CaptureX
examples = {6: "issue6_import.py", 7: "issue7_func.py"}
with open(examples[6]) as file:
code = file.read()
module = ast.parse(code)
duc = beniget.DefUseChains()
duc.visit(module)
ancestors = beniget.Ancestors()
ancestors.visit(module)
boost = [d for d in duc.locals[module] if d.name() == "boost"][0]
for user in boost.users():
# we're interested in the parent of the decorator
fdef = ancestors.parent(user.node)
chain = duc.chains[fdef]
for node in fdef.decorator_list:
def raw_parse(code):
# hacky way to turn OpenMP comments into strings
code = re.sub(r'(\s*)#\s*(omp\s[^\n]+)', r'\1"\2"', code)
return ast.parse(code)
def parse(code, *args, **kwargs):
"""Parse a code and produce the extended AST"""
tree = ast.parse(code, *args, **kwargs)
CommentInserter(tree, code)
return tree
def parse_str(src, preamble_len=0, single_node=True):
"""Returns the AST of given piece of code.
Args:
src: Text
preamble_len: Int, indicates leading nodes in the parsed AST which should be
dropped.
single_node: Bool, whether `src` is assumed to be represented by exactly one
AST node.
Returns:
ast.AST
"""
module_node = gast.parse(src)
nodes = module_node.body
if preamble_len:
nodes = nodes[preamble_len:]
if single_node:
if len(nodes) != 1:
raise ValueError('expected exactly one node node, found {}'.format(nodes))
return nodes[0]
return nodes