Python ast.UnaryOp() Examples
The following are 30
code examples of ast.UnaryOp().
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: SimulatorExpressionParser.py From urh with GNU General Public License v3.0 | 6 votes |
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)
Example #2
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 6 votes |
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)
Example #3
Source File: _ast_to_ir2.py From tmppy with Apache License 2.0 | 6 votes |
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)
Example #4
Source File: cheader.py From steamcontroller with MIT License | 6 votes |
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)
Example #5
Source File: yacc.py From yaksok with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #6
Source File: SimulatorExpressionParser.py From urh with GNU General Public License v3.0 | 6 votes |
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")
Example #7
Source File: SimulatorExpressionParser.py From urh with GNU General Public License v3.0 | 6 votes |
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)
Example #8
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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
Example #9
Source File: pattern_matcher.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #10
Source File: tags_manager.py From golem with MIT License | 6 votes |
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)
Example #11
Source File: flatten.py From kappa with BSD 2-Clause "Simplified" License | 5 votes |
def visit_UnaryOp(self, unaryop: ast.UnaryOp) -> VisitExprReturnT: operand, operand_actions = self.visit_expr(unaryop.operand) unaryop_flattened = ast.UnaryOp(op=unaryop.op, operand=operand) result_id = self.next_symbol_id() result_node = assign(result_id, unaryop_flattened) return load(result_id), operand_actions + [result_node]
Example #12
Source File: utils.py From vulture with MIT License | 5 votes |
def _safe_eval(node, default): """ Safely evaluate the Boolean expression under the given AST node. Substitute `default` for all sub-expressions that cannot be evaluated (because variables or functions are undefined). We could use eval() to evaluate more sub-expressions. However, this function is not safe for arbitrary Python code. Even after overwriting the "__builtins__" dictionary, the original dictionary can be restored (https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html). """ if isinstance(node, ast.BoolOp): results = [_safe_eval(value, default) for value in node.values] if isinstance(node.op, ast.And): return all(results) else: return any(results) elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): return not _safe_eval(node.operand, not default) else: try: return ast.literal_eval(node) except ValueError: return default
Example #13
Source File: bugbear.py From flake8-bugbear with MIT License | 5 votes |
def visit_UAdd(self, node): trailing_nodes = list(map(type, self.node_window[-4:])) if trailing_nodes == [ast.UnaryOp, ast.UAdd, ast.UnaryOp, ast.UAdd]: originator = self.node_window[-4] self.errors.append(B002(originator.lineno, originator.col_offset)) self.generic_visit(node)
Example #14
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_factor_1(p): '''factor : PLUS factor''' # 1 2 op = ast.UAdd(rule=inspect.currentframe().f_code.co_name, **p[1][1]) p[0] = ast.UnaryOp(op, p[2], rule=inspect.currentframe().f_code.co_name) inherit_lineno(p[0], op)
Example #15
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_not_test_1(p): '''not_test : NOT not_test''' # 1 2 thenot = ast.Not(rule=inspect.currentframe().f_code.co_name) inherit_lineno(thenot, p[2]) p[0] = ast.UnaryOp(thenot, p[2], rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #16
Source File: ParseMathExp.py From Projects with MIT License | 5 votes |
def eval_node(node): """Recursively parse math expression using AST""" if isinstance(node, ast.Num): # <number> return node.n elif isinstance(node, ast.BinOp): # <left> <operator> <right> return operators[type(node.op)](eval_node(node.left), eval_node(node.right)) elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 return operators[type(node.op)](eval_node(node.operand)) else: raise TypeError(node)
Example #17
Source File: misc.py From sisl with GNU Lesser General Public License v3.0 | 5 votes |
def _eval(node): if isinstance(node, ast.Num): # <number> return node.n elif isinstance(node, ast.BinOp): # <left> <operator> <right> return _operators[type(node.op)](_eval(node.left), _eval(node.right)) elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 return _operators[type(node.op)](_eval(node.operand)) else: raise TypeError(node)
Example #18
Source File: flatten.py From kappa with BSD 2-Clause "Simplified" License | 5 votes |
def _not_expr(expr: ast.expr) -> ast.expr: """Generates AST node for `not expr`.""" return ast.UnaryOp(op=ast.Not(), operand=expr)
Example #19
Source File: _343.py From codetransformer with GNU General Public License v2.0 | 5 votes |
def _make_expr_unary_not(toplevel, stack_builders): return ast.UnaryOp( op=ast.Not(), operand=make_expr(stack_builders), )
Example #20
Source File: matheval.py From OpenNIR with MIT License | 5 votes |
def eval_(node, numtype): if isinstance(node, ast.Num): # <number> return numtype(str(node.n)) if isinstance(node, ast.BinOp): # <left> <operator> <right> return operators[type(node.op)](eval_(node.left, numtype), eval_(node.right, numtype)) if isinstance(node, ast.Compare): # <left> <operator> <right> assert len(node.ops) == 1 and len(node.comparators) == 1 return operators[type(node.ops[0])](eval_(node.left, numtype), eval_(node.comparators[0], numtype)) if isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1 return operators[type(node.op)](eval_(node.operand, numtype)) raise TypeError(node)
Example #21
Source File: _343.py From codetransformer with GNU General Public License v2.0 | 5 votes |
def make_if_statement(instr, queue, stack, context): """ Make an ast.If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE. """ test_expr = make_expr(stack) if isinstance(instr, instrs.POP_JUMP_IF_TRUE): test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr) first_block = popwhile(op.is_not(instr.arg), queue, side='left') if isinstance(first_block[-1], instrs.RETURN_VALUE): body = instrs_to_body(first_block, context) return ast.If(test=test_expr, body=body, orelse=[]) jump_to_end = expect( first_block.pop(), instrs.JUMP_FORWARD, "at end of if-block" ) body = instrs_to_body(first_block, context) # First instruction after the whole if-block. end = jump_to_end.arg if instr.arg is jump_to_end.arg: orelse = [] else: orelse = instrs_to_body( popwhile(op.is_not(end), queue, side='left'), context, ) return ast.If(test=test_expr, body=body, orelse=orelse)
Example #22
Source File: yacc.py From yaksok with BSD 3-Clause "New" or "Revised" License | 5 votes |
def p_unary_expr_minus_primary(t): #'''unary_expr : MINUS primary %prec UMINUS''' '''unary_expr : MINUS primary''' usub = ast.USub() usub.lineno = t.lineno(1) usub.col_offset = -1 # XXX t[0] = ast.UnaryOp(usub, t[2]) t[0].lineno = t.lineno(2) t[0].col_offset = -1 # XXX
Example #23
Source File: bird.py From executing with MIT License | 5 votes |
def is_interesting_expression(node): # type: (ast.AST) -> bool """ If this expression has a value that may not be exactly what it looks like, return True. Put differently, return False if this is just a literal. """ return (isinstance(node, ast.expr) and not (isinstance(node, (ast.Num, ast.Str, getattr(ast, 'NameConstant', ()))) or isinstance(getattr(node, 'ctx', None), (ast.Store, ast.Del)) or (isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)) and isinstance(node.operand, ast.Num)) or (isinstance(node, (ast.List, ast.Tuple, ast.Dict)) and not any(is_interesting_expression(n) for n in ast.iter_child_nodes(node)))))
Example #24
Source File: tests.py From executing with MIT License | 5 votes |
def __invert__(self): node = self.get_node(ast.UnaryOp) self.check(node.operand, self) return self
Example #25
Source File: test_main.py From executing with MIT License | 5 votes |
def is_literal(node): if isinstance(node, ast.UnaryOp): return is_literal(node.operand) if isinstance(node, ast.BinOp): return is_literal(node.left) and is_literal(node.right) if isinstance(node, ast.Compare): return all(map(is_literal, [node.left] + node.comparators)) if isinstance(node, ast.Subscript) and is_literal(node.value): if isinstance(node.slice, ast.Slice): return all( x is None or is_literal(x) for x in [ node.slice.lower, node.slice.upper, node.slice.step, ] ) else: return is_literal(subscript_item(node)) try: ast.literal_eval(node) return True except ValueError: return False
Example #26
Source File: test_main.py From executing with MIT License | 5 votes |
def is_unary_not(node): return isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not)
Example #27
Source File: utils.py From executing with MIT License | 5 votes |
def __invert__(self): node = self.get_node(ast.UnaryOp) self.check(node.operand, self) return self
Example #28
Source File: parser.py From vecpy with MIT License | 5 votes |
def expression(self, block, expr, var=None): if isinstance(expr, ast.Num): var = self.add_literal(expr.n) elif isinstance(expr, ast.Name): var = self.kernel.get_variable(expr.id) if var is None: raise Exception('Undefined Variable (%s)'%(expr.id)) if var.is_fuse: raise Exception('Fuse variables are write-only') if var.is_arg: var.is_input = True elif isinstance(expr, ast.BinOp): var = self.binop(block, expr, var) elif isinstance(expr, ast.UnaryOp): var = self.unaryop(block, expr) elif isinstance(expr, ast.Call): var = self.call(block, expr, var) elif isinstance(expr, ast.Attribute): var = self.attribute(block, expr) elif isinstance(expr, ast.Compare): var = self.compare(block, expr) elif isinstance(expr, ast.BoolOp): var = self.boolop(block, expr) elif isinstance(expr, ast.Subscript): (var, assignment) = self.subscript(block, expr) block.add(assignment) else: Parser._dump(expr, 'Unexpected Expression') raise Exception('Unexpected Expression (%s)'%(expr.__class__)) return var #Generates a new block mask
Example #29
Source File: parser.py From vecpy with MIT License | 5 votes |
def unaryop(self, block, node): operand = self.expression(block, node.operand) if isinstance(node.op, ast.UAdd): #No-Op var = operand elif isinstance(node.op, ast.USub): if operand.value is not None: #It's a literal, return the negation var = self.add_literal(-operand.value) else: #It's an expression, subtract from zero (faster than multiplying by -1) var = self.add_variable(None) zero = self.add_literal(0, 'ZERO') operation = BinaryOperation(zero, Operator.subtract, operand) assignment = Assignment(var, operation) block.add(assignment) elif isinstance(node.op, ast.Invert): #Make sure it's numeric if operand.is_mask: raise Exception('Unary invert requires a numeric operand') #Bit-flip var = self.add_variable(None) operation = UnaryOperation(Operator.bit_not, operand) assignment = Assignment(var, operation) block.add(assignment) elif isinstance(node.op, ast.Not): #Make sure it's boolean if not operand.is_mask: raise Exception('Unary not requires a boolean operand') #Invert the mask var = self.add_variable(None, is_mask=True) operation = UnaryOperation(Operator.bool_not, operand) assignment = Assignment(var, operation) block.add(assignment) else: raise Exception('Unexpected UnaryOp (%s)'%(node.op.__class__)) return var #Parses a comparison operator (AST CmpOp)
Example #30
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)