Python ast.Mult() Examples
The following are 30
code examples of ast.Mult().
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: helper.py From YAPyPy with MIT License | 6 votes |
def term_rewrite(head, tail): if tail: for op, each in tail: head = ast.BinOp( head, { '*': ast.Mult, '@': ast.MatMult, '%': ast.Mod, '//': ast.FloorDiv, '/': ast.Div }[op.value](), each, **loc @ op, ) return head
Example #2
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def check_neg(self, target, pattern): 'Check (-1)*... pattern that could be in another form' if self.is_wildcard(pattern.right): wkey = pattern.right.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.right.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.BinOp(ast.Num(-1), ast.Mult(), target) return True return self.check_eq_z3(target, pattern)
Example #3
Source File: pre_processing.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def visit_UnaryOp(self, node): 'Change -x to (-1)*x' self.generic_visit(node) if isinstance(node.op, ast.USub): ope = node.operand cond_mult = (isinstance(ope, ast.BinOp) and isinstance(ope.op, ast.Mult)) if cond_mult: if isinstance(ope.left, ast.Num): node = ast.BinOp(ast.Num(-ope.left.n), ast.Mult(), ope.right) elif isinstance(ope.right, ast.Num): node = ast.BinOp(ope.left, ast.Mult(), ast.Num(-ope.right.n)) else: node = ast.BinOp(ast.Num(-1), ast.Mult(), ope) else: node = ast.BinOp(ast.Num(-1), ast.Mult(), ope) return node
Example #4
Source File: test_flattening.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_noflattening(self): 'Tests where nothing should be flattened' corresp = [(["a + b", "b + a"], ast.BinOp(ast.Name('a', ast.Load()), ast.Add(), ast.Name('b', ast.Load()))), (["c*d", "d*c"], ast.BinOp(ast.Name('c', ast.Load()), ast.Mult(), ast.Name('d', ast.Load()))), (["a + c*d", "d*c + a"], ast.BinOp(ast.Name('a', ast.Load()), ast.Add(), ast.BinOp(ast.Name('c', ast.Load()), ast.Mult(), ast.Name('d', ast.Load()))))] for refstring, result in corresp: self.generic_flattening(refstring, result)
Example #5
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def visit_BoolOp(self, node): 'A custom BoolOp can be used in flattened AST' if type(node.op) not in (ast.Add, ast.Mult, ast.BitXor, ast.BitAnd, ast.BitOr): return self.generic_visit(node) # get constant parts of node: list_cste = [child for child in node.values if isinstance(child, ast.Num)] if len(list_cste) < 2: return self.generic_visit(node) rest_values = [n for n in node.values if n not in list_cste] fake_node = Unflattening().visit(ast.BoolOp(node.op, list_cste)) fake_node = ast.Expression(fake_node) ast.fix_missing_locations(fake_node) code = compile(fake_node, '<constant folding>', 'eval') obj_env = globals().copy() exec code in obj_env value = eval(code, obj_env) new_node = ast.Num(value) rest_values.append(new_node) return ast.BoolOp(node.op, rest_values)
Example #6
Source File: test_flattening.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_afterSubMult(self): 'Tests after SubToMult pre-processing' tests = [("1 + 2 - 3", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.BinOp(ast.Num(-1), ast.Mult(), ast.Num(3))])), ("1 + 2 - 3 + 4", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.BinOp(ast.Num(-1), ast.Mult(), ast.Num(3)), ast.Num(4)])), ("(1 + 2) - (3 + 4)", ast.BoolOp(ast.Add(), [ast.Num(1), ast.Num(2), ast.BinOp(ast.Num(-1), ast.Mult(), ast.BinOp(ast.Num(3), ast.Add(), ast.Num(4)))]))] for teststring, ref_ast in tests: test_ast = ast.parse(teststring, mode="eval").body test_ast = pre_processing.all_preprocessings(test_ast) test_ast = Flattening(ast.Add).visit(test_ast) self.assertTrue(Comparator().visit(test_ast, ref_ast))
Example #7
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
def visit_BinOp(self, node1, node2): 'Check type of operation and operands' if type(node1.op) != type(node2.op): return False # if operation is commutative, left and right operands are # interchangeable cond1 = (self.visit(node1.left, node2.left) and self.visit(node1.right, node2.right)) cond2 = (self.visit(node1.left, node2.right) and self.visit(node1.right, node2.left)) # non-commutative comparator if not self.commut: return cond1 if isinstance(node1.op, (ast.Add, ast.Mult, ast.BitAnd, ast.BitOr, ast.BitXor)): if cond1 or cond2: return True else: return False else: if cond1: return True return False
Example #8
Source File: helper.py From YAPyPy with MIT License | 6 votes |
def augassign_rewrite(it: Tokenizer): return { '+=': ast.Add, '-=': ast.Sub, '*=': ast.Mult, '/=': ast.Div, '//=': ast.FloorDiv, '@=': ast.MatMult, '%=': ast.Mod, '&=': ast.BitAnd, '|=': ast.BitOr, '^=': ast.BitXor, '<<=': ast.LShift, '>>=': ast.RShift, '**=': ast.Pow, }[it.value]
Example #9
Source File: _toVHDL.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def visit_AugAssign(self, node): # XXX apparently no signed context required for augmented assigns left, op, right = node.target, node.op, node.value isFunc = False pre, suf = "", "" if isinstance(op, (ast.Add, ast.Sub, ast.Mult, ast.Mod, ast.FloorDiv)): pre, suf = self.inferBinaryOpCast(node, left, right, op) elif isinstance(op, (ast.LShift, ast.RShift)): isFunc = True pre, suf = self.inferShiftOpCast(node, left, right, op) self.visit(left) self.write(" := ") self.write(pre) if isFunc: self.write("%s(" % opmap[type(op)]) self.visit(left) if isFunc: self.write(", ") else: self.write(" %s " % opmap[type(op)]) self.visit(right) if isFunc: self.write(")") self.write(suf) self.write(";")
Example #10
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_nodeclasses(self): # IronPyhon performs argument typechecking l=ast.Str('A') o=ast.Mult() r=ast.Num('13') x=ast.BinOp(l,o,r,lineno=42) self.assertEqual(x.left, l) self.assertEqual(x.op, o) self.assertEqual(x.right, r) self.assertEqual(x.lineno, 42) # node raises exception when not given enough arguments self.assertRaises(TypeError, ast.BinOp, l, o) # can set attributes through kwargs too x = ast.BinOp(left=l, op=o, right=r, lineno=42) self.assertEqual(x.left, l) self.assertEqual(x.op, o) self.assertEqual(x.right, r) self.assertEqual(x.lineno, 42) # this used to fail because Sub._fields was None x = ast.Sub()
Example #11
Source File: test_transformers.py From mutatest with MIT License | 6 votes |
def test_MutateAST_visit_augassign(augassign_file, augassign_expected_locs): """Test mutation for AugAssign: +=, -=, /=, *=.""" tree = Genome(augassign_file).ast test_mutation = "AugAssign_Div" testing_tree = deepcopy(tree) mutated_tree = MutateAST(target_idx=augassign_expected_locs[0], mutation=test_mutation).visit( testing_tree ) mast = MutateAST(readonly=True) mast.visit(mutated_tree) assert len(mast.locs) == 4 for loc in mast.locs: # spot check on mutation from Add tp Div if loc.lineno == 1 and loc.col_offset == 4: assert loc.op_type == test_mutation # spot check on not-mutated location still being Mult if loc.lineno == 5 and loc.col_offset == 4: assert loc.op_type == "AugAssign_Mult"
Example #12
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 6 votes |
def test_nodeclasses(self): # IronPyhon performs argument typechecking l=ast.Str('A') o=ast.Mult() r=ast.Num('13') x=ast.BinOp(l,o,r,lineno=42) self.assertEqual(x.left, l) self.assertEqual(x.op, o) self.assertEqual(x.right, r) self.assertEqual(x.lineno, 42) # node raises exception when not given enough arguments self.assertRaises(TypeError, ast.BinOp, l, o) # can set attributes through kwargs too x = ast.BinOp(left=l, op=o, right=r, lineno=42) self.assertEqual(x.left, l) self.assertEqual(x.op, o) self.assertEqual(x.right, r) self.assertEqual(x.lineno, 42) # this used to fail because Sub._fields was None x = ast.Sub()
Example #13
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_term_star_1(p): '''term_star : STAR factor''' # 1 2 p[0] = [ast.Mult(rule=inspect.currentframe().f_code.co_name, **p[1][1]), p[2]]
Example #14
Source File: _recompute.py From icontract with MIT License | 5 votes |
def visit_BinOp(self, node: ast.BinOp) -> Any: """Recursively visit the left and right operand, respectively, and apply the operation on the results.""" # pylint: disable=too-many-branches left = self.visit(node=node.left) right = self.visit(node=node.right) if isinstance(node.op, ast.Add): result = left + right elif isinstance(node.op, ast.Sub): result = left - right elif isinstance(node.op, ast.Mult): result = left * right elif isinstance(node.op, ast.Div): result = left / right elif isinstance(node.op, ast.FloorDiv): result = left // right elif isinstance(node.op, ast.Mod): result = left % right elif isinstance(node.op, ast.Pow): result = left**right elif isinstance(node.op, ast.LShift): result = left << right elif isinstance(node.op, ast.RShift): result = left >> right elif isinstance(node.op, ast.BitOr): result = left | right elif isinstance(node.op, ast.BitXor): result = left ^ right elif isinstance(node.op, ast.BitAnd): result = left & right elif isinstance(node.op, ast.MatMult): result = left @ right else: raise NotImplementedError("Unhandled op of {}: {}".format(node, node.op)) self.recomputed_values[node] = result return result
Example #15
Source File: test_ast.py From ironpython3 with Apache License 2.0 | 5 votes |
def test_example_from_net(self): node = ast.Expression(ast.BinOp(ast.Str('xy'), ast.Mult(), ast.Num(3)))
Example #16
Source File: parser.py From vecpy with MIT License | 5 votes |
def binop(self, block, node, var=None): if var is None: var = self.add_variable(None) left = self.expression(block, node.left) right = self.expression(block, node.right) if isinstance(node.op, ast.Add): op = Operator.add elif isinstance(node.op, ast.Sub): op = Operator.subtract elif isinstance(node.op, ast.Mult): op = Operator.multiply elif isinstance(node.op, ast.Div): op = Operator.divide elif isinstance(node.op, ast.FloorDiv): op = Operator.divide_int elif isinstance(node.op, ast.Mod): op = Operator.mod elif isinstance(node.op, ast.Pow): op = Operator.pow elif isinstance(node.op, ast.BitAnd): op = Operator.bit_and elif isinstance(node.op, ast.BitOr): op = Operator.bit_or elif isinstance(node.op, ast.BitXor): op = Operator.bit_xor elif isinstance(node.op, ast.LShift): op = Operator.shift_left elif isinstance(node.op, ast.RShift): op = Operator.shift_right else: raise Exception('Unexpected BinOp (%s)'%(node.op.__class__)) operation = BinaryOperation(left, op, right) assignment = Assignment(var, operation) block.add(assignment) return var #Parses a unary uperation (AST UnaryOp)
Example #17
Source File: expressions.py From lexpredict-contraxsuite with GNU Affero General Public License v3.0 | 5 votes |
def stringify_operation(op: Any) -> str: if isinstance(op, ast.Add): return '+' if isinstance(op, ast.Sub): return '-' if isinstance(op, ast.Mult): return '*' if isinstance(op, ast.Div) or isinstance(op, ast.FloorDiv): return '/' return str(op)
Example #18
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_augassign_3(p): '''augassign : STAREQUAL''' # 1 p[0] = ast.Mult(rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #19
Source File: test_api.py From mutatest with MIT License | 5 votes |
def test_create_mutant_with_cache(binop_file, stdoutIO): """Change ast.Add to ast.Mult in a mutation including pycache changes.""" genome = Genome(source_file=binop_file) # this target is the add_five() function, changing add to mult end_lineno = None if sys.version_info < (3, 8) else 10 end_col_offset = None if sys.version_info < (3, 8) else 16 target_idx = LocIndex( ast_class="BinOp", lineno=10, col_offset=11, op_type=ast.Add, end_lineno=end_lineno, end_col_offset=end_col_offset, ) mutation_op = ast.Mult mutant = genome.mutate(target_idx, mutation_op, write_cache=True) # uses the redirection for stdout to capture the value from the final output of binop_file with stdoutIO() as s: exec(mutant.mutant_code) assert int(s.getvalue()) == 25 tag = sys.implementation.cache_tag expected_cfile = binop_file.parent / "__pycache__" / ".".join([binop_file.stem, tag, "pyc"]) assert mutant.src_file == binop_file assert mutant.cfile == expected_cfile assert mutant.src_idx == target_idx
Example #20
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_term_star_5(p): '''term_star : term_star STAR factor''' # 1 2 3 p[0] = p[1] + [ast.Mult(rule=inspect.currentframe().f_code.co_name, **p[2][1]), p[3]]
Example #21
Source File: definitions.py From vkbottle with MIT License | 5 votes |
def mult_operator(d: ast.Mult): return "*"
Example #22
Source File: common.py From fdroidserver with GNU Affero General Public License v3.0 | 5 votes |
def calculate_math_string(expr): ops = { ast.Add: operator.add, ast.Mult: operator.mul, ast.Sub: operator.sub, ast.USub: operator.neg, } def execute_ast(node): if isinstance(node, ast.Num): # <number> return node.n elif isinstance(node, ast.BinOp): # <left> <operator> <right> return ops[type(node.op)](execute_ast(node.left), execute_ast(node.right)) elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 return ops[type(node.op)](ast.literal_eval(node.operand)) else: raise SyntaxError(node) try: if '#' in expr: raise SyntaxError('no comments allowed') return execute_ast(ast.parse(expr, mode='eval').body) except SyntaxError: raise SyntaxError("could not parse expression '{expr}', " "only basic math operations are allowed (+, -, *)" .format(expr=expr))
Example #23
Source File: transpiler.py From pyrs with MIT License | 5 votes |
def visit_BinOp(self, node): if (isinstance(node.left, ast.List) and isinstance(node.op, ast.Mult) and isinstance(node.right, ast.Num)): return "std::vector ({0},{1})".format(self.visit(node.right), self.visit(node.left.elts[0])) else: return super(RustTranspiler, self).visit_BinOp(node)
Example #24
Source File: operators.py From wemake-python-styleguide with MIT License | 5 votes |
def _check_list_multiply(self, node: ast.BinOp) -> None: is_list_multiply = ( isinstance(node.op, ast.Mult) and isinstance(node.left, self._list_nodes) ) if is_list_multiply: self.add_violation(ListMultiplyViolation(node.left))
Example #25
Source File: test_fstring.py From android_universal with MIT License | 5 votes |
def test_ast_line_numbers(self): expr = """ a = 10 f'{a * x()}'""" t = ast.parse(expr) self.assertEqual(type(t), ast.Module) self.assertEqual(len(t.body), 2) # check `a = 10` self.assertEqual(type(t.body[0]), ast.Assign) self.assertEqual(t.body[0].lineno, 2) # check `f'...'` self.assertEqual(type(t.body[1]), ast.Expr) self.assertEqual(type(t.body[1].value), ast.JoinedStr) self.assertEqual(len(t.body[1].value.values), 1) self.assertEqual(type(t.body[1].value.values[0]), ast.FormattedValue) self.assertEqual(t.body[1].lineno, 3) self.assertEqual(t.body[1].value.lineno, 3) self.assertEqual(t.body[1].value.values[0].lineno, 3) # check the binop location binop = t.body[1].value.values[0].value self.assertEqual(type(binop), ast.BinOp) self.assertEqual(type(binop.left), ast.Name) self.assertEqual(type(binop.op), ast.Mult) self.assertEqual(type(binop.right), ast.Call) self.assertEqual(binop.lineno, 3) self.assertEqual(binop.left.lineno, 3) self.assertEqual(binop.right.lineno, 3) self.assertEqual(binop.col_offset, 3) self.assertEqual(binop.left.col_offset, 3) self.assertEqual(binop.right.col_offset, 7)
Example #26
Source File: BehavioralRTLIRGenL2Pass.py From pymtl3 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__( s, component ): super().__init__( component ) s.loop_var_env = set() s.tmp_var_env = set() # opmap maps an ast operator to its RTLIR counterpart. s.opmap = { # Bool operators # Note: we do not support boolean operators because Python does # not allow overloading And and Or operators. Using them in # expressions might lead to inconsistent semantics. # ast.And : bir.And(), ast.Or : bir.Or(), # Unary operators # Note: ast.Not is disallowed because it is a boolean operator # ast.Not : bir.Not(), ast.Invert : bir.Invert(), ast.UAdd : bir.UAdd(), ast.USub : bir.USub(), # Binary operators ast.Add : bir.Add(), ast.Sub : bir.Sub(), ast.Mult : bir.Mult(), ast.Div : bir.Div(), ast.Mod : bir.Mod(), ast.Pow : bir.Pow(), ast.LShift : bir.ShiftLeft(), ast.RShift : bir.ShiftRightLogic(), ast.BitOr : bir.BitOr(), ast.BitAnd : bir.BitAnd(), ast.BitXor : bir.BitXor(), # Compare bir.bir.operators ast.Eq : bir.Eq(), ast.NotEq : bir.NotEq(), ast.Lt : bir.Lt(), ast.LtE : bir.LtE(), ast.Gt : bir.Gt(), ast.GtE : bir.GtE() } # Override
Example #27
Source File: FileFormat.py From qiew with GNU General Public License v2.0 | 5 votes |
def onReturnPressed(self): expr = str(self.ui.lineEdit.text()) import ast import operator as op # supported operators operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.floordiv, ast.Pow: op.pow, ast.USub: op.neg} def eval_expr(expr): return eval_(ast.parse(expr, mode='eval').body) 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, object): # handle constants k = str(node.id).upper() if k in self.konstants: return self.konstants[k](k) else: raise TypeError(node) else: raise TypeError(node) try: result = eval_expr(expr) except Exception as e: self.ui.label.setText('error.') return self.ui.label.setText('{0} ({1})'.format(hex(result), result)) self.onResult(result)
Example #28
Source File: test_ast.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_example_from_net(self): node = ast.Expression(ast.BinOp(ast.Str('xy'), ast.Mult(), ast.Num(3)))
Example #29
Source File: cse.py From sspam with BSD 3-Clause "New" or "Revised" License | 5 votes |
def visit_UnaryOp(self, node): 'Change USub and Invert' operand = self.visit(node.operand) if isinstance(node.op, ast.UAdd): return operand if isinstance(node.op, ast.USub): return ast.BinOp(ast.Num(-1), ast.Mult(), operand) if isinstance(node.op, ast.Invert): return ast.BinOp(ast.Num(-1), ast.BitXor(), operand) assert False, 'unhandled node type: ' + ast.dump(node)
Example #30
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 5 votes |
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