本文整理汇总了Python中ast.BinOp方法的典型用法代码示例。如果您正苦于以下问题:Python ast.BinOp方法的具体用法?Python ast.BinOp怎么用?Python ast.BinOp使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.BinOp方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def visit_Compare(self, node, **kwargs):
ops = node.ops
comps = node.comparators
# base case: we have something like a CMP b
if len(comps) == 1:
op = self.translate_In(ops[0])
binop = ast.BinOp(op=op, left=node.left, right=comps[0])
return self.visit(binop)
# recursive case: we have a chained comparison, a CMP b CMP c, etc.
left = node.left
values = []
for op, comp in zip(ops, comps):
new_node = self.visit(ast.Compare(comparators=[comp], left=left,
ops=[self.translate_In(op)]))
left = comp
values.append(new_node)
return self.visit(ast.BoolOp(op=ast.And(), values=values))
示例2: test_afterSubMult
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
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))
示例3: test_noflattening
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
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)
示例4: visit_UnaryOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
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
示例5: check_neg
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
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)
示例6: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [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
示例7: visit_BinOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def visit_BinOp(self, node):
'If node is a constant expression, replace it with its evaluated value'
if node in self.constexpr:
# evaluation
fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
ast.Num(self.mod)))
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)
return new_node
else:
return self.generic_visit(node)
示例8: visit_UnaryOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def visit_UnaryOp(self, node):
'Same idea as visit_BinOp'
if node in self.constexpr:
# evaluation
fake_node = ast.Expression(ast.BinOp(node, ast.Mod(),
ast.Num(self.mod)))
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)
return new_node
else:
return self.generic_visit(node)
示例9: visit_BinOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def visit_BinOp(self, node, partial=False):
'Regroup associative operators'
if isinstance(node.op, self.op):
operands = []
for child in node.left, node.right:
cond = (isinstance(child, ast.BinOp)
and isinstance(child.op, self.op)
and self.op in ASSOCIATIVE_OPERATORS)
if cond:
operands.extend(self.visit_BinOp(child, partial=True))
else:
self.visit(child)
operands.append(child)
if not partial:
self.result_nodes.append(node)
self.result.append(operands)
return operands
else:
self.generic_visit(node)
return []
示例10: pop_format_context
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def pop_format_context(self, expl_expr):
"""Format the %-formatted string with current format context.
The expl_expr should be an ast.Str instance constructed from
the %-placeholders created by .explanation_param(). This will
add the required code to format said string to .expl_stmts and
return the ast.Name instance of the formatted string.
"""
current = self.stack.pop()
if self.stack:
self.explanation_specifiers = self.stack[-1]
keys = [ast.Str(key) for key in current.keys()]
format_dict = ast.Dict(keys, list(current.values()))
form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
name = "@py_format" + str(next(self.variable_counter))
if self.enable_assertion_pass_hook:
self.format_variables.append(name)
self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
return ast.Name(name, ast.Load())
示例11: test_increment_lineno
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def test_increment_lineno(self):
src = ast.parse('1 + 1', mode='eval')
self.assertEqual(ast.increment_lineno(src, n=3), src)
self.assertEqual(ast.dump(src, include_attributes=True),
'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
'col_offset=0))'
)
# issue10869: do not increment lineno of root twice
src = ast.parse('1 + 1', mode='eval')
self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
self.assertEqual(ast.dump(src, include_attributes=True),
'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
'col_offset=0))'
)
示例12: test_nodeclasses
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
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()
示例13: _fix_percent_format_tuple
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def _fix_percent_format_tuple(
tokens: List[Token],
start: int,
node: ast.BinOp,
) -> None:
# TODO: this is overly timid
paren = start + 4
if tokens_to_src(tokens[start + 1:paren + 1]) != ' % (':
return
victims = _victims(tokens, paren, node.right, gen=False)
victims.ends.pop()
for index in reversed(victims.starts + victims.ends):
_remove_brace(tokens, index)
newsrc = _percent_to_format(tokens[start].src)
tokens[start] = tokens[start]._replace(src=newsrc)
tokens[start + 1:paren] = [Token('Format', '.format'), Token('OP', '(')]
示例14: pop_format_context
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [as 别名]
def pop_format_context(self, expl_expr: ast.expr) -> ast.Name:
"""Format the %-formatted string with current format context.
The expl_expr should be an str ast.expr instance constructed from
the %-placeholders created by .explanation_param(). This will
add the required code to format said string to .expl_stmts and
return the ast.Name instance of the formatted string.
"""
current = self.stack.pop()
if self.stack:
self.explanation_specifiers = self.stack[-1]
keys = [ast.Str(key) for key in current.keys()]
format_dict = ast.Dict(keys, list(current.values()))
form = ast.BinOp(expl_expr, ast.Mod(), format_dict)
name = "@py_format" + str(next(self.variable_counter))
if self.enable_assertion_pass_hook:
self.format_variables.append(name)
self.expl_stmts.append(ast.Assign([ast.Name(name, ast.Store())], form))
return ast.Name(name, ast.Load())
示例15: visit_BinOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import BinOp [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