How to use the gast.parse function in gast

To help you get started, we’ve selected a few gast examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github serge-sans-paille / beniget / tests / definitions.py View on Github external
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)
github serge-sans-paille / beniget / tests / chains.py View on Github external
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")
github martinRenou / ipycanvas / ipycanvas / animation.py View on Github external
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')
github fluiddyn / transonic / transonic / util.py View on Github external
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
github fluiddyn / transonic / tmp / analyses / filter_body.py View on Github external
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)
github fluiddyn / transonic / doc / examples / inlined / bug_beniget.py View on Github external
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]
github fluiddyn / transonic / doc / examples / issues / analyze_issue6.py View on Github external
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:
github serge-sans-paille / pythran / pythran / frontend.py View on Github external
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)
github fluiddyn / transonic / transonic / analyses / extast.py View on Github external
def parse(code, *args, **kwargs):
    """Parse a code and produce the extended AST"""
    tree = ast.parse(code, *args, **kwargs)
    CommentInserter(tree, code)
    return tree
github tensorflow / tensorflow / tensorflow / python / autograph / pyct / parser.py View on Github external
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