我们从Python开源项目中,提取了以下23个代码示例,用于说明如何使用ast.Mult()。
def num_negate(op): top = type(op) neg = not op.num_negated if hasattr(op, "num_negated") else True if top == ast.Add: newOp = ast.Sub() elif top == ast.Sub: newOp = ast.Add() elif top in [ast.Mult, ast.Div, ast.Mod, ast.Pow, ast.LShift, ast.RShift, ast.BitOr, ast.BitXor, ast.BitAnd, ast.FloorDiv]: return None # can't negate this elif top in [ast.Num, ast.Name]: # this is a normal value, so put a - in front of it newOp = ast.UnaryOp(ast.USub(addedNeg=True), op) else: log("astTools\tnum_negate\tUnusual type: " + str(top), "bug") transferMetaData(op, newOp) newOp.num_negated = neg return newOp
def eval_numeric_constexpr(node: ast.AST) -> int: if isinstance(node, ast.Num): return node.n if isinstance(node, ast.UnaryOp): if isinstance(node.op, ast.UAdd): return +eval_numeric_constexpr(node.operand) elif isinstance(node.op, ast.USub): return -eval_numeric_constexpr(node.operand) else: return None if isinstance(node, ast.BinOp): if isinstance(node.op, ast.Add): return eval_numeric_constexpr(node.left) + eval_numeric_constexpr(node.right) if isinstance(node.op, ast.Sub): return eval_numeric_constexpr(node.left) - eval_numeric_constexpr(node.right) if isinstance(node.op, ast.Mult): return eval_numeric_constexpr(node.left) * eval_numeric_constexpr(node.right) if isinstance(node.op, ast.Div): return eval_numeric_constexpr(node.left) / eval_numeric_constexpr(node.right) return None
def binop_str(op: ast.AST) -> str: if isinstance(op, ast.Add): return '+' if isinstance(op, ast.Sub): return '-' if isinstance(op, ast.Mult): return '*' if isinstance(op, ast.Div): return '/ ' if isinstance(op, ast.Mod): return '%' if isinstance(op, ast.LShift): return '<<' if isinstance(op, ast.RShift): return '>>' if isinstance(op, ast.BitOr): return '|' if isinstance(op, ast.BitXor): return '^' if isinstance(op, ast.BitAnd): return '&' if isinstance(op, ast.MatMult): return '@' error(loc(op), "Invalid binary operator encountered: {0}:{1}. Check supported intrinsics.".format(op.lineno, op.col_offset)) return 'INVALID_BINOP'
def eval_expr(expr): import ast import operator as op op = { ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor, ast.USub: op.neg, } def eval_(node): if isinstance(node, ast.Num): return fractions.Fraction(node.n) elif isinstance(node, ast.BinOp): return op[type(node.op)](eval_(node.left), eval_(node.right)) elif isinstance(node, ast.UnaryOp): return op[type(node.op)](eval_(node.operand)) raise TypeError(node) return eval_(ast.parse(str(expr), mode='eval').body)
def runTest(self): """Makes a simple test of the output""" body = ast.parse(self.candidate_code, self.file_name, 'exec') code = compile(self.candidate_code, self.file_name, 'exec') mult_instructions = [ node for node in ast.walk(body) if isinstance(node, ast.Mult) ] self.assertGreater(len(mult_instructions), 0, "It should have at least one duplication" ) exec(code) self.assertMultiLineEqual('ka'*10+'\n', self.__mockstdout.getvalue(), "Should have printed ka 10 times")
def parse_unit(item): if isinstance(item, ast.Name): if item.id not in valid_units: raise InvalidTypeException("Invalid base unit", item) return {item.id: 1} elif isinstance(item, ast.Num) and item.n == 1: return {} elif not isinstance(item, ast.BinOp): raise InvalidTypeException("Invalid unit expression", item) elif isinstance(item.op, ast.Mult): left, right = parse_unit(item.left), parse_unit(item.right) return combine_units(left, right) elif isinstance(item.op, ast.Div): left, right = parse_unit(item.left), parse_unit(item.right) return combine_units(left, right, div=True) elif isinstance(item.op, ast.Pow): if not isinstance(item.left, ast.Name): raise InvalidTypeException("Can only raise a base type to an exponent", item) if not isinstance(item.right, ast.Num) or not isinstance(item.right.n, int) or item.right.n <= 0: raise InvalidTypeException("Exponent must be positive integer", item) return {item.left.id: item.right.n} else: raise InvalidTypeException("Invalid unit expression", item) # Parses an expression representing a type. Annotation refers to whether # the type is to be located in memory or storage
def aug_assign(self): target = self.get_target(self.stmt.target) sub = Expr.parse_value_expr(self.stmt.value, self.context) if not isinstance(self.stmt.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod)): raise Exception("Unsupported operator for augassign") if not isinstance(target.typ, BaseType): raise TypeMismatchException("Can only use aug-assign operators with simple types!", self.stmt.target) if target.location == 'storage': o = Expr.parse_value_expr(ast.BinOp(left=LLLnode.from_list(['sload', '_stloc'], typ=target.typ, pos=target.pos), right=sub, op=self.stmt.op, lineno=self.stmt.lineno, col_offset=self.stmt.col_offset), self.context) return LLLnode.from_list(['with', '_stloc', target, ['sstore', '_stloc', base_type_conversion(o, o.typ, target.typ)]], typ=None, pos=getpos(self.stmt)) elif target.location == 'memory': o = Expr.parse_value_expr(ast.BinOp(left=LLLnode.from_list(['mload', '_mloc'], typ=target.typ, pos=target.pos), right=sub, op=self.stmt.op, lineno=self.stmt.lineno, col_offset=self.stmt.col_offset), self.context) return LLLnode.from_list(['with', '_mloc', target, ['mstore', '_mloc', base_type_conversion(o, o.typ, target.typ)]], typ=None, pos=getpos(self.stmt))
def _is_numeric_mult(self, node: ast.BinOp) -> bool: if isinstance(node.op, ast.Mult): if isinstance(node.left , (ast.Name, ast.Num)) \ and isinstance(node.right, ast.Num): return True if isinstance(node.right, (ast.Name, ast.Num)) \ and isinstance(node.left , ast.Num): return True return False
def visit_BinOp(self, node: ast.BinOp): node = self.generic_visit(node) if self._is_numeric_pow(node): left, right = node.left, node.right degree = ( right.n if isinstance(right, ast.Num) else -right.operand.n if isinstance(right.op, ast.USub) else right.operand.n ) degree = int(degree) if abs(degree) == 0: node = ast.copy_location(ast.Num(n = 1), node) elif abs(degree) == 1: node = node.left elif 2 <= abs(degree) <= self.MAX_DEGREE: for _ in range(1, abs(degree)): new_node = ast.BinOp\ ( left = left , op = ast.Mult() , right = copy(node.left) ) left = new_node = ast.copy_location(new_node, node) node = new_node else: return node if degree < 0: new_node = ast.BinOp\ ( left = ast.Num(n = 1) , op = ast.Div() , right = node ) node = ast.copy_location(new_node, node) return node
def doBinaryOp(op, l, r): """Perform the given AST binary operation on the values""" top = type(op) if top == ast.Add: return l + r elif top == ast.Sub: return l - r elif top == ast.Mult: return l * r elif top == ast.Div: # Don't bother if this will be a really long float- it won't work properly! # Also, in Python 3 this is floating division, so perform it accordingly. val = 1.0 * l / r if (val * 1e10 % 1.0) != 0: raise Exception("Repeating Float") return val elif top == ast.Mod: return l % r elif top == ast.Pow: return l ** r elif top == ast.LShift: return l << r elif top == ast.RShift: return l >> r elif top == ast.BitOr: return l | r elif top == ast.BitXor: return l ^ r elif top == ast.BitAnd: return l & r elif top == ast.FloorDiv: return l // r
def get_binary_op_str(bin_op_node): """Returns the string representation of the binary operator node (e.g. +, -, etc.). For some reason astor doesn't implement this??? """ if isinstance(bin_op_node, ast.Add): return "+" elif isinstance(bin_op_node, ast.Sub): return "-" elif isinstance(bin_op_node, ast.Mult): return "*" elif isinstance(bin_op_node, ast.Div): return "/" elif isinstance(bin_op_node, ast.Mod): return "%" elif isinstance(bin_op_node, ast.Pow): return "**" elif isinstance(bin_op_node, ast.LShift): return "<<" elif isinstance(bin_op_node, ast.RShift): return ">>" else: raise ValueError("No string defined for binary operator node %s" % \ bin_op_node.__class__.__name__)
def get_op_string(op_class): return { ast.Add: '+', ast.Sub: '-', ast.Div: '/', ast.Mult: '*' }[op_class.__class__] # For expr code
def binary_operation_type(left_type, op, right_type, lineno, solver): """Infer the type of a binary operation result""" if isinstance(op, ast.Add): inference_func = _infer_add elif isinstance(op, ast.Mult): inference_func = _infer_mult elif isinstance(op, ast.Div): inference_func = _infer_div elif isinstance(op, (ast.BitOr, ast.BitXor, ast.BitAnd)): return _infer_bitwise(left_type, right_type, op, lineno, solver) else: return _infer_arithmetic(left_type, right_type, op, lineno, solver) return inference_func(left_type, right_type, lineno, solver)
def mutate_Div_to_Mult(self, node): if self.should_mutate(node): return ast.Mult() raise MutationResign()
def mutate_FloorDiv_to_Mult(self, node): if self.should_mutate(node): return ast.Mult() raise MutationResign()
def mutate_Mod(self, node): if self.should_mutate(node): return ast.Mult() raise MutationResign()
def mutate_Pow(self, node): if self.should_mutate(node): return ast.Mult() raise MutationResign()
def pythonast(self, args, tonative=False): return reduce(lambda x, y: ast.BinOp(x, ast.Mult(), y), args)
def _update(self): """update tkk """ # we don't need to update the base TKK value when it is still valid now = math.floor(int(time.time() * 1000) / 3600000.0) if self.tkk and int(self.tkk.split('.')[0]) == now: return r = self.session.get(self.host) # this will be the same as python code after stripping out a reserved word 'var' code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '') # unescape special ascii characters such like a \x3d(=) if PY3: # pragma: no cover code = code.encode().decode('unicode-escape') else: # pragma: no cover code = code.decode('string_escape') if code: tree = ast.parse(code) visit_return = False operator = '+' n, keys = 0, dict(a=0, b=0) for node in ast.walk(tree): if isinstance(node, ast.Assign): name = node.targets[0].id if name in keys: if isinstance(node.value, ast.Num): keys[name] = node.value.n # the value can sometimes be negative elif isinstance(node.value, ast.UnaryOp) and \ isinstance(node.value.op, ast.USub): # pragma: nocover keys[name] = -node.value.operand.n elif isinstance(node, ast.Return): # parameters should be set after this point visit_return = True elif visit_return and isinstance(node, ast.Num): n = node.n elif visit_return and n > 0: # the default operator is '+' but implement some more for # all possible scenarios if isinstance(node, ast.Add): # pragma: nocover pass elif isinstance(node, ast.Sub): # pragma: nocover operator = '-' elif isinstance(node, ast.Mult): # pragma: nocover operator = '*' elif isinstance(node, ast.Pow): # pragma: nocover operator = '**' elif isinstance(node, ast.BitXor): # pragma: nocover operator = '^' # a safety way to avoid Exceptions clause = compile('{1}{0}{2}'.format( operator, keys['a'], keys['b']), '', 'eval') value = eval(clause, dict(__builtin__={})) result = '{}.{}'.format(n, value) self.tkk = result
def check_binop(self, op, left, right): if isinstance(left, COMPLEX_TYPES) and isinstance(right, COMPLEX_TYPES): if isinstance(op, DIVIDE_BINOPS) and not right: # x/0: ZeroDivisionError return False if isinstance(op, ast.Pow): if isinstance(left, complex) or isinstance(right, complex): return False return check_pow(self.config, left, right) if isinstance(op, (ast.LShift, ast.RShift)) and right < 0: # 1 << -3 and 1 >> -3 raise a ValueError return False if isinstance(left, int) and isinstance(right, int): return True if isinstance(left, FLOAT_TYPES) and isinstance(right, FLOAT_TYPES): return isinstance(op, FLOAT_BINOPS) if isinstance(left, COMPLEX_TYPES) and isinstance(right, COMPLEX_TYPES): return isinstance(op, COMPLEX_BINOPS) if isinstance(op, ast.Mult): if isinstance(right, int): # bytes * int if isinstance(left, bytes): return (len(left) * right <= self.config.max_bytes_len) # str * int if isinstance(left, str): return (len(left) * right <= self.config.max_str_len) # tuple * int if isinstance(left, tuple): size = get_constant_size(left) return (size * right <= self.config.max_seq_len) if isinstance(left, int): # int * bytes if isinstance(right, bytes): return (left * len(right) <= self.config.max_bytes_len) # int * str if isinstance(right, str): return (left * len(right) <= self.config.max_str_len) # int * tuple if isinstance(right, tuple): size = get_constant_size(right) return (left * size <= self.config.max_seq_len) if isinstance(op, ast.Add): if isinstance(left, str) and isinstance(right, str): return ((len(left) + len(right)) <= self.config.max_str_len) if isinstance(left, bytes) and isinstance(right, bytes): return ((len(left) + len(right)) <= self.config.max_bytes_len) if isinstance(left, tuple) and isinstance(right, tuple): return ((len(left) + len(right)) <= self.config.max_seq_len) return False
def visit_BinOp(self, node): left_term = self.visit(node.left) right_term = self.visit(node.right) if self.__is_bool(left_term) and self.__is_bool(right_term): if isinstance(node.op, ast.BitAnd): return And(left_term, right_term) elif isinstance(node.op, ast.BitOr): return Or(left_term, right_term) elif isinstance(node.op, ast.BitXor): return Xor(left_term, right_term) else: raise Exception("Unsupported bool binary operation %s" % unparse(node)) if DATA_TYPE == "int": if isinstance(node.op, ast.Mod): return left_term % right_term elif isinstance(node.op, ast.Add): return left_term + right_term elif isinstance(node.op, ast.Sub): return left_term - right_term elif isinstance(node.op, ast.Mult): return left_term * right_term elif isinstance(node.op, ast.BitXor): # Special-case for bool circuit-examples: if is_is_int(left_term): left_term = left_term == IntVal(1) if is_is_int(right_term): right_term = right_term == IntVal(1) return left_term != right_term else: raise Exception("Unsupported integer binary operation %s" % unparse(node)) elif DATA_TYPE.startswith("bit_"): if isinstance(node.op, ast.BitAnd): return left_term & right_term elif isinstance(node.op, ast.BitOr): return left_term | right_term elif isinstance(node.op, ast.BitXor): return left_term ^ right_term else: raise Exception("Unsupported bitvector operation %s" % unparse(node)) else: raise Exception("Unsupported data type %s" % DATA_TYPE)
def _update(self): """update tkk """ # we don't need to update the base TKK value when it is still valid now = math.floor(int(time.time() * 1000) / 3600000.0) if self.tkk and int(self.tkk.split('.')[0]) == now: return r = self.session.get(self.host) # this will be the same as python code after stripping out a reserved word 'var' code = str(self.RE_TKK.search(r.text).group(1)).replace('var ', '') # unescape special ascii characters such like a \x3d(=) code = code.encode().decode('unicode-escape') if code: tree = ast.parse(code) visit_return = False operator = '+' n, keys = 0, dict(a=0, b=0) for node in ast.walk(tree): if isinstance(node, ast.Assign): name = node.targets[0].id if name in keys: if isinstance(node.value, ast.Num): keys[name] = node.value.n # the value can sometimes be negative elif isinstance(node.value, ast.UnaryOp) and \ isinstance(node.value.op, ast.USub): # pragma: nocover keys[name] = -node.value.operand.n elif isinstance(node, ast.Return): # parameters should be set after this point visit_return = True elif visit_return and isinstance(node, ast.Num): n = node.n elif visit_return and n > 0: # the default operator is '+' but implement some more for # all possible scenarios if isinstance(node, ast.Add): # pragma: nocover pass elif isinstance(node, ast.Sub): # pragma: nocover operator = '-' elif isinstance(node, ast.Mult): # pragma: nocover operator = '*' elif isinstance(node, ast.Pow): # pragma: nocover operator = '**' elif isinstance(node, ast.BitXor): # pragma: nocover operator = '^' # a safety way to avoid Exceptions clause = compile('{1}{0}{2}'.format( operator, keys['a'], keys['b']), '', 'eval') value = eval(clause, dict(__builtin__={})) result = '{}.{}'.format(n, value) self.tkk = result
def _aslimit(value, lc): if isinstance(value, string_types): module = ast.parse(value) if isinstance(module, ast.Module) and len(module.body) == 1 and isinstance(module.body[0], ast.Expr): def restrictedeval(expr): if isinstance(expr, ast.Num): return expr.n elif isinstance(expr, ast.Name) and expr.id == "inf": return femtocode.typesystem.inf elif isinstance(expr, ast.Name) and expr.id == "pi": return math.pi elif isinstance(expr, ast.UnaryOp) and isinstance(expr.op, ast.USub): return -restrictedeval(expr.operand) elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Add): return restrictedeval(expr.left) + restrictedeval(expr.right) elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Sub): return restrictedeval(expr.left) - restrictedeval(expr.right) elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Mult): return restrictedeval(expr.left) * restrictedeval(expr.right) elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Div): return restrictedeval(expr.left) / restrictedeval(expr.right) elif isinstance(expr, ast.BinOp) and isinstance(expr.op, ast.Pow): return restrictedeval(expr.left) ** restrictedeval(expr.right) elif isinstance(expr, ast.Call) and isinstance(expr.func, ast.Name) and expr.func.id == "almost" and len(expr.args) == 1 and len(expr.keywords) == 0 and expr.kwargs is None and expr.starargs is None: return femtocode.typesystem.almost(restrictedeval(expr.args[0])) else: raise DatasetDeclaration.Error(lc, "couldn't parse as a min/max/least/most limit: {0}".format(value)) return restrictedeval(module.body[0].value) elif isinstance(value, (int, long, float)): return value elif isinstance(value, femtocode.typesystem.almost) and isinstance(value.real, (int, long, float)): return value else: raise DatasetDeclaration.Error(lc, "unrecognized type for min/max/least/most limit: {0}".format(value))