Python _ast.Call() Examples

The following are 10 code examples of _ast.Call(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module _ast , or try the search function .
Example #1
Source File: types.py    From equip with Apache License 2.0 6 votes vote down vote up
def run(self, node, input_state):
    result_state = input_state.copy()
    block = node.data

    constraints = self.cfg.block_constraints

    for stmt in block.statements:
      native = stmt.native
      if isinstance(native, _ast.Assign) or isinstance(native, _ast.AugAssign):
        self.transfer_assign(result_state, native, stmt.start_bytecode_index)

      elif isinstance(native, _ast.Expr):
        value = native.value
        logger.debug("Stmt kind: %s", type(value))
        if isinstance(value, _ast.Call):
          self.transfer_call(result_state, native, stmt.start_bytecode_index)
      else:
        logger.error("Unknown stmt: %s", dump_native_ast(native))

    return result_state


  # Assign: a <- b 
Example #2
Source File: config.py    From portray with MIT License 6 votes vote down vote up
def setup_py(location: str) -> dict:
    """Returns back any configuration info we are able to determine from a setup.py file"""
    setup_config = {}
    try:
        with open(location) as setup_py_file:
            for node in ast.walk(ast.parse(setup_py_file.read())):
                if (
                    type(node) == _ast.Call
                    and type(getattr(node, "func", None)) == _ast.Name
                    and node.func.id == "setup"  # type: ignore
                ):
                    for keyword in node.keywords:  # type: ignore
                        if keyword.arg == "packages":
                            setup_config["modules"] = ast.literal_eval(keyword.value)
                            break
                    break
    except Exception as error:
        warnings.warn(f"Error ({error}) occurred trying to parse setup.py file: {location}")

    return setup_config 
Example #3
Source File: cpp.py    From pymtl with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def visit_Call( self, node ):
    # TODO: specially handle self.visit( node.func ) if attr
    #       currently not visiting at all!
    args     = [self.visit(x) for x in node.args]
    keywords = [self.visit(x) for x in node.keywords]
    if node.starargs:
      starargs = [self.visit(x) for x in node.starargs]
    else:
      starargs = None
    if node.kwargs:
      kwargs = [self.visit(x) for x in node.kwargs]
    else:
      kwargs = None

    return _ast.Call(func=node.func,
                     args=args,
                     keyword=keywords,
                     starargs=starargs,
                     kwargs=kwargs) 
Example #4
Source File: checker.py    From blackmamba with MIT License 6 votes vote down vote up
def NAME(self, node):
        """
        Handle occurrence of Name (which can be a load/store/delete access.)
        """
        # Locate the name in locals / function / globals scopes.
        if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
            self.handleNodeLoad(node)
            if (node.id == 'locals' and isinstance(self.scope, FunctionScope)
                    and isinstance(node.parent, ast.Call)):
                # we are doing locals() call in current scope
                self.scope.usesLocals = True
        elif isinstance(node.ctx, (ast.Store, ast.AugStore)):
            self.handleNodeStore(node)
        elif isinstance(node.ctx, ast.Del):
            self.handleNodeDelete(node)
        else:
            # must be a Param context -- this only happens for names in function
            # arguments, but these aren't dispatched through here
            raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) 
Example #5
Source File: checker.py    From Transcrypt with Apache License 2.0 6 votes vote down vote up
def NAME(self, node):
        """
        Handle occurrence of Name (which can be a load/store/delete access.)
        """
        # Locate the name in locals / function / globals scopes.
        if isinstance(node.ctx, (ast.Load, ast.AugLoad)):
            self.handleNodeLoad(node)
            if (node.id == 'locals' and isinstance(self.scope, FunctionScope)
                    and isinstance(node.parent, ast.Call)):
                # we are doing locals() call in current scope
                self.scope.usesLocals = True
        elif isinstance(node.ctx, (ast.Store, ast.AugStore)):
            self.handleNodeStore(node)
        elif isinstance(node.ctx, ast.Del):
            self.handleNodeDelete(node)
        else:
            # must be a Param context -- this only happens for names in function
            # arguments, but these aren't dispatched through here
            raise RuntimeError("Got impossible expression context: %r" % (node.ctx,)) 
Example #6
Source File: calc.py    From yui with GNU Affero General Public License v3.0 5 votes vote down vote up
def visit_call(self, node: _ast.Call):  # func, args, keywords
        func = self._run(node.func)
        args = [self._run(x) for x in node.args]
        keywords = {x.arg: self._run(x.value) for x in node.keywords}
        return func(*args, **keywords) 
Example #7
Source File: grammar.py    From runa with MIT License 5 votes vote down vote up
def get_rules():
	
	with open(PARSER_FILE) as f:
		src = f.read()
	
	rules = collections.OrderedDict()
	for node in ast.parse(src).body:
		
		if not isinstance(node, _ast.FunctionDef):
			continue
		
		if not node.decorator_list:
			continue
		
		assert len(node.decorator_list) == 1
		decorator = node.decorator_list[0]
		if not isinstance(decorator, _ast.Call):
			continue
		
		func = decorator.func
		if not isinstance(func, _ast.Attribute):
			continue
		
		assert func.attr == 'production'
		ln = decorator.args[0].s
		name, match = ln.split(' : ', 1)
		rules.setdefault(name, []).append(tuple(match.split()))
	
	return rules 
Example #8
Source File: stmt.py    From equip with Apache License 2.0 4 votes vote down vote up
def make_call(i, bytecode):
    op = bytecode[i][2]

    def get_call_arg_length(op, arg):
      na = arg & 0xff         # num args
      nk = (arg >> 8) & 0xff  # num keywords
      return na, nk, na + 2 * nk + CALL_EXTRA_ARG_OFFSET[op]

    has_var, has_kw = 0, 0
    if op in (CALL_FUNCTION_VAR, CALL_FUNCTION_VAR_KW): has_var = 1
    if op in (CALL_FUNCTION_KW, CALL_FUNCTION_VAR_KW): has_kw = 1

    op, arg = bytecode[i][2], bytecode[i][3]
    num_args, num_keywords, offset = get_call_arg_length(op, arg)

    func, args, keywords, starargs, kwargs = None, None, None, None, None

    if has_kw > 0:
      i, kwargs = Statement.make_expr(i - 1, bytecode)

    if has_var > 0:
      i, starargs = Statement.make_expr(i - 1, bytecode)

    # Handle keywords
    if num_keywords > 0:
      keywords = []
      while num_keywords > 0:
        i, kw_value = Statement.make_expr(i - 1, bytecode)
        i, kw_name = Statement.make_expr(i - 1, bytecode)
        keywords.insert(0, _ast.keyword(kw_name, kw_value))
        num_keywords -= 1

    finger = i - 1

    if num_args > 0:
      n = num_args - 1
      args = [None] * num_args
      for k in range(num_args):
        cur_stack = 0
        loc_bytecode = []
        is_first = True
        while True:
          op, arg = bytecode[finger][2], bytecode[finger][3]
          pop, push = get_stack_effect(op, arg)
          cur_stack -= (pop - push) if not is_first else pop
          is_first = False
          loc_bytecode.insert(0, bytecode[finger])
          if cur_stack == 0:
            break
          finger -= 1
        _, args[n] = Statement.make_expr(len(loc_bytecode) - 1, loc_bytecode)
        n -= 1
        finger -= 1

    _, func = Statement.make_expr(finger, bytecode)

    call = _ast.Call(func, args, keywords, starargs, kwargs)
    logger.debug("\n%s", dump(call))
    return finger, call 
Example #9
Source File: source_parser.py    From pyFileFixity with MIT License 4 votes vote down vote up
def parse_source_file(file_name):
  """
  Parses the AST of Python file for lines containing
  references to the argparse module.

  returns the collection of ast objects found.

  Example client code:

    1. parser = ArgumentParser(desc="My help Message")
    2. parser.add_argument('filename', help="Name of the file to load")
    3. parser.add_argument('-f', '--format', help='Format of output \nOptions: ['md', 'html']
    4. args = parser.parse_args()

  Variables:
    * nodes 									Primary syntax tree object
    *	argparse_assignments   	The assignment of the ArgumentParser (line 1 in example code)
    * add_arg_assignments     Calls to add_argument() (lines 2-3 in example code)
    * parser_var_name					The instance variable of the ArgumentParser (line 1 in example code)
    * ast_source							The curated collection of all parser related nodes in the client code
  """

  nodes = ast.parse(_openfile(file_name))

  module_imports = get_nodes_by_instance_type(nodes, _ast.Import)
  specific_imports = get_nodes_by_instance_type(nodes, _ast.ImportFrom)

  assignment_objs = get_nodes_by_instance_type(nodes, _ast.Assign)
  call_objects = get_nodes_by_instance_type(nodes, _ast.Call)

  argparse_assignments = get_nodes_by_containing_attr(assignment_objs, 'ArgumentParser')
  add_arg_assignments  = get_nodes_by_containing_attr(call_objects, 'add_argument')
  parse_args_assignment = get_nodes_by_containing_attr(call_objects, 'parse_args')

  ast_argparse_source = chain(
    module_imports,
    specific_imports,
    argparse_assignments,
    add_arg_assignments
    # parse_args_assignment
  )
  return ast_argparse_source 
Example #10
Source File: visitors.py    From pymtl with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def visit_For( self, node ):
    self.generic_visit( node )

    if not ( isinstance( node.iter,      _ast.Call ) and
             isinstance( node.iter.func, _ast.Name ) and
             node.iter.func.id in ['range', 'xrange'] ):
      raise VerilogTranslationError(
        'For loops are only translatable when using range or xrange!\n'
        'Please use "for i in range(...)/xrange(...)".',
        node.lineno
      )

    call = node.iter

    if   len( call.args ) == 1:
      start = _ast.Num( n=0 )
      stop  = call.args[0]
      step  = _ast.Num( n=1 )
    elif len( call.args ) == 2:
      start = call.args[0]
      stop  = call.args[1]
      step  = _ast.Num( n=1 ) # TODO: should be an expression
    elif len( call.args ) == 3:
      start = call.args[0]
      stop  = call.args[1]
      step  = call.args[2]
    else:
      raise VerilogTranslationError(
        'An invalid number of arguments provided to (x)range function!\n',
        node.lineno
      )

    # Must know if the step is negative or positive in order to set the
    # correct bound check. This is because of Python's range behavior.
    try:
      if   hasattr( step, '_object' ): step_val = step._object
      elif hasattr( step, 'n'       ): step_val = step.n
      assert step_val != 0
    except (UnboundLocalError,AssertionError):
      raise VerilogTranslationError(
        'An error occurred when translating a "for loop"!\n'
        'The "step" parameter to range must be a constant integer value != 0!',
        node.lineno
      )

    node.iter       = _ast.Slice( lower=start, upper=stop, step=step )
    node.iter.lt_gt = '<' if step_val > 0 else '>'

    return node

#-------------------------------------------------------------------------
# ConstantToSlice
#-------------------------------------------------------------------------