Python ast.Mod() Examples
The following are 30
code examples of ast.Mod().
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: source_visitor.py From vermin with MIT License | 6 votes |
def visit_BinOp(self, node): # Examples: # BinOp(left=Bytes(s=b'%4x'), op=Mod(), right=Num(n=10)) # BinOp(left=Call(func=Name(id='bytearray', ctx=Load()), args=[Bytes(s=b'%x')], keywords=[]), # op=Mod(), right=Num(n=10)) if (hasattr(ast, "Bytes") and isinstance(node.left, ast.Bytes))\ and isinstance(node.op, ast.Mod): self.__bytes_format = True self.__vvprint("bytes `%` formatting requires 3.5+ (or 2.6+ as `str` synonym)") if (isinstance(node.left, ast.Call) and isinstance(node.left.func, ast.Name) and node.left.func.id == "bytearray") and isinstance(node.op, ast.Mod): self.__bytearray_format = True self.__vvprint("bytearray `%` formatting requires 3.5+") self.generic_visit(node)
Example #2
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 #3
Source File: gen.py From ChromeController with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __build_unconditional_arg_check(self, argname, argtype): presence_check = ast.Call(func = ast.Name(id='isinstance', ctx=ast.Load()), args = [ast.Name(id=argname, ctx=ast.Load()), argtype], keywords = [], lineno = self.__get_line()) types = [t.id for t in argtype.elts] check_message = ast.BinOp( left = ast.Str(s='Argument \'{}\' must be of type \'{}\'. Received type: \'%s\''.format(argname, types)), op = ast.Mod(), right = ast.Call(func=ast.Name(id='type', ctx=ast.Load()), args=[ast.Name(id=argname, ctx=ast.Load())], keywords=[]), lineno = self.__get_line()) new_ret = ast.Assert( test = presence_check, msg = check_message, lineno = self.__get_line()) return new_ret
Example #4
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 #5
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 #6
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #7
Source File: asttools.py From sspam with BSD 3-Clause "New" or "Revised" License | 6 votes |
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)
Example #8
Source File: rewrite.py From python-netsurv with MIT License | 6 votes |
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())
Example #9
Source File: rewrite.py From python-netsurv with MIT License | 6 votes |
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())
Example #10
Source File: _toVerilog.py From myhdl with GNU Lesser General Public License v2.1 | 6 votes |
def visit_BinOp(self, node): if isinstance(node.op, ast.Mod) and self.context == _context.PRINT: self.visit(node.left) self.write(", ") self.visit(node.right) else: if isinstance(node.op, ast.RShift): # Additional cast to signed of the full expression # this is apparently required by cver - not sure if it # is actually required by standard Verilog. # It shouldn't hurt however. if node.signed: self.write("$signed") self.context = None if node.signed: self.context = _context.SIGNED self.write("(") self.visit(node.left) self.write(" %s " % opmap[type(node.op)]) self.visit(node.right) self.write(")") self.context = None
Example #11
Source File: django_xss.py From bandit with Apache License 2.0 | 6 votes |
def transform2call(var): if isinstance(var, ast.BinOp): is_mod = isinstance(var.op, ast.Mod) is_left_str = isinstance(var.left, ast.Str) if is_mod and is_left_str: new_call = ast.Call() new_call.args = [] new_call.args = [] if six.PY2: new_call.starargs = None new_call.keywords = None if six.PY2: new_call.kwargs = None new_call.lineno = var.lineno new_call.func = ast.Attribute() new_call.func.value = var.left new_call.func.attr = 'format' if isinstance(var.right, ast.Tuple): new_call.args = var.right.elts elif six.PY2 and isinstance(var.right, ast.Dict): new_call.kwargs = var.right else: new_call.args = [var.right] return new_call
Example #12
Source File: rewrite.py From pytest with MIT License | 6 votes |
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())
Example #13
Source File: checker.py From pyflakes with MIT License | 5 votes |
def BINOP(self, node): if ( isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str) ): self._handle_percent_format(node) self.handleChildren(node)
Example #14
Source File: gen.py From ChromeController with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __build_conditional_arg_check(self, argname, argtype): target_value = ast.Subscript( value=ast.Name(id='kwargs', ctx=ast.Load()), slice=ast.Index(ast.Str(s=argname)), ctx=ast.Load() ) presence_check = ast.Call(func = ast.Name(id='isinstance', ctx=ast.Load()), args = [target_value, argtype], keywords = [], lineno = self.__get_line()) # Assumes that argtype is a ast.Tuple of ast.Name items types = [t.id for t in argtype.elts] check_message = ast.BinOp( left = ast.Str(s='Optional argument \'{}\' must be of type \'{}\'. Received type: \'%s\''.format(argname, types)), op = ast.Mod(), right = ast.Call(func=ast.Name(id='type', ctx=ast.Load()), args=[target_value], keywords=[]), lineno = self.__get_line()) assert_check = ast.Assert( test = presence_check, msg = check_message, lineno = self.__get_line()) check_body = [assert_check] check = ast.Compare(left=ast.Str(s=argname, ctx=ast.Load()), ops=[ast.In()], comparators=[ast.Name(id='kwargs', ctx=ast.Load())]) new_ret = ast.If( test = check, body = check_body, orelse = [], lineno = self.__get_line()) return new_ret
Example #15
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 #16
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_augassign_5(p): '''augassign : PERCENTEQUAL''' # 1 p[0] = ast.Mod(rule=inspect.currentframe().f_code.co_name, **p[1][1])
Example #17
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_term_star_3(p): '''term_star : PERCENT factor''' # 1 2 p[0] = [ast.Mod(rule=inspect.currentframe().f_code.co_name, **p[1][1]), p[2]]
Example #18
Source File: hgawk_grammar.py From histogrammar-python with Apache License 2.0 | 5 votes |
def p_term_star_7(p): '''term_star : term_star PERCENT factor''' # 1 2 3 p[0] = p[1] + [ast.Mod(rule=inspect.currentframe().f_code.co_name, **p[2][1]), p[3]]
Example #19
Source File: definitions.py From vkbottle with MIT License | 5 votes |
def mod_operator(d: ast.Mod): return "%"
Example #20
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 #21
Source File: test_mock.py From rally-openstack with Apache License 2.0 | 5 votes |
def _get_value(self, node): """Get mock.patch string argument regexp. It is either a string (if we are lucky), string-format of ("%s.something" % GVAL) or (GVAL + ".something") """ val = None if isinstance(node, ast.Str): val = node.s elif isinstance(node, ast.BinOp): if pairwise_isinstance( (node.op, ast.Mod), (node.left, ast.Str), (node.right, ast.Name)): val = node.left.s % self.globals_[node.right.id] elif pairwise_isinstance( (node.op, ast.Add), (node.left, ast.Name), (node.right, ast.Str)): val = self.globals_[node.left.id] + node.right.s elif isinstance(node, ast.Name): val = self.globals_[node.id] if val is None: raise ValueError( "Unable to find value in %s, only the following are parsed: " "GLOBAL, 'pkg.foobar', '%%s.foobar' %% GLOBAL or 'GLOBAL + " "'.foobar'" % ast.dump(node)) return val
Example #22
Source File: sembuilder.py From miasm with GNU General Public License v2.0 | 5 votes |
def visit_Call(self, node): """iX(Y) -> ExprIntX(Y), 'X'(Y) -> ExprOp('X', Y), ('X' % Y)(Z) -> ExprOp('X' % Y, Z)""" # Recursive visit node = self.generic_visit(node) if isinstance(node.func, ast.Name): # iX(Y) -> ExprInt(Y, X) fc_name = node.func.id # Match the function name new_name = fc_name integer = self.parse_integer.search(fc_name) # Do replacement if integer is not None: size = int(integer.groups()[0]) new_name = "ExprInt" # Replace in the node node.func.id = new_name node.args.append(ast.Num(n=size)) elif (isinstance(node.func, ast.Str) or (isinstance(node.func, ast.BinOp) and isinstance(node.func.op, ast.Mod) and isinstance(node.func.left, ast.Str))): # 'op'(args...) -> ExprOp('op', args...) # ('op' % (fmt))(args...) -> ExprOp('op' % (fmt), args...) op_name = node.func # Do replacement node.func = ast.Name(id="ExprOp", ctx=ast.Load()) node.args[0:0] = [op_name] return node
Example #23
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 #24
Source File: pyupgrade.py From pyupgrade with MIT License | 5 votes |
def visit_BinOp(self, node: ast.BinOp) -> None: if isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str): try: parsed = parse_percent_format(node.left.s) except ValueError: pass else: for _, fmt in parsed: if not fmt: continue key, conversion_flag, width, precision, conversion = fmt # timid: these require out-of-order parameter consumption if width == '*' or precision == '.*': break # these conversions require modification of parameters if conversion in {'d', 'i', 'u', 'c'}: break # timid: py2: %#o formats different from {:#o} (--py3?) if '#' in (conversion_flag or '') and conversion == 'o': break # no equivalent in format if key == '': break # timid: py2: conversion is subject to modifiers (--py3?) nontrivial_fmt = any((conversion_flag, width, precision)) if conversion == '%' and nontrivial_fmt: break # no equivalent in format if conversion in {'a', 'r'} and nontrivial_fmt: break # all dict substitutions must be named if isinstance(node.right, ast.Dict) and not key: break else: self.found[_ast_to_offset(node)] = node self.generic_visit(node)
Example #25
Source File: _toVHDL.py From myhdl with GNU Lesser General Public License v2.1 | 5 votes |
def visit_BinOp(self, node): self.generic_visit(node) if isinstance(node.op, (ast.LShift, ast.RShift)): self.inferShiftType(node) elif isinstance(node.op, (ast.BitAnd, ast.BitOr, ast.BitXor)): self.inferBitOpType(node) elif isinstance(node.op, ast.Mod) and isinstance(node.left, ast.Str): # format string pass else: self.inferBinOpType(node)
Example #26
Source File: parse.py From qiime2 with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _expr(expr): node = type(expr) if node is ast.Name: return _build_atomic(expr.id) if node is ast.Call: args = _parse_args(expr.args) kwargs = _parse_kwargs(expr.keywords) return _build_predicate(expr.func.id, args, kwargs) if node is ast.Subscript: field_expr = expr.slice.value if type(field_expr) is ast.Tuple: field_expr = field_expr.elts else: field_expr = (field_expr,) base = _expr(expr.value) base['fields'] = [_expr(e) for e in field_expr] return base if node is ast.BinOp: op = type(expr.op) left = _expr(expr.left) right = _expr(expr.right) if op is ast.Mod: left['predicate'] = right return left if op is ast.BitOr: return _build_union(left, right) if op is ast.BitAnd: return _build_intersection(left, right) raise ValueError("Unknown expression: %r" % node)
Example #27
Source File: compiler.py From Transcrypt with Apache License 2.0 | 4 votes |
def visit_BinOp (self, node): if type (node.op) == ast.FloorDiv: if self.allowOperatorOverloading: self.emit ('__floordiv__ (') self.visitSubExpr (node, node.left) self.emit (', ') self.visitSubExpr (node, node.right) self.emit (')') else: self.emit ('Math.floor (') self.visitSubExpr (node, node.left) self.emit (' / ') self.visitSubExpr (node, node.right) self.emit (')') elif ( type (node.op) in (ast.Pow, ast.MatMult) or (type (node.op) == ast.Mod and (self.allowOperatorOverloading or not self.allowJavaScriptMod)) or (type (node.op) in ( ast.Mult, ast.Div, ast.Add, ast.Sub, ast.LShift, ast.RShift, ast.BitOr, ast.BitXor, ast.BitAnd ) and self.allowOperatorOverloading) ): self.emit ('{} ('.format (self.filterId ( # Non-overloaded ('__floordiv__' if self.allowOperatorOverloading else 'Math.floor') if type (node.op) == ast.FloorDiv else ('__pow__' if self.allowOperatorOverloading else 'Math.pow') if type (node.op) == ast.Pow else '__matmul__' if type (node.op) == ast.MatMult else ('__jsmod__' if self.allowJavaScriptMod else '__mod__') if type (node.op) == ast.Mod else # Overloaded arithmetic '__mul__' if type (node.op) == ast.Mult else '__truediv__' if type (node.op) == ast.Div else '__add__' if type (node.op) == ast.Add else '__sub__' if type (node.op) == ast.Sub else # Overloaded bitwise '__lshift__' if type (node.op) == ast.LShift else '__rshift__' if type (node.op) == ast.RShift else '__or__' if type (node.op) == ast.BitOr else '__xor__' if type (node.op) == ast.BitXor else '__and__' if type (node.op) == ast.BitAnd else 'Never here' ))) self.visit (node.left) self.emit (', ') self.visit (node.right) self.emit (')') else: self.visitSubExpr (node, node.left) self.emit (' {} '.format (self.operators [type (node.op)][0])) self.visitSubExpr (node, node.right)
Example #28
Source File: django_xss.py From bandit with Apache License 2.0 | 4 votes |
def check_risk(node): description = "Potential XSS on mark_safe function." xss_var = node.args[0] secure = False if isinstance(xss_var, ast.Name): # Check if the var are secure parent = node._bandit_parent while not isinstance(parent, (ast.Module, ast.FunctionDef)): parent = parent._bandit_parent is_param = False if isinstance(parent, ast.FunctionDef): for name in parent.args.args: arg_name = name.id if six.PY2 else name.arg if arg_name == xss_var.id: is_param = True break if not is_param: secure = evaluate_var(xss_var, parent, node.lineno) elif isinstance(xss_var, ast.Call): parent = node._bandit_parent while not isinstance(parent, (ast.Module, ast.FunctionDef)): parent = parent._bandit_parent secure = evaluate_call(xss_var, parent) elif isinstance(xss_var, ast.BinOp): is_mod = isinstance(xss_var.op, ast.Mod) is_left_str = isinstance(xss_var.left, ast.Str) if is_mod and is_left_str: parent = node._bandit_parent while not isinstance(parent, (ast.Module, ast.FunctionDef)): parent = parent._bandit_parent new_call = transform2call(xss_var) secure = evaluate_call(new_call, parent) if not secure: return bandit.Issue( severity=bandit.MEDIUM, confidence=bandit.HIGH, text=description )
Example #29
Source File: FstringifyTransformer.py From flynt with MIT License | 4 votes |
def visit_BinOp(self, node): """Convert `ast.BinOp` to `ast.JoinedStr` f-string Currently only if a string literal `ast.Str` is on the left side of the `%` and one of `ast.Tuple`, `ast.Name`, `ast.Dict` is on the right Args: node (ast.BinOp): The node to convert to a f-string Returns ast.JoinedStr (f-string) """ percent_stringify = ( isinstance(node.left, ast.Str) and isinstance(node.op, ast.Mod) and isinstance( node.right, tuple( [ast.Tuple, ast.Dict] + supported_operands), ) ) if percent_stringify: state.percent_candidates += 1 # bail in these edge cases... no_good = ["}", "{"] for ng in no_good: if ng in node.left.s: return node for ch in ast.walk(node.right): # f-string expression part cannot include a backslash if isinstance(ch, ast.Str) and ( any( map( lambda x: x in ch.s, ("\n", "\t", "\r", "'", '"', "%s", "%%"), ) ) or "\\" in ch.s ): return node result_node, str_in_str = transform_binop(node) self.string_in_string = str_in_str self.counter += 1 state.percent_transforms += 1 return result_node return node
Example #30
Source File: _toVHDL.py From myhdl with GNU Lesser General Public License v2.1 | 4 votes |
def inferBinaryOpCast(self, node, left, right, op): ns, os = node.vhd.size, node.vhdOri.size ds = ns - os if ds > 0: if isinstance(left.vhd, vhd_vector) and isinstance(right.vhd, vhd_vector): if isinstance(op, (ast.Add, ast.Sub)): left.vhd.size = ns # in general, resize right also # for a simple name, resizing is not necessary if not isinstance(right, ast.Name): right.vhd.size = ns node.vhdOri.size = ns elif isinstance(op, ast.Mod): right.vhd.size = ns node.vhdOri.size = ns elif isinstance(op, ast.FloorDiv): left.vhd.size = ns node.vhdOri.size = ns elif isinstance(op, ast.Mult): left.vhd.size += ds node.vhdOri.size = ns else: raise AssertionError("unexpected op %s" % op) elif isinstance(left.vhd, vhd_vector) and isinstance(right.vhd, vhd_int): if isinstance(op, (ast.Add, ast.Sub, ast.Mod, ast.FloorDiv)): left.vhd.size = ns node.vhdOri.size = ns elif isinstance(op, ast.Mult): left.vhd.size += ds node.vhdOri.size = 2 * left.vhd.size else: raise AssertionError("unexpected op %s" % op) elif isinstance(left.vhd, vhd_int) and isinstance(right.vhd, vhd_vector): if isinstance(op, (ast.Add, ast.Sub, ast.Mod, ast.FloorDiv)): right.vhd.size = ns node.vhdOri.size = ns elif isinstance(op, ast.Mult): node.vhdOri.size = 2 * right.vhd.size else: raise AssertionError("unexpected op %s" % op) pre, suf = self.inferCast(node.vhd, node.vhdOri) if pre == "": pre, suf = "(", ")" return pre, suf