当前位置: 首页>>代码示例>>Python>>正文


Python ast.copy_location方法代码示例

本文整理汇总了Python中ast.copy_location方法的典型用法代码示例。如果您正苦于以下问题:Python ast.copy_location方法的具体用法?Python ast.copy_location怎么用?Python ast.copy_location使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ast的用法示例。


在下文中一共展示了ast.copy_location方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: visit_BoolOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_BoolOp(self, node: ast.BoolOp) -> ast.AST:
        """Boolean operations, AND/OR."""
        self.generic_visit(node)
        log_header = f"visit_BoolOp: {self.src_file}:"

        node_span = NodeSpan(node)
        idx = LocIndex(
            ast_class="BoolOp",
            lineno=node_span.lineno,
            col_offset=node_span.col_offset,
            op_type=type(node.op),
            end_lineno=node_span.end_lineno,
            end_col_offset=node_span.end_col_offset,
        )
        self.locs.add(idx)

        if idx == self.target_idx and self.mutation and not self.readonly:
            LOGGER.debug("%s mutating idx: %s with %s", log_header, self.target_idx, self.mutation)
            return ast.copy_location(ast.BoolOp(op=self.mutation(), values=node.values), node)

        LOGGER.debug("%s (%s, %s): no mutations applied.", log_header, node.lineno, node.col_offset)
        return node 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:24,代码来源:transformers.py

示例2: visit_Expr

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_Expr(self, node):
        newnode = ast.copy_location(ast.Expr(
                value = ast.Call(
                    func = ast.Attribute(
                        value = ast.Name(id='__swirlypy_recorder__',
                                    ctx=ast.Load()),
                                    attr="record",
                                    ctx=ast.Load()),
                                    args=[node.value],
                                    keywords=[],
                                    starargs=None,
                                    kwargs=None
                        )
                    ),
                node)
        ast.fix_missing_locations(newnode)
        return newnode 
开发者ID:alexander-bauer,项目名称:swirlypy,代码行数:19,代码来源:Recording.py

示例3: visit_BinOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_BinOp(self, node: ast.BinOp) -> Union[ast.BinOp, ast.Num]:
        """Evaluate binary operation and return ast.Num if operands are bound.

        Args:
            node: Binary operation to evaluate.

        Returns:
            Evaluated value.
        """
        node.left = self.visit(node.left)
        node.right = self.visit(node.right)
        if isinstance(node.left, ast.Num) and isinstance(node.right, ast.Num):
            val = ast.Num(n=self._match_ops(node.op, self._binary_ops,
                                            node.left.n, node.right.n))
            return ast.copy_location(val, node)
        return node 
开发者ID:Qiskit,项目名称:qiskit-terra,代码行数:18,代码来源:parser.py

示例4: visit_Call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_Call(self, node: ast.Call) -> Union[ast.Call, ast.Num]:
        """Evaluate function and return ast.Num if all arguments are bound.

        Args:
            node: Function to evaluate.

        Returns:
            Evaluated value.

        Raises:
            PulseError: When unsupported or unsafe function is specified.
        """
        if not isinstance(node.func, ast.Name):
            raise PulseError('Unsafe expression is detected.')
        node.args = [self.visit(arg) for arg in node.args]
        if all(isinstance(arg, ast.Num) for arg in node.args):
            if node.func.id not in self._math_ops.keys():
                raise PulseError('Function %s is not supported.' % node.func.id)
            _args = [arg.n for arg in node.args]
            _val = self._math_ops[node.func.id](*_args)
            if not _val.imag:
                _val = _val.real
            val = ast.Num(n=_val)
            return ast.copy_location(val, node)
        return node 
开发者ID:Qiskit,项目名称:qiskit-terra,代码行数:27,代码来源:parser.py

示例5: visit_Name

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_Name( self, node ):
    new_node = LocalVar( id=node.id )
    new_node._name = node.id
    return ast.copy_location( new_node, node )


#-------------------------------------------------------------------------
# ReorderAST
#-------------------------------------------------------------------------
# Reorders an AST branch beginning with the indicated node.  Intended
# for inverting the order of Name/Attribute chains so that the Name
# node comes first, followed by chains of Attribute/Subscript nodes.
#
# This visitor will also insert Self nodes to represent references to the
# self variable, and remove Index nodes which seem to serve no useful
# purpose. 
开发者ID:cornell-brg,项目名称:pymtl,代码行数:18,代码来源:ast_transformer.py

示例6: visit_Attribute

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_Attribute( self, node ):

    # Visit children
    self.generic_visit( node )

    # If the direct child of this attribute was a portbundle then the node
    # will be removed by the visitor. We must update our name to include
    # portbundle name for proper mangling.
    if self.portbundle:
      new_node = _ast.Name( id  = '{}_{}'.format(self.portbundle, node.attr ),
                            ctx = node.ctx )
      new_node._object = node._object
      node = new_node

    # Attribute is a PortBundle, remove the node, set the submodule name
    if isinstance( node._object, PortBundle ):
      self.portbundle = node.attr
      return None

    # Otherwise, clear the submodule name, return node unmodified
    self.portbundle = None
    return ast.copy_location( node, node ) 
开发者ID:cornell-brg,项目名称:pymtl,代码行数:24,代码来源:visitors.py

示例7: visit_Call

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_Call(self, node):
        if node.starargs:
            star = gast.Starred(self._visit(node.starargs), gast.Load())
            gast.copy_location(star, node)
            star.end_lineno = star.end_col_offset = None
            starred = [star]
        else:
            starred = []

        if node.kwargs:
            kwargs = [gast.keyword(None, self._visit(node.kwargs))]
        else:
            kwargs = []

        new_node = gast.Call(
            self._visit(node.func),
            self._visit(node.args) + starred,
            self._visit(node.keywords) + kwargs,
        )
        gast.copy_location(new_node, node)
        new_node.end_lineno = new_node.end_col_offset = None
        return new_node 
开发者ID:serge-sans-paille,项目名称:gast,代码行数:24,代码来源:ast2.py

示例8: visit_BinOp

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_BinOp(self, node: ast.BinOp) -> ast.AST:
        """BinOp nodes are bit-shifts and general operators like add, divide, etc."""
        self.generic_visit(node)
        log_header = f"visit_BinOp: {self.src_file}:"

        # default case for this node, can be BinOpBC or BinOpBS
        ast_class = "BinOp"
        op_type = type(node.op)

        # binop_bit_cmp_types: Set[type] = {ast.BitAnd, ast.BitOr, ast.BitXor}
        if op_type in {ast.BitAnd, ast.BitOr, ast.BitXor}:
            ast_class = "BinOpBC"

        # binop_bit_shift_types: Set[type] = {ast.LShift, ast.RShift}
        if op_type in {ast.LShift, ast.RShift}:
            ast_class = "BinOpBS"

        node_span = NodeSpan(node)
        idx = LocIndex(
            ast_class=ast_class,
            lineno=node_span.lineno,
            col_offset=node_span.col_offset,
            op_type=op_type,
            end_lineno=node_span.end_lineno,
            end_col_offset=node_span.end_col_offset,
        )

        self.locs.add(idx)

        if idx == self.target_idx and self.mutation and not self.readonly:
            LOGGER.debug("%s mutating idx: %s with %s", log_header, self.target_idx, self.mutation)
            return ast.copy_location(
                ast.BinOp(left=node.left, op=self.mutation(), right=node.right), node
            )

        LOGGER.debug("%s (%s, %s): no mutations applied.", log_header, node.lineno, node.col_offset)
        return node 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:39,代码来源:transformers.py

示例9: mixin_NameConstant

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def mixin_NameConstant(self, node: Union[ast.NameConstant, ast.Constant]) -> ast.AST:
        """Constants: ``True, False, None``.

        This method is called by using the Mixin classes for handling the difference of
        ast.NameConstant (Py 3.7) an ast.Constant (Py 3.8).
        """
        self.generic_visit(node)
        log_header = f"visit_NameConstant: {self.src_file}:"

        node_span = NodeSpan(node)
        idx = LocIndex(
            ast_class="NameConstant",
            lineno=node_span.lineno,
            col_offset=node_span.col_offset,
            op_type=node.value,
            end_lineno=node_span.end_lineno,
            end_col_offset=node_span.end_col_offset,
        )
        self.locs.add(idx)

        if idx == self.target_idx and not self.readonly:
            LOGGER.debug("%s mutating idx: %s with %s", log_header, self.target_idx, self.mutation)
            return ast.copy_location(self.constant_type(value=self.mutation), node)

        LOGGER.debug("%s (%s, %s): no mutations applied.", log_header, node.lineno, node.col_offset)
        return node 
开发者ID:EvanKepner,项目名称:mutatest,代码行数:28,代码来源:transformers.py

示例10: visit_Attribute

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_Attribute(self, node):
        self.generic_visit(node)

        reserved = ('next', 'posedge', 'negedge', 'max', 'min', 'val', 'signed',
                    'verilog_code', 'vhdl_code')
        if node.attr in reserved:
            return node

        # Don't handle subscripts for now.
        if not isinstance(node.value, ast.Name):
            return node

        # Don't handle locals
        if node.value.id not in self.data.symdict:
            return node

        obj = self.data.symdict[node.value.id]
        # Don't handle enums and functions, handle signals as long as it is a new attribute
        if isinstance(obj, (EnumType, FunctionType)):
            return node
        elif isinstance(obj, SignalType):
            if hasattr(SignalType, node.attr):
                return node

        attrobj = getattr(obj, node.attr)

        orig_name = node.value.id + '.' + node.attr
        if orig_name not in self.name_map:
            base_name = node.value.id + '_' + node.attr
            self.name_map[orig_name] = _suffixer(base_name, self.data.symdict)
        new_name = self.name_map[orig_name]
        self.data.symdict[new_name] = attrobj
        self.data.objlist.append(new_name)

        new_node = ast.Name(id=new_name, ctx=node.value.ctx)
        return ast.copy_location(new_node, node) 
开发者ID:myhdl,项目名称:myhdl,代码行数:38,代码来源:_resolverefs.py

示例11: filterstr_to_filterfunc

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def filterstr_to_filterfunc(filter_str: str, item_type: type):
    """Takes an --post-filter=... or --storyitem-filter=... filter
     specification and makes a filter_func Callable out of it."""

    # The filter_str is parsed, then all names occurring in its AST are replaced by loads to post.<name>. A
    # function Post->bool is returned which evaluates the filter with the post as 'post' in its namespace.

    class TransformFilterAst(ast.NodeTransformer):
        def visit_Name(self, node: ast.Name):
            # pylint:disable=no-self-use
            if not isinstance(node.ctx, ast.Load):
                raise InvalidArgumentException("Invalid filter: Modifying variables ({}) not allowed.".format(node.id))
            if node.id == "datetime":
                return node
            if not hasattr(item_type, node.id):
                raise InvalidArgumentException("Invalid filter: {} not a {} attribute.".format(node.id,
                                                                                               item_type.__name__))
            new_node = ast.Attribute(ast.copy_location(ast.Name('item', ast.Load()), node), node.id,
                                     ast.copy_location(ast.Load(), node))
            return ast.copy_location(new_node, node)

    input_filename = '<command line filter parameter>'
    compiled_filter = compile(TransformFilterAst().visit(ast.parse(filter_str, filename=input_filename, mode='eval')),
                              filename=input_filename, mode='eval')

    def filterfunc(item) -> bool:
        # pylint:disable=eval-used
        return bool(eval(compiled_filter, {'item': item, 'datetime': datetime.datetime}))

    return filterfunc 
开发者ID:instaloader,项目名称:instaloader,代码行数:32,代码来源:__main__.py

示例12: stateful_get_all_emojis

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def stateful_get_all_emojis(self, call):
        if not isinstance(call.func, ast.Attribute):
            return call
        if call.func.attr != 'get_all_emojis':
            return call

        new_expr = ast.Expr()
        ast.copy_location(new_expr, call)
        call.func.attr = 'emojis'
        new_expr.value = call.func
        return new_expr 
开发者ID:tylergibbs2,项目名称:async2rewrite,代码行数:13,代码来源:transformers.py

示例13: to_messageable

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def to_messageable(self, call):
        if not isinstance(call.func, ast.Attribute):
            return call
        if call.func.attr == 'say':
            call.func.value = ast.Name(id='ctx', ctx=ast.Load())
            call.func.attr = 'send'
            stats_counter['call_changes'] += 1
        elif call.func.attr == 'send_message':
            destination = find_arg(call, "destination", 0)

            for kw in call.keywords.copy():
                if kw.arg == "destination":
                    call.keywords.remove(kw)

            wrap_attr = ast.Attribute()
            wrap_attr.value = destination
            wrap_attr.attr = 'send'
            wrap_attr.ctx = ast.Load()

            newcall = ast.Call()
            newcall.func = wrap_attr
            newcall.args = call.args[1:]
            newcall.keywords = call.keywords

            newcall = ast.copy_location(newcall, call)
            stats_counter['call_changes'] += 1

            return newcall

        return call 
开发者ID:tylergibbs2,项目名称:async2rewrite,代码行数:32,代码来源:transformers.py

示例14: handleAnnotation

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def handleAnnotation(self, annotation, node):
        if isinstance(annotation, ast.Str):
            # Defer handling forward annotation.
            def handleForwardAnnotation():
                try:
                    tree = ast.parse(annotation.s)
                except SyntaxError:
                    self.report(
                        messages.ForwardAnnotationSyntaxError,
                        node,
                        annotation.s,
                    )
                    return

                body = tree.body
                if len(body) != 1 or not isinstance(body[0], ast.Expr):
                    self.report(
                        messages.ForwardAnnotationSyntaxError,
                        node,
                        annotation.s,
                    )
                    return

                parsed_annotation = tree.body[0].value
                for descendant in ast.walk(parsed_annotation):
                    ast.copy_location(descendant, annotation)

                self.handleNode(parsed_annotation, node)

            self.deferFunction(handleForwardAnnotation)
        else:
            self.handleNode(annotation, node) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:34,代码来源:checker.py

示例15: visit_Attribute

# 需要导入模块: import ast [as 别名]
# 或者: from ast import copy_location [as 别名]
def visit_Attribute(self, node):
        """Flatten one level of attribute access."""
        new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx)
        return ast.copy_location(new_node, node) 
开发者ID:jpush,项目名称:jbox,代码行数:6,代码来源:markers.py


注:本文中的ast.copy_location方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。