| 1 |
""" |
| 2 |
|
| 3 |
Gateway between app-level and interpreter-level: |
| 4 |
* BuiltinCode (call interp-level code from app-level) |
| 5 |
* app2interp (embed an app-level function into an interp-level callable) |
| 6 |
* interp2app (publish an interp-level object to be visible from app-level) |
| 7 |
* interpindirect2app (publish an interp-level object to be visible from |
| 8 |
app-level as an indirect call to implementation) |
| 9 |
|
| 10 |
""" |
| 11 |
|
| 12 |
import sys |
| 13 |
import os |
| 14 |
import types |
| 15 |
import inspect |
| 16 |
|
| 17 |
import py |
| 18 |
|
| 19 |
from pypy.interpreter.eval import Code |
| 20 |
from pypy.interpreter.argument import Arguments |
| 21 |
from pypy.interpreter.signature import Signature |
| 22 |
from pypy.interpreter.baseobjspace import (W_Root, ObjSpace, SpaceCache, |
| 23 |
DescrMismatch) |
| 24 |
from pypy.interpreter.error import OperationError, oefmt |
| 25 |
from pypy.interpreter.function import ClassMethod, FunctionWithFixedCode, Method |
| 26 |
from rpython.rlib.objectmodel import we_are_translated, not_rpython |
| 27 |
from rpython.rlib.rarithmetic import r_longlong, r_int, r_ulonglong, r_uint |
| 28 |
from rpython.tool.sourcetools import func_with_new_name, compile2 |
| 29 |
|
| 30 |
from rpython.rlib.signature import signature, finishsigs |
| 31 |
from rpython.rlib import types as sigtypes |
| 32 |
|
| 33 |
NO_DEFAULT = object() |
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
class SignatureBuilder(object): |
| 38 |
"NOT_RPYTHON" |
| 39 |
def __init__(self, func=None, argnames=None, varargname=None, |
| 40 |
kwargname=None, name=None): |
| 41 |
self.func = func |
| 42 |
if func is not None: |
| 43 |
self.name = func.__name__ |
| 44 |
else: |
| 45 |
self.name = name |
| 46 |
if argnames is None: |
| 47 |
argnames = [] |
| 48 |
self.argnames = argnames |
| 49 |
self.varargname = varargname |
| 50 |
self.kwargname = kwargname |
| 51 |
self.posonlyargcount = 0 |
| 52 |
self.kwonlystartindex = -1 |
| 53 |
|
| 54 |
def append(self, argname): |
| 55 |
self.argnames.append(argname) |
| 56 |
|
| 57 |
def marker_posonly(self): |
| 58 |
assert self.posonlyargcount == 0 |
| 59 |
assert self.kwonlystartindex == -1 |
| 60 |
self.posonlyargcount = len(self.argnames) |
| 61 |
|
| 62 |
def marker_kwonly(self): |
| 63 |
assert self.kwonlystartindex == -1 |
| 64 |
self.kwonlystartindex = len(self.argnames) |
| 65 |
|
| 66 |
def signature(self): |
| 67 |
if self.kwonlystartindex == -1: |
| 68 |
kwonlyargcount = 0 |
| 69 |
else: |
| 70 |
kwonlyargcount = len(self.argnames) - self.kwonlystartindex |
| 71 |
return Signature(self.argnames, |
| 72 |
self.varargname, self.kwargname, |
| 73 |
kwonlyargcount, self.posonlyargcount) |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
class Unwrapper(object): |
| 79 |
"""A base class for custom unwrap_spec items. |
| 80 |
|
| 81 |
Subclasses must override unwrap(). |
| 82 |
""" |
| 83 |
def _freeze_(self): |
| 84 |
return True |
| 85 |
|
| 86 |
@not_rpython |
| 87 |
def unwrap(self, space, w_value): |
| 88 |
raise NotImplementedError |
| 89 |
|
| 90 |
|
| 91 |
class UnwrapSpecRecipe(object): |
| 92 |
"NOT_RPYTHON" |
| 93 |
|
| 94 |
bases_order = [W_Root, ObjSpace, Arguments, Unwrapper, object] |
| 95 |
|
| 96 |
def dispatch(self, el, *args): |
| 97 |
if isinstance(el, str): |
| 98 |
getattr(self, "visit_%s" % (el,))(el, *args) |
| 99 |
elif isinstance(el, tuple): |
| 100 |
if el[0] == 'INTERNAL:self': |
| 101 |
self.visit_self(el[1], *args) |
| 102 |
else: |
| 103 |
assert False, "not supported any more, use WrappedDefault" |
| 104 |
elif isinstance(el, WrappedDefault): |
| 105 |
self.visit__W_Root(W_Root, *args) |
| 106 |
elif isinstance(el, type): |
| 107 |
for typ in self.bases_order: |
| 108 |
if issubclass(el, typ): |
| 109 |
visit = getattr(self, "visit__%s" % (typ.__name__,)) |
| 110 |
visit(el, *args) |
| 111 |
break |
| 112 |
else: |
| 113 |
raise Exception("%s: no match for unwrap_spec element %s" % ( |
| 114 |
self.__class__.__name__, el)) |
| 115 |
else: |
| 116 |
raise Exception("unable to dispatch, %s, perhaps your parameter should have started with w_?" % el) |
| 117 |
|
| 118 |
def apply_over(self, unwrap_spec, *extra): |
| 119 |
dispatch = self.dispatch |
| 120 |
for el in unwrap_spec: |
| 121 |
dispatch(el, *extra) |
| 122 |
|
| 123 |
|
| 124 |
class UnwrapSpecEmit(UnwrapSpecRecipe): |
| 125 |
def __init__(self): |
| 126 |
self.n = 0 |
| 127 |
self.miniglobals = {} |
| 128 |
|
| 129 |
def succ(self): |
| 130 |
n = self.n |
| 131 |
self.n += 1 |
| 132 |
return n |
| 133 |
|
| 134 |
def use(self, obj): |
| 135 |
name = obj.__name__ |
| 136 |
self.miniglobals[name] = obj |
| 137 |
return name |
| 138 |
|
| 139 |
|
| 140 |
|
| 141 |
|
| 142 |
|
| 143 |
class UnwrapSpec_Check(UnwrapSpecRecipe): |
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
def __init__(self, func, argnames): |
| 148 |
self.func = func |
| 149 |
self.orig_arg = iter(argnames).next |
| 150 |
|
| 151 |
def visit_self(self, cls, app_sig): |
| 152 |
self.visit__W_Root(cls, app_sig) |
| 153 |
|
| 154 |
def checked_space_method(self, typname, app_sig): |
| 155 |
argname = self.orig_arg() |
| 156 |
assert not argname.startswith('w_'), ( |
| 157 |
"unwrapped %s argument %s of built-in function %r in %r should " |
| 158 |
"not start with 'w_'" % (typname, argname, self.func.func_name, self.func.func_globals['__name__'])) |
| 159 |
app_sig.append(argname) |
| 160 |
|
| 161 |
def visit_index(self, index, app_sig): |
| 162 |
self.checked_space_method(index, app_sig) |
| 163 |
|
| 164 |
def visit_bufferstr(self, el, app_sig): |
| 165 |
self.checked_space_method(el, app_sig) |
| 166 |
|
| 167 |
def visit_text_or_none(self, el, app_sig): |
| 168 |
self.checked_space_method(el, app_sig) |
| 169 |
|
| 170 |
def visit_text0_or_none(self, el, app_sig): |
| 171 |
self.checked_space_method(el, app_sig) |
| 172 |
|
| 173 |
def visit_bytes(self, el, app_sig): |
| 174 |
self.checked_space_method(el, app_sig) |
| 175 |
|
| 176 |
def visit_bytes0(self, el, app_sig): |
| 177 |
self.checked_space_method(el, app_sig) |
| 178 |
|
| 179 |
def visit_text(self, el, app_sig): |
| 180 |
self.checked_space_method(el, app_sig) |
| 181 |
|
| 182 |
def visit_text0(self, el, app_sig): |
| 183 |
self.checked_space_method(el, app_sig) |
| 184 |
|
| 185 |
def visit_unicode(self, el, app_sig): |
| 186 |
self.checked_space_method(el, app_sig) |
| 187 |
|
| 188 |
def visit_utf8(self, el, app_sig): |
| 189 |
self.checked_space_method(el, app_sig) |
| 190 |
|
| 191 |
def visit_fsencode(self, el, app_sig): |
| 192 |
self.checked_space_method(el, app_sig) |
| 193 |
|
| 194 |
def visit_fsencode_or_none(self, el, app_sig): |
| 195 |
self.checked_space_method(el, app_sig) |
| 196 |
|
| 197 |
def visit_nonnegint(self, el, app_sig): |
| 198 |
self.checked_space_method(el, app_sig) |
| 199 |
|
| 200 |
def visit_c_int(self, el, app_sig): |
| 201 |
self.checked_space_method(el, app_sig) |
| 202 |
|
| 203 |
def visit_c_uint(self, el, app_sig): |
| 204 |
self.checked_space_method(el, app_sig) |
| 205 |
|
| 206 |
def visit_c_nonnegint(self, el, app_sig): |
| 207 |
self.checked_space_method(el, app_sig) |
| 208 |
|
| 209 |
def visit_c_short(self, el, app_sig): |
| 210 |
self.checked_space_method(el, app_sig) |
| 211 |
|
| 212 |
def visit_c_ushort(self, el, app_sig): |
| 213 |
self.checked_space_method(el, app_sig) |
| 214 |
|
| 215 |
def visit_c_uid_t(self, el, app_sig): |
| 216 |
self.checked_space_method(el, app_sig) |
| 217 |
|
| 218 |
def visit_truncatedint_w(self, el, app_sig): |
| 219 |
self.checked_space_method(el, app_sig) |
| 220 |
|
| 221 |
def visit__Unwrapper(self, el, app_sig): |
| 222 |
self.checked_space_method(el, app_sig) |
| 223 |
|
| 224 |
def visit__ObjSpace(self, el, app_sig): |
| 225 |
self.orig_arg() |
| 226 |
|
| 227 |
def visit__W_Root(self, el, app_sig): |
| 228 |
argname = self.orig_arg() |
| 229 |
if argname == 'self': |
| 230 |
assert el is not W_Root |
| 231 |
app_sig.append(argname) |
| 232 |
return |
| 233 |
assert argname.startswith('w_'), ( |
| 234 |
"argument %s of built-in function %r in %r should " |
| 235 |
"start with 'w_'" % (argname, self.func.func_name, self.func.func_globals['__name__'])) |
| 236 |
app_sig.append(argname[2:]) |
| 237 |
|
| 238 |
def visit__Arguments(self, el, app_sig): |
| 239 |
self.orig_arg() |
| 240 |
assert app_sig.varargname is None, ( |
| 241 |
"built-in function %r has conflicting rest args specs" % self.func) |
| 242 |
app_sig.varargname = 'args' |
| 243 |
app_sig.kwargname = 'keywords' |
| 244 |
|
| 245 |
def visit_args_w(self, el, app_sig): |
| 246 |
argname = self.orig_arg() |
| 247 |
assert argname.endswith('_w'), ( |
| 248 |
"rest arguments arg %s of built-in function %r should end in '_w'" % |
| 249 |
(argname, self.func)) |
| 250 |
assert app_sig.varargname is None, ( |
| 251 |
"built-in function %r has conflicting rest args specs" % self.func) |
| 252 |
app_sig.varargname = argname[:-2] |
| 253 |
|
| 254 |
def visit_w_args(self, el, app_sig): |
| 255 |
argname = self.orig_arg() |
| 256 |
assert argname.startswith('w_'), ( |
| 257 |
"rest arguments arg %s of built-in function %r should start 'w_'" % |
| 258 |
(argname, self.func)) |
| 259 |
assert app_sig.varargname is None, ( |
| 260 |
"built-in function %r has conflicting rest args specs" % self.func) |
| 261 |
app_sig.varargname = argname[2:] |
| 262 |
|
| 263 |
def visit__object(self, typ, app_sig): |
| 264 |
name = int_unwrapping_space_method(typ) |
| 265 |
self.checked_space_method(name, app_sig) |
| 266 |
|
| 267 |
def visit_posonly(self, _, app_sig): |
| 268 |
argname = self.orig_arg() |
| 269 |
assert argname == '__posonly__' |
| 270 |
app_sig.marker_posonly() |
| 271 |
|
| 272 |
def visit_kwonly(self, _, app_sig): |
| 273 |
argname = self.orig_arg() |
| 274 |
assert argname == '__kwonly__' |
| 275 |
app_sig.marker_kwonly() |
| 276 |
|
| 277 |
|
| 278 |
class UnwrapSpec_EmitRun(UnwrapSpecEmit): |
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
def __init__(self, app_sig): |
| 283 |
self.app_sig = app_sig |
| 284 |
UnwrapSpecEmit.__init__(self) |
| 285 |
self.run_args = [] |
| 286 |
|
| 287 |
def scope_starargs(self): |
| 288 |
app_sig = self.app_sig |
| 289 |
pos = app_sig.num_argnames() + app_sig.num_kwonlyargnames() |
| 290 |
return "scope_w[%d]" % (pos, ) |
| 291 |
|
| 292 |
def scope_kwargs(self): |
| 293 |
app_sig = self.app_sig |
| 294 |
pos = app_sig.num_argnames() + app_sig.num_kwonlyargnames() + app_sig.has_vararg() |
| 295 |
return "scope_w[%d]" % (pos, ) |
| 296 |
|
| 297 |
def scopenext(self): |
| 298 |
return "scope_w[%d]" % self.succ() |
| 299 |
|
| 300 |
def visit_self(self, typ): |
| 301 |
self.run_args.append("space.descr_self_interp_w(%s, %s)" % |
| 302 |
(self.use(typ), self.scopenext())) |
| 303 |
|
| 304 |
def visit__Unwrapper(self, typ): |
| 305 |
self.run_args.append("%s().unwrap(space, %s)" % |
| 306 |
(self.use(typ), self.scopenext())) |
| 307 |
|
| 308 |
def visit__ObjSpace(self, el): |
| 309 |
self.run_args.append('space') |
| 310 |
|
| 311 |
def visit__W_Root(self, el): |
| 312 |
if el is not W_Root: |
| 313 |
self.run_args.append("space.interp_w(%s, %s)" % (self.use(el), |
| 314 |
self.scopenext())) |
| 315 |
else: |
| 316 |
self.run_args.append(self.scopenext()) |
| 317 |
|
| 318 |
def visit__Arguments(self, el): |
| 319 |
self.miniglobals['Arguments'] = Arguments |
| 320 |
self.run_args.append("Arguments.frompacked(space, %s, %s)" |
| 321 |
% (self.scope_starargs(), self.scope_kwargs())) |
| 322 |
|
| 323 |
def visit_args_w(self, el): |
| 324 |
self.run_args.append("space.fixedview(%s)" % self.scope_starargs()) |
| 325 |
|
| 326 |
def visit_w_args(self, el): |
| 327 |
self.run_args.append(self.scope_starargs()) |
| 328 |
|
| 329 |
def visit__object(self, typ): |
| 330 |
name = int_unwrapping_space_method(typ) |
| 331 |
self.run_args.append("space.%s(%s)" % |
| 332 |
(name, self.scopenext())) |
| 333 |
|
| 334 |
def visit_index(self, typ): |
| 335 |
self.run_args.append("space.getindex_w(%s, space.w_OverflowError)" |
| 336 |
% (self.scopenext(), )) |
| 337 |
|
| 338 |
def visit_bufferstr(self, typ): |
| 339 |
self.run_args.append("space.charbuf_w(%s)" % (self.scopenext(),)) |
| 340 |
|
| 341 |
def visit_text_or_none(self, typ): |
| 342 |
self.run_args.append("space.text_or_none_w(%s)" % (self.scopenext(),)) |
| 343 |
|
| 344 |
def visit_text0_or_none(self, typ): |
| 345 |
self.run_args.append("space.text0_or_none_w(%s)" % (self.scopenext(),)) |
| 346 |
|
| 347 |
def visit_bytes(self, typ): |
| 348 |
self.run_args.append("space.bytes_w(%s)" % (self.scopenext(),)) |
| 349 |
|
| 350 |
def visit_bytes0(self, typ): |
| 351 |
self.run_args.append("space.bytes0_w(%s)" % (self.scopenext(),)) |
| 352 |
|
| 353 |
def visit_text(self, typ): |
| 354 |
self.run_args.append("space.text_w(%s)" % (self.scopenext(),)) |
| 355 |
|
| 356 |
def visit_text0(self, typ): |
| 357 |
self.run_args.append("space.text0_w(%s)" % (self.scopenext(),)) |
| 358 |
|
| 359 |
def visit_unicode(self, typ): |
| 360 |
self.run_args.append("space.realunicode_w(%s)" % (self.scopenext(),)) |
| 361 |
|
| 362 |
def visit_utf8(self, typ): |
| 363 |
self.run_args.append("space.utf8_w(%s)" % (self.scopenext(),)) |
| 364 |
|
| 365 |
def visit_fsencode(self, typ): |
| 366 |
self.run_args.append("space.fsencode_w(%s)" % (self.scopenext(),)) |
| 367 |
|
| 368 |
def visit_fsencode_or_none(self, typ): |
| 369 |
self.run_args.append("space.fsencode_or_none_w(%s)" % (self.scopenext(),)) |
| 370 |
|
| 371 |
def visit_nonnegint(self, typ): |
| 372 |
self.run_args.append("space.gateway_nonnegint_w(%s)" % ( |
| 373 |
self.scopenext(),)) |
| 374 |
|
| 375 |
def visit_c_int(self, typ): |
| 376 |
self.run_args.append("space.c_int_w(%s)" % (self.scopenext(),)) |
| 377 |
|
| 378 |
def visit_c_uint(self, typ): |
| 379 |
self.run_args.append("space.c_uint_w(%s)" % (self.scopenext(),)) |
| 380 |
|
| 381 |
def visit_c_nonnegint(self, typ): |
| 382 |
self.run_args.append("space.c_nonnegint_w(%s)" % (self.scopenext(),)) |
| 383 |
|
| 384 |
def visit_c_short(self, typ): |
| 385 |
self.run_args.append("space.c_short_w(%s)" % (self.scopenext(),)) |
| 386 |
|
| 387 |
def visit_c_ushort(self, typ): |
| 388 |
self.run_args.append("space.c_ushort_w(%s)" % (self.scopenext(),)) |
| 389 |
|
| 390 |
def visit_c_uid_t(self, typ): |
| 391 |
self.run_args.append("space.c_uid_t_w(%s)" % (self.scopenext(),)) |
| 392 |
|
| 393 |
def visit_truncatedint_w(self, typ): |
| 394 |
self.run_args.append("space.truncatedint_w(%s)" % (self.scopenext(),)) |
| 395 |
|
| 396 |
def visit_posonly(self, typ): |
| 397 |
self.run_args.append("None") |
| 398 |
|
| 399 |
def visit_kwonly(self, typ): |
| 400 |
self.run_args.append("None") |
| 401 |
|
| 402 |
def _make_unwrap_activation_class(self, unwrap_spec, cache={}): |
| 403 |
try: |
| 404 |
key = tuple(unwrap_spec) |
| 405 |
activation_factory_cls, run_args = cache[key] |
| 406 |
assert run_args == self.run_args, ( |
| 407 |
"unexpected: same spec, different run_args") |
| 408 |
return activation_factory_cls |
| 409 |
except KeyError: |
| 410 |
parts = [] |
| 411 |
for el in unwrap_spec: |
| 412 |
if isinstance(el, tuple): |
| 413 |
parts.append(''.join([getattr(subel, '__name__', subel) |
| 414 |
for subel in el])) |
| 415 |
elif isinstance(el, WrappedDefault): |
| 416 |
parts.append('W_Root') |
| 417 |
else: |
| 418 |
parts.append(getattr(el, '__name__', el)) |
| 419 |
label = '_'.join(parts) |
| 420 |
|
| 421 |
|
| 422 |
d = {} |
| 423 |
source = """if 1: |
| 424 |
def _run(self, space, scope_w): |
| 425 |
return self.behavior(%s) |
| 426 |
\n""" % (', '.join(self.run_args),) |
| 427 |
exec compile2(source) in self.miniglobals, d |
| 428 |
|
| 429 |
activation_cls = type("BuiltinActivation_UwS_%s" % label, |
| 430 |
(BuiltinActivation,), d) |
| 431 |
activation_cls._immutable_ = True |
| 432 |
|
| 433 |
cache[key] = activation_cls, self.run_args |
| 434 |
return activation_cls |
| 435 |
|
| 436 |
@staticmethod |
| 437 |
def make_activation(unwrap_spec, func, app_sig): |
| 438 |
emit = UnwrapSpec_EmitRun(app_sig) |
| 439 |
emit.apply_over(unwrap_spec) |
| 440 |
activation_uw_cls = emit._make_unwrap_activation_class(unwrap_spec) |
| 441 |
return activation_uw_cls(func, unwrap_spec) |
| 442 |
|
| 443 |
|
| 444 |
class UnwrapSpec_EmitShortcut(UnwrapSpec_EmitRun): |
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
def __init__(self, rpy_cls): |
| 453 |
UnwrapSpecEmit.__init__(self) |
| 454 |
self.run_args = [] |
| 455 |
self.rpy_cls = rpy_cls |
| 456 |
self.extraargs = [] |
| 457 |
|
| 458 |
def scopenext(self): |
| 459 |
x = self.succ() |
| 460 |
res = "w_%d" % (x - 1, ) |
| 461 |
self.extraargs.append(res) |
| 462 |
return res |
| 463 |
|
| 464 |
def visit_self(self, typ): |
| 465 |
x = self.succ() |
| 466 |
assert x == 0 |
| 467 |
assert issubclass(self.rpy_cls, typ) |
| 468 |
self.run_args.append("self") |
| 469 |
|
| 470 |
def visit__W_Root(self, el): |
| 471 |
if issubclass(self.rpy_cls, el) and self.n == 0: |
| 472 |
return self.visit_self(el) |
| 473 |
return UnwrapSpec_EmitRun.visit__W_Root(self, el) |
| 474 |
|
| 475 |
|
| 476 |
class BuiltinActivation(object): |
| 477 |
_immutable_ = True |
| 478 |
|
| 479 |
@not_rpython |
| 480 |
def __init__(self, behavior, unwrap_spec): |
| 481 |
self.behavior = behavior |
| 482 |
|
| 483 |
def _run(self, space, scope_w): |
| 484 |
"""Subclasses with behavior specific for an unwrap spec are generated""" |
| 485 |
raise TypeError("abstract") |
| 486 |
|
| 487 |
|
| 488 |
|
| 489 |
|
| 490 |
class FastFuncNotSupported(Exception): |
| 491 |
pass |
| 492 |
|
| 493 |
|
| 494 |
class UnwrapSpec_FastFunc_Unwrap(UnwrapSpecEmit): |
| 495 |
def __init__(self): |
| 496 |
UnwrapSpecEmit.__init__(self) |
| 497 |
self.args = [] |
| 498 |
self.unwrap = [] |
| 499 |
self.finger = 0 |
| 500 |
|
| 501 |
def dispatch(self, el, *args): |
| 502 |
UnwrapSpecEmit.dispatch(self, el, *args) |
| 503 |
self.finger += 1 |
| 504 |
if self.n > 4: |
| 505 |
raise FastFuncNotSupported |
| 506 |
|
| 507 |
def nextarg(self): |
| 508 |
arg = "w%d" % self.succ() |
| 509 |
self.args.append(arg) |
| 510 |
return arg |
| 511 |
|
| 512 |
def visit_self(self, typ): |
| 513 |
self.unwrap.append("space.descr_self_interp_w(%s, %s)" % |
| 514 |
(self.use(typ), self.nextarg())) |
| 515 |
|
| 516 |
def visit__Unwrapper(self, typ): |
| 517 |
self.unwrap.append("%s().unwrap(space, %s)" % |
| 518 |
(self.use(typ), self.nextarg())) |
| 519 |
|
| 520 |
def visit__ObjSpace(self, el): |
| 521 |
if self.finger > 1: |
| 522 |
raise FastFuncNotSupported |
| 523 |
self.unwrap.append("space") |
| 524 |
|
| 525 |
def visit__W_Root(self, el): |
| 526 |
if el is not W_Root: |
| 527 |
self.unwrap.append("space.interp_w(%s, %s)" % (self.use(el), |
| 528 |
self.nextarg())) |
| 529 |
else: |
| 530 |
self.unwrap.append(self.nextarg()) |
| 531 |
|
| 532 |
def visit__Arguments(self, el): |
| 533 |
raise FastFuncNotSupported |
| 534 |
|
| 535 |
def visit_args_w(self, el): |
| 536 |
raise FastFuncNotSupported |
| 537 |
|
| 538 |
def visit_w_args(self, el): |
| 539 |
raise FastFuncNotSupported |
| 540 |
|
| 541 |
def visit__object(self, typ): |
| 542 |
name = int_unwrapping_space_method(typ) |
| 543 |
self.unwrap.append("space.%s(%s)" % (name, |
| 544 |
self.nextarg())) |
| 545 |
|
| 546 |
def visit_index(self, typ): |
| 547 |
self.unwrap.append("space.getindex_w(%s, space.w_OverflowError)" |
| 548 |
% (self.nextarg()), ) |
| 549 |
|
| 550 |
def visit_bufferstr(self, typ): |
| 551 |
self.unwrap.append("space.charbuf_w(%s)" % (self.nextarg(),)) |
| 552 |
|
| 553 |
def visit_text_or_none(self, typ): |
| 554 |
self.unwrap.append("space.text_or_none_w(%s)" % (self.nextarg(),)) |
| 555 |
|
| 556 |
def visit_text0_or_none(self, typ): |
| 557 |
self.unwrap.append("space.text0_or_none_w(%s)" % (self.nextarg(),)) |
| 558 |
|
| 559 |
def visit_bytes(self, typ): |
| 560 |
self.unwrap.append("space.bytes_w(%s)" % (self.nextarg(),)) |
| 561 |
|
| 562 |
def visit_bytes0(self, typ): |
| 563 |
self.unwrap.append("space.bytes0_w(%s)" % (self.nextarg(),)) |
| 564 |
|
| 565 |
def visit_text(self, typ): |
| 566 |
self.unwrap.append("space.text_w(%s)" % (self.nextarg(),)) |
| 567 |
|
| 568 |
def visit_unicode(self, typ): |
| 569 |
self.unwrap.append("space.realunicode_w(%s)" % (self.nextarg(),)) |
| 570 |
|
| 571 |
def visit_text0(self, typ): |
| 572 |
self.unwrap.append("space.text0_w(%s)" % (self.nextarg(),)) |
| 573 |
|
| 574 |
def visit_utf8(self, typ): |
| 575 |
self.unwrap.append("space.utf8_w(%s)" % (self.nextarg(),)) |
| 576 |
|
| 577 |
def visit_fsencode(self, typ): |
| 578 |
self.unwrap.append("space.fsencode_w(%s)" % (self.nextarg(),)) |
| 579 |
|
| 580 |
def visit_fsencode_or_none(self, typ): |
| 581 |
self.unwrap.append("space.fsencode_or_none_w(%s)" % (self.nextarg(),)) |
| 582 |
|
| 583 |
def visit_nonnegint(self, typ): |
| 584 |
self.unwrap.append("space.gateway_nonnegint_w(%s)" % (self.nextarg(),)) |
| 585 |
|
| 586 |
def visit_c_int(self, typ): |
| 587 |
self.unwrap.append("space.c_int_w(%s)" % (self.nextarg(),)) |
| 588 |
|
| 589 |
def visit_c_uint(self, typ): |
| 590 |
self.unwrap.append("space.c_uint_w(%s)" % (self.nextarg(),)) |
| 591 |
|
| 592 |
def visit_c_nonnegint(self, typ): |
| 593 |
self.unwrap.append("space.c_nonnegint_w(%s)" % (self.nextarg(),)) |
| 594 |
|
| 595 |
def visit_c_short(self, typ): |
| 596 |
self.unwrap.append("space.c_short_w(%s)" % (self.nextarg(),)) |
| 597 |
|
| 598 |
def visit_c_ushort(self, typ): |
| 599 |
self.unwrap.append("space.c_ushort_w(%s)" % (self.nextarg(),)) |
| 600 |
|
| 601 |
def visit_c_uid_t(self, typ): |
| 602 |
self.unwrap.append("space.c_uid_t_w(%s)" % (self.nextarg(),)) |
| 603 |
|
| 604 |
def visit_truncatedint_w(self, typ): |
| 605 |
self.unwrap.append("space.truncatedint_w(%s)" % (self.nextarg(),)) |
| 606 |
|
| 607 |
def visit_posonly(self, typ): |
| 608 |
raise FastFuncNotSupported |
| 609 |
|
| 610 |
def visit_kwonly(self, typ): |
| 611 |
raise FastFuncNotSupported |
| 612 |
|
| 613 |
@staticmethod |
| 614 |
def make_fastfunc(unwrap_spec, func): |
| 615 |
unwrap_info = UnwrapSpec_FastFunc_Unwrap() |
| 616 |
unwrap_info.apply_over(unwrap_spec) |
| 617 |
narg = unwrap_info.n |
| 618 |
args = ['space'] + unwrap_info.args |
| 619 |
if args == unwrap_info.unwrap: |
| 620 |
fastfunc = func |
| 621 |
else: |
| 622 |
|
| 623 |
mod = func.__module__ |
| 624 |
if mod is None: |
| 625 |
mod = "" |
| 626 |
if mod == 'pypy.interpreter.astcompiler.ast': |
| 627 |
raise FastFuncNotSupported |
| 628 |
|
| 629 |
|
| 630 |
|
| 631 |
|
| 632 |
|
| 633 |
d = {} |
| 634 |
unwrap_info.miniglobals['func'] = func |
| 635 |
source = """if 1: |
| 636 |
def fastfunc_%s_%d(%s): |
| 637 |
return func(%s) |
| 638 |
\n""" % (func.__name__.replace('-', '_'), narg, |
| 639 |
', '.join(args), |
| 640 |
', '.join(unwrap_info.unwrap)) |
| 641 |
exec compile2(source) in unwrap_info.miniglobals, d |
| 642 |
fastfunc = d['fastfunc_%s_%d' % (func.__name__.replace('-', '_'), narg)] |
| 643 |
return narg, fastfunc |
| 644 |
|
| 645 |
|
| 646 |
def int_unwrapping_space_method(typ): |
| 647 |
assert typ in (int, str, float, unicode, r_longlong, r_uint, r_ulonglong, bool) |
| 648 |
if typ is r_int is r_longlong: |
| 649 |
return 'gateway_r_longlong_w' |
| 650 |
elif typ is str: |
| 651 |
return 'utf8_w' |
| 652 |
elif typ is unicode: |
| 653 |
return 'realunicode_w' |
| 654 |
elif typ is bool: |
| 655 |
|
| 656 |
|
| 657 |
|
| 658 |
|
| 659 |
|
| 660 |
|
| 661 |
|
| 662 |
return 'is_true' |
| 663 |
else: |
| 664 |
return 'gateway_' + typ.__name__ + '_w' |
| 665 |
|
| 666 |
|
| 667 |
def unwrap_spec(*spec, **kwargs): |
| 668 |
"""A decorator which attaches the unwrap_spec attribute. |
| 669 |
Use either positional or keyword arguments. |
| 670 |
- positional arguments must be as many as the function parameters |
| 671 |
- keywords arguments allow to change only some parameter specs |
| 672 |
""" |
| 673 |
assert spec or kwargs |
| 674 |
def decorator(func): |
| 675 |
if kwargs: |
| 676 |
if spec: |
| 677 |
raise ValueError("Please specify either positional or " |
| 678 |
"keywords arguments") |
| 679 |
func.unwrap_spec = kwargs |
| 680 |
else: |
| 681 |
func.unwrap_spec = spec |
| 682 |
return func |
| 683 |
return decorator |
| 684 |
|
| 685 |
class WrappedDefault(object): |
| 686 |
""" Can be used inside unwrap_spec as WrappedDefault(3) which means |
| 687 |
it'll be treated as W_Root, but fed with default which will be a wrapped |
| 688 |
argument to constructor. |
| 689 |
""" |
| 690 |
def __init__(self, default_value): |
| 691 |
self.default_value = default_value |
| 692 |
|
| 693 |
|
| 694 |
def build_unwrap_spec(func, argnames, self_type=None): |
| 695 |
"""build the list of parameter unwrap spec for the function. |
| 696 |
""" |
| 697 |
unwrap_spec = getattr(func, 'unwrap_spec', None) |
| 698 |
|
| 699 |
if isinstance(unwrap_spec, dict): |
| 700 |
kw_spec = unwrap_spec |
| 701 |
unwrap_spec = None |
| 702 |
else: |
| 703 |
kw_spec = {} |
| 704 |
|
| 705 |
if unwrap_spec is None: |
| 706 |
|
| 707 |
unwrap_spec = [] |
| 708 |
for argname in argnames: |
| 709 |
if argname == 'self': |
| 710 |
unwrap_spec.append('self') |
| 711 |
elif argname == 'space': |
| 712 |
unwrap_spec.append(ObjSpace) |
| 713 |
elif argname == '__args__': |
| 714 |
unwrap_spec.append(Arguments) |
| 715 |
elif argname.endswith('_w') and not argname.startswith('w_'): |
| 716 |
unwrap_spec.append('args_w') |
| 717 |
elif argname.startswith('w_'): |
| 718 |
unwrap_spec.append(W_Root) |
| 719 |
elif argname == '__posonly__': |
| 720 |
unwrap_spec.append('posonly') |
| 721 |
elif argname == '__kwonly__': |
| 722 |
unwrap_spec.append('kwonly') |
| 723 |
else: |
| 724 |
unwrap_spec.append(None) |
| 725 |
|
| 726 |
|
| 727 |
for name, spec in kw_spec.items(): |
| 728 |
try: |
| 729 |
unwrap_spec[argnames.index(name)] = spec |
| 730 |
except ValueError: |
| 731 |
raise ValueError("unwrap_spec() got a keyword %r but it is not " |
| 732 |
"the name of an argument of the following " |
| 733 |
"function" % (name,)) |
| 734 |
|
| 735 |
assert str not in unwrap_spec |
| 736 |
|
| 737 |
return unwrap_spec |
| 738 |
|
| 739 |
|
| 740 |
class BuiltinCode(Code): |
| 741 |
"The code object implementing a built-in (interpreter-level) hook." |
| 742 |
_immutable_ = True |
| 743 |
hidden_applevel = True |
| 744 |
descrmismatch_op = None |
| 745 |
descr_reqcls = None |
| 746 |
|
| 747 |
|
| 748 |
|
| 749 |
|
| 750 |
@not_rpython |
| 751 |
def __init__(self, func, unwrap_spec=None, self_type=None, |
| 752 |
descrmismatch=None, doc=None): |
| 753 |
from rpython.rlib import rutf8 |
| 754 |
from rpython.flowspace.bytecode import cpython_code_signature |
| 755 |
|
| 756 |
|
| 757 |
Code.__init__(self, func.__name__) |
| 758 |
self.docstring = doc or func.__doc__ |
| 759 |
if self.docstring: |
| 760 |
|
| 761 |
rutf8.check_utf8(self.docstring, False) |
| 762 |
|
| 763 |
self.identifier = "%s-%s-%s" % (func.__module__, func.__name__, |
| 764 |
getattr(self_type, '__name__', '*')) |
| 765 |
|
| 766 |
|
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
|
| 771 |
|
| 772 |
|
| 773 |
|
| 774 |
|
| 775 |
|
| 776 |
|
| 777 |
|
| 778 |
sig = cpython_code_signature(func.func_code) |
| 779 |
argnames = sig.argnames |
| 780 |
varargname = sig.varargname |
| 781 |
kwargname = sig.kwargname |
| 782 |
self._argnames = argnames |
| 783 |
|
| 784 |
if unwrap_spec is None: |
| 785 |
unwrap_spec = build_unwrap_spec(func, argnames, self_type) |
| 786 |
|
| 787 |
if self_type: |
| 788 |
assert unwrap_spec[0] == 'self', "self_type without 'self' spec element" |
| 789 |
unwrap_spec = list(unwrap_spec) |
| 790 |
if descrmismatch is not None: |
| 791 |
assert issubclass(self_type, W_Root) |
| 792 |
unwrap_spec[0] = ('INTERNAL:self', self_type) |
| 793 |
self.descrmismatch_op = descrmismatch |
| 794 |
self.descr_reqcls = self_type |
| 795 |
else: |
| 796 |
unwrap_spec[0] = self_type |
| 797 |
else: |
| 798 |
assert descrmismatch is None, ( |
| 799 |
"descrmismatch without a self-type specified") |
| 800 |
|
| 801 |
app_sig = SignatureBuilder(func) |
| 802 |
|
| 803 |
UnwrapSpec_Check(func, argnames).apply_over(unwrap_spec, app_sig) |
| 804 |
self.sig = app_sig.signature() |
| 805 |
argnames = self.sig.argnames |
| 806 |
varargname = self.sig.varargname |
| 807 |
|
| 808 |
self.minargs = len(argnames) |
| 809 |
if varargname: |
| 810 |
self.maxargs = sys.maxint |
| 811 |
else: |
| 812 |
self.maxargs = self.minargs |
| 813 |
|
| 814 |
self.activation = UnwrapSpec_EmitRun.make_activation(unwrap_spec, func, self.sig) |
| 815 |
self._bltin = func |
| 816 |
self._unwrap_spec = unwrap_spec |
| 817 |
|
| 818 |
|
| 819 |
if 0 <= len(unwrap_spec) <= 5: |
| 820 |
try: |
| 821 |
arity, fastfunc = UnwrapSpec_FastFunc_Unwrap.make_fastfunc( |
| 822 |
unwrap_spec, func) |
| 823 |
except FastFuncNotSupported: |
| 824 |
if unwrap_spec == [ObjSpace, Arguments]: |
| 825 |
self.__class__ = BuiltinCodePassThroughArguments0 |
| 826 |
self.func__args__ = func |
| 827 |
elif unwrap_spec == [ObjSpace, W_Root, Arguments]: |
| 828 |
self.__class__ = BuiltinCodePassThroughArguments1 |
| 829 |
self.func__args__ = func |
| 830 |
elif unwrap_spec == [self_type, ObjSpace, Arguments]: |
| 831 |
self.__class__ = BuiltinCodePassThroughArguments1 |
| 832 |
self.descr_reqcls = self_type |
| 833 |
miniglobals = {'func': func, 'self_type': self_type} |
| 834 |
d = {} |
| 835 |
source = """if 1: |
| 836 |
def _call(space, w_obj, args): |
| 837 |
self = space.descr_self_interp_w(self_type, w_obj) |
| 838 |
return func(self, space, args) |
| 839 |
\n""" |
| 840 |
exec compile2(source) in miniglobals, d |
| 841 |
self.func__args__ = d['_call'] |
| 842 |
else: |
| 843 |
self.__class__ = globals()['BuiltinCode%d' % arity] |
| 844 |
setattr(self, 'fastfunc_%d' % arity, fastfunc) |
| 845 |
|
| 846 |
def descr__reduce__(self, space): |
| 847 |
from pypy.interpreter.mixedmodule import MixedModule |
| 848 |
w_mod = space.getbuiltinmodule('_pickle_support') |
| 849 |
mod = space.interp_w(MixedModule, w_mod) |
| 850 |
builtin_code = mod.get('builtin_code') |
| 851 |
return space.newtuple2(builtin_code, |
| 852 |
space.newtuple([space.newtext(self.identifier)])) |
| 853 |
|
| 854 |
@staticmethod |
| 855 |
def find(space, identifier): |
| 856 |
from pypy.interpreter.function import Function |
| 857 |
func = Function.find(space, identifier) |
| 858 |
if not func: |
| 859 |
raise oefmt(space.w_ValueError, "invalid code: '%s'", identifier) |
| 860 |
return func.code |
| 861 |
|
| 862 |
def signature(self): |
| 863 |
return self.sig |
| 864 |
|
| 865 |
def getdocstring(self, space): |
| 866 |
return space.newtext_or_none(self.docstring) |
| 867 |
|
| 868 |
def funcrun(self, func, args): |
| 869 |
return BuiltinCode.funcrun_obj(self, func, None, args) |
| 870 |
|
| 871 |
def funcrun_obj(self, func, w_obj, args): |
| 872 |
space = func.space |
| 873 |
activation = self.activation |
| 874 |
|
| 875 |
scope_w = args.parse_obj(w_obj, func.qualname, self.sig, |
| 876 |
func.defs_w, func.w_kw_defs, self.minargs) |
| 877 |
try: |
| 878 |
w_result = activation._run(space, scope_w) |
| 879 |
except DescrMismatch: |
| 880 |
if w_obj is not None: |
| 881 |
args = args.prepend(w_obj) |
| 882 |
return self._type_unwrap_mismatch(space, args) |
| 883 |
except Exception as e: |
| 884 |
self.handle_exception(space, e) |
| 885 |
w_result = None |
| 886 |
if w_result is None: |
| 887 |
w_result = space.w_None |
| 888 |
return w_result |
| 889 |
|
| 890 |
def _type_unwrap_mismatch(self, space, args): |
| 891 |
w_obj = args.firstarg() |
| 892 |
if w_obj is None: |
| 893 |
raise oefmt(space.w_SystemError, "unexpected DescrMismatch error") |
| 894 |
return w_obj.descr_call_mismatch(space, |
| 895 |
self.descrmismatch_op, |
| 896 |
self.descr_reqcls, |
| 897 |
args) |
| 898 |
|
| 899 |
def handle_exception(self, space, e): |
| 900 |
try: |
| 901 |
if not we_are_translated(): |
| 902 |
raise |
| 903 |
raise e |
| 904 |
except OperationError: |
| 905 |
raise |
| 906 |
except Exception as e: |
| 907 |
from pypy.interpreter import error |
| 908 |
raise error.get_converted_unexpected_exception(space, e) |
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
class BuiltinCodePassThroughArguments0(BuiltinCode): |
| 914 |
_immutable_ = True |
| 915 |
|
| 916 |
def funcrun(self, func, args): |
| 917 |
space = func.space |
| 918 |
try: |
| 919 |
w_result = self.func__args__(space, args) |
| 920 |
except DescrMismatch: |
| 921 |
return self._type_unwrap_mismatch(space, args) |
| 922 |
except Exception as e: |
| 923 |
self.handle_exception(space, e) |
| 924 |
w_result = None |
| 925 |
if w_result is None: |
| 926 |
w_result = space.w_None |
| 927 |
return w_result |
| 928 |
|
| 929 |
|
| 930 |
class BuiltinCodePassThroughArguments1(BuiltinCode): |
| 931 |
_immutable_ = True |
| 932 |
fast_natural_arity = Code.PASSTHROUGHARGS1 |
| 933 |
|
| 934 |
def funcrun_obj(self, func, w_obj, args): |
| 935 |
space = func.space |
| 936 |
try: |
| 937 |
w_result = self.func__args__(space, w_obj, args) |
| 938 |
except DescrMismatch: |
| 939 |
return self._type_unwrap_mismatch(space, args.prepend(w_obj)) |
| 940 |
except Exception as e: |
| 941 |
self.handle_exception(space, e) |
| 942 |
w_result = None |
| 943 |
if w_result is None: |
| 944 |
w_result = space.w_None |
| 945 |
return w_result |
| 946 |
|
| 947 |
|
| 948 |
class BuiltinCode0(BuiltinCode): |
| 949 |
_immutable_ = True |
| 950 |
fast_natural_arity = 0 |
| 951 |
|
| 952 |
def fastcall_0(self, space, w_func): |
| 953 |
try: |
| 954 |
w_result = self.fastfunc_0(space) |
| 955 |
except DescrMismatch: |
| 956 |
raise oefmt(space.w_SystemError, "unexpected DescrMismatch error") |
| 957 |
except Exception as e: |
| 958 |
self.handle_exception(space, e) |
| 959 |
w_result = None |
| 960 |
if w_result is None: |
| 961 |
w_result = space.w_None |
| 962 |
return w_result |
| 963 |
|
| 964 |
w_root_or_none = sigtypes.instance(W_Root, can_be_None=True) |
| 965 |
|
| 966 |
@finishsigs |
| 967 |
class BuiltinCode1(BuiltinCode): |
| 968 |
_immutable_ = True |
| 969 |
fast_natural_arity = 1 |
| 970 |
|
| 971 |
@signature(sigtypes.self(), sigtypes.any(), |
| 972 |
w_root_or_none, |
| 973 |
w_root_or_none, |
| 974 |
returns=w_root_or_none) |
| 975 |
def fastcall_1(self, space, w_func, w1): |
| 976 |
try: |
| 977 |
w_result = self.fastfunc_1(space, w1) |
| 978 |
except DescrMismatch: |
| 979 |
return self._type_unwrap_mismatch(space, |
| 980 |
Arguments(space, [w1])) |
| 981 |
except Exception as e: |
| 982 |
self.handle_exception(space, e) |
| 983 |
w_result = None |
| 984 |
if w_result is None: |
| 985 |
w_result = space.w_None |
| 986 |
return w_result |
| 987 |
|
| 988 |
|
| 989 |
@finishsigs |
| 990 |
class BuiltinCode2(BuiltinCode): |
| 991 |
_immutable_ = True |
| 992 |
fast_natural_arity = 2 |
| 993 |
|
| 994 |
@signature(sigtypes.self(), sigtypes.any(), |
| 995 |
w_root_or_none, |
| 996 |
w_root_or_none, |
| 997 |
w_root_or_none, |
| 998 |
returns=w_root_or_none) |
| 999 |
def fastcall_2(self, space, w_func, w1, w2): |
| 1000 |
try: |
| 1001 |
w_result = self.fastfunc_2(space, w1, w2) |
| 1002 |
except DescrMismatch: |
| 1003 |
return self._type_unwrap_mismatch(space, |
| 1004 |
Arguments(space, [w1, w2])) |
| 1005 |
except Exception as e: |
| 1006 |
self.handle_exception(space, e) |
| 1007 |
w_result = None |
| 1008 |
if w_result is None: |
| 1009 |
w_result = space.w_None |
| 1010 |
return w_result |
| 1011 |
|
| 1012 |
|
| 1013 |
@finishsigs |
| 1014 |
class BuiltinCode3(BuiltinCode): |
| 1015 |
_immutable_ = True |
| 1016 |
fast_natural_arity = 3 |
| 1017 |
|
| 1018 |
@signature(sigtypes.self(), sigtypes.any(), |
| 1019 |
w_root_or_none, |
| 1020 |
w_root_or_none, |
| 1021 |
w_root_or_none, |
| 1022 |
w_root_or_none, |
| 1023 |
returns=w_root_or_none) |
| 1024 |
def fastcall_3(self, space, func, w1, w2, w3): |
| 1025 |
try: |
| 1026 |
w_result = self.fastfunc_3(space, w1, w2, w3) |
| 1027 |
except DescrMismatch: |
| 1028 |
return self._type_unwrap_mismatch(space, |
| 1029 |
Arguments(space, [w1, w2, w3])) |
| 1030 |
except Exception as e: |
| 1031 |
self.handle_exception(space, e) |
| 1032 |
w_result = None |
| 1033 |
if w_result is None: |
| 1034 |
w_result = space.w_None |
| 1035 |
return w_result |
| 1036 |
|
| 1037 |
@finishsigs |
| 1038 |
class BuiltinCode4(BuiltinCode): |
| 1039 |
_immutable_ = True |
| 1040 |
fast_natural_arity = 4 |
| 1041 |
|
| 1042 |
@signature(sigtypes.self(), sigtypes.any(), |
| 1043 |
w_root_or_none, |
| 1044 |
w_root_or_none, |
| 1045 |
w_root_or_none, |
| 1046 |
w_root_or_none, |
| 1047 |
w_root_or_none, |
| 1048 |
returns=w_root_or_none) |
| 1049 |
def fastcall_4(self, space, func, w1, w2, w3, w4): |
| 1050 |
from rpython.rlib.debug import check_annotation |
| 1051 |
try: |
| 1052 |
w_result = self.fastfunc_4(space, w1, w2, w3, w4) |
| 1053 |
except DescrMismatch: |
| 1054 |
return self._type_unwrap_mismatch(space, |
| 1055 |
Arguments(space, |
| 1056 |
[w1, w2, w3, w4])) |
| 1057 |
except Exception as e: |
| 1058 |
self.handle_exception(space, e) |
| 1059 |
w_result = None |
| 1060 |
if w_result is None: |
| 1061 |
w_result = space.w_None |
| 1062 |
return w_result |
| 1063 |
|
| 1064 |
def interpindirect2app(unbound_meth, unwrap_spec=None): |
| 1065 |
base_cls = unbound_meth.im_class |
| 1066 |
func = unbound_meth.im_func |
| 1067 |
args = inspect.getargs(func.func_code) |
| 1068 |
if args.varargs or args.keywords: |
| 1069 |
raise TypeError("Varargs and keywords not supported in unwrap_spec") |
| 1070 |
argspec = ', '.join([arg for arg in args.args[1:]]) |
| 1071 |
func_code = py.code.Source(""" |
| 1072 |
def f(self, %(args)s): |
| 1073 |
return self.%(func_name)s(%(args)s) |
| 1074 |
""" % {'args': argspec, 'func_name': func.func_name}) |
| 1075 |
d = {} |
| 1076 |
exec func_code.compile() in d |
| 1077 |
f = d['f'] |
| 1078 |
f.func_defaults = unbound_meth.func_defaults |
| 1079 |
f.func_doc = unbound_meth.func_doc |
| 1080 |
f.__module__ = func.__module__ |
| 1081 |
f.__text_signature__ = getattr(func, '__text_signature__', None) |
| 1082 |
|
| 1083 |
f.func_name = func.func_name |
| 1084 |
if unwrap_spec is None: |
| 1085 |
unwrap_spec = getattr(unbound_meth, 'unwrap_spec', {}) |
| 1086 |
else: |
| 1087 |
assert isinstance(unwrap_spec, dict) |
| 1088 |
unwrap_spec = unwrap_spec.copy() |
| 1089 |
unwrap_spec['self'] = 'self' |
| 1090 |
return interp2app(globals()['unwrap_spec'](**unwrap_spec)(f), |
| 1091 |
self_type=base_cls) |
| 1092 |
|
| 1093 |
class interp2app(W_Root): |
| 1094 |
"""Build a gateway that calls 'f' at interp-level.""" |
| 1095 |
|
| 1096 |
|
| 1097 |
|
| 1098 |
instancecache = {} |
| 1099 |
|
| 1100 |
@not_rpython |
| 1101 |
def __new__(cls, f, app_name=None, unwrap_spec=None, descrmismatch=None, |
| 1102 |
as_classmethod=False, doc=None, self_type=None): |
| 1103 |
|
| 1104 |
|
| 1105 |
if hasattr(f, 'im_func'): |
| 1106 |
assert self_type in (None, f.im_class) |
| 1107 |
self_type = f.im_class |
| 1108 |
f = f.im_func |
| 1109 |
if not isinstance(f, types.FunctionType): |
| 1110 |
raise TypeError("function expected, got %r instead" % f) |
| 1111 |
if app_name is None: |
| 1112 |
if f.func_name.startswith('app_'): |
| 1113 |
raise ValueError("function name %r suspiciously starts " |
| 1114 |
"with 'app_'" % f.func_name) |
| 1115 |
app_name = f.func_name |
| 1116 |
|
| 1117 |
if unwrap_spec is not None: |
| 1118 |
unwrap_spec_key = tuple(unwrap_spec) |
| 1119 |
else: |
| 1120 |
unwrap_spec_key = None |
| 1121 |
key = (f, self_type, unwrap_spec_key, descrmismatch, as_classmethod) |
| 1122 |
if key in cls.instancecache: |
| 1123 |
result = cls.instancecache[key] |
| 1124 |
assert result.__class__ is cls |
| 1125 |
return result |
| 1126 |
self = W_Root.__new__(cls) |
| 1127 |
cls.instancecache[key] = self |
| 1128 |
self._code = BuiltinCode(f, unwrap_spec=unwrap_spec, |
| 1129 |
self_type=self_type, |
| 1130 |
descrmismatch=descrmismatch, |
| 1131 |
doc=doc) |
| 1132 |
self.__name__ = f.func_name |
| 1133 |
self.name = app_name |
| 1134 |
self.as_classmethod = as_classmethod |
| 1135 |
|
| 1136 |
argnames = self._code._argnames |
| 1137 |
defaults = f.func_defaults or () |
| 1138 |
self._staticdefs = dict(zip( |
| 1139 |
argnames[len(argnames) - len(defaults):], defaults)) |
| 1140 |
self.self_type = self_type |
| 1141 |
self._explicit_text_sig = getattr(f, '__text_signature__', None) |
| 1142 |
|
| 1143 |
return self |
| 1144 |
|
| 1145 |
@not_rpython |
| 1146 |
def _generate_text_signature(self): |
| 1147 |
"""Generate a __text_signature__ string for use by inspect.signature.""" |
| 1148 |
if self._explicit_text_sig is not None: |
| 1149 |
return self._explicit_text_sig |
| 1150 |
code = self._code |
| 1151 |
sig = code.sig |
| 1152 |
|
| 1153 |
if sig.varargname or sig.kwargname: |
| 1154 |
return None |
| 1155 |
|
| 1156 |
defaults_map = {} |
| 1157 |
for rpyname, spec in zip(code._argnames, code._unwrap_spec): |
| 1158 |
if rpyname in ('__posonly__', '__kwonly__', '__args__', 'w_args') or (rpyname.endswith('_w') and not rpyname.startswith('w_')): |
| 1159 |
continue |
| 1160 |
pyname = rpyname[2:] if rpyname.startswith('w_') else rpyname |
| 1161 |
if isinstance(spec, WrappedDefault): |
| 1162 |
defaults_map[pyname] = spec.default_value |
| 1163 |
elif rpyname in self._staticdefs: |
| 1164 |
if isinstance(spec, type) and issubclass(spec, Unwrapper) and hasattr(spec, 'text_default'): |
| 1165 |
defaults_map[pyname] = spec.text_default |
| 1166 |
else: |
| 1167 |
defaults_map[pyname] = self._staticdefs[rpyname] |
| 1168 |
argnames = sig.argnames |
| 1169 |
kwonly_count = sig.kwonlyargcount |
| 1170 |
pos_argnames = argnames[:len(argnames) - kwonly_count] |
| 1171 |
kw_argnames = argnames[len(argnames) - kwonly_count:] |
| 1172 |
posonlyargcount = sig.posonlyargcount |
| 1173 |
parts = [] |
| 1174 |
if self.self_type is None: |
| 1175 |
if getattr(self, '_is_type_method', False) and pos_argnames: |
| 1176 |
|
| 1177 |
|
| 1178 |
|
| 1179 |
|
| 1180 |
parts.append('$' + pos_argnames[0]) |
| 1181 |
pos_argnames = list(pos_argnames[1:]) |
| 1182 |
else: |
| 1183 |
parts.append('$module') |
| 1184 |
posonly_slash_added = False |
| 1185 |
for i, name in enumerate(pos_argnames): |
| 1186 |
if self.self_type is not None and i == 0 and name == 'self': |
| 1187 |
parts.append('$self') |
| 1188 |
continue |
| 1189 |
if posonlyargcount > 0 and i == posonlyargcount and not posonly_slash_added: |
| 1190 |
parts.append('/') |
| 1191 |
posonly_slash_added = True |
| 1192 |
if name in defaults_map: |
| 1193 |
parts.append('%s=%r' % (name, defaults_map[name])) |
| 1194 |
else: |
| 1195 |
parts.append(name) |
| 1196 |
if not kw_argnames and not posonly_slash_added: |
| 1197 |
parts.append('/') |
| 1198 |
elif posonlyargcount > 0 and not posonly_slash_added: |
| 1199 |
parts.append('/') |
| 1200 |
if kw_argnames: |
| 1201 |
parts.append('*') |
| 1202 |
for name in kw_argnames: |
| 1203 |
if name in defaults_map: |
| 1204 |
parts.append('%s=%r' % (name, defaults_map[name])) |
| 1205 |
else: |
| 1206 |
parts.append(name) |
| 1207 |
return '(' + ', '.join(parts) + ')' |
| 1208 |
|
| 1209 |
@not_rpython |
| 1210 |
def _getdefaults(self, space): |
| 1211 |
alldefs_w = {} |
| 1212 |
assert len(self._code._argnames) == len(self._code._unwrap_spec) |
| 1213 |
for name, spec in zip(self._code._argnames, self._code._unwrap_spec): |
| 1214 |
if name in ('__posonly__', '__kwonly__'): |
| 1215 |
continue |
| 1216 |
|
| 1217 |
defaultval = self._staticdefs.get(name, NO_DEFAULT) |
| 1218 |
w_def = Ellipsis |
| 1219 |
if name.startswith('w_'): |
| 1220 |
assert defaultval in (NO_DEFAULT, None), ( |
| 1221 |
"%s: default value for '%s' can only be None, got %r; " |
| 1222 |
"use unwrap_spec(...=WrappedDefault(default))" % ( |
| 1223 |
self._code.identifier, name, defaultval)) |
| 1224 |
if defaultval is None: |
| 1225 |
w_def = None |
| 1226 |
|
| 1227 |
if isinstance(spec, tuple) and spec[0] is W_Root: |
| 1228 |
assert False, "use WrappedDefault" |
| 1229 |
elif isinstance(spec, WrappedDefault): |
| 1230 |
assert name.startswith('w_') |
| 1231 |
defaultval = spec.default_value |
| 1232 |
w_def = Ellipsis |
| 1233 |
|
| 1234 |
if defaultval is not NO_DEFAULT: |
| 1235 |
if name != '__args__' and not (name.endswith('_w') and not name.startswith('w_')): |
| 1236 |
if w_def is Ellipsis: |
| 1237 |
if isinstance(defaultval, str) and ( |
| 1238 |
|
| 1239 |
spec == 'bytes' or spec == 'bufferstr' |
| 1240 |
or isinstance(spec, WrappedDefault)): |
| 1241 |
w_def = space.newbytes(defaultval) |
| 1242 |
else: |
| 1243 |
w_def = space.wrap(defaultval) |
| 1244 |
if name.startswith('w_'): |
| 1245 |
name = name[2:] |
| 1246 |
alldefs_w[name] = w_def |
| 1247 |
|
| 1248 |
|
| 1249 |
|
| 1250 |
|
| 1251 |
|
| 1252 |
|
| 1253 |
|
| 1254 |
sig = self._code.sig |
| 1255 |
first_defined = 0 |
| 1256 |
allposargnames = sig.argnames[:sig.num_argnames()] |
| 1257 |
n_allposargnames = len(allposargnames) |
| 1258 |
while (first_defined < n_allposargnames and |
| 1259 |
allposargnames[first_defined] not in alldefs_w): |
| 1260 |
first_defined += 1 |
| 1261 |
defs_w = [alldefs_w.pop(name) for name in allposargnames[first_defined:]] |
| 1262 |
|
| 1263 |
kw_defs_w = None |
| 1264 |
if alldefs_w: |
| 1265 |
kw_defs_w = [] |
| 1266 |
for name, w_def in sorted(alldefs_w.items()): |
| 1267 |
assert name in sig.argnames[-sig.kwonlyargcount:] |
| 1268 |
w_name = space.newtext(name) |
| 1269 |
kw_defs_w.append((w_name, w_def)) |
| 1270 |
|
| 1271 |
return defs_w, kw_defs_w |
| 1272 |
|
| 1273 |
|
| 1274 |
|
| 1275 |
def spacebind(self, space): |
| 1276 |
|
| 1277 |
|
| 1278 |
return self.get_function(space) |
| 1279 |
|
| 1280 |
def get_function(self, space): |
| 1281 |
return self.getcache(space).getorbuild(self) |
| 1282 |
|
| 1283 |
def getcache(self, space): |
| 1284 |
return space.fromcache(GatewayCache) |
| 1285 |
|
| 1286 |
|
| 1287 |
|
| 1288 |
_shortcut = None |
| 1289 |
|
| 1290 |
def _make_descroperation_shortcut(self, name, rpy_cls, checkerfunc): |
| 1291 |
if self._shortcut: |
| 1292 |
return self._shortcut |
| 1293 |
emit = UnwrapSpec_EmitShortcut(rpy_cls) |
| 1294 |
emit.apply_over(self._code._unwrap_spec) |
| 1295 |
assert emit.rpy_cls is rpy_cls |
| 1296 |
d = {} |
| 1297 |
f = self._code.activation.behavior |
| 1298 |
d['func'] = f |
| 1299 |
d['checkerfunc'] = checkerfunc |
| 1300 |
d['we_are_translated'] = we_are_translated |
| 1301 |
source = """def shortcut_%s(self, space, %s): # for %s |
| 1302 |
w_res = func(%s) |
| 1303 |
if not we_are_translated(): |
| 1304 |
assert not self.user_overridden_class |
| 1305 |
if checkerfunc: |
| 1306 |
assert checkerfunc(space, w_res) |
| 1307 |
if w_res is None: |
| 1308 |
return space.w_None |
| 1309 |
return w_res |
| 1310 |
""" % (name, ", ".join(emit.extraargs), |
| 1311 |
rpy_cls, ', '.join(emit.run_args)) |
| 1312 |
exec compile2(source) in d |
| 1313 |
shortcut = d['shortcut_%s' % name] |
| 1314 |
self._shortcut = shortcut |
| 1315 |
return shortcut |
| 1316 |
|
| 1317 |
|
| 1318 |
class GatewayCache(SpaceCache): |
| 1319 |
@not_rpython |
| 1320 |
def build(cache, gateway): |
| 1321 |
space = cache.space |
| 1322 |
defs_w, kw_defs_w = gateway._getdefaults(space) |
| 1323 |
code = gateway._code |
| 1324 |
fn = FunctionWithFixedCode(space, code, None, defs_w, kw_defs_w, |
| 1325 |
forcename=gateway.name) |
| 1326 |
if not space.config.translating: |
| 1327 |
fn.add_to_table() |
| 1328 |
text_sig = gateway._generate_text_signature() |
| 1329 |
if text_sig: |
| 1330 |
fn.w_text_signature = space.newtext(text_sig) |
| 1331 |
if not code.docstring: |
| 1332 |
code.docstring = '%s%s\n--\n\n' % (gateway.name, text_sig) |
| 1333 |
if gateway.as_classmethod: |
| 1334 |
fn = ClassMethod(fn) |
| 1335 |
|
| 1336 |
from pypy.module.sys.vm import exc_info |
| 1337 |
if code._bltin is exc_info: |
| 1338 |
assert space._code_of_sys_exc_info is None |
| 1339 |
space._code_of_sys_exc_info = code |
| 1340 |
|
| 1341 |
if hasattr(space, '_see_interp2app'): |
| 1342 |
space._see_interp2app(gateway) |
| 1343 |
return fn |
| 1344 |
|
| 1345 |
|
| 1346 |
|
| 1347 |
|
| 1348 |
|
| 1349 |
|
| 1350 |
class interp2app_temp(interp2app): |
| 1351 |
"NOT_RPYTHON" |
| 1352 |
def getcache(self, space): |
| 1353 |
return self.__dict__.setdefault(space, GatewayCache(space)) |
| 1354 |
|
| 1355 |
|
| 1356 |
|
| 1357 |
|
| 1358 |
|
| 1359 |
class ApplevelClass: |
| 1360 |
"""NOT_RPYTHON |
| 1361 |
A container for app-level source code that should be executed |
| 1362 |
as a module in the object space; interphook() builds a static |
| 1363 |
interp-level function that invokes the callable with the given |
| 1364 |
name at app-level.""" |
| 1365 |
|
| 1366 |
hidden_applevel = True |
| 1367 |
|
| 1368 |
def __init__(self, source, filename=None, modname='__builtin__'): |
| 1369 |
|
| 1370 |
self.filename = filename |
| 1371 |
self.source = str(py.code.Source(source).deindent()) |
| 1372 |
self.modname = modname |
| 1373 |
if filename is None: |
| 1374 |
f = sys._getframe(1) |
| 1375 |
filename = '<%s:%d>' % (f.f_code.co_filename, f.f_lineno) |
| 1376 |
if not os.path.exists(filename): |
| 1377 |
|
| 1378 |
lines = [x + "\n" for x in source.split("\n")] |
| 1379 |
py.std.linecache.cache[filename] = (1, None, lines, filename) |
| 1380 |
self.filename = filename |
| 1381 |
|
| 1382 |
def __repr__(self): |
| 1383 |
return "<ApplevelClass filename=%r>" % (self.filename,) |
| 1384 |
|
| 1385 |
def getwdict(self, space): |
| 1386 |
return space.fromcache(ApplevelCache).getorbuild(self) |
| 1387 |
|
| 1388 |
def buildmodule(self, space, name='applevel'): |
| 1389 |
from pypy.interpreter.module import Module |
| 1390 |
return Module(space, space.newtext(name), self.getwdict(space)) |
| 1391 |
|
| 1392 |
def wget(self, space, name): |
| 1393 |
w_globals = self.getwdict(space) |
| 1394 |
return space.getitem(w_globals, space.newtext(name)) |
| 1395 |
|
| 1396 |
@not_rpython |
| 1397 |
def interphook(self, name): |
| 1398 |
def appcaller(space, *args_w): |
| 1399 |
if not isinstance(space, ObjSpace): |
| 1400 |
raise TypeError("first argument must be a space instance.") |
| 1401 |
|
| 1402 |
w_func = self.wget(space, name) |
| 1403 |
if not args_w: |
| 1404 |
return space.call_function(w_func) |
| 1405 |
else: |
| 1406 |
args = args_w[-1] |
| 1407 |
assert args is not None |
| 1408 |
if not isinstance(args, Arguments): |
| 1409 |
return space.call_function(w_func, *args_w) |
| 1410 |
else: |
| 1411 |
if len(args_w) == 2: |
| 1412 |
return space.call_obj_args(w_func, args_w[0], args) |
| 1413 |
elif len(args_w) > 2: |
| 1414 |
|
| 1415 |
|
| 1416 |
args = args.replace_arguments(list(args_w[:-1]) + |
| 1417 |
args.arguments_w) |
| 1418 |
return space.call_args(w_func, args) |
| 1419 |
def get_function(space): |
| 1420 |
w_func = self.wget(space, name) |
| 1421 |
return space.unwrap(w_func) |
| 1422 |
appcaller = func_with_new_name(appcaller, name) |
| 1423 |
appcaller.get_function = get_function |
| 1424 |
return appcaller |
| 1425 |
|
| 1426 |
def _freeze_(self): |
| 1427 |
return True |
| 1428 |
|
| 1429 |
|
| 1430 |
class ApplevelCache(SpaceCache): |
| 1431 |
"""NOT_RPYTHON |
| 1432 |
The cache mapping each applevel instance to its lazily built w_dict""" |
| 1433 |
|
| 1434 |
@not_rpython |
| 1435 |
def build(self, app): |
| 1436 |
"Called indirectly by Applevel.getwdict()." |
| 1437 |
return build_applevel_dict(app, self.space) |
| 1438 |
|
| 1439 |
|
| 1440 |
|
| 1441 |
|
| 1442 |
@not_rpython |
| 1443 |
def build_applevel_dict(self, space): |
| 1444 |
w_glob = space.newdict(module=True) |
| 1445 |
space.setitem(w_glob, space.newtext('__name__'), space.newtext(self.modname)) |
| 1446 |
space.exec_(self.source, w_glob, w_glob, |
| 1447 |
hidden_applevel=self.hidden_applevel, |
| 1448 |
filename=self.filename) |
| 1449 |
return w_glob |
| 1450 |
|
| 1451 |
|
| 1452 |
|
| 1453 |
|
| 1454 |
@not_rpython |
| 1455 |
def appdef(source, applevel=ApplevelClass, filename=None): |
| 1456 |
""" build an app-level helper function, like for example: |
| 1457 |
myfunc = appdef('''myfunc(x, y): |
| 1458 |
return x+y |
| 1459 |
''') |
| 1460 |
""" |
| 1461 |
prefix = "" |
| 1462 |
if not isinstance(source, str): |
| 1463 |
flags = source.__code__.co_flags |
| 1464 |
source = py.std.inspect.getsource(source).lstrip() |
| 1465 |
while source.startswith(('@py.test.mark.', '@pytest.mark.')): |
| 1466 |
|
| 1467 |
|
| 1468 |
assert '\n' in source |
| 1469 |
source = source[source.find('\n') + 1:].lstrip() |
| 1470 |
assert source.startswith("def "), "can only transform functions" |
| 1471 |
source = source[4:] |
| 1472 |
|
| 1473 |
|
| 1474 |
|
| 1475 |
|
| 1476 |
|
| 1477 |
|
| 1478 |
|
| 1479 |
|
| 1480 |
|
| 1481 |
p = source.find('(') |
| 1482 |
assert p >= 0 |
| 1483 |
funcname = source[:p].strip() |
| 1484 |
source = source[p:] |
| 1485 |
assert source.strip() |
| 1486 |
funcsource = prefix + "def %s%s\n" % (funcname, source) |
| 1487 |
|
| 1488 |
a = applevel(funcsource, filename=filename) |
| 1489 |
return a.interphook(funcname) |
| 1490 |
|
| 1491 |
applevel = ApplevelClass |
| 1492 |
app2interp = appdef |
| 1493 |
|
| 1494 |
|
| 1495 |
class applevel_temp(ApplevelClass): |
| 1496 |
hidden_applevel = False |
| 1497 |
def getwdict(self, space): |
| 1498 |
return build_applevel_dict(self, space) |
| 1499 |
|
| 1500 |
|
| 1501 |
|
| 1502 |
@not_rpython |
| 1503 |
def app2interp_temp(func, applevel_temp=applevel_temp, filename=None): |
| 1504 |
return appdef(func, applevel_temp, filename=filename) |
| 1505 |
|
| 1506 |
|
| 1507 |
@unwrap_spec(w_owner = WrappedDefault(None)) |
| 1508 |
def descr_function_get(space, w_function, w_instance, w_owner=None): |
| 1509 |
"""functionobject.__get__(instance, owner=None, /) -> method""" |
| 1510 |
|
| 1511 |
|
| 1512 |
if space.is_none(w_instance): |
| 1513 |
if space.is_none(w_owner): |
| 1514 |
raise oefmt(space.w_TypeError, "__get__(None, None) is invalid") |
| 1515 |
return w_function |
| 1516 |
else: |
| 1517 |
return Method(space, w_function, w_instance) |