rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
x = complex(x)
|
x = _to_complex(x)
|
def polar(x): x = complex(x) phi = math.atan2(x.imag, x.real) r = abs(x) return r, phi
|
r, phi = complex(r), complex(phi)
|
def rect(r, phi): r, phi = complex(r), complex(phi) return complex(r * math.cos(phi), r * math.sin(phi))
|
|
x = _to_complex(x)
|
def acos(x): """acos(x) Return the arc cosine of x.""" return -(_prodi(log((x+(_i*sqrt((_one-(x*x))))))))
|
|
x = _to_complex(x)
|
def asin(x): """asin(x) Return the arc sine of x.""" # -i * log[(sqrt(1-x**2) + i*x] squared = x*x sqrt_1_minus_x_sq = sqrt(_one-squared) return -(_prodi(log((sqrt_1_minus_x_sq+_prodi(x)))))
|
|
x = _to_complex(x)
|
def asinh(x): """asinh(x) Return the hyperbolic arc sine of x.""" z = log((_sqrt_half * (sqrt(x+_i)+sqrt((x-_i))) )) return z+z
|
|
x = _to_complex(x)
|
def atan(x): """atan(x) Return the arc tangent of x.""" return _halfi*log(((_i+x)/(_i-x)))
|
|
x = _to_complex(x)
|
def atanh(x): """atanh(x) Return the hyperbolic arc tangent of x.""" return _half*log((_one+x)/(_one-x))
|
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def cos(x): """cos(x) Return the cosine of x.""" x = complex(x, 0) real = math.cos(x.real) * math.cosh(x.imag) imag = -math.sin(x.real) * math.sinh(x.imag) return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def cosh(x): """cosh(x) Return the hyperbolic cosine of x.""" x = complex(x, 0) real = math.cos(x.imag) * math.cosh(x.real) imag = math.sin(x.imag) * math.sinh(x.real) return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def exp(x): """exp(x) Return the exponential value e**x.""" x = complex(x, 0) l = math.exp(x.real) real = l * math.cos(x.imag) imag = l * math.sin(x.imag) return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def log(x, base=None): """log(x) Return the natural logarithm of x.""" if base is not None: return log(x) / log(base) x = complex(x, 0) l = math.hypot(x.real,x.imag) imag = math.atan2(x.imag, x.real) real = math.log(l) return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def log10(x): """log10(x) Return the base-10 logarithm of x.""" x = complex(x, 0) l = math.hypot(x.real, x.imag) imag = math.atan2(x.imag, x.real)/math.log(10.) real = math.log10(l) return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def sin(x): """sin(x) Return the sine of x.""" x = complex(x, 0) real = math.sin(x.real) * math.cosh(x.imag) imag = math.cos(x.real) * math.sinh(x.imag) return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def sinh(x): """sinh(x) Return the hyperbolic sine of x.""" x = complex(x, 0) real = math.cos(x.imag) * math.sinh(x.real) imag = math.sin(x.imag) * math.cosh(x.real) return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def sqrt(x): """sqrt(x) Return the square root of x.""" x = complex(x, 0) if x.real == 0. and x.imag == 0.: real, imag = 0, 0 else: s = math.sqrt(0.5*(math.fabs(x.real) + math.hypot(x.real,x.imag))) d = 0.5*x.imag/s if x.real > 0.: real = s imag = d elif x.imag >= 0.: real = d imag = s else: real = -d imag = -s return complex(real, imag)
|
x = complex(x, 0)
|
x = _to_complex(x)
|
def tan(x): """tan(x) Return the tangent of x.""" x = complex(x, 0) sr = math.sin(x.real) cr = math.cos(x.real) shi = math.sinh(x.imag) chi = math.cosh(x.imag) rs = sr * chi is_ = cr * shi rc = cr * chi ic = -sr * shi d = rc*rc + ic * ic real = (rs*rc + is_*ic) / d imag = (is_*rc - rs*ic) / d return complex(real, imag)
|
cc = 'gcc'
|
try: cc = os.environ['CC'] except KeyError: cc = 'gcc'
|
def __init__(self, cc=None): if cc is None: cc = 'gcc' self.cc = cc
|
if generic_cpy_call(space, pto.c_tp_init, w_obj, w_args, w_kw) < 0:
|
res = generic_cpy_call(space, pto.c_tp_init, w_obj, w_args, w_kw) if rffi.cast(lltype.Signed, res) < 0:
|
def c_type_descr__call__(space, w_type, __args__): if not isinstance(w_type, W_PyCTypeObject): # XXX is this possible? w_type = _precheck_for_new(space, w_type) return call__Type(space, w_type, __args__) pyo = make_ref(space, w_type) pto = rffi.cast(PyTypeObjectPtr, pyo) tp_new = pto.c_tp_new try: if not tp_new: raise operationerrfmt(space.w_TypeError, "cannot create '%s' instances", w_type.getname(space, '?')) args_w, kw_w = __args__.unpack() w_args = space.newtuple(args_w) w_kw = space.newdict() for key, w_obj in kw_w.items(): space.setitem(w_kw, space.wrap(key), w_obj) w_obj = generic_cpy_call(space, tp_new, pto, w_args, w_kw) finally: Py_DecRef(space, pyo) # If the returned object is not an instance of type, # it won't be initialized. w_obj_type = space.type(w_obj) if not (space.is_w(w_obj_type, w_type) or space.is_true(space.issubtype(w_obj_type, w_type))): return w_obj # call tp_init pyo = make_ref(space, w_obj_type) pto = rffi.cast(PyTypeObjectPtr, pyo) try: if pto.c_tp_init: if generic_cpy_call(space, pto.c_tp_init, w_obj, w_args, w_kw) < 0: state = space.fromcache(State) state.check_and_raise_exception() finally: Py_DecRef(space, pyo) return w_obj
|
co = compile(mod, "<string>", "exec")
|
co = compile(mod, "<string>", "eval")
|
def test_simple_sums(self): ast = self.ast mod = self.get_ast("x = 4 + 5") expr = mod.body[0].value assert isinstance(expr, ast.BinOp) assert isinstance(expr.op, ast.Add) expr.op = ast.Sub() assert isinstance(expr.op, ast.Sub) co = compile(mod, "<example>", "exec") ns = {} exec co in ns assert ns["x"] == -1 mod = self.get_ast("4 < 5 < 6", "eval") assert isinstance(mod.body, ast.Compare) assert len(mod.body.ops) == 2 for op in mod.body.ops: assert isinstance(op, ast.Lt) mod.body.ops[0] = ast.Gt() co = compile(mod, "<string>", "exec") assert not eval(co)
|
self.pendingcr = (flag & 1)
|
self.pendingcr = bool(flag & 1)
|
def setstate_w(self, space, w_state): w_buffer, w_flag = space.unpackiterable(w_state, 2) flag = space.r_longlong_w(w_flag) self.pendingcr = (flag & 1) flag >>= 1
|
refs = [node.getAttribute('href') for node in dom.getElementsByTagName('a')]
|
refs = [node.getAttribute('href') for node in dom.getElementsByTagName('a') if 'pypy' in node.getAttribute('href')]
|
def browse_nightly(branch, baseurl=BASEURL, override_xml=None): if override_xml is None: url = baseurl + branch + '/' xml = urllib2.urlopen(url).read() else: xml = override_xml dom = minidom.parseString(xml) refs = [node.getAttribute('href') for node in dom.getElementsByTagName('a')] # all refs are of form: pypy-{type}-{revision}-{platform}.tar.bz2 r = re.compile('pypy-c-([\w\d]+)-(\d+)-([\w\d]+).tar.bz2$') d = {} for ref in refs: kind, rev, platform = r.match(ref).groups() rev = int(rev) try: lastrev, _ = d[(kind, platform)] except KeyError: lastrev = -1 if rev > lastrev: d[(kind, platform)] = rev, ref return d
|
w_type, w_value, w_tb ) if set_sys_last_vars: w_dict = space.sys.getdict() w_dict.setitem_str("last_type", w_type) w_dict.setitem_str("last_value", w_value) w_dict.setitem_str("last_traceback", w_tb)
|
w_type, w_value, w_tb)
|
def PyErr_PrintEx(space, set_sys_last_vars): """Print a standard traceback to sys.stderr and clear the error indicator. Call this function only when the error indicator is set. (Otherwise it will cause a fatal error!) If set_sys_last_vars is nonzero, the variables sys.last_type, sys.last_value and sys.last_traceback will be set to the type, value and traceback of the printed exception, respectively.""" if not PyErr_Occurred(space): PyErr_BadInternalCall(space) state = space.fromcache(State) operror = state.clear_exception() w_type = operror.w_type w_value = operror.get_w_value(space) w_tb = space.wrap(operror.application_traceback) space.call_function(space.sys.get("excepthook"), w_type, w_value, w_tb ) if set_sys_last_vars: w_dict = space.sys.getdict() w_dict.setitem_str("last_type", w_type) w_dict.setitem_str("last_value", w_value) w_dict.setitem_str("last_traceback", w_tb)
|
if op >= opcode.HAVE_ARGUMENT:
|
if op >= HAVE_ARGUMENT:
|
def _dispatch_loop(self): code = self.code.co_code instr_index = 0 while True: jitdriver.jit_merge_point(code=code, instr_index=instr_index, frame=self) self.stack_depth = hint(self.stack_depth, promote=True) op = ord(code[instr_index]) instr_index += 1 if op >= opcode.HAVE_ARGUMENT: low = ord(code[instr_index]) hi = ord(code[instr_index + 1]) oparg = (hi << 8) | low instr_index += 2 else: oparg = 0 if we_are_translated(): for opdesc in unrolling_opcode_descs: if op == opdesc.index: meth = getattr(self, opdesc.methodname) instr_index = meth(oparg, instr_index, code) break else: raise MissingOpcode(op) else: meth = getattr(self, opcode_method_names[op]) instr_index = meth(oparg, instr_index, code)
|
assert len(self.loops) < 10
|
assert len(self.loops) == 2 op, = self.get_by_bytecode("CALL_FUNCTION_KW") assert len(op.get_opnames("guard")) <= 10
|
def main(x): s = 0 d = {} for i in range(x): s += g(**d) d[str(i)] = i if i % 100 == 99: d = {} return s
|
''', 37,
|
''', 39,
|
def main(n): i = 2 l = [] while i < n: i += 1 l.append(i) return i, len(l)
|
assert len(bytecode.get_opnames("guard")) == 1
|
assert len(bytecode.get_opnames("guard")) == 2
|
def main(n): i = 2 l = [] while i < n: i += 1 l.append(i) return i, len(l)
|
if generic_cpy_call(space, func_target, w_self, w_name, w_value) < 0:
|
res = generic_cpy_call(space, func_target, w_self, w_name, w_value) if rffi.cast(lltype.Signed, res) == -1:
|
def wrap_setattr(space, w_self, w_args, func): func_target = rffi.cast(setattrofunc, func) check_num_args(space, w_args, 2) w_name, w_value = space.fixedview(w_args) # XXX "Carlo Verre hack"? if generic_cpy_call(space, func_target, w_self, w_name, w_value) < 0: space.fromcache(State).check_and_raise_exception(always=True) return space.w_None
|
return space.w_None
|
def wrap_setattr(space, w_self, w_args, func): func_target = rffi.cast(setattrofunc, func) check_num_args(space, w_args, 2) w_name, w_value = space.fixedview(w_args) # XXX "Carlo Verre hack"? if generic_cpy_call(space, func_target, w_self, w_name, w_value) < 0: space.fromcache(State).check_and_raise_exception(always=True) return space.w_None
|
|
if generic_cpy_call(space, func_target, w_self, w_name, None) < 0:
|
res = generic_cpy_call(space, func_target, w_self, w_name, None) if rffi.cast(lltype.Signed, res) == -1:
|
def wrap_delattr(space, w_self, w_args, func): func_target = rffi.cast(setattrofunc, func) check_num_args(space, w_args, 1) w_name, = space.fixedview(w_args) # XXX "Carlo Verre hack"? if generic_cpy_call(space, func_target, w_self, w_name, None) < 0: space.fromcache(State).check_and_raise_exception(always=True) return space.w_None
|
return space.w_None
|
def wrap_delattr(space, w_self, w_args, func): func_target = rffi.cast(setattrofunc, func) check_num_args(space, w_args, 1) w_name, = space.fixedview(w_args) # XXX "Carlo Verre hack"? if generic_cpy_call(space, func_target, w_self, w_name, None) < 0: space.fromcache(State).check_and_raise_exception(always=True) return space.w_None
|
|
wrap_encoder.unwrap_spec = [ObjSpace, unicode, str]
|
wrap_encoder.unwrap_spec = [ObjSpace, unicode, 'str_or_None']
|
def wrap_encoder(space, uni, errors="strict"): state = space.fromcache(CodecState) func = getattr(runicode, rname) result = func(uni, len(uni), errors, state.encode_error_handler) return space.newtuple([space.wrap(result), space.wrap(len(uni))])
|
wrap_decoder.unwrap_spec = [ObjSpace, 'bufferstr', str, W_Root]
|
wrap_decoder.unwrap_spec = [ObjSpace, 'bufferstr', 'str_or_None', W_Root]
|
def wrap_decoder(space, string, errors="strict", w_final=False): final = space.is_true(w_final) state = space.fromcache(CodecState) func = getattr(runicode, rname) result, consumed = func(string, len(string), errors, final, state.decode_error_handler) return space.newtuple([space.wrap(result), space.wrap(consumed)])
|
"fields. Found %r" % seen.keys())
|
"fields. Found %r" % list(seen))
|
def __init__(self, cpu, jd): self.cpu = cpu self.jitdriver_sd = jd # XXX for now, only supports a single instance, # but several fields of it can be green seen = set() for name in jd.jitdriver.greens: if '.' in name: objname, fieldname = name.split('.') seen.add(objname) assert len(seen) == 1, ( "Current limitation: you can only give one instance with green " "fields. Found %r" % seen.keys()) self.red_index = jd.jitdriver.reds.index(objname) # # a list of (GTYPE, fieldname) self.green_fields = jd.jitdriver.ll_greenfields.values() self.green_field_descrs = [cpu.fielddescrof(GTYPE, fieldname) for GTYPE, fieldname in self.green_fields]
|
print "AFA REPR", (w_complex, w_complex.realval, w_complex.imagval)
|
def repr__Complex(space, w_complex): print "AFA REPR", (w_complex, w_complex.realval, w_complex.imagval) if w_complex.realval == 0 and math.copysign(1., w_complex.realval) == 1.: return space.wrap(repr_format(w_complex.imagval) + 'j') sign = (math.copysign(1., w_complex.imagval) == 1.) and '+' or '' return space.wrap('(' + repr_format(w_complex.realval) + sign + repr_format(w_complex.imagval) + 'j)')
|
|
flags |= os.O_CREAT | os.O_TRUNC
|
flags |= O_CREAT | O_TRUNC
|
def decode_mode(space, mode): flags = 0 rwa = False readable = False writable = False append = False plus = False for s in mode: if s == 'r': if rwa: _bad_mode(space) rwa = True readable = True elif s == 'w': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT | os.O_TRUNC elif s == 'a': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT append = True elif s == 'b': pass elif s == '+': if plus: _bad_mode(space) readable = writable = True plus = True else: raise OperationError(space.w_ValueError, space.wrap( "invalid mode: %s" % (mode,))) if not rwa: _bad_mode(space) if readable and writable: flags |= os.O_RDWR elif readable: flags |= os.O_RDONLY else: flags |= os.O_WRONLY if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND return readable, writable, flags
|
flags |= os.O_CREAT
|
flags |= O_CREAT
|
def decode_mode(space, mode): flags = 0 rwa = False readable = False writable = False append = False plus = False for s in mode: if s == 'r': if rwa: _bad_mode(space) rwa = True readable = True elif s == 'w': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT | os.O_TRUNC elif s == 'a': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT append = True elif s == 'b': pass elif s == '+': if plus: _bad_mode(space) readable = writable = True plus = True else: raise OperationError(space.w_ValueError, space.wrap( "invalid mode: %s" % (mode,))) if not rwa: _bad_mode(space) if readable and writable: flags |= os.O_RDWR elif readable: flags |= os.O_RDONLY else: flags |= os.O_WRONLY if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND return readable, writable, flags
|
flags |= os.O_RDWR
|
flags |= O_RDWR
|
def decode_mode(space, mode): flags = 0 rwa = False readable = False writable = False append = False plus = False for s in mode: if s == 'r': if rwa: _bad_mode(space) rwa = True readable = True elif s == 'w': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT | os.O_TRUNC elif s == 'a': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT append = True elif s == 'b': pass elif s == '+': if plus: _bad_mode(space) readable = writable = True plus = True else: raise OperationError(space.w_ValueError, space.wrap( "invalid mode: %s" % (mode,))) if not rwa: _bad_mode(space) if readable and writable: flags |= os.O_RDWR elif readable: flags |= os.O_RDONLY else: flags |= os.O_WRONLY if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND return readable, writable, flags
|
flags |= os.O_RDONLY
|
flags |= O_RDONLY
|
def decode_mode(space, mode): flags = 0 rwa = False readable = False writable = False append = False plus = False for s in mode: if s == 'r': if rwa: _bad_mode(space) rwa = True readable = True elif s == 'w': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT | os.O_TRUNC elif s == 'a': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT append = True elif s == 'b': pass elif s == '+': if plus: _bad_mode(space) readable = writable = True plus = True else: raise OperationError(space.w_ValueError, space.wrap( "invalid mode: %s" % (mode,))) if not rwa: _bad_mode(space) if readable and writable: flags |= os.O_RDWR elif readable: flags |= os.O_RDONLY else: flags |= os.O_WRONLY if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND return readable, writable, flags
|
flags |= os.O_WRONLY
|
flags |= O_WRONLY
|
def decode_mode(space, mode): flags = 0 rwa = False readable = False writable = False append = False plus = False for s in mode: if s == 'r': if rwa: _bad_mode(space) rwa = True readable = True elif s == 'w': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT | os.O_TRUNC elif s == 'a': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT append = True elif s == 'b': pass elif s == '+': if plus: _bad_mode(space) readable = writable = True plus = True else: raise OperationError(space.w_ValueError, space.wrap( "invalid mode: %s" % (mode,))) if not rwa: _bad_mode(space) if readable and writable: flags |= os.O_RDWR elif readable: flags |= os.O_RDONLY else: flags |= os.O_WRONLY if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND return readable, writable, flags
|
if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY
|
flags |= O_BINARY
|
def decode_mode(space, mode): flags = 0 rwa = False readable = False writable = False append = False plus = False for s in mode: if s == 'r': if rwa: _bad_mode(space) rwa = True readable = True elif s == 'w': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT | os.O_TRUNC elif s == 'a': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT append = True elif s == 'b': pass elif s == '+': if plus: _bad_mode(space) readable = writable = True plus = True else: raise OperationError(space.w_ValueError, space.wrap( "invalid mode: %s" % (mode,))) if not rwa: _bad_mode(space) if readable and writable: flags |= os.O_RDWR elif readable: flags |= os.O_RDONLY else: flags |= os.O_WRONLY if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND return readable, writable, flags
|
if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND
|
if append: flags |= O_APPEND
|
def decode_mode(space, mode): flags = 0 rwa = False readable = False writable = False append = False plus = False for s in mode: if s == 'r': if rwa: _bad_mode(space) rwa = True readable = True elif s == 'w': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT | os.O_TRUNC elif s == 'a': if rwa: _bad_mode(space) rwa = True writable = True flags |= os.O_CREAT append = True elif s == 'b': pass elif s == '+': if plus: _bad_mode(space) readable = writable = True plus = True else: raise OperationError(space.w_ValueError, space.wrap( "invalid mode: %s" % (mode,))) if not rwa: _bad_mode(space) if readable and writable: flags |= os.O_RDWR elif readable: flags |= os.O_RDONLY else: flags |= os.O_WRONLY if hasattr(os, 'O_BINARY'): flags |= os.O_BINARY if hasattr(os, 'O_APPEND') and append: flags |= os.O_APPEND return readable, writable, flags
|
def _normalizedcontainer(self): return self._ptr._obj
|
def _normalizedcontainer(self, check=True): return self._ptr._getobj(check=check)._normalizedcontainer(check=check) def _was_freed(self): return self._ptr._was_freed()
|
def _normalizedcontainer(self): return self._ptr._obj
|
self.mc.SETNE(lower_byte(resloc)) self.mc.MOVZX(resloc, lower_byte(resloc))
|
rl = resloc.lowest8bits() rh = resloc.higher8bits() self.mc.SETNE(rl) self.mc.SETP(rh) self.mc.OR(rl, rh) self.mc.MOVZX(resloc, rl)
|
def genop_float_is_true(self, op, arglocs, resloc): loc0, loc1 = arglocs self.mc.XORPD(loc0, loc0) self.mc.UCOMISD(loc0, loc1) self.mc.SETNE(lower_byte(resloc)) self.mc.MOVZX(resloc, lower_byte(resloc))
|
assert ops[0].get_opnames() == ["getfield_gc", "getarrayitem_gc",
|
assert ops[0].get_opnames() == ["getfield_gc",
|
def main(n): i = 0 a = A(1) while i < n: x = a.f(i) i = a.f(x) return i
|
return cls(*_time.strptime(date_string, format)[0:6])
|
struct, micros = _time.strptime(date_string, format) return cls(*(struct[0:6] + (micros,)))
|
def strptime(cls, date_string, format): 'string, format -> new datetime parsed from a string (like time.strptime()).' return cls(*_time.strptime(date_string, format)[0:6])
|
for cls in inspect.getmro(superclass): all_fields += getattr(cls, '_fields_', []) all_fields += _fields_
|
for cls in reversed(inspect.getmro(superclass)): all_fields.extend(getattr(cls, '_fields_', [])) all_fields.extend(_fields_)
|
def names_and_fields(_fields_, superclass, zero_offset=False, anon=None, is_union=False): # _fields_: list of (name, ctype, [optional_bitfield]) if isinstance(_fields_, tuple): _fields_ = list(_fields_) for f in _fields_: tp = f[1] if not isinstance(tp, _CDataMeta): raise TypeError("Expected CData subclass, got %s" % (tp,)) if isinstance(tp, StructOrUnionMeta): tp._make_final() import ctypes all_fields = [] for cls in inspect.getmro(superclass): all_fields += getattr(cls, '_fields_', []) all_fields += _fields_ names = [f[0] for f in all_fields] rawfields = [(f[0], f[1]._ffishape) for f in all_fields] if not zero_offset: _, _, pos = size_alignment_pos(all_fields, is_union) else: pos = [0] * len(all_fields) fields = {} for i, field in enumerate(all_fields): name = field[0] ctype = field[1] fields[name] = Field(name, pos[i], ctypes.sizeof(ctype), ctype, i) if anon: resnames = [] for i, (name, value) in enumerate(all_fields): if name in anon: for subname in value._names: resnames.append(subname) relpos = pos[i] + value._fieldtypes[subname].offset subvalue = value._fieldtypes[subname].ctype fields[subname] = Field(subname, relpos, ctypes.sizeof(subvalue), subvalue, i) # XXX we never set rawfields here, let's wait for a test else: resnames.append(name) names = resnames return names, rawfields, fields
|
assert len(parts) == 7
|
assert len(parts) == 6
|
def test_find_functions_darwin(): source = """\
|
assert parts[3] == (True, lines[11:13]) assert parts[4] == (False, lines[13:18]) assert parts[5] == (True, lines[18:20]) assert parts[6] == (False, lines[20:])
|
assert parts[3] == (True, lines[11:18]) assert parts[4] == (True, lines[18:20]) assert parts[5] == (False, lines[20:])
|
def test_find_functions_darwin(): source = """\
|
self.is_of_instance_type(x)
|
assert self.is_of_instance_type(x)
|
def f(): return virtual_ref(X())
|
assert lltype.typeOf(x) == OBJECTPTR
|
assert self.is_of_instance_type(x)
|
def f(n): if n > 0: return virtual_ref(Y()) else: return non_virtual_ref(Z())
|
assert lltype.typeOf(x) == OBJECTPTR
|
assert self.is_of_instance_type(x)
|
def f(n): if n > 0: return virtual_ref(X()) else: return vref_None
|
if hasattr(sys, 'pypy_version_info'):
|
if hasattr(sys, 'pypy_version_info') and hasattr(sys, 'prefix'):
|
def addsitepackages(known_paths): """Add site-packages to sys.path, in a PyPy-specific way.""" if hasattr(sys, 'pypy_version_info'): from distutils.sysconfig import get_python_lib sitedir = get_python_lib(standard_lib=False) if os.path.isdir(sitedir): addsitedir(sitedir, known_paths) return None
|
def _make_signed_32(v): if v >= 0x80000000: v -= 0x100000000 return int(v) crc_32_tab = map(_make_signed_32, crc_32_tab)
|
crc_32_tab = map(intmask, crc_32_tab)
|
def _make_signed_32(v): if v >= 0x80000000: v -= 0x100000000 return int(v)
|
return space.wrap(w_obj.num.bit_length())
|
return space.wrap(bigint.bit_length())
|
def bit_length(space, w_obj): try: return space.wrap(w_obj.num.bit_length()) except OverflowError: raise OperationError(space.w_OverflowError, space.wrap("too many digits in integer"))
|
'Py_BuildValue', 'PyTuple_Pack', 'PyErr_Format', 'PyErr_NewException',
|
'Py_BuildValue', 'Py_VaBuildValue', 'PyTuple_Pack', 'PyErr_Format', 'PyErr_NewException',
|
def cpython_struct(name, fields, forward=None): configname = name.replace(' ', '__') setattr(CConfig, configname, rffi_platform.Struct(name, fields)) if forward is None: forward = lltype.ForwardReference() TYPES[configname] = forward return forward
|
self.stack_check_slowpath_imm = imm0
|
self.stack_check_slowpath = 0
|
def __init__(self, cpu, translate_support_code=False, failargs_limit=1000): self.cpu = cpu self.verbose = False self.rtyper = cpu.rtyper self.malloc_func_addr = 0 self.malloc_array_func_addr = 0 self.malloc_str_func_addr = 0 self.malloc_unicode_func_addr = 0 self.fail_boxes_int = values_array(lltype.Signed, failargs_limit) self.fail_boxes_ptr = values_array(llmemory.GCREF, failargs_limit) self.fail_boxes_float = values_array(lltype.Float, failargs_limit) self.fail_ebp = 0 self.loop_run_counters = [] self.float_const_neg_addr = 0 self.float_const_abs_addr = 0 self.malloc_fixedsize_slowpath1 = 0 self.malloc_fixedsize_slowpath2 = 0 self.memcpy_addr = 0 self.setup_failure_recovery() self._debug = False self.debug_counter_descr = cpu.fielddescrof(DEBUG_COUNTER, 'i') self.fail_boxes_count = 0 self._current_depths_cache = (0, 0) self.datablockwrapper = None self.stack_check_slowpath_imm = imm0 self.teardown()
|
_STACK_CHECK_SLOWPATH = lltype.Ptr(lltype.FuncType([lltype.Signed], lltype.Void))
|
def _build_malloc_fixedsize_slowpath(self): # ---------- first helper for the slow path of malloc ---------- mc = codebuf.MachineCodeBlockWrapper() if self.cpu.supports_floats: # save the XMM registers in for i in range(self.cpu.NUM_REGS):# the *caller* frame, from esp+8 mc.MOVSD_sx((WORD*2)+8*i, i) mc.SUB_rr(edx.value, eax.value) # compute the size we want if IS_X86_32: mc.MOV_sr(WORD, edx.value) # save it as the new argument elif IS_X86_64: # rdi can be clobbered: its content was forced to the stack # by _fastpath_malloc(), like all other save_around_call_regs. mc.MOV_rr(edi.value, edx.value)
|
|
f = llhelper(self._STACK_CHECK_SLOWPATH, rstack.stack_check_slowpath) addr = rffi.cast(lltype.Signed, f) mc.CALL(imm(addr))
|
mc.CALL(imm(slowpathaddr))
|
def _build_stack_check_slowpath(self): from pypy.rlib import rstack mc = codebuf.MachineCodeBlockWrapper() mc.PUSH_r(ebp.value) mc.MOV_rr(ebp.value, esp.value) # if IS_X86_64: # on the x86_64, we have to save all the registers that may # have been used to pass arguments for reg in [edi, esi, edx, ecx, r8, r9]: mc.PUSH_r(reg.value) mc.SUB_ri(esp.value, 8*8) for i in range(8): mc.MOVSD_sx(8*i, i) # xmm0 to xmm7 # if IS_X86_32: mc.LEA_rb(eax.value, +8) mc.PUSH_r(eax.value) elif IS_X86_64: mc.LEA_rb(edi.value, +16) mc.AND_ri(esp.value, -16) # f = llhelper(self._STACK_CHECK_SLOWPATH, rstack.stack_check_slowpath) addr = rffi.cast(lltype.Signed, f) mc.CALL(imm(addr)) # mc.MOV(eax, heap(self.cpu.pos_exception())) mc.TEST_rr(eax.value, eax.value) mc.J_il8(rx86.Conditions['NZ'], 0) jnz_location = mc.get_relative_pos() # if IS_X86_64: # restore the registers for i in range(7, -1, -1): mc.MOVSD_xs(i, 8*i) for i, reg in [(6, r9), (5, r8), (4, ecx), (3, edx), (2, esi), (1, edi)]: mc.MOV_rb(reg.value, -8*i) # mc.MOV_rr(esp.value, ebp.value) mc.POP_r(ebp.value) mc.RET() # # patch the JNZ above offset = mc.get_relative_pos() - jnz_location assert 0 < offset <= 127 mc.overwrite(jnz_location-1, chr(offset)) # clear the exception from the global position mc.MOV(eax, heap(self.cpu.pos_exc_value())) mc.MOV(heap(self.cpu.pos_exception()), imm0) mc.MOV(heap(self.cpu.pos_exc_value()), imm0) # save the current exception instance into fail_boxes_ptr[0] adr = self.fail_boxes_ptr.get_addr_for_num(0) mc.MOV(heap(adr), eax) # call the helper function to set the GC flag on the fail_boxes_ptr # array (note that there is no exception any more here) addr = self.cpu.get_on_leave_jitted_int(save_exception=False) mc.CALL(imm(addr)) # assert self.cpu.exit_frame_with_exception_v >= 0 mc.MOV_ri(eax.value, self.cpu.exit_frame_with_exception_v) # # footer -- note the ADD, which skips the return address of this # function, and will instead return to the caller's caller. Note # also that we completely ignore the saved arguments, because we # are interrupting the function. mc.MOV_rr(esp.value, ebp.value) mc.POP_r(ebp.value) mc.ADD_ri(esp.value, WORD) mc.RET() # rawstart = mc.materialize(self.cpu.asmmemmgr, []) self.stack_check_slowpath_imm = imm(rawstart)
|
assert self.cpu.exit_frame_with_exception_v >= 0
|
def _build_stack_check_slowpath(self): from pypy.rlib import rstack mc = codebuf.MachineCodeBlockWrapper() mc.PUSH_r(ebp.value) mc.MOV_rr(ebp.value, esp.value) # if IS_X86_64: # on the x86_64, we have to save all the registers that may # have been used to pass arguments for reg in [edi, esi, edx, ecx, r8, r9]: mc.PUSH_r(reg.value) mc.SUB_ri(esp.value, 8*8) for i in range(8): mc.MOVSD_sx(8*i, i) # xmm0 to xmm7 # if IS_X86_32: mc.LEA_rb(eax.value, +8) mc.PUSH_r(eax.value) elif IS_X86_64: mc.LEA_rb(edi.value, +16) mc.AND_ri(esp.value, -16) # f = llhelper(self._STACK_CHECK_SLOWPATH, rstack.stack_check_slowpath) addr = rffi.cast(lltype.Signed, f) mc.CALL(imm(addr)) # mc.MOV(eax, heap(self.cpu.pos_exception())) mc.TEST_rr(eax.value, eax.value) mc.J_il8(rx86.Conditions['NZ'], 0) jnz_location = mc.get_relative_pos() # if IS_X86_64: # restore the registers for i in range(7, -1, -1): mc.MOVSD_xs(i, 8*i) for i, reg in [(6, r9), (5, r8), (4, ecx), (3, edx), (2, esi), (1, edi)]: mc.MOV_rb(reg.value, -8*i) # mc.MOV_rr(esp.value, ebp.value) mc.POP_r(ebp.value) mc.RET() # # patch the JNZ above offset = mc.get_relative_pos() - jnz_location assert 0 < offset <= 127 mc.overwrite(jnz_location-1, chr(offset)) # clear the exception from the global position mc.MOV(eax, heap(self.cpu.pos_exc_value())) mc.MOV(heap(self.cpu.pos_exception()), imm0) mc.MOV(heap(self.cpu.pos_exc_value()), imm0) # save the current exception instance into fail_boxes_ptr[0] adr = self.fail_boxes_ptr.get_addr_for_num(0) mc.MOV(heap(adr), eax) # call the helper function to set the GC flag on the fail_boxes_ptr # array (note that there is no exception any more here) addr = self.cpu.get_on_leave_jitted_int(save_exception=False) mc.CALL(imm(addr)) # assert self.cpu.exit_frame_with_exception_v >= 0 mc.MOV_ri(eax.value, self.cpu.exit_frame_with_exception_v) # # footer -- note the ADD, which skips the return address of this # function, and will instead return to the caller's caller. Note # also that we completely ignore the saved arguments, because we # are interrupting the function. mc.MOV_rr(esp.value, ebp.value) mc.POP_r(ebp.value) mc.ADD_ri(esp.value, WORD) mc.RET() # rawstart = mc.materialize(self.cpu.asmmemmgr, []) self.stack_check_slowpath_imm = imm(rawstart)
|
|
self.stack_check_slowpath_imm = imm(rawstart)
|
self.stack_check_slowpath = rawstart
|
def _build_stack_check_slowpath(self): from pypy.rlib import rstack mc = codebuf.MachineCodeBlockWrapper() mc.PUSH_r(ebp.value) mc.MOV_rr(ebp.value, esp.value) # if IS_X86_64: # on the x86_64, we have to save all the registers that may # have been used to pass arguments for reg in [edi, esi, edx, ecx, r8, r9]: mc.PUSH_r(reg.value) mc.SUB_ri(esp.value, 8*8) for i in range(8): mc.MOVSD_sx(8*i, i) # xmm0 to xmm7 # if IS_X86_32: mc.LEA_rb(eax.value, +8) mc.PUSH_r(eax.value) elif IS_X86_64: mc.LEA_rb(edi.value, +16) mc.AND_ri(esp.value, -16) # f = llhelper(self._STACK_CHECK_SLOWPATH, rstack.stack_check_slowpath) addr = rffi.cast(lltype.Signed, f) mc.CALL(imm(addr)) # mc.MOV(eax, heap(self.cpu.pos_exception())) mc.TEST_rr(eax.value, eax.value) mc.J_il8(rx86.Conditions['NZ'], 0) jnz_location = mc.get_relative_pos() # if IS_X86_64: # restore the registers for i in range(7, -1, -1): mc.MOVSD_xs(i, 8*i) for i, reg in [(6, r9), (5, r8), (4, ecx), (3, edx), (2, esi), (1, edi)]: mc.MOV_rb(reg.value, -8*i) # mc.MOV_rr(esp.value, ebp.value) mc.POP_r(ebp.value) mc.RET() # # patch the JNZ above offset = mc.get_relative_pos() - jnz_location assert 0 < offset <= 127 mc.overwrite(jnz_location-1, chr(offset)) # clear the exception from the global position mc.MOV(eax, heap(self.cpu.pos_exc_value())) mc.MOV(heap(self.cpu.pos_exception()), imm0) mc.MOV(heap(self.cpu.pos_exc_value()), imm0) # save the current exception instance into fail_boxes_ptr[0] adr = self.fail_boxes_ptr.get_addr_for_num(0) mc.MOV(heap(adr), eax) # call the helper function to set the GC flag on the fail_boxes_ptr # array (note that there is no exception any more here) addr = self.cpu.get_on_leave_jitted_int(save_exception=False) mc.CALL(imm(addr)) # assert self.cpu.exit_frame_with_exception_v >= 0 mc.MOV_ri(eax.value, self.cpu.exit_frame_with_exception_v) # # footer -- note the ADD, which skips the return address of this # function, and will instead return to the caller's caller. Note # also that we completely ignore the saved arguments, because we # are interrupting the function. mc.MOV_rr(esp.value, ebp.value) mc.POP_r(ebp.value) mc.ADD_ri(esp.value, WORD) mc.RET() # rawstart = mc.materialize(self.cpu.asmmemmgr, []) self.stack_check_slowpath_imm = imm(rawstart)
|
startaddr, length, slowpathaddr = self.cpu.insert_stack_check() if slowpathaddr == 0:
|
if self.stack_check_slowpath == 0:
|
def _call_header_with_stack_check(self): startaddr, length, slowpathaddr = self.cpu.insert_stack_check() if slowpathaddr == 0: pass # no stack check (e.g. not translated) else: self.mc.MOV(eax, esp) # MOV eax, current self.mc.SUB(eax, heap(startaddr)) # SUB eax, [startaddr] self.mc.CMP(eax, imm(length)) # CMP eax, length self.mc.J_il8(rx86.Conditions['B'], 0) # JB .skip jb_location = self.mc.get_relative_pos() self.mc.CALL(self.stack_check_slowpath_imm) # CALL slowpath # patch the JB above # .skip: offset = self.mc.get_relative_pos() - jb_location assert 0 < offset <= 127 self.mc.overwrite(jb_location-1, chr(offset)) # self._call_header()
|
self.mc.CALL(self.stack_check_slowpath_imm)
|
self.mc.CALL(imm(self.stack_check_slowpath))
|
def _call_header_with_stack_check(self): startaddr, length, slowpathaddr = self.cpu.insert_stack_check() if slowpathaddr == 0: pass # no stack check (e.g. not translated) else: self.mc.MOV(eax, esp) # MOV eax, current self.mc.SUB(eax, heap(startaddr)) # SUB eax, [startaddr] self.mc.CMP(eax, imm(length)) # CMP eax, length self.mc.J_il8(rx86.Conditions['B'], 0) # JB .skip jb_location = self.mc.get_relative_pos() self.mc.CALL(self.stack_check_slowpath_imm) # CALL slowpath # patch the JB above # .skip: offset = self.mc.get_relative_pos() - jb_location assert 0 < offset <= 127 self.mc.overwrite(jb_location-1, chr(offset)) # self._call_header()
|
ev.c_data.c_fd = fd
|
rffi.setintfield(ev.c_data, 'c_fd', fd)
|
def epoll_ctl(self, ctl, w_fd, eventmask, ignore_ebadf=False): fd = as_fd_w(self.space, w_fd) with lltype.scoped_alloc(epoll_event) as ev: ev.c_events = rffi.cast(rffi.UINT, eventmask) ev.c_data.c_fd = fd
|
expect(f, g, "ll_os.ll_os_open", ("/proc/cpuinfo", 0, 420), OSError(5232, "xyz"))
|
if sys.platform == 'linux2': expect(f, g, "ll_os.ll_os_open", ("/proc/cpuinfo", 0, 420), OSError(5232, "xyz"))
|
def entry_point(argv): l = [] for i in range(int(argv[1])): l.append("x" * int(argv[2])) return int(len(l) > 1000)
|
return 8.0
|
return 9.0
|
def get_build_version(): """Return the version of MSVC that was used to build Python. For Python 2.3 and up, the version number is included in sys.version. For earlier versions, assume the compiler is MSVC 6. """ return 8.0
|
option_ptr = lltype.malloc(rffi.INTP.TO, 1, flavor='raw') try: option_ptr[0] = space.uint_w(w_option) option_ptr = rffi.cast(rffi.VOIDP, option_ptr) res = _c.WSAIoctl( self.fd, cmd, option_ptr, rffi.sizeof(rffi.INTP), rffi.NULL, 0, recv_ptr, rffi.NULL, rffi.NULL) if res < 0: raise error() finally: lltype.free(option_ptr, flavor='raw')
|
value_size = rffi.sizeof(rffi.INTP)
|
def ioctl_w(self, space, cmd, w_option): from pypy.rpython.lltypesystem import rffi, lltype from pypy.rlib import rwin32 from pypy.rlib.rsocket import _c
|
w_onoff, w_time, w_interval = space.unpackiterable(w_option) option_ptr = lltype.malloc(_c.tcp_keepalive, flavor='raw') try:
|
value_size = rffi.sizeof(_c.tcp_keepalive) else: raise operationerrfmt(space.w_ValueError, "invalid ioctl command %d", cmd) value_ptr = lltype.malloc(rffi.VOIDP.TO, value_size, flavor='raw') try: if cmd == _c.SIO_RCVALL: option_ptr = rffi.cast(rffi.INTP, value_ptr) option_ptr[0] = space.int_w(w_option) elif cmd == _c.SIO_KEEPALIVE_VALS: w_onoff, w_time, w_interval = space.unpackiterable(w_option) option_ptr = rffi.cast(lltype.Ptr(_c.tcp_keepalive), value_ptr)
|
def ioctl_w(self, space, cmd, w_option): from pypy.rpython.lltypesystem import rffi, lltype from pypy.rlib import rwin32 from pypy.rlib.rsocket import _c
|
option_ptr = rffi.cast(rffi.VOIDP, option_ptr) res = _c.WSAIoctl( self.fd, cmd, option_ptr, rffi.sizeof(_c.tcp_keepalive), rffi.NULL, 0, recv_ptr, rffi.NULL, rffi.NULL) if res < 0: raise error() finally: lltype.free(option_ptr, flavor='raw') else: raise operationerrfmt(space.w_ValueError, "invalid ioctl command %d", cmd)
|
res = _c.WSAIoctl( self.fd, cmd, value_ptr, value_size, rffi.NULL, 0, recv_ptr, rffi.NULL, rffi.NULL) if res < 0: raise converted_error(space, rsocket.last_error()) finally: if value_ptr: lltype.free(value_ptr, flavor='raw')
|
def ioctl_w(self, space, cmd, w_option): from pypy.rpython.lltypesystem import rffi, lltype from pypy.rlib import rwin32 from pypy.rlib.rsocket import _c
|
chars = self.decoded_chars[self.decoded_chars_used: self.decoded_chars_used + size]
|
start = self.decoded_chars_used end = self.decoded_chars_used + size assert start >= 0 assert end >= 0 chars = self.decoded_chars[start:end]
|
def _get_decoded_chars(self, size): if self.decoded_chars is None: return u""
|
res_incl_dirs.append('/usr/local/include')
|
res_incl_dirs.append(os.path.join(get_env("LOCALBASE", "/usr/local"), "include"))
|
def _preprocess_include_dirs(self, include_dirs): res_incl_dirs = list(include_dirs) res_incl_dirs.append('/usr/local/include') return res_incl_dirs
|
res_lib_dirs.append('/usr/local/lib')
|
res_lib_dirs.append(os.path.join(get_env("LOCALBASE", "/usr/local"), "lib"))
|
def _preprocess_library_dirs(self, library_dirs): res_lib_dirs = list(library_dirs) res_lib_dirs.append('/usr/local/lib') return res_lib_dirs
|
return ['/usr/local/include']
|
return [os.path.join(get_env("LOCALBASE", "/usr/local"), "include")]
|
def include_dirs_for_libffi(self): return ['/usr/local/include']
|
return ['/usr/local/lib']
|
return [os.path.join(get_env("LOCALBASE", "/usr/local"), "lib")]
|
def library_dirs_for_libffi(self): return ['/usr/local/lib']
|
class Freebsd7_64(Freebsd7):
|
class Freebsd_64(Freebsd):
|
def library_dirs_for_libffi(self): return ['/usr/local/lib']
|
raise wrap_oserror(space, e)
|
raise wrap_oserror(space, e, exception_name='w_IOError')
|
def descr_init(self, space, w_name, mode='r', closefd=True): if space.isinstance_w(w_name, space.w_float): raise OperationError(space.w_TypeError, space.wrap( "integer argument expected, got float"))
|
raise wrap_oserror(space, e)
|
raise wrap_oserror(space, e, exception_name='w_IOError')
|
def isatty_w(self, space): self._check_closed(space) try: res = os.isatty(self.fd) except OSError, e: raise wrap_oserror(space, e) return space.wrap(res)
|
self._check_writable(space)
|
def write_w(self, space, w_data): self._check_closed(space) # XXX self._check_writable(space) data = space.str_w(w_data)
|
|
self._check_readable(space)
|
def read_w(self, space, w_size=None): self._check_closed(space) # XXX self._check_readable(space) size = convert_size(space, w_size)
|
|
self._check_readable(space)
|
def readinto_w(self, space, w_buffer): self._check_closed(space)
|
|
raise wrap_oserror(space, e)
|
raise wrap_oserror(space, e, exception_name='w_IOError')
|
def truncate_w(self, space, w_size=None): if space.is_w(w_size, space.w_None): w_size = self.tell_w(space)
|
if w_obj: w_obj_type = space.type(w_obj) if not int(space.is_w(w_obj_type, w_type) or space.is_true(space.issubtype(w_obj_type, w_type))): return w_obj pyo = make_ref(space, w_type) pto = rffi.cast(PyTypeObjectPtr, pyo) try: if pto.c_tp_init: generic_cpy_call(space, pto.c_tp_init, w_obj, w_args, w_kw) else: w_descr = space.lookup(w_obj, '__init__') w_result = space.get_and_call_args(w_descr, w_obj, __args__) return w_obj finally: Py_DecRef(space, pyo)
|
def c_type_descr__call__(space, w_type, __args__): if isinstance(w_type, W_PyCTypeObject): pyo = make_ref(space, w_type) pto = rffi.cast(PyTypeObjectPtr, pyo) tp_new = pto.c_tp_new try: if not tp_new: raise operationerrfmt(space.w_TypeError, "cannot create '%s' instances", w_type.getname(space, '?')) args_w, kw_w = __args__.unpack() w_args = space.newtuple(args_w) w_kw = space.newdict() for key, w_obj in kw_w.items(): space.setitem(w_kw, space.wrap(key), w_obj) w_obj = generic_cpy_call(space, tp_new, pto, w_args, w_kw) if w_obj: w_obj_type = space.type(w_obj) if not int(space.is_w(w_obj_type, w_type) or space.is_true(space.issubtype(w_obj_type, w_type))): return w_obj pyo = make_ref(space, w_type) pto = rffi.cast(PyTypeObjectPtr, pyo) try: if pto.c_tp_init: generic_cpy_call(space, pto.c_tp_init, w_obj, w_args, w_kw) else: w_descr = space.lookup(w_obj, '__init__') w_result = space.get_and_call_args(w_descr, w_obj, __args__) return w_obj finally: Py_DecRef(space, pyo) finally: Py_DecRef(space, pyo) else: w_type = _precheck_for_new(space, w_type) return call__Type(space, w_type, __args__)
|
|
expected = """
|
preamble = """
|
def test_bound_lt(self): ops = """ [i0] i1 = int_lt(i0, 4) guard_true(i1) [] i2 = int_lt(i0, 5) guard_true(i2) [] jump(i0) """ expected = """ [i0] i1 = int_lt(i0, 4) guard_true(i1) [] jump(i0) """ self.optimize_loop(ops, expected)
|
self.optimize_loop(ops, expected)
|
expected = """ [i0] jump(i0) """ self.optimize_loop(ops, expected, preamble)
|
def test_bound_lt(self): ops = """ [i0] i1 = int_lt(i0, 4) guard_true(i1) [] i2 = int_lt(i0, 5) guard_true(i2) [] jump(i0) """ expected = """ [i0] i1 = int_lt(i0, 4) guard_true(i1) [] jump(i0) """ self.optimize_loop(ops, expected)
|
OptString(),
|
def optimize_loop_1(metainterp_sd, loop, virtuals=True): """Optimize loop.operations to make it match the input of loop.specnodes and to remove internal overheadish operations. Note that loop.specnodes must be applicable to the loop; you will probably get an AssertionError if not. """ optimizations = [OptIntBounds(), OptRewrite(), OptVirtualize(), OptString(), OptHeap(), ] optimizer = Optimizer(metainterp_sd, loop, optimizations, virtuals) optimizer.propagate_all_forward()
|
|
do_test_merge(merge_int, [r_longlong(i) for i in range(4)])
|
if r_longlong is not r_int: do_test_merge(merge_int, [r_longlong(i) for i in range(4)])
|
def merge_int(n): n += 1 if n == 1: return 1 elif n == 2: return 2 elif n == 3: return 3 return 4
|
... return i*i for i in xrange(n) Traceback (most recent call last): ... SyntaxError: invalid syntax
|
... return i*i for i in xrange(n) Traceback (most recent call last): ... SyntaxError: invalid syntax...
|
>>> def f(n):
|
return lltype.free(ptr, flavor='raw')
|
lltype.free(ptr, flavor='raw')
|
def PyObject_FREE(space, ptr): return lltype.free(ptr, flavor='raw')
|
time = rffi.llexternal('time', [rffi.VOIDP], time_t, includes=['time.h'])
|
eci = ExternalCompilationInfo(includes=['time.h']) time = rffi.llexternal('time', [int], time_t, compilation_info=eci)
|
from pypy.interpreter.typedef import TypeDef, GetSetProperty
|
starttime = time(None)
|
starttime = time(0)
|
def measuretime(space, repetitions, w_callable): if repetitions <= 0: w_DemoError = get(space, 'DemoError') msg = "repetition count must be > 0" raise OperationError(w_DemoError, space.wrap(msg)) starttime = time(None) for i in range(repetitions): space.call_function(w_callable) endtime = time(None) return space.wrap(endtime - starttime)
|
endtime = time(None)
|
endtime = time(0)
|
def measuretime(space, repetitions, w_callable): if repetitions <= 0: w_DemoError = get(space, 'DemoError') msg = "repetition count must be > 0" raise OperationError(w_DemoError, space.wrap(msg)) starttime = time(None) for i in range(repetitions): space.call_function(w_callable) endtime = time(None) return space.wrap(endtime - starttime)
|
return float_unpack(unsigned, size)
|
return float_unpack(unsigned, size, le)
|
def unpack_float(data, index, size, le): binary = data[index:index + 8] if le == "big": binary.reverse() unsigned = 0 for i in range(8): unsigned |= ord(binary[i]) << (i * 8) return float_unpack(unsigned, size)
|
bitsize = l_w[2]
|
bitsize = space.int_w(l_w[2])
|
def unpack_fields(space, w_fields): fields_w = space.unpackiterable(w_fields) fields = [] for w_tup in fields_w: l_w = space.unpackiterable(w_tup) len_l = len(l_w) if len_l == 2: bitsize = 0 elif len_l == 3: bitsize = l_w[2] else: raise OperationError(space.w_ValueError, space.wrap( "Expected list of 2- or 3-size tuples")) name = space.str_w(l_w[0]) tp = unpack_shape_with_length(space, l_w[1]) fields.append((name, tp, bitsize)) return fields
|
self.check_loops(getfield_gc=1)
|
self.check_loops(getfield_gc=1, everywhere=True)
|
def f(n): a = A() a.x = 1 if n < 1091212: a.x = 2 # fool the annotator lst = [n * 5, n * 10, n * 20] while n > 0: jitdriver.can_enter_jit(n=n, a=a, lst=lst) jitdriver.jit_merge_point(n=n, a=a, lst=lst) n += a.x n = lst.pop() lst.append(n - 10 + a.x) if a.x in lst: pass a.x = a.x + 1 - 1 a = lst.pop() b = lst.pop() return a * b
|
self.warmrunnerdesc.rtyper.set_type_for_typeptr( self.jit_virtual_ref_vtable, self.JIT_VIRTUAL_REF)
|
if hasattr(self.warmrunnerdesc, 'rtyper'): self.warmrunnerdesc.rtyper.set_type_for_typeptr( self.jit_virtual_ref_vtable, self.JIT_VIRTUAL_REF)
|
def __init__(self, warmrunnerdesc): self.warmrunnerdesc = warmrunnerdesc self.cpu = warmrunnerdesc.cpu # we make the low-level type of an RPython class directly self.JIT_VIRTUAL_REF = lltype.GcStruct('JitVirtualRef', ('super', rclass.OBJECT), ('virtual_token', lltype.Signed), ('virtualref_index', lltype.Signed), ('forced', rclass.OBJECTPTR)) self.jit_virtual_ref_vtable = lltype.malloc(rclass.OBJECT_VTABLE, zero=True, flavor='raw') self.jit_virtual_ref_vtable.name = rclass.alloc_array_name( 'jit_virtual_ref') # build some constants adr = llmemory.cast_ptr_to_adr(self.jit_virtual_ref_vtable) self.jit_virtual_ref_const_class = history.ConstAddr(adr, self.cpu) fielddescrof = self.cpu.fielddescrof self.descr_virtual_token = fielddescrof(self.JIT_VIRTUAL_REF, 'virtual_token') self.descr_virtualref_index = fielddescrof(self.JIT_VIRTUAL_REF, 'virtualref_index') self.descr_forced = fielddescrof(self.JIT_VIRTUAL_REF, 'forced') # # record the type JIT_VIRTUAL_REF explicitly in the rtyper, too self.warmrunnerdesc.rtyper.set_type_for_typeptr( self.jit_virtual_ref_vtable, self.JIT_VIRTUAL_REF)
|
if self.source_op is None: from pypy.rlib.debug import ll_assert ll_assert(False, "_really_force: source_op is None") raise InvalidLoop
|
assert self.source_op is not None
|
def _really_force(self): if self.source_op is None: # this case should not occur; I only managed to get it once # in pypy-c-jit and couldn't reproduce it. The point is # that it relies on optimizefindnode.py computing exactly # the right level of specialization, and it seems that there # is still a corner case where it gets too specialized for # optimizeopt.py. Let's not crash in release-built # pypy-c-jit's. XXX find out when from pypy.rlib.debug import ll_assert ll_assert(False, "_really_force: source_op is None") raise InvalidLoop # newoperations = self.optimizer.newoperations newoperations.append(self.source_op) self.box = box = self.source_op.result # iteritems = self._fields.iteritems() if not we_are_translated(): #random order is fine, except for tests iteritems = list(iteritems) iteritems.sort(key = lambda (x,y): x.sort_key()) for ofs, value in iteritems: if value.is_null(): continue subbox = value.force_box() op = ResOperation(rop.SETFIELD_GC, [box, subbox], None, descr=ofs) newoperations.append(op) self._fields = None
|
_sqrtpi = 1.772453850905516027298167483341145182798;
|
_sqrtpi = 1.772453850905516027298167483341145182798
|
def erfc(space, x): """The complementary error function""" return math1(space, _erfc, x)
|
fk = ERF_SERIES_TERMS * + .5
|
fk = ERF_SERIES_TERMS + .5
|
def _erf_series(x): x2 = x * x acc = 0. fk = ERF_SERIES_TERMS * + .5 for i in range(ERF_SERIES_TERMS): acc = 2.0 * x2 * acc / fk fk -= 1. return acc * x * math.exp(-x2) / _sqrtpi
|
acc = 2.0 * x2 * acc / fk
|
acc = 2.0 + x2 * acc / fk
|
def _erf_series(x): x2 = x * x acc = 0. fk = ERF_SERIES_TERMS * + .5 for i in range(ERF_SERIES_TERMS): acc = 2.0 * x2 * acc / fk fk -= 1. return acc * x * math.exp(-x2) / _sqrtpi
|
da = 0.
|
da = .5
|
def _erfc_contfrac(x): if x >= ERFC_CONTFRAC_CUTOFF: return 0. x2 = x * x a = 0. da = 0. p = 1. p_last = 0. q = da + x2 q_last = 1. for i in range(ERFC_CONTFRAC_TERMS): a += da da += 2. b = da + x2 temp = p p = b * p - a * p_last p_last = temp temp = q q = b * q - a * q_last q_last = temp return p / q * x * math.exp(-x2) / _sqrtpi
|
temp = p p = b * p - a * p_last p_last = temp temp = q q = b * q - a * q_last q_last = temp
|
p_last, p = p, b * p - a * p_last q_last, q = q, b * q - a * q_last
|
def _erfc_contfrac(x): if x >= ERFC_CONTFRAC_CUTOFF: return 0. x2 = x * x a = 0. da = 0. p = 1. p_last = 0. q = da + x2 q_last = 1. for i in range(ERFC_CONTFRAC_TERMS): a += da da += 2. b = da + x2 temp = p p = b * p - a * p_last p_last = temp temp = q q = b * q - a * q_last q_last = temp return p / q * x * math.exp(-x2) / _sqrtpi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.