def test_cast_adr_to_int(): S = Struct('S') p = malloc(S, immortal=True) def fn(n): a = llmemory.cast_ptr_to_adr(p) if n == 2: return llmemory.cast_adr_to_int(a, "emulated") elif n == 4: return llmemory.cast_adr_to_int(a, "symbolic") else: return llmemory.cast_adr_to_int(a, "forced") res = interpret(fn, [2]) assert is_valid_int(res) assert res == cast_ptr_to_int(p) # res = interpret(fn, [4]) assert isinstance(res, llmemory.AddressAsInt) assert llmemory.cast_int_to_adr(res) == llmemory.cast_ptr_to_adr(p) # res = interpret(fn, [6]) assert is_valid_int(res) from pypy.rpython.lltypesystem import rffi assert res == rffi.cast(Signed, p)
def op_int_xor(x, y): # used in computing hashes if isinstance(x, AddressAsInt): x = llmemory.cast_adr_to_int(x.adr) if isinstance(y, AddressAsInt): y = llmemory.cast_adr_to_int(y.adr) assert is_valid_int(x) assert is_valid_int(y) return x ^ y
def __init__(self, lower, upper): self.has_upper = True self.has_lower = True self.upper = upper self.lower = lower # check for unexpected overflows: if not we_are_translated(): assert type(upper) is not long or is_valid_int(upper) assert type(lower) is not long or is_valid_int(lower)
def test_open(self): def f(): ff = posix.open(path, posix.O_RDONLY, 0777) return ff func = self.interpret(f, []) assert is_valid_int(func)
def setup(): for key, value in cpy_signal.__dict__.items(): if (key.startswith('SIG') or key.startswith('CTRL_')) and \ is_valid_int(value) and \ key != 'SIG_DFL' and key != 'SIG_IGN': globals()[key] = value yield key
def int_w(self, w_obj): if isinstance(w_obj, Constant): val = w_obj.value if not is_valid_int(val): raise TypeError("expected integer: " + repr(w_obj)) return val return self.unwrap(w_obj)
def meta_interp( self, function, args, repeat=1, inline=False, trace_limit=sys.maxint, backendopt=None, listcomp=False, **kwds ): # XXX ignored from pypy.jit.metainterp.warmspot import WarmRunnerDesc from pypy.annotation.listdef import s_list_of_strings from pypy.annotation import model as annmodel for arg in args: assert is_valid_int(arg) self.pre_translation_hook() t = self._get_TranslationContext() t.config.translation.type_system = self.type_system # force typesystem-specific options if listcomp: t.config.translation.list_comprehension_operations = True arglist = ", ".join(["int(argv[%d])" % (i + 1) for i in range(len(args))]) if len(args) == 1: arglist += "," arglist = "(%s)" % arglist if repeat != 1: src = py.code.Source( """ def entry_point(argv): args = %s res = function(*args) for k in range(%d - 1): res = function(*args) print res return 0 """ % (arglist, repeat) ) else: src = py.code.Source( """ def entry_point(argv): args = %s res = function(*args) print res return 0 """ % (arglist,) ) exec src.compile() in locals() t.buildannotator().build_types(function, [int] * len(args), main_entry_point=True) t.buildrtyper(type_system=self.type_system).specialize() warmrunnerdesc = WarmRunnerDesc(t, translate_support_code=True, CPUClass=self.CPUClass, **kwds) for jd in warmrunnerdesc.jitdrivers_sd: jd.warmstate.set_param_threshold(3) # for tests jd.warmstate.set_param_trace_eagerness(2) # for tests jd.warmstate.set_param_trace_limit(trace_limit) jd.warmstate.set_param_inlining(inline) jd.warmstate.set_param_enable_opts(ALL_OPTS_NAMES) mixlevelann = warmrunnerdesc.annhelper entry_point_graph = mixlevelann.getgraph(entry_point, [s_list_of_strings], annmodel.SomeInteger()) warmrunnerdesc.finish() self.post_translation_hook() return self._compile_and_run(t, entry_point, entry_point_graph, args)
def op_is_group_member_nonzero(memberoffset): from pypy.rpython.lltypesystem import llgroup if isinstance(memberoffset, llgroup.GroupMemberOffset): return memberoffset.index != 0 else: assert is_valid_int(memberoffset) return memberoffset != 0
def __init__(self, value=0): if not we_are_translated(): if is_valid_int(value): value = int(value) # bool -> int else: assert isinstance(value, Symbolic) self.value = value
def _wrap_not_rpython(self, x): "NOT_RPYTHON" # _____ this code is here to support testing only _____ # we might get there in non-translated versions if 'x' is # a long that fits the correct range. if is_valid_int(x): return self.newint(x) # wrap() of a container works on CPython, but the code is # not RPython. Don't use -- it is kept around mostly for tests. # Use instead newdict(), newlist(), newtuple(). if isinstance(x, dict): items_w = [(self.wrap(k), self.wrap(v)) for (k, v) in x.iteritems()] r = self.newdict() r.initialize_content(items_w) return r if isinstance(x, tuple): wrappeditems = [self.wrap(item) for item in list(x)] return self.newtuple(wrappeditems) if isinstance(x, list): wrappeditems = [self.wrap(item) for item in x] return self.newlist(wrappeditems) # The following cases are even stranger. # Really really only for tests. if type(x) is long: return self.wraplong(x) if isinstance(x, slice): return W_SliceObject(self.wrap(x.start), self.wrap(x.stop), self.wrap(x.step)) if isinstance(x, complex): return W_ComplexObject(x.real, x.imag) if isinstance(x, set): res = W_SetObject(self, self.newlist([self.wrap(item) for item in x])) return res if isinstance(x, frozenset): wrappeditems = [self.wrap(item) for item in x] return W_FrozensetObject(self, wrappeditems) if x is __builtin__.Ellipsis: # '__builtin__.Ellipsis' avoids confusion with special.Ellipsis return self.w_Ellipsis if self.config.objspace.nofaking: raise OperationError( self.w_RuntimeError, self.wrap("nofaking enabled: refusing " "to wrap cpython value %r" % (x, ))) if isinstance(x, type(Exception)) and issubclass(x, Exception): w_result = self.wrap_exception_cls(x) if w_result is not None: return w_result from pypy.objspace.std.fake import fake_object return fake_object(self, x)
def do_read_timestamp(cpu, _): x = read_timestamp() if longlong.is_64_bit: assert is_valid_int(x) # 64-bit return BoxInt(x) else: assert isinstance(x, r_longlong) # 32-bit return BoxFloat(x)
def test_times(self): import py; py.test.skip("llinterp does not like tuple returns") from pypy.rpython.test.test_llinterp import interpret times = interpret(lambda: posix.times(), ()) assert isinstance(times, tuple) assert len(times) == 5 for value in times: assert is_valid_int(value)
def _findall_call_oopspec(): prefix = 'opt_call_stroruni_' result = [] for name in dir(OptString): if name.startswith(prefix): value = getattr(EffectInfo, 'OS_' + name[len(prefix):]) assert is_valid_int(value) and value != 0 result.append((value, getattr(OptString, name))) return unrolling_iterable(result)
def test_times(self): import py py.test.skip("llinterp does not like tuple returns") from pypy.rpython.test.test_llinterp import interpret times = interpret(lambda: posix.times(), ()) assert isinstance(times, tuple) assert len(times) == 5 for value in times: assert is_valid_int(value)
def _wrap_not_rpython(self, x): "NOT_RPYTHON" # _____ this code is here to support testing only _____ # we might get there in non-translated versions if 'x' is # a long that fits the correct range. if is_valid_int(x): return self.newint(x) # wrap() of a container works on CPython, but the code is # not RPython. Don't use -- it is kept around mostly for tests. # Use instead newdict(), newlist(), newtuple(). if isinstance(x, dict): items_w = [(self.wrap(k), self.wrap(v)) for (k, v) in x.iteritems()] r = self.newdict() r.initialize_content(items_w) return r if isinstance(x, tuple): wrappeditems = [self.wrap(item) for item in list(x)] return self.newtuple(wrappeditems) if isinstance(x, list): wrappeditems = [self.wrap(item) for item in x] return self.newlist(wrappeditems) # The following cases are even stranger. # Really really only for tests. if type(x) is long: return self.wraplong(x) if isinstance(x, slice): return W_SliceObject(self.wrap(x.start), self.wrap(x.stop), self.wrap(x.step)) if isinstance(x, complex): return W_ComplexObject(x.real, x.imag) if isinstance(x, set): res = W_SetObject(self, self.newlist([self.wrap(item) for item in x])) return res if isinstance(x, frozenset): wrappeditems = [self.wrap(item) for item in x] return W_FrozensetObject(self, wrappeditems) if x is __builtin__.Ellipsis: # '__builtin__.Ellipsis' avoids confusion with special.Ellipsis return self.w_Ellipsis if self.config.objspace.nofaking: raise OperationError(self.w_RuntimeError, self.wrap("nofaking enabled: refusing " "to wrap cpython value %r" %(x,))) if isinstance(x, type(Exception)) and issubclass(x, Exception): w_result = self.wrap_exception_cls(x) if w_result is not None: return w_result from pypy.objspace.std.fake import fake_object return fake_object(self, x)
def __ge__(self, other): if self is other: return True elif (is_valid_int(other) and other == 0 and self.known_nonneg()): return True else: raise TypeError("Symbolics cannot be compared! (%r, %r)" % (self, other))
def _longshiftresult(self, x): """ calculate an overflowing shift """ n = 1 l = long(x) while 1: ires = x << n lres = l << n if not is_valid_int(ires) or lres != ires: return n n += 1
def __sub__(self, other): if isinstance(other, llmemory.AddressOffset): other = llmemory.raw_malloc_usage(other) if is_valid_int(other): return self.arena.getaddr(self.offset - other) if isinstance(other, fakearenaaddress): if self.arena is not other.arena: raise ArenaError("The two addresses are from different arenas") return self.offset - other.offset return NotImplemented
def test_gen_write_barrier(self): gc_ll_descr = self.gc_ll_descr llop1 = self.llop1 # rewriter = GcRewriterAssembler(gc_ll_descr, None) newops = rewriter.newops v_base = BoxPtr() v_value = BoxPtr() rewriter.gen_write_barrier(v_base, v_value) assert llop1.record == [] assert len(newops) == 1 assert newops[0].getopnum() == rop.COND_CALL_GC_WB assert newops[0].getarg(0) == v_base assert newops[0].getarg(1) == v_value assert newops[0].result is None wbdescr = newops[0].getdescr() assert is_valid_int(wbdescr.jit_wb_if_flag) assert is_valid_int(wbdescr.jit_wb_if_flag_byteofs) assert is_valid_int(wbdescr.jit_wb_if_flag_singlebyte)
def test_cast_adr_to_int(): A = lltype.Array(Address) ptr = lltype.malloc(A, 10, immortal=True) adr = cast_ptr_to_adr(ptr) i = cast_adr_to_int(adr, mode="symbolic") assert isinstance(i, AddressAsInt) assert cast_int_to_adr(i) == adr assert cast_adr_to_int(NULL, mode="symbolic") == 0 assert cast_int_to_adr(0) == NULL # i = cast_adr_to_int(adr, mode="emulated") assert is_valid_int(i) i = cast_adr_to_int(NULL, mode="emulated") assert is_valid_int(i) and i == 0 # i = cast_adr_to_int(adr, mode="forced") assert is_valid_int(i) #assert cast_int_to_adr(i) == adr -- depends on ll2ctypes details i = cast_adr_to_int(NULL, mode="forced") assert is_valid_int(i) and i == 0
def test_random_setitem_delitem(self): w = self.space.wrap s = range(39) w_list = W_ListObject(self.space, map(w, s)) expected = list(s) keys = range(-len(s) - 5, len(s) + 5) choices = keys + [None] * 12 stepchoices = [ None, None, None, 1, 1, -1, -1, 2, -2, len(s) - 1, len(s), len(s) + 1, -len(s) - 1, -len(s), -len(s) + 1 ] for i in range(50): keys.append( slice(random.choice(choices), random.choice(choices), random.choice(stepchoices))) random.shuffle(keys) n = len(s) for key in keys: if random.random() < 0.15: random.shuffle(s) w_list = W_ListObject(self.space, map(w, s)) expected = list(s) try: value = expected[key] except IndexError: self.space.raises_w(self.space.w_IndexError, self.space.setitem, w_list, w(key), w(42)) else: if is_valid_int(value): # non-slicing if random.random() < 0.25: # deleting self.space.delitem(w_list, w(key)) del expected[key] else: self.space.setitem(w_list, w(key), w(n)) expected[key] = n n += 1 else: # slice assignment mode = random.choice(['samesize', 'resize', 'delete']) if mode == 'delete': self.space.delitem(w_list, w(key)) del expected[key] elif mode == 'samesize': newvalue = range(n, n + len(value)) self.space.setitem(w_list, w(key), w(newvalue)) expected[key] = newvalue n += len(newvalue) elif mode == 'resize' and key.step is None: newvalue = range(n, n + random.randrange(0, 20)) self.space.setitem(w_list, w(key), w(newvalue)) expected[key] = newvalue n += len(newvalue) assert self.space.unwrap(w_list) == expected
def test_random_setitem_delitem(self): w = self.space.wrap s = range(39) w_list = W_ListObject(self.space, map(w, s)) expected = list(s) keys = range(-len(s)-5, len(s)+5) choices = keys + [None]*12 stepchoices = [None, None, None, 1, 1, -1, -1, 2, -2, len(s)-1, len(s), len(s)+1, -len(s)-1, -len(s), -len(s)+1] for i in range(50): keys.append(slice(random.choice(choices), random.choice(choices), random.choice(stepchoices))) random.shuffle(keys) n = len(s) for key in keys: if random.random() < 0.15: random.shuffle(s) w_list = W_ListObject(self.space, map(w, s)) expected = list(s) try: value = expected[key] except IndexError: self.space.raises_w(self.space.w_IndexError, self.space.setitem, w_list, w(key), w(42)) else: if is_valid_int(value): # non-slicing if random.random() < 0.25: # deleting self.space.delitem(w_list, w(key)) del expected[key] else: self.space.setitem(w_list, w(key), w(n)) expected[key] = n n += 1 else: # slice assignment mode = random.choice(['samesize', 'resize', 'delete']) if mode == 'delete': self.space.delitem(w_list, w(key)) del expected[key] elif mode == 'samesize': newvalue = range(n, n+len(value)) self.space.setitem(w_list, w(key), w(newvalue)) expected[key] = newvalue n += len(newvalue) elif mode == 'resize' and key.step is None: newvalue = range(n, n+random.randrange(0, 20)) self.space.setitem(w_list, w(key), w(newvalue)) expected[key] = newvalue n += len(newvalue) assert self.space.unwrap(w_list) == expected
def __add__(self, other): if is_valid_int(other): position = self.offset + other elif isinstance(other, llmemory.AddressOffset): # this is really some Do What I Mean logic. There are two # possible meanings: either we want to go past the current # object in the arena, or we want to take the address inside # the current object. Try to guess... bytes = llmemory.raw_malloc_usage(other) if (self.offset in self.arena.objectsizes and bytes < self.arena.objectsizes[self.offset]): # looks like we mean "inside the object" return llmemory.fakeaddress.__add__(self, other) position = self.offset + bytes else: return NotImplemented return self.arena.getaddr(position)
def test_cast(self): def llfn(v): return rffi.cast(rffi.VOIDP, v) res = self.interpret(llfn, [r_ulonglong(0)]) assert res == lltype.nullptr(rffi.VOIDP.TO) # def llfn(v): return rffi.cast(rffi.LONGLONG, v) res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)]) assert res == 0 if r_longlong is not r_int: assert isinstance(res, r_longlong) else: assert is_valid_int(res) # def llfn(v): return rffi.cast(rffi.ULONGLONG, v) res = self.interpret(llfn, [lltype.nullptr(rffi.VOIDP.TO)]) assert res == 0 assert isinstance(res, r_ulonglong)
def interp_eval(code, pc, args, pool): assert is_valid_int(pc) frame = Frame(args, pc) pc = frame.pc while pc < len(code): if jitted: myjitdriver.jit_merge_point(frame=frame, code=code, pc=pc, pool=pool) opcode = ord(code[pc]) pc += 1 stack = frame.stack if opcode == NOP: pass elif opcode == NIL: stack.append(nil) elif opcode == CONS: car, cdr = stack.pop(), stack.pop() stack.append(ConsObj(car, cdr)) elif opcode == CAR: stack.append(stack.pop().car()) elif opcode == CDR: stack.append(stack.pop().cdr()) elif opcode == PUSH: stack.append(IntObj(char2int(code[pc]))) pc += 1 elif opcode == POP: stack.pop() elif opcode == SWAP: a, b = stack.pop(), stack.pop() stack.append(a) stack.append(b) elif opcode == ROLL: #rotate stack top to somewhere below r = char2int(code[pc]) if r < -1: i = len(stack) + r if i < 0: raise IndexError stack.insert(i, stack.pop()) elif r > 1: i = len(stack) - r if i < 0: raise IndexError stack.append(stack.pop(i)) pc += 1 elif opcode == PICK: stack.append(stack[-1 - char2int(code[pc])]) pc += 1 elif opcode == PUT: stack[-1 - char2int(code[pc])] = stack.pop() pc += 1 elif opcode == ADD: a, b = stack.pop(), stack.pop() stack.append(b.add(a)) elif opcode == SUB: a, b = stack.pop(), stack.pop() stack.append(b.sub(a)) elif opcode == MUL: a, b = stack.pop(), stack.pop() stack.append(b.mul(a)) elif opcode == DIV: a, b = stack.pop(), stack.pop() stack.append(b.div(a)) elif opcode == EQ: a, b = stack.pop(), stack.pop() stack.append(IntObj(b.eq(a))) elif opcode == NE: a, b = stack.pop(), stack.pop() stack.append(IntObj(not b.eq(a))) elif opcode == LT: a, b = stack.pop(), stack.pop() stack.append(IntObj(b.lt(a))) elif opcode == LE: a, b = stack.pop(), stack.pop() stack.append(IntObj(not a.lt(b))) elif opcode == GT: a, b = stack.pop(), stack.pop() stack.append(IntObj(a.lt(b))) elif opcode == GE: a, b = stack.pop(), stack.pop() stack.append(IntObj(not b.lt(a))) elif opcode == BR: old_pc = pc pc += char2int(code[pc]) pc += 1 if jitted and old_pc > pc: myjitdriver.can_enter_jit(code=code, pc=pc, frame=frame, pool=pool) elif opcode == BR_COND: cond = stack.pop() if cond.t(): old_pc = pc pc += char2int(code[pc]) + 1 if jitted and old_pc > pc: myjitdriver.can_enter_jit(code=code, pc=pc, frame=frame, pool=pool) else: pc += 1 elif opcode == BR_COND_STK: offset = stack.pop().int_o() if stack.pop().t(): old_pc = pc pc += offset if jitted and old_pc > pc: myjitdriver.can_enter_jit(code=code, pc=pc, frame=frame, pool=pool) elif supports_call and opcode == CALL: offset = char2int(code[pc]) pc += 1 res = interp_eval(code, pc + offset, [zero], pool) if res: stack.append(res) elif opcode == RETURN: break elif opcode == PUSHARG: stack.append(frame.args[0]) elif opcode == PUSHARGN: idx = char2int(code[pc]) pc += 1 stack.append(frame.args[idx]) elif opcode == NEW: idx = char2int(code[pc]) pc += 1 descr = pool.classdescrs[idx] cls = Class.get(descr) stack.append(InstanceObj(cls)) elif opcode == GETATTR: idx = char2int(code[pc]) pc += 1 name = pool.strings[idx] a = stack.pop() stack.append(a.getattr(name)) elif opcode == SETATTR: idx = char2int(code[pc]) pc += 1 name = pool.strings[idx] a, b = stack.pop(), stack.pop() b.setattr(name, a) elif supports_call and opcode == SEND: idx = char2int(code[pc]) pc += 1 num_args = char2int(code[pc]) pc += 1 num_args += 1 # include self name = pool.strings[idx] meth_args = [None] * num_args while num_args > 0: num_args -= 1 meth_args[num_args] = stack.pop() a = meth_args[0] meth_pc = a.send(name) res = interp_eval(code, meth_pc, meth_args, pool) if res: stack.append(res) elif opcode == PRINT: if not we_are_translated(): a = stack.pop() print a.to_string() elif opcode == DUMP: if not we_are_translated(): parts = [] for obj in stack: parts.append(obj.to_string()) print '[%s]' % ', '.join(parts) else: raise RuntimeError("unknown opcode: " + str(opcode)) if frame.stack: return frame.stack[-1] else: return None
def test_identityhash(self): # a "does not crash" kind of test p_const = lltype.malloc(S, immortal=True) self.consider_constant(p_const) # (1) p is in the nursery self.gc.collect() p = self.malloc(S) hash = self.gc.identityhash(p) print hash assert is_valid_int(hash) assert hash == self.gc.identityhash(p) self.stackroots.append(p) for i in range(6): self.gc.collect() assert hash == self.gc.identityhash(self.stackroots[-1]) self.stackroots.pop() # (2) p is an older object p = self.malloc(S) self.stackroots.append(p) self.gc.collect() hash = self.gc.identityhash(self.stackroots[-1]) print hash assert is_valid_int(hash) for i in range(6): self.gc.collect() assert hash == self.gc.identityhash(self.stackroots[-1]) self.stackroots.pop() # (3) p is a gen3 object (for hybrid) p = self.malloc(S) self.stackroots.append(p) for i in range(6): self.gc.collect() hash = self.gc.identityhash(self.stackroots[-1]) print hash assert is_valid_int(hash) for i in range(2): self.gc.collect() assert hash == self.gc.identityhash(self.stackroots[-1]) self.stackroots.pop() # (4) p is a prebuilt object hash = self.gc.identityhash(p_const) print hash assert is_valid_int(hash) assert hash == self.gc.identityhash(p_const) # (5) p is actually moving (for the markcompact gc) p0 = self.malloc(S) self.stackroots.append(p0) p = self.malloc(S) self.stackroots.append(p) hash = self.gc.identityhash(p) self.stackroots.pop(-2) self.gc.collect() # p0 goes away, p shifts left assert hash == self.gc.identityhash(self.stackroots[-1]) self.gc.collect() assert hash == self.gc.identityhash(self.stackroots[-1]) self.stackroots.pop() # (6) ask for the hash of varsized objects, larger and larger for i in range(10): self.gc.collect() p = self.malloc(VAR, i) self.stackroots.append(p) hash = self.gc.identityhash(p) self.gc.collect() assert hash == self.gc.identityhash(self.stackroots[-1]) self.stackroots.pop() # (7) the same, but the objects are dying young for i in range(10): self.gc.collect() p = self.malloc(VAR, i) self.stackroots.append(p) hash1 = self.gc.identityhash(p) hash2 = self.gc.identityhash(p) assert hash1 == hash2 self.stackroots.pop()
def checkgraph(graph): "Check the consistency of a flow graph." if not __debug__: return try: vars_previous_blocks = {} exitblocks = { graph.returnblock: 1, # retval graph.exceptblock: 2 } # exc_cls, exc_value for block, nbargs in exitblocks.items(): assert len(block.inputargs) == nbargs assert block.operations == () assert block.exits == () def definevar(v, only_in_link=None): assert isinstance(v, Variable) assert v not in vars, "duplicate variable %r" % (v, ) assert v not in vars_previous_blocks, ( "variable %r used in more than one block" % (v, )) vars[v] = only_in_link def usevar(v, in_link=None): assert v in vars if in_link is not None: assert vars[v] is None or vars[v] is in_link for block in graph.iterblocks(): assert type(block.exits) is tuple, ( "block.exits is a %s (closeblock() or recloseblock() missing?)" % (type(block.exits).__name__, )) if not block.exits: assert block in exitblocks vars = {} for v in block.inputargs: definevar(v) for op in block.operations: for v in op.args: assert isinstance(v, (Constant, Variable)) if isinstance(v, Variable): usevar(v) else: assert v.value is not last_exception #assert v.value != last_exc_value if op.opname == 'direct_call': assert isinstance(op.args[0], Constant) elif op.opname == 'indirect_call': assert isinstance(op.args[0], Variable) definevar(op.result) exc_links = {} if block.exitswitch is None: assert len(block.exits) <= 1 if block.exits: assert block.exits[0].exitcase is None elif block.exitswitch == Constant(last_exception): assert len(block.operations) >= 1 # check if an exception catch is done on a reasonable # operation assert block.operations[-1].opname not in ("keepalive", "cast_pointer", "same_as") assert len(block.exits) >= 2 assert block.exits[0].exitcase is None for link in block.exits[1:]: assert issubclass(link.exitcase, py.builtin.BaseException) exc_links[link] = True else: assert isinstance(block.exitswitch, Variable) assert block.exitswitch in vars if (len(block.exits) == 2 and block.exits[0].exitcase is False and block.exits[1].exitcase is True): # a boolean switch pass else: # a multiple-cases switch (or else the False and True # branches are in the wrong order) assert len(block.exits) >= 1 cases = [link.exitcase for link in block.exits] has_default = cases[-1] == 'default' for n in cases[:len(cases) - has_default]: if is_valid_int(n): continue if isinstance(n, (r_longlong, r_ulonglong, r_uint)): continue if isinstance(n, (str, unicode)) and len(n) == 1: continue assert n != 'default', ( "'default' branch of a switch is not the last exit" ) assert n is not None, ( "exitswitch Variable followed by a None exitcase") raise AssertionError( "switch on a non-primitive value %r" % (n, )) allexitcases = {} for link in block.exits: assert len(link.args) == len(link.target.inputargs) assert link.prevblock is block exc_link = link in exc_links if exc_link: for v in [link.last_exception, link.last_exc_value]: assert isinstance(v, (Variable, Constant)) if isinstance(v, Variable): definevar(v, only_in_link=link) else: assert link.last_exception is None assert link.last_exc_value is None for v in link.args: assert isinstance(v, (Constant, Variable)) if isinstance(v, Variable): usevar(v, in_link=link) if exc_link: assert v != block.operations[-1].result #else: # if not exc_link: # assert v.value is not last_exception # #assert v.value != last_exc_value allexitcases[link.exitcase] = True assert len(allexitcases) == len(block.exits) vars_previous_blocks.update(vars) except AssertionError, e: # hack for debug tools only #graph.show() # <== ENABLE THIS TO SEE THE BROKEN GRAPH if block and not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise
def header_forwarded(self, addr): # like header(), but asserts that we have a forwarding header hdr = MovingGCBase.header(self, addr) if not we_are_translated(): assert is_valid_int(hdr.tid) return hdr
def __init__(w_self, intval): assert is_valid_int(intval) w_self.intval = intval
def __init__(w_self, intval, is_symbolic=False, symval=''): assert is_valid_int(intval) w_self.intval = intval w_self.__is_symbolic = is_symbolic w_self.symval = symval
def unerase_int(y): assert y._identity is _identity_for_ints assert is_valid_int(y._x) return y._x
def test_functions(): xll = longlong.getfloatstorage(3.5) assert longlong.getrealfloat(xll) == 3.5 assert is_valid_int(longlong.gethash(xll))
def check_regular_int(x): """Give a translation-time error if 'x' is not a plain int (e.g. if it's a r_longlong or an r_uint). """ assert is_valid_int(x) return x
def __init__(self, args, pc): assert is_valid_int(pc) self.args = args self.pc = pc self.stack = []
def interp_eval(code, pc, args, pool): assert is_valid_int(pc) frame = Frame(args, pc) pc = frame.pc while pc < len(code): if jitted: myjitdriver.jit_merge_point(frame=frame, code=code, pc=pc, pool=pool) opcode = ord(code[pc]) pc += 1 stack = frame.stack if opcode == NOP: pass elif opcode == NIL: stack.append(nil) elif opcode == CONS: car, cdr = stack.pop(), stack.pop() stack.append(ConsObj(car, cdr)) elif opcode == CAR: stack.append(stack.pop().car()) elif opcode == CDR: stack.append(stack.pop().cdr()) elif opcode == PUSH: stack.append(IntObj(char2int(code[pc]))) pc += 1 elif opcode == POP: stack.pop() elif opcode == SWAP: a, b = stack.pop(), stack.pop() stack.append(a) stack.append(b) elif opcode == ROLL: #rotate stack top to somewhere below r = char2int(code[pc]) if r < -1: i = len(stack) + r if i < 0: raise IndexError stack.insert( i, stack.pop() ) elif r > 1: i = len(stack) - r if i < 0: raise IndexError stack.append(stack.pop(i)) pc += 1 elif opcode == PICK: stack.append( stack[-1 - char2int(code[pc])] ) pc += 1 elif opcode == PUT: stack[-1 - char2int(code[pc])] = stack.pop() pc += 1 elif opcode == ADD: a, b = stack.pop(), stack.pop() stack.append(b.add(a)) elif opcode == SUB: a, b = stack.pop(), stack.pop() stack.append(b.sub(a)) elif opcode == MUL: a, b = stack.pop(), stack.pop() stack.append(b.mul(a)) elif opcode == DIV: a, b = stack.pop(), stack.pop() stack.append(b.div(a)) elif opcode == EQ: a, b = stack.pop(), stack.pop() stack.append(IntObj(b.eq(a))) elif opcode == NE: a, b = stack.pop(), stack.pop() stack.append(IntObj(not b.eq(a))) elif opcode == LT: a, b = stack.pop(), stack.pop() stack.append(IntObj(b.lt(a))) elif opcode == LE: a, b = stack.pop(), stack.pop() stack.append(IntObj(not a.lt(b))) elif opcode == GT: a, b = stack.pop(), stack.pop() stack.append(IntObj(a.lt(b))) elif opcode == GE: a, b = stack.pop(), stack.pop() stack.append(IntObj(not b.lt(a))) elif opcode == BR: old_pc = pc pc += char2int(code[pc]) pc += 1 if jitted and old_pc > pc: myjitdriver.can_enter_jit(code=code, pc=pc, frame=frame, pool=pool) elif opcode == BR_COND: cond = stack.pop() if cond.t(): old_pc = pc pc += char2int(code[pc]) + 1 if jitted and old_pc > pc: myjitdriver.can_enter_jit(code=code, pc=pc, frame=frame, pool=pool) else: pc += 1 elif opcode == BR_COND_STK: offset = stack.pop().int_o() if stack.pop().t(): old_pc = pc pc += offset if jitted and old_pc > pc: myjitdriver.can_enter_jit(code=code, pc=pc, frame=frame, pool=pool) elif supports_call and opcode == CALL: offset = char2int(code[pc]) pc += 1 res = interp_eval(code, pc + offset, [zero], pool) if res: stack.append(res) elif opcode == RETURN: break elif opcode == PUSHARG: stack.append(frame.args[0]) elif opcode == PUSHARGN: idx = char2int(code[pc]) pc += 1 stack.append(frame.args[idx]) elif opcode == NEW: idx = char2int(code[pc]) pc += 1 descr = pool.classdescrs[idx] cls = Class.get(descr) stack.append(InstanceObj(cls)) elif opcode == GETATTR: idx = char2int(code[pc]) pc += 1 name = pool.strings[idx] a = stack.pop() stack.append(a.getattr(name)) elif opcode == SETATTR: idx = char2int(code[pc]) pc += 1 name = pool.strings[idx] a, b = stack.pop(), stack.pop() b.setattr(name, a) elif supports_call and opcode == SEND: idx = char2int(code[pc]) pc += 1 num_args = char2int(code[pc]) pc += 1 num_args += 1 # include self name = pool.strings[idx] meth_args = [None] * num_args while num_args > 0: num_args -= 1 meth_args[num_args] = stack.pop() a = meth_args[0] meth_pc = a.send(name) res = interp_eval(code, meth_pc, meth_args, pool) if res: stack.append(res) elif opcode == PRINT: if not we_are_translated(): a = stack.pop() print a.to_string() elif opcode == DUMP: if not we_are_translated(): parts = [] for obj in stack: parts.append(obj.to_string()) print '[%s]' % ', '.join(parts) else: raise RuntimeError("unknown opcode: " + str(opcode)) if frame.stack: return frame.stack[-1] else: return None
def __mul__(self, other): if not is_valid_int(other): return NotImplemented return ItemOffset(self.TYPE, self.repeat * other)
def erase_int(x): assert is_valid_int(x) res = 2 * x + 1 if res > sys.maxint or res < -sys.maxint - 1: raise OverflowError return Erased(x, _identity_for_ints)
def checkgraph(graph): "Check the consistency of a flow graph." if not __debug__: return try: vars_previous_blocks = {} exitblocks = {graph.returnblock: 1, # retval graph.exceptblock: 2} # exc_cls, exc_value for block, nbargs in exitblocks.items(): assert len(block.inputargs) == nbargs assert block.operations == () assert block.exits == () def definevar(v, only_in_link=None): assert isinstance(v, Variable) assert v not in vars, "duplicate variable %r" % (v,) assert v not in vars_previous_blocks, ( "variable %r used in more than one block" % (v,)) vars[v] = only_in_link def usevar(v, in_link=None): assert v in vars if in_link is not None: assert vars[v] is None or vars[v] is in_link for block in graph.iterblocks(): assert type(block.exits) is tuple, ( "block.exits is a %s (closeblock() or recloseblock() missing?)" % (type(block.exits).__name__,)) if not block.exits: assert block in exitblocks vars = {} for v in block.inputargs: definevar(v) for op in block.operations: for v in op.args: assert isinstance(v, (Constant, Variable)) if isinstance(v, Variable): usevar(v) else: assert v.value is not last_exception #assert v.value != last_exc_value if op.opname == 'direct_call': assert isinstance(op.args[0], Constant) elif op.opname == 'indirect_call': assert isinstance(op.args[0], Variable) definevar(op.result) exc_links = {} if block.exitswitch is None: assert len(block.exits) <= 1 if block.exits: assert block.exits[0].exitcase is None elif block.exitswitch == Constant(last_exception): assert len(block.operations) >= 1 # check if an exception catch is done on a reasonable # operation assert block.operations[-1].opname not in ("keepalive", "cast_pointer", "same_as") assert len(block.exits) >= 2 assert block.exits[0].exitcase is None for link in block.exits[1:]: assert issubclass(link.exitcase, py.builtin.BaseException) exc_links[link] = True else: assert isinstance(block.exitswitch, Variable) assert block.exitswitch in vars if (len(block.exits) == 2 and block.exits[0].exitcase is False and block.exits[1].exitcase is True): # a boolean switch pass else: # a multiple-cases switch (or else the False and True # branches are in the wrong order) assert len(block.exits) >= 1 cases = [link.exitcase for link in block.exits] has_default = cases[-1] == 'default' for n in cases[:len(cases)-has_default]: if is_valid_int(n): continue if isinstance(n, (r_longlong, r_ulonglong, r_uint)): continue if isinstance(n, (str, unicode)) and len(n) == 1: continue assert n != 'default', ( "'default' branch of a switch is not the last exit" ) assert n is not None, ( "exitswitch Variable followed by a None exitcase") raise AssertionError( "switch on a non-primitive value %r" % (n,)) allexitcases = {} for link in block.exits: assert len(link.args) == len(link.target.inputargs) assert link.prevblock is block exc_link = link in exc_links if exc_link: for v in [link.last_exception, link.last_exc_value]: assert isinstance(v, (Variable, Constant)) if isinstance(v, Variable): definevar(v, only_in_link=link) else: assert link.last_exception is None assert link.last_exc_value is None for v in link.args: assert isinstance(v, (Constant, Variable)) if isinstance(v, Variable): usevar(v, in_link=link) if exc_link: assert v != block.operations[-1].result #else: # if not exc_link: # assert v.value is not last_exception # #assert v.value != last_exc_value allexitcases[link.exitcase] = True assert len(allexitcases) == len(block.exits) vars_previous_blocks.update(vars) except AssertionError, e: # hack for debug tools only #graph.show() # <== ENABLE THIS TO SEE THE BROKEN GRAPH if block and not hasattr(e, '__annotator_block'): setattr(e, '__annotator_block', block) raise