當前位置: 首頁>>代碼示例>>Python>>正文


Python ast.UnaryOp方法代碼示例

本文整理匯總了Python中ast.UnaryOp方法的典型用法代碼示例。如果您正苦於以下問題:Python ast.UnaryOp方法的具體用法?Python ast.UnaryOp怎麽用?Python ast.UnaryOp使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在ast的用法示例。


在下文中一共展示了ast.UnaryOp方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: check_not

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def check_not(self, target, pattern):
        'Check NOT pattern node that could be in another form'
        if self.is_wildcard(pattern.operand):
            wkey = pattern.operand.id
            if isinstance(target, ast.Num):
                if wkey not in self.wildcards:
                    mod = 2**self.nbits
                    self.wildcards[wkey] = ast.Num((~target.n) % mod)
                    return True
                else:
                    wilds2 = self.wildcards[pattern.operand.id]
                    num = ast.Num((~target.n) % 2**self.nbits)
                    return asttools.Comparator().visit(wilds2, num)
            else:
                if wkey not in self.wildcards:
                    self.wildcards[wkey] = ast.UnaryOp(ast.Invert(),
                                                       target)
                    return True
            return self.check_eq_z3(target, pattern)
        else:
            subpattern = pattern.operand
            newtarget = ast.UnaryOp(ast.Invert(), target)
            return self.check_eq_z3(newtarget, subpattern) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:25,代碼來源:pattern_matcher.py

示例2: __init__

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def __init__(self, patt_ast, target_ast, rep_ast, nbits=0):
        'Pattern ast should have as root: BinOp, BoolOp, UnaryOp or Call'
        if isinstance(patt_ast, ast.Module):
            self.patt_ast = patt_ast.body[0].value
        elif isinstance(patt_ast, ast.Expression):
            self.patt_ast = patt_ast.body
        else:
            self.patt_ast = patt_ast
        if isinstance(rep_ast, ast.Module):
            self.rep_ast = deepcopy(rep_ast.body[0].value)
        elif isinstance(rep_ast, ast.Expression):
            self.rep_ast = deepcopy(rep_ast.body)
        else:
            self.rep_ast = deepcopy(rep_ast)

        if not nbits:
            getsize = asttools.GetSize()
            getsize.visit(target_ast)
            if getsize.result:
                self.nbits = getsize.result
            # default bitsize is 8
            else:
                self.nbits = 8
        else:
            self.nbits = nbits 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:27,代碼來源:pattern_matcher.py

示例3: not_expression_ast_to_ir2

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def not_expression_ast_to_ir2(ast_node: ast.UnaryOp,
                              compilation_context: CompilationContext,
                              in_match_pattern: bool,
                              check_var_reference: Callable[[ast.Name], None],
                              match_lambda_argument_names: Set[str],
                              current_stmt_line: int):
    assert isinstance(ast_node.op, ast.Not)

    if in_match_pattern:
        raise CompilationError(compilation_context, ast_node,
                               'The "not" operator is not allowed in match patterns')

    expr = expression_ast_to_ir2(ast_node.operand,
                                 compilation_context,
                                 in_match_pattern,
                                 check_var_reference,
                                 match_lambda_argument_names,
                                 current_stmt_line)

    if expr.expr_type != ir2.BoolType():
        raise CompilationError(compilation_context, ast_node.operand,
                               'The "not" operator is only supported for booleans, but this value has type %s.' % str(expr.expr_type))

    return ir2.NotExpr(expr=expr) 
開發者ID:google,項目名稱:tmppy,代碼行數:26,代碼來源:_ast_to_ir2.py

示例4: unary_minus_expression_ast_to_ir2

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def unary_minus_expression_ast_to_ir2(ast_node: ast.UnaryOp,
                                      compilation_context: CompilationContext,
                                      in_match_pattern: bool,
                                      check_var_reference: Callable[[ast.Name], None],
                                      match_lambda_argument_names: Set[str],
                                      current_stmt_line: int):
    assert isinstance(ast_node.op, ast.USub)

    if in_match_pattern:
        raise CompilationError(compilation_context, ast_node,
                               'The "-" operator is not allowed in match patterns')

    expr = expression_ast_to_ir2(ast_node.operand,
                                 compilation_context,
                                 in_match_pattern,
                                 check_var_reference,
                                 match_lambda_argument_names,
                                 current_stmt_line)

    if expr.expr_type != ir2.IntType():
        raise CompilationError(compilation_context, ast_node.operand,
                               'The "-" operator is only supported for ints, but this value has type %s.' % str(expr.expr_type))

    return ir2.IntUnaryMinusExpr(expr=expr) 
開發者ID:google,項目名稱:tmppy,代碼行數:26,代碼來源:_ast_to_ir2.py

示例5: eval_expr

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def eval_expr(expr):

    """ Eval and expression inside a #define using a suppart of python grammar """

    def _eval(node):
        if isinstance(node, ast.Num):
            return node.n
        elif isinstance(node, ast.BinOp):
            return OPERATORS[type(node.op)](_eval(node.left), _eval(node.right))
        elif isinstance(node, ast.UnaryOp):
            return OPERATORS[type(node.op)](_eval(node.operand))
        elif isinstance(node, ast.BoolOp):
            values = [_eval(x) for x in node.values]
            return OPERATORS[type(node.op)](**values)
        else:
            raise TypeError(node)

    return _eval(ast.parse(expr, mode='eval').body) 
開發者ID:ynsta,項目名稱:steamcontroller,代碼行數:20,代碼來源:cheader.py

示例6: p_if_elif_else

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def p_if_elif_else(t):
    '''elif : ELSE IF expression ELSE suite
            | ELSEAND IF expression ELSE suite'''
    # NOTE
    # 아니면 만약, 아니라면 만약 / 아니면서 만약
    # ELSE랑 충분히 헷갈릴 수 있으므로 일단 모두 처리가능하게
    not_ast = ast.Not()
    not_ast.lineno = t.lineno(2)
    nonassoc.col_offset = -1 # XXX

    cond = ast.UnaryOp(not_ast, t[3])
    cond.lineno = t.lineno(2)
    cond.col_offset = -1 # XXX

    elif_block = ast.If(cond, t[5], [])
    elif_block.lineno = t.lineno(4)
    elif_block.col_offset = -1  # XXX
    t[0] = elif_block 
開發者ID:yaksok,項目名稱:yaksok,代碼行數:20,代碼來源:yacc.py

示例7: evaluate_node

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def evaluate_node(self, node):
        if isinstance(node, ast.BinOp):
            return self.operators[type(node.op)](self.evaluate_node(node.left),
                                                 self.evaluate_node(node.right))
        elif isinstance(node, ast.UnaryOp):
            return self.operators[type(node.op)](self.evaluate_node(node.operand))
        elif isinstance(node, ast.Compare):
            to_string = isinstance(node.comparators[0], ast.Str)

            return self.operators[type(node.ops[0])](self.evaluate_attribute_node(node.left, to_string),
                                                     self.evaluate_node(node.comparators[0]))
        elif isinstance(node, ast.BoolOp):
            func = all if isinstance(node.op, ast.And) else any
            return func(self.evaluate_node(value) for value in node.values)
        elif isinstance(node, ast.Str):
            return node.s
        elif isinstance(node, ast.Attribute):
            return self.evaluate_attribute_node(node)
        elif isinstance(node, ast.Num):
            return node.n
        else:
            logger.error("Error during parsing") 
開發者ID:jopohl,項目名稱:urh,代碼行數:24,代碼來源:SimulatorExpressionParser.py

示例8: validate_formula_node

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def validate_formula_node(self, node):
        if isinstance(node, ast.Num):
            return
        elif isinstance(node, ast.BinOp):
            if type(node.op) not in self.op_formula:
                self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)

            self.validate_formula_node(node.left)
            self.validate_formula_node(node.right)
        elif isinstance(node, ast.UnaryOp):
            if type(node.op) not in self.op_formula:
                self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)

            self.validate_formula_node(node.operand)
        elif isinstance(node, ast.Attribute):
            return self.validate_attribute_node(node)
        else:
            self.raise_syntax_error("", node.lineno, node.col_offset) 
開發者ID:jopohl,項目名稱:urh,代碼行數:20,代碼來源:SimulatorExpressionParser.py

示例9: validate_condition_node

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def validate_condition_node(self, node):
        if isinstance(node, ast.UnaryOp):
            if type(node.op) not in self.op_cond:
                self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)

            self.validate_condition_node(node.operand)
        elif isinstance(node, ast.Compare):
            if not (len(node.ops) == 1 and len(node.comparators) == 1):
                self.raise_syntax_error("", node.lineno, node.col_offset)

            if type(node.ops[0]) not in self.op_cond:
                self.raise_syntax_error("unknown operator", node.lineno, node.col_offset)

            self.validate_compare_nodes(node.left, node.comparators[0])
        elif isinstance(node, ast.BoolOp):
            for node in node.values:
                self.validate_condition_node(node)
        else:
            self.raise_syntax_error("", node.lineno, node.col_offset) 
開發者ID:jopohl,項目名稱:urh,代碼行數:21,代碼來源:SimulatorExpressionParser.py

示例10: _evaluate

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def _evaluate(self, expr):
        if isinstance(expr, ast.Expr):
            return self._evaluate(expr.value)
        elif isinstance(expr, ast.BoolOp):
            if isinstance(expr.op, ast.Or):
                evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values]
                return ' or '.join(evaluated)
            elif isinstance(expr.op, ast.And):
                evaluated = ['({})'.format(self._evaluate(v)) for v in expr.values]
                return ' and '.join(evaluated)
        elif isinstance(expr, ast.UnaryOp):
            if isinstance(expr.op, ast.Not):
                return 'not {}'.format(self._evaluate(expr.operand))
        elif isinstance(expr, ast.Num):
            return '"{}" in {}'.format(str(expr.n), self.tags)
        elif isinstance(expr, ast.Str):
            return '"{}" in {}'.format(expr.s, self.tags)
        elif isinstance(expr, ast.Name):
            return '"{}" in {}'.format(expr.id, self.tags)
        else:
            msg = ('unknown expression {}, the only valid operators for tag expressions '
                   'are: \'and\', \'or\' & \'not\''.format(type(expr)))
            raise InvalidTagExpression(msg) 
開發者ID:golemhq,項目名稱:golem,代碼行數:25,代碼來源:tags_manager.py

示例11: factor_rewrite

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def factor_rewrite(mark: Tokenizer, factor, power):
    return power if power else ast.UnaryOp(
        **(loc @ mark),
        op={
            '~': ast.Invert,
            '+': ast.UAdd,
            '-': ast.USub
        }[mark.value](),
        operand=factor,
    ) 
開發者ID:Xython,項目名稱:YAPyPy,代碼行數:12,代碼來源:helper.py

示例12: _safe_eval_node

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def _safe_eval_node(node):
    if isinstance(node, ast.Num):  # <number>
        return node.n
    elif isinstance(node, ast.BinOp):  # <left> <operator> <right>
        return operators[type(node.op)](
            _safe_eval_node(node.left), _safe_eval_node(node.right))
    elif isinstance(node, ast.UnaryOp):  # <operator> <operand> e.g., -1
        return operators[type(node.op)](_safe_eval_node(node.operand))
    else:
        raise TypeError(node)
# End of snippet derived from http://stackoverflow.com/a/9558001/974555 
開發者ID:atmtools,項目名稱:typhon,代碼行數:13,代碼來源:common.py

示例13: test_withUnaryOp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def test_withUnaryOp(self):
        'Test with UnaryOp involved'
        tests = [("5 + (-(6 + 2)) + 3",
                  ast.BoolOp(ast.Add(),
                             [ast.Num(5),
                              ast.UnaryOp(ast.USub(), ast.BinOp(ast.Num(6),
                                                                ast.Add(),
                                                                ast.Num(2))),
                              ast.Num(3)]))]
        for teststring, ref_ast in tests:
            test_ast = ast.parse(teststring, mode="eval").body
            test_ast = Flattening(ast.Add).visit(test_ast)
            self.assertTrue(Comparator().visit(test_ast, ref_ast)) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:15,代碼來源:test_flattening.py

示例14: check_pattern

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def check_pattern(self, target, pattern):
        'Try to match pattern written in different ways'

        if asttools.CheckConstExpr().visit(pattern):
            if isinstance(target, ast.Num):
                # if pattern is only a constant, evaluate and compare
                # to target
                pattcopy = deepcopy(pattern)
                eval_pat = asttools.ConstFolding(pattcopy,
                                                 self.nbits).visit(pattcopy)
                return self.visit(target, eval_pat)

        if isinstance(target, ast.Num):
            # check that wildcards in pattern have not been affected
            return self.get_model(target, pattern)

        # deal with NOT that could have been evaluated before
        notnode = (isinstance(pattern, ast.UnaryOp) and
                   isinstance(pattern.op, ast.Invert))
        if notnode:
            return self.check_not(target, pattern)

        # deal with (-1)*B that could have been evaluated
        negnode = (isinstance(pattern, ast.BinOp)
                   and isinstance(pattern.op, ast.Mult)
                   and isinstance(pattern.left, ast.Num)
                   and pattern.left.n == -1)
        if negnode:
            return self.check_neg(target, pattern)

        # deal with 2*B
        multnode = (isinstance(pattern, ast.BinOp) and
                    isinstance(pattern.op, ast.Mult))
        if multnode:
            return self.check_twomult(target, pattern)

        # return self.general_check(target, pattern)
        return False 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:40,代碼來源:pattern_matcher.py

示例15: visit_UnaryOp

# 需要導入模塊: import ast [as 別名]
# 或者: from ast import UnaryOp [as 別名]
def visit_UnaryOp(self, target, pattern):
        'Match type of UnaryOp and operands'
        if type(target.op) != type(pattern.op):
            return False
        return self.visit(target.operand, pattern.operand) 
開發者ID:quarkslab,項目名稱:sspam,代碼行數:7,代碼來源:pattern_matcher.py


注:本文中的ast.UnaryOp方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。