本文整理汇总了Python中ast.And方法的典型用法代码示例。如果您正苦于以下问题:Python ast.And方法的具体用法?Python ast.And怎么用?Python ast.And使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ast
的用法示例。
在下文中一共展示了ast.And方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: visit_Compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [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: normalize_compare
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def normalize_compare(node):
"""Rewrites a compare expression to a `and` expression
1 < 2 < 3 > 0
1 < 2 and 2 < 3 and 3 > 0"""
and_values = []
left = node.left
for (op, val) in zip(node.ops, node.comparators):
comp = ast.Compare(ops=[op],
left=left,
comparators=[val],
lineno=node.lineno,
col_offset=node.col_offset)
and_values.append(comp)
left = val
return ast.BoolOp(op=ast.And(),
values=and_values,
lineno=node.lineno,
col_offset=node.col_offset)
示例3: verify_ast
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def verify_ast(expr, variables_and_values):
"""Verifies that |expr| is of the form
expr ::= expr ( "or" | "and" ) expr
| identifier "==" ( string | int )
Also collects the variable identifiers and string/int values in the dict
|variables_and_values|, in the form {'var': set([val1, val2, ...]), ...}.
"""
assert isinstance(expr, (ast.BoolOp, ast.Compare))
if isinstance(expr, ast.BoolOp):
assert isinstance(expr.op, (ast.And, ast.Or))
for subexpr in expr.values:
verify_ast(subexpr, variables_and_values)
else:
assert isinstance(expr.left.ctx, ast.Load)
assert len(expr.ops) == 1
assert isinstance(expr.ops[0], ast.Eq)
var_values = variables_and_values.setdefault(expr.left.id, set())
rhs = expr.comparators[0]
assert isinstance(rhs, (ast.Str, ast.Num))
var_values.add(rhs.n if isinstance(rhs, ast.Num) else rhs.s)
示例4: boolop
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def boolop(self, block, node, var=None):
#Get the type of operation
if isinstance(node.op, ast.And):
op = Operator.bool_and
elif isinstance(node.op, ast.Or):
op = Operator.bool_or
else:
raise Exception('Unexpected BoolOp (%s)'%(node.op.__class__))
#Chain operations together
left = self.expression(block, node.values[0])
for node_value in node.values[1:]:
right = self.expression(block, node_value)
operation = BinaryOperation(left, op, right)
if node_value == node.values[-1] and var is not None:
#The last operation in the chain should be assigned to this variable
temp_var = var
else:
#Create a temporary variable to store the intermediate result
temp_var = self.add_variable(None, is_mask=True)
assignment = Assignment(temp_var, operation)
block.add(assignment)
left = temp_var
return temp_var
#Parses an array element (AST Subscript)
示例5: normalize_boolop
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def normalize_boolop(expr):
"""
Normalize a boolop by folding together nested And/Or exprs.
"""
optype = expr.op
newvalues = []
for subexpr in expr.values:
if not isinstance(subexpr, ast.BoolOp):
newvalues.append(subexpr)
elif type(subexpr.op) != type(optype):
newvalues.append(normalize_boolop(subexpr))
else:
# Normalize subexpression, then inline its values into the
# top-level subexpr.
newvalues.extend(normalize_boolop(subexpr).values)
return ast.BoolOp(op=optype, values=newvalues)
示例6: visit_BoolOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def visit_BoolOp(self, node):
len_t = len(node.values)
assert(len_t >= 2)
End_target_label = self.codegencontext.NewLabel()
End_target_postion = End_target_label.to_bytes(2, 'little', signed=True)
for i in range(len_t):
self.visit(node.values[i])
if i != (len_t - 1):
if (type(node.op).__name__ == 'Or'):
self.codegencontext.tokenizer.Emit_Token(VMOp.DUP, node)
self.codegencontext.tokenizer.Emit_Token(VMOp.JMPIF, node, End_target_postion)
self.codegencontext.tokenizer.Emit_Token(VMOp.DROP, node)
elif (type(node.op).__name__ == 'And'):
self.codegencontext.tokenizer.Emit_Token(VMOp.DUP, node)
self.codegencontext.tokenizer.Emit_Token(VMOp.JMPIFNOT, node, End_target_postion)
self.codegencontext.tokenizer.Emit_Token(VMOp.DROP, node)
else:
assert(False)
self.codegencontext.SetLabel(End_target_label, self.codegencontext.pc + 1)
示例7: p_logic_and_expr
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def p_logic_and_expr(t):
'''logic_and_expr : logic_and_expr AND logic_expr
| logic_expr'''
if len(t) == 4:
if isinstance(t[1], ast.BoolOp) and isinstance(t[1].op, ast.And):
t[0] = t[1]
t[0].values.append(t[3])
else:
and_ast = ast.And()
and_ast.lineno = t.lineno(2)
and_ast.col_offset = -1 # XXX
t[0] = ast.BoolOp(and_ast, [t[1], t[3]])
t[0].lineno = t.lineno(2)
t[0].col_offset = -1 # XXX
else:
t[0] = t[1]
示例8: gen_bool_op
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def gen_bool_op(self, condition, yes_block, no_block):
""" Compile a boolean operator such as 'and' """
assert len(condition.values) >= 1
first_values = condition.values[:-1]
last_value = condition.values[-1]
if isinstance(condition.op, ast.And):
# All values must be true here,
# so bail out on first false value.
for value in first_values:
all_true_block = self.builder.new_block()
self.gen_cond(value, all_true_block, no_block)
self.builder.set_block(all_true_block)
self.gen_cond(last_value, yes_block, no_block)
elif isinstance(condition.op, ast.Or):
# The first true value is enough to make this work!
for value in first_values:
all_false_block = self.builder.new_block()
self.gen_cond(value, yes_block, all_false_block)
self.builder.set_block(all_false_block)
self.gen_cond(last_value, yes_block, no_block)
else: # pragma: no cover
self.not_impl(condition)
示例9: evaluate_node
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [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")
示例10: _evaluate
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [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)
示例11: boolop_expected_loc
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def boolop_expected_loc():
"""Expected location index of the boolop fixture"""
# Py 3.7 vs 3.8
end_lineno = None if sys.version_info < (3, 8) else 2
end_col_offset = None if sys.version_info < (3, 8) else 18
return LocIndex(
ast_class="BoolOp",
lineno=2,
col_offset=11,
op_type=ast.And,
end_lineno=end_lineno,
end_col_offset=end_col_offset,
)
示例12: do_boolop
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def do_boolop(self, node):
result = self.evaluate(node.values[0])
is_or = node.op.__class__ is ast.Or
is_and = node.op.__class__ is ast.And
assert is_or or is_and
if (is_and and result) or (is_or and not result):
for n in node.values[1:]:
result = self.evaluate(n)
if (is_or and result) or (is_and and not result):
break
return result
示例13: and_expression_ast_to_ir2
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def and_expression_ast_to_ir2(ast_node: ast.BoolOp,
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.And)
if in_match_pattern:
raise CompilationError(compilation_context, ast_node,
'The "and" operator is not allowed in match patterns')
if not compilation_context.current_function_name:
raise CompilationError(compilation_context, ast_node,
'The "and" operator is only supported in functions, not at toplevel.')
assert len(ast_node.values) >= 2
exprs = []
for expr_ast_node in ast_node.values:
expr = expression_ast_to_ir2(expr_ast_node,
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, expr_ast_node,
'The "and" operator is only supported for booleans, but this value has type %s.' % str(expr.expr_type))
exprs.append(expr)
final_expr = exprs[-1]
for expr in reversed(exprs[:-1]):
final_expr = ir2.AndExpr(lhs=expr, rhs=final_expr)
return final_expr
示例14: __init__
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
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
示例15: visit_BoolOp
# 需要导入模块: import ast [as 别名]
# 或者: from ast import And [as 别名]
def visit_BoolOp(self, node: ast.BoolOp) -> Any:
"""Recursively visit the operands and apply the operation on them."""
values = [self.visit(value_node) for value_node in node.values]
if isinstance(node.op, ast.And):
result = functools.reduce(lambda left, right: left and right, values, True)
elif isinstance(node.op, ast.Or):
result = functools.reduce(lambda left, right: left or right, values, True)
else:
raise NotImplementedError("Unhandled op of {}: {}".format(node, node.op))
self.recomputed_values[node] = result
return result