/
gateway.py
1322 lines (1085 loc) · 45.9 KB
/
gateway.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Gateway between app-level and interpreter-level:
* BuiltinCode (call interp-level code from app-level)
* app2interp (embed an app-level function into an interp-level callable)
* interp2app (publish an interp-level object to be visible from app-level)
* interpindirect2app (publish an interp-level object to be visible from
app-level as an indirect call to implementation)
"""
import sys
import os
import types
import inspect
import py
from pypy.interpreter.eval import Code
from pypy.interpreter.argument import Arguments
from pypy.interpreter.signature import Signature
from pypy.interpreter.baseobjspace import (W_Root, ObjSpace, SpaceCache,
DescrMismatch)
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.function import ClassMethod, FunctionWithFixedCode
from rpython.rlib.objectmodel import we_are_translated, not_rpython
from rpython.rlib.rarithmetic import r_longlong, r_int, r_ulonglong, r_uint
from rpython.tool.sourcetools import func_with_new_name, compile2
from rpython.rlib.signature import signature, finishsigs
from rpython.rlib import types as sigtypes
# internal non-translatable parts:
class SignatureBuilder(object):
"NOT_RPYTHON"
def __init__(self, func=None, argnames=None, varargname=None,
kwargname=None, name=None):
self.func = func
if func is not None:
self.name = func.__name__
else:
self.name = name
if argnames is None:
argnames = []
self.argnames = argnames
self.varargname = varargname
self.kwargname = kwargname
def append(self, argname):
self.argnames.append(argname)
def signature(self):
return Signature(self.argnames, self.varargname, self.kwargname)
#________________________________________________________________
class Unwrapper(object):
"""A base class for custom unwrap_spec items.
Subclasses must override unwrap().
"""
def _freeze_(self):
return True
@not_rpython
def unwrap(self, space, w_value):
raise NotImplementedError
class UnwrapSpecRecipe(object):
"NOT_RPYTHON"
bases_order = [W_Root, ObjSpace, Arguments, Unwrapper, object]
def dispatch(self, el, *args):
if isinstance(el, str):
getattr(self, "visit_%s" % (el,))(el, *args)
elif isinstance(el, tuple):
if el[0] == 'INTERNAL:self':
self.visit_self(el[1], *args)
else:
assert False, "not supported any more, use WrappedDefault"
elif isinstance(el, WrappedDefault):
self.visit__W_Root(W_Root, *args)
elif isinstance(el, type):
for typ in self.bases_order:
if issubclass(el, typ):
visit = getattr(self, "visit__%s" % (typ.__name__,))
visit(el, *args)
break
else:
raise Exception("%s: no match for unwrap_spec element %s" % (
self.__class__.__name__, el))
else:
raise Exception("unable to dispatch, %s, perhaps your parameter should have started with w_?" % el)
def apply_over(self, unwrap_spec, *extra):
dispatch = self.dispatch
for el in unwrap_spec:
dispatch(el, *extra)
class UnwrapSpecEmit(UnwrapSpecRecipe):
def __init__(self):
self.n = 0
self.miniglobals = {}
def succ(self):
n = self.n
self.n += 1
return n
def use(self, obj):
name = obj.__name__
self.miniglobals[name] = obj
return name
#________________________________________________________________
class UnwrapSpec_Check(UnwrapSpecRecipe):
# checks for checking interp2app func argument names wrt unwrap_spec
# and synthetizing an app-level signature
def __init__(self, func, argnames):
self.func = func
self.orig_arg = iter(argnames).next
def visit_self(self, cls, app_sig):
self.visit__W_Root(cls, app_sig)
def checked_space_method(self, typname, app_sig):
argname = self.orig_arg()
assert not argname.startswith('w_'), (
"unwrapped %s argument %s of built-in function %r in %r should "
"not start with 'w_'" % (typname, argname, self.func.func_name, self.func.func_globals['__name__']))
app_sig.append(argname)
def visit_index(self, index, app_sig):
self.checked_space_method(index, app_sig)
def visit_bufferstr(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_text_or_none(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_bytes(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_bytes0(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_text(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_text0(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_utf8(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_fsencode(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_fsencode_or_none(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_nonnegint(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_c_int(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_c_uint(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_c_nonnegint(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_c_short(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_c_ushort(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_c_uid_t(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit_truncatedint_w(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit__Unwrapper(self, el, app_sig):
self.checked_space_method(el, app_sig)
def visit__ObjSpace(self, el, app_sig):
self.orig_arg()
def visit__W_Root(self, el, app_sig):
argname = self.orig_arg()
if argname == 'self':
assert el is not W_Root
app_sig.append(argname)
return
assert argname.startswith('w_'), (
"argument %s of built-in function %r in %r should "
"start with 'w_'" % (argname, self.func.func_name, self.func.func_globals['__name__']))
app_sig.append(argname[2:])
def visit__Arguments(self, el, app_sig):
self.orig_arg()
assert app_sig.varargname is None, (
"built-in function %r has conflicting rest args specs" % self.func)
app_sig.varargname = 'args'
app_sig.kwargname = 'keywords'
def visit_args_w(self, el, app_sig):
argname = self.orig_arg()
assert argname.endswith('_w'), (
"rest arguments arg %s of built-in function %r should end in '_w'" %
(argname, self.func))
assert app_sig.varargname is None, (
"built-in function %r has conflicting rest args specs" % self.func)
app_sig.varargname = argname[:-2]
def visit_w_args(self, el, app_sig):
argname = self.orig_arg()
assert argname.startswith('w_'), (
"rest arguments arg %s of built-in function %r should start 'w_'" %
(argname, self.func))
assert app_sig.varargname is None, (
"built-in function %r has conflicting rest args specs" % self.func)
app_sig.varargname = argname[2:]
def visit__object(self, typ, app_sig):
name = int_unwrapping_space_method(typ)
self.checked_space_method(name, app_sig)
class UnwrapSpec_EmitRun(UnwrapSpecEmit):
# collect code to emit for interp2app builtin frames based on unwrap_spec
def __init__(self):
UnwrapSpecEmit.__init__(self)
self.run_args = []
def scopenext(self):
return "scope_w[%d]" % self.succ()
def visit_self(self, typ):
self.run_args.append("space.descr_self_interp_w(%s, %s)" %
(self.use(typ), self.scopenext()))
def visit__Unwrapper(self, typ):
self.run_args.append("%s().unwrap(space, %s)" %
(self.use(typ), self.scopenext()))
def visit__ObjSpace(self, el):
self.run_args.append('space')
def visit__W_Root(self, el):
if el is not W_Root:
self.run_args.append("space.interp_w(%s, %s)" % (self.use(el),
self.scopenext()))
else:
self.run_args.append(self.scopenext())
def visit__Arguments(self, el):
self.miniglobals['Arguments'] = Arguments
self.run_args.append("Arguments.frompacked(space, %s, %s)"
% (self.scopenext(), self.scopenext()))
def visit_args_w(self, el):
self.run_args.append("space.fixedview(%s)" % self.scopenext())
def visit_w_args(self, el):
self.run_args.append(self.scopenext())
def visit__object(self, typ):
name = int_unwrapping_space_method(typ)
self.run_args.append("space.%s(%s)" %
(name, self.scopenext()))
def visit_index(self, typ):
self.run_args.append("space.getindex_w(%s, space.w_OverflowError)"
% (self.scopenext(), ))
def visit_bufferstr(self, typ):
self.run_args.append("space.bufferstr_w(%s)" % (self.scopenext(),))
def visit_text_or_none(self, typ):
self.run_args.append("space.text_or_none_w(%s)" % (self.scopenext(),))
def visit_bytes(self, typ):
self.run_args.append("space.bytes_w(%s)" % (self.scopenext(),))
def visit_bytes0(self, typ):
self.run_args.append("space.bytes0_w(%s)" % (self.scopenext(),))
def visit_text(self, typ):
self.run_args.append("space.text_w(%s)" % (self.scopenext(),))
def visit_text0(self, typ):
self.run_args.append("space.text0_w(%s)" % (self.scopenext(),))
def visit_utf8(self, typ):
self.run_args.append("space.utf8_w(%s)" % (self.scopenext(),))
def visit_fsencode(self, typ):
self.run_args.append("space.fsencode_w(%s)" % (self.scopenext(),))
def visit_fsencode_or_none(self, typ):
self.run_args.append("space.fsencode_or_none_w(%s)" % (self.scopenext(),))
def visit_nonnegint(self, typ):
self.run_args.append("space.gateway_nonnegint_w(%s)" % (
self.scopenext(),))
def visit_c_int(self, typ):
self.run_args.append("space.c_int_w(%s)" % (self.scopenext(),))
def visit_c_uint(self, typ):
self.run_args.append("space.c_uint_w(%s)" % (self.scopenext(),))
def visit_c_nonnegint(self, typ):
self.run_args.append("space.c_nonnegint_w(%s)" % (self.scopenext(),))
def visit_c_short(self, typ):
self.run_args.append("space.c_short_w(%s)" % (self.scopenext(),))
def visit_c_ushort(self, typ):
self.run_args.append("space.c_ushort_w(%s)" % (self.scopenext(),))
def visit_c_uid_t(self, typ):
self.run_args.append("space.c_uid_t_w(%s)" % (self.scopenext(),))
def visit_truncatedint_w(self, typ):
self.run_args.append("space.truncatedint_w(%s)" % (self.scopenext(),))
def _make_unwrap_activation_class(self, unwrap_spec, cache={}):
try:
key = tuple(unwrap_spec)
activation_factory_cls, run_args = cache[key]
assert run_args == self.run_args, (
"unexpected: same spec, different run_args")
return activation_factory_cls
except KeyError:
parts = []
for el in unwrap_spec:
if isinstance(el, tuple):
parts.append(''.join([getattr(subel, '__name__', subel)
for subel in el]))
elif isinstance(el, WrappedDefault):
parts.append('W_Root')
else:
parts.append(getattr(el, '__name__', el))
label = '_'.join(parts)
#print label
d = {}
source = """if 1:
def _run(self, space, scope_w):
return self.behavior(%s)
\n""" % (', '.join(self.run_args),)
exec compile2(source) in self.miniglobals, d
activation_cls = type("BuiltinActivation_UwS_%s" % label,
(BuiltinActivation,), d)
activation_cls._immutable_ = True
cache[key] = activation_cls, self.run_args
return activation_cls
@staticmethod
def make_activation(unwrap_spec, func):
emit = UnwrapSpec_EmitRun()
emit.apply_over(unwrap_spec)
activation_uw_cls = emit._make_unwrap_activation_class(unwrap_spec)
return activation_uw_cls(func, unwrap_spec)
class UnwrapSpec_EmitShortcut(UnwrapSpec_EmitRun):
# emit a special method shortcut. the calling function always has the signature:
# def shortcut_meth(self, space, *args_w):
# return underlying_function(...correct args...)
# example for 'next':
# def shortcut_next(self, space, *args_w):
# return descr_next(self, space)
def __init__(self, rpy_cls):
UnwrapSpecEmit.__init__(self)
self.run_args = []
self.rpy_cls = rpy_cls
self.extraargs = []
def scopenext(self):
x = self.succ()
res = "w_%d" % (x - 1, )
self.extraargs.append(res)
return res
def visit_self(self, typ):
x = self.succ()
assert x == 0
assert issubclass(self.rpy_cls, typ)
self.run_args.append("self") # no need to check, done implicitly
def visit__W_Root(self, el):
if issubclass(self.rpy_cls, el) and self.n == 0:
return self.visit_self(el)
return UnwrapSpec_EmitRun.visit__W_Root(self, el)
class BuiltinActivation(object):
_immutable_ = True
@not_rpython
def __init__(self, behavior, unwrap_spec):
self.behavior = behavior
def _run(self, space, scope_w):
"""Subclasses with behavior specific for an unwrap spec are generated"""
raise TypeError("abstract")
#________________________________________________________________
class FastFuncNotSupported(Exception):
pass
class UnwrapSpec_FastFunc_Unwrap(UnwrapSpecEmit):
def __init__(self):
UnwrapSpecEmit.__init__(self)
self.args = []
self.unwrap = []
self.finger = 0
def dispatch(self, el, *args):
UnwrapSpecEmit.dispatch(self, el, *args)
self.finger += 1
if self.n > 4:
raise FastFuncNotSupported
def nextarg(self):
arg = "w%d" % self.succ()
self.args.append(arg)
return arg
def visit_self(self, typ):
self.unwrap.append("space.descr_self_interp_w(%s, %s)" %
(self.use(typ), self.nextarg()))
def visit__Unwrapper(self, typ):
self.unwrap.append("%s().unwrap(space, %s)" %
(self.use(typ), self.nextarg()))
def visit__ObjSpace(self, el):
if self.finger > 1:
raise FastFuncNotSupported
self.unwrap.append("space")
def visit__W_Root(self, el):
if el is not W_Root:
self.unwrap.append("space.interp_w(%s, %s)" % (self.use(el),
self.nextarg()))
else:
self.unwrap.append(self.nextarg())
def visit__Arguments(self, el):
raise FastFuncNotSupported
def visit_args_w(self, el):
raise FastFuncNotSupported
def visit_w_args(self, el):
raise FastFuncNotSupported
def visit__object(self, typ):
name = int_unwrapping_space_method(typ)
self.unwrap.append("space.%s(%s)" % (name,
self.nextarg()))
def visit_index(self, typ):
self.unwrap.append("space.getindex_w(%s, space.w_OverflowError)"
% (self.nextarg()), )
def visit_bufferstr(self, typ):
self.unwrap.append("space.bufferstr_w(%s)" % (self.nextarg(),))
def visit_text_or_none(self, typ):
self.unwrap.append("space.text_or_none_w(%s)" % (self.nextarg(),))
def visit_bytes(self, typ):
self.unwrap.append("space.bytes_w(%s)" % (self.nextarg(),))
def visit_bytes0(self, typ):
self.unwrap.append("space.bytes0_w(%s)" % (self.nextarg(),))
def visit_text(self, typ):
self.unwrap.append("space.text_w(%s)" % (self.nextarg(),))
def visit_text0(self, typ):
self.unwrap.append("space.text0_w(%s)" % (self.nextarg(),))
def visit_utf8(self, typ):
self.unwrap.append("space.utf8_w(%s)" % (self.nextarg(),))
def visit_fsencode(self, typ):
self.unwrap.append("space.fsencode_w(%s)" % (self.nextarg(),))
def visit_fsencode_or_none(self, typ):
self.unwrap.append("space.fsencode_or_none_w(%s)" % (self.nextarg(),))
def visit_nonnegint(self, typ):
self.unwrap.append("space.gateway_nonnegint_w(%s)" % (self.nextarg(),))
def visit_c_int(self, typ):
self.unwrap.append("space.c_int_w(%s)" % (self.nextarg(),))
def visit_c_uint(self, typ):
self.unwrap.append("space.c_uint_w(%s)" % (self.nextarg(),))
def visit_c_nonnegint(self, typ):
self.unwrap.append("space.c_nonnegint_w(%s)" % (self.nextarg(),))
def visit_c_short(self, typ):
self.unwrap.append("space.c_short_w(%s)" % (self.nextarg(),))
def visit_c_ushort(self, typ):
self.unwrap.append("space.c_ushort_w(%s)" % (self.nextarg(),))
def visit_c_uid_t(self, typ):
self.unwrap.append("space.c_uid_t_w(%s)" % (self.nextarg(),))
def visit_truncatedint_w(self, typ):
self.unwrap.append("space.truncatedint_w(%s)" % (self.nextarg(),))
@staticmethod
def make_fastfunc(unwrap_spec, func):
unwrap_info = UnwrapSpec_FastFunc_Unwrap()
unwrap_info.apply_over(unwrap_spec)
narg = unwrap_info.n
args = ['space'] + unwrap_info.args
if args == unwrap_info.unwrap:
fastfunc = func
else:
# try to avoid excessive bloat
mod = func.__module__
if mod is None:
mod = ""
if mod == 'pypy.interpreter.astcompiler.ast':
raise FastFuncNotSupported
#if (not mod.startswith('pypy.module.__builtin__') and
# not mod.startswith('pypy.module.sys') and
# not mod.startswith('pypy.module.math')):
# if not func.__name__.startswith('descr'):
# raise FastFuncNotSupported
d = {}
unwrap_info.miniglobals['func'] = func
source = """if 1:
def fastfunc_%s_%d(%s):
return func(%s)
\n""" % (func.__name__.replace('-', '_'), narg,
', '.join(args),
', '.join(unwrap_info.unwrap))
exec compile2(source) in unwrap_info.miniglobals, d
fastfunc = d['fastfunc_%s_%d' % (func.__name__.replace('-', '_'), narg)]
return narg, fastfunc
def int_unwrapping_space_method(typ):
assert typ in (int, str, float, r_longlong, r_uint, r_ulonglong, bool)
if typ is r_int is r_longlong:
return 'gateway_r_longlong_w'
elif typ in (str, bool):
return typ.__name__ + '_w'
else:
return 'gateway_' + typ.__name__ + '_w'
def unwrap_spec(*spec, **kwargs):
"""A decorator which attaches the unwrap_spec attribute.
Use either positional or keyword arguments.
- positional arguments must be as many as the function parameters
- keywords arguments allow to change only some parameter specs
"""
assert spec or kwargs
def decorator(func):
if kwargs:
if spec:
raise ValueError("Please specify either positional or "
"keywords arguments")
func.unwrap_spec = kwargs
else:
func.unwrap_spec = spec
return func
return decorator
class WrappedDefault(object):
""" Can be used inside unwrap_spec as WrappedDefault(3) which means
it'll be treated as W_Root, but fed with default which will be a wrapped
argument to constructor.
"""
def __init__(self, default_value):
self.default_value = default_value
def build_unwrap_spec(func, argnames, self_type=None):
"""build the list of parameter unwrap spec for the function.
"""
unwrap_spec = getattr(func, 'unwrap_spec', None)
if isinstance(unwrap_spec, dict):
kw_spec = unwrap_spec
unwrap_spec = None
else:
kw_spec = {}
if unwrap_spec is None:
# build unwrap_spec after the name of arguments
unwrap_spec = []
for argname in argnames:
if argname == 'self':
unwrap_spec.append('self')
elif argname == 'space':
unwrap_spec.append(ObjSpace)
elif argname == '__args__':
unwrap_spec.append(Arguments)
elif argname == 'args_w':
unwrap_spec.append('args_w')
elif argname.startswith('w_'):
unwrap_spec.append(W_Root)
else:
unwrap_spec.append(None)
# apply kw_spec
for name, spec in kw_spec.items():
try:
unwrap_spec[argnames.index(name)] = spec
except ValueError:
raise ValueError("unwrap_spec() got a keyword %r but it is not "
"the name of an argument of the following "
"function" % (name,))
assert str not in unwrap_spec # use 'text' or 'bytes' instead of str
return unwrap_spec
class BuiltinCode(Code):
"The code object implementing a built-in (interpreter-level) hook."
_immutable_ = True
hidden_applevel = True
descrmismatch_op = None
descr_reqcls = None
# When a BuiltinCode is stored in a Function object,
# you get the functionality of CPython's built-in function type.
@not_rpython
def __init__(self, func, unwrap_spec=None, self_type=None,
descrmismatch=None, doc=None):
from rpython.rlib import rutf8
from rpython.flowspace.bytecode import cpython_code_signature
# 'implfunc' is the interpreter-level function.
# Note that this uses a lot of (construction-time) introspection.
Code.__init__(self, func.__name__)
self.docstring = doc or func.__doc__
if self.docstring:
# check that it's utf-8
rutf8.check_utf8(self.docstring, False)
self.identifier = "%s-%s-%s" % (func.__module__, func.__name__,
getattr(self_type, '__name__', '*'))
# unwrap_spec can be passed to interp2app or
# attached as an attribute to the function.
# It is a list of types or singleton objects:
# baseobjspace.ObjSpace is used to specify the space argument
# baseobjspace.W_Root is for wrapped arguments to keep wrapped
# argument.Arguments is for a final rest arguments Arguments object
# 'args_w' for fixedview applied to rest arguments
# 'w_args' for rest arguments passed as wrapped tuple
# str,int,float: unwrap argument as such type
# (function, cls) use function to check/unwrap argument of type cls
# First extract the signature from the (CPython-level) code object
sig = cpython_code_signature(func.func_code)
argnames = sig.argnames
varargname = sig.varargname
kwargname = sig.kwargname
self._argnames = argnames
if unwrap_spec is None:
unwrap_spec = build_unwrap_spec(func, argnames, self_type)
if self_type:
assert unwrap_spec[0] == 'self', "self_type without 'self' spec element"
unwrap_spec = list(unwrap_spec)
if descrmismatch is not None:
assert issubclass(self_type, W_Root)
unwrap_spec[0] = ('INTERNAL:self', self_type)
self.descrmismatch_op = descrmismatch
self.descr_reqcls = self_type
else:
unwrap_spec[0] = self_type
else:
assert descrmismatch is None, (
"descrmismatch without a self-type specified")
app_sig = SignatureBuilder(func)
UnwrapSpec_Check(func, argnames).apply_over(unwrap_spec, app_sig)
self.sig = app_sig.signature()
argnames = self.sig.argnames
varargname = self.sig.varargname
self.minargs = len(argnames)
if varargname:
self.maxargs = sys.maxint
else:
self.maxargs = self.minargs
self.activation = UnwrapSpec_EmitRun.make_activation(unwrap_spec, func)
self._bltin = func
self._unwrap_spec = unwrap_spec
# speed hack
if 0 <= len(unwrap_spec) <= 5:
try:
arity, fastfunc = UnwrapSpec_FastFunc_Unwrap.make_fastfunc(
unwrap_spec, func)
except FastFuncNotSupported:
if unwrap_spec == [ObjSpace, Arguments]:
self.__class__ = BuiltinCodePassThroughArguments0
self.func__args__ = func
elif unwrap_spec == [ObjSpace, W_Root, Arguments]:
self.__class__ = BuiltinCodePassThroughArguments1
self.func__args__ = func
elif unwrap_spec == [self_type, ObjSpace, Arguments]:
self.__class__ = BuiltinCodePassThroughArguments1
self.descr_reqcls = self_type
miniglobals = {'func': func, 'self_type': self_type}
d = {}
source = """if 1:
def _call(space, w_obj, args):
self = space.descr_self_interp_w(self_type, w_obj)
return func(self, space, args)
\n"""
exec compile2(source) in miniglobals, d
self.func__args__ = d['_call']
else:
self.__class__ = globals()['BuiltinCode%d' % arity]
setattr(self, 'fastfunc_%d' % arity, fastfunc)
def descr__reduce__(self, space):
from pypy.interpreter.mixedmodule import MixedModule
w_mod = space.getbuiltinmodule('_pickle_support')
mod = space.interp_w(MixedModule, w_mod)
builtin_code = mod.get('builtin_code')
return space.newtuple2(builtin_code,
space.newtuple([space.newtext(self.identifier)]))
@staticmethod
def find(space, identifier):
from pypy.interpreter.function import Function
return Function.find(space, identifier).code
def signature(self):
return self.sig
def getdocstring(self, space):
return space.newtext_or_none(self.docstring)
def funcrun(self, func, args):
return BuiltinCode.funcrun_obj(self, func, None, args)
def funcrun_obj(self, func, w_obj, args):
space = func.space
activation = self.activation
scope_w = args.parse_obj(w_obj, func.name, self.sig,
func.defs_w, self.minargs)
try:
w_result = activation._run(space, scope_w)
except DescrMismatch:
if w_obj is not None:
args = args.prepend(w_obj)
return self._type_unwrap_mismatch(space, args)
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
def _type_unwrap_mismatch(self, space, args):
w_obj = args.firstarg()
if w_obj is None:
raise oefmt(space.w_SystemError, "unexpected DescrMismatch error")
return w_obj.descr_call_mismatch(space,
self.descrmismatch_op,
self.descr_reqcls,
args)
def handle_exception(self, space, e):
try:
if not we_are_translated():
raise
raise e
except OperationError:
raise
except Exception as e: # general fall-back
from pypy.interpreter import error
raise error.get_converted_unexpected_exception(space, e)
# (verbose) performance hack below
class BuiltinCodePassThroughArguments0(BuiltinCode):
_immutable_ = True
def funcrun(self, func, args):
space = func.space
try:
w_result = self.func__args__(space, args)
except DescrMismatch:
return self._type_unwrap_mismatch(space, args)
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
class BuiltinCodePassThroughArguments1(BuiltinCode):
_immutable_ = True
fast_natural_arity = Code.PASSTHROUGHARGS1
def funcrun_obj(self, func, w_obj, args):
space = func.space
try:
w_result = self.func__args__(space, w_obj, args)
except DescrMismatch:
return self._type_unwrap_mismatch(space, args.prepend(w_obj))
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
class BuiltinCode0(BuiltinCode):
_immutable_ = True
fast_natural_arity = 0
def fastcall_0(self, space, w_func):
try:
w_result = self.fastfunc_0(space)
except DescrMismatch:
raise oefmt(space.w_SystemError, "unexpected DescrMismatch error")
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
w_root_or_none = sigtypes.instance(W_Root, can_be_None=True)
@finishsigs
class BuiltinCode1(BuiltinCode):
_immutable_ = True
fast_natural_arity = 1
@signature(sigtypes.self(), sigtypes.any(),
w_root_or_none,
w_root_or_none,
returns=w_root_or_none)
def fastcall_1(self, space, w_func, w1):
try:
w_result = self.fastfunc_1(space, w1)
except DescrMismatch:
return self._type_unwrap_mismatch(space,
Arguments(space, [w1]))
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
@finishsigs
class BuiltinCode2(BuiltinCode):
_immutable_ = True
fast_natural_arity = 2
@signature(sigtypes.self(), sigtypes.any(),
w_root_or_none,
w_root_or_none,
w_root_or_none,
returns=w_root_or_none)
def fastcall_2(self, space, w_func, w1, w2):
try:
w_result = self.fastfunc_2(space, w1, w2)
except DescrMismatch:
return self._type_unwrap_mismatch(space,
Arguments(space, [w1, w2]))
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
@finishsigs
class BuiltinCode3(BuiltinCode):
_immutable_ = True
fast_natural_arity = 3
@signature(sigtypes.self(), sigtypes.any(),
w_root_or_none,
w_root_or_none,
w_root_or_none,
w_root_or_none,
returns=w_root_or_none)
def fastcall_3(self, space, func, w1, w2, w3):
try:
w_result = self.fastfunc_3(space, w1, w2, w3)
except DescrMismatch:
return self._type_unwrap_mismatch(space,
Arguments(space, [w1, w2, w3]))
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
@finishsigs
class BuiltinCode4(BuiltinCode):
_immutable_ = True
fast_natural_arity = 4
@signature(sigtypes.self(), sigtypes.any(),
w_root_or_none,
w_root_or_none,
w_root_or_none,
w_root_or_none,
w_root_or_none,
returns=w_root_or_none)
def fastcall_4(self, space, func, w1, w2, w3, w4):
from rpython.rlib.debug import check_annotation
try:
w_result = self.fastfunc_4(space, w1, w2, w3, w4)
except DescrMismatch:
return self._type_unwrap_mismatch(space,
Arguments(space,
[w1, w2, w3, w4]))
except Exception as e:
self.handle_exception(space, e)
w_result = None
if w_result is None:
w_result = space.w_None
return w_result
def interpindirect2app(unbound_meth, unwrap_spec=None):
base_cls = unbound_meth.im_class
func = unbound_meth.im_func
args = inspect.getargs(func.func_code)
if args.varargs or args.keywords:
raise TypeError("Varargs and keywords not supported in unwrap_spec")
argspec = ', '.join([arg for arg in args.args[1:]])
func_code = py.code.Source("""
def f(self, %(args)s):
return self.%(func_name)s(%(args)s)
""" % {'args': argspec, 'func_name': func.func_name})
d = {}
exec func_code.compile() in d
f = d['f']
f.func_defaults = unbound_meth.func_defaults
f.func_doc = unbound_meth.func_doc
f.__module__ = func.__module__
# necessary for unique identifiers for pickling
f.func_name = func.func_name
if unwrap_spec is None:
unwrap_spec = getattr(unbound_meth, 'unwrap_spec', {})
else:
assert isinstance(unwrap_spec, dict)
unwrap_spec = unwrap_spec.copy()
unwrap_spec['self'] = 'self'
return interp2app(globals()['unwrap_spec'](**unwrap_spec)(f),